Debian Codegraph @

pypy/module/pyexpat/src/expat/xmlparse.c

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