xmlparse.c 279 KB

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