Coverage Report

Created: 2024-05-20 06:19

/src/expat/expat/lib/xmlparse.c
Line
Count
Source (jump to first uncovered line)
1
/* 2a14271ad4d35e82bde8ba210b4edb7998794bcbae54deab114046a300f9639a (2.6.2+)
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 <coopercc@users.sourceforge.net>
11
   Copyright (c) 2000-2006 Fred L. Drake, Jr. <fdrake@users.sourceforge.net>
12
   Copyright (c) 2001-2002 Greg Stein <gstein@users.sourceforge.net>
13
   Copyright (c) 2002-2016 Karl Waclawek <karl@waclawek.net>
14
   Copyright (c) 2005-2009 Steven Solie <steven@solie.ca>
15
   Copyright (c) 2016      Eric Rahm <erahm@mozilla.com>
16
   Copyright (c) 2016-2024 Sebastian Pipping <sebastian@pipping.org>
17
   Copyright (c) 2016      Gaurav <g.gupta@samsung.com>
18
   Copyright (c) 2016      Thomas Beutlich <tc@tbeu.de>
19
   Copyright (c) 2016      Gustavo Grieco <gustavo.grieco@imag.fr>
20
   Copyright (c) 2016      Pascal Cuoq <cuoq@trust-in-soft.com>
21
   Copyright (c) 2016      Ed Schouten <ed@nuxi.nl>
22
   Copyright (c) 2017-2022 Rhodri James <rhodri@wildebeest.org.uk>
23
   Copyright (c) 2017      Václav Slavík <vaclav@slavik.io>
24
   Copyright (c) 2017      Viktor Szakats <commit@vsz.me>
25
   Copyright (c) 2017      Chanho Park <chanho61.park@samsung.com>
26
   Copyright (c) 2017      Rolf Eike Beer <eike@sf-mail.de>
27
   Copyright (c) 2017      Hans Wennborg <hans@chromium.org>
28
   Copyright (c) 2018      Anton Maklakov <antmak.pub@gmail.com>
29
   Copyright (c) 2018      Benjamin Peterson <benjamin@python.org>
30
   Copyright (c) 2018      Marco Maggi <marco.maggi-ipsu@poste.it>
31
   Copyright (c) 2018      Mariusz Zaborski <oshogbo@vexillium.org>
32
   Copyright (c) 2019      David Loffredo <loffredo@steptools.com>
33
   Copyright (c) 2019-2020 Ben Wagner <bungeman@chromium.org>
34
   Copyright (c) 2019      Vadim Zeitlin <vadim@zeitlins.org>
35
   Copyright (c) 2021      Donghee Na <donghee.na@python.org>
36
   Copyright (c) 2022      Samanta Navarro <ferivoz@riseup.net>
37
   Copyright (c) 2022      Jeffrey Walton <noloader@gmail.com>
38
   Copyright (c) 2022      Jann Horn <jannh@google.com>
39
   Copyright (c) 2022      Sean McBride <sean@rogue-research.com>
40
   Copyright (c) 2023      Owain Davies <owaind@bath.edu>
41
   Copyright (c) 2023-2024 Sony Corporation / Snild Dolkow <snild@sony.com>
42
   Licensed under the MIT license:
43
44
   Permission is  hereby granted,  free of charge,  to any  person obtaining
45
   a  copy  of  this  software   and  associated  documentation  files  (the
46
   "Software"),  to  deal in  the  Software  without restriction,  including
47
   without  limitation the  rights  to use,  copy,  modify, merge,  publish,
48
   distribute, sublicense, and/or sell copies of the Software, and to permit
49
   persons  to whom  the Software  is  furnished to  do so,  subject to  the
50
   following conditions:
51
52
   The above copyright  notice and this permission notice  shall be included
53
   in all copies or substantial portions of the Software.
54
55
   THE  SOFTWARE  IS  PROVIDED  "AS  IS",  WITHOUT  WARRANTY  OF  ANY  KIND,
56
   EXPRESS  OR IMPLIED,  INCLUDING  BUT  NOT LIMITED  TO  THE WARRANTIES  OF
57
   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
58
   NO EVENT SHALL THE AUTHORS OR  COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
59
   DAMAGES OR  OTHER LIABILITY, WHETHER  IN AN  ACTION OF CONTRACT,  TORT OR
60
   OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
61
   USE OR OTHER DEALINGS IN THE SOFTWARE.
62
*/
63
64
#define XML_BUILDING_EXPAT 1
65
66
#include "expat_config.h"
67
68
#if ! defined(XML_GE) || (1 - XML_GE - 1 == 2) || (XML_GE < 0) || (XML_GE > 1)
69
#  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)
70
#endif
71
72
#if defined(XML_DTD) && XML_GE == 0
73
#  error Either undefine XML_DTD or define XML_GE to 1.
74
#endif
75
76
#if ! defined(XML_CONTEXT_BYTES) || (1 - XML_CONTEXT_BYTES - 1 == 2)           \
77
    || (XML_CONTEXT_BYTES + 0 < 0)
78
#  error XML_CONTEXT_BYTES must be defined, non-empty and >=0 (0 to disable, >=1 to enable; 1024 is a common default)
79
#endif
80
81
#if defined(HAVE_SYSCALL_GETRANDOM)
82
#  if ! defined(_GNU_SOURCE)
83
#    define _GNU_SOURCE 1 /* syscall prototype */
84
#  endif
85
#endif
86
87
#ifdef _WIN32
88
/* force stdlib to define rand_s() */
89
#  if ! defined(_CRT_RAND_S)
90
#    define _CRT_RAND_S
91
#  endif
92
#endif
93
94
#include <stdbool.h>
95
#include <stddef.h>
96
#include <string.h> /* memset(), memcpy() */
97
#include <assert.h>
98
#include <limits.h> /* UINT_MAX */
99
#include <stdio.h>  /* fprintf */
100
#include <stdlib.h> /* getenv, rand_s */
101
#include <stdint.h> /* uintptr_t */
102
#include <math.h>   /* isnan */
103
104
#ifdef _WIN32
105
#  define getpid GetCurrentProcessId
106
#else
107
#  include <sys/time.h>  /* gettimeofday() */
108
#  include <sys/types.h> /* getpid() */
109
#  include <unistd.h>    /* getpid() */
110
#  include <fcntl.h>     /* O_RDONLY */
111
#  include <errno.h>
112
#endif
113
114
#ifdef _WIN32
115
#  include "winconfig.h"
116
#endif
117
118
#include "ascii.h"
119
#include "expat.h"
120
#include "siphash.h"
121
122
#if defined(HAVE_GETRANDOM) || defined(HAVE_SYSCALL_GETRANDOM)
123
#  if defined(HAVE_GETRANDOM)
124
#    include <sys/random.h> /* getrandom */
125
#  else
126
#    include <unistd.h>      /* syscall */
127
#    include <sys/syscall.h> /* SYS_getrandom */
128
#  endif
129
#  if ! defined(GRND_NONBLOCK)
130
#    define GRND_NONBLOCK 0x0001
131
#  endif /* defined(GRND_NONBLOCK) */
132
#endif   /* defined(HAVE_GETRANDOM) || defined(HAVE_SYSCALL_GETRANDOM) */
133
134
#if defined(HAVE_LIBBSD)                                                       \
135
    && (defined(HAVE_ARC4RANDOM_BUF) || defined(HAVE_ARC4RANDOM))
136
#  include <bsd/stdlib.h>
137
#endif
138
139
#if defined(_WIN32) && ! defined(LOAD_LIBRARY_SEARCH_SYSTEM32)
140
#  define LOAD_LIBRARY_SEARCH_SYSTEM32 0x00000800
141
#endif
142
143
#if ! defined(HAVE_GETRANDOM) && ! defined(HAVE_SYSCALL_GETRANDOM)             \
144
    && ! defined(HAVE_ARC4RANDOM_BUF) && ! defined(HAVE_ARC4RANDOM)            \
145
    && ! defined(XML_DEV_URANDOM) && ! defined(_WIN32)                         \
146
    && ! defined(XML_POOR_ENTROPY)
147
#  error You do not have support for any sources of high quality entropy \
148
    enabled.  For end user security, that is probably not what you want. \
149
    \
150
    Your options include: \
151
      * Linux >=3.17 + glibc >=2.25 (getrandom): HAVE_GETRANDOM, \
152
      * Linux >=3.17 + glibc (including <2.25) (syscall SYS_getrandom): HAVE_SYSCALL_GETRANDOM, \
153
      * BSD / macOS >=10.7 / glibc >=2.36 (arc4random_buf): HAVE_ARC4RANDOM_BUF, \
154
      * BSD / macOS (including <10.7) / glibc >=2.36 (arc4random): HAVE_ARC4RANDOM, \
155
      * libbsd (arc4random_buf): HAVE_ARC4RANDOM_BUF + HAVE_LIBBSD, \
156
      * libbsd (arc4random): HAVE_ARC4RANDOM + HAVE_LIBBSD, \
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
21.4M
#  define XmlConvert XmlUtf8Convert
178
63.3k
#  define XmlGetInternalEncoding XmlGetUtf8InternalEncoding
179
21.1k
#  define XmlGetInternalEncodingNS XmlGetUtf8InternalEncodingNS
180
111k
#  define XmlEncode XmlUtf8Encode
181
2.20M
#  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
11.1M
#  define XML_T(x) x
208
82.1k
#  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
562k
#define ROUND_UP(n, sz) (((n) + ((sz) - 1)) & ~((sz) - 1))
214
215
/* Do safe (NULL-aware) pointer arithmetic */
216
991k
#define EXPAT_SAFE_PTR_DIFF(p, q) (((p) && (q)) ? ((p) - (q)) : 0)
217
218
84.4k
#define EXPAT_MIN(a, b) (((a) < (b)) ? (a) : (b))
219
220
#include "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
  const XML_Memory_Handling_Suite *mem;
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
228k
  ((((hash) & ~(mask)) >> ((power) - 1)) & ((mask) >> 2))
252
#define PROBE_STEP(hash, mask, power)                                          \
253
228k
  ((unsigned char)((SECOND_HASH(hash, mask, power)) | 1))
254
255
typedef struct {
256
  NAMED **p;
257
  NAMED **end;
258
} HASH_TABLE_ITER;
259
260
1.92M
#define INIT_TAG_BUF_SIZE 32 /* must be a multiple of sizeof(XML_Char) */
261
84.4k
#define INIT_DATA_BUF_SIZE 1024
262
86.3k
#define INIT_ATTS_SIZE 16
263
303
#define INIT_ATTS_VERSION 0xFFFFFFFF
264
181k
#define INIT_BLOCK_SIZE 1024
265
84.4k
#define INIT_BUFFER_SIZE 1024
266
267
49.2k
#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
   XMLParseBuffer() 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
  char *buf;     /* buffer for name components */
312
  char *bufEnd;  /* end of the buffer */
313
  BINDING *bindings;
314
} TAG;
315
316
typedef struct {
317
  const XML_Char *name;
318
  const XML_Char *textPtr;
319
  int textLen;   /* length in XML_Chars */
320
  int processed; /* # of processed bytes - when suspended */
321
  const XML_Char *systemId;
322
  const XML_Char *base;
323
  const XML_Char *publicId;
324
  const XML_Char *notation;
325
  XML_Bool open;
326
  XML_Bool is_param;
327
  XML_Bool is_internal; /* true if declared in internal subset outside PE */
328
} ENTITY;
329
330
typedef struct {
331
  enum XML_Content_Type type;
332
  enum XML_Content_Quant quant;
333
  const XML_Char *name;
334
  int firstchild;
335
  int lastchild;
336
  int childcnt;
337
  int nextsib;
338
} CONTENT_SCAFFOLD;
339
340
0
#define INIT_SCAFFOLD_ELEMENTS 32
341
342
typedef struct block {
343
  struct block *next;
344
  int size;
345
  XML_Char s[1];
346
} BLOCK;
347
348
typedef struct {
349
  BLOCK *blocks;
350
  BLOCK *freeBlocks;
351
  const XML_Char *end;
352
  XML_Char *ptr;
353
  XML_Char *start;
354
  const XML_Memory_Handling_Suite *mem;
355
} STRING_POOL;
356
357
/* The XML_Char before the name is used to determine whether
358
   an attribute has been specified. */
359
typedef struct attribute_id {
360
  XML_Char *name;
361
  PREFIX *prefix;
362
  XML_Bool maybeTokenized;
363
  XML_Bool xmlns;
364
} ATTRIBUTE_ID;
365
366
typedef struct {
367
  const ATTRIBUTE_ID *id;
368
  XML_Bool isCdata;
369
  const XML_Char *value;
370
} DEFAULT_ATTRIBUTE;
371
372
typedef struct {
373
  unsigned long version;
374
  unsigned long hash;
375
  const XML_Char *uriName;
376
} NS_ATT;
377
378
typedef struct {
379
  const XML_Char *name;
380
  PREFIX *prefix;
381
  const ATTRIBUTE_ID *idAtt;
382
  int nDefaultAtts;
383
  int allocDefaultAtts;
384
  DEFAULT_ATTRIBUTE *defaultAtts;
385
} ELEMENT_TYPE;
386
387
typedef struct {
388
  HASH_TABLE generalEntities;
389
  HASH_TABLE elementTypes;
390
  HASH_TABLE attributeIds;
391
  HASH_TABLE prefixes;
392
  STRING_POOL pool;
393
  STRING_POOL entityValuePool;
394
  /* false once a parameter entity reference has been skipped */
395
  XML_Bool keepProcessing;
396
  /* true once an internal or external PE reference has been encountered;
397
     this includes the reference to an external subset */
398
  XML_Bool hasParamEntityRefs;
399
  XML_Bool standalone;
400
#ifdef XML_DTD
401
  /* indicates if external PE has been read */
402
  XML_Bool paramEntityRead;
403
  HASH_TABLE paramEntities;
404
#endif /* XML_DTD */
405
  PREFIX defaultPrefix;
406
  /* === scaffolding for building content model === */
407
  XML_Bool in_eldecl;
408
  CONTENT_SCAFFOLD *scaffold;
409
  unsigned contentStringLen;
410
  unsigned scaffSize;
411
  unsigned scaffCount;
412
  int scaffLevel;
413
  int *scaffIndex;
414
} DTD;
415
416
typedef struct open_internal_entity {
417
  const char *internalEventPtr;
418
  const char *internalEventEndPtr;
419
  struct open_internal_entity *next;
420
  ENTITY *entity;
421
  int startTagLevel;
422
  XML_Bool betweenDecl; /* WFC: PE Between Declarations */
423
} OPEN_INTERNAL_ENTITY;
424
425
enum XML_Account {
426
  XML_ACCOUNT_DIRECT,           /* bytes directly passed to the Expat parser */
427
  XML_ACCOUNT_ENTITY_EXPANSION, /* intermediate bytes produced during entity
428
                                   expansion */
429
  XML_ACCOUNT_NONE              /* i.e. do not account, was accounted already */
430
};
431
432
#if XML_GE == 1
433
typedef unsigned long long XmlBigCount;
434
typedef struct accounting {
435
  XmlBigCount countBytesDirect;
436
  XmlBigCount countBytesIndirect;
437
  unsigned long debugLevel;
438
  float maximumAmplificationFactor; // >=1.0
439
  unsigned long long activationThresholdBytes;
440
} ACCOUNTING;
441
442
typedef struct entity_stats {
443
  unsigned int countEverOpened;
444
  unsigned int currentDepth;
445
  unsigned int maximumDepthSeen;
446
  unsigned long debugLevel;
447
} ENTITY_STATS;
448
#endif /* XML_GE == 1 */
449
450
typedef enum XML_Error PTRCALL Processor(XML_Parser parser, const char *start,
451
                                         const char *end, const char **endPtr);
452
453
static Processor prologProcessor;
454
static Processor prologInitProcessor;
455
static Processor contentProcessor;
456
static Processor cdataSectionProcessor;
457
#ifdef XML_DTD
458
static Processor ignoreSectionProcessor;
459
static Processor externalParEntProcessor;
460
static Processor externalParEntInitProcessor;
461
static Processor entityValueProcessor;
462
static Processor entityValueInitProcessor;
463
#endif /* XML_DTD */
464
static Processor epilogProcessor;
465
static Processor errorProcessor;
466
static Processor externalEntityInitProcessor;
467
static Processor externalEntityInitProcessor2;
468
static Processor externalEntityInitProcessor3;
469
static Processor externalEntityContentProcessor;
470
static Processor internalEntityProcessor;
471
472
static enum XML_Error handleUnknownEncoding(XML_Parser parser,
473
                                            const XML_Char *encodingName);
474
static enum XML_Error processXmlDecl(XML_Parser parser, int isGeneralTextEntity,
475
                                     const char *s, const char *next);
476
static enum XML_Error initializeEncoding(XML_Parser parser);
477
static enum XML_Error doProlog(XML_Parser parser, const ENCODING *enc,
478
                               const char *s, const char *end, int tok,
479
                               const char *next, const char **nextPtr,
480
                               XML_Bool haveMore, XML_Bool allowClosingDoctype,
481
                               enum XML_Account account);
482
static enum XML_Error processInternalEntity(XML_Parser parser, ENTITY *entity,
483
                                            XML_Bool betweenDecl);
484
static enum XML_Error doContent(XML_Parser parser, int startTagLevel,
485
                                const ENCODING *enc, const char *start,
486
                                const char *end, const char **endPtr,
487
                                XML_Bool haveMore, enum XML_Account account);
488
static enum XML_Error doCdataSection(XML_Parser parser, const ENCODING *enc,
489
                                     const char **startPtr, const char *end,
490
                                     const char **nextPtr, XML_Bool haveMore,
491
                                     enum XML_Account account);
492
#ifdef XML_DTD
493
static enum XML_Error doIgnoreSection(XML_Parser parser, const ENCODING *enc,
494
                                      const char **startPtr, const char *end,
495
                                      const char **nextPtr, XML_Bool haveMore);
496
#endif /* XML_DTD */
497
498
static void freeBindings(XML_Parser parser, BINDING *bindings);
499
static enum XML_Error storeAtts(XML_Parser parser, const ENCODING *enc,
500
                                const char *attStr, TAG_NAME *tagNamePtr,
501
                                BINDING **bindingsPtr,
502
                                enum XML_Account account);
503
static enum XML_Error addBinding(XML_Parser parser, PREFIX *prefix,
504
                                 const ATTRIBUTE_ID *attId, const XML_Char *uri,
505
                                 BINDING **bindingsPtr);
506
static int defineAttribute(ELEMENT_TYPE *type, ATTRIBUTE_ID *attId,
507
                           XML_Bool isCdata, XML_Bool isId,
508
                           const XML_Char *value, XML_Parser parser);
509
static enum XML_Error storeAttributeValue(XML_Parser parser,
510
                                          const ENCODING *enc, XML_Bool isCdata,
511
                                          const char *ptr, const char *end,
512
                                          STRING_POOL *pool,
513
                                          enum XML_Account account);
514
static enum XML_Error appendAttributeValue(XML_Parser parser,
515
                                           const ENCODING *enc,
516
                                           XML_Bool isCdata, const char *ptr,
517
                                           const char *end, STRING_POOL *pool,
518
                                           enum XML_Account account);
519
static ATTRIBUTE_ID *getAttributeId(XML_Parser parser, const ENCODING *enc,
520
                                    const char *start, const char *end);
521
static int setElementTypePrefix(XML_Parser parser, ELEMENT_TYPE *elementType);
522
#if XML_GE == 1
523
static enum XML_Error storeEntityValue(XML_Parser parser, const ENCODING *enc,
524
                                       const char *start, const char *end,
525
                                       enum XML_Account account);
526
#else
527
static enum XML_Error storeSelfEntityValue(XML_Parser parser, ENTITY *entity);
528
#endif
529
static int reportProcessingInstruction(XML_Parser parser, const ENCODING *enc,
530
                                       const char *start, const char *end);
531
static int reportComment(XML_Parser parser, const ENCODING *enc,
532
                         const char *start, const char *end);
533
static void reportDefault(XML_Parser parser, const ENCODING *enc,
534
                          const char *start, const char *end);
535
536
static const XML_Char *getContext(XML_Parser parser);
537
static XML_Bool setContext(XML_Parser parser, const XML_Char *context);
538
539
static void FASTCALL normalizePublicId(XML_Char *s);
540
541
static DTD *dtdCreate(const XML_Memory_Handling_Suite *ms);
542
/* do not call if m_parentParser != NULL */
543
static void dtdReset(DTD *p, const XML_Memory_Handling_Suite *ms);
544
static void dtdDestroy(DTD *p, XML_Bool isDocEntity,
545
                       const XML_Memory_Handling_Suite *ms);
546
static int dtdCopy(XML_Parser oldParser, DTD *newDtd, const DTD *oldDtd,
547
                   const XML_Memory_Handling_Suite *ms);
548
static int copyEntityTable(XML_Parser oldParser, HASH_TABLE *newTable,
549
                           STRING_POOL *newPool, const HASH_TABLE *oldTable);
550
static NAMED *lookup(XML_Parser parser, HASH_TABLE *table, KEY name,
551
                     size_t createSize);
552
static void FASTCALL hashTableInit(HASH_TABLE *table,
553
                                   const XML_Memory_Handling_Suite *ms);
554
static void FASTCALL hashTableClear(HASH_TABLE *table);
555
static void FASTCALL hashTableDestroy(HASH_TABLE *table);
556
static void FASTCALL hashTableIterInit(HASH_TABLE_ITER *iter,
557
                                       const HASH_TABLE *table);
558
static NAMED *FASTCALL hashTableIterNext(HASH_TABLE_ITER *iter);
559
560
static void FASTCALL poolInit(STRING_POOL *pool,
561
                              const XML_Memory_Handling_Suite *ms);
562
static void FASTCALL poolClear(STRING_POOL *pool);
563
static void FASTCALL poolDestroy(STRING_POOL *pool);
564
static XML_Char *poolAppend(STRING_POOL *pool, const ENCODING *enc,
565
                            const char *ptr, const char *end);
566
static XML_Char *poolStoreString(STRING_POOL *pool, const ENCODING *enc,
567
                                 const char *ptr, const char *end);
568
static XML_Bool FASTCALL poolGrow(STRING_POOL *pool);
569
static const XML_Char *FASTCALL poolCopyString(STRING_POOL *pool,
570
                                               const XML_Char *s);
571
static const XML_Char *poolCopyStringN(STRING_POOL *pool, const XML_Char *s,
572
                                       int n);
573
static const XML_Char *FASTCALL poolAppendString(STRING_POOL *pool,
574
                                                 const XML_Char *s);
575
576
static int FASTCALL nextScaffoldPart(XML_Parser parser);
577
static XML_Content *build_model(XML_Parser parser);
578
static ELEMENT_TYPE *getElementType(XML_Parser parser, const ENCODING *enc,
579
                                    const char *ptr, const char *end);
580
581
static XML_Char *copyString(const XML_Char *s,
582
                            const XML_Memory_Handling_Suite *memsuite);
583
584
static unsigned long generate_hash_secret_salt(XML_Parser parser);
585
static XML_Bool startParsing(XML_Parser parser);
586
587
static XML_Parser parserCreate(const XML_Char *encodingName,
588
                               const XML_Memory_Handling_Suite *memsuite,
589
                               const XML_Char *nameSep, DTD *dtd);
590
591
static void parserInit(XML_Parser parser, const XML_Char *encodingName);
592
593
#if XML_GE == 1
594
static float accountingGetCurrentAmplification(XML_Parser rootParser);
595
static void accountingReportStats(XML_Parser originParser, const char *epilog);
596
static void accountingOnAbort(XML_Parser originParser);
597
static void accountingReportDiff(XML_Parser rootParser,
598
                                 unsigned int levelsAwayFromRootParser,
599
                                 const char *before, const char *after,
600
                                 ptrdiff_t bytesMore, int source_line,
601
                                 enum XML_Account account);
602
static XML_Bool accountingDiffTolerated(XML_Parser originParser, int tok,
603
                                        const char *before, const char *after,
604
                                        int source_line,
605
                                        enum XML_Account account);
606
607
static void entityTrackingReportStats(XML_Parser parser, ENTITY *entity,
608
                                      const char *action, int sourceLine);
609
static void entityTrackingOnOpen(XML_Parser parser, ENTITY *entity,
610
                                 int sourceLine);
611
static void entityTrackingOnClose(XML_Parser parser, ENTITY *entity,
612
                                  int sourceLine);
613
614
static XML_Parser getRootParserOf(XML_Parser parser,
615
                                  unsigned int *outLevelDiff);
616
#endif /* XML_GE == 1 */
617
618
static unsigned long getDebugLevel(const char *variableName,
619
                                   unsigned long defaultDebugLevel);
620
621
262k
#define poolStart(pool) ((pool)->start)
622
1.74M
#define poolLength(pool) ((pool)->ptr - (pool)->start)
623
272
#define poolChop(pool) ((void)--(pool->ptr))
624
1.69M
#define poolLastChar(pool) (((pool)->ptr)[-1])
625
1.81M
#define poolDiscard(pool) ((pool)->ptr = (pool)->start)
626
968k
#define poolFinish(pool) ((pool)->start = (pool)->ptr)
627
#define poolAppendChar(pool, c)                                                \
628
56.6M
  (((pool)->ptr == (pool)->end && ! poolGrow(pool))                            \
629
56.6M
       ? 0                                                                     \
630
56.6M
       : ((*((pool)->ptr)++ = c), 1))
631
632
#if ! defined(XML_TESTING)
633
const
634
#endif
635
    XML_Bool g_reparseDeferralEnabledDefault
636
    = XML_TRUE; // write ONLY in runtests.c
637
#if defined(XML_TESTING)
638
unsigned int g_bytesScanned = 0; // used for testing only
639
#endif
640
641
struct XML_ParserStruct {
642
  /* The first member must be m_userData so that the XML_GetUserData
643
     macro works. */
644
  void *m_userData;
645
  void *m_handlerArg;
646
647
  // How the four parse buffer pointers below relate in time and space:
648
  //
649
  //   m_buffer <= m_bufferPtr <= m_bufferEnd  <= m_bufferLim
650
  //   |           |              |               |
651
  //   <--parsed-->|              |               |
652
  //               <---parsing--->|               |
653
  //                              <--unoccupied-->|
654
  //   <---------total-malloced/realloced-------->|
655
656
  char *m_buffer; // malloc/realloc base pointer of parse buffer
657
  const XML_Memory_Handling_Suite m_mem;
658
  const char *m_bufferPtr; // first character to be parsed
659
  char *m_bufferEnd;       // past last character to be parsed
660
  const char *m_bufferLim; // allocated end of m_buffer
661
662
  XML_Index m_parseEndByteIndex;
663
  const char *m_parseEndPtr;
664
  size_t m_partialTokenBytesBefore; /* used in heuristic to avoid O(n^2) */
665
  XML_Bool m_reparseDeferralEnabled;
666
  int m_lastBufferRequestSize;
667
  XML_Char *m_dataBuf;
668
  XML_Char *m_dataBufEnd;
669
  XML_StartElementHandler m_startElementHandler;
670
  XML_EndElementHandler m_endElementHandler;
671
  XML_CharacterDataHandler m_characterDataHandler;
672
  XML_ProcessingInstructionHandler m_processingInstructionHandler;
673
  XML_CommentHandler m_commentHandler;
674
  XML_StartCdataSectionHandler m_startCdataSectionHandler;
675
  XML_EndCdataSectionHandler m_endCdataSectionHandler;
676
  XML_DefaultHandler m_defaultHandler;
677
  XML_StartDoctypeDeclHandler m_startDoctypeDeclHandler;
678
  XML_EndDoctypeDeclHandler m_endDoctypeDeclHandler;
679
  XML_UnparsedEntityDeclHandler m_unparsedEntityDeclHandler;
680
  XML_NotationDeclHandler m_notationDeclHandler;
681
  XML_StartNamespaceDeclHandler m_startNamespaceDeclHandler;
682
  XML_EndNamespaceDeclHandler m_endNamespaceDeclHandler;
683
  XML_NotStandaloneHandler m_notStandaloneHandler;
684
  XML_ExternalEntityRefHandler m_externalEntityRefHandler;
685
  XML_Parser m_externalEntityRefHandlerArg;
686
  XML_SkippedEntityHandler m_skippedEntityHandler;
687
  XML_UnknownEncodingHandler m_unknownEncodingHandler;
688
  XML_ElementDeclHandler m_elementDeclHandler;
689
  XML_AttlistDeclHandler m_attlistDeclHandler;
690
  XML_EntityDeclHandler m_entityDeclHandler;
691
  XML_XmlDeclHandler m_xmlDeclHandler;
692
  const ENCODING *m_encoding;
693
  INIT_ENCODING m_initEncoding;
694
  const ENCODING *m_internalEncoding;
695
  const XML_Char *m_protocolEncodingName;
696
  XML_Bool m_ns;
697
  XML_Bool m_ns_triplets;
698
  void *m_unknownEncodingMem;
699
  void *m_unknownEncodingData;
700
  void *m_unknownEncodingHandlerData;
701
  void(XMLCALL *m_unknownEncodingRelease)(void *);
702
  PROLOG_STATE m_prologState;
703
  Processor *m_processor;
704
  enum XML_Error m_errorCode;
705
  const char *m_eventPtr;
706
  const char *m_eventEndPtr;
707
  const char *m_positionPtr;
708
  OPEN_INTERNAL_ENTITY *m_openInternalEntities;
709
  OPEN_INTERNAL_ENTITY *m_freeInternalEntities;
710
  XML_Bool m_defaultExpandInternalEntities;
711
  int m_tagLevel;
712
  ENTITY *m_declEntity;
713
  const XML_Char *m_doctypeName;
714
  const XML_Char *m_doctypeSysid;
715
  const XML_Char *m_doctypePubid;
716
  const XML_Char *m_declAttributeType;
717
  const XML_Char *m_declNotationName;
718
  const XML_Char *m_declNotationPublicId;
719
  ELEMENT_TYPE *m_declElementType;
720
  ATTRIBUTE_ID *m_declAttributeId;
721
  XML_Bool m_declAttributeIsCdata;
722
  XML_Bool m_declAttributeIsId;
723
  DTD *m_dtd;
724
  const XML_Char *m_curBase;
725
  TAG *m_tagStack;
726
  TAG *m_freeTagList;
727
  BINDING *m_inheritedBindings;
728
  BINDING *m_freeBindingList;
729
  int m_attsSize;
730
  int m_nSpecifiedAtts;
731
  int m_idAttIndex;
732
  ATTRIBUTE *m_atts;
733
  NS_ATT *m_nsAtts;
734
  unsigned long m_nsAttsVersion;
735
  unsigned char m_nsAttsPower;
736
#ifdef XML_ATTR_INFO
737
  XML_AttrInfo *m_attInfo;
738
#endif
739
  POSITION m_position;
740
  STRING_POOL m_tempPool;
741
  STRING_POOL m_temp2Pool;
742
  char *m_groupConnector;
743
  unsigned int m_groupSize;
744
  XML_Char m_namespaceSeparator;
745
  XML_Parser m_parentParser;
746
  XML_ParsingStatus m_parsingStatus;
747
#ifdef XML_DTD
748
  XML_Bool m_isParamEntity;
749
  XML_Bool m_useForeignDTD;
750
  enum XML_ParamEntityParsing m_paramEntityParsing;
751
#endif
752
  unsigned long m_hash_secret_salt;
753
#if XML_GE == 1
754
  ACCOUNTING m_accounting;
755
  ENTITY_STATS m_entity_stats;
756
#endif
757
};
758
759
4.17M
#define MALLOC(parser, s) (parser->m_mem.malloc_fcn((s)))
760
17.3k
#define REALLOC(parser, p, s) (parser->m_mem.realloc_fcn((p), (s)))
761
4.62M
#define FREE(parser, p) (parser->m_mem.free_fcn((p)))
762
763
XML_Parser XMLCALL
764
21.1k
XML_ParserCreate(const XML_Char *encodingName) {
765
21.1k
  return XML_ParserCreate_MM(encodingName, NULL, NULL);
766
21.1k
}
767
768
XML_Parser XMLCALL
769
21.1k
XML_ParserCreateNS(const XML_Char *encodingName, XML_Char nsSep) {
770
21.1k
  XML_Char tmp[2] = {nsSep, 0};
771
21.1k
  return XML_ParserCreate_MM(encodingName, NULL, tmp);
772
21.1k
}
773
774
// "xml=http://www.w3.org/XML/1998/namespace"
775
static const XML_Char implicitContext[]
776
    = {ASCII_x,     ASCII_m,     ASCII_l,      ASCII_EQUALS, ASCII_h,
777
       ASCII_t,     ASCII_t,     ASCII_p,      ASCII_COLON,  ASCII_SLASH,
778
       ASCII_SLASH, ASCII_w,     ASCII_w,      ASCII_w,      ASCII_PERIOD,
779
       ASCII_w,     ASCII_3,     ASCII_PERIOD, ASCII_o,      ASCII_r,
780
       ASCII_g,     ASCII_SLASH, ASCII_X,      ASCII_M,      ASCII_L,
781
       ASCII_SLASH, ASCII_1,     ASCII_9,      ASCII_9,      ASCII_8,
782
       ASCII_SLASH, ASCII_n,     ASCII_a,      ASCII_m,      ASCII_e,
783
       ASCII_s,     ASCII_p,     ASCII_a,      ASCII_c,      ASCII_e,
784
       '\0'};
