xmlparse.c 280 KB

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