xmlparse.c 289 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841
  1. /* d19ae032c224863c1527ba44d228cc34b99192c3a4c5a27af1f4e054d45ee031 (2.7.1+)
  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. switch (parser->m_parsingStatus.parsing) {
  3131. case XML_SUSPENDED:
  3132. *eventPP = next;
  3133. *nextPtr = next;
  3134. return XML_ERROR_NONE;
  3135. case XML_FINISHED:
  3136. *eventPP = next;
  3137. return XML_ERROR_ABORTED;
  3138. case XML_PARSING:
  3139. if (parser->m_reenter) {
  3140. *nextPtr = next;
  3141. return XML_ERROR_NONE;
  3142. }
  3143. /* Fall through */
  3144. default:;
  3145. *eventPP = s = next;
  3146. }
  3147. }
  3148. /* not reached */
  3149. }
  3150. /* This function does not call free() on the allocated memory, merely
  3151. * moving it to the parser's m_freeBindingList where it can be freed or
  3152. * reused as appropriate.
  3153. */
  3154. static void
  3155. freeBindings(XML_Parser parser, BINDING *bindings) {
  3156. while (bindings) {
  3157. BINDING *b = bindings;
  3158. /* m_startNamespaceDeclHandler will have been called for this
  3159. * binding in addBindings(), so call the end handler now.
  3160. */
  3161. if (parser->m_endNamespaceDeclHandler)
  3162. parser->m_endNamespaceDeclHandler(parser->m_handlerArg, b->prefix->name);
  3163. bindings = bindings->nextTagBinding;
  3164. b->nextTagBinding = parser->m_freeBindingList;
  3165. parser->m_freeBindingList = b;
  3166. b->prefix->binding = b->prevPrefixBinding;
  3167. }
  3168. }
  3169. /* Precondition: all arguments must be non-NULL;
  3170. Purpose:
  3171. - normalize attributes
  3172. - check attributes for well-formedness
  3173. - generate namespace aware attribute names (URI, prefix)
  3174. - build list of attributes for startElementHandler
  3175. - default attributes
  3176. - process namespace declarations (check and report them)
  3177. - generate namespace aware element name (URI, prefix)
  3178. */
  3179. static enum XML_Error
  3180. storeAtts(XML_Parser parser, const ENCODING *enc, const char *attStr,
  3181. TAG_NAME *tagNamePtr, BINDING **bindingsPtr,
  3182. enum XML_Account account) {
  3183. DTD *const dtd = parser->m_dtd; /* save one level of indirection */
  3184. ELEMENT_TYPE *elementType;
  3185. int nDefaultAtts;
  3186. const XML_Char **appAtts; /* the attribute list for the application */
  3187. int attIndex = 0;
  3188. int prefixLen;
  3189. int i;
  3190. int n;
  3191. XML_Char *uri;
  3192. int nPrefixes = 0;
  3193. BINDING *binding;
  3194. const XML_Char *localPart;
  3195. /* lookup the element type name */
  3196. elementType
  3197. = (ELEMENT_TYPE *)lookup(parser, &dtd->elementTypes, tagNamePtr->str, 0);
  3198. if (! elementType) {
  3199. const XML_Char *name = poolCopyString(&dtd->pool, tagNamePtr->str);
  3200. if (! name)
  3201. return XML_ERROR_NO_MEMORY;
  3202. elementType = (ELEMENT_TYPE *)lookup(parser, &dtd->elementTypes, name,
  3203. sizeof(ELEMENT_TYPE));
  3204. if (! elementType)
  3205. return XML_ERROR_NO_MEMORY;
  3206. if (parser->m_ns && ! setElementTypePrefix(parser, elementType))
  3207. return XML_ERROR_NO_MEMORY;
  3208. }
  3209. nDefaultAtts = elementType->nDefaultAtts;
  3210. /* get the attributes from the tokenizer */
  3211. n = XmlGetAttributes(enc, attStr, parser->m_attsSize, parser->m_atts);
  3212. /* Detect and prevent integer overflow */
  3213. if (n > INT_MAX - nDefaultAtts) {
  3214. return XML_ERROR_NO_MEMORY;
  3215. }
  3216. if (n + nDefaultAtts > parser->m_attsSize) {
  3217. int oldAttsSize = parser->m_attsSize;
  3218. ATTRIBUTE *temp;
  3219. #ifdef XML_ATTR_INFO
  3220. XML_AttrInfo *temp2;
  3221. #endif
  3222. /* Detect and prevent integer overflow */
  3223. if ((nDefaultAtts > INT_MAX - INIT_ATTS_SIZE)
  3224. || (n > INT_MAX - (nDefaultAtts + INIT_ATTS_SIZE))) {
  3225. return XML_ERROR_NO_MEMORY;
  3226. }
  3227. parser->m_attsSize = n + nDefaultAtts + INIT_ATTS_SIZE;
  3228. /* Detect and prevent integer overflow.
  3229. * The preprocessor guard addresses the "always false" warning
  3230. * from -Wtype-limits on platforms where
  3231. * sizeof(unsigned int) < sizeof(size_t), e.g. on x86_64. */
  3232. #if UINT_MAX >= SIZE_MAX
  3233. if ((unsigned)parser->m_attsSize > (size_t)(-1) / sizeof(ATTRIBUTE)) {
  3234. parser->m_attsSize = oldAttsSize;
  3235. return XML_ERROR_NO_MEMORY;
  3236. }
  3237. #endif
  3238. temp = (ATTRIBUTE *)REALLOC(parser, (void *)parser->m_atts,
  3239. parser->m_attsSize * sizeof(ATTRIBUTE));
  3240. if (temp == NULL) {
  3241. parser->m_attsSize = oldAttsSize;
  3242. return XML_ERROR_NO_MEMORY;
  3243. }
  3244. parser->m_atts = temp;
  3245. #ifdef XML_ATTR_INFO
  3246. /* Detect and prevent integer overflow.
  3247. * The preprocessor guard addresses the "always false" warning
  3248. * from -Wtype-limits on platforms where
  3249. * sizeof(unsigned int) < sizeof(size_t), e.g. on x86_64. */
  3250. # if UINT_MAX >= SIZE_MAX
  3251. if ((unsigned)parser->m_attsSize > (size_t)(-1) / sizeof(XML_AttrInfo)) {
  3252. parser->m_attsSize = oldAttsSize;
  3253. return XML_ERROR_NO_MEMORY;
  3254. }
  3255. # endif
  3256. temp2 = (XML_AttrInfo *)REALLOC(parser, (void *)parser->m_attInfo,
  3257. parser->m_attsSize * sizeof(XML_AttrInfo));
  3258. if (temp2 == NULL) {
  3259. parser->m_attsSize = oldAttsSize;
  3260. return XML_ERROR_NO_MEMORY;
  3261. }
  3262. parser->m_attInfo = temp2;
  3263. #endif
  3264. if (n > oldAttsSize)
  3265. XmlGetAttributes(enc, attStr, n, parser->m_atts);
  3266. }
  3267. appAtts = (const XML_Char **)parser->m_atts;
  3268. for (i = 0; i < n; i++) {
  3269. ATTRIBUTE *currAtt = &parser->m_atts[i];
  3270. #ifdef XML_ATTR_INFO
  3271. XML_AttrInfo *currAttInfo = &parser->m_attInfo[i];
  3272. #endif
  3273. /* add the name and value to the attribute list */
  3274. ATTRIBUTE_ID *attId
  3275. = getAttributeId(parser, enc, currAtt->name,
  3276. currAtt->name + XmlNameLength(enc, currAtt->name));
  3277. if (! attId)
  3278. return XML_ERROR_NO_MEMORY;
  3279. #ifdef XML_ATTR_INFO
  3280. currAttInfo->nameStart
  3281. = parser->m_parseEndByteIndex - (parser->m_parseEndPtr - currAtt->name);
  3282. currAttInfo->nameEnd
  3283. = currAttInfo->nameStart + XmlNameLength(enc, currAtt->name);
  3284. currAttInfo->valueStart = parser->m_parseEndByteIndex
  3285. - (parser->m_parseEndPtr - currAtt->valuePtr);
  3286. currAttInfo->valueEnd = parser->m_parseEndByteIndex
  3287. - (parser->m_parseEndPtr - currAtt->valueEnd);
  3288. #endif
  3289. /* Detect duplicate attributes by their QNames. This does not work when
  3290. namespace processing is turned on and different prefixes for the same
  3291. namespace are used. For this case we have a check further down.
  3292. */
  3293. if ((attId->name)[-1]) {
  3294. if (enc == parser->m_encoding)
  3295. parser->m_eventPtr = parser->m_atts[i].name;
  3296. return XML_ERROR_DUPLICATE_ATTRIBUTE;
  3297. }
  3298. (attId->name)[-1] = 1;
  3299. appAtts[attIndex++] = attId->name;
  3300. if (! parser->m_atts[i].normalized) {
  3301. enum XML_Error result;
  3302. XML_Bool isCdata = XML_TRUE;
  3303. /* figure out whether declared as other than CDATA */
  3304. if (attId->maybeTokenized) {
  3305. int j;
  3306. for (j = 0; j < nDefaultAtts; j++) {
  3307. if (attId == elementType->defaultAtts[j].id) {
  3308. isCdata = elementType->defaultAtts[j].isCdata;
  3309. break;
  3310. }
  3311. }
  3312. }
  3313. /* normalize the attribute value */
  3314. result = storeAttributeValue(
  3315. parser, enc, isCdata, parser->m_atts[i].valuePtr,
  3316. parser->m_atts[i].valueEnd, &parser->m_tempPool, account);
  3317. if (result)
  3318. return result;
  3319. appAtts[attIndex] = poolStart(&parser->m_tempPool);
  3320. poolFinish(&parser->m_tempPool);
  3321. } else {
  3322. /* the value did not need normalizing */
  3323. appAtts[attIndex] = poolStoreString(&parser->m_tempPool, enc,
  3324. parser->m_atts[i].valuePtr,
  3325. parser->m_atts[i].valueEnd);
  3326. if (appAtts[attIndex] == 0)
  3327. return XML_ERROR_NO_MEMORY;
  3328. poolFinish(&parser->m_tempPool);
  3329. }
  3330. /* handle prefixed attribute names */
  3331. if (attId->prefix) {
  3332. if (attId->xmlns) {
  3333. /* deal with namespace declarations here */
  3334. enum XML_Error result = addBinding(parser, attId->prefix, attId,
  3335. appAtts[attIndex], bindingsPtr);
  3336. if (result)
  3337. return result;
  3338. --attIndex;
  3339. } else {
  3340. /* deal with other prefixed names later */
  3341. attIndex++;
  3342. nPrefixes++;
  3343. (attId->name)[-1] = 2;
  3344. }
  3345. } else
  3346. attIndex++;
  3347. }
  3348. /* set-up for XML_GetSpecifiedAttributeCount and XML_GetIdAttributeIndex */
  3349. parser->m_nSpecifiedAtts = attIndex;
  3350. if (elementType->idAtt && (elementType->idAtt->name)[-1]) {
  3351. for (i = 0; i < attIndex; i += 2)
  3352. if (appAtts[i] == elementType->idAtt->name) {
  3353. parser->m_idAttIndex = i;
  3354. break;
  3355. }
  3356. } else
  3357. parser->m_idAttIndex = -1;
  3358. /* do attribute defaulting */
  3359. for (i = 0; i < nDefaultAtts; i++) {
  3360. const DEFAULT_ATTRIBUTE *da = elementType->defaultAtts + i;
  3361. if (! (da->id->name)[-1] && da->value) {
  3362. if (da->id->prefix) {
  3363. if (da->id->xmlns) {
  3364. enum XML_Error result = addBinding(parser, da->id->prefix, da->id,
  3365. da->value, bindingsPtr);
  3366. if (result)
  3367. return result;
  3368. } else {
  3369. (da->id->name)[-1] = 2;
  3370. nPrefixes++;
  3371. appAtts[attIndex++] = da->id->name;
  3372. appAtts[attIndex++] = da->value;
  3373. }
  3374. } else {
  3375. (da->id->name)[-1] = 1;
  3376. appAtts[attIndex++] = da->id->name;
  3377. appAtts[attIndex++] = da->value;
  3378. }
  3379. }
  3380. }
  3381. appAtts[attIndex] = 0;
  3382. /* expand prefixed attribute names, check for duplicates,
  3383. and clear flags that say whether attributes were specified */
  3384. i = 0;
  3385. if (nPrefixes) {
  3386. int j; /* hash table index */
  3387. unsigned long version = parser->m_nsAttsVersion;
  3388. /* Detect and prevent invalid shift */
  3389. if (parser->m_nsAttsPower >= sizeof(unsigned int) * 8 /* bits per byte */) {
  3390. return XML_ERROR_NO_MEMORY;
  3391. }
  3392. unsigned int nsAttsSize = 1u << parser->m_nsAttsPower;
  3393. unsigned char oldNsAttsPower = parser->m_nsAttsPower;
  3394. /* size of hash table must be at least 2 * (# of prefixed attributes) */
  3395. if ((nPrefixes << 1)
  3396. >> parser->m_nsAttsPower) { /* true for m_nsAttsPower = 0 */
  3397. NS_ATT *temp;
  3398. /* hash table size must also be a power of 2 and >= 8 */
  3399. while (nPrefixes >> parser->m_nsAttsPower++)
  3400. ;
  3401. if (parser->m_nsAttsPower < 3)
  3402. parser->m_nsAttsPower = 3;
  3403. /* Detect and prevent invalid shift */
  3404. if (parser->m_nsAttsPower >= sizeof(nsAttsSize) * 8 /* bits per byte */) {
  3405. /* Restore actual size of memory in m_nsAtts */
  3406. parser->m_nsAttsPower = oldNsAttsPower;
  3407. return XML_ERROR_NO_MEMORY;
  3408. }
  3409. nsAttsSize = 1u << parser->m_nsAttsPower;
  3410. /* Detect and prevent integer overflow.
  3411. * The preprocessor guard addresses the "always false" warning
  3412. * from -Wtype-limits on platforms where
  3413. * sizeof(unsigned int) < sizeof(size_t), e.g. on x86_64. */
  3414. #if UINT_MAX >= SIZE_MAX
  3415. if (nsAttsSize > (size_t)(-1) / sizeof(NS_ATT)) {
  3416. /* Restore actual size of memory in m_nsAtts */
  3417. parser->m_nsAttsPower = oldNsAttsPower;
  3418. return XML_ERROR_NO_MEMORY;
  3419. }
  3420. #endif
  3421. temp = (NS_ATT *)REALLOC(parser, parser->m_nsAtts,
  3422. nsAttsSize * sizeof(NS_ATT));
  3423. if (! temp) {
  3424. /* Restore actual size of memory in m_nsAtts */
  3425. parser->m_nsAttsPower = oldNsAttsPower;
  3426. return XML_ERROR_NO_MEMORY;
  3427. }
  3428. parser->m_nsAtts = temp;
  3429. version = 0; /* force re-initialization of m_nsAtts hash table */
  3430. }
  3431. /* using a version flag saves us from initializing m_nsAtts every time */
  3432. if (! version) { /* initialize version flags when version wraps around */
  3433. version = INIT_ATTS_VERSION;
  3434. for (j = nsAttsSize; j != 0;)
  3435. parser->m_nsAtts[--j].version = version;
  3436. }
  3437. parser->m_nsAttsVersion = --version;
  3438. /* expand prefixed names and check for duplicates */
  3439. for (; i < attIndex; i += 2) {
  3440. const XML_Char *s = appAtts[i];
  3441. if (s[-1] == 2) { /* prefixed */
  3442. ATTRIBUTE_ID *id;
  3443. const BINDING *b;
  3444. unsigned long uriHash;
  3445. struct siphash sip_state;
  3446. struct sipkey sip_key;
  3447. copy_salt_to_sipkey(parser, &sip_key);
  3448. sip24_init(&sip_state, &sip_key);
  3449. ((XML_Char *)s)[-1] = 0; /* clear flag */
  3450. id = (ATTRIBUTE_ID *)lookup(parser, &dtd->attributeIds, s, 0);
  3451. if (! id || ! id->prefix) {
  3452. /* This code is walking through the appAtts array, dealing
  3453. * with (in this case) a prefixed attribute name. To be in
  3454. * the array, the attribute must have already been bound, so
  3455. * has to have passed through the hash table lookup once
  3456. * already. That implies that an entry for it already
  3457. * exists, so the lookup above will return a pointer to
  3458. * already allocated memory. There is no opportunaity for
  3459. * the allocator to fail, so the condition above cannot be
  3460. * fulfilled.
  3461. *
  3462. * Since it is difficult to be certain that the above
  3463. * analysis is complete, we retain the test and merely
  3464. * remove the code from coverage tests.
  3465. */
  3466. return XML_ERROR_NO_MEMORY; /* LCOV_EXCL_LINE */
  3467. }
  3468. b = id->prefix->binding;
  3469. if (! b)
  3470. return XML_ERROR_UNBOUND_PREFIX;
  3471. for (j = 0; j < b->uriLen; j++) {
  3472. const XML_Char c = b->uri[j];
  3473. if (! poolAppendChar(&parser->m_tempPool, c))
  3474. return XML_ERROR_NO_MEMORY;
  3475. }
  3476. sip24_update(&sip_state, b->uri, b->uriLen * sizeof(XML_Char));
  3477. while (*s++ != XML_T(ASCII_COLON))
  3478. ;
  3479. sip24_update(&sip_state, s, keylen(s) * sizeof(XML_Char));
  3480. do { /* copies null terminator */
  3481. if (! poolAppendChar(&parser->m_tempPool, *s))
  3482. return XML_ERROR_NO_MEMORY;
  3483. } while (*s++);
  3484. uriHash = (unsigned long)sip24_final(&sip_state);
  3485. { /* Check hash table for duplicate of expanded name (uriName).
  3486. Derived from code in lookup(parser, HASH_TABLE *table, ...).
  3487. */
  3488. unsigned char step = 0;
  3489. unsigned long mask = nsAttsSize - 1;
  3490. j = uriHash & mask; /* index into hash table */
  3491. while (parser->m_nsAtts[j].version == version) {
  3492. /* for speed we compare stored hash values first */
  3493. if (uriHash == parser->m_nsAtts[j].hash) {
  3494. const XML_Char *s1 = poolStart(&parser->m_tempPool);
  3495. const XML_Char *s2 = parser->m_nsAtts[j].uriName;
  3496. /* s1 is null terminated, but not s2 */
  3497. for (; *s1 == *s2 && *s1 != 0; s1++, s2++)
  3498. ;
  3499. if (*s1 == 0)
  3500. return XML_ERROR_DUPLICATE_ATTRIBUTE;
  3501. }
  3502. if (! step)
  3503. step = PROBE_STEP(uriHash, mask, parser->m_nsAttsPower);
  3504. j < step ? (j += nsAttsSize - step) : (j -= step);
  3505. }
  3506. }
  3507. if (parser->m_ns_triplets) { /* append namespace separator and prefix */
  3508. parser->m_tempPool.ptr[-1] = parser->m_namespaceSeparator;
  3509. s = b->prefix->name;
  3510. do {
  3511. if (! poolAppendChar(&parser->m_tempPool, *s))
  3512. return XML_ERROR_NO_MEMORY;
  3513. } while (*s++);
  3514. }
  3515. /* store expanded name in attribute list */
  3516. s = poolStart(&parser->m_tempPool);
  3517. poolFinish(&parser->m_tempPool);
  3518. appAtts[i] = s;
  3519. /* fill empty slot with new version, uriName and hash value */
  3520. parser->m_nsAtts[j].version = version;
  3521. parser->m_nsAtts[j].hash = uriHash;
  3522. parser->m_nsAtts[j].uriName = s;
  3523. if (! --nPrefixes) {
  3524. i += 2;
  3525. break;
  3526. }
  3527. } else /* not prefixed */
  3528. ((XML_Char *)s)[-1] = 0; /* clear flag */
  3529. }
  3530. }
  3531. /* clear flags for the remaining attributes */
  3532. for (; i < attIndex; i += 2)
  3533. ((XML_Char *)(appAtts[i]))[-1] = 0;
  3534. for (binding = *bindingsPtr; binding; binding = binding->nextTagBinding)
  3535. binding->attId->name[-1] = 0;
  3536. if (! parser->m_ns)
  3537. return XML_ERROR_NONE;
  3538. /* expand the element type name */
  3539. if (elementType->prefix) {
  3540. binding = elementType->prefix->binding;
  3541. if (! binding)
  3542. return XML_ERROR_UNBOUND_PREFIX;
  3543. localPart = tagNamePtr->str;
  3544. while (*localPart++ != XML_T(ASCII_COLON))
  3545. ;
  3546. } else if (dtd->defaultPrefix.binding) {
  3547. binding = dtd->defaultPrefix.binding;
  3548. localPart = tagNamePtr->str;
  3549. } else
  3550. return XML_ERROR_NONE;
  3551. prefixLen = 0;
  3552. if (parser->m_ns_triplets && binding->prefix->name) {
  3553. for (; binding->prefix->name[prefixLen++];)
  3554. ; /* prefixLen includes null terminator */
  3555. }
  3556. tagNamePtr->localPart = localPart;
  3557. tagNamePtr->uriLen = binding->uriLen;
  3558. tagNamePtr->prefix = binding->prefix->name;
  3559. tagNamePtr->prefixLen = prefixLen;
  3560. for (i = 0; localPart[i++];)
  3561. ; /* i includes null terminator */
  3562. /* Detect and prevent integer overflow */
  3563. if (binding->uriLen > INT_MAX - prefixLen
  3564. || i > INT_MAX - (binding->uriLen + prefixLen)) {
  3565. return XML_ERROR_NO_MEMORY;
  3566. }
  3567. n = i + binding->uriLen + prefixLen;
  3568. if (n > binding->uriAlloc) {
  3569. TAG *p;
  3570. /* Detect and prevent integer overflow */
  3571. if (n > INT_MAX - EXPAND_SPARE) {
  3572. return XML_ERROR_NO_MEMORY;
  3573. }
  3574. /* Detect and prevent integer overflow.
  3575. * The preprocessor guard addresses the "always false" warning
  3576. * from -Wtype-limits on platforms where
  3577. * sizeof(unsigned int) < sizeof(size_t), e.g. on x86_64. */
  3578. #if UINT_MAX >= SIZE_MAX
  3579. if ((unsigned)(n + EXPAND_SPARE) > (size_t)(-1) / sizeof(XML_Char)) {
  3580. return XML_ERROR_NO_MEMORY;
  3581. }
  3582. #endif
  3583. uri = (XML_Char *)MALLOC(parser, (n + EXPAND_SPARE) * sizeof(XML_Char));
  3584. if (! uri)
  3585. return XML_ERROR_NO_MEMORY;
  3586. binding->uriAlloc = n + EXPAND_SPARE;
  3587. memcpy(uri, binding->uri, binding->uriLen * sizeof(XML_Char));
  3588. for (p = parser->m_tagStack; p; p = p->parent)
  3589. if (p->name.str == binding->uri)
  3590. p->name.str = uri;
  3591. FREE(parser, binding->uri);
  3592. binding->uri = uri;
  3593. }
  3594. /* if m_namespaceSeparator != '\0' then uri includes it already */
  3595. uri = binding->uri + binding->uriLen;
  3596. memcpy(uri, localPart, i * sizeof(XML_Char));
  3597. /* we always have a namespace separator between localPart and prefix */
  3598. if (prefixLen) {
  3599. uri += i - 1;
  3600. *uri = parser->m_namespaceSeparator; /* replace null terminator */
  3601. memcpy(uri + 1, binding->prefix->name, prefixLen * sizeof(XML_Char));
  3602. }
  3603. tagNamePtr->str = binding->uri;
  3604. return XML_ERROR_NONE;
  3605. }
  3606. static XML_Bool
  3607. is_rfc3986_uri_char(XML_Char candidate) {
  3608. // For the RFC 3986 ANBF grammar see
  3609. // https://datatracker.ietf.org/doc/html/rfc3986#appendix-A
  3610. switch (candidate) {
  3611. // From rule "ALPHA" (uppercase half)
  3612. case 'A':
  3613. case 'B':
  3614. case 'C':
  3615. case 'D':
  3616. case 'E':
  3617. case 'F':
  3618. case 'G':
  3619. case 'H':
  3620. case 'I':
  3621. case 'J':
  3622. case 'K':
  3623. case 'L':
  3624. case 'M':
  3625. case 'N':
  3626. case 'O':
  3627. case 'P':
  3628. case 'Q':
  3629. case 'R':
  3630. case 'S':
  3631. case 'T':
  3632. case 'U':
  3633. case 'V':
  3634. case 'W':
  3635. case 'X':
  3636. case 'Y':
  3637. case 'Z':
  3638. // From rule "ALPHA" (lowercase half)
  3639. case 'a':
  3640. case 'b':
  3641. case 'c':
  3642. case 'd':
  3643. case 'e':
  3644. case 'f':
  3645. case 'g':
  3646. case 'h':
  3647. case 'i':
  3648. case 'j':
  3649. case 'k':
  3650. case 'l':
  3651. case 'm':
  3652. case 'n':
  3653. case 'o':
  3654. case 'p':
  3655. case 'q':
  3656. case 'r':
  3657. case 's':
  3658. case 't':
  3659. case 'u':
  3660. case 'v':
  3661. case 'w':
  3662. case 'x':
  3663. case 'y':
  3664. case 'z':
  3665. // From rule "DIGIT"
  3666. case '0':
  3667. case '1':
  3668. case '2':
  3669. case '3':
  3670. case '4':
  3671. case '5':
  3672. case '6':
  3673. case '7':
  3674. case '8':
  3675. case '9':
  3676. // From rule "pct-encoded"
  3677. case '%':
  3678. // From rule "unreserved"
  3679. case '-':
  3680. case '.':
  3681. case '_':
  3682. case '~':
  3683. // From rule "gen-delims"
  3684. case ':':
  3685. case '/':
  3686. case '?':
  3687. case '#':
  3688. case '[':
  3689. case ']':
  3690. case '@':
  3691. // From rule "sub-delims"
  3692. case '!':
  3693. case '$':
  3694. case '&':
  3695. case '\'':
  3696. case '(':
  3697. case ')':
  3698. case '*':
  3699. case '+':
  3700. case ',':
  3701. case ';':
  3702. case '=':
  3703. return XML_TRUE;
  3704. default:
  3705. return XML_FALSE;
  3706. }
  3707. }
  3708. /* addBinding() overwrites the value of prefix->binding without checking.
  3709. Therefore one must keep track of the old value outside of addBinding().
  3710. */
  3711. static enum XML_Error
  3712. addBinding(XML_Parser parser, PREFIX *prefix, const ATTRIBUTE_ID *attId,
  3713. const XML_Char *uri, BINDING **bindingsPtr) {
  3714. // "http://www.w3.org/XML/1998/namespace"
  3715. static const XML_Char xmlNamespace[]
  3716. = {ASCII_h, ASCII_t, ASCII_t, ASCII_p, ASCII_COLON,
  3717. ASCII_SLASH, ASCII_SLASH, ASCII_w, ASCII_w, ASCII_w,
  3718. ASCII_PERIOD, ASCII_w, ASCII_3, ASCII_PERIOD, ASCII_o,
  3719. ASCII_r, ASCII_g, ASCII_SLASH, ASCII_X, ASCII_M,
  3720. ASCII_L, ASCII_SLASH, ASCII_1, ASCII_9, ASCII_9,
  3721. ASCII_8, ASCII_SLASH, ASCII_n, ASCII_a, ASCII_m,
  3722. ASCII_e, ASCII_s, ASCII_p, ASCII_a, ASCII_c,
  3723. ASCII_e, '\0'};
  3724. static const int xmlLen = (int)sizeof(xmlNamespace) / sizeof(XML_Char) - 1;
  3725. // "http://www.w3.org/2000/xmlns/"
  3726. static const XML_Char xmlnsNamespace[]
  3727. = {ASCII_h, ASCII_t, ASCII_t, ASCII_p, ASCII_COLON, ASCII_SLASH,
  3728. ASCII_SLASH, ASCII_w, ASCII_w, ASCII_w, ASCII_PERIOD, ASCII_w,
  3729. ASCII_3, ASCII_PERIOD, ASCII_o, ASCII_r, ASCII_g, ASCII_SLASH,
  3730. ASCII_2, ASCII_0, ASCII_0, ASCII_0, ASCII_SLASH, ASCII_x,
  3731. ASCII_m, ASCII_l, ASCII_n, ASCII_s, ASCII_SLASH, '\0'};
  3732. static const int xmlnsLen
  3733. = (int)sizeof(xmlnsNamespace) / sizeof(XML_Char) - 1;
  3734. XML_Bool mustBeXML = XML_FALSE;
  3735. XML_Bool isXML = XML_TRUE;
  3736. XML_Bool isXMLNS = XML_TRUE;
  3737. BINDING *b;
  3738. int len;
  3739. /* empty URI is only valid for default namespace per XML NS 1.0 (not 1.1) */
  3740. if (*uri == XML_T('\0') && prefix->name)
  3741. return XML_ERROR_UNDECLARING_PREFIX;
  3742. if (prefix->name && prefix->name[0] == XML_T(ASCII_x)
  3743. && prefix->name[1] == XML_T(ASCII_m)
  3744. && prefix->name[2] == XML_T(ASCII_l)) {
  3745. /* Not allowed to bind xmlns */
  3746. if (prefix->name[3] == XML_T(ASCII_n) && prefix->name[4] == XML_T(ASCII_s)
  3747. && prefix->name[5] == XML_T('\0'))
  3748. return XML_ERROR_RESERVED_PREFIX_XMLNS;
  3749. if (prefix->name[3] == XML_T('\0'))
  3750. mustBeXML = XML_TRUE;
  3751. }
  3752. for (len = 0; uri[len]; len++) {
  3753. if (isXML && (len > xmlLen || uri[len] != xmlNamespace[len]))
  3754. isXML = XML_FALSE;
  3755. if (! mustBeXML && isXMLNS
  3756. && (len > xmlnsLen || uri[len] != xmlnsNamespace[len]))
  3757. isXMLNS = XML_FALSE;
  3758. // NOTE: While Expat does not validate namespace URIs against RFC 3986
  3759. // today (and is not REQUIRED to do so with regard to the XML 1.0
  3760. // namespaces specification) we have to at least make sure, that
  3761. // the application on top of Expat (that is likely splitting expanded
  3762. // element names ("qualified names") of form
  3763. // "[uri sep] local [sep prefix] '\0'" back into 1, 2 or 3 pieces
  3764. // in its element handler code) cannot be confused by an attacker
  3765. // putting additional namespace separator characters into namespace
  3766. // declarations. That would be ambiguous and not to be expected.
  3767. //
  3768. // While the HTML API docs of function XML_ParserCreateNS have been
  3769. // advising against use of a namespace separator character that can
  3770. // appear in a URI for >20 years now, some widespread applications
  3771. // are using URI characters (':' (colon) in particular) for a
  3772. // namespace separator, in practice. To keep these applications
  3773. // functional, we only reject namespaces URIs containing the
  3774. // application-chosen namespace separator if the chosen separator
  3775. // is a non-URI character with regard to RFC 3986.
  3776. if (parser->m_ns && (uri[len] == parser->m_namespaceSeparator)
  3777. && ! is_rfc3986_uri_char(uri[len])) {
  3778. return XML_ERROR_SYNTAX;
  3779. }
  3780. }
  3781. isXML = isXML && len == xmlLen;
  3782. isXMLNS = isXMLNS && len == xmlnsLen;
  3783. if (mustBeXML != isXML)
  3784. return mustBeXML ? XML_ERROR_RESERVED_PREFIX_XML
  3785. : XML_ERROR_RESERVED_NAMESPACE_URI;
  3786. if (isXMLNS)
  3787. return XML_ERROR_RESERVED_NAMESPACE_URI;
  3788. if (parser->m_namespaceSeparator)
  3789. len++;
  3790. if (parser->m_freeBindingList) {
  3791. b = parser->m_freeBindingList;
  3792. if (len > b->uriAlloc) {
  3793. /* Detect and prevent integer overflow */
  3794. if (len > INT_MAX - EXPAND_SPARE) {
  3795. return XML_ERROR_NO_MEMORY;
  3796. }
  3797. /* Detect and prevent integer overflow.
  3798. * The preprocessor guard addresses the "always false" warning
  3799. * from -Wtype-limits on platforms where
  3800. * sizeof(unsigned int) < sizeof(size_t), e.g. on x86_64. */
  3801. #if UINT_MAX >= SIZE_MAX
  3802. if ((unsigned)(len + EXPAND_SPARE) > (size_t)(-1) / sizeof(XML_Char)) {
  3803. return XML_ERROR_NO_MEMORY;
  3804. }
  3805. #endif
  3806. XML_Char *temp = (XML_Char *)REALLOC(
  3807. parser, b->uri, sizeof(XML_Char) * (len + EXPAND_SPARE));
  3808. if (temp == NULL)
  3809. return XML_ERROR_NO_MEMORY;
  3810. b->uri = temp;
  3811. b->uriAlloc = len + EXPAND_SPARE;
  3812. }
  3813. parser->m_freeBindingList = b->nextTagBinding;
  3814. } else {
  3815. b = (BINDING *)MALLOC(parser, sizeof(BINDING));
  3816. if (! b)
  3817. return XML_ERROR_NO_MEMORY;
  3818. /* Detect and prevent integer overflow */
  3819. if (len > INT_MAX - EXPAND_SPARE) {
  3820. return XML_ERROR_NO_MEMORY;
  3821. }
  3822. /* Detect and prevent integer overflow.
  3823. * The preprocessor guard addresses the "always false" warning
  3824. * from -Wtype-limits on platforms where
  3825. * sizeof(unsigned int) < sizeof(size_t), e.g. on x86_64. */
  3826. #if UINT_MAX >= SIZE_MAX
  3827. if ((unsigned)(len + EXPAND_SPARE) > (size_t)(-1) / sizeof(XML_Char)) {
  3828. return XML_ERROR_NO_MEMORY;
  3829. }
  3830. #endif
  3831. b->uri
  3832. = (XML_Char *)MALLOC(parser, sizeof(XML_Char) * (len + EXPAND_SPARE));
  3833. if (! b->uri) {
  3834. FREE(parser, b);
  3835. return XML_ERROR_NO_MEMORY;
  3836. }
  3837. b->uriAlloc = len + EXPAND_SPARE;
  3838. }
  3839. b->uriLen = len;
  3840. memcpy(b->uri, uri, len * sizeof(XML_Char));
  3841. if (parser->m_namespaceSeparator)
  3842. b->uri[len - 1] = parser->m_namespaceSeparator;
  3843. b->prefix = prefix;
  3844. b->attId = attId;
  3845. b->prevPrefixBinding = prefix->binding;
  3846. /* NULL binding when default namespace undeclared */
  3847. if (*uri == XML_T('\0') && prefix == &parser->m_dtd->defaultPrefix)
  3848. prefix->binding = NULL;
  3849. else
  3850. prefix->binding = b;
  3851. b->nextTagBinding = *bindingsPtr;
  3852. *bindingsPtr = b;
  3853. /* if attId == NULL then we are not starting a namespace scope */
  3854. if (attId && parser->m_startNamespaceDeclHandler)
  3855. parser->m_startNamespaceDeclHandler(parser->m_handlerArg, prefix->name,
  3856. prefix->binding ? uri : 0);
  3857. return XML_ERROR_NONE;
  3858. }
  3859. /* The idea here is to avoid using stack for each CDATA section when
  3860. the whole file is parsed with one call.
  3861. */
  3862. static enum XML_Error PTRCALL
  3863. cdataSectionProcessor(XML_Parser parser, const char *start, const char *end,
  3864. const char **endPtr) {
  3865. enum XML_Error result = doCdataSection(
  3866. parser, parser->m_encoding, &start, end, endPtr,
  3867. (XML_Bool)! parser->m_parsingStatus.finalBuffer, XML_ACCOUNT_DIRECT);
  3868. if (result != XML_ERROR_NONE)
  3869. return result;
  3870. if (start) {
  3871. if (parser->m_parentParser) { /* we are parsing an external entity */
  3872. parser->m_processor = externalEntityContentProcessor;
  3873. return externalEntityContentProcessor(parser, start, end, endPtr);
  3874. } else {
  3875. parser->m_processor = contentProcessor;
  3876. return contentProcessor(parser, start, end, endPtr);
  3877. }
  3878. }
  3879. return result;
  3880. }
  3881. /* startPtr gets set to non-null if the section is closed, and to null if
  3882. the section is not yet closed.
  3883. */
  3884. static enum XML_Error
  3885. doCdataSection(XML_Parser parser, const ENCODING *enc, const char **startPtr,
  3886. const char *end, const char **nextPtr, XML_Bool haveMore,
  3887. enum XML_Account account) {
  3888. const char *s = *startPtr;
  3889. const char **eventPP;
  3890. const char **eventEndPP;
  3891. if (enc == parser->m_encoding) {
  3892. eventPP = &parser->m_eventPtr;
  3893. *eventPP = s;
  3894. eventEndPP = &parser->m_eventEndPtr;
  3895. } else {
  3896. eventPP = &(parser->m_openInternalEntities->internalEventPtr);
  3897. eventEndPP = &(parser->m_openInternalEntities->internalEventEndPtr);
  3898. }
  3899. *eventPP = s;
  3900. *startPtr = NULL;
  3901. for (;;) {
  3902. const char *next = s; /* in case of XML_TOK_NONE or XML_TOK_PARTIAL */
  3903. int tok = XmlCdataSectionTok(enc, s, end, &next);
  3904. #if XML_GE == 1
  3905. if (! accountingDiffTolerated(parser, tok, s, next, __LINE__, account)) {
  3906. accountingOnAbort(parser);
  3907. return XML_ERROR_AMPLIFICATION_LIMIT_BREACH;
  3908. }
  3909. #else
  3910. UNUSED_P(account);
  3911. #endif
  3912. *eventEndPP = next;
  3913. switch (tok) {
  3914. case XML_TOK_CDATA_SECT_CLOSE:
  3915. if (parser->m_endCdataSectionHandler)
  3916. parser->m_endCdataSectionHandler(parser->m_handlerArg);
  3917. /* BEGIN disabled code */
  3918. /* see comment under XML_TOK_CDATA_SECT_OPEN */
  3919. else if ((0) && parser->m_characterDataHandler)
  3920. parser->m_characterDataHandler(parser->m_handlerArg, parser->m_dataBuf,
  3921. 0);
  3922. /* END disabled code */
  3923. else if (parser->m_defaultHandler)
  3924. reportDefault(parser, enc, s, next);
  3925. *startPtr = next;
  3926. *nextPtr = next;
  3927. if (parser->m_parsingStatus.parsing == XML_FINISHED)
  3928. return XML_ERROR_ABORTED;
  3929. else
  3930. return XML_ERROR_NONE;
  3931. case XML_TOK_DATA_NEWLINE:
  3932. if (parser->m_characterDataHandler) {
  3933. XML_Char c = 0xA;
  3934. parser->m_characterDataHandler(parser->m_handlerArg, &c, 1);
  3935. } else if (parser->m_defaultHandler)
  3936. reportDefault(parser, enc, s, next);
  3937. break;
  3938. case XML_TOK_DATA_CHARS: {
  3939. XML_CharacterDataHandler charDataHandler = parser->m_characterDataHandler;
  3940. if (charDataHandler) {
  3941. if (MUST_CONVERT(enc, s)) {
  3942. for (;;) {
  3943. ICHAR *dataPtr = (ICHAR *)parser->m_dataBuf;
  3944. const enum XML_Convert_Result convert_res = XmlConvert(
  3945. enc, &s, next, &dataPtr, (ICHAR *)parser->m_dataBufEnd);
  3946. *eventEndPP = next;
  3947. charDataHandler(parser->m_handlerArg, parser->m_dataBuf,
  3948. (int)(dataPtr - (ICHAR *)parser->m_dataBuf));
  3949. if ((convert_res == XML_CONVERT_COMPLETED)
  3950. || (convert_res == XML_CONVERT_INPUT_INCOMPLETE))
  3951. break;
  3952. *eventPP = s;
  3953. }
  3954. } else
  3955. charDataHandler(parser->m_handlerArg, (const XML_Char *)s,
  3956. (int)((const XML_Char *)next - (const XML_Char *)s));
  3957. } else if (parser->m_defaultHandler)
  3958. reportDefault(parser, enc, s, next);
  3959. } break;
  3960. case XML_TOK_INVALID:
  3961. *eventPP = next;
  3962. return XML_ERROR_INVALID_TOKEN;
  3963. case XML_TOK_PARTIAL_CHAR:
  3964. if (haveMore) {
  3965. *nextPtr = s;
  3966. return XML_ERROR_NONE;
  3967. }
  3968. return XML_ERROR_PARTIAL_CHAR;
  3969. case XML_TOK_PARTIAL:
  3970. case XML_TOK_NONE:
  3971. if (haveMore) {
  3972. *nextPtr = s;
  3973. return XML_ERROR_NONE;
  3974. }
  3975. return XML_ERROR_UNCLOSED_CDATA_SECTION;
  3976. default:
  3977. /* Every token returned by XmlCdataSectionTok() has its own
  3978. * explicit case, so this default case will never be executed.
  3979. * We retain it as a safety net and exclude it from the coverage
  3980. * statistics.
  3981. *
  3982. * LCOV_EXCL_START
  3983. */
  3984. *eventPP = next;
  3985. return XML_ERROR_UNEXPECTED_STATE;
  3986. /* LCOV_EXCL_STOP */
  3987. }
  3988. switch (parser->m_parsingStatus.parsing) {
  3989. case XML_SUSPENDED:
  3990. *eventPP = next;
  3991. *nextPtr = next;
  3992. return XML_ERROR_NONE;
  3993. case XML_FINISHED:
  3994. *eventPP = next;
  3995. return XML_ERROR_ABORTED;
  3996. case XML_PARSING:
  3997. if (parser->m_reenter) {
  3998. return XML_ERROR_UNEXPECTED_STATE; // LCOV_EXCL_LINE
  3999. }
  4000. /* Fall through */
  4001. default:;
  4002. *eventPP = s = next;
  4003. }
  4004. }
  4005. /* not reached */
  4006. }
  4007. #ifdef XML_DTD
  4008. /* The idea here is to avoid using stack for each IGNORE section when
  4009. the whole file is parsed with one call.
  4010. */
  4011. static enum XML_Error PTRCALL
  4012. ignoreSectionProcessor(XML_Parser parser, const char *start, const char *end,
  4013. const char **endPtr) {
  4014. enum XML_Error result
  4015. = doIgnoreSection(parser, parser->m_encoding, &start, end, endPtr,
  4016. (XML_Bool)! parser->m_parsingStatus.finalBuffer);
  4017. if (result != XML_ERROR_NONE)
  4018. return result;
  4019. if (start) {
  4020. parser->m_processor = prologProcessor;
  4021. return prologProcessor(parser, start, end, endPtr);
  4022. }
  4023. return result;
  4024. }
  4025. /* startPtr gets set to non-null is the section is closed, and to null
  4026. if the section is not yet closed.
  4027. */
  4028. static enum XML_Error
  4029. doIgnoreSection(XML_Parser parser, const ENCODING *enc, const char **startPtr,
  4030. const char *end, const char **nextPtr, XML_Bool haveMore) {
  4031. const char *next = *startPtr; /* in case of XML_TOK_NONE or XML_TOK_PARTIAL */
  4032. int tok;
  4033. const char *s = *startPtr;
  4034. const char **eventPP;
  4035. const char **eventEndPP;
  4036. if (enc == parser->m_encoding) {
  4037. eventPP = &parser->m_eventPtr;
  4038. *eventPP = s;
  4039. eventEndPP = &parser->m_eventEndPtr;
  4040. } else {
  4041. /* It's not entirely clear, but it seems the following two lines
  4042. * of code cannot be executed. The only occasions on which 'enc'
  4043. * is not 'encoding' are when this function is called
  4044. * from the internal entity processing, and IGNORE sections are an
  4045. * error in internal entities.
  4046. *
  4047. * Since it really isn't clear that this is true, we keep the code
  4048. * and just remove it from our coverage tests.
  4049. *
  4050. * LCOV_EXCL_START
  4051. */
  4052. eventPP = &(parser->m_openInternalEntities->internalEventPtr);
  4053. eventEndPP = &(parser->m_openInternalEntities->internalEventEndPtr);
  4054. /* LCOV_EXCL_STOP */
  4055. }
  4056. *eventPP = s;
  4057. *startPtr = NULL;
  4058. tok = XmlIgnoreSectionTok(enc, s, end, &next);
  4059. # if XML_GE == 1
  4060. if (! accountingDiffTolerated(parser, tok, s, next, __LINE__,
  4061. XML_ACCOUNT_DIRECT)) {
  4062. accountingOnAbort(parser);
  4063. return XML_ERROR_AMPLIFICATION_LIMIT_BREACH;
  4064. }
  4065. # endif
  4066. *eventEndPP = next;
  4067. switch (tok) {
  4068. case XML_TOK_IGNORE_SECT:
  4069. if (parser->m_defaultHandler)
  4070. reportDefault(parser, enc, s, next);
  4071. *startPtr = next;
  4072. *nextPtr = next;
  4073. if (parser->m_parsingStatus.parsing == XML_FINISHED)
  4074. return XML_ERROR_ABORTED;
  4075. else
  4076. return XML_ERROR_NONE;
  4077. case XML_TOK_INVALID:
  4078. *eventPP = next;
  4079. return XML_ERROR_INVALID_TOKEN;
  4080. case XML_TOK_PARTIAL_CHAR:
  4081. if (haveMore) {
  4082. *nextPtr = s;
  4083. return XML_ERROR_NONE;
  4084. }
  4085. return XML_ERROR_PARTIAL_CHAR;
  4086. case XML_TOK_PARTIAL:
  4087. case XML_TOK_NONE:
  4088. if (haveMore) {
  4089. *nextPtr = s;
  4090. return XML_ERROR_NONE;
  4091. }
  4092. return XML_ERROR_SYNTAX; /* XML_ERROR_UNCLOSED_IGNORE_SECTION */
  4093. default:
  4094. /* All of the tokens that XmlIgnoreSectionTok() returns have
  4095. * explicit cases to handle them, so this default case is never
  4096. * executed. We keep it as a safety net anyway, and remove it
  4097. * from our test coverage statistics.
  4098. *
  4099. * LCOV_EXCL_START
  4100. */
  4101. *eventPP = next;
  4102. return XML_ERROR_UNEXPECTED_STATE;
  4103. /* LCOV_EXCL_STOP */
  4104. }
  4105. /* not reached */
  4106. }
  4107. #endif /* XML_DTD */
  4108. static enum XML_Error
  4109. initializeEncoding(XML_Parser parser) {
  4110. const char *s;
  4111. #ifdef XML_UNICODE
  4112. char encodingBuf[128];
  4113. /* See comments about `protocolEncodingName` in parserInit() */
  4114. if (! parser->m_protocolEncodingName)
  4115. s = NULL;
  4116. else {
  4117. int i;
  4118. for (i = 0; parser->m_protocolEncodingName[i]; i++) {
  4119. if (i == sizeof(encodingBuf) - 1
  4120. || (parser->m_protocolEncodingName[i] & ~0x7f) != 0) {
  4121. encodingBuf[0] = '\0';
  4122. break;
  4123. }
  4124. encodingBuf[i] = (char)parser->m_protocolEncodingName[i];
  4125. }
  4126. encodingBuf[i] = '\0';
  4127. s = encodingBuf;
  4128. }
  4129. #else
  4130. s = parser->m_protocolEncodingName;
  4131. #endif
  4132. if ((parser->m_ns ? XmlInitEncodingNS : XmlInitEncoding)(
  4133. &parser->m_initEncoding, &parser->m_encoding, s))
  4134. return XML_ERROR_NONE;
  4135. return handleUnknownEncoding(parser, parser->m_protocolEncodingName);
  4136. }
  4137. static enum XML_Error
  4138. processXmlDecl(XML_Parser parser, int isGeneralTextEntity, const char *s,
  4139. const char *next) {
  4140. const char *encodingName = NULL;
  4141. const XML_Char *storedEncName = NULL;
  4142. const ENCODING *newEncoding = NULL;
  4143. const char *version = NULL;
  4144. const char *versionend = NULL;
  4145. const XML_Char *storedversion = NULL;
  4146. int standalone = -1;
  4147. #if XML_GE == 1
  4148. if (! accountingDiffTolerated(parser, XML_TOK_XML_DECL, s, next, __LINE__,
  4149. XML_ACCOUNT_DIRECT)) {
  4150. accountingOnAbort(parser);
  4151. return XML_ERROR_AMPLIFICATION_LIMIT_BREACH;
  4152. }
  4153. #endif
  4154. if (! (parser->m_ns ? XmlParseXmlDeclNS : XmlParseXmlDecl)(
  4155. isGeneralTextEntity, parser->m_encoding, s, next, &parser->m_eventPtr,
  4156. &version, &versionend, &encodingName, &newEncoding, &standalone)) {
  4157. if (isGeneralTextEntity)
  4158. return XML_ERROR_TEXT_DECL;
  4159. else
  4160. return XML_ERROR_XML_DECL;
  4161. }
  4162. if (! isGeneralTextEntity && standalone == 1) {
  4163. parser->m_dtd->standalone = XML_TRUE;
  4164. #ifdef XML_DTD
  4165. if (parser->m_paramEntityParsing
  4166. == XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE)
  4167. parser->m_paramEntityParsing = XML_PARAM_ENTITY_PARSING_NEVER;
  4168. #endif /* XML_DTD */
  4169. }
  4170. if (parser->m_xmlDeclHandler) {
  4171. if (encodingName != NULL) {
  4172. storedEncName = poolStoreString(
  4173. &parser->m_temp2Pool, parser->m_encoding, encodingName,
  4174. encodingName + XmlNameLength(parser->m_encoding, encodingName));
  4175. if (! storedEncName)
  4176. return XML_ERROR_NO_MEMORY;
  4177. poolFinish(&parser->m_temp2Pool);
  4178. }
  4179. if (version) {
  4180. storedversion
  4181. = poolStoreString(&parser->m_temp2Pool, parser->m_encoding, version,
  4182. versionend - parser->m_encoding->minBytesPerChar);
  4183. if (! storedversion)
  4184. return XML_ERROR_NO_MEMORY;
  4185. }
  4186. parser->m_xmlDeclHandler(parser->m_handlerArg, storedversion, storedEncName,
  4187. standalone);
  4188. } else if (parser->m_defaultHandler)
  4189. reportDefault(parser, parser->m_encoding, s, next);
  4190. if (parser->m_protocolEncodingName == NULL) {
  4191. if (newEncoding) {
  4192. /* Check that the specified encoding does not conflict with what
  4193. * the parser has already deduced. Do we have the same number
  4194. * of bytes in the smallest representation of a character? If
  4195. * this is UTF-16, is it the same endianness?
  4196. */
  4197. if (newEncoding->minBytesPerChar != parser->m_encoding->minBytesPerChar
  4198. || (newEncoding->minBytesPerChar == 2
  4199. && newEncoding != parser->m_encoding)) {
  4200. parser->m_eventPtr = encodingName;
  4201. return XML_ERROR_INCORRECT_ENCODING;
  4202. }
  4203. parser->m_encoding = newEncoding;
  4204. } else if (encodingName) {
  4205. enum XML_Error result;
  4206. if (! storedEncName) {
  4207. storedEncName = poolStoreString(
  4208. &parser->m_temp2Pool, parser->m_encoding, encodingName,
  4209. encodingName + XmlNameLength(parser->m_encoding, encodingName));
  4210. if (! storedEncName)
  4211. return XML_ERROR_NO_MEMORY;
  4212. }
  4213. result = handleUnknownEncoding(parser, storedEncName);
  4214. poolClear(&parser->m_temp2Pool);
  4215. if (result == XML_ERROR_UNKNOWN_ENCODING)
  4216. parser->m_eventPtr = encodingName;
  4217. return result;
  4218. }
  4219. }
  4220. if (storedEncName || storedversion)
  4221. poolClear(&parser->m_temp2Pool);
  4222. return XML_ERROR_NONE;
  4223. }
  4224. static enum XML_Error
  4225. handleUnknownEncoding(XML_Parser parser, const XML_Char *encodingName) {
  4226. if (parser->m_unknownEncodingHandler) {
  4227. XML_Encoding info;
  4228. int i;
  4229. for (i = 0; i < 256; i++)
  4230. info.map[i] = -1;
  4231. info.convert = NULL;
  4232. info.data = NULL;
  4233. info.release = NULL;
  4234. if (parser->m_unknownEncodingHandler(parser->m_unknownEncodingHandlerData,
  4235. encodingName, &info)) {
  4236. ENCODING *enc;
  4237. parser->m_unknownEncodingMem = MALLOC(parser, XmlSizeOfUnknownEncoding());
  4238. if (! parser->m_unknownEncodingMem) {
  4239. if (info.release)
  4240. info.release(info.data);
  4241. return XML_ERROR_NO_MEMORY;
  4242. }
  4243. enc = (parser->m_ns ? XmlInitUnknownEncodingNS : XmlInitUnknownEncoding)(
  4244. parser->m_unknownEncodingMem, info.map, info.convert, info.data);
  4245. if (enc) {
  4246. parser->m_unknownEncodingData = info.data;
  4247. parser->m_unknownEncodingRelease = info.release;
  4248. parser->m_encoding = enc;
  4249. return XML_ERROR_NONE;
  4250. }
  4251. }
  4252. if (info.release != NULL)
  4253. info.release(info.data);
  4254. }
  4255. return XML_ERROR_UNKNOWN_ENCODING;
  4256. }
  4257. static enum XML_Error PTRCALL
  4258. prologInitProcessor(XML_Parser parser, const char *s, const char *end,
  4259. const char **nextPtr) {
  4260. enum XML_Error result = initializeEncoding(parser);
  4261. if (result != XML_ERROR_NONE)
  4262. return result;
  4263. parser->m_processor = prologProcessor;
  4264. return prologProcessor(parser, s, end, nextPtr);
  4265. }
  4266. #ifdef XML_DTD
  4267. static enum XML_Error PTRCALL
  4268. externalParEntInitProcessor(XML_Parser parser, const char *s, const char *end,
  4269. const char **nextPtr) {
  4270. enum XML_Error result = initializeEncoding(parser);
  4271. if (result != XML_ERROR_NONE)
  4272. return result;
  4273. /* we know now that XML_Parse(Buffer) has been called,
  4274. so we consider the external parameter entity read */
  4275. parser->m_dtd->paramEntityRead = XML_TRUE;
  4276. if (parser->m_prologState.inEntityValue) {
  4277. parser->m_processor = entityValueInitProcessor;
  4278. return entityValueInitProcessor(parser, s, end, nextPtr);
  4279. } else {
  4280. parser->m_processor = externalParEntProcessor;
  4281. return externalParEntProcessor(parser, s, end, nextPtr);
  4282. }
  4283. }
  4284. static enum XML_Error PTRCALL
  4285. entityValueInitProcessor(XML_Parser parser, const char *s, const char *end,
  4286. const char **nextPtr) {
  4287. int tok;
  4288. const char *start = s;
  4289. const char *next = start;
  4290. parser->m_eventPtr = start;
  4291. for (;;) {
  4292. tok = XmlPrologTok(parser->m_encoding, start, end, &next);
  4293. /* Note: Except for XML_TOK_BOM below, these bytes are accounted later in:
  4294. - storeEntityValue
  4295. - processXmlDecl
  4296. */
  4297. parser->m_eventEndPtr = next;
  4298. if (tok <= 0) {
  4299. if (! parser->m_parsingStatus.finalBuffer && tok != XML_TOK_INVALID) {
  4300. *nextPtr = s;
  4301. return XML_ERROR_NONE;
  4302. }
  4303. switch (tok) {
  4304. case XML_TOK_INVALID:
  4305. return XML_ERROR_INVALID_TOKEN;
  4306. case XML_TOK_PARTIAL:
  4307. return XML_ERROR_UNCLOSED_TOKEN;
  4308. case XML_TOK_PARTIAL_CHAR:
  4309. return XML_ERROR_PARTIAL_CHAR;
  4310. case XML_TOK_NONE: /* start == end */
  4311. default:
  4312. break;
  4313. }
  4314. /* found end of entity value - can store it now */
  4315. return storeEntityValue(parser, parser->m_encoding, s, end,
  4316. XML_ACCOUNT_DIRECT, NULL);
  4317. } else if (tok == XML_TOK_XML_DECL) {
  4318. enum XML_Error result;
  4319. result = processXmlDecl(parser, 0, start, next);
  4320. if (result != XML_ERROR_NONE)
  4321. return result;
  4322. /* At this point, m_parsingStatus.parsing cannot be XML_SUSPENDED. For
  4323. * that to happen, a parameter entity parsing handler must have attempted
  4324. * to suspend the parser, which fails and raises an error. The parser can
  4325. * be aborted, but can't be suspended.
  4326. */
  4327. if (parser->m_parsingStatus.parsing == XML_FINISHED)
  4328. return XML_ERROR_ABORTED;
  4329. *nextPtr = next;
  4330. /* stop scanning for text declaration - we found one */
  4331. parser->m_processor = entityValueProcessor;
  4332. return entityValueProcessor(parser, next, end, nextPtr);
  4333. }
  4334. /* XmlPrologTok has now set the encoding based on the BOM it found, and we
  4335. must move s and nextPtr forward to consume the BOM.
  4336. If we didn't, and got XML_TOK_NONE from the next XmlPrologTok call, we
  4337. would leave the BOM in the buffer and return. On the next call to this
  4338. function, our XmlPrologTok call would return XML_TOK_INVALID, since it
  4339. is not valid to have multiple BOMs.
  4340. */
  4341. else if (tok == XML_TOK_BOM) {
  4342. # if XML_GE == 1
  4343. if (! accountingDiffTolerated(parser, tok, s, next, __LINE__,
  4344. XML_ACCOUNT_DIRECT)) {
  4345. accountingOnAbort(parser);
  4346. return XML_ERROR_AMPLIFICATION_LIMIT_BREACH;
  4347. }
  4348. # endif
  4349. *nextPtr = next;
  4350. s = next;
  4351. }
  4352. /* If we get this token, we have the start of what might be a
  4353. normal tag, but not a declaration (i.e. it doesn't begin with
  4354. "<!"). In a DTD context, that isn't legal.
  4355. */
  4356. else if (tok == XML_TOK_INSTANCE_START) {
  4357. *nextPtr = next;
  4358. return XML_ERROR_SYNTAX;
  4359. }
  4360. start = next;
  4361. parser->m_eventPtr = start;
  4362. }
  4363. }
  4364. static enum XML_Error PTRCALL
  4365. externalParEntProcessor(XML_Parser parser, const char *s, const char *end,
  4366. const char **nextPtr) {
  4367. const char *next = s;
  4368. int tok;
  4369. tok = XmlPrologTok(parser->m_encoding, s, end, &next);
  4370. if (tok <= 0) {
  4371. if (! parser->m_parsingStatus.finalBuffer && tok != XML_TOK_INVALID) {
  4372. *nextPtr = s;
  4373. return XML_ERROR_NONE;
  4374. }
  4375. switch (tok) {
  4376. case XML_TOK_INVALID:
  4377. return XML_ERROR_INVALID_TOKEN;
  4378. case XML_TOK_PARTIAL:
  4379. return XML_ERROR_UNCLOSED_TOKEN;
  4380. case XML_TOK_PARTIAL_CHAR:
  4381. return XML_ERROR_PARTIAL_CHAR;
  4382. case XML_TOK_NONE: /* start == end */
  4383. default:
  4384. break;
  4385. }
  4386. }
  4387. /* This would cause the next stage, i.e. doProlog to be passed XML_TOK_BOM.
  4388. However, when parsing an external subset, doProlog will not accept a BOM
  4389. as valid, and report a syntax error, so we have to skip the BOM, and
  4390. account for the BOM bytes.
  4391. */
  4392. else if (tok == XML_TOK_BOM) {
  4393. if (! accountingDiffTolerated(parser, tok, s, next, __LINE__,
  4394. XML_ACCOUNT_DIRECT)) {
  4395. accountingOnAbort(parser);
  4396. return XML_ERROR_AMPLIFICATION_LIMIT_BREACH;
  4397. }
  4398. s = next;
  4399. tok = XmlPrologTok(parser->m_encoding, s, end, &next);
  4400. }
  4401. parser->m_processor = prologProcessor;
  4402. return doProlog(parser, parser->m_encoding, s, end, tok, next, nextPtr,
  4403. (XML_Bool)! parser->m_parsingStatus.finalBuffer, XML_TRUE,
  4404. XML_ACCOUNT_DIRECT);
  4405. }
  4406. static enum XML_Error PTRCALL
  4407. entityValueProcessor(XML_Parser parser, const char *s, const char *end,
  4408. const char **nextPtr) {
  4409. const char *start = s;
  4410. const char *next = s;
  4411. const ENCODING *enc = parser->m_encoding;
  4412. int tok;
  4413. for (;;) {
  4414. tok = XmlPrologTok(enc, start, end, &next);
  4415. /* Note: These bytes are accounted later in:
  4416. - storeEntityValue
  4417. */
  4418. if (tok <= 0) {
  4419. if (! parser->m_parsingStatus.finalBuffer && tok != XML_TOK_INVALID) {
  4420. *nextPtr = s;
  4421. return XML_ERROR_NONE;
  4422. }
  4423. switch (tok) {
  4424. case XML_TOK_INVALID:
  4425. return XML_ERROR_INVALID_TOKEN;
  4426. case XML_TOK_PARTIAL:
  4427. return XML_ERROR_UNCLOSED_TOKEN;
  4428. case XML_TOK_PARTIAL_CHAR:
  4429. return XML_ERROR_PARTIAL_CHAR;
  4430. case XML_TOK_NONE: /* start == end */
  4431. default:
  4432. break;
  4433. }
  4434. /* found end of entity value - can store it now */
  4435. return storeEntityValue(parser, enc, s, end, XML_ACCOUNT_DIRECT, NULL);
  4436. }
  4437. start = next;
  4438. }
  4439. }
  4440. #endif /* XML_DTD */
  4441. static enum XML_Error PTRCALL
  4442. prologProcessor(XML_Parser parser, const char *s, const char *end,
  4443. const char **nextPtr) {
  4444. const char *next = s;
  4445. int tok = XmlPrologTok(parser->m_encoding, s, end, &next);
  4446. return doProlog(parser, parser->m_encoding, s, end, tok, next, nextPtr,
  4447. (XML_Bool)! parser->m_parsingStatus.finalBuffer, XML_TRUE,
  4448. XML_ACCOUNT_DIRECT);
  4449. }
  4450. static enum XML_Error
  4451. doProlog(XML_Parser parser, const ENCODING *enc, const char *s, const char *end,
  4452. int tok, const char *next, const char **nextPtr, XML_Bool haveMore,
  4453. XML_Bool allowClosingDoctype, enum XML_Account account) {
  4454. #ifdef XML_DTD
  4455. static const XML_Char externalSubsetName[] = {ASCII_HASH, '\0'};
  4456. #endif /* XML_DTD */
  4457. static const XML_Char atypeCDATA[]
  4458. = {ASCII_C, ASCII_D, ASCII_A, ASCII_T, ASCII_A, '\0'};
  4459. static const XML_Char atypeID[] = {ASCII_I, ASCII_D, '\0'};
  4460. static const XML_Char atypeIDREF[]
  4461. = {ASCII_I, ASCII_D, ASCII_R, ASCII_E, ASCII_F, '\0'};
  4462. static const XML_Char atypeIDREFS[]
  4463. = {ASCII_I, ASCII_D, ASCII_R, ASCII_E, ASCII_F, ASCII_S, '\0'};
  4464. static const XML_Char atypeENTITY[]
  4465. = {ASCII_E, ASCII_N, ASCII_T, ASCII_I, ASCII_T, ASCII_Y, '\0'};
  4466. static const XML_Char atypeENTITIES[]
  4467. = {ASCII_E, ASCII_N, ASCII_T, ASCII_I, ASCII_T,
  4468. ASCII_I, ASCII_E, ASCII_S, '\0'};
  4469. static const XML_Char atypeNMTOKEN[]
  4470. = {ASCII_N, ASCII_M, ASCII_T, ASCII_O, ASCII_K, ASCII_E, ASCII_N, '\0'};
  4471. static const XML_Char atypeNMTOKENS[]
  4472. = {ASCII_N, ASCII_M, ASCII_T, ASCII_O, ASCII_K,
  4473. ASCII_E, ASCII_N, ASCII_S, '\0'};
  4474. static const XML_Char notationPrefix[]
  4475. = {ASCII_N, ASCII_O, ASCII_T, ASCII_A, ASCII_T,
  4476. ASCII_I, ASCII_O, ASCII_N, ASCII_LPAREN, '\0'};
  4477. static const XML_Char enumValueSep[] = {ASCII_PIPE, '\0'};
  4478. static const XML_Char enumValueStart[] = {ASCII_LPAREN, '\0'};
  4479. #ifndef XML_DTD
  4480. UNUSED_P(account);
  4481. #endif
  4482. /* save one level of indirection */
  4483. DTD *const dtd = parser->m_dtd;
  4484. const char **eventPP;
  4485. const char **eventEndPP;
  4486. enum XML_Content_Quant quant;
  4487. if (enc == parser->m_encoding) {
  4488. eventPP = &parser->m_eventPtr;
  4489. eventEndPP = &parser->m_eventEndPtr;
  4490. } else {
  4491. eventPP = &(parser->m_openInternalEntities->internalEventPtr);
  4492. eventEndPP = &(parser->m_openInternalEntities->internalEventEndPtr);
  4493. }
  4494. for (;;) {
  4495. int role;
  4496. XML_Bool handleDefault = XML_TRUE;
  4497. *eventPP = s;
  4498. *eventEndPP = next;
  4499. if (tok <= 0) {
  4500. if (haveMore && tok != XML_TOK_INVALID) {
  4501. *nextPtr = s;
  4502. return XML_ERROR_NONE;
  4503. }
  4504. switch (tok) {
  4505. case XML_TOK_INVALID:
  4506. *eventPP = next;
  4507. return XML_ERROR_INVALID_TOKEN;
  4508. case XML_TOK_PARTIAL:
  4509. return XML_ERROR_UNCLOSED_TOKEN;
  4510. case XML_TOK_PARTIAL_CHAR:
  4511. return XML_ERROR_PARTIAL_CHAR;
  4512. case -XML_TOK_PROLOG_S:
  4513. tok = -tok;
  4514. break;
  4515. case XML_TOK_NONE:
  4516. #ifdef XML_DTD
  4517. /* for internal PE NOT referenced between declarations */
  4518. if (enc != parser->m_encoding
  4519. && ! parser->m_openInternalEntities->betweenDecl) {
  4520. *nextPtr = s;
  4521. return XML_ERROR_NONE;
  4522. }
  4523. /* WFC: PE Between Declarations - must check that PE contains
  4524. complete markup, not only for external PEs, but also for
  4525. internal PEs if the reference occurs between declarations.
  4526. */
  4527. if (parser->m_isParamEntity || enc != parser->m_encoding) {
  4528. if (XmlTokenRole(&parser->m_prologState, XML_TOK_NONE, end, end, enc)
  4529. == XML_ROLE_ERROR)
  4530. return XML_ERROR_INCOMPLETE_PE;
  4531. *nextPtr = s;
  4532. return XML_ERROR_NONE;
  4533. }
  4534. #endif /* XML_DTD */
  4535. return XML_ERROR_NO_ELEMENTS;
  4536. default:
  4537. tok = -tok;
  4538. next = end;
  4539. break;
  4540. }
  4541. }
  4542. role = XmlTokenRole(&parser->m_prologState, tok, s, next, enc);
  4543. #if XML_GE == 1
  4544. switch (role) {
  4545. case XML_ROLE_INSTANCE_START: // bytes accounted in contentProcessor
  4546. case XML_ROLE_XML_DECL: // bytes accounted in processXmlDecl
  4547. # ifdef XML_DTD
  4548. case XML_ROLE_TEXT_DECL: // bytes accounted in processXmlDecl
  4549. # endif
  4550. break;
  4551. default:
  4552. if (! accountingDiffTolerated(parser, tok, s, next, __LINE__, account)) {
  4553. accountingOnAbort(parser);
  4554. return XML_ERROR_AMPLIFICATION_LIMIT_BREACH;
  4555. }
  4556. }
  4557. #endif
  4558. switch (role) {
  4559. case XML_ROLE_XML_DECL: {
  4560. enum XML_Error result = processXmlDecl(parser, 0, s, next);
  4561. if (result != XML_ERROR_NONE)
  4562. return result;
  4563. enc = parser->m_encoding;
  4564. handleDefault = XML_FALSE;
  4565. } break;
  4566. case XML_ROLE_DOCTYPE_NAME:
  4567. if (parser->m_startDoctypeDeclHandler) {
  4568. parser->m_doctypeName
  4569. = poolStoreString(&parser->m_tempPool, enc, s, next);
  4570. if (! parser->m_doctypeName)
  4571. return XML_ERROR_NO_MEMORY;
  4572. poolFinish(&parser->m_tempPool);
  4573. parser->m_doctypePubid = NULL;
  4574. handleDefault = XML_FALSE;
  4575. }
  4576. parser->m_doctypeSysid = NULL; /* always initialize to NULL */
  4577. break;
  4578. case XML_ROLE_DOCTYPE_INTERNAL_SUBSET:
  4579. if (parser->m_startDoctypeDeclHandler) {
  4580. parser->m_startDoctypeDeclHandler(
  4581. parser->m_handlerArg, parser->m_doctypeName, parser->m_doctypeSysid,
  4582. parser->m_doctypePubid, 1);
  4583. parser->m_doctypeName = NULL;
  4584. poolClear(&parser->m_tempPool);
  4585. handleDefault = XML_FALSE;
  4586. }
  4587. break;
  4588. #ifdef XML_DTD
  4589. case XML_ROLE_TEXT_DECL: {
  4590. enum XML_Error result = processXmlDecl(parser, 1, s, next);
  4591. if (result != XML_ERROR_NONE)
  4592. return result;
  4593. enc = parser->m_encoding;
  4594. handleDefault = XML_FALSE;
  4595. } break;
  4596. #endif /* XML_DTD */
  4597. case XML_ROLE_DOCTYPE_PUBLIC_ID:
  4598. #ifdef XML_DTD
  4599. parser->m_useForeignDTD = XML_FALSE;
  4600. parser->m_declEntity = (ENTITY *)lookup(
  4601. parser, &dtd->paramEntities, externalSubsetName, sizeof(ENTITY));
  4602. if (! parser->m_declEntity)
  4603. return XML_ERROR_NO_MEMORY;
  4604. #endif /* XML_DTD */
  4605. dtd->hasParamEntityRefs = XML_TRUE;
  4606. if (parser->m_startDoctypeDeclHandler) {
  4607. XML_Char *pubId;
  4608. if (! XmlIsPublicId(enc, s, next, eventPP))
  4609. return XML_ERROR_PUBLICID;
  4610. pubId = poolStoreString(&parser->m_tempPool, enc,
  4611. s + enc->minBytesPerChar,
  4612. next - enc->minBytesPerChar);
  4613. if (! pubId)
  4614. return XML_ERROR_NO_MEMORY;
  4615. normalizePublicId(pubId);
  4616. poolFinish(&parser->m_tempPool);
  4617. parser->m_doctypePubid = pubId;
  4618. handleDefault = XML_FALSE;
  4619. goto alreadyChecked;
  4620. }
  4621. /* fall through */
  4622. case XML_ROLE_ENTITY_PUBLIC_ID:
  4623. if (! XmlIsPublicId(enc, s, next, eventPP))
  4624. return XML_ERROR_PUBLICID;
  4625. alreadyChecked:
  4626. if (dtd->keepProcessing && parser->m_declEntity) {
  4627. XML_Char *tem
  4628. = poolStoreString(&dtd->pool, enc, s + enc->minBytesPerChar,
  4629. next - enc->minBytesPerChar);
  4630. if (! tem)
  4631. return XML_ERROR_NO_MEMORY;
  4632. normalizePublicId(tem);
  4633. parser->m_declEntity->publicId = tem;
  4634. poolFinish(&dtd->pool);
  4635. /* Don't suppress the default handler if we fell through from
  4636. * the XML_ROLE_DOCTYPE_PUBLIC_ID case.
  4637. */
  4638. if (parser->m_entityDeclHandler && role == XML_ROLE_ENTITY_PUBLIC_ID)
  4639. handleDefault = XML_FALSE;
  4640. }
  4641. break;
  4642. case XML_ROLE_DOCTYPE_CLOSE:
  4643. if (allowClosingDoctype != XML_TRUE) {
  4644. /* Must not close doctype from within expanded parameter entities */
  4645. return XML_ERROR_INVALID_TOKEN;
  4646. }
  4647. if (parser->m_doctypeName) {
  4648. parser->m_startDoctypeDeclHandler(
  4649. parser->m_handlerArg, parser->m_doctypeName, parser->m_doctypeSysid,
  4650. parser->m_doctypePubid, 0);
  4651. poolClear(&parser->m_tempPool);
  4652. handleDefault = XML_FALSE;
  4653. }
  4654. /* parser->m_doctypeSysid will be non-NULL in the case of a previous
  4655. XML_ROLE_DOCTYPE_SYSTEM_ID, even if parser->m_startDoctypeDeclHandler
  4656. was not set, indicating an external subset
  4657. */
  4658. #ifdef XML_DTD
  4659. if (parser->m_doctypeSysid || parser->m_useForeignDTD) {
  4660. XML_Bool hadParamEntityRefs = dtd->hasParamEntityRefs;
  4661. dtd->hasParamEntityRefs = XML_TRUE;
  4662. if (parser->m_paramEntityParsing
  4663. && parser->m_externalEntityRefHandler) {
  4664. ENTITY *entity = (ENTITY *)lookup(parser, &dtd->paramEntities,
  4665. externalSubsetName, sizeof(ENTITY));
  4666. if (! entity) {
  4667. /* The external subset name "#" will have already been
  4668. * inserted into the hash table at the start of the
  4669. * external entity parsing, so no allocation will happen
  4670. * and lookup() cannot fail.
  4671. */
  4672. return XML_ERROR_NO_MEMORY; /* LCOV_EXCL_LINE */
  4673. }
  4674. if (parser->m_useForeignDTD)
  4675. entity->base = parser->m_curBase;
  4676. dtd->paramEntityRead = XML_FALSE;
  4677. if (! parser->m_externalEntityRefHandler(
  4678. parser->m_externalEntityRefHandlerArg, 0, entity->base,
  4679. entity->systemId, entity->publicId))
  4680. return XML_ERROR_EXTERNAL_ENTITY_HANDLING;
  4681. if (dtd->paramEntityRead) {
  4682. if (! dtd->standalone && parser->m_notStandaloneHandler
  4683. && ! parser->m_notStandaloneHandler(parser->m_handlerArg))
  4684. return XML_ERROR_NOT_STANDALONE;
  4685. }
  4686. /* if we didn't read the foreign DTD then this means that there
  4687. is no external subset and we must reset dtd->hasParamEntityRefs
  4688. */
  4689. else if (! parser->m_doctypeSysid)
  4690. dtd->hasParamEntityRefs = hadParamEntityRefs;
  4691. /* end of DTD - no need to update dtd->keepProcessing */
  4692. }
  4693. parser->m_useForeignDTD = XML_FALSE;
  4694. }
  4695. #endif /* XML_DTD */
  4696. if (parser->m_endDoctypeDeclHandler) {
  4697. parser->m_endDoctypeDeclHandler(parser->m_handlerArg);
  4698. handleDefault = XML_FALSE;
  4699. }
  4700. break;
  4701. case XML_ROLE_INSTANCE_START:
  4702. #ifdef XML_DTD
  4703. /* if there is no DOCTYPE declaration then now is the
  4704. last chance to read the foreign DTD
  4705. */
  4706. if (parser->m_useForeignDTD) {
  4707. XML_Bool hadParamEntityRefs = dtd->hasParamEntityRefs;
  4708. dtd->hasParamEntityRefs = XML_TRUE;
  4709. if (parser->m_paramEntityParsing
  4710. && parser->m_externalEntityRefHandler) {
  4711. ENTITY *entity = (ENTITY *)lookup(parser, &dtd->paramEntities,
  4712. externalSubsetName, sizeof(ENTITY));
  4713. if (! entity)
  4714. return XML_ERROR_NO_MEMORY;
  4715. entity->base = parser->m_curBase;
  4716. dtd->paramEntityRead = XML_FALSE;
  4717. if (! parser->m_externalEntityRefHandler(
  4718. parser->m_externalEntityRefHandlerArg, 0, entity->base,
  4719. entity->systemId, entity->publicId))
  4720. return XML_ERROR_EXTERNAL_ENTITY_HANDLING;
  4721. if (dtd->paramEntityRead) {
  4722. if (! dtd->standalone && parser->m_notStandaloneHandler
  4723. && ! parser->m_notStandaloneHandler(parser->m_handlerArg))
  4724. return XML_ERROR_NOT_STANDALONE;
  4725. }
  4726. /* if we didn't read the foreign DTD then this means that there
  4727. is no external subset and we must reset dtd->hasParamEntityRefs
  4728. */
  4729. else
  4730. dtd->hasParamEntityRefs = hadParamEntityRefs;
  4731. /* end of DTD - no need to update dtd->keepProcessing */
  4732. }
  4733. }
  4734. #endif /* XML_DTD */
  4735. parser->m_processor = contentProcessor;
  4736. return contentProcessor(parser, s, end, nextPtr);
  4737. case XML_ROLE_ATTLIST_ELEMENT_NAME:
  4738. parser->m_declElementType = getElementType(parser, enc, s, next);
  4739. if (! parser->m_declElementType)
  4740. return XML_ERROR_NO_MEMORY;
  4741. goto checkAttListDeclHandler;
  4742. case XML_ROLE_ATTRIBUTE_NAME:
  4743. parser->m_declAttributeId = getAttributeId(parser, enc, s, next);
  4744. if (! parser->m_declAttributeId)
  4745. return XML_ERROR_NO_MEMORY;
  4746. parser->m_declAttributeIsCdata = XML_FALSE;
  4747. parser->m_declAttributeType = NULL;
  4748. parser->m_declAttributeIsId = XML_FALSE;
  4749. goto checkAttListDeclHandler;
  4750. case XML_ROLE_ATTRIBUTE_TYPE_CDATA:
  4751. parser->m_declAttributeIsCdata = XML_TRUE;
  4752. parser->m_declAttributeType = atypeCDATA;
  4753. goto checkAttListDeclHandler;
  4754. case XML_ROLE_ATTRIBUTE_TYPE_ID:
  4755. parser->m_declAttributeIsId = XML_TRUE;
  4756. parser->m_declAttributeType = atypeID;
  4757. goto checkAttListDeclHandler;
  4758. case XML_ROLE_ATTRIBUTE_TYPE_IDREF:
  4759. parser->m_declAttributeType = atypeIDREF;
  4760. goto checkAttListDeclHandler;
  4761. case XML_ROLE_ATTRIBUTE_TYPE_IDREFS:
  4762. parser->m_declAttributeType = atypeIDREFS;
  4763. goto checkAttListDeclHandler;
  4764. case XML_ROLE_ATTRIBUTE_TYPE_ENTITY:
  4765. parser->m_declAttributeType = atypeENTITY;
  4766. goto checkAttListDeclHandler;
  4767. case XML_ROLE_ATTRIBUTE_TYPE_ENTITIES:
  4768. parser->m_declAttributeType = atypeENTITIES;
  4769. goto checkAttListDeclHandler;
  4770. case XML_ROLE_ATTRIBUTE_TYPE_NMTOKEN:
  4771. parser->m_declAttributeType = atypeNMTOKEN;
  4772. goto checkAttListDeclHandler;
  4773. case XML_ROLE_ATTRIBUTE_TYPE_NMTOKENS:
  4774. parser->m_declAttributeType = atypeNMTOKENS;
  4775. checkAttListDeclHandler:
  4776. if (dtd->keepProcessing && parser->m_attlistDeclHandler)
  4777. handleDefault = XML_FALSE;
  4778. break;
  4779. case XML_ROLE_ATTRIBUTE_ENUM_VALUE:
  4780. case XML_ROLE_ATTRIBUTE_NOTATION_VALUE:
  4781. if (dtd->keepProcessing && parser->m_attlistDeclHandler) {
  4782. const XML_Char *prefix;
  4783. if (parser->m_declAttributeType) {
  4784. prefix = enumValueSep;
  4785. } else {
  4786. prefix = (role == XML_ROLE_ATTRIBUTE_NOTATION_VALUE ? notationPrefix
  4787. : enumValueStart);
  4788. }
  4789. if (! poolAppendString(&parser->m_tempPool, prefix))
  4790. return XML_ERROR_NO_MEMORY;
  4791. if (! poolAppend(&parser->m_tempPool, enc, s, next))
  4792. return XML_ERROR_NO_MEMORY;
  4793. parser->m_declAttributeType = parser->m_tempPool.start;
  4794. handleDefault = XML_FALSE;
  4795. }
  4796. break;
  4797. case XML_ROLE_IMPLIED_ATTRIBUTE_VALUE:
  4798. case XML_ROLE_REQUIRED_ATTRIBUTE_VALUE:
  4799. if (dtd->keepProcessing) {
  4800. if (! defineAttribute(parser->m_declElementType,
  4801. parser->m_declAttributeId,
  4802. parser->m_declAttributeIsCdata,
  4803. parser->m_declAttributeIsId, 0, parser))
  4804. return XML_ERROR_NO_MEMORY;
  4805. if (parser->m_attlistDeclHandler && parser->m_declAttributeType) {
  4806. if (*parser->m_declAttributeType == XML_T(ASCII_LPAREN)
  4807. || (*parser->m_declAttributeType == XML_T(ASCII_N)
  4808. && parser->m_declAttributeType[1] == XML_T(ASCII_O))) {
  4809. /* Enumerated or Notation type */
  4810. if (! poolAppendChar(&parser->m_tempPool, XML_T(ASCII_RPAREN))
  4811. || ! poolAppendChar(&parser->m_tempPool, XML_T('\0')))
  4812. return XML_ERROR_NO_MEMORY;
  4813. parser->m_declAttributeType = parser->m_tempPool.start;
  4814. poolFinish(&parser->m_tempPool);
  4815. }
  4816. *eventEndPP = s;
  4817. parser->m_attlistDeclHandler(
  4818. parser->m_handlerArg, parser->m_declElementType->name,
  4819. parser->m_declAttributeId->name, parser->m_declAttributeType, 0,
  4820. role == XML_ROLE_REQUIRED_ATTRIBUTE_VALUE);
  4821. handleDefault = XML_FALSE;
  4822. }
  4823. }
  4824. poolClear(&parser->m_tempPool);
  4825. break;
  4826. case XML_ROLE_DEFAULT_ATTRIBUTE_VALUE:
  4827. case XML_ROLE_FIXED_ATTRIBUTE_VALUE:
  4828. if (dtd->keepProcessing) {
  4829. const XML_Char *attVal;
  4830. enum XML_Error result = storeAttributeValue(
  4831. parser, enc, parser->m_declAttributeIsCdata,
  4832. s + enc->minBytesPerChar, next - enc->minBytesPerChar, &dtd->pool,
  4833. XML_ACCOUNT_NONE);
  4834. if (result)
  4835. return result;
  4836. attVal = poolStart(&dtd->pool);
  4837. poolFinish(&dtd->pool);
  4838. /* ID attributes aren't allowed to have a default */
  4839. if (! defineAttribute(
  4840. parser->m_declElementType, parser->m_declAttributeId,
  4841. parser->m_declAttributeIsCdata, XML_FALSE, attVal, parser))
  4842. return XML_ERROR_NO_MEMORY;
  4843. if (parser->m_attlistDeclHandler && parser->m_declAttributeType) {
  4844. if (*parser->m_declAttributeType == XML_T(ASCII_LPAREN)
  4845. || (*parser->m_declAttributeType == XML_T(ASCII_N)
  4846. && parser->m_declAttributeType[1] == XML_T(ASCII_O))) {
  4847. /* Enumerated or Notation type */
  4848. if (! poolAppendChar(&parser->m_tempPool, XML_T(ASCII_RPAREN))
  4849. || ! poolAppendChar(&parser->m_tempPool, XML_T('\0')))
  4850. return XML_ERROR_NO_MEMORY;
  4851. parser->m_declAttributeType = parser->m_tempPool.start;
  4852. poolFinish(&parser->m_tempPool);
  4853. }
  4854. *eventEndPP = s;
  4855. parser->m_attlistDeclHandler(
  4856. parser->m_handlerArg, parser->m_declElementType->name,
  4857. parser->m_declAttributeId->name, parser->m_declAttributeType,
  4858. attVal, role == XML_ROLE_FIXED_ATTRIBUTE_VALUE);
  4859. poolClear(&parser->m_tempPool);
  4860. handleDefault = XML_FALSE;
  4861. }
  4862. }
  4863. break;
  4864. case XML_ROLE_ENTITY_VALUE:
  4865. if (dtd->keepProcessing) {
  4866. #if XML_GE == 1
  4867. // This will store the given replacement text in
  4868. // parser->m_declEntity->textPtr.
  4869. enum XML_Error result = callStoreEntityValue(
  4870. parser, enc, s + enc->minBytesPerChar, next - enc->minBytesPerChar,
  4871. XML_ACCOUNT_NONE);
  4872. if (parser->m_declEntity) {
  4873. parser->m_declEntity->textPtr = poolStart(&dtd->entityValuePool);
  4874. parser->m_declEntity->textLen
  4875. = (int)(poolLength(&dtd->entityValuePool));
  4876. poolFinish(&dtd->entityValuePool);
  4877. if (parser->m_entityDeclHandler) {
  4878. *eventEndPP = s;
  4879. parser->m_entityDeclHandler(
  4880. parser->m_handlerArg, parser->m_declEntity->name,
  4881. parser->m_declEntity->is_param, parser->m_declEntity->textPtr,
  4882. parser->m_declEntity->textLen, parser->m_curBase, 0, 0, 0);
  4883. handleDefault = XML_FALSE;
  4884. }
  4885. } else
  4886. poolDiscard(&dtd->entityValuePool);
  4887. if (result != XML_ERROR_NONE)
  4888. return result;
  4889. #else
  4890. // This will store "&amp;entity123;" in parser->m_declEntity->textPtr
  4891. // to end up as "&entity123;" in the handler.
  4892. if (parser->m_declEntity != NULL) {
  4893. const enum XML_Error result
  4894. = storeSelfEntityValue(parser, parser->m_declEntity);
  4895. if (result != XML_ERROR_NONE)
  4896. return result;
  4897. if (parser->m_entityDeclHandler) {
  4898. *eventEndPP = s;
  4899. parser->m_entityDeclHandler(
  4900. parser->m_handlerArg, parser->m_declEntity->name,
  4901. parser->m_declEntity->is_param, parser->m_declEntity->textPtr,
  4902. parser->m_declEntity->textLen, parser->m_curBase, 0, 0, 0);
  4903. handleDefault = XML_FALSE;
  4904. }
  4905. }
  4906. #endif
  4907. }
  4908. break;
  4909. case XML_ROLE_DOCTYPE_SYSTEM_ID:
  4910. #ifdef XML_DTD
  4911. parser->m_useForeignDTD = XML_FALSE;
  4912. #endif /* XML_DTD */
  4913. dtd->hasParamEntityRefs = XML_TRUE;
  4914. if (parser->m_startDoctypeDeclHandler) {
  4915. parser->m_doctypeSysid = poolStoreString(&parser->m_tempPool, enc,
  4916. s + enc->minBytesPerChar,
  4917. next - enc->minBytesPerChar);
  4918. if (parser->m_doctypeSysid == NULL)
  4919. return XML_ERROR_NO_MEMORY;
  4920. poolFinish(&parser->m_tempPool);
  4921. handleDefault = XML_FALSE;
  4922. }
  4923. #ifdef XML_DTD
  4924. else
  4925. /* use externalSubsetName to make parser->m_doctypeSysid non-NULL
  4926. for the case where no parser->m_startDoctypeDeclHandler is set */
  4927. parser->m_doctypeSysid = externalSubsetName;
  4928. #endif /* XML_DTD */
  4929. if (! dtd->standalone
  4930. #ifdef XML_DTD
  4931. && ! parser->m_paramEntityParsing
  4932. #endif /* XML_DTD */
  4933. && parser->m_notStandaloneHandler
  4934. && ! parser->m_notStandaloneHandler(parser->m_handlerArg))
  4935. return XML_ERROR_NOT_STANDALONE;
  4936. #ifndef XML_DTD
  4937. break;
  4938. #else /* XML_DTD */
  4939. if (! parser->m_declEntity) {
  4940. parser->m_declEntity = (ENTITY *)lookup(
  4941. parser, &dtd->paramEntities, externalSubsetName, sizeof(ENTITY));
  4942. if (! parser->m_declEntity)
  4943. return XML_ERROR_NO_MEMORY;
  4944. parser->m_declEntity->publicId = NULL;
  4945. }
  4946. #endif /* XML_DTD */
  4947. /* fall through */
  4948. case XML_ROLE_ENTITY_SYSTEM_ID:
  4949. if (dtd->keepProcessing && parser->m_declEntity) {
  4950. parser->m_declEntity->systemId
  4951. = poolStoreString(&dtd->pool, enc, s + enc->minBytesPerChar,
  4952. next - enc->minBytesPerChar);
  4953. if (! parser->m_declEntity->systemId)
  4954. return XML_ERROR_NO_MEMORY;
  4955. parser->m_declEntity->base = parser->m_curBase;
  4956. poolFinish(&dtd->pool);
  4957. /* Don't suppress the default handler if we fell through from
  4958. * the XML_ROLE_DOCTYPE_SYSTEM_ID case.
  4959. */
  4960. if (parser->m_entityDeclHandler && role == XML_ROLE_ENTITY_SYSTEM_ID)
  4961. handleDefault = XML_FALSE;
  4962. }
  4963. break;
  4964. case XML_ROLE_ENTITY_COMPLETE:
  4965. #if XML_GE == 0
  4966. // This will store "&amp;entity123;" in entity->textPtr
  4967. // to end up as "&entity123;" in the handler.
  4968. if (parser->m_declEntity != NULL) {
  4969. const enum XML_Error result
  4970. = storeSelfEntityValue(parser, parser->m_declEntity);
  4971. if (result != XML_ERROR_NONE)
  4972. return result;
  4973. }
  4974. #endif
  4975. if (dtd->keepProcessing && parser->m_declEntity
  4976. && parser->m_entityDeclHandler) {
  4977. *eventEndPP = s;
  4978. parser->m_entityDeclHandler(
  4979. parser->m_handlerArg, parser->m_declEntity->name,
  4980. parser->m_declEntity->is_param, 0, 0, parser->m_declEntity->base,
  4981. parser->m_declEntity->systemId, parser->m_declEntity->publicId, 0);
  4982. handleDefault = XML_FALSE;
  4983. }
  4984. break;
  4985. case XML_ROLE_ENTITY_NOTATION_NAME:
  4986. if (dtd->keepProcessing && parser->m_declEntity) {
  4987. parser->m_declEntity->notation
  4988. = poolStoreString(&dtd->pool, enc, s, next);
  4989. if (! parser->m_declEntity->notation)
  4990. return XML_ERROR_NO_MEMORY;
  4991. poolFinish(&dtd->pool);
  4992. if (parser->m_unparsedEntityDeclHandler) {
  4993. *eventEndPP = s;
  4994. parser->m_unparsedEntityDeclHandler(
  4995. parser->m_handlerArg, parser->m_declEntity->name,
  4996. parser->m_declEntity->base, parser->m_declEntity->systemId,
  4997. parser->m_declEntity->publicId, parser->m_declEntity->notation);
  4998. handleDefault = XML_FALSE;
  4999. } else if (parser->m_entityDeclHandler) {
  5000. *eventEndPP = s;
  5001. parser->m_entityDeclHandler(
  5002. parser->m_handlerArg, parser->m_declEntity->name, 0, 0, 0,
  5003. parser->m_declEntity->base, parser->m_declEntity->systemId,
  5004. parser->m_declEntity->publicId, parser->m_declEntity->notation);
  5005. handleDefault = XML_FALSE;
  5006. }
  5007. }
  5008. break;
  5009. case XML_ROLE_GENERAL_ENTITY_NAME: {
  5010. if (XmlPredefinedEntityName(enc, s, next)) {
  5011. parser->m_declEntity = NULL;
  5012. break;
  5013. }
  5014. if (dtd->keepProcessing) {
  5015. const XML_Char *name = poolStoreString(&dtd->pool, enc, s, next);
  5016. if (! name)
  5017. return XML_ERROR_NO_MEMORY;
  5018. parser->m_declEntity = (ENTITY *)lookup(parser, &dtd->generalEntities,
  5019. name, sizeof(ENTITY));
  5020. if (! parser->m_declEntity)
  5021. return XML_ERROR_NO_MEMORY;
  5022. if (parser->m_declEntity->name != name) {
  5023. poolDiscard(&dtd->pool);
  5024. parser->m_declEntity = NULL;
  5025. } else {
  5026. poolFinish(&dtd->pool);
  5027. parser->m_declEntity->publicId = NULL;
  5028. parser->m_declEntity->is_param = XML_FALSE;
  5029. /* if we have a parent parser or are reading an internal parameter
  5030. entity, then the entity declaration is not considered "internal"
  5031. */
  5032. parser->m_declEntity->is_internal
  5033. = ! (parser->m_parentParser || parser->m_openInternalEntities);
  5034. if (parser->m_entityDeclHandler)
  5035. handleDefault = XML_FALSE;
  5036. }
  5037. } else {
  5038. poolDiscard(&dtd->pool);
  5039. parser->m_declEntity = NULL;
  5040. }
  5041. } break;
  5042. case XML_ROLE_PARAM_ENTITY_NAME:
  5043. #ifdef XML_DTD
  5044. if (dtd->keepProcessing) {
  5045. const XML_Char *name = poolStoreString(&dtd->pool, enc, s, next);
  5046. if (! name)
  5047. return XML_ERROR_NO_MEMORY;
  5048. parser->m_declEntity = (ENTITY *)lookup(parser, &dtd->paramEntities,
  5049. name, sizeof(ENTITY));
  5050. if (! parser->m_declEntity)
  5051. return XML_ERROR_NO_MEMORY;
  5052. if (parser->m_declEntity->name != name) {
  5053. poolDiscard(&dtd->pool);
  5054. parser->m_declEntity = NULL;
  5055. } else {
  5056. poolFinish(&dtd->pool);
  5057. parser->m_declEntity->publicId = NULL;
  5058. parser->m_declEntity->is_param = XML_TRUE;
  5059. /* if we have a parent parser or are reading an internal parameter
  5060. entity, then the entity declaration is not considered "internal"
  5061. */
  5062. parser->m_declEntity->is_internal
  5063. = ! (parser->m_parentParser || parser->m_openInternalEntities);
  5064. if (parser->m_entityDeclHandler)
  5065. handleDefault = XML_FALSE;
  5066. }
  5067. } else {
  5068. poolDiscard(&dtd->pool);
  5069. parser->m_declEntity = NULL;
  5070. }
  5071. #else /* not XML_DTD */
  5072. parser->m_declEntity = NULL;
  5073. #endif /* XML_DTD */
  5074. break;
  5075. case XML_ROLE_NOTATION_NAME:
  5076. parser->m_declNotationPublicId = NULL;
  5077. parser->m_declNotationName = NULL;
  5078. if (parser->m_notationDeclHandler) {
  5079. parser->m_declNotationName
  5080. = poolStoreString(&parser->m_tempPool, enc, s, next);
  5081. if (! parser->m_declNotationName)
  5082. return XML_ERROR_NO_MEMORY;
  5083. poolFinish(&parser->m_tempPool);
  5084. handleDefault = XML_FALSE;
  5085. }
  5086. break;
  5087. case XML_ROLE_NOTATION_PUBLIC_ID:
  5088. if (! XmlIsPublicId(enc, s, next, eventPP))
  5089. return XML_ERROR_PUBLICID;
  5090. if (parser
  5091. ->m_declNotationName) { /* means m_notationDeclHandler != NULL */
  5092. XML_Char *tem = poolStoreString(&parser->m_tempPool, enc,
  5093. s + enc->minBytesPerChar,
  5094. next - enc->minBytesPerChar);
  5095. if (! tem)
  5096. return XML_ERROR_NO_MEMORY;
  5097. normalizePublicId(tem);
  5098. parser->m_declNotationPublicId = tem;
  5099. poolFinish(&parser->m_tempPool);
  5100. handleDefault = XML_FALSE;
  5101. }
  5102. break;
  5103. case XML_ROLE_NOTATION_SYSTEM_ID:
  5104. if (parser->m_declNotationName && parser->m_notationDeclHandler) {
  5105. const XML_Char *systemId = poolStoreString(&parser->m_tempPool, enc,
  5106. s + enc->minBytesPerChar,
  5107. next - enc->minBytesPerChar);
  5108. if (! systemId)
  5109. return XML_ERROR_NO_MEMORY;
  5110. *eventEndPP = s;
  5111. parser->m_notationDeclHandler(
  5112. parser->m_handlerArg, parser->m_declNotationName, parser->m_curBase,
  5113. systemId, parser->m_declNotationPublicId);
  5114. handleDefault = XML_FALSE;
  5115. }
  5116. poolClear(&parser->m_tempPool);
  5117. break;
  5118. case XML_ROLE_NOTATION_NO_SYSTEM_ID:
  5119. if (parser->m_declNotationPublicId && parser->m_notationDeclHandler) {
  5120. *eventEndPP = s;
  5121. parser->m_notationDeclHandler(
  5122. parser->m_handlerArg, parser->m_declNotationName, parser->m_curBase,
  5123. 0, parser->m_declNotationPublicId);
  5124. handleDefault = XML_FALSE;
  5125. }
  5126. poolClear(&parser->m_tempPool);
  5127. break;
  5128. case XML_ROLE_ERROR:
  5129. switch (tok) {
  5130. case XML_TOK_PARAM_ENTITY_REF:
  5131. /* PE references in internal subset are
  5132. not allowed within declarations. */
  5133. return XML_ERROR_PARAM_ENTITY_REF;
  5134. case XML_TOK_XML_DECL:
  5135. return XML_ERROR_MISPLACED_XML_PI;
  5136. default:
  5137. return XML_ERROR_SYNTAX;
  5138. }
  5139. #ifdef XML_DTD
  5140. case XML_ROLE_IGNORE_SECT: {
  5141. enum XML_Error result;
  5142. if (parser->m_defaultHandler)
  5143. reportDefault(parser, enc, s, next);
  5144. handleDefault = XML_FALSE;
  5145. result = doIgnoreSection(parser, enc, &next, end, nextPtr, haveMore);
  5146. if (result != XML_ERROR_NONE)
  5147. return result;
  5148. else if (! next) {
  5149. parser->m_processor = ignoreSectionProcessor;
  5150. return result;
  5151. }
  5152. } break;
  5153. #endif /* XML_DTD */
  5154. case XML_ROLE_GROUP_OPEN:
  5155. if (parser->m_prologState.level >= parser->m_groupSize) {
  5156. if (parser->m_groupSize) {
  5157. {
  5158. /* Detect and prevent integer overflow */
  5159. if (parser->m_groupSize > (unsigned int)(-1) / 2u) {
  5160. return XML_ERROR_NO_MEMORY;
  5161. }
  5162. char *const new_connector = (char *)REALLOC(
  5163. parser, parser->m_groupConnector, parser->m_groupSize *= 2);
  5164. if (new_connector == NULL) {
  5165. parser->m_groupSize /= 2;
  5166. return XML_ERROR_NO_MEMORY;
  5167. }
  5168. parser->m_groupConnector = new_connector;
  5169. }
  5170. if (dtd->scaffIndex) {
  5171. /* Detect and prevent integer overflow.
  5172. * The preprocessor guard addresses the "always false" warning
  5173. * from -Wtype-limits on platforms where
  5174. * sizeof(unsigned int) < sizeof(size_t), e.g. on x86_64. */
  5175. #if UINT_MAX >= SIZE_MAX
  5176. if (parser->m_groupSize > (size_t)(-1) / sizeof(int)) {
  5177. return XML_ERROR_NO_MEMORY;
  5178. }
  5179. #endif
  5180. int *const new_scaff_index = (int *)REALLOC(
  5181. parser, dtd->scaffIndex, parser->m_groupSize * sizeof(int));
  5182. if (new_scaff_index == NULL)
  5183. return XML_ERROR_NO_MEMORY;
  5184. dtd->scaffIndex = new_scaff_index;
  5185. }
  5186. } else {
  5187. parser->m_groupConnector
  5188. = (char *)MALLOC(parser, parser->m_groupSize = 32);
  5189. if (! parser->m_groupConnector) {
  5190. parser->m_groupSize = 0;
  5191. return XML_ERROR_NO_MEMORY;
  5192. }
  5193. }
  5194. }
  5195. parser->m_groupConnector[parser->m_prologState.level] = 0;
  5196. if (dtd->in_eldecl) {
  5197. int myindex = nextScaffoldPart(parser);
  5198. if (myindex < 0)
  5199. return XML_ERROR_NO_MEMORY;
  5200. assert(dtd->scaffIndex != NULL);
  5201. dtd->scaffIndex[dtd->scaffLevel] = myindex;
  5202. dtd->scaffLevel++;
  5203. dtd->scaffold[myindex].type = XML_CTYPE_SEQ;
  5204. if (parser->m_elementDeclHandler)
  5205. handleDefault = XML_FALSE;
  5206. }
  5207. break;
  5208. case XML_ROLE_GROUP_SEQUENCE:
  5209. if (parser->m_groupConnector[parser->m_prologState.level] == ASCII_PIPE)
  5210. return XML_ERROR_SYNTAX;
  5211. parser->m_groupConnector[parser->m_prologState.level] = ASCII_COMMA;
  5212. if (dtd->in_eldecl && parser->m_elementDeclHandler)
  5213. handleDefault = XML_FALSE;
  5214. break;
  5215. case XML_ROLE_GROUP_CHOICE:
  5216. if (parser->m_groupConnector[parser->m_prologState.level] == ASCII_COMMA)
  5217. return XML_ERROR_SYNTAX;
  5218. if (dtd->in_eldecl
  5219. && ! parser->m_groupConnector[parser->m_prologState.level]
  5220. && (dtd->scaffold[dtd->scaffIndex[dtd->scaffLevel - 1]].type
  5221. != XML_CTYPE_MIXED)) {
  5222. dtd->scaffold[dtd->scaffIndex[dtd->scaffLevel - 1]].type
  5223. = XML_CTYPE_CHOICE;
  5224. if (parser->m_elementDeclHandler)
  5225. handleDefault = XML_FALSE;
  5226. }
  5227. parser->m_groupConnector[parser->m_prologState.level] = ASCII_PIPE;
  5228. break;
  5229. case XML_ROLE_PARAM_ENTITY_REF:
  5230. #ifdef XML_DTD
  5231. case XML_ROLE_INNER_PARAM_ENTITY_REF:
  5232. dtd->hasParamEntityRefs = XML_TRUE;
  5233. if (! parser->m_paramEntityParsing)
  5234. dtd->keepProcessing = dtd->standalone;
  5235. else {
  5236. const XML_Char *name;
  5237. ENTITY *entity;
  5238. name = poolStoreString(&dtd->pool, enc, s + enc->minBytesPerChar,
  5239. next - enc->minBytesPerChar);
  5240. if (! name)
  5241. return XML_ERROR_NO_MEMORY;
  5242. entity = (ENTITY *)lookup(parser, &dtd->paramEntities, name, 0);
  5243. poolDiscard(&dtd->pool);
  5244. /* first, determine if a check for an existing declaration is needed;
  5245. if yes, check that the entity exists, and that it is internal,
  5246. otherwise call the skipped entity handler
  5247. */
  5248. if (parser->m_prologState.documentEntity
  5249. && (dtd->standalone ? ! parser->m_openInternalEntities
  5250. : ! dtd->hasParamEntityRefs)) {
  5251. if (! entity)
  5252. return XML_ERROR_UNDEFINED_ENTITY;
  5253. else if (! entity->is_internal) {
  5254. /* It's hard to exhaustively search the code to be sure,
  5255. * but there doesn't seem to be a way of executing the
  5256. * following line. There are two cases:
  5257. *
  5258. * If 'standalone' is false, the DTD must have no
  5259. * parameter entities or we wouldn't have passed the outer
  5260. * 'if' statement. That means the only entity in the hash
  5261. * table is the external subset name "#" which cannot be
  5262. * given as a parameter entity name in XML syntax, so the
  5263. * lookup must have returned NULL and we don't even reach
  5264. * the test for an internal entity.
  5265. *
  5266. * If 'standalone' is true, it does not seem to be
  5267. * possible to create entities taking this code path that
  5268. * are not internal entities, so fail the test above.
  5269. *
  5270. * Because this analysis is very uncertain, the code is
  5271. * being left in place and merely removed from the
  5272. * coverage test statistics.
  5273. */
  5274. return XML_ERROR_ENTITY_DECLARED_IN_PE; /* LCOV_EXCL_LINE */
  5275. }
  5276. } else if (! entity) {
  5277. dtd->keepProcessing = dtd->standalone;
  5278. /* cannot report skipped entities in declarations */
  5279. if ((role == XML_ROLE_PARAM_ENTITY_REF)
  5280. && parser->m_skippedEntityHandler) {
  5281. parser->m_skippedEntityHandler(parser->m_handlerArg, name, 1);
  5282. handleDefault = XML_FALSE;
  5283. }
  5284. break;
  5285. }
  5286. if (entity->open)
  5287. return XML_ERROR_RECURSIVE_ENTITY_REF;
  5288. if (entity->textPtr) {
  5289. enum XML_Error result;
  5290. XML_Bool betweenDecl
  5291. = (role == XML_ROLE_PARAM_ENTITY_REF ? XML_TRUE : XML_FALSE);
  5292. result = processEntity(parser, entity, betweenDecl, ENTITY_INTERNAL);
  5293. if (result != XML_ERROR_NONE)
  5294. return result;
  5295. handleDefault = XML_FALSE;
  5296. break;
  5297. }
  5298. if (parser->m_externalEntityRefHandler) {
  5299. dtd->paramEntityRead = XML_FALSE;
  5300. entity->open = XML_TRUE;
  5301. entityTrackingOnOpen(parser, entity, __LINE__);
  5302. if (! parser->m_externalEntityRefHandler(
  5303. parser->m_externalEntityRefHandlerArg, 0, entity->base,
  5304. entity->systemId, entity->publicId)) {
  5305. entityTrackingOnClose(parser, entity, __LINE__);
  5306. entity->open = XML_FALSE;
  5307. return XML_ERROR_EXTERNAL_ENTITY_HANDLING;
  5308. }
  5309. entityTrackingOnClose(parser, entity, __LINE__);
  5310. entity->open = XML_FALSE;
  5311. handleDefault = XML_FALSE;
  5312. if (! dtd->paramEntityRead) {
  5313. dtd->keepProcessing = dtd->standalone;
  5314. break;
  5315. }
  5316. } else {
  5317. dtd->keepProcessing = dtd->standalone;
  5318. break;
  5319. }
  5320. }
  5321. #endif /* XML_DTD */
  5322. if (! dtd->standalone && parser->m_notStandaloneHandler
  5323. && ! parser->m_notStandaloneHandler(parser->m_handlerArg))
  5324. return XML_ERROR_NOT_STANDALONE;
  5325. break;
  5326. /* Element declaration stuff */
  5327. case XML_ROLE_ELEMENT_NAME:
  5328. if (parser->m_elementDeclHandler) {
  5329. parser->m_declElementType = getElementType(parser, enc, s, next);
  5330. if (! parser->m_declElementType)
  5331. return XML_ERROR_NO_MEMORY;
  5332. dtd->scaffLevel = 0;
  5333. dtd->scaffCount = 0;
  5334. dtd->in_eldecl = XML_TRUE;
  5335. handleDefault = XML_FALSE;
  5336. }
  5337. break;
  5338. case XML_ROLE_CONTENT_ANY:
  5339. case XML_ROLE_CONTENT_EMPTY:
  5340. if (dtd->in_eldecl) {
  5341. if (parser->m_elementDeclHandler) {
  5342. XML_Content *content
  5343. = (XML_Content *)MALLOC(parser, sizeof(XML_Content));
  5344. if (! content)
  5345. return XML_ERROR_NO_MEMORY;
  5346. content->quant = XML_CQUANT_NONE;
  5347. content->name = NULL;
  5348. content->numchildren = 0;
  5349. content->children = NULL;
  5350. content->type = ((role == XML_ROLE_CONTENT_ANY) ? XML_CTYPE_ANY
  5351. : XML_CTYPE_EMPTY);
  5352. *eventEndPP = s;
  5353. parser->m_elementDeclHandler(
  5354. parser->m_handlerArg, parser->m_declElementType->name, content);
  5355. handleDefault = XML_FALSE;
  5356. }
  5357. dtd->in_eldecl = XML_FALSE;
  5358. }
  5359. break;
  5360. case XML_ROLE_CONTENT_PCDATA:
  5361. if (dtd->in_eldecl) {
  5362. dtd->scaffold[dtd->scaffIndex[dtd->scaffLevel - 1]].type
  5363. = XML_CTYPE_MIXED;
  5364. if (parser->m_elementDeclHandler)
  5365. handleDefault = XML_FALSE;
  5366. }
  5367. break;
  5368. case XML_ROLE_CONTENT_ELEMENT:
  5369. quant = XML_CQUANT_NONE;
  5370. goto elementContent;
  5371. case XML_ROLE_CONTENT_ELEMENT_OPT:
  5372. quant = XML_CQUANT_OPT;
  5373. goto elementContent;
  5374. case XML_ROLE_CONTENT_ELEMENT_REP:
  5375. quant = XML_CQUANT_REP;
  5376. goto elementContent;
  5377. case XML_ROLE_CONTENT_ELEMENT_PLUS:
  5378. quant = XML_CQUANT_PLUS;
  5379. elementContent:
  5380. if (dtd->in_eldecl) {
  5381. ELEMENT_TYPE *el;
  5382. const XML_Char *name;
  5383. size_t nameLen;
  5384. const char *nxt
  5385. = (quant == XML_CQUANT_NONE ? next : next - enc->minBytesPerChar);
  5386. int myindex = nextScaffoldPart(parser);
  5387. if (myindex < 0)
  5388. return XML_ERROR_NO_MEMORY;
  5389. dtd->scaffold[myindex].type = XML_CTYPE_NAME;
  5390. dtd->scaffold[myindex].quant = quant;
  5391. el = getElementType(parser, enc, s, nxt);
  5392. if (! el)
  5393. return XML_ERROR_NO_MEMORY;
  5394. name = el->name;
  5395. dtd->scaffold[myindex].name = name;
  5396. nameLen = 0;
  5397. for (; name[nameLen++];)
  5398. ;
  5399. /* Detect and prevent integer overflow */
  5400. if (nameLen > UINT_MAX - dtd->contentStringLen) {
  5401. return XML_ERROR_NO_MEMORY;
  5402. }
  5403. dtd->contentStringLen += (unsigned)nameLen;
  5404. if (parser->m_elementDeclHandler)
  5405. handleDefault = XML_FALSE;
  5406. }
  5407. break;
  5408. case XML_ROLE_GROUP_CLOSE:
  5409. quant = XML_CQUANT_NONE;
  5410. goto closeGroup;
  5411. case XML_ROLE_GROUP_CLOSE_OPT:
  5412. quant = XML_CQUANT_OPT;
  5413. goto closeGroup;
  5414. case XML_ROLE_GROUP_CLOSE_REP:
  5415. quant = XML_CQUANT_REP;
  5416. goto closeGroup;
  5417. case XML_ROLE_GROUP_CLOSE_PLUS:
  5418. quant = XML_CQUANT_PLUS;
  5419. closeGroup:
  5420. if (dtd->in_eldecl) {
  5421. if (parser->m_elementDeclHandler)
  5422. handleDefault = XML_FALSE;
  5423. dtd->scaffLevel--;
  5424. dtd->scaffold[dtd->scaffIndex[dtd->scaffLevel]].quant = quant;
  5425. if (dtd->scaffLevel == 0) {
  5426. if (! handleDefault) {
  5427. XML_Content *model = build_model(parser);
  5428. if (! model)
  5429. return XML_ERROR_NO_MEMORY;
  5430. *eventEndPP = s;
  5431. parser->m_elementDeclHandler(
  5432. parser->m_handlerArg, parser->m_declElementType->name, model);
  5433. }
  5434. dtd->in_eldecl = XML_FALSE;
  5435. dtd->contentStringLen = 0;
  5436. }
  5437. }
  5438. break;
  5439. /* End element declaration stuff */
  5440. case XML_ROLE_PI:
  5441. if (! reportProcessingInstruction(parser, enc, s, next))
  5442. return XML_ERROR_NO_MEMORY;
  5443. handleDefault = XML_FALSE;
  5444. break;
  5445. case XML_ROLE_COMMENT:
  5446. if (! reportComment(parser, enc, s, next))
  5447. return XML_ERROR_NO_MEMORY;
  5448. handleDefault = XML_FALSE;
  5449. break;
  5450. case XML_ROLE_NONE:
  5451. switch (tok) {
  5452. case XML_TOK_BOM:
  5453. handleDefault = XML_FALSE;
  5454. break;
  5455. }
  5456. break;
  5457. case XML_ROLE_DOCTYPE_NONE:
  5458. if (parser->m_startDoctypeDeclHandler)
  5459. handleDefault = XML_FALSE;
  5460. break;
  5461. case XML_ROLE_ENTITY_NONE:
  5462. if (dtd->keepProcessing && parser->m_entityDeclHandler)
  5463. handleDefault = XML_FALSE;
  5464. break;
  5465. case XML_ROLE_NOTATION_NONE:
  5466. if (parser->m_notationDeclHandler)
  5467. handleDefault = XML_FALSE;
  5468. break;
  5469. case XML_ROLE_ATTLIST_NONE:
  5470. if (dtd->keepProcessing && parser->m_attlistDeclHandler)
  5471. handleDefault = XML_FALSE;
  5472. break;
  5473. case XML_ROLE_ELEMENT_NONE:
  5474. if (parser->m_elementDeclHandler)
  5475. handleDefault = XML_FALSE;
  5476. break;
  5477. } /* end of big switch */
  5478. if (handleDefault && parser->m_defaultHandler)
  5479. reportDefault(parser, enc, s, next);
  5480. switch (parser->m_parsingStatus.parsing) {
  5481. case XML_SUSPENDED:
  5482. *nextPtr = next;
  5483. return XML_ERROR_NONE;
  5484. case XML_FINISHED:
  5485. return XML_ERROR_ABORTED;
  5486. case XML_PARSING:
  5487. if (parser->m_reenter) {
  5488. *nextPtr = next;
  5489. return XML_ERROR_NONE;
  5490. }
  5491. /* Fall through */
  5492. default:
  5493. s = next;
  5494. tok = XmlPrologTok(enc, s, end, &next);
  5495. }
  5496. }
  5497. /* not reached */
  5498. }
  5499. static enum XML_Error PTRCALL
  5500. epilogProcessor(XML_Parser parser, const char *s, const char *end,
  5501. const char **nextPtr) {
  5502. parser->m_processor = epilogProcessor;
  5503. parser->m_eventPtr = s;
  5504. for (;;) {
  5505. const char *next = NULL;
  5506. int tok = XmlPrologTok(parser->m_encoding, s, end, &next);
  5507. #if XML_GE == 1
  5508. if (! accountingDiffTolerated(parser, tok, s, next, __LINE__,
  5509. XML_ACCOUNT_DIRECT)) {
  5510. accountingOnAbort(parser);
  5511. return XML_ERROR_AMPLIFICATION_LIMIT_BREACH;
  5512. }
  5513. #endif
  5514. parser->m_eventEndPtr = next;
  5515. switch (tok) {
  5516. /* report partial linebreak - it might be the last token */
  5517. case -XML_TOK_PROLOG_S:
  5518. if (parser->m_defaultHandler) {
  5519. reportDefault(parser, parser->m_encoding, s, next);
  5520. if (parser->m_parsingStatus.parsing == XML_FINISHED)
  5521. return XML_ERROR_ABORTED;
  5522. }
  5523. *nextPtr = next;
  5524. return XML_ERROR_NONE;
  5525. case XML_TOK_NONE:
  5526. *nextPtr = s;
  5527. return XML_ERROR_NONE;
  5528. case XML_TOK_PROLOG_S:
  5529. if (parser->m_defaultHandler)
  5530. reportDefault(parser, parser->m_encoding, s, next);
  5531. break;
  5532. case XML_TOK_PI:
  5533. if (! reportProcessingInstruction(parser, parser->m_encoding, s, next))
  5534. return XML_ERROR_NO_MEMORY;
  5535. break;
  5536. case XML_TOK_COMMENT:
  5537. if (! reportComment(parser, parser->m_encoding, s, next))
  5538. return XML_ERROR_NO_MEMORY;
  5539. break;
  5540. case XML_TOK_INVALID:
  5541. parser->m_eventPtr = next;
  5542. return XML_ERROR_INVALID_TOKEN;
  5543. case XML_TOK_PARTIAL:
  5544. if (! parser->m_parsingStatus.finalBuffer) {
  5545. *nextPtr = s;
  5546. return XML_ERROR_NONE;
  5547. }
  5548. return XML_ERROR_UNCLOSED_TOKEN;
  5549. case XML_TOK_PARTIAL_CHAR:
  5550. if (! parser->m_parsingStatus.finalBuffer) {
  5551. *nextPtr = s;
  5552. return XML_ERROR_NONE;
  5553. }
  5554. return XML_ERROR_PARTIAL_CHAR;
  5555. default:
  5556. return XML_ERROR_JUNK_AFTER_DOC_ELEMENT;
  5557. }
  5558. switch (parser->m_parsingStatus.parsing) {
  5559. case XML_SUSPENDED:
  5560. parser->m_eventPtr = next;
  5561. *nextPtr = next;
  5562. return XML_ERROR_NONE;
  5563. case XML_FINISHED:
  5564. parser->m_eventPtr = next;
  5565. return XML_ERROR_ABORTED;
  5566. case XML_PARSING:
  5567. if (parser->m_reenter) {
  5568. return XML_ERROR_UNEXPECTED_STATE; // LCOV_EXCL_LINE
  5569. }
  5570. /* Fall through */
  5571. default:;
  5572. parser->m_eventPtr = s = next;
  5573. }
  5574. }
  5575. }
  5576. static enum XML_Error
  5577. processEntity(XML_Parser parser, ENTITY *entity, XML_Bool betweenDecl,
  5578. enum EntityType type) {
  5579. OPEN_INTERNAL_ENTITY *openEntity, **openEntityList, **freeEntityList;
  5580. switch (type) {
  5581. case ENTITY_INTERNAL:
  5582. parser->m_processor = internalEntityProcessor;
  5583. openEntityList = &parser->m_openInternalEntities;
  5584. freeEntityList = &parser->m_freeInternalEntities;
  5585. break;
  5586. case ENTITY_ATTRIBUTE:
  5587. openEntityList = &parser->m_openAttributeEntities;
  5588. freeEntityList = &parser->m_freeAttributeEntities;
  5589. break;
  5590. case ENTITY_VALUE:
  5591. openEntityList = &parser->m_openValueEntities;
  5592. freeEntityList = &parser->m_freeValueEntities;
  5593. break;
  5594. /* default case serves merely as a safety net in case of a
  5595. * wrong entityType. Therefore we exclude the following lines
  5596. * from the test coverage.
  5597. *
  5598. * LCOV_EXCL_START
  5599. */
  5600. default:
  5601. // Should not reach here
  5602. assert(0);
  5603. /* LCOV_EXCL_STOP */
  5604. }
  5605. if (*freeEntityList) {
  5606. openEntity = *freeEntityList;
  5607. *freeEntityList = openEntity->next;
  5608. } else {
  5609. openEntity
  5610. = (OPEN_INTERNAL_ENTITY *)MALLOC(parser, sizeof(OPEN_INTERNAL_ENTITY));
  5611. if (! openEntity)
  5612. return XML_ERROR_NO_MEMORY;
  5613. }
  5614. entity->open = XML_TRUE;
  5615. entity->hasMore = XML_TRUE;
  5616. #if XML_GE == 1
  5617. entityTrackingOnOpen(parser, entity, __LINE__);
  5618. #endif
  5619. entity->processed = 0;
  5620. openEntity->next = *openEntityList;
  5621. *openEntityList = openEntity;
  5622. openEntity->entity = entity;
  5623. openEntity->type = type;
  5624. openEntity->startTagLevel = parser->m_tagLevel;
  5625. openEntity->betweenDecl = betweenDecl;
  5626. openEntity->internalEventPtr = NULL;
  5627. openEntity->internalEventEndPtr = NULL;
  5628. // Only internal entities make use of the reenter flag
  5629. // therefore no need to set it for other entity types
  5630. if (type == ENTITY_INTERNAL) {
  5631. triggerReenter(parser);
  5632. }
  5633. return XML_ERROR_NONE;
  5634. }
  5635. static enum XML_Error PTRCALL
  5636. internalEntityProcessor(XML_Parser parser, const char *s, const char *end,
  5637. const char **nextPtr) {
  5638. UNUSED_P(s);
  5639. UNUSED_P(end);
  5640. UNUSED_P(nextPtr);
  5641. ENTITY *entity;
  5642. const char *textStart, *textEnd;
  5643. const char *next;
  5644. enum XML_Error result;
  5645. OPEN_INTERNAL_ENTITY *openEntity = parser->m_openInternalEntities;
  5646. if (! openEntity)
  5647. return XML_ERROR_UNEXPECTED_STATE;
  5648. entity = openEntity->entity;
  5649. // This will return early
  5650. if (entity->hasMore) {
  5651. textStart = ((const char *)entity->textPtr) + entity->processed;
  5652. textEnd = (const char *)(entity->textPtr + entity->textLen);
  5653. /* Set a safe default value in case 'next' does not get set */
  5654. next = textStart;
  5655. if (entity->is_param) {
  5656. int tok
  5657. = XmlPrologTok(parser->m_internalEncoding, textStart, textEnd, &next);
  5658. result = doProlog(parser, parser->m_internalEncoding, textStart, textEnd,
  5659. tok, next, &next, XML_FALSE, XML_FALSE,
  5660. XML_ACCOUNT_ENTITY_EXPANSION);
  5661. } else {
  5662. result = doContent(parser, openEntity->startTagLevel,
  5663. parser->m_internalEncoding, textStart, textEnd, &next,
  5664. XML_FALSE, XML_ACCOUNT_ENTITY_EXPANSION);
  5665. }
  5666. if (result != XML_ERROR_NONE)
  5667. return result;
  5668. // Check if entity is complete, if not, mark down how much of it is
  5669. // processed
  5670. if (textEnd != next
  5671. && (parser->m_parsingStatus.parsing == XML_SUSPENDED
  5672. || (parser->m_parsingStatus.parsing == XML_PARSING
  5673. && parser->m_reenter))) {
  5674. entity->processed = (int)(next - (const char *)entity->textPtr);
  5675. return result;
  5676. }
  5677. // Entity is complete. We cannot close it here since we need to first
  5678. // process its possible inner entities (which are added to the
  5679. // m_openInternalEntities during doProlog or doContent calls above)
  5680. entity->hasMore = XML_FALSE;
  5681. triggerReenter(parser);
  5682. return result;
  5683. } // End of entity processing, "if" block will return here
  5684. // Remove fully processed openEntity from open entity list.
  5685. #if XML_GE == 1
  5686. entityTrackingOnClose(parser, entity, __LINE__);
  5687. #endif
  5688. // openEntity is m_openInternalEntities' head, as we set it at the start of
  5689. // this function and we skipped doProlog and doContent calls with hasMore set
  5690. // to false. This means we can directly remove the head of
  5691. // m_openInternalEntities
  5692. assert(parser->m_openInternalEntities == openEntity);
  5693. entity->open = XML_FALSE;
  5694. parser->m_openInternalEntities = parser->m_openInternalEntities->next;
  5695. /* put openEntity back in list of free instances */
  5696. openEntity->next = parser->m_freeInternalEntities;
  5697. parser->m_freeInternalEntities = openEntity;
  5698. if (parser->m_openInternalEntities == NULL) {
  5699. parser->m_processor = entity->is_param ? prologProcessor : contentProcessor;
  5700. }
  5701. triggerReenter(parser);
  5702. return XML_ERROR_NONE;
  5703. }
  5704. static enum XML_Error PTRCALL
  5705. errorProcessor(XML_Parser parser, const char *s, const char *end,
  5706. const char **nextPtr) {
  5707. UNUSED_P(s);
  5708. UNUSED_P(end);
  5709. UNUSED_P(nextPtr);
  5710. return parser->m_errorCode;
  5711. }
  5712. static enum XML_Error
  5713. storeAttributeValue(XML_Parser parser, const ENCODING *enc, XML_Bool isCdata,
  5714. const char *ptr, const char *end, STRING_POOL *pool,
  5715. enum XML_Account account) {
  5716. const char *next = ptr;
  5717. enum XML_Error result = XML_ERROR_NONE;
  5718. while (1) {
  5719. if (! parser->m_openAttributeEntities) {
  5720. result = appendAttributeValue(parser, enc, isCdata, next, end, pool,
  5721. account, &next);
  5722. } else {
  5723. OPEN_INTERNAL_ENTITY *const openEntity = parser->m_openAttributeEntities;
  5724. if (! openEntity)
  5725. return XML_ERROR_UNEXPECTED_STATE;
  5726. ENTITY *const entity = openEntity->entity;
  5727. const char *const textStart
  5728. = ((const char *)entity->textPtr) + entity->processed;
  5729. const char *const textEnd
  5730. = (const char *)(entity->textPtr + entity->textLen);
  5731. /* Set a safe default value in case 'next' does not get set */
  5732. const char *nextInEntity = textStart;
  5733. if (entity->hasMore) {
  5734. result = appendAttributeValue(
  5735. parser, parser->m_internalEncoding, isCdata, textStart, textEnd,
  5736. pool, XML_ACCOUNT_ENTITY_EXPANSION, &nextInEntity);
  5737. if (result != XML_ERROR_NONE)
  5738. break;
  5739. // Check if entity is complete, if not, mark down how much of it is
  5740. // processed. A XML_SUSPENDED check here is not required as
  5741. // appendAttributeValue will never suspend the parser.
  5742. if (textEnd != nextInEntity) {
  5743. entity->processed
  5744. = (int)(nextInEntity - (const char *)entity->textPtr);
  5745. continue;
  5746. }
  5747. // Entity is complete. We cannot close it here since we need to first
  5748. // process its possible inner entities (which are added to the
  5749. // m_openAttributeEntities during appendAttributeValue)
  5750. entity->hasMore = XML_FALSE;
  5751. continue;
  5752. } // End of entity processing, "if" block skips the rest
  5753. // Remove fully processed openEntity from open entity list.
  5754. #if XML_GE == 1
  5755. entityTrackingOnClose(parser, entity, __LINE__);
  5756. #endif
  5757. // openEntity is m_openAttributeEntities' head, since we set it at the
  5758. // start of this function and because we skipped appendAttributeValue call
  5759. // with hasMore set to false. This means we can directly remove the head
  5760. // of m_openAttributeEntities
  5761. assert(parser->m_openAttributeEntities == openEntity);
  5762. entity->open = XML_FALSE;
  5763. parser->m_openAttributeEntities = parser->m_openAttributeEntities->next;
  5764. /* put openEntity back in list of free instances */
  5765. openEntity->next = parser->m_freeAttributeEntities;
  5766. parser->m_freeAttributeEntities = openEntity;
  5767. }
  5768. // Break if an error occurred or there is nothing left to process
  5769. if (result || (parser->m_openAttributeEntities == NULL && end == next)) {
  5770. break;
  5771. }
  5772. }
  5773. if (result)
  5774. return result;
  5775. if (! isCdata && poolLength(pool) && poolLastChar(pool) == 0x20)
  5776. poolChop(pool);
  5777. if (! poolAppendChar(pool, XML_T('\0')))
  5778. return XML_ERROR_NO_MEMORY;
  5779. return XML_ERROR_NONE;
  5780. }
  5781. static enum XML_Error
  5782. appendAttributeValue(XML_Parser parser, const ENCODING *enc, XML_Bool isCdata,
  5783. const char *ptr, const char *end, STRING_POOL *pool,
  5784. enum XML_Account account, const char **nextPtr) {
  5785. DTD *const dtd = parser->m_dtd; /* save one level of indirection */
  5786. #ifndef XML_DTD
  5787. UNUSED_P(account);
  5788. #endif
  5789. for (;;) {
  5790. const char *next
  5791. = ptr; /* XmlAttributeValueTok doesn't always set the last arg */
  5792. int tok = XmlAttributeValueTok(enc, ptr, end, &next);
  5793. #if XML_GE == 1
  5794. if (! accountingDiffTolerated(parser, tok, ptr, next, __LINE__, account)) {
  5795. accountingOnAbort(parser);
  5796. return XML_ERROR_AMPLIFICATION_LIMIT_BREACH;
  5797. }
  5798. #endif
  5799. switch (tok) {
  5800. case XML_TOK_NONE:
  5801. if (nextPtr) {
  5802. *nextPtr = next;
  5803. }
  5804. return XML_ERROR_NONE;
  5805. case XML_TOK_INVALID:
  5806. if (enc == parser->m_encoding)
  5807. parser->m_eventPtr = next;
  5808. return XML_ERROR_INVALID_TOKEN;
  5809. case XML_TOK_PARTIAL:
  5810. if (enc == parser->m_encoding)
  5811. parser->m_eventPtr = ptr;
  5812. return XML_ERROR_INVALID_TOKEN;
  5813. case XML_TOK_CHAR_REF: {
  5814. XML_Char buf[XML_ENCODE_MAX];
  5815. int i;
  5816. int n = XmlCharRefNumber(enc, ptr);
  5817. if (n < 0) {
  5818. if (enc == parser->m_encoding)
  5819. parser->m_eventPtr = ptr;
  5820. return XML_ERROR_BAD_CHAR_REF;
  5821. }
  5822. if (! isCdata && n == 0x20 /* space */
  5823. && (poolLength(pool) == 0 || poolLastChar(pool) == 0x20))
  5824. break;
  5825. n = XmlEncode(n, (ICHAR *)buf);
  5826. /* The XmlEncode() functions can never return 0 here. That
  5827. * error return happens if the code point passed in is either
  5828. * negative or greater than or equal to 0x110000. The
  5829. * XmlCharRefNumber() functions will all return a number
  5830. * strictly less than 0x110000 or a negative value if an error
  5831. * occurred. The negative value is intercepted above, so
  5832. * XmlEncode() is never passed a value it might return an
  5833. * error for.
  5834. */
  5835. for (i = 0; i < n; i++) {
  5836. if (! poolAppendChar(pool, buf[i]))
  5837. return XML_ERROR_NO_MEMORY;
  5838. }
  5839. } break;
  5840. case XML_TOK_DATA_CHARS:
  5841. if (! poolAppend(pool, enc, ptr, next))
  5842. return XML_ERROR_NO_MEMORY;
  5843. break;
  5844. case XML_TOK_TRAILING_CR:
  5845. next = ptr + enc->minBytesPerChar;
  5846. /* fall through */
  5847. case XML_TOK_ATTRIBUTE_VALUE_S:
  5848. case XML_TOK_DATA_NEWLINE:
  5849. if (! isCdata && (poolLength(pool) == 0 || poolLastChar(pool) == 0x20))
  5850. break;
  5851. if (! poolAppendChar(pool, 0x20))
  5852. return XML_ERROR_NO_MEMORY;
  5853. break;
  5854. case XML_TOK_ENTITY_REF: {
  5855. const XML_Char *name;
  5856. ENTITY *entity;
  5857. char checkEntityDecl;
  5858. XML_Char ch = (XML_Char)XmlPredefinedEntityName(
  5859. enc, ptr + enc->minBytesPerChar, next - enc->minBytesPerChar);
  5860. if (ch) {
  5861. #if XML_GE == 1
  5862. /* NOTE: We are replacing 4-6 characters original input for 1 character
  5863. * so there is no amplification and hence recording without
  5864. * protection. */
  5865. accountingDiffTolerated(parser, tok, (char *)&ch,
  5866. ((char *)&ch) + sizeof(XML_Char), __LINE__,
  5867. XML_ACCOUNT_ENTITY_EXPANSION);
  5868. #endif /* XML_GE == 1 */
  5869. if (! poolAppendChar(pool, ch))
  5870. return XML_ERROR_NO_MEMORY;
  5871. break;
  5872. }
  5873. name = poolStoreString(&parser->m_temp2Pool, enc,
  5874. ptr + enc->minBytesPerChar,
  5875. next - enc->minBytesPerChar);
  5876. if (! name)
  5877. return XML_ERROR_NO_MEMORY;
  5878. entity = (ENTITY *)lookup(parser, &dtd->generalEntities, name, 0);
  5879. poolDiscard(&parser->m_temp2Pool);
  5880. /* First, determine if a check for an existing declaration is needed;
  5881. if yes, check that the entity exists, and that it is internal.
  5882. */
  5883. if (pool == &dtd->pool) /* are we called from prolog? */
  5884. checkEntityDecl =
  5885. #ifdef XML_DTD
  5886. parser->m_prologState.documentEntity &&
  5887. #endif /* XML_DTD */
  5888. (dtd->standalone ? ! parser->m_openInternalEntities
  5889. : ! dtd->hasParamEntityRefs);
  5890. else /* if (pool == &parser->m_tempPool): we are called from content */
  5891. checkEntityDecl = ! dtd->hasParamEntityRefs || dtd->standalone;
  5892. if (checkEntityDecl) {
  5893. if (! entity)
  5894. return XML_ERROR_UNDEFINED_ENTITY;
  5895. else if (! entity->is_internal)
  5896. return XML_ERROR_ENTITY_DECLARED_IN_PE;
  5897. } else if (! entity) {
  5898. /* Cannot report skipped entity here - see comments on
  5899. parser->m_skippedEntityHandler.
  5900. if (parser->m_skippedEntityHandler)
  5901. parser->m_skippedEntityHandler(parser->m_handlerArg, name, 0);
  5902. */
  5903. /* Cannot call the default handler because this would be
  5904. out of sync with the call to the startElementHandler.
  5905. if ((pool == &parser->m_tempPool) && parser->m_defaultHandler)
  5906. reportDefault(parser, enc, ptr, next);
  5907. */
  5908. break;
  5909. }
  5910. if (entity->open) {
  5911. if (enc == parser->m_encoding) {
  5912. /* It does not appear that this line can be executed.
  5913. *
  5914. * The "if (entity->open)" check catches recursive entity
  5915. * definitions. In order to be called with an open
  5916. * entity, it must have gone through this code before and
  5917. * been through the recursive call to
  5918. * appendAttributeValue() some lines below. That call
  5919. * sets the local encoding ("enc") to the parser's
  5920. * internal encoding (internal_utf8 or internal_utf16),
  5921. * which can never be the same as the principle encoding.
  5922. * It doesn't appear there is another code path that gets
  5923. * here with entity->open being TRUE.
  5924. *
  5925. * Since it is not certain that this logic is watertight,
  5926. * we keep the line and merely exclude it from coverage
  5927. * tests.
  5928. */
  5929. parser->m_eventPtr = ptr; /* LCOV_EXCL_LINE */
  5930. }
  5931. return XML_ERROR_RECURSIVE_ENTITY_REF;
  5932. }
  5933. if (entity->notation) {
  5934. if (enc == parser->m_encoding)
  5935. parser->m_eventPtr = ptr;
  5936. return XML_ERROR_BINARY_ENTITY_REF;
  5937. }
  5938. if (! entity->textPtr) {
  5939. if (enc == parser->m_encoding)
  5940. parser->m_eventPtr = ptr;
  5941. return XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF;
  5942. } else {
  5943. enum XML_Error result;
  5944. result = processEntity(parser, entity, XML_FALSE, ENTITY_ATTRIBUTE);
  5945. if ((result == XML_ERROR_NONE) && (nextPtr != NULL)) {
  5946. *nextPtr = next;
  5947. }
  5948. return result;
  5949. }
  5950. } break;
  5951. default:
  5952. /* The only token returned by XmlAttributeValueTok() that does
  5953. * not have an explicit case here is XML_TOK_PARTIAL_CHAR.
  5954. * Getting that would require an entity name to contain an
  5955. * incomplete XML character (e.g. \xE2\x82); however previous
  5956. * tokenisers will have already recognised and rejected such
  5957. * names before XmlAttributeValueTok() gets a look-in. This
  5958. * default case should be retained as a safety net, but the code
  5959. * excluded from coverage tests.
  5960. *
  5961. * LCOV_EXCL_START
  5962. */
  5963. if (enc == parser->m_encoding)
  5964. parser->m_eventPtr = ptr;
  5965. return XML_ERROR_UNEXPECTED_STATE;
  5966. /* LCOV_EXCL_STOP */
  5967. }
  5968. ptr = next;
  5969. }
  5970. /* not reached */
  5971. }
  5972. #if XML_GE == 1
  5973. static enum XML_Error
  5974. storeEntityValue(XML_Parser parser, const ENCODING *enc,
  5975. const char *entityTextPtr, const char *entityTextEnd,
  5976. enum XML_Account account, const char **nextPtr) {
  5977. DTD *const dtd = parser->m_dtd; /* save one level of indirection */
  5978. STRING_POOL *pool = &(dtd->entityValuePool);
  5979. enum XML_Error result = XML_ERROR_NONE;
  5980. # ifdef XML_DTD
  5981. int oldInEntityValue = parser->m_prologState.inEntityValue;
  5982. parser->m_prologState.inEntityValue = 1;
  5983. # else
  5984. UNUSED_P(account);
  5985. # endif /* XML_DTD */
  5986. /* never return Null for the value argument in EntityDeclHandler,
  5987. since this would indicate an external entity; therefore we
  5988. have to make sure that entityValuePool.start is not null */
  5989. if (! pool->blocks) {
  5990. if (! poolGrow(pool))
  5991. return XML_ERROR_NO_MEMORY;
  5992. }
  5993. const char *next;
  5994. for (;;) {
  5995. next
  5996. = entityTextPtr; /* XmlEntityValueTok doesn't always set the last arg */
  5997. int tok = XmlEntityValueTok(enc, entityTextPtr, entityTextEnd, &next);
  5998. if (! accountingDiffTolerated(parser, tok, entityTextPtr, next, __LINE__,
  5999. account)) {
  6000. accountingOnAbort(parser);
  6001. result = XML_ERROR_AMPLIFICATION_LIMIT_BREACH;
  6002. goto endEntityValue;
  6003. }
  6004. switch (tok) {
  6005. case XML_TOK_PARAM_ENTITY_REF:
  6006. # ifdef XML_DTD
  6007. if (parser->m_isParamEntity || enc != parser->m_encoding) {
  6008. const XML_Char *name;
  6009. ENTITY *entity;
  6010. name = poolStoreString(&parser->m_tempPool, enc,
  6011. entityTextPtr + enc->minBytesPerChar,
  6012. next - enc->minBytesPerChar);
  6013. if (! name) {
  6014. result = XML_ERROR_NO_MEMORY;
  6015. goto endEntityValue;
  6016. }
  6017. entity = (ENTITY *)lookup(parser, &dtd->paramEntities, name, 0);
  6018. poolDiscard(&parser->m_tempPool);
  6019. if (! entity) {
  6020. /* not a well-formedness error - see XML 1.0: WFC Entity Declared */
  6021. /* cannot report skipped entity here - see comments on
  6022. parser->m_skippedEntityHandler
  6023. if (parser->m_skippedEntityHandler)
  6024. parser->m_skippedEntityHandler(parser->m_handlerArg, name, 0);
  6025. */
  6026. dtd->keepProcessing = dtd->standalone;
  6027. goto endEntityValue;
  6028. }
  6029. if (entity->open || (entity == parser->m_declEntity)) {
  6030. if (enc == parser->m_encoding)
  6031. parser->m_eventPtr = entityTextPtr;
  6032. result = XML_ERROR_RECURSIVE_ENTITY_REF;
  6033. goto endEntityValue;
  6034. }
  6035. if (entity->systemId) {
  6036. if (parser->m_externalEntityRefHandler) {
  6037. dtd->paramEntityRead = XML_FALSE;
  6038. entity->open = XML_TRUE;
  6039. entityTrackingOnOpen(parser, entity, __LINE__);
  6040. if (! parser->m_externalEntityRefHandler(
  6041. parser->m_externalEntityRefHandlerArg, 0, entity->base,
  6042. entity->systemId, entity->publicId)) {
  6043. entityTrackingOnClose(parser, entity, __LINE__);
  6044. entity->open = XML_FALSE;
  6045. result = XML_ERROR_EXTERNAL_ENTITY_HANDLING;
  6046. goto endEntityValue;
  6047. }
  6048. entityTrackingOnClose(parser, entity, __LINE__);
  6049. entity->open = XML_FALSE;
  6050. if (! dtd->paramEntityRead)
  6051. dtd->keepProcessing = dtd->standalone;
  6052. } else
  6053. dtd->keepProcessing = dtd->standalone;
  6054. } else {
  6055. result = processEntity(parser, entity, XML_FALSE, ENTITY_VALUE);
  6056. goto endEntityValue;
  6057. }
  6058. break;
  6059. }
  6060. # endif /* XML_DTD */
  6061. /* In the internal subset, PE references are not legal
  6062. within markup declarations, e.g entity values in this case. */
  6063. parser->m_eventPtr = entityTextPtr;
  6064. result = XML_ERROR_PARAM_ENTITY_REF;
  6065. goto endEntityValue;
  6066. case XML_TOK_NONE:
  6067. result = XML_ERROR_NONE;
  6068. goto endEntityValue;
  6069. case XML_TOK_ENTITY_REF:
  6070. case XML_TOK_DATA_CHARS:
  6071. if (! poolAppend(pool, enc, entityTextPtr, next)) {
  6072. result = XML_ERROR_NO_MEMORY;
  6073. goto endEntityValue;
  6074. }
  6075. break;
  6076. case XML_TOK_TRAILING_CR:
  6077. next = entityTextPtr + enc->minBytesPerChar;
  6078. /* fall through */
  6079. case XML_TOK_DATA_NEWLINE:
  6080. if (pool->end == pool->ptr && ! poolGrow(pool)) {
  6081. result = XML_ERROR_NO_MEMORY;
  6082. goto endEntityValue;
  6083. }
  6084. *(pool->ptr)++ = 0xA;
  6085. break;
  6086. case XML_TOK_CHAR_REF: {
  6087. XML_Char buf[XML_ENCODE_MAX];
  6088. int i;
  6089. int n = XmlCharRefNumber(enc, entityTextPtr);
  6090. if (n < 0) {
  6091. if (enc == parser->m_encoding)
  6092. parser->m_eventPtr = entityTextPtr;
  6093. result = XML_ERROR_BAD_CHAR_REF;
  6094. goto endEntityValue;
  6095. }
  6096. n = XmlEncode(n, (ICHAR *)buf);
  6097. /* The XmlEncode() functions can never return 0 here. That
  6098. * error return happens if the code point passed in is either
  6099. * negative or greater than or equal to 0x110000. The
  6100. * XmlCharRefNumber() functions will all return a number
  6101. * strictly less than 0x110000 or a negative value if an error
  6102. * occurred. The negative value is intercepted above, so
  6103. * XmlEncode() is never passed a value it might return an
  6104. * error for.
  6105. */
  6106. for (i = 0; i < n; i++) {
  6107. if (pool->end == pool->ptr && ! poolGrow(pool)) {
  6108. result = XML_ERROR_NO_MEMORY;
  6109. goto endEntityValue;
  6110. }
  6111. *(pool->ptr)++ = buf[i];
  6112. }
  6113. } break;
  6114. case XML_TOK_PARTIAL:
  6115. if (enc == parser->m_encoding)
  6116. parser->m_eventPtr = entityTextPtr;
  6117. result = XML_ERROR_INVALID_TOKEN;
  6118. goto endEntityValue;
  6119. case XML_TOK_INVALID:
  6120. if (enc == parser->m_encoding)
  6121. parser->m_eventPtr = next;
  6122. result = XML_ERROR_INVALID_TOKEN;
  6123. goto endEntityValue;
  6124. default:
  6125. /* This default case should be unnecessary -- all the tokens
  6126. * that XmlEntityValueTok() can return have their own explicit
  6127. * cases -- but should be retained for safety. We do however
  6128. * exclude it from the coverage statistics.
  6129. *
  6130. * LCOV_EXCL_START
  6131. */
  6132. if (enc == parser->m_encoding)
  6133. parser->m_eventPtr = entityTextPtr;
  6134. result = XML_ERROR_UNEXPECTED_STATE;
  6135. goto endEntityValue;
  6136. /* LCOV_EXCL_STOP */
  6137. }
  6138. entityTextPtr = next;
  6139. }
  6140. endEntityValue:
  6141. # ifdef XML_DTD
  6142. parser->m_prologState.inEntityValue = oldInEntityValue;
  6143. # endif /* XML_DTD */
  6144. // If 'nextPtr' is given, it should be updated during the processing
  6145. if (nextPtr != NULL) {
  6146. *nextPtr = next;
  6147. }
  6148. return result;
  6149. }
  6150. static enum XML_Error
  6151. callStoreEntityValue(XML_Parser parser, const ENCODING *enc,
  6152. const char *entityTextPtr, const char *entityTextEnd,
  6153. enum XML_Account account) {
  6154. const char *next = entityTextPtr;
  6155. enum XML_Error result = XML_ERROR_NONE;
  6156. while (1) {
  6157. if (! parser->m_openValueEntities) {
  6158. result
  6159. = storeEntityValue(parser, enc, next, entityTextEnd, account, &next);
  6160. } else {
  6161. OPEN_INTERNAL_ENTITY *const openEntity = parser->m_openValueEntities;
  6162. if (! openEntity)
  6163. return XML_ERROR_UNEXPECTED_STATE;
  6164. ENTITY *const entity = openEntity->entity;
  6165. const char *const textStart
  6166. = ((const char *)entity->textPtr) + entity->processed;
  6167. const char *const textEnd
  6168. = (const char *)(entity->textPtr + entity->textLen);
  6169. /* Set a safe default value in case 'next' does not get set */
  6170. const char *nextInEntity = textStart;
  6171. if (entity->hasMore) {
  6172. result = storeEntityValue(parser, parser->m_internalEncoding, textStart,
  6173. textEnd, XML_ACCOUNT_ENTITY_EXPANSION,
  6174. &nextInEntity);
  6175. if (result != XML_ERROR_NONE)
  6176. break;
  6177. // Check if entity is complete, if not, mark down how much of it is
  6178. // processed. A XML_SUSPENDED check here is not required as
  6179. // appendAttributeValue will never suspend the parser.
  6180. if (textEnd != nextInEntity) {
  6181. entity->processed
  6182. = (int)(nextInEntity - (const char *)entity->textPtr);
  6183. continue;
  6184. }
  6185. // Entity is complete. We cannot close it here since we need to first
  6186. // process its possible inner entities (which are added to the
  6187. // m_openValueEntities during storeEntityValue)
  6188. entity->hasMore = XML_FALSE;
  6189. continue;
  6190. } // End of entity processing, "if" block skips the rest
  6191. // Remove fully processed openEntity from open entity list.
  6192. # if XML_GE == 1
  6193. entityTrackingOnClose(parser, entity, __LINE__);
  6194. # endif
  6195. // openEntity is m_openValueEntities' head, since we set it at the
  6196. // start of this function and because we skipped storeEntityValue call
  6197. // with hasMore set to false. This means we can directly remove the head
  6198. // of m_openValueEntities
  6199. assert(parser->m_openValueEntities == openEntity);
  6200. entity->open = XML_FALSE;
  6201. parser->m_openValueEntities = parser->m_openValueEntities->next;
  6202. /* put openEntity back in list of free instances */
  6203. openEntity->next = parser->m_freeValueEntities;
  6204. parser->m_freeValueEntities = openEntity;
  6205. }
  6206. // Break if an error occurred or there is nothing left to process
  6207. if (result
  6208. || (parser->m_openValueEntities == NULL && entityTextEnd == next)) {
  6209. break;
  6210. }
  6211. }
  6212. return result;
  6213. }
  6214. #else /* XML_GE == 0 */
  6215. static enum XML_Error
  6216. storeSelfEntityValue(XML_Parser parser, ENTITY *entity) {
  6217. // This will store "&amp;entity123;" in entity->textPtr
  6218. // to end up as "&entity123;" in the handler.
  6219. const char *const entity_start = "&amp;";
  6220. const char *const entity_end = ";";
  6221. STRING_POOL *const pool = &(parser->m_dtd->entityValuePool);
  6222. if (! poolAppendString(pool, entity_start)
  6223. || ! poolAppendString(pool, entity->name)
  6224. || ! poolAppendString(pool, entity_end)) {
  6225. poolDiscard(pool);
  6226. return XML_ERROR_NO_MEMORY;
  6227. }
  6228. entity->textPtr = poolStart(pool);
  6229. entity->textLen = (int)(poolLength(pool));
  6230. poolFinish(pool);
  6231. return XML_ERROR_NONE;
  6232. }
  6233. #endif /* XML_GE == 0 */
  6234. static void FASTCALL
  6235. normalizeLines(XML_Char *s) {
  6236. XML_Char *p;
  6237. for (;; s++) {
  6238. if (*s == XML_T('\0'))
  6239. return;
  6240. if (*s == 0xD)
  6241. break;
  6242. }
  6243. p = s;
  6244. do {
  6245. if (*s == 0xD) {
  6246. *p++ = 0xA;
  6247. if (*++s == 0xA)
  6248. s++;
  6249. } else
  6250. *p++ = *s++;
  6251. } while (*s);
  6252. *p = XML_T('\0');
  6253. }
  6254. static int
  6255. reportProcessingInstruction(XML_Parser parser, const ENCODING *enc,
  6256. const char *start, const char *end) {
  6257. const XML_Char *target;
  6258. XML_Char *data;
  6259. const char *tem;
  6260. if (! parser->m_processingInstructionHandler) {
  6261. if (parser->m_defaultHandler)
  6262. reportDefault(parser, enc, start, end);
  6263. return 1;
  6264. }
  6265. start += enc->minBytesPerChar * 2;
  6266. tem = start + XmlNameLength(enc, start);
  6267. target = poolStoreString(&parser->m_tempPool, enc, start, tem);
  6268. if (! target)
  6269. return 0;
  6270. poolFinish(&parser->m_tempPool);
  6271. data = poolStoreString(&parser->m_tempPool, enc, XmlSkipS(enc, tem),
  6272. end - enc->minBytesPerChar * 2);
  6273. if (! data)
  6274. return 0;
  6275. normalizeLines(data);
  6276. parser->m_processingInstructionHandler(parser->m_handlerArg, target, data);
  6277. poolClear(&parser->m_tempPool);
  6278. return 1;
  6279. }
  6280. static int
  6281. reportComment(XML_Parser parser, const ENCODING *enc, const char *start,
  6282. const char *end) {
  6283. XML_Char *data;
  6284. if (! parser->m_commentHandler) {
  6285. if (parser->m_defaultHandler)
  6286. reportDefault(parser, enc, start, end);
  6287. return 1;
  6288. }
  6289. data = poolStoreString(&parser->m_tempPool, enc,
  6290. start + enc->minBytesPerChar * 4,
  6291. end - enc->minBytesPerChar * 3);
  6292. if (! data)
  6293. return 0;
  6294. normalizeLines(data);
  6295. parser->m_commentHandler(parser->m_handlerArg, data);
  6296. poolClear(&parser->m_tempPool);
  6297. return 1;
  6298. }
  6299. static void
  6300. reportDefault(XML_Parser parser, const ENCODING *enc, const char *s,
  6301. const char *end) {
  6302. if (MUST_CONVERT(enc, s)) {
  6303. enum XML_Convert_Result convert_res;
  6304. const char **eventPP;
  6305. const char **eventEndPP;
  6306. if (enc == parser->m_encoding) {
  6307. eventPP = &parser->m_eventPtr;
  6308. eventEndPP = &parser->m_eventEndPtr;
  6309. } else {
  6310. /* To get here, two things must be true; the parser must be
  6311. * using a character encoding that is not the same as the
  6312. * encoding passed in, and the encoding passed in must need
  6313. * conversion to the internal format (UTF-8 unless XML_UNICODE
  6314. * is defined). The only occasions on which the encoding passed
  6315. * in is not the same as the parser's encoding are when it is
  6316. * the internal encoding (e.g. a previously defined parameter
  6317. * entity, already converted to internal format). This by
  6318. * definition doesn't need conversion, so the whole branch never
  6319. * gets executed.
  6320. *
  6321. * For safety's sake we don't delete these lines and merely
  6322. * exclude them from coverage statistics.
  6323. *
  6324. * LCOV_EXCL_START
  6325. */
  6326. eventPP = &(parser->m_openInternalEntities->internalEventPtr);
  6327. eventEndPP = &(parser->m_openInternalEntities->internalEventEndPtr);
  6328. /* LCOV_EXCL_STOP */
  6329. }
  6330. do {
  6331. ICHAR *dataPtr = (ICHAR *)parser->m_dataBuf;
  6332. convert_res
  6333. = XmlConvert(enc, &s, end, &dataPtr, (ICHAR *)parser->m_dataBufEnd);
  6334. *eventEndPP = s;
  6335. parser->m_defaultHandler(parser->m_handlerArg, parser->m_dataBuf,
  6336. (int)(dataPtr - (ICHAR *)parser->m_dataBuf));
  6337. *eventPP = s;
  6338. } while ((convert_res != XML_CONVERT_COMPLETED)
  6339. && (convert_res != XML_CONVERT_INPUT_INCOMPLETE));
  6340. } else
  6341. parser->m_defaultHandler(
  6342. parser->m_handlerArg, (const XML_Char *)s,
  6343. (int)((const XML_Char *)end - (const XML_Char *)s));
  6344. }
  6345. static int
  6346. defineAttribute(ELEMENT_TYPE *type, ATTRIBUTE_ID *attId, XML_Bool isCdata,
  6347. XML_Bool isId, const XML_Char *value, XML_Parser parser) {
  6348. DEFAULT_ATTRIBUTE *att;
  6349. if (value || isId) {
  6350. /* The handling of default attributes gets messed up if we have
  6351. a default which duplicates a non-default. */
  6352. int i;
  6353. for (i = 0; i < type->nDefaultAtts; i++)
  6354. if (attId == type->defaultAtts[i].id)
  6355. return 1;
  6356. if (isId && ! type->idAtt && ! attId->xmlns)
  6357. type->idAtt = attId;
  6358. }
  6359. if (type->nDefaultAtts == type->allocDefaultAtts) {
  6360. if (type->allocDefaultAtts == 0) {
  6361. type->allocDefaultAtts = 8;
  6362. type->defaultAtts = (DEFAULT_ATTRIBUTE *)MALLOC(
  6363. parser, type->allocDefaultAtts * sizeof(DEFAULT_ATTRIBUTE));
  6364. if (! type->defaultAtts) {
  6365. type->allocDefaultAtts = 0;
  6366. return 0;
  6367. }
  6368. } else {
  6369. DEFAULT_ATTRIBUTE *temp;
  6370. /* Detect and prevent integer overflow */
  6371. if (type->allocDefaultAtts > INT_MAX / 2) {
  6372. return 0;
  6373. }
  6374. int count = type->allocDefaultAtts * 2;
  6375. /* Detect and prevent integer overflow.
  6376. * The preprocessor guard addresses the "always false" warning
  6377. * from -Wtype-limits on platforms where
  6378. * sizeof(unsigned int) < sizeof(size_t), e.g. on x86_64. */
  6379. #if UINT_MAX >= SIZE_MAX
  6380. if ((unsigned)count > (size_t)(-1) / sizeof(DEFAULT_ATTRIBUTE)) {
  6381. return 0;
  6382. }
  6383. #endif
  6384. temp = (DEFAULT_ATTRIBUTE *)REALLOC(parser, type->defaultAtts,
  6385. (count * sizeof(DEFAULT_ATTRIBUTE)));
  6386. if (temp == NULL)
  6387. return 0;
  6388. type->allocDefaultAtts = count;
  6389. type->defaultAtts = temp;
  6390. }
  6391. }
  6392. att = type->defaultAtts + type->nDefaultAtts;
  6393. att->id = attId;
  6394. att->value = value;
  6395. att->isCdata = isCdata;
  6396. if (! isCdata)
  6397. attId->maybeTokenized = XML_TRUE;
  6398. type->nDefaultAtts += 1;
  6399. return 1;
  6400. }
  6401. static int
  6402. setElementTypePrefix(XML_Parser parser, ELEMENT_TYPE *elementType) {
  6403. DTD *const dtd = parser->m_dtd; /* save one level of indirection */
  6404. const XML_Char *name;
  6405. for (name = elementType->name; *name; name++) {
  6406. if (*name == XML_T(ASCII_COLON)) {
  6407. PREFIX *prefix;
  6408. const XML_Char *s;
  6409. for (s = elementType->name; s != name; s++) {
  6410. if (! poolAppendChar(&dtd->pool, *s))
  6411. return 0;
  6412. }
  6413. if (! poolAppendChar(&dtd->pool, XML_T('\0')))
  6414. return 0;
  6415. prefix = (PREFIX *)lookup(parser, &dtd->prefixes, poolStart(&dtd->pool),
  6416. sizeof(PREFIX));
  6417. if (! prefix)
  6418. return 0;
  6419. if (prefix->name == poolStart(&dtd->pool))
  6420. poolFinish(&dtd->pool);
  6421. else
  6422. poolDiscard(&dtd->pool);
  6423. elementType->prefix = prefix;
  6424. break;
  6425. }
  6426. }
  6427. return 1;
  6428. }
  6429. static ATTRIBUTE_ID *
  6430. getAttributeId(XML_Parser parser, const ENCODING *enc, const char *start,
  6431. const char *end) {
  6432. DTD *const dtd = parser->m_dtd; /* save one level of indirection */
  6433. ATTRIBUTE_ID *id;
  6434. const XML_Char *name;
  6435. if (! poolAppendChar(&dtd->pool, XML_T('\0')))
  6436. return NULL;
  6437. name = poolStoreString(&dtd->pool, enc, start, end);
  6438. if (! name)
  6439. return NULL;
  6440. /* skip quotation mark - its storage will be reused (like in name[-1]) */
  6441. ++name;
  6442. id = (ATTRIBUTE_ID *)lookup(parser, &dtd->attributeIds, name,
  6443. sizeof(ATTRIBUTE_ID));
  6444. if (! id)
  6445. return NULL;
  6446. if (id->name != name)
  6447. poolDiscard(&dtd->pool);
  6448. else {
  6449. poolFinish(&dtd->pool);
  6450. if (! parser->m_ns)
  6451. ;
  6452. else if (name[0] == XML_T(ASCII_x) && name[1] == XML_T(ASCII_m)
  6453. && name[2] == XML_T(ASCII_l) && name[3] == XML_T(ASCII_n)
  6454. && name[4] == XML_T(ASCII_s)
  6455. && (name[5] == XML_T('\0') || name[5] == XML_T(ASCII_COLON))) {
  6456. if (name[5] == XML_T('\0'))
  6457. id->prefix = &dtd->defaultPrefix;
  6458. else
  6459. id->prefix = (PREFIX *)lookup(parser, &dtd->prefixes, name + 6,
  6460. sizeof(PREFIX));
  6461. id->xmlns = XML_TRUE;
  6462. } else {
  6463. int i;
  6464. for (i = 0; name[i]; i++) {
  6465. /* attributes without prefix are *not* in the default namespace */
  6466. if (name[i] == XML_T(ASCII_COLON)) {
  6467. int j;
  6468. for (j = 0; j < i; j++) {
  6469. if (! poolAppendChar(&dtd->pool, name[j]))
  6470. return NULL;
  6471. }
  6472. if (! poolAppendChar(&dtd->pool, XML_T('\0')))
  6473. return NULL;
  6474. id->prefix = (PREFIX *)lookup(parser, &dtd->prefixes,
  6475. poolStart(&dtd->pool), sizeof(PREFIX));
  6476. if (! id->prefix)
  6477. return NULL;
  6478. if (id->prefix->name == poolStart(&dtd->pool))
  6479. poolFinish(&dtd->pool);
  6480. else
  6481. poolDiscard(&dtd->pool);
  6482. break;
  6483. }
  6484. }
  6485. }
  6486. }
  6487. return id;
  6488. }
  6489. #define CONTEXT_SEP XML_T(ASCII_FF)
  6490. static const XML_Char *
  6491. getContext(XML_Parser parser) {
  6492. DTD *const dtd = parser->m_dtd; /* save one level of indirection */
  6493. HASH_TABLE_ITER iter;
  6494. XML_Bool needSep = XML_FALSE;
  6495. if (dtd->defaultPrefix.binding) {
  6496. int i;
  6497. int len;
  6498. if (! poolAppendChar(&parser->m_tempPool, XML_T(ASCII_EQUALS)))
  6499. return NULL;
  6500. len = dtd->defaultPrefix.binding->uriLen;
  6501. if (parser->m_namespaceSeparator)
  6502. len--;
  6503. for (i = 0; i < len; i++) {
  6504. if (! poolAppendChar(&parser->m_tempPool,
  6505. dtd->defaultPrefix.binding->uri[i])) {
  6506. /* Because of memory caching, I don't believe this line can be
  6507. * executed.
  6508. *
  6509. * This is part of a loop copying the default prefix binding
  6510. * URI into the parser's temporary string pool. Previously,
  6511. * that URI was copied into the same string pool, with a
  6512. * terminating NUL character, as part of setContext(). When
  6513. * the pool was cleared, that leaves a block definitely big
  6514. * enough to hold the URI on the free block list of the pool.
  6515. * The URI copy in getContext() therefore cannot run out of
  6516. * memory.
  6517. *
  6518. * If the pool is used between the setContext() and
  6519. * getContext() calls, the worst it can do is leave a bigger
  6520. * block on the front of the free list. Given that this is
  6521. * all somewhat inobvious and program logic can be changed, we
  6522. * don't delete the line but we do exclude it from the test
  6523. * coverage statistics.
  6524. */
  6525. return NULL; /* LCOV_EXCL_LINE */
  6526. }
  6527. }
  6528. needSep = XML_TRUE;
  6529. }
  6530. hashTableIterInit(&iter, &(dtd->prefixes));
  6531. for (;;) {
  6532. int i;
  6533. int len;
  6534. const XML_Char *s;
  6535. PREFIX *prefix = (PREFIX *)hashTableIterNext(&iter);
  6536. if (! prefix)
  6537. break;
  6538. if (! prefix->binding) {
  6539. /* This test appears to be (justifiable) paranoia. There does
  6540. * not seem to be a way of injecting a prefix without a binding
  6541. * that doesn't get errored long before this function is called.
  6542. * The test should remain for safety's sake, so we instead
  6543. * exclude the following line from the coverage statistics.
  6544. */
  6545. continue; /* LCOV_EXCL_LINE */
  6546. }
  6547. if (needSep && ! poolAppendChar(&parser->m_tempPool, CONTEXT_SEP))
  6548. return NULL;
  6549. for (s = prefix->name; *s; s++)
  6550. if (! poolAppendChar(&parser->m_tempPool, *s))
  6551. return NULL;
  6552. if (! poolAppendChar(&parser->m_tempPool, XML_T(ASCII_EQUALS)))
  6553. return NULL;
  6554. len = prefix->binding->uriLen;
  6555. if (parser->m_namespaceSeparator)
  6556. len--;
  6557. for (i = 0; i < len; i++)
  6558. if (! poolAppendChar(&parser->m_tempPool, prefix->binding->uri[i]))
  6559. return NULL;
  6560. needSep = XML_TRUE;
  6561. }
  6562. hashTableIterInit(&iter, &(dtd->generalEntities));
  6563. for (;;) {
  6564. const XML_Char *s;
  6565. ENTITY *e = (ENTITY *)hashTableIterNext(&iter);
  6566. if (! e)
  6567. break;
  6568. if (! e->open)
  6569. continue;
  6570. if (needSep && ! poolAppendChar(&parser->m_tempPool, CONTEXT_SEP))
  6571. return NULL;
  6572. for (s = e->name; *s; s++)
  6573. if (! poolAppendChar(&parser->m_tempPool, *s))
  6574. return 0;
  6575. needSep = XML_TRUE;
  6576. }
  6577. if (! poolAppendChar(&parser->m_tempPool, XML_T('\0')))
  6578. return NULL;
  6579. return parser->m_tempPool.start;
  6580. }
  6581. static XML_Bool
  6582. setContext(XML_Parser parser, const XML_Char *context) {
  6583. if (context == NULL) {
  6584. return XML_FALSE;
  6585. }
  6586. DTD *const dtd = parser->m_dtd; /* save one level of indirection */
  6587. const XML_Char *s = context;
  6588. while (*context != XML_T('\0')) {
  6589. if (*s == CONTEXT_SEP || *s == XML_T('\0')) {
  6590. ENTITY *e;
  6591. if (! poolAppendChar(&parser->m_tempPool, XML_T('\0')))
  6592. return XML_FALSE;
  6593. e = (ENTITY *)lookup(parser, &dtd->generalEntities,
  6594. poolStart(&parser->m_tempPool), 0);
  6595. if (e)
  6596. e->open = XML_TRUE;
  6597. if (*s != XML_T('\0'))
  6598. s++;
  6599. context = s;
  6600. poolDiscard(&parser->m_tempPool);
  6601. } else if (*s == XML_T(ASCII_EQUALS)) {
  6602. PREFIX *prefix;
  6603. if (poolLength(&parser->m_tempPool) == 0)
  6604. prefix = &dtd->defaultPrefix;
  6605. else {
  6606. if (! poolAppendChar(&parser->m_tempPool, XML_T('\0')))
  6607. return XML_FALSE;
  6608. prefix
  6609. = (PREFIX *)lookup(parser, &dtd->prefixes,
  6610. poolStart(&parser->m_tempPool), sizeof(PREFIX));
  6611. if (! prefix)
  6612. return XML_FALSE;
  6613. if (prefix->name == poolStart(&parser->m_tempPool)) {
  6614. prefix->name = poolCopyString(&dtd->pool, prefix->name);
  6615. if (! prefix->name)
  6616. return XML_FALSE;
  6617. }
  6618. poolDiscard(&parser->m_tempPool);
  6619. }
  6620. for (context = s + 1; *context != CONTEXT_SEP && *context != XML_T('\0');
  6621. context++)
  6622. if (! poolAppendChar(&parser->m_tempPool, *context))
  6623. return XML_FALSE;
  6624. if (! poolAppendChar(&parser->m_tempPool, XML_T('\0')))
  6625. return XML_FALSE;
  6626. if (addBinding(parser, prefix, NULL, poolStart(&parser->m_tempPool),
  6627. &parser->m_inheritedBindings)
  6628. != XML_ERROR_NONE)
  6629. return XML_FALSE;
  6630. poolDiscard(&parser->m_tempPool);
  6631. if (*context != XML_T('\0'))
  6632. ++context;
  6633. s = context;
  6634. } else {
  6635. if (! poolAppendChar(&parser->m_tempPool, *s))
  6636. return XML_FALSE;
  6637. s++;
  6638. }
  6639. }
  6640. return XML_TRUE;
  6641. }
  6642. static void FASTCALL
  6643. normalizePublicId(XML_Char *publicId) {
  6644. XML_Char *p = publicId;
  6645. XML_Char *s;
  6646. for (s = publicId; *s; s++) {
  6647. switch (*s) {
  6648. case 0x20:
  6649. case 0xD:
  6650. case 0xA:
  6651. if (p != publicId && p[-1] != 0x20)
  6652. *p++ = 0x20;
  6653. break;
  6654. default:
  6655. *p++ = *s;
  6656. }
  6657. }
  6658. if (p != publicId && p[-1] == 0x20)
  6659. --p;
  6660. *p = XML_T('\0');
  6661. }
  6662. static DTD *
  6663. dtdCreate(const XML_Memory_Handling_Suite *ms) {
  6664. DTD *p = ms->malloc_fcn(sizeof(DTD));
  6665. if (p == NULL)
  6666. return p;
  6667. poolInit(&(p->pool), ms);
  6668. poolInit(&(p->entityValuePool), ms);
  6669. hashTableInit(&(p->generalEntities), ms);
  6670. hashTableInit(&(p->elementTypes), ms);
  6671. hashTableInit(&(p->attributeIds), ms);
  6672. hashTableInit(&(p->prefixes), ms);
  6673. #ifdef XML_DTD
  6674. p->paramEntityRead = XML_FALSE;
  6675. hashTableInit(&(p->paramEntities), ms);
  6676. #endif /* XML_DTD */
  6677. p->defaultPrefix.name = NULL;
  6678. p->defaultPrefix.binding = NULL;
  6679. p->in_eldecl = XML_FALSE;
  6680. p->scaffIndex = NULL;
  6681. p->scaffold = NULL;
  6682. p->scaffLevel = 0;
  6683. p->scaffSize = 0;
  6684. p->scaffCount = 0;
  6685. p->contentStringLen = 0;
  6686. p->keepProcessing = XML_TRUE;
  6687. p->hasParamEntityRefs = XML_FALSE;
  6688. p->standalone = XML_FALSE;
  6689. return p;
  6690. }
  6691. static void
  6692. dtdReset(DTD *p, const XML_Memory_Handling_Suite *ms) {
  6693. HASH_TABLE_ITER iter;
  6694. hashTableIterInit(&iter, &(p->elementTypes));
  6695. for (;;) {
  6696. ELEMENT_TYPE *e = (ELEMENT_TYPE *)hashTableIterNext(&iter);
  6697. if (! e)
  6698. break;
  6699. if (e->allocDefaultAtts != 0)
  6700. ms->free_fcn(e->defaultAtts);
  6701. }
  6702. hashTableClear(&(p->generalEntities));
  6703. #ifdef XML_DTD
  6704. p->paramEntityRead = XML_FALSE;
  6705. hashTableClear(&(p->paramEntities));
  6706. #endif /* XML_DTD */
  6707. hashTableClear(&(p->elementTypes));
  6708. hashTableClear(&(p->attributeIds));
  6709. hashTableClear(&(p->prefixes));
  6710. poolClear(&(p->pool));
  6711. poolClear(&(p->entityValuePool));
  6712. p->defaultPrefix.name = NULL;
  6713. p->defaultPrefix.binding = NULL;
  6714. p->in_eldecl = XML_FALSE;
  6715. ms->free_fcn(p->scaffIndex);
  6716. p->scaffIndex = NULL;
  6717. ms->free_fcn(p->scaffold);
  6718. p->scaffold = NULL;
  6719. p->scaffLevel = 0;
  6720. p->scaffSize = 0;
  6721. p->scaffCount = 0;
  6722. p->contentStringLen = 0;
  6723. p->keepProcessing = XML_TRUE;
  6724. p->hasParamEntityRefs = XML_FALSE;
  6725. p->standalone = XML_FALSE;
  6726. }
  6727. static void
  6728. dtdDestroy(DTD *p, XML_Bool isDocEntity, const XML_Memory_Handling_Suite *ms) {
  6729. HASH_TABLE_ITER iter;
  6730. hashTableIterInit(&iter, &(p->elementTypes));
  6731. for (;;) {
  6732. ELEMENT_TYPE *e = (ELEMENT_TYPE *)hashTableIterNext(&iter);
  6733. if (! e)
  6734. break;
  6735. if (e->allocDefaultAtts != 0)
  6736. ms->free_fcn(e->defaultAtts);
  6737. }
  6738. hashTableDestroy(&(p->generalEntities));
  6739. #ifdef XML_DTD
  6740. hashTableDestroy(&(p->paramEntities));
  6741. #endif /* XML_DTD */
  6742. hashTableDestroy(&(p->elementTypes));
  6743. hashTableDestroy(&(p->attributeIds));
  6744. hashTableDestroy(&(p->prefixes));
  6745. poolDestroy(&(p->pool));
  6746. poolDestroy(&(p->entityValuePool));
  6747. if (isDocEntity) {
  6748. ms->free_fcn(p->scaffIndex);
  6749. ms->free_fcn(p->scaffold);
  6750. }
  6751. ms->free_fcn(p);
  6752. }
  6753. /* Do a deep copy of the DTD. Return 0 for out of memory, non-zero otherwise.
  6754. The new DTD has already been initialized.
  6755. */
  6756. static int
  6757. dtdCopy(XML_Parser oldParser, DTD *newDtd, const DTD *oldDtd,
  6758. const XML_Memory_Handling_Suite *ms) {
  6759. HASH_TABLE_ITER iter;
  6760. /* Copy the prefix table. */
  6761. hashTableIterInit(&iter, &(oldDtd->prefixes));
  6762. for (;;) {
  6763. const XML_Char *name;
  6764. const PREFIX *oldP = (PREFIX *)hashTableIterNext(&iter);
  6765. if (! oldP)
  6766. break;
  6767. name = poolCopyString(&(newDtd->pool), oldP->name);
  6768. if (! name)
  6769. return 0;
  6770. if (! lookup(oldParser, &(newDtd->prefixes), name, sizeof(PREFIX)))
  6771. return 0;
  6772. }
  6773. hashTableIterInit(&iter, &(oldDtd->attributeIds));
  6774. /* Copy the attribute id table. */
  6775. for (;;) {
  6776. ATTRIBUTE_ID *newA;
  6777. const XML_Char *name;
  6778. const ATTRIBUTE_ID *oldA = (ATTRIBUTE_ID *)hashTableIterNext(&iter);
  6779. if (! oldA)
  6780. break;
  6781. /* Remember to allocate the scratch byte before the name. */
  6782. if (! poolAppendChar(&(newDtd->pool), XML_T('\0')))
  6783. return 0;
  6784. name = poolCopyString(&(newDtd->pool), oldA->name);
  6785. if (! name)
  6786. return 0;
  6787. ++name;
  6788. newA = (ATTRIBUTE_ID *)lookup(oldParser, &(newDtd->attributeIds), name,
  6789. sizeof(ATTRIBUTE_ID));
  6790. if (! newA)
  6791. return 0;
  6792. newA->maybeTokenized = oldA->maybeTokenized;
  6793. if (oldA->prefix) {
  6794. newA->xmlns = oldA->xmlns;
  6795. if (oldA->prefix == &oldDtd->defaultPrefix)
  6796. newA->prefix = &newDtd->defaultPrefix;
  6797. else
  6798. newA->prefix = (PREFIX *)lookup(oldParser, &(newDtd->prefixes),
  6799. oldA->prefix->name, 0);
  6800. }
  6801. }
  6802. /* Copy the element type table. */
  6803. hashTableIterInit(&iter, &(oldDtd->elementTypes));
  6804. for (;;) {
  6805. int i;
  6806. ELEMENT_TYPE *newE;
  6807. const XML_Char *name;
  6808. const ELEMENT_TYPE *oldE = (ELEMENT_TYPE *)hashTableIterNext(&iter);
  6809. if (! oldE)
  6810. break;
  6811. name = poolCopyString(&(newDtd->pool), oldE->name);
  6812. if (! name)
  6813. return 0;
  6814. newE = (ELEMENT_TYPE *)lookup(oldParser, &(newDtd->elementTypes), name,
  6815. sizeof(ELEMENT_TYPE));
  6816. if (! newE)
  6817. return 0;
  6818. if (oldE->nDefaultAtts) {
  6819. /* Detect and prevent integer overflow.
  6820. * The preprocessor guard addresses the "always false" warning
  6821. * from -Wtype-limits on platforms where
  6822. * sizeof(int) < sizeof(size_t), e.g. on x86_64. */
  6823. #if UINT_MAX >= SIZE_MAX
  6824. if ((size_t)oldE->nDefaultAtts
  6825. > ((size_t)(-1) / sizeof(DEFAULT_ATTRIBUTE))) {
  6826. return 0;
  6827. }
  6828. #endif
  6829. newE->defaultAtts
  6830. = ms->malloc_fcn(oldE->nDefaultAtts * sizeof(DEFAULT_ATTRIBUTE));
  6831. if (! newE->defaultAtts) {
  6832. return 0;
  6833. }
  6834. }
  6835. if (oldE->idAtt)
  6836. newE->idAtt = (ATTRIBUTE_ID *)lookup(oldParser, &(newDtd->attributeIds),
  6837. oldE->idAtt->name, 0);
  6838. newE->allocDefaultAtts = newE->nDefaultAtts = oldE->nDefaultAtts;
  6839. if (oldE->prefix)
  6840. newE->prefix = (PREFIX *)lookup(oldParser, &(newDtd->prefixes),
  6841. oldE->prefix->name, 0);
  6842. for (i = 0; i < newE->nDefaultAtts; i++) {
  6843. newE->defaultAtts[i].id = (ATTRIBUTE_ID *)lookup(
  6844. oldParser, &(newDtd->attributeIds), oldE->defaultAtts[i].id->name, 0);
  6845. newE->defaultAtts[i].isCdata = oldE->defaultAtts[i].isCdata;
  6846. if (oldE->defaultAtts[i].value) {
  6847. newE->defaultAtts[i].value
  6848. = poolCopyString(&(newDtd->pool), oldE->defaultAtts[i].value);
  6849. if (! newE->defaultAtts[i].value)
  6850. return 0;
  6851. } else
  6852. newE->defaultAtts[i].value = NULL;
  6853. }
  6854. }
  6855. /* Copy the entity tables. */
  6856. if (! copyEntityTable(oldParser, &(newDtd->generalEntities), &(newDtd->pool),
  6857. &(oldDtd->generalEntities)))
  6858. return 0;
  6859. #ifdef XML_DTD
  6860. if (! copyEntityTable(oldParser, &(newDtd->paramEntities), &(newDtd->pool),
  6861. &(oldDtd->paramEntities)))
  6862. return 0;
  6863. newDtd->paramEntityRead = oldDtd->paramEntityRead;
  6864. #endif /* XML_DTD */
  6865. newDtd->keepProcessing = oldDtd->keepProcessing;
  6866. newDtd->hasParamEntityRefs = oldDtd->hasParamEntityRefs;
  6867. newDtd->standalone = oldDtd->standalone;
  6868. /* Don't want deep copying for scaffolding */
  6869. newDtd->in_eldecl = oldDtd->in_eldecl;
  6870. newDtd->scaffold = oldDtd->scaffold;
  6871. newDtd->contentStringLen = oldDtd->contentStringLen;
  6872. newDtd->scaffSize = oldDtd->scaffSize;
  6873. newDtd->scaffLevel = oldDtd->scaffLevel;
  6874. newDtd->scaffIndex = oldDtd->scaffIndex;
  6875. return 1;
  6876. } /* End dtdCopy */
  6877. static int
  6878. copyEntityTable(XML_Parser oldParser, HASH_TABLE *newTable,
  6879. STRING_POOL *newPool, const HASH_TABLE *oldTable) {
  6880. HASH_TABLE_ITER iter;
  6881. const XML_Char *cachedOldBase = NULL;
  6882. const XML_Char *cachedNewBase = NULL;
  6883. hashTableIterInit(&iter, oldTable);
  6884. for (;;) {
  6885. ENTITY *newE;
  6886. const XML_Char *name;
  6887. const ENTITY *oldE = (ENTITY *)hashTableIterNext(&iter);
  6888. if (! oldE)
  6889. break;
  6890. name = poolCopyString(newPool, oldE->name);
  6891. if (! name)
  6892. return 0;
  6893. newE = (ENTITY *)lookup(oldParser, newTable, name, sizeof(ENTITY));
  6894. if (! newE)
  6895. return 0;
  6896. if (oldE->systemId) {
  6897. const XML_Char *tem = poolCopyString(newPool, oldE->systemId);
  6898. if (! tem)
  6899. return 0;
  6900. newE->systemId = tem;
  6901. if (oldE->base) {
  6902. if (oldE->base == cachedOldBase)
  6903. newE->base = cachedNewBase;
  6904. else {
  6905. cachedOldBase = oldE->base;
  6906. tem = poolCopyString(newPool, cachedOldBase);
  6907. if (! tem)
  6908. return 0;
  6909. cachedNewBase = newE->base = tem;
  6910. }
  6911. }
  6912. if (oldE->publicId) {
  6913. tem = poolCopyString(newPool, oldE->publicId);
  6914. if (! tem)
  6915. return 0;
  6916. newE->publicId = tem;
  6917. }
  6918. } else {
  6919. const XML_Char *tem
  6920. = poolCopyStringN(newPool, oldE->textPtr, oldE->textLen);
  6921. if (! tem)
  6922. return 0;
  6923. newE->textPtr = tem;
  6924. newE->textLen = oldE->textLen;
  6925. }
  6926. if (oldE->notation) {
  6927. const XML_Char *tem = poolCopyString(newPool, oldE->notation);
  6928. if (! tem)
  6929. return 0;
  6930. newE->notation = tem;
  6931. }
  6932. newE->is_param = oldE->is_param;
  6933. newE->is_internal = oldE->is_internal;
  6934. }
  6935. return 1;
  6936. }
  6937. #define INIT_POWER 6
  6938. static XML_Bool FASTCALL
  6939. keyeq(KEY s1, KEY s2) {
  6940. for (; *s1 == *s2; s1++, s2++)
  6941. if (*s1 == 0)
  6942. return XML_TRUE;
  6943. return XML_FALSE;
  6944. }
  6945. static size_t
  6946. keylen(KEY s) {
  6947. size_t len = 0;
  6948. for (; *s; s++, len++)
  6949. ;
  6950. return len;
  6951. }
  6952. static void
  6953. copy_salt_to_sipkey(XML_Parser parser, struct sipkey *key) {
  6954. key->k[0] = 0;
  6955. key->k[1] = get_hash_secret_salt(parser);
  6956. }
  6957. static unsigned long FASTCALL
  6958. hash(XML_Parser parser, KEY s) {
  6959. struct siphash state;
  6960. struct sipkey key;
  6961. (void)sip24_valid;
  6962. copy_salt_to_sipkey(parser, &key);
  6963. sip24_init(&state, &key);
  6964. sip24_update(&state, s, keylen(s) * sizeof(XML_Char));
  6965. return (unsigned long)sip24_final(&state);
  6966. }
  6967. static NAMED *
  6968. lookup(XML_Parser parser, HASH_TABLE *table, KEY name, size_t createSize) {
  6969. size_t i;
  6970. if (table->size == 0) {
  6971. size_t tsize;
  6972. if (! createSize)
  6973. return NULL;
  6974. table->power = INIT_POWER;
  6975. /* table->size is a power of 2 */
  6976. table->size = (size_t)1 << INIT_POWER;
  6977. tsize = table->size * sizeof(NAMED *);
  6978. table->v = table->mem->malloc_fcn(tsize);
  6979. if (! table->v) {
  6980. table->size = 0;
  6981. return NULL;
  6982. }
  6983. memset(table->v, 0, tsize);
  6984. i = hash(parser, name) & ((unsigned long)table->size - 1);
  6985. } else {
  6986. unsigned long h = hash(parser, name);
  6987. unsigned long mask = (unsigned long)table->size - 1;
  6988. unsigned char step = 0;
  6989. i = h & mask;
  6990. while (table->v[i]) {
  6991. if (keyeq(name, table->v[i]->name))
  6992. return table->v[i];
  6993. if (! step)
  6994. step = PROBE_STEP(h, mask, table->power);
  6995. i < step ? (i += table->size - step) : (i -= step);
  6996. }
  6997. if (! createSize)
  6998. return NULL;
  6999. /* check for overflow (table is half full) */
  7000. if (table->used >> (table->power - 1)) {
  7001. unsigned char newPower = table->power + 1;
  7002. /* Detect and prevent invalid shift */
  7003. if (newPower >= sizeof(unsigned long) * 8 /* bits per byte */) {
  7004. return NULL;
  7005. }
  7006. size_t newSize = (size_t)1 << newPower;
  7007. unsigned long newMask = (unsigned long)newSize - 1;
  7008. /* Detect and prevent integer overflow */
  7009. if (newSize > (size_t)(-1) / sizeof(NAMED *)) {
  7010. return NULL;
  7011. }
  7012. size_t tsize = newSize * sizeof(NAMED *);
  7013. NAMED **newV = table->mem->malloc_fcn(tsize);
  7014. if (! newV)
  7015. return NULL;
  7016. memset(newV, 0, tsize);
  7017. for (i = 0; i < table->size; i++)
  7018. if (table->v[i]) {
  7019. unsigned long newHash = hash(parser, table->v[i]->name);
  7020. size_t j = newHash & newMask;
  7021. step = 0;
  7022. while (newV[j]) {
  7023. if (! step)
  7024. step = PROBE_STEP(newHash, newMask, newPower);
  7025. j < step ? (j += newSize - step) : (j -= step);
  7026. }
  7027. newV[j] = table->v[i];
  7028. }
  7029. table->mem->free_fcn(table->v);
  7030. table->v = newV;
  7031. table->power = newPower;
  7032. table->size = newSize;
  7033. i = h & newMask;
  7034. step = 0;
  7035. while (table->v[i]) {
  7036. if (! step)
  7037. step = PROBE_STEP(h, newMask, newPower);
  7038. i < step ? (i += newSize - step) : (i -= step);
  7039. }
  7040. }
  7041. }
  7042. table->v[i] = table->mem->malloc_fcn(createSize);
  7043. if (! table->v[i])
  7044. return NULL;
  7045. memset(table->v[i], 0, createSize);
  7046. table->v[i]->name = name;
  7047. (table->used)++;
  7048. return table->v[i];
  7049. }
  7050. static void FASTCALL
  7051. hashTableClear(HASH_TABLE *table) {
  7052. size_t i;
  7053. for (i = 0; i < table->size; i++) {
  7054. table->mem->free_fcn(table->v[i]);
  7055. table->v[i] = NULL;
  7056. }
  7057. table->used = 0;
  7058. }
  7059. static void FASTCALL
  7060. hashTableDestroy(HASH_TABLE *table) {
  7061. size_t i;
  7062. for (i = 0; i < table->size; i++)
  7063. table->mem->free_fcn(table->v[i]);
  7064. table->mem->free_fcn(table->v);
  7065. }
  7066. static void FASTCALL
  7067. hashTableInit(HASH_TABLE *p, const XML_Memory_Handling_Suite *ms) {
  7068. p->power = 0;
  7069. p->size = 0;
  7070. p->used = 0;
  7071. p->v = NULL;
  7072. p->mem = ms;
  7073. }
  7074. static void FASTCALL
  7075. hashTableIterInit(HASH_TABLE_ITER *iter, const HASH_TABLE *table) {
  7076. iter->p = table->v;
  7077. iter->end = iter->p ? iter->p + table->size : NULL;
  7078. }
  7079. static NAMED *FASTCALL
  7080. hashTableIterNext(HASH_TABLE_ITER *iter) {
  7081. while (iter->p != iter->end) {
  7082. NAMED *tem = *(iter->p)++;
  7083. if (tem)
  7084. return tem;
  7085. }
  7086. return NULL;
  7087. }
  7088. static void FASTCALL
  7089. poolInit(STRING_POOL *pool, const XML_Memory_Handling_Suite *ms) {
  7090. pool->blocks = NULL;
  7091. pool->freeBlocks = NULL;
  7092. pool->start = NULL;
  7093. pool->ptr = NULL;
  7094. pool->end = NULL;
  7095. pool->mem = ms;
  7096. }
  7097. static void FASTCALL
  7098. poolClear(STRING_POOL *pool) {
  7099. if (! pool->freeBlocks)
  7100. pool->freeBlocks = pool->blocks;
  7101. else {
  7102. BLOCK *p = pool->blocks;
  7103. while (p) {
  7104. BLOCK *tem = p->next;
  7105. p->next = pool->freeBlocks;
  7106. pool->freeBlocks = p;
  7107. p = tem;
  7108. }
  7109. }
  7110. pool->blocks = NULL;
  7111. pool->start = NULL;
  7112. pool->ptr = NULL;
  7113. pool->end = NULL;
  7114. }
  7115. static void FASTCALL
  7116. poolDestroy(STRING_POOL *pool) {
  7117. BLOCK *p = pool->blocks;
  7118. while (p) {
  7119. BLOCK *tem = p->next;
  7120. pool->mem->free_fcn(p);
  7121. p = tem;
  7122. }
  7123. p = pool->freeBlocks;
  7124. while (p) {
  7125. BLOCK *tem = p->next;
  7126. pool->mem->free_fcn(p);
  7127. p = tem;
  7128. }
  7129. }
  7130. static XML_Char *
  7131. poolAppend(STRING_POOL *pool, const ENCODING *enc, const char *ptr,
  7132. const char *end) {
  7133. if (! pool->ptr && ! poolGrow(pool))
  7134. return NULL;
  7135. for (;;) {
  7136. const enum XML_Convert_Result convert_res = XmlConvert(
  7137. enc, &ptr, end, (ICHAR **)&(pool->ptr), (const ICHAR *)pool->end);
  7138. if ((convert_res == XML_CONVERT_COMPLETED)
  7139. || (convert_res == XML_CONVERT_INPUT_INCOMPLETE))
  7140. break;
  7141. if (! poolGrow(pool))
  7142. return NULL;
  7143. }
  7144. return pool->start;
  7145. }
  7146. static const XML_Char *FASTCALL
  7147. poolCopyString(STRING_POOL *pool, const XML_Char *s) {
  7148. do {
  7149. if (! poolAppendChar(pool, *s))
  7150. return NULL;
  7151. } while (*s++);
  7152. s = pool->start;
  7153. poolFinish(pool);
  7154. return s;
  7155. }
  7156. static const XML_Char *
  7157. poolCopyStringN(STRING_POOL *pool, const XML_Char *s, int n) {
  7158. if (! pool->ptr && ! poolGrow(pool)) {
  7159. /* The following line is unreachable given the current usage of
  7160. * poolCopyStringN(). Currently it is called from exactly one
  7161. * place to copy the text of a simple general entity. By that
  7162. * point, the name of the entity is already stored in the pool, so
  7163. * pool->ptr cannot be NULL.
  7164. *
  7165. * If poolCopyStringN() is used elsewhere as it well might be,
  7166. * this line may well become executable again. Regardless, this
  7167. * sort of check shouldn't be removed lightly, so we just exclude
  7168. * it from the coverage statistics.
  7169. */
  7170. return NULL; /* LCOV_EXCL_LINE */
  7171. }
  7172. for (; n > 0; --n, s++) {
  7173. if (! poolAppendChar(pool, *s))
  7174. return NULL;
  7175. }
  7176. s = pool->start;
  7177. poolFinish(pool);
  7178. return s;
  7179. }
  7180. static const XML_Char *FASTCALL
  7181. poolAppendString(STRING_POOL *pool, const XML_Char *s) {
  7182. while (*s) {
  7183. if (! poolAppendChar(pool, *s))
  7184. return NULL;
  7185. s++;
  7186. }
  7187. return pool->start;
  7188. }
  7189. static XML_Char *
  7190. poolStoreString(STRING_POOL *pool, const ENCODING *enc, const char *ptr,
  7191. const char *end) {
  7192. if (! poolAppend(pool, enc, ptr, end))
  7193. return NULL;
  7194. if (pool->ptr == pool->end && ! poolGrow(pool))
  7195. return NULL;
  7196. *(pool->ptr)++ = 0;
  7197. return pool->start;
  7198. }
  7199. static size_t
  7200. poolBytesToAllocateFor(int blockSize) {
  7201. /* Unprotected math would be:
  7202. ** return offsetof(BLOCK, s) + blockSize * sizeof(XML_Char);
  7203. **
  7204. ** Detect overflow, avoiding _signed_ overflow undefined behavior
  7205. ** For a + b * c we check b * c in isolation first, so that addition of a
  7206. ** on top has no chance of making us accept a small non-negative number
  7207. */
  7208. const size_t stretch = sizeof(XML_Char); /* can be 4 bytes */
  7209. if (blockSize <= 0)
  7210. return 0;
  7211. if (blockSize > (int)(INT_MAX / stretch))
  7212. return 0;
  7213. {
  7214. const int stretchedBlockSize = blockSize * (int)stretch;
  7215. const int bytesToAllocate
  7216. = (int)(offsetof(BLOCK, s) + (unsigned)stretchedBlockSize);
  7217. if (bytesToAllocate < 0)
  7218. return 0;
  7219. return (size_t)bytesToAllocate;
  7220. }
  7221. }
  7222. static XML_Bool FASTCALL
  7223. poolGrow(STRING_POOL *pool) {
  7224. if (pool->freeBlocks) {
  7225. if (pool->start == 0) {
  7226. pool->blocks = pool->freeBlocks;
  7227. pool->freeBlocks = pool->freeBlocks->next;
  7228. pool->blocks->next = NULL;
  7229. pool->start = pool->blocks->s;
  7230. pool->end = pool->start + pool->blocks->size;
  7231. pool->ptr = pool->start;
  7232. return XML_TRUE;
  7233. }
  7234. if (pool->end - pool->start < pool->freeBlocks->size) {
  7235. BLOCK *tem = pool->freeBlocks->next;
  7236. pool->freeBlocks->next = pool->blocks;
  7237. pool->blocks = pool->freeBlocks;
  7238. pool->freeBlocks = tem;
  7239. memcpy(pool->blocks->s, pool->start,
  7240. (pool->end - pool->start) * sizeof(XML_Char));
  7241. pool->ptr = pool->blocks->s + (pool->ptr - pool->start);
  7242. pool->start = pool->blocks->s;
  7243. pool->end = pool->start + pool->blocks->size;
  7244. return XML_TRUE;
  7245. }
  7246. }
  7247. if (pool->blocks && pool->start == pool->blocks->s) {
  7248. BLOCK *temp;
  7249. int blockSize = (int)((unsigned)(pool->end - pool->start) * 2U);
  7250. size_t bytesToAllocate;
  7251. /* NOTE: Needs to be calculated prior to calling `realloc`
  7252. to avoid dangling pointers: */
  7253. const ptrdiff_t offsetInsideBlock = pool->ptr - pool->start;
  7254. if (blockSize < 0) {
  7255. /* This condition traps a situation where either more than
  7256. * INT_MAX/2 bytes have already been allocated. This isn't
  7257. * readily testable, since it is unlikely that an average
  7258. * machine will have that much memory, so we exclude it from the
  7259. * coverage statistics.
  7260. */
  7261. return XML_FALSE; /* LCOV_EXCL_LINE */
  7262. }
  7263. bytesToAllocate = poolBytesToAllocateFor(blockSize);
  7264. if (bytesToAllocate == 0)
  7265. return XML_FALSE;
  7266. temp = (BLOCK *)pool->mem->realloc_fcn(pool->blocks,
  7267. (unsigned)bytesToAllocate);
  7268. if (temp == NULL)
  7269. return XML_FALSE;
  7270. pool->blocks = temp;
  7271. pool->blocks->size = blockSize;
  7272. pool->ptr = pool->blocks->s + offsetInsideBlock;
  7273. pool->start = pool->blocks->s;
  7274. pool->end = pool->start + blockSize;
  7275. } else {
  7276. BLOCK *tem;
  7277. int blockSize = (int)(pool->end - pool->start);
  7278. size_t bytesToAllocate;
  7279. if (blockSize < 0) {
  7280. /* This condition traps a situation where either more than
  7281. * INT_MAX bytes have already been allocated (which is prevented
  7282. * by various pieces of program logic, not least this one, never
  7283. * mind the unlikelihood of actually having that much memory) or
  7284. * the pool control fields have been corrupted (which could
  7285. * conceivably happen in an extremely buggy user handler
  7286. * function). Either way it isn't readily testable, so we
  7287. * exclude it from the coverage statistics.
  7288. */
  7289. return XML_FALSE; /* LCOV_EXCL_LINE */
  7290. }
  7291. if (blockSize < INIT_BLOCK_SIZE)
  7292. blockSize = INIT_BLOCK_SIZE;
  7293. else {
  7294. /* Detect overflow, avoiding _signed_ overflow undefined behavior */
  7295. if ((int)((unsigned)blockSize * 2U) < 0) {
  7296. return XML_FALSE;
  7297. }
  7298. blockSize *= 2;
  7299. }
  7300. bytesToAllocate = poolBytesToAllocateFor(blockSize);
  7301. if (bytesToAllocate == 0)
  7302. return XML_FALSE;
  7303. tem = pool->mem->malloc_fcn(bytesToAllocate);
  7304. if (! tem)
  7305. return XML_FALSE;
  7306. tem->size = blockSize;
  7307. tem->next = pool->blocks;
  7308. pool->blocks = tem;
  7309. if (pool->ptr != pool->start)
  7310. memcpy(tem->s, pool->start, (pool->ptr - pool->start) * sizeof(XML_Char));
  7311. pool->ptr = tem->s + (pool->ptr - pool->start);
  7312. pool->start = tem->s;
  7313. pool->end = tem->s + blockSize;
  7314. }
  7315. return XML_TRUE;
  7316. }
  7317. static int FASTCALL
  7318. nextScaffoldPart(XML_Parser parser) {
  7319. DTD *const dtd = parser->m_dtd; /* save one level of indirection */
  7320. CONTENT_SCAFFOLD *me;
  7321. int next;
  7322. if (! dtd->scaffIndex) {
  7323. /* Detect and prevent integer overflow.
  7324. * The preprocessor guard addresses the "always false" warning
  7325. * from -Wtype-limits on platforms where
  7326. * sizeof(unsigned int) < sizeof(size_t), e.g. on x86_64. */
  7327. #if UINT_MAX >= SIZE_MAX
  7328. if (parser->m_groupSize > ((size_t)(-1) / sizeof(int))) {
  7329. return -1;
  7330. }
  7331. #endif
  7332. dtd->scaffIndex = (int *)MALLOC(parser, parser->m_groupSize * sizeof(int));
  7333. if (! dtd->scaffIndex)
  7334. return -1;
  7335. dtd->scaffIndex[0] = 0;
  7336. }
  7337. if (dtd->scaffCount >= dtd->scaffSize) {
  7338. CONTENT_SCAFFOLD *temp;
  7339. if (dtd->scaffold) {
  7340. /* Detect and prevent integer overflow */
  7341. if (dtd->scaffSize > UINT_MAX / 2u) {
  7342. return -1;
  7343. }
  7344. /* Detect and prevent integer overflow.
  7345. * The preprocessor guard addresses the "always false" warning
  7346. * from -Wtype-limits on platforms where
  7347. * sizeof(unsigned int) < sizeof(size_t), e.g. on x86_64. */
  7348. #if UINT_MAX >= SIZE_MAX
  7349. if (dtd->scaffSize > (size_t)(-1) / 2u / sizeof(CONTENT_SCAFFOLD)) {
  7350. return -1;
  7351. }
  7352. #endif
  7353. temp = (CONTENT_SCAFFOLD *)REALLOC(
  7354. parser, dtd->scaffold, dtd->scaffSize * 2 * sizeof(CONTENT_SCAFFOLD));
  7355. if (temp == NULL)
  7356. return -1;
  7357. dtd->scaffSize *= 2;
  7358. } else {
  7359. temp = (CONTENT_SCAFFOLD *)MALLOC(parser, INIT_SCAFFOLD_ELEMENTS
  7360. * sizeof(CONTENT_SCAFFOLD));
  7361. if (temp == NULL)
  7362. return -1;
  7363. dtd->scaffSize = INIT_SCAFFOLD_ELEMENTS;
  7364. }
  7365. dtd->scaffold = temp;
  7366. }
  7367. next = dtd->scaffCount++;
  7368. me = &dtd->scaffold[next];
  7369. if (dtd->scaffLevel) {
  7370. CONTENT_SCAFFOLD *parent
  7371. = &dtd->scaffold[dtd->scaffIndex[dtd->scaffLevel - 1]];
  7372. if (parent->lastchild) {
  7373. dtd->scaffold[parent->lastchild].nextsib = next;
  7374. }
  7375. if (! parent->childcnt)
  7376. parent->firstchild = next;
  7377. parent->lastchild = next;
  7378. parent->childcnt++;
  7379. }
  7380. me->firstchild = me->lastchild = me->childcnt = me->nextsib = 0;
  7381. return next;
  7382. }
  7383. static XML_Content *
  7384. build_model(XML_Parser parser) {
  7385. /* Function build_model transforms the existing parser->m_dtd->scaffold
  7386. * array of CONTENT_SCAFFOLD tree nodes into a new array of
  7387. * XML_Content tree nodes followed by a gapless list of zero-terminated
  7388. * strings. */
  7389. DTD *const dtd = parser->m_dtd; /* save one level of indirection */
  7390. XML_Content *ret;
  7391. XML_Char *str; /* the current string writing location */
  7392. /* Detect and prevent integer overflow.
  7393. * The preprocessor guard addresses the "always false" warning
  7394. * from -Wtype-limits on platforms where
  7395. * sizeof(unsigned int) < sizeof(size_t), e.g. on x86_64. */
  7396. #if UINT_MAX >= SIZE_MAX
  7397. if (dtd->scaffCount > (size_t)(-1) / sizeof(XML_Content)) {
  7398. return NULL;
  7399. }
  7400. if (dtd->contentStringLen > (size_t)(-1) / sizeof(XML_Char)) {
  7401. return NULL;
  7402. }
  7403. #endif
  7404. if (dtd->scaffCount * sizeof(XML_Content)
  7405. > (size_t)(-1) - dtd->contentStringLen * sizeof(XML_Char)) {
  7406. return NULL;
  7407. }
  7408. const size_t allocsize = (dtd->scaffCount * sizeof(XML_Content)
  7409. + (dtd->contentStringLen * sizeof(XML_Char)));
  7410. ret = (XML_Content *)MALLOC(parser, allocsize);
  7411. if (! ret)
  7412. return NULL;
  7413. /* What follows is an iterative implementation (of what was previously done
  7414. * recursively in a dedicated function called "build_node". The old recursive
  7415. * build_node could be forced into stack exhaustion from input as small as a
  7416. * few megabyte, and so that was a security issue. Hence, a function call
  7417. * stack is avoided now by resolving recursion.)
  7418. *
  7419. * The iterative approach works as follows:
  7420. *
  7421. * - We have two writing pointers, both walking up the result array; one does
  7422. * the work, the other creates "jobs" for its colleague to do, and leads
  7423. * the way:
  7424. *
  7425. * - The faster one, pointer jobDest, always leads and writes "what job
  7426. * to do" by the other, once they reach that place in the
  7427. * array: leader "jobDest" stores the source node array index (relative
  7428. * to array dtd->scaffold) in field "numchildren".
  7429. *
  7430. * - The slower one, pointer dest, looks at the value stored in the
  7431. * "numchildren" field (which actually holds a source node array index
  7432. * at that time) and puts the real data from dtd->scaffold in.
  7433. *
  7434. * - Before the loop starts, jobDest writes source array index 0
  7435. * (where the root node is located) so that dest will have something to do
  7436. * when it starts operation.
  7437. *
  7438. * - Whenever nodes with children are encountered, jobDest appends
  7439. * them as new jobs, in order. As a result, tree node siblings are
  7440. * adjacent in the resulting array, for example:
  7441. *
  7442. * [0] root, has two children
  7443. * [1] first child of 0, has three children
  7444. * [3] first child of 1, does not have children
  7445. * [4] second child of 1, does not have children
  7446. * [5] third child of 1, does not have children
  7447. * [2] second child of 0, does not have children
  7448. *
  7449. * Or (the same data) presented in flat array view:
  7450. *
  7451. * [0] root, has two children
  7452. *
  7453. * [1] first child of 0, has three children
  7454. * [2] second child of 0, does not have children
  7455. *
  7456. * [3] first child of 1, does not have children
  7457. * [4] second child of 1, does not have children
  7458. * [5] third child of 1, does not have children
  7459. *
  7460. * - The algorithm repeats until all target array indices have been processed.
  7461. */
  7462. XML_Content *dest = ret; /* tree node writing location, moves upwards */
  7463. XML_Content *const destLimit = &ret[dtd->scaffCount];
  7464. XML_Content *jobDest = ret; /* next free writing location in target array */
  7465. str = (XML_Char *)&ret[dtd->scaffCount];
  7466. /* Add the starting job, the root node (index 0) of the source tree */
  7467. (jobDest++)->numchildren = 0;
  7468. for (; dest < destLimit; dest++) {
  7469. /* Retrieve source tree array index from job storage */
  7470. const int src_node = (int)dest->numchildren;
  7471. /* Convert item */
  7472. dest->type = dtd->scaffold[src_node].type;
  7473. dest->quant = dtd->scaffold[src_node].quant;
  7474. if (dest->type == XML_CTYPE_NAME) {
  7475. const XML_Char *src;
  7476. dest->name = str;
  7477. src = dtd->scaffold[src_node].name;
  7478. for (;;) {
  7479. *str++ = *src;
  7480. if (! *src)
  7481. break;
  7482. src++;
  7483. }
  7484. dest->numchildren = 0;
  7485. dest->children = NULL;
  7486. } else {
  7487. unsigned int i;
  7488. int cn;
  7489. dest->name = NULL;
  7490. dest->numchildren = dtd->scaffold[src_node].childcnt;
  7491. dest->children = jobDest;
  7492. /* Append scaffold indices of children to array */
  7493. for (i = 0, cn = dtd->scaffold[src_node].firstchild;
  7494. i < dest->numchildren; i++, cn = dtd->scaffold[cn].nextsib)
  7495. (jobDest++)->numchildren = (unsigned int)cn;
  7496. }
  7497. }
  7498. return ret;
  7499. }
  7500. static ELEMENT_TYPE *
  7501. getElementType(XML_Parser parser, const ENCODING *enc, const char *ptr,
  7502. const char *end) {
  7503. DTD *const dtd = parser->m_dtd; /* save one level of indirection */
  7504. const XML_Char *name = poolStoreString(&dtd->pool, enc, ptr, end);
  7505. ELEMENT_TYPE *ret;
  7506. if (! name)
  7507. return NULL;
  7508. ret = (ELEMENT_TYPE *)lookup(parser, &dtd->elementTypes, name,
  7509. sizeof(ELEMENT_TYPE));
  7510. if (! ret)
  7511. return NULL;
  7512. if (ret->name != name)
  7513. poolDiscard(&dtd->pool);
  7514. else {
  7515. poolFinish(&dtd->pool);
  7516. if (! setElementTypePrefix(parser, ret))
  7517. return NULL;
  7518. }
  7519. return ret;
  7520. }
  7521. static XML_Char *
  7522. copyString(const XML_Char *s, const XML_Memory_Handling_Suite *memsuite) {
  7523. size_t charsRequired = 0;
  7524. XML_Char *result;
  7525. /* First determine how long the string is */
  7526. while (s[charsRequired] != 0) {
  7527. charsRequired++;
  7528. }
  7529. /* Include the terminator */
  7530. charsRequired++;
  7531. /* Now allocate space for the copy */
  7532. result = memsuite->malloc_fcn(charsRequired * sizeof(XML_Char));
  7533. if (result == NULL)
  7534. return NULL;
  7535. /* Copy the original into place */
  7536. memcpy(result, s, charsRequired * sizeof(XML_Char));
  7537. return result;
  7538. }
  7539. #if XML_GE == 1
  7540. static float
  7541. accountingGetCurrentAmplification(XML_Parser rootParser) {
  7542. // 1.........1.........12 => 22
  7543. const size_t lenOfShortestInclude = sizeof("<!ENTITY a SYSTEM 'b'>") - 1;
  7544. const XmlBigCount countBytesOutput
  7545. = rootParser->m_accounting.countBytesDirect
  7546. + rootParser->m_accounting.countBytesIndirect;
  7547. const float amplificationFactor
  7548. = rootParser->m_accounting.countBytesDirect
  7549. ? (countBytesOutput
  7550. / (float)(rootParser->m_accounting.countBytesDirect))
  7551. : ((lenOfShortestInclude
  7552. + rootParser->m_accounting.countBytesIndirect)
  7553. / (float)lenOfShortestInclude);
  7554. assert(! rootParser->m_parentParser);
  7555. return amplificationFactor;
  7556. }
  7557. static void
  7558. accountingReportStats(XML_Parser originParser, const char *epilog) {
  7559. const XML_Parser rootParser = getRootParserOf(originParser, NULL);
  7560. assert(! rootParser->m_parentParser);
  7561. if (rootParser->m_accounting.debugLevel == 0u) {
  7562. return;
  7563. }
  7564. const float amplificationFactor
  7565. = accountingGetCurrentAmplification(rootParser);
  7566. fprintf(stderr,
  7567. "expat: Accounting(%p): Direct " EXPAT_FMT_ULL(
  7568. "10") ", indirect " EXPAT_FMT_ULL("10") ", amplification %8.2f%s",
  7569. (void *)rootParser, rootParser->m_accounting.countBytesDirect,
  7570. rootParser->m_accounting.countBytesIndirect,
  7571. (double)amplificationFactor, epilog);
  7572. }
  7573. static void
  7574. accountingOnAbort(XML_Parser originParser) {
  7575. accountingReportStats(originParser, " ABORTING\n");
  7576. }
  7577. static void
  7578. accountingReportDiff(XML_Parser rootParser,
  7579. unsigned int levelsAwayFromRootParser, const char *before,
  7580. const char *after, ptrdiff_t bytesMore, int source_line,
  7581. enum XML_Account account) {
  7582. assert(! rootParser->m_parentParser);
  7583. fprintf(stderr,
  7584. " (+" EXPAT_FMT_PTRDIFF_T("6") " bytes %s|%u, xmlparse.c:%d) %*s\"",
  7585. bytesMore, (account == XML_ACCOUNT_DIRECT) ? "DIR" : "EXP",
  7586. levelsAwayFromRootParser, source_line, 10, "");
  7587. const char ellipis[] = "[..]";
  7588. const size_t ellipsisLength = sizeof(ellipis) /* because compile-time */ - 1;
  7589. const unsigned int contextLength = 10;
  7590. /* Note: Performance is of no concern here */
  7591. const char *walker = before;
  7592. if ((rootParser->m_accounting.debugLevel >= 3u)
  7593. || (after - before)
  7594. <= (ptrdiff_t)(contextLength + ellipsisLength + contextLength)) {
  7595. for (; walker < after; walker++) {
  7596. fprintf(stderr, "%s", unsignedCharToPrintable(walker[0]));
  7597. }
  7598. } else {
  7599. for (; walker < before + contextLength; walker++) {
  7600. fprintf(stderr, "%s", unsignedCharToPrintable(walker[0]));
  7601. }
  7602. fprintf(stderr, ellipis);
  7603. walker = after - contextLength;
  7604. for (; walker < after; walker++) {
  7605. fprintf(stderr, "%s", unsignedCharToPrintable(walker[0]));
  7606. }
  7607. }
  7608. fprintf(stderr, "\"\n");
  7609. }
  7610. static XML_Bool
  7611. accountingDiffTolerated(XML_Parser originParser, int tok, const char *before,
  7612. const char *after, int source_line,
  7613. enum XML_Account account) {
  7614. /* Note: We need to check the token type *first* to be sure that
  7615. * we can even access variable <after>, safely.
  7616. * E.g. for XML_TOK_NONE <after> may hold an invalid pointer. */
  7617. switch (tok) {
  7618. case XML_TOK_INVALID:
  7619. case XML_TOK_PARTIAL:
  7620. case XML_TOK_PARTIAL_CHAR:
  7621. case XML_TOK_NONE:
  7622. return XML_TRUE;
  7623. }
  7624. if (account == XML_ACCOUNT_NONE)
  7625. return XML_TRUE; /* because these bytes have been accounted for, already */
  7626. unsigned int levelsAwayFromRootParser;
  7627. const XML_Parser rootParser
  7628. = getRootParserOf(originParser, &levelsAwayFromRootParser);
  7629. assert(! rootParser->m_parentParser);
  7630. const int isDirect
  7631. = (account == XML_ACCOUNT_DIRECT) && (originParser == rootParser);
  7632. const ptrdiff_t bytesMore = after - before;
  7633. XmlBigCount *const additionTarget
  7634. = isDirect ? &rootParser->m_accounting.countBytesDirect
  7635. : &rootParser->m_accounting.countBytesIndirect;
  7636. /* Detect and avoid integer overflow */
  7637. if (*additionTarget > (XmlBigCount)(-1) - (XmlBigCount)bytesMore)
  7638. return XML_FALSE;
  7639. *additionTarget += bytesMore;
  7640. const XmlBigCount countBytesOutput
  7641. = rootParser->m_accounting.countBytesDirect
  7642. + rootParser->m_accounting.countBytesIndirect;
  7643. const float amplificationFactor
  7644. = accountingGetCurrentAmplification(rootParser);
  7645. const XML_Bool tolerated
  7646. = (countBytesOutput < rootParser->m_accounting.activationThresholdBytes)
  7647. || (amplificationFactor
  7648. <= rootParser->m_accounting.maximumAmplificationFactor);
  7649. if (rootParser->m_accounting.debugLevel >= 2u) {
  7650. accountingReportStats(rootParser, "");
  7651. accountingReportDiff(rootParser, levelsAwayFromRootParser, before, after,
  7652. bytesMore, source_line, account);
  7653. }
  7654. return tolerated;
  7655. }
  7656. unsigned long long
  7657. testingAccountingGetCountBytesDirect(XML_Parser parser) {
  7658. if (! parser)
  7659. return 0;
  7660. return parser->m_accounting.countBytesDirect;
  7661. }
  7662. unsigned long long
  7663. testingAccountingGetCountBytesIndirect(XML_Parser parser) {
  7664. if (! parser)
  7665. return 0;
  7666. return parser->m_accounting.countBytesIndirect;
  7667. }
  7668. static void
  7669. entityTrackingReportStats(XML_Parser rootParser, ENTITY *entity,
  7670. const char *action, int sourceLine) {
  7671. assert(! rootParser->m_parentParser);
  7672. if (rootParser->m_entity_stats.debugLevel == 0u)
  7673. return;
  7674. # if defined(XML_UNICODE)
  7675. const char *const entityName = "[..]";
  7676. # else
  7677. const char *const entityName = entity->name;
  7678. # endif
  7679. fprintf(
  7680. stderr,
  7681. "expat: Entities(%p): Count %9u, depth %2u/%2u %*s%s%s; %s length %d (xmlparse.c:%d)\n",
  7682. (void *)rootParser, rootParser->m_entity_stats.countEverOpened,
  7683. rootParser->m_entity_stats.currentDepth,
  7684. rootParser->m_entity_stats.maximumDepthSeen,
  7685. ((int)rootParser->m_entity_stats.currentDepth - 1) * 2, "",
  7686. entity->is_param ? "%" : "&", entityName, action, entity->textLen,
  7687. sourceLine);
  7688. }
  7689. static void
  7690. entityTrackingOnOpen(XML_Parser originParser, ENTITY *entity, int sourceLine) {
  7691. const XML_Parser rootParser = getRootParserOf(originParser, NULL);
  7692. assert(! rootParser->m_parentParser);
  7693. rootParser->m_entity_stats.countEverOpened++;
  7694. rootParser->m_entity_stats.currentDepth++;
  7695. if (rootParser->m_entity_stats.currentDepth
  7696. > rootParser->m_entity_stats.maximumDepthSeen) {
  7697. rootParser->m_entity_stats.maximumDepthSeen++;
  7698. }
  7699. entityTrackingReportStats(rootParser, entity, "OPEN ", sourceLine);
  7700. }
  7701. static void
  7702. entityTrackingOnClose(XML_Parser originParser, ENTITY *entity, int sourceLine) {
  7703. const XML_Parser rootParser = getRootParserOf(originParser, NULL);
  7704. assert(! rootParser->m_parentParser);
  7705. entityTrackingReportStats(rootParser, entity, "CLOSE", sourceLine);
  7706. rootParser->m_entity_stats.currentDepth--;
  7707. }
  7708. static XML_Parser
  7709. getRootParserOf(XML_Parser parser, unsigned int *outLevelDiff) {
  7710. XML_Parser rootParser = parser;
  7711. unsigned int stepsTakenUpwards = 0;
  7712. while (rootParser->m_parentParser) {
  7713. rootParser = rootParser->m_parentParser;
  7714. stepsTakenUpwards++;
  7715. }
  7716. assert(! rootParser->m_parentParser);
  7717. if (outLevelDiff != NULL) {
  7718. *outLevelDiff = stepsTakenUpwards;
  7719. }
  7720. return rootParser;
  7721. }
  7722. const char *
  7723. unsignedCharToPrintable(unsigned char c) {
  7724. switch (c) {
  7725. case 0:
  7726. return "\\0";
  7727. case 1:
  7728. return "\\x1";
  7729. case 2:
  7730. return "\\x2";
  7731. case 3:
  7732. return "\\x3";
  7733. case 4:
  7734. return "\\x4";
  7735. case 5:
  7736. return "\\x5";
  7737. case 6:
  7738. return "\\x6";
  7739. case 7:
  7740. return "\\x7";
  7741. case 8:
  7742. return "\\x8";
  7743. case 9:
  7744. return "\\t";
  7745. case 10:
  7746. return "\\n";
  7747. case 11:
  7748. return "\\xB";
  7749. case 12:
  7750. return "\\xC";
  7751. case 13:
  7752. return "\\r";
  7753. case 14:
  7754. return "\\xE";
  7755. case 15:
  7756. return "\\xF";
  7757. case 16:
  7758. return "\\x10";
  7759. case 17:
  7760. return "\\x11";
  7761. case 18:
  7762. return "\\x12";
  7763. case 19:
  7764. return "\\x13";
  7765. case 20:
  7766. return "\\x14";
  7767. case 21:
  7768. return "\\x15";
  7769. case 22:
  7770. return "\\x16";
  7771. case 23:
  7772. return "\\x17";
  7773. case 24:
  7774. return "\\x18";
  7775. case 25:
  7776. return "\\x19";
  7777. case 26:
  7778. return "\\x1A";
  7779. case 27:
  7780. return "\\x1B";
  7781. case 28:
  7782. return "\\x1C";
  7783. case 29:
  7784. return "\\x1D";
  7785. case 30:
  7786. return "\\x1E";
  7787. case 31:
  7788. return "\\x1F";
  7789. case 32:
  7790. return " ";
  7791. case 33:
  7792. return "!";
  7793. case 34:
  7794. return "\\\"";
  7795. case 35:
  7796. return "#";
  7797. case 36:
  7798. return "$";
  7799. case 37:
  7800. return "%";
  7801. case 38:
  7802. return "&";
  7803. case 39:
  7804. return "'";
  7805. case 40:
  7806. return "(";
  7807. case 41:
  7808. return ")";
  7809. case 42:
  7810. return "*";
  7811. case 43:
  7812. return "+";
  7813. case 44:
  7814. return ",";
  7815. case 45:
  7816. return "-";
  7817. case 46:
  7818. return ".";
  7819. case 47:
  7820. return "/";
  7821. case 48:
  7822. return "0";
  7823. case 49:
  7824. return "1";
  7825. case 50:
  7826. return "2";
  7827. case 51:
  7828. return "3";
  7829. case 52:
  7830. return "4";
  7831. case 53:
  7832. return "5";
  7833. case 54:
  7834. return "6";
  7835. case 55:
  7836. return "7";
  7837. case 56:
  7838. return "8";
  7839. case 57:
  7840. return "9";
  7841. case 58:
  7842. return ":";
  7843. case 59:
  7844. return ";";
  7845. case 60:
  7846. return "<";
  7847. case 61:
  7848. return "=";
  7849. case 62:
  7850. return ">";
  7851. case 63:
  7852. return "?";
  7853. case 64:
  7854. return "@";
  7855. case 65:
  7856. return "A";
  7857. case 66:
  7858. return "B";
  7859. case 67:
  7860. return "C";
  7861. case 68:
  7862. return "D";
  7863. case 69:
  7864. return "E";
  7865. case 70:
  7866. return "F";
  7867. case 71:
  7868. return "G";
  7869. case 72:
  7870. return "H";
  7871. case 73:
  7872. return "I";
  7873. case 74:
  7874. return "J";
  7875. case 75:
  7876. return "K";
  7877. case 76:
  7878. return "L";
  7879. case 77:
  7880. return "M";
  7881. case 78:
  7882. return "N";
  7883. case 79:
  7884. return "O";
  7885. case 80:
  7886. return "P";
  7887. case 81:
  7888. return "Q";
  7889. case 82:
  7890. return "R";
  7891. case 83:
  7892. return "S";
  7893. case 84:
  7894. return "T";
  7895. case 85:
  7896. return "U";
  7897. case 86:
  7898. return "V";
  7899. case 87:
  7900. return "W";
  7901. case 88:
  7902. return "X";
  7903. case 89:
  7904. return "Y";
  7905. case 90:
  7906. return "Z";
  7907. case 91:
  7908. return "[";
  7909. case 92:
  7910. return "\\\\";
  7911. case 93:
  7912. return "]";
  7913. case 94:
  7914. return "^";
  7915. case 95:
  7916. return "_";
  7917. case 96:
  7918. return "`";
  7919. case 97:
  7920. return "a";
  7921. case 98:
  7922. return "b";
  7923. case 99:
  7924. return "c";
  7925. case 100:
  7926. return "d";
  7927. case 101:
  7928. return "e";
  7929. case 102:
  7930. return "f";
  7931. case 103:
  7932. return "g";
  7933. case 104:
  7934. return "h";
  7935. case 105:
  7936. return "i";
  7937. case 106:
  7938. return "j";
  7939. case 107:
  7940. return "k";
  7941. case 108:
  7942. return "l";
  7943. case 109:
  7944. return "m";
  7945. case 110:
  7946. return "n";
  7947. case 111:
  7948. return "o";
  7949. case 112:
  7950. return "p";
  7951. case 113:
  7952. return "q";
  7953. case 114:
  7954. return "r";
  7955. case 115:
  7956. return "s";
  7957. case 116:
  7958. return "t";
  7959. case 117:
  7960. return "u";
  7961. case 118:
  7962. return "v";
  7963. case 119:
  7964. return "w";
  7965. case 120:
  7966. return "x";
  7967. case 121:
  7968. return "y";
  7969. case 122:
  7970. return "z";
  7971. case 123:
  7972. return "{";
  7973. case 124:
  7974. return "|";
  7975. case 125:
  7976. return "}";
  7977. case 126:
  7978. return "~";
  7979. case 127:
  7980. return "\\x7F";
  7981. case 128:
  7982. return "\\x80";
  7983. case 129:
  7984. return "\\x81";
  7985. case 130:
  7986. return "\\x82";
  7987. case 131:
  7988. return "\\x83";
  7989. case 132:
  7990. return "\\x84";
  7991. case 133:
  7992. return "\\x85";
  7993. case 134:
  7994. return "\\x86";
  7995. case 135:
  7996. return "\\x87";
  7997. case 136:
  7998. return "\\x88";
  7999. case 137:
  8000. return "\\x89";
  8001. case 138:
  8002. return "\\x8A";
  8003. case 139:
  8004. return "\\x8B";
  8005. case 140:
  8006. return "\\x8C";
  8007. case 141:
  8008. return "\\x8D";
  8009. case 142:
  8010. return "\\x8E";
  8011. case 143:
  8012. return "\\x8F";
  8013. case 144:
  8014. return "\\x90";
  8015. case 145:
  8016. return "\\x91";
  8017. case 146:
  8018. return "\\x92";
  8019. case 147:
  8020. return "\\x93";
  8021. case 148:
  8022. return "\\x94";
  8023. case 149:
  8024. return "\\x95";
  8025. case 150:
  8026. return "\\x96";
  8027. case 151:
  8028. return "\\x97";
  8029. case 152:
  8030. return "\\x98";
  8031. case 153:
  8032. return "\\x99";
  8033. case 154:
  8034. return "\\x9A";
  8035. case 155:
  8036. return "\\x9B";
  8037. case 156:
  8038. return "\\x9C";
  8039. case 157:
  8040. return "\\x9D";
  8041. case 158:
  8042. return "\\x9E";
  8043. case 159:
  8044. return "\\x9F";
  8045. case 160:
  8046. return "\\xA0";
  8047. case 161:
  8048. return "\\xA1";
  8049. case 162:
  8050. return "\\xA2";
  8051. case 163:
  8052. return "\\xA3";
  8053. case 164:
  8054. return "\\xA4";
  8055. case 165:
  8056. return "\\xA5";
  8057. case 166:
  8058. return "\\xA6";
  8059. case 167:
  8060. return "\\xA7";
  8061. case 168:
  8062. return "\\xA8";
  8063. case 169:
  8064. return "\\xA9";
  8065. case 170:
  8066. return "\\xAA";
  8067. case 171:
  8068. return "\\xAB";
  8069. case 172:
  8070. return "\\xAC";
  8071. case 173:
  8072. return "\\xAD";
  8073. case 174:
  8074. return "\\xAE";
  8075. case 175:
  8076. return "\\xAF";
  8077. case 176:
  8078. return "\\xB0";
  8079. case 177:
  8080. return "\\xB1";
  8081. case 178:
  8082. return "\\xB2";
  8083. case 179:
  8084. return "\\xB3";
  8085. case 180:
  8086. return "\\xB4";
  8087. case 181:
  8088. return "\\xB5";
  8089. case 182:
  8090. return "\\xB6";
  8091. case 183:
  8092. return "\\xB7";
  8093. case 184:
  8094. return "\\xB8";
  8095. case 185:
  8096. return "\\xB9";
  8097. case 186:
  8098. return "\\xBA";
  8099. case 187:
  8100. return "\\xBB";
  8101. case 188:
  8102. return "\\xBC";
  8103. case 189:
  8104. return "\\xBD";
  8105. case 190:
  8106. return "\\xBE";
  8107. case 191:
  8108. return "\\xBF";
  8109. case 192:
  8110. return "\\xC0";
  8111. case 193:
  8112. return "\\xC1";
  8113. case 194:
  8114. return "\\xC2";
  8115. case 195:
  8116. return "\\xC3";
  8117. case 196:
  8118. return "\\xC4";
  8119. case 197:
  8120. return "\\xC5";
  8121. case 198:
  8122. return "\\xC6";
  8123. case 199:
  8124. return "\\xC7";
  8125. case 200:
  8126. return "\\xC8";
  8127. case 201:
  8128. return "\\xC9";
  8129. case 202:
  8130. return "\\xCA";
  8131. case 203:
  8132. return "\\xCB";
  8133. case 204:
  8134. return "\\xCC";
  8135. case 205:
  8136. return "\\xCD";
  8137. case 206:
  8138. return "\\xCE";
  8139. case 207:
  8140. return "\\xCF";
  8141. case 208:
  8142. return "\\xD0";
  8143. case 209:
  8144. return "\\xD1";
  8145. case 210:
  8146. return "\\xD2";
  8147. case 211:
  8148. return "\\xD3";
  8149. case 212:
  8150. return "\\xD4";
  8151. case 213:
  8152. return "\\xD5";
  8153. case 214:
  8154. return "\\xD6";
  8155. case 215:
  8156. return "\\xD7";
  8157. case 216:
  8158. return "\\xD8";
  8159. case 217:
  8160. return "\\xD9";
  8161. case 218:
  8162. return "\\xDA";
  8163. case 219:
  8164. return "\\xDB";
  8165. case 220:
  8166. return "\\xDC";
  8167. case 221:
  8168. return "\\xDD";
  8169. case 222:
  8170. return "\\xDE";
  8171. case 223:
  8172. return "\\xDF";
  8173. case 224:
  8174. return "\\xE0";
  8175. case 225:
  8176. return "\\xE1";
  8177. case 226:
  8178. return "\\xE2";
  8179. case 227:
  8180. return "\\xE3";
  8181. case 228:
  8182. return "\\xE4";
  8183. case 229:
  8184. return "\\xE5";
  8185. case 230:
  8186. return "\\xE6";
  8187. case 231:
  8188. return "\\xE7";
  8189. case 232:
  8190. return "\\xE8";
  8191. case 233:
  8192. return "\\xE9";
  8193. case 234:
  8194. return "\\xEA";
  8195. case 235:
  8196. return "\\xEB";
  8197. case 236:
  8198. return "\\xEC";
  8199. case 237:
  8200. return "\\xED";
  8201. case 238:
  8202. return "\\xEE";
  8203. case 239:
  8204. return "\\xEF";
  8205. case 240:
  8206. return "\\xF0";
  8207. case 241:
  8208. return "\\xF1";
  8209. case 242:
  8210. return "\\xF2";
  8211. case 243:
  8212. return "\\xF3";
  8213. case 244:
  8214. return "\\xF4";
  8215. case 245:
  8216. return "\\xF5";
  8217. case 246:
  8218. return "\\xF6";
  8219. case 247:
  8220. return "\\xF7";
  8221. case 248:
  8222. return "\\xF8";
  8223. case 249:
  8224. return "\\xF9";
  8225. case 250:
  8226. return "\\xFA";
  8227. case 251:
  8228. return "\\xFB";
  8229. case 252:
  8230. return "\\xFC";
  8231. case 253:
  8232. return "\\xFD";
  8233. case 254:
  8234. return "\\xFE";
  8235. case 255:
  8236. return "\\xFF";
  8237. // LCOV_EXCL_START
  8238. default:
  8239. assert(0); /* never gets here */
  8240. return "dead code";
  8241. }
  8242. assert(0); /* never gets here */
  8243. // LCOV_EXCL_STOP
  8244. }
  8245. #endif /* XML_GE == 1 */
  8246. static unsigned long
  8247. getDebugLevel(const char *variableName, unsigned long defaultDebugLevel) {
  8248. const char *const valueOrNull = getenv(variableName);
  8249. if (valueOrNull == NULL) {
  8250. return defaultDebugLevel;
  8251. }
  8252. const char *const value = valueOrNull;
  8253. errno = 0;
  8254. char *afterValue = NULL;
  8255. unsigned long debugLevel = strtoul(value, &afterValue, 10);
  8256. if ((errno != 0) || (afterValue == value) || (afterValue[0] != '\0')) {
  8257. errno = 0;
  8258. return defaultDebugLevel;
  8259. }
  8260. return debugLevel;
  8261. }