xmlparse.c 289 KB

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