785
786
/* To avoid warnings about unused functions: */
787
#if ! defined(HAVE_ARC4RANDOM_BUF) && ! defined(HAVE_ARC4RANDOM)
788
789
#  if defined(HAVE_GETRANDOM) || defined(HAVE_SYSCALL_GETRANDOM)
790
791
/* Obtain entropy on Linux 3.17+ */
792
static int
793
0
writeRandomBytes_getrandom_nonblock(void *target, size_t count) {
794
0
  int success = 0; /* full count bytes written? */
795
0
  size_t bytesWrittenTotal = 0;
796
0
  const unsigned int getrandomFlags = GRND_NONBLOCK;
797
798
0
  do {
799
0
    void *const currentTarget = (void *)((char *)target + bytesWrittenTotal);
800
0
    const size_t bytesToWrite = count - bytesWrittenTotal;
801
802
0
    const int bytesWrittenMore =
803
0
#    if defined(HAVE_GETRANDOM)
804
0
        getrandom(currentTarget, bytesToWrite, getrandomFlags);
805
#    else
806
        syscall(SYS_getrandom, currentTarget, bytesToWrite, getrandomFlags);
807
#    endif
808
809
0
    if (bytesWrittenMore > 0) {
810
0
      bytesWrittenTotal += bytesWrittenMore;
811
0
      if (bytesWrittenTotal >= count)
812
0
        success = 1;
813
0
    }
814
0
  } while (! success && (errno == EINTR));
815
816
0
  return success;
817
0
}
818
819
#  endif /* defined(HAVE_GETRANDOM) || defined(HAVE_SYSCALL_GETRANDOM) */
820
821
#  if ! defined(_WIN32) && defined(XML_DEV_URANDOM)
822
823
/* Extract entropy from /dev/urandom */
824
static int
825
0
writeRandomBytes_dev_urandom(void *target, size_t count) {
826
0
  int success = 0; /* full count bytes written? */
827
0
  size_t bytesWrittenTotal = 0;
828
829
0
  const int fd = open("/dev/urandom", O_RDONLY);
830
0
  if (fd < 0) {
831
0
    return 0;
832
0
  }
833
834
0
  do {
835
0
    void *const currentTarget = (void *)((char *)target + bytesWrittenTotal);
836
0
    const size_t bytesToWrite = count - bytesWrittenTotal;
837
838
0
    const ssize_t bytesWrittenMore = read(fd, currentTarget, bytesToWrite);
839
840
0
    if (bytesWrittenMore > 0) {
841
0
      bytesWrittenTotal += bytesWrittenMore;
842
0
      if (bytesWrittenTotal >= count)
843
0
        success = 1;
844
0
    }
845
0
  } while (! success && (errno == EINTR));
846
847
0
  close(fd);
848
0
  return success;
849
0
}
850
851
#  endif /* ! defined(_WIN32) && defined(XML_DEV_URANDOM) */
852
853
#endif /* ! defined(HAVE_ARC4RANDOM_BUF) && ! defined(HAVE_ARC4RANDOM) */
854
855
#if defined(HAVE_ARC4RANDOM) && ! defined(HAVE_ARC4RANDOM_BUF)
856
857
static void
858
writeRandomBytes_arc4random(void *target, size_t count) {
859
  size_t bytesWrittenTotal = 0;
860
861
  while (bytesWrittenTotal < count) {
862
    const uint32_t random32 = arc4random();
863
    size_t i = 0;
864
865
    for (; (i < sizeof(random32)) && (bytesWrittenTotal < count);
866
         i++, bytesWrittenTotal++) {
867
      const uint8_t random8 = (uint8_t)(random32 >> (i * 8));
868
      ((uint8_t *)target)[bytesWrittenTotal] = random8;
869
    }
870
  }
871
}
872
873
#endif /* defined(HAVE_ARC4RANDOM) && ! defined(HAVE_ARC4RANDOM_BUF) */
874
875
#ifdef _WIN32
876
877
/* Provide declaration of rand_s() for MinGW-32 (not 64, which has it),
878
   as it didn't declare it in its header prior to version 5.3.0 of its
879
   runtime package (mingwrt, containing stdlib.h).  The upstream fix
880
   was introduced at https://osdn.net/projects/mingw/ticket/39658 . */
881
#  if defined(__MINGW32__) && defined(__MINGW32_VERSION)                       \
882
      && __MINGW32_VERSION < 5003000L && ! defined(__MINGW64_VERSION_MAJOR)
883
__declspec(dllimport) int rand_s(unsigned int *);
884
#  endif
885
886
/* Obtain entropy on Windows using the rand_s() function which
887
 * generates cryptographically secure random numbers.  Internally it
888
 * uses RtlGenRandom API which is present in Windows XP and later.
889
 */
