xmlparse.c 304 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267
  1. /* 93c1caa66e2b0310459482516af05505b57c5cb7b96df777105308fc585c85d1 (2.7.5+)
  2. __ __ _
  3. ___\ \/ /_ __ __ _| |_
  4. / _ \\ /| '_ \ / _` | __|
  5. | __// \| |_) | (_| | |_
  6. \___/_/\_\ .__/ \__,_|\__|
  7. |_| XML parser
  8. Copyright (c) 1997-2000 Thai Open Source Software Center Ltd
  9. Copyright (c) 2000 Clark Cooper <[email protected]>
  10. Copyright (c) 2000-2006 Fred L. Drake, Jr. <[email protected]>
  11. Copyright (c) 2001-2002 Greg Stein <[email protected]>
  12. Copyright (c) 2002-2016 Karl Waclawek <[email protected]>
  13. Copyright (c) 2005-2009 Steven Solie <[email protected]>
  14. Copyright (c) 2016 Eric Rahm <[email protected]>
  15. Copyright (c) 2016-2026 Sebastian Pipping <[email protected]>
  16. Copyright (c) 2016 Gaurav <[email protected]>
  17. Copyright (c) 2016 Thomas Beutlich <[email protected]>
  18. Copyright (c) 2016 Gustavo Grieco <[email protected]>
  19. Copyright (c) 2016 Pascal Cuoq <[email protected]>
  20. Copyright (c) 2016 Ed Schouten <[email protected]>
  21. Copyright (c) 2017-2022 Rhodri James <[email protected]>
  22. Copyright (c) 2017 Václav Slavík <[email protected]>
  23. Copyright (c) 2017 Viktor Szakats <[email protected]>
  24. Copyright (c) 2017 Chanho Park <[email protected]>
  25. Copyright (c) 2017 Rolf Eike Beer <[email protected]>
  26. Copyright (c) 2017 Hans Wennborg <[email protected]>
  27. Copyright (c) 2018 Anton Maklakov <[email protected]>
  28. Copyright (c) 2018 Benjamin Peterson <[email protected]>
  29. Copyright (c) 2018 Marco Maggi <[email protected]>
  30. Copyright (c) 2018 Mariusz Zaborski <[email protected]>
  31. Copyright (c) 2019 David Loffredo <[email protected]>
  32. Copyright (c) 2019-2020 Ben Wagner <[email protected]>
  33. Copyright (c) 2019 Vadim Zeitlin <[email protected]>
  34. Copyright (c) 2021 Donghee Na <[email protected]>
  35. Copyright (c) 2022 Samanta Navarro <[email protected]>
  36. Copyright (c) 2022 Jeffrey Walton <[email protected]>
  37. Copyright (c) 2022 Jann Horn <[email protected]>
  38. Copyright (c) 2022 Sean McBride <[email protected]>
  39. Copyright (c) 2023 Owain Davies <[email protected]>
  40. Copyright (c) 2023-2024 Sony Corporation / Snild Dolkow <[email protected]>
  41. Copyright (c) 2024-2025 Berkay Eren Ürün <[email protected]>
  42. Copyright (c) 2024 Hanno Böck <[email protected]>
  43. Copyright (c) 2025 Matthew Fernandez <[email protected]>
  44. Copyright (c) 2025 Atrem Borovik <[email protected]>
  45. Copyright (c) 2025 Alfonso Gregory <[email protected]>
  46. Copyright (c) 2026 Rosen Penev <[email protected]>
  47. Licensed under the MIT license:
  48. Permission is hereby granted, free of charge, to any person obtaining
  49. a copy of this software and associated documentation files (the
  50. "Software"), to deal in the Software without restriction, including
  51. without limitation the rights to use, copy, modify, merge, publish,
  52. distribute, sublicense, and/or sell copies of the Software, and to permit
  53. persons to whom the Software is furnished to do so, subject to the
  54. following conditions:
  55. The above copyright notice and this permission notice shall be included
  56. in all copies or substantial portions of the Software.
  57. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  58. EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  59. MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  60. NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  61. DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  62. OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  63. USE OR OTHER DEALINGS IN THE SOFTWARE.
  64. */
  65. #define XML_BUILDING_EXPAT 1
  66. #include "expat_config.h"
  67. #if ! defined(XML_GE) || (1 - XML_GE - 1 == 2) || (XML_GE < 0) || (XML_GE > 1)
  68. # error XML_GE (for general entities) must be defined, non-empty, either 1 or 0 (0 to disable, 1 to enable; 1 is a common default)
  69. #endif
  70. #if defined(XML_DTD) && XML_GE == 0
  71. # error Either undefine XML_DTD or define XML_GE to 1.
  72. #endif
  73. #if ! defined(XML_CONTEXT_BYTES) || (1 - XML_CONTEXT_BYTES - 1 == 2) \
  74. || (XML_CONTEXT_BYTES + 0 < 0)
  75. # error XML_CONTEXT_BYTES must be defined, non-empty and >=0 (0 to disable, >=1 to enable; 1024 is a common default)
  76. #endif
  77. #if defined(HAVE_SYSCALL_GETRANDOM)
  78. # if ! defined(_GNU_SOURCE)
  79. # define _GNU_SOURCE 1 /* syscall prototype */
  80. # endif
  81. #endif
  82. #ifdef _WIN32
  83. /* force stdlib to define rand_s() */
  84. # if ! defined(_CRT_RAND_S)
  85. # define _CRT_RAND_S
  86. # endif
  87. #endif
  88. #include <stdbool.h>
  89. #include <stddef.h>
  90. #include <string.h> /* memset(), memcpy() */
  91. #include <assert.h>
  92. #include <limits.h> /* INT_MAX, UINT_MAX */
  93. #include <stdio.h> /* fprintf */
  94. #include <stdlib.h> /* getenv, rand_s */
  95. #include <stdint.h> /* SIZE_MAX, uintptr_t */
  96. #include <math.h> /* isnan */
  97. #ifdef _WIN32
  98. # define getpid GetCurrentProcessId
  99. #else
  100. # include <sys/time.h> /* gettimeofday() */
  101. # include <sys/types.h> /* getpid() */
  102. # include <unistd.h> /* getpid() */
  103. # include <fcntl.h> /* O_RDONLY */
  104. # include <errno.h>
  105. #endif
  106. #ifdef _WIN32
  107. # include "winconfig.h"
  108. #endif
  109. #include "ascii.h"
  110. #include "expat.h"
  111. #include "siphash.h"
  112. #if defined(HAVE_GETRANDOM) || defined(HAVE_SYSCALL_GETRANDOM)
  113. # if defined(HAVE_GETRANDOM)
  114. # include <sys/random.h> /* getrandom */
  115. # else
  116. # include <unistd.h> /* syscall */
  117. # include <sys/syscall.h> /* SYS_getrandom */
  118. # endif
  119. # if ! defined(GRND_NONBLOCK)
  120. # define GRND_NONBLOCK 0x0001
  121. # endif /* defined(GRND_NONBLOCK) */
  122. #endif /* defined(HAVE_GETRANDOM) || defined(HAVE_SYSCALL_GETRANDOM) */
  123. #if defined(_WIN32) && ! defined(LOAD_LIBRARY_SEARCH_SYSTEM32)
  124. # define LOAD_LIBRARY_SEARCH_SYSTEM32 0x00000800
  125. #endif
  126. #if ! defined(HAVE_GETRANDOM) && ! defined(HAVE_SYSCALL_GETRANDOM) \
  127. && ! defined(HAVE_ARC4RANDOM_BUF) && ! defined(HAVE_ARC4RANDOM) \
  128. && ! defined(XML_DEV_URANDOM) && ! defined(_WIN32) \
  129. && ! defined(XML_POOR_ENTROPY)
  130. # error You do not have support for any sources of high quality entropy \
  131. enabled. For end user security, that is probably not what you want. \
  132. \
  133. Your options include: \
  134. * Linux >=3.17 + glibc >=2.25 (getrandom): HAVE_GETRANDOM, \
  135. * Linux >=3.17 + glibc (including <2.25) (syscall SYS_getrandom): HAVE_SYSCALL_GETRANDOM, \
  136. * BSD / macOS >=10.7 / glibc >=2.36 (arc4random_buf): HAVE_ARC4RANDOM_BUF, \
  137. * BSD / macOS (including <10.7) / glibc >=2.36 (arc4random): HAVE_ARC4RANDOM, \
  138. * Linux (including <3.17) / BSD / macOS (including <10.7) / Solaris >=8 (/dev/urandom): XML_DEV_URANDOM, \
  139. * Windows >=Vista (rand_s): _WIN32. \
  140. \
  141. If insist on not using any of these, bypass this error by defining \
  142. XML_POOR_ENTROPY; you have been warned. \
  143. \
  144. If you have reasons to patch this detection code away or need changes \
  145. to the build system, please open a bug. Thank you!
  146. #endif
  147. #ifdef XML_UNICODE
  148. # define XML_ENCODE_MAX XML_UTF16_ENCODE_MAX
  149. # define XmlConvert XmlUtf16Convert
  150. # define XmlGetInternalEncoding XmlGetUtf16InternalEncoding
  151. # define XmlGetInternalEncodingNS XmlGetUtf16InternalEncodingNS
  152. # define XmlEncode XmlUtf16Encode
  153. # define MUST_CONVERT(enc, s) (! (enc)->isUtf16 || (((uintptr_t)(s)) & 1))
  154. typedef unsigned short ICHAR;
  155. #else
  156. # define XML_ENCODE_MAX XML_UTF8_ENCODE_MAX
  157. # define XmlConvert XmlUtf8Convert
  158. # define XmlGetInternalEncoding XmlGetUtf8InternalEncoding
  159. # define XmlGetInternalEncodingNS XmlGetUtf8InternalEncodingNS
  160. # define XmlEncode XmlUtf8Encode
  161. # define MUST_CONVERT(enc, s) (! (enc)->isUtf8)
  162. typedef char ICHAR;
  163. #endif
  164. #ifndef XML_NS
  165. # define XmlInitEncodingNS XmlInitEncoding
  166. # define XmlInitUnknownEncodingNS XmlInitUnknownEncoding
  167. # undef XmlGetInternalEncodingNS
  168. # define XmlGetInternalEncodingNS XmlGetInternalEncoding
  169. # define XmlParseXmlDeclNS XmlParseXmlDecl
  170. #endif
  171. #ifdef XML_UNICODE
  172. # ifdef XML_UNICODE_WCHAR_T
  173. # define XML_T(x) (const wchar_t) x
  174. # define XML_L(x) L##x
  175. # else
  176. # define XML_T(x) (const unsigned short)x
  177. # define XML_L(x) x
  178. # endif
  179. #else
  180. # define XML_T(x) x
  181. # define XML_L(x) x
  182. #endif
  183. /* Round up n to be a multiple of sz, where sz is a power of 2. */
  184. #define ROUND_UP(n, sz) (((n) + ((sz) - 1)) & ~((sz) - 1))
  185. /* Do safe (NULL-aware) pointer arithmetic */
  186. #define EXPAT_SAFE_PTR_DIFF(p, q) (((p) && (q)) ? ((p) - (q)) : 0)
  187. #define EXPAT_MIN(a, b) (((a) < (b)) ? (a) : (b))
  188. #include "internal.h"
  189. #include "xmltok.h"
  190. #include "xmlrole.h"
  191. typedef const XML_Char *KEY;
  192. typedef struct {
  193. KEY name;
  194. } NAMED;
  195. typedef struct {
  196. NAMED **v;
  197. unsigned char power;
  198. size_t size;
  199. size_t used;
  200. XML_Parser parser;
  201. } HASH_TABLE;
  202. static size_t keylen(KEY s);
  203. static void copy_salt_to_sipkey(XML_Parser parser, struct sipkey *key);
  204. /* For probing (after a collision) we need a step size relative prime
  205. to the hash table size, which is a power of 2. We use double-hashing,
  206. since we can calculate a second hash value cheaply by taking those bits
  207. of the first hash value that were discarded (masked out) when the table
  208. index was calculated: index = hash & mask, where mask = table->size - 1.
  209. We limit the maximum step size to table->size / 4 (mask >> 2) and make
  210. it odd, since odd numbers are always relative prime to a power of 2.
  211. */
  212. #define SECOND_HASH(hash, mask, power) \
  213. ((((hash) & ~(mask)) >> ((power) - 1)) & ((mask) >> 2))
  214. #define PROBE_STEP(hash, mask, power) \
  215. ((unsigned char)((SECOND_HASH(hash, mask, power)) | 1))
  216. typedef struct {
  217. NAMED **p;
  218. NAMED **end;
  219. } HASH_TABLE_ITER;
  220. #define INIT_TAG_BUF_SIZE 32 /* must be a multiple of sizeof(XML_Char) */
  221. #define INIT_DATA_BUF_SIZE 1024
  222. #define INIT_ATTS_SIZE 16
  223. #define INIT_ATTS_VERSION 0xFFFFFFFF
  224. #define INIT_BLOCK_SIZE 1024
  225. #define INIT_BUFFER_SIZE 1024
  226. #define EXPAND_SPARE 24
  227. typedef struct binding {
  228. struct prefix *prefix;
  229. struct binding *nextTagBinding;
  230. struct binding *prevPrefixBinding;
  231. const struct attribute_id *attId;
  232. XML_Char *uri;
  233. int uriLen;
  234. int uriAlloc;
  235. } BINDING;
  236. typedef struct prefix {
  237. const XML_Char *name;
  238. BINDING *binding;
  239. } PREFIX;
  240. typedef struct {
  241. const XML_Char *str;
  242. const XML_Char *localPart;
  243. const XML_Char *prefix;
  244. int strLen;
  245. int uriLen;
  246. int prefixLen;
  247. } TAG_NAME;
  248. /* TAG represents an open element.
  249. The name of the element is stored in both the document and API
  250. encodings. The memory buffer 'buf' is a separately-allocated
  251. memory area which stores the name. During the XML_Parse()/
  252. XML_ParseBuffer() when the element is open, the memory for the 'raw'
  253. version of the name (in the document encoding) is shared with the
  254. document buffer. If the element is open across calls to
  255. XML_Parse()/XML_ParseBuffer(), the buffer is re-allocated to
  256. contain the 'raw' name as well.
  257. A parser reuses these structures, maintaining a list of allocated
  258. TAG objects in a free list.
  259. */
  260. typedef struct tag {
  261. struct tag *parent; /* parent of this element */
  262. const char *rawName; /* tagName in the original encoding */
  263. int rawNameLength;
  264. TAG_NAME name; /* tagName in the API encoding */
  265. union {
  266. char *raw; /* for byte-level access (rawName storage) */
  267. XML_Char *str; /* for character-level access (converted name) */
  268. } buf; /* buffer for name components */
  269. char *bufEnd; /* end of the buffer */
  270. BINDING *bindings;
  271. } TAG;
  272. typedef struct {
  273. const XML_Char *name;
  274. const XML_Char *textPtr;
  275. int textLen; /* length in XML_Chars */
  276. int processed; /* # of processed bytes - when suspended */
  277. const XML_Char *systemId;
  278. const XML_Char *base;
  279. const XML_Char *publicId;
  280. const XML_Char *notation;
  281. XML_Bool open;
  282. XML_Bool hasMore; /* true if entity has not been completely processed */
  283. /* An entity can be open while being already completely processed (hasMore ==
  284. XML_FALSE). The reason is the delayed closing of entities until their inner
  285. entities are processed and closed */
  286. XML_Bool is_param;
  287. XML_Bool is_internal; /* true if declared in internal subset outside PE */
  288. } ENTITY;
  289. typedef struct {
  290. enum XML_Content_Type type;
  291. enum XML_Content_Quant quant;
  292. const XML_Char *name;
  293. int firstchild;
  294. int lastchild;
  295. int childcnt;
  296. int nextsib;
  297. } CONTENT_SCAFFOLD;
  298. #define INIT_SCAFFOLD_ELEMENTS 32
  299. typedef struct block {
  300. struct block *next;
  301. int size;
  302. XML_Char s[];
  303. } BLOCK;
  304. typedef struct {
  305. BLOCK *blocks;
  306. BLOCK *freeBlocks;
  307. const XML_Char *end;
  308. XML_Char *ptr;
  309. XML_Char *start;
  310. XML_Parser parser;
  311. } STRING_POOL;
  312. /* The XML_Char before the name is used to determine whether
  313. an attribute has been specified. */
  314. typedef struct attribute_id {
  315. XML_Char *name;
  316. PREFIX *prefix;
  317. XML_Bool maybeTokenized;
  318. XML_Bool xmlns;
  319. } ATTRIBUTE_ID;
  320. typedef struct {
  321. const ATTRIBUTE_ID *id;
  322. XML_Bool isCdata;
  323. const XML_Char *value;
  324. } DEFAULT_ATTRIBUTE;
  325. typedef struct {
  326. unsigned long version;
  327. unsigned long hash;
  328. const XML_Char *uriName;
  329. } NS_ATT;
  330. typedef struct {
  331. const XML_Char *name;
  332. PREFIX *prefix;
  333. const ATTRIBUTE_ID *idAtt;
  334. int nDefaultAtts;
  335. int allocDefaultAtts;
  336. DEFAULT_ATTRIBUTE *defaultAtts;
  337. } ELEMENT_TYPE;
  338. typedef struct {
  339. HASH_TABLE generalEntities;
  340. HASH_TABLE elementTypes;
  341. HASH_TABLE attributeIds;
  342. HASH_TABLE prefixes;
  343. STRING_POOL pool;
  344. STRING_POOL entityValuePool;
  345. /* false once a parameter entity reference has been skipped */
  346. XML_Bool keepProcessing;
  347. /* true once an internal or external PE reference has been encountered;
  348. this includes the reference to an external subset */
  349. XML_Bool hasParamEntityRefs;
  350. XML_Bool standalone;
  351. #ifdef XML_DTD
  352. /* indicates if external PE has been read */
  353. XML_Bool paramEntityRead;
  354. HASH_TABLE paramEntities;
  355. #endif /* XML_DTD */
  356. PREFIX defaultPrefix;
  357. /* === scaffolding for building content model === */
  358. XML_Bool in_eldecl;
  359. CONTENT_SCAFFOLD *scaffold;
  360. unsigned contentStringLen;
  361. unsigned scaffSize;
  362. unsigned scaffCount;
  363. int scaffLevel;
  364. int *scaffIndex;
  365. } DTD;
  366. enum EntityType {
  367. ENTITY_INTERNAL,
  368. ENTITY_ATTRIBUTE,
  369. ENTITY_VALUE,
  370. };
  371. typedef struct open_internal_entity {
  372. const char *internalEventPtr;
  373. const char *internalEventEndPtr;
  374. struct open_internal_entity *next;
  375. ENTITY *entity;
  376. int startTagLevel;
  377. XML_Bool betweenDecl; /* WFC: PE Between Declarations */
  378. enum EntityType type;
  379. } OPEN_INTERNAL_ENTITY;
  380. enum XML_Account {
  381. XML_ACCOUNT_DIRECT, /* bytes directly passed to the Expat parser */
  382. XML_ACCOUNT_ENTITY_EXPANSION, /* intermediate bytes produced during entity
  383. expansion */
  384. XML_ACCOUNT_NONE /* i.e. do not account, was accounted already */
  385. };
  386. #if XML_GE == 1
  387. typedef unsigned long long XmlBigCount;
  388. typedef struct accounting {
  389. XmlBigCount countBytesDirect;
  390. XmlBigCount countBytesIndirect;
  391. unsigned long debugLevel;
  392. float maximumAmplificationFactor; // >=1.0
  393. unsigned long long activationThresholdBytes;
  394. } ACCOUNTING;
  395. typedef struct MALLOC_TRACKER {
  396. XmlBigCount bytesAllocated;
  397. XmlBigCount peakBytesAllocated; // updated live only for debug level >=2
  398. unsigned long debugLevel;
  399. float maximumAmplificationFactor; // >=1.0
  400. XmlBigCount activationThresholdBytes;
  401. } MALLOC_TRACKER;
  402. typedef struct entity_stats {
  403. unsigned int countEverOpened;
  404. unsigned int currentDepth;
  405. unsigned int maximumDepthSeen;
  406. unsigned long debugLevel;
  407. } ENTITY_STATS;
  408. #endif /* XML_GE == 1 */
  409. typedef enum XML_Error PTRCALL Processor(XML_Parser parser, const char *start,
  410. const char *end, const char **endPtr);
  411. static Processor prologProcessor;
  412. static Processor prologInitProcessor;
  413. static Processor contentProcessor;
  414. static Processor cdataSectionProcessor;
  415. #ifdef XML_DTD
  416. static Processor ignoreSectionProcessor;
  417. static Processor externalParEntProcessor;
  418. static Processor externalParEntInitProcessor;
  419. static Processor entityValueProcessor;
  420. static Processor entityValueInitProcessor;
  421. #endif /* XML_DTD */
  422. static Processor epilogProcessor;
  423. static Processor errorProcessor;
  424. static Processor externalEntityInitProcessor;
  425. static Processor externalEntityInitProcessor2;
  426. static Processor externalEntityInitProcessor3;
  427. static Processor externalEntityContentProcessor;
  428. static Processor internalEntityProcessor;
  429. static enum XML_Error handleUnknownEncoding(XML_Parser parser,
  430. const XML_Char *encodingName);
  431. static enum XML_Error processXmlDecl(XML_Parser parser, int isGeneralTextEntity,
  432. const char *s, const char *next);
  433. static enum XML_Error initializeEncoding(XML_Parser parser);
  434. static enum XML_Error doProlog(XML_Parser parser, const ENCODING *enc,
  435. const char *s, const char *end, int tok,
  436. const char *next, const char **nextPtr,
  437. XML_Bool haveMore, XML_Bool allowClosingDoctype,
  438. enum XML_Account account);
  439. static enum XML_Error processEntity(XML_Parser parser, ENTITY *entity,
  440. XML_Bool betweenDecl, enum EntityType type);
  441. static enum XML_Error doContent(XML_Parser parser, int startTagLevel,
  442. const ENCODING *enc, const char *start,
  443. const char *end, const char **endPtr,
  444. XML_Bool haveMore, enum XML_Account account);
  445. static enum XML_Error doCdataSection(XML_Parser parser, const ENCODING *enc,
  446. const char **startPtr, const char *end,
  447. const char **nextPtr, XML_Bool haveMore,
  448. enum XML_Account account);
  449. #ifdef XML_DTD
  450. static enum XML_Error doIgnoreSection(XML_Parser parser, const ENCODING *enc,
  451. const char **startPtr, const char *end,
  452. const char **nextPtr, XML_Bool haveMore);
  453. #endif /* XML_DTD */
  454. static void freeBindings(XML_Parser parser, BINDING *bindings);
  455. static enum XML_Error storeAtts(XML_Parser parser, const ENCODING *enc,
  456. const char *attStr, TAG_NAME *tagNamePtr,
  457. BINDING **bindingsPtr,
  458. enum XML_Account account);
  459. static enum XML_Error addBinding(XML_Parser parser, PREFIX *prefix,
  460. const ATTRIBUTE_ID *attId, const XML_Char *uri,
  461. BINDING **bindingsPtr);
  462. static int defineAttribute(ELEMENT_TYPE *type, ATTRIBUTE_ID *attId,
  463. XML_Bool isCdata, XML_Bool isId,
  464. const XML_Char *value, XML_Parser parser);
  465. static enum XML_Error storeAttributeValue(XML_Parser parser,
  466. const ENCODING *enc, XML_Bool isCdata,
  467. const char *ptr, const char *end,
  468. STRING_POOL *pool,
  469. enum XML_Account account);
  470. static enum XML_Error
  471. appendAttributeValue(XML_Parser parser, const ENCODING *enc, XML_Bool isCdata,
  472. const char *ptr, const char *end, STRING_POOL *pool,
  473. enum XML_Account account, const char **nextPtr);
  474. static ATTRIBUTE_ID *getAttributeId(XML_Parser parser, const ENCODING *enc,
  475. const char *start, const char *end);
  476. static int setElementTypePrefix(XML_Parser parser, ELEMENT_TYPE *elementType);
  477. #if XML_GE == 1
  478. static enum XML_Error storeEntityValue(XML_Parser parser, const ENCODING *enc,
  479. const char *start, const char *end,
  480. enum XML_Account account,
  481. const char **nextPtr);
  482. static enum XML_Error callStoreEntityValue(XML_Parser parser,
  483. const ENCODING *enc,
  484. const char *start, const char *end,
  485. enum XML_Account account);
  486. #else
  487. static enum XML_Error storeSelfEntityValue(XML_Parser parser, ENTITY *entity);
  488. #endif
  489. static int reportProcessingInstruction(XML_Parser parser, const ENCODING *enc,
  490. const char *start, const char *end);
  491. static int reportComment(XML_Parser parser, const ENCODING *enc,
  492. const char *start, const char *end);
  493. static void reportDefault(XML_Parser parser, const ENCODING *enc,
  494. const char *start, const char *end);
  495. static const XML_Char *getContext(XML_Parser parser);
  496. static XML_Bool setContext(XML_Parser parser, const XML_Char *context);
  497. static void FASTCALL normalizePublicId(XML_Char *s);
  498. static DTD *dtdCreate(XML_Parser parser);
  499. /* do not call if m_parentParser != NULL */
  500. static void dtdReset(DTD *p, XML_Parser parser);
  501. static void dtdDestroy(DTD *p, XML_Bool isDocEntity, XML_Parser parser);
  502. static int dtdCopy(XML_Parser oldParser, DTD *newDtd, const DTD *oldDtd,
  503. XML_Parser parser);
  504. static int copyEntityTable(XML_Parser oldParser, HASH_TABLE *newTable,
  505. STRING_POOL *newPool, const HASH_TABLE *oldTable);
  506. static NAMED *lookup(XML_Parser parser, HASH_TABLE *table, KEY name,
  507. size_t createSize);
  508. static void FASTCALL hashTableInit(HASH_TABLE *table, XML_Parser parser);
  509. static void FASTCALL hashTableClear(HASH_TABLE *table);
  510. static void FASTCALL hashTableDestroy(HASH_TABLE *table);
  511. static void FASTCALL hashTableIterInit(HASH_TABLE_ITER *iter,
  512. const HASH_TABLE *table);
  513. static NAMED *FASTCALL hashTableIterNext(HASH_TABLE_ITER *iter);
  514. static void FASTCALL poolInit(STRING_POOL *pool, XML_Parser parser);
  515. static void FASTCALL poolClear(STRING_POOL *pool);
  516. static void FASTCALL poolDestroy(STRING_POOL *pool);
  517. static XML_Char *poolAppend(STRING_POOL *pool, const ENCODING *enc,
  518. const char *ptr, const char *end);
  519. static XML_Char *poolStoreString(STRING_POOL *pool, const ENCODING *enc,
  520. const char *ptr, const char *end);
  521. static XML_Bool FASTCALL poolGrow(STRING_POOL *pool);
  522. static const XML_Char *FASTCALL poolCopyString(STRING_POOL *pool,
  523. const XML_Char *s);
  524. static const XML_Char *FASTCALL poolCopyStringNoFinish(STRING_POOL *pool,
  525. const XML_Char *s);
  526. static const XML_Char *poolCopyStringN(STRING_POOL *pool, const XML_Char *s,
  527. int n);
  528. static const XML_Char *FASTCALL poolAppendString(STRING_POOL *pool,
  529. const XML_Char *s);
  530. static int FASTCALL nextScaffoldPart(XML_Parser parser);
  531. static XML_Content *build_model(XML_Parser parser);
  532. static ELEMENT_TYPE *getElementType(XML_Parser parser, const ENCODING *enc,
  533. const char *ptr, const char *end);
  534. static XML_Char *copyString(const XML_Char *s, XML_Parser parser);
  535. static unsigned long generate_hash_secret_salt(XML_Parser parser);
  536. static XML_Bool startParsing(XML_Parser parser);
  537. static XML_Parser parserCreate(const XML_Char *encodingName,
  538. const XML_Memory_Handling_Suite *memsuite,
  539. const XML_Char *nameSep, DTD *dtd,
  540. XML_Parser parentParser);
  541. static void parserInit(XML_Parser parser, const XML_Char *encodingName);
  542. #if XML_GE == 1
  543. static float accountingGetCurrentAmplification(XML_Parser rootParser);
  544. static void accountingReportStats(XML_Parser originParser, const char *epilog);
  545. static void accountingOnAbort(XML_Parser originParser);
  546. static void accountingReportDiff(XML_Parser rootParser,
  547. unsigned int levelsAwayFromRootParser,
  548. const char *before, const char *after,
  549. ptrdiff_t bytesMore, int source_line,
  550. enum XML_Account account);
  551. static XML_Bool accountingDiffTolerated(XML_Parser originParser, int tok,
  552. const char *before, const char *after,
  553. int source_line,
  554. enum XML_Account account);
  555. static void entityTrackingReportStats(XML_Parser parser, ENTITY *entity,
  556. const char *action, int sourceLine);
  557. static void entityTrackingOnOpen(XML_Parser parser, ENTITY *entity,
  558. int sourceLine);
  559. static void entityTrackingOnClose(XML_Parser parser, ENTITY *entity,
  560. int sourceLine);
  561. #endif /* XML_GE == 1 */
  562. static XML_Parser getRootParserOf(XML_Parser parser,
  563. unsigned int *outLevelDiff);
  564. static unsigned long getDebugLevel(const char *variableName,
  565. unsigned long defaultDebugLevel);
  566. #define poolStart(pool) ((pool)->start)
  567. #define poolLength(pool) ((pool)->ptr - (pool)->start)
  568. #define poolChop(pool) ((void)--(pool->ptr))
  569. #define poolLastChar(pool) (((pool)->ptr)[-1])
  570. #define poolDiscard(pool) ((pool)->ptr = (pool)->start)
  571. #define poolFinish(pool) ((pool)->start = (pool)->ptr)
  572. #define poolAppendChar(pool, c) \
  573. (((pool)->ptr == (pool)->end && ! poolGrow(pool)) \
  574. ? 0 \
  575. : ((*((pool)->ptr)++ = c), 1))
  576. #if ! defined(XML_TESTING)
  577. const
  578. #endif
  579. XML_Bool g_reparseDeferralEnabledDefault
  580. = XML_TRUE; // write ONLY in runtests.c
  581. #if defined(XML_TESTING)
  582. unsigned int g_bytesScanned = 0; // used for testing only
  583. #endif
  584. struct XML_ParserStruct {
  585. /* The first member must be m_userData so that the XML_GetUserData
  586. macro works. */
  587. void *m_userData;
  588. void *m_handlerArg;
  589. // How the four parse buffer pointers below relate in time and space:
  590. //
  591. // m_buffer <= m_bufferPtr <= m_bufferEnd <= m_bufferLim
  592. // | | | |
  593. // <--parsed-->| | |
  594. // <---parsing--->| |
  595. // <--unoccupied-->|
  596. // <---------total-malloced/realloced-------->|
  597. char *m_buffer; // malloc/realloc base pointer of parse buffer
  598. const XML_Memory_Handling_Suite m_mem;
  599. const char *m_bufferPtr; // first character to be parsed
  600. char *m_bufferEnd; // past last character to be parsed
  601. const char *m_bufferLim; // allocated end of m_buffer
  602. XML_Index m_parseEndByteIndex;
  603. const char *m_parseEndPtr;
  604. size_t m_partialTokenBytesBefore; /* used in heuristic to avoid O(n^2) */
  605. XML_Bool m_reparseDeferralEnabled;
  606. int m_lastBufferRequestSize;
  607. XML_Char *m_dataBuf;
  608. XML_Char *m_dataBufEnd;
  609. XML_StartElementHandler m_startElementHandler;
  610. XML_EndElementHandler m_endElementHandler;
  611. XML_CharacterDataHandler m_characterDataHandler;
  612. XML_ProcessingInstructionHandler m_processingInstructionHandler;
  613. XML_CommentHandler m_commentHandler;
  614. XML_StartCdataSectionHandler m_startCdataSectionHandler;
  615. XML_EndCdataSectionHandler m_endCdataSectionHandler;
  616. XML_DefaultHandler m_defaultHandler;
  617. XML_StartDoctypeDeclHandler m_startDoctypeDeclHandler;
  618. XML_EndDoctypeDeclHandler m_endDoctypeDeclHandler;
  619. XML_UnparsedEntityDeclHandler m_unparsedEntityDeclHandler;
  620. XML_NotationDeclHandler m_notationDeclHandler;
  621. XML_StartNamespaceDeclHandler m_startNamespaceDeclHandler;
  622. XML_EndNamespaceDeclHandler m_endNamespaceDeclHandler;
  623. XML_NotStandaloneHandler m_notStandaloneHandler;
  624. XML_ExternalEntityRefHandler m_externalEntityRefHandler;
  625. XML_Parser m_externalEntityRefHandlerArg;
  626. XML_SkippedEntityHandler m_skippedEntityHandler;
  627. XML_UnknownEncodingHandler m_unknownEncodingHandler;
  628. XML_ElementDeclHandler m_elementDeclHandler;
  629. XML_AttlistDeclHandler m_attlistDeclHandler;
  630. XML_EntityDeclHandler m_entityDeclHandler;
  631. XML_XmlDeclHandler m_xmlDeclHandler;
  632. const ENCODING *m_encoding;
  633. INIT_ENCODING m_initEncoding;
  634. const ENCODING *m_internalEncoding;
  635. const XML_Char *m_protocolEncodingName;
  636. XML_Bool m_ns;
  637. XML_Bool m_ns_triplets;
  638. void *m_unknownEncodingMem;
  639. void *m_unknownEncodingData;
  640. void *m_unknownEncodingHandlerData;
  641. void(XMLCALL *m_unknownEncodingRelease)(void *);
  642. PROLOG_STATE m_prologState;
  643. Processor *m_processor;
  644. enum XML_Error m_errorCode;
  645. const char *m_eventPtr;
  646. const char *m_eventEndPtr;
  647. const char *m_positionPtr;
  648. OPEN_INTERNAL_ENTITY *m_openInternalEntities;
  649. OPEN_INTERNAL_ENTITY *m_freeInternalEntities;
  650. OPEN_INTERNAL_ENTITY *m_openAttributeEntities;
  651. OPEN_INTERNAL_ENTITY *m_freeAttributeEntities;
  652. OPEN_INTERNAL_ENTITY *m_openValueEntities;
  653. OPEN_INTERNAL_ENTITY *m_freeValueEntities;
  654. XML_Bool m_defaultExpandInternalEntities;
  655. int m_tagLevel;
  656. ENTITY *m_declEntity;
  657. const XML_Char *m_doctypeName;
  658. const XML_Char *m_doctypeSysid;
  659. const XML_Char *m_doctypePubid;
  660. const XML_Char *m_declAttributeType;
  661. const XML_Char *m_declNotationName;
  662. const XML_Char *m_declNotationPublicId;
  663. ELEMENT_TYPE *m_declElementType;
  664. ATTRIBUTE_ID *m_declAttributeId;
  665. XML_Bool m_declAttributeIsCdata;
  666. XML_Bool m_declAttributeIsId;
  667. DTD *m_dtd;
  668. const XML_Char *m_curBase;
  669. TAG *m_tagStack;
  670. TAG *m_freeTagList;
  671. BINDING *m_inheritedBindings;
  672. BINDING *m_freeBindingList;
  673. int m_attsSize;
  674. int m_nSpecifiedAtts;
  675. int m_idAttIndex;
  676. ATTRIBUTE *m_atts;
  677. NS_ATT *m_nsAtts;
  678. unsigned long m_nsAttsVersion;
  679. unsigned char m_nsAttsPower;
  680. #ifdef XML_ATTR_INFO
  681. XML_AttrInfo *m_attInfo;
  682. #endif
  683. POSITION m_position;
  684. STRING_POOL m_tempPool;
  685. STRING_POOL m_temp2Pool;
  686. char *m_groupConnector;
  687. unsigned int m_groupSize;
  688. XML_Char m_namespaceSeparator;
  689. XML_Parser m_parentParser;
  690. XML_ParsingStatus m_parsingStatus;
  691. #ifdef XML_DTD
  692. XML_Bool m_isParamEntity;
  693. XML_Bool m_useForeignDTD;
  694. enum XML_ParamEntityParsing m_paramEntityParsing;
  695. #endif
  696. unsigned long m_hash_secret_salt;
  697. #if XML_GE == 1
  698. ACCOUNTING m_accounting;
  699. MALLOC_TRACKER m_alloc_tracker;
  700. ENTITY_STATS m_entity_stats;
  701. #endif
  702. XML_Bool m_reenter;
  703. };
  704. #if XML_GE == 1
  705. # define MALLOC(parser, s) (expat_malloc((parser), (s), __LINE__))
  706. # define REALLOC(parser, p, s) (expat_realloc((parser), (p), (s), __LINE__))
  707. # define FREE(parser, p) (expat_free((parser), (p), __LINE__))
  708. #else
  709. # define MALLOC(parser, s) (parser->m_mem.malloc_fcn((s)))
  710. # define REALLOC(parser, p, s) (parser->m_mem.realloc_fcn((p), (s)))
  711. # define FREE(parser, p) (parser->m_mem.free_fcn((p)))
  712. #endif
  713. #if XML_GE == 1
  714. static void
  715. expat_heap_stat(XML_Parser rootParser, char operator, XmlBigCount absDiff,
  716. XmlBigCount newTotal, XmlBigCount peakTotal, int sourceLine) {
  717. // NOTE: This can be +infinity or -nan
  718. const float amplification
  719. = (float)newTotal / (float)rootParser->m_accounting.countBytesDirect;
  720. fprintf(
  721. stderr,
  722. "expat: Allocations(%p): Direct " EXPAT_FMT_ULL("10") ", allocated %c" EXPAT_FMT_ULL(
  723. "10") " to " EXPAT_FMT_ULL("10") " (" EXPAT_FMT_ULL("10") " peak), amplification %8.2f (xmlparse.c:%d)\n",
  724. (void *)rootParser, rootParser->m_accounting.countBytesDirect, operator,
  725. absDiff, newTotal, peakTotal, (double)amplification, sourceLine);
  726. }
  727. static bool
  728. expat_heap_increase_tolerable(XML_Parser rootParser, XmlBigCount increase,
  729. int sourceLine) {
  730. assert(rootParser != NULL);
  731. assert(increase > 0);
  732. XmlBigCount newTotal = 0;
  733. bool tolerable = true;
  734. // Detect integer overflow
  735. if ((XmlBigCount)-1 - rootParser->m_alloc_tracker.bytesAllocated < increase) {
  736. tolerable = false;
  737. } else {
  738. newTotal = rootParser->m_alloc_tracker.bytesAllocated + increase;
  739. if (newTotal >= rootParser->m_alloc_tracker.activationThresholdBytes) {
  740. assert(newTotal > 0);
  741. // NOTE: This can be +infinity when dividing by zero but not -nan
  742. const float amplification
  743. = (float)newTotal / (float)rootParser->m_accounting.countBytesDirect;
  744. if (amplification
  745. > rootParser->m_alloc_tracker.maximumAmplificationFactor) {
  746. tolerable = false;
  747. }
  748. }
  749. }
  750. if (! tolerable && (rootParser->m_alloc_tracker.debugLevel >= 1)) {
  751. expat_heap_stat(rootParser, '+', increase, newTotal, newTotal, sourceLine);
  752. }
  753. return tolerable;
  754. }
  755. # if defined(XML_TESTING)
  756. void *
  757. # else
  758. static void *
  759. # endif
  760. expat_malloc(XML_Parser parser, size_t size, int sourceLine) {
  761. // Detect integer overflow
  762. if (SIZE_MAX - size < sizeof(size_t) + EXPAT_MALLOC_PADDING) {
  763. return NULL;
  764. }
  765. const XML_Parser rootParser = getRootParserOf(parser, NULL);
  766. assert(rootParser->m_parentParser == NULL);
  767. const size_t bytesToAllocate = sizeof(size_t) + EXPAT_MALLOC_PADDING + size;
  768. if ((XmlBigCount)-1 - rootParser->m_alloc_tracker.bytesAllocated
  769. < bytesToAllocate) {
  770. return NULL; // i.e. signal integer overflow as out-of-memory
  771. }
  772. if (! expat_heap_increase_tolerable(rootParser, bytesToAllocate,
  773. sourceLine)) {
  774. return NULL; // i.e. signal violation as out-of-memory
  775. }
  776. // Actually allocate
  777. void *const mallocedPtr = parser->m_mem.malloc_fcn(bytesToAllocate);
  778. if (mallocedPtr == NULL) {
  779. return NULL;
  780. }
  781. // Update in-block recorded size
  782. *(size_t *)mallocedPtr = size;
  783. // Update accounting
  784. rootParser->m_alloc_tracker.bytesAllocated += bytesToAllocate;
  785. // Report as needed
  786. if (rootParser->m_alloc_tracker.debugLevel >= 2) {
  787. if (rootParser->m_alloc_tracker.bytesAllocated
  788. > rootParser->m_alloc_tracker.peakBytesAllocated) {
  789. rootParser->m_alloc_tracker.peakBytesAllocated
  790. = rootParser->m_alloc_tracker.bytesAllocated;
  791. }
  792. expat_heap_stat(rootParser, '+', bytesToAllocate,
  793. rootParser->m_alloc_tracker.bytesAllocated,
  794. rootParser->m_alloc_tracker.peakBytesAllocated, sourceLine);
  795. }
  796. return (char *)mallocedPtr + sizeof(size_t) + EXPAT_MALLOC_PADDING;
  797. }
  798. # if defined(XML_TESTING)
  799. void
  800. # else
  801. static void
  802. # endif
  803. expat_free(XML_Parser parser, void *ptr, int sourceLine) {
  804. assert(parser != NULL);
  805. if (ptr == NULL) {
  806. return;
  807. }
  808. const XML_Parser rootParser = getRootParserOf(parser, NULL);
  809. assert(rootParser->m_parentParser == NULL);
  810. // Extract size (to the eyes of malloc_fcn/realloc_fcn) and
  811. // the original pointer returned by malloc/realloc
  812. void *const mallocedPtr = (char *)ptr - EXPAT_MALLOC_PADDING - sizeof(size_t);
  813. const size_t bytesAllocated
  814. = sizeof(size_t) + EXPAT_MALLOC_PADDING + *(size_t *)mallocedPtr;
  815. // Update accounting
  816. assert(rootParser->m_alloc_tracker.bytesAllocated >= bytesAllocated);
  817. rootParser->m_alloc_tracker.bytesAllocated -= bytesAllocated;
  818. // Report as needed
  819. if (rootParser->m_alloc_tracker.debugLevel >= 2) {
  820. expat_heap_stat(rootParser, '-', bytesAllocated,
  821. rootParser->m_alloc_tracker.bytesAllocated,
  822. rootParser->m_alloc_tracker.peakBytesAllocated, sourceLine);
  823. }
  824. // NOTE: This may be freeing rootParser, so freeing has to come last
  825. parser->m_mem.free_fcn(mallocedPtr);
  826. }
  827. # if defined(XML_TESTING)
  828. void *
  829. # else
  830. static void *
  831. # endif
  832. expat_realloc(XML_Parser parser, void *ptr, size_t size, int sourceLine) {
  833. assert(parser != NULL);
  834. if (ptr == NULL) {
  835. return expat_malloc(parser, size, sourceLine);
  836. }
  837. if (size == 0) {
  838. expat_free(parser, ptr, sourceLine);
  839. return NULL;
  840. }
  841. const XML_Parser rootParser = getRootParserOf(parser, NULL);
  842. assert(rootParser->m_parentParser == NULL);
  843. // Extract original size (to the eyes of the caller) and the original
  844. // pointer returned by malloc/realloc
  845. void *mallocedPtr = (char *)ptr - EXPAT_MALLOC_PADDING - sizeof(size_t);
  846. const size_t prevSize = *(size_t *)mallocedPtr;
  847. // Classify upcoming change
  848. const bool isIncrease = (size > prevSize);
  849. const size_t absDiff
  850. = (size > prevSize) ? (size - prevSize) : (prevSize - size);
  851. // Ask for permission from accounting
  852. if (isIncrease) {
  853. if (! expat_heap_increase_tolerable(rootParser, absDiff, sourceLine)) {
  854. return NULL; // i.e. signal violation as out-of-memory
  855. }
  856. }
  857. // NOTE: Integer overflow detection has already been done for us
  858. // by expat_heap_increase_tolerable(..) above
  859. assert(SIZE_MAX - sizeof(size_t) - EXPAT_MALLOC_PADDING >= size);
  860. // Actually allocate
  861. mallocedPtr = parser->m_mem.realloc_fcn(
  862. mallocedPtr, sizeof(size_t) + EXPAT_MALLOC_PADDING + size);
  863. if (mallocedPtr == NULL) {
  864. return NULL;
  865. }
  866. // Update accounting
  867. if (isIncrease) {
  868. assert((XmlBigCount)-1 - rootParser->m_alloc_tracker.bytesAllocated
  869. >= absDiff);
  870. rootParser->m_alloc_tracker.bytesAllocated += absDiff;
  871. } else { // i.e. decrease
  872. assert(rootParser->m_alloc_tracker.bytesAllocated >= absDiff);
  873. rootParser->m_alloc_tracker.bytesAllocated -= absDiff;
  874. }
  875. // Report as needed
  876. if (rootParser->m_alloc_tracker.debugLevel >= 2) {
  877. if (rootParser->m_alloc_tracker.bytesAllocated
  878. > rootParser->m_alloc_tracker.peakBytesAllocated) {
  879. rootParser->m_alloc_tracker.peakBytesAllocated
  880. = rootParser->m_alloc_tracker.bytesAllocated;
  881. }
  882. expat_heap_stat(rootParser, isIncrease ? '+' : '-', absDiff,
  883. rootParser->m_alloc_tracker.bytesAllocated,
  884. rootParser->m_alloc_tracker.peakBytesAllocated, sourceLine);
  885. }
  886. // Update in-block recorded size
  887. *(size_t *)mallocedPtr = size;
  888. return (char *)mallocedPtr + sizeof(size_t) + EXPAT_MALLOC_PADDING;
  889. }
  890. #endif // XML_GE == 1
  891. XML_Parser XMLCALL
  892. XML_ParserCreate(const XML_Char *encodingName) {
  893. return XML_ParserCreate_MM(encodingName, NULL, NULL);
  894. }
  895. XML_Parser XMLCALL
  896. XML_ParserCreateNS(const XML_Char *encodingName, XML_Char nsSep) {
  897. XML_Char tmp[2] = {nsSep, 0};
  898. return XML_ParserCreate_MM(encodingName, NULL, tmp);
  899. }
  900. // "xml=http://www.w3.org/XML/1998/namespace"
  901. static const XML_Char implicitContext[]
  902. = {ASCII_x, ASCII_m, ASCII_l, ASCII_EQUALS, ASCII_h,
  903. ASCII_t, ASCII_t, ASCII_p, ASCII_COLON, ASCII_SLASH,
  904. ASCII_SLASH, ASCII_w, ASCII_w, ASCII_w, ASCII_PERIOD,
  905. ASCII_w, ASCII_3, ASCII_PERIOD, ASCII_o, ASCII_r,
  906. ASCII_g, ASCII_SLASH, ASCII_X, ASCII_M, ASCII_L,
  907. ASCII_SLASH, ASCII_1, ASCII_9, ASCII_9, ASCII_8,
  908. ASCII_SLASH, ASCII_n, ASCII_a, ASCII_m, ASCII_e,
  909. ASCII_s, ASCII_p, ASCII_a, ASCII_c, ASCII_e,
  910. '\0'};
  911. /* To avoid warnings about unused functions: */
  912. #if ! defined(HAVE_ARC4RANDOM_BUF) && ! defined(HAVE_ARC4RANDOM)
  913. # if defined(HAVE_GETRANDOM) || defined(HAVE_SYSCALL_GETRANDOM)
  914. /* Obtain entropy on Linux 3.17+ */
  915. static int
  916. writeRandomBytes_getrandom_nonblock(void *target, size_t count) {
  917. int success = 0; /* full count bytes written? */
  918. size_t bytesWrittenTotal = 0;
  919. const unsigned int getrandomFlags = GRND_NONBLOCK;
  920. do {
  921. void *const currentTarget = (void *)((char *)target + bytesWrittenTotal);
  922. const size_t bytesToWrite = count - bytesWrittenTotal;
  923. assert(bytesToWrite <= INT_MAX);
  924. const int bytesWrittenMore =
  925. # if defined(HAVE_GETRANDOM)
  926. (int)getrandom(currentTarget, bytesToWrite, getrandomFlags);
  927. # else
  928. (int)syscall(SYS_getrandom, currentTarget, bytesToWrite,
  929. getrandomFlags);
  930. # endif
  931. if (bytesWrittenMore > 0) {
  932. bytesWrittenTotal += bytesWrittenMore;
  933. if (bytesWrittenTotal >= count)
  934. success = 1;
  935. }
  936. } while (! success && (errno == EINTR));
  937. return success;
  938. }
  939. # endif /* defined(HAVE_GETRANDOM) || defined(HAVE_SYSCALL_GETRANDOM) */
  940. # if ! defined(_WIN32) && defined(XML_DEV_URANDOM)
  941. /* Extract entropy from /dev/urandom */
  942. static int
  943. writeRandomBytes_dev_urandom(void *target, size_t count) {
  944. int success = 0; /* full count bytes written? */
  945. size_t bytesWrittenTotal = 0;
  946. const int fd = open("/dev/urandom", O_RDONLY);
  947. if (fd < 0) {
  948. return 0;
  949. }
  950. do {
  951. void *const currentTarget = (void *)((char *)target + bytesWrittenTotal);
  952. const size_t bytesToWrite = count - bytesWrittenTotal;
  953. const ssize_t bytesWrittenMore = read(fd, currentTarget, bytesToWrite);
  954. if (bytesWrittenMore > 0) {
  955. bytesWrittenTotal += bytesWrittenMore;
  956. if (bytesWrittenTotal >= count)
  957. success = 1;
  958. }
  959. } while (! success && (errno == EINTR));
  960. close(fd);
  961. return success;
  962. }
  963. # endif /* ! defined(_WIN32) && defined(XML_DEV_URANDOM) */
  964. #endif /* ! defined(HAVE_ARC4RANDOM_BUF) && ! defined(HAVE_ARC4RANDOM) */
  965. #if defined(HAVE_ARC4RANDOM) && ! defined(HAVE_ARC4RANDOM_BUF)
  966. static void
  967. writeRandomBytes_arc4random(void *target, size_t count) {
  968. size_t bytesWrittenTotal = 0;
  969. while (bytesWrittenTotal < count) {
  970. const uint32_t random32 = arc4random();
  971. size_t i = 0;
  972. for (; (i < sizeof(random32)) && (bytesWrittenTotal < count);
  973. i++, bytesWrittenTotal++) {
  974. const uint8_t random8 = (uint8_t)(random32 >> (i * 8));
  975. ((uint8_t *)target)[bytesWrittenTotal] = random8;
  976. }
  977. }
  978. }
  979. #endif /* defined(HAVE_ARC4RANDOM) && ! defined(HAVE_ARC4RANDOM_BUF) */
  980. #ifdef _WIN32
  981. /* Provide declaration of rand_s() for MinGW-32 (not 64, which has it),
  982. as it didn't declare it in its header prior to version 5.3.0 of its
  983. runtime package (mingwrt, containing stdlib.h). The upstream fix
  984. was introduced at https://osdn.net/projects/mingw/ticket/39658 . */
  985. # if defined(__MINGW32__) && defined(__MINGW32_VERSION) \
  986. && __MINGW32_VERSION < 5003000L && ! defined(__MINGW64_VERSION_MAJOR)
  987. __declspec(dllimport) int rand_s(unsigned int *);
  988. # endif
  989. /* Obtain entropy on Windows using the rand_s() function which
  990. * generates cryptographically secure random numbers. Internally it
  991. * uses RtlGenRandom API which is present in Windows XP and later.
  992. */
  993. static int
  994. writeRandomBytes_rand_s(void *target, size_t count) {
  995. size_t bytesWrittenTotal = 0;
  996. while (bytesWrittenTotal < count) {
  997. unsigned int random32 = 0;
  998. size_t i = 0;
  999. if (rand_s(&random32))
  1000. return 0; /* failure */
  1001. for (; (i < sizeof(random32)) && (bytesWrittenTotal < count);
  1002. i++, bytesWrittenTotal++) {
  1003. const uint8_t random8 = (uint8_t)(random32 >> (i * 8));
  1004. ((uint8_t *)target)[bytesWrittenTotal] = random8;
  1005. }
  1006. }
  1007. return 1; /* success */
  1008. }
  1009. #endif /* _WIN32 */
  1010. #if ! defined(HAVE_ARC4RANDOM_BUF) && ! defined(HAVE_ARC4RANDOM)
  1011. static unsigned long
  1012. gather_time_entropy(void) {
  1013. # ifdef _WIN32
  1014. FILETIME ft;
  1015. GetSystemTimeAsFileTime(&ft); /* never fails */
  1016. return ft.dwHighDateTime ^ ft.dwLowDateTime;
  1017. # else
  1018. struct timeval tv;
  1019. int gettimeofday_res;
  1020. gettimeofday_res = gettimeofday(&tv, NULL);
  1021. # if defined(NDEBUG)
  1022. (void)gettimeofday_res;
  1023. # else
  1024. assert(gettimeofday_res == 0);
  1025. # endif /* defined(NDEBUG) */
  1026. /* Microseconds time is <20 bits entropy */
  1027. return tv.tv_usec;
  1028. # endif
  1029. }
  1030. #endif /* ! defined(HAVE_ARC4RANDOM_BUF) && ! defined(HAVE_ARC4RANDOM) */
  1031. static unsigned long
  1032. ENTROPY_DEBUG(const char *label, unsigned long entropy) {
  1033. if (getDebugLevel("EXPAT_ENTROPY_DEBUG", 0) >= 1u) {
  1034. fprintf(stderr, "expat: Entropy: %s --> 0x%0*lx (%lu bytes)\n", label,
  1035. (int)sizeof(entropy) * 2, entropy, (unsigned long)sizeof(entropy));
  1036. }
  1037. return entropy;
  1038. }
  1039. static unsigned long
  1040. generate_hash_secret_salt(XML_Parser parser) {
  1041. unsigned long entropy;
  1042. (void)parser;
  1043. /* "Failproof" high quality providers: */
  1044. #if defined(HAVE_ARC4RANDOM_BUF)
  1045. arc4random_buf(&entropy, sizeof(entropy));
  1046. return ENTROPY_DEBUG("arc4random_buf", entropy);
  1047. #elif defined(HAVE_ARC4RANDOM)
  1048. writeRandomBytes_arc4random((void *)&entropy, sizeof(entropy));
  1049. return ENTROPY_DEBUG("arc4random", entropy);
  1050. #else
  1051. /* Try high quality providers first .. */
  1052. # ifdef _WIN32
  1053. if (writeRandomBytes_rand_s((void *)&entropy, sizeof(entropy))) {
  1054. return ENTROPY_DEBUG("rand_s", entropy);
  1055. }
  1056. # elif defined(HAVE_GETRANDOM) || defined(HAVE_SYSCALL_GETRANDOM)
  1057. if (writeRandomBytes_getrandom_nonblock((void *)&entropy, sizeof(entropy))) {
  1058. return ENTROPY_DEBUG("getrandom", entropy);
  1059. }
  1060. # endif
  1061. # if ! defined(_WIN32) && defined(XML_DEV_URANDOM)
  1062. if (writeRandomBytes_dev_urandom((void *)&entropy, sizeof(entropy))) {
  1063. return ENTROPY_DEBUG("/dev/urandom", entropy);
  1064. }
  1065. # endif /* ! defined(_WIN32) && defined(XML_DEV_URANDOM) */
  1066. /* .. and self-made low quality for backup: */
  1067. entropy = gather_time_entropy();
  1068. # if ! defined(__wasi__)
  1069. /* Process ID is 0 bits entropy if attacker has local access */
  1070. entropy ^= getpid();
  1071. # endif
  1072. /* Factors are 2^31-1 and 2^61-1 (Mersenne primes M31 and M61) */
  1073. if (sizeof(unsigned long) == 4) {
  1074. return ENTROPY_DEBUG("fallback(4)", entropy * 2147483647);
  1075. } else {
  1076. return ENTROPY_DEBUG("fallback(8)",
  1077. entropy * (unsigned long)2305843009213693951ULL);
  1078. }
  1079. #endif
  1080. }
  1081. static unsigned long
  1082. get_hash_secret_salt(XML_Parser parser) {
  1083. const XML_Parser rootParser = getRootParserOf(parser, NULL);
  1084. assert(! rootParser->m_parentParser);
  1085. return rootParser->m_hash_secret_salt;
  1086. }
  1087. static enum XML_Error
  1088. callProcessor(XML_Parser parser, const char *start, const char *end,
  1089. const char **endPtr) {
  1090. const size_t have_now = EXPAT_SAFE_PTR_DIFF(end, start);
  1091. if (parser->m_reparseDeferralEnabled
  1092. && ! parser->m_parsingStatus.finalBuffer) {
  1093. // Heuristic: don't try to parse a partial token again until the amount of
  1094. // available data has increased significantly.
  1095. const size_t had_before = parser->m_partialTokenBytesBefore;
  1096. // ...but *do* try anyway if we're close to causing a reallocation.
  1097. size_t available_buffer
  1098. = EXPAT_SAFE_PTR_DIFF(parser->m_bufferPtr, parser->m_buffer);
  1099. #if XML_CONTEXT_BYTES > 0
  1100. available_buffer -= EXPAT_MIN(available_buffer, XML_CONTEXT_BYTES);
  1101. #endif
  1102. available_buffer
  1103. += EXPAT_SAFE_PTR_DIFF(parser->m_bufferLim, parser->m_bufferEnd);
  1104. // m_lastBufferRequestSize is never assigned a value < 0, so the cast is ok
  1105. const bool enough
  1106. = (have_now >= 2 * had_before)
  1107. || ((size_t)parser->m_lastBufferRequestSize > available_buffer);
  1108. if (! enough) {
  1109. *endPtr = start; // callers may expect this to be set
  1110. return XML_ERROR_NONE;
  1111. }
  1112. }
  1113. #if defined(XML_TESTING)
  1114. g_bytesScanned += (unsigned)have_now;
  1115. #endif
  1116. // Run in a loop to eliminate dangerous recursion depths
  1117. enum XML_Error ret;
  1118. *endPtr = start;
  1119. while (1) {
  1120. // Use endPtr as the new start in each iteration, since it will
  1121. // be set to the next start point by m_processor.
  1122. ret = parser->m_processor(parser, *endPtr, end, endPtr);
  1123. // Make parsing status (and in particular XML_SUSPENDED) take
  1124. // precedence over re-enter flag when they disagree
  1125. if (parser->m_parsingStatus.parsing != XML_PARSING) {
  1126. parser->m_reenter = XML_FALSE;
  1127. }
  1128. if (! parser->m_reenter) {
  1129. break;
  1130. }
  1131. parser->m_reenter = XML_FALSE;
  1132. if (ret != XML_ERROR_NONE)
  1133. return ret;
  1134. }
  1135. if (ret == XML_ERROR_NONE) {
  1136. // if we consumed nothing, remember what we had on this parse attempt.
  1137. if (*endPtr == start) {
  1138. parser->m_partialTokenBytesBefore = have_now;
  1139. } else {
  1140. parser->m_partialTokenBytesBefore = 0;
  1141. }
  1142. }
  1143. return ret;
  1144. }
  1145. static XML_Bool /* only valid for root parser */
  1146. startParsing(XML_Parser parser) {
  1147. /* hash functions must be initialized before setContext() is called */
  1148. if (parser->m_hash_secret_salt == 0)
  1149. parser->m_hash_secret_salt = generate_hash_secret_salt(parser);
  1150. if (parser->m_ns) {
  1151. /* implicit context only set for root parser, since child
  1152. parsers (i.e. external entity parsers) will inherit it
  1153. */
  1154. return setContext(parser, implicitContext);
  1155. }
  1156. return XML_TRUE;
  1157. }
  1158. XML_Parser XMLCALL
  1159. XML_ParserCreate_MM(const XML_Char *encodingName,
  1160. const XML_Memory_Handling_Suite *memsuite,
  1161. const XML_Char *nameSep) {
  1162. return parserCreate(encodingName, memsuite, nameSep, NULL, NULL);
  1163. }
  1164. static XML_Parser
  1165. parserCreate(const XML_Char *encodingName,
  1166. const XML_Memory_Handling_Suite *memsuite, const XML_Char *nameSep,
  1167. DTD *dtd, XML_Parser parentParser) {
  1168. XML_Parser parser = NULL;
  1169. #if XML_GE == 1
  1170. const size_t increase
  1171. = sizeof(size_t) + EXPAT_MALLOC_PADDING + sizeof(struct XML_ParserStruct);
  1172. if (parentParser != NULL) {
  1173. const XML_Parser rootParser = getRootParserOf(parentParser, NULL);
  1174. if (! expat_heap_increase_tolerable(rootParser, increase, __LINE__)) {
  1175. return NULL;
  1176. }
  1177. }
  1178. #else
  1179. UNUSED_P(parentParser);
  1180. #endif
  1181. if (memsuite) {
  1182. XML_Memory_Handling_Suite *mtemp;
  1183. #if XML_GE == 1
  1184. void *const sizeAndParser
  1185. = memsuite->malloc_fcn(sizeof(size_t) + EXPAT_MALLOC_PADDING
  1186. + sizeof(struct XML_ParserStruct));
  1187. if (sizeAndParser != NULL) {
  1188. *(size_t *)sizeAndParser = sizeof(struct XML_ParserStruct);
  1189. parser = (XML_Parser)((char *)sizeAndParser + sizeof(size_t)
  1190. + EXPAT_MALLOC_PADDING);
  1191. #else
  1192. parser = memsuite->malloc_fcn(sizeof(struct XML_ParserStruct));
  1193. if (parser != NULL) {
  1194. #endif
  1195. mtemp = (XML_Memory_Handling_Suite *)&(parser->m_mem);
  1196. mtemp->malloc_fcn = memsuite->malloc_fcn;
  1197. mtemp->realloc_fcn = memsuite->realloc_fcn;
  1198. mtemp->free_fcn = memsuite->free_fcn;
  1199. }
  1200. } else {
  1201. XML_Memory_Handling_Suite *mtemp;
  1202. #if XML_GE == 1
  1203. void *const sizeAndParser = malloc(sizeof(size_t) + EXPAT_MALLOC_PADDING
  1204. + sizeof(struct XML_ParserStruct));
  1205. if (sizeAndParser != NULL) {
  1206. *(size_t *)sizeAndParser = sizeof(struct XML_ParserStruct);
  1207. parser = (XML_Parser)((char *)sizeAndParser + sizeof(size_t)
  1208. + EXPAT_MALLOC_PADDING);
  1209. #else
  1210. parser = malloc(sizeof(struct XML_ParserStruct));
  1211. if (parser != NULL) {
  1212. #endif
  1213. mtemp = (XML_Memory_Handling_Suite *)&(parser->m_mem);
  1214. mtemp->malloc_fcn = malloc;
  1215. mtemp->realloc_fcn = realloc;
  1216. mtemp->free_fcn = free;
  1217. }
  1218. } // cppcheck-suppress[memleak symbolName=sizeAndParser] // Cppcheck >=2.18.0
  1219. if (! parser)
  1220. return parser;
  1221. #if XML_GE == 1
  1222. // Initialize .m_alloc_tracker
  1223. memset(&parser->m_alloc_tracker, 0, sizeof(MALLOC_TRACKER));
  1224. if (parentParser == NULL) {
  1225. parser->m_alloc_tracker.debugLevel
  1226. = getDebugLevel("EXPAT_MALLOC_DEBUG", 0u);
  1227. parser->m_alloc_tracker.maximumAmplificationFactor
  1228. = EXPAT_ALLOC_TRACKER_MAXIMUM_AMPLIFICATION_DEFAULT;
  1229. parser->m_alloc_tracker.activationThresholdBytes
  1230. = EXPAT_ALLOC_TRACKER_ACTIVATION_THRESHOLD_DEFAULT;
  1231. // NOTE: This initialization needs to come this early because these fields
  1232. // are read by allocation tracking code
  1233. parser->m_parentParser = NULL;
  1234. parser->m_accounting.countBytesDirect = 0;
  1235. } else {
  1236. parser->m_parentParser = parentParser;
  1237. }
  1238. // Record XML_ParserStruct allocation we did a few lines up before
  1239. const XML_Parser rootParser = getRootParserOf(parser, NULL);
  1240. assert(rootParser->m_parentParser == NULL);
  1241. assert(SIZE_MAX - rootParser->m_alloc_tracker.bytesAllocated >= increase);
  1242. rootParser->m_alloc_tracker.bytesAllocated += increase;
  1243. // Report on allocation
  1244. if (rootParser->m_alloc_tracker.debugLevel >= 2) {
  1245. if (rootParser->m_alloc_tracker.bytesAllocated
  1246. > rootParser->m_alloc_tracker.peakBytesAllocated) {
  1247. rootParser->m_alloc_tracker.peakBytesAllocated
  1248. = rootParser->m_alloc_tracker.bytesAllocated;
  1249. }
  1250. expat_heap_stat(rootParser, '+', increase,
  1251. rootParser->m_alloc_tracker.bytesAllocated,
  1252. rootParser->m_alloc_tracker.peakBytesAllocated, __LINE__);
  1253. }
  1254. #else
  1255. parser->m_parentParser = NULL;
  1256. #endif // XML_GE == 1
  1257. parser->m_buffer = NULL;
  1258. parser->m_bufferLim = NULL;
  1259. parser->m_attsSize = INIT_ATTS_SIZE;
  1260. parser->m_atts = MALLOC(parser, parser->m_attsSize * sizeof(ATTRIBUTE));
  1261. if (parser->m_atts == NULL) {
  1262. FREE(parser, parser);
  1263. return NULL;
  1264. }
  1265. #ifdef XML_ATTR_INFO
  1266. parser->m_attInfo = MALLOC(parser, parser->m_attsSize * sizeof(XML_AttrInfo));
  1267. if (parser->m_attInfo == NULL) {
  1268. FREE(parser, parser->m_atts);
  1269. FREE(parser, parser);
  1270. return NULL;
  1271. }
  1272. #endif
  1273. parser->m_dataBuf = MALLOC(parser, INIT_DATA_BUF_SIZE * sizeof(XML_Char));
  1274. if (parser->m_dataBuf == NULL) {
  1275. FREE(parser, parser->m_atts);
  1276. #ifdef XML_ATTR_INFO
  1277. FREE(parser, parser->m_attInfo);
  1278. #endif
  1279. FREE(parser, parser);
  1280. return NULL;
  1281. }
  1282. parser->m_dataBufEnd = parser->m_dataBuf + INIT_DATA_BUF_SIZE;
  1283. if (dtd)
  1284. parser->m_dtd = dtd;
  1285. else {
  1286. parser->m_dtd = dtdCreate(parser);
  1287. if (parser->m_dtd == NULL) {
  1288. FREE(parser, parser->m_dataBuf);
  1289. FREE(parser, parser->m_atts);
  1290. #ifdef XML_ATTR_INFO
  1291. FREE(parser, parser->m_attInfo);
  1292. #endif
  1293. FREE(parser, parser);
  1294. return NULL;
  1295. }
  1296. }
  1297. parser->m_freeBindingList = NULL;
  1298. parser->m_freeTagList = NULL;
  1299. parser->m_freeInternalEntities = NULL;
  1300. parser->m_freeAttributeEntities = NULL;
  1301. parser->m_freeValueEntities = NULL;
  1302. parser->m_groupSize = 0;
  1303. parser->m_groupConnector = NULL;
  1304. parser->m_unknownEncodingHandler = NULL;
  1305. parser->m_unknownEncodingHandlerData = NULL;
  1306. parser->m_namespaceSeparator = ASCII_EXCL;
  1307. parser->m_ns = XML_FALSE;
  1308. parser->m_ns_triplets = XML_FALSE;
  1309. parser->m_nsAtts = NULL;
  1310. parser->m_nsAttsVersion = 0;
  1311. parser->m_nsAttsPower = 0;
  1312. parser->m_protocolEncodingName = NULL;
  1313. poolInit(&parser->m_tempPool, parser);
  1314. poolInit(&parser->m_temp2Pool, parser);
  1315. parserInit(parser, encodingName);
  1316. if (encodingName && ! parser->m_protocolEncodingName) {
  1317. if (dtd) {
  1318. // We need to stop the upcoming call to XML_ParserFree from happily
  1319. // destroying parser->m_dtd because the DTD is shared with the parent
  1320. // parser and the only guard that keeps XML_ParserFree from destroying
  1321. // parser->m_dtd is parser->m_isParamEntity but it will be set to
  1322. // XML_TRUE only later in XML_ExternalEntityParserCreate (or not at all).
  1323. parser->m_dtd = NULL;
  1324. }
  1325. XML_ParserFree(parser);
  1326. return NULL;
  1327. }
  1328. if (nameSep) {
  1329. parser->m_ns = XML_TRUE;
  1330. parser->m_internalEncoding = XmlGetInternalEncodingNS();
  1331. parser->m_namespaceSeparator = *nameSep;
  1332. } else {
  1333. parser->m_internalEncoding = XmlGetInternalEncoding();
  1334. }
  1335. return parser;
  1336. }
  1337. static void
  1338. parserInit(XML_Parser parser, const XML_Char *encodingName) {
  1339. parser->m_processor = prologInitProcessor;
  1340. XmlPrologStateInit(&parser->m_prologState);
  1341. if (encodingName != NULL) {
  1342. parser->m_protocolEncodingName = copyString(encodingName, parser);
  1343. }
  1344. parser->m_curBase = NULL;
  1345. XmlInitEncoding(&parser->m_initEncoding, &parser->m_encoding, 0);
  1346. parser->m_userData = NULL;
  1347. parser->m_handlerArg = NULL;
  1348. parser->m_startElementHandler = NULL;
  1349. parser->m_endElementHandler = NULL;
  1350. parser->m_characterDataHandler = NULL;
  1351. parser->m_processingInstructionHandler = NULL;
  1352. parser->m_commentHandler = NULL;
  1353. parser->m_startCdataSectionHandler = NULL;
  1354. parser->m_endCdataSectionHandler = NULL;
  1355. parser->m_defaultHandler = NULL;
  1356. parser->m_startDoctypeDeclHandler = NULL;
  1357. parser->m_endDoctypeDeclHandler = NULL;
  1358. parser->m_unparsedEntityDeclHandler = NULL;
  1359. parser->m_notationDeclHandler = NULL;
  1360. parser->m_startNamespaceDeclHandler = NULL;
  1361. parser->m_endNamespaceDeclHandler = NULL;
  1362. parser->m_notStandaloneHandler = NULL;
  1363. parser->m_externalEntityRefHandler = NULL;
  1364. parser->m_externalEntityRefHandlerArg = parser;
  1365. parser->m_skippedEntityHandler = NULL;
  1366. parser->m_elementDeclHandler = NULL;
  1367. parser->m_attlistDeclHandler = NULL;
  1368. parser->m_entityDeclHandler = NULL;
  1369. parser->m_xmlDeclHandler = NULL;
  1370. parser->m_bufferPtr = parser->m_buffer;
  1371. parser->m_bufferEnd = parser->m_buffer;
  1372. parser->m_parseEndByteIndex = 0;
  1373. parser->m_parseEndPtr = NULL;
  1374. parser->m_partialTokenBytesBefore = 0;
  1375. parser->m_reparseDeferralEnabled = g_reparseDeferralEnabledDefault;
  1376. parser->m_lastBufferRequestSize = 0;
  1377. parser->m_declElementType = NULL;
  1378. parser->m_declAttributeId = NULL;
  1379. parser->m_declEntity = NULL;
  1380. parser->m_doctypeName = NULL;
  1381. parser->m_doctypeSysid = NULL;
  1382. parser->m_doctypePubid = NULL;
  1383. parser->m_declAttributeType = NULL;
  1384. parser->m_declNotationName = NULL;
  1385. parser->m_declNotationPublicId = NULL;
  1386. parser->m_declAttributeIsCdata = XML_FALSE;
  1387. parser->m_declAttributeIsId = XML_FALSE;
  1388. memset(&parser->m_position, 0, sizeof(POSITION));
  1389. parser->m_errorCode = XML_ERROR_NONE;
  1390. parser->m_eventPtr = NULL;
  1391. parser->m_eventEndPtr = NULL;
  1392. parser->m_positionPtr = NULL;
  1393. parser->m_openInternalEntities = NULL;
  1394. parser->m_openAttributeEntities = NULL;
  1395. parser->m_openValueEntities = NULL;
  1396. parser->m_defaultExpandInternalEntities = XML_TRUE;
  1397. parser->m_tagLevel = 0;
  1398. parser->m_tagStack = NULL;
  1399. parser->m_inheritedBindings = NULL;
  1400. parser->m_nSpecifiedAtts = 0;
  1401. parser->m_unknownEncodingMem = NULL;
  1402. parser->m_unknownEncodingRelease = NULL;
  1403. parser->m_unknownEncodingData = NULL;
  1404. parser->m_parsingStatus.parsing = XML_INITIALIZED;
  1405. // Reentry can only be triggered inside m_processor calls
  1406. parser->m_reenter = XML_FALSE;
  1407. #ifdef XML_DTD
  1408. parser->m_isParamEntity = XML_FALSE;
  1409. parser->m_useForeignDTD = XML_FALSE;
  1410. parser->m_paramEntityParsing = XML_PARAM_ENTITY_PARSING_NEVER;
  1411. #endif
  1412. parser->m_hash_secret_salt = 0;
  1413. #if XML_GE == 1
  1414. memset(&parser->m_accounting, 0, sizeof(ACCOUNTING));
  1415. parser->m_accounting.debugLevel = getDebugLevel("EXPAT_ACCOUNTING_DEBUG", 0u);
  1416. parser->m_accounting.maximumAmplificationFactor
  1417. = EXPAT_BILLION_LAUGHS_ATTACK_PROTECTION_MAXIMUM_AMPLIFICATION_DEFAULT;
  1418. parser->m_accounting.activationThresholdBytes
  1419. = EXPAT_BILLION_LAUGHS_ATTACK_PROTECTION_ACTIVATION_THRESHOLD_DEFAULT;
  1420. memset(&parser->m_entity_stats, 0, sizeof(ENTITY_STATS));
  1421. parser->m_entity_stats.debugLevel = getDebugLevel("EXPAT_ENTITY_DEBUG", 0u);
  1422. #endif
  1423. }
  1424. /* moves list of bindings to m_freeBindingList */
  1425. static void FASTCALL
  1426. moveToFreeBindingList(XML_Parser parser, BINDING *bindings) {
  1427. while (bindings) {
  1428. BINDING *b = bindings;
  1429. bindings = bindings->nextTagBinding;
  1430. b->nextTagBinding = parser->m_freeBindingList;
  1431. parser->m_freeBindingList = b;
  1432. }
  1433. }
  1434. XML_Bool XMLCALL
  1435. XML_ParserReset(XML_Parser parser, const XML_Char *encodingName) {
  1436. TAG *tStk;
  1437. OPEN_INTERNAL_ENTITY *openEntityList;
  1438. if (parser == NULL)
  1439. return XML_FALSE;
  1440. if (parser->m_parentParser)
  1441. return XML_FALSE;
  1442. /* move m_tagStack to m_freeTagList */
  1443. tStk = parser->m_tagStack;
  1444. while (tStk) {
  1445. TAG *tag = tStk;
  1446. tStk = tStk->parent;
  1447. tag->parent = parser->m_freeTagList;
  1448. moveToFreeBindingList(parser, tag->bindings);
  1449. tag->bindings = NULL;
  1450. parser->m_freeTagList = tag;
  1451. }
  1452. /* move m_openInternalEntities to m_freeInternalEntities */
  1453. openEntityList = parser->m_openInternalEntities;
  1454. while (openEntityList) {
  1455. OPEN_INTERNAL_ENTITY *openEntity = openEntityList;
  1456. openEntityList = openEntity->next;
  1457. openEntity->next = parser->m_freeInternalEntities;
  1458. parser->m_freeInternalEntities = openEntity;
  1459. }
  1460. /* move m_openAttributeEntities to m_freeAttributeEntities (i.e. same task but
  1461. * for attributes) */
  1462. openEntityList = parser->m_openAttributeEntities;
  1463. while (openEntityList) {
  1464. OPEN_INTERNAL_ENTITY *openEntity = openEntityList;
  1465. openEntityList = openEntity->next;
  1466. openEntity->next = parser->m_freeAttributeEntities;
  1467. parser->m_freeAttributeEntities = openEntity;
  1468. }
  1469. /* move m_openValueEntities to m_freeValueEntities (i.e. same task but
  1470. * for value entities) */
  1471. openEntityList = parser->m_openValueEntities;
  1472. while (openEntityList) {
  1473. OPEN_INTERNAL_ENTITY *openEntity = openEntityList;
  1474. openEntityList = openEntity->next;
  1475. openEntity->next = parser->m_freeValueEntities;
  1476. parser->m_freeValueEntities = openEntity;
  1477. }
  1478. moveToFreeBindingList(parser, parser->m_inheritedBindings);
  1479. FREE(parser, parser->m_unknownEncodingMem);
  1480. if (parser->m_unknownEncodingRelease)
  1481. parser->m_unknownEncodingRelease(parser->m_unknownEncodingData);
  1482. poolClear(&parser->m_tempPool);
  1483. poolClear(&parser->m_temp2Pool);
  1484. FREE(parser, (void *)parser->m_protocolEncodingName);
  1485. parser->m_protocolEncodingName = NULL;
  1486. parserInit(parser, encodingName);
  1487. dtdReset(parser->m_dtd, parser);
  1488. return XML_TRUE;
  1489. }
  1490. static XML_Bool
  1491. parserBusy(XML_Parser parser) {
  1492. switch (parser->m_parsingStatus.parsing) {
  1493. case XML_PARSING:
  1494. case XML_SUSPENDED:
  1495. return XML_TRUE;
  1496. case XML_INITIALIZED:
  1497. case XML_FINISHED:
  1498. default:
  1499. return XML_FALSE;
  1500. }
  1501. }
  1502. enum XML_Status XMLCALL
  1503. XML_SetEncoding(XML_Parser parser, const XML_Char *encodingName) {
  1504. if (parser == NULL)
  1505. return XML_STATUS_ERROR;
  1506. /* Block after XML_Parse()/XML_ParseBuffer() has been called.
  1507. XXX There's no way for the caller to determine which of the
  1508. XXX possible error cases caused the XML_STATUS_ERROR return.
  1509. */
  1510. if (parserBusy(parser))
  1511. return XML_STATUS_ERROR;
  1512. /* Get rid of any previous encoding name */
  1513. FREE(parser, (void *)parser->m_protocolEncodingName);
  1514. if (encodingName == NULL)
  1515. /* No new encoding name */
  1516. parser->m_protocolEncodingName = NULL;
  1517. else {
  1518. /* Copy the new encoding name into allocated memory */
  1519. parser->m_protocolEncodingName = copyString(encodingName, parser);
  1520. if (! parser->m_protocolEncodingName)
  1521. return XML_STATUS_ERROR;
  1522. }
  1523. return XML_STATUS_OK;
  1524. }
  1525. XML_Parser XMLCALL
  1526. XML_ExternalEntityParserCreate(XML_Parser oldParser, const XML_Char *context,
  1527. const XML_Char *encodingName) {
  1528. XML_Parser parser = oldParser;
  1529. DTD *newDtd = NULL;
  1530. DTD *oldDtd;
  1531. XML_StartElementHandler oldStartElementHandler;
  1532. XML_EndElementHandler oldEndElementHandler;
  1533. XML_CharacterDataHandler oldCharacterDataHandler;
  1534. XML_ProcessingInstructionHandler oldProcessingInstructionHandler;
  1535. XML_CommentHandler oldCommentHandler;
  1536. XML_StartCdataSectionHandler oldStartCdataSectionHandler;
  1537. XML_EndCdataSectionHandler oldEndCdataSectionHandler;
  1538. XML_DefaultHandler oldDefaultHandler;
  1539. XML_UnparsedEntityDeclHandler oldUnparsedEntityDeclHandler;
  1540. XML_NotationDeclHandler oldNotationDeclHandler;
  1541. XML_StartNamespaceDeclHandler oldStartNamespaceDeclHandler;
  1542. XML_EndNamespaceDeclHandler oldEndNamespaceDeclHandler;
  1543. XML_NotStandaloneHandler oldNotStandaloneHandler;
  1544. XML_ExternalEntityRefHandler oldExternalEntityRefHandler;
  1545. XML_SkippedEntityHandler oldSkippedEntityHandler;
  1546. XML_UnknownEncodingHandler oldUnknownEncodingHandler;
  1547. void *oldUnknownEncodingHandlerData;
  1548. XML_ElementDeclHandler oldElementDeclHandler;
  1549. XML_AttlistDeclHandler oldAttlistDeclHandler;
  1550. XML_EntityDeclHandler oldEntityDeclHandler;
  1551. XML_XmlDeclHandler oldXmlDeclHandler;
  1552. ELEMENT_TYPE *oldDeclElementType;
  1553. void *oldUserData;
  1554. void *oldHandlerArg;
  1555. XML_Bool oldDefaultExpandInternalEntities;
  1556. XML_Parser oldExternalEntityRefHandlerArg;
  1557. #ifdef XML_DTD
  1558. enum XML_ParamEntityParsing oldParamEntityParsing;
  1559. int oldInEntityValue;
  1560. #endif
  1561. XML_Bool oldns_triplets;
  1562. /* Note that the new parser shares the same hash secret as the old
  1563. parser, so that dtdCopy and copyEntityTable can lookup values
  1564. from hash tables associated with either parser without us having
  1565. to worry which hash secrets each table has.
  1566. */
  1567. unsigned long oldhash_secret_salt;
  1568. XML_Bool oldReparseDeferralEnabled;
  1569. /* Validate the oldParser parameter before we pull everything out of it */
  1570. if (oldParser == NULL)
  1571. return NULL;
  1572. /* Stash the original parser contents on the stack */
  1573. oldDtd = parser->m_dtd;
  1574. oldStartElementHandler = parser->m_startElementHandler;
  1575. oldEndElementHandler = parser->m_endElementHandler;
  1576. oldCharacterDataHandler = parser->m_characterDataHandler;
  1577. oldProcessingInstructionHandler = parser->m_processingInstructionHandler;
  1578. oldCommentHandler = parser->m_commentHandler;
  1579. oldStartCdataSectionHandler = parser->m_startCdataSectionHandler;
  1580. oldEndCdataSectionHandler = parser->m_endCdataSectionHandler;
  1581. oldDefaultHandler = parser->m_defaultHandler;
  1582. oldUnparsedEntityDeclHandler = parser->m_unparsedEntityDeclHandler;
  1583. oldNotationDeclHandler = parser->m_notationDeclHandler;
  1584. oldStartNamespaceDeclHandler = parser->m_startNamespaceDeclHandler;
  1585. oldEndNamespaceDeclHandler = parser->m_endNamespaceDeclHandler;
  1586. oldNotStandaloneHandler = parser->m_notStandaloneHandler;
  1587. oldExternalEntityRefHandler = parser->m_externalEntityRefHandler;
  1588. oldSkippedEntityHandler = parser->m_skippedEntityHandler;
  1589. oldUnknownEncodingHandler = parser->m_unknownEncodingHandler;
  1590. oldUnknownEncodingHandlerData = parser->m_unknownEncodingHandlerData;
  1591. oldElementDeclHandler = parser->m_elementDeclHandler;
  1592. oldAttlistDeclHandler = parser->m_attlistDeclHandler;
  1593. oldEntityDeclHandler = parser->m_entityDeclHandler;
  1594. oldXmlDeclHandler = parser->m_xmlDeclHandler;
  1595. oldDeclElementType = parser->m_declElementType;
  1596. oldUserData = parser->m_userData;
  1597. oldHandlerArg = parser->m_handlerArg;
  1598. oldDefaultExpandInternalEntities = parser->m_defaultExpandInternalEntities;
  1599. oldExternalEntityRefHandlerArg = parser->m_externalEntityRefHandlerArg;
  1600. #ifdef XML_DTD
  1601. oldParamEntityParsing = parser->m_paramEntityParsing;
  1602. oldInEntityValue = parser->m_prologState.inEntityValue;
  1603. #endif
  1604. oldns_triplets = parser->m_ns_triplets;
  1605. /* Note that the new parser shares the same hash secret as the old
  1606. parser, so that dtdCopy and copyEntityTable can lookup values
  1607. from hash tables associated with either parser without us having
  1608. to worry which hash secrets each table has.
  1609. */
  1610. oldhash_secret_salt = parser->m_hash_secret_salt;
  1611. oldReparseDeferralEnabled = parser->m_reparseDeferralEnabled;
  1612. #ifdef XML_DTD
  1613. if (! context)
  1614. newDtd = oldDtd;
  1615. #endif /* XML_DTD */
  1616. /* Note that the magical uses of the pre-processor to make field
  1617. access look more like C++ require that `parser' be overwritten
  1618. here. This makes this function more painful to follow than it
  1619. would be otherwise.
  1620. */
  1621. if (parser->m_ns) {
  1622. XML_Char tmp[2] = {parser->m_namespaceSeparator, 0};
  1623. parser = parserCreate(encodingName, &parser->m_mem, tmp, newDtd, oldParser);
  1624. } else {
  1625. parser
  1626. = parserCreate(encodingName, &parser->m_mem, NULL, newDtd, oldParser);
  1627. }
  1628. if (! parser)
  1629. return NULL;
  1630. parser->m_startElementHandler = oldStartElementHandler;
  1631. parser->m_endElementHandler = oldEndElementHandler;
  1632. parser->m_characterDataHandler = oldCharacterDataHandler;
  1633. parser->m_processingInstructionHandler = oldProcessingInstructionHandler;
  1634. parser->m_commentHandler = oldCommentHandler;
  1635. parser->m_startCdataSectionHandler = oldStartCdataSectionHandler;
  1636. parser->m_endCdataSectionHandler = oldEndCdataSectionHandler;
  1637. parser->m_defaultHandler = oldDefaultHandler;
  1638. parser->m_unparsedEntityDeclHandler = oldUnparsedEntityDeclHandler;
  1639. parser->m_notationDeclHandler = oldNotationDeclHandler;
  1640. parser->m_startNamespaceDeclHandler = oldStartNamespaceDeclHandler;
  1641. parser->m_endNamespaceDeclHandler = oldEndNamespaceDeclHandler;
  1642. parser->m_notStandaloneHandler = oldNotStandaloneHandler;
  1643. parser->m_externalEntityRefHandler = oldExternalEntityRefHandler;
  1644. parser->m_skippedEntityHandler = oldSkippedEntityHandler;
  1645. parser->m_unknownEncodingHandler = oldUnknownEncodingHandler;
  1646. parser->m_unknownEncodingHandlerData = oldUnknownEncodingHandlerData;
  1647. parser->m_elementDeclHandler = oldElementDeclHandler;
  1648. parser->m_attlistDeclHandler = oldAttlistDeclHandler;
  1649. parser->m_entityDeclHandler = oldEntityDeclHandler;
  1650. parser->m_xmlDeclHandler = oldXmlDeclHandler;
  1651. parser->m_declElementType = oldDeclElementType;
  1652. parser->m_userData = oldUserData;
  1653. if (oldUserData == oldHandlerArg)
  1654. parser->m_handlerArg = parser->m_userData;
  1655. else
  1656. parser->m_handlerArg = parser;
  1657. if (oldExternalEntityRefHandlerArg != oldParser)
  1658. parser->m_externalEntityRefHandlerArg = oldExternalEntityRefHandlerArg;
  1659. parser->m_defaultExpandInternalEntities = oldDefaultExpandInternalEntities;
  1660. parser->m_ns_triplets = oldns_triplets;
  1661. parser->m_hash_secret_salt = oldhash_secret_salt;
  1662. parser->m_reparseDeferralEnabled = oldReparseDeferralEnabled;
  1663. parser->m_parentParser = oldParser;
  1664. #ifdef XML_DTD
  1665. parser->m_paramEntityParsing = oldParamEntityParsing;
  1666. parser->m_prologState.inEntityValue = oldInEntityValue;
  1667. if (context) {
  1668. #endif /* XML_DTD */
  1669. if (! dtdCopy(oldParser, parser->m_dtd, oldDtd, parser)
  1670. || ! setContext(parser, context)) {
  1671. XML_ParserFree(parser);
  1672. return NULL;
  1673. }
  1674. parser->m_processor = externalEntityInitProcessor;
  1675. #ifdef XML_DTD
  1676. } else {
  1677. /* The DTD instance referenced by parser->m_dtd is shared between the
  1678. document's root parser and external PE parsers, therefore one does not
  1679. need to call setContext. In addition, one also *must* not call
  1680. setContext, because this would overwrite existing prefix->binding
  1681. pointers in parser->m_dtd with ones that get destroyed with the external
  1682. PE parser. This would leave those prefixes with dangling pointers.
  1683. */
  1684. parser->m_isParamEntity = XML_TRUE;
  1685. XmlPrologStateInitExternalEntity(&parser->m_prologState);
  1686. parser->m_processor = externalParEntInitProcessor;
  1687. }
  1688. #endif /* XML_DTD */
  1689. return parser;
  1690. }
  1691. static void FASTCALL
  1692. destroyBindings(BINDING *bindings, XML_Parser parser) {
  1693. for (;;) {
  1694. BINDING *b = bindings;
  1695. if (! b)
  1696. break;
  1697. bindings = b->nextTagBinding;
  1698. FREE(parser, b->uri);
  1699. FREE(parser, b);
  1700. }
  1701. }
  1702. void XMLCALL
  1703. XML_ParserFree(XML_Parser parser) {
  1704. TAG *tagList;
  1705. OPEN_INTERNAL_ENTITY *entityList;
  1706. if (parser == NULL)
  1707. return;
  1708. /* free m_tagStack and m_freeTagList */
  1709. tagList = parser->m_tagStack;
  1710. for (;;) {
  1711. TAG *p;
  1712. if (tagList == NULL) {
  1713. if (parser->m_freeTagList == NULL)
  1714. break;
  1715. tagList = parser->m_freeTagList;
  1716. parser->m_freeTagList = NULL;
  1717. }
  1718. p = tagList;
  1719. tagList = tagList->parent;
  1720. FREE(parser, p->buf.raw);
  1721. destroyBindings(p->bindings, parser);
  1722. FREE(parser, p);
  1723. }
  1724. /* free m_openInternalEntities and m_freeInternalEntities */
  1725. entityList = parser->m_openInternalEntities;
  1726. for (;;) {
  1727. OPEN_INTERNAL_ENTITY *openEntity;
  1728. if (entityList == NULL) {
  1729. if (parser->m_freeInternalEntities == NULL)
  1730. break;
  1731. entityList = parser->m_freeInternalEntities;
  1732. parser->m_freeInternalEntities = NULL;
  1733. }
  1734. openEntity = entityList;
  1735. entityList = entityList->next;
  1736. FREE(parser, openEntity);
  1737. }
  1738. /* free m_openAttributeEntities and m_freeAttributeEntities */
  1739. entityList = parser->m_openAttributeEntities;
  1740. for (;;) {
  1741. OPEN_INTERNAL_ENTITY *openEntity;
  1742. if (entityList == NULL) {
  1743. if (parser->m_freeAttributeEntities == NULL)
  1744. break;
  1745. entityList = parser->m_freeAttributeEntities;
  1746. parser->m_freeAttributeEntities = NULL;
  1747. }
  1748. openEntity = entityList;
  1749. entityList = entityList->next;
  1750. FREE(parser, openEntity);
  1751. }
  1752. /* free m_openValueEntities and m_freeValueEntities */
  1753. entityList = parser->m_openValueEntities;
  1754. for (;;) {
  1755. OPEN_INTERNAL_ENTITY *openEntity;
  1756. if (entityList == NULL) {
  1757. if (parser->m_freeValueEntities == NULL)
  1758. break;
  1759. entityList = parser->m_freeValueEntities;
  1760. parser->m_freeValueEntities = NULL;
  1761. }
  1762. openEntity = entityList;
  1763. entityList = entityList->next;
  1764. FREE(parser, openEntity);
  1765. }
  1766. destroyBindings(parser->m_freeBindingList, parser);
  1767. destroyBindings(parser->m_inheritedBindings, parser);
  1768. poolDestroy(&parser->m_tempPool);
  1769. poolDestroy(&parser->m_temp2Pool);
  1770. FREE(parser, (void *)parser->m_protocolEncodingName);
  1771. #ifdef XML_DTD
  1772. /* external parameter entity parsers share the DTD structure
  1773. parser->m_dtd with the root parser, so we must not destroy it
  1774. */
  1775. if (! parser->m_isParamEntity && parser->m_dtd)
  1776. #else
  1777. if (parser->m_dtd)
  1778. #endif /* XML_DTD */
  1779. dtdDestroy(parser->m_dtd, (XML_Bool)! parser->m_parentParser, parser);
  1780. FREE(parser, parser->m_atts);
  1781. #ifdef XML_ATTR_INFO
  1782. FREE(parser, parser->m_attInfo);
  1783. #endif
  1784. FREE(parser, parser->m_groupConnector);
  1785. // NOTE: We are avoiding FREE(..) here because parser->m_buffer
  1786. // is not being allocated with MALLOC(..) but with plain
  1787. // .malloc_fcn(..).
  1788. parser->m_mem.free_fcn(parser->m_buffer);
  1789. FREE(parser, parser->m_dataBuf);
  1790. FREE(parser, parser->m_nsAtts);
  1791. FREE(parser, parser->m_unknownEncodingMem);
  1792. if (parser->m_unknownEncodingRelease)
  1793. parser->m_unknownEncodingRelease(parser->m_unknownEncodingData);
  1794. FREE(parser, parser);
  1795. }
  1796. void XMLCALL
  1797. XML_UseParserAsHandlerArg(XML_Parser parser) {
  1798. if (parser != NULL)
  1799. parser->m_handlerArg = parser;
  1800. }
  1801. enum XML_Error XMLCALL
  1802. XML_UseForeignDTD(XML_Parser parser, XML_Bool useDTD) {
  1803. if (parser == NULL)
  1804. return XML_ERROR_INVALID_ARGUMENT;
  1805. #ifdef XML_DTD
  1806. /* block after XML_Parse()/XML_ParseBuffer() has been called */
  1807. if (parserBusy(parser))
  1808. return XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING;
  1809. parser->m_useForeignDTD = useDTD;
  1810. return XML_ERROR_NONE;
  1811. #else
  1812. UNUSED_P(useDTD);
  1813. return XML_ERROR_FEATURE_REQUIRES_XML_DTD;
  1814. #endif
  1815. }
  1816. void XMLCALL
  1817. XML_SetReturnNSTriplet(XML_Parser parser, int do_nst) {
  1818. if (parser == NULL)
  1819. return;
  1820. /* block after XML_Parse()/XML_ParseBuffer() has been called */
  1821. if (parserBusy(parser))
  1822. return;
  1823. parser->m_ns_triplets = do_nst ? XML_TRUE : XML_FALSE;
  1824. }
  1825. void XMLCALL
  1826. XML_SetUserData(XML_Parser parser, void *p) {
  1827. if (parser == NULL)
  1828. return;
  1829. if (parser->m_handlerArg == parser->m_userData)
  1830. parser->m_handlerArg = parser->m_userData = p;
  1831. else
  1832. parser->m_userData = p;
  1833. }
  1834. enum XML_Status XMLCALL
  1835. XML_SetBase(XML_Parser parser, const XML_Char *p) {
  1836. if (parser == NULL)
  1837. return XML_STATUS_ERROR;
  1838. if (p) {
  1839. p = poolCopyString(&parser->m_dtd->pool, p);
  1840. if (! p)
  1841. return XML_STATUS_ERROR;
  1842. parser->m_curBase = p;
  1843. } else
  1844. parser->m_curBase = NULL;
  1845. return XML_STATUS_OK;
  1846. }
  1847. const XML_Char *XMLCALL
  1848. XML_GetBase(XML_Parser parser) {
  1849. if (parser == NULL)
  1850. return NULL;
  1851. return parser->m_curBase;
  1852. }
  1853. int XMLCALL
  1854. XML_GetSpecifiedAttributeCount(XML_Parser parser) {
  1855. if (parser == NULL)
  1856. return -1;
  1857. return parser->m_nSpecifiedAtts;
  1858. }
  1859. int XMLCALL
  1860. XML_GetIdAttributeIndex(XML_Parser parser) {
  1861. if (parser == NULL)
  1862. return -1;
  1863. return parser->m_idAttIndex;
  1864. }
  1865. #ifdef XML_ATTR_INFO
  1866. const XML_AttrInfo *XMLCALL
  1867. XML_GetAttributeInfo(XML_Parser parser) {
  1868. if (parser == NULL)
  1869. return NULL;
  1870. return parser->m_attInfo;
  1871. }
  1872. #endif
  1873. void XMLCALL
  1874. XML_SetElementHandler(XML_Parser parser, XML_StartElementHandler start,
  1875. XML_EndElementHandler end) {
  1876. if (parser == NULL)
  1877. return;
  1878. parser->m_startElementHandler = start;
  1879. parser->m_endElementHandler = end;
  1880. }
  1881. void XMLCALL
  1882. XML_SetStartElementHandler(XML_Parser parser, XML_StartElementHandler start) {
  1883. if (parser != NULL)
  1884. parser->m_startElementHandler = start;
  1885. }
  1886. void XMLCALL
  1887. XML_SetEndElementHandler(XML_Parser parser, XML_EndElementHandler end) {
  1888. if (parser != NULL)
  1889. parser->m_endElementHandler = end;
  1890. }
  1891. void XMLCALL
  1892. XML_SetCharacterDataHandler(XML_Parser parser,
  1893. XML_CharacterDataHandler handler) {
  1894. if (parser != NULL)
  1895. parser->m_characterDataHandler = handler;
  1896. }
  1897. void XMLCALL
  1898. XML_SetProcessingInstructionHandler(XML_Parser parser,
  1899. XML_ProcessingInstructionHandler handler) {
  1900. if (parser != NULL)
  1901. parser->m_processingInstructionHandler = handler;
  1902. }
  1903. void XMLCALL
  1904. XML_SetCommentHandler(XML_Parser parser, XML_CommentHandler handler) {
  1905. if (parser != NULL)
  1906. parser->m_commentHandler = handler;
  1907. }
  1908. void XMLCALL
  1909. XML_SetCdataSectionHandler(XML_Parser parser,
  1910. XML_StartCdataSectionHandler start,
  1911. XML_EndCdataSectionHandler end) {
  1912. if (parser == NULL)
  1913. return;
  1914. parser->m_startCdataSectionHandler = start;
  1915. parser->m_endCdataSectionHandler = end;
  1916. }
  1917. void XMLCALL
  1918. XML_SetStartCdataSectionHandler(XML_Parser parser,
  1919. XML_StartCdataSectionHandler start) {
  1920. if (parser != NULL)
  1921. parser->m_startCdataSectionHandler = start;
  1922. }
  1923. void XMLCALL
  1924. XML_SetEndCdataSectionHandler(XML_Parser parser,
  1925. XML_EndCdataSectionHandler end) {
  1926. if (parser != NULL)
  1927. parser->m_endCdataSectionHandler = end;
  1928. }
  1929. void XMLCALL
  1930. XML_SetDefaultHandler(XML_Parser parser, XML_DefaultHandler handler) {
  1931. if (parser == NULL)
  1932. return;
  1933. parser->m_defaultHandler = handler;
  1934. parser->m_defaultExpandInternalEntities = XML_FALSE;
  1935. }
  1936. void XMLCALL
  1937. XML_SetDefaultHandlerExpand(XML_Parser parser, XML_DefaultHandler handler) {
  1938. if (parser == NULL)
  1939. return;
  1940. parser->m_defaultHandler = handler;
  1941. parser->m_defaultExpandInternalEntities = XML_TRUE;
  1942. }
  1943. void XMLCALL
  1944. XML_SetDoctypeDeclHandler(XML_Parser parser, XML_StartDoctypeDeclHandler start,
  1945. XML_EndDoctypeDeclHandler end) {
  1946. if (parser == NULL)
  1947. return;
  1948. parser->m_startDoctypeDeclHandler = start;
  1949. parser->m_endDoctypeDeclHandler = end;
  1950. }
  1951. void XMLCALL
  1952. XML_SetStartDoctypeDeclHandler(XML_Parser parser,
  1953. XML_StartDoctypeDeclHandler start) {
  1954. if (parser != NULL)
  1955. parser->m_startDoctypeDeclHandler = start;
  1956. }
  1957. void XMLCALL
  1958. XML_SetEndDoctypeDeclHandler(XML_Parser parser, XML_EndDoctypeDeclHandler end) {
  1959. if (parser != NULL)
  1960. parser->m_endDoctypeDeclHandler = end;
  1961. }
  1962. void XMLCALL
  1963. XML_SetUnparsedEntityDeclHandler(XML_Parser parser,
  1964. XML_UnparsedEntityDeclHandler handler) {
  1965. if (parser != NULL)
  1966. parser->m_unparsedEntityDeclHandler = handler;
  1967. }
  1968. void XMLCALL
  1969. XML_SetNotationDeclHandler(XML_Parser parser, XML_NotationDeclHandler handler) {
  1970. if (parser != NULL)
  1971. parser->m_notationDeclHandler = handler;
  1972. }
  1973. void XMLCALL
  1974. XML_SetNamespaceDeclHandler(XML_Parser parser,
  1975. XML_StartNamespaceDeclHandler start,
  1976. XML_EndNamespaceDeclHandler end) {
  1977. if (parser == NULL)
  1978. return;
  1979. parser->m_startNamespaceDeclHandler = start;
  1980. parser->m_endNamespaceDeclHandler = end;
  1981. }
  1982. void XMLCALL
  1983. XML_SetStartNamespaceDeclHandler(XML_Parser parser,
  1984. XML_StartNamespaceDeclHandler start) {
  1985. if (parser != NULL)
  1986. parser->m_startNamespaceDeclHandler = start;
  1987. }
  1988. void XMLCALL
  1989. XML_SetEndNamespaceDeclHandler(XML_Parser parser,
  1990. XML_EndNamespaceDeclHandler end) {
  1991. if (parser != NULL)
  1992. parser->m_endNamespaceDeclHandler = end;
  1993. }
  1994. void XMLCALL
  1995. XML_SetNotStandaloneHandler(XML_Parser parser,
  1996. XML_NotStandaloneHandler handler) {
  1997. if (parser != NULL)
  1998. parser->m_notStandaloneHandler = handler;
  1999. }
  2000. void XMLCALL
  2001. XML_SetExternalEntityRefHandler(XML_Parser parser,
  2002. XML_ExternalEntityRefHandler handler) {
  2003. if (parser != NULL)
  2004. parser->m_externalEntityRefHandler = handler;
  2005. }
  2006. void XMLCALL
  2007. XML_SetExternalEntityRefHandlerArg(XML_Parser parser, void *arg) {
  2008. if (parser == NULL)
  2009. return;
  2010. if (arg)
  2011. parser->m_externalEntityRefHandlerArg = (XML_Parser)arg;
  2012. else
  2013. parser->m_externalEntityRefHandlerArg = parser;
  2014. }
  2015. void XMLCALL
  2016. XML_SetSkippedEntityHandler(XML_Parser parser,
  2017. XML_SkippedEntityHandler handler) {
  2018. if (parser != NULL)
  2019. parser->m_skippedEntityHandler = handler;
  2020. }
  2021. void XMLCALL
  2022. XML_SetUnknownEncodingHandler(XML_Parser parser,
  2023. XML_UnknownEncodingHandler handler, void *data) {
  2024. if (parser == NULL)
  2025. return;
  2026. parser->m_unknownEncodingHandler = handler;
  2027. parser->m_unknownEncodingHandlerData = data;
  2028. }
  2029. void XMLCALL
  2030. XML_SetElementDeclHandler(XML_Parser parser, XML_ElementDeclHandler eldecl) {
  2031. if (parser != NULL)
  2032. parser->m_elementDeclHandler = eldecl;
  2033. }
  2034. void XMLCALL
  2035. XML_SetAttlistDeclHandler(XML_Parser parser, XML_AttlistDeclHandler attdecl) {
  2036. if (parser != NULL)
  2037. parser->m_attlistDeclHandler = attdecl;
  2038. }
  2039. void XMLCALL
  2040. XML_SetEntityDeclHandler(XML_Parser parser, XML_EntityDeclHandler handler) {
  2041. if (parser != NULL)
  2042. parser->m_entityDeclHandler = handler;
  2043. }
  2044. void XMLCALL
  2045. XML_SetXmlDeclHandler(XML_Parser parser, XML_XmlDeclHandler handler) {
  2046. if (parser != NULL)
  2047. parser->m_xmlDeclHandler = handler;
  2048. }
  2049. int XMLCALL
  2050. XML_SetParamEntityParsing(XML_Parser parser,
  2051. enum XML_ParamEntityParsing peParsing) {
  2052. if (parser == NULL)
  2053. return 0;
  2054. /* block after XML_Parse()/XML_ParseBuffer() has been called */
  2055. if (parserBusy(parser))
  2056. return 0;
  2057. #ifdef XML_DTD
  2058. parser->m_paramEntityParsing = peParsing;
  2059. return 1;
  2060. #else
  2061. return peParsing == XML_PARAM_ENTITY_PARSING_NEVER;
  2062. #endif
  2063. }
  2064. int XMLCALL
  2065. XML_SetHashSalt(XML_Parser parser, unsigned long hash_salt) {
  2066. if (parser == NULL)
  2067. return 0;
  2068. const XML_Parser rootParser = getRootParserOf(parser, NULL);
  2069. assert(! rootParser->m_parentParser);
  2070. /* block after XML_Parse()/XML_ParseBuffer() has been called */
  2071. if (parserBusy(rootParser))
  2072. return 0;
  2073. rootParser->m_hash_secret_salt = hash_salt;
  2074. return 1;
  2075. }
  2076. enum XML_Status XMLCALL
  2077. XML_Parse(XML_Parser parser, const char *s, int len, int isFinal) {
  2078. if ((parser == NULL) || (len < 0) || ((s == NULL) && (len != 0))) {
  2079. if (parser != NULL)
  2080. parser->m_errorCode = XML_ERROR_INVALID_ARGUMENT;
  2081. return XML_STATUS_ERROR;
  2082. }
  2083. switch (parser->m_parsingStatus.parsing) {
  2084. case XML_SUSPENDED:
  2085. parser->m_errorCode = XML_ERROR_SUSPENDED;
  2086. return XML_STATUS_ERROR;
  2087. case XML_FINISHED:
  2088. parser->m_errorCode = XML_ERROR_FINISHED;
  2089. return XML_STATUS_ERROR;
  2090. case XML_INITIALIZED:
  2091. if (parser->m_parentParser == NULL && ! startParsing(parser)) {
  2092. parser->m_errorCode = XML_ERROR_NO_MEMORY;
  2093. return XML_STATUS_ERROR;
  2094. }
  2095. /* fall through */
  2096. default:
  2097. parser->m_parsingStatus.parsing = XML_PARSING;
  2098. }
  2099. #if XML_CONTEXT_BYTES == 0
  2100. if (parser->m_bufferPtr == parser->m_bufferEnd) {
  2101. const char *end;
  2102. int nLeftOver;
  2103. enum XML_Status result;
  2104. /* Detect overflow (a+b > MAX <==> b > MAX-a) */
  2105. if ((XML_Size)len > ((XML_Size)-1) / 2 - parser->m_parseEndByteIndex) {
  2106. parser->m_errorCode = XML_ERROR_NO_MEMORY;
  2107. parser->m_eventPtr = parser->m_eventEndPtr = NULL;
  2108. parser->m_processor = errorProcessor;
  2109. return XML_STATUS_ERROR;
  2110. }
  2111. // though this isn't a buffer request, we assume that `len` is the app's
  2112. // preferred buffer fill size, and therefore save it here.
  2113. parser->m_lastBufferRequestSize = len;
  2114. parser->m_parseEndByteIndex += len;
  2115. parser->m_positionPtr = s;
  2116. parser->m_parsingStatus.finalBuffer = (XML_Bool)isFinal;
  2117. parser->m_errorCode
  2118. = callProcessor(parser, s, parser->m_parseEndPtr = s + len, &end);
  2119. if (parser->m_errorCode != XML_ERROR_NONE) {
  2120. parser->m_eventEndPtr = parser->m_eventPtr;
  2121. parser->m_processor = errorProcessor;
  2122. return XML_STATUS_ERROR;
  2123. } else {
  2124. switch (parser->m_parsingStatus.parsing) {
  2125. case XML_SUSPENDED:
  2126. result = XML_STATUS_SUSPENDED;
  2127. break;
  2128. case XML_INITIALIZED:
  2129. case XML_PARSING:
  2130. if (isFinal) {
  2131. parser->m_parsingStatus.parsing = XML_FINISHED;
  2132. return XML_STATUS_OK;
  2133. }
  2134. /* fall through */
  2135. default:
  2136. result = XML_STATUS_OK;
  2137. }
  2138. }
  2139. XmlUpdatePosition(parser->m_encoding, parser->m_positionPtr, end,
  2140. &parser->m_position);
  2141. nLeftOver = s + len - end;
  2142. if (nLeftOver) {
  2143. // Back up and restore the parsing status to avoid XML_ERROR_SUSPENDED
  2144. // (and XML_ERROR_FINISHED) from XML_GetBuffer.
  2145. const enum XML_Parsing originalStatus = parser->m_parsingStatus.parsing;
  2146. parser->m_parsingStatus.parsing = XML_PARSING;
  2147. void *const temp = XML_GetBuffer(parser, nLeftOver);
  2148. parser->m_parsingStatus.parsing = originalStatus;
  2149. // GetBuffer may have overwritten this, but we want to remember what the
  2150. // app requested, not how many bytes were left over after parsing.
  2151. parser->m_lastBufferRequestSize = len;
  2152. if (temp == NULL) {
  2153. // NOTE: parser->m_errorCode has already been set by XML_GetBuffer().
  2154. parser->m_eventPtr = parser->m_eventEndPtr = NULL;
  2155. parser->m_processor = errorProcessor;
  2156. return XML_STATUS_ERROR;
  2157. }
  2158. // Since we know that the buffer was empty and XML_CONTEXT_BYTES is 0, we
  2159. // don't have any data to preserve, and can copy straight into the start
  2160. // of the buffer rather than the GetBuffer return pointer (which may be
  2161. // pointing further into the allocated buffer).
  2162. memcpy(parser->m_buffer, end, nLeftOver);
  2163. }
  2164. parser->m_bufferPtr = parser->m_buffer;
  2165. parser->m_bufferEnd = parser->m_buffer + nLeftOver;
  2166. parser->m_positionPtr = parser->m_bufferPtr;
  2167. parser->m_parseEndPtr = parser->m_bufferEnd;
  2168. parser->m_eventPtr = parser->m_bufferPtr;
  2169. parser->m_eventEndPtr = parser->m_bufferPtr;
  2170. return result;
  2171. }
  2172. #endif /* XML_CONTEXT_BYTES == 0 */
  2173. void *buff = XML_GetBuffer(parser, len);
  2174. if (buff == NULL)
  2175. return XML_STATUS_ERROR;
  2176. if (len > 0) {
  2177. assert(s != NULL); // make sure s==NULL && len!=0 was rejected above
  2178. memcpy(buff, s, len);
  2179. }
  2180. return XML_ParseBuffer(parser, len, isFinal);
  2181. }
  2182. enum XML_Status XMLCALL
  2183. XML_ParseBuffer(XML_Parser parser, int len, int isFinal) {
  2184. const char *start;
  2185. enum XML_Status result = XML_STATUS_OK;
  2186. if (parser == NULL)
  2187. return XML_STATUS_ERROR;
  2188. if (len < 0) {
  2189. parser->m_errorCode = XML_ERROR_INVALID_ARGUMENT;
  2190. return XML_STATUS_ERROR;
  2191. }
  2192. switch (parser->m_parsingStatus.parsing) {
  2193. case XML_SUSPENDED:
  2194. parser->m_errorCode = XML_ERROR_SUSPENDED;
  2195. return XML_STATUS_ERROR;
  2196. case XML_FINISHED:
  2197. parser->m_errorCode = XML_ERROR_FINISHED;
  2198. return XML_STATUS_ERROR;
  2199. case XML_INITIALIZED:
  2200. /* Has someone called XML_GetBuffer successfully before? */
  2201. if (! parser->m_bufferPtr) {
  2202. parser->m_errorCode = XML_ERROR_NO_BUFFER;
  2203. return XML_STATUS_ERROR;
  2204. }
  2205. if (parser->m_parentParser == NULL && ! startParsing(parser)) {
  2206. parser->m_errorCode = XML_ERROR_NO_MEMORY;
  2207. return XML_STATUS_ERROR;
  2208. }
  2209. /* fall through */
  2210. default:
  2211. parser->m_parsingStatus.parsing = XML_PARSING;
  2212. }
  2213. start = parser->m_bufferPtr;
  2214. parser->m_positionPtr = start;
  2215. parser->m_bufferEnd += len;
  2216. parser->m_parseEndPtr = parser->m_bufferEnd;
  2217. parser->m_parseEndByteIndex += len;
  2218. parser->m_parsingStatus.finalBuffer = (XML_Bool)isFinal;
  2219. parser->m_errorCode = callProcessor(parser, start, parser->m_parseEndPtr,
  2220. &parser->m_bufferPtr);
  2221. if (parser->m_errorCode != XML_ERROR_NONE) {
  2222. parser->m_eventEndPtr = parser->m_eventPtr;
  2223. parser->m_processor = errorProcessor;
  2224. return XML_STATUS_ERROR;
  2225. } else {
  2226. switch (parser->m_parsingStatus.parsing) {
  2227. case XML_SUSPENDED:
  2228. result = XML_STATUS_SUSPENDED;
  2229. break;
  2230. case XML_INITIALIZED:
  2231. case XML_PARSING:
  2232. if (isFinal) {
  2233. parser->m_parsingStatus.parsing = XML_FINISHED;
  2234. return result;
  2235. }
  2236. default:; /* should not happen */
  2237. }
  2238. }
  2239. XmlUpdatePosition(parser->m_encoding, parser->m_positionPtr,
  2240. parser->m_bufferPtr, &parser->m_position);
  2241. parser->m_positionPtr = parser->m_bufferPtr;
  2242. return result;
  2243. }
  2244. void *XMLCALL
  2245. XML_GetBuffer(XML_Parser parser, int len) {
  2246. if (parser == NULL)
  2247. return NULL;
  2248. if (len < 0) {
  2249. parser->m_errorCode = XML_ERROR_NO_MEMORY;
  2250. return NULL;
  2251. }
  2252. switch (parser->m_parsingStatus.parsing) {
  2253. case XML_SUSPENDED:
  2254. parser->m_errorCode = XML_ERROR_SUSPENDED;
  2255. return NULL;
  2256. case XML_FINISHED:
  2257. parser->m_errorCode = XML_ERROR_FINISHED;
  2258. return NULL;
  2259. default:;
  2260. }
  2261. // whether or not the request succeeds, `len` seems to be the app's preferred
  2262. // buffer fill size; remember it.
  2263. parser->m_lastBufferRequestSize = len;
  2264. if (len > EXPAT_SAFE_PTR_DIFF(parser->m_bufferLim, parser->m_bufferEnd)
  2265. || parser->m_buffer == NULL) {
  2266. #if XML_CONTEXT_BYTES > 0
  2267. int keep;
  2268. #endif /* XML_CONTEXT_BYTES > 0 */
  2269. /* Do not invoke signed arithmetic overflow: */
  2270. int neededSize = (int)((unsigned)len
  2271. + (unsigned)EXPAT_SAFE_PTR_DIFF(
  2272. parser->m_bufferEnd, parser->m_bufferPtr));
  2273. if (neededSize < 0) {
  2274. parser->m_errorCode = XML_ERROR_NO_MEMORY;
  2275. return NULL;
  2276. }
  2277. #if XML_CONTEXT_BYTES > 0
  2278. keep = (int)EXPAT_SAFE_PTR_DIFF(parser->m_bufferPtr, parser->m_buffer);
  2279. if (keep > XML_CONTEXT_BYTES)
  2280. keep = XML_CONTEXT_BYTES;
  2281. /* Detect and prevent integer overflow */
  2282. if (keep > INT_MAX - neededSize) {
  2283. parser->m_errorCode = XML_ERROR_NO_MEMORY;
  2284. return NULL;
  2285. }
  2286. neededSize += keep;
  2287. #endif /* XML_CONTEXT_BYTES > 0 */
  2288. if (parser->m_buffer && parser->m_bufferPtr
  2289. && neededSize
  2290. <= EXPAT_SAFE_PTR_DIFF(parser->m_bufferLim, parser->m_buffer)) {
  2291. #if XML_CONTEXT_BYTES > 0
  2292. if (keep < EXPAT_SAFE_PTR_DIFF(parser->m_bufferPtr, parser->m_buffer)) {
  2293. int offset
  2294. = (int)EXPAT_SAFE_PTR_DIFF(parser->m_bufferPtr, parser->m_buffer)
  2295. - keep;
  2296. /* The buffer pointers cannot be NULL here; we have at least some bytes
  2297. * in the buffer */
  2298. memmove(parser->m_buffer, &parser->m_buffer[offset],
  2299. parser->m_bufferEnd - parser->m_bufferPtr + keep);
  2300. parser->m_bufferEnd -= offset;
  2301. parser->m_bufferPtr -= offset;
  2302. }
  2303. #else
  2304. memmove(parser->m_buffer, parser->m_bufferPtr,
  2305. EXPAT_SAFE_PTR_DIFF(parser->m_bufferEnd, parser->m_bufferPtr));
  2306. parser->m_bufferEnd
  2307. = parser->m_buffer
  2308. + EXPAT_SAFE_PTR_DIFF(parser->m_bufferEnd, parser->m_bufferPtr);
  2309. parser->m_bufferPtr = parser->m_buffer;
  2310. #endif /* XML_CONTEXT_BYTES > 0 */
  2311. } else {
  2312. char *newBuf;
  2313. int bufferSize
  2314. = (int)EXPAT_SAFE_PTR_DIFF(parser->m_bufferLim, parser->m_buffer);
  2315. if (bufferSize == 0)
  2316. bufferSize = INIT_BUFFER_SIZE;
  2317. do {
  2318. /* Do not invoke signed arithmetic overflow: */
  2319. bufferSize = (int)(2U * (unsigned)bufferSize);
  2320. } while (bufferSize < neededSize && bufferSize > 0);
  2321. if (bufferSize <= 0) {
  2322. parser->m_errorCode = XML_ERROR_NO_MEMORY;
  2323. return NULL;
  2324. }
  2325. // NOTE: We are avoiding MALLOC(..) here to leave limiting
  2326. // the input size to the application using Expat.
  2327. newBuf = parser->m_mem.malloc_fcn(bufferSize);
  2328. if (newBuf == NULL) {
  2329. parser->m_errorCode = XML_ERROR_NO_MEMORY;
  2330. return NULL;
  2331. }
  2332. parser->m_bufferLim = newBuf + bufferSize;
  2333. #if XML_CONTEXT_BYTES > 0
  2334. if (parser->m_bufferPtr) {
  2335. memcpy(newBuf, &parser->m_bufferPtr[-keep],
  2336. EXPAT_SAFE_PTR_DIFF(parser->m_bufferEnd, parser->m_bufferPtr)
  2337. + keep);
  2338. // NOTE: We are avoiding FREE(..) here because parser->m_buffer
  2339. // is not being allocated with MALLOC(..) but with plain
  2340. // .malloc_fcn(..).
  2341. parser->m_mem.free_fcn(parser->m_buffer);
  2342. parser->m_buffer = newBuf;
  2343. parser->m_bufferEnd
  2344. = parser->m_buffer
  2345. + EXPAT_SAFE_PTR_DIFF(parser->m_bufferEnd, parser->m_bufferPtr)
  2346. + keep;
  2347. parser->m_bufferPtr = parser->m_buffer + keep;
  2348. } else {
  2349. /* This must be a brand new buffer with no data in it yet */
  2350. parser->m_bufferEnd = newBuf;
  2351. parser->m_bufferPtr = parser->m_buffer = newBuf;
  2352. }
  2353. #else
  2354. if (parser->m_bufferPtr) {
  2355. memcpy(newBuf, parser->m_bufferPtr,
  2356. EXPAT_SAFE_PTR_DIFF(parser->m_bufferEnd, parser->m_bufferPtr));
  2357. // NOTE: We are avoiding FREE(..) here because parser->m_buffer
  2358. // is not being allocated with MALLOC(..) but with plain
  2359. // .malloc_fcn(..).
  2360. parser->m_mem.free_fcn(parser->m_buffer);
  2361. parser->m_bufferEnd
  2362. = newBuf
  2363. + EXPAT_SAFE_PTR_DIFF(parser->m_bufferEnd, parser->m_bufferPtr);
  2364. } else {
  2365. /* This must be a brand new buffer with no data in it yet */
  2366. parser->m_bufferEnd = newBuf;
  2367. }
  2368. parser->m_bufferPtr = parser->m_buffer = newBuf;
  2369. #endif /* XML_CONTEXT_BYTES > 0 */
  2370. }
  2371. parser->m_eventPtr = parser->m_eventEndPtr = NULL;
  2372. parser->m_positionPtr = NULL;
  2373. }
  2374. return parser->m_bufferEnd;
  2375. }
  2376. static void
  2377. triggerReenter(XML_Parser parser) {
  2378. parser->m_reenter = XML_TRUE;
  2379. }
  2380. enum XML_Status XMLCALL
  2381. XML_StopParser(XML_Parser parser, XML_Bool resumable) {
  2382. if (parser == NULL)
  2383. return XML_STATUS_ERROR;
  2384. switch (parser->m_parsingStatus.parsing) {
  2385. case XML_INITIALIZED:
  2386. parser->m_errorCode = XML_ERROR_NOT_STARTED;
  2387. return XML_STATUS_ERROR;
  2388. case XML_SUSPENDED:
  2389. if (resumable) {
  2390. parser->m_errorCode = XML_ERROR_SUSPENDED;
  2391. return XML_STATUS_ERROR;
  2392. }
  2393. parser->m_parsingStatus.parsing = XML_FINISHED;
  2394. break;
  2395. case XML_FINISHED:
  2396. parser->m_errorCode = XML_ERROR_FINISHED;
  2397. return XML_STATUS_ERROR;
  2398. case XML_PARSING:
  2399. if (resumable) {
  2400. #ifdef XML_DTD
  2401. if (parser->m_isParamEntity) {
  2402. parser->m_errorCode = XML_ERROR_SUSPEND_PE;
  2403. return XML_STATUS_ERROR;
  2404. }
  2405. #endif
  2406. parser->m_parsingStatus.parsing = XML_SUSPENDED;
  2407. } else
  2408. parser->m_parsingStatus.parsing = XML_FINISHED;
  2409. break;
  2410. default:
  2411. assert(0);
  2412. }
  2413. return XML_STATUS_OK;
  2414. }
  2415. enum XML_Status XMLCALL
  2416. XML_ResumeParser(XML_Parser parser) {
  2417. enum XML_Status result = XML_STATUS_OK;
  2418. if (parser == NULL)
  2419. return XML_STATUS_ERROR;
  2420. if (parser->m_parsingStatus.parsing != XML_SUSPENDED) {
  2421. parser->m_errorCode = XML_ERROR_NOT_SUSPENDED;
  2422. return XML_STATUS_ERROR;
  2423. }
  2424. parser->m_parsingStatus.parsing = XML_PARSING;
  2425. parser->m_errorCode = callProcessor(
  2426. parser, parser->m_bufferPtr, parser->m_parseEndPtr, &parser->m_bufferPtr);
  2427. if (parser->m_errorCode != XML_ERROR_NONE) {
  2428. parser->m_eventEndPtr = parser->m_eventPtr;
  2429. parser->m_processor = errorProcessor;
  2430. return XML_STATUS_ERROR;
  2431. } else {
  2432. switch (parser->m_parsingStatus.parsing) {
  2433. case XML_SUSPENDED:
  2434. result = XML_STATUS_SUSPENDED;
  2435. break;
  2436. case XML_INITIALIZED:
  2437. case XML_PARSING:
  2438. if (parser->m_parsingStatus.finalBuffer) {
  2439. parser->m_parsingStatus.parsing = XML_FINISHED;
  2440. return result;
  2441. }
  2442. default:;
  2443. }
  2444. }
  2445. XmlUpdatePosition(parser->m_encoding, parser->m_positionPtr,
  2446. parser->m_bufferPtr, &parser->m_position);
  2447. parser->m_positionPtr = parser->m_bufferPtr;
  2448. return result;
  2449. }
  2450. void XMLCALL
  2451. XML_GetParsingStatus(XML_Parser parser, XML_ParsingStatus *status) {
  2452. if (parser == NULL)
  2453. return;
  2454. assert(status != NULL);
  2455. *status = parser->m_parsingStatus;
  2456. }
  2457. enum XML_Error XMLCALL
  2458. XML_GetErrorCode(XML_Parser parser) {
  2459. if (parser == NULL)
  2460. return XML_ERROR_INVALID_ARGUMENT;
  2461. return parser->m_errorCode;
  2462. }
  2463. XML_Index XMLCALL
  2464. XML_GetCurrentByteIndex(XML_Parser parser) {
  2465. if (parser == NULL)
  2466. return -1;
  2467. if (parser->m_eventPtr)
  2468. return (XML_Index)(parser->m_parseEndByteIndex
  2469. - (parser->m_parseEndPtr - parser->m_eventPtr));
  2470. return -1;
  2471. }
  2472. int XMLCALL
  2473. XML_GetCurrentByteCount(XML_Parser parser) {
  2474. if (parser == NULL)
  2475. return 0;
  2476. if (parser->m_eventEndPtr && parser->m_eventPtr)
  2477. return (int)(parser->m_eventEndPtr - parser->m_eventPtr);
  2478. return 0;
  2479. }
  2480. const char *XMLCALL
  2481. XML_GetInputContext(XML_Parser parser, int *offset, int *size) {
  2482. #if XML_CONTEXT_BYTES > 0
  2483. if (parser == NULL)
  2484. return NULL;
  2485. if (parser->m_eventPtr && parser->m_buffer) {
  2486. if (offset != NULL)
  2487. *offset = (int)(parser->m_eventPtr - parser->m_buffer);
  2488. if (size != NULL)
  2489. *size = (int)(parser->m_bufferEnd - parser->m_buffer);
  2490. return parser->m_buffer;
  2491. }
  2492. #else
  2493. (void)parser;
  2494. (void)offset;
  2495. (void)size;
  2496. #endif /* XML_CONTEXT_BYTES > 0 */
  2497. return (const char *)0;
  2498. }
  2499. XML_Size XMLCALL
  2500. XML_GetCurrentLineNumber(XML_Parser parser) {
  2501. if (parser == NULL)
  2502. return 0;
  2503. if (parser->m_eventPtr && parser->m_eventPtr >= parser->m_positionPtr) {
  2504. XmlUpdatePosition(parser->m_encoding, parser->m_positionPtr,
  2505. parser->m_eventPtr, &parser->m_position);
  2506. parser->m_positionPtr = parser->m_eventPtr;
  2507. }
  2508. return parser->m_position.lineNumber + 1;
  2509. }
  2510. XML_Size XMLCALL
  2511. XML_GetCurrentColumnNumber(XML_Parser parser) {
  2512. if (parser == NULL)
  2513. return 0;
  2514. if (parser->m_eventPtr && parser->m_eventPtr >= parser->m_positionPtr) {
  2515. XmlUpdatePosition(parser->m_encoding, parser->m_positionPtr,
  2516. parser->m_eventPtr, &parser->m_position);
  2517. parser->m_positionPtr = parser->m_eventPtr;
  2518. }
  2519. return parser->m_position.columnNumber;
  2520. }
  2521. void XMLCALL
  2522. XML_FreeContentModel(XML_Parser parser, XML_Content *model) {
  2523. if (parser == NULL)
  2524. return;
  2525. // NOTE: We are avoiding FREE(..) here because the content model
  2526. // has been created using plain .malloc_fcn(..) rather than MALLOC(..).
  2527. parser->m_mem.free_fcn(model);
  2528. }
  2529. void *XMLCALL
  2530. XML_MemMalloc(XML_Parser parser, size_t size) {
  2531. if (parser == NULL)
  2532. return NULL;
  2533. // NOTE: We are avoiding MALLOC(..) here to not include
  2534. // user allocations with allocation tracking and limiting.
  2535. return parser->m_mem.malloc_fcn(size);
  2536. }
  2537. void *XMLCALL
  2538. XML_MemRealloc(XML_Parser parser, void *ptr, size_t size) {
  2539. if (parser == NULL)
  2540. return NULL;
  2541. // NOTE: We are avoiding REALLOC(..) here to not include
  2542. // user allocations with allocation tracking and limiting.
  2543. return parser->m_mem.realloc_fcn(ptr, size);
  2544. }
  2545. void XMLCALL
  2546. XML_MemFree(XML_Parser parser, void *ptr) {
  2547. if (parser == NULL)
  2548. return;
  2549. // NOTE: We are avoiding FREE(..) here because XML_MemMalloc and
  2550. // XML_MemRealloc are not using MALLOC(..) and REALLOC(..)
  2551. // but plain .malloc_fcn(..) and .realloc_fcn(..), internally.
  2552. parser->m_mem.free_fcn(ptr);
  2553. }
  2554. void XMLCALL
  2555. XML_DefaultCurrent(XML_Parser parser) {
  2556. if (parser == NULL)
  2557. return;
  2558. if (parser->m_defaultHandler) {
  2559. if (parser->m_openInternalEntities)
  2560. reportDefault(parser, parser->m_internalEncoding,
  2561. parser->m_openInternalEntities->internalEventPtr,
  2562. parser->m_openInternalEntities->internalEventEndPtr);
  2563. else
  2564. reportDefault(parser, parser->m_encoding, parser->m_eventPtr,
  2565. parser->m_eventEndPtr);
  2566. }
  2567. }
  2568. const XML_LChar *XMLCALL
  2569. XML_ErrorString(enum XML_Error code) {
  2570. switch (code) {
  2571. case XML_ERROR_NONE:
  2572. return NULL;
  2573. case XML_ERROR_NO_MEMORY:
  2574. return XML_L("out of memory");
  2575. case XML_ERROR_SYNTAX:
  2576. return XML_L("syntax error");
  2577. case XML_ERROR_NO_ELEMENTS:
  2578. return XML_L("no element found");
  2579. case XML_ERROR_INVALID_TOKEN:
  2580. return XML_L("not well-formed (invalid token)");
  2581. case XML_ERROR_UNCLOSED_TOKEN:
  2582. return XML_L("unclosed token");
  2583. case XML_ERROR_PARTIAL_CHAR:
  2584. return XML_L("partial character");
  2585. case XML_ERROR_TAG_MISMATCH:
  2586. return XML_L("mismatched tag");
  2587. case XML_ERROR_DUPLICATE_ATTRIBUTE:
  2588. return XML_L("duplicate attribute");
  2589. case XML_ERROR_JUNK_AFTER_DOC_ELEMENT:
  2590. return XML_L("junk after document element");
  2591. case XML_ERROR_PARAM_ENTITY_REF:
  2592. return XML_L("illegal parameter entity reference");
  2593. case XML_ERROR_UNDEFINED_ENTITY:
  2594. return XML_L("undefined entity");
  2595. case XML_ERROR_RECURSIVE_ENTITY_REF:
  2596. return XML_L("recursive entity reference");
  2597. case XML_ERROR_ASYNC_ENTITY:
  2598. return XML_L("asynchronous entity");
  2599. case XML_ERROR_BAD_CHAR_REF:
  2600. return XML_L("reference to invalid character number");
  2601. case XML_ERROR_BINARY_ENTITY_REF:
  2602. return XML_L("reference to binary entity");
  2603. case XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF:
  2604. return XML_L("reference to external entity in attribute");
  2605. case XML_ERROR_MISPLACED_XML_PI:
  2606. return XML_L("XML or text declaration not at start of entity");
  2607. case XML_ERROR_UNKNOWN_ENCODING:
  2608. return XML_L("unknown encoding");
  2609. case XML_ERROR_INCORRECT_ENCODING:
  2610. return XML_L("encoding specified in XML declaration is incorrect");
  2611. case XML_ERROR_UNCLOSED_CDATA_SECTION:
  2612. return XML_L("unclosed CDATA section");
  2613. case XML_ERROR_EXTERNAL_ENTITY_HANDLING:
  2614. return XML_L("error in processing external entity reference");
  2615. case XML_ERROR_NOT_STANDALONE:
  2616. return XML_L("document is not standalone");
  2617. case XML_ERROR_UNEXPECTED_STATE:
  2618. return XML_L("unexpected parser state - please send a bug report");
  2619. case XML_ERROR_ENTITY_DECLARED_IN_PE:
  2620. return XML_L("entity declared in parameter entity");
  2621. case XML_ERROR_FEATURE_REQUIRES_XML_DTD:
  2622. return XML_L("requested feature requires XML_DTD support in Expat");
  2623. case XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING:
  2624. return XML_L("cannot change setting once parsing has begun");
  2625. /* Added in 1.95.7. */
  2626. case XML_ERROR_UNBOUND_PREFIX:
  2627. return XML_L("unbound prefix");
  2628. /* Added in 1.95.8. */
  2629. case XML_ERROR_UNDECLARING_PREFIX:
  2630. return XML_L("must not undeclare prefix");
  2631. case XML_ERROR_INCOMPLETE_PE:
  2632. return XML_L("incomplete markup in parameter entity");
  2633. case XML_ERROR_XML_DECL:
  2634. return XML_L("XML declaration not well-formed");
  2635. case XML_ERROR_TEXT_DECL:
  2636. return XML_L("text declaration not well-formed");
  2637. case XML_ERROR_PUBLICID:
  2638. return XML_L("illegal character(s) in public id");
  2639. case XML_ERROR_SUSPENDED:
  2640. return XML_L("parser suspended");
  2641. case XML_ERROR_NOT_SUSPENDED:
  2642. return XML_L("parser not suspended");
  2643. case XML_ERROR_ABORTED:
  2644. return XML_L("parsing aborted");
  2645. case XML_ERROR_FINISHED:
  2646. return XML_L("parsing finished");
  2647. case XML_ERROR_SUSPEND_PE:
  2648. return XML_L("cannot suspend in external parameter entity");
  2649. /* Added in 2.0.0. */
  2650. case XML_ERROR_RESERVED_PREFIX_XML:
  2651. return XML_L(
  2652. "reserved prefix (xml) must not be undeclared or bound to another namespace name");
  2653. case XML_ERROR_RESERVED_PREFIX_XMLNS:
  2654. return XML_L("reserved prefix (xmlns) must not be declared or undeclared");
  2655. case XML_ERROR_RESERVED_NAMESPACE_URI:
  2656. return XML_L(
  2657. "prefix must not be bound to one of the reserved namespace names");
  2658. /* Added in 2.2.5. */
  2659. case XML_ERROR_INVALID_ARGUMENT: /* Constant added in 2.2.1, already */
  2660. return XML_L("invalid argument");
  2661. /* Added in 2.3.0. */
  2662. case XML_ERROR_NO_BUFFER:
  2663. return XML_L(
  2664. "a successful prior call to function XML_GetBuffer is required");
  2665. /* Added in 2.4.0. */
  2666. case XML_ERROR_AMPLIFICATION_LIMIT_BREACH:
  2667. return XML_L(
  2668. "limit on input amplification factor (from DTD and entities) breached");
  2669. /* Added in 2.6.4. */
  2670. case XML_ERROR_NOT_STARTED:
  2671. return XML_L("parser not started");
  2672. }
  2673. return NULL;
  2674. }
  2675. const XML_LChar *XMLCALL
  2676. XML_ExpatVersion(void) {
  2677. /* V1 is used to string-ize the version number. However, it would
  2678. string-ize the actual version macro *names* unless we get them
  2679. substituted before being passed to V1. CPP is defined to expand
  2680. a macro, then rescan for more expansions. Thus, we use V2 to expand
  2681. the version macros, then CPP will expand the resulting V1() macro
  2682. with the correct numerals. */
  2683. /* ### I'm assuming cpp is portable in this respect... */
  2684. #define V1(a, b, c) XML_L(#a) XML_L(".") XML_L(#b) XML_L(".") XML_L(#c)
  2685. #define V2(a, b, c) XML_L("expat_") V1(a, b, c)
  2686. return V2(XML_MAJOR_VERSION, XML_MINOR_VERSION, XML_MICRO_VERSION);
  2687. #undef V1
  2688. #undef V2
  2689. }
  2690. XML_Expat_Version XMLCALL
  2691. XML_ExpatVersionInfo(void) {
  2692. XML_Expat_Version version;
  2693. version.major = XML_MAJOR_VERSION;
  2694. version.minor = XML_MINOR_VERSION;
  2695. version.micro = XML_MICRO_VERSION;
  2696. return version;
  2697. }
  2698. const XML_Feature *XMLCALL
  2699. XML_GetFeatureList(void) {
  2700. static const XML_Feature features[] = {
  2701. {XML_FEATURE_SIZEOF_XML_CHAR, XML_L("sizeof(XML_Char)"),
  2702. sizeof(XML_Char)},
  2703. {XML_FEATURE_SIZEOF_XML_LCHAR, XML_L("sizeof(XML_LChar)"),
  2704. sizeof(XML_LChar)},
  2705. #ifdef XML_UNICODE
  2706. {XML_FEATURE_UNICODE, XML_L("XML_UNICODE"), 0},
  2707. #endif
  2708. #ifdef XML_UNICODE_WCHAR_T
  2709. {XML_FEATURE_UNICODE_WCHAR_T, XML_L("XML_UNICODE_WCHAR_T"), 0},
  2710. #endif
  2711. #ifdef XML_DTD
  2712. {XML_FEATURE_DTD, XML_L("XML_DTD"), 0},
  2713. #endif
  2714. #if XML_CONTEXT_BYTES > 0
  2715. {XML_FEATURE_CONTEXT_BYTES, XML_L("XML_CONTEXT_BYTES"),
  2716. XML_CONTEXT_BYTES},
  2717. #endif
  2718. #ifdef XML_MIN_SIZE
  2719. {XML_FEATURE_MIN_SIZE, XML_L("XML_MIN_SIZE"), 0},
  2720. #endif
  2721. #ifdef XML_NS
  2722. {XML_FEATURE_NS, XML_L("XML_NS"), 0},
  2723. #endif
  2724. #ifdef XML_LARGE_SIZE
  2725. {XML_FEATURE_LARGE_SIZE, XML_L("XML_LARGE_SIZE"), 0},
  2726. #endif
  2727. #ifdef XML_ATTR_INFO
  2728. {XML_FEATURE_ATTR_INFO, XML_L("XML_ATTR_INFO"), 0},
  2729. #endif
  2730. #if XML_GE == 1
  2731. /* Added in Expat 2.4.0 for XML_DTD defined and
  2732. * added in Expat 2.6.0 for XML_GE == 1. */
  2733. {XML_FEATURE_BILLION_LAUGHS_ATTACK_PROTECTION_MAXIMUM_AMPLIFICATION_DEFAULT,
  2734. XML_L("XML_BLAP_MAX_AMP"),
  2735. (long int)
  2736. EXPAT_BILLION_LAUGHS_ATTACK_PROTECTION_MAXIMUM_AMPLIFICATION_DEFAULT},
  2737. {XML_FEATURE_BILLION_LAUGHS_ATTACK_PROTECTION_ACTIVATION_THRESHOLD_DEFAULT,
  2738. XML_L("XML_BLAP_ACT_THRES"),
  2739. EXPAT_BILLION_LAUGHS_ATTACK_PROTECTION_ACTIVATION_THRESHOLD_DEFAULT},
  2740. /* Added in Expat 2.6.0. */
  2741. {XML_FEATURE_GE, XML_L("XML_GE"), 0},
  2742. /* Added in Expat 2.7.2. */
  2743. {XML_FEATURE_ALLOC_TRACKER_MAXIMUM_AMPLIFICATION_DEFAULT,
  2744. XML_L("XML_AT_MAX_AMP"),
  2745. (long int)EXPAT_ALLOC_TRACKER_MAXIMUM_AMPLIFICATION_DEFAULT},
  2746. {XML_FEATURE_ALLOC_TRACKER_ACTIVATION_THRESHOLD_DEFAULT,
  2747. XML_L("XML_AT_ACT_THRES"),
  2748. (long int)EXPAT_ALLOC_TRACKER_ACTIVATION_THRESHOLD_DEFAULT},
  2749. #endif
  2750. {XML_FEATURE_END, NULL, 0}};
  2751. return features;
  2752. }
  2753. #if XML_GE == 1
  2754. XML_Bool XMLCALL
  2755. XML_SetBillionLaughsAttackProtectionMaximumAmplification(
  2756. XML_Parser parser, float maximumAmplificationFactor) {
  2757. if ((parser == NULL) || (parser->m_parentParser != NULL)
  2758. || isnan(maximumAmplificationFactor)
  2759. || (maximumAmplificationFactor < 1.0f)) {
  2760. return XML_FALSE;
  2761. }
  2762. parser->m_accounting.maximumAmplificationFactor = maximumAmplificationFactor;
  2763. return XML_TRUE;
  2764. }
  2765. XML_Bool XMLCALL
  2766. XML_SetBillionLaughsAttackProtectionActivationThreshold(
  2767. XML_Parser parser, unsigned long long activationThresholdBytes) {
  2768. if ((parser == NULL) || (parser->m_parentParser != NULL)) {
  2769. return XML_FALSE;
  2770. }
  2771. parser->m_accounting.activationThresholdBytes = activationThresholdBytes;
  2772. return XML_TRUE;
  2773. }
  2774. XML_Bool XMLCALL
  2775. XML_SetAllocTrackerMaximumAmplification(XML_Parser parser,
  2776. float maximumAmplificationFactor) {
  2777. if ((parser == NULL) || (parser->m_parentParser != NULL)
  2778. || isnan(maximumAmplificationFactor)
  2779. || (maximumAmplificationFactor < 1.0f)) {
  2780. return XML_FALSE;
  2781. }
  2782. parser->m_alloc_tracker.maximumAmplificationFactor
  2783. = maximumAmplificationFactor;
  2784. return XML_TRUE;
  2785. }
  2786. XML_Bool XMLCALL
  2787. XML_SetAllocTrackerActivationThreshold(
  2788. XML_Parser parser, unsigned long long activationThresholdBytes) {
  2789. if ((parser == NULL) || (parser->m_parentParser != NULL)) {
  2790. return XML_FALSE;
  2791. }
  2792. parser->m_alloc_tracker.activationThresholdBytes = activationThresholdBytes;
  2793. return XML_TRUE;
  2794. }
  2795. #endif /* XML_GE == 1 */
  2796. XML_Bool XMLCALL
  2797. XML_SetReparseDeferralEnabled(XML_Parser parser, XML_Bool enabled) {
  2798. if (parser != NULL && (enabled == XML_TRUE || enabled == XML_FALSE)) {
  2799. parser->m_reparseDeferralEnabled = enabled;
  2800. return XML_TRUE;
  2801. }
  2802. return XML_FALSE;
  2803. }
  2804. /* Initially tag->rawName always points into the parse buffer;
  2805. for those TAG instances opened while the current parse buffer was
  2806. processed, and not yet closed, we need to store tag->rawName in a more
  2807. permanent location, since the parse buffer is about to be discarded.
  2808. */
  2809. static XML_Bool
  2810. storeRawNames(XML_Parser parser) {
  2811. TAG *tag = parser->m_tagStack;
  2812. while (tag) {
  2813. size_t bufSize;
  2814. size_t nameLen = sizeof(XML_Char) * (tag->name.strLen + 1);
  2815. size_t rawNameLen;
  2816. char *rawNameBuf = tag->buf.raw + nameLen;
  2817. /* Stop if already stored. Since m_tagStack is a stack, we can stop
  2818. at the first entry that has already been copied; everything
  2819. below it in the stack is already been accounted for in a
  2820. previous call to this function.
  2821. */
  2822. if (tag->rawName == rawNameBuf)
  2823. break;
  2824. /* For reuse purposes we need to ensure that the
  2825. size of tag->buf is a multiple of sizeof(XML_Char).
  2826. */
  2827. rawNameLen = ROUND_UP(tag->rawNameLength, sizeof(XML_Char));
  2828. /* Detect and prevent integer overflow. */
  2829. if (rawNameLen > (size_t)INT_MAX - nameLen)
  2830. return XML_FALSE;
  2831. bufSize = nameLen + rawNameLen;
  2832. if (bufSize > (size_t)(tag->bufEnd - tag->buf.raw)) {
  2833. char *temp = REALLOC(parser, tag->buf.raw, bufSize);
  2834. if (temp == NULL)
  2835. return XML_FALSE;
  2836. /* if tag->name.str points to tag->buf.str (only when namespace
  2837. processing is off) then we have to update it
  2838. */
  2839. if (tag->name.str == tag->buf.str)
  2840. tag->name.str = (XML_Char *)temp;
  2841. /* if tag->name.localPart is set (when namespace processing is on)
  2842. then update it as well, since it will always point into tag->buf
  2843. */
  2844. if (tag->name.localPart)
  2845. tag->name.localPart
  2846. = (XML_Char *)temp + (tag->name.localPart - tag->buf.str);
  2847. tag->buf.raw = temp;
  2848. tag->bufEnd = temp + bufSize;
  2849. rawNameBuf = temp + nameLen;
  2850. }
  2851. memcpy(rawNameBuf, tag->rawName, tag->rawNameLength);
  2852. tag->rawName = rawNameBuf;
  2853. tag = tag->parent;
  2854. }
  2855. return XML_TRUE;
  2856. }
  2857. static enum XML_Error PTRCALL
  2858. contentProcessor(XML_Parser parser, const char *start, const char *end,
  2859. const char **endPtr) {
  2860. enum XML_Error result = doContent(
  2861. parser, parser->m_parentParser ? 1 : 0, parser->m_encoding, start, end,
  2862. endPtr, (XML_Bool)! parser->m_parsingStatus.finalBuffer,
  2863. XML_ACCOUNT_DIRECT);
  2864. if (result == XML_ERROR_NONE) {
  2865. if (! storeRawNames(parser))
  2866. return XML_ERROR_NO_MEMORY;
  2867. }
  2868. return result;
  2869. }
  2870. static enum XML_Error PTRCALL
  2871. externalEntityInitProcessor(XML_Parser parser, const char *start,
  2872. const char *end, const char **endPtr) {
  2873. enum XML_Error result = initializeEncoding(parser);
  2874. if (result != XML_ERROR_NONE)
  2875. return result;
  2876. parser->m_processor = externalEntityInitProcessor2;
  2877. return externalEntityInitProcessor2(parser, start, end, endPtr);
  2878. }
  2879. static enum XML_Error PTRCALL
  2880. externalEntityInitProcessor2(XML_Parser parser, const char *start,
  2881. const char *end, const char **endPtr) {
  2882. const char *next = start; /* XmlContentTok doesn't always set the last arg */
  2883. int tok = XmlContentTok(parser->m_encoding, start, end, &next);
  2884. switch (tok) {
  2885. case XML_TOK_BOM:
  2886. #if XML_GE == 1
  2887. if (! accountingDiffTolerated(parser, tok, start, next, __LINE__,
  2888. XML_ACCOUNT_DIRECT)) {
  2889. accountingOnAbort(parser);
  2890. return XML_ERROR_AMPLIFICATION_LIMIT_BREACH;
  2891. }
  2892. #endif /* XML_GE == 1 */
  2893. /* If we are at the end of the buffer, this would cause the next stage,
  2894. i.e. externalEntityInitProcessor3, to pass control directly to
  2895. doContent (by detecting XML_TOK_NONE) without processing any xml text
  2896. declaration - causing the error XML_ERROR_MISPLACED_XML_PI in doContent.
  2897. */
  2898. if (next == end && ! parser->m_parsingStatus.finalBuffer) {
  2899. *endPtr = next;
  2900. return XML_ERROR_NONE;
  2901. }
  2902. start = next;
  2903. break;
  2904. case XML_TOK_PARTIAL:
  2905. if (! parser->m_parsingStatus.finalBuffer) {
  2906. *endPtr = start;
  2907. return XML_ERROR_NONE;
  2908. }
  2909. parser->m_eventPtr = start;
  2910. return XML_ERROR_UNCLOSED_TOKEN;
  2911. case XML_TOK_PARTIAL_CHAR:
  2912. if (! parser->m_parsingStatus.finalBuffer) {
  2913. *endPtr = start;
  2914. return XML_ERROR_NONE;
  2915. }
  2916. parser->m_eventPtr = start;
  2917. return XML_ERROR_PARTIAL_CHAR;
  2918. }
  2919. parser->m_processor = externalEntityInitProcessor3;
  2920. return externalEntityInitProcessor3(parser, start, end, endPtr);
  2921. }
  2922. static enum XML_Error PTRCALL
  2923. externalEntityInitProcessor3(XML_Parser parser, const char *start,
  2924. const char *end, const char **endPtr) {
  2925. int tok;
  2926. const char *next = start; /* XmlContentTok doesn't always set the last arg */
  2927. parser->m_eventPtr = start;
  2928. tok = XmlContentTok(parser->m_encoding, start, end, &next);
  2929. /* Note: These bytes are accounted later in:
  2930. - processXmlDecl
  2931. - externalEntityContentProcessor
  2932. */
  2933. parser->m_eventEndPtr = next;
  2934. switch (tok) {
  2935. case XML_TOK_XML_DECL: {
  2936. enum XML_Error result;
  2937. result = processXmlDecl(parser, 1, start, next);
  2938. if (result != XML_ERROR_NONE)
  2939. return result;
  2940. switch (parser->m_parsingStatus.parsing) {
  2941. case XML_SUSPENDED:
  2942. *endPtr = next;
  2943. return XML_ERROR_NONE;
  2944. case XML_FINISHED:
  2945. return XML_ERROR_ABORTED;
  2946. case XML_PARSING:
  2947. if (parser->m_reenter) {
  2948. return XML_ERROR_UNEXPECTED_STATE; // LCOV_EXCL_LINE
  2949. }
  2950. /* Fall through */
  2951. default:
  2952. start = next;
  2953. }
  2954. } break;
  2955. case XML_TOK_PARTIAL:
  2956. if (! parser->m_parsingStatus.finalBuffer) {
  2957. *endPtr = start;
  2958. return XML_ERROR_NONE;
  2959. }
  2960. return XML_ERROR_UNCLOSED_TOKEN;
  2961. case XML_TOK_PARTIAL_CHAR:
  2962. if (! parser->m_parsingStatus.finalBuffer) {
  2963. *endPtr = start;
  2964. return XML_ERROR_NONE;
  2965. }
  2966. return XML_ERROR_PARTIAL_CHAR;
  2967. }
  2968. parser->m_processor = externalEntityContentProcessor;
  2969. parser->m_tagLevel = 1;
  2970. return externalEntityContentProcessor(parser, start, end, endPtr);
  2971. }
  2972. static enum XML_Error PTRCALL
  2973. externalEntityContentProcessor(XML_Parser parser, const char *start,
  2974. const char *end, const char **endPtr) {
  2975. enum XML_Error result
  2976. = doContent(parser, 1, parser->m_encoding, start, end, endPtr,
  2977. (XML_Bool)! parser->m_parsingStatus.finalBuffer,
  2978. XML_ACCOUNT_ENTITY_EXPANSION);
  2979. if (result == XML_ERROR_NONE) {
  2980. if (! storeRawNames(parser))
  2981. return XML_ERROR_NO_MEMORY;
  2982. }
  2983. return result;
  2984. }
  2985. static enum XML_Error
  2986. doContent(XML_Parser parser, int startTagLevel, const ENCODING *enc,
  2987. const char *s, const char *end, const char **nextPtr,
  2988. XML_Bool haveMore, enum XML_Account account) {
  2989. /* save one level of indirection */
  2990. DTD *const dtd = parser->m_dtd;
  2991. const char **eventPP;
  2992. const char **eventEndPP;
  2993. if (enc == parser->m_encoding) {
  2994. eventPP = &parser->m_eventPtr;
  2995. eventEndPP = &parser->m_eventEndPtr;
  2996. } else {
  2997. eventPP = &(parser->m_openInternalEntities->internalEventPtr);
  2998. eventEndPP = &(parser->m_openInternalEntities->internalEventEndPtr);
  2999. }
  3000. *eventPP = s;
  3001. for (;;) {
  3002. const char *next = s; /* XmlContentTok doesn't always set the last arg */
  3003. int tok = XmlContentTok(enc, s, end, &next);
  3004. #if XML_GE == 1
  3005. const char *accountAfter
  3006. = ((tok == XML_TOK_TRAILING_RSQB) || (tok == XML_TOK_TRAILING_CR))
  3007. ? (haveMore ? s /* i.e. 0 bytes */ : end)
  3008. : next;
  3009. if (! accountingDiffTolerated(parser, tok, s, accountAfter, __LINE__,
  3010. account)) {
  3011. accountingOnAbort(parser);
  3012. return XML_ERROR_AMPLIFICATION_LIMIT_BREACH;
  3013. }
  3014. #endif
  3015. *eventEndPP = next;
  3016. switch (tok) {
  3017. case XML_TOK_TRAILING_CR:
  3018. if (haveMore) {
  3019. *nextPtr = s;
  3020. return XML_ERROR_NONE;
  3021. }
  3022. *eventEndPP = end;
  3023. if (parser->m_characterDataHandler) {
  3024. XML_Char c = 0xA;
  3025. parser->m_characterDataHandler(parser->m_handlerArg, &c, 1);
  3026. } else if (parser->m_defaultHandler)
  3027. reportDefault(parser, enc, s, end);
  3028. /* We are at the end of the final buffer, should we check for
  3029. XML_SUSPENDED, XML_FINISHED?
  3030. */
  3031. if (startTagLevel == 0)
  3032. return XML_ERROR_NO_ELEMENTS;
  3033. if (parser->m_tagLevel != startTagLevel)
  3034. return XML_ERROR_ASYNC_ENTITY;
  3035. *nextPtr = end;
  3036. return XML_ERROR_NONE;
  3037. case XML_TOK_NONE:
  3038. if (haveMore) {
  3039. *nextPtr = s;
  3040. return XML_ERROR_NONE;
  3041. }
  3042. if (startTagLevel > 0) {
  3043. if (parser->m_tagLevel != startTagLevel)
  3044. return XML_ERROR_ASYNC_ENTITY;
  3045. *nextPtr = s;
  3046. return XML_ERROR_NONE;
  3047. }
  3048. return XML_ERROR_NO_ELEMENTS;
  3049. case XML_TOK_INVALID:
  3050. *eventPP = next;
  3051. return XML_ERROR_INVALID_TOKEN;
  3052. case XML_TOK_PARTIAL:
  3053. if (haveMore) {
  3054. *nextPtr = s;
  3055. return XML_ERROR_NONE;
  3056. }
  3057. return XML_ERROR_UNCLOSED_TOKEN;
  3058. case XML_TOK_PARTIAL_CHAR:
  3059. if (haveMore) {
  3060. *nextPtr = s;
  3061. return XML_ERROR_NONE;
  3062. }
  3063. return XML_ERROR_PARTIAL_CHAR;
  3064. case XML_TOK_ENTITY_REF: {
  3065. const XML_Char *name;
  3066. ENTITY *entity;
  3067. XML_Char ch = (XML_Char)XmlPredefinedEntityName(
  3068. enc, s + enc->minBytesPerChar, next - enc->minBytesPerChar);
  3069. if (ch) {
  3070. #if XML_GE == 1
  3071. /* NOTE: We are replacing 4-6 characters original input for 1 character
  3072. * so there is no amplification and hence recording without
  3073. * protection. */
  3074. accountingDiffTolerated(parser, tok, (char *)&ch,
  3075. ((char *)&ch) + sizeof(XML_Char), __LINE__,
  3076. XML_ACCOUNT_ENTITY_EXPANSION);
  3077. #endif /* XML_GE == 1 */
  3078. if (parser->m_characterDataHandler)
  3079. parser->m_characterDataHandler(parser->m_handlerArg, &ch, 1);
  3080. else if (parser->m_defaultHandler)
  3081. reportDefault(parser, enc, s, next);
  3082. break;
  3083. }
  3084. name = poolStoreString(&dtd->pool, enc, s + enc->minBytesPerChar,
  3085. next - enc->minBytesPerChar);
  3086. if (! name)
  3087. return XML_ERROR_NO_MEMORY;
  3088. entity = (ENTITY *)lookup(parser, &dtd->generalEntities, name, 0);
  3089. poolDiscard(&dtd->pool);
  3090. /* First, determine if a check for an existing declaration is needed;
  3091. if yes, check that the entity exists, and that it is internal,
  3092. otherwise call the skipped entity or default handler.
  3093. */
  3094. if (! dtd->hasParamEntityRefs || dtd->standalone) {
  3095. if (! entity)
  3096. return XML_ERROR_UNDEFINED_ENTITY;
  3097. else if (! entity->is_internal)
  3098. return XML_ERROR_ENTITY_DECLARED_IN_PE;
  3099. } else if (! entity) {
  3100. if (parser->m_skippedEntityHandler)
  3101. parser->m_skippedEntityHandler(parser->m_handlerArg, name, 0);
  3102. else if (parser->m_defaultHandler)
  3103. reportDefault(parser, enc, s, next);
  3104. break;
  3105. }
  3106. if (entity->open)
  3107. return XML_ERROR_RECURSIVE_ENTITY_REF;
  3108. if (entity->notation)
  3109. return XML_ERROR_BINARY_ENTITY_REF;
  3110. if (entity->textPtr) {
  3111. enum XML_Error result;
  3112. if (! parser->m_defaultExpandInternalEntities) {
  3113. if (parser->m_skippedEntityHandler)
  3114. parser->m_skippedEntityHandler(parser->m_handlerArg, entity->name,
  3115. 0);
  3116. else if (parser->m_defaultHandler)
  3117. reportDefault(parser, enc, s, next);
  3118. break;
  3119. }
  3120. result = processEntity(parser, entity, XML_FALSE, ENTITY_INTERNAL);
  3121. if (result != XML_ERROR_NONE)
  3122. return result;
  3123. } else if (parser->m_externalEntityRefHandler) {
  3124. const XML_Char *context;
  3125. entity->open = XML_TRUE;
  3126. context = getContext(parser);
  3127. entity->open = XML_FALSE;
  3128. if (! context)
  3129. return XML_ERROR_NO_MEMORY;
  3130. if (! parser->m_externalEntityRefHandler(
  3131. parser->m_externalEntityRefHandlerArg, context, entity->base,
  3132. entity->systemId, entity->publicId))
  3133. return XML_ERROR_EXTERNAL_ENTITY_HANDLING;
  3134. poolDiscard(&parser->m_tempPool);
  3135. } else if (parser->m_defaultHandler)
  3136. reportDefault(parser, enc, s, next);
  3137. break;
  3138. }
  3139. case XML_TOK_START_TAG_NO_ATTS:
  3140. /* fall through */
  3141. case XML_TOK_START_TAG_WITH_ATTS: {
  3142. TAG *tag;
  3143. enum XML_Error result;
  3144. XML_Char *toPtr;
  3145. if (parser->m_freeTagList) {
  3146. tag = parser->m_freeTagList;
  3147. parser->m_freeTagList = parser->m_freeTagList->parent;
  3148. } else {
  3149. tag = MALLOC(parser, sizeof(TAG));
  3150. if (! tag)
  3151. return XML_ERROR_NO_MEMORY;
  3152. tag->buf.raw = MALLOC(parser, INIT_TAG_BUF_SIZE);
  3153. if (! tag->buf.raw) {
  3154. FREE(parser, tag);
  3155. return XML_ERROR_NO_MEMORY;
  3156. }
  3157. tag->bufEnd = tag->buf.raw + INIT_TAG_BUF_SIZE;
  3158. }
  3159. tag->bindings = NULL;
  3160. tag->parent = parser->m_tagStack;
  3161. parser->m_tagStack = tag;
  3162. tag->name.localPart = NULL;
  3163. tag->name.prefix = NULL;
  3164. tag->rawName = s + enc->minBytesPerChar;
  3165. tag->rawNameLength = XmlNameLength(enc, tag->rawName);
  3166. ++parser->m_tagLevel;
  3167. {
  3168. const char *rawNameEnd = tag->rawName + tag->rawNameLength;
  3169. const char *fromPtr = tag->rawName;
  3170. toPtr = tag->buf.str;
  3171. for (;;) {
  3172. int convLen;
  3173. const enum XML_Convert_Result convert_res
  3174. = XmlConvert(enc, &fromPtr, rawNameEnd, (ICHAR **)&toPtr,
  3175. (ICHAR *)tag->bufEnd - 1);
  3176. convLen = (int)(toPtr - tag->buf.str);
  3177. if ((fromPtr >= rawNameEnd)
  3178. || (convert_res == XML_CONVERT_INPUT_INCOMPLETE)) {
  3179. tag->name.strLen = convLen;
  3180. break;
  3181. }
  3182. if (SIZE_MAX / 2 < (size_t)(tag->bufEnd - tag->buf.raw))
  3183. return XML_ERROR_NO_MEMORY;
  3184. const size_t bufSize = (size_t)(tag->bufEnd - tag->buf.raw) * 2;
  3185. {
  3186. char *temp = REALLOC(parser, tag->buf.raw, bufSize);
  3187. if (temp == NULL)
  3188. return XML_ERROR_NO_MEMORY;
  3189. tag->buf.raw = temp;
  3190. tag->bufEnd = temp + bufSize;
  3191. toPtr = (XML_Char *)temp + convLen;
  3192. }
  3193. }
  3194. }
  3195. tag->name.str = tag->buf.str;
  3196. *toPtr = XML_T('\0');
  3197. result
  3198. = storeAtts(parser, enc, s, &(tag->name), &(tag->bindings), account);
  3199. if (result)
  3200. return result;
  3201. if (parser->m_startElementHandler)
  3202. parser->m_startElementHandler(parser->m_handlerArg, tag->name.str,
  3203. (const XML_Char **)parser->m_atts);
  3204. else if (parser->m_defaultHandler)
  3205. reportDefault(parser, enc, s, next);
  3206. poolClear(&parser->m_tempPool);
  3207. break;
  3208. }
  3209. case XML_TOK_EMPTY_ELEMENT_NO_ATTS:
  3210. /* fall through */
  3211. case XML_TOK_EMPTY_ELEMENT_WITH_ATTS: {
  3212. const char *rawName = s + enc->minBytesPerChar;
  3213. enum XML_Error result;
  3214. BINDING *bindings = NULL;
  3215. XML_Bool noElmHandlers = XML_TRUE;
  3216. TAG_NAME name;
  3217. name.str = poolStoreString(&parser->m_tempPool, enc, rawName,
  3218. rawName + XmlNameLength(enc, rawName));
  3219. if (! name.str)
  3220. return XML_ERROR_NO_MEMORY;
  3221. poolFinish(&parser->m_tempPool);
  3222. result = storeAtts(parser, enc, s, &name, &bindings,
  3223. XML_ACCOUNT_NONE /* token spans whole start tag */);
  3224. if (result != XML_ERROR_NONE) {
  3225. freeBindings(parser, bindings);
  3226. return result;
  3227. }
  3228. poolFinish(&parser->m_tempPool);
  3229. if (parser->m_startElementHandler) {
  3230. parser->m_startElementHandler(parser->m_handlerArg, name.str,
  3231. (const XML_Char **)parser->m_atts);
  3232. noElmHandlers = XML_FALSE;
  3233. }
  3234. if (parser->m_endElementHandler) {
  3235. if (parser->m_startElementHandler)
  3236. *eventPP = *eventEndPP;
  3237. parser->m_endElementHandler(parser->m_handlerArg, name.str);
  3238. noElmHandlers = XML_FALSE;
  3239. }
  3240. if (noElmHandlers && parser->m_defaultHandler)
  3241. reportDefault(parser, enc, s, next);
  3242. poolClear(&parser->m_tempPool);
  3243. freeBindings(parser, bindings);
  3244. }
  3245. if ((parser->m_tagLevel == 0)
  3246. && (parser->m_parsingStatus.parsing != XML_FINISHED)) {
  3247. if (parser->m_parsingStatus.parsing == XML_SUSPENDED
  3248. || (parser->m_parsingStatus.parsing == XML_PARSING
  3249. && parser->m_reenter))
  3250. parser->m_processor = epilogProcessor;
  3251. else
  3252. return epilogProcessor(parser, next, end, nextPtr);
  3253. }
  3254. break;
  3255. case XML_TOK_END_TAG:
  3256. if (parser->m_tagLevel == startTagLevel)
  3257. return XML_ERROR_ASYNC_ENTITY;
  3258. else {
  3259. int len;
  3260. const char *rawName;
  3261. TAG *tag = parser->m_tagStack;
  3262. rawName = s + enc->minBytesPerChar * 2;
  3263. len = XmlNameLength(enc, rawName);
  3264. if (len != tag->rawNameLength
  3265. || memcmp(tag->rawName, rawName, len) != 0) {
  3266. *eventPP = rawName;
  3267. return XML_ERROR_TAG_MISMATCH;
  3268. }
  3269. parser->m_tagStack = tag->parent;
  3270. tag->parent = parser->m_freeTagList;
  3271. parser->m_freeTagList = tag;
  3272. --parser->m_tagLevel;
  3273. if (parser->m_endElementHandler) {
  3274. const XML_Char *localPart;
  3275. const XML_Char *prefix;
  3276. XML_Char *uri;
  3277. localPart = tag->name.localPart;
  3278. if (parser->m_ns && localPart) {
  3279. /* localPart and prefix may have been overwritten in
  3280. tag->name.str, since this points to the binding->uri
  3281. buffer which gets reused; so we have to add them again
  3282. */
  3283. uri = (XML_Char *)tag->name.str + tag->name.uriLen;
  3284. /* don't need to check for space - already done in storeAtts() */
  3285. while (*localPart)
  3286. *uri++ = *localPart++;
  3287. prefix = tag->name.prefix;
  3288. if (parser->m_ns_triplets && prefix) {
  3289. *uri++ = parser->m_namespaceSeparator;
  3290. while (*prefix)
  3291. *uri++ = *prefix++;
  3292. }
  3293. *uri = XML_T('\0');
  3294. }
  3295. parser->m_endElementHandler(parser->m_handlerArg, tag->name.str);
  3296. } else if (parser->m_defaultHandler)
  3297. reportDefault(parser, enc, s, next);
  3298. while (tag->bindings) {
  3299. BINDING *b = tag->bindings;
  3300. if (parser->m_endNamespaceDeclHandler)
  3301. parser->m_endNamespaceDeclHandler(parser->m_handlerArg,
  3302. b->prefix->name);
  3303. tag->bindings = tag->bindings->nextTagBinding;
  3304. b->nextTagBinding = parser->m_freeBindingList;
  3305. parser->m_freeBindingList = b;
  3306. b->prefix->binding = b->prevPrefixBinding;
  3307. }
  3308. if ((parser->m_tagLevel == 0)
  3309. && (parser->m_parsingStatus.parsing != XML_FINISHED)) {
  3310. if (parser->m_parsingStatus.parsing == XML_SUSPENDED
  3311. || (parser->m_parsingStatus.parsing == XML_PARSING
  3312. && parser->m_reenter))
  3313. parser->m_processor = epilogProcessor;
  3314. else
  3315. return epilogProcessor(parser, next, end, nextPtr);
  3316. }
  3317. }
  3318. break;
  3319. case XML_TOK_CHAR_REF: {
  3320. int n = XmlCharRefNumber(enc, s);
  3321. if (n < 0)
  3322. return XML_ERROR_BAD_CHAR_REF;
  3323. if (parser->m_characterDataHandler) {
  3324. XML_Char buf[XML_ENCODE_MAX];
  3325. parser->m_characterDataHandler(parser->m_handlerArg, buf,
  3326. XmlEncode(n, (ICHAR *)buf));
  3327. } else if (parser->m_defaultHandler)
  3328. reportDefault(parser, enc, s, next);
  3329. } break;
  3330. case XML_TOK_XML_DECL:
  3331. return XML_ERROR_MISPLACED_XML_PI;
  3332. case XML_TOK_DATA_NEWLINE:
  3333. if (parser->m_characterDataHandler) {
  3334. XML_Char c = 0xA;
  3335. parser->m_characterDataHandler(parser->m_handlerArg, &c, 1);
  3336. } else if (parser->m_defaultHandler)
  3337. reportDefault(parser, enc, s, next);
  3338. break;
  3339. case XML_TOK_CDATA_SECT_OPEN: {
  3340. enum XML_Error result;
  3341. if (parser->m_startCdataSectionHandler)
  3342. parser->m_startCdataSectionHandler(parser->m_handlerArg);
  3343. /* BEGIN disabled code */
  3344. /* Suppose you doing a transformation on a document that involves
  3345. changing only the character data. You set up a defaultHandler
  3346. and a characterDataHandler. The defaultHandler simply copies
  3347. characters through. The characterDataHandler does the
  3348. transformation and writes the characters out escaping them as
  3349. necessary. This case will fail to work if we leave out the
  3350. following two lines (because & and < inside CDATA sections will
  3351. be incorrectly escaped).
  3352. However, now we have a start/endCdataSectionHandler, so it seems
  3353. easier to let the user deal with this.
  3354. */
  3355. else if ((0) && parser->m_characterDataHandler)
  3356. parser->m_characterDataHandler(parser->m_handlerArg, parser->m_dataBuf,
  3357. 0);
  3358. /* END disabled code */
  3359. else if (parser->m_defaultHandler)
  3360. reportDefault(parser, enc, s, next);
  3361. result
  3362. = doCdataSection(parser, enc, &next, end, nextPtr, haveMore, account);
  3363. if (result != XML_ERROR_NONE)
  3364. return result;
  3365. else if (! next) {
  3366. parser->m_processor = cdataSectionProcessor;
  3367. return result;
  3368. }
  3369. } break;
  3370. case XML_TOK_TRAILING_RSQB:
  3371. if (haveMore) {
  3372. *nextPtr = s;
  3373. return XML_ERROR_NONE;
  3374. }
  3375. if (parser->m_characterDataHandler) {
  3376. if (MUST_CONVERT(enc, s)) {
  3377. ICHAR *dataPtr = (ICHAR *)parser->m_dataBuf;
  3378. XmlConvert(enc, &s, end, &dataPtr, (ICHAR *)parser->m_dataBufEnd);
  3379. parser->m_characterDataHandler(
  3380. parser->m_handlerArg, parser->m_dataBuf,
  3381. (int)(dataPtr - (ICHAR *)parser->m_dataBuf));
  3382. } else
  3383. parser->m_characterDataHandler(
  3384. parser->m_handlerArg, (const XML_Char *)s,
  3385. (int)((const XML_Char *)end - (const XML_Char *)s));
  3386. } else if (parser->m_defaultHandler)
  3387. reportDefault(parser, enc, s, end);
  3388. /* We are at the end of the final buffer, should we check for
  3389. XML_SUSPENDED, XML_FINISHED?
  3390. */
  3391. if (startTagLevel == 0) {
  3392. *eventPP = end;
  3393. return XML_ERROR_NO_ELEMENTS;
  3394. }
  3395. if (parser->m_tagLevel != startTagLevel) {
  3396. *eventPP = end;
  3397. return XML_ERROR_ASYNC_ENTITY;
  3398. }
  3399. *nextPtr = end;
  3400. return XML_ERROR_NONE;
  3401. case XML_TOK_DATA_CHARS: {
  3402. XML_CharacterDataHandler charDataHandler = parser->m_characterDataHandler;
  3403. if (charDataHandler) {
  3404. if (MUST_CONVERT(enc, s)) {
  3405. for (;;) {
  3406. ICHAR *dataPtr = (ICHAR *)parser->m_dataBuf;
  3407. const enum XML_Convert_Result convert_res = XmlConvert(
  3408. enc, &s, next, &dataPtr, (ICHAR *)parser->m_dataBufEnd);
  3409. *eventEndPP = s;
  3410. charDataHandler(parser->m_handlerArg, parser->m_dataBuf,
  3411. (int)(dataPtr - (ICHAR *)parser->m_dataBuf));
  3412. if ((convert_res == XML_CONVERT_COMPLETED)
  3413. || (convert_res == XML_CONVERT_INPUT_INCOMPLETE))
  3414. break;
  3415. *eventPP = s;
  3416. }
  3417. } else
  3418. charDataHandler(parser->m_handlerArg, (const XML_Char *)s,
  3419. (int)((const XML_Char *)next - (const XML_Char *)s));
  3420. } else if (parser->m_defaultHandler)
  3421. reportDefault(parser, enc, s, next);
  3422. } break;
  3423. case XML_TOK_PI:
  3424. if (! reportProcessingInstruction(parser, enc, s, next))
  3425. return XML_ERROR_NO_MEMORY;
  3426. break;
  3427. case XML_TOK_COMMENT:
  3428. if (! reportComment(parser, enc, s, next))
  3429. return XML_ERROR_NO_MEMORY;
  3430. break;
  3431. default:
  3432. /* All of the tokens produced by XmlContentTok() have their own
  3433. * explicit cases, so this default is not strictly necessary.
  3434. * However it is a useful safety net, so we retain the code and
  3435. * simply exclude it from the coverage tests.
  3436. *
  3437. * LCOV_EXCL_START
  3438. */
  3439. if (parser->m_defaultHandler)
  3440. reportDefault(parser, enc, s, next);
  3441. break;
  3442. /* LCOV_EXCL_STOP */
  3443. }
  3444. switch (parser->m_parsingStatus.parsing) {
  3445. case XML_SUSPENDED:
  3446. *eventPP = next;
  3447. *nextPtr = next;
  3448. return XML_ERROR_NONE;
  3449. case XML_FINISHED:
  3450. *eventPP = next;
  3451. return XML_ERROR_ABORTED;
  3452. case XML_PARSING:
  3453. if (parser->m_reenter) {
  3454. *nextPtr = next;
  3455. return XML_ERROR_NONE;
  3456. }
  3457. /* Fall through */
  3458. default:;
  3459. *eventPP = s = next;
  3460. }
  3461. }
  3462. /* not reached */
  3463. }
  3464. /* This function does not call free() on the allocated memory, merely
  3465. * moving it to the parser's m_freeBindingList where it can be freed or
  3466. * reused as appropriate.
  3467. */
  3468. static void
  3469. freeBindings(XML_Parser parser, BINDING *bindings) {
  3470. while (bindings) {
  3471. BINDING *b = bindings;
  3472. /* m_startNamespaceDeclHandler will have been called for this
  3473. * binding in addBindings(), so call the end handler now.
  3474. */
  3475. if (parser->m_endNamespaceDeclHandler)
  3476. parser->m_endNamespaceDeclHandler(parser->m_handlerArg, b->prefix->name);
  3477. bindings = bindings->nextTagBinding;
  3478. b->nextTagBinding = parser->m_freeBindingList;
  3479. parser->m_freeBindingList = b;
  3480. b->prefix->binding = b->prevPrefixBinding;
  3481. }
  3482. }
  3483. /* Precondition: all arguments must be non-NULL;
  3484. Purpose:
  3485. - normalize attributes
  3486. - check attributes for well-formedness
  3487. - generate namespace aware attribute names (URI, prefix)
  3488. - build list of attributes for startElementHandler
  3489. - default attributes
  3490. - process namespace declarations (check and report them)
  3491. - generate namespace aware element name (URI, prefix)
  3492. */
  3493. static enum XML_Error
  3494. storeAtts(XML_Parser parser, const ENCODING *enc, const char *attStr,
  3495. TAG_NAME *tagNamePtr, BINDING **bindingsPtr,
  3496. enum XML_Account account) {
  3497. DTD *const dtd = parser->m_dtd; /* save one level of indirection */
  3498. ELEMENT_TYPE *elementType;
  3499. int nDefaultAtts;
  3500. const XML_Char **appAtts; /* the attribute list for the application */
  3501. int attIndex = 0;
  3502. int prefixLen;
  3503. int i;
  3504. int n;
  3505. XML_Char *uri;
  3506. int nPrefixes = 0;
  3507. BINDING *binding;
  3508. const XML_Char *localPart;
  3509. /* lookup the element type name */
  3510. elementType
  3511. = (ELEMENT_TYPE *)lookup(parser, &dtd->elementTypes, tagNamePtr->str, 0);
  3512. if (! elementType) {
  3513. const XML_Char *name = poolCopyString(&dtd->pool, tagNamePtr->str);
  3514. if (! name)
  3515. return XML_ERROR_NO_MEMORY;
  3516. elementType = (ELEMENT_TYPE *)lookup(parser, &dtd->elementTypes, name,
  3517. sizeof(ELEMENT_TYPE));
  3518. if (! elementType)
  3519. return XML_ERROR_NO_MEMORY;
  3520. if (parser->m_ns && ! setElementTypePrefix(parser, elementType))
  3521. return XML_ERROR_NO_MEMORY;
  3522. }
  3523. nDefaultAtts = elementType->nDefaultAtts;
  3524. /* get the attributes from the tokenizer */
  3525. n = XmlGetAttributes(enc, attStr, parser->m_attsSize, parser->m_atts);
  3526. /* Detect and prevent integer overflow */
  3527. if (n > INT_MAX - nDefaultAtts) {
  3528. return XML_ERROR_NO_MEMORY;
  3529. }
  3530. if (n + nDefaultAtts > parser->m_attsSize) {
  3531. int oldAttsSize = parser->m_attsSize;
  3532. ATTRIBUTE *temp;
  3533. #ifdef XML_ATTR_INFO
  3534. XML_AttrInfo *temp2;
  3535. #endif
  3536. /* Detect and prevent integer overflow */
  3537. if ((nDefaultAtts > INT_MAX - INIT_ATTS_SIZE)
  3538. || (n > INT_MAX - (nDefaultAtts + INIT_ATTS_SIZE))) {
  3539. return XML_ERROR_NO_MEMORY;
  3540. }
  3541. parser->m_attsSize = n + nDefaultAtts + INIT_ATTS_SIZE;
  3542. /* Detect and prevent integer overflow.
  3543. * The preprocessor guard addresses the "always false" warning
  3544. * from -Wtype-limits on platforms where
  3545. * sizeof(unsigned int) < sizeof(size_t), e.g. on x86_64. */
  3546. #if UINT_MAX >= SIZE_MAX
  3547. if ((unsigned)parser->m_attsSize > SIZE_MAX / sizeof(ATTRIBUTE)) {
  3548. parser->m_attsSize = oldAttsSize;
  3549. return XML_ERROR_NO_MEMORY;
  3550. }
  3551. #endif
  3552. temp = REALLOC(parser, parser->m_atts,
  3553. parser->m_attsSize * sizeof(ATTRIBUTE));
  3554. if (temp == NULL) {
  3555. parser->m_attsSize = oldAttsSize;
  3556. return XML_ERROR_NO_MEMORY;
  3557. }
  3558. parser->m_atts = temp;
  3559. #ifdef XML_ATTR_INFO
  3560. /* Detect and prevent integer overflow.
  3561. * The preprocessor guard addresses the "always false" warning
  3562. * from -Wtype-limits on platforms where
  3563. * sizeof(unsigned int) < sizeof(size_t), e.g. on x86_64. */
  3564. # if UINT_MAX >= SIZE_MAX
  3565. if ((unsigned)parser->m_attsSize > SIZE_MAX / sizeof(XML_AttrInfo)) {
  3566. parser->m_attsSize = oldAttsSize;
  3567. return XML_ERROR_NO_MEMORY;
  3568. }
  3569. # endif
  3570. temp2 = REALLOC(parser, parser->m_attInfo,
  3571. parser->m_attsSize * sizeof(XML_AttrInfo));
  3572. if (temp2 == NULL) {
  3573. parser->m_attsSize = oldAttsSize;
  3574. return XML_ERROR_NO_MEMORY;
  3575. }
  3576. parser->m_attInfo = temp2;
  3577. #endif
  3578. if (n > oldAttsSize)
  3579. XmlGetAttributes(enc, attStr, n, parser->m_atts);
  3580. }
  3581. appAtts = (const XML_Char **)parser->m_atts;
  3582. for (i = 0; i < n; i++) {
  3583. ATTRIBUTE *currAtt = &parser->m_atts[i];
  3584. #ifdef XML_ATTR_INFO
  3585. XML_AttrInfo *currAttInfo = &parser->m_attInfo[i];
  3586. #endif
  3587. /* add the name and value to the attribute list */
  3588. ATTRIBUTE_ID *attId
  3589. = getAttributeId(parser, enc, currAtt->name,
  3590. currAtt->name + XmlNameLength(enc, currAtt->name));
  3591. if (! attId)
  3592. return XML_ERROR_NO_MEMORY;
  3593. #ifdef XML_ATTR_INFO
  3594. currAttInfo->nameStart
  3595. = parser->m_parseEndByteIndex - (parser->m_parseEndPtr - currAtt->name);
  3596. currAttInfo->nameEnd
  3597. = currAttInfo->nameStart + XmlNameLength(enc, currAtt->name);
  3598. currAttInfo->valueStart = parser->m_parseEndByteIndex
  3599. - (parser->m_parseEndPtr - currAtt->valuePtr);
  3600. currAttInfo->valueEnd = parser->m_parseEndByteIndex
  3601. - (parser->m_parseEndPtr - currAtt->valueEnd);
  3602. #endif
  3603. /* Detect duplicate attributes by their QNames. This does not work when
  3604. namespace processing is turned on and different prefixes for the same
  3605. namespace are used. For this case we have a check further down.
  3606. */
  3607. if ((attId->name)[-1]) {
  3608. if (enc == parser->m_encoding)
  3609. parser->m_eventPtr = parser->m_atts[i].name;
  3610. return XML_ERROR_DUPLICATE_ATTRIBUTE;
  3611. }
  3612. (attId->name)[-1] = 1;
  3613. appAtts[attIndex++] = attId->name;
  3614. if (! parser->m_atts[i].normalized) {
  3615. enum XML_Error result;
  3616. XML_Bool isCdata = XML_TRUE;
  3617. /* figure out whether declared as other than CDATA */
  3618. if (attId->maybeTokenized) {
  3619. int j;
  3620. for (j = 0; j < nDefaultAtts; j++) {
  3621. if (attId == elementType->defaultAtts[j].id) {
  3622. isCdata = elementType->defaultAtts[j].isCdata;
  3623. break;
  3624. }
  3625. }
  3626. }
  3627. /* normalize the attribute value */
  3628. result = storeAttributeValue(
  3629. parser, enc, isCdata, parser->m_atts[i].valuePtr,
  3630. parser->m_atts[i].valueEnd, &parser->m_tempPool, account);
  3631. if (result)
  3632. return result;
  3633. appAtts[attIndex] = poolStart(&parser->m_tempPool);
  3634. poolFinish(&parser->m_tempPool);
  3635. } else {
  3636. /* the value did not need normalizing */
  3637. appAtts[attIndex] = poolStoreString(&parser->m_tempPool, enc,
  3638. parser->m_atts[i].valuePtr,
  3639. parser->m_atts[i].valueEnd);
  3640. if (appAtts[attIndex] == 0)
  3641. return XML_ERROR_NO_MEMORY;
  3642. poolFinish(&parser->m_tempPool);
  3643. }
  3644. /* handle prefixed attribute names */
  3645. if (attId->prefix) {
  3646. if (attId->xmlns) {
  3647. /* deal with namespace declarations here */
  3648. enum XML_Error result = addBinding(parser, attId->prefix, attId,
  3649. appAtts[attIndex], bindingsPtr);
  3650. if (result)
  3651. return result;
  3652. --attIndex;
  3653. } else {
  3654. /* deal with other prefixed names later */
  3655. attIndex++;
  3656. nPrefixes++;
  3657. (attId->name)[-1] = 2;
  3658. }
  3659. } else
  3660. attIndex++;
  3661. }
  3662. /* set-up for XML_GetSpecifiedAttributeCount and XML_GetIdAttributeIndex */
  3663. parser->m_nSpecifiedAtts = attIndex;
  3664. if (elementType->idAtt && (elementType->idAtt->name)[-1]) {
  3665. for (i = 0; i < attIndex; i += 2)
  3666. if (appAtts[i] == elementType->idAtt->name) {
  3667. parser->m_idAttIndex = i;
  3668. break;
  3669. }
  3670. } else
  3671. parser->m_idAttIndex = -1;
  3672. /* do attribute defaulting */
  3673. for (i = 0; i < nDefaultAtts; i++) {
  3674. const DEFAULT_ATTRIBUTE *da = elementType->defaultAtts + i;
  3675. if (! (da->id->name)[-1] && da->value) {
  3676. if (da->id->prefix) {
  3677. if (da->id->xmlns) {
  3678. enum XML_Error result = addBinding(parser, da->id->prefix, da->id,
  3679. da->value, bindingsPtr);
  3680. if (result)
  3681. return result;
  3682. } else {
  3683. (da->id->name)[-1] = 2;
  3684. nPrefixes++;
  3685. appAtts[attIndex++] = da->id->name;
  3686. appAtts[attIndex++] = da->value;
  3687. }
  3688. } else {
  3689. (da->id->name)[-1] = 1;
  3690. appAtts[attIndex++] = da->id->name;
  3691. appAtts[attIndex++] = da->value;
  3692. }
  3693. }
  3694. }
  3695. appAtts[attIndex] = 0;
  3696. /* expand prefixed attribute names, check for duplicates,
  3697. and clear flags that say whether attributes were specified */
  3698. i = 0;
  3699. if (nPrefixes) {
  3700. unsigned int j; /* hash table index */
  3701. unsigned long version = parser->m_nsAttsVersion;
  3702. /* Detect and prevent invalid shift */
  3703. if (parser->m_nsAttsPower >= sizeof(unsigned int) * 8 /* bits per byte */) {
  3704. return XML_ERROR_NO_MEMORY;
  3705. }
  3706. unsigned int nsAttsSize = 1u << parser->m_nsAttsPower;
  3707. unsigned char oldNsAttsPower = parser->m_nsAttsPower;
  3708. /* size of hash table must be at least 2 * (# of prefixed attributes) */
  3709. if ((nPrefixes << 1)
  3710. >> parser->m_nsAttsPower) { /* true for m_nsAttsPower = 0 */
  3711. NS_ATT *temp;
  3712. /* hash table size must also be a power of 2 and >= 8 */
  3713. while (nPrefixes >> parser->m_nsAttsPower++)
  3714. ;
  3715. if (parser->m_nsAttsPower < 3)
  3716. parser->m_nsAttsPower = 3;
  3717. /* Detect and prevent invalid shift */
  3718. if (parser->m_nsAttsPower >= sizeof(nsAttsSize) * 8 /* bits per byte */) {
  3719. /* Restore actual size of memory in m_nsAtts */
  3720. parser->m_nsAttsPower = oldNsAttsPower;
  3721. return XML_ERROR_NO_MEMORY;
  3722. }
  3723. nsAttsSize = 1u << parser->m_nsAttsPower;
  3724. /* Detect and prevent integer overflow.
  3725. * The preprocessor guard addresses the "always false" warning
  3726. * from -Wtype-limits on platforms where
  3727. * sizeof(unsigned int) < sizeof(size_t), e.g. on x86_64. */
  3728. #if UINT_MAX >= SIZE_MAX
  3729. if (nsAttsSize > SIZE_MAX / sizeof(NS_ATT)) {
  3730. /* Restore actual size of memory in m_nsAtts */
  3731. parser->m_nsAttsPower = oldNsAttsPower;
  3732. return XML_ERROR_NO_MEMORY;
  3733. }
  3734. #endif
  3735. temp = REALLOC(parser, parser->m_nsAtts, nsAttsSize * sizeof(NS_ATT));
  3736. if (! temp) {
  3737. /* Restore actual size of memory in m_nsAtts */
  3738. parser->m_nsAttsPower = oldNsAttsPower;
  3739. return XML_ERROR_NO_MEMORY;
  3740. }
  3741. parser->m_nsAtts = temp;
  3742. version = 0; /* force re-initialization of m_nsAtts hash table */
  3743. }
  3744. /* using a version flag saves us from initializing m_nsAtts every time */
  3745. if (! version) { /* initialize version flags when version wraps around */
  3746. version = INIT_ATTS_VERSION;
  3747. for (j = nsAttsSize; j != 0;)
  3748. parser->m_nsAtts[--j].version = version;
  3749. }
  3750. parser->m_nsAttsVersion = --version;
  3751. /* expand prefixed names and check for duplicates */
  3752. for (; i < attIndex; i += 2) {
  3753. const XML_Char *s = appAtts[i];
  3754. if (s[-1] == 2) { /* prefixed */
  3755. ATTRIBUTE_ID *id;
  3756. const BINDING *b;
  3757. unsigned long uriHash;
  3758. struct siphash sip_state;
  3759. struct sipkey sip_key;
  3760. copy_salt_to_sipkey(parser, &sip_key);
  3761. sip24_init(&sip_state, &sip_key);
  3762. ((XML_Char *)s)[-1] = 0; /* clear flag */
  3763. id = (ATTRIBUTE_ID *)lookup(parser, &dtd->attributeIds, s, 0);
  3764. if (! id || ! id->prefix) {
  3765. /* This code is walking through the appAtts array, dealing
  3766. * with (in this case) a prefixed attribute name. To be in
  3767. * the array, the attribute must have already been bound, so
  3768. * has to have passed through the hash table lookup once
  3769. * already. That implies that an entry for it already
  3770. * exists, so the lookup above will return a pointer to
  3771. * already allocated memory. There is no opportunaity for
  3772. * the allocator to fail, so the condition above cannot be
  3773. * fulfilled.
  3774. *
  3775. * Since it is difficult to be certain that the above
  3776. * analysis is complete, we retain the test and merely
  3777. * remove the code from coverage tests.
  3778. */
  3779. return XML_ERROR_NO_MEMORY; /* LCOV_EXCL_LINE */
  3780. }
  3781. b = id->prefix->binding;
  3782. if (! b)
  3783. return XML_ERROR_UNBOUND_PREFIX;
  3784. for (j = 0; j < (unsigned int)b->uriLen; j++) {
  3785. const XML_Char c = b->uri[j];
  3786. if (! poolAppendChar(&parser->m_tempPool, c))
  3787. return XML_ERROR_NO_MEMORY;
  3788. }
  3789. sip24_update(&sip_state, b->uri, b->uriLen * sizeof(XML_Char));
  3790. while (*s++ != XML_T(ASCII_COLON))
  3791. ;
  3792. sip24_update(&sip_state, s, keylen(s) * sizeof(XML_Char));
  3793. do { /* copies null terminator */
  3794. if (! poolAppendChar(&parser->m_tempPool, *s))
  3795. return XML_ERROR_NO_MEMORY;
  3796. } while (*s++);
  3797. uriHash = (unsigned long)sip24_final(&sip_state);
  3798. { /* Check hash table for duplicate of expanded name (uriName).
  3799. Derived from code in lookup(parser, HASH_TABLE *table, ...).
  3800. */
  3801. unsigned char step = 0;
  3802. unsigned long mask = nsAttsSize - 1;
  3803. j = uriHash & mask; /* index into hash table */
  3804. while (parser->m_nsAtts[j].version == version) {
  3805. /* for speed we compare stored hash values first */
  3806. if (uriHash == parser->m_nsAtts[j].hash) {
  3807. const XML_Char *s1 = poolStart(&parser->m_tempPool);
  3808. const XML_Char *s2 = parser->m_nsAtts[j].uriName;
  3809. /* s1 is null terminated, but not s2 */
  3810. for (; *s1 == *s2 && *s1 != 0; s1++, s2++)
  3811. ;
  3812. if (*s1 == 0)
  3813. return XML_ERROR_DUPLICATE_ATTRIBUTE;
  3814. }
  3815. if (! step)
  3816. step = PROBE_STEP(uriHash, mask, parser->m_nsAttsPower);
  3817. j < step ? (j += nsAttsSize - step) : (j -= step);
  3818. }
  3819. }
  3820. if (parser->m_ns_triplets) { /* append namespace separator and prefix */
  3821. parser->m_tempPool.ptr[-1] = parser->m_namespaceSeparator;
  3822. s = b->prefix->name;
  3823. do {
  3824. if (! poolAppendChar(&parser->m_tempPool, *s))
  3825. return XML_ERROR_NO_MEMORY;
  3826. } while (*s++);
  3827. }
  3828. /* store expanded name in attribute list */
  3829. s = poolStart(&parser->m_tempPool);
  3830. poolFinish(&parser->m_tempPool);
  3831. appAtts[i] = s;
  3832. /* fill empty slot with new version, uriName and hash value */
  3833. parser->m_nsAtts[j].version = version;
  3834. parser->m_nsAtts[j].hash = uriHash;
  3835. parser->m_nsAtts[j].uriName = s;
  3836. if (! --nPrefixes) {
  3837. i += 2;
  3838. break;
  3839. }
  3840. } else /* not prefixed */
  3841. ((XML_Char *)s)[-1] = 0; /* clear flag */
  3842. }
  3843. }
  3844. /* clear flags for the remaining attributes */
  3845. for (; i < attIndex; i += 2)
  3846. ((XML_Char *)(appAtts[i]))[-1] = 0;
  3847. for (binding = *bindingsPtr; binding; binding = binding->nextTagBinding)
  3848. binding->attId->name[-1] = 0;
  3849. if (! parser->m_ns)
  3850. return XML_ERROR_NONE;
  3851. /* expand the element type name */
  3852. if (elementType->prefix) {
  3853. binding = elementType->prefix->binding;
  3854. if (! binding)
  3855. return XML_ERROR_UNBOUND_PREFIX;
  3856. localPart = tagNamePtr->str;
  3857. while (*localPart++ != XML_T(ASCII_COLON))
  3858. ;
  3859. } else if (dtd->defaultPrefix.binding) {
  3860. binding = dtd->defaultPrefix.binding;
  3861. localPart = tagNamePtr->str;
  3862. } else
  3863. return XML_ERROR_NONE;
  3864. prefixLen = 0;
  3865. if (parser->m_ns_triplets && binding->prefix->name) {
  3866. while (binding->prefix->name[prefixLen++])
  3867. ; /* prefixLen includes null terminator */
  3868. }
  3869. tagNamePtr->localPart = localPart;
  3870. tagNamePtr->uriLen = binding->uriLen;
  3871. tagNamePtr->prefix = binding->prefix->name;
  3872. tagNamePtr->prefixLen = prefixLen;
  3873. for (i = 0; localPart[i++];)
  3874. ; /* i includes null terminator */
  3875. /* Detect and prevent integer overflow */
  3876. if (binding->uriLen > INT_MAX - prefixLen
  3877. || i > INT_MAX - (binding->uriLen + prefixLen)) {
  3878. return XML_ERROR_NO_MEMORY;
  3879. }
  3880. n = i + binding->uriLen + prefixLen;
  3881. if (n > binding->uriAlloc) {
  3882. TAG *p;
  3883. /* Detect and prevent integer overflow */
  3884. if (n > INT_MAX - EXPAND_SPARE) {
  3885. return XML_ERROR_NO_MEMORY;
  3886. }
  3887. /* Detect and prevent integer overflow.
  3888. * The preprocessor guard addresses the "always false" warning
  3889. * from -Wtype-limits on platforms where
  3890. * sizeof(unsigned int) < sizeof(size_t), e.g. on x86_64. */
  3891. #if UINT_MAX >= SIZE_MAX
  3892. if ((unsigned)(n + EXPAND_SPARE) > SIZE_MAX / sizeof(XML_Char)) {
  3893. return XML_ERROR_NO_MEMORY;
  3894. }
  3895. #endif
  3896. uri = MALLOC(parser, (n + EXPAND_SPARE) * sizeof(XML_Char));
  3897. if (! uri)
  3898. return XML_ERROR_NO_MEMORY;
  3899. binding->uriAlloc = n + EXPAND_SPARE;
  3900. memcpy(uri, binding->uri, binding->uriLen * sizeof(XML_Char));
  3901. for (p = parser->m_tagStack; p; p = p->parent)
  3902. if (p->name.str == binding->uri)
  3903. p->name.str = uri;
  3904. FREE(parser, binding->uri);
  3905. binding->uri = uri;
  3906. }
  3907. /* if m_namespaceSeparator != '\0' then uri includes it already */
  3908. uri = binding->uri + binding->uriLen;
  3909. memcpy(uri, localPart, i * sizeof(XML_Char));
  3910. /* we always have a namespace separator between localPart and prefix */
  3911. if (prefixLen) {
  3912. uri += i - 1;
  3913. *uri = parser->m_namespaceSeparator; /* replace null terminator */
  3914. memcpy(uri + 1, binding->prefix->name, prefixLen * sizeof(XML_Char));
  3915. }
  3916. tagNamePtr->str = binding->uri;
  3917. return XML_ERROR_NONE;
  3918. }
  3919. static XML_Bool
  3920. is_rfc3986_uri_char(XML_Char candidate) {
  3921. // For the RFC 3986 ANBF grammar see
  3922. // https://datatracker.ietf.org/doc/html/rfc3986#appendix-A
  3923. switch (candidate) {
  3924. // From rule "ALPHA" (uppercase half)
  3925. case 'A':
  3926. case 'B':
  3927. case 'C':
  3928. case 'D':
  3929. case 'E':
  3930. case 'F':
  3931. case 'G':
  3932. case 'H':
  3933. case 'I':
  3934. case 'J':
  3935. case 'K':
  3936. case 'L':
  3937. case 'M':
  3938. case 'N':
  3939. case 'O':
  3940. case 'P':
  3941. case 'Q':
  3942. case 'R':
  3943. case 'S':
  3944. case 'T':
  3945. case 'U':
  3946. case 'V':
  3947. case 'W':
  3948. case 'X':
  3949. case 'Y':
  3950. case 'Z':
  3951. // From rule "ALPHA" (lowercase half)
  3952. case 'a':
  3953. case 'b':
  3954. case 'c':
  3955. case 'd':
  3956. case 'e':
  3957. case 'f':
  3958. case 'g':
  3959. case 'h':
  3960. case 'i':
  3961. case 'j':
  3962. case 'k':
  3963. case 'l':
  3964. case 'm':
  3965. case 'n':
  3966. case 'o':
  3967. case 'p':
  3968. case 'q':
  3969. case 'r':
  3970. case 's':
  3971. case 't':
  3972. case 'u':
  3973. case 'v':
  3974. case 'w':
  3975. case 'x':
  3976. case 'y':
  3977. case 'z':
  3978. // From rule "DIGIT"
  3979. case '0':
  3980. case '1':
  3981. case '2':
  3982. case '3':
  3983. case '4':
  3984. case '5':
  3985. case '6':
  3986. case '7':
  3987. case '8':
  3988. case '9':
  3989. // From rule "pct-encoded"
  3990. case '%':
  3991. // From rule "unreserved"
  3992. case '-':
  3993. case '.':
  3994. case '_':
  3995. case '~':
  3996. // From rule "gen-delims"
  3997. case ':':
  3998. case '/':
  3999. case '?':
  4000. case '#':
  4001. case '[':
  4002. case ']':
  4003. case '@':
  4004. // From rule "sub-delims"
  4005. case '!':
  4006. case '$':
  4007. case '&':
  4008. case '\'':
  4009. case '(':
  4010. case ')':
  4011. case '*':
  4012. case '+':
  4013. case ',':
  4014. case ';':
  4015. case '=':
  4016. return XML_TRUE;
  4017. default:
  4018. return XML_FALSE;
  4019. }
  4020. }
  4021. /* addBinding() overwrites the value of prefix->binding without checking.
  4022. Therefore one must keep track of the old value outside of addBinding().
  4023. */
  4024. static enum XML_Error
  4025. addBinding(XML_Parser parser, PREFIX *prefix, const ATTRIBUTE_ID *attId,
  4026. const XML_Char *uri, BINDING **bindingsPtr) {
  4027. // "http://www.w3.org/XML/1998/namespace"
  4028. static const XML_Char xmlNamespace[]
  4029. = {ASCII_h, ASCII_t, ASCII_t, ASCII_p, ASCII_COLON,
  4030. ASCII_SLASH, ASCII_SLASH, ASCII_w, ASCII_w, ASCII_w,
  4031. ASCII_PERIOD, ASCII_w, ASCII_3, ASCII_PERIOD, ASCII_o,
  4032. ASCII_r, ASCII_g, ASCII_SLASH, ASCII_X, ASCII_M,
  4033. ASCII_L, ASCII_SLASH, ASCII_1, ASCII_9, ASCII_9,
  4034. ASCII_8, ASCII_SLASH, ASCII_n, ASCII_a, ASCII_m,
  4035. ASCII_e, ASCII_s, ASCII_p, ASCII_a, ASCII_c,
  4036. ASCII_e, '\0'};
  4037. static const int xmlLen = (int)sizeof(xmlNamespace) / sizeof(XML_Char) - 1;
  4038. // "http://www.w3.org/2000/xmlns/"
  4039. static const XML_Char xmlnsNamespace[]
  4040. = {ASCII_h, ASCII_t, ASCII_t, ASCII_p, ASCII_COLON, ASCII_SLASH,
  4041. ASCII_SLASH, ASCII_w, ASCII_w, ASCII_w, ASCII_PERIOD, ASCII_w,
  4042. ASCII_3, ASCII_PERIOD, ASCII_o, ASCII_r, ASCII_g, ASCII_SLASH,
  4043. ASCII_2, ASCII_0, ASCII_0, ASCII_0, ASCII_SLASH, ASCII_x,
  4044. ASCII_m, ASCII_l, ASCII_n, ASCII_s, ASCII_SLASH, '\0'};
  4045. static const int xmlnsLen
  4046. = (int)sizeof(xmlnsNamespace) / sizeof(XML_Char) - 1;
  4047. XML_Bool mustBeXML = XML_FALSE;
  4048. XML_Bool isXML = XML_TRUE;
  4049. XML_Bool isXMLNS = XML_TRUE;
  4050. BINDING *b;
  4051. int len;
  4052. /* empty URI is only valid for default namespace per XML NS 1.0 (not 1.1) */
  4053. if (*uri == XML_T('\0') && prefix->name)
  4054. return XML_ERROR_UNDECLARING_PREFIX;
  4055. if (prefix->name && prefix->name[0] == XML_T(ASCII_x)
  4056. && prefix->name[1] == XML_T(ASCII_m)
  4057. && prefix->name[2] == XML_T(ASCII_l)) {
  4058. /* Not allowed to bind xmlns */
  4059. if (prefix->name[3] == XML_T(ASCII_n) && prefix->name[4] == XML_T(ASCII_s)
  4060. && prefix->name[5] == XML_T('\0'))
  4061. return XML_ERROR_RESERVED_PREFIX_XMLNS;
  4062. if (prefix->name[3] == XML_T('\0'))
  4063. mustBeXML = XML_TRUE;
  4064. }
  4065. for (len = 0; uri[len]; len++) {
  4066. if (isXML && (len > xmlLen || uri[len] != xmlNamespace[len]))
  4067. isXML = XML_FALSE;
  4068. if (! mustBeXML && isXMLNS
  4069. && (len > xmlnsLen || uri[len] != xmlnsNamespace[len]))
  4070. isXMLNS = XML_FALSE;
  4071. // NOTE: While Expat does not validate namespace URIs against RFC 3986
  4072. // today (and is not REQUIRED to do so with regard to the XML 1.0
  4073. // namespaces specification) we have to at least make sure, that
  4074. // the application on top of Expat (that is likely splitting expanded
  4075. // element names ("qualified names") of form
  4076. // "[uri sep] local [sep prefix] '\0'" back into 1, 2 or 3 pieces
  4077. // in its element handler code) cannot be confused by an attacker
  4078. // putting additional namespace separator characters into namespace
  4079. // declarations. That would be ambiguous and not to be expected.
  4080. //
  4081. // While the HTML API docs of function XML_ParserCreateNS have been
  4082. // advising against use of a namespace separator character that can
  4083. // appear in a URI for >20 years now, some widespread applications
  4084. // are using URI characters (':' (colon) in particular) for a
  4085. // namespace separator, in practice. To keep these applications
  4086. // functional, we only reject namespaces URIs containing the
  4087. // application-chosen namespace separator if the chosen separator
  4088. // is a non-URI character with regard to RFC 3986.
  4089. if (parser->m_ns && (uri[len] == parser->m_namespaceSeparator)
  4090. && ! is_rfc3986_uri_char(uri[len])) {
  4091. return XML_ERROR_SYNTAX;
  4092. }
  4093. }
  4094. isXML = isXML && len == xmlLen;
  4095. isXMLNS = isXMLNS && len == xmlnsLen;
  4096. if (mustBeXML != isXML)
  4097. return mustBeXML ? XML_ERROR_RESERVED_PREFIX_XML
  4098. : XML_ERROR_RESERVED_NAMESPACE_URI;
  4099. if (isXMLNS)
  4100. return XML_ERROR_RESERVED_NAMESPACE_URI;
  4101. if (parser->m_namespaceSeparator)
  4102. len++;
  4103. if (parser->m_freeBindingList) {
  4104. b = parser->m_freeBindingList;
  4105. if (len > b->uriAlloc) {
  4106. /* Detect and prevent integer overflow */
  4107. if (len > INT_MAX - EXPAND_SPARE) {
  4108. return XML_ERROR_NO_MEMORY;
  4109. }
  4110. /* Detect and prevent integer overflow.
  4111. * The preprocessor guard addresses the "always false" warning
  4112. * from -Wtype-limits on platforms where
  4113. * sizeof(unsigned int) < sizeof(size_t), e.g. on x86_64. */
  4114. #if UINT_MAX >= SIZE_MAX
  4115. if ((unsigned)(len + EXPAND_SPARE) > SIZE_MAX / sizeof(XML_Char)) {
  4116. return XML_ERROR_NO_MEMORY;
  4117. }
  4118. #endif
  4119. XML_Char *temp
  4120. = REALLOC(parser, b->uri, sizeof(XML_Char) * (len + EXPAND_SPARE));
  4121. if (temp == NULL)
  4122. return XML_ERROR_NO_MEMORY;
  4123. b->uri = temp;
  4124. b->uriAlloc = len + EXPAND_SPARE;
  4125. }
  4126. parser->m_freeBindingList = b->nextTagBinding;
  4127. } else {
  4128. b = MALLOC(parser, sizeof(BINDING));
  4129. if (! b)
  4130. return XML_ERROR_NO_MEMORY;
  4131. /* Detect and prevent integer overflow */
  4132. if (len > INT_MAX - EXPAND_SPARE) {
  4133. return XML_ERROR_NO_MEMORY;
  4134. }
  4135. /* Detect and prevent integer overflow.
  4136. * The preprocessor guard addresses the "always false" warning
  4137. * from -Wtype-limits on platforms where
  4138. * sizeof(unsigned int) < sizeof(size_t), e.g. on x86_64. */
  4139. #if UINT_MAX >= SIZE_MAX
  4140. if ((unsigned)(len + EXPAND_SPARE) > SIZE_MAX / sizeof(XML_Char)) {
  4141. return XML_ERROR_NO_MEMORY;
  4142. }
  4143. #endif
  4144. b->uri = MALLOC(parser, sizeof(XML_Char) * (len + EXPAND_SPARE));
  4145. if (! b->uri) {
  4146. FREE(parser, b);
  4147. return XML_ERROR_NO_MEMORY;
  4148. }
  4149. b->uriAlloc = len + EXPAND_SPARE;
  4150. }
  4151. b->uriLen = len;
  4152. memcpy(b->uri, uri, len * sizeof(XML_Char));
  4153. if (parser->m_namespaceSeparator)
  4154. b->uri[len - 1] = parser->m_namespaceSeparator;
  4155. b->prefix = prefix;
  4156. b->attId = attId;
  4157. b->prevPrefixBinding = prefix->binding;
  4158. /* NULL binding when default namespace undeclared */
  4159. if (*uri == XML_T('\0') && prefix == &parser->m_dtd->defaultPrefix)
  4160. prefix->binding = NULL;
  4161. else
  4162. prefix->binding = b;
  4163. b->nextTagBinding = *bindingsPtr;
  4164. *bindingsPtr = b;
  4165. /* if attId == NULL then we are not starting a namespace scope */
  4166. if (attId && parser->m_startNamespaceDeclHandler)
  4167. parser->m_startNamespaceDeclHandler(parser->m_handlerArg, prefix->name,
  4168. prefix->binding ? uri : 0);
  4169. return XML_ERROR_NONE;
  4170. }
  4171. /* The idea here is to avoid using stack for each CDATA section when
  4172. the whole file is parsed with one call.
  4173. */
  4174. static enum XML_Error PTRCALL
  4175. cdataSectionProcessor(XML_Parser parser, const char *start, const char *end,
  4176. const char **endPtr) {
  4177. enum XML_Error result = doCdataSection(
  4178. parser, parser->m_encoding, &start, end, endPtr,
  4179. (XML_Bool)! parser->m_parsingStatus.finalBuffer, XML_ACCOUNT_DIRECT);
  4180. if (result != XML_ERROR_NONE)
  4181. return result;
  4182. if (start) {
  4183. if (parser->m_parentParser) { /* we are parsing an external entity */
  4184. parser->m_processor = externalEntityContentProcessor;
  4185. return externalEntityContentProcessor(parser, start, end, endPtr);
  4186. } else {
  4187. parser->m_processor = contentProcessor;
  4188. return contentProcessor(parser, start, end, endPtr);
  4189. }
  4190. }
  4191. return result;
  4192. }
  4193. /* startPtr gets set to non-null if the section is closed, and to null if
  4194. the section is not yet closed.
  4195. */
  4196. static enum XML_Error
  4197. doCdataSection(XML_Parser parser, const ENCODING *enc, const char **startPtr,
  4198. const char *end, const char **nextPtr, XML_Bool haveMore,
  4199. enum XML_Account account) {
  4200. const char *s = *startPtr;
  4201. const char **eventPP;
  4202. const char **eventEndPP;
  4203. if (enc == parser->m_encoding) {
  4204. eventPP = &parser->m_eventPtr;
  4205. *eventPP = s;
  4206. eventEndPP = &parser->m_eventEndPtr;
  4207. } else {
  4208. eventPP = &(parser->m_openInternalEntities->internalEventPtr);
  4209. eventEndPP = &(parser->m_openInternalEntities->internalEventEndPtr);
  4210. }
  4211. *eventPP = s;
  4212. *startPtr = NULL;
  4213. for (;;) {
  4214. const char *next = s; /* in case of XML_TOK_NONE or XML_TOK_PARTIAL */
  4215. int tok = XmlCdataSectionTok(enc, s, end, &next);
  4216. #if XML_GE == 1
  4217. if (! accountingDiffTolerated(parser, tok, s, next, __LINE__, account)) {
  4218. accountingOnAbort(parser);
  4219. return XML_ERROR_AMPLIFICATION_LIMIT_BREACH;
  4220. }
  4221. #else
  4222. UNUSED_P(account);
  4223. #endif
  4224. *eventEndPP = next;
  4225. switch (tok) {
  4226. case XML_TOK_CDATA_SECT_CLOSE:
  4227. if (parser->m_endCdataSectionHandler)
  4228. parser->m_endCdataSectionHandler(parser->m_handlerArg);
  4229. /* BEGIN disabled code */
  4230. /* see comment under XML_TOK_CDATA_SECT_OPEN */
  4231. else if ((0) && parser->m_characterDataHandler)
  4232. parser->m_characterDataHandler(parser->m_handlerArg, parser->m_dataBuf,
  4233. 0);
  4234. /* END disabled code */
  4235. else if (parser->m_defaultHandler)
  4236. reportDefault(parser, enc, s, next);
  4237. *startPtr = next;
  4238. *nextPtr = next;
  4239. if (parser->m_parsingStatus.parsing == XML_FINISHED)
  4240. return XML_ERROR_ABORTED;
  4241. else
  4242. return XML_ERROR_NONE;
  4243. case XML_TOK_DATA_NEWLINE:
  4244. if (parser->m_characterDataHandler) {
  4245. XML_Char c = 0xA;
  4246. parser->m_characterDataHandler(parser->m_handlerArg, &c, 1);
  4247. } else if (parser->m_defaultHandler)
  4248. reportDefault(parser, enc, s, next);
  4249. break;
  4250. case XML_TOK_DATA_CHARS: {
  4251. XML_CharacterDataHandler charDataHandler = parser->m_characterDataHandler;
  4252. if (charDataHandler) {
  4253. if (MUST_CONVERT(enc, s)) {
  4254. for (;;) {
  4255. ICHAR *dataPtr = (ICHAR *)parser->m_dataBuf;
  4256. const enum XML_Convert_Result convert_res = XmlConvert(
  4257. enc, &s, next, &dataPtr, (ICHAR *)parser->m_dataBufEnd);
  4258. *eventEndPP = next;
  4259. charDataHandler(parser->m_handlerArg, parser->m_dataBuf,
  4260. (int)(dataPtr - (ICHAR *)parser->m_dataBuf));
  4261. if ((convert_res == XML_CONVERT_COMPLETED)
  4262. || (convert_res == XML_CONVERT_INPUT_INCOMPLETE))
  4263. break;
  4264. *eventPP = s;
  4265. }
  4266. } else
  4267. charDataHandler(parser->m_handlerArg, (const XML_Char *)s,
  4268. (int)((const XML_Char *)next - (const XML_Char *)s));
  4269. } else if (parser->m_defaultHandler)
  4270. reportDefault(parser, enc, s, next);
  4271. } break;
  4272. case XML_TOK_INVALID:
  4273. *eventPP = next;
  4274. return XML_ERROR_INVALID_TOKEN;
  4275. case XML_TOK_PARTIAL_CHAR:
  4276. if (haveMore) {
  4277. *nextPtr = s;
  4278. return XML_ERROR_NONE;
  4279. }
  4280. return XML_ERROR_PARTIAL_CHAR;
  4281. case XML_TOK_PARTIAL:
  4282. case XML_TOK_NONE:
  4283. if (haveMore) {
  4284. *nextPtr = s;
  4285. return XML_ERROR_NONE;
  4286. }
  4287. return XML_ERROR_UNCLOSED_CDATA_SECTION;
  4288. default:
  4289. /* Every token returned by XmlCdataSectionTok() has its own
  4290. * explicit case, so this default case will never be executed.
  4291. * We retain it as a safety net and exclude it from the coverage
  4292. * statistics.
  4293. *
  4294. * LCOV_EXCL_START
  4295. */
  4296. *eventPP = next;
  4297. return XML_ERROR_UNEXPECTED_STATE;
  4298. /* LCOV_EXCL_STOP */
  4299. }
  4300. switch (parser->m_parsingStatus.parsing) {
  4301. case XML_SUSPENDED:
  4302. *eventPP = next;
  4303. *nextPtr = next;
  4304. return XML_ERROR_NONE;
  4305. case XML_FINISHED:
  4306. *eventPP = next;
  4307. return XML_ERROR_ABORTED;
  4308. case XML_PARSING:
  4309. if (parser->m_reenter) {
  4310. return XML_ERROR_UNEXPECTED_STATE; // LCOV_EXCL_LINE
  4311. }
  4312. /* Fall through */
  4313. default:;
  4314. *eventPP = s = next;
  4315. }
  4316. }
  4317. /* not reached */
  4318. }
  4319. #ifdef XML_DTD
  4320. /* The idea here is to avoid using stack for each IGNORE section when
  4321. the whole file is parsed with one call.
  4322. */
  4323. static enum XML_Error PTRCALL
  4324. ignoreSectionProcessor(XML_Parser parser, const char *start, const char *end,
  4325. const char **endPtr) {
  4326. enum XML_Error result
  4327. = doIgnoreSection(parser, parser->m_encoding, &start, end, endPtr,
  4328. (XML_Bool)! parser->m_parsingStatus.finalBuffer);
  4329. if (result != XML_ERROR_NONE)
  4330. return result;
  4331. if (start) {
  4332. parser->m_processor = prologProcessor;
  4333. return prologProcessor(parser, start, end, endPtr);
  4334. }
  4335. return result;
  4336. }
  4337. /* startPtr gets set to non-null is the section is closed, and to null
  4338. if the section is not yet closed.
  4339. */
  4340. static enum XML_Error
  4341. doIgnoreSection(XML_Parser parser, const ENCODING *enc, const char **startPtr,
  4342. const char *end, const char **nextPtr, XML_Bool haveMore) {
  4343. const char *next = *startPtr; /* in case of XML_TOK_NONE or XML_TOK_PARTIAL */
  4344. int tok;
  4345. const char *s = *startPtr;
  4346. const char **eventPP;
  4347. const char **eventEndPP;
  4348. if (enc == parser->m_encoding) {
  4349. eventPP = &parser->m_eventPtr;
  4350. *eventPP = s;
  4351. eventEndPP = &parser->m_eventEndPtr;
  4352. } else {
  4353. /* It's not entirely clear, but it seems the following two lines
  4354. * of code cannot be executed. The only occasions on which 'enc'
  4355. * is not 'encoding' are when this function is called
  4356. * from the internal entity processing, and IGNORE sections are an
  4357. * error in internal entities.
  4358. *
  4359. * Since it really isn't clear that this is true, we keep the code
  4360. * and just remove it from our coverage tests.
  4361. *
  4362. * LCOV_EXCL_START
  4363. */
  4364. eventPP = &(parser->m_openInternalEntities->internalEventPtr);
  4365. eventEndPP = &(parser->m_openInternalEntities->internalEventEndPtr);
  4366. /* LCOV_EXCL_STOP */
  4367. }
  4368. *eventPP = s;
  4369. *startPtr = NULL;
  4370. tok = XmlIgnoreSectionTok(enc, s, end, &next);
  4371. # if XML_GE == 1
  4372. if (! accountingDiffTolerated(parser, tok, s, next, __LINE__,
  4373. XML_ACCOUNT_DIRECT)) {
  4374. accountingOnAbort(parser);
  4375. return XML_ERROR_AMPLIFICATION_LIMIT_BREACH;
  4376. }
  4377. # endif
  4378. *eventEndPP = next;
  4379. switch (tok) {
  4380. case XML_TOK_IGNORE_SECT:
  4381. if (parser->m_defaultHandler)
  4382. reportDefault(parser, enc, s, next);
  4383. *startPtr = next;
  4384. *nextPtr = next;
  4385. if (parser->m_parsingStatus.parsing == XML_FINISHED)
  4386. return XML_ERROR_ABORTED;
  4387. else
  4388. return XML_ERROR_NONE;
  4389. case XML_TOK_INVALID:
  4390. *eventPP = next;
  4391. return XML_ERROR_INVALID_TOKEN;
  4392. case XML_TOK_PARTIAL_CHAR:
  4393. if (haveMore) {
  4394. *nextPtr = s;
  4395. return XML_ERROR_NONE;
  4396. }
  4397. return XML_ERROR_PARTIAL_CHAR;
  4398. case XML_TOK_PARTIAL:
  4399. case XML_TOK_NONE:
  4400. if (haveMore) {
  4401. *nextPtr = s;
  4402. return XML_ERROR_NONE;
  4403. }
  4404. return XML_ERROR_SYNTAX; /* XML_ERROR_UNCLOSED_IGNORE_SECTION */
  4405. default:
  4406. /* All of the tokens that XmlIgnoreSectionTok() returns have
  4407. * explicit cases to handle them, so this default case is never
  4408. * executed. We keep it as a safety net anyway, and remove it
  4409. * from our test coverage statistics.
  4410. *
  4411. * LCOV_EXCL_START
  4412. */
  4413. *eventPP = next;
  4414. return XML_ERROR_UNEXPECTED_STATE;
  4415. /* LCOV_EXCL_STOP */
  4416. }
  4417. /* not reached */
  4418. }
  4419. #endif /* XML_DTD */
  4420. static enum XML_Error
  4421. initializeEncoding(XML_Parser parser) {
  4422. const char *s;
  4423. #ifdef XML_UNICODE
  4424. char encodingBuf[128];
  4425. /* See comments about `protocolEncodingName` in parserInit() */
  4426. if (! parser->m_protocolEncodingName)
  4427. s = NULL;
  4428. else {
  4429. int i;
  4430. for (i = 0; parser->m_protocolEncodingName[i]; i++) {
  4431. if (i == sizeof(encodingBuf) - 1
  4432. || (parser->m_protocolEncodingName[i] & ~0x7f) != 0) {
  4433. encodingBuf[0] = '\0';
  4434. break;
  4435. }
  4436. encodingBuf[i] = (char)parser->m_protocolEncodingName[i];
  4437. }
  4438. encodingBuf[i] = '\0';
  4439. s = encodingBuf;
  4440. }
  4441. #else
  4442. s = parser->m_protocolEncodingName;
  4443. #endif
  4444. if ((parser->m_ns ? XmlInitEncodingNS : XmlInitEncoding)(
  4445. &parser->m_initEncoding, &parser->m_encoding, s))
  4446. return XML_ERROR_NONE;
  4447. return handleUnknownEncoding(parser, parser->m_protocolEncodingName);
  4448. }
  4449. static enum XML_Error
  4450. processXmlDecl(XML_Parser parser, int isGeneralTextEntity, const char *s,
  4451. const char *next) {
  4452. const char *encodingName = NULL;
  4453. const XML_Char *storedEncName = NULL;
  4454. const ENCODING *newEncoding = NULL;
  4455. const char *version = NULL;
  4456. const char *versionend = NULL;
  4457. const XML_Char *storedversion = NULL;
  4458. int standalone = -1;
  4459. #if XML_GE == 1
  4460. if (! accountingDiffTolerated(parser, XML_TOK_XML_DECL, s, next, __LINE__,
  4461. XML_ACCOUNT_DIRECT)) {
  4462. accountingOnAbort(parser);
  4463. return XML_ERROR_AMPLIFICATION_LIMIT_BREACH;
  4464. }
  4465. #endif
  4466. if (! (parser->m_ns ? XmlParseXmlDeclNS : XmlParseXmlDecl)(
  4467. isGeneralTextEntity, parser->m_encoding, s, next, &parser->m_eventPtr,
  4468. &version, &versionend, &encodingName, &newEncoding, &standalone)) {
  4469. if (isGeneralTextEntity)
  4470. return XML_ERROR_TEXT_DECL;
  4471. else
  4472. return XML_ERROR_XML_DECL;
  4473. }
  4474. if (! isGeneralTextEntity && standalone == 1) {
  4475. parser->m_dtd->standalone = XML_TRUE;
  4476. #ifdef XML_DTD
  4477. if (parser->m_paramEntityParsing
  4478. == XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE)
  4479. parser->m_paramEntityParsing = XML_PARAM_ENTITY_PARSING_NEVER;
  4480. #endif /* XML_DTD */
  4481. }
  4482. if (parser->m_xmlDeclHandler) {
  4483. if (encodingName != NULL) {
  4484. storedEncName = poolStoreString(
  4485. &parser->m_temp2Pool, parser->m_encoding, encodingName,
  4486. encodingName + XmlNameLength(parser->m_encoding, encodingName));
  4487. if (! storedEncName)
  4488. return XML_ERROR_NO_MEMORY;
  4489. poolFinish(&parser->m_temp2Pool);
  4490. }
  4491. if (version) {
  4492. storedversion
  4493. = poolStoreString(&parser->m_temp2Pool, parser->m_encoding, version,
  4494. versionend - parser->m_encoding->minBytesPerChar);
  4495. if (! storedversion)
  4496. return XML_ERROR_NO_MEMORY;
  4497. }
  4498. parser->m_xmlDeclHandler(parser->m_handlerArg, storedversion, storedEncName,
  4499. standalone);
  4500. } else if (parser->m_defaultHandler)
  4501. reportDefault(parser, parser->m_encoding, s, next);
  4502. if (parser->m_protocolEncodingName == NULL) {
  4503. if (newEncoding) {
  4504. /* Check that the specified encoding does not conflict with what
  4505. * the parser has already deduced. Do we have the same number
  4506. * of bytes in the smallest representation of a character? If
  4507. * this is UTF-16, is it the same endianness?
  4508. */
  4509. if (newEncoding->minBytesPerChar != parser->m_encoding->minBytesPerChar
  4510. || (newEncoding->minBytesPerChar == 2
  4511. && newEncoding != parser->m_encoding)) {
  4512. parser->m_eventPtr = encodingName;
  4513. return XML_ERROR_INCORRECT_ENCODING;
  4514. }
  4515. parser->m_encoding = newEncoding;
  4516. } else if (encodingName) {
  4517. enum XML_Error result;
  4518. if (! storedEncName) {
  4519. storedEncName = poolStoreString(
  4520. &parser->m_temp2Pool, parser->m_encoding, encodingName,
  4521. encodingName + XmlNameLength(parser->m_encoding, encodingName));
  4522. if (! storedEncName)
  4523. return XML_ERROR_NO_MEMORY;
  4524. }
  4525. result = handleUnknownEncoding(parser, storedEncName);
  4526. poolClear(&parser->m_temp2Pool);
  4527. if (result == XML_ERROR_UNKNOWN_ENCODING)
  4528. parser->m_eventPtr = encodingName;
  4529. return result;
  4530. }
  4531. }
  4532. if (storedEncName || storedversion)
  4533. poolClear(&parser->m_temp2Pool);
  4534. return XML_ERROR_NONE;
  4535. }
  4536. static enum XML_Error
  4537. handleUnknownEncoding(XML_Parser parser, const XML_Char *encodingName) {
  4538. if (parser->m_unknownEncodingHandler) {
  4539. XML_Encoding info;
  4540. int i;
  4541. for (i = 0; i < 256; i++)
  4542. info.map[i] = -1;
  4543. info.convert = NULL;
  4544. info.data = NULL;
  4545. info.release = NULL;
  4546. if (parser->m_unknownEncodingHandler(parser->m_unknownEncodingHandlerData,
  4547. encodingName, &info)) {
  4548. ENCODING *enc;
  4549. parser->m_unknownEncodingMem = MALLOC(parser, XmlSizeOfUnknownEncoding());
  4550. if (! parser->m_unknownEncodingMem) {
  4551. if (info.release)
  4552. info.release(info.data);
  4553. return XML_ERROR_NO_MEMORY;
  4554. }
  4555. enc = (parser->m_ns ? XmlInitUnknownEncodingNS : XmlInitUnknownEncoding)(
  4556. parser->m_unknownEncodingMem, info.map, info.convert, info.data);
  4557. if (enc) {
  4558. parser->m_unknownEncodingData = info.data;
  4559. parser->m_unknownEncodingRelease = info.release;
  4560. parser->m_encoding = enc;
  4561. return XML_ERROR_NONE;
  4562. }
  4563. }
  4564. if (info.release != NULL)
  4565. info.release(info.data);
  4566. }
  4567. return XML_ERROR_UNKNOWN_ENCODING;
  4568. }
  4569. static enum XML_Error PTRCALL
  4570. prologInitProcessor(XML_Parser parser, const char *s, const char *end,
  4571. const char **nextPtr) {
  4572. enum XML_Error result = initializeEncoding(parser);
  4573. if (result != XML_ERROR_NONE)
  4574. return result;
  4575. parser->m_processor = prologProcessor;
  4576. return prologProcessor(parser, s, end, nextPtr);
  4577. }
  4578. #ifdef XML_DTD
  4579. static enum XML_Error PTRCALL
  4580. externalParEntInitProcessor(XML_Parser parser, const char *s, const char *end,
  4581. const char **nextPtr) {
  4582. enum XML_Error result = initializeEncoding(parser);
  4583. if (result != XML_ERROR_NONE)
  4584. return result;
  4585. /* we know now that XML_Parse(Buffer) has been called,
  4586. so we consider the external parameter entity read */
  4587. parser->m_dtd->paramEntityRead = XML_TRUE;
  4588. if (parser->m_prologState.inEntityValue) {
  4589. parser->m_processor = entityValueInitProcessor;
  4590. return entityValueInitProcessor(parser, s, end, nextPtr);
  4591. } else {
  4592. parser->m_processor = externalParEntProcessor;
  4593. return externalParEntProcessor(parser, s, end, nextPtr);
  4594. }
  4595. }
  4596. static enum XML_Error PTRCALL
  4597. entityValueInitProcessor(XML_Parser parser, const char *s, const char *end,
  4598. const char **nextPtr) {
  4599. int tok;
  4600. const char *start = s;
  4601. const char *next = start;
  4602. parser->m_eventPtr = start;
  4603. for (;;) {
  4604. tok = XmlPrologTok(parser->m_encoding, start, end, &next);
  4605. /* Note: Except for XML_TOK_BOM below, these bytes are accounted later in:
  4606. - storeEntityValue
  4607. - processXmlDecl
  4608. */
  4609. parser->m_eventEndPtr = next;
  4610. if (tok <= 0) {
  4611. if (! parser->m_parsingStatus.finalBuffer && tok != XML_TOK_INVALID) {
  4612. *nextPtr = s;
  4613. return XML_ERROR_NONE;
  4614. }
  4615. switch (tok) {
  4616. case XML_TOK_INVALID:
  4617. return XML_ERROR_INVALID_TOKEN;
  4618. case XML_TOK_PARTIAL:
  4619. return XML_ERROR_UNCLOSED_TOKEN;
  4620. case XML_TOK_PARTIAL_CHAR:
  4621. return XML_ERROR_PARTIAL_CHAR;
  4622. case XML_TOK_NONE: /* start == end */
  4623. default:
  4624. break;
  4625. }
  4626. /* found end of entity value - can store it now */
  4627. return storeEntityValue(parser, parser->m_encoding, s, end,
  4628. XML_ACCOUNT_DIRECT, NULL);
  4629. } else if (tok == XML_TOK_XML_DECL) {
  4630. enum XML_Error result;
  4631. result = processXmlDecl(parser, 0, start, next);
  4632. if (result != XML_ERROR_NONE)
  4633. return result;
  4634. /* At this point, m_parsingStatus.parsing cannot be XML_SUSPENDED. For
  4635. * that to happen, a parameter entity parsing handler must have attempted
  4636. * to suspend the parser, which fails and raises an error. The parser can
  4637. * be aborted, but can't be suspended.
  4638. */
  4639. if (parser->m_parsingStatus.parsing == XML_FINISHED)
  4640. return XML_ERROR_ABORTED;
  4641. *nextPtr = next;
  4642. /* stop scanning for text declaration - we found one */
  4643. parser->m_processor = entityValueProcessor;
  4644. return entityValueProcessor(parser, next, end, nextPtr);
  4645. }
  4646. /* XmlPrologTok has now set the encoding based on the BOM it found, and we
  4647. must move s and nextPtr forward to consume the BOM.
  4648. If we didn't, and got XML_TOK_NONE from the next XmlPrologTok call, we
  4649. would leave the BOM in the buffer and return. On the next call to this
  4650. function, our XmlPrologTok call would return XML_TOK_INVALID, since it
  4651. is not valid to have multiple BOMs.
  4652. */
  4653. else if (tok == XML_TOK_BOM) {
  4654. # if XML_GE == 1
  4655. if (! accountingDiffTolerated(parser, tok, s, next, __LINE__,
  4656. XML_ACCOUNT_DIRECT)) {
  4657. accountingOnAbort(parser);
  4658. return XML_ERROR_AMPLIFICATION_LIMIT_BREACH;
  4659. }
  4660. # endif
  4661. *nextPtr = next;
  4662. s = next;
  4663. }
  4664. /* If we get this token, we have the start of what might be a
  4665. normal tag, but not a declaration (i.e. it doesn't begin with
  4666. "<!" or "<?"). In a DTD context, that isn't legal.
  4667. */
  4668. else if (tok == XML_TOK_INSTANCE_START) {
  4669. *nextPtr = next;
  4670. return XML_ERROR_SYNTAX;
  4671. }
  4672. start = next;
  4673. parser->m_eventPtr = start;
  4674. }
  4675. }
  4676. static enum XML_Error PTRCALL
  4677. externalParEntProcessor(XML_Parser parser, const char *s, const char *end,
  4678. const char **nextPtr) {
  4679. const char *next = s;
  4680. int tok;
  4681. tok = XmlPrologTok(parser->m_encoding, s, end, &next);
  4682. if (tok <= 0) {
  4683. if (! parser->m_parsingStatus.finalBuffer && tok != XML_TOK_INVALID) {
  4684. *nextPtr = s;
  4685. return XML_ERROR_NONE;
  4686. }
  4687. switch (tok) {
  4688. case XML_TOK_INVALID:
  4689. return XML_ERROR_INVALID_TOKEN;
  4690. case XML_TOK_PARTIAL:
  4691. return XML_ERROR_UNCLOSED_TOKEN;
  4692. case XML_TOK_PARTIAL_CHAR:
  4693. return XML_ERROR_PARTIAL_CHAR;
  4694. case XML_TOK_NONE: /* start == end */
  4695. default:
  4696. break;
  4697. }
  4698. }
  4699. /* This would cause the next stage, i.e. doProlog to be passed XML_TOK_BOM.
  4700. However, when parsing an external subset, doProlog will not accept a BOM
  4701. as valid, and report a syntax error, so we have to skip the BOM, and
  4702. account for the BOM bytes.
  4703. */
  4704. else if (tok == XML_TOK_BOM) {
  4705. if (! accountingDiffTolerated(parser, tok, s, next, __LINE__,
  4706. XML_ACCOUNT_DIRECT)) {
  4707. accountingOnAbort(parser);
  4708. return XML_ERROR_AMPLIFICATION_LIMIT_BREACH;
  4709. }
  4710. s = next;
  4711. tok = XmlPrologTok(parser->m_encoding, s, end, &next);
  4712. }
  4713. parser->m_processor = prologProcessor;
  4714. return doProlog(parser, parser->m_encoding, s, end, tok, next, nextPtr,
  4715. (XML_Bool)! parser->m_parsingStatus.finalBuffer, XML_TRUE,
  4716. XML_ACCOUNT_DIRECT);
  4717. }
  4718. static enum XML_Error PTRCALL
  4719. entityValueProcessor(XML_Parser parser, const char *s, const char *end,
  4720. const char **nextPtr) {
  4721. const char *start = s;
  4722. const char *next = s;
  4723. const ENCODING *enc = parser->m_encoding;
  4724. int tok;
  4725. for (;;) {
  4726. tok = XmlPrologTok(enc, start, end, &next);
  4727. /* Note: These bytes are accounted later in:
  4728. - storeEntityValue
  4729. */
  4730. if (tok <= 0) {
  4731. if (! parser->m_parsingStatus.finalBuffer && tok != XML_TOK_INVALID) {
  4732. *nextPtr = s;
  4733. return XML_ERROR_NONE;
  4734. }
  4735. switch (tok) {
  4736. case XML_TOK_INVALID:
  4737. return XML_ERROR_INVALID_TOKEN;
  4738. case XML_TOK_PARTIAL:
  4739. return XML_ERROR_UNCLOSED_TOKEN;
  4740. case XML_TOK_PARTIAL_CHAR:
  4741. return XML_ERROR_PARTIAL_CHAR;
  4742. case XML_TOK_NONE: /* start == end */
  4743. default:
  4744. break;
  4745. }
  4746. /* found end of entity value - can store it now */
  4747. return storeEntityValue(parser, enc, s, end, XML_ACCOUNT_DIRECT, NULL);
  4748. }
  4749. /* If we get this token, we have the start of what might be a
  4750. normal tag, but not a declaration (i.e. it doesn't begin with
  4751. "<!" or "<?"). In a DTD context, that isn't legal.
  4752. */
  4753. else if (tok == XML_TOK_INSTANCE_START) {
  4754. *nextPtr = next;
  4755. return XML_ERROR_SYNTAX;
  4756. }
  4757. start = next;
  4758. }
  4759. }
  4760. #endif /* XML_DTD */
  4761. static enum XML_Error PTRCALL
  4762. prologProcessor(XML_Parser parser, const char *s, const char *end,
  4763. const char **nextPtr) {
  4764. const char *next = s;
  4765. int tok = XmlPrologTok(parser->m_encoding, s, end, &next);
  4766. return doProlog(parser, parser->m_encoding, s, end, tok, next, nextPtr,
  4767. (XML_Bool)! parser->m_parsingStatus.finalBuffer, XML_TRUE,
  4768. XML_ACCOUNT_DIRECT);
  4769. }
  4770. static enum XML_Error
  4771. doProlog(XML_Parser parser, const ENCODING *enc, const char *s, const char *end,
  4772. int tok, const char *next, const char **nextPtr, XML_Bool haveMore,
  4773. XML_Bool allowClosingDoctype, enum XML_Account account) {
  4774. #ifdef XML_DTD
  4775. static const XML_Char externalSubsetName[] = {ASCII_HASH, '\0'};
  4776. #endif /* XML_DTD */
  4777. static const XML_Char atypeCDATA[]
  4778. = {ASCII_C, ASCII_D, ASCII_A, ASCII_T, ASCII_A, '\0'};
  4779. static const XML_Char atypeID[] = {ASCII_I, ASCII_D, '\0'};
  4780. static const XML_Char atypeIDREF[]
  4781. = {ASCII_I, ASCII_D, ASCII_R, ASCII_E, ASCII_F, '\0'};
  4782. static const XML_Char atypeIDREFS[]
  4783. = {ASCII_I, ASCII_D, ASCII_R, ASCII_E, ASCII_F, ASCII_S, '\0'};
  4784. static const XML_Char atypeENTITY[]
  4785. = {ASCII_E, ASCII_N, ASCII_T, ASCII_I, ASCII_T, ASCII_Y, '\0'};
  4786. static const XML_Char atypeENTITIES[]
  4787. = {ASCII_E, ASCII_N, ASCII_T, ASCII_I, ASCII_T,
  4788. ASCII_I, ASCII_E, ASCII_S, '\0'};
  4789. static const XML_Char atypeNMTOKEN[]
  4790. = {ASCII_N, ASCII_M, ASCII_T, ASCII_O, ASCII_K, ASCII_E, ASCII_N, '\0'};
  4791. static const XML_Char atypeNMTOKENS[]
  4792. = {ASCII_N, ASCII_M, ASCII_T, ASCII_O, ASCII_K,
  4793. ASCII_E, ASCII_N, ASCII_S, '\0'};
  4794. static const XML_Char notationPrefix[]
  4795. = {ASCII_N, ASCII_O, ASCII_T, ASCII_A, ASCII_T,
  4796. ASCII_I, ASCII_O, ASCII_N, ASCII_LPAREN, '\0'};
  4797. static const XML_Char enumValueSep[] = {ASCII_PIPE, '\0'};
  4798. static const XML_Char enumValueStart[] = {ASCII_LPAREN, '\0'};
  4799. #ifndef XML_DTD
  4800. UNUSED_P(account);
  4801. #endif
  4802. /* save one level of indirection */
  4803. DTD *const dtd = parser->m_dtd;
  4804. const char **eventPP;
  4805. const char **eventEndPP;
  4806. enum XML_Content_Quant quant;
  4807. if (enc == parser->m_encoding) {
  4808. eventPP = &parser->m_eventPtr;
  4809. eventEndPP = &parser->m_eventEndPtr;
  4810. } else {
  4811. eventPP = &(parser->m_openInternalEntities->internalEventPtr);
  4812. eventEndPP = &(parser->m_openInternalEntities->internalEventEndPtr);
  4813. }
  4814. for (;;) {
  4815. int role;
  4816. XML_Bool handleDefault = XML_TRUE;
  4817. *eventPP = s;
  4818. *eventEndPP = next;
  4819. if (tok <= 0) {
  4820. if (haveMore && tok != XML_TOK_INVALID) {
  4821. *nextPtr = s;
  4822. return XML_ERROR_NONE;
  4823. }
  4824. switch (tok) {
  4825. case XML_TOK_INVALID:
  4826. *eventPP = next;
  4827. return XML_ERROR_INVALID_TOKEN;
  4828. case XML_TOK_PARTIAL:
  4829. return XML_ERROR_UNCLOSED_TOKEN;
  4830. case XML_TOK_PARTIAL_CHAR:
  4831. return XML_ERROR_PARTIAL_CHAR;
  4832. case -XML_TOK_PROLOG_S:
  4833. tok = -tok;
  4834. break;
  4835. case XML_TOK_NONE:
  4836. #ifdef XML_DTD
  4837. /* for internal PE NOT referenced between declarations */
  4838. if (enc != parser->m_encoding
  4839. && ! parser->m_openInternalEntities->betweenDecl) {
  4840. *nextPtr = s;
  4841. return XML_ERROR_NONE;
  4842. }
  4843. /* WFC: PE Between Declarations - must check that PE contains
  4844. complete markup, not only for external PEs, but also for
  4845. internal PEs if the reference occurs between declarations.
  4846. */
  4847. if (parser->m_isParamEntity || enc != parser->m_encoding) {
  4848. if (XmlTokenRole(&parser->m_prologState, XML_TOK_NONE, end, end, enc)
  4849. == XML_ROLE_ERROR)
  4850. return XML_ERROR_INCOMPLETE_PE;
  4851. *nextPtr = s;
  4852. return XML_ERROR_NONE;
  4853. }
  4854. #endif /* XML_DTD */
  4855. return XML_ERROR_NO_ELEMENTS;
  4856. default:
  4857. tok = -tok;
  4858. next = end;
  4859. break;
  4860. }
  4861. }
  4862. role = XmlTokenRole(&parser->m_prologState, tok, s, next, enc);
  4863. #if XML_GE == 1
  4864. switch (role) {
  4865. case XML_ROLE_INSTANCE_START: // bytes accounted in contentProcessor
  4866. case XML_ROLE_XML_DECL: // bytes accounted in processXmlDecl
  4867. # ifdef XML_DTD
  4868. case XML_ROLE_TEXT_DECL: // bytes accounted in processXmlDecl
  4869. # endif
  4870. break;
  4871. default:
  4872. if (! accountingDiffTolerated(parser, tok, s, next, __LINE__, account)) {
  4873. accountingOnAbort(parser);
  4874. return XML_ERROR_AMPLIFICATION_LIMIT_BREACH;
  4875. }
  4876. }
  4877. #endif
  4878. switch (role) {
  4879. case XML_ROLE_XML_DECL: {
  4880. enum XML_Error result = processXmlDecl(parser, 0, s, next);
  4881. if (result != XML_ERROR_NONE)
  4882. return result;
  4883. enc = parser->m_encoding;
  4884. handleDefault = XML_FALSE;
  4885. } break;
  4886. case XML_ROLE_DOCTYPE_NAME:
  4887. if (parser->m_startDoctypeDeclHandler) {
  4888. parser->m_doctypeName
  4889. = poolStoreString(&parser->m_tempPool, enc, s, next);
  4890. if (! parser->m_doctypeName)
  4891. return XML_ERROR_NO_MEMORY;
  4892. poolFinish(&parser->m_tempPool);
  4893. parser->m_doctypePubid = NULL;
  4894. handleDefault = XML_FALSE;
  4895. }
  4896. parser->m_doctypeSysid = NULL; /* always initialize to NULL */
  4897. break;
  4898. case XML_ROLE_DOCTYPE_INTERNAL_SUBSET:
  4899. if (parser->m_startDoctypeDeclHandler) {
  4900. parser->m_startDoctypeDeclHandler(
  4901. parser->m_handlerArg, parser->m_doctypeName, parser->m_doctypeSysid,
  4902. parser->m_doctypePubid, 1);
  4903. parser->m_doctypeName = NULL;
  4904. poolClear(&parser->m_tempPool);
  4905. handleDefault = XML_FALSE;
  4906. }
  4907. break;
  4908. #ifdef XML_DTD
  4909. case XML_ROLE_TEXT_DECL: {
  4910. enum XML_Error result = processXmlDecl(parser, 1, s, next);
  4911. if (result != XML_ERROR_NONE)
  4912. return result;
  4913. enc = parser->m_encoding;
  4914. handleDefault = XML_FALSE;
  4915. } break;
  4916. #endif /* XML_DTD */
  4917. case XML_ROLE_DOCTYPE_PUBLIC_ID:
  4918. #ifdef XML_DTD
  4919. parser->m_useForeignDTD = XML_FALSE;
  4920. parser->m_declEntity = (ENTITY *)lookup(
  4921. parser, &dtd->paramEntities, externalSubsetName, sizeof(ENTITY));
  4922. if (! parser->m_declEntity)
  4923. return XML_ERROR_NO_MEMORY;
  4924. #endif /* XML_DTD */
  4925. dtd->hasParamEntityRefs = XML_TRUE;
  4926. if (parser->m_startDoctypeDeclHandler) {
  4927. XML_Char *pubId;
  4928. if (! XmlIsPublicId(enc, s, next, eventPP))
  4929. return XML_ERROR_PUBLICID;
  4930. pubId = poolStoreString(&parser->m_tempPool, enc,
  4931. s + enc->minBytesPerChar,
  4932. next - enc->minBytesPerChar);
  4933. if (! pubId)
  4934. return XML_ERROR_NO_MEMORY;
  4935. normalizePublicId(pubId);
  4936. poolFinish(&parser->m_tempPool);
  4937. parser->m_doctypePubid = pubId;
  4938. handleDefault = XML_FALSE;
  4939. goto alreadyChecked;
  4940. }
  4941. /* fall through */
  4942. case XML_ROLE_ENTITY_PUBLIC_ID:
  4943. if (! XmlIsPublicId(enc, s, next, eventPP))
  4944. return XML_ERROR_PUBLICID;
  4945. alreadyChecked:
  4946. if (dtd->keepProcessing && parser->m_declEntity) {
  4947. XML_Char *tem
  4948. = poolStoreString(&dtd->pool, enc, s + enc->minBytesPerChar,
  4949. next - enc->minBytesPerChar);
  4950. if (! tem)
  4951. return XML_ERROR_NO_MEMORY;
  4952. normalizePublicId(tem);
  4953. parser->m_declEntity->publicId = tem;
  4954. poolFinish(&dtd->pool);
  4955. /* Don't suppress the default handler if we fell through from
  4956. * the XML_ROLE_DOCTYPE_PUBLIC_ID case.
  4957. */
  4958. if (parser->m_entityDeclHandler && role == XML_ROLE_ENTITY_PUBLIC_ID)
  4959. handleDefault = XML_FALSE;
  4960. }
  4961. break;
  4962. case XML_ROLE_DOCTYPE_CLOSE:
  4963. if (allowClosingDoctype != XML_TRUE) {
  4964. /* Must not close doctype from within expanded parameter entities */
  4965. return XML_ERROR_INVALID_TOKEN;
  4966. }
  4967. if (parser->m_doctypeName) {
  4968. parser->m_startDoctypeDeclHandler(
  4969. parser->m_handlerArg, parser->m_doctypeName, parser->m_doctypeSysid,
  4970. parser->m_doctypePubid, 0);
  4971. poolClear(&parser->m_tempPool);
  4972. handleDefault = XML_FALSE;
  4973. }
  4974. /* parser->m_doctypeSysid will be non-NULL in the case of a previous
  4975. XML_ROLE_DOCTYPE_SYSTEM_ID, even if parser->m_startDoctypeDeclHandler
  4976. was not set, indicating an external subset
  4977. */
  4978. #ifdef XML_DTD
  4979. if (parser->m_doctypeSysid || parser->m_useForeignDTD) {
  4980. XML_Bool hadParamEntityRefs = dtd->hasParamEntityRefs;
  4981. dtd->hasParamEntityRefs = XML_TRUE;
  4982. if (parser->m_paramEntityParsing
  4983. && parser->m_externalEntityRefHandler) {
  4984. ENTITY *entity = (ENTITY *)lookup(parser, &dtd->paramEntities,
  4985. externalSubsetName, sizeof(ENTITY));
  4986. if (! entity) {
  4987. /* The external subset name "#" will have already been
  4988. * inserted into the hash table at the start of the
  4989. * external entity parsing, so no allocation will happen
  4990. * and lookup() cannot fail.
  4991. */
  4992. return XML_ERROR_NO_MEMORY; /* LCOV_EXCL_LINE */
  4993. }
  4994. if (parser->m_useForeignDTD)
  4995. entity->base = parser->m_curBase;
  4996. dtd->paramEntityRead = XML_FALSE;
  4997. if (! parser->m_externalEntityRefHandler(
  4998. parser->m_externalEntityRefHandlerArg, 0, entity->base,
  4999. entity->systemId, entity->publicId))
  5000. return XML_ERROR_EXTERNAL_ENTITY_HANDLING;
  5001. if (dtd->paramEntityRead) {
  5002. if (! dtd->standalone && parser->m_notStandaloneHandler
  5003. && ! parser->m_notStandaloneHandler(parser->m_handlerArg))
  5004. return XML_ERROR_NOT_STANDALONE;
  5005. }
  5006. /* if we didn't read the foreign DTD then this means that there
  5007. is no external subset and we must reset dtd->hasParamEntityRefs
  5008. */
  5009. else if (! parser->m_doctypeSysid)
  5010. dtd->hasParamEntityRefs = hadParamEntityRefs;
  5011. /* end of DTD - no need to update dtd->keepProcessing */
  5012. }
  5013. parser->m_useForeignDTD = XML_FALSE;
  5014. }
  5015. #endif /* XML_DTD */
  5016. if (parser->m_endDoctypeDeclHandler) {
  5017. parser->m_endDoctypeDeclHandler(parser->m_handlerArg);
  5018. handleDefault = XML_FALSE;
  5019. }
  5020. break;
  5021. case XML_ROLE_INSTANCE_START:
  5022. #ifdef XML_DTD
  5023. /* if there is no DOCTYPE declaration then now is the
  5024. last chance to read the foreign DTD
  5025. */
  5026. if (parser->m_useForeignDTD) {
  5027. XML_Bool hadParamEntityRefs = dtd->hasParamEntityRefs;
  5028. dtd->hasParamEntityRefs = XML_TRUE;
  5029. if (parser->m_paramEntityParsing
  5030. && parser->m_externalEntityRefHandler) {
  5031. ENTITY *entity = (ENTITY *)lookup(parser, &dtd->paramEntities,
  5032. externalSubsetName, sizeof(ENTITY));
  5033. if (! entity)
  5034. return XML_ERROR_NO_MEMORY;
  5035. entity->base = parser->m_curBase;
  5036. dtd->paramEntityRead = XML_FALSE;
  5037. if (! parser->m_externalEntityRefHandler(
  5038. parser->m_externalEntityRefHandlerArg, 0, entity->base,
  5039. entity->systemId, entity->publicId))
  5040. return XML_ERROR_EXTERNAL_ENTITY_HANDLING;
  5041. if (dtd->paramEntityRead) {
  5042. if (! dtd->standalone && parser->m_notStandaloneHandler
  5043. && ! parser->m_notStandaloneHandler(parser->m_handlerArg))
  5044. return XML_ERROR_NOT_STANDALONE;
  5045. }
  5046. /* if we didn't read the foreign DTD then this means that there
  5047. is no external subset and we must reset dtd->hasParamEntityRefs
  5048. */
  5049. else
  5050. dtd->hasParamEntityRefs = hadParamEntityRefs;
  5051. /* end of DTD - no need to update dtd->keepProcessing */
  5052. }
  5053. }
  5054. #endif /* XML_DTD */
  5055. parser->m_processor = contentProcessor;
  5056. return contentProcessor(parser, s, end, nextPtr);
  5057. case XML_ROLE_ATTLIST_ELEMENT_NAME:
  5058. parser->m_declElementType = getElementType(parser, enc, s, next);
  5059. if (! parser->m_declElementType)
  5060. return XML_ERROR_NO_MEMORY;
  5061. goto checkAttListDeclHandler;
  5062. case XML_ROLE_ATTRIBUTE_NAME:
  5063. parser->m_declAttributeId = getAttributeId(parser, enc, s, next);
  5064. if (! parser->m_declAttributeId)
  5065. return XML_ERROR_NO_MEMORY;
  5066. parser->m_declAttributeIsCdata = XML_FALSE;
  5067. parser->m_declAttributeType = NULL;
  5068. parser->m_declAttributeIsId = XML_FALSE;
  5069. goto checkAttListDeclHandler;
  5070. case XML_ROLE_ATTRIBUTE_TYPE_CDATA:
  5071. parser->m_declAttributeIsCdata = XML_TRUE;
  5072. parser->m_declAttributeType = atypeCDATA;
  5073. goto checkAttListDeclHandler;
  5074. case XML_ROLE_ATTRIBUTE_TYPE_ID:
  5075. parser->m_declAttributeIsId = XML_TRUE;
  5076. parser->m_declAttributeType = atypeID;
  5077. goto checkAttListDeclHandler;
  5078. case XML_ROLE_ATTRIBUTE_TYPE_IDREF:
  5079. parser->m_declAttributeType = atypeIDREF;
  5080. goto checkAttListDeclHandler;
  5081. case XML_ROLE_ATTRIBUTE_TYPE_IDREFS:
  5082. parser->m_declAttributeType = atypeIDREFS;
  5083. goto checkAttListDeclHandler;
  5084. case XML_ROLE_ATTRIBUTE_TYPE_ENTITY:
  5085. parser->m_declAttributeType = atypeENTITY;
  5086. goto checkAttListDeclHandler;
  5087. case XML_ROLE_ATTRIBUTE_TYPE_ENTITIES:
  5088. parser->m_declAttributeType = atypeENTITIES;
  5089. goto checkAttListDeclHandler;
  5090. case XML_ROLE_ATTRIBUTE_TYPE_NMTOKEN:
  5091. parser->m_declAttributeType = atypeNMTOKEN;
  5092. goto checkAttListDeclHandler;
  5093. case XML_ROLE_ATTRIBUTE_TYPE_NMTOKENS:
  5094. parser->m_declAttributeType = atypeNMTOKENS;
  5095. checkAttListDeclHandler:
  5096. if (dtd->keepProcessing && parser->m_attlistDeclHandler)
  5097. handleDefault = XML_FALSE;
  5098. break;
  5099. case XML_ROLE_ATTRIBUTE_ENUM_VALUE:
  5100. case XML_ROLE_ATTRIBUTE_NOTATION_VALUE:
  5101. if (dtd->keepProcessing && parser->m_attlistDeclHandler) {
  5102. const XML_Char *prefix;
  5103. if (parser->m_declAttributeType) {
  5104. prefix = enumValueSep;
  5105. } else {
  5106. prefix = (role == XML_ROLE_ATTRIBUTE_NOTATION_VALUE ? notationPrefix
  5107. : enumValueStart);
  5108. }
  5109. if (! poolAppendString(&parser->m_tempPool, prefix))
  5110. return XML_ERROR_NO_MEMORY;
  5111. if (! poolAppend(&parser->m_tempPool, enc, s, next))
  5112. return XML_ERROR_NO_MEMORY;
  5113. parser->m_declAttributeType = parser->m_tempPool.start;
  5114. handleDefault = XML_FALSE;
  5115. }
  5116. break;
  5117. case XML_ROLE_IMPLIED_ATTRIBUTE_VALUE:
  5118. case XML_ROLE_REQUIRED_ATTRIBUTE_VALUE:
  5119. if (dtd->keepProcessing) {
  5120. if (! defineAttribute(parser->m_declElementType,
  5121. parser->m_declAttributeId,
  5122. parser->m_declAttributeIsCdata,
  5123. parser->m_declAttributeIsId, 0, parser))
  5124. return XML_ERROR_NO_MEMORY;
  5125. if (parser->m_attlistDeclHandler && parser->m_declAttributeType) {
  5126. if (*parser->m_declAttributeType == XML_T(ASCII_LPAREN)
  5127. || (*parser->m_declAttributeType == XML_T(ASCII_N)
  5128. && parser->m_declAttributeType[1] == XML_T(ASCII_O))) {
  5129. /* Enumerated or Notation type */
  5130. if (! poolAppendChar(&parser->m_tempPool, XML_T(ASCII_RPAREN))
  5131. || ! poolAppendChar(&parser->m_tempPool, XML_T('\0')))
  5132. return XML_ERROR_NO_MEMORY;
  5133. parser->m_declAttributeType = parser->m_tempPool.start;
  5134. poolFinish(&parser->m_tempPool);
  5135. }
  5136. *eventEndPP = s;
  5137. parser->m_attlistDeclHandler(
  5138. parser->m_handlerArg, parser->m_declElementType->name,
  5139. parser->m_declAttributeId->name, parser->m_declAttributeType, 0,
  5140. role == XML_ROLE_REQUIRED_ATTRIBUTE_VALUE);
  5141. handleDefault = XML_FALSE;
  5142. }
  5143. }
  5144. poolClear(&parser->m_tempPool);
  5145. break;
  5146. case XML_ROLE_DEFAULT_ATTRIBUTE_VALUE:
  5147. case XML_ROLE_FIXED_ATTRIBUTE_VALUE:
  5148. if (dtd->keepProcessing) {
  5149. const XML_Char *attVal;
  5150. enum XML_Error result = storeAttributeValue(
  5151. parser, enc, parser->m_declAttributeIsCdata,
  5152. s + enc->minBytesPerChar, next - enc->minBytesPerChar, &dtd->pool,
  5153. XML_ACCOUNT_NONE);
  5154. if (result)
  5155. return result;
  5156. attVal = poolStart(&dtd->pool);
  5157. poolFinish(&dtd->pool);
  5158. /* ID attributes aren't allowed to have a default */
  5159. if (! defineAttribute(
  5160. parser->m_declElementType, parser->m_declAttributeId,
  5161. parser->m_declAttributeIsCdata, XML_FALSE, attVal, parser))
  5162. return XML_ERROR_NO_MEMORY;
  5163. if (parser->m_attlistDeclHandler && parser->m_declAttributeType) {
  5164. if (*parser->m_declAttributeType == XML_T(ASCII_LPAREN)
  5165. || (*parser->m_declAttributeType == XML_T(ASCII_N)
  5166. && parser->m_declAttributeType[1] == XML_T(ASCII_O))) {
  5167. /* Enumerated or Notation type */
  5168. if (! poolAppendChar(&parser->m_tempPool, XML_T(ASCII_RPAREN))
  5169. || ! poolAppendChar(&parser->m_tempPool, XML_T('\0')))
  5170. return XML_ERROR_NO_MEMORY;
  5171. parser->m_declAttributeType = parser->m_tempPool.start;
  5172. poolFinish(&parser->m_tempPool);
  5173. }
  5174. *eventEndPP = s;
  5175. parser->m_attlistDeclHandler(
  5176. parser->m_handlerArg, parser->m_declElementType->name,
  5177. parser->m_declAttributeId->name, parser->m_declAttributeType,
  5178. attVal, role == XML_ROLE_FIXED_ATTRIBUTE_VALUE);
  5179. poolClear(&parser->m_tempPool);
  5180. handleDefault = XML_FALSE;
  5181. }
  5182. }
  5183. break;
  5184. case XML_ROLE_ENTITY_VALUE:
  5185. if (dtd->keepProcessing) {
  5186. #if XML_GE == 1
  5187. // This will store the given replacement text in
  5188. // parser->m_declEntity->textPtr.
  5189. enum XML_Error result = callStoreEntityValue(
  5190. parser, enc, s + enc->minBytesPerChar, next - enc->minBytesPerChar,
  5191. XML_ACCOUNT_NONE);
  5192. if (parser->m_declEntity) {
  5193. parser->m_declEntity->textPtr = poolStart(&dtd->entityValuePool);
  5194. parser->m_declEntity->textLen
  5195. = (int)(poolLength(&dtd->entityValuePool));
  5196. poolFinish(&dtd->entityValuePool);
  5197. if (parser->m_entityDeclHandler) {
  5198. *eventEndPP = s;
  5199. parser->m_entityDeclHandler(
  5200. parser->m_handlerArg, parser->m_declEntity->name,
  5201. parser->m_declEntity->is_param, parser->m_declEntity->textPtr,
  5202. parser->m_declEntity->textLen, parser->m_curBase, 0, 0, 0);
  5203. handleDefault = XML_FALSE;
  5204. }
  5205. } else
  5206. poolDiscard(&dtd->entityValuePool);
  5207. if (result != XML_ERROR_NONE)
  5208. return result;
  5209. #else
  5210. // This will store "&amp;entity123;" in parser->m_declEntity->textPtr
  5211. // to end up as "&entity123;" in the handler.
  5212. if (parser->m_declEntity != NULL) {
  5213. const enum XML_Error result
  5214. = storeSelfEntityValue(parser, parser->m_declEntity);
  5215. if (result != XML_ERROR_NONE)
  5216. return result;
  5217. if (parser->m_entityDeclHandler) {
  5218. *eventEndPP = s;
  5219. parser->m_entityDeclHandler(
  5220. parser->m_handlerArg, parser->m_declEntity->name,
  5221. parser->m_declEntity->is_param, parser->m_declEntity->textPtr,
  5222. parser->m_declEntity->textLen, parser->m_curBase, 0, 0, 0);
  5223. handleDefault = XML_FALSE;
  5224. }
  5225. }
  5226. #endif
  5227. }
  5228. break;
  5229. case XML_ROLE_DOCTYPE_SYSTEM_ID:
  5230. #ifdef XML_DTD
  5231. parser->m_useForeignDTD = XML_FALSE;
  5232. #endif /* XML_DTD */
  5233. dtd->hasParamEntityRefs = XML_TRUE;
  5234. if (parser->m_startDoctypeDeclHandler) {
  5235. parser->m_doctypeSysid = poolStoreString(&parser->m_tempPool, enc,
  5236. s + enc->minBytesPerChar,
  5237. next - enc->minBytesPerChar);
  5238. if (parser->m_doctypeSysid == NULL)
  5239. return XML_ERROR_NO_MEMORY;
  5240. poolFinish(&parser->m_tempPool);
  5241. handleDefault = XML_FALSE;
  5242. }
  5243. #ifdef XML_DTD
  5244. else
  5245. /* use externalSubsetName to make parser->m_doctypeSysid non-NULL
  5246. for the case where no parser->m_startDoctypeDeclHandler is set */
  5247. parser->m_doctypeSysid = externalSubsetName;
  5248. #endif /* XML_DTD */
  5249. if (! dtd->standalone
  5250. #ifdef XML_DTD
  5251. && ! parser->m_paramEntityParsing
  5252. #endif /* XML_DTD */
  5253. && parser->m_notStandaloneHandler
  5254. && ! parser->m_notStandaloneHandler(parser->m_handlerArg))
  5255. return XML_ERROR_NOT_STANDALONE;
  5256. #ifndef XML_DTD
  5257. break;
  5258. #else /* XML_DTD */
  5259. if (! parser->m_declEntity) {
  5260. parser->m_declEntity = (ENTITY *)lookup(
  5261. parser, &dtd->paramEntities, externalSubsetName, sizeof(ENTITY));
  5262. if (! parser->m_declEntity)
  5263. return XML_ERROR_NO_MEMORY;
  5264. parser->m_declEntity->publicId = NULL;
  5265. }
  5266. #endif /* XML_DTD */
  5267. /* fall through */
  5268. case XML_ROLE_ENTITY_SYSTEM_ID:
  5269. if (dtd->keepProcessing && parser->m_declEntity) {
  5270. parser->m_declEntity->systemId
  5271. = poolStoreString(&dtd->pool, enc, s + enc->minBytesPerChar,
  5272. next - enc->minBytesPerChar);
  5273. if (! parser->m_declEntity->systemId)
  5274. return XML_ERROR_NO_MEMORY;
  5275. parser->m_declEntity->base = parser->m_curBase;
  5276. poolFinish(&dtd->pool);
  5277. /* Don't suppress the default handler if we fell through from
  5278. * the XML_ROLE_DOCTYPE_SYSTEM_ID case.
  5279. */
  5280. if (parser->m_entityDeclHandler && role == XML_ROLE_ENTITY_SYSTEM_ID)
  5281. handleDefault = XML_FALSE;
  5282. }
  5283. break;
  5284. case XML_ROLE_ENTITY_COMPLETE:
  5285. #if XML_GE == 0
  5286. // This will store "&amp;entity123;" in entity->textPtr
  5287. // to end up as "&entity123;" in the handler.
  5288. if (parser->m_declEntity != NULL) {
  5289. const enum XML_Error result
  5290. = storeSelfEntityValue(parser, parser->m_declEntity);
  5291. if (result != XML_ERROR_NONE)
  5292. return result;
  5293. }
  5294. #endif
  5295. if (dtd->keepProcessing && parser->m_declEntity
  5296. && parser->m_entityDeclHandler) {
  5297. *eventEndPP = s;
  5298. parser->m_entityDeclHandler(
  5299. parser->m_handlerArg, parser->m_declEntity->name,
  5300. parser->m_declEntity->is_param, 0, 0, parser->m_declEntity->base,
  5301. parser->m_declEntity->systemId, parser->m_declEntity->publicId, 0);
  5302. handleDefault = XML_FALSE;
  5303. }
  5304. break;
  5305. case XML_ROLE_ENTITY_NOTATION_NAME:
  5306. if (dtd->keepProcessing && parser->m_declEntity) {
  5307. parser->m_declEntity->notation
  5308. = poolStoreString(&dtd->pool, enc, s, next);
  5309. if (! parser->m_declEntity->notation)
  5310. return XML_ERROR_NO_MEMORY;
  5311. poolFinish(&dtd->pool);
  5312. if (parser->m_unparsedEntityDeclHandler) {
  5313. *eventEndPP = s;
  5314. parser->m_unparsedEntityDeclHandler(
  5315. parser->m_handlerArg, parser->m_declEntity->name,
  5316. parser->m_declEntity->base, parser->m_declEntity->systemId,
  5317. parser->m_declEntity->publicId, parser->m_declEntity->notation);
  5318. handleDefault = XML_FALSE;
  5319. } else if (parser->m_entityDeclHandler) {
  5320. *eventEndPP = s;
  5321. parser->m_entityDeclHandler(
  5322. parser->m_handlerArg, parser->m_declEntity->name, 0, 0, 0,
  5323. parser->m_declEntity->base, parser->m_declEntity->systemId,
  5324. parser->m_declEntity->publicId, parser->m_declEntity->notation);
  5325. handleDefault = XML_FALSE;
  5326. }
  5327. }
  5328. break;
  5329. case XML_ROLE_GENERAL_ENTITY_NAME: {
  5330. if (XmlPredefinedEntityName(enc, s, next)) {
  5331. parser->m_declEntity = NULL;
  5332. break;
  5333. }
  5334. if (dtd->keepProcessing) {
  5335. const XML_Char *name = poolStoreString(&dtd->pool, enc, s, next);
  5336. if (! name)
  5337. return XML_ERROR_NO_MEMORY;
  5338. parser->m_declEntity = (ENTITY *)lookup(parser, &dtd->generalEntities,
  5339. name, sizeof(ENTITY));
  5340. if (! parser->m_declEntity)
  5341. return XML_ERROR_NO_MEMORY;
  5342. if (parser->m_declEntity->name != name) {
  5343. poolDiscard(&dtd->pool);
  5344. parser->m_declEntity = NULL;
  5345. } else {
  5346. poolFinish(&dtd->pool);
  5347. parser->m_declEntity->publicId = NULL;
  5348. parser->m_declEntity->is_param = XML_FALSE;
  5349. /* if we have a parent parser or are reading an internal parameter
  5350. entity, then the entity declaration is not considered "internal"
  5351. */
  5352. parser->m_declEntity->is_internal
  5353. = ! (parser->m_parentParser || parser->m_openInternalEntities);
  5354. if (parser->m_entityDeclHandler)
  5355. handleDefault = XML_FALSE;
  5356. }
  5357. } else {
  5358. poolDiscard(&dtd->pool);
  5359. parser->m_declEntity = NULL;
  5360. }
  5361. } break;
  5362. case XML_ROLE_PARAM_ENTITY_NAME:
  5363. #ifdef XML_DTD
  5364. if (dtd->keepProcessing) {
  5365. const XML_Char *name = poolStoreString(&dtd->pool, enc, s, next);
  5366. if (! name)
  5367. return XML_ERROR_NO_MEMORY;
  5368. parser->m_declEntity = (ENTITY *)lookup(parser, &dtd->paramEntities,
  5369. name, sizeof(ENTITY));
  5370. if (! parser->m_declEntity)
  5371. return XML_ERROR_NO_MEMORY;
  5372. if (parser->m_declEntity->name != name) {
  5373. poolDiscard(&dtd->pool);
  5374. parser->m_declEntity = NULL;
  5375. } else {
  5376. poolFinish(&dtd->pool);
  5377. parser->m_declEntity->publicId = NULL;
  5378. parser->m_declEntity->is_param = XML_TRUE;
  5379. /* if we have a parent parser or are reading an internal parameter
  5380. entity, then the entity declaration is not considered "internal"
  5381. */
  5382. parser->m_declEntity->is_internal
  5383. = ! (parser->m_parentParser || parser->m_openInternalEntities);
  5384. if (parser->m_entityDeclHandler)
  5385. handleDefault = XML_FALSE;
  5386. }
  5387. } else {
  5388. poolDiscard(&dtd->pool);
  5389. parser->m_declEntity = NULL;
  5390. }
  5391. #else /* not XML_DTD */
  5392. parser->m_declEntity = NULL;
  5393. #endif /* XML_DTD */
  5394. break;
  5395. case XML_ROLE_NOTATION_NAME:
  5396. parser->m_declNotationPublicId = NULL;
  5397. parser->m_declNotationName = NULL;
  5398. if (parser->m_notationDeclHandler) {
  5399. parser->m_declNotationName
  5400. = poolStoreString(&parser->m_tempPool, enc, s, next);
  5401. if (! parser->m_declNotationName)
  5402. return XML_ERROR_NO_MEMORY;
  5403. poolFinish(&parser->m_tempPool);
  5404. handleDefault = XML_FALSE;
  5405. }
  5406. break;
  5407. case XML_ROLE_NOTATION_PUBLIC_ID:
  5408. if (! XmlIsPublicId(enc, s, next, eventPP))
  5409. return XML_ERROR_PUBLICID;
  5410. if (parser
  5411. ->m_declNotationName) { /* means m_notationDeclHandler != NULL */
  5412. XML_Char *tem = poolStoreString(&parser->m_tempPool, enc,
  5413. s + enc->minBytesPerChar,
  5414. next - enc->minBytesPerChar);
  5415. if (! tem)
  5416. return XML_ERROR_NO_MEMORY;
  5417. normalizePublicId(tem);
  5418. parser->m_declNotationPublicId = tem;
  5419. poolFinish(&parser->m_tempPool);
  5420. handleDefault = XML_FALSE;
  5421. }
  5422. break;
  5423. case XML_ROLE_NOTATION_SYSTEM_ID:
  5424. if (parser->m_declNotationName && parser->m_notationDeclHandler) {
  5425. const XML_Char *systemId = poolStoreString(&parser->m_tempPool, enc,
  5426. s + enc->minBytesPerChar,
  5427. next - enc->minBytesPerChar);
  5428. if (! systemId)
  5429. return XML_ERROR_NO_MEMORY;
  5430. *eventEndPP = s;
  5431. parser->m_notationDeclHandler(
  5432. parser->m_handlerArg, parser->m_declNotationName, parser->m_curBase,
  5433. systemId, parser->m_declNotationPublicId);
  5434. handleDefault = XML_FALSE;
  5435. }
  5436. poolClear(&parser->m_tempPool);
  5437. break;
  5438. case XML_ROLE_NOTATION_NO_SYSTEM_ID:
  5439. if (parser->m_declNotationPublicId && parser->m_notationDeclHandler) {
  5440. *eventEndPP = s;
  5441. parser->m_notationDeclHandler(
  5442. parser->m_handlerArg, parser->m_declNotationName, parser->m_curBase,
  5443. 0, parser->m_declNotationPublicId);
  5444. handleDefault = XML_FALSE;
  5445. }
  5446. poolClear(&parser->m_tempPool);
  5447. break;
  5448. case XML_ROLE_ERROR:
  5449. switch (tok) {
  5450. case XML_TOK_PARAM_ENTITY_REF:
  5451. /* PE references in internal subset are
  5452. not allowed within declarations. */
  5453. return XML_ERROR_PARAM_ENTITY_REF;
  5454. case XML_TOK_XML_DECL:
  5455. return XML_ERROR_MISPLACED_XML_PI;
  5456. default:
  5457. return XML_ERROR_SYNTAX;
  5458. }
  5459. #ifdef XML_DTD
  5460. case XML_ROLE_IGNORE_SECT: {
  5461. enum XML_Error result;
  5462. if (parser->m_defaultHandler)
  5463. reportDefault(parser, enc, s, next);
  5464. handleDefault = XML_FALSE;
  5465. result = doIgnoreSection(parser, enc, &next, end, nextPtr, haveMore);
  5466. if (result != XML_ERROR_NONE)
  5467. return result;
  5468. else if (! next) {
  5469. parser->m_processor = ignoreSectionProcessor;
  5470. return result;
  5471. }
  5472. } break;
  5473. #endif /* XML_DTD */
  5474. case XML_ROLE_GROUP_OPEN:
  5475. if (parser->m_prologState.level >= parser->m_groupSize) {
  5476. if (parser->m_groupSize) {
  5477. {
  5478. /* Detect and prevent integer overflow */
  5479. if (parser->m_groupSize > (unsigned int)(-1) / 2u) {
  5480. return XML_ERROR_NO_MEMORY;
  5481. }
  5482. char *const new_connector = REALLOC(
  5483. parser, parser->m_groupConnector, parser->m_groupSize *= 2);
  5484. if (new_connector == NULL) {
  5485. parser->m_groupSize /= 2;
  5486. return XML_ERROR_NO_MEMORY;
  5487. }
  5488. parser->m_groupConnector = new_connector;
  5489. }
  5490. if (dtd->scaffIndex) {
  5491. /* Detect and prevent integer overflow.
  5492. * The preprocessor guard addresses the "always false" warning
  5493. * from -Wtype-limits on platforms where
  5494. * sizeof(unsigned int) < sizeof(size_t), e.g. on x86_64. */
  5495. #if UINT_MAX >= SIZE_MAX
  5496. if (parser->m_groupSize > SIZE_MAX / sizeof(int)) {
  5497. parser->m_groupSize /= 2;
  5498. return XML_ERROR_NO_MEMORY;
  5499. }
  5500. #endif
  5501. int *const new_scaff_index = REALLOC(
  5502. parser, dtd->scaffIndex, parser->m_groupSize * sizeof(int));
  5503. if (new_scaff_index == NULL) {
  5504. parser->m_groupSize /= 2;
  5505. return XML_ERROR_NO_MEMORY;
  5506. }
  5507. dtd->scaffIndex = new_scaff_index;
  5508. }
  5509. } else {
  5510. parser->m_groupConnector = MALLOC(parser, parser->m_groupSize = 32);
  5511. if (! parser->m_groupConnector) {
  5512. parser->m_groupSize = 0;
  5513. return XML_ERROR_NO_MEMORY;
  5514. }
  5515. }
  5516. }
  5517. parser->m_groupConnector[parser->m_prologState.level] = 0;
  5518. if (dtd->in_eldecl) {
  5519. int myindex = nextScaffoldPart(parser);
  5520. if (myindex < 0)
  5521. return XML_ERROR_NO_MEMORY;
  5522. assert(dtd->scaffIndex != NULL);
  5523. dtd->scaffIndex[dtd->scaffLevel] = myindex;
  5524. dtd->scaffLevel++;
  5525. dtd->scaffold[myindex].type = XML_CTYPE_SEQ;
  5526. if (parser->m_elementDeclHandler)
  5527. handleDefault = XML_FALSE;
  5528. }
  5529. break;
  5530. case XML_ROLE_GROUP_SEQUENCE:
  5531. if (parser->m_groupConnector[parser->m_prologState.level] == ASCII_PIPE)
  5532. return XML_ERROR_SYNTAX;
  5533. parser->m_groupConnector[parser->m_prologState.level] = ASCII_COMMA;
  5534. if (dtd->in_eldecl && parser->m_elementDeclHandler)
  5535. handleDefault = XML_FALSE;
  5536. break;
  5537. case XML_ROLE_GROUP_CHOICE:
  5538. if (parser->m_groupConnector[parser->m_prologState.level] == ASCII_COMMA)
  5539. return XML_ERROR_SYNTAX;
  5540. if (dtd->in_eldecl
  5541. && ! parser->m_groupConnector[parser->m_prologState.level]
  5542. && (dtd->scaffold[dtd->scaffIndex[dtd->scaffLevel - 1]].type
  5543. != XML_CTYPE_MIXED)) {
  5544. dtd->scaffold[dtd->scaffIndex[dtd->scaffLevel - 1]].type
  5545. = XML_CTYPE_CHOICE;
  5546. if (parser->m_elementDeclHandler)
  5547. handleDefault = XML_FALSE;
  5548. }
  5549. parser->m_groupConnector[parser->m_prologState.level] = ASCII_PIPE;
  5550. break;
  5551. case XML_ROLE_PARAM_ENTITY_REF:
  5552. #ifdef XML_DTD
  5553. case XML_ROLE_INNER_PARAM_ENTITY_REF:
  5554. dtd->hasParamEntityRefs = XML_TRUE;
  5555. if (! parser->m_paramEntityParsing)
  5556. dtd->keepProcessing = dtd->standalone;
  5557. else {
  5558. const XML_Char *name;
  5559. ENTITY *entity;
  5560. name = poolStoreString(&dtd->pool, enc, s + enc->minBytesPerChar,
  5561. next - enc->minBytesPerChar);
  5562. if (! name)
  5563. return XML_ERROR_NO_MEMORY;
  5564. entity = (ENTITY *)lookup(parser, &dtd->paramEntities, name, 0);
  5565. poolDiscard(&dtd->pool);
  5566. /* first, determine if a check for an existing declaration is needed;
  5567. if yes, check that the entity exists, and that it is internal,
  5568. otherwise call the skipped entity handler
  5569. */
  5570. if (parser->m_prologState.documentEntity
  5571. && (dtd->standalone ? ! parser->m_openInternalEntities
  5572. : ! dtd->hasParamEntityRefs)) {
  5573. if (! entity)
  5574. return XML_ERROR_UNDEFINED_ENTITY;
  5575. else if (! entity->is_internal) {
  5576. /* It's hard to exhaustively search the code to be sure,
  5577. * but there doesn't seem to be a way of executing the
  5578. * following line. There are two cases:
  5579. *
  5580. * If 'standalone' is false, the DTD must have no
  5581. * parameter entities or we wouldn't have passed the outer
  5582. * 'if' statement. That means the only entity in the hash
  5583. * table is the external subset name "#" which cannot be
  5584. * given as a parameter entity name in XML syntax, so the
  5585. * lookup must have returned NULL and we don't even reach
  5586. * the test for an internal entity.
  5587. *
  5588. * If 'standalone' is true, it does not seem to be
  5589. * possible to create entities taking this code path that
  5590. * are not internal entities, so fail the test above.
  5591. *
  5592. * Because this analysis is very uncertain, the code is
  5593. * being left in place and merely removed from the
  5594. * coverage test statistics.
  5595. */
  5596. return XML_ERROR_ENTITY_DECLARED_IN_PE; /* LCOV_EXCL_LINE */
  5597. }
  5598. } else if (! entity) {
  5599. dtd->keepProcessing = dtd->standalone;
  5600. /* cannot report skipped entities in declarations */
  5601. if ((role == XML_ROLE_PARAM_ENTITY_REF)
  5602. && parser->m_skippedEntityHandler) {
  5603. parser->m_skippedEntityHandler(parser->m_handlerArg, name, 1);
  5604. handleDefault = XML_FALSE;
  5605. }
  5606. break;
  5607. }
  5608. if (entity->open)
  5609. return XML_ERROR_RECURSIVE_ENTITY_REF;
  5610. if (entity->textPtr) {
  5611. enum XML_Error result;
  5612. XML_Bool betweenDecl
  5613. = (role == XML_ROLE_PARAM_ENTITY_REF ? XML_TRUE : XML_FALSE);
  5614. result = processEntity(parser, entity, betweenDecl, ENTITY_INTERNAL);
  5615. if (result != XML_ERROR_NONE)
  5616. return result;
  5617. handleDefault = XML_FALSE;
  5618. break;
  5619. }
  5620. if (parser->m_externalEntityRefHandler) {
  5621. dtd->paramEntityRead = XML_FALSE;
  5622. entity->open = XML_TRUE;
  5623. entityTrackingOnOpen(parser, entity, __LINE__);
  5624. if (! parser->m_externalEntityRefHandler(
  5625. parser->m_externalEntityRefHandlerArg, 0, entity->base,
  5626. entity->systemId, entity->publicId)) {
  5627. entityTrackingOnClose(parser, entity, __LINE__);
  5628. entity->open = XML_FALSE;
  5629. return XML_ERROR_EXTERNAL_ENTITY_HANDLING;
  5630. }
  5631. entityTrackingOnClose(parser, entity, __LINE__);
  5632. entity->open = XML_FALSE;
  5633. handleDefault = XML_FALSE;
  5634. if (! dtd->paramEntityRead) {
  5635. dtd->keepProcessing = dtd->standalone;
  5636. break;
  5637. }
  5638. } else {
  5639. dtd->keepProcessing = dtd->standalone;
  5640. break;
  5641. }
  5642. }
  5643. #endif /* XML_DTD */
  5644. if (! dtd->standalone && parser->m_notStandaloneHandler
  5645. && ! parser->m_notStandaloneHandler(parser->m_handlerArg))
  5646. return XML_ERROR_NOT_STANDALONE;
  5647. break;
  5648. /* Element declaration stuff */
  5649. case XML_ROLE_ELEMENT_NAME:
  5650. if (parser->m_elementDeclHandler) {
  5651. parser->m_declElementType = getElementType(parser, enc, s, next);
  5652. if (! parser->m_declElementType)
  5653. return XML_ERROR_NO_MEMORY;
  5654. dtd->scaffLevel = 0;
  5655. dtd->scaffCount = 0;
  5656. dtd->in_eldecl = XML_TRUE;
  5657. handleDefault = XML_FALSE;
  5658. }
  5659. break;
  5660. case XML_ROLE_CONTENT_ANY:
  5661. case XML_ROLE_CONTENT_EMPTY:
  5662. if (dtd->in_eldecl) {
  5663. if (parser->m_elementDeclHandler) {
  5664. // NOTE: We are avoiding MALLOC(..) here to so that
  5665. // applications that are not using XML_FreeContentModel but
  5666. // plain free(..) or .free_fcn() to free the content model's
  5667. // memory are safe.
  5668. XML_Content *content = parser->m_mem.malloc_fcn(sizeof(XML_Content));
  5669. if (! content)
  5670. return XML_ERROR_NO_MEMORY;
  5671. content->quant = XML_CQUANT_NONE;
  5672. content->name = NULL;
  5673. content->numchildren = 0;
  5674. content->children = NULL;
  5675. content->type = ((role == XML_ROLE_CONTENT_ANY) ? XML_CTYPE_ANY
  5676. : XML_CTYPE_EMPTY);
  5677. *eventEndPP = s;
  5678. parser->m_elementDeclHandler(
  5679. parser->m_handlerArg, parser->m_declElementType->name, content);
  5680. handleDefault = XML_FALSE;
  5681. }
  5682. dtd->in_eldecl = XML_FALSE;
  5683. }
  5684. break;
  5685. case XML_ROLE_CONTENT_PCDATA:
  5686. if (dtd->in_eldecl) {
  5687. dtd->scaffold[dtd->scaffIndex[dtd->scaffLevel - 1]].type
  5688. = XML_CTYPE_MIXED;
  5689. if (parser->m_elementDeclHandler)
  5690. handleDefault = XML_FALSE;
  5691. }
  5692. break;
  5693. case XML_ROLE_CONTENT_ELEMENT:
  5694. quant = XML_CQUANT_NONE;
  5695. goto elementContent;
  5696. case XML_ROLE_CONTENT_ELEMENT_OPT:
  5697. quant = XML_CQUANT_OPT;
  5698. goto elementContent;
  5699. case XML_ROLE_CONTENT_ELEMENT_REP:
  5700. quant = XML_CQUANT_REP;
  5701. goto elementContent;
  5702. case XML_ROLE_CONTENT_ELEMENT_PLUS:
  5703. quant = XML_CQUANT_PLUS;
  5704. elementContent:
  5705. if (dtd->in_eldecl) {
  5706. ELEMENT_TYPE *el;
  5707. const XML_Char *name;
  5708. size_t nameLen;
  5709. const char *nxt
  5710. = (quant == XML_CQUANT_NONE ? next : next - enc->minBytesPerChar);
  5711. int myindex = nextScaffoldPart(parser);
  5712. if (myindex < 0)
  5713. return XML_ERROR_NO_MEMORY;
  5714. dtd->scaffold[myindex].type = XML_CTYPE_NAME;
  5715. dtd->scaffold[myindex].quant = quant;
  5716. el = getElementType(parser, enc, s, nxt);
  5717. if (! el)
  5718. return XML_ERROR_NO_MEMORY;
  5719. name = el->name;
  5720. dtd->scaffold[myindex].name = name;
  5721. nameLen = 0;
  5722. while (name[nameLen++])
  5723. ;
  5724. /* Detect and prevent integer overflow */
  5725. if (nameLen > UINT_MAX - dtd->contentStringLen) {
  5726. return XML_ERROR_NO_MEMORY;
  5727. }
  5728. dtd->contentStringLen += (unsigned)nameLen;
  5729. if (parser->m_elementDeclHandler)
  5730. handleDefault = XML_FALSE;
  5731. }
  5732. break;
  5733. case XML_ROLE_GROUP_CLOSE:
  5734. quant = XML_CQUANT_NONE;
  5735. goto closeGroup;
  5736. case XML_ROLE_GROUP_CLOSE_OPT:
  5737. quant = XML_CQUANT_OPT;
  5738. goto closeGroup;
  5739. case XML_ROLE_GROUP_CLOSE_REP:
  5740. quant = XML_CQUANT_REP;
  5741. goto closeGroup;
  5742. case XML_ROLE_GROUP_CLOSE_PLUS:
  5743. quant = XML_CQUANT_PLUS;
  5744. closeGroup:
  5745. if (dtd->in_eldecl) {
  5746. if (parser->m_elementDeclHandler)
  5747. handleDefault = XML_FALSE;
  5748. dtd->scaffLevel--;
  5749. dtd->scaffold[dtd->scaffIndex[dtd->scaffLevel]].quant = quant;
  5750. if (dtd->scaffLevel == 0) {
  5751. if (! handleDefault) {
  5752. XML_Content *model = build_model(parser);
  5753. if (! model)
  5754. return XML_ERROR_NO_MEMORY;
  5755. *eventEndPP = s;
  5756. parser->m_elementDeclHandler(
  5757. parser->m_handlerArg, parser->m_declElementType->name, model);
  5758. }
  5759. dtd->in_eldecl = XML_FALSE;
  5760. dtd->contentStringLen = 0;
  5761. }
  5762. }
  5763. break;
  5764. /* End element declaration stuff */
  5765. case XML_ROLE_PI:
  5766. if (! reportProcessingInstruction(parser, enc, s, next))
  5767. return XML_ERROR_NO_MEMORY;
  5768. handleDefault = XML_FALSE;
  5769. break;
  5770. case XML_ROLE_COMMENT:
  5771. if (! reportComment(parser, enc, s, next))
  5772. return XML_ERROR_NO_MEMORY;
  5773. handleDefault = XML_FALSE;
  5774. break;
  5775. case XML_ROLE_NONE:
  5776. switch (tok) {
  5777. case XML_TOK_BOM:
  5778. handleDefault = XML_FALSE;
  5779. break;
  5780. }
  5781. break;
  5782. case XML_ROLE_DOCTYPE_NONE:
  5783. if (parser->m_startDoctypeDeclHandler)
  5784. handleDefault = XML_FALSE;
  5785. break;
  5786. case XML_ROLE_ENTITY_NONE:
  5787. if (dtd->keepProcessing && parser->m_entityDeclHandler)
  5788. handleDefault = XML_FALSE;
  5789. break;
  5790. case XML_ROLE_NOTATION_NONE:
  5791. if (parser->m_notationDeclHandler)
  5792. handleDefault = XML_FALSE;
  5793. break;
  5794. case XML_ROLE_ATTLIST_NONE:
  5795. if (dtd->keepProcessing && parser->m_attlistDeclHandler)
  5796. handleDefault = XML_FALSE;
  5797. break;
  5798. case XML_ROLE_ELEMENT_NONE:
  5799. if (parser->m_elementDeclHandler)
  5800. handleDefault = XML_FALSE;
  5801. break;
  5802. } /* end of big switch */
  5803. if (handleDefault && parser->m_defaultHandler)
  5804. reportDefault(parser, enc, s, next);
  5805. switch (parser->m_parsingStatus.parsing) {
  5806. case XML_SUSPENDED:
  5807. *nextPtr = next;
  5808. return XML_ERROR_NONE;
  5809. case XML_FINISHED:
  5810. return XML_ERROR_ABORTED;
  5811. case XML_PARSING:
  5812. if (parser->m_reenter) {
  5813. *nextPtr = next;
  5814. return XML_ERROR_NONE;
  5815. }
  5816. /* Fall through */
  5817. default:
  5818. s = next;
  5819. tok = XmlPrologTok(enc, s, end, &next);
  5820. }
  5821. }
  5822. /* not reached */
  5823. }
  5824. static enum XML_Error PTRCALL
  5825. epilogProcessor(XML_Parser parser, const char *s, const char *end,
  5826. const char **nextPtr) {
  5827. parser->m_processor = epilogProcessor;
  5828. parser->m_eventPtr = s;
  5829. for (;;) {
  5830. const char *next = NULL;
  5831. int tok = XmlPrologTok(parser->m_encoding, s, end, &next);
  5832. #if XML_GE == 1
  5833. if (! accountingDiffTolerated(parser, tok, s, next, __LINE__,
  5834. XML_ACCOUNT_DIRECT)) {
  5835. accountingOnAbort(parser);
  5836. return XML_ERROR_AMPLIFICATION_LIMIT_BREACH;
  5837. }
  5838. #endif
  5839. parser->m_eventEndPtr = next;
  5840. switch (tok) {
  5841. /* report partial linebreak - it might be the last token */
  5842. case -XML_TOK_PROLOG_S:
  5843. if (parser->m_defaultHandler) {
  5844. reportDefault(parser, parser->m_encoding, s, next);
  5845. if (parser->m_parsingStatus.parsing == XML_FINISHED)
  5846. return XML_ERROR_ABORTED;
  5847. }
  5848. *nextPtr = next;
  5849. return XML_ERROR_NONE;
  5850. case XML_TOK_NONE:
  5851. *nextPtr = s;
  5852. return XML_ERROR_NONE;
  5853. case XML_TOK_PROLOG_S:
  5854. if (parser->m_defaultHandler)
  5855. reportDefault(parser, parser->m_encoding, s, next);
  5856. break;
  5857. case XML_TOK_PI:
  5858. if (! reportProcessingInstruction(parser, parser->m_encoding, s, next))
  5859. return XML_ERROR_NO_MEMORY;
  5860. break;
  5861. case XML_TOK_COMMENT:
  5862. if (! reportComment(parser, parser->m_encoding, s, next))
  5863. return XML_ERROR_NO_MEMORY;
  5864. break;
  5865. case XML_TOK_INVALID:
  5866. parser->m_eventPtr = next;
  5867. return XML_ERROR_INVALID_TOKEN;
  5868. case XML_TOK_PARTIAL:
  5869. if (! parser->m_parsingStatus.finalBuffer) {
  5870. *nextPtr = s;
  5871. return XML_ERROR_NONE;
  5872. }
  5873. return XML_ERROR_UNCLOSED_TOKEN;
  5874. case XML_TOK_PARTIAL_CHAR:
  5875. if (! parser->m_parsingStatus.finalBuffer) {
  5876. *nextPtr = s;
  5877. return XML_ERROR_NONE;
  5878. }
  5879. return XML_ERROR_PARTIAL_CHAR;
  5880. default:
  5881. return XML_ERROR_JUNK_AFTER_DOC_ELEMENT;
  5882. }
  5883. switch (parser->m_parsingStatus.parsing) {
  5884. case XML_SUSPENDED:
  5885. parser->m_eventPtr = next;
  5886. *nextPtr = next;
  5887. return XML_ERROR_NONE;
  5888. case XML_FINISHED:
  5889. parser->m_eventPtr = next;
  5890. return XML_ERROR_ABORTED;
  5891. case XML_PARSING:
  5892. if (parser->m_reenter) {
  5893. return XML_ERROR_UNEXPECTED_STATE; // LCOV_EXCL_LINE
  5894. }
  5895. /* Fall through */
  5896. default:;
  5897. parser->m_eventPtr = s = next;
  5898. }
  5899. }
  5900. }
  5901. static enum XML_Error
  5902. processEntity(XML_Parser parser, ENTITY *entity, XML_Bool betweenDecl,
  5903. enum EntityType type) {
  5904. OPEN_INTERNAL_ENTITY *openEntity, **openEntityList, **freeEntityList;
  5905. switch (type) {
  5906. case ENTITY_INTERNAL:
  5907. parser->m_processor = internalEntityProcessor;
  5908. openEntityList = &parser->m_openInternalEntities;
  5909. freeEntityList = &parser->m_freeInternalEntities;
  5910. break;
  5911. case ENTITY_ATTRIBUTE:
  5912. openEntityList = &parser->m_openAttributeEntities;
  5913. freeEntityList = &parser->m_freeAttributeEntities;
  5914. break;
  5915. case ENTITY_VALUE:
  5916. openEntityList = &parser->m_openValueEntities;
  5917. freeEntityList = &parser->m_freeValueEntities;
  5918. break;
  5919. /* default case serves merely as a safety net in case of a
  5920. * wrong entityType. Therefore we exclude the following lines
  5921. * from the test coverage.
  5922. *
  5923. * LCOV_EXCL_START
  5924. */
  5925. default:
  5926. // Should not reach here
  5927. assert(0);
  5928. /* LCOV_EXCL_STOP */
  5929. }
  5930. if (*freeEntityList) {
  5931. openEntity = *freeEntityList;
  5932. *freeEntityList = openEntity->next;
  5933. } else {
  5934. openEntity = MALLOC(parser, sizeof(OPEN_INTERNAL_ENTITY));
  5935. if (! openEntity)
  5936. return XML_ERROR_NO_MEMORY;
  5937. }
  5938. entity->open = XML_TRUE;
  5939. entity->hasMore = XML_TRUE;
  5940. #if XML_GE == 1
  5941. entityTrackingOnOpen(parser, entity, __LINE__);
  5942. #endif
  5943. entity->processed = 0;
  5944. openEntity->next = *openEntityList;
  5945. *openEntityList = openEntity;
  5946. openEntity->entity = entity;
  5947. openEntity->type = type;
  5948. openEntity->startTagLevel = parser->m_tagLevel;
  5949. openEntity->betweenDecl = betweenDecl;
  5950. openEntity->internalEventPtr = NULL;
  5951. openEntity->internalEventEndPtr = NULL;
  5952. // Only internal entities make use of the reenter flag
  5953. // therefore no need to set it for other entity types
  5954. if (type == ENTITY_INTERNAL) {
  5955. triggerReenter(parser);
  5956. }
  5957. return XML_ERROR_NONE;
  5958. }
  5959. static enum XML_Error PTRCALL
  5960. internalEntityProcessor(XML_Parser parser, const char *s, const char *end,
  5961. const char **nextPtr) {
  5962. UNUSED_P(s);
  5963. UNUSED_P(end);
  5964. UNUSED_P(nextPtr);
  5965. ENTITY *entity;
  5966. const char *textStart, *textEnd;
  5967. const char *next;
  5968. enum XML_Error result;
  5969. OPEN_INTERNAL_ENTITY *openEntity = parser->m_openInternalEntities;
  5970. if (! openEntity)
  5971. return XML_ERROR_UNEXPECTED_STATE;
  5972. entity = openEntity->entity;
  5973. // This will return early
  5974. if (entity->hasMore) {
  5975. textStart = ((const char *)entity->textPtr) + entity->processed;
  5976. textEnd = (const char *)(entity->textPtr + entity->textLen);
  5977. /* Set a safe default value in case 'next' does not get set */
  5978. next = textStart;
  5979. if (entity->is_param) {
  5980. int tok
  5981. = XmlPrologTok(parser->m_internalEncoding, textStart, textEnd, &next);
  5982. result = doProlog(parser, parser->m_internalEncoding, textStart, textEnd,
  5983. tok, next, &next, XML_FALSE, XML_FALSE,
  5984. XML_ACCOUNT_ENTITY_EXPANSION);
  5985. } else {
  5986. result = doContent(parser, openEntity->startTagLevel,
  5987. parser->m_internalEncoding, textStart, textEnd, &next,
  5988. XML_FALSE, XML_ACCOUNT_ENTITY_EXPANSION);
  5989. }
  5990. if (result != XML_ERROR_NONE)
  5991. return result;
  5992. // Check if entity is complete, if not, mark down how much of it is
  5993. // processed
  5994. if (textEnd != next
  5995. && (parser->m_parsingStatus.parsing == XML_SUSPENDED
  5996. || (parser->m_parsingStatus.parsing == XML_PARSING
  5997. && parser->m_reenter))) {
  5998. entity->processed = (int)(next - (const char *)entity->textPtr);
  5999. return result;
  6000. }
  6001. // Entity is complete. We cannot close it here since we need to first
  6002. // process its possible inner entities (which are added to the
  6003. // m_openInternalEntities during doProlog or doContent calls above)
  6004. entity->hasMore = XML_FALSE;
  6005. if (! entity->is_param
  6006. && (openEntity->startTagLevel != parser->m_tagLevel)) {
  6007. return XML_ERROR_ASYNC_ENTITY;
  6008. }
  6009. triggerReenter(parser);
  6010. return result;
  6011. } // End of entity processing, "if" block will return here
  6012. // Remove fully processed openEntity from open entity list.
  6013. #if XML_GE == 1
  6014. entityTrackingOnClose(parser, entity, __LINE__);
  6015. #endif
  6016. // openEntity is m_openInternalEntities' head, as we set it at the start of
  6017. // this function and we skipped doProlog and doContent calls with hasMore set
  6018. // to false. This means we can directly remove the head of
  6019. // m_openInternalEntities
  6020. assert(parser->m_openInternalEntities == openEntity);
  6021. entity->open = XML_FALSE;
  6022. parser->m_openInternalEntities = parser->m_openInternalEntities->next;
  6023. /* put openEntity back in list of free instances */
  6024. openEntity->next = parser->m_freeInternalEntities;
  6025. parser->m_freeInternalEntities = openEntity;
  6026. if (parser->m_openInternalEntities == NULL) {
  6027. parser->m_processor = entity->is_param ? prologProcessor : contentProcessor;
  6028. }
  6029. triggerReenter(parser);
  6030. return XML_ERROR_NONE;
  6031. }
  6032. static enum XML_Error PTRCALL
  6033. errorProcessor(XML_Parser parser, const char *s, const char *end,
  6034. const char **nextPtr) {
  6035. UNUSED_P(s);
  6036. UNUSED_P(end);
  6037. UNUSED_P(nextPtr);
  6038. return parser->m_errorCode;
  6039. }
  6040. static enum XML_Error
  6041. storeAttributeValue(XML_Parser parser, const ENCODING *enc, XML_Bool isCdata,
  6042. const char *ptr, const char *end, STRING_POOL *pool,
  6043. enum XML_Account account) {
  6044. const char *next = ptr;
  6045. enum XML_Error result = XML_ERROR_NONE;
  6046. while (1) {
  6047. if (! parser->m_openAttributeEntities) {
  6048. result = appendAttributeValue(parser, enc, isCdata, next, end, pool,
  6049. account, &next);
  6050. } else {
  6051. OPEN_INTERNAL_ENTITY *const openEntity = parser->m_openAttributeEntities;
  6052. if (! openEntity)
  6053. return XML_ERROR_UNEXPECTED_STATE;
  6054. ENTITY *const entity = openEntity->entity;
  6055. const char *const textStart
  6056. = ((const char *)entity->textPtr) + entity->processed;
  6057. const char *const textEnd
  6058. = (const char *)(entity->textPtr + entity->textLen);
  6059. /* Set a safe default value in case 'next' does not get set */
  6060. const char *nextInEntity = textStart;
  6061. if (entity->hasMore) {
  6062. result = appendAttributeValue(
  6063. parser, parser->m_internalEncoding, isCdata, textStart, textEnd,
  6064. pool, XML_ACCOUNT_ENTITY_EXPANSION, &nextInEntity);
  6065. if (result != XML_ERROR_NONE)
  6066. break;
  6067. // Check if entity is complete, if not, mark down how much of it is
  6068. // processed. A XML_SUSPENDED check here is not required as
  6069. // appendAttributeValue will never suspend the parser.
  6070. if (textEnd != nextInEntity) {
  6071. entity->processed
  6072. = (int)(nextInEntity - (const char *)entity->textPtr);
  6073. continue;
  6074. }
  6075. // Entity is complete. We cannot close it here since we need to first
  6076. // process its possible inner entities (which are added to the
  6077. // m_openAttributeEntities during appendAttributeValue)
  6078. entity->hasMore = XML_FALSE;
  6079. continue;
  6080. } // End of entity processing, "if" block skips the rest
  6081. // Remove fully processed openEntity from open entity list.
  6082. #if XML_GE == 1
  6083. entityTrackingOnClose(parser, entity, __LINE__);
  6084. #endif
  6085. // openEntity is m_openAttributeEntities' head, since we set it at the
  6086. // start of this function and because we skipped appendAttributeValue call
  6087. // with hasMore set to false. This means we can directly remove the head
  6088. // of m_openAttributeEntities
  6089. assert(parser->m_openAttributeEntities == openEntity);
  6090. entity->open = XML_FALSE;
  6091. parser->m_openAttributeEntities = parser->m_openAttributeEntities->next;
  6092. /* put openEntity back in list of free instances */
  6093. openEntity->next = parser->m_freeAttributeEntities;
  6094. parser->m_freeAttributeEntities = openEntity;
  6095. }
  6096. // Break if an error occurred or there is nothing left to process
  6097. if (result || (parser->m_openAttributeEntities == NULL && end == next)) {
  6098. break;
  6099. }
  6100. }
  6101. if (result)
  6102. return result;
  6103. if (! isCdata && poolLength(pool) && poolLastChar(pool) == 0x20)
  6104. poolChop(pool);
  6105. if (! poolAppendChar(pool, XML_T('\0')))
  6106. return XML_ERROR_NO_MEMORY;
  6107. return XML_ERROR_NONE;
  6108. }
  6109. static enum XML_Error
  6110. appendAttributeValue(XML_Parser parser, const ENCODING *enc, XML_Bool isCdata,
  6111. const char *ptr, const char *end, STRING_POOL *pool,
  6112. enum XML_Account account, const char **nextPtr) {
  6113. DTD *const dtd = parser->m_dtd; /* save one level of indirection */
  6114. #ifndef XML_DTD
  6115. UNUSED_P(account);
  6116. #endif
  6117. for (;;) {
  6118. const char *next
  6119. = ptr; /* XmlAttributeValueTok doesn't always set the last arg */
  6120. int tok = XmlAttributeValueTok(enc, ptr, end, &next);
  6121. #if XML_GE == 1
  6122. if (! accountingDiffTolerated(parser, tok, ptr, next, __LINE__, account)) {
  6123. accountingOnAbort(parser);
  6124. return XML_ERROR_AMPLIFICATION_LIMIT_BREACH;
  6125. }
  6126. #endif
  6127. switch (tok) {
  6128. case XML_TOK_NONE:
  6129. if (nextPtr) {
  6130. *nextPtr = next;
  6131. }
  6132. return XML_ERROR_NONE;
  6133. case XML_TOK_INVALID:
  6134. if (enc == parser->m_encoding)
  6135. parser->m_eventPtr = next;
  6136. return XML_ERROR_INVALID_TOKEN;
  6137. case XML_TOK_PARTIAL:
  6138. if (enc == parser->m_encoding)
  6139. parser->m_eventPtr = ptr;
  6140. return XML_ERROR_INVALID_TOKEN;
  6141. case XML_TOK_CHAR_REF: {
  6142. XML_Char buf[XML_ENCODE_MAX];
  6143. int i;
  6144. int n = XmlCharRefNumber(enc, ptr);
  6145. if (n < 0) {
  6146. if (enc == parser->m_encoding)
  6147. parser->m_eventPtr = ptr;
  6148. return XML_ERROR_BAD_CHAR_REF;
  6149. }
  6150. if (! isCdata && n == 0x20 /* space */
  6151. && (poolLength(pool) == 0 || poolLastChar(pool) == 0x20))
  6152. break;
  6153. n = XmlEncode(n, (ICHAR *)buf);
  6154. /* The XmlEncode() functions can never return 0 here. That
  6155. * error return happens if the code point passed in is either
  6156. * negative or greater than or equal to 0x110000. The
  6157. * XmlCharRefNumber() functions will all return a number
  6158. * strictly less than 0x110000 or a negative value if an error
  6159. * occurred. The negative value is intercepted above, so
  6160. * XmlEncode() is never passed a value it might return an
  6161. * error for.
  6162. */
  6163. for (i = 0; i < n; i++) {
  6164. if (! poolAppendChar(pool, buf[i]))
  6165. return XML_ERROR_NO_MEMORY;
  6166. }
  6167. } break;
  6168. case XML_TOK_DATA_CHARS:
  6169. if (! poolAppend(pool, enc, ptr, next))
  6170. return XML_ERROR_NO_MEMORY;
  6171. break;
  6172. case XML_TOK_TRAILING_CR:
  6173. next = ptr + enc->minBytesPerChar;
  6174. /* fall through */
  6175. case XML_TOK_ATTRIBUTE_VALUE_S:
  6176. case XML_TOK_DATA_NEWLINE:
  6177. if (! isCdata && (poolLength(pool) == 0 || poolLastChar(pool) == 0x20))
  6178. break;
  6179. if (! poolAppendChar(pool, 0x20))
  6180. return XML_ERROR_NO_MEMORY;
  6181. break;
  6182. case XML_TOK_ENTITY_REF: {
  6183. const XML_Char *name;
  6184. ENTITY *entity;
  6185. bool checkEntityDecl;
  6186. XML_Char ch = (XML_Char)XmlPredefinedEntityName(
  6187. enc, ptr + enc->minBytesPerChar, next - enc->minBytesPerChar);
  6188. if (ch) {
  6189. #if XML_GE == 1
  6190. /* NOTE: We are replacing 4-6 characters original input for 1 character
  6191. * so there is no amplification and hence recording without
  6192. * protection. */
  6193. accountingDiffTolerated(parser, tok, (char *)&ch,
  6194. ((char *)&ch) + sizeof(XML_Char), __LINE__,
  6195. XML_ACCOUNT_ENTITY_EXPANSION);
  6196. #endif /* XML_GE == 1 */
  6197. if (! poolAppendChar(pool, ch))
  6198. return XML_ERROR_NO_MEMORY;
  6199. break;
  6200. }
  6201. name = poolStoreString(&parser->m_temp2Pool, enc,
  6202. ptr + enc->minBytesPerChar,
  6203. next - enc->minBytesPerChar);
  6204. if (! name)
  6205. return XML_ERROR_NO_MEMORY;
  6206. entity = (ENTITY *)lookup(parser, &dtd->generalEntities, name, 0);
  6207. poolDiscard(&parser->m_temp2Pool);
  6208. /* First, determine if a check for an existing declaration is needed;
  6209. if yes, check that the entity exists, and that it is internal.
  6210. */
  6211. if (pool == &dtd->pool) /* are we called from prolog? */
  6212. checkEntityDecl =
  6213. #ifdef XML_DTD
  6214. parser->m_prologState.documentEntity &&
  6215. #endif /* XML_DTD */
  6216. (dtd->standalone ? ! parser->m_openInternalEntities
  6217. : ! dtd->hasParamEntityRefs);
  6218. else /* if (pool == &parser->m_tempPool): we are called from content */
  6219. checkEntityDecl = ! dtd->hasParamEntityRefs || dtd->standalone;
  6220. if (checkEntityDecl) {
  6221. if (! entity)
  6222. return XML_ERROR_UNDEFINED_ENTITY;
  6223. else if (! entity->is_internal)
  6224. return XML_ERROR_ENTITY_DECLARED_IN_PE;
  6225. } else if (! entity) {
  6226. /* Cannot report skipped entity here - see comments on
  6227. parser->m_skippedEntityHandler.
  6228. if (parser->m_skippedEntityHandler)
  6229. parser->m_skippedEntityHandler(parser->m_handlerArg, name, 0);
  6230. */
  6231. /* Cannot call the default handler because this would be
  6232. out of sync with the call to the startElementHandler.
  6233. if ((pool == &parser->m_tempPool) && parser->m_defaultHandler)
  6234. reportDefault(parser, enc, ptr, next);
  6235. */
  6236. break;
  6237. }
  6238. if (entity->open) {
  6239. if (enc == parser->m_encoding) {
  6240. /* It does not appear that this line can be executed.
  6241. *
  6242. * The "if (entity->open)" check catches recursive entity
  6243. * definitions. In order to be called with an open
  6244. * entity, it must have gone through this code before and
  6245. * been through the recursive call to
  6246. * appendAttributeValue() some lines below. That call
  6247. * sets the local encoding ("enc") to the parser's
  6248. * internal encoding (internal_utf8 or internal_utf16),
  6249. * which can never be the same as the principle encoding.
  6250. * It doesn't appear there is another code path that gets
  6251. * here with entity->open being TRUE.
  6252. *
  6253. * Since it is not certain that this logic is watertight,
  6254. * we keep the line and merely exclude it from coverage
  6255. * tests.
  6256. */
  6257. parser->m_eventPtr = ptr; /* LCOV_EXCL_LINE */
  6258. }
  6259. return XML_ERROR_RECURSIVE_ENTITY_REF;
  6260. }
  6261. if (entity->notation) {
  6262. if (enc == parser->m_encoding)
  6263. parser->m_eventPtr = ptr;
  6264. return XML_ERROR_BINARY_ENTITY_REF;
  6265. }
  6266. if (! entity->textPtr) {
  6267. if (enc == parser->m_encoding)
  6268. parser->m_eventPtr = ptr;
  6269. return XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF;
  6270. } else {
  6271. enum XML_Error result;
  6272. result = processEntity(parser, entity, XML_FALSE, ENTITY_ATTRIBUTE);
  6273. if ((result == XML_ERROR_NONE) && (nextPtr != NULL)) {
  6274. *nextPtr = next;
  6275. }
  6276. return result;
  6277. }
  6278. } break;
  6279. default:
  6280. /* The only token returned by XmlAttributeValueTok() that does
  6281. * not have an explicit case here is XML_TOK_PARTIAL_CHAR.
  6282. * Getting that would require an entity name to contain an
  6283. * incomplete XML character (e.g. \xE2\x82); however previous
  6284. * tokenisers will have already recognised and rejected such
  6285. * names before XmlAttributeValueTok() gets a look-in. This
  6286. * default case should be retained as a safety net, but the code
  6287. * excluded from coverage tests.
  6288. *
  6289. * LCOV_EXCL_START
  6290. */
  6291. if (enc == parser->m_encoding)
  6292. parser->m_eventPtr = ptr;
  6293. return XML_ERROR_UNEXPECTED_STATE;
  6294. /* LCOV_EXCL_STOP */
  6295. }
  6296. ptr = next;
  6297. }
  6298. /* not reached */
  6299. }
  6300. #if XML_GE == 1
  6301. static enum XML_Error
  6302. storeEntityValue(XML_Parser parser, const ENCODING *enc,
  6303. const char *entityTextPtr, const char *entityTextEnd,
  6304. enum XML_Account account, const char **nextPtr) {
  6305. DTD *const dtd = parser->m_dtd; /* save one level of indirection */
  6306. STRING_POOL *pool = &(dtd->entityValuePool);
  6307. enum XML_Error result = XML_ERROR_NONE;
  6308. # ifdef XML_DTD
  6309. int oldInEntityValue = parser->m_prologState.inEntityValue;
  6310. parser->m_prologState.inEntityValue = 1;
  6311. # else
  6312. UNUSED_P(account);
  6313. # endif /* XML_DTD */
  6314. /* never return Null for the value argument in EntityDeclHandler,
  6315. since this would indicate an external entity; therefore we
  6316. have to make sure that entityValuePool.start is not null */
  6317. if (! pool->blocks) {
  6318. if (! poolGrow(pool))
  6319. return XML_ERROR_NO_MEMORY;
  6320. }
  6321. const char *next = entityTextPtr;
  6322. /* Nothing to tokenize. */
  6323. if (entityTextPtr >= entityTextEnd) {
  6324. result = XML_ERROR_NONE;
  6325. goto endEntityValue;
  6326. }
  6327. for (;;) {
  6328. next
  6329. = entityTextPtr; /* XmlEntityValueTok doesn't always set the last arg */
  6330. int tok = XmlEntityValueTok(enc, entityTextPtr, entityTextEnd, &next);
  6331. if (! accountingDiffTolerated(parser, tok, entityTextPtr, next, __LINE__,
  6332. account)) {
  6333. accountingOnAbort(parser);
  6334. result = XML_ERROR_AMPLIFICATION_LIMIT_BREACH;
  6335. goto endEntityValue;
  6336. }
  6337. switch (tok) {
  6338. case XML_TOK_PARAM_ENTITY_REF:
  6339. # ifdef XML_DTD
  6340. if (parser->m_isParamEntity || enc != parser->m_encoding) {
  6341. const XML_Char *name;
  6342. ENTITY *entity;
  6343. name = poolStoreString(&parser->m_tempPool, enc,
  6344. entityTextPtr + enc->minBytesPerChar,
  6345. next - enc->minBytesPerChar);
  6346. if (! name) {
  6347. result = XML_ERROR_NO_MEMORY;
  6348. goto endEntityValue;
  6349. }
  6350. entity = (ENTITY *)lookup(parser, &dtd->paramEntities, name, 0);
  6351. poolDiscard(&parser->m_tempPool);
  6352. if (! entity) {
  6353. /* not a well-formedness error - see XML 1.0: WFC Entity Declared */
  6354. /* cannot report skipped entity here - see comments on
  6355. parser->m_skippedEntityHandler
  6356. if (parser->m_skippedEntityHandler)
  6357. parser->m_skippedEntityHandler(parser->m_handlerArg, name, 0);
  6358. */
  6359. dtd->keepProcessing = dtd->standalone;
  6360. goto endEntityValue;
  6361. }
  6362. if (entity->open || (entity == parser->m_declEntity)) {
  6363. if (enc == parser->m_encoding)
  6364. parser->m_eventPtr = entityTextPtr;
  6365. result = XML_ERROR_RECURSIVE_ENTITY_REF;
  6366. goto endEntityValue;
  6367. }
  6368. if (entity->systemId) {
  6369. if (parser->m_externalEntityRefHandler) {
  6370. dtd->paramEntityRead = XML_FALSE;
  6371. entity->open = XML_TRUE;
  6372. entityTrackingOnOpen(parser, entity, __LINE__);
  6373. if (! parser->m_externalEntityRefHandler(
  6374. parser->m_externalEntityRefHandlerArg, 0, entity->base,
  6375. entity->systemId, entity->publicId)) {
  6376. entityTrackingOnClose(parser, entity, __LINE__);
  6377. entity->open = XML_FALSE;
  6378. result = XML_ERROR_EXTERNAL_ENTITY_HANDLING;
  6379. goto endEntityValue;
  6380. }
  6381. entityTrackingOnClose(parser, entity, __LINE__);
  6382. entity->open = XML_FALSE;
  6383. if (! dtd->paramEntityRead)
  6384. dtd->keepProcessing = dtd->standalone;
  6385. } else
  6386. dtd->keepProcessing = dtd->standalone;
  6387. } else {
  6388. result = processEntity(parser, entity, XML_FALSE, ENTITY_VALUE);
  6389. goto endEntityValue;
  6390. }
  6391. break;
  6392. }
  6393. # endif /* XML_DTD */
  6394. /* In the internal subset, PE references are not legal
  6395. within markup declarations, e.g entity values in this case. */
  6396. parser->m_eventPtr = entityTextPtr;
  6397. result = XML_ERROR_PARAM_ENTITY_REF;
  6398. goto endEntityValue;
  6399. case XML_TOK_NONE:
  6400. result = XML_ERROR_NONE;
  6401. goto endEntityValue;
  6402. case XML_TOK_ENTITY_REF:
  6403. case XML_TOK_DATA_CHARS:
  6404. if (! poolAppend(pool, enc, entityTextPtr, next)) {
  6405. result = XML_ERROR_NO_MEMORY;
  6406. goto endEntityValue;
  6407. }
  6408. break;
  6409. case XML_TOK_TRAILING_CR:
  6410. next = entityTextPtr + enc->minBytesPerChar;
  6411. /* fall through */
  6412. case XML_TOK_DATA_NEWLINE:
  6413. if (pool->end == pool->ptr && ! poolGrow(pool)) {
  6414. result = XML_ERROR_NO_MEMORY;
  6415. goto endEntityValue;
  6416. }
  6417. *(pool->ptr)++ = 0xA;
  6418. break;
  6419. case XML_TOK_CHAR_REF: {
  6420. XML_Char buf[XML_ENCODE_MAX];
  6421. int i;
  6422. int n = XmlCharRefNumber(enc, entityTextPtr);
  6423. if (n < 0) {
  6424. if (enc == parser->m_encoding)
  6425. parser->m_eventPtr = entityTextPtr;
  6426. result = XML_ERROR_BAD_CHAR_REF;
  6427. goto endEntityValue;
  6428. }
  6429. n = XmlEncode(n, (ICHAR *)buf);
  6430. /* The XmlEncode() functions can never return 0 here. That
  6431. * error return happens if the code point passed in is either
  6432. * negative or greater than or equal to 0x110000. The
  6433. * XmlCharRefNumber() functions will all return a number
  6434. * strictly less than 0x110000 or a negative value if an error
  6435. * occurred. The negative value is intercepted above, so
  6436. * XmlEncode() is never passed a value it might return an
  6437. * error for.
  6438. */
  6439. for (i = 0; i < n; i++) {
  6440. if (pool->end == pool->ptr && ! poolGrow(pool)) {
  6441. result = XML_ERROR_NO_MEMORY;
  6442. goto endEntityValue;
  6443. }
  6444. *(pool->ptr)++ = buf[i];
  6445. }
  6446. } break;
  6447. case XML_TOK_PARTIAL:
  6448. if (enc == parser->m_encoding)
  6449. parser->m_eventPtr = entityTextPtr;
  6450. result = XML_ERROR_INVALID_TOKEN;
  6451. goto endEntityValue;
  6452. case XML_TOK_INVALID:
  6453. if (enc == parser->m_encoding)
  6454. parser->m_eventPtr = next;
  6455. result = XML_ERROR_INVALID_TOKEN;
  6456. goto endEntityValue;
  6457. default:
  6458. /* This default case should be unnecessary -- all the tokens
  6459. * that XmlEntityValueTok() can return have their own explicit
  6460. * cases -- but should be retained for safety. We do however
  6461. * exclude it from the coverage statistics.
  6462. *
  6463. * LCOV_EXCL_START
  6464. */
  6465. if (enc == parser->m_encoding)
  6466. parser->m_eventPtr = entityTextPtr;
  6467. result = XML_ERROR_UNEXPECTED_STATE;
  6468. goto endEntityValue;
  6469. /* LCOV_EXCL_STOP */
  6470. }
  6471. entityTextPtr = next;
  6472. }
  6473. endEntityValue:
  6474. # ifdef XML_DTD
  6475. parser->m_prologState.inEntityValue = oldInEntityValue;
  6476. # endif /* XML_DTD */
  6477. // If 'nextPtr' is given, it should be updated during the processing
  6478. if (nextPtr != NULL) {
  6479. *nextPtr = next;
  6480. }
  6481. return result;
  6482. }
  6483. static enum XML_Error
  6484. callStoreEntityValue(XML_Parser parser, const ENCODING *enc,
  6485. const char *entityTextPtr, const char *entityTextEnd,
  6486. enum XML_Account account) {
  6487. const char *next = entityTextPtr;
  6488. enum XML_Error result = XML_ERROR_NONE;
  6489. while (1) {
  6490. if (! parser->m_openValueEntities) {
  6491. result
  6492. = storeEntityValue(parser, enc, next, entityTextEnd, account, &next);
  6493. } else {
  6494. OPEN_INTERNAL_ENTITY *const openEntity = parser->m_openValueEntities;
  6495. if (! openEntity)
  6496. return XML_ERROR_UNEXPECTED_STATE;
  6497. ENTITY *const entity = openEntity->entity;
  6498. const char *const textStart
  6499. = ((const char *)entity->textPtr) + entity->processed;
  6500. const char *const textEnd
  6501. = (const char *)(entity->textPtr + entity->textLen);
  6502. /* Set a safe default value in case 'next' does not get set */
  6503. const char *nextInEntity = textStart;
  6504. if (entity->hasMore) {
  6505. result = storeEntityValue(parser, parser->m_internalEncoding, textStart,
  6506. textEnd, XML_ACCOUNT_ENTITY_EXPANSION,
  6507. &nextInEntity);
  6508. if (result != XML_ERROR_NONE)
  6509. break;
  6510. // Check if entity is complete, if not, mark down how much of it is
  6511. // processed. A XML_SUSPENDED check here is not required as
  6512. // appendAttributeValue will never suspend the parser.
  6513. if (textEnd != nextInEntity) {
  6514. entity->processed
  6515. = (int)(nextInEntity - (const char *)entity->textPtr);
  6516. continue;
  6517. }
  6518. // Entity is complete. We cannot close it here since we need to first
  6519. // process its possible inner entities (which are added to the
  6520. // m_openValueEntities during storeEntityValue)
  6521. entity->hasMore = XML_FALSE;
  6522. continue;
  6523. } // End of entity processing, "if" block skips the rest
  6524. // Remove fully processed openEntity from open entity list.
  6525. # if XML_GE == 1
  6526. entityTrackingOnClose(parser, entity, __LINE__);
  6527. # endif
  6528. // openEntity is m_openValueEntities' head, since we set it at the
  6529. // start of this function and because we skipped storeEntityValue call
  6530. // with hasMore set to false. This means we can directly remove the head
  6531. // of m_openValueEntities
  6532. assert(parser->m_openValueEntities == openEntity);
  6533. entity->open = XML_FALSE;
  6534. parser->m_openValueEntities = parser->m_openValueEntities->next;
  6535. /* put openEntity back in list of free instances */
  6536. openEntity->next = parser->m_freeValueEntities;
  6537. parser->m_freeValueEntities = openEntity;
  6538. }
  6539. // Break if an error occurred or there is nothing left to process
  6540. if (result
  6541. || (parser->m_openValueEntities == NULL && entityTextEnd == next)) {
  6542. break;
  6543. }
  6544. }
  6545. return result;
  6546. }
  6547. #else /* XML_GE == 0 */
  6548. static enum XML_Error
  6549. storeSelfEntityValue(XML_Parser parser, ENTITY *entity) {
  6550. // This will store "&amp;entity123;" in entity->textPtr
  6551. // to end up as "&entity123;" in the handler.
  6552. const char *const entity_start = "&amp;";
  6553. const char *const entity_end = ";";
  6554. STRING_POOL *const pool = &(parser->m_dtd->entityValuePool);
  6555. if (! poolAppendString(pool, entity_start)
  6556. || ! poolAppendString(pool, entity->name)
  6557. || ! poolAppendString(pool, entity_end)) {
  6558. poolDiscard(pool);
  6559. return XML_ERROR_NO_MEMORY;
  6560. }
  6561. entity->textPtr = poolStart(pool);
  6562. entity->textLen = (int)(poolLength(pool));
  6563. poolFinish(pool);
  6564. return XML_ERROR_NONE;
  6565. }
  6566. #endif /* XML_GE == 0 */
  6567. static void FASTCALL
  6568. normalizeLines(XML_Char *s) {
  6569. XML_Char *p;
  6570. for (;; s++) {
  6571. if (*s == XML_T('\0'))
  6572. return;
  6573. if (*s == 0xD)
  6574. break;
  6575. }
  6576. p = s;
  6577. do {
  6578. if (*s == 0xD) {
  6579. *p++ = 0xA;
  6580. if (*++s == 0xA)
  6581. s++;
  6582. } else
  6583. *p++ = *s++;
  6584. } while (*s);
  6585. *p = XML_T('\0');
  6586. }
  6587. static int
  6588. reportProcessingInstruction(XML_Parser parser, const ENCODING *enc,
  6589. const char *start, const char *end) {
  6590. const XML_Char *target;
  6591. XML_Char *data;
  6592. const char *tem;
  6593. if (! parser->m_processingInstructionHandler) {
  6594. if (parser->m_defaultHandler)
  6595. reportDefault(parser, enc, start, end);
  6596. return 1;
  6597. }
  6598. start += enc->minBytesPerChar * 2;
  6599. tem = start + XmlNameLength(enc, start);
  6600. target = poolStoreString(&parser->m_tempPool, enc, start, tem);
  6601. if (! target)
  6602. return 0;
  6603. poolFinish(&parser->m_tempPool);
  6604. data = poolStoreString(&parser->m_tempPool, enc, XmlSkipS(enc, tem),
  6605. end - enc->minBytesPerChar * 2);
  6606. if (! data)
  6607. return 0;
  6608. normalizeLines(data);
  6609. parser->m_processingInstructionHandler(parser->m_handlerArg, target, data);
  6610. poolClear(&parser->m_tempPool);
  6611. return 1;
  6612. }
  6613. static int
  6614. reportComment(XML_Parser parser, const ENCODING *enc, const char *start,
  6615. const char *end) {
  6616. XML_Char *data;
  6617. if (! parser->m_commentHandler) {
  6618. if (parser->m_defaultHandler)
  6619. reportDefault(parser, enc, start, end);
  6620. return 1;
  6621. }
  6622. data = poolStoreString(&parser->m_tempPool, enc,
  6623. start + enc->minBytesPerChar * 4,
  6624. end - enc->minBytesPerChar * 3);
  6625. if (! data)
  6626. return 0;
  6627. normalizeLines(data);
  6628. parser->m_commentHandler(parser->m_handlerArg, data);
  6629. poolClear(&parser->m_tempPool);
  6630. return 1;
  6631. }
  6632. static void
  6633. reportDefault(XML_Parser parser, const ENCODING *enc, const char *s,
  6634. const char *end) {
  6635. if (MUST_CONVERT(enc, s)) {
  6636. enum XML_Convert_Result convert_res;
  6637. const char **eventPP;
  6638. const char **eventEndPP;
  6639. if (enc == parser->m_encoding) {
  6640. eventPP = &parser->m_eventPtr;
  6641. eventEndPP = &parser->m_eventEndPtr;
  6642. } else {
  6643. /* To get here, two things must be true; the parser must be
  6644. * using a character encoding that is not the same as the
  6645. * encoding passed in, and the encoding passed in must need
  6646. * conversion to the internal format (UTF-8 unless XML_UNICODE
  6647. * is defined). The only occasions on which the encoding passed
  6648. * in is not the same as the parser's encoding are when it is
  6649. * the internal encoding (e.g. a previously defined parameter
  6650. * entity, already converted to internal format). This by
  6651. * definition doesn't need conversion, so the whole branch never
  6652. * gets executed.
  6653. *
  6654. * For safety's sake we don't delete these lines and merely
  6655. * exclude them from coverage statistics.
  6656. *
  6657. * LCOV_EXCL_START
  6658. */
  6659. eventPP = &(parser->m_openInternalEntities->internalEventPtr);
  6660. eventEndPP = &(parser->m_openInternalEntities->internalEventEndPtr);
  6661. /* LCOV_EXCL_STOP */
  6662. }
  6663. do {
  6664. ICHAR *dataPtr = (ICHAR *)parser->m_dataBuf;
  6665. convert_res
  6666. = XmlConvert(enc, &s, end, &dataPtr, (ICHAR *)parser->m_dataBufEnd);
  6667. *eventEndPP = s;
  6668. parser->m_defaultHandler(parser->m_handlerArg, parser->m_dataBuf,
  6669. (int)(dataPtr - (ICHAR *)parser->m_dataBuf));
  6670. *eventPP = s;
  6671. } while ((convert_res != XML_CONVERT_COMPLETED)
  6672. && (convert_res != XML_CONVERT_INPUT_INCOMPLETE));
  6673. } else
  6674. parser->m_defaultHandler(
  6675. parser->m_handlerArg, (const XML_Char *)s,
  6676. (int)((const XML_Char *)end - (const XML_Char *)s));
  6677. }
  6678. static int
  6679. defineAttribute(ELEMENT_TYPE *type, ATTRIBUTE_ID *attId, XML_Bool isCdata,
  6680. XML_Bool isId, const XML_Char *value, XML_Parser parser) {
  6681. DEFAULT_ATTRIBUTE *att;
  6682. if (value || isId) {
  6683. /* The handling of default attributes gets messed up if we have
  6684. a default which duplicates a non-default. */
  6685. int i;
  6686. for (i = 0; i < type->nDefaultAtts; i++)
  6687. if (attId == type->defaultAtts[i].id)
  6688. return 1;
  6689. if (isId && ! type->idAtt && ! attId->xmlns)
  6690. type->idAtt = attId;
  6691. }
  6692. if (type->nDefaultAtts == type->allocDefaultAtts) {
  6693. if (type->allocDefaultAtts == 0) {
  6694. type->allocDefaultAtts = 8;
  6695. type->defaultAtts
  6696. = MALLOC(parser, type->allocDefaultAtts * sizeof(DEFAULT_ATTRIBUTE));
  6697. if (! type->defaultAtts) {
  6698. type->allocDefaultAtts = 0;
  6699. return 0;
  6700. }
  6701. } else {
  6702. DEFAULT_ATTRIBUTE *temp;
  6703. /* Detect and prevent integer overflow */
  6704. if (type->allocDefaultAtts > INT_MAX / 2) {
  6705. return 0;
  6706. }
  6707. int count = type->allocDefaultAtts * 2;
  6708. /* Detect and prevent integer overflow.
  6709. * The preprocessor guard addresses the "always false" warning
  6710. * from -Wtype-limits on platforms where
  6711. * sizeof(unsigned int) < sizeof(size_t), e.g. on x86_64. */
  6712. #if UINT_MAX >= SIZE_MAX
  6713. if ((unsigned)count > SIZE_MAX / sizeof(DEFAULT_ATTRIBUTE)) {
  6714. return 0;
  6715. }
  6716. #endif
  6717. temp = REALLOC(parser, type->defaultAtts,
  6718. (count * sizeof(DEFAULT_ATTRIBUTE)));
  6719. if (temp == NULL)
  6720. return 0;
  6721. type->allocDefaultAtts = count;
  6722. type->defaultAtts = temp;
  6723. }
  6724. }
  6725. att = type->defaultAtts + type->nDefaultAtts;
  6726. att->id = attId;
  6727. att->value = value;
  6728. att->isCdata = isCdata;
  6729. if (! isCdata)
  6730. attId->maybeTokenized = XML_TRUE;
  6731. type->nDefaultAtts += 1;
  6732. return 1;
  6733. }
  6734. static int
  6735. setElementTypePrefix(XML_Parser parser, ELEMENT_TYPE *elementType) {
  6736. DTD *const dtd = parser->m_dtd; /* save one level of indirection */
  6737. const XML_Char *name;
  6738. for (name = elementType->name; *name; name++) {
  6739. if (*name == XML_T(ASCII_COLON)) {
  6740. PREFIX *prefix;
  6741. const XML_Char *s;
  6742. for (s = elementType->name; s != name; s++) {
  6743. if (! poolAppendChar(&dtd->pool, *s))
  6744. return 0;
  6745. }
  6746. if (! poolAppendChar(&dtd->pool, XML_T('\0')))
  6747. return 0;
  6748. prefix = (PREFIX *)lookup(parser, &dtd->prefixes, poolStart(&dtd->pool),
  6749. sizeof(PREFIX));
  6750. if (! prefix)
  6751. return 0;
  6752. if (prefix->name == poolStart(&dtd->pool))
  6753. poolFinish(&dtd->pool);
  6754. else
  6755. poolDiscard(&dtd->pool);
  6756. elementType->prefix = prefix;
  6757. break;
  6758. }
  6759. }
  6760. return 1;
  6761. }
  6762. static ATTRIBUTE_ID *
  6763. getAttributeId(XML_Parser parser, const ENCODING *enc, const char *start,
  6764. const char *end) {
  6765. DTD *const dtd = parser->m_dtd; /* save one level of indirection */
  6766. ATTRIBUTE_ID *id;
  6767. const XML_Char *name;
  6768. if (! poolAppendChar(&dtd->pool, XML_T('\0')))
  6769. return NULL;
  6770. name = poolStoreString(&dtd->pool, enc, start, end);
  6771. if (! name)
  6772. return NULL;
  6773. /* skip quotation mark - its storage will be reused (like in name[-1]) */
  6774. ++name;
  6775. id = (ATTRIBUTE_ID *)lookup(parser, &dtd->attributeIds, name,
  6776. sizeof(ATTRIBUTE_ID));
  6777. if (! id)
  6778. return NULL;
  6779. if (id->name != name)
  6780. poolDiscard(&dtd->pool);
  6781. else {
  6782. poolFinish(&dtd->pool);
  6783. if (! parser->m_ns)
  6784. ;
  6785. else if (name[0] == XML_T(ASCII_x) && name[1] == XML_T(ASCII_m)
  6786. && name[2] == XML_T(ASCII_l) && name[3] == XML_T(ASCII_n)
  6787. && name[4] == XML_T(ASCII_s)
  6788. && (name[5] == XML_T('\0') || name[5] == XML_T(ASCII_COLON))) {
  6789. if (name[5] == XML_T('\0'))
  6790. id->prefix = &dtd->defaultPrefix;
  6791. else
  6792. id->prefix = (PREFIX *)lookup(parser, &dtd->prefixes, name + 6,
  6793. sizeof(PREFIX));
  6794. id->xmlns = XML_TRUE;
  6795. } else {
  6796. int i;
  6797. for (i = 0; name[i]; i++) {
  6798. /* attributes without prefix are *not* in the default namespace */
  6799. if (name[i] == XML_T(ASCII_COLON)) {
  6800. int j;
  6801. for (j = 0; j < i; j++) {
  6802. if (! poolAppendChar(&dtd->pool, name[j]))
  6803. return NULL;
  6804. }
  6805. if (! poolAppendChar(&dtd->pool, XML_T('\0')))
  6806. return NULL;
  6807. id->prefix = (PREFIX *)lookup(parser, &dtd->prefixes,
  6808. poolStart(&dtd->pool), sizeof(PREFIX));
  6809. if (! id->prefix)
  6810. return NULL;
  6811. if (id->prefix->name == poolStart(&dtd->pool))
  6812. poolFinish(&dtd->pool);
  6813. else
  6814. poolDiscard(&dtd->pool);
  6815. break;
  6816. }
  6817. }
  6818. }
  6819. }
  6820. return id;
  6821. }
  6822. #define CONTEXT_SEP XML_T(ASCII_FF)
  6823. static const XML_Char *
  6824. getContext(XML_Parser parser) {
  6825. DTD *const dtd = parser->m_dtd; /* save one level of indirection */
  6826. HASH_TABLE_ITER iter;
  6827. XML_Bool needSep = XML_FALSE;
  6828. if (dtd->defaultPrefix.binding) {
  6829. int i;
  6830. int len;
  6831. if (! poolAppendChar(&parser->m_tempPool, XML_T(ASCII_EQUALS)))
  6832. return NULL;
  6833. len = dtd->defaultPrefix.binding->uriLen;
  6834. if (parser->m_namespaceSeparator)
  6835. len--;
  6836. for (i = 0; i < len; i++) {
  6837. if (! poolAppendChar(&parser->m_tempPool,
  6838. dtd->defaultPrefix.binding->uri[i])) {
  6839. /* Because of memory caching, I don't believe this line can be
  6840. * executed.
  6841. *
  6842. * This is part of a loop copying the default prefix binding
  6843. * URI into the parser's temporary string pool. Previously,
  6844. * that URI was copied into the same string pool, with a
  6845. * terminating NUL character, as part of setContext(). When
  6846. * the pool was cleared, that leaves a block definitely big
  6847. * enough to hold the URI on the free block list of the pool.
  6848. * The URI copy in getContext() therefore cannot run out of
  6849. * memory.
  6850. *
  6851. * If the pool is used between the setContext() and
  6852. * getContext() calls, the worst it can do is leave a bigger
  6853. * block on the front of the free list. Given that this is
  6854. * all somewhat inobvious and program logic can be changed, we
  6855. * don't delete the line but we do exclude it from the test
  6856. * coverage statistics.
  6857. */
  6858. return NULL; /* LCOV_EXCL_LINE */
  6859. }
  6860. }
  6861. needSep = XML_TRUE;
  6862. }
  6863. hashTableIterInit(&iter, &(dtd->prefixes));
  6864. for (;;) {
  6865. int i;
  6866. int len;
  6867. const XML_Char *s;
  6868. PREFIX *prefix = (PREFIX *)hashTableIterNext(&iter);
  6869. if (! prefix)
  6870. break;
  6871. if (! prefix->binding) {
  6872. /* This test appears to be (justifiable) paranoia. There does
  6873. * not seem to be a way of injecting a prefix without a binding
  6874. * that doesn't get errored long before this function is called.
  6875. * The test should remain for safety's sake, so we instead
  6876. * exclude the following line from the coverage statistics.
  6877. */
  6878. continue; /* LCOV_EXCL_LINE */
  6879. }
  6880. if (needSep && ! poolAppendChar(&parser->m_tempPool, CONTEXT_SEP))
  6881. return NULL;
  6882. for (s = prefix->name; *s; s++)
  6883. if (! poolAppendChar(&parser->m_tempPool, *s))
  6884. return NULL;
  6885. if (! poolAppendChar(&parser->m_tempPool, XML_T(ASCII_EQUALS)))
  6886. return NULL;
  6887. len = prefix->binding->uriLen;
  6888. if (parser->m_namespaceSeparator)
  6889. len--;
  6890. for (i = 0; i < len; i++)
  6891. if (! poolAppendChar(&parser->m_tempPool, prefix->binding->uri[i]))
  6892. return NULL;
  6893. needSep = XML_TRUE;
  6894. }
  6895. hashTableIterInit(&iter, &(dtd->generalEntities));
  6896. for (;;) {
  6897. const XML_Char *s;
  6898. ENTITY *e = (ENTITY *)hashTableIterNext(&iter);
  6899. if (! e)
  6900. break;
  6901. if (! e->open)
  6902. continue;
  6903. if (needSep && ! poolAppendChar(&parser->m_tempPool, CONTEXT_SEP))
  6904. return NULL;
  6905. for (s = e->name; *s; s++)
  6906. if (! poolAppendChar(&parser->m_tempPool, *s))
  6907. return 0;
  6908. needSep = XML_TRUE;
  6909. }
  6910. if (! poolAppendChar(&parser->m_tempPool, XML_T('\0')))
  6911. return NULL;
  6912. return parser->m_tempPool.start;
  6913. }
  6914. static XML_Bool
  6915. setContext(XML_Parser parser, const XML_Char *context) {
  6916. if (context == NULL) {
  6917. return XML_FALSE;
  6918. }
  6919. DTD *const dtd = parser->m_dtd; /* save one level of indirection */
  6920. const XML_Char *s = context;
  6921. while (*context != XML_T('\0')) {
  6922. if (*s == CONTEXT_SEP || *s == XML_T('\0')) {
  6923. ENTITY *e;
  6924. if (! poolAppendChar(&parser->m_tempPool, XML_T('\0')))
  6925. return XML_FALSE;
  6926. e = (ENTITY *)lookup(parser, &dtd->generalEntities,
  6927. poolStart(&parser->m_tempPool), 0);
  6928. if (e)
  6929. e->open = XML_TRUE;
  6930. if (*s != XML_T('\0'))
  6931. s++;
  6932. context = s;
  6933. poolDiscard(&parser->m_tempPool);
  6934. } else if (*s == XML_T(ASCII_EQUALS)) {
  6935. PREFIX *prefix;
  6936. if (poolLength(&parser->m_tempPool) == 0)
  6937. prefix = &dtd->defaultPrefix;
  6938. else {
  6939. if (! poolAppendChar(&parser->m_tempPool, XML_T('\0')))
  6940. return XML_FALSE;
  6941. const XML_Char *const prefixName = poolCopyStringNoFinish(
  6942. &dtd->pool, poolStart(&parser->m_tempPool));
  6943. if (! prefixName) {
  6944. return XML_FALSE;
  6945. }
  6946. prefix = (PREFIX *)lookup(parser, &dtd->prefixes, prefixName,
  6947. sizeof(PREFIX));
  6948. const bool prefixNameUsed = prefix && prefix->name == prefixName;
  6949. if (prefixNameUsed)
  6950. poolFinish(&dtd->pool);
  6951. else
  6952. poolDiscard(&dtd->pool);
  6953. if (! prefix)
  6954. return XML_FALSE;
  6955. poolDiscard(&parser->m_tempPool);
  6956. }
  6957. for (context = s + 1; *context != CONTEXT_SEP && *context != XML_T('\0');
  6958. context++)
  6959. if (! poolAppendChar(&parser->m_tempPool, *context))
  6960. return XML_FALSE;
  6961. if (! poolAppendChar(&parser->m_tempPool, XML_T('\0')))
  6962. return XML_FALSE;
  6963. if (addBinding(parser, prefix, NULL, poolStart(&parser->m_tempPool),
  6964. &parser->m_inheritedBindings)
  6965. != XML_ERROR_NONE)
  6966. return XML_FALSE;
  6967. poolDiscard(&parser->m_tempPool);
  6968. if (*context != XML_T('\0'))
  6969. ++context;
  6970. s = context;
  6971. } else {
  6972. if (! poolAppendChar(&parser->m_tempPool, *s))
  6973. return XML_FALSE;
  6974. s++;
  6975. }
  6976. }
  6977. return XML_TRUE;
  6978. }
  6979. static void FASTCALL
  6980. normalizePublicId(XML_Char *publicId) {
  6981. XML_Char *p = publicId;
  6982. XML_Char *s;
  6983. for (s = publicId; *s; s++) {
  6984. switch (*s) {
  6985. case 0x20:
  6986. case 0xD:
  6987. case 0xA:
  6988. if (p != publicId && p[-1] != 0x20)
  6989. *p++ = 0x20;
  6990. break;
  6991. default:
  6992. *p++ = *s;
  6993. }
  6994. }
  6995. if (p != publicId && p[-1] == 0x20)
  6996. --p;
  6997. *p = XML_T('\0');
  6998. }
  6999. static DTD *
  7000. dtdCreate(XML_Parser parser) {
  7001. DTD *p = MALLOC(parser, sizeof(DTD));
  7002. if (p == NULL)
  7003. return p;
  7004. poolInit(&(p->pool), parser);
  7005. poolInit(&(p->entityValuePool), parser);
  7006. hashTableInit(&(p->generalEntities), parser);
  7007. hashTableInit(&(p->elementTypes), parser);
  7008. hashTableInit(&(p->attributeIds), parser);
  7009. hashTableInit(&(p->prefixes), parser);
  7010. #ifdef XML_DTD
  7011. p->paramEntityRead = XML_FALSE;
  7012. hashTableInit(&(p->paramEntities), parser);
  7013. #endif /* XML_DTD */
  7014. p->defaultPrefix.name = NULL;
  7015. p->defaultPrefix.binding = NULL;
  7016. p->in_eldecl = XML_FALSE;
  7017. p->scaffIndex = NULL;
  7018. p->scaffold = NULL;
  7019. p->scaffLevel = 0;
  7020. p->scaffSize = 0;
  7021. p->scaffCount = 0;
  7022. p->contentStringLen = 0;
  7023. p->keepProcessing = XML_TRUE;
  7024. p->hasParamEntityRefs = XML_FALSE;
  7025. p->standalone = XML_FALSE;
  7026. return p;
  7027. }
  7028. static void
  7029. dtdReset(DTD *p, XML_Parser parser) {
  7030. HASH_TABLE_ITER iter;
  7031. hashTableIterInit(&iter, &(p->elementTypes));
  7032. for (;;) {
  7033. ELEMENT_TYPE *e = (ELEMENT_TYPE *)hashTableIterNext(&iter);
  7034. if (! e)
  7035. break;
  7036. if (e->allocDefaultAtts != 0)
  7037. FREE(parser, e->defaultAtts);
  7038. }
  7039. hashTableClear(&(p->generalEntities));
  7040. #ifdef XML_DTD
  7041. p->paramEntityRead = XML_FALSE;
  7042. hashTableClear(&(p->paramEntities));
  7043. #endif /* XML_DTD */
  7044. hashTableClear(&(p->elementTypes));
  7045. hashTableClear(&(p->attributeIds));
  7046. hashTableClear(&(p->prefixes));
  7047. poolClear(&(p->pool));
  7048. poolClear(&(p->entityValuePool));
  7049. p->defaultPrefix.name = NULL;
  7050. p->defaultPrefix.binding = NULL;
  7051. p->in_eldecl = XML_FALSE;
  7052. FREE(parser, p->scaffIndex);
  7053. p->scaffIndex = NULL;
  7054. FREE(parser, p->scaffold);
  7055. p->scaffold = NULL;
  7056. p->scaffLevel = 0;
  7057. p->scaffSize = 0;
  7058. p->scaffCount = 0;
  7059. p->contentStringLen = 0;
  7060. p->keepProcessing = XML_TRUE;
  7061. p->hasParamEntityRefs = XML_FALSE;
  7062. p->standalone = XML_FALSE;
  7063. }
  7064. static void
  7065. dtdDestroy(DTD *p, XML_Bool isDocEntity, XML_Parser parser) {
  7066. HASH_TABLE_ITER iter;
  7067. hashTableIterInit(&iter, &(p->elementTypes));
  7068. for (;;) {
  7069. ELEMENT_TYPE *e = (ELEMENT_TYPE *)hashTableIterNext(&iter);
  7070. if (! e)
  7071. break;
  7072. if (e->allocDefaultAtts != 0)
  7073. FREE(parser, e->defaultAtts);
  7074. }
  7075. hashTableDestroy(&(p->generalEntities));
  7076. #ifdef XML_DTD
  7077. hashTableDestroy(&(p->paramEntities));
  7078. #endif /* XML_DTD */
  7079. hashTableDestroy(&(p->elementTypes));
  7080. hashTableDestroy(&(p->attributeIds));
  7081. hashTableDestroy(&(p->prefixes));
  7082. poolDestroy(&(p->pool));
  7083. poolDestroy(&(p->entityValuePool));
  7084. if (isDocEntity) {
  7085. FREE(parser, p->scaffIndex);
  7086. FREE(parser, p->scaffold);
  7087. }
  7088. FREE(parser, p);
  7089. }
  7090. /* Do a deep copy of the DTD. Return 0 for out of memory, non-zero otherwise.
  7091. The new DTD has already been initialized.
  7092. */
  7093. static int
  7094. dtdCopy(XML_Parser oldParser, DTD *newDtd, const DTD *oldDtd,
  7095. XML_Parser parser) {
  7096. HASH_TABLE_ITER iter;
  7097. /* Copy the prefix table. */
  7098. hashTableIterInit(&iter, &(oldDtd->prefixes));
  7099. for (;;) {
  7100. const XML_Char *name;
  7101. const PREFIX *oldP = (PREFIX *)hashTableIterNext(&iter);
  7102. if (! oldP)
  7103. break;
  7104. name = poolCopyString(&(newDtd->pool), oldP->name);
  7105. if (! name)
  7106. return 0;
  7107. if (! lookup(oldParser, &(newDtd->prefixes), name, sizeof(PREFIX)))
  7108. return 0;
  7109. }
  7110. hashTableIterInit(&iter, &(oldDtd->attributeIds));
  7111. /* Copy the attribute id table. */
  7112. for (;;) {
  7113. ATTRIBUTE_ID *newA;
  7114. const XML_Char *name;
  7115. const ATTRIBUTE_ID *oldA = (ATTRIBUTE_ID *)hashTableIterNext(&iter);
  7116. if (! oldA)
  7117. break;
  7118. /* Remember to allocate the scratch byte before the name. */
  7119. if (! poolAppendChar(&(newDtd->pool), XML_T('\0')))
  7120. return 0;
  7121. name = poolCopyString(&(newDtd->pool), oldA->name);
  7122. if (! name)
  7123. return 0;
  7124. ++name;
  7125. newA = (ATTRIBUTE_ID *)lookup(oldParser, &(newDtd->attributeIds), name,
  7126. sizeof(ATTRIBUTE_ID));
  7127. if (! newA)
  7128. return 0;
  7129. newA->maybeTokenized = oldA->maybeTokenized;
  7130. if (oldA->prefix) {
  7131. newA->xmlns = oldA->xmlns;
  7132. if (oldA->prefix == &oldDtd->defaultPrefix)
  7133. newA->prefix = &newDtd->defaultPrefix;
  7134. else
  7135. newA->prefix = (PREFIX *)lookup(oldParser, &(newDtd->prefixes),
  7136. oldA->prefix->name, 0);
  7137. }
  7138. }
  7139. /* Copy the element type table. */
  7140. hashTableIterInit(&iter, &(oldDtd->elementTypes));
  7141. for (;;) {
  7142. int i;
  7143. ELEMENT_TYPE *newE;
  7144. const XML_Char *name;
  7145. const ELEMENT_TYPE *oldE = (ELEMENT_TYPE *)hashTableIterNext(&iter);
  7146. if (! oldE)
  7147. break;
  7148. name = poolCopyString(&(newDtd->pool), oldE->name);
  7149. if (! name)
  7150. return 0;
  7151. newE = (ELEMENT_TYPE *)lookup(oldParser, &(newDtd->elementTypes), name,
  7152. sizeof(ELEMENT_TYPE));
  7153. if (! newE)
  7154. return 0;
  7155. if (oldE->nDefaultAtts) {
  7156. /* Detect and prevent integer overflow.
  7157. * The preprocessor guard addresses the "always false" warning
  7158. * from -Wtype-limits on platforms where
  7159. * sizeof(int) < sizeof(size_t), e.g. on x86_64. */
  7160. #if UINT_MAX >= SIZE_MAX
  7161. if ((size_t)oldE->nDefaultAtts > SIZE_MAX / sizeof(DEFAULT_ATTRIBUTE)) {
  7162. return 0;
  7163. }
  7164. #endif
  7165. newE->defaultAtts
  7166. = MALLOC(parser, oldE->nDefaultAtts * sizeof(DEFAULT_ATTRIBUTE));
  7167. if (! newE->defaultAtts) {
  7168. return 0;
  7169. }
  7170. }
  7171. if (oldE->idAtt)
  7172. newE->idAtt = (ATTRIBUTE_ID *)lookup(oldParser, &(newDtd->attributeIds),
  7173. oldE->idAtt->name, 0);
  7174. newE->allocDefaultAtts = newE->nDefaultAtts = oldE->nDefaultAtts;
  7175. if (oldE->prefix)
  7176. newE->prefix = (PREFIX *)lookup(oldParser, &(newDtd->prefixes),
  7177. oldE->prefix->name, 0);
  7178. for (i = 0; i < newE->nDefaultAtts; i++) {
  7179. newE->defaultAtts[i].id = (ATTRIBUTE_ID *)lookup(
  7180. oldParser, &(newDtd->attributeIds), oldE->defaultAtts[i].id->name, 0);
  7181. newE->defaultAtts[i].isCdata = oldE->defaultAtts[i].isCdata;
  7182. if (oldE->defaultAtts[i].value) {
  7183. newE->defaultAtts[i].value
  7184. = poolCopyString(&(newDtd->pool), oldE->defaultAtts[i].value);
  7185. if (! newE->defaultAtts[i].value)
  7186. return 0;
  7187. } else
  7188. newE->defaultAtts[i].value = NULL;
  7189. }
  7190. }
  7191. /* Copy the entity tables. */
  7192. if (! copyEntityTable(oldParser, &(newDtd->generalEntities), &(newDtd->pool),
  7193. &(oldDtd->generalEntities)))
  7194. return 0;
  7195. #ifdef XML_DTD
  7196. if (! copyEntityTable(oldParser, &(newDtd->paramEntities), &(newDtd->pool),
  7197. &(oldDtd->paramEntities)))
  7198. return 0;
  7199. newDtd->paramEntityRead = oldDtd->paramEntityRead;
  7200. #endif /* XML_DTD */
  7201. newDtd->keepProcessing = oldDtd->keepProcessing;
  7202. newDtd->hasParamEntityRefs = oldDtd->hasParamEntityRefs;
  7203. newDtd->standalone = oldDtd->standalone;
  7204. /* Don't want deep copying for scaffolding */
  7205. newDtd->in_eldecl = oldDtd->in_eldecl;
  7206. newDtd->scaffold = oldDtd->scaffold;
  7207. newDtd->contentStringLen = oldDtd->contentStringLen;
  7208. newDtd->scaffSize = oldDtd->scaffSize;
  7209. newDtd->scaffLevel = oldDtd->scaffLevel;
  7210. newDtd->scaffIndex = oldDtd->scaffIndex;
  7211. return 1;
  7212. } /* End dtdCopy */
  7213. static int
  7214. copyEntityTable(XML_Parser oldParser, HASH_TABLE *newTable,
  7215. STRING_POOL *newPool, const HASH_TABLE *oldTable) {
  7216. HASH_TABLE_ITER iter;
  7217. const XML_Char *cachedOldBase = NULL;
  7218. const XML_Char *cachedNewBase = NULL;
  7219. hashTableIterInit(&iter, oldTable);
  7220. for (;;) {
  7221. ENTITY *newE;
  7222. const XML_Char *name;
  7223. const ENTITY *oldE = (ENTITY *)hashTableIterNext(&iter);
  7224. if (! oldE)
  7225. break;
  7226. name = poolCopyString(newPool, oldE->name);
  7227. if (! name)
  7228. return 0;
  7229. newE = (ENTITY *)lookup(oldParser, newTable, name, sizeof(ENTITY));
  7230. if (! newE)
  7231. return 0;
  7232. if (oldE->systemId) {
  7233. const XML_Char *tem = poolCopyString(newPool, oldE->systemId);
  7234. if (! tem)
  7235. return 0;
  7236. newE->systemId = tem;
  7237. if (oldE->base) {
  7238. if (oldE->base == cachedOldBase)
  7239. newE->base = cachedNewBase;
  7240. else {
  7241. cachedOldBase = oldE->base;
  7242. tem = poolCopyString(newPool, cachedOldBase);
  7243. if (! tem)
  7244. return 0;
  7245. cachedNewBase = newE->base = tem;
  7246. }
  7247. }
  7248. if (oldE->publicId) {
  7249. tem = poolCopyString(newPool, oldE->publicId);
  7250. if (! tem)
  7251. return 0;
  7252. newE->publicId = tem;
  7253. }
  7254. } else {
  7255. const XML_Char *tem
  7256. = poolCopyStringN(newPool, oldE->textPtr, oldE->textLen);
  7257. if (! tem)
  7258. return 0;
  7259. newE->textPtr = tem;
  7260. newE->textLen = oldE->textLen;
  7261. }
  7262. if (oldE->notation) {
  7263. const XML_Char *tem = poolCopyString(newPool, oldE->notation);
  7264. if (! tem)
  7265. return 0;
  7266. newE->notation = tem;
  7267. }
  7268. newE->is_param = oldE->is_param;
  7269. newE->is_internal = oldE->is_internal;
  7270. }
  7271. return 1;
  7272. }
  7273. #define INIT_POWER 6
  7274. static XML_Bool FASTCALL
  7275. keyeq(KEY s1, KEY s2) {
  7276. for (; *s1 == *s2; s1++, s2++)
  7277. if (*s1 == 0)
  7278. return XML_TRUE;
  7279. return XML_FALSE;
  7280. }
  7281. static size_t
  7282. keylen(KEY s) {
  7283. size_t len = 0;
  7284. for (; *s; s++, len++)
  7285. ;
  7286. return len;
  7287. }
  7288. static void
  7289. copy_salt_to_sipkey(XML_Parser parser, struct sipkey *key) {
  7290. key->k[0] = 0;
  7291. key->k[1] = get_hash_secret_salt(parser);
  7292. }
  7293. static unsigned long FASTCALL
  7294. hash(XML_Parser parser, KEY s) {
  7295. struct siphash state;
  7296. struct sipkey key;
  7297. (void)sip24_valid;
  7298. copy_salt_to_sipkey(parser, &key);
  7299. sip24_init(&state, &key);
  7300. sip24_update(&state, s, keylen(s) * sizeof(XML_Char));
  7301. return (unsigned long)sip24_final(&state);
  7302. }
  7303. static NAMED *
  7304. lookup(XML_Parser parser, HASH_TABLE *table, KEY name, size_t createSize) {
  7305. size_t i;
  7306. if (table->size == 0) {
  7307. size_t tsize;
  7308. if (! createSize)
  7309. return NULL;
  7310. table->power = INIT_POWER;
  7311. /* table->size is a power of 2 */
  7312. table->size = (size_t)1 << INIT_POWER;
  7313. tsize = table->size * sizeof(NAMED *);
  7314. table->v = MALLOC(table->parser, tsize);
  7315. if (! table->v) {
  7316. table->size = 0;
  7317. return NULL;
  7318. }
  7319. memset(table->v, 0, tsize);
  7320. i = hash(parser, name) & ((unsigned long)table->size - 1);
  7321. } else {
  7322. unsigned long h = hash(parser, name);
  7323. unsigned long mask = (unsigned long)table->size - 1;
  7324. unsigned char step = 0;
  7325. i = h & mask;
  7326. while (table->v[i]) {
  7327. if (keyeq(name, table->v[i]->name))
  7328. return table->v[i];
  7329. if (! step)
  7330. step = PROBE_STEP(h, mask, table->power);
  7331. i < step ? (i += table->size - step) : (i -= step);
  7332. }
  7333. if (! createSize)
  7334. return NULL;
  7335. /* check for overflow (table is half full) */
  7336. if (table->used >> (table->power - 1)) {
  7337. unsigned char newPower = table->power + 1;
  7338. /* Detect and prevent invalid shift */
  7339. if (newPower >= sizeof(unsigned long) * 8 /* bits per byte */) {
  7340. return NULL;
  7341. }
  7342. size_t newSize = (size_t)1 << newPower;
  7343. unsigned long newMask = (unsigned long)newSize - 1;
  7344. /* Detect and prevent integer overflow */
  7345. if (newSize > SIZE_MAX / sizeof(NAMED *)) {
  7346. return NULL;
  7347. }
  7348. size_t tsize = newSize * sizeof(NAMED *);
  7349. NAMED **newV = MALLOC(table->parser, tsize);
  7350. if (! newV)
  7351. return NULL;
  7352. memset(newV, 0, tsize);
  7353. for (i = 0; i < table->size; i++)
  7354. if (table->v[i]) {
  7355. unsigned long newHash = hash(parser, table->v[i]->name);
  7356. size_t j = newHash & newMask;
  7357. step = 0;
  7358. while (newV[j]) {
  7359. if (! step)
  7360. step = PROBE_STEP(newHash, newMask, newPower);
  7361. j < step ? (j += newSize - step) : (j -= step);
  7362. }
  7363. newV[j] = table->v[i];
  7364. }
  7365. FREE(table->parser, table->v);
  7366. table->v = newV;
  7367. table->power = newPower;
  7368. table->size = newSize;
  7369. i = h & newMask;
  7370. step = 0;
  7371. while (table->v[i]) {
  7372. if (! step)
  7373. step = PROBE_STEP(h, newMask, newPower);
  7374. i < step ? (i += newSize - step) : (i -= step);
  7375. }
  7376. }
  7377. }
  7378. table->v[i] = MALLOC(table->parser, createSize);
  7379. if (! table->v[i])
  7380. return NULL;
  7381. memset(table->v[i], 0, createSize);
  7382. table->v[i]->name = name;
  7383. (table->used)++;
  7384. return table->v[i];
  7385. }
  7386. static void FASTCALL
  7387. hashTableClear(HASH_TABLE *table) {
  7388. size_t i;
  7389. for (i = 0; i < table->size; i++) {
  7390. FREE(table->parser, table->v[i]);
  7391. table->v[i] = NULL;
  7392. }
  7393. table->used = 0;
  7394. }
  7395. static void FASTCALL
  7396. hashTableDestroy(HASH_TABLE *table) {
  7397. size_t i;
  7398. for (i = 0; i < table->size; i++)
  7399. FREE(table->parser, table->v[i]);
  7400. FREE(table->parser, table->v);
  7401. }
  7402. static void FASTCALL
  7403. hashTableInit(HASH_TABLE *p, XML_Parser parser) {
  7404. p->power = 0;
  7405. p->size = 0;
  7406. p->used = 0;
  7407. p->v = NULL;
  7408. p->parser = parser;
  7409. }
  7410. static void FASTCALL
  7411. hashTableIterInit(HASH_TABLE_ITER *iter, const HASH_TABLE *table) {
  7412. iter->p = table->v;
  7413. iter->end = iter->p ? iter->p + table->size : NULL;
  7414. }
  7415. static NAMED *FASTCALL
  7416. hashTableIterNext(HASH_TABLE_ITER *iter) {
  7417. while (iter->p != iter->end) {
  7418. NAMED *tem = *(iter->p)++;
  7419. if (tem)
  7420. return tem;
  7421. }
  7422. return NULL;
  7423. }
  7424. static void FASTCALL
  7425. poolInit(STRING_POOL *pool, XML_Parser parser) {
  7426. pool->blocks = NULL;
  7427. pool->freeBlocks = NULL;
  7428. pool->start = NULL;
  7429. pool->ptr = NULL;
  7430. pool->end = NULL;
  7431. pool->parser = parser;
  7432. }
  7433. static void FASTCALL
  7434. poolClear(STRING_POOL *pool) {
  7435. if (! pool->freeBlocks)
  7436. pool->freeBlocks = pool->blocks;
  7437. else {
  7438. BLOCK *p = pool->blocks;
  7439. while (p) {
  7440. BLOCK *tem = p->next;
  7441. p->next = pool->freeBlocks;
  7442. pool->freeBlocks = p;
  7443. p = tem;
  7444. }
  7445. }
  7446. pool->blocks = NULL;
  7447. pool->start = NULL;
  7448. pool->ptr = NULL;
  7449. pool->end = NULL;
  7450. }
  7451. static void FASTCALL
  7452. poolDestroy(STRING_POOL *pool) {
  7453. BLOCK *p = pool->blocks;
  7454. while (p) {
  7455. BLOCK *tem = p->next;
  7456. FREE(pool->parser, p);
  7457. p = tem;
  7458. }
  7459. p = pool->freeBlocks;
  7460. while (p) {
  7461. BLOCK *tem = p->next;
  7462. FREE(pool->parser, p);
  7463. p = tem;
  7464. }
  7465. }
  7466. static XML_Char *
  7467. poolAppend(STRING_POOL *pool, const ENCODING *enc, const char *ptr,
  7468. const char *end) {
  7469. if (! pool->ptr && ! poolGrow(pool))
  7470. return NULL;
  7471. for (;;) {
  7472. const enum XML_Convert_Result convert_res = XmlConvert(
  7473. enc, &ptr, end, (ICHAR **)&(pool->ptr), (const ICHAR *)pool->end);
  7474. if ((convert_res == XML_CONVERT_COMPLETED)
  7475. || (convert_res == XML_CONVERT_INPUT_INCOMPLETE))
  7476. break;
  7477. if (! poolGrow(pool))
  7478. return NULL;
  7479. }
  7480. return pool->start;
  7481. }
  7482. static const XML_Char *FASTCALL
  7483. poolCopyString(STRING_POOL *pool, const XML_Char *s) {
  7484. do {
  7485. if (! poolAppendChar(pool, *s))
  7486. return NULL;
  7487. } while (*s++);
  7488. s = pool->start;
  7489. poolFinish(pool);
  7490. return s;
  7491. }
  7492. // A version of `poolCopyString` that does not call `poolFinish`
  7493. // and reverts any partial advancement upon failure.
  7494. static const XML_Char *FASTCALL
  7495. poolCopyStringNoFinish(STRING_POOL *pool, const XML_Char *s) {
  7496. const XML_Char *const original = s;
  7497. do {
  7498. if (! poolAppendChar(pool, *s)) {
  7499. // Revert any previously successful advancement
  7500. const ptrdiff_t advancedBy = s - original;
  7501. if (advancedBy > 0)
  7502. pool->ptr -= advancedBy;
  7503. return NULL;
  7504. }
  7505. } while (*s++);
  7506. return pool->start;
  7507. }
  7508. static const XML_Char *
  7509. poolCopyStringN(STRING_POOL *pool, const XML_Char *s, int n) {
  7510. if (! pool->ptr && ! poolGrow(pool)) {
  7511. /* The following line is unreachable given the current usage of
  7512. * poolCopyStringN(). Currently it is called from exactly one
  7513. * place to copy the text of a simple general entity. By that
  7514. * point, the name of the entity is already stored in the pool, so
  7515. * pool->ptr cannot be NULL.
  7516. *
  7517. * If poolCopyStringN() is used elsewhere as it well might be,
  7518. * this line may well become executable again. Regardless, this
  7519. * sort of check shouldn't be removed lightly, so we just exclude
  7520. * it from the coverage statistics.
  7521. */
  7522. return NULL; /* LCOV_EXCL_LINE */
  7523. }
  7524. for (; n > 0; --n, s++) {
  7525. if (! poolAppendChar(pool, *s))
  7526. return NULL;
  7527. }
  7528. s = pool->start;
  7529. poolFinish(pool);
  7530. return s;
  7531. }
  7532. static const XML_Char *FASTCALL
  7533. poolAppendString(STRING_POOL *pool, const XML_Char *s) {
  7534. while (*s) {
  7535. if (! poolAppendChar(pool, *s))
  7536. return NULL;
  7537. s++;
  7538. }
  7539. return pool->start;
  7540. }
  7541. static XML_Char *
  7542. poolStoreString(STRING_POOL *pool, const ENCODING *enc, const char *ptr,
  7543. const char *end) {
  7544. if (! poolAppend(pool, enc, ptr, end))
  7545. return NULL;
  7546. if (pool->ptr == pool->end && ! poolGrow(pool))
  7547. return NULL;
  7548. *(pool->ptr)++ = 0;
  7549. return pool->start;
  7550. }
  7551. static size_t
  7552. poolBytesToAllocateFor(int blockSize) {
  7553. /* Unprotected math would be:
  7554. ** return offsetof(BLOCK, s) + blockSize * sizeof(XML_Char);
  7555. **
  7556. ** Detect overflow, avoiding _signed_ overflow undefined behavior
  7557. ** For a + b * c we check b * c in isolation first, so that addition of a
  7558. ** on top has no chance of making us accept a small non-negative number
  7559. */
  7560. const size_t stretch = sizeof(XML_Char); /* can be 4 bytes */
  7561. if (blockSize <= 0)
  7562. return 0;
  7563. if (blockSize > (int)(INT_MAX / stretch))
  7564. return 0;
  7565. {
  7566. const int stretchedBlockSize = blockSize * (int)stretch;
  7567. const int bytesToAllocate
  7568. = (int)(offsetof(BLOCK, s) + (unsigned)stretchedBlockSize);
  7569. if (bytesToAllocate < 0)
  7570. return 0;
  7571. return (size_t)bytesToAllocate;
  7572. }
  7573. }
  7574. static XML_Bool FASTCALL
  7575. poolGrow(STRING_POOL *pool) {
  7576. if (pool->freeBlocks) {
  7577. if (pool->start == NULL) {
  7578. pool->blocks = pool->freeBlocks;
  7579. pool->freeBlocks = pool->freeBlocks->next;
  7580. pool->blocks->next = NULL;
  7581. pool->start = pool->blocks->s;
  7582. pool->end = pool->start + pool->blocks->size;
  7583. pool->ptr = pool->start;
  7584. return XML_TRUE;
  7585. }
  7586. if (pool->end - pool->start < pool->freeBlocks->size) {
  7587. BLOCK *tem = pool->freeBlocks->next;
  7588. pool->freeBlocks->next = pool->blocks;
  7589. pool->blocks = pool->freeBlocks;
  7590. pool->freeBlocks = tem;
  7591. memcpy(pool->blocks->s, pool->start,
  7592. (pool->end - pool->start) * sizeof(XML_Char));
  7593. pool->ptr = pool->blocks->s + (pool->ptr - pool->start);
  7594. pool->start = pool->blocks->s;
  7595. pool->end = pool->start + pool->blocks->size;
  7596. return XML_TRUE;
  7597. }
  7598. }
  7599. if (pool->blocks && pool->start == pool->blocks->s) {
  7600. BLOCK *temp;
  7601. int blockSize = (int)((unsigned)(pool->end - pool->start) * 2U);
  7602. size_t bytesToAllocate;
  7603. /* NOTE: Needs to be calculated prior to calling `realloc`
  7604. to avoid dangling pointers: */
  7605. const ptrdiff_t offsetInsideBlock = pool->ptr - pool->start;
  7606. if (blockSize < 0) {
  7607. /* This condition traps a situation where either more than
  7608. * INT_MAX/2 bytes have already been allocated. This isn't
  7609. * readily testable, since it is unlikely that an average
  7610. * machine will have that much memory, so we exclude it from the
  7611. * coverage statistics.
  7612. */
  7613. return XML_FALSE; /* LCOV_EXCL_LINE */
  7614. }
  7615. bytesToAllocate = poolBytesToAllocateFor(blockSize);
  7616. if (bytesToAllocate == 0)
  7617. return XML_FALSE;
  7618. temp = REALLOC(pool->parser, pool->blocks, bytesToAllocate);
  7619. if (temp == NULL)
  7620. return XML_FALSE;
  7621. pool->blocks = temp;
  7622. pool->blocks->size = blockSize;
  7623. pool->ptr = pool->blocks->s + offsetInsideBlock;
  7624. pool->start = pool->blocks->s;
  7625. pool->end = pool->start + blockSize;
  7626. } else {
  7627. BLOCK *tem;
  7628. int blockSize = (int)(pool->end - pool->start);
  7629. size_t bytesToAllocate;
  7630. if (blockSize < 0) {
  7631. /* This condition traps a situation where either more than
  7632. * INT_MAX bytes have already been allocated (which is prevented
  7633. * by various pieces of program logic, not least this one, never
  7634. * mind the unlikelihood of actually having that much memory) or
  7635. * the pool control fields have been corrupted (which could
  7636. * conceivably happen in an extremely buggy user handler
  7637. * function). Either way it isn't readily testable, so we
  7638. * exclude it from the coverage statistics.
  7639. */
  7640. return XML_FALSE; /* LCOV_EXCL_LINE */
  7641. }
  7642. if (blockSize < INIT_BLOCK_SIZE)
  7643. blockSize = INIT_BLOCK_SIZE;
  7644. else {
  7645. /* Detect overflow, avoiding _signed_ overflow undefined behavior */
  7646. if ((int)((unsigned)blockSize * 2U) < 0) {
  7647. return XML_FALSE;
  7648. }
  7649. blockSize *= 2;
  7650. }
  7651. bytesToAllocate = poolBytesToAllocateFor(blockSize);
  7652. if (bytesToAllocate == 0)
  7653. return XML_FALSE;
  7654. tem = MALLOC(pool->parser, bytesToAllocate);
  7655. if (! tem)
  7656. return XML_FALSE;
  7657. tem->size = blockSize;
  7658. tem->next = pool->blocks;
  7659. pool->blocks = tem;
  7660. if (pool->ptr != pool->start)
  7661. memcpy(tem->s, pool->start, (pool->ptr - pool->start) * sizeof(XML_Char));
  7662. pool->ptr = tem->s + (pool->ptr - pool->start);
  7663. pool->start = tem->s;
  7664. pool->end = tem->s + blockSize;
  7665. }
  7666. return XML_TRUE;
  7667. }
  7668. static int FASTCALL
  7669. nextScaffoldPart(XML_Parser parser) {
  7670. DTD *const dtd = parser->m_dtd; /* save one level of indirection */
  7671. CONTENT_SCAFFOLD *me;
  7672. int next;
  7673. if (! dtd->scaffIndex) {
  7674. /* Detect and prevent integer overflow.
  7675. * The preprocessor guard addresses the "always false" warning
  7676. * from -Wtype-limits on platforms where
  7677. * sizeof(unsigned int) < sizeof(size_t), e.g. on x86_64. */
  7678. #if UINT_MAX >= SIZE_MAX
  7679. if (parser->m_groupSize > SIZE_MAX / sizeof(int)) {
  7680. return -1;
  7681. }
  7682. #endif
  7683. dtd->scaffIndex = MALLOC(parser, parser->m_groupSize * sizeof(int));
  7684. if (! dtd->scaffIndex)
  7685. return -1;
  7686. dtd->scaffIndex[0] = 0;
  7687. }
  7688. // Will casting to int be safe further down?
  7689. if (dtd->scaffCount > INT_MAX) {
  7690. return -1;
  7691. }
  7692. if (dtd->scaffCount >= dtd->scaffSize) {
  7693. CONTENT_SCAFFOLD *temp;
  7694. if (dtd->scaffold) {
  7695. /* Detect and prevent integer overflow */
  7696. if (dtd->scaffSize > UINT_MAX / 2u) {
  7697. return -1;
  7698. }
  7699. /* Detect and prevent integer overflow.
  7700. * The preprocessor guard addresses the "always false" warning
  7701. * from -Wtype-limits on platforms where
  7702. * sizeof(unsigned int) < sizeof(size_t), e.g. on x86_64. */
  7703. #if UINT_MAX >= SIZE_MAX
  7704. if (dtd->scaffSize > SIZE_MAX / 2u / sizeof(CONTENT_SCAFFOLD)) {
  7705. return -1;
  7706. }
  7707. #endif
  7708. temp = REALLOC(parser, dtd->scaffold,
  7709. dtd->scaffSize * 2 * sizeof(CONTENT_SCAFFOLD));
  7710. if (temp == NULL)
  7711. return -1;
  7712. dtd->scaffSize *= 2;
  7713. } else {
  7714. temp = MALLOC(parser, INIT_SCAFFOLD_ELEMENTS * sizeof(CONTENT_SCAFFOLD));
  7715. if (temp == NULL)
  7716. return -1;
  7717. dtd->scaffSize = INIT_SCAFFOLD_ELEMENTS;
  7718. }
  7719. dtd->scaffold = temp;
  7720. }
  7721. next = (int)dtd->scaffCount++;
  7722. me = &dtd->scaffold[next];
  7723. if (dtd->scaffLevel) {
  7724. CONTENT_SCAFFOLD *parent
  7725. = &dtd->scaffold[dtd->scaffIndex[dtd->scaffLevel - 1]];
  7726. if (parent->lastchild) {
  7727. dtd->scaffold[parent->lastchild].nextsib = next;
  7728. }
  7729. if (! parent->childcnt)
  7730. parent->firstchild = next;
  7731. parent->lastchild = next;
  7732. parent->childcnt++;
  7733. }
  7734. me->firstchild = me->lastchild = me->childcnt = me->nextsib = 0;
  7735. return next;
  7736. }
  7737. static XML_Content *
  7738. build_model(XML_Parser parser) {
  7739. /* Function build_model transforms the existing parser->m_dtd->scaffold
  7740. * array of CONTENT_SCAFFOLD tree nodes into a new array of
  7741. * XML_Content tree nodes followed by a gapless list of zero-terminated
  7742. * strings. */
  7743. DTD *const dtd = parser->m_dtd; /* save one level of indirection */
  7744. XML_Content *ret;
  7745. XML_Char *str; /* the current string writing location */
  7746. /* Detect and prevent integer overflow.
  7747. * The preprocessor guard addresses the "always false" warning
  7748. * from -Wtype-limits on platforms where
  7749. * sizeof(unsigned int) < sizeof(size_t), e.g. on x86_64. */
  7750. #if UINT_MAX >= SIZE_MAX
  7751. if (dtd->scaffCount > SIZE_MAX / sizeof(XML_Content)) {
  7752. return NULL;
  7753. }
  7754. if (dtd->contentStringLen > SIZE_MAX / sizeof(XML_Char)) {
  7755. return NULL;
  7756. }
  7757. #endif
  7758. if (dtd->scaffCount * sizeof(XML_Content)
  7759. > SIZE_MAX - dtd->contentStringLen * sizeof(XML_Char)) {
  7760. return NULL;
  7761. }
  7762. const size_t allocsize = (dtd->scaffCount * sizeof(XML_Content)
  7763. + (dtd->contentStringLen * sizeof(XML_Char)));
  7764. // NOTE: We are avoiding MALLOC(..) here to so that
  7765. // applications that are not using XML_FreeContentModel but plain
  7766. // free(..) or .free_fcn() to free the content model's memory are safe.
  7767. ret = parser->m_mem.malloc_fcn(allocsize);
  7768. if (! ret)
  7769. return NULL;
  7770. /* What follows is an iterative implementation (of what was previously done
  7771. * recursively in a dedicated function called "build_node". The old recursive
  7772. * build_node could be forced into stack exhaustion from input as small as a
  7773. * few megabyte, and so that was a security issue. Hence, a function call
  7774. * stack is avoided now by resolving recursion.)
  7775. *
  7776. * The iterative approach works as follows:
  7777. *
  7778. * - We have two writing pointers, both walking up the result array; one does
  7779. * the work, the other creates "jobs" for its colleague to do, and leads
  7780. * the way:
  7781. *
  7782. * - The faster one, pointer jobDest, always leads and writes "what job
  7783. * to do" by the other, once they reach that place in the
  7784. * array: leader "jobDest" stores the source node array index (relative
  7785. * to array dtd->scaffold) in field "numchildren".
  7786. *
  7787. * - The slower one, pointer dest, looks at the value stored in the
  7788. * "numchildren" field (which actually holds a source node array index
  7789. * at that time) and puts the real data from dtd->scaffold in.
  7790. *
  7791. * - Before the loop starts, jobDest writes source array index 0
  7792. * (where the root node is located) so that dest will have something to do
  7793. * when it starts operation.
  7794. *
  7795. * - Whenever nodes with children are encountered, jobDest appends
  7796. * them as new jobs, in order. As a result, tree node siblings are
  7797. * adjacent in the resulting array, for example:
  7798. *
  7799. * [0] root, has two children
  7800. * [1] first child of 0, has three children
  7801. * [3] first child of 1, does not have children
  7802. * [4] second child of 1, does not have children
  7803. * [5] third child of 1, does not have children
  7804. * [2] second child of 0, does not have children
  7805. *
  7806. * Or (the same data) presented in flat array view:
  7807. *
  7808. * [0] root, has two children
  7809. *
  7810. * [1] first child of 0, has three children
  7811. * [2] second child of 0, does not have children
  7812. *
  7813. * [3] first child of 1, does not have children
  7814. * [4] second child of 1, does not have children
  7815. * [5] third child of 1, does not have children
  7816. *
  7817. * - The algorithm repeats until all target array indices have been processed.
  7818. */
  7819. XML_Content *dest = ret; /* tree node writing location, moves upwards */
  7820. XML_Content *const destLimit = &ret[dtd->scaffCount];
  7821. XML_Content *jobDest = ret; /* next free writing location in target array */
  7822. str = (XML_Char *)&ret[dtd->scaffCount];
  7823. /* Add the starting job, the root node (index 0) of the source tree */
  7824. (jobDest++)->numchildren = 0;
  7825. for (; dest < destLimit; dest++) {
  7826. /* Retrieve source tree array index from job storage */
  7827. const int src_node = (int)dest->numchildren;
  7828. /* Convert item */
  7829. dest->type = dtd->scaffold[src_node].type;
  7830. dest->quant = dtd->scaffold[src_node].quant;
  7831. if (dest->type == XML_CTYPE_NAME) {
  7832. const XML_Char *src;
  7833. dest->name = str;
  7834. src = dtd->scaffold[src_node].name;
  7835. for (;;) {
  7836. *str++ = *src;
  7837. if (! *src)
  7838. break;
  7839. src++;
  7840. }
  7841. dest->numchildren = 0;
  7842. dest->children = NULL;
  7843. } else {
  7844. unsigned int i;
  7845. int cn;
  7846. dest->name = NULL;
  7847. dest->numchildren = dtd->scaffold[src_node].childcnt;
  7848. dest->children = jobDest;
  7849. /* Append scaffold indices of children to array */
  7850. for (i = 0, cn = dtd->scaffold[src_node].firstchild;
  7851. i < dest->numchildren; i++, cn = dtd->scaffold[cn].nextsib)
  7852. (jobDest++)->numchildren = (unsigned int)cn;
  7853. }
  7854. }
  7855. return ret;
  7856. }
  7857. static ELEMENT_TYPE *
  7858. getElementType(XML_Parser parser, const ENCODING *enc, const char *ptr,
  7859. const char *end) {
  7860. DTD *const dtd = parser->m_dtd; /* save one level of indirection */
  7861. const XML_Char *name = poolStoreString(&dtd->pool, enc, ptr, end);
  7862. ELEMENT_TYPE *ret;
  7863. if (! name)
  7864. return NULL;
  7865. ret = (ELEMENT_TYPE *)lookup(parser, &dtd->elementTypes, name,
  7866. sizeof(ELEMENT_TYPE));
  7867. if (! ret)
  7868. return NULL;
  7869. if (ret->name != name)
  7870. poolDiscard(&dtd->pool);
  7871. else {
  7872. poolFinish(&dtd->pool);
  7873. if (! setElementTypePrefix(parser, ret))
  7874. return NULL;
  7875. }
  7876. return ret;
  7877. }
  7878. static XML_Char *
  7879. copyString(const XML_Char *s, XML_Parser parser) {
  7880. size_t charsRequired = 0;
  7881. XML_Char *result;
  7882. /* First determine how long the string is */
  7883. while (s[charsRequired] != 0) {
  7884. charsRequired++;
  7885. }
  7886. /* Include the terminator */
  7887. charsRequired++;
  7888. /* Now allocate space for the copy */
  7889. result = MALLOC(parser, charsRequired * sizeof(XML_Char));
  7890. if (result == NULL)
  7891. return NULL;
  7892. /* Copy the original into place */
  7893. memcpy(result, s, charsRequired * sizeof(XML_Char));
  7894. return result;
  7895. }
  7896. #if XML_GE == 1
  7897. static float
  7898. accountingGetCurrentAmplification(XML_Parser rootParser) {
  7899. // 1.........1.........12 => 22
  7900. const size_t lenOfShortestInclude = sizeof("<!ENTITY a SYSTEM 'b'>") - 1;
  7901. const XmlBigCount countBytesOutput
  7902. = rootParser->m_accounting.countBytesDirect
  7903. + rootParser->m_accounting.countBytesIndirect;
  7904. const float amplificationFactor
  7905. = rootParser->m_accounting.countBytesDirect
  7906. ? ((float)countBytesOutput
  7907. / (float)(rootParser->m_accounting.countBytesDirect))
  7908. : ((float)(lenOfShortestInclude
  7909. + rootParser->m_accounting.countBytesIndirect)
  7910. / (float)lenOfShortestInclude);
  7911. assert(! rootParser->m_parentParser);
  7912. return amplificationFactor;
  7913. }
  7914. static void
  7915. accountingReportStats(XML_Parser originParser, const char *epilog) {
  7916. const XML_Parser rootParser = getRootParserOf(originParser, NULL);
  7917. assert(! rootParser->m_parentParser);
  7918. if (rootParser->m_accounting.debugLevel == 0u) {
  7919. return;
  7920. }
  7921. const float amplificationFactor
  7922. = accountingGetCurrentAmplification(rootParser);
  7923. fprintf(stderr,
  7924. "expat: Accounting(%p): Direct " EXPAT_FMT_ULL(
  7925. "10") ", indirect " EXPAT_FMT_ULL("10") ", amplification %8.2f%s",
  7926. (void *)rootParser, rootParser->m_accounting.countBytesDirect,
  7927. rootParser->m_accounting.countBytesIndirect,
  7928. (double)amplificationFactor, epilog);
  7929. }
  7930. static void
  7931. accountingOnAbort(XML_Parser originParser) {
  7932. accountingReportStats(originParser, " ABORTING\n");
  7933. }
  7934. static void
  7935. accountingReportDiff(XML_Parser rootParser,
  7936. unsigned int levelsAwayFromRootParser, const char *before,
  7937. const char *after, ptrdiff_t bytesMore, int source_line,
  7938. enum XML_Account account) {
  7939. assert(! rootParser->m_parentParser);
  7940. fprintf(stderr,
  7941. " (+" EXPAT_FMT_PTRDIFF_T("6") " bytes %s|%u, xmlparse.c:%d) %*s\"",
  7942. bytesMore, (account == XML_ACCOUNT_DIRECT) ? "DIR" : "EXP",
  7943. levelsAwayFromRootParser, source_line, 10, "");
  7944. const char ellipis[] = "[..]";
  7945. const size_t ellipsisLength = sizeof(ellipis) /* because compile-time */ - 1;
  7946. const unsigned int contextLength = 10;
  7947. /* Note: Performance is of no concern here */
  7948. const char *walker = before;
  7949. if ((rootParser->m_accounting.debugLevel >= 3u)
  7950. || (after - before)
  7951. <= (ptrdiff_t)(contextLength + ellipsisLength + contextLength)) {
  7952. for (; walker < after; walker++) {
  7953. fprintf(stderr, "%s", unsignedCharToPrintable(walker[0]));
  7954. }
  7955. } else {
  7956. for (; walker < before + contextLength; walker++) {
  7957. fprintf(stderr, "%s", unsignedCharToPrintable(walker[0]));
  7958. }
  7959. fprintf(stderr, ellipis);
  7960. walker = after - contextLength;
  7961. for (; walker < after; walker++) {
  7962. fprintf(stderr, "%s", unsignedCharToPrintable(walker[0]));
  7963. }
  7964. }
  7965. fprintf(stderr, "\"\n");
  7966. }
  7967. static XML_Bool
  7968. accountingDiffTolerated(XML_Parser originParser, int tok, const char *before,
  7969. const char *after, int source_line,
  7970. enum XML_Account account) {
  7971. /* Note: We need to check the token type *first* to be sure that
  7972. * we can even access variable <after>, safely.
  7973. * E.g. for XML_TOK_NONE <after> may hold an invalid pointer. */
  7974. switch (tok) {
  7975. case XML_TOK_INVALID:
  7976. case XML_TOK_PARTIAL:
  7977. case XML_TOK_PARTIAL_CHAR:
  7978. case XML_TOK_NONE:
  7979. return XML_TRUE;
  7980. }
  7981. if (account == XML_ACCOUNT_NONE)
  7982. return XML_TRUE; /* because these bytes have been accounted for, already */
  7983. unsigned int levelsAwayFromRootParser;
  7984. const XML_Parser rootParser
  7985. = getRootParserOf(originParser, &levelsAwayFromRootParser);
  7986. assert(! rootParser->m_parentParser);
  7987. const int isDirect
  7988. = (account == XML_ACCOUNT_DIRECT) && (originParser == rootParser);
  7989. const ptrdiff_t bytesMore = after - before;
  7990. XmlBigCount *const additionTarget
  7991. = isDirect ? &rootParser->m_accounting.countBytesDirect
  7992. : &rootParser->m_accounting.countBytesIndirect;
  7993. /* Detect and avoid integer overflow */
  7994. if (*additionTarget > (XmlBigCount)(-1) - (XmlBigCount)bytesMore)
  7995. return XML_FALSE;
  7996. *additionTarget += bytesMore;
  7997. const XmlBigCount countBytesOutput
  7998. = rootParser->m_accounting.countBytesDirect
  7999. + rootParser->m_accounting.countBytesIndirect;
  8000. const float amplificationFactor
  8001. = accountingGetCurrentAmplification(rootParser);
  8002. const XML_Bool tolerated
  8003. = (countBytesOutput < rootParser->m_accounting.activationThresholdBytes)
  8004. || (amplificationFactor
  8005. <= rootParser->m_accounting.maximumAmplificationFactor);
  8006. if (rootParser->m_accounting.debugLevel >= 2u) {
  8007. accountingReportStats(rootParser, "");
  8008. accountingReportDiff(rootParser, levelsAwayFromRootParser, before, after,
  8009. bytesMore, source_line, account);
  8010. }
  8011. return tolerated;
  8012. }
  8013. unsigned long long
  8014. testingAccountingGetCountBytesDirect(XML_Parser parser) {
  8015. if (! parser)
  8016. return 0;
  8017. return parser->m_accounting.countBytesDirect;
  8018. }
  8019. unsigned long long
  8020. testingAccountingGetCountBytesIndirect(XML_Parser parser) {
  8021. if (! parser)
  8022. return 0;
  8023. return parser->m_accounting.countBytesIndirect;
  8024. }
  8025. static void
  8026. entityTrackingReportStats(XML_Parser rootParser, ENTITY *entity,
  8027. const char *action, int sourceLine) {
  8028. assert(! rootParser->m_parentParser);
  8029. if (rootParser->m_entity_stats.debugLevel == 0u)
  8030. return;
  8031. # if defined(XML_UNICODE)
  8032. const char *const entityName = "[..]";
  8033. # else
  8034. const char *const entityName = entity->name;
  8035. # endif
  8036. fprintf(
  8037. stderr,
  8038. "expat: Entities(%p): Count %9u, depth %2u/%2u %*s%s%s; %s length %d (xmlparse.c:%d)\n",
  8039. (void *)rootParser, rootParser->m_entity_stats.countEverOpened,
  8040. rootParser->m_entity_stats.currentDepth,
  8041. rootParser->m_entity_stats.maximumDepthSeen,
  8042. ((int)rootParser->m_entity_stats.currentDepth - 1) * 2, "",
  8043. entity->is_param ? "%" : "&", entityName, action, entity->textLen,
  8044. sourceLine);
  8045. }
  8046. static void
  8047. entityTrackingOnOpen(XML_Parser originParser, ENTITY *entity, int sourceLine) {
  8048. const XML_Parser rootParser = getRootParserOf(originParser, NULL);
  8049. assert(! rootParser->m_parentParser);
  8050. rootParser->m_entity_stats.countEverOpened++;
  8051. rootParser->m_entity_stats.currentDepth++;
  8052. if (rootParser->m_entity_stats.currentDepth
  8053. > rootParser->m_entity_stats.maximumDepthSeen) {
  8054. rootParser->m_entity_stats.maximumDepthSeen++;
  8055. }
  8056. entityTrackingReportStats(rootParser, entity, "OPEN ", sourceLine);
  8057. }
  8058. static void
  8059. entityTrackingOnClose(XML_Parser originParser, ENTITY *entity, int sourceLine) {
  8060. const XML_Parser rootParser = getRootParserOf(originParser, NULL);
  8061. assert(! rootParser->m_parentParser);
  8062. entityTrackingReportStats(rootParser, entity, "CLOSE", sourceLine);
  8063. rootParser->m_entity_stats.currentDepth--;
  8064. }
  8065. #endif /* XML_GE == 1 */
  8066. static XML_Parser
  8067. getRootParserOf(XML_Parser parser, unsigned int *outLevelDiff) {
  8068. XML_Parser rootParser = parser;
  8069. unsigned int stepsTakenUpwards = 0;
  8070. while (rootParser->m_parentParser) {
  8071. rootParser = rootParser->m_parentParser;
  8072. stepsTakenUpwards++;
  8073. }
  8074. assert(! rootParser->m_parentParser);
  8075. if (outLevelDiff != NULL) {
  8076. *outLevelDiff = stepsTakenUpwards;
  8077. }
  8078. return rootParser;
  8079. }
  8080. #if XML_GE == 1
  8081. const char *
  8082. unsignedCharToPrintable(unsigned char c) {
  8083. switch (c) {
  8084. case 0:
  8085. return "\\0";
  8086. case 1:
  8087. return "\\x1";
  8088. case 2:
  8089. return "\\x2";
  8090. case 3:
  8091. return "\\x3";
  8092. case 4:
  8093. return "\\x4";
  8094. case 5:
  8095. return "\\x5";
  8096. case 6:
  8097. return "\\x6";
  8098. case 7:
  8099. return "\\x7";
  8100. case 8:
  8101. return "\\x8";
  8102. case 9:
  8103. return "\\t";
  8104. case 10:
  8105. return "\\n";
  8106. case 11:
  8107. return "\\xB";
  8108. case 12:
  8109. return "\\xC";
  8110. case 13:
  8111. return "\\r";
  8112. case 14:
  8113. return "\\xE";
  8114. case 15:
  8115. return "\\xF";
  8116. case 16:
  8117. return "\\x10";
  8118. case 17:
  8119. return "\\x11";
  8120. case 18:
  8121. return "\\x12";
  8122. case 19:
  8123. return "\\x13";
  8124. case 20:
  8125. return "\\x14";
  8126. case 21:
  8127. return "\\x15";
  8128. case 22:
  8129. return "\\x16";
  8130. case 23:
  8131. return "\\x17";
  8132. case 24:
  8133. return "\\x18";
  8134. case 25:
  8135. return "\\x19";
  8136. case 26:
  8137. return "\\x1A";
  8138. case 27:
  8139. return "\\x1B";
  8140. case 28:
  8141. return "\\x1C";
  8142. case 29:
  8143. return "\\x1D";
  8144. case 30:
  8145. return "\\x1E";
  8146. case 31:
  8147. return "\\x1F";
  8148. case 32:
  8149. return " ";
  8150. case 33:
  8151. return "!";
  8152. case 34:
  8153. return "\\\"";
  8154. case 35:
  8155. return "#";
  8156. case 36:
  8157. return "$";
  8158. case 37:
  8159. return "%";
  8160. case 38:
  8161. return "&";
  8162. case 39:
  8163. return "'";
  8164. case 40:
  8165. return "(";
  8166. case 41:
  8167. return ")";
  8168. case 42:
  8169. return "*";
  8170. case 43:
  8171. return "+";
  8172. case 44:
  8173. return ",";
  8174. case 45:
  8175. return "-";
  8176. case 46:
  8177. return ".";
  8178. case 47:
  8179. return "/";
  8180. case 48:
  8181. return "0";
  8182. case 49:
  8183. return "1";
  8184. case 50:
  8185. return "2";
  8186. case 51:
  8187. return "3";
  8188. case 52:
  8189. return "4";
  8190. case 53:
  8191. return "5";
  8192. case 54:
  8193. return "6";
  8194. case 55:
  8195. return "7";
  8196. case 56:
  8197. return "8";
  8198. case 57:
  8199. return "9";
  8200. case 58:
  8201. return ":";
  8202. case 59:
  8203. return ";";
  8204. case 60:
  8205. return "<";
  8206. case 61:
  8207. return "=";
  8208. case 62:
  8209. return ">";
  8210. case 63:
  8211. return "?";
  8212. case 64:
  8213. return "@";
  8214. case 65:
  8215. return "A";
  8216. case 66:
  8217. return "B";
  8218. case 67:
  8219. return "C";
  8220. case 68:
  8221. return "D";
  8222. case 69:
  8223. return "E";
  8224. case 70:
  8225. return "F";
  8226. case 71:
  8227. return "G";
  8228. case 72:
  8229. return "H";
  8230. case 73:
  8231. return "I";
  8232. case 74:
  8233. return "J";
  8234. case 75:
  8235. return "K";
  8236. case 76:
  8237. return "L";
  8238. case 77:
  8239. return "M";
  8240. case 78:
  8241. return "N";
  8242. case 79:
  8243. return "O";
  8244. case 80:
  8245. return "P";
  8246. case 81:
  8247. return "Q";
  8248. case 82:
  8249. return "R";
  8250. case 83:
  8251. return "S";
  8252. case 84:
  8253. return "T";
  8254. case 85:
  8255. return "U";
  8256. case 86:
  8257. return "V";
  8258. case 87:
  8259. return "W";
  8260. case 88:
  8261. return "X";
  8262. case 89:
  8263. return "Y";
  8264. case 90:
  8265. return "Z";
  8266. case 91:
  8267. return "[";
  8268. case 92:
  8269. return "\\\\";
  8270. case 93:
  8271. return "]";
  8272. case 94:
  8273. return "^";
  8274. case 95:
  8275. return "_";
  8276. case 96:
  8277. return "`";
  8278. case 97:
  8279. return "a";
  8280. case 98:
  8281. return "b";
  8282. case 99:
  8283. return "c";
  8284. case 100:
  8285. return "d";
  8286. case 101:
  8287. return "e";
  8288. case 102:
  8289. return "f";
  8290. case 103:
  8291. return "g";
  8292. case 104:
  8293. return "h";
  8294. case 105:
  8295. return "i";
  8296. case 106:
  8297. return "j";
  8298. case 107:
  8299. return "k";
  8300. case 108:
  8301. return "l";
  8302. case 109:
  8303. return "m";
  8304. case 110:
  8305. return "n";
  8306. case 111:
  8307. return "o";
  8308. case 112:
  8309. return "p";
  8310. case 113:
  8311. return "q";
  8312. case 114:
  8313. return "r";
  8314. case 115:
  8315. return "s";
  8316. case 116:
  8317. return "t";
  8318. case 117:
  8319. return "u";
  8320. case 118:
  8321. return "v";
  8322. case 119:
  8323. return "w";
  8324. case 120:
  8325. return "x";
  8326. case 121:
  8327. return "y";
  8328. case 122:
  8329. return "z";
  8330. case 123:
  8331. return "{";
  8332. case 124:
  8333. return "|";
  8334. case 125:
  8335. return "}";
  8336. case 126:
  8337. return "~";
  8338. case 127:
  8339. return "\\x7F";
  8340. case 128:
  8341. return "\\x80";
  8342. case 129:
  8343. return "\\x81";
  8344. case 130:
  8345. return "\\x82";
  8346. case 131:
  8347. return "\\x83";
  8348. case 132:
  8349. return "\\x84";
  8350. case 133:
  8351. return "\\x85";
  8352. case 134:
  8353. return "\\x86";
  8354. case 135:
  8355. return "\\x87";
  8356. case 136:
  8357. return "\\x88";
  8358. case 137:
  8359. return "\\x89";
  8360. case 138:
  8361. return "\\x8A";
  8362. case 139:
  8363. return "\\x8B";
  8364. case 140:
  8365. return "\\x8C";
  8366. case 141:
  8367. return "\\x8D";
  8368. case 142:
  8369. return "\\x8E";
  8370. case 143:
  8371. return "\\x8F";
  8372. case 144:
  8373. return "\\x90";
  8374. case 145:
  8375. return "\\x91";
  8376. case 146:
  8377. return "\\x92";
  8378. case 147:
  8379. return "\\x93";
  8380. case 148:
  8381. return "\\x94";
  8382. case 149:
  8383. return "\\x95";
  8384. case 150:
  8385. return "\\x96";
  8386. case 151:
  8387. return "\\x97";
  8388. case 152:
  8389. return "\\x98";
  8390. case 153:
  8391. return "\\x99";
  8392. case 154:
  8393. return "\\x9A";
  8394. case 155:
  8395. return "\\x9B";
  8396. case 156:
  8397. return "\\x9C";
  8398. case 157:
  8399. return "\\x9D";
  8400. case 158:
  8401. return "\\x9E";
  8402. case 159:
  8403. return "\\x9F";
  8404. case 160:
  8405. return "\\xA0";
  8406. case 161:
  8407. return "\\xA1";
  8408. case 162:
  8409. return "\\xA2";
  8410. case 163:
  8411. return "\\xA3";
  8412. case 164:
  8413. return "\\xA4";
  8414. case 165:
  8415. return "\\xA5";
  8416. case 166:
  8417. return "\\xA6";
  8418. case 167:
  8419. return "\\xA7";
  8420. case 168:
  8421. return "\\xA8";
  8422. case 169:
  8423. return "\\xA9";
  8424. case 170:
  8425. return "\\xAA";
  8426. case 171:
  8427. return "\\xAB";
  8428. case 172:
  8429. return "\\xAC";
  8430. case 173:
  8431. return "\\xAD";
  8432. case 174:
  8433. return "\\xAE";
  8434. case 175:
  8435. return "\\xAF";
  8436. case 176:
  8437. return "\\xB0";
  8438. case 177:
  8439. return "\\xB1";
  8440. case 178:
  8441. return "\\xB2";
  8442. case 179:
  8443. return "\\xB3";
  8444. case 180:
  8445. return "\\xB4";
  8446. case 181:
  8447. return "\\xB5";
  8448. case 182:
  8449. return "\\xB6";
  8450. case 183:
  8451. return "\\xB7";
  8452. case 184:
  8453. return "\\xB8";
  8454. case 185:
  8455. return "\\xB9";
  8456. case 186:
  8457. return "\\xBA";
  8458. case 187:
  8459. return "\\xBB";
  8460. case 188:
  8461. return "\\xBC";
  8462. case 189:
  8463. return "\\xBD";
  8464. case 190:
  8465. return "\\xBE";
  8466. case 191:
  8467. return "\\xBF";
  8468. case 192:
  8469. return "\\xC0";
  8470. case 193:
  8471. return "\\xC1";
  8472. case 194:
  8473. return "\\xC2";
  8474. case 195:
  8475. return "\\xC3";
  8476. case 196:
  8477. return "\\xC4";
  8478. case 197:
  8479. return "\\xC5";
  8480. case 198:
  8481. return "\\xC6";
  8482. case 199:
  8483. return "\\xC7";
  8484. case 200:
  8485. return "\\xC8";
  8486. case 201:
  8487. return "\\xC9";
  8488. case 202:
  8489. return "\\xCA";
  8490. case 203:
  8491. return "\\xCB";
  8492. case 204:
  8493. return "\\xCC";
  8494. case 205:
  8495. return "\\xCD";
  8496. case 206:
  8497. return "\\xCE";
  8498. case 207:
  8499. return "\\xCF";
  8500. case 208:
  8501. return "\\xD0";
  8502. case 209:
  8503. return "\\xD1";
  8504. case 210:
  8505. return "\\xD2";
  8506. case 211:
  8507. return "\\xD3";
  8508. case 212:
  8509. return "\\xD4";
  8510. case 213:
  8511. return "\\xD5";
  8512. case 214:
  8513. return "\\xD6";
  8514. case 215:
  8515. return "\\xD7";
  8516. case 216:
  8517. return "\\xD8";
  8518. case 217:
  8519. return "\\xD9";
  8520. case 218:
  8521. return "\\xDA";
  8522. case 219:
  8523. return "\\xDB";
  8524. case 220:
  8525. return "\\xDC";
  8526. case 221:
  8527. return "\\xDD";
  8528. case 222:
  8529. return "\\xDE";
  8530. case 223:
  8531. return "\\xDF";
  8532. case 224:
  8533. return "\\xE0";
  8534. case 225:
  8535. return "\\xE1";
  8536. case 226:
  8537. return "\\xE2";
  8538. case 227:
  8539. return "\\xE3";
  8540. case 228:
  8541. return "\\xE4";
  8542. case 229:
  8543. return "\\xE5";
  8544. case 230:
  8545. return "\\xE6";
  8546. case 231:
  8547. return "\\xE7";
  8548. case 232:
  8549. return "\\xE8";
  8550. case 233:
  8551. return "\\xE9";
  8552. case 234:
  8553. return "\\xEA";
  8554. case 235:
  8555. return "\\xEB";
  8556. case 236:
  8557. return "\\xEC";
  8558. case 237:
  8559. return "\\xED";
  8560. case 238:
  8561. return "\\xEE";
  8562. case 239:
  8563. return "\\xEF";
  8564. case 240:
  8565. return "\\xF0";
  8566. case 241:
  8567. return "\\xF1";
  8568. case 242:
  8569. return "\\xF2";
  8570. case 243:
  8571. return "\\xF3";
  8572. case 244:
  8573. return "\\xF4";
  8574. case 245:
  8575. return "\\xF5";
  8576. case 246:
  8577. return "\\xF6";
  8578. case 247:
  8579. return "\\xF7";
  8580. case 248:
  8581. return "\\xF8";
  8582. case 249:
  8583. return "\\xF9";
  8584. case 250:
  8585. return "\\xFA";
  8586. case 251:
  8587. return "\\xFB";
  8588. case 252:
  8589. return "\\xFC";
  8590. case 253:
  8591. return "\\xFD";
  8592. case 254:
  8593. return "\\xFE";
  8594. case 255:
  8595. return "\\xFF";
  8596. // LCOV_EXCL_START
  8597. default:
  8598. assert(0); /* never gets here */
  8599. return "dead code";
  8600. }
  8601. assert(0); /* never gets here */
  8602. // LCOV_EXCL_STOP
  8603. }
  8604. #endif /* XML_GE == 1 */
  8605. static unsigned long
  8606. getDebugLevel(const char *variableName, unsigned long defaultDebugLevel) {
  8607. const char *const valueOrNull = getenv(variableName);
  8608. if (valueOrNull == NULL) {
  8609. return defaultDebugLevel;
  8610. }
  8611. const char *const value = valueOrNull;
  8612. errno = 0;
  8613. char *afterValue = NULL;
  8614. unsigned long debugLevel = strtoul(value, &afterValue, 10);
  8615. if ((errno != 0) || (afterValue == value) || (afterValue[0] != '\0')) {
  8616. errno = 0;
  8617. return defaultDebugLevel;
  8618. }
  8619. return debugLevel;
  8620. }