xmlparse.c 304 KB

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