890
static int
891
writeRandomBytes_rand_s(void *target, size_t count) {
892
  size_t bytesWrittenTotal = 0;
893
894
  while (bytesWrittenTotal < count) {
895
    unsigned int random32 = 0;
896
    size_t i = 0;
897
898
    if (rand_s(&random32))
899
      return 0; /* failure */
900
901
    for (; (i < sizeof(random32)) && (bytesWrittenTotal < count);
902
         i++, bytesWrittenTotal++) {
903
      const uint8_t random8 = (uint8_t)(random32 >> (i * 8));
904
      ((uint8_t *)target)[bytesWrittenTotal] = random8;
905
    }
906
  }
907
  return 1; /* success */
908
}
909
910
#endif /* _WIN32 */
911
912
#if ! defined(HAVE_ARC4RANDOM_BUF) && ! defined(HAVE_ARC4RANDOM)
913
914
static unsigned long
915
0
gather_time_entropy(void) {
916
#  ifdef _WIN32
917
  FILETIME ft;
918
  GetSystemTimeAsFileTime(&ft); /* never fails */
919
  return ft.dwHighDateTime ^ ft.dwLowDateTime;
920
#  else
921
0
  struct timeval tv;
922
0
  int gettimeofday_res;
923
924
0
  gettimeofday_res = gettimeofday(&tv, NULL);
925
926
#    if defined(NDEBUG)
927
  (void)gettimeofday_res;
928
#    else
929
0
  assert(gettimeofday_res == 0);
930
0
#    endif /* defined(NDEBUG) */
931
932
  /* Microseconds time is <20 bits entropy */
933
0
  return tv.tv_usec;
934
0
#  endif
935
0
}
936
937
#endif /* ! defined(HAVE_ARC4RANDOM_BUF) && ! defined(HAVE_ARC4RANDOM) */
938
939
static unsigned long
940
0
ENTROPY_DEBUG(const char *label, unsigned long entropy) {
941
0
  if (getDebugLevel("EXPAT_ENTROPY_DEBUG", 0) >= 1u) {
942
0
    fprintf(stderr, "expat: Entropy: %s --> 0x%0*lx (%lu bytes)\n", label,
943
0
            (int)sizeof(entropy) * 2, entropy, (unsigned long)sizeof(entropy));
944
0
  }
945
0
  return entropy;
946
0
}
947
948
static unsigned long
949
0
generate_hash_secret_salt(XML_Parser parser) {
950
0
  unsigned long entropy;
951
0
  (void)parser;
952
953
  /* "Failproof" high quality providers: */
954
#if defined(HAVE_ARC4RANDOM_BUF)
955
  arc4random_buf(&entropy, sizeof(entropy));
956
  return ENTROPY_DEBUG("arc4random_buf", entropy);
957
#elif defined(HAVE_ARC4RANDOM)
958
  writeRandomBytes_arc4random((void *)&entropy, sizeof(entropy));
959
  return ENTROPY_DEBUG("arc4random", entropy);
960
#else
961
  /* Try high quality providers first .. */
962
#  ifdef _WIN32
963
  if (writeRandomBytes_rand_s((void *)&entropy, sizeof(entropy))) {
964
    return ENTROPY_DEBUG("rand_s", entropy);
965
  }
966
#  elif defined(HAVE_GETRANDOM) || defined(HAVE_SYSCALL_GETRANDOM)
967
0
  if (writeRandomBytes_getrandom_nonblock((void *)&entropy, sizeof(entropy))) {
968
0
    return ENTROPY_DEBUG("getrandom", entropy);
969
0
  }
970
0
#  endif
971
0
#  if ! defined(_WIN32) && defined(XML_DEV_URANDOM)
972
0
  if (writeRandomBytes_dev_urandom((void *)&entropy, sizeof(entropy))) {
973
0
    return ENTROPY_DEBUG("/dev/urandom", entropy);
974
0
  }
975
0
#  endif /* ! defined(_WIN32) && defined(XML_DEV_URANDOM) */
976
  /* .. and self-made low quality for backup: */
977
978
  /* Process ID is 0 bits entropy if attacker has local access */
979
0
  entropy = gather_time_entropy() ^ getpid();
980
981
  /* Factors are 2^31-1 and 2^61-1 (Mersenne primes M31 and M61) */
982
0
  if (sizeof(unsigned long) == 4) {
983
0
    return ENTROPY_DEBUG("fallback(4)", entropy * 2147483647);
984
0
  } else {
985
0
    return ENTROPY_DEBUG("fallback(8)",
986
0
                         entropy * (unsigned long)2305843009213693951ULL);
987
0
  }
988
0
#endif
989
0
}
990
991
static unsigned long
992
4.63M
get_hash_secret_salt(XML_Parser parser) {
993
4.63M
  if (parser->m_parentParser != NULL)
994
94.3k
    return get_hash_secret_salt(parser->m_parentParser);
995
4.53M
  return parser->m_hash_secret_salt;
996
4.63M
}
997
998
static enum XML_Error
999
callProcessor(XML_Parser parser, const char *start, const char *end,
1000
168k
              const char **endPtr) {
1001
168k
  const size_t have_now = EXPAT_SAFE_PTR_DIFF(end, start);
1002
1003
168k
  if (parser->m_reparseDeferralEnabled
1004
168k
      && ! parser->m_parsingStatus.finalBuffer) {
1005
    // Heuristic: don't try to parse a partial token again until the amount of
1006
    // available data has increased significantly.
1007
84.4k
    const size_t had_before = parser->m_partialTokenBytesBefore;
1008
    // ...but *do* try anyway if we're close to causing a reallocation.
1009
84.4k
    size_t available_buffer
1010
84.4k
        = EXPAT_SAFE_PTR_DIFF(parser->m_bufferPtr, parser->m_buffer);
1011
84.4k
#if XML_CONTEXT_BYTES > 0
1012
84.4k
    available_buffer -= EXPAT_MIN(available_buffer, XML_CONTEXT_BYTES);
1013
84.4k
#endif
1014
84.4k
    available_buffer
1015
84.4k
        += EXPAT_SAFE_PTR_DIFF(parser->m_bufferLim, parser->m_bufferEnd);
1016
    // m_lastBufferRequestSize is never assigned a value < 0, so the cast is ok
1017
84.4k
    const bool enough
1018
84.4k
        = (have_now >= 2 * had_before)
1019
84.4k
          || ((size_t)parser->m_lastBufferRequestSize > available_buffer);
1020
1021
84.4k
    if (! enough) {
1022
0
      *endPtr = start; // callers may expect this to be set
1023
0
      return XML_ERROR_NONE;
1024
0
    }
1025
84.4k
  }
1026
#if defined(XML_TESTING)
1027
  g_bytesScanned += (unsigned)have_now;
1028
#endif
1029
168k
  const enum XML_Error ret = parser->m_processor(parser, start, end, endPtr);
1030
168k
  if (ret == XML_ERROR_NONE) {
1031
    // if we consumed nothing, remember what we had on this parse attempt.
1032
36.1k
    if (*endPtr == start) {
1033
11.0k
      parser->m_partialTokenBytesBefore = have_now;
1034
25.1k
    } else {
1035
25.1k
      parser->m_partialTokenBytesBefore = 0;
1036
25.1k
    }
1037
36.1k
  }
1038
168k
  return ret;
1039
168k
}
1040
1041
static XML_Bool /* only valid for root parser */
1042
42.2k
startParsing(XML_Parser parser) {
1043
  /* hash functions must be initialized before setContext() is called */
1044
42.2k
  if (parser->m_hash_secret_salt == 0)
1045
0
    parser->m_hash_secret_salt = generate_hash_secret_salt(parser);
1046
42.2k
  if (parser->m_ns) {
1047
    /* implicit context only set for root parser, since child
1048
       parsers (i.e. external entity parsers) will inherit it
1049
    */
1050
21.1k
    return setContext(parser, implicitContext);
1051
21.1k
  }
1052
21.1k
  return XML_TRUE;
1053
42.2k
}
1054
1055
XML_Parser XMLCALL
1056
XML_ParserCreate_MM(const XML_Char *encodingName,
1057
                    const XML_Memory_Handling_Suite *memsuite,
1058
42.2k
                    const XML_Char *nameSep) {
1059
42.2k
  return parserCreate(encodingName, memsuite, nameSep, NULL);
1060
42.2k
}
1061
1062
static XML_Parser
1063
parserCreate(const XML_Char *encodingName,
1064
             const XML_Memory_Handling_Suite *memsuite, const XML_Char *nameSep,
1065
84.4k
             DTD *dtd) {
1066
84.4k
  XML_Parser parser;
1067
1068
84.4k
  if (memsuite) {
1069
42.2k
    XML_Memory_Handling_Suite *mtemp;
1070
42.2k
    parser = memsuite->malloc_fcn(sizeof(struct XML_ParserStruct));
1071
42.2k
    if (parser != NULL) {
1072
42.2k
      mtemp = (XML_Memory_Handling_Suite *)&(parser->m_mem);
1073
42.2k
      mtemp->malloc_fcn = memsuite->malloc_fcn;
1074
42.2k
      mtemp->realloc_fcn = memsuite->realloc_fcn;
1075
42.2k
      mtemp->free_fcn = memsuite->free_fcn;
1076
42.2k
    }
1077
42.2k
  } else {
1078
42.2k
    XML_Memory_Handling_Suite *mtemp;
1079
42.2k
    parser = (XML_Parser)malloc(sizeof(struct XML_ParserStruct));
1080
42.2k
    if (parser != NULL) {
1081
42.2k
      mtemp = (XML_Memory_Handling_Suite *)&(parser->m_mem);
1082
42.2k
      mtemp->malloc_fcn = malloc;
1083
42.2k
      mtemp->realloc_fcn = realloc;
1084
42.2k
      mtemp->free_fcn = free;
1085
42.2k
    }
1086
42.2k
  }
1087
1088
84.4k
  if (! parser)
1089
0
    return parser;
1090
1091
84.4k
  parser->m_buffer = NULL;
1092
84.4k
  parser->m_bufferLim = NULL;
1093
1094
84.4k
  parser->m_attsSize = INIT_ATTS_SIZE;
1095
84.4k
  parser->m_atts
1096
84.4k
      = (ATTRIBUTE *)MALLOC(parser, parser->m_attsSize * sizeof(ATTRIBUTE));
1097
84.4k
  if (parser->m_atts == NULL) {
1098
0
    FREE(parser, parser);
1099
0
    return NULL;
1100
0
  }
1101
#ifdef XML_ATTR_INFO
1102
  parser->m_attInfo = (XML_AttrInfo *)MALLOC(
1103
      parser, parser->m_attsSize * sizeof(XML_AttrInfo));
1104
  if (parser->m_attInfo == NULL) {
1105
    FREE(parser, parser->m_atts);
1106
    FREE(parser, parser);
1107
    return NULL;
1108
  }
1109
#endif
1110
84.4k
  parser->m_dataBuf
1111
84.4k
      = (XML_Char *)MALLOC(parser, INIT_DATA_BUF_SIZE * sizeof(XML_Char));
1112
84.4k
  if (parser->m_dataBuf == NULL) {
1113
0
    FREE(parser, parser->m_atts);
1114
#ifdef XML_ATTR_INFO
1115
    FREE(parser, parser->m_attInfo);
1116
#endif
1117
0
    FREE(parser, parser);
1118
0
    return NULL;
1119
0
  }
1120
84.4k
  parser->m_dataBufEnd = parser->m_dataBuf + INIT_DATA_BUF_SIZE;
1121
1122
84.4k
  if (dtd)
1123
21.1k
    parser->m_dtd = dtd;
1124
63.3k
  else {
1125
63.3k
    parser->m_dtd = dtdCreate(&parser->m_mem);
1126
63.3k
    if (parser->m_dtd == NULL) {
1127
0
      FREE(parser, parser->m_dataBuf);
1128
0
      FREE(parser, parser->m_atts);
1129
#ifdef XML_ATTR_INFO
1130
      FREE(parser, parser->m_attInfo);
1131
#endif
1132
0
      FREE(parser, parser);
1133
0
      return NULL;
1134
0
    }
1135
63.3k
  }
1136
1137
84.4k
  parser->m_freeBindingList = NULL;
1138
84.4k
  parser->m_freeTagList = NULL;
1139
84.4k
  parser->m_freeInternalEntities = NULL;
1140
1141
84.4k
  parser->m_groupSize = 0;
1142
84.4k
  parser->m_groupConnector = NULL;
1143
1144
84.4k
  parser->m_unknownEncodingHandler = NULL;
1145
84.4k
  parser->m_unknownEncodingHandlerData = NULL;
1146
1147
84.4k
  parser->m_namespaceSeparator = ASCII_EXCL;
1148
84.4k
  parser->m_ns = XML_FALSE;
1149
84.4k
  parser->m_ns_triplets = XML_FALSE;
1150
1151
84.4k
  parser->m_nsAtts = NULL;
1152
84.4k
  parser->m_nsAttsVersion = 0;
1153
84.4k
  parser->m_nsAttsPower = 0;
1154
1155
84.4k
  parser->m_protocolEncodingName = NULL;
1156
1157
84.4k
  poolInit(&parser->m_tempPool, &(parser->m_mem));
1158
84.4k
  poolInit(&parser->m_temp2Pool, &(parser->m_mem));
1159
84.4k
  parserInit(parser, encodingName);
1160
1161
84.4k
  if (encodingName && ! parser->m_protocolEncodingName) {
1162
0
    if (dtd) {
1163
      // We need to stop the upcoming call to XML_ParserFree from happily
1164
      // destroying parser->m_dtd because the DTD is shared with the parent
1165
      // parser and the only guard that keeps XML_ParserFree from destroying
1166
      // parser->m_dtd is parser->m_isParamEntity but it will be set to
1167
      // XML_TRUE only later in XML_ExternalEntityParserCreate (or not at all).
1168
0
      parser->m_dtd = NULL;
1169
0
    }
1170
0
    XML_ParserFree(parser);
1171
0
    return NULL;
1172
0
  }
1173
1174
84.4k
  if (nameSep) {
1175
21.1k
    parser->m_ns = XML_TRUE;
1176
21.1k
    parser->m_internalEncoding = XmlGetInternalEncodingNS();
1177
21.1k
    parser->m_namespaceSeparator = *nameSep;
1178
63.3k
  } else {
1179
63.3k
    parser->m_internalEncoding = XmlGetInternalEncoding();
1180
63.3k
  }
1181
1182
84.4k
  return parser;
1183
84.4k
}
1184
1185
static void
1186
102k
parserInit(XML_Parser parser, const XML_Char *encodingName) {
1187
102k
  parser->m_processor = prologInitProcessor;
1188
102k
  XmlPrologStateInit(&parser->m_prologState);
1189
102k
  if (encodingName != NULL) {
1190
21.1k
    parser->m_protocolEncodingName = copyString(encodingName, &(parser->m_mem));
1191
21.1k
  }
1192
102k
  parser->m_curBase = NULL;
1193
102k
  XmlInitEncoding(&parser->m_initEncoding, &parser->m_encoding, 0);
1194
102k
  parser->m_userData = NULL;
1195
102k
  parser->m_handlerArg = NULL;
1196
102k
  parser->m_startElementHandler = NULL;
1197
102k
  parser->m_endElementHandler = NULL;
1198
102k
  parser->m_characterDataHandler = NULL;
1199
102k
  parser->m_processingInstructionHandler = NULL;
1200
102k
  parser->m_commentHandler = NULL;
1201
102k
  parser->m_startCdataSectionHandler = NULL;
1202
102k
  parser->m_endCdataSectionHandler = NULL;
1203
102k
  parser->m_defaultHandler = NULL;
1204
102k
  parser->m_startDoctypeDeclHandler = NULL;
1205
102k
  parser->m_endDoctypeDeclHandler = NULL;
1206
102k
  parser->m_unparsedEntityDeclHandler = NULL;
1207
102k
  parser->m_notationDeclHandler = NULL;
1208
102k
  parser->m_startNamespaceDeclHandler = NULL;
1209
102k
  parser->m_endNamespaceDeclHandler = NULL;
1210
102k
  parser->m_notStandaloneHandler = NULL;
1211
102k
  parser->m_externalEntityRefHandler = NULL;
1212
102k
  parser->m_externalEntityRefHandlerArg = parser;
1213
102k
  parser->m_skippedEntityHandler = NULL;
1214
102k
  parser->m_elementDeclHandler = NULL;
1215
102k
  parser->m_attlistDeclHandler = NULL;
1216
102k
  parser->m_entityDeclHandler = NULL;
1217
102k
  parser->m_xmlDeclHandler = NULL;
1218
102k
  parser->m_bufferPtr = parser->m_buffer;
1219
102k
  parser->m_bufferEnd = parser->m_buffer;
1220
102k
  parser->m_parseEndByteIndex = 0;
1221
102k
  parser->m_parseEndPtr = NULL;
1222
102k
  parser->m_partialTokenBytesBefore = 0;
1223
102k
  parser->m_reparseDeferralEnabled = g_reparseDeferralEnabledDefault;
1224
102k
  parser->m_lastBufferRequestSize = 0;
1225
102k
  parser->m_declElementType = NULL;
1226
102k
  parser->m_declAttributeId = NULL;
1227
102k
  parser->m_declEntity = NULL;
1228
102k
  parser->m_doctypeName = NULL;
1229
102k
  parser->m_doctypeSysid = NULL;
1230
102k
  parser->m_doctypePubid = NULL;
1231
102k
  parser->m_declAttributeType = NULL;
1232
102k
  parser->m_declNotationName = NULL;
1233
102k
  parser->m_declNotationPublicId = NULL;
1234
102k
  parser->m_declAttributeIsCdata = XML_FALSE;
1235
102k
  parser->m_declAttributeIsId = XML_FALSE;
1236
102k
  memset(&parser->m_position, 0, sizeof(POSITION));
1237
102k
  parser->m_errorCode = XML_ERROR_NONE;
1238
102k
  parser->m_eventPtr = NULL;
1239
102k
  parser->m_eventEndPtr = NULL;
1240
102k
  parser->m_positionPtr = NULL;
1241
102k
  parser->m_openInternalEntities = NULL;
1242
102k
  parser->m_defaultExpandInternalEntities = XML_TRUE;
1243
102k
  parser->m_tagLevel = 0;
1244
102k
  parser->m_tagStack = NULL;
1245
102k
  parser->m_inheritedBindings = NULL;
1246
102k
  parser->m_nSpecifiedAtts = 0;
1247
102k
  parser->m_unknownEncodingMem = NULL;
1248
102k
  parser->m_unknownEncodingRelease = NULL;
1249
102k
  parser->m_unknownEncodingData = NULL;
1250
102k
  parser->m_parentParser = NULL;
1251
102k
  parser->m_parsingStatus.parsing = XML_INITIALIZED;
1252
102k
#ifdef XML_DTD
1253
102k
  parser->m_isParamEntity = XML_FALSE;
1254
102k
  parser->m_useForeignDTD = XML_FALSE;
1255
102k
  parser->m_paramEntityParsing = XML_PARAM_ENTITY_PARSING_NEVER;
1256
102k
#endif
1257
102k
  parser->m_hash_secret_salt = 0;
1258
1259
102k
#if XML_GE == 1
1260
102k
  memset(&parser->m_accounting, 0, sizeof(ACCOUNTING));
1261
102k
  parser->m_accounting.debugLevel = getDebugLevel("EXPAT_ACCOUNTING_DEBUG", 0u);
1262
102k
  parser->m_accounting.maximumAmplificationFactor
1263
102k
      = EXPAT_BILLION_LAUGHS_ATTACK_PROTECTION_MAXIMUM_AMPLIFICATION_DEFAULT;
1264
102k
  parser->m_accounting.activationThresholdBytes
1265
102k
      = EXPAT_BILLION_LAUGHS_ATTACK_PROTECTION_ACTIVATION_THRESHOLD_DEFAULT;
1266
1267
102k
  memset(&parser->m_entity_stats, 0, sizeof(ENTITY_STATS));
1268
102k
  parser->m_entity_stats.debugLevel = getDebugLevel("EXPAT_ENTITY_DEBUG", 0u);
1269
102k
#endif
1270
102k
}
1271
1272
/* moves list of bindings to m_freeBindingList */
1273
static void FASTCALL
1274
1.35M
moveToFreeBindingList(XML_Parser parser, BINDING *bindings) {
1275
1.36M
  while (bindings) {
1276
10.5k
    BINDING *b = bindings;
1277
10.5k
    bindings = bindings->nextTagBinding;
1278
10.5k
    b->nextTagBinding = parser->m_freeBindingList;
1279
10.5k
    parser->m_freeBindingList = b;
1280
10.5k
  }
1281
1.35M
}
1282
1283
XML_Bool XMLCALL
1284
35.8k
XML_ParserReset(XML_Parser parser, const XML_Char *encodingName) {
1285
35.8k
  TAG *tStk;
1286
35.8k
  OPEN_INTERNAL_ENTITY *openEntityList;
1287
1288
35.8k
  if (parser == NULL)
1289
0
    return XML_FALSE;
1290
1291
35.8k
  if (parser->m_parentParser)
1292
17.9k
    return XML_FALSE;
1293
  /* move m_tagStack to m_freeTagList */
1294
17.9k
  tStk = parser->m_tagStack;
1295
1.35M
  while (tStk) {
1296
1.34M
    TAG *tag = tStk;
1297
1.34M
    tStk = tStk->parent;
1298
1.34M
    tag->parent = parser->m_freeTagList;
1299
1.34M
    moveToFreeBindingList(parser, tag->bindings);
1300
1.34M
    tag->bindings = NULL;
1301
1.34M
    parser->m_freeTagList = tag;
1302
1.34M
  }
1303
  /* move m_openInternalEntities to m_freeInternalEntities */
1304
17.9k
  openEntityList = parser->m_openInternalEntities;
1305
19.6k
  while (openEntityList) {
1306
1.66k
    OPEN_INTERNAL_ENTITY *openEntity = openEntityList;
1307
1.66k
    openEntityList = openEntity->next;
1308
1.66k
    openEntity->next = parser->m_freeInternalEntities;
1309
1.66k
    parser->m_freeInternalEntities = openEntity;
1310
1.66k
  }
1311
17.9k
  moveToFreeBindingList(parser, parser->m_inheritedBindings);
1312
17.9k
  FREE(parser, parser->m_unknownEncodingMem);
1313
17.9k
  if (parser->m_unknownEncodingRelease)
1314
0
    parser->m_unknownEncodingRelease(parser->m_unknownEncodingData);
1315
17.9k
  poolClear(&parser->m_tempPool);
1316
17.9k
  poolClear(&parser->m_temp2Pool);
1317
17.9k
  FREE(parser, (void *)parser->m_protocolEncodingName);
1318
17.9k
  parser->m_protocolEncodingName = NULL;
1319
17.9k
  parserInit(parser, encodingName);
1320
17.9k
  dtdReset(parser->m_dtd, &parser->m_mem);
1321
17.9k
  return XML_TRUE;
1322
35.8k
}
1323
1324
enum XML_Status XMLCALL
1325
0
XML_SetEncoding(XML_Parser parser, const XML_Char *encodingName) {
1326
0
  if (parser == NULL)
1327
0
    return XML_STATUS_ERROR;
1328
  /* Block after XML_Parse()/XML_ParseBuffer() has been called.
1329
     XXX There's no way for the caller to determine which of the
1330
     XXX possible error cases caused the XML_STATUS_ERROR return.
1331
  */
1332
0
  if (parser->m_parsingStatus.parsing == XML_PARSING
1333
0
      || parser->m_parsingStatus.parsing == XML_SUSPENDED)
1334
0
    return XML_STATUS_ERROR;
1335
1336
  /* Get rid of any previous encoding name */
1337
0
  FREE(parser, (void *)parser->m_protocolEncodingName);
1338
1339
0
  if (encodingName == NULL)
1340
    /* No new encoding name */
1341
0
    parser->m_protocolEncodingName = NULL;
1342
0
  else {
1343
    /* Copy the new encoding name into allocated memory */
1344
0
    parser->m_protocolEncodingName = copyString(encodingName, &(parser->m_mem));
1345
0
    if (! parser->m_protocolEncodingName)
1346
0
      return XML_STATUS_ERROR;
1347
0
  }
1348
0
  return XML_STATUS_OK;
1349
0
}
1350
1351
XML_Parser XMLCALL
1352
XML_ExternalEntityParserCreate(XML_Parser oldParser, const XML_Char *context,
1353
42.2k
                               const XML_Char *encodingName) {
1354
42.2k
  XML_Parser parser = oldParser;
1355
42.2k
  DTD *newDtd = NULL;
1356
42.2k
  DTD *oldDtd;
1357
42.2k
  XML_StartElementHandler oldStartElementHandler;
1358
42.2k
  XML_EndElementHandler oldEndElementHandler;
1359
42.2k
  XML_CharacterDataHandler oldCharacterDataHandler;
1360
42.2k
  XML_ProcessingInstructionHandler oldProcessingInstructionHandler;
1361
42.2k
  XML_CommentHandler oldCommentHandler;
1362
42.2k
  XML_StartCdataSectionHandler oldStartCdataSectionHandler;
1363
42.2k
  XML_EndCdataSectionHandler oldEndCdataSectionHandler;
1364
42.2k
  XML_DefaultHandler oldDefaultHandler;
1365
42.2k
  XML_UnparsedEntityDeclHandler oldUnparsedEntityDeclHandler;
1366
42.2k
  XML_NotationDeclHandler oldNotationDeclHandler;
1367
42.2k
  XML_StartNamespaceDeclHandler oldStartNamespaceDeclHandler;
1368
42.2k
  XML_EndNamespaceDeclHandler oldEndNamespaceDeclHandler;
1369
42.2k
  XML_NotStandaloneHandler oldNotStandaloneHandler;
1370
42.2k
  XML_ExternalEntityRefHandler oldExternalEntityRefHandler;
1371
42.2k
  XML_SkippedEntityHandler oldSkippedEntityHandler;
1372
42.2k
  XML_UnknownEncodingHandler oldUnknownEncodingHandler;
1373
42.2k
  XML_ElementDeclHandler oldElementDeclHandler;
1374
42.2k
  XML_AttlistDeclHandler oldAttlistDeclHandler;
1375
42.2k
  XML_EntityDeclHandler oldEntityDeclHandler;
1376
42.2k
  XML_XmlDeclHandler oldXmlDeclHandler;
1377
42.2k
  ELEMENT_TYPE *oldDeclElementType;
1378
1379
42.2k
  void *oldUserData;
1380
42.2k
  void *oldHandlerArg;
1381
42.2k
  XML_Bool oldDefaultExpandInternalEntities;
1382
42.2k
  XML_Parser oldExternalEntityRefHandlerArg;
1383
42.2k
#ifdef XML_DTD
1384
42.2k
  enum XML_ParamEntityParsing oldParamEntityParsing;
1385
42.2k
  int oldInEntityValue;
1386
42.2k
#endif
1387
42.2k
  XML_Bool oldns_triplets;
1388
  /* Note that the new parser shares the same hash secret as the old
1389
     parser, so that dtdCopy and copyEntityTable can lookup values
1390
     from hash tables associated with either parser without us having
1391
     to worry which hash secrets each table has.
1392
  */
1393
42.2k
  unsigned long oldhash_secret_salt;
1394
42.2k
  XML_Bool oldReparseDeferralEnabled;
1395
1396
  /* Validate the oldParser parameter before we pull everything out of it */
1397
42.2k
  if (oldParser == NULL)
1398
0
    return NULL;
1399
1400
  /* Stash the original parser contents on the stack */
1401
42.2k
  oldDtd = parser->m_dtd;
1402
42.2k
  oldStartElementHandler = parser->m_startElementHandler;
1403
42.2k
  oldEndElementHandler = parser->m_endElementHandler;
1404
42.2k
  oldCharacterDataHandler = parser->m_characterDataHandler;
1405
42.2k
  oldProcessingInstructionHandler = parser->m_processingInstructionHandler;
1406
42.2k
  oldCommentHandler = parser->m_commentHandler;
1407
42.2k
  oldStartCdataSectionHandler = parser->m_startCdataSectionHandler;
1408
42.2k
  oldEndCdataSectionHandler = parser->m_endCdataSectionHandler;
1409
42.2k
  oldDefaultHandler = parser->m_defaultHandler;
1410
42.2k
  oldUnparsedEntityDeclHandler = parser->m_unparsedEntityDeclHandler;
1411
42.2k
  oldNotationDeclHandler = parser->m_notationDeclHandler;
1412
42.2k
  oldStartNamespaceDeclHandler = parser->m_startNamespaceDeclHandler;
1413
42.2k
  oldEndNamespaceDeclHandler = parser->m_endNamespaceDeclHandler;
1414
42.2k
  oldNotStandaloneHandler = parser->m_notStandaloneHandler;
1415
42.2k
  oldExternalEntityRefHandler = parser->m_externalEntityRefHandler;
1416
42.2k
  oldSkippedEntityHandler = parser->m_skippedEntityHandler;
1417
42.2k
  oldUnknownEncodingHandler = parser->m_unknownEncodingHandler;
1418
42.2k
  oldElementDeclHandler = parser->m_elementDeclHandler;
1419
42.2k
  oldAttlistDeclHandler = parser->m_attlistDeclHandler;
1420
42.2k
  oldEntityDeclHandler = parser->m_entityDeclHandler;
1421
42.2k
  oldXmlDeclHandler = parser->m_xmlDeclHandler;
1422
42.2k
  oldDeclElementType = parser->m_declElementType;
1423
1424
42.2k
  oldUserData = parser->m_userData;
1425
42.2k
  oldHandlerArg = parser->m_handlerArg;
1426
42.2k
  oldDefaultExpandInternalEntities = parser->m_defaultExpandInternalEntities;
1427
42.2k
  oldExternalEntityRefHandlerArg = parser->m_externalEntityRefHandlerArg;
1428
42.2k
#ifdef XML_DTD
1429
42.2k
  oldParamEntityParsing = parser->m_paramEntityParsing;
1430
42.2k
  oldInEntityValue = parser->m_prologState.inEntityValue;
1431
42.2k
#endif
1432
42.2k
  oldns_triplets = parser->m_ns_triplets;
1433
  /* Note that the new parser shares the same hash secret as the old
1434
     parser, so that dtdCopy and copyEntityTable can lookup values
1435
     from hash tables associated with either parser without us having
1436
     to worry which hash secrets each table has.
1437
  */
1438
42.2k
  oldhash_secret_salt = parser->m_hash_secret_salt;
1439
42.2k
  oldReparseDeferralEnabled = parser->m_reparseDeferralEnabled;
1440
1441
42.2k
#ifdef XML_DTD
1442
42.2k
  if (! context)
1443
21.1k
    newDtd = oldDtd;
1444
42.2k
#endif /* XML_DTD */
1445
1446
  /* Note that the magical uses of the pre-processor to make field
1447
     access look more like C++ require that `parser' be overwritten
1448
     here.  This makes this function more painful to follow than it
1449
     would be otherwise.
1450
  */
1451
42.2k
  if (parser->m_ns) {
1452
0
    XML_Char tmp[2] = {parser->m_namespaceSeparator, 0};
1453
0
    parser = parserCreate(encodingName, &parser->m_mem, tmp, newDtd);
1454
42.2k
  } else {
1455
42.2k
    parser = parserCreate(encodingName, &parser->m_mem, NULL, newDtd);
1456
42.2k
  }
1457
1458
42.2k
  if (! parser)
1459
0
    return NULL;
1460
1461
42.2k
  parser->m_startElementHandler = oldStartElementHandler;
1462
42.2k
  parser->m_endElementHandler = oldEndElementHandler;
1463
42.2k
  parser->m_characterDataHandler = oldCharacterDataHandler;
1464
42.2k
  parser->m_processingInstructionHandler = oldProcessingInstructionHandler;
1465
42.2k
  parser->m_commentHandler = oldCommentHandler;
1466
42.2k
  parser->m_startCdataSectionHandler = oldStartCdataSectionHandler;
1467
42.2k
  parser->m_endCdataSectionHandler = oldEndCdataSectionHandler;
1468
42.2k
  parser->m_defaultHandler = oldDefaultHandler;
1469
42.2k
  parser->m_unparsedEntityDeclHandler = oldUnparsedEntityDeclHandler;
1470
42.2k
  parser->m_notationDeclHandler = oldNotationDeclHandler;
1471
42.2k
  parser->m_startNamespaceDeclHandler = oldStartNamespaceDeclHandler;
1472
42.2k
  parser->m_endNamespaceDeclHandler = oldEndNamespaceDeclHandler;
1473
42.2k
  parser->m_notStandaloneHandler = oldNotStandaloneHandler;
1474
42.2k
  parser->m_externalEntityRefHandler = oldExternalEntityRefHandler;
1475
42.2k
  parser->m_skippedEntityHandler = oldSkippedEntityHandler;
1476
42.2k
  parser->m_unknownEncodingHandler = oldUnknownEncodingHandler;
1477
42.2k
  parser->m_elementDeclHandler = oldElementDeclHandler;
1478
42.2k
  parser->m_attlistDeclHandler = oldAttlistDeclHandler;
1479
42.2k
  parser->m_entityDeclHandler = oldEntityDeclHandler;
1480
42.2k
  parser->m_xmlDeclHandler = oldXmlDeclHandler;
1481
42.2k
  parser->m_declElementType = oldDeclElementType;
1482
42.2k
  parser->m_userData = oldUserData;
1483
42.2k
  if (oldUserData == oldHandlerArg)
1484
42.2k
    parser->m_handlerArg = parser->m_userData;
1485
0
  else
1486
0
    parser->m_handlerArg = parser;
1487
42.2k
  if (oldExternalEntityRefHandlerArg != oldParser)
1488
0
    parser->m_externalEntityRefHandlerArg = oldExternalEntityRefHandlerArg;
1489
42.2k
  parser->m_defaultExpandInternalEntities = oldDefaultExpandInternalEntities;
1490
42.2k
  parser->m_ns_triplets = oldns_triplets;
1491
42.2k
  parser->m_hash_secret_salt = oldhash_secret_salt;
1492
42.2k
  parser->m_reparseDeferralEnabled = oldReparseDeferralEnabled;
1493
42.2k
  parser->m_parentParser = oldParser;
1494
42.2k
#ifdef XML_DTD
1495
42.2k
  parser->m_paramEntityParsing = oldParamEntityParsing;
1496
42.2k
  parser->m_prologState.inEntityValue = oldInEntityValue;
1497
42.2k
  if (context) {
1498
21.1k
#endif /* XML_DTD */
1499
21.1k
    if (! dtdCopy(oldParser, parser->m_dtd, oldDtd, &parser->m_mem)
1500
21.1k
        || ! setContext(parser, context)) {
1501
0
      XML_ParserFree(parser);
1502
0
      return NULL;
1503
0
    }
1504
21.1k
    parser->m_processor = externalEntityInitProcessor;
1505
21.1k
#ifdef XML_DTD
1506
21.1k
  } else {
1507
    /* The DTD instance referenced by parser->m_dtd is shared between the
1508
       document's root parser and external PE parsers, therefore one does not
1509
       need to call setContext. In addition, one also *must* not call
1510
       setContext, because this would overwrite existing prefix->binding
1511
       pointers in parser->m_dtd with ones that get destroyed with the external
1512
       PE parser. This would leave those prefixes with dangling pointers.
1513
    */
1514
21.1k
    parser->m_isParamEntity = XML_TRUE;
1515
21.1k
    XmlPrologStateInitExternalEntity(&parser->m_prologState);
1516
21.1k
    parser->m_processor = externalParEntInitProcessor;
1517
21.1k
  }
1518
42.2k
#endif /* XML_DTD */
1519
42.2k
  return parser;
1520
42.2k
}
1521
1522
static void FASTCALL
1523
2.09M
destroyBindings(BINDING *bindings, XML_Parser parser) {
1524
2.11M
  for (;;) {
1525
2.11M
    BINDING *b = bindings;
1526
2.11M
    if (! b)
1527
2.09M
      break;
1528
23.9k
    bindings = b->nextTagBinding;
1529
23.9k
    FREE(parser, b->uri);
1530
23.9k
    FREE(parser, b);
1531
23.9k
  }
1532
2.09M
}
1533
1534
void XMLCALL
1535
84.4k
XML_ParserFree(XML_Parser parser) {
1536
84.4k
  TAG *tagList;
1537
84.4k
  OPEN_INTERNAL_ENTITY *entityList;
1538
84.4k
  if (parser == NULL)
1539
0
    return;
1540
  /* free m_tagStack and m_freeTagList */
1541
84.4k
  tagList = parser->m_tagStack;
1542
2.01M
  for (;;) {
1543
2.01M
    TAG *p;
1544
2.01M
    if (tagList == NULL) {
1545
90.0k
      if (parser->m_freeTagList == NULL)
1546
84.4k
        break;
1547
5.63k
      tagList = parser->m_freeTagList;
1548
5.63k
      parser->m_freeTagList = NULL;
1549
5.63k
    }
1550
1.92M
    p = tagList;
1551
1.92M
    tagList = tagList->parent;
1552
1.92M
    FREE(parser, p->buf);
1553
1.92M
    destroyBindings(p->bindings, parser);
1554
1.92M
    FREE(parser, p);
1555
1.92M
  }
1556
  /* free m_openInternalEntities and m_freeInternalEntities */
1557
84.4k
  entityList = parser->m_openInternalEntities;
1558
87.3k
  for (;;) {
1559
87.3k
    OPEN_INTERNAL_ENTITY *openEntity;
1560
87.3k
    if (entityList == NULL) {
1561
86.4k
      if (parser->m_freeInternalEntities == NULL)
1562
84.4k
        break;
1563
1.97k
      entityList = parser->m_freeInternalEntities;
1564
1.97k
      parser->m_freeInternalEntities = NULL;
1565
1.97k
    }
1566
2.86k
    openEntity = entityList;
1567
2.86k
    entityList = entityList->next;
1568
2.86k
    FREE(parser, openEntity);
1569
2.86k
  }
1570
1571
84.4k
  destroyBindings(parser->m_freeBindingList, parser);
1572
84.4k
  destroyBindings(parser->m_inheritedBindings, parser);
1573
84.4k
  poolDestroy(&parser->m_tempPool);
1574
84.4k
  poolDestroy(&parser->m_temp2Pool);
1575
84.4k
  FREE(parser, (void *)parser->m_protocolEncodingName);
1576
84.4k
#ifdef XML_DTD
1577
  /* external parameter entity parsers share the DTD structure
1578
     parser->m_dtd with the root parser, so we must not destroy it
1579
  */
1580
84.4k
  if (! parser->m_isParamEntity && parser->m_dtd)
1581
#else
1582
  if (parser->m_dtd)
1583
#endif /* XML_DTD */
1584
63.3k
    dtdDestroy(parser->m_dtd, (XML_Bool)! parser->m_parentParser,
1585
63.3k
               &parser->m_mem);
1586
84.4k
  FREE(parser, (void *)parser->m_atts);
1587
#ifdef XML_ATTR_INFO
1588
  FREE(parser, (void *)parser->m_attInfo);
1589
#endif
1590
84.4k
  FREE(parser, parser->m_groupConnector);
1591
84.4k
  FREE(parser, parser->m_buffer);
1592
84.4k
  FREE(parser, parser->m_dataBuf);
1593
84.4k
  FREE(parser, parser->m_nsAtts);
1594
84.4k
  FREE(parser, parser->m_unknownEncodingMem);
1595
84.4k
  if (parser->m_unknownEncodingRelease)
1596
0
    parser->m_unknownEncodingRelease(parser->m_unknownEncodingData);
1597
84.4k
  FREE(parser, parser);
1598
84.4k
}
1599
1600
void XMLCALL
1601
0
XML_UseParserAsHandlerArg(XML_Parser parser) {
1602
0
  if (parser != NULL)
1603
0
    parser->m_handlerArg = parser;
1604
0
}
1605
1606
enum XML_Error XMLCALL
1607
0
XML_UseForeignDTD(XML_Parser parser, XML_Bool useDTD) {
1608
0
  if (parser == NULL)
1609
0
    return XML_ERROR_INVALID_ARGUMENT;
1610
0
#ifdef XML_DTD
1611
  /* block after XML_Parse()/XML_ParseBuffer() has been called */
1612
0
  if (parser->m_parsingStatus.parsing == XML_PARSING
1613
0
      || parser->m_parsingStatus.parsing == XML_SUSPENDED)
1614
0
    return XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING;
1615
0
  parser->m_useForeignDTD = useDTD;
1616
0
  return XML_ERROR_NONE;
1617
#else
1618
  UNUSED_P(useDTD);
1619
  return XML_ERROR_FEATURE_REQUIRES_XML_DTD;
1620
#endif
1621
0
}
1622
1623
void XMLCALL
1624
0
XML_SetReturnNSTriplet(XML_Parser parser, int do_nst) {
1625
0
  if (parser == NULL)
1626
0
    return;
1627
  /* block after XML_Parse()/XML_ParseBuffer() has been called */
1628
0
  if (parser->m_parsingStatus.parsing == XML_PARSING
1629
0
      || parser->m_parsingStatus.parsing == XML_SUSPENDED)
1630
0
    return;
1631
0
  parser->m_ns_triplets = do_nst ? XML_TRUE : XML_FALSE;
1632
0
}
1633
1634
void XMLCALL
1635
84.4k
XML_SetUserData(XML_Parser parser, void *p) {
1636
84.4k
  if (parser == NULL)
1637
0
    return;
1638
84.4k
  if (parser->m_handlerArg == parser->m_userData)
1639
84.4k
    parser->m_handlerArg = parser->m_userData = p;
1640
0
  else
1641
0
    parser->m_userData = p;
1642
84.4k
}
1643
1644
enum XML_Status XMLCALL
1645
0
XML_SetBase(XML_Parser parser, const XML_Char *p) {
1646
0
  if (parser == NULL)
1647
0
    return XML_STATUS_ERROR;
1648
0
  if (p) {
1649
0
    p = poolCopyString(&parser->m_dtd->pool, p);
1650
0
    if (! p)
1651
0
      return XML_STATUS_ERROR;
1652
0
    parser->m_curBase = p;
1653
0
  } else
1654
0
    parser->m_curBase = NULL;
1655
0
  return XML_STATUS_OK;
1656
0
}
1657
1658
const XML_Char *XMLCALL
1659
0
XML_GetBase(XML_Parser parser) {
1660
0
  if (parser == NULL)
1661
0
    return NULL;
1662
0
  return parser->m_curBase;
1663
0
}
1664
1665
int XMLCALL
1666
0
XML_GetSpecifiedAttributeCount(XML_Parser parser) {
1667
0
  if (parser == NULL)
1668
0
    return -1;
1669
0
  return parser->m_nSpecifiedAtts;
1670
0
}
1671
1672
int XMLCALL
1673
0
XML_GetIdAttributeIndex(XML_Parser parser) {
1674
0
  if (parser == NULL)
1675
0
    return -1;
1676
0
  return parser->m_idAttIndex;
1677
0
}
1678
1679
#ifdef XML_ATTR_INFO
1680
const XML_AttrInfo *XMLCALL
1681
XML_GetAttributeInfo(XML_Parser parser) {
1682
  if (parser == NULL)
1683
    return NULL;
1684
  return parser->m_attInfo;
1685
}
1686
#endif
1687
1688
void XMLCALL
1689
XML_SetElementHandler(XML_Parser parser, XML_StartElementHandler start,
1690
84.4k
                      XML_EndElementHandler end) {
1691
84.4k
  if (parser == NULL)
1692
0
    return;
1693
84.4k
  parser->m_startElementHandler = start;
1694
84.4k
  parser->m_endElementHandler = end;
1695
84.4k
}
1696
1697
void XMLCALL
1698
0
XML_SetStartElementHandler(XML_Parser parser, XML_StartElementHandler start) {
1699
0
  if (parser != NULL)
1700
0
    parser->m_startElementHandler = start;
1701
0
}
1702
1703
void XMLCALL
1704
0
XML_SetEndElementHandler(XML_Parser parser, XML_EndElementHandler end) {
1705
0
  if (parser != NULL)
1706
0
    parser->m_endElementHandler = end;
1707
0
}
1708
1709
void XMLCALL
1710
XML_SetCharacterDataHandler(XML_Parser parser,
1711
84.4k
                            XML_CharacterDataHandler handler) {
1712
84.4k
  if (parser != NULL)
1713
84.4k
    parser->m_characterDataHandler = handler;
1714
84.4k
}
1715
1716
void XMLCALL
1717
XML_SetProcessingInstructionHandler(XML_Parser parser,
1718
0
                                    XML_ProcessingInstructionHandler handler) {
1719
0
  if (parser != NULL)
1720
0
    parser->m_processingInstructionHandler = handler;
1721
0
}
1722
1723
void XMLCALL
1724
0
XML_SetCommentHandler(XML_Parser parser, XML_CommentHandler handler) {
1725
0
  if (parser != NULL)
1726
0
    parser->m_commentHandler = handler;
1727
0
}
1728
1729
void XMLCALL
1730
XML_SetCdataSectionHandler(XML_Parser parser,
1731
                           XML_StartCdataSectionHandler start,
1732
0
                           XML_EndCdataSectionHandler end) {
1733
0
  if (parser == NULL)
1734
0
    return;
1735
0
  parser->m_startCdataSectionHandler = start;
1736
0
  parser->m_endCdataSectionHandler = end;
1737
0
}
1738
1739
void XMLCALL
1740
XML_SetStartCdataSectionHandler(XML_Parser parser,
1741
0
                                XML_StartCdataSectionHandler start) {
1742
0
  if (parser != NULL)
1743
0
    parser->m_startCdataSectionHandler = start;
1744
0
}
1745
1746
void XMLCALL
1747
XML_SetEndCdataSectionHandler(XML_Parser parser,
1748
0
                              XML_EndCdataSectionHandler end) {
1749
0
  if (parser != NULL)
1750
0
    parser->m_endCdataSectionHandler = end;
1751
0
}
1752
1753
void XMLCALL
1754
0
XML_SetDefaultHandler(XML_Parser parser, XML_DefaultHandler handler) {
1755
0
  if (parser == NULL)
1756
0
    return;
1757
0
  parser->m_defaultHandler = handler;
1758
0
  parser->m_defaultExpandInternalEntities = XML_FALSE;
1759
0
}
1760
1761
void XMLCALL
1762
0
XML_SetDefaultHandlerExpand(XML_Parser parser, XML_DefaultHandler handler) {
1763
0
  if (parser == NULL)
1764
0
    return;
1765
0
  parser->m_defaultHandler = handler;
1766
0
  parser->m_defaultExpandInternalEntities = XML_TRUE;
1767
0
}
1768
1769
void XMLCALL
1770
XML_SetDoctypeDeclHandler(XML_Parser parser, XML_StartDoctypeDeclHandler start,
1771
0
                          XML_EndDoctypeDeclHandler end) {
1772
0
  if (parser == NULL)
1773
0
    return;
1774
0
  parser->m_startDoctypeDeclHandler = start;
1775
0
  parser->m_endDoctypeDeclHandler = end;
1776
0
}
1777
1778
void XMLCALL
1779
XML_SetStartDoctypeDeclHandler(XML_Parser parser,
1780
0
                               XML_StartDoctypeDeclHandler start) {
1781
0
  if (parser != NULL)
1782
0
    parser->m_startDoctypeDeclHandler = start;
1783
0
}
1784
1785
void XMLCALL
1786
0
XML_SetEndDoctypeDeclHandler(XML_Parser parser, XML_EndDoctypeDeclHandler end) {
1787
0
  if (parser != NULL)
1788
0
    parser->m_endDoctypeDeclHandler = end;
1789
0
}
1790
1791
void XMLCALL
1792
XML_SetUnparsedEntityDeclHandler(XML_Parser parser,
1793
0
                                 XML_UnparsedEntityDeclHandler handler) {
1794
0
  if (parser != NULL)
1795
0
    parser->m_unparsedEntityDeclHandler = handler;
1796
0
}
1797
1798
void XMLCALL
1799
0
XML_SetNotationDeclHandler(XML_Parser parser, XML_NotationDeclHandler handler) {
1800
0
  if (parser != NULL)
1801
0
    parser->m_notationDeclHandler = handler;
1802
0
}
1803
1804
void XMLCALL
1805
XML_SetNamespaceDeclHandler(XML_Parser parser,
1806
                            XML_StartNamespaceDeclHandler start,
1807
0
                            XML_EndNamespaceDeclHandler end) {
1808
0
  if (parser == NULL)
1809
0
    return;
1810
0
  parser->m_startNamespaceDeclHandler = start;
1811
0
  parser->m_endNamespaceDeclHandler = end;
1812
0
}
1813
1814
void XMLCALL
1815
XML_SetStartNamespaceDeclHandler(XML_Parser parser,
1816
0
                                 XML_StartNamespaceDeclHandler start) {
1817
0
  if (parser != NULL)
1818
0
    parser->m_startNamespaceDeclHandler = start;
1819
0
}
1820
1821
void XMLCALL
1822
XML_SetEndNamespaceDeclHandler(XML_Parser parser,
1823
0
                               XML_EndNamespaceDeclHandler end) {
1824
0
  if (parser != NULL)
1825
0
    parser->m_endNamespaceDeclHandler = end;
1826
0
}
1827
1828
void XMLCALL
1829
XML_SetNotStandaloneHandler(XML_Parser parser,
1830
0
                            XML_NotStandaloneHandler handler) {
1831
0
  if (parser != NULL)
1832
0
    parser->m_notStandaloneHandler = handler;
1833
0
}
1834
1835
void XMLCALL
1836
XML_SetExternalEntityRefHandler(XML_Parser parser,
1837
0
                                XML_ExternalEntityRefHandler handler) {
1838
0
  if (parser != NULL)
1839
0
    parser->m_externalEntityRefHandler = handler;
1840
0
}
1841
1842
void XMLCALL
1843
0
XML_SetExternalEntityRefHandlerArg(XML_Parser parser, void *arg) {
1844
0
  if (parser == NULL)
1845
0
    return;
1846
0
  if (arg)
1847
0
    parser->m_externalEntityRefHandlerArg = (XML_Parser)arg;
1848
0
  else
1849
0
    parser->m_externalEntityRefHandlerArg = parser;
1850
0
}
1851
1852
void XMLCALL
1853
XML_SetSkippedEntityHandler(XML_Parser parser,
1854
0
                            XML_SkippedEntityHandler handler) {
1855
0
  if (parser != NULL)
1856
0
    parser->m_skippedEntityHandler = handler;
1857
0
}
1858
1859
void XMLCALL
1860
XML_SetUnknownEncodingHandler(XML_Parser parser,
1861
0
                              XML_UnknownEncodingHandler handler, void *data) {
1862
0
  if (parser == NULL)
1863
0
    return;
1864
0
  parser->m_unknownEncodingHandler = handler;
1865
0
  parser->m_unknownEncodingHandlerData = data;
1866
0
}
1867
1868
void XMLCALL
1869
0
XML_SetElementDeclHandler(XML_Parser parser, XML_ElementDeclHandler eldecl) {
1870
0
  if (parser != NULL)
1871
0
    parser->m_elementDeclHandler = eldecl;
1872
0
}
1873
1874
void XMLCALL
1875
0
XML_SetAttlistDeclHandler(XML_Parser parser, XML_AttlistDeclHandler attdecl) {
1876
0
  if (parser != NULL)
1877
0
    parser->m_attlistDeclHandler = attdecl;
1878
0
}
1879
1880
void XMLCALL
1881
0
XML_SetEntityDeclHandler(XML_Parser parser, XML_EntityDeclHandler handler) {
1882
0
  if (parser != NULL)
1883
0
    parser->m_entityDeclHandler = handler;
1884
0
}
1885
1886
void XMLCALL
1887
0
XML_SetXmlDeclHandler(XML_Parser parser, XML_XmlDeclHandler handler) {
1888
0
  if (parser != NULL)
1889
0
    parser->m_xmlDeclHandler = handler;
1890
0
}
1891
1892
int XMLCALL
1893
XML_SetParamEntityParsing(XML_Parser parser,
1894
0
                          enum XML_ParamEntityParsing peParsing) {
1895
0
  if (parser == NULL)
1896
0
    return 0;
1897
  /* block after XML_Parse()/XML_ParseBuffer() has been called */
1898
0
  if (parser->m_parsingStatus.parsing == XML_PARSING
1899
0
      || parser->m_parsingStatus.parsing == XML_SUSPENDED)
1900
0
    return 0;
1901
0
#ifdef XML_DTD
1902
0
  parser->m_paramEntityParsing = peParsing;
1903
0
  return 1;
1904
#else
1905
  return peParsing == XML_PARAM_ENTITY_PARSING_NEVER;
1906
#endif
1907
0
}
1908
1909
int XMLCALL
1910
126k
XML_SetHashSalt(XML_Parser parser, unsigned long hash_salt) {
1911
126k
  if (parser == NULL)
1912
0
    return 0;
1913
126k
  if (parser->m_parentParser)
1914
42.2k
    return XML_SetHashSalt(parser->m_parentParser, hash_salt);
1915
  /* block after XML_Parse()/XML_ParseBuffer() has been called */
1916
84.4k
  if (parser->m_parsingStatus.parsing == XML_PARSING
1917
84.4k
      || parser->m_parsingStatus.parsing == XML_SUSPENDED)
1918
24.2k
    return 0;
1919
60.1k
  parser->m_hash_secret_salt = hash_salt;
1920
60.1k
  return 1;
1921
84.4k
}
1922
1923
enum XML_Status XMLCALL
1924
168k
XML_Parse(XML_Parser parser, const char *s, int len, int isFinal) {
1925
168k
  if ((parser == NULL) || (len < 0) || ((s == NULL) && (len != 0))) {
1926
0
    if (parser != NULL)
1927
0
      parser->m_errorCode = XML_ERROR_INVALID_ARGUMENT;
1928
0
    return XML_STATUS_ERROR;
1929
0
  }
1930
168k
  switch (parser->m_parsingStatus.parsing) {
1931
77
  case XML_SUSPENDED:
1932
77
    parser->m_errorCode = XML_ERROR_SUSPENDED;
1933
77
    return XML_STATUS_ERROR;
1934
48
  case XML_FINISHED:
1935
48
    parser->m_errorCode = XML_ERROR_FINISHED;
1936
48
    return XML_STATUS_ERROR;
1937
84.4k
  case XML_INITIALIZED:
1938
84.4k
    if (parser->m_parentParser == NULL && ! startParsing(parser)) {
1939
0
      parser->m_errorCode = XML_ERROR_NO_MEMORY;
1940
0
      return XML_STATUS_ERROR;
1941
0
    }
1942
    /* fall through */
1943
168k
  default:
1944
168k
    parser->m_parsingStatus.parsing = XML_PARSING;
1945
168k
  }
1946
1947
#if XML_CONTEXT_BYTES == 0
1948
  if (parser->m_bufferPtr == parser->m_bufferEnd) {
1949
    const char *end;
1950
    int nLeftOver;
1951
    enum XML_Status result;
1952
    /* Detect overflow (a+b > MAX <==> b > MAX-a) */
1953
    if ((XML_Size)len > ((XML_Size)-1) / 2 - parser->m_parseEndByteIndex) {
1954
      parser->m_errorCode = XML_ERROR_NO_MEMORY;
1955
      parser->m_eventPtr = parser->m_eventEndPtr = NULL;
1956
      parser->m_processor = errorProcessor;
1957
      return XML_STATUS_ERROR;
1958
    }
1959
    // though this isn't a buffer request, we assume that `len` is the app's
1960
    // preferred buffer fill size, and therefore save it here.
1961
    parser->m_lastBufferRequestSize = len;
1962
    parser->m_parseEndByteIndex += len;
1963
    parser->m_positionPtr = s;
1964
    parser->m_parsingStatus.finalBuffer = (XML_Bool)isFinal;
1965
1966
    parser->m_errorCode
1967
        = callProcessor(parser, s, parser->m_parseEndPtr = s + len, &end);
1968
1969
    if (parser->m_errorCode != XML_ERROR_NONE) {
1970
      parser->m_eventEndPtr = parser->m_eventPtr;
1971
      parser->m_processor = errorProcessor;
1972
      return XML_STATUS_ERROR;
1973
    } else {
1974
      switch (parser->m_parsingStatus.parsing) {
1975
      case XML_SUSPENDED:
1976
        result = XML_STATUS_SUSPENDED;
1977
        break;
1978
      case XML_INITIALIZED:
1979
      case XML_PARSING:
1980
        if (isFinal) {
1981
          parser->m_parsingStatus.parsing = XML_FINISHED;
1982
          return XML_STATUS_OK;
1983
        }
1984
      /* fall through */
1985
      default:
1986
        result = XML_STATUS_OK;
1987
      }
1988
    }
1989
1990
    XmlUpdatePosition(parser->m_encoding, parser->m_positionPtr, end,
1991
                      &parser->m_position);
1992
    nLeftOver = s + len - end;
1993
    if (nLeftOver) {
1994
      // Back up and restore the parsing status to avoid XML_ERROR_SUSPENDED
1995
      // (and XML_ERROR_FINISHED) from XML_GetBuffer.
1996
      const enum XML_Parsing originalStatus = parser->m_parsingStatus.parsing;
1997
      parser->m_parsingStatus.parsing = XML_PARSING;
1998
      void *const temp = XML_GetBuffer(parser, nLeftOver);
1999
      parser->m_parsingStatus.parsing = originalStatus;
2000
      // GetBuffer may have overwritten this, but we want to remember what the
2001
      // app requested, not how many bytes were left over after parsing.
2002
      parser->m_lastBufferRequestSize = len;
2003
      if (temp == NULL) {
2004
        // NOTE: parser->m_errorCode has already been set by XML_GetBuffer().
2005
        parser->m_eventPtr = parser->m_eventEndPtr = NULL;
2006
        parser->m_processor = errorProcessor;
2007
        return XML_STATUS_ERROR;
2008
      }
2009
      // Since we know that the buffer was empty and XML_CONTEXT_BYTES is 0, we
2010
      // don't have any data to preserve, and can copy straight into the start
2011
      // of the buffer rather than the GetBuffer return pointer (which may be
2012
      // pointing further into the allocated buffer).
2013
      memcpy(parser->m_buffer, end, nLeftOver);
2014
    }
2015
    parser->m_bufferPtr = parser->m_buffer;
2016
    parser->m_bufferEnd = parser->m_buffer + nLeftOver;
2017
    parser->m_positionPtr = parser->m_bufferPtr;
2018
    parser->m_parseEndPtr = parser->m_bufferEnd;
2019
    parser->m_eventPtr = parser->m_bufferPtr;
2020
    parser->m_eventEndPtr = parser->m_bufferPtr;
2021
    return result;
2022
  }
2023
#endif /* XML_CONTEXT_BYTES == 0 */
2024
168k
  void *buff = XML_GetBuffer(parser, len);
2025
168k
  if (buff == NULL)
2026
0
    return XML_STATUS_ERROR;
2027
168k
  if (len > 0) {
2028
168k
    assert(s != NULL); // make sure s==NULL && len!=0 was rejected above
2029
168k
    memcpy(buff, s, len);
2030
168k
  }
2031
168k
  return XML_ParseBuffer(parser, len, isFinal);
2032
168k
}
2033
2034
enum XML_Status XMLCALL
2035
168k
XML_ParseBuffer(XML_Parser parser, int len, int isFinal) {
2036
168k
  const char *start;
2037
168k
  enum XML_Status result = XML_STATUS_OK;
2038
2039
168k
  if (parser == NULL)
2040
0
    return XML_STATUS_ERROR;
2041
168k
  switch (parser->m_parsingStatus.parsing) {
2042
0
  case XML_SUSPENDED:
2043
0
    parser->m_errorCode = XML_ERROR_SUSPENDED;
2044
0
    return XML_STATUS_ERROR;
2045
0
  case XML_FINISHED:
2046
0
    parser->m_errorCode = XML_ERROR_FINISHED;
2047
0
    return XML_STATUS_ERROR;
2048
0
  case XML_INITIALIZED:
2049
    /* Has someone called XML_GetBuffer successfully before? */
2050
0
    if (! parser->m_bufferPtr) {
2051
0
      parser->m_errorCode = XML_ERROR_NO_BUFFER;
2052
0
      return XML_STATUS_ERROR;
2053
0
    }
2054
2055
0
    if (parser->m_parentParser == NULL && ! startParsing(parser)) {
2056
0
      parser->m_errorCode = XML_ERROR_NO_MEMORY;
2057
0
      return XML_STATUS_ERROR;
2058
0
    }
2059
    /* fall through */
2060
168k
  default:
2061
168k
    parser->m_parsingStatus.parsing = XML_PARSING;
2062
168k
  }
2063
2064
168k
  start = parser->m_bufferPtr;
2065
168k
  parser->m_positionPtr = start;
2066
168k
  parser->m_bufferEnd += len;
2067
168k
  parser->m_parseEndPtr = parser->m_bufferEnd;
2068
168k
  parser->m_parseEndByteIndex += len;
2069
168k
  parser->m_parsingStatus.finalBuffer = (XML_Bool)isFinal;
2070
2071
168k
  parser->m_errorCode = callProcessor(parser, start, parser->m_parseEndPtr,
2072
168k
                                      &parser->m_bufferPtr);
2073
2074
168k
  if (parser->m_errorCode != XML_ERROR_NONE) {
2075
132k
    parser->m_eventEndPtr = parser->m_eventPtr;
2076
132k
    parser->m_processor = errorProcessor;
2077
132k
    return XML_STATUS_ERROR;
2078
132k
  } else {
2079
36.1k
    switch (parser->m_parsingStatus.parsing) {
2080
190
    case XML_SUSPENDED:
2081
190
      result = XML_STATUS_SUSPENDED;
2082
190
      break;
2083
0
    case XML_INITIALIZED:
2084
35.9k
    case XML_PARSING:
2085
35.9k
      if (isFinal) {
2086
2.14k
        parser->m_parsingStatus.parsing = XML_FINISHED;
2087
2.14k
        return result;
2088
2.14k
      }
2089
33.8k
    default:; /* should not happen */
2090
36.1k
    }
2091
36.1k
  }
2092
2093
34.0k
  XmlUpdatePosition(parser->m_encoding, parser->m_positionPtr,
2094
34.0k
                    parser->m_bufferPtr, &parser->m_position);
2095
34.0k
  parser->m_positionPtr = parser->m_bufferPtr;
2096
34.0k
  return result;
2097
168k
}
2098
2099
void *XMLCALL
2100
168k
XML_GetBuffer(XML_Parser parser, int len) {
2101
168k
  if (parser == NULL)
2102
0
    return NULL;
2103
168k
  if (len < 0) {
2104
0
    parser->m_errorCode = XML_ERROR_NO_MEMORY;
2105
0
    return NULL;
2106
0
  }
2107
168k
  switch (parser->m_parsingStatus.parsing) {
2108
0
  case XML_SUSPENDED:
2109
0
    parser->m_errorCode = XML_ERROR_SUSPENDED;
2110
0
    return NULL;
2111
0
  case XML_FINISHED:
2112
0
    parser->m_errorCode = XML_ERROR_FINISHED;
2113
0
    return NULL;
2114
168k
  default:;
2115
168k
  }
2116
2117
  // whether or not the request succeeds, `len` seems to be the app's preferred
2118
  // buffer fill size; remember it.
2119
168k
  parser->m_lastBufferRequestSize = len;
2120
168k
  if (len > EXPAT_SAFE_PTR_DIFF(parser->m_bufferLim, parser->m_bufferEnd)
2121
168k
      || parser->m_buffer == NULL) {
2122
94.9k
#if XML_CONTEXT_BYTES > 0
2123
94.9k
    int keep;
2124
94.9k
#endif /* XML_CONTEXT_BYTES > 0 */
2125
    /* Do not invoke signed arithmetic overflow: */
2126
94.9k
    int neededSize = (int)((unsigned)len
2127
94.9k
                           + (unsigned)EXPAT_SAFE_PTR_DIFF(
2128
94.9k
                               parser->m_bufferEnd, parser->m_bufferPtr));
2129
94.9k
    if (neededSize < 0) {
2130
0
      parser->m_errorCode = XML_ERROR_NO_MEMORY;
2131
0
      return NULL;
2132
0
    }
2133
94.9k
#if XML_CONTEXT_BYTES > 0
2134
94.9k
    keep = (int)EXPAT_SAFE_PTR_DIFF(parser->m_bufferPtr, parser->m_buffer);
2135
94.9k
    if (keep > XML_CONTEXT_BYTES)
2136
1.04k
      keep = XML_CONTEXT_BYTES;
2137
    /* Detect and prevent integer overflow */
2138
94.9k
    if (keep > INT_MAX - neededSize) {
2139
0
      parser->m_errorCode = XML_ERROR_NO_MEMORY;
2140
0
      return NULL;
2141
0
    }
2142
94.9k
    neededSize += keep;
2143
94.9k
#endif /* XML_CONTEXT_BYTES > 0 */
2144
94.9k
    if (parser->m_buffer && parser->m_bufferPtr
2145
94.9k
        && neededSize
2146
10.5k
               <= EXPAT_SAFE_PTR_DIFF(parser->m_bufferLim, parser->m_buffer)) {
2147
579
#if XML_CONTEXT_BYTES > 0
2148
579
      if (keep < EXPAT_SAFE_PTR_DIFF(parser->m_bufferPtr, parser->m_buffer)) {
2149
579
        int offset
2150
579
            = (int)EXPAT_SAFE_PTR_DIFF(parser->m_bufferPtr, parser->m_buffer)
2151
579
              - keep;
2152
        /* The buffer pointers cannot be NULL here; we have at least some bytes
2153
         * in the buffer */
2154
579
        memmove(parser->m_buffer, &parser->m_buffer[offset],
2155
579
                parser->m_bufferEnd - parser->m_bufferPtr + keep);
2156
579
        parser->m_bufferEnd -= offset;
2157
579
        parser->m_bufferPtr -= offset;
2158
579
      }
2159
#else
2160
      memmove(parser->m_buffer, parser->m_bufferPtr,
2161
              EXPAT_SAFE_PTR_DIFF(parser->m_bufferEnd, parser->m_bufferPtr));
2162
      parser->m_bufferEnd
2163
          = parser->m_buffer
2164
            + EXPAT_SAFE_PTR_DIFF(parser->m_bufferEnd, parser->m_bufferPtr);
2165
      parser->m_bufferPtr = parser->m_buffer;
2166
#endif /* XML_CONTEXT_BYTES > 0 */
2167
94.3k
    } else {
2168
94.3k
      char *newBuf;
2169
94.3k
      int bufferSize
2170
94.3k
          = (int)EXPAT_SAFE_PTR_DIFF(parser->m_bufferLim, parser->m_buffer);
2171
94.3k
      if (bufferSize == 0)
2172
84.4k
        bufferSize = INIT_BUFFER_SIZE;
2173
134k
      do {
2174
        /* Do not invoke signed arithmetic overflow: */
2175
134k
        bufferSize = (int)(2U * (unsigned)bufferSize);
2176
134k
      } while (bufferSize < neededSize && bufferSize > 0);
2177
94.3k
      if (bufferSize <= 0) {
2178
0
        parser->m_errorCode = XML_ERROR_NO_MEMORY;
2179
0
        return NULL;
2180
0
      }
2181
94.3k
      newBuf = (char *)MALLOC(parser, bufferSize);
2182
94.3k
      if (newBuf == 0) {
2183
0
        parser->m_errorCode = XML_ERROR_NO_MEMORY;
2184
0
        return NULL;
2185
0
      }
2186
94.3k
      parser->m_bufferLim = newBuf + bufferSize;
2187
94.3k
#if XML_CONTEXT_BYTES > 0
2188
94.3k
      if (parser->m_bufferPtr) {
2189
9.94k
        memcpy(newBuf, &parser->m_bufferPtr[-keep],
2190
9.94k
               EXPAT_SAFE_PTR_DIFF(parser->m_bufferEnd, parser->m_bufferPtr)
2191
9.94k
                   + keep);
2192
9.94k
        FREE(parser, parser->m_buffer);
2193
9.94k
        parser->m_buffer = newBuf;
2194
9.94k
        parser->m_bufferEnd
2195
9.94k
            = parser->m_buffer
2196
9.94k
              + EXPAT_SAFE_PTR_DIFF(parser->m_bufferEnd, parser->m_bufferPtr)
2197
9.94k
              + keep;
2198
9.94k
        parser->m_bufferPtr = parser->m_buffer + keep;
2199
84.4k
      } else {
2200
        /* This must be a brand new buffer with no data in it yet */
2201
84.4k
        parser->m_bufferEnd = newBuf;
2202
84.4k
        parser->m_bufferPtr = parser->m_buffer = newBuf;
2203
84.4k
      }
2204
#else
2205
      if (parser->m_bufferPtr) {
2206
        memcpy(newBuf, parser->m_bufferPtr,
2207
               EXPAT_SAFE_PTR_DIFF(parser->m_bufferEnd, parser->m_bufferPtr));
2208
        FREE(parser, parser->m_buffer);
2209
        parser->m_bufferEnd
2210
            = newBuf
2211
              + EXPAT_SAFE_PTR_DIFF(parser->m_bufferEnd, parser->m_bufferPtr);
2212
      } else {
2213
        /* This must be a brand new buffer with no data in it yet */
2214
        parser->m_bufferEnd = newBuf;
2215
      }
2216
      parser->m_bufferPtr = parser->m_buffer = newBuf;
2217
#endif /* XML_CONTEXT_BYTES > 0 */
2218
94.3k
    }
2219
94.9k
    parser->m_eventPtr = parser->m_eventEndPtr = NULL;
2220
94.9k
    parser->m_positionPtr = NULL;
2221
94.9k
  }
2222
168k
  return parser->m_bufferEnd;
2223
168k
}
2224
2225
enum XML_Status XMLCALL
2226
755
XML_StopParser(XML_Parser parser, XML_Bool resumable) {
2227
755
  if (parser == NULL)
2228
0
    return XML_STATUS_ERROR;
2229
755
  switch (parser->m_parsingStatus.parsing) {
2230
298
  case XML_SUSPENDED:
2231
298
    if (resumable) {
2232
286
      parser->m_errorCode = XML_ERROR_SUSPENDED;
2233
286
      return XML_STATUS_ERROR;
2234
286
    }
2235
12
    parser->m_parsingStatus.parsing = XML_FINISHED;
2236
12
    break;
2237
219
  case XML_FINISHED:
2238
219
    parser->m_errorCode = XML_ERROR_FINISHED;
2239
219
    return XML_STATUS_ERROR;
2240
238
  default:
2241
238
    if (resumable) {
2242
202
#ifdef XML_DTD
2243
202
      if (parser->m_isParamEntity) {
2244
0
        parser->m_errorCode = XML_ERROR_SUSPEND_PE;
2245
0
        return XML_STATUS_ERROR;
2246
0
      }
2247
202
#endif
2248
202
      parser->m_parsingStatus.parsing = XML_SUSPENDED;
2249
202
    } else
2250
36
      parser->m_parsingStatus.parsing = XML_FINISHED;
2251
755
  }
2252
250
  return XML_STATUS_OK;
2253
755
}
2254
2255
enum XML_Status XMLCALL
2256
0
XML_ResumeParser(XML_Parser parser) {
2257
0
  enum XML_Status result = XML_STATUS_OK;
2258
2259
0
  if (parser == NULL)
2260
0
    return XML_STATUS_ERROR;
2261
0
  if (parser->m_parsingStatus.parsing != XML_SUSPENDED) {
2262
0
    parser->m_errorCode = XML_ERROR_NOT_SUSPENDED;
2263
0
    return XML_STATUS_ERROR;
2264
0
  }
2265
0
  parser->m_parsingStatus.parsing = XML_PARSING;
2266
2267
0
  parser->m_errorCode = callProcessor(
2268
0
      parser, parser->m_bufferPtr, parser->m_parseEndPtr, &parser->m_bufferPtr);
2269
2270
0
  if (parser->m_errorCode != XML_ERROR_NONE) {
2271
0
    parser->m_eventEndPtr = parser->m_eventPtr;
2272
0
    parser->m_processor = errorProcessor;
2273
0
    return XML_STATUS_ERROR;
2274
0
  } else {
2275
0
    switch (parser->m_parsingStatus.parsing) {
2276
0
    case XML_SUSPENDED:
2277
0
      result = XML_STATUS_SUSPENDED;
2278
0
      break;
2279
0
    case XML_INITIALIZED:
2280
0
    case XML_PARSING:
2281
0
      if (parser->m_parsingStatus.finalBuffer) {
2282
0
        parser->m_parsingStatus.parsing = XML_FINISHED;
2283
0
        return result;
2284
0
      }
2285
0
    default:;
2286
0
    }
2287
0
  }
2288
2289
0
  XmlUpdatePosition(parser->m_encoding, parser->m_positionPtr,
2290
0
                    parser->m_bufferPtr, &parser->m_position);
2291
0
  parser->m_positionPtr = parser->m_bufferPtr;
2292
0
  return result;
2293
0
}
2294
2295
void XMLCALL
2296
0
XML_GetParsingStatus(XML_Parser parser, XML_ParsingStatus *status) {
2297
0
  if (parser == NULL)
2298
0
    return;
2299
0
  assert(status != NULL);
2300
0
  *status = parser->m_parsingStatus;
2301
0
}
2302
2303
enum XML_Error XMLCALL
2304
82.1k
XML_GetErrorCode(XML_Parser parser) {
2305
82.1k
  if (parser == NULL)
2306
0
    return XML_ERROR_INVALID_ARGUMENT;
2307
82.1k
  return parser->m_errorCode;
2308
82.1k
}
2309
2310
XML_Index XMLCALL
2311
0
XML_GetCurrentByteIndex(XML_Parser parser) {
2312
0
  if (parser == NULL)
2313
0
    return -1;
2314
0
  if (parser->m_eventPtr)
2315
0
    return (XML_Index)(parser->m_parseEndByteIndex
2316
0
                       - (parser->m_parseEndPtr - parser->m_eventPtr));
2317
0
  return -1;
2318
0
}
2319
2320
int XMLCALL
2321
0
XML_GetCurrentByteCount(XML_Parser parser) {
2322
0
  if (parser == NULL)
2323
0
    return 0;
2324
0
  if (parser->m_eventEndPtr && parser->m_eventPtr)
2325
0
    return (int)(parser->m_eventEndPtr - parser->m_eventPtr);
2326
0
  return 0;
2327
0
}
2328
2329
const char *XMLCALL
2330
0
XML_GetInputContext(XML_Parser parser, int *offset, int *size) {
2331
0
#if XML_CONTEXT_BYTES > 0
2332
0
  if (parser == NULL)
2333
0
    return NULL;
2334
0
  if (parser->m_eventPtr && parser->m_buffer) {
2335
0
    if (offset != NULL)
2336
0
      *offset = (int)(parser->m_eventPtr - parser->m_buffer);
2337
0
    if (size != NULL)
2338
0
      *size = (int)(parser->m_bufferEnd - parser->m_buffer);
2339
0
    return parser->m_buffer;
2340
0
  }
2341
#else
2342
  (void)parser;
2343
  (void)offset;
2344
  (void)size;
2345
#endif /* XML_CONTEXT_BYTES > 0 */
2346
0
  return (const char *)0;
2347
0
}
2348
2349
XML_Size XMLCALL
2350
84.4k
XML_GetCurrentLineNumber(XML_Parser parser) {
2351
84.4k
  if (parser == NULL)
2352
0
    return 0;
2353
84.4k
  if (parser->m_eventPtr && parser->m_eventPtr >= parser->m_positionPtr) {
2354
73.3k
    XmlUpdatePosition(parser->m_encoding, parser->m_positionPtr,
2355
73.3k
                      parser->m_eventPtr, &parser->m_position);
2356
73.3k
    parser->m_positionPtr = parser->m_eventPtr;
2357
73.3k
  }
2358
84.4k
  return parser->m_position.lineNumber + 1;
2359
84.4k
}
2360
2361
XML_Size XMLCALL
2362
0
XML_GetCurrentColumnNumber(XML_Parser parser) {
2363
0
  if (parser == NULL)
2364
0
    return 0;
2365
0
  if (parser->m_eventPtr && parser->m_eventPtr >= parser->m_positionPtr) {
2366
0
    XmlUpdatePosition(parser->m_encoding, parser->m_positionPtr,
2367
0
                      parser->m_eventPtr, &parser->m_position);
2368
0
    parser->m_positionPtr = parser->m_eventPtr;
2369
0
  }
2370
0
  return parser->m_position.columnNumber;
2371
0
}
2372
2373
void XMLCALL
2374
0
XML_FreeContentModel(XML_Parser parser, XML_Content *model) {
2375
0
  if (parser != NULL)
2376
0
    FREE(parser, model);
2377
0
}
2378
2379
void *XMLCALL
2380
0
XML_MemMalloc(XML_Parser parser, size_t size) {
2381
0
  if (parser == NULL)
2382
0
    return NULL;
2383
0
  return MALLOC(parser, size);
2384
0
}
2385
2386
void *XMLCALL
2387
0
XML_MemRealloc(XML_Parser parser, void *ptr, size_t size) {
2388
0
  if (parser == NULL)
2389
0
    return NULL;
2390
0
  return REALLOC(parser, ptr, size);
2391
0
}
2392
2393
void XMLCALL
2394
0
XML_MemFree(XML_Parser parser, void *ptr) {
2395
0
  if (parser != NULL)
2396
0
    FREE(parser, ptr);
2397
0
}
2398
2399
void XMLCALL
2400
0
XML_DefaultCurrent(XML_Parser parser) {
2401
0
  if (parser == NULL)
2402
0
    return;
2403
0
  if (parser->m_defaultHandler) {
2404
0
    if (parser->m_openInternalEntities)
2405
0
      reportDefault(parser, parser->m_internalEncoding,
2406
0
                    parser->m_openInternalEntities->internalEventPtr,
2407
0
                    parser->m_openInternalEntities->internalEventEndPtr);
2408
0
    else
2409
0
      reportDefault(parser, parser->m_encoding, parser->m_eventPtr,
2410
0
                    parser->m_eventEndPtr);
2411
0
  }
2412
0
}
2413
2414
const XML_LChar *XMLCALL
2415
82.1k
XML_ErrorString(enum XML_Error code) {
2416
82.1k
  switch (code) {
2417
0
  case XML_ERROR_NONE:
2418
0
    return NULL;
2419
0
  case XML_ERROR_NO_MEMORY:
2420
0
    return XML_L("out of memory");
2421
21.4k
  case XML_ERROR_SYNTAX:
2422
21.4k
    return XML_L("syntax error");
2423
4.44k
  case XML_ERROR_NO_ELEMENTS:
2424
4.44k
    return XML_L("no element found");
2425
43.1k
  case XML_ERROR_INVALID_TOKEN:
2426
43.1k
    return XML_L("not well-formed (invalid token)");
2427
2.99k
  case XML_ERROR_UNCLOSED_TOKEN:
2428
2.99k
    return XML_L("unclosed token");
2429
1.57k
  case XML_ERROR_PARTIAL_CHAR:
2430
1.57k
    return XML_L("partial character");
2431
268
  case XML_ERROR_TAG_MISMATCH:
2432
268
    return XML_L("mismatched tag");
2433
643
  case XML_ERROR_DUPLICATE_ATTRIBUTE:
2434
643
    return XML_L("duplicate attribute");
2435
412
  case XML_ERROR_JUNK_AFTER_DOC_ELEMENT:
2436
412
    return XML_L("junk after document element");
2437
611
  case XML_ERROR_PARAM_ENTITY_REF:
2438
611
    return XML_L("illegal parameter entity reference");
2439
698
  case XML_ERROR_UNDEFINED_ENTITY:
2440
698
    return XML_L("undefined entity");
2441
18
  case XML_ERROR_RECURSIVE_ENTITY_REF:
2442
18
    return XML_L("recursive entity reference");
2443
2.09k
  case XML_ERROR_ASYNC_ENTITY:
2444
2.09k
    return XML_L("asynchronous entity");
2445
429
  case XML_ERROR_BAD_CHAR_REF:
2446
429
    return XML_L("reference to invalid character number");
2447
7
  case XML_ERROR_BINARY_ENTITY_REF:
2448
7
    return XML_L("reference to binary entity");
2449
4
  case XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF:
2450
4
    return XML_L("reference to external entity in attribute");
2451
113
  case XML_ERROR_MISPLACED_XML_PI:
2452
113
    return XML_L("XML or text declaration not at start of entity");
2453
121
  case XML_ERROR_UNKNOWN_ENCODING:
2454
121
    return XML_L("unknown encoding");
2455
8
  case XML_ERROR_INCORRECT_ENCODING:
2456
8
    return XML_L("encoding specified in XML declaration is incorrect");
2457
1.00k
  case XML_ERROR_UNCLOSED_CDATA_SECTION:
2458
1.00k
    return XML_L("unclosed CDATA section");
2459
0
  case XML_ERROR_EXTERNAL_ENTITY_HANDLING:
2460
0
    return XML_L("error in processing external entity reference");
2461
0
  case XML_ERROR_NOT_STANDALONE:
2462
0
    return XML_L("document is not standalone");
2463
0
  case XML_ERROR_UNEXPECTED_STATE:
2464
0
    return XML_L("unexpected parser state - please send a bug report");
2465
0
  case XML_ERROR_ENTITY_DECLARED_IN_PE:
2466
0
    return XML_L("entity declared in parameter entity");
2467
0
  case XML_ERROR_FEATURE_REQUIRES_XML_DTD:
2468
0
    return XML_L("requested feature requires XML_DTD support in Expat");
2469
0
  case XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING:
2470
0
    return XML_L("cannot change setting once parsing has begun");
2471
  /* Added in 1.95.7. */
2472
96
  case XML_ERROR_UNBOUND_PREFIX:
2473
96
    return XML_L("unbound prefix");
2474
  /* Added in 1.95.8. */
2475
2
  case XML_ERROR_UNDECLARING_PREFIX:
2476
2
    return XML_L("must not undeclare prefix");
2477
111
  case XML_ERROR_INCOMPLETE_PE:
2478
111
    return XML_L("incomplete markup in parameter entity");
2479
475
  case XML_ERROR_XML_DECL:
2480
475
    return XML_L("XML declaration not well-formed");
2481
404
  case XML_ERROR_TEXT_DECL:
2482
404
    return XML_L("text declaration not well-formed");
2483
853
  case XML_ERROR_PUBLICID:
2484
853
    return XML_L("illegal character(s) in public id");
2485
77
  case XML_ERROR_SUSPENDED:
2486
77
    return XML_L("parser suspended");
2487
0
  case XML_ERROR_NOT_SUSPENDED:
2488
0
    return XML_L("parser not suspended");
2489
0
  case XML_ERROR_ABORTED:
2490
0
    return XML_L("parsing aborted");
2491
48
  case XML_ERROR_FINISHED:
2492
48
    return XML_L("parsing finished");
2493
0
  case XML_ERROR_SUSPEND_PE:
2494
0
    return XML_L("cannot suspend in external parameter entity");
2495
  /* Added in 2.0.0. */
2496
14
  case XML_ERROR_RESERVED_PREFIX_XML:
2497
14
    return XML_L(
2498
0
        "reserved prefix (xml) must not be undeclared or bound to another namespace name");
2499
1
  case XML_ERROR_RESERVED_PREFIX_XMLNS:
2500
1
    return XML_L("reserved prefix (xmlns) must not be declared or undeclared");
2501
1
  case XML_ERROR_RESERVED_NAMESPACE_URI:
2502
1
    return XML_L(
2503
0
        "prefix must not be bound to one of the reserved namespace names");
2504
  /* Added in 2.2.5. */
2505
0
  case XML_ERROR_INVALID_ARGUMENT: /* Constant added in 2.2.1, already */
2506
0
    return XML_L("invalid argument");
2507
    /* Added in 2.3.0. */
2508
0
  case XML_ERROR_NO_BUFFER:
2509
0
    return XML_L(
2510
0
        "a successful prior call to function XML_GetBuffer is required");
2511
  /* Added in 2.4.0. */
2512
65
  case XML_ERROR_AMPLIFICATION_LIMIT_BREACH:
2513
65
    return XML_L(
2514
82.1k
        "limit on input amplification factor (from DTD and entities) breached");
2515
82.1k
  }
2516
0
  return NULL;
2517
82.1k
}
2518
2519
const XML_LChar *XMLCALL
2520
0
XML_ExpatVersion(void) {
2521
  /* V1 is used to string-ize the version number. However, it would
2522
     string-ize the actual version macro *names* unless we get them
2523
     substituted before being passed to V1. CPP is defined to expand
2524
     a macro, then rescan for more expansions. Thus, we use V2 to expand
2525
     the version macros, then CPP will expand the resulting V1() macro
2526
     with the correct numerals. */
2527
  /* ### I'm assuming cpp is portable in this respect... */
2528
2529
0
#define V1(a, b, c) XML_L(#a) XML_L(".") XML_L(#b) XML_L(".") XML_L(#c)
2530
0
#define V2(a, b, c) XML_L("expat_") V1(a, b, c)
2531
2532
0
  return V2(XML_MAJOR_VERSION, XML_MINOR_VERSION, XML_MICRO_VERSION);
2533
2534
0
#undef V1
2535
0
#undef V2
2536
0
}
2537
2538
XML_Expat_Version XMLCALL
2539
0
XML_ExpatVersionInfo(void) {
2540
0
  XML_Expat_Version version;
2541
2542
0
  version.major = XML_MAJOR_VERSION;
2543
0
  version.minor = XML_MINOR_VERSION;
2544
0
  version.micro = XML_MICRO_VERSION;
2545
2546
0
  return version;
2547
0
}
2548
2549
const XML_Feature *XMLCALL
2550
0
XML_GetFeatureList(void) {
2551
0
  static const XML_Feature features[] = {
2552
0
      {XML_FEATURE_SIZEOF_XML_CHAR, XML_L("sizeof(XML_Char)"),
2553
0
       sizeof(XML_Char)},
2554
0
      {XML_FEATURE_SIZEOF_XML_LCHAR, XML_L("sizeof(XML_LChar)"),
2555
0
       sizeof(XML_LChar)},
2556
#ifdef XML_UNICODE
2557
      {XML_FEATURE_UNICODE, XML_L("XML_UNICODE"), 0},
2558
#endif
2559
#ifdef XML_UNICODE_WCHAR_T
2560
      {XML_FEATURE_UNICODE_WCHAR_T, XML_L("XML_UNICODE_WCHAR_T"), 0},
2561
#endif
2562
0
#ifdef XML_DTD
2563
0
      {XML_FEATURE_DTD, XML_L("XML_DTD"), 0},
2564
0
#endif
2565
0
#if XML_CONTEXT_BYTES > 0
2566
0
      {XML_FEATURE_CONTEXT_BYTES, XML_L("XML_CONTEXT_BYTES"),
2567
0
       XML_CONTEXT_BYTES},
2568
0
#endif
2569
#ifdef XML_MIN_SIZE
2570
      {XML_FEATURE_MIN_SIZE, XML_L("XML_MIN_SIZE"), 0},
2571
#endif
2572
0
#ifdef XML_NS
2573
0
      {XML_FEATURE_NS, XML_L("XML_NS"), 0},
2574
0
#endif
2575
#ifdef XML_LARGE_SIZE
2576
      {XML_FEATURE_LARGE_SIZE, XML_L("XML_LARGE_SIZE"), 0},
2577
#endif
2578
#ifdef XML_ATTR_INFO
2579
      {XML_FEATURE_ATTR_INFO, XML_L("XML_ATTR_INFO"), 0},
2580
#endif
2581
0
#if XML_GE == 1
2582
      /* Added in Expat 2.4.0 for XML_DTD defined and
2583
       * added in Expat 2.6.0 for XML_GE == 1. */
2584
0
      {XML_FEATURE_BILLION_LAUGHS_ATTACK_PROTECTION_MAXIMUM_AMPLIFICATION_DEFAULT,
2585
0
       XML_L("XML_BLAP_MAX_AMP"),
2586
0
       (long int)
2587
0
           EXPAT_BILLION_LAUGHS_ATTACK_PROTECTION_MAXIMUM_AMPLIFICATION_DEFAULT},
2588
0
      {XML_FEATURE_BILLION_LAUGHS_ATTACK_PROTECTION_ACTIVATION_THRESHOLD_DEFAULT,
2589
0
       XML_L("XML_BLAP_ACT_THRES"),
2590
0
       EXPAT_BILLION_LAUGHS_ATTACK_PROTECTION_ACTIVATION_THRESHOLD_DEFAULT},
2591
      /* Added in Expat 2.6.0. */
2592
0
      {XML_FEATURE_GE, XML_L("XML_GE"), 0},
2593
0
#endif
2594
0
      {XML_FEATURE_END, NULL, 0}};
2595
2596
0
  return features;
2597
0
}
2598
2599
#if XML_GE == 1
2600
XML_Bool XMLCALL
2601
XML_SetBillionLaughsAttackProtectionMaximumAmplification(
2602
0
    XML_Parser parser, float maximumAmplificationFactor) {
2603
0
  if ((parser == NULL) || (parser->m_parentParser != NULL)
2604
0
      || isnan(maximumAmplificationFactor)
2605
0
      || (maximumAmplificationFactor < 1.0f)) {
2606
0
    return XML_FALSE;
2607
0
  }
2608
0
  parser->m_accounting.maximumAmplificationFactor = maximumAmplificationFactor;
2609
0
  return XML_TRUE;
2610
0
}
2611
2612
XML_Bool XMLCALL
2613
XML_SetBillionLaughsAttackProtectionActivationThreshold(
2614
0
    XML_Parser parser, unsigned long long activationThresholdBytes) {
2615
0
  if ((parser == NULL) || (parser->m_parentParser != NULL)) {
2616
0
    return XML_FALSE;
2617
0
  }
2618
0
  parser->m_accounting.activationThresholdBytes = activationThresholdBytes;
2619
0
  return XML_TRUE;
2620
0
}
2621
#endif /* XML_GE == 1 */
2622
2623
XML_Bool XMLCALL
2624
0
XML_SetReparseDeferralEnabled(XML_Parser parser, XML_Bool enabled) {
2625
0
  if (parser != NULL && (enabled == XML_TRUE || enabled == XML_FALSE)) {
2626
0
    parser->m_reparseDeferralEnabled = enabled;
2627
0
    return XML_TRUE;
2628
0
  }
2629
0
  return XML_FALSE;
2630
0
}
2631
2632
/* Initially tag->rawName always points into the parse buffer;
2633
   for those TAG instances opened while the current parse buffer was
2634
   processed, and not yet closed, we need to store tag->rawName in a more
2635
   permanent location, since the parse buffer is about to be discarded.
2636
*/
2637
static XML_Bool
2638
18.8k
storeRawNames(XML_Parser parser) {
2639
18.8k
  TAG *tag = parser->m_tagStack;
2640
581k
  while (tag) {
2641
562k
    int bufSize;
2642
562k
    int nameLen = sizeof(XML_Char) * (tag->name.strLen + 1);
2643
562k
    size_t rawNameLen;
2644
562k
    char *rawNameBuf = tag->buf + nameLen;
2645
    /* Stop if already stored.  Since m_tagStack is a stack, we can stop
2646
       at the first entry that has already been copied; everything
2647
       below it in the stack is already been accounted for in a
2648
       previous call to this function.
2649
    */
2650
562k
    if (tag->rawName == rawNameBuf)
2651
106
      break;
2652
    /* For reuse purposes we need to ensure that the
2653
       size of tag->buf is a multiple of sizeof(XML_Char).
2654
    */
2655
562k
    rawNameLen = ROUND_UP(tag->rawNameLength, sizeof(XML_Char));
2656
    /* Detect and prevent integer overflow. */
2657
562k
    if (rawNameLen > (size_t)INT_MAX - nameLen)
2658
0
      return XML_FALSE;
2659
562k
    bufSize = nameLen + (int)rawNameLen;
2660
562k
    if (bufSize > tag->bufEnd - tag->buf) {
2661
4.57k
      char *temp = (char *)REALLOC(parser, tag->buf, bufSize);
2662
4.57k
      if (temp == NULL)
2663
0
        return XML_FALSE;
2664
      /* if tag->name.str points to tag->buf (only when namespace
2665
         processing is off) then we have to update it
2666
      */
2667
4.57k
      if (tag->name.str == (XML_Char *)tag->buf)
2668
3.38k
        tag->name.str = (XML_Char *)temp;
2669
      /* if tag->name.localPart is set (when namespace processing is on)
2670
         then update it as well, since it will always point into tag->buf
2671
      */
2672
4.57k
      if (tag->name.localPart)
2673
1.19k
        tag->name.localPart
2674
1.19k
            = (XML_Char *)temp + (tag->name.localPart - (XML_Char *)tag->buf);
2675
4.57k
      tag->buf = temp;
2676
4.57k
      tag->bufEnd = temp + bufSize;
2677
4.57k
      rawNameBuf = temp + nameLen;
2678
4.57k
    }
2679
562k
    memcpy(rawNameBuf, tag->rawName, tag->rawNameLength);
2680
562k
    tag->rawName = rawNameBuf;
2681
562k
    tag = tag->parent;
2682
562k
  }
2683
18.8k
  return XML_TRUE;
2684
18.8k
}
2685
2686
static enum XML_Error PTRCALL
2687
contentProcessor(XML_Parser parser, const char *start, const char *end,
2688
25.5k
                 const char **endPtr) {
2689
25.5k
  enum XML_Error result = doContent(
2690
25.5k
      parser, 0, parser->m_encoding, start, end, endPtr,
2691
25.5k
      (XML_Bool)! parser->m_parsingStatus.finalBuffer, XML_ACCOUNT_DIRECT);
2692
25.5k
  if (result == XML_ERROR_NONE) {
2693
10.1k
    if (! storeRawNames(parser))
2694
0
      return XML_ERROR_NO_MEMORY;
2695
10.1k
  }
2696
25.5k
  return result;
2697
25.5k
}
2698
2699
static enum XML_Error PTRCALL
2700
externalEntityInitProcessor(XML_Parser parser, const char *start,
2701
21.1k
                            const char *end, const char **endPtr) {
2702
21.1k
  enum XML_Error result = initializeEncoding(parser);
2703
21.1k
  if (result != XML_ERROR_NONE)
2704
0
    return result;
2705
21.1k
  parser->m_processor = externalEntityInitProcessor2;
2706
21.1k
  return externalEntityInitProcessor2(parser, start, end, endPtr);
2707
21.1k
}
2708
2709
static enum XML_Error PTRCALL
2710
externalEntityInitProcessor2(XML_Parser parser, const char *start,
2711
24.0k
                             const char *end, const char **endPtr) {
2712
24.0k
  const char *next = start; /* XmlContentTok doesn't always set the last arg */
2713
24.0k
  int tok = XmlContentTok(parser->m_encoding, start, end, &next);
2714
24.0k
  switch (tok) {
2715
1.64k
  case XML_TOK_BOM:
2716
1.64k
#if XML_GE == 1
2717
1.64k
    if (! accountingDiffTolerated(parser, tok, start, next, __LINE__,
2718
1.64k
                                  XML_ACCOUNT_DIRECT)) {
2719
0
      accountingOnAbort(parser);
2720
0
      return XML_ERROR_AMPLIFICATION_LIMIT_BREACH;
2721
0
    }
2722
1.64k
#endif /* XML_GE == 1 */
2723
2724
    /* If we are at the end of the buffer, this would cause the next stage,
2725
       i.e. externalEntityInitProcessor3, to pass control directly to
2726
       doContent (by detecting XML_TOK_NONE) without processing any xml text
2727
       declaration - causing the error XML_ERROR_MISPLACED_XML_PI in doContent.
2728
    */
2729
1.64k
    if (next == end && ! parser->m_parsingStatus.finalBuffer) {
2730
3
      *endPtr = next;
2731
3
      return XML_ERROR_NONE;
2732
3
    }
2733
1.64k
    start = next;
2734
1.64k
    break;
2735
2.73k
  case XML_TOK_PARTIAL:
2736
2.73k
    if (! parser->m_parsingStatus.finalBuffer) {
2737
2.48k
      *endPtr = start;
2738
2.48k
      return XML_ERROR_NONE;
2739
2.48k
    }
2740
252
    parser->m_eventPtr = start;
2741
252
    return XML_ERROR_UNCLOSED_TOKEN;
2742
536
  case XML_TOK_PARTIAL_CHAR:
2743
536
    if (! parser->m_parsingStatus.finalBuffer) {
2744
459
      *endPtr = start;
2745
459
      return XML_ERROR_NONE;
2746
459
    }
2747
77
    parser->m_eventPtr = start;
2748
77
    return XML_ERROR_PARTIAL_CHAR;
2749
24.0k
  }
2750
20.7k
  parser->m_processor = externalEntityInitProcessor3;
2751
20.7k
  return externalEntityInitProcessor3(parser, start, end, endPtr);
2752
24.0k
}
2753
2754
static enum XML_Error PTRCALL
2755
externalEntityInitProcessor3(XML_Parser parser, const char *start,
2756
21.0k
                             const char *end, const char **endPtr) {
2757
21.0k
  int tok;
2758
21.0k
  const char *next = start; /* XmlContentTok doesn't always set the last arg */
2759
21.0k
  parser->m_eventPtr = start;
2760
21.0k
  tok = XmlContentTok(parser->m_encoding, start, end, &next);
2761
  /* Note: These bytes are accounted later in:
2762
           - processXmlDecl
2763
           - externalEntityContentProcessor
2764
  */
2765
21.0k
  parser->m_eventEndPtr = next;
2766
2767
21.0k
  switch (tok) {
2768
366
  case XML_TOK_XML_DECL: {
2769
366
    enum XML_Error result;
2770
366
    result = processXmlDecl(parser, 1, start, next);
2771
366
    if (result != XML_ERROR_NONE)
2772
250
      return result;
2773
116
    switch (parser->m_parsingStatus.parsing) {
2774
0
    case XML_SUSPENDED:
2775
0
      *endPtr = next;
2776
0
      return XML_ERROR_NONE;
2777
0
    case XML_FINISHED:
2778
0
      return XML_ERROR_ABORTED;
2779
116
    default:
2780
116
      start = next;
2781
116
    }
2782
116
  } break;
2783
197
  case XML_TOK_PARTIAL:
2784
197
    if (! parser->m_parsingStatus.finalBuffer) {
2785
191
      *endPtr = start;
2786
191
      return XML_ERROR_NONE;
2787
191
    }
2788
6
    return XML_ERROR_UNCLOSED_TOKEN;
2789
76
  case XML_TOK_PARTIAL_CHAR:
2790
76
    if (! parser->m_parsingStatus.finalBuffer) {
2791
75
      *endPtr = start;
2792
75
      return XML_ERROR_NONE;
2793
75
    }
2794
1
    return XML_ERROR_PARTIAL_CHAR;
2795
21.0k
  }
2796
20.5k
  parser->m_processor = externalEntityContentProcessor;
2797
20.5k
  parser->m_tagLevel = 1;
2798
20.5k
  return externalEntityContentProcessor(parser, start, end, endPtr);
2799
21.0k
}
2800
2801
static enum XML_Error PTRCALL
2802
externalEntityContentProcessor(XML_Parser parser, const char *start,
2803
26.8k
                               const char *end, const char **endPtr) {
2804
26.8k
  enum XML_Error result
2805
26.8k
      = doContent(parser, 1, parser->m_encoding, start, end, endPtr,
2806
26.8k
                  (XML_Bool)! parser->m_parsingStatus.finalBuffer,
2807
26.8k
                  XML_ACCOUNT_ENTITY_EXPANSION);
2808
26.8k
  if (result == XML_ERROR_NONE) {
2809
8.67k
    if (! storeRawNames(parser))
2810
0
      return XML_ERROR_NO_MEMORY;
2811
8.67k
  }
2812
26.8k
  return result;
2813
26.8k
}
2814
2815
static enum XML_Error
2816
doContent(XML_Parser parser, int startTagLevel, const ENCODING *enc,
2817
          const char *s, const char *end, const char **nextPtr,
2818
874k
          XML_Bool haveMore, enum XML_Account account) {
2819
  /* save one level of indirection */
2820
874k
  DTD *const dtd = parser->m_dtd;
2821
2822
874k
  const char **eventPP;
2823
874k
  const char **eventEndPP;
2824
874k
  if (enc == parser->m_encoding) {
2825
52.4k
    eventPP = &parser->m_eventPtr;
2826
52.4k
    eventEndPP = &parser->m_eventEndPtr;
2827
822k
  } else {
2828
822k
    eventPP = &(parser->m_openInternalEntities->internalEventPtr);
2829
822k
    eventEndPP = &(parser->m_openInternalEntities->internalEventEndPtr);
2830
822k
  }
2831
874k
  *eventPP = s;
2832
2833
7.54M
  for (;;) {
2834
7.54M
    const char *next = s; /* XmlContentTok doesn't always set the last arg */
2835
7.54M
    int tok = XmlContentTok(enc, s, end, &next);
2836
7.54M
#if XML_GE == 1
2837
7.54M
    const char *accountAfter
2838
7.54M
        = ((tok == XML_TOK_TRAILING_RSQB) || (tok == XML_TOK_TRAILING_CR))
2839
7.54M
              ? (haveMore ? s /* i.e. 0 bytes */ : end)
2840
7.54M
              : next;
2841
7.54M
    if (! accountingDiffTolerated(parser, tok, s, accountAfter, __LINE__,
2842
7.54M
                                  account)) {
2843
13
      accountingOnAbort(parser);
2844
13
      return XML_ERROR_AMPLIFICATION_LIMIT_BREACH;
2845
13
    }
2846
7.54M
#endif
2847
7.54M
    *eventEndPP = next;
2848
7.54M
    switch (tok) {
2849
453
    case XML_TOK_TRAILING_CR:
2850
453
      if (haveMore) {
2851
243
        *nextPtr = s;
2852
243
        return XML_ERROR_NONE;
2853
243
      }
2854
210
      *eventEndPP = end;
2855
210
      if (parser->m_characterDataHandler) {
2856
210
        XML_Char c = 0xA;
2857
210
        parser->m_characterDataHandler(parser->m_handlerArg, &c, 1);
2858
210
      } else if (parser->m_defaultHandler)
2859
0
        reportDefault(parser, enc, s, end);
2860
      /* We are at the end of the final buffer, should we check for
2861
         XML_SUSPENDED, XML_FINISHED?
2862
      */
2863
210
      if (startTagLevel == 0)
2864
88
        return XML_ERROR_NO_ELEMENTS;
2865
122
      if (parser->m_tagLevel != startTagLevel)
2866
49
        return XML_ERROR_ASYNC_ENTITY;
2867
73
      *nextPtr = end;
2868
73
      return XML_ERROR_NONE;
2869
825k
    case XML_TOK_NONE:
2870
825k
      if (haveMore) {
2871
6.51k
        *nextPtr = s;
2872
6.51k
        return XML_ERROR_NONE;
2873
6.51k
      }
2874
819k
      if (startTagLevel > 0) {
2875
815k
        if (parser->m_tagLevel != startTagLevel)
2876
1.96k
          return XML_ERROR_ASYNC_ENTITY;
2877
813k
        *nextPtr = s;
2878
813k
        return XML_ERROR_NONE;
2879
815k
      }
2880
3.79k
      return XML_ERROR_NO_ELEMENTS;
2881
22.2k
    case XML_TOK_INVALID:
2882
22.2k
      *eventPP = next;
2883
22.2k
      return XML_ERROR_INVALID_TOKEN;
2884
7.85k
    case XML_TOK_PARTIAL:
2885
7.85k
      if (haveMore) {
2886
6.72k
        *nextPtr = s;
2887
6.72k
        return XML_ERROR_NONE;
2888
6.72k
      }
2889
1.12k
      return XML_ERROR_UNCLOSED_TOKEN;
2890
2.72k
    case XML_TOK_PARTIAL_CHAR:
2891
2.72k
      if (haveMore) {
2892
1.74k
        *nextPtr = s;
2893
1.74k
        return XML_ERROR_NONE;
2894
1.74k
      }
2895
985
      return XML_ERROR_PARTIAL_CHAR;
2896
854k
    case XML_TOK_ENTITY_REF: {
2897
854k
      const XML_Char *name;
2898
854k
      ENTITY *entity;
2899
854k
      XML_Char ch = (XML_Char)XmlPredefinedEntityName(
2900
854k
          enc, s + enc->minBytesPerChar, next - enc->minBytesPerChar);
2901
854k
      if (ch) {
2902
5.48k
#if XML_GE == 1
2903
        /* NOTE: We are replacing 4-6 characters original input for 1 character
2904
         *       so there is no amplification and hence recording without
2905
         *       protection. */
2906
5.48k
        accountingDiffTolerated(parser, tok, (char *)&ch,
2907
5.48k
                                ((char *)&ch) + sizeof(XML_Char), __LINE__,
2908
5.48k
                                XML_ACCOUNT_ENTITY_EXPANSION);
2909
5.48k
#endif /* XML_GE == 1 */
2910
5.48k
        if (parser->m_characterDataHandler)
2911
5.48k
          parser->m_characterDataHandler(parser->m_handlerArg, &ch, 1);
2912
0
        else if (parser->m_defaultHandler)
2913
0
          reportDefault(parser, enc, s, next);
2914
5.48k
        break;
2915
5.48k
      }
2916
849k
      name = poolStoreString(&dtd->pool, enc, s + enc->minBytesPerChar,
2917
849k
                             next - enc->minBytesPerChar);
2918
849k
      if (! name)
2919
0
        return XML_ERROR_NO_MEMORY;
2920
849k
      entity = (ENTITY *)lookup(parser, &dtd->generalEntities, name, 0);
2921
849k
      poolDiscard(&dtd->pool);
2922
      /* First, determine if a check for an existing declaration is needed;
2923
         if yes, check that the entity exists, and that it is internal,
2924
         otherwise call the skipped entity or default handler.
2925
      */
2926
849k
      if (! dtd->hasParamEntityRefs || dtd->standalone) {
2927
820k
        if (! entity)
2928
579
          return XML_ERROR_UNDEFINED_ENTITY;
2929
820k
        else if (! entity->is_internal)
2930
0
          return XML_ERROR_ENTITY_DECLARED_IN_PE;
2931
820k
      } else if (! entity) {
2932
25.9k
        if (parser->m_skippedEntityHandler)
2933
0
          parser->m_skippedEntityHandler(parser->m_handlerArg, name, 0);
2934
25.9k
        else if (parser->m_defaultHandler)
2935
0
          reportDefault(parser, enc, s, next);
2936
25.9k
        break;
2937
25.9k
      }
2938
822k
      if (entity->open)
2939
7
        return XML_ERROR_RECURSIVE_ENTITY_REF;
2940
822k
      if (entity->notation)
2941
3
        return XML_ERROR_BINARY_ENTITY_REF;
2942
822k
      if (entity->textPtr) {
2943
822k
        enum XML_Error result;
2944
822k
        if (! parser->m_defaultExpandInternalEntities) {
2945
0
          if (parser->m_skippedEntityHandler)
2946
0
            parser->m_skippedEntityHandler(parser->m_handlerArg, entity->name,
2947
0
                                           0);
2948
0
          else if (parser->m_defaultHandler)
2949
0
            reportDefault(parser, enc, s, next);
2950
0
          break;
2951
0
        }
2952
822k
        result = processInternalEntity(parser, entity, XML_FALSE);
2953
822k
        if (result != XML_ERROR_NONE)
2954
2.00k
          return result;
2955
822k
      } else if (parser->m_externalEntityRefHandler) {
2956
0
        const XML_Char *context;
2957
0
        entity->open = XML_TRUE;
2958
0
        context = getContext(parser);
2959
0
        entity->open = XML_FALSE;
2960
0
        if (! context)
2961
0
          return XML_ERROR_NO_MEMORY;
2962
0
        if (! parser->m_externalEntityRefHandler(
2963
0
                parser->m_externalEntityRefHandlerArg, context, entity->base,
2964
0
                entity->systemId, entity->publicId))
2965
0
          return XML_ERROR_EXTERNAL_ENTITY_HANDLING;
2966
0
        poolDiscard(&parser->m_tempPool);
2967
194
      } else if (parser->m_defaultHandler)
2968
0
        reportDefault(parser, enc, s, next);
2969
820k
      break;
2970
822k
    }
2971
2.03M
    case XML_TOK_START_TAG_NO_ATTS:
2972
      /* fall through */
2973
2.06M
    case XML_TOK_START_TAG_WITH_ATTS: {
2974
2.06M
      TAG *tag;
2975
2.06M
      enum XML_Error result;
2976
2.06M
      XML_Char *toPtr;
2977
2.06M
      if (parser->m_freeTagList) {
2978
138k
        tag = parser->m_freeTagList;
2979
138k
        parser->m_freeTagList = parser->m_freeTagList->parent;
2980
1.92M
      } else {
2981
1.92M
        tag = (TAG *)MALLOC(parser, sizeof(TAG));
2982
1.92M
        if (! tag)
2983
0
          return XML_ERROR_NO_MEMORY;
2984
1.92M
        tag->buf = (char *)MALLOC(parser, INIT_TAG_BUF_SIZE);
2985
1.92M
        if (! tag->buf) {
2986
0
          FREE(parser, tag);
2987
0
          return XML_ERROR_NO_MEMORY;
2988
0
        }
2989
1.92M
        tag->bufEnd = tag->buf + INIT_TAG_BUF_SIZE;
2990
1.92M
      }
2991
2.06M
      tag->bindings = NULL;
2992
2.06M
      tag->parent = parser->m_tagStack;
2993
2.06M
      parser->m_tagStack = tag;
2994
2.06M
      tag->name.localPart = NULL;
2995
2.06M
      tag->name.prefix = NULL;
2996
2.06M
      tag->rawName = s + enc->minBytesPerChar;
2997
2.06M
      tag->rawNameLength = XmlNameLength(enc, tag->rawName);
2998
2.06M
      ++parser->m_tagLevel;
2999
2.06M
      {
3000
2.06M
        const char *rawNameEnd = tag->rawName + tag->rawNameLength;
3001
2.06M
        const char *fromPtr = tag->rawName;
3002
2.06M
        toPtr = (XML_Char *)tag->buf;
3003
2.07M
        for (;;) {
3004
2.07M
          int bufSize;
3005
2.07M
          int convLen;
3006
2.07M
          const enum XML_Convert_Result convert_res
3007
2.07M
              = XmlConvert(enc, &fromPtr, rawNameEnd, (ICHAR **)&toPtr,
3008
2.07M
                           (ICHAR *)tag->bufEnd - 1);
3009
2.07M
          convLen = (int)(toPtr - (XML_Char *)tag->buf);
3010
2.07M
          if ((fromPtr >= rawNameEnd)
3011
2.07M
              || (convert_res == XML_CONVERT_INPUT_INCOMPLETE)) {
3012
2.06M
            tag->name.strLen = convLen;
3013
2.06M
            break;
3014
2.06M
          }
3015
10.8k
          bufSize = (int)(tag->bufEnd - tag->buf) << 1;
3016
10.8k
          {
3017
10.8k
            char *temp = (char *)REALLOC(parser, tag->buf, bufSize);
3018
10.8k
            if (temp == NULL)
3019
0
              return XML_ERROR_NO_MEMORY;
3020
10.8k
            tag->buf = temp;
3021
10.8k
            tag->bufEnd = temp + bufSize;
3022
10.8k
            toPtr = (XML_Char *)temp + convLen;
3023
10.8k
          }
3024
10.8k
        }
3025
2.06M
      }
3026
2.06M
      tag->name.str = (XML_Char *)tag->buf;
3027
2.06M
      *toPtr = XML_T('\0');
3028
2.06M
      result
3029
2.06M
          = storeAtts(parser, enc, s, &(tag->name), &(tag->bindings), account);
3030
2.06M
      if (result)
3031
878
        return result;
3032
2.06M
      if (parser->m_startElementHandler)
3033
2.06M
        parser->m_startElementHandler(parser->m_handlerArg, tag->name.str,
3034
2.06M
                                      (const XML_Char **)parser->m_atts);
3035
0
      else if (parser->m_defaultHandler)
3036
0
        reportDefault(parser, enc, s, next);
3037
2.06M
      poolClear(&parser->m_tempPool);
3038
2.06M
      break;
3039
2.06M
    }
3040
319k
    case XML_TOK_EMPTY_ELEMENT_NO_ATTS:
3041
      /* fall through */
3042
327k
    case XML_TOK_EMPTY_ELEMENT_WITH_ATTS: {
3043
327k
      const char *rawName = s + enc->minBytesPerChar;
3044
327k
      enum XML_Error result;
3045
327k
      BINDING *bindings = NULL;
3046
327k
      XML_Bool noElmHandlers = XML_TRUE;
3047
327k
      TAG_NAME name;
3048
327k
      name.str = poolStoreString(&parser->m_tempPool, enc, rawName,
3049
327k
                                 rawName + XmlNameLength(enc, rawName));
3050
327k
      if (! name.str)
3051
0
        return XML_ERROR_NO_MEMORY;
3052
327k
      poolFinish(&parser->m_tempPool);
3053
327k
      result = storeAtts(parser, enc, s, &name, &bindings,
3054
327k
                         XML_ACCOUNT_NONE /* token spans whole start tag */);
3055
327k
      if (result != XML_ERROR_NONE) {
3056
78
        freeBindings(parser, bindings);
3057
78
        return result;
3058
78
      }
3059
327k
      poolFinish(&parser->m_tempPool);
3060
327k
      if (parser->m_startElementHandler) {
3061
327k
        parser->m_startElementHandler(parser->m_handlerArg, name.str,
3062
327k
                                      (const XML_Char **)parser->m_atts);
3063
327k
        noElmHandlers = XML_FALSE;
3064
327k
      }
3065
327k
      if (parser->m_endElementHandler) {
3066
327k
        if (parser->m_startElementHandler)
3067
327k
          *eventPP = *eventEndPP;
3068
327k
        parser->m_endElementHandler(parser->m_handlerArg, name.str);
3069
327k
        noElmHandlers = XML_FALSE;
3070
327k
      }
3071
327k
      if (noElmHandlers && parser->m_defaultHandler)
3072
0
        reportDefault(parser, enc, s, next);
3073
327k
      poolClear(&parser->m_tempPool);
3074
327k
      freeBindings(parser, bindings);
3075
327k
    }
3076
327k
      if ((parser->m_tagLevel == 0)
3077
327k
          && (parser->m_parsingStatus.parsing != XML_FINISHED)) {
3078
730
        if (parser->m_parsingStatus.parsing == XML_SUSPENDED)
3079
0
          parser->m_processor = epilogProcessor;
3080
730
        else
3081
730
          return epilogProcessor(parser, next, end, nextPtr);
3082
730
      }
3083
326k
      break;
3084
326k
    case XML_TOK_END_TAG:
3085
139k
      if (parser->m_tagLevel == startTagLevel)
3086
25
        return XML_ERROR_ASYNC_ENTITY;
3087
139k
      else {
3088
139k
        int len;
3089
139k
        const char *rawName;
3090
139k
        TAG *tag = parser->m_tagStack;
3091
139k
        rawName = s + enc->minBytesPerChar * 2;
3092
139k
        len = XmlNameLength(enc, rawName);
3093
139k
        if (len != tag->rawNameLength
3094
139k
            || memcmp(tag->rawName, rawName, len) != 0) {
3095
268
          *eventPP = rawName;
3096
268
          return XML_ERROR_TAG_MISMATCH;
3097
268
        }
3098
138k
        parser->m_tagStack = tag->parent;
3099
138k
        tag->parent = parser->m_freeTagList;
3100
138k
        parser->m_freeTagList = tag;
3101
138k
        --parser->m_tagLevel;
3102
138k
        if (parser->m_endElementHandler) {
3103
138k
          const XML_Char *localPart;
3104
138k
          const XML_Char *prefix;
3105
138k
          XML_Char *uri;
3106
138k
          localPart = tag->name.localPart;
3107
138k
          if (parser->m_ns && localPart) {
3108
            /* localPart and prefix may have been overwritten in
3109
               tag->name.str, since this points to the binding->uri
3110
               buffer which gets reused; so we have to add them again
3111
            */
3112
562
            uri = (XML_Char *)tag->name.str + tag->name.uriLen;
3113
            /* don't need to check for space - already done in storeAtts() */
3114
1.38k
            while (*localPart)
3115
824
              *uri++ = *localPart++;
3116
562
            prefix = tag->name.prefix;
3117
562
            if (parser->m_ns_triplets && prefix) {
3118
0
              *uri++ = parser->m_namespaceSeparator;
3119
0
              while (*prefix)
3120
0
                *uri++ = *prefix++;
3121
0
            }
3122
562
            *uri = XML_T('\0');
3123
562
          }
3124
138k
          parser->m_endElementHandler(parser->m_handlerArg, tag->name.str);
3125
138k
        } else if (parser->m_defaultHandler)
3126
0
          reportDefault(parser, enc, s, next);
3127
139k
        while (tag->bindings) {
3128
752
          BINDING *b = tag->bindings;
3129
752
          if (parser->m_endNamespaceDeclHandler)
3130
0
            parser->m_endNamespaceDeclHandler(parser->m_handlerArg,
3131
0
                                              b->prefix->name);
3132
752
          tag->bindings = tag->bindings->nextTagBinding;
3133
752
          b->nextTagBinding = parser->m_freeBindingList;
3134
752
          parser->m_freeBindingList = b;
3135
752
          b->prefix->binding = b->prevPrefixBinding;
3136
752
        }
3137
138k
        if ((parser->m_tagLevel == 0)
3138
138k
            && (parser->m_parsingStatus.parsing != XML_FINISHED)) {
3139
58
          if (parser->m_parsingStatus.parsing == XML_SUSPENDED)
3140
0
            parser->m_processor = epilogProcessor;
3141
58
          else
3142
58
            return epilogProcessor(parser, next, end, nextPtr);
3143
58
        }
3144
138k
      }
3145
138k
      break;
3146
138k
    case XML_TOK_CHAR_REF: {
3147
15.8k
      int n = XmlCharRefNumber(enc, s);
3148
15.8k
      if (n < 0)
3149
389
        return XML_ERROR_BAD_CHAR_REF;
3150
15.4k
      if (parser->m_characterDataHandler) {
3151
15.4k
        XML_Char buf[XML_ENCODE_MAX];
3152
15.4k
        parser->m_characterDataHandler(parser->m_handlerArg, buf,
3153
15.4k
                                       XmlEncode(n, (ICHAR *)buf));
3154
15.4k
      } else if (parser->m_defaultHandler)
3155
0
        reportDefault(parser, enc, s, next);
3156
15.4k
    } break;
3157
47
    case XML_TOK_XML_DECL:
3158
47
      return XML_ERROR_MISPLACED_XML_PI;
3159
766k
    case XML_TOK_DATA_NEWLINE:
3160
766k
      if (parser->m_characterDataHandler) {
3161
766k
        XML_Char c = 0xA;
3162
766k
        parser->m_characterDataHandler(parser->m_handlerArg, &c, 1);
3163
766k
      } else if (parser->m_defaultHandler)
3164
0
        reportDefault(parser, enc, s, next);
3165
766k
      break;
3166
470k
    case XML_TOK_CDATA_SECT_OPEN: {
3167
470k
      enum XML_Error result;
3168
470k
      if (parser->m_startCdataSectionHandler)
3169
0
        parser->m_startCdataSectionHandler(parser->m_handlerArg);
3170
      /* BEGIN disabled code */
3171
      /* Suppose you doing a transformation on a document that involves
3172
         changing only the character data.  You set up a defaultHandler
3173
         and a characterDataHandler.  The defaultHandler simply copies
3174
         characters through.  The characterDataHandler does the
3175
         transformation and writes the characters out escaping them as
3176
         necessary.  This case will fail to work if we leave out the
3177
         following two lines (because & and < inside CDATA sections will
3178
         be incorrectly escaped).
3179
3180
         However, now we have a start/endCdataSectionHandler, so it seems
3181
         easier to let the user deal with this.
3182
      */
3183
470k
      else if ((0) && parser->m_characterDataHandler)
3184
0
        parser->m_characterDataHandler(parser->m_handlerArg, parser->m_dataBuf,
3185
0
                                       0);
3186
      /* END disabled code */
3187
470k
      else if (parser->m_defaultHandler)
3188
0
        reportDefault(parser, enc, s, next);
3189
470k
      result
3190
470k
          = doCdataSection(parser, enc, &next, end, nextPtr, haveMore, account);
3191
470k
      if (result != XML_ERROR_NONE)
3192
467
        return result;
3193
470k
      else if (! next) {
3194
1.11k
        parser->m_processor = cdataSectionProcessor;
3195
1.11k
        return result;
3196
1.11k
      }
3197
470k
    } break;
3198
469k
    case XML_TOK_TRAILING_RSQB:
3199
9.02k
      if (haveMore) {
3200
216
        *nextPtr = s;
3201
216
        return XML_ERROR_NONE;
3202
216
      }
3203
8.80k
      if (parser->m_characterDataHandler) {
3204
8.80k
        if (MUST_CONVERT(enc, s)) {
3205
115
          ICHAR *dataPtr = (ICHAR *)parser->m_dataBuf;
3206
115
          XmlConvert(enc, &s, end, &dataPtr, (ICHAR *)parser->m_dataBufEnd);
3207
115
          parser->m_characterDataHandler(
3208
115
              parser->m_handlerArg, parser->m_dataBuf,
3209
115
              (int)(dataPtr - (ICHAR *)parser->m_dataBuf));
3210
115
        } else
3211
8.69k
          parser->m_characterDataHandler(
3212
8.69k
              parser->m_handlerArg, (const XML_Char *)s,
3213
8.69k
              (int)((const XML_Char *)end - (const XML_Char *)s));
3214
8.80k
      } else if (parser->m_defaultHandler)
3215
0
        reportDefault(parser, enc, s, end);
3216
      /* We are at the end of the final buffer, should we check for
3217
         XML_SUSPENDED, XML_FINISHED?
3218
      */
3219
8.80k
      if (startTagLevel == 0) {
3220
78
        *eventPP = end;
3221
78
        return XML_ERROR_NO_ELEMENTS;
3222
78
      }
3223
8.73k
      if (parser->m_tagLevel != startTagLevel) {
3224
60
        *eventPP = end;
3225
60
        return XML_ERROR_ASYNC_ENTITY;
3226
60
      }
3227
8.67k
      *nextPtr = end;
3228
8.67k
      return XML_ERROR_NONE;
3229
1.98M
    case XML_TOK_DATA_CHARS: {
3230
1.98M
      XML_CharacterDataHandler charDataHandler = parser->m_characterDataHandler;
3231
1.98M
      if (charDataHandler) {
3232
1.98M
        if (MUST_CONVERT(enc, s)) {
3233
334k
          for (;;) {
3234
334k
            ICHAR *dataPtr = (ICHAR *)parser->m_dataBuf;
3235
334k
            const enum XML_Convert_Result convert_res = XmlConvert(
3236
334k
                enc, &s, next, &dataPtr, (ICHAR *)parser->m_dataBufEnd);
3237
334k
            *eventEndPP = s;
3238
334k
            charDataHandler(parser->m_handlerArg, parser->m_dataBuf,
3239
334k
                            (int)(dataPtr - (ICHAR *)parser->m_dataBuf));
3240
334k
            if ((convert_res == XML_CONVERT_COMPLETED)
3241
334k
                || (convert_res == XML_CONVERT_INPUT_INCOMPLETE))
3242
318k
              break;
3243
16.6k
            *eventPP = s;
3244
16.6k
          }
3245
318k
        } else
3246
1.67M
          charDataHandler(parser->m_handlerArg, (const XML_Char *)s,
3247
1.67M
                          (int)((const XML_Char *)next - (const XML_Char *)s));
3248
1.98M
      } else if (parser->m_defaultHandler)
3249
0
        reportDefault(parser, enc, s, next);
3250
1.98M
    } break;
3251
45.6k
    case XML_TOK_PI:
3252
45.6k
      if (! reportProcessingInstruction(parser, enc, s, next))
3253
0
        return XML_ERROR_NO_MEMORY;
3254
45.6k
      break;
3255
45.6k
    case XML_TOK_COMMENT:
3256
1.38k
      if (! reportComment(parser, enc, s, next))
3257
0
        return XML_ERROR_NO_MEMORY;
3258
1.38k
      break;
3259
1.38k
    default:
3260
      /* All of the tokens produced by XmlContentTok() have their own
3261
       * explicit cases, so this default is not strictly necessary.
3262
       * However it is a useful safety net, so we retain the code and
3263
       * simply exclude it from the coverage tests.
3264
       *
3265
       * LCOV_EXCL_START
3266
       */
3267
0
      if (parser->m_defaultHandler)
3268
0
        reportDefault(parser, enc, s, next);
3269
0
      break;
3270
      /* LCOV_EXCL_STOP */
3271
7.54M
    }
3272
6.67M
    *eventPP = s = next;
3273
6.67M
    switch (parser->m_parsingStatus.parsing) {
3274
261
    case XML_SUSPENDED:
3275
261
      *nextPtr = next;
3276
261
      return XML_ERROR_NONE;
3277
11
    case XML_FINISHED:
3278
11
      return XML_ERROR_ABORTED;
3279
6.66M
    default:;
3280
6.67M
    }
3281
6.67M
  }
3282
  /* not reached */
3283
874k
}
3284
3285
/* This function does not call free() on the allocated memory, merely
3286
 * moving it to the parser's m_freeBindingList where it can be freed or
3287
 * reused as appropriate.
3288
 */
3289
static void
3290
327k
freeBindings(XML_Parser parser, BINDING *bindings) {
3291
329k
  while (bindings) {
3292
1.42k
    BINDING *b = bindings;
3293
3294
    /* m_startNamespaceDeclHandler will have been called for this
3295
     * binding in addBindings(), so call the end handler now.
3296
     */
3297
1.42k
    if (parser->m_endNamespaceDeclHandler)
3298
0
      parser->m_endNamespaceDeclHandler(parser->m_handlerArg, b->prefix->name);
3299
3300
1.42k
    bindings = bindings->nextTagBinding;
3301
1.42k
    b->nextTagBinding = parser->m_freeBindingList;
3302
1.42k
    parser->m_freeBindingList = b;
3303
1.42k
    b->prefix->binding = b->prevPrefixBinding;
3304
1.42k
  }
3305
327k
}
3306
3307
/* Precondition: all arguments must be non-NULL;
3308
   Purpose:
3309
   - normalize attributes
3310
   - check attributes for well-formedness
3311
   - generate namespace aware attribute names (URI, prefix)
3312
   - build list of attributes for startElementHandler
3313
   - default attributes
3314
   - process namespace declarations (check and report them)
3315
   - generate namespace aware element name (URI, prefix)
3316
*/
3317
static enum XML_Error
3318
storeAtts(XML_Parser parser, const ENCODING *enc, const char *attStr,
3319
          TAG_NAME *tagNamePtr, BINDING **bindingsPtr,
3320
2.39M
          enum XML_Account account) {
3321
2.39M
  DTD *const dtd = parser->m_dtd; /* save one level of indirection */
3322
2.39M
  ELEMENT_TYPE *elementType;
3323
2.39M
  int nDefaultAtts;
3324
2.39M
  const XML_Char **appAtts; /* the attribute list for the application */
3325
2.39M
  int attIndex = 0;
3326
2.39M
  int prefixLen;
3327
2.39M
  int i;
3328
2.39M
  int n;
3329
2.39M
  XML_Char *uri;
3330
2.39M
  int nPrefixes = 0;
3331
2.39M
  BINDING *binding;
3332
2.39M
  const XML_Char *localPart;
3333
3334
  /* lookup the element type name */
3335
2.39M
  elementType
3336
2.39M
      = (ELEMENT_TYPE *)lookup(parser, &dtd->elementTypes, tagNamePtr->str, 0);
3337
2.39M
  if (! elementType) {
3338
32.3k
    const XML_Char *name = poolCopyString(&dtd->pool, tagNamePtr->str);
3339
32.3k
    if (! name)
3340
0
      return XML_ERROR_NO_MEMORY;
3341
32.3k
    elementType = (ELEMENT_TYPE *)lookup(parser, &dtd->elementTypes, name,
3342
32.3k
                                         sizeof(ELEMENT_TYPE));
3343
32.3k
    if (! elementType)
3344
0
      return XML_ERROR_NO_MEMORY;
3345
32.3k
    if (parser->m_ns && ! setElementTypePrefix(parser, elementType))
3346
0
      return XML_ERROR_NO_MEMORY;
3347
32.3k
  }
3348
2.39M
  nDefaultAtts = elementType->nDefaultAtts;
3349
3350
  /* get the attributes from the tokenizer */
3351
2.39M
  n = XmlGetAttributes(enc, attStr, parser->m_attsSize, parser->m_atts);
3352
3353
  /* Detect and prevent integer overflow */
3354
2.39M
  if (n > INT_MAX - nDefaultAtts) {
3355
0
    return XML_ERROR_NO_MEMORY;
3356
0
  }
3357
3358
2.39M
  if (n + nDefaultAtts > parser->m_attsSize) {
3359
630
    int oldAttsSize = parser->m_attsSize;
3360
630
    ATTRIBUTE *temp;
3361
#ifdef XML_ATTR_INFO
3362
    XML_AttrInfo *temp2;
3363
#endif
3364
3365
    /* Detect and prevent integer overflow */
3366
630
    if ((nDefaultAtts > INT_MAX - INIT_ATTS_SIZE)
3367
630
        || (n > INT_MAX - (nDefaultAtts + INIT_ATTS_SIZE))) {
3368
0
      return XML_ERROR_NO_MEMORY;
3369
0
    }
3370
3371
630
    parser->m_attsSize = n + nDefaultAtts + INIT_ATTS_SIZE;
3372
3373
    /* Detect and prevent integer overflow.
3374
     * The preprocessor guard addresses the "always false" warning
3375
     * from -Wtype-limits on platforms where
3376
     * sizeof(unsigned int) < sizeof(size_t), e.g. on x86_64. */
3377
#if UINT_MAX >= SIZE_MAX
3378
    if ((unsigned)parser->m_attsSize > (size_t)(-1) / sizeof(ATTRIBUTE)) {
3379
      parser->m_attsSize = oldAttsSize;
3380
      return XML_ERROR_NO_MEMORY;
3381
    }
3382
#endif
3383
3384
630
    temp = (ATTRIBUTE *)REALLOC(parser, (void *)parser->m_atts,
3385
630
                                parser->m_attsSize * sizeof(ATTRIBUTE));
3386
630
    if (temp == NULL) {
3387
0
      parser->m_attsSize = oldAttsSize;
3388
0
      return XML_ERROR_NO_MEMORY;
3389
0
    }
3390
630
    parser->m_atts = temp;
3391
#ifdef XML_ATTR_INFO
3392
    /* Detect and prevent integer overflow.
3393
     * The preprocessor guard addresses the "always false" warning
3394
     * from -Wtype-limits on platforms where
3395
     * sizeof(unsigned int) < sizeof(size_t), e.g. on x86_64. */
3396
#  if UINT_MAX >= SIZE_MAX
3397
    if ((unsigned)parser->m_attsSize > (size_t)(-1) / sizeof(XML_AttrInfo)) {
3398
      parser->m_attsSize = oldAttsSize;
3399
      return XML_ERROR_NO_MEMORY;
3400
    }
3401
#  endif
3402
3403
    temp2 = (XML_AttrInfo *)REALLOC(parser, (void *)parser->m_attInfo,
3404
                                    parser->m_attsSize * sizeof(XML_AttrInfo));
3405
    if (temp2 == NULL) {
3406
      parser->m_attsSize = oldAttsSize;
3407
      return XML_ERROR_NO_MEMORY;
3408
    }
3409
    parser->m_attInfo = temp2;
3410
#endif
3411
630
    if (n > oldAttsSize)
3412
613
      XmlGetAttributes(enc, attStr, n, parser->m_atts);
3413
630
  }
3414
3415
2.39M
  appAtts = (const XML_Char **)parser->m_atts;
3416
2.44M
  for (i = 0; i < n; i++) {
3417
52.2k
    ATTRIBUTE *currAtt = &parser->m_atts[i];
3418
#ifdef XML_ATTR_INFO
3419
    XML_AttrInfo *currAttInfo = &parser->m_attInfo[i];
3420
#endif
3421
    /* add the name and value to the attribute list */
3422
52.2k
    ATTRIBUTE_ID *attId
3423
52.2k
        = getAttributeId(parser, enc, currAtt->name,
3424
52.2k
                         currAtt->name + XmlNameLength(enc, currAtt->name));
3425
52.2k
    if (! attId)
3426
0
      return XML_ERROR_NO_MEMORY;
3427
#ifdef XML_ATTR_INFO
3428
    currAttInfo->nameStart
3429
        = parser->m_parseEndByteIndex - (parser->m_parseEndPtr - currAtt->name);
3430
    currAttInfo->nameEnd
3431
        = currAttInfo->nameStart + XmlNameLength(enc, currAtt->name);
3432
    currAttInfo->valueStart = parser->m_parseEndByteIndex
3433
                              - (parser->m_parseEndPtr - currAtt->valuePtr);
3434
    currAttInfo->valueEnd = parser->m_parseEndByteIndex
3435
                            - (parser->m_parseEndPtr - currAtt->valueEnd);
3436
#endif
3437
    /* Detect duplicate attributes by their QNames. This does not work when
3438
       namespace processing is turned on and different prefixes for the same
3439
       namespace are used. For this case we have a check further down.
3440
    */
3441
52.2k
    if ((attId->name)[-1]) {
3442
642
      if (enc == parser->m_encoding)
3443
637
        parser->m_eventPtr = parser->m_atts[i].name;
3444
642
      return XML_ERROR_DUPLICATE_ATTRIBUTE;
3445
642
    }
3446
51.6k
    (attId->name)[-1] = 1;
3447
51.6k
    appAtts[attIndex++] = attId->name;
3448
51.6k
    if (! parser->m_atts[i].normalized) {
3449
12.8k
      enum XML_Error result;
3450
12.8k
      XML_Bool isCdata = XML_TRUE;
3451
3452
      /* figure out whether declared as other than CDATA */
3453
12.8k
      if (attId->maybeTokenized) {
3454
957
        int j;
3455
51.5k
        for (j = 0; j < nDefaultAtts; j++) {
3456
51.3k
          if (attId == elementType->defaultAtts[j].id) {
3457
737
            isCdata = elementType->defaultAtts[j].isCdata;
3458
737
            break;
3459
737
          }
3460
51.3k
        }
3461
957
      }
3462
3463
      /* normalize the attribute value */
3464
12.8k
      result = storeAttributeValue(
3465
12.8k
          parser, enc, isCdata, parser->m_atts[i].valuePtr,
3466
12.8k
          parser->m_atts[i].valueEnd, &parser->m_tempPool, account);
3467
12.8k
      if (result)
3468
199
        return result;
3469
12.6k
      appAtts[attIndex] = poolStart(&parser->m_tempPool);
3470
12.6k
      poolFinish(&parser->m_tempPool);
3471
38.8k
    } else {
3472
      /* the value did not need normalizing */
3473
38.8k
      appAtts[attIndex] = poolStoreString(&parser->m_tempPool, enc,
3474
38.8k
                                          parser->m_atts[i].valuePtr,
3475
38.8k
                                          parser->m_atts[i].valueEnd);
3476
38.8k
      if (appAtts[attIndex] == 0)
3477
0
        return XML_ERROR_NO_MEMORY;
3478
38.8k
      poolFinish(&parser->m_tempPool);
3479
38.8k
    }
3480
    /* handle prefixed attribute names */
3481
51.4k
    if (attId->prefix) {
3482
7.91k
      if (attId->xmlns) {
3483
        /* deal with namespace declarations here */
3484
4.28k
        enum XML_Error result = addBinding(parser, attId->prefix, attId,
3485
4.28k
                                           appAtts[attIndex], bindingsPtr);
3486
4.28k
        if (result)
3487
17
          return result;
3488
4.26k
        --attIndex;
3489
4.26k
      } else {
3490
        /* deal with other prefixed names later */
3491
3.63k
        attIndex++;
3492
3.63k
        nPrefixes++;
3493
3.63k
        (attId->name)[-1] = 2;
3494
3.63k
      }
3495
7.91k
    } else
3496
43.5k
      attIndex++;
3497
51.4k
  }
3498
3499
  /* set-up for XML_GetSpecifiedAttributeCount and XML_GetIdAttributeIndex */
3500
2.39M
  parser->m_nSpecifiedAtts = attIndex;
3501
2.39M
  if (elementType->idAtt && (elementType->idAtt->name)[-1]) {
3502
144
    for (i = 0; i < attIndex; i += 2)
3503
144
      if (appAtts[i] == elementType->idAtt->name) {
3504
67
        parser->m_idAttIndex = i;
3505
67
        break;
3506
67
      }
3507
67
  } else
3508
2.39M
    parser->m_idAttIndex = -1;
3509
3510
  /* do attribute defaulting */
3511
2.75M
  for (i = 0; i < nDefaultAtts; i++) {
3512
360k
    const DEFAULT_ATTRIBUTE *da = elementType->defaultAtts + i;
3513
360k
    if (! (da->id->name)[-1] && da->value) {
3514
283k
      if (da->id->prefix) {
3515
141k
        if (da->id->xmlns) {
3516
593
          enum XML_Error result = addBinding(parser, da->id->prefix, da->id,
3517
593
                                             da->value, bindingsPtr);
3518
593
          if (result)
3519
1
            return result;
3520
141k
        } else {
3521
141k
          (da->id->name)[-1] = 2;
3522
141k
          nPrefixes++;
3523
141k
          appAtts[attIndex++] = da->id->name;
3524
141k
          appAtts[attIndex++] = da->value;
3525
141k
        }
3526
142k
      } else {
3527
142k
        (da->id->name)[-1] = 1;
3528
142k
        appAtts[attIndex++] = da->id->name;
3529
142k
        appAtts[attIndex++] = da->value;
3530
142k
      }
3531
283k
    }
3532
360k
  }
3533
2.39M
  appAtts[attIndex] = 0;
3534
3535
  /* expand prefixed attribute names, check for duplicates,
3536
     and clear flags that say whether attributes were specified */
3537
2.39M
  i = 0;
3538
2.39M
  if (nPrefixes) {
3539
141k
    int j; /* hash table index */
3540
141k
    unsigned long version = parser->m_nsAttsVersion;
3541
3542
    /* Detect and prevent invalid shift */
3543
141k
    if (parser->m_nsAttsPower >= sizeof(unsigned int) * 8 /* bits per byte */) {
3544
0
      return XML_ERROR_NO_MEMORY;
3545
0
    }
3546
3547
141k
    unsigned int nsAttsSize = 1u << parser->m_nsAttsPower;
3548
141k
    unsigned char oldNsAttsPower = parser->m_nsAttsPower;
3549
    /* size of hash table must be at least 2 * (# of prefixed attributes) */
3550
141k
    if ((nPrefixes << 1)
3551
141k
        >> parser->m_nsAttsPower) { /* true for m_nsAttsPower = 0 */
3552
303
      NS_ATT *temp;
3553
      /* hash table size must also be a power of 2 and >= 8 */
3554
753
      while (nPrefixes >> parser->m_nsAttsPower++)
3555
450
        ;
3556
303
      if (parser->m_nsAttsPower < 3)
3557
175
        parser->m_nsAttsPower = 3;
3558
3559
      /* Detect and prevent invalid shift */
3560
303
      if (parser->m_nsAttsPower >= sizeof(nsAttsSize) * 8 /* bits per byte */) {
3561
        /* Restore actual size of memory in m_nsAtts */
3562
0
        parser->m_nsAttsPower = oldNsAttsPower;
3563
0
        return XML_ERROR_NO_MEMORY;
3564
0
      }
3565
3566
303
      nsAttsSize = 1u << parser->m_nsAttsPower;
3567
3568
      /* Detect and prevent integer overflow.
3569
       * The preprocessor guard addresses the "always false" warning
3570
       * from -Wtype-limits on platforms where
3571
       * sizeof(unsigned int) < sizeof(size_t), e.g. on x86_64. */
3572
#if UINT_MAX >= SIZE_MAX
3573
      if (nsAttsSize > (size_t)(-1) / sizeof(NS_ATT)) {
3574
        /* Restore actual size of memory in m_nsAtts */
3575
        parser->m_nsAttsPower = oldNsAttsPower;
3576
        return XML_ERROR_NO_MEMORY;
3577
      }
3578
#endif
3579
3580
303
      temp = (NS_ATT *)REALLOC(parser, parser->m_nsAtts,
3581
303
                               nsAttsSize * sizeof(NS_ATT));
3582
303
      if (! temp) {
3583
        /* Restore actual size of memory in m_nsAtts */
3584
0
        parser->m_nsAttsPower = oldNsAttsPower;
3585
0
        return XML_ERROR_NO_MEMORY;
3586
0
      }
3587
303
      parser->m_nsAtts = temp;
3588
303
      version = 0; /* force re-initialization of m_nsAtts hash table */
3589
303
    }
3590
    /* using a version flag saves us from initializing m_nsAtts every time */
3591
141k
    if (! version) { /* initialize version flags when version wraps around */
3592
303
      version = INIT_ATTS_VERSION;
3593
3.41k
      for (j = nsAttsSize; j != 0;)
3594
3.11k
        parser->m_nsAtts[--j].version = version;
3595
303
    }
3596
141k
    parser->m_nsAttsVersion = --version;
3597
3598
    /* expand prefixed names and check for duplicates */
3599
145k
    for (; i < attIndex; i += 2) {
3600
145k
      const XML_Char *s = appAtts[i];
3601
145k
      if (s[-1] == 2) { /* prefixed */
3602
144k
        ATTRIBUTE_ID *id;
3603
144k
        const BINDING *b;
3604
144k
        unsigned long uriHash;
3605
144k
        struct siphash sip_state;
3606
144k
        struct sipkey sip_key;
3607
3608
144k
        copy_salt_to_sipkey(parser, &sip_key);
3609
144k
        sip24_init(&sip_state, &sip_key);
3610
3611
144k
        ((XML_Char *)s)[-1] = 0; /* clear flag */
3612
144k
        id = (ATTRIBUTE_ID *)lookup(parser, &dtd->attributeIds, s, 0);
3613
144k
        if (! id || ! id->prefix) {
3614
          /* This code is walking through the appAtts array, dealing
3615
           * with (in this case) a prefixed attribute name.  To be in
3616
           * the array, the attribute must have already been bound, so
3617
           * has to have passed through the hash table lookup once
3618
           * already.  That implies that an entry for it already
3619
           * exists, so the lookup above will return a pointer to
3620
           * already allocated memory.  There is no opportunaity for
3621
           * the allocator to fail, so the condition above cannot be
3622
           * fulfilled.
3623
           *
3624
           * Since it is difficult to be certain that the above
3625
           * analysis is complete, we retain the test and merely
3626
           * remove the code from coverage tests.
3627
           */
3628
0
          return XML_ERROR_NO_MEMORY; /* LCOV_EXCL_LINE */
3629
0
        }
3630
144k
        b = id->prefix->binding;
3631
144k
        if (! b)
3632
55
          return XML_ERROR_UNBOUND_PREFIX;
3633
3634
5.77M
        for (j = 0; j < b->uriLen; j++) {
3635
5.63M
          const XML_Char c = b->uri[j];
3636
5.63M
          if (! poolAppendChar(&parser->m_tempPool, c))
3637
0
            return XML_ERROR_NO_MEMORY;
3638
5.63M
        }
3639
3640
144k
        sip24_update(&sip_state, b->uri, b->uriLen * sizeof(XML_Char));
3641
3642
578k
        while (*s++ != XML_T(ASCII_COLON))
3643
433k
          ;
3644
3645
144k
        sip24_update(&sip_state, s, keylen(s) * sizeof(XML_Char));
3646
3647
815k
        do { /* copies null terminator */
3648
815k
          if (! poolAppendChar(&parser->m_tempPool, *s))
3649
0
            return XML_ERROR_NO_MEMORY;
3650
815k
        } while (*s++);
3651
3652
144k
        uriHash = (unsigned long)sip24_final(&sip_state);
3653
3654
144k
        { /* Check hash table for duplicate of expanded name (uriName).
3655
             Derived from code in lookup(parser, HASH_TABLE *table, ...).
3656
          */
3657
144k
          unsigned char step = 0;
3658
144k
          unsigned long mask = nsAttsSize - 1;
3659
144k
          j = uriHash & mask; /* index into hash table */
3660
145k
          while (parser->m_nsAtts[j].version == version) {
3661
            /* for speed we compare stored hash values first */
3662
1.34k
            if (uriHash == parser->m_nsAtts[j].hash) {
3663
1
              const XML_Char *s1 = poolStart(&parser->m_tempPool);
3664
1
              const XML_Char *s2 = parser->m_nsAtts[j].uriName;
3665
              /* s1 is null terminated, but not s2 */
3666
5
              for (; *s1 == *s2 && *s1 != 0; s1++, s2++)
3667
4
                ;
3668
1
              if (*s1 == 0)
3669
1
                return XML_ERROR_DUPLICATE_ATTRIBUTE;
3670
1
            }
3671
1.34k
            if (! step)
3672
916
              step = PROBE_STEP(uriHash, mask, parser->m_nsAttsPower);
3673
1.34k
            j < step ? (j += nsAttsSize - step) : (j -= step);
3674
1.34k
          }
3675
144k
        }
3676
3677
144k
        if (parser->m_ns_triplets) { /* append namespace separator and prefix */
3678
0
          parser->m_tempPool.ptr[-1] = parser->m_namespaceSeparator;
3679
0
          s = b->prefix->name;
3680
0
          do {
3681
0
            if (! poolAppendChar(&parser->m_tempPool, *s))
3682
0
              return XML_ERROR_NO_MEMORY;
3683
0
          } while (*s++);
3684
0
        }
3685
3686
        /* store expanded name in attribute list */
3687
144k
        s = poolStart(&parser->m_tempPool);
3688
144k
        poolFinish(&parser->m_tempPool);
3689
144k
        appAtts[i] = s;
3690
3691
        /* fill empty slot with new version, uriName and hash value */
3692
144k
        parser->m_nsAtts[j].version = version;
3693
144k
        parser->m_nsAtts[j].hash = uriHash;
3694
144k
        parser->m_nsAtts[j].uriName = s;
3695
3696
144k
        if (! --nPrefixes) {
3697
141k
          i += 2;
3698
141k
          break;
3699
141k
        }
3700
144k
      } else                     /* not prefixed */
3701
638
        ((XML_Char *)s)[-1] = 0; /* clear flag */
3702
145k
    }
3703
141k
  }
3704
  /* clear flags for the remaining attributes */
3705
2.57M
  for (; i < attIndex; i += 2)
3706
183k
    ((XML_Char *)(appAtts[i]))[-1] = 0;
3707
2.39M
  for (binding = *bindingsPtr; binding; binding = binding->nextTagBinding)
3708
4.79k
    binding->attId->name[-1] = 0;
3709
3710
2.39M
  if (! parser->m_ns)
3711
2.06M
    return XML_ERROR_NONE;
3712
3713
  /* expand the element type name */
3714
321k
  if (elementType->prefix) {
3715
3.04k
    binding = elementType->prefix->binding;
3716
3.04k
    if (! binding)
3717
41
      return XML_ERROR_UNBOUND_PREFIX;
3718
3.00k
    localPart = tagNamePtr->str;
3719
12.0k
    while (*localPart++ != XML_T(ASCII_COLON))
3720
9.02k
      ;
3721
318k
  } else if (dtd->defaultPrefix.binding) {
3722
132k
    binding = dtd->defaultPrefix.binding;
3723
132k
    localPart = tagNamePtr->str;
3724
132k
  } else
3725
186k
    return XML_ERROR_NONE;
3726
135k
  prefixLen = 0;
3727
135k
  if (parser->m_ns_triplets && binding->prefix->name) {
3728
0
    for (; binding->prefix->name[prefixLen++];)
3729
0
      ; /* prefixLen includes null terminator */
3730
0
  }
3731
135k
  tagNamePtr->localPart = localPart;
3732
135k
  tagNamePtr->uriLen = binding->uriLen;
3733
135k
  tagNamePtr->prefix = binding->prefix->name;
3734
135k
  tagNamePtr->prefixLen = prefixLen;
3735
7.22M
  for (i = 0; localPart[i++];)
3736
7.09M
    ; /* i includes null terminator */
3737
3738
  /* Detect and prevent integer overflow */
3739
135k
  if (binding->uriLen > INT_MAX - prefixLen
3740
135k
      || i > INT_MAX - (binding->uriLen + prefixLen)) {
3741
0
    return XML_ERROR_NO_MEMORY;
3742
0
  }
3743
3744
135k
  n = i + binding->uriLen + prefixLen;
3745
135k
  if (n > binding->uriAlloc) {
3746
506
    TAG *p;
3747
3748
    /* Detect and prevent integer overflow */
3749
506
    if (n > INT_MAX - EXPAND_SPARE) {
3750
0
      return XML_ERROR_NO_MEMORY;
3751
0
    }
3752
    /* Detect and prevent integer overflow.
3753
     * The preprocessor guard addresses the "always false" warning
3754
     * from -Wtype-limits on platforms where
3755
     * sizeof(unsigned int) < sizeof(size_t), e.g. on x86_64. */
3756
#if UINT_MAX >= SIZE_MAX
3757
    if ((unsigned)(n + EXPAND_SPARE) > (size_t)(-1) / sizeof(XML_Char)) {
3758
      return XML_ERROR_NO_MEMORY;
3759
    }
3760
#endif
3761
3762
506
    uri = (XML_Char *)MALLOC(parser, (n + EXPAND_SPARE) * sizeof(XML_Char));
3763
506
    if (! uri)
3764
0
      return XML_ERROR_NO_MEMORY;
3765
506
    binding->uriAlloc = n + EXPAND_SPARE;
3766
506
    memcpy(uri, binding->uri, binding->uriLen * sizeof(XML_Char));
3767
582k
    for (p = parser->m_tagStack; p; p = p->parent)
3768
581k
      if (p->name.str == binding->uri)
3769
1.28k
        p->name.str = uri;
3770
506
    FREE(parser, binding->uri);
3771
506
    binding->uri = uri;
3772
506
  }
3773
  /* if m_namespaceSeparator != '\0' then uri includes it already */
3774
135k
  uri = binding->uri + binding->uriLen;
3775
135k
  memcpy(uri, localPart, i * sizeof(XML_Char));
3776
  /* we always have a namespace separator between localPart and prefix */
3777
135k
  if (prefixLen) {
3778
0
    uri += i - 1;
3779
0
    *uri = parser->m_namespaceSeparator; /* replace null terminator */
3780
0
    memcpy(uri + 1, binding->prefix->name, prefixLen * sizeof(XML_Char));
3781
0
  }
3782
135k
  tagNamePtr->str = binding->uri;
3783
135k
  return XML_ERROR_NONE;
3784
135k
}
3785
3786
static XML_Bool
3787
861
is_rfc3986_uri_char(XML_Char candidate) {
3788
  // For the RFC 3986 ANBF grammar see
3789
  // https://datatracker.ietf.org/doc/html/rfc3986#appendix-A
3790
3791
861
  switch (candidate) {
3792
  // From rule "ALPHA" (uppercase half)
3793
0
  case 'A':
3794
0
  case 'B':
3795
0
  case 'C':
3796
0
  case 'D':
3797
0
  case 'E':
3798
0
  case 'F':
3799
0
  case 'G':
3800
0
  case 'H':
3801
0
  case 'I':
3802
0
  case 'J':
3803
0
  case 'K':
3804
0
  case 'L':
3805
0
  case 'M':
3806
0
  case 'N':
3807
0
  case 'O':
3808
0
  case 'P':
3809
0
  case 'Q':
3810
0
  case 'R':
3811
0
  case 'S':
3812
0
  case 'T':
3813
0
  case 'U':
3814
0
  case 'V':
3815
0
  case 'W':
3816
0
  case 'X':
3817
0
  case 'Y':
3818
0
  case 'Z':
3819
3820
  // From rule "ALPHA" (lowercase half)
3821
0
  case 'a':
3822
0
  case 'b':
3823
0
  case 'c':
3824
0
  case 'd':
3825
0
  case 'e':
3826
0
  case 'f':
3827
0
  case 'g':
3828
0
  case 'h':
3829
0
  case 'i':
3830
0
  case 'j':
3831
0
  case 'k':
3832
0
  case 'l':
3833
0
  case 'm':
3834
0
  case 'n':
3835
0
  case 'o':
3836
0
  case 'p':
3837
0
  case 'q':
3838
0
  case 'r':
3839
0
  case 's':
3840
0
  case 't':
3841
0
  case 'u':
3842
0
  case 'v':
3843
0
  case 'w':
3844
0
  case 'x':
3845
0
  case 'y':
3846
0
  case 'z':
3847
3848
  // From rule "DIGIT"
3849
0
  case '0':
3850
0
  case '1':
3851
0
  case '2':
3852
0
  case '3':
3853
0
  case '4':
3854
0
  case '5':
3855
0
  case '6':
3856
0
  case '7':
3857
0
  case '8':
3858
0
  case '9':
3859
3860
  // From rule "pct-encoded"
3861
0
  case '%':
3862
3863
  // From rule "unreserved"
3864
0
  case '-':
3865
0
  case '.':
3866
0
  case '_':
3867
0
  case '~':
3868
3869
  // From rule "gen-delims"
3870
0
  case ':':
3871
0
  case '/':
3872
0
  case '?':
3873
0
  case '#':
3874
0
  case '[':
3875
0
  case ']':
3876
0
  case '@':
3877
3878
  // From rule "sub-delims"
3879
861
  case '!':
3880
861
  case '$':
3881
861
  case '&':
3882
861
  case '\'':
3883
861
  case '(':
3884
861
  case ')':
3885
861
  case '*':
3886
861
  case '+':
3887
861
  case ',':
3888
861
  case ';':
3889
861
  case '=':
3890
861
    return XML_TRUE;
3891
3892
0
  default:
3893
0
    return XML_FALSE;
3894
861
  }
3895
861
}
3896
3897
/* addBinding() overwrites the value of prefix->binding without checking.
3898
   Therefore one must keep track of the old value outside of addBinding().
3899
*/
3900
static enum XML_Error
3901
addBinding(XML_Parser parser, PREFIX *prefix, const ATTRIBUTE_ID *attId,
3902
25.9k
           const XML_Char *uri, BINDING **bindingsPtr) {
3903
  // "http://www.w3.org/XML/1998/namespace"
3904
25.9k
  static const XML_Char xmlNamespace[]
3905
25.9k
      = {ASCII_h,      ASCII_t,     ASCII_t,     ASCII_p,      ASCII_COLON,
3906
25.9k
         ASCII_SLASH,  ASCII_SLASH, ASCII_w,     ASCII_w,      ASCII_w,
3907
25.9k
         ASCII_PERIOD, ASCII_w,     ASCII_3,     ASCII_PERIOD, ASCII_o,
3908
25.9k
         ASCII_r,      ASCII_g,     ASCII_SLASH, ASCII_X,      ASCII_M,
3909
25.9k
         ASCII_L,      ASCII_SLASH, ASCII_1,     ASCII_9,      ASCII_9,
3910
25.9k
         ASCII_8,      ASCII_SLASH, ASCII_n,     ASCII_a,      ASCII_m,
3911
25.9k
         ASCII_e,      ASCII_s,     ASCII_p,     ASCII_a,      ASCII_c,
3912
25.9k
         ASCII_e,      '\0'};
3913
25.9k
  static const int xmlLen = (int)sizeof(xmlNamespace) / sizeof(XML_Char) - 1;
3914
  // "http://www.w3.org/2000/xmlns/"
3915
25.9k
  static const XML_Char xmlnsNamespace[]
3916
25.9k
      = {ASCII_h,     ASCII_t,      ASCII_t, ASCII_p, ASCII_COLON,  ASCII_SLASH,
3917
25.9k
         ASCII_SLASH, ASCII_w,      ASCII_w, ASCII_w, ASCII_PERIOD, ASCII_w,
3918
25.9k
         ASCII_3,     ASCII_PERIOD, ASCII_o, ASCII_r, ASCII_g,      ASCII_SLASH,
3919
25.9k
         ASCII_2,     ASCII_0,      ASCII_0, ASCII_0, ASCII_SLASH,  ASCII_x,
3920
25.9k
         ASCII_m,     ASCII_l,      ASCII_n, ASCII_s, ASCII_SLASH,  '\0'};
3921
25.9k
  static const int xmlnsLen
3922
25.9k
      = (int)sizeof(xmlnsNamespace) / sizeof(XML_Char) - 1;
3923
3924
25.9k
  XML_Bool mustBeXML = XML_FALSE;
3925
25.9k
  XML_Bool isXML = XML_TRUE;
3926
25.9k
  XML_Bool isXMLNS = XML_TRUE;
3927
3928
25.9k
  BINDING *b;
3929
25.9k
  int len;
3930
3931
  /* empty URI is only valid for default namespace per XML NS 1.0 (not 1.1) */
3932
25.9k
  if (*uri == XML_T('\0') && prefix->name)
3933
2
    return XML_ERROR_UNDECLARING_PREFIX;
3934
3935
25.9k
  if (prefix->name && prefix->name[0] == XML_T(ASCII_x)
3936
25.9k
      && prefix->name[1] == XML_T(ASCII_m)
3937
25.9k
      && prefix->name[2] == XML_T(ASCII_l)) {
3938
    /* Not allowed to bind xmlns */
3939
21.4k
    if (prefix->name[3] == XML_T(ASCII_n) && prefix->name[4] == XML_T(ASCII_s)
3940
21.4k
        && prefix->name[5] == XML_T('\0'))
3941
1
      return XML_ERROR_RESERVED_PREFIX_XMLNS;
3942
3943
21.4k
    if (prefix->name[3] == XML_T('\0'))
3944
21.1k
      mustBeXML = XML_TRUE;
3945
21.4k
  }
3946
3947
17.5M
  for (len = 0; uri[len]; len++) {
3948
17.5M
    if (isXML && (len > xmlLen || uri[len] != xmlNamespace[len]))
3949
4.30k
      isXML = XML_FALSE;
3950
3951
17.5M
    if (! mustBeXML && isXMLNS
3952
17.5M
        && (len > xmlnsLen || uri[len] != xmlnsNamespace[len]))
3953
4.31k
      isXMLNS = XML_FALSE;
3954
3955
    // NOTE: While Expat does not validate namespace URIs against RFC 3986
3956
    //       today (and is not REQUIRED to do so with regard to the XML 1.0
3957
    //       namespaces specification) we have to at least make sure, that
3958
    //       the application on top of Expat (that is likely splitting expanded
3959
    //       element names ("qualified names") of form
3960
    //       "[uri sep] local [sep prefix] '\0'" back into 1, 2 or 3 pieces
3961
    //       in its element handler code) cannot be confused by an attacker
3962
    //       putting additional namespace separator characters into namespace
3963
    //       declarations.  That would be ambiguous and not to be expected.
3964
    //
3965
    //       While the HTML API docs of function XML_ParserCreateNS have been
3966
    //       advising against use of a namespace separator character that can
3967
    //       appear in a URI for >20 years now, some widespread applications
3968
    //       are using URI characters (':' (colon) in particular) for a
3969
    //       namespace separator, in practice.  To keep these applications
3970
    //       functional, we only reject namespaces URIs containing the
3971
    //       application-chosen namespace separator if the chosen separator
3972
    //       is a non-URI character with regard to RFC 3986.
3973
17.5M
    if (parser->m_ns && (uri[len] == parser->m_namespaceSeparator)
3974
17.5M
        && ! is_rfc3986_uri_char(uri[len])) {
3975
0
      return XML_ERROR_SYNTAX;
3976
0
    }
3977
17.5M
  }
3978
25.9k
  isXML = isXML && len == xmlLen;
3979
25.9k
  isXMLNS = isXMLNS && len == xmlnsLen;
3980
3981
25.9k
  if (mustBeXML != isXML)
3982
14
    return mustBeXML ? XML_ERROR_RESERVED_PREFIX_XML
3983
14
                     : XML_ERROR_RESERVED_NAMESPACE_URI;
3984
3985
25.9k
  if (isXMLNS)
3986
1
    return XML_ERROR_RESERVED_NAMESPACE_URI;
3987
3988
25.9k
  if (parser->m_namespaceSeparator)
3989
25.9k
    len++;
3990
25.9k
  if (parser->m_freeBindingList) {
3991
1.98k
    b = parser->m_freeBindingList;
3992
1.98k
    if (len > b->uriAlloc) {
3993
      /* Detect and prevent integer overflow */
3994
114
      if (len > INT_MAX - EXPAND_SPARE) {
3995
0
        return XML_ERROR_NO_MEMORY;
3996
0
      }
3997
3998
      /* Detect and prevent integer overflow.
3999
       * The preprocessor guard addresses the "always false" warning
4000
       * from -Wtype-limits on platforms where
4001
       * sizeof(unsigned int) < sizeof(size_t), e.g. on x86_64. */
4002
#if UINT_MAX >= SIZE_MAX
4003
      if ((unsigned)(len + EXPAND_SPARE) > (size_t)(-1) / sizeof(XML_Char)) {
4004
        return XML_ERROR_NO_MEMORY;
4005
      }
4006
#endif
4007
4008
114
      XML_Char *temp = (XML_Char *)REALLOC(
4009
114
          parser, b->uri, sizeof(XML_Char) * (len + EXPAND_SPARE));
4010
114
      if (temp == NULL)
4011
0
        return XML_ERROR_NO_MEMORY;
4012
114
      b->uri = temp;
4013
114
      b->uriAlloc = len + EXPAND_SPARE;
4014
114
    }
4015
1.98k
    parser->m_freeBindingList = b->nextTagBinding;
4016
23.9k
  } else {
4017
23.9k
    b = (BINDING *)MALLOC(parser, sizeof(BINDING));
4018
23.9k
    if (! b)
4019
0
      return XML_ERROR_NO_MEMORY;
4020
4021
    /* Detect and prevent integer overflow */
4022
23.9k
    if (len > INT_MAX - EXPAND_SPARE) {
4023
0
      return XML_ERROR_NO_MEMORY;
4024
0
    }
4025
    /* Detect and prevent integer overflow.
4026
     * The preprocessor guard addresses the "always false" warning
4027
     * from -Wtype-limits on platforms where
4028
     * sizeof(unsigned int) < sizeof(size_t), e.g. on x86_64. */
4029
#if UINT_MAX >= SIZE_MAX
4030
    if ((unsigned)(len + EXPAND_SPARE) > (size_t)(-1) / sizeof(XML_Char)) {
4031
      return XML_ERROR_NO_MEMORY;
4032
    }
4033
#endif
4034
4035
23.9k
    b->uri
4036
23.9k
        = (XML_Char *)MALLOC(parser, sizeof(XML_Char) * (len + EXPAND_SPARE));
4037
23.9k
    if (! b->uri) {
4038
0
      FREE(parser, b);
4039
0
      return XML_ERROR_NO_MEMORY;
4040
0
    }
4041
23.9k
    b->uriAlloc = len + EXPAND_SPARE;
4042
23.9k
  }
4043
25.9k
  b->uriLen = len;
4044
25.9k
  memcpy(b->uri, uri, len * sizeof(XML_Char));
4045
25.9k
  if (parser->m_namespaceSeparator)
4046
25.9k
    b->uri[len - 1] = parser->m_namespaceSeparator;
4047
25.9k
  b->prefix = prefix;
4048
25.9k
  b->attId = attId;
4049
25.9k
  b->prevPrefixBinding = prefix->binding;
4050
  /* NULL binding when default namespace undeclared */
4051
25.9k
  if (*uri == XML_T('\0') && prefix == &parser->m_dtd->defaultPrefix)
4052
459
    prefix->binding = NULL;
4053
25.5k
  else
4054
25.5k
    prefix->binding = b;
4055
25.9k
  b->nextTagBinding = *bindingsPtr;
4056
25.9k
  *bindingsPtr = b;
4057
  /* if attId == NULL then we are not starting a namespace scope */
4058
25.9k
  if (attId && parser->m_startNamespaceDeclHandler)
4059
0
    parser->m_startNamespaceDeclHandler(parser->m_handlerArg, prefix->name,
4060
0
                                        prefix->binding ? uri : 0);
4061
25.9k
  return XML_ERROR_NONE;
4062
25.9k
}
4063
4064
/* The idea here is to avoid using stack for each CDATA section when
4065
   the whole file is parsed with one call.
4066
*/
4067
static enum XML_Error PTRCALL
4068
cdataSectionProcessor(XML_Parser parser, const char *start, const char *end,
4069
1.09k
                      const char **endPtr) {
4070
1.09k
  enum XML_Error result = doCdataSection(
4071
1.09k
      parser, parser->m_encoding, &start, end, endPtr,
4072
1.09k
      (XML_Bool)! parser->m_parsingStatus.finalBuffer, XML_ACCOUNT_DIRECT);
4073
1.09k
  if (result != XML_ERROR_NONE)
4074
1.07k
    return result;
4075
23
  if (start) {
4076
16
    if (parser->m_parentParser) { /* we are parsing an external entity */
4077
6
      parser->m_processor = externalEntityContentProcessor;
4078
6
      return externalEntityContentProcessor(parser, start, end, endPtr);
4079
10
    } else {
4080
10
      parser->m_processor = contentProcessor;
4081
10
      return contentProcessor(parser, start, end, endPtr);
4082
10
    }
4083
16
  }
4084
7
  return result;
4085
23
}
4086
4087
/* startPtr gets set to non-null if the section is closed, and to null if
4088
   the section is not yet closed.
4089
*/
4090
static enum XML_Error
4091
doCdataSection(XML_Parser parser, const ENCODING *enc, const char **startPtr,
4092
               const char *end, const char **nextPtr, XML_Bool haveMore,
4093
472k
               enum XML_Account account) {
4094
472k
  const char *s = *startPtr;
4095
472k
  const char **eventPP;
4096
472k
  const char **eventEndPP;
4097
472k
  if (enc == parser->m_encoding) {
4098
3.49k
    eventPP = &parser->m_eventPtr;
4099
3.49k
    *eventPP = s;
4100
3.49k
    eventEndPP = &parser->m_eventEndPtr;
4101
468k
  } else {
4102
468k
    eventPP = &(parser->m_openInternalEntities->internalEventPtr);
4103
468k
    eventEndPP = &(parser->m_openInternalEntities->internalEventEndPtr);
4104
468k
  }
4105
472k
  *eventPP = s;
4106
472k
  *startPtr = NULL;
4107
4108
1.96M
  for (;;) {
4109
1.96M
    const char *next = s; /* in case of XML_TOK_NONE or XML_TOK_PARTIAL */
4110
1.96M
    int tok = XmlCdataSectionTok(enc, s, end, &next);
4111
1.96M
#if XML_GE == 1
4112
1.96M
    if (! accountingDiffTolerated(parser, tok, s, next, __LINE__, account)) {
4113
3
      accountingOnAbort(parser);
4114
3
      return XML_ERROR_AMPLIFICATION_LIMIT_BREACH;
4115
3
    }
4116
#else
4117
    UNUSED_P(account);
4118
#endif
4119
1.96M
    *eventEndPP = next;
4120
1.96M
    switch (tok) {
4121
469k
    case XML_TOK_CDATA_SECT_CLOSE:
4122
469k
      if (parser->m_endCdataSectionHandler)
4123
0
        parser->m_endCdataSectionHandler(parser->m_handlerArg);
4124
      /* BEGIN disabled code */
4125
      /* see comment under XML_TOK_CDATA_SECT_OPEN */
4126
469k
      else if ((0) && parser->m_characterDataHandler)
4127
0
        parser->m_characterDataHandler(parser->m_handlerArg, parser->m_dataBuf,
4128
0
                                       0);
4129
      /* END disabled code */
4130
469k
      else if (parser->m_defaultHandler)
4131
0
        reportDefault(parser, enc, s, next);
4132
469k
      *startPtr = next;
4133
469k
      *nextPtr = next;
4134
469k
      if (parser->m_parsingStatus.parsing == XML_FINISHED)
4135
0
        return XML_ERROR_ABORTED;
4136
469k
      else
4137
469k
        return XML_ERROR_NONE;
4138
1.29M
    case XML_TOK_DATA_NEWLINE:
4139
1.29M
      if (parser->m_characterDataHandler) {
4140
1.29M
        XML_Char c = 0xA;
4141
1.29M
        parser->m_characterDataHandler(parser->m_handlerArg, &c, 1);
4142
1.29M
      } else if (parser->m_defaultHandler)
4143
0
        reportDefault(parser, enc, s, next);
4144
1.29M
      break;
4145
203k
    case XML_TOK_DATA_CHARS: {
4146
203k
      XML_CharacterDataHandler charDataHandler = parser->m_characterDataHandler;
4147
203k
      if (charDataHandler) {
4148
203k
        if (MUST_CONVERT(enc, s)) {
4149
96.7k
          for (;;) {
4150
96.7k
            ICHAR *dataPtr = (ICHAR *)parser->m_dataBuf;
4151
96.7k
            const enum XML_Convert_Result convert_res = XmlConvert(
4152
96.7k
                enc, &s, next, &dataPtr, (ICHAR *)parser->m_dataBufEnd);
4153
96.7k
            *eventEndPP = next;
4154
96.7k
            charDataHandler(parser->m_handlerArg, parser->m_dataBuf,
4155
96.7k
                            (int)(dataPtr - (ICHAR *)parser->m_dataBuf));
4156
96.7k
            if ((convert_res == XML_CONVERT_COMPLETED)
4157
96.7k
                || (convert_res == XML_CONVERT_INPUT_INCOMPLETE))
4158
89.4k
              break;
4159
7.31k
            *eventPP = s;
4160
7.31k
          }
4161
89.4k
        } else
4162
114k
          charDataHandler(parser->m_handlerArg, (const XML_Char *)s,
4163
114k
                          (int)((const XML_Char *)next - (const XML_Char *)s));
4164
203k
      } else if (parser->m_defaultHandler)
4165
0
        reportDefault(parser, enc, s, next);
4166
203k
    } break;
4167
339
    case XML_TOK_INVALID:
4168
339
      *eventPP = next;
4169
339
      return XML_ERROR_INVALID_TOKEN;
4170
339
    case XML_TOK_PARTIAL_CHAR:
4171
339
      if (haveMore) {
4172
183
        *nextPtr = s;
4173
183
        return XML_ERROR_NONE;
4174
183
      }
4175
156
      return XML_ERROR_PARTIAL_CHAR;
4176
528
    case XML_TOK_PARTIAL:
4177
1.91k
    case XML_TOK_NONE:
4178
1.91k
      if (haveMore) {
4179
910
        *nextPtr = s;
4180
910
        return XML_ERROR_NONE;
4181
910
      }
4182
1.00k
      return XML_ERROR_UNCLOSED_CDATA_SECTION;
4183
0
    default:
4184
      /* Every token returned by XmlCdataSectionTok() has its own
4185
       * explicit case, so this default case will never be executed.
4186
       * We retain it as a safety net and exclude it from the coverage
4187
       * statistics.
4188
       *
4189
       * LCOV_EXCL_START
4190
       */
4191
0
      *eventPP = next;
4192
0
      return XML_ERROR_UNEXPECTED_STATE;
4193
      /* LCOV_EXCL_STOP */
4194
1.96M
    }
4195
4196
1.49M
    *eventPP = s = next;
4197
1.49M
    switch (parser->m_parsingStatus.parsing) {
4198
32
    case XML_SUSPENDED:
4199
32
      *nextPtr = next;
4200
32
      return XML_ERROR_NONE;
4201
37
    case XML_FINISHED:
4202
37
      return XML_ERROR_ABORTED;
4203
1.49M
    default:;
4204
1.49M
    }
4205
1.49M
  }
4206
  /* not reached */
4207
472k
}
4208
4209
#ifdef XML_DTD
4210
4211
/* The idea here is to avoid using stack for each IGNORE section when
4212
   the whole file is parsed with one call.
4213
*/
4214
static enum XML_Error PTRCALL
4215
ignoreSectionProcessor(XML_Parser parser, const char *start, const char *end,
4216
505
                       const char **endPtr) {
4217
505
  enum XML_Error result
4218
505
      = doIgnoreSection(parser, parser->m_encoding, &start, end, endPtr,
4219
505
                        (XML_Bool)! parser->m_parsingStatus.finalBuffer);
4220
505
  if (result != XML_ERROR_NONE)
4221
498
    return result;
4222
7
  if (start) {
4223
7
    parser->m_processor = prologProcessor;
4224
7
    return prologProcessor(parser, start, end, endPtr);
4225
7
  }
4226
0
  return result;
4227
7
}
4228
4229
/* startPtr gets set to non-null is the section is closed, and to null
4230
   if the section is not yet closed.
4231
*/
4232
static enum XML_Error
4233
doIgnoreSection(XML_Parser parser, const ENCODING *enc, const char **startPtr,
4234
1.85k
                const char *end, const char **nextPtr, XML_Bool haveMore) {
4235
1.85k
  const char *next = *startPtr; /* in case of XML_TOK_NONE or XML_TOK_PARTIAL */
4236
1.85k
  int tok;
4237
1.85k
  const char *s = *startPtr;
4238
1.85k
  const char **eventPP;
4239
1.85k
  const char **eventEndPP;
4240
1.85k
  if (enc == parser->m_encoding) {
4241
1.85k
    eventPP = &parser->m_eventPtr;
4242
1.85k
    *eventPP = s;
4243
1.85k
    eventEndPP = &parser->m_eventEndPtr;
4244
1.85k
  } else {
4245
    /* It's not entirely clear, but it seems the following two lines
4246
     * of code cannot be executed.  The only occasions on which 'enc'
4247
     * is not 'encoding' are when this function is called
4248
     * from the internal entity processing, and IGNORE sections are an
4249
     * error in internal entities.
4250
     *
4251
     * Since it really isn't clear that this is true, we keep the code
4252
     * and just remove it from our coverage tests.
4253
     *
4254
     * LCOV_EXCL_START
4255
     */
4256
0
    eventPP = &(parser->m_openInternalEntities->internalEventPtr);
4257
0
    eventEndPP = &(parser->m_openInternalEntities->internalEventEndPtr);
4258
    /* LCOV_EXCL_STOP */
4259
0
  }
4260
1.85k
  *eventPP = s;
4261
1.85k
  *startPtr = NULL;
4262
1.85k
  tok = XmlIgnoreSectionTok(enc, s, end, &next);
4263
1.85k
#  if XML_GE == 1
4264
1.85k
  if (! accountingDiffTolerated(parser, tok, s, next, __LINE__,
4265
1.85k
                                XML_ACCOUNT_DIRECT)) {
4266
0
    accountingOnAbort(parser);
4267
0
    return XML_ERROR_AMPLIFICATION_LIMIT_BREACH;
4268
0
  }
4269
1.85k
#  endif
4270
1.85k
  *eventEndPP = next;
4271
1.85k
  switch (tok) {
4272
773
  case XML_TOK_IGNORE_SECT:
4273
773
    if (parser->m_defaultHandler)
4274
0
      reportDefault(parser, enc, s, next);
4275
773
    *startPtr = next;
4276
773
    *nextPtr = next;
4277
773
    if (parser->m_parsingStatus.parsing == XML_FINISHED)
4278
0
      return XML_ERROR_ABORTED;
4279
773
    else
4280
773
      return XML_ERROR_NONE;
4281
141
  case XML_TOK_INVALID:
4282
141
    *eventPP = next;
4283
141
    return XML_ERROR_INVALID_TOKEN;
4284
99
  case XML_TOK_PARTIAL_CHAR:
4285
99
    if (haveMore) {
4286
58
      *nextPtr = s;
4287
58
      return XML_ERROR_NONE;
4288
58
    }
4289
41
    return XML_ERROR_PARTIAL_CHAR;
4290
839
  case XML_TOK_PARTIAL:
4291
839
  case XML_TOK_NONE:
4292
839
    if (haveMore) {
4293
447
      *nextPtr = s;
4294
447
      return XML_ERROR_NONE;
4295
447
    }
4296
392
    return XML_ERROR_SYNTAX; /* XML_ERROR_UNCLOSED_IGNORE_SECTION */
4297
0
  default:
4298
    /* All of the tokens that XmlIgnoreSectionTok() returns have
4299
     * explicit cases to handle them, so this default case is never
4300
     * executed.  We keep it as a safety net anyway, and remove it
4301
     * from our test coverage statistics.
4302
     *
4303
     * LCOV_EXCL_START
4304
     */
4305
0
    *eventPP = next;
4306
0
    return XML_ERROR_UNEXPECTED_STATE;
4307
    /* LCOV_EXCL_STOP */
4308
1.85k
  }
4309
  /* not reached */
4310
1.85k
}
4311
4312
#endif /* XML_DTD */
4313
4314
static enum XML_Error
4315
84.4k
initializeEncoding(XML_Parser parser) {
4316
84.4k
  const char *s;
4317
#ifdef XML_UNICODE
4318
  char encodingBuf[128];
4319
  /* See comments about `protocolEncodingName` in parserInit() */
4320
  if (! parser->m_protocolEncodingName)
4321
    s = NULL;
4322
  else {
4323
    int i;
4324
    for (i = 0; parser->m_protocolEncodingName[i]; i++) {
4325
      if (i == sizeof(encodingBuf) - 1
4326
          || (parser->m_protocolEncodingName[i] & ~0x7f) != 0) {
4327
        encodingBuf[0] = '\0';
4328
        break;
4329
      }
4330
      encodingBuf[i] = (char)parser->m_protocolEncodingName[i];
4331
    }
4332
    encodingBuf[i] = '\0';
4333
    s = encodingBuf;
4334
  }
4335
#else
4336
84.4k
  s = parser->m_protocolEncodingName;
4337
84.4k
#endif
4338
84.4k
  if ((parser->m_ns ? XmlInitEncodingNS : XmlInitEncoding)(
4339
84.4k
          &parser->m_initEncoding, &parser->m_encoding, s))
4340
84.4k
    return XML_ERROR_NONE;
4341
0
  return handleUnknownEncoding(parser, parser->m_protocolEncodingName);
4342
84.4k
}
4343
4344
static enum XML_Error
4345
processXmlDecl(XML_Parser parser, int isGeneralTextEntity, const char *s,
4346
1.52k
               const char *next) {
4347
1.52k
  const char *encodingName = NULL;
4348
1.52k
  const XML_Char *storedEncName = NULL;
4349
1.52k
  const ENCODING *newEncoding = NULL;
4350
1.52k
  const char *version = NULL;
4351
1.52k
  const char *versionend = NULL;
4352
1.52k
  const XML_Char *storedversion = NULL;
4353
1.52k
  int standalone = -1;
4354
4355
1.52k
#if XML_GE == 1
4356
1.52k
  if (! accountingDiffTolerated(parser, XML_TOK_XML_DECL, s, next, __LINE__,
4357
1.52k
                                XML_ACCOUNT_DIRECT)) {
4358
2
    accountingOnAbort(parser);
4359
2
    return XML_ERROR_AMPLIFICATION_LIMIT_BREACH;
4360
2
  }
4361
1.52k
#endif
4362
4363
1.52k
  if (! (parser->m_ns ? XmlParseXmlDeclNS : XmlParseXmlDecl)(
4364
1.52k
          isGeneralTextEntity, parser->m_encoding, s, next, &parser->m_eventPtr,
4365
1.52k
          &version, &versionend, &encodingName, &newEncoding, &standalone)) {
4366
879
    if (isGeneralTextEntity)
4367
404
      return XML_ERROR_TEXT_DECL;
4368
475
    else
4369
475
      return XML_ERROR_XML_DECL;
4370
879
  }
4371
648
  if (! isGeneralTextEntity && standalone == 1) {
4372
52
    parser->m_dtd->standalone = XML_TRUE;
4373
52
#ifdef XML_DTD
4374
52
    if (parser->m_paramEntityParsing
4375
52
        == XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE)
4376
0
      parser->m_paramEntityParsing = XML_PARAM_ENTITY_PARSING_NEVER;
4377
52
#endif /* XML_DTD */
4378
52
  }
4379
648
  if (parser->m_xmlDeclHandler) {
4380
0
    if (encodingName != NULL) {
4381
0
      storedEncName = poolStoreString(
4382
0
          &parser->m_temp2Pool, parser->m_encoding, encodingName,
4383
0
          encodingName + XmlNameLength(parser->m_encoding, encodingName));
4384
0
      if (! storedEncName)
4385
0
        return XML_ERROR_NO_MEMORY;
4386
0
      poolFinish(&parser->m_temp2Pool);
4387
0
    }
4388
0
    if (version) {
4389
0
      storedversion
4390
0
          = poolStoreString(&parser->m_temp2Pool, parser->m_encoding, version,
4391
0
                            versionend - parser->m_encoding->minBytesPerChar);
4392
0
      if (! storedversion)
4393
0
        return XML_ERROR_NO_MEMORY;
4394
0
    }
4395
0
    parser->m_xmlDeclHandler(parser->m_handlerArg, storedversion, storedEncName,
4396
0
                             standalone);
4397
648
  } else if (parser->m_defaultHandler)
4398
0
    reportDefault(parser, parser->m_encoding, s, next);
4399
648
  if (parser->m_protocolEncodingName == NULL) {
4400
487
    if (newEncoding) {
4401
      /* Check that the specified encoding does not conflict with what
4402
       * the parser has already deduced.  Do we have the same number
4403
       * of bytes in the smallest representation of a character?  If
4404
       * this is UTF-16, is it the same endianness?
4405
       */
4406
326
      if (newEncoding->minBytesPerChar != parser->m_encoding->minBytesPerChar
4407
326
          || (newEncoding->minBytesPerChar == 2
4408
318
              && newEncoding != parser->m_encoding)) {
4409
8
        parser->m_eventPtr = encodingName;
4410
8
        return XML_ERROR_INCORRECT_ENCODING;
4411
8
      }
4412
318
      parser->m_encoding = newEncoding;
4413
318
    } else if (encodingName) {
4414
121
      enum XML_Error result;
4415
121
      if (! storedEncName) {
4416
121
        storedEncName = poolStoreString(
4417
121
            &parser->m_temp2Pool, parser->m_encoding, encodingName,
4418
121
            encodingName + XmlNameLength(parser->m_encoding, encodingName));
4419
121
        if (! storedEncName)
4420
0
          return XML_ERROR_NO_MEMORY;
4421
121
      }
4422
121
      result = handleUnknownEncoding(parser, storedEncName);
4423
121
      poolClear(&parser->m_temp2Pool);
4424
121
      if (result == XML_ERROR_UNKNOWN_ENCODING)
4425
121
        parser->m_eventPtr = encodingName;
4426
121
      return result;
4427
121
    }
4428
487
  }
4429
4430
519
  if (storedEncName || storedversion)
4431
0
    poolClear(&parser->m_temp2Pool);
4432
4433
519
  return XML_ERROR_NONE;
4434
648
}
4435
4436
static enum XML_Error
4437
121
handleUnknownEncoding(XML_Parser parser, const XML_Char *encodingName) {
4438
121
  if (parser->m_unknownEncodingHandler) {
4439
0
    XML_Encoding info;
4440
0
    int i;
4441
0
    for (i = 0; i < 256; i++)
4442
0
      info.map[i] = -1;
4443
0
    info.convert = NULL;
4444
0
    info.data = NULL;
4445
0
    info.release = NULL;
4446
0
    if (parser->m_unknownEncodingHandler(parser->m_unknownEncodingHandlerData,
4447
0
                                         encodingName, &info)) {
4448
0
      ENCODING *enc;
4449
0
      parser->m_unknownEncodingMem = MALLOC(parser, XmlSizeOfUnknownEncoding());
4450
0
      if (! parser->m_unknownEncodingMem) {
4451
0
        if (info.release)
4452
0
          info.release(info.data);
4453
0
        return XML_ERROR_NO_MEMORY;
4454
0
      }
4455
0
      enc = (parser->m_ns ? XmlInitUnknownEncodingNS : XmlInitUnknownEncoding)(
4456
0
          parser->m_unknownEncodingMem, info.map, info.convert, info.data);
4457
0
      if (enc) {
4458
0
        parser->m_unknownEncodingData = info.data;
4459
0
        parser->m_unknownEncodingRelease = info.release;
4460
0
        parser->m_encoding = enc;
4461
0
        return XML_ERROR_NONE;
4462
0
      }
4463
0
    }
4464
0
    if (info.release != NULL)
4465
0
      info.release(info.data);
4466
0
  }
4467
121
  return XML_ERROR_UNKNOWN_ENCODING;
4468
121
}
4469
4470
static enum XML_Error PTRCALL
4471
prologInitProcessor(XML_Parser parser, const char *s, const char *end,
4472
42.2k
                    const char **nextPtr) {
4473
42.2k
  enum XML_Error result = initializeEncoding(parser);
4474
42.2k
  if (result != XML_ERROR_NONE)
4475
0
    return result;
4476
42.2k
  parser->m_processor = prologProcessor;
4477
42.2k
  return prologProcessor(parser, s, end, nextPtr);
4478
42.2k
}
4479
4480
#ifdef XML_DTD
4481
4482
static enum XML_Error PTRCALL
4483
externalParEntInitProcessor(XML_Parser parser, const char *s, const char *end,
4484
21.1k
                            const char **nextPtr) {
4485
21.1k
  enum XML_Error result = initializeEncoding(parser);
4486
21.1k
  if (result != XML_ERROR_NONE)
4487
0
    return result;
4488
4489
  /* we know now that XML_Parse(Buffer) has been called,
4490
     so we consider the external parameter entity read */
4491
21.1k
  parser->m_dtd->paramEntityRead = XML_TRUE;
4492
4493
21.1k
  if (parser->m_prologState.inEntityValue) {
4494
0
    parser->m_processor = entityValueInitProcessor;
4495
0
    return entityValueInitProcessor(parser, s, end, nextPtr);
4496
21.1k
  } else {
4497
21.1k
    parser->m_processor = externalParEntProcessor;
4498
21.1k
    return externalParEntProcessor(parser, s, end, nextPtr);
4499
21.1k
  }
4500
21.1k
}
4501
4502
static enum XML_Error PTRCALL
4503
entityValueInitProcessor(XML_Parser parser, const char *s, const char *end,
4504
0
                         const char **nextPtr) {
4505
0
  int tok;
4506
0
  const char *start = s;
4507
0
  const char *next = start;
4508
0
  parser->m_eventPtr = start;
4509
4510
0
  for (;;) {
4511
0
    tok = XmlPrologTok(parser->m_encoding, start, end, &next);
4512
    /* Note: Except for XML_TOK_BOM below, these bytes are accounted later in:
4513
             - storeEntityValue
4514
             - processXmlDecl
4515
    */
4516
0
    parser->m_eventEndPtr = next;
4517
0
    if (tok <= 0) {
4518
0
      if (! parser->m_parsingStatus.finalBuffer && tok != XML_TOK_INVALID) {
4519
0
        *nextPtr = s;
4520
0
        return XML_ERROR_NONE;
4521
0
      }
4522
0
      switch (tok) {
4523
0
      case XML_TOK_INVALID:
4524
0
        return XML_ERROR_INVALID_TOKEN;
4525
0
      case XML_TOK_PARTIAL:
4526
0
        return XML_ERROR_UNCLOSED_TOKEN;
4527
0
      case XML_TOK_PARTIAL_CHAR:
4528
0
        return XML_ERROR_PARTIAL_CHAR;
4529
0
      case XML_TOK_NONE: /* start == end */
4530
0
      default:
4531
0
        break;
4532
0
      }
4533
      /* found end of entity value - can store it now */
4534
0
      return storeEntityValue(parser, parser->m_encoding, s, end,
4535
0
                              XML_ACCOUNT_DIRECT);
4536
0
    } else if (tok == XML_TOK_XML_DECL) {
4537
0
      enum XML_Error result;
4538
0
      result = processXmlDecl(parser, 0, start, next);
4539
0
      if (result != XML_ERROR_NONE)
4540
0
        return result;
4541
      /* At this point, m_parsingStatus.parsing cannot be XML_SUSPENDED.  For
4542
       * that to happen, a parameter entity parsing handler must have attempted
4543
       * to suspend the parser, which fails and raises an error.  The parser can
4544
       * be aborted, but can't be suspended.
4545
       */
4546
0
      if (parser->m_parsingStatus.parsing == XML_FINISHED)
4547
0
        return XML_ERROR_ABORTED;
4548
0
      *nextPtr = next;
4549
      /* stop scanning for text declaration - we found one */
4550
0
      parser->m_processor = entityValueProcessor;
4551
0
      return entityValueProcessor(parser, next, end, nextPtr);
4552
0
    }
4553
    /* XmlPrologTok has now set the encoding based on the BOM it found, and we
4554
       must move s and nextPtr forward to consume the BOM.
4555
4556
       If we didn't, and got XML_TOK_NONE from the next XmlPrologTok call, we
4557
       would leave the BOM in the buffer and return. On the next call to this
4558
       function, our XmlPrologTok call would return XML_TOK_INVALID, since it
4559
       is not valid to have multiple BOMs.
4560
    */
4561
0
    else if (tok == XML_TOK_BOM) {
4562
0
#  if XML_GE == 1
4563
0
      if (! accountingDiffTolerated(parser, tok, s, next, __LINE__,
4564
0
                                    XML_ACCOUNT_DIRECT)) {
4565
0
        accountingOnAbort(parser);
4566
0
        return XML_ERROR_AMPLIFICATION_LIMIT_BREACH;
4567
0
      }
4568
0
#  endif
4569
4570
0
      *nextPtr = next;
4571
0
      s = next;
4572
0
    }
4573
    /* If we get this token, we have the start of what might be a
4574
       normal tag, but not a declaration (i.e. it doesn't begin with
4575
       "<!").  In a DTD context, that isn't legal.
4576
    */
4577
0
    else if (tok == XML_TOK_INSTANCE_START) {
4578
0
      *nextPtr = next;
4579
0
      return XML_ERROR_SYNTAX;
4580
0
    }
4581
0
    start = next;
4582
0
    parser->m_eventPtr = start;
4583
0
  }
4584
0
}
4585
4586
static enum XML_Error PTRCALL
4587
externalParEntProcessor(XML_Parser parser, const char *s, const char *end,
4588
23.0k
                        const char **nextPtr) {
4589
23.0k
  const char *next = s;
4590
23.0k
  int tok;
4591
4592
23.0k
  tok = XmlPrologTok(parser->m_encoding, s, end, &next);
4593
23.0k
  if (tok <= 0) {
4594
6.47k
    if (! parser->m_parsingStatus.finalBuffer && tok != XML_TOK_INVALID) {
4595
1.89k
      *nextPtr = s;
4596
1.89k
      return XML_ERROR_NONE;
4597
1.89k
    }
4598
4.58k
    switch (tok) {
4599
4.09k
    case XML_TOK_INVALID:
4600
4.09k
      return XML_ERROR_INVALID_TOKEN;
4601
201
    case XML_TOK_PARTIAL:
4602
201
      return XML_ERROR_UNCLOSED_TOKEN;
4603
99
    case XML_TOK_PARTIAL_CHAR:
4604
99
      return XML_ERROR_PARTIAL_CHAR;
4605
0
    case XML_TOK_NONE: /* start == end */
4606
198
    default:
4607
198
      break;
4608
4.58k
    }
4609
4.58k
  }
4610
  /* This would cause the next stage, i.e. doProlog to be passed XML_TOK_BOM.
4611
     However, when parsing an external subset, doProlog will not accept a BOM
4612
     as valid, and report a syntax error, so we have to skip the BOM, and
4613
     account for the BOM bytes.
4614
  */
4615
16.5k
  else if (tok == XML_TOK_BOM) {
4616
1.64k
    if (! accountingDiffTolerated(parser, tok, s, next, __LINE__,
4617
1.64k
                                  XML_ACCOUNT_DIRECT)) {
4618
0
      accountingOnAbort(parser);
4619
0
      return XML_ERROR_AMPLIFICATION_LIMIT_BREACH;
4620
0
    }
4621
4622
1.64k
    s = next;
4623
1.64k
    tok = XmlPrologTok(parser->m_encoding, s, end, &next);
4624
1.64k
  }
4625
4626
16.7k
  parser->m_processor = prologProcessor;
4627
16.7k
  return doProlog(parser, parser->m_encoding, s, end, tok, next, nextPtr,
4628
16.7k
                  (XML_Bool)! parser->m_parsingStatus.finalBuffer, XML_TRUE,
4629
16.7k
                  XML_ACCOUNT_DIRECT);
4630
23.0k
}
4631
4632
static enum XML_Error PTRCALL
4633
entityValueProcessor(XML_Parser parser, const char *s, const char *end,
4634
0
                     const char **nextPtr) {
4635
0
  const char *start = s;
4636
0
  const char *next = s;
4637
0
  const ENCODING *enc = parser->m_encoding;
4638
0
  int tok;
4639
4640
0
  for (;;) {
4641
0
    tok = XmlPrologTok(enc, start, end, &next);
4642
    /* Note: These bytes are accounted later in:
4643
             - storeEntityValue
4644
    */
4645
0
    if (tok <= 0) {
4646
0
      if (! parser->m_parsingStatus.finalBuffer && tok != XML_TOK_INVALID) {
4647
0
        *nextPtr = s;
4648
0
        return XML_ERROR_NONE;
4649
0
      }
4650
0
      switch (tok) {
4651
0
      case XML_TOK_INVALID:
4652
0
        return XML_ERROR_INVALID_TOKEN;
4653
0
      case XML_TOK_PARTIAL:
4654
0
        return XML_ERROR_UNCLOSED_TOKEN;
4655
0
      case XML_TOK_PARTIAL_CHAR:
4656
0
        return XML_ERROR_PARTIAL_CHAR;
4657
0
      case XML_TOK_NONE: /* start == end */
4658
0
      default:
4659
0
        break;
4660
0
      }
4661
      /* found end of entity value - can store it now */
4662
0
      return storeEntityValue(parser, enc, s, end, XML_ACCOUNT_DIRECT);
4663
0
    }
4664
0
    start = next;
4665
0
  }
4666
0
}
4667
4668
#endif /* XML_DTD */
4669
4670
static enum XML_Error PTRCALL
4671
prologProcessor(XML_Parser parser, const char *s, const char *end,
4672
53.6k
                const char **nextPtr) {
4673
53.6k
  const char *next = s;
4674
53.6k
  int tok = XmlPrologTok(parser->m_encoding, s, end, &next);
4675
53.6k
  return doProlog(parser, parser->m_encoding, s, end, tok, next, nextPtr,
4676
53.6k
                  (XML_Bool)! parser->m_parsingStatus.finalBuffer, XML_TRUE,
4677
53.6k
                  XML_ACCOUNT_DIRECT);
4678
53.6k
}
4679
4680
static enum XML_Error
4681
doProlog(XML_Parser parser, const ENCODING *enc, const char *s, const char *end,
4682
         int tok, const char *next, const char **nextPtr, XML_Bool haveMore,
4683
70.3k
         XML_Bool allowClosingDoctype, enum XML_Account account) {
4684
70.3k
#ifdef XML_DTD
4685
70.3k
  static const XML_Char externalSubsetName[] = {ASCII_HASH, '\0'};
4686
70.3k
#endif /* XML_DTD */
4687
70.3k
  static const XML_Char atypeCDATA[]
4688
70.3k
      = {ASCII_C, ASCII_D, ASCII_A, ASCII_T, ASCII_A, '\0'};
4689
70.3k
  static const XML_Char atypeID[] = {ASCII_I, ASCII_D, '\0'};
4690
70.3k
  static const XML_Char atypeIDREF[]
4691
70.3k
      = {ASCII_I, ASCII_D, ASCII_R, ASCII_E, ASCII_F, '\0'};
4692
70.3k
  static const XML_Char atypeIDREFS[]
4693
70.3k
      = {ASCII_I, ASCII_D, ASCII_R, ASCII_E, ASCII_F, ASCII_S, '\0'};
4694
70.3k
  static const XML_Char atypeENTITY[]
4695
70.3k
      = {ASCII_E, ASCII_N, ASCII_T, ASCII_I, ASCII_T, ASCII_Y, '\0'};
4696
70.3k
  static const XML_Char atypeENTITIES[]
4697
70.3k
      = {ASCII_E, ASCII_N, ASCII_T, ASCII_I, ASCII_T,
4698
70.3k
         ASCII_I, ASCII_E, ASCII_S, '\0'};
4699
70.3k
  static const XML_Char atypeNMTOKEN[]
4700
70.3k
      = {ASCII_N, ASCII_M, ASCII_T, ASCII_O, ASCII_K, ASCII_E, ASCII_N, '\0'};
4701
70.3k
  static const XML_Char atypeNMTOKENS[]
4702
70.3k
      = {ASCII_N, ASCII_M, ASCII_T, ASCII_O, ASCII_K,
4703
70.3k
         ASCII_E, ASCII_N, ASCII_S, '\0'};
4704
70.3k
  static const XML_Char notationPrefix[]
4705
70.3k
      = {ASCII_N, ASCII_O, ASCII_T, ASCII_A,      ASCII_T,
4706
70.3k
         ASCII_I, ASCII_O, ASCII_N, ASCII_LPAREN, '\0'};
4707
70.3k
  static const XML_Char enumValueSep[] = {ASCII_PIPE, '\0'};
4708
70.3k
  static const XML_Char enumValueStart[] = {ASCII_LPAREN, '\0'};
4709
4710
#ifndef XML_DTD
4711
  UNUSED_P(account);
4712
#endif
4713
4714
  /* save one level of indirection */
4715
70.3k
  DTD *const dtd = parser->m_dtd;
4716
4717
70.3k
  const char **eventPP;
4718
70.3k
  const char **eventEndPP;
4719
70.3k
  enum XML_Content_Quant quant;
4720
4721
70.3k
  if (enc == parser->m_encoding) {
4722
70.3k
    eventPP = &parser->m_eventPtr;
4723
70.3k
    eventEndPP = &parser->m_eventEndPtr;
4724
70.3k
  } else {
4725
0
    eventPP = &(parser->m_openInternalEntities->internalEventPtr);
4726
0
    eventEndPP = &(parser->m_openInternalEntities->internalEventEndPtr);
4727
0
  }
4728
4729
5.46M
  for (;;) {
4730
5.46M
    int role;
4731
5.46M
    XML_Bool handleDefault = XML_TRUE;
4732
5.46M
    *eventPP = s;
4733
5.46M
    *eventEndPP = next;
4734
5.46M
    if (tok <= 0) {
4735
30.6k
      if (haveMore && tok != XML_TOK_INVALID) {
4736
11.3k
        *nextPtr = s;
4737
11.3k
        return XML_ERROR_NONE;
4738
11.3k
      }
4739
19.2k
      switch (tok) {
4740
15.7k
      case XML_TOK_INVALID:
4741
15.7k
        *eventPP = next;
4742
15.7k
        return XML_ERROR_INVALID_TOKEN;
4743
1.39k
      case XML_TOK_PARTIAL:
4744
1.39k
        return XML_ERROR_UNCLOSED_TOKEN;
4745
214
      case XML_TOK_PARTIAL_CHAR:
4746
214
        return XML_ERROR_PARTIAL_CHAR;
4747
166
      case -XML_TOK_PROLOG_S:
4748
166
        tok = -tok;
4749
166
        break;
4750
945
      case XML_TOK_NONE:
4751
945
#ifdef XML_DTD
4752
        /* for internal PE NOT referenced between declarations */
4753
945
        if (enc != parser->m_encoding
4754
945
            && ! parser->m_openInternalEntities->betweenDecl) {
4755
0
          *nextPtr = s;
4756
0
          return XML_ERROR_NONE;
4757
0
        }
4758
        /* WFC: PE Between Declarations - must check that PE contains
4759
           complete markup, not only for external PEs, but also for
4760
           internal PEs if the reference occurs between declarations.
4761
        */
4762
945
        if (parser->m_isParamEntity || enc != parser->m_encoding) {
4763
459
          if (XmlTokenRole(&parser->m_prologState, XML_TOK_NONE, end, end, enc)
4764
459
              == XML_ROLE_ERROR)
4765
111
            return XML_ERROR_INCOMPLETE_PE;
4766
348
          *nextPtr = s;
4767
348
          return XML_ERROR_NONE;
4768
459
        }
4769
486
#endif /* XML_DTD */
4770
486
        return XML_ERROR_NO_ELEMENTS;
4771
826
      default:
4772
826
        tok = -tok;
4773
826
        next = end;
4774
826
        break;
4775
19.2k
      }
4776
19.2k
    }
4777
5.43M
    role = XmlTokenRole(&parser->m_prologState, tok, s, next, enc);
4778
5.43M
#if XML_GE == 1
4779
5.43M
    switch (role) {
4780
16.4k
    case XML_ROLE_INSTANCE_START: // bytes accounted in contentProcessor
4781
17.2k
    case XML_ROLE_XML_DECL:       // bytes accounted in processXmlDecl
4782
17.2k
#  ifdef XML_DTD
4783
17.6k
    case XML_ROLE_TEXT_DECL: // bytes accounted in processXmlDecl
4784
17.6k
#  endif
4785
17.6k
      break;
4786
5.41M
    default:
4787
5.41M
      if (! accountingDiffTolerated(parser, tok, s, next, __LINE__, account)) {
4788
8
        accountingOnAbort(parser);
4789
8
        return XML_ERROR_AMPLIFICATION_LIMIT_BREACH;
4790
8
      }
4791
5.43M
    }
4792
5.43M
#endif
4793
5.43M
    switch (role) {
4794
797
    case XML_ROLE_XML_DECL: {
4795
797
      enum XML_Error result = processXmlDecl(parser, 0, s, next);
4796
797
      if (result != XML_ERROR_NONE)
4797
510
        return result;
4798
287
      enc = parser->m_encoding;
4799
287
      handleDefault = XML_FALSE;
4800
287
    } break;
4801
7.92k
    case XML_ROLE_DOCTYPE_NAME:
4802
7.92k
      if (parser->m_startDoctypeDeclHandler) {
4803
0
        parser->m_doctypeName
4804
0
            = poolStoreString(&parser->m_tempPool, enc, s, next);
4805
0
        if (! parser->m_doctypeName)
4806
0
          return XML_ERROR_NO_MEMORY;
4807
0
        poolFinish(&parser->m_tempPool);
4808
0
        parser->m_doctypePubid = NULL;
4809
0
        handleDefault = XML_FALSE;
4810
0
      }
4811
7.92k
      parser->m_doctypeSysid = NULL; /* always initialize to NULL */
4812
7.92k
      break;
4813
6.61k
    case XML_ROLE_DOCTYPE_INTERNAL_SUBSET:
4814
6.61k
      if (parser->m_startDoctypeDeclHandler) {
4815
0
        parser->m_startDoctypeDeclHandler(
4816
0
            parser->m_handlerArg, parser->m_doctypeName, parser->m_doctypeSysid,
4817
0
            parser->m_doctypePubid, 1);
4818
0
        parser->m_doctypeName = NULL;
4819
0
        poolClear(&parser->m_tempPool);
4820
0
        handleDefault = XML_FALSE;
4821
0
      }
4822
6.61k
      break;
4823
0
#ifdef XML_DTD
4824
366
    case XML_ROLE_TEXT_DECL: {
4825
366
      enum XML_Error result = processXmlDecl(parser, 1, s, next);
4826
366
      if (result != XML_ERROR_NONE)
4827
250
        return result;
4828
116
      enc = parser->m_encoding;
4829
116
      handleDefault = XML_FALSE;
4830
116
    } break;
4831
0
#endif /* XML_DTD */
4832
1.10k
    case XML_ROLE_DOCTYPE_PUBLIC_ID:
4833
1.10k
#ifdef XML_DTD
4834
1.10k
      parser->m_useForeignDTD = XML_FALSE;
4835
1.10k
      parser->m_declEntity = (ENTITY *)lookup(
4836
1.10k
          parser, &dtd->paramEntities, externalSubsetName, sizeof(ENTITY));
4837
1.10k
      if (! parser->m_declEntity)
4838
0
        return XML_ERROR_NO_MEMORY;
4839
1.10k
#endif /* XML_DTD */
4840
1.10k
      dtd->hasParamEntityRefs = XML_TRUE;
4841
1.10k
      if (parser->m_startDoctypeDeclHandler) {
4842
0
        XML_Char *pubId;
4843
0
        if (! XmlIsPublicId(enc, s, next, eventPP))
4844
0
          return XML_ERROR_PUBLICID;
4845
0
        pubId = poolStoreString(&parser->m_tempPool, enc,
4846
0
                                s + enc->minBytesPerChar,
4847
0
                                next - enc->minBytesPerChar);
4848
0
        if (! pubId)
4849
0
          return XML_ERROR_NO_MEMORY;
4850
0
        normalizePublicId(pubId);
4851
0
        poolFinish(&parser->m_tempPool);
4852
0
        parser->m_doctypePubid = pubId;
4853
0
        handleDefault = XML_FALSE;
4854
0
        goto alreadyChecked;
4855
0
      }
4856
      /* fall through */
4857
3.62k
    case XML_ROLE_ENTITY_PUBLIC_ID:
4858
3.62k
      if (! XmlIsPublicId(enc, s, next, eventPP))
4859
847
        return XML_ERROR_PUBLICID;
4860
2.78k
    alreadyChecked:
4861
2.78k
      if (dtd->keepProcessing && parser->m_declEntity) {
4862
1.05k
        XML_Char *tem
4863
1.05k
            = poolStoreString(&dtd->pool, enc, s + enc->minBytesPerChar,
4864
1.05k
                              next - enc->minBytesPerChar);
4865
1.05k
        if (! tem)
4866
0
          return XML_ERROR_NO_MEMORY;
4867
1.05k
        normalizePublicId(tem);
4868
1.05k
        parser->m_declEntity->publicId = tem;
4869
1.05k
        poolFinish(&dtd->pool);
4870
        /* Don't suppress the default handler if we fell through from
4871
         * the XML_ROLE_DOCTYPE_PUBLIC_ID case.
4872
         */
4873
1.05k
        if (parser->m_entityDeclHandler && role == XML_ROLE_ENTITY_PUBLIC_ID)
4874
0
          handleDefault = XML_FALSE;
4875
1.05k
      }
4876
2.78k
      break;
4877
3.25k
    case XML_ROLE_DOCTYPE_CLOSE:
4878
3.25k
      if (allowClosingDoctype != XML_TRUE) {
4879
        /* Must not close doctype from within expanded parameter entities */
4880
0
        return XML_ERROR_INVALID_TOKEN;
4881
0
      }
4882
4883
3.25k
      if (parser->m_doctypeName) {
4884
0
        parser->m_startDoctypeDeclHandler(
4885
0
            parser->m_handlerArg, parser->m_doctypeName, parser->m_doctypeSysid,
4886
0
            parser->m_doctypePubid, 0);
4887
0
        poolClear(&parser->m_tempPool);
4888
0
        handleDefault = XML_FALSE;
4889
0
      }
4890
      /* parser->m_doctypeSysid will be non-NULL in the case of a previous
4891
         XML_ROLE_DOCTYPE_SYSTEM_ID, even if parser->m_startDoctypeDeclHandler
4892
         was not set, indicating an external subset
4893
      */
4894
3.25k
#ifdef XML_DTD
4895
3.25k
      if (parser->m_doctypeSysid || parser->m_useForeignDTD) {
4896
44
        XML_Bool hadParamEntityRefs = dtd->hasParamEntityRefs;
4897
44
        dtd->hasParamEntityRefs = XML_TRUE;
4898
44
        if (parser->m_paramEntityParsing
4899
44
            && parser->m_externalEntityRefHandler) {
4900
0
          ENTITY *entity = (ENTITY *)lookup(parser, &dtd->paramEntities,
4901
0
                                            externalSubsetName, sizeof(ENTITY));
4902
0
          if (! entity) {
4903
            /* The external subset name "#" will have already been
4904
             * inserted into the hash table at the start of the
4905
             * external entity parsing, so no allocation will happen
4906
             * and lookup() cannot fail.
4907
             */
4908
0
            return XML_ERROR_NO_MEMORY; /* LCOV_EXCL_LINE */
4909
0
          }
4910
0
          if (parser->m_useForeignDTD)
4911
0
            entity->base = parser->m_curBase;
4912
0
          dtd->paramEntityRead = XML_FALSE;
4913
0
          if (! parser->m_externalEntityRefHandler(
4914
0
                  parser->m_externalEntityRefHandlerArg, 0, entity->base,
4915
0
                  entity->systemId, entity->publicId))
4916
0
            return XML_ERROR_EXTERNAL_ENTITY_HANDLING;
4917
0
          if (dtd->paramEntityRead) {
4918
0
            if (! dtd->standalone && parser->m_notStandaloneHandler
4919
0
                && ! parser->m_notStandaloneHandler(parser->m_handlerArg))
4920
0
              return XML_ERROR_NOT_STANDALONE;
4921
0
          }
4922
          /* if we didn't read the foreign DTD then this means that there
4923
             is no external subset and we must reset dtd->hasParamEntityRefs
4924
          */
4925
0
          else if (! parser->m_doctypeSysid)
4926
0
            dtd->hasParamEntityRefs = hadParamEntityRefs;
4927
          /* end of DTD - no need to update dtd->keepProcessing */
4928
0
        }
4929
44
        parser->m_useForeignDTD = XML_FALSE;
4930
44
      }
4931
3.25k
#endif /* XML_DTD */
4932
3.25k
      if (parser->m_endDoctypeDeclHandler) {
4933
0
        parser->m_endDoctypeDeclHandler(parser->m_handlerArg);
4934
0
        handleDefault = XML_FALSE;
4935
0
      }
4936
3.25k
      break;
4937
16.4k
    case XML_ROLE_INSTANCE_START:
4938
16.4k
#ifdef XML_DTD
4939
      /* if there is no DOCTYPE declaration then now is the
4940
         last chance to read the foreign DTD
4941
      */
4942
16.4k
      if (parser->m_useForeignDTD) {
4943
0
        XML_Bool hadParamEntityRefs = dtd->hasParamEntityRefs;
4944
0
        dtd->hasParamEntityRefs = XML_TRUE;
4945
0
        if (parser->m_paramEntityParsing
4946
0
            && parser->m_externalEntityRefHandler) {
4947
0
          ENTITY *entity = (ENTITY *)lookup(parser, &dtd->paramEntities,
4948
0
                                            externalSubsetName, sizeof(ENTITY));
4949
0
          if (! entity)
4950
0
            return XML_ERROR_NO_MEMORY;
4951
0
          entity->base = parser->m_curBase;
4952
0
          dtd->paramEntityRead = XML_FALSE;
4953
0
          if (! parser->m_externalEntityRefHandler(
4954
0
                  parser->m_externalEntityRefHandlerArg, 0, entity->base,
4955
0
                  entity->systemId, entity->publicId))
4956
0
            return XML_ERROR_EXTERNAL_ENTITY_HANDLING;
4957
0
          if (dtd->paramEntityRead) {
4958
0
            if (! dtd->standalone && parser->m_notStandaloneHandler
4959
0
                && ! parser->m_notStandaloneHandler(parser->m_handlerArg))
4960
0
              return XML_ERROR_NOT_STANDALONE;
4961
0
          }
4962
          /* if we didn't read the foreign DTD then this means that there
4963
             is no external subset and we must reset dtd->hasParamEntityRefs
4964
          */
4965
0
          else
4966
0
            dtd->hasParamEntityRefs = hadParamEntityRefs;
4967
          /* end of DTD - no need to update dtd->keepProcessing */
4968
0
        }
4969
0
      }
4970
16.4k
#endif /* XML_DTD */
4971
16.4k
      parser->m_processor = contentProcessor;
4972
16.4k
      return contentProcessor(parser, s, end, nextPtr);
4973
7.27k
    case XML_ROLE_ATTLIST_ELEMENT_NAME:
4974
7.27k
      parser->m_declElementType = getElementType(parser, enc, s, next);
4975
7.27k
      if (! parser->m_declElementType)
4976
0
        return XML_ERROR_NO_MEMORY;
4977
7.27k
      goto checkAttListDeclHandler;
4978
43.5k
    case XML_ROLE_ATTRIBUTE_NAME:
4979
43.5k
      parser->m_declAttributeId = getAttributeId(parser, enc, s, next);
4980
43.5k
      if (! parser->m_declAttributeId)
4981
0
        return XML_ERROR_NO_MEMORY;
4982
43.5k
      parser->m_declAttributeIsCdata = XML_FALSE;
4983
43.5k
      parser->m_declAttributeType = NULL;
4984
43.5k
      parser->m_declAttributeIsId = XML_FALSE;
4985
43.5k
      goto checkAttListDeclHandler;
4986
197
    case XML_ROLE_ATTRIBUTE_TYPE_CDATA:
4987
197
      parser->m_declAttributeIsCdata = XML_TRUE;
4988
197
      parser->m_declAttributeType = atypeCDATA;
4989
197
      goto checkAttListDeclHandler;
4990
7.21k
    case XML_ROLE_ATTRIBUTE_TYPE_ID:
4991
7.21k
      parser->m_declAttributeIsId = XML_TRUE;
4992
7.21k
      parser->m_declAttributeType = atypeID;
4993
7.21k
      goto checkAttListDeclHandler;
4994
844
    case XML_ROLE_ATTRIBUTE_TYPE_IDREF:
4995
844
      parser->m_declAttributeType = atypeIDREF;
4996
844
      goto checkAttListDeclHandler;
4997
766
    case XML_ROLE_ATTRIBUTE_TYPE_IDREFS:
4998
766
      parser->m_declAttributeType = atypeIDREFS;
4999
766
      goto checkAttListDeclHandler;
5000
106
    case XML_ROLE_ATTRIBUTE_TYPE_ENTITY:
5001
106
      parser->m_declAttributeType = atypeENTITY;
5002
106
      goto checkAttListDeclHandler;
5003
513
    case XML_ROLE_ATTRIBUTE_TYPE_ENTITIES:
5004
513
      parser->m_declAttributeType = atypeENTITIES;
5005
513
      goto checkAttListDeclHandler;
5006
101
    case XML_ROLE_ATTRIBUTE_TYPE_NMTOKEN:
5007
101
      parser->m_declAttributeType = atypeNMTOKEN;
5008
101
      goto checkAttListDeclHandler;
5009
114
    case XML_ROLE_ATTRIBUTE_TYPE_NMTOKENS:
5010
114
      parser->m_declAttributeType = atypeNMTOKENS;
5011
60.7k
    checkAttListDeclHandler:
5012
60.7k
      if (dtd->keepProcessing && parser->m_attlistDeclHandler)
5013
0
        handleDefault = XML_FALSE;
5014
60.7k
      break;
5015
60.3k
    case XML_ROLE_ATTRIBUTE_ENUM_VALUE:
5016
61.7k
    case XML_ROLE_ATTRIBUTE_NOTATION_VALUE:
5017
61.7k
      if (dtd->keepProcessing && parser->m_attlistDeclHandler) {
5018
0
        const XML_Char *prefix;
5019
0
        if (parser->m_declAttributeType) {
5020
0
          prefix = enumValueSep;
5021
0
        } else {
5022
0
          prefix = (role == XML_ROLE_ATTRIBUTE_NOTATION_VALUE ? notationPrefix
5023
0
                                                              : enumValueStart);
5024
0
        }
5025
0
        if (! poolAppendString(&parser->m_tempPool, prefix))
5026
0
          return XML_ERROR_NO_MEMORY;
5027
0
        if (! poolAppend(&parser->m_tempPool, enc, s, next))
5028
0
          return XML_ERROR_NO_MEMORY;
5029
0
        parser->m_declAttributeType = parser->m_tempPool.start;
5030
0
        handleDefault = XML_FALSE;
5031
0
      }
5032
61.7k
      break;
5033
61.7k
    case XML_ROLE_IMPLIED_ATTRIBUTE_VALUE:
5034
33.8k
    case XML_ROLE_REQUIRED_ATTRIBUTE_VALUE:
5035
33.8k
      if (dtd->keepProcessing) {
5036
33.7k
        if (! defineAttribute(parser->m_declElementType,
5037
33.7k
                              parser->m_declAttributeId,
5038
33.7k
                              parser->m_declAttributeIsCdata,
5039
33.7k
                              parser->m_declAttributeIsId, 0, parser))
5040
0
          return XML_ERROR_NO_MEMORY;
5041
33.7k
        if (parser->m_attlistDeclHandler && parser->m_declAttributeType) {
5042
0
          if (*parser->m_declAttributeType == XML_T(ASCII_LPAREN)
5043
0
              || (*parser->m_declAttributeType == XML_T(ASCII_N)
5044
0
                  && parser->m_declAttributeType[1] == XML_T(ASCII_O))) {
5045
            /* Enumerated or Notation type */
5046
0
            if (! poolAppendChar(&parser->m_tempPool, XML_T(ASCII_RPAREN))
5047
0
                || ! poolAppendChar(&parser->m_tempPool, XML_T('\0')))
5048
0
              return XML_ERROR_NO_MEMORY;
5049
0
            parser->m_declAttributeType = parser->m_tempPool.start;
5050
0
            poolFinish(&parser->m_tempPool);
5051
0
          }
5052
0
          *eventEndPP = s;
5053
0
          parser->m_attlistDeclHandler(
5054
0
              parser->m_handlerArg, parser->m_declElementType->name,
5055
0
              parser->m_declAttributeId->name, parser->m_declAttributeType, 0,
5056
0
              role == XML_ROLE_REQUIRED_ATTRIBUTE_VALUE);
5057
0
          handleDefault = XML_FALSE;
5058
0
        }
5059
33.7k
      }
5060
33.8k
      poolClear(&parser->m_tempPool);
5061
33.8k
      break;
5062
7.56k
    case XML_ROLE_DEFAULT_ATTRIBUTE_VALUE:
5063
9.00k
    case XML_ROLE_FIXED_ATTRIBUTE_VALUE:
5064
9.00k
      if (dtd->keepProcessing) {
5065
8.93k
        const XML_Char *attVal;
5066
8.93k
        enum XML_Error result = storeAttributeValue(
5067
8.93k
            parser, enc, parser->m_declAttributeIsCdata,
5068
8.93k
            s + enc->minBytesPerChar, next - enc->minBytesPerChar, &dtd->pool,
5069
8.93k
            XML_ACCOUNT_NONE);
5070
8.93k
        if (result)
5071
67
          return result;
5072
8.86k
        attVal = poolStart(&dtd->pool);
5073
8.86k
        poolFinish(&dtd->pool);
5074
        /* ID attributes aren't allowed to have a default */
5075
8.86k
        if (! defineAttribute(
5076
8.86k
                parser->m_declElementType, parser->m_declAttributeId,
5077
8.86k
                parser->m_declAttributeIsCdata, XML_FALSE, attVal, parser))
5078
0
          return XML_ERROR_NO_MEMORY;
5079
8.86k
        if (parser->m_attlistDeclHandler && parser->m_declAttributeType) {
5080
0
          if (*parser->m_declAttributeType == XML_T(ASCII_LPAREN)
5081
0
              || (*parser->m_declAttributeType == XML_T(ASCII_N)
5082
0
                  && parser->m_declAttributeType[1] == XML_T(ASCII_O))) {
5083
            /* Enumerated or Notation type */
5084
0