Coverage Report

Created: 2025-11-16 09:57

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/work/workdir/UnpackedTarball/libxml2/xpath.c
Line
Count
Source
1
/*
2
 * xpath.c: XML Path Language implementation
3
 *          XPath is a language for addressing parts of an XML document,
4
 *          designed to be used by both XSLT and XPointer
5
 *
6
 * Reference: W3C Recommendation 16 November 1999
7
 *     http://www.w3.org/TR/1999/REC-xpath-19991116
8
 * Public reference:
9
 *     http://www.w3.org/TR/xpath
10
 *
11
 * See Copyright for the status of this software
12
 *
13
 * Author: daniel@veillard.com
14
 *
15
 */
16
17
/* To avoid EBCDIC trouble when parsing on zOS */
18
#if defined(__MVS__)
19
#pragma convert("ISO8859-1")
20
#endif
21
22
#define IN_LIBXML
23
#include "libxml.h"
24
25
#include <limits.h>
26
#include <string.h>
27
#include <stddef.h>
28
#include <math.h>
29
#include <float.h>
30
#include <ctype.h>
31
32
#include <libxml/xmlmemory.h>
33
#include <libxml/tree.h>
34
#include <libxml/xpath.h>
35
#include <libxml/xpathInternals.h>
36
#include <libxml/parserInternals.h>
37
#include <libxml/hash.h>
38
#ifdef LIBXML_DEBUG_ENABLED
39
#include <libxml/debugXML.h>
40
#endif
41
#include <libxml/xmlerror.h>
42
#include <libxml/threads.h>
43
#ifdef LIBXML_PATTERN_ENABLED
44
#include <libxml/pattern.h>
45
#endif
46
47
#include "private/buf.h"
48
#include "private/error.h"
49
#include "private/memory.h"
50
#include "private/xpath.h"
51
52
/* Disabled for now */
53
#if 0
54
#ifdef LIBXML_PATTERN_ENABLED
55
#define XPATH_STREAMING
56
#endif
57
#endif
58
59
/**
60
 * WITH_TIM_SORT:
61
 *
62
 * Use the Timsort algorithm provided in timsort.h to sort
63
 * nodeset as this is a great improvement over the old Shell sort
64
 * used in xmlXPathNodeSetSort()
65
 */
66
#define WITH_TIM_SORT
67
68
/*
69
* XP_OPTIMIZED_NON_ELEM_COMPARISON:
70
* If defined, this will use xmlXPathCmpNodesExt() instead of
71
* xmlXPathCmpNodes(). The new function is optimized comparison of
72
* non-element nodes; actually it will speed up comparison only if
73
* xmlXPathOrderDocElems() was called in order to index the elements of
74
* a tree in document order; Libxslt does such an indexing, thus it will
75
* benefit from this optimization.
76
*/
77
#define XP_OPTIMIZED_NON_ELEM_COMPARISON
78
79
/*
80
* XP_OPTIMIZED_FILTER_FIRST:
81
* If defined, this will optimize expressions like "key('foo', 'val')[b][1]"
82
* in a way, that it stop evaluation at the first node.
83
*/
84
#define XP_OPTIMIZED_FILTER_FIRST
85
86
/*
87
 * XPATH_MAX_STEPS:
88
 * when compiling an XPath expression we arbitrary limit the maximum
89
 * number of step operation in the compiled expression. 1000000 is
90
 * an insanely large value which should never be reached under normal
91
 * circumstances
92
 */
93
2.53k
#define XPATH_MAX_STEPS 1000000
94
95
/*
96
 * XPATH_MAX_STACK_DEPTH:
97
 * when evaluating an XPath expression we arbitrary limit the maximum
98
 * number of object allowed to be pushed on the stack. 1000000 is
99
 * an insanely large value which should never be reached under normal
100
 * circumstances
101
 */
102
0
#define XPATH_MAX_STACK_DEPTH 1000000
103
104
/*
105
 * XPATH_MAX_NODESET_LENGTH:
106
 * when evaluating an XPath expression nodesets are created and we
107
 * arbitrary limit the maximum length of those node set. 10000000 is
108
 * an insanely large value which should never be reached under normal
109
 * circumstances, one would first need to construct an in memory tree
110
 * with more than 10 millions nodes.
111
 */
112
568
#define XPATH_MAX_NODESET_LENGTH 10000000
113
114
/*
115
 * XPATH_MAX_RECRUSION_DEPTH:
116
 * Maximum amount of nested functions calls when parsing or evaluating
117
 * expressions
118
 */
119
#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
120
8.50k
#define XPATH_MAX_RECURSION_DEPTH 500
121
#elif defined(_WIN32)
122
/* Windows typically limits stack size to 1MB. */
123
#define XPATH_MAX_RECURSION_DEPTH 1000
124
#else
125
#define XPATH_MAX_RECURSION_DEPTH 5000
126
#endif
127
128
/*
129
 * TODO:
130
 * There are a few spots where some tests are done which depend upon ascii
131
 * data.  These should be enhanced for full UTF8 support (see particularly
132
 * any use of the macros IS_ASCII_CHARACTER and IS_ASCII_DIGIT)
133
 */
134
135
#if defined(LIBXML_XPATH_ENABLED)
136
137
static void
138
xmlXPathNameFunction(xmlXPathParserContextPtr ctxt, int nargs);
139
140
static const struct {
141
    const char *name;
142
    xmlXPathFunction func;
143
} xmlXPathStandardFunctions[] = {
144
    { "boolean", xmlXPathBooleanFunction },
145
    { "ceiling", xmlXPathCeilingFunction },
146
    { "count", xmlXPathCountFunction },
147
    { "concat", xmlXPathConcatFunction },
148
    { "contains", xmlXPathContainsFunction },
149
    { "id", xmlXPathIdFunction },
150
    { "false", xmlXPathFalseFunction },
151
    { "floor", xmlXPathFloorFunction },
152
    { "last", xmlXPathLastFunction },
153
    { "lang", xmlXPathLangFunction },
154
    { "local-name", xmlXPathLocalNameFunction },
155
    { "not", xmlXPathNotFunction },
156
    { "name", xmlXPathNameFunction },
157
    { "namespace-uri", xmlXPathNamespaceURIFunction },
158
    { "normalize-space", xmlXPathNormalizeFunction },
159
    { "number", xmlXPathNumberFunction },
160
    { "position", xmlXPathPositionFunction },
161
    { "round", xmlXPathRoundFunction },
162
    { "string", xmlXPathStringFunction },
163
    { "string-length", xmlXPathStringLengthFunction },
164
    { "starts-with", xmlXPathStartsWithFunction },
165
    { "substring", xmlXPathSubstringFunction },
166
    { "substring-before", xmlXPathSubstringBeforeFunction },
167
    { "substring-after", xmlXPathSubstringAfterFunction },
168
    { "sum", xmlXPathSumFunction },
169
    { "true", xmlXPathTrueFunction },
170
    { "translate", xmlXPathTranslateFunction }
171
};
172
173
#define NUM_STANDARD_FUNCTIONS \
174
504
    (sizeof(xmlXPathStandardFunctions) / sizeof(xmlXPathStandardFunctions[0]))
175
176
1.87k
#define SF_HASH_SIZE 64
177
178
static unsigned char xmlXPathSFHash[SF_HASH_SIZE];
179
180
double xmlXPathNAN = 0.0;
181
double xmlXPathPINF = 0.0;
182
double xmlXPathNINF = 0.0;
183
184
/**
185
 * xmlXPathInit:
186
 *
187
 * DEPRECATED: Alias for xmlInitParser.
188
 */
189
void
190
0
xmlXPathInit(void) {
191
0
    xmlInitParser();
192
0
}
193
194
ATTRIBUTE_NO_SANITIZE_INTEGER
195
static unsigned
196
579
xmlXPathSFComputeHash(const xmlChar *name) {
197
579
    unsigned hashValue = 5381;
198
579
    const xmlChar *ptr;
199
200
4.79k
    for (ptr = name; *ptr; ptr++)
201
4.21k
        hashValue = hashValue * 33 + *ptr;
202
203
579
    return(hashValue);
204
579
}
205
206
/**
207
 * xmlInitXPathInternal:
208
 *
209
 * Initialize the XPath environment
210
 */
211
ATTRIBUTE_NO_SANITIZE("float-divide-by-zero")
212
void
213
18
xmlInitXPathInternal(void) {
214
18
    size_t i;
215
216
18
#if defined(NAN) && defined(INFINITY)
217
18
    xmlXPathNAN = NAN;
218
18
    xmlXPathPINF = INFINITY;
219
18
    xmlXPathNINF = -INFINITY;
220
#else
221
    /* MSVC doesn't allow division by zero in constant expressions. */
222
    double zero = 0.0;
223
    xmlXPathNAN = 0.0 / zero;
224
    xmlXPathPINF = 1.0 / zero;
225
    xmlXPathNINF = -xmlXPathPINF;
226
#endif
227
228
    /*
229
     * Initialize hash table for standard functions
230
     */
231
232
1.17k
    for (i = 0; i < SF_HASH_SIZE; i++)
233
1.15k
        xmlXPathSFHash[i] = UCHAR_MAX;
234
235
504
    for (i = 0; i < NUM_STANDARD_FUNCTIONS; i++) {
236
486
        const char *name = xmlXPathStandardFunctions[i].name;
237
486
        int bucketIndex = xmlXPathSFComputeHash(BAD_CAST name) % SF_HASH_SIZE;
238
239
612
        while (xmlXPathSFHash[bucketIndex] != UCHAR_MAX) {
240
126
            bucketIndex += 1;
241
126
            if (bucketIndex >= SF_HASH_SIZE)
242
0
                bucketIndex = 0;
243
126
        }
244
245
486
        xmlXPathSFHash[bucketIndex] = i;
246
486
    }
247
18
}
248
249
/************************************************************************
250
 *                  *
251
 *      Floating point stuff        *
252
 *                  *
253
 ************************************************************************/
254
255
/**
256
 * xmlXPathIsNaN:
257
 * @val:  a double value
258
 *
259
 * Checks whether a double is a NaN.
260
 *
261
 * Returns 1 if the value is a NaN, 0 otherwise
262
 */
263
int
264
0
xmlXPathIsNaN(double val) {
265
0
#ifdef isnan
266
0
    return isnan(val);
267
#else
268
    return !(val == val);
269
#endif
270
0
}
271
272
/**
273
 * xmlXPathIsInf:
274
 * @val:  a double value
275
 *
276
 * Checks whether a double is an infinity.
277
 *
278
 * Returns 1 if the value is +Infinite, -1 if -Infinite, 0 otherwise
279
 */
280
int
281
0
xmlXPathIsInf(double val) {
282
0
#ifdef isinf
283
0
    return isinf(val) ? (val > 0 ? 1 : -1) : 0;
284
#else
285
    if (val >= xmlXPathPINF)
286
        return 1;
287
    if (val <= -xmlXPathPINF)
288
        return -1;
289
    return 0;
290
#endif
291
0
}
292
293
/*
294
 * TODO: when compatibility allows remove all "fake node libxslt" strings
295
 *       the test should just be name[0] = ' '
296
 */
297
298
static const xmlNs xmlXPathXMLNamespaceStruct = {
299
    NULL,
300
    XML_NAMESPACE_DECL,
301
    XML_XML_NAMESPACE,
302
    BAD_CAST "xml",
303
    NULL,
304
    NULL
305
};
306
static const xmlNs *const xmlXPathXMLNamespace = &xmlXPathXMLNamespaceStruct;
307
308
static void
309
xmlXPathNodeSetClear(xmlNodeSetPtr set, int hasNsNodes);
310
311
0
#define XML_NODE_SORT_VALUE(n) XML_PTR_TO_INT((n)->content)
312
313
#ifdef XP_OPTIMIZED_NON_ELEM_COMPARISON
314
315
/**
316
 * xmlXPathCmpNodesExt:
317
 * @node1:  the first node
318
 * @node2:  the second node
319
 *
320
 * Compare two nodes w.r.t document order.
321
 * This one is optimized for handling of non-element nodes.
322
 *
323
 * Returns -2 in case of error 1 if first point < second point, 0 if
324
 *         it's the same node, -1 otherwise
325
 */
326
static int
327
0
xmlXPathCmpNodesExt(xmlNodePtr node1, xmlNodePtr node2) {
328
0
    int depth1, depth2;
329
0
    int misc = 0, precedence1 = 0, precedence2 = 0;
330
0
    xmlNodePtr miscNode1 = NULL, miscNode2 = NULL;
331
0
    xmlNodePtr cur, root;
332
0
    XML_INTPTR_T l1, l2;
333
334
0
    if ((node1 == NULL) || (node2 == NULL))
335
0
  return(-2);
336
337
0
    if (node1 == node2)
338
0
  return(0);
339
340
    /*
341
     * a couple of optimizations which will avoid computations in most cases
342
     */
343
0
    switch (node1->type) {
344
0
  case XML_ELEMENT_NODE:
345
0
      if (node2->type == XML_ELEMENT_NODE) {
346
0
    if ((0 > XML_NODE_SORT_VALUE(node1)) &&
347
0
        (0 > XML_NODE_SORT_VALUE(node2)) &&
348
0
        (node1->doc == node2->doc))
349
0
    {
350
0
        l1 = -XML_NODE_SORT_VALUE(node1);
351
0
        l2 = -XML_NODE_SORT_VALUE(node2);
352
0
        if (l1 < l2)
353
0
      return(1);
354
0
        if (l1 > l2)
355
0
      return(-1);
356
0
    } else
357
0
        goto turtle_comparison;
358
0
      }
359
0
      break;
360
0
  case XML_ATTRIBUTE_NODE:
361
0
      precedence1 = 1; /* element is owner */
362
0
      miscNode1 = node1;
363
0
      node1 = node1->parent;
364
0
      misc = 1;
365
0
      break;
366
0
  case XML_TEXT_NODE:
367
0
  case XML_CDATA_SECTION_NODE:
368
0
  case XML_COMMENT_NODE:
369
0
  case XML_PI_NODE: {
370
0
      miscNode1 = node1;
371
      /*
372
      * Find nearest element node.
373
      */
374
0
      if (node1->prev != NULL) {
375
0
    do {
376
0
        node1 = node1->prev;
377
0
        if (node1->type == XML_ELEMENT_NODE) {
378
0
      precedence1 = 3; /* element in prev-sibl axis */
379
0
      break;
380
0
        }
381
0
        if (node1->prev == NULL) {
382
0
      precedence1 = 2; /* element is parent */
383
      /*
384
      * URGENT TODO: Are there any cases, where the
385
      * parent of such a node is not an element node?
386
      */
387
0
      node1 = node1->parent;
388
0
      break;
389
0
        }
390
0
    } while (1);
391
0
      } else {
392
0
    precedence1 = 2; /* element is parent */
393
0
    node1 = node1->parent;
394
0
      }
395
0
      if ((node1 == NULL) || (node1->type != XML_ELEMENT_NODE) ||
396
0
    (0 <= XML_NODE_SORT_VALUE(node1))) {
397
    /*
398
    * Fallback for whatever case.
399
    */
400
0
    node1 = miscNode1;
401
0
    precedence1 = 0;
402
0
      } else
403
0
    misc = 1;
404
0
  }
405
0
      break;
406
0
  case XML_NAMESPACE_DECL:
407
      /*
408
      * TODO: why do we return 1 for namespace nodes?
409
      */
410
0
      return(1);
411
0
  default:
412
0
      break;
413
0
    }
414
0
    switch (node2->type) {
415
0
  case XML_ELEMENT_NODE:
416
0
      break;
417
0
  case XML_ATTRIBUTE_NODE:
418
0
      precedence2 = 1; /* element is owner */
419
0
      miscNode2 = node2;
420
0
      node2 = node2->parent;
421
0
      misc = 1;
422
0
      break;
423
0
  case XML_TEXT_NODE:
424
0
  case XML_CDATA_SECTION_NODE:
425
0
  case XML_COMMENT_NODE:
426
0
  case XML_PI_NODE: {
427
0
      miscNode2 = node2;
428
0
      if (node2->prev != NULL) {
429
0
    do {
430
0
        node2 = node2->prev;
431
0
        if (node2->type == XML_ELEMENT_NODE) {
432
0
      precedence2 = 3; /* element in prev-sibl axis */
433
0
      break;
434
0
        }
435
0
        if (node2->prev == NULL) {
436
0
      precedence2 = 2; /* element is parent */
437
0
      node2 = node2->parent;
438
0
      break;
439
0
        }
440
0
    } while (1);
441
0
      } else {
442
0
    precedence2 = 2; /* element is parent */
443
0
    node2 = node2->parent;
444
0
      }
445
0
      if ((node2 == NULL) || (node2->type != XML_ELEMENT_NODE) ||
446
0
    (0 <= XML_NODE_SORT_VALUE(node2)))
447
0
      {
448
0
    node2 = miscNode2;
449
0
    precedence2 = 0;
450
0
      } else
451
0
    misc = 1;
452
0
  }
453
0
      break;
454
0
  case XML_NAMESPACE_DECL:
455
0
      return(1);
456
0
  default:
457
0
      break;
458
0
    }
459
0
    if (misc) {
460
0
  if (node1 == node2) {
461
0
      if (precedence1 == precedence2) {
462
    /*
463
    * The ugly case; but normally there aren't many
464
    * adjacent non-element nodes around.
465
    */
466
0
    cur = miscNode2->prev;
467
0
    while (cur != NULL) {
468
0
        if (cur == miscNode1)
469
0
      return(1);
470
0
        if (cur->type == XML_ELEMENT_NODE)
471
0
      return(-1);
472
0
        cur = cur->prev;
473
0
    }
474
0
    return (-1);
475
0
      } else {
476
    /*
477
    * Evaluate based on higher precedence wrt to the element.
478
    * TODO: This assumes attributes are sorted before content.
479
    *   Is this 100% correct?
480
    */
481
0
    if (precedence1 < precedence2)
482
0
        return(1);
483
0
    else
484
0
        return(-1);
485
0
      }
486
0
  }
487
  /*
488
  * Special case: One of the helper-elements is contained by the other.
489
  * <foo>
490
  *   <node2>
491
  *     <node1>Text-1(precedence1 == 2)</node1>
492
  *   </node2>
493
  *   Text-6(precedence2 == 3)
494
  * </foo>
495
  */
496
0
  if ((precedence2 == 3) && (precedence1 > 1)) {
497
0
      cur = node1->parent;
498
0
      while (cur) {
499
0
    if (cur == node2)
500
0
        return(1);
501
0
    cur = cur->parent;
502
0
      }
503
0
  }
504
0
  if ((precedence1 == 3) && (precedence2 > 1)) {
505
0
      cur = node2->parent;
506
0
      while (cur) {
507
0
    if (cur == node1)
508
0
        return(-1);
509
0
    cur = cur->parent;
510
0
      }
511
0
  }
512
0
    }
513
514
    /*
515
     * Speedup using document order if available.
516
     */
517
0
    if ((node1->type == XML_ELEMENT_NODE) &&
518
0
  (node2->type == XML_ELEMENT_NODE) &&
519
0
  (0 > XML_NODE_SORT_VALUE(node1)) &&
520
0
  (0 > XML_NODE_SORT_VALUE(node2)) &&
521
0
  (node1->doc == node2->doc)) {
522
523
0
  l1 = -XML_NODE_SORT_VALUE(node1);
524
0
  l2 = -XML_NODE_SORT_VALUE(node2);
525
0
  if (l1 < l2)
526
0
      return(1);
527
0
  if (l1 > l2)
528
0
      return(-1);
529
0
    }
530
531
0
turtle_comparison:
532
533
0
    if (node1 == node2->prev)
534
0
  return(1);
535
0
    if (node1 == node2->next)
536
0
  return(-1);
537
    /*
538
     * compute depth to root
539
     */
540
0
    for (depth2 = 0, cur = node2; cur->parent != NULL; cur = cur->parent) {
541
0
  if (cur->parent == node1)
542
0
      return(1);
543
0
  depth2++;
544
0
    }
545
0
    root = cur;
546
0
    for (depth1 = 0, cur = node1; cur->parent != NULL; cur = cur->parent) {
547
0
  if (cur->parent == node2)
548
0
      return(-1);
549
0
  depth1++;
550
0
    }
551
    /*
552
     * Distinct document (or distinct entities :-( ) case.
553
     */
554
0
    if (root != cur) {
555
0
  return(-2);
556
0
    }
557
    /*
558
     * get the nearest common ancestor.
559
     */
560
0
    while (depth1 > depth2) {
561
0
  depth1--;
562
0
  node1 = node1->parent;
563
0
    }
564
0
    while (depth2 > depth1) {
565
0
  depth2--;
566
0
  node2 = node2->parent;
567
0
    }
568
0
    while (node1->parent != node2->parent) {
569
0
  node1 = node1->parent;
570
0
  node2 = node2->parent;
571
  /* should not happen but just in case ... */
572
0
  if ((node1 == NULL) || (node2 == NULL))
573
0
      return(-2);
574
0
    }
575
    /*
576
     * Find who's first.
577
     */
578
0
    if (node1 == node2->prev)
579
0
  return(1);
580
0
    if (node1 == node2->next)
581
0
  return(-1);
582
    /*
583
     * Speedup using document order if available.
584
     */
585
0
    if ((node1->type == XML_ELEMENT_NODE) &&
586
0
  (node2->type == XML_ELEMENT_NODE) &&
587
0
  (0 > XML_NODE_SORT_VALUE(node1)) &&
588
0
  (0 > XML_NODE_SORT_VALUE(node2)) &&
589
0
  (node1->doc == node2->doc)) {
590
591
0
  l1 = -XML_NODE_SORT_VALUE(node1);
592
0
  l2 = -XML_NODE_SORT_VALUE(node2);
593
0
  if (l1 < l2)
594
0
      return(1);
595
0
  if (l1 > l2)
596
0
      return(-1);
597
0
    }
598
599
0
    for (cur = node1->next;cur != NULL;cur = cur->next)
600
0
  if (cur == node2)
601
0
      return(1);
602
0
    return(-1); /* assume there is no sibling list corruption */
603
0
}
604
#endif /* XP_OPTIMIZED_NON_ELEM_COMPARISON */
605
606
/*
607
 * Wrapper for the Timsort algorithm from timsort.h
608
 */
609
#ifdef WITH_TIM_SORT
610
#define SORT_NAME libxml_domnode
611
0
#define SORT_TYPE xmlNodePtr
612
/**
613
 * wrap_cmp:
614
 * @x: a node
615
 * @y: another node
616
 *
617
 * Comparison function for the Timsort implementation
618
 *
619
 * Returns -2 in case of error -1 if first point < second point, 0 if
620
 *         it's the same node, +1 otherwise
621
 */
622
static
623
int wrap_cmp( xmlNodePtr x, xmlNodePtr y );
624
#ifdef XP_OPTIMIZED_NON_ELEM_COMPARISON
625
    static int wrap_cmp( xmlNodePtr x, xmlNodePtr y )
626
0
    {
627
0
        int res = xmlXPathCmpNodesExt(x, y);
628
0
        return res == -2 ? res : -res;
629
0
    }
630
#else
631
    static int wrap_cmp( xmlNodePtr x, xmlNodePtr y )
632
    {
633
        int res = xmlXPathCmpNodes(x, y);
634
        return res == -2 ? res : -res;
635
    }
636
#endif
637
0
#define SORT_CMP(x, y)  (wrap_cmp(x, y))
638
#include "timsort.h"
639
#endif /* WITH_TIM_SORT */
640
641
/************************************************************************
642
 *                  *
643
 *      Error handling routines       *
644
 *                  *
645
 ************************************************************************/
646
647
/**
648
 * XP_ERRORNULL:
649
 * @X:  the error code
650
 *
651
 * Macro to raise an XPath error and return NULL.
652
 */
653
#define XP_ERRORNULL(X)             \
654
0
    { xmlXPathErr(ctxt, X); return(NULL); }
655
656
/*
657
 * The array xmlXPathErrorMessages corresponds to the enum xmlXPathError
658
 */
659
static const char* const xmlXPathErrorMessages[] = {
660
    "Ok\n",
661
    "Number encoding\n",
662
    "Unfinished literal\n",
663
    "Start of literal\n",
664
    "Expected $ for variable reference\n",
665
    "Undefined variable\n",
666
    "Invalid predicate\n",
667
    "Invalid expression\n",
668
    "Missing closing curly brace\n",
669
    "Unregistered function\n",
670
    "Invalid operand\n",
671
    "Invalid type\n",
672
    "Invalid number of arguments\n",
673
    "Invalid context size\n",
674
    "Invalid context position\n",
675
    "Memory allocation error\n",
676
    "Syntax error\n",
677
    "Resource error\n",
678
    "Sub resource error\n",
679
    "Undefined namespace prefix\n",
680
    "Encoding error\n",
681
    "Char out of XML range\n",
682
    "Invalid or incomplete context\n",
683
    "Stack usage error\n",
684
    "Forbidden variable\n",
685
    "Operation limit exceeded\n",
686
    "Recursion limit exceeded\n",
687
    "?? Unknown error ??\n" /* Must be last in the list! */
688
};
689
0
#define MAXERRNO ((int)(sizeof(xmlXPathErrorMessages) /  \
690
0
       sizeof(xmlXPathErrorMessages[0])) - 1)
691
/**
692
 * xmlXPathErrMemory:
693
 * @ctxt:  an XPath context
694
 *
695
 * Handle a memory allocation failure.
696
 */
697
void
698
xmlXPathErrMemory(xmlXPathContextPtr ctxt)
699
0
{
700
0
    if (ctxt == NULL)
701
0
        return;
702
0
    xmlRaiseMemoryError(ctxt->error, NULL, ctxt->userData, XML_FROM_XPATH,
703
0
                        &ctxt->lastError);
704
0
}
705
706
/**
707
 * xmlXPathPErrMemory:
708
 * @ctxt:  an XPath parser context
709
 *
710
 * Handle a memory allocation failure.
711
 */
712
void
713
xmlXPathPErrMemory(xmlXPathParserContextPtr ctxt)
714
0
{
715
0
    if (ctxt == NULL)
716
0
        return;
717
0
    ctxt->error = XPATH_MEMORY_ERROR;
718
0
    xmlXPathErrMemory(ctxt->context);
719
0
}
720
721
/**
722
 * xmlXPathErr:
723
 * @ctxt:  a XPath parser context
724
 * @code:  the error code
725
 *
726
 * Handle an XPath error
727
 */
728
void
729
xmlXPathErr(xmlXPathParserContextPtr ctxt, int code)
730
0
{
731
0
    xmlStructuredErrorFunc schannel = NULL;
732
0
    xmlGenericErrorFunc channel = NULL;
733
0
    void *data = NULL;
734
0
    xmlNodePtr node = NULL;
735
0
    int res;
736
737
0
    if (ctxt == NULL)
738
0
        return;
739
0
    if ((code < 0) || (code > MAXERRNO))
740
0
  code = MAXERRNO;
741
    /* Only report the first error */
742
0
    if (ctxt->error != 0)
743
0
        return;
744
745
0
    ctxt->error = code;
746
747
0
    if (ctxt->context != NULL) {
748
0
        xmlErrorPtr err = &ctxt->context->lastError;
749
750
        /* Don't overwrite memory error. */
751
0
        if (err->code == XML_ERR_NO_MEMORY)
752
0
            return;
753
754
        /* cleanup current last error */
755
0
        xmlResetError(err);
756
757
0
        err->domain = XML_FROM_XPATH;
758
0
        err->code = code + XML_XPATH_EXPRESSION_OK - XPATH_EXPRESSION_OK;
759
0
        err->level = XML_ERR_ERROR;
760
0
        if (ctxt->base != NULL) {
761
0
            err->str1 = (char *) xmlStrdup(ctxt->base);
762
0
            if (err->str1 == NULL) {
763
0
                xmlXPathPErrMemory(ctxt);
764
0
                return;
765
0
            }
766
0
        }
767
0
        err->int1 = ctxt->cur - ctxt->base;
768
0
        err->node = ctxt->context->debugNode;
769
770
0
        schannel = ctxt->context->error;
771
0
        data = ctxt->context->userData;
772
0
        node = ctxt->context->debugNode;
773
0
    }
774
775
0
    if (schannel == NULL) {
776
0
        channel = xmlGenericError;
777
0
        data = xmlGenericErrorContext;
778
0
    }
779
780
0
    res = xmlRaiseError(schannel, channel, data, NULL, node, XML_FROM_XPATH,
781
0
                        code + XML_XPATH_EXPRESSION_OK - XPATH_EXPRESSION_OK,
782
0
                        XML_ERR_ERROR, NULL, 0,
783
0
                        (const char *) ctxt->base, NULL, NULL,
784
0
                        ctxt->cur - ctxt->base, 0,
785
0
                        "%s", xmlXPathErrorMessages[code]);
786
0
    if (res < 0)
787
0
        xmlXPathPErrMemory(ctxt);
788
0
}
789
790
/**
791
 * xmlXPatherror:
792
 * @ctxt:  the XPath Parser context
793
 * @file:  the file name
794
 * @line:  the line number
795
 * @no:  the error number
796
 *
797
 * Formats an error message.
798
 */
799
void
800
xmlXPatherror(xmlXPathParserContextPtr ctxt, const char *file ATTRIBUTE_UNUSED,
801
0
              int line ATTRIBUTE_UNUSED, int no) {
802
0
    xmlXPathErr(ctxt, no);
803
0
}
804
805
/**
806
 * xmlXPathCheckOpLimit:
807
 * @ctxt:  the XPath Parser context
808
 * @opCount:  the number of operations to be added
809
 *
810
 * Adds opCount to the running total of operations and returns -1 if the
811
 * operation limit is exceeded. Returns 0 otherwise.
812
 */
813
static int
814
0
xmlXPathCheckOpLimit(xmlXPathParserContextPtr ctxt, unsigned long opCount) {
815
0
    xmlXPathContextPtr xpctxt = ctxt->context;
816
817
0
    if ((opCount > xpctxt->opLimit) ||
818
0
        (xpctxt->opCount > xpctxt->opLimit - opCount)) {
819
0
        xpctxt->opCount = xpctxt->opLimit;
820
0
        xmlXPathErr(ctxt, XPATH_OP_LIMIT_EXCEEDED);
821
0
        return(-1);
822
0
    }
823
824
0
    xpctxt->opCount += opCount;
825
0
    return(0);
826
0
}
827
828
#define OP_LIMIT_EXCEEDED(ctxt, n) \
829
5.50k
    ((ctxt->context->opLimit != 0) && (xmlXPathCheckOpLimit(ctxt, n) < 0))
830
831
/************************************************************************
832
 *                  *
833
 *      Parser Types          *
834
 *                  *
835
 ************************************************************************/
836
837
/*
838
 * Types are private:
839
 */
840
841
typedef enum {
842
    XPATH_OP_END=0,
843
    XPATH_OP_AND,
844
    XPATH_OP_OR,
845
    XPATH_OP_EQUAL,
846
    XPATH_OP_CMP,
847
    XPATH_OP_PLUS,
848
    XPATH_OP_MULT,
849
    XPATH_OP_UNION,
850
    XPATH_OP_ROOT,
851
    XPATH_OP_NODE,
852
    XPATH_OP_COLLECT,
853
    XPATH_OP_VALUE, /* 11 */
854
    XPATH_OP_VARIABLE,
855
    XPATH_OP_FUNCTION,
856
    XPATH_OP_ARG,
857
    XPATH_OP_PREDICATE,
858
    XPATH_OP_FILTER, /* 16 */
859
    XPATH_OP_SORT /* 17 */
860
} xmlXPathOp;
861
862
typedef enum {
863
    AXIS_ANCESTOR = 1,
864
    AXIS_ANCESTOR_OR_SELF,
865
    AXIS_ATTRIBUTE,
866
    AXIS_CHILD,
867
    AXIS_DESCENDANT,
868
    AXIS_DESCENDANT_OR_SELF,
869
    AXIS_FOLLOWING,
870
    AXIS_FOLLOWING_SIBLING,
871
    AXIS_NAMESPACE,
872
    AXIS_PARENT,
873
    AXIS_PRECEDING,
874
    AXIS_PRECEDING_SIBLING,
875
    AXIS_SELF
876
} xmlXPathAxisVal;
877
878
typedef enum {
879
    NODE_TEST_NONE = 0,
880
    NODE_TEST_TYPE = 1,
881
    NODE_TEST_PI = 2,
882
    NODE_TEST_ALL = 3,
883
    NODE_TEST_NS = 4,
884
    NODE_TEST_NAME = 5
885
} xmlXPathTestVal;
886
887
typedef enum {
888
    NODE_TYPE_NODE = 0,
889
    NODE_TYPE_COMMENT = XML_COMMENT_NODE,
890
    NODE_TYPE_TEXT = XML_TEXT_NODE,
891
    NODE_TYPE_PI = XML_PI_NODE
892
} xmlXPathTypeVal;
893
894
typedef struct _xmlXPathStepOp xmlXPathStepOp;
895
typedef xmlXPathStepOp *xmlXPathStepOpPtr;
896
struct _xmlXPathStepOp {
897
    xmlXPathOp op;    /* The identifier of the operation */
898
    int ch1;      /* First child */
899
    int ch2;      /* Second child */
900
    int value;
901
    int value2;
902
    int value3;
903
    void *value4;
904
    void *value5;
905
    xmlXPathFunction cache;
906
    void *cacheURI;
907
};
908
909
struct _xmlXPathCompExpr {
910
    int nbStep;     /* Number of steps in this expression */
911
    int maxStep;    /* Maximum number of steps allocated */
912
    xmlXPathStepOp *steps;  /* ops for computation of this expression */
913
    int last;     /* index of last step in expression */
914
    xmlChar *expr;    /* the expression being computed */
915
    xmlDictPtr dict;    /* the dictionary to use if any */
916
#ifdef XPATH_STREAMING
917
    xmlPatternPtr stream;
918
#endif
919
};
920
921
/************************************************************************
922
 *                  *
923
 *      Forward declarations        *
924
 *                  *
925
 ************************************************************************/
926
927
static void
928
xmlXPathReleaseObject(xmlXPathContextPtr ctxt, xmlXPathObjectPtr obj);
929
static int
930
xmlXPathCompOpEvalFirst(xmlXPathParserContextPtr ctxt,
931
                        xmlXPathStepOpPtr op, xmlNodePtr *first);
932
static int
933
xmlXPathCompOpEvalToBoolean(xmlXPathParserContextPtr ctxt,
934
          xmlXPathStepOpPtr op,
935
          int isPredicate);
936
static void
937
xmlXPathFreeObjectEntry(void *obj, const xmlChar *name);
938
939
/************************************************************************
940
 *                  *
941
 *      Parser Type functions       *
942
 *                  *
943
 ************************************************************************/
944
945
/**
946
 * xmlXPathNewCompExpr:
947
 *
948
 * Create a new Xpath component
949
 *
950
 * Returns the newly allocated xmlXPathCompExprPtr or NULL in case of error
951
 */
952
static xmlXPathCompExprPtr
953
633
xmlXPathNewCompExpr(void) {
954
633
    xmlXPathCompExprPtr cur;
955
956
633
    cur = (xmlXPathCompExprPtr) xmlMalloc(sizeof(xmlXPathCompExpr));
957
633
    if (cur == NULL)
958
0
  return(NULL);
959
633
    memset(cur, 0, sizeof(xmlXPathCompExpr));
960
633
#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
961
633
    cur->maxStep = 1;
962
#else
963
    cur->maxStep = 10;
964
#endif
965
633
    cur->nbStep = 0;
966
633
    cur->steps = (xmlXPathStepOp *) xmlMalloc(cur->maxStep *
967
633
                                     sizeof(xmlXPathStepOp));
968
633
    if (cur->steps == NULL) {
969
0
  xmlFree(cur);
970
0
  return(NULL);
971
0
    }
972
633
    memset(cur->steps, 0, cur->maxStep * sizeof(xmlXPathStepOp));
973
633
    cur->last = -1;
974
633
    return(cur);
975
633
}
976
977
/**
978
 * xmlXPathFreeCompExpr:
979
 * @comp:  an XPATH comp
980
 *
981
 * Free up the memory allocated by @comp
982
 */
983
void
984
xmlXPathFreeCompExpr(xmlXPathCompExprPtr comp)
985
633
{
986
633
    xmlXPathStepOpPtr op;
987
633
    int i;
988
989
633
    if (comp == NULL)
990
0
        return;
991
633
    if (comp->dict == NULL) {
992
5.60k
  for (i = 0; i < comp->nbStep; i++) {
993
4.97k
      op = &comp->steps[i];
994
4.97k
      if (op->value4 != NULL) {
995
2.43k
    if (op->op == XPATH_OP_VALUE)
996
1.08k
        xmlXPathFreeObject(op->value4);
997
1.35k
    else
998
1.35k
        xmlFree(op->value4);
999
2.43k
      }
1000
4.97k
      if (op->value5 != NULL)
1001
1.26k
    xmlFree(op->value5);
1002
4.97k
  }
1003
633
    } else {
1004
0
  for (i = 0; i < comp->nbStep; i++) {
1005
0
      op = &comp->steps[i];
1006
0
      if (op->value4 != NULL) {
1007
0
    if (op->op == XPATH_OP_VALUE)
1008
0
        xmlXPathFreeObject(op->value4);
1009
0
      }
1010
0
  }
1011
0
        xmlDictFree(comp->dict);
1012
0
    }
1013
633
    if (comp->steps != NULL) {
1014
633
        xmlFree(comp->steps);
1015
633
    }
1016
#ifdef XPATH_STREAMING
1017
    if (comp->stream != NULL) {
1018
        xmlFreePatternList(comp->stream);
1019
    }
1020
#endif
1021
633
    if (comp->expr != NULL) {
1022
0
        xmlFree(comp->expr);
1023
0
    }
1024
1025
633
    xmlFree(comp);
1026
633
}
1027
1028
/**
1029
 * xmlXPathCompExprAdd:
1030
 * @comp:  the compiled expression
1031
 * @ch1: first child index
1032
 * @ch2: second child index
1033
 * @op:  an op
1034
 * @value:  the first int value
1035
 * @value2:  the second int value
1036
 * @value3:  the third int value
1037
 * @value4:  the first string value
1038
 * @value5:  the second string value
1039
 *
1040
 * Add a step to an XPath Compiled Expression
1041
 *
1042
 * Returns -1 in case of failure, the index otherwise
1043
 */
1044
static int
1045
xmlXPathCompExprAdd(xmlXPathParserContextPtr ctxt, int ch1, int ch2,
1046
   xmlXPathOp op, int value,
1047
4.97k
   int value2, int value3, void *value4, void *value5) {
1048
4.97k
    xmlXPathCompExprPtr comp = ctxt->comp;
1049
4.97k
    if (comp->nbStep >= comp->maxStep) {
1050
2.53k
  xmlXPathStepOp *real;
1051
2.53k
        int newSize;
1052
1053
2.53k
        newSize = xmlGrowCapacity(comp->maxStep, sizeof(real[0]),
1054
2.53k
                                  10, XPATH_MAX_STEPS);
1055
2.53k
        if (newSize < 0) {
1056
0
      xmlXPathPErrMemory(ctxt);
1057
0
      return(-1);
1058
0
        }
1059
2.53k
  real = xmlRealloc(comp->steps, newSize * sizeof(real[0]));
1060
2.53k
  if (real == NULL) {
1061
0
      xmlXPathPErrMemory(ctxt);
1062
0
      return(-1);
1063
0
  }
1064
2.53k
  comp->steps = real;
1065
2.53k
  comp->maxStep = newSize;
1066
2.53k
    }
1067
4.97k
    comp->last = comp->nbStep;
1068
4.97k
    comp->steps[comp->nbStep].ch1 = ch1;
1069
4.97k
    comp->steps[comp->nbStep].ch2 = ch2;
1070
4.97k
    comp->steps[comp->nbStep].op = op;
1071
4.97k
    comp->steps[comp->nbStep].value = value;
1072
4.97k
    comp->steps[comp->nbStep].value2 = value2;
1073
4.97k
    comp->steps[comp->nbStep].value3 = value3;
1074
4.97k
    if ((comp->dict != NULL) &&
1075
0
        ((op == XPATH_OP_FUNCTION) || (op == XPATH_OP_VARIABLE) ||
1076
0
   (op == XPATH_OP_COLLECT))) {
1077
0
        if (value4 != NULL) {
1078
0
      comp->steps[comp->nbStep].value4 = (xmlChar *)
1079
0
          (void *)xmlDictLookup(comp->dict, value4, -1);
1080
0
      xmlFree(value4);
1081
0
  } else
1082
0
      comp->steps[comp->nbStep].value4 = NULL;
1083
0
        if (value5 != NULL) {
1084
0
      comp->steps[comp->nbStep].value5 = (xmlChar *)
1085
0
          (void *)xmlDictLookup(comp->dict, value5, -1);
1086
0
      xmlFree(value5);
1087
0
  } else
1088
0
      comp->steps[comp->nbStep].value5 = NULL;
1089
4.97k
    } else {
1090
4.97k
  comp->steps[comp->nbStep].value4 = value4;
1091
4.97k
  comp->steps[comp->nbStep].value5 = value5;
1092
4.97k
    }
1093
4.97k
    comp->steps[comp->nbStep].cache = NULL;
1094
4.97k
    return(comp->nbStep++);
1095
4.97k
}
1096
1097
#define PUSH_FULL_EXPR(op, op1, op2, val, val2, val3, val4, val5) \
1098
1.26k
    xmlXPathCompExprAdd(ctxt, (op1), (op2),     \
1099
1.26k
                  (op), (val), (val2), (val3), (val4), (val5))
1100
#define PUSH_LONG_EXPR(op, val, val2, val3, val4, val5)     \
1101
1.17k
    xmlXPathCompExprAdd(ctxt, ctxt->comp->last, -1,   \
1102
1.17k
                  (op), (val), (val2), (val3), (val4), (val5))
1103
1104
633
#define PUSH_LEAVE_EXPR(op, val, val2)          \
1105
633
xmlXPathCompExprAdd(ctxt, -1, -1, (op), (val), (val2), 0 ,NULL ,NULL)
1106
1107
726
#define PUSH_UNARY_EXPR(op, ch, val, val2)        \
1108
726
xmlXPathCompExprAdd(ctxt, (ch), -1, (op), (val), (val2), 0 ,NULL ,NULL)
1109
1110
1.17k
#define PUSH_BINARY_EXPR(op, ch1, ch2, val, val2)     \
1111
1.17k
xmlXPathCompExprAdd(ctxt, (ch1), (ch2), (op),     \
1112
1.17k
      (val), (val2), 0 ,NULL ,NULL)
1113
1114
/************************************************************************
1115
 *                  *
1116
 *    XPath object cache structures       *
1117
 *                  *
1118
 ************************************************************************/
1119
1120
/* #define XP_DEFAULT_CACHE_ON */
1121
1122
typedef struct _xmlXPathContextCache xmlXPathContextCache;
1123
typedef xmlXPathContextCache *xmlXPathContextCachePtr;
1124
struct _xmlXPathContextCache {
1125
    xmlXPathObjectPtr nodesetObjs;  /* stringval points to next */
1126
    xmlXPathObjectPtr miscObjs;     /* stringval points to next */
1127
    int numNodeset;
1128
    int maxNodeset;
1129
    int numMisc;
1130
    int maxMisc;
1131
};
1132
1133
/************************************************************************
1134
 *                  *
1135
 *    Debugging related functions       *
1136
 *                  *
1137
 ************************************************************************/
1138
1139
#ifdef LIBXML_DEBUG_ENABLED
1140
static void
1141
0
xmlXPathDebugDumpNode(FILE *output, xmlNodePtr cur, int depth) {
1142
0
    int i;
1143
0
    char shift[100];
1144
1145
0
    for (i = 0;((i < depth) && (i < 25));i++)
1146
0
        shift[2 * i] = shift[2 * i + 1] = ' ';
1147
0
    shift[2 * i] = shift[2 * i + 1] = 0;
1148
0
    if (cur == NULL) {
1149
0
  fprintf(output, "%s", shift);
1150
0
  fprintf(output, "Node is NULL !\n");
1151
0
  return;
1152
1153
0
    }
1154
1155
0
    if ((cur->type == XML_DOCUMENT_NODE) ||
1156
0
       (cur->type == XML_HTML_DOCUMENT_NODE)) {
1157
0
  fprintf(output, "%s", shift);
1158
0
  fprintf(output, " /\n");
1159
0
    } else if (cur->type == XML_ATTRIBUTE_NODE)
1160
0
  xmlDebugDumpAttr(output, (xmlAttrPtr)cur, depth);
1161
0
    else
1162
0
  xmlDebugDumpOneNode(output, cur, depth);
1163
0
}
1164
static void
1165
0
xmlXPathDebugDumpNodeList(FILE *output, xmlNodePtr cur, int depth) {
1166
0
    xmlNodePtr tmp;
1167
0
    int i;
1168
0
    char shift[100];
1169
1170
0
    for (i = 0;((i < depth) && (i < 25));i++)
1171
0
        shift[2 * i] = shift[2 * i + 1] = ' ';
1172
0
    shift[2 * i] = shift[2 * i + 1] = 0;
1173
0
    if (cur == NULL) {
1174
0
  fprintf(output, "%s", shift);
1175
0
  fprintf(output, "Node is NULL !\n");
1176
0
  return;
1177
1178
0
    }
1179
1180
0
    while (cur != NULL) {
1181
0
  tmp = cur;
1182
0
  cur = cur->next;
1183
0
  xmlDebugDumpOneNode(output, tmp, depth);
1184
0
    }
1185
0
}
1186
1187
static void
1188
0
xmlXPathDebugDumpNodeSet(FILE *output, xmlNodeSetPtr cur, int depth) {
1189
0
    int i;
1190
0
    char shift[100];
1191
1192
0
    for (i = 0;((i < depth) && (i < 25));i++)
1193
0
        shift[2 * i] = shift[2 * i + 1] = ' ';
1194
0
    shift[2 * i] = shift[2 * i + 1] = 0;
1195
1196
0
    if (cur == NULL) {
1197
0
  fprintf(output, "%s", shift);
1198
0
  fprintf(output, "NodeSet is NULL !\n");
1199
0
  return;
1200
1201
0
    }
1202
1203
0
    if (cur != NULL) {
1204
0
  fprintf(output, "Set contains %d nodes:\n", cur->nodeNr);
1205
0
  for (i = 0;i < cur->nodeNr;i++) {
1206
0
      fprintf(output, "%s", shift);
1207
0
      fprintf(output, "%d", i + 1);
1208
0
      xmlXPathDebugDumpNode(output, cur->nodeTab[i], depth + 1);
1209
0
  }
1210
0
    }
1211
0
}
1212
1213
static void
1214
0
xmlXPathDebugDumpValueTree(FILE *output, xmlNodeSetPtr cur, int depth) {
1215
0
    int i;
1216
0
    char shift[100];
1217
1218
0
    for (i = 0;((i < depth) && (i < 25));i++)
1219
0
        shift[2 * i] = shift[2 * i + 1] = ' ';
1220
0
    shift[2 * i] = shift[2 * i + 1] = 0;
1221
1222
0
    if ((cur == NULL) || (cur->nodeNr == 0) || (cur->nodeTab[0] == NULL)) {
1223
0
  fprintf(output, "%s", shift);
1224
0
  fprintf(output, "Value Tree is NULL !\n");
1225
0
  return;
1226
1227
0
    }
1228
1229
0
    fprintf(output, "%s", shift);
1230
0
    fprintf(output, "%d", i + 1);
1231
0
    xmlXPathDebugDumpNodeList(output, cur->nodeTab[0]->children, depth + 1);
1232
0
}
1233
1234
/**
1235
 * xmlXPathDebugDumpObject:
1236
 * @output:  the FILE * to dump the output
1237
 * @cur:  the object to inspect
1238
 * @depth:  indentation level
1239
 *
1240
 * Dump the content of the object for debugging purposes
1241
 */
1242
void
1243
0
xmlXPathDebugDumpObject(FILE *output, xmlXPathObjectPtr cur, int depth) {
1244
0
    int i;
1245
0
    char shift[100];
1246
1247
0
    if (output == NULL) return;
1248
1249
0
    for (i = 0;((i < depth) && (i < 25));i++)
1250
0
        shift[2 * i] = shift[2 * i + 1] = ' ';
1251
0
    shift[2 * i] = shift[2 * i + 1] = 0;
1252
1253
1254
0
    fprintf(output, "%s", shift);
1255
1256
0
    if (cur == NULL) {
1257
0
        fprintf(output, "Object is empty (NULL)\n");
1258
0
  return;
1259
0
    }
1260
0
    switch(cur->type) {
1261
0
        case XPATH_UNDEFINED:
1262
0
      fprintf(output, "Object is uninitialized\n");
1263
0
      break;
1264
0
        case XPATH_NODESET:
1265
0
      fprintf(output, "Object is a Node Set :\n");
1266
0
      xmlXPathDebugDumpNodeSet(output, cur->nodesetval, depth);
1267
0
      break;
1268
0
  case XPATH_XSLT_TREE:
1269
0
      fprintf(output, "Object is an XSLT value tree :\n");
1270
0
      xmlXPathDebugDumpValueTree(output, cur->nodesetval, depth);
1271
0
      break;
1272
0
        case XPATH_BOOLEAN:
1273
0
      fprintf(output, "Object is a Boolean : ");
1274
0
      if (cur->boolval) fprintf(output, "true\n");
1275
0
      else fprintf(output, "false\n");
1276
0
      break;
1277
0
        case XPATH_NUMBER:
1278
0
      switch (xmlXPathIsInf(cur->floatval)) {
1279
0
      case 1:
1280
0
    fprintf(output, "Object is a number : Infinity\n");
1281
0
    break;
1282
0
      case -1:
1283
0
    fprintf(output, "Object is a number : -Infinity\n");
1284
0
    break;
1285
0
      default:
1286
0
    if (xmlXPathIsNaN(cur->floatval)) {
1287
0
        fprintf(output, "Object is a number : NaN\n");
1288
0
    } else if (cur->floatval == 0) {
1289
                    /* Omit sign for negative zero. */
1290
0
        fprintf(output, "Object is a number : 0\n");
1291
0
    } else {
1292
0
        fprintf(output, "Object is a number : %0g\n", cur->floatval);
1293
0
    }
1294
0
      }
1295
0
      break;
1296
0
        case XPATH_STRING:
1297
0
      fprintf(output, "Object is a string : ");
1298
0
      xmlDebugDumpString(output, cur->stringval);
1299
0
      fprintf(output, "\n");
1300
0
      break;
1301
0
  case XPATH_USERS:
1302
0
      fprintf(output, "Object is user defined\n");
1303
0
      break;
1304
0
    }
1305
0
}
1306
1307
static void
1308
xmlXPathDebugDumpStepOp(FILE *output, xmlXPathCompExprPtr comp,
1309
0
                       xmlXPathStepOpPtr op, int depth) {
1310
0
    int i;
1311
0
    char shift[100];
1312
1313
0
    for (i = 0;((i < depth) && (i < 25));i++)
1314
0
        shift[2 * i] = shift[2 * i + 1] = ' ';
1315
0
    shift[2 * i] = shift[2 * i + 1] = 0;
1316
1317
0
    fprintf(output, "%s", shift);
1318
0
    if (op == NULL) {
1319
0
  fprintf(output, "Step is NULL\n");
1320
0
  return;
1321
0
    }
1322
0
    switch (op->op) {
1323
0
        case XPATH_OP_END:
1324
0
      fprintf(output, "END"); break;
1325
0
        case XPATH_OP_AND:
1326
0
      fprintf(output, "AND"); break;
1327
0
        case XPATH_OP_OR:
1328
0
      fprintf(output, "OR"); break;
1329
0
        case XPATH_OP_EQUAL:
1330
0
       if (op->value)
1331
0
     fprintf(output, "EQUAL =");
1332
0
       else
1333
0
     fprintf(output, "EQUAL !=");
1334
0
       break;
1335
0
        case XPATH_OP_CMP:
1336
0
       if (op->value)
1337
0
     fprintf(output, "CMP <");
1338
0
       else
1339
0
     fprintf(output, "CMP >");
1340
0
       if (!op->value2)
1341
0
     fprintf(output, "=");
1342
0
       break;
1343
0
        case XPATH_OP_PLUS:
1344
0
       if (op->value == 0)
1345
0
     fprintf(output, "PLUS -");
1346
0
       else if (op->value == 1)
1347
0
     fprintf(output, "PLUS +");
1348
0
       else if (op->value == 2)
1349
0
     fprintf(output, "PLUS unary -");
1350
0
       else if (op->value == 3)
1351
0
     fprintf(output, "PLUS unary - -");
1352
0
       break;
1353
0
        case XPATH_OP_MULT:
1354
0
       if (op->value == 0)
1355
0
     fprintf(output, "MULT *");
1356
0
       else if (op->value == 1)
1357
0
     fprintf(output, "MULT div");
1358
0
       else
1359
0
     fprintf(output, "MULT mod");
1360
0
       break;
1361
0
        case XPATH_OP_UNION:
1362
0
       fprintf(output, "UNION"); break;
1363
0
        case XPATH_OP_ROOT:
1364
0
       fprintf(output, "ROOT"); break;
1365
0
        case XPATH_OP_NODE:
1366
0
       fprintf(output, "NODE"); break;
1367
0
        case XPATH_OP_SORT:
1368
0
       fprintf(output, "SORT"); break;
1369
0
        case XPATH_OP_COLLECT: {
1370
0
      xmlXPathAxisVal axis = (xmlXPathAxisVal)op->value;
1371
0
      xmlXPathTestVal test = (xmlXPathTestVal)op->value2;
1372
0
      xmlXPathTypeVal type = (xmlXPathTypeVal)op->value3;
1373
0
      const xmlChar *prefix = op->value4;
1374
0
      const xmlChar *name = op->value5;
1375
1376
0
      fprintf(output, "COLLECT ");
1377
0
      switch (axis) {
1378
0
    case AXIS_ANCESTOR:
1379
0
        fprintf(output, " 'ancestors' "); break;
1380
0
    case AXIS_ANCESTOR_OR_SELF:
1381
0
        fprintf(output, " 'ancestors-or-self' "); break;
1382
0
    case AXIS_ATTRIBUTE:
1383
0
        fprintf(output, " 'attributes' "); break;
1384
0
    case AXIS_CHILD:
1385
0
        fprintf(output, " 'child' "); break;
1386
0
    case AXIS_DESCENDANT:
1387
0
        fprintf(output, " 'descendant' "); break;
1388
0
    case AXIS_DESCENDANT_OR_SELF:
1389
0
        fprintf(output, " 'descendant-or-self' "); break;
1390
0
    case AXIS_FOLLOWING:
1391
0
        fprintf(output, " 'following' "); break;
1392
0
    case AXIS_FOLLOWING_SIBLING:
1393
0
        fprintf(output, " 'following-siblings' "); break;
1394
0
    case AXIS_NAMESPACE:
1395
0
        fprintf(output, " 'namespace' "); break;
1396
0
    case AXIS_PARENT:
1397
0
        fprintf(output, " 'parent' "); break;
1398
0
    case AXIS_PRECEDING:
1399
0
        fprintf(output, " 'preceding' "); break;
1400
0
    case AXIS_PRECEDING_SIBLING:
1401
0
        fprintf(output, " 'preceding-sibling' "); break;
1402
0
    case AXIS_SELF:
1403
0
        fprintf(output, " 'self' "); break;
1404
0
      }
1405
0
      switch (test) {
1406
0
                case NODE_TEST_NONE:
1407
0
        fprintf(output, "'none' "); break;
1408
0
                case NODE_TEST_TYPE:
1409
0
        fprintf(output, "'type' "); break;
1410
0
                case NODE_TEST_PI:
1411
0
        fprintf(output, "'PI' "); break;
1412
0
                case NODE_TEST_ALL:
1413
0
        fprintf(output, "'all' "); break;
1414
0
                case NODE_TEST_NS:
1415
0
        fprintf(output, "'namespace' "); break;
1416
0
                case NODE_TEST_NAME:
1417
0
        fprintf(output, "'name' "); break;
1418
0
      }
1419
0
      switch (type) {
1420
0
                case NODE_TYPE_NODE:
1421
0
        fprintf(output, "'node' "); break;
1422
0
                case NODE_TYPE_COMMENT:
1423
0
        fprintf(output, "'comment' "); break;
1424
0
                case NODE_TYPE_TEXT:
1425
0
        fprintf(output, "'text' "); break;
1426
0
                case NODE_TYPE_PI:
1427
0
        fprintf(output, "'PI' "); break;
1428
0
      }
1429
0
      if (prefix != NULL)
1430
0
    fprintf(output, "%s:", prefix);
1431
0
      if (name != NULL)
1432
0
    fprintf(output, "%s", (const char *) name);
1433
0
      break;
1434
1435
0
        }
1436
0
  case XPATH_OP_VALUE: {
1437
0
      xmlXPathObjectPtr object = (xmlXPathObjectPtr) op->value4;
1438
1439
0
      fprintf(output, "ELEM ");
1440
0
      xmlXPathDebugDumpObject(output, object, 0);
1441
0
      goto finish;
1442
0
  }
1443
0
  case XPATH_OP_VARIABLE: {
1444
0
      const xmlChar *prefix = op->value5;
1445
0
      const xmlChar *name = op->value4;
1446
1447
0
      if (prefix != NULL)
1448
0
    fprintf(output, "VARIABLE %s:%s", prefix, name);
1449
0
      else
1450
0
    fprintf(output, "VARIABLE %s", name);
1451
0
      break;
1452
0
  }
1453
0
  case XPATH_OP_FUNCTION: {
1454
0
      int nbargs = op->value;
1455
0
      const xmlChar *prefix = op->value5;
1456
0
      const xmlChar *name = op->value4;
1457
1458
0
      if (prefix != NULL)
1459
0
    fprintf(output, "FUNCTION %s:%s(%d args)",
1460
0
      prefix, name, nbargs);
1461
0
      else
1462
0
    fprintf(output, "FUNCTION %s(%d args)", name, nbargs);
1463
0
      break;
1464
0
  }
1465
0
        case XPATH_OP_ARG: fprintf(output, "ARG"); break;
1466
0
        case XPATH_OP_PREDICATE: fprintf(output, "PREDICATE"); break;
1467
0
        case XPATH_OP_FILTER: fprintf(output, "FILTER"); break;
1468
0
  default:
1469
0
        fprintf(output, "UNKNOWN %d\n", op->op); return;
1470
0
    }
1471
0
    fprintf(output, "\n");
1472
0
finish:
1473
    /* OP_VALUE has invalid ch1. */
1474
0
    if (op->op == XPATH_OP_VALUE)
1475
0
        return;
1476
1477
0
    if (op->ch1 >= 0)
1478
0
  xmlXPathDebugDumpStepOp(output, comp, &comp->steps[op->ch1], depth + 1);
1479
0
    if (op->ch2 >= 0)
1480
0
  xmlXPathDebugDumpStepOp(output, comp, &comp->steps[op->ch2], depth + 1);
1481
0
}
1482
1483
/**
1484
 * xmlXPathDebugDumpCompExpr:
1485
 * @output:  the FILE * for the output
1486
 * @comp:  the precompiled XPath expression
1487
 * @depth:  the indentation level.
1488
 *
1489
 * Dumps the tree of the compiled XPath expression.
1490
 */
1491
void
1492
xmlXPathDebugDumpCompExpr(FILE *output, xmlXPathCompExprPtr comp,
1493
0
                    int depth) {
1494
0
    int i;
1495
0
    char shift[100];
1496
1497
0
    if ((output == NULL) || (comp == NULL)) return;
1498
1499
0
    for (i = 0;((i < depth) && (i < 25));i++)
1500
0
        shift[2 * i] = shift[2 * i + 1] = ' ';
1501
0
    shift[2 * i] = shift[2 * i + 1] = 0;
1502
1503
0
    fprintf(output, "%s", shift);
1504
1505
#ifdef XPATH_STREAMING
1506
    if (comp->stream) {
1507
        fprintf(output, "Streaming Expression\n");
1508
    } else
1509
#endif
1510
0
    {
1511
0
        fprintf(output, "Compiled Expression : %d elements\n",
1512
0
                comp->nbStep);
1513
0
        i = comp->last;
1514
0
        xmlXPathDebugDumpStepOp(output, comp, &comp->steps[i], depth + 1);
1515
0
    }
1516
0
}
1517
1518
#endif /* LIBXML_DEBUG_ENABLED */
1519
1520
/************************************************************************
1521
 *                  *
1522
 *      XPath object caching        *
1523
 *                  *
1524
 ************************************************************************/
1525
1526
/**
1527
 * xmlXPathNewCache:
1528
 *
1529
 * Create a new object cache
1530
 *
1531
 * Returns the xmlXPathCache just allocated.
1532
 */
1533
static xmlXPathContextCachePtr
1534
xmlXPathNewCache(void)
1535
0
{
1536
0
    xmlXPathContextCachePtr ret;
1537
1538
0
    ret = (xmlXPathContextCachePtr) xmlMalloc(sizeof(xmlXPathContextCache));
1539
0
    if (ret == NULL)
1540
0
  return(NULL);
1541
0
    memset(ret, 0 , sizeof(xmlXPathContextCache));
1542
0
    ret->maxNodeset = 100;
1543
0
    ret->maxMisc = 100;
1544
0
    return(ret);
1545
0
}
1546
1547
static void
1548
xmlXPathCacheFreeObjectList(xmlXPathObjectPtr list)
1549
0
{
1550
0
    while (list != NULL) {
1551
0
        xmlXPathObjectPtr next;
1552
1553
0
        next = (void *) list->stringval;
1554
1555
0
  if (list->nodesetval != NULL) {
1556
0
      if (list->nodesetval->nodeTab != NULL)
1557
0
    xmlFree(list->nodesetval->nodeTab);
1558
0
      xmlFree(list->nodesetval);
1559
0
  }
1560
0
  xmlFree(list);
1561
1562
0
        list = next;
1563
0
    }
1564
0
}
1565
1566
static void
1567
xmlXPathFreeCache(xmlXPathContextCachePtr cache)
1568
0
{
1569
0
    if (cache == NULL)
1570
0
  return;
1571
0
    if (cache->nodesetObjs)
1572
0
  xmlXPathCacheFreeObjectList(cache->nodesetObjs);
1573
0
    if (cache->miscObjs)
1574
0
  xmlXPathCacheFreeObjectList(cache->miscObjs);
1575
0
    xmlFree(cache);
1576
0
}
1577
1578
/**
1579
 * xmlXPathContextSetCache:
1580
 *
1581
 * @ctxt:  the XPath context
1582
 * @active: enables/disables (creates/frees) the cache
1583
 * @value: a value with semantics dependent on @options
1584
 * @options: options (currently only the value 0 is used)
1585
 *
1586
 * Creates/frees an object cache on the XPath context.
1587
 * If activates XPath objects (xmlXPathObject) will be cached internally
1588
 * to be reused.
1589
 * @options:
1590
 *   0: This will set the XPath object caching:
1591
 *      @value:
1592
 *        This will set the maximum number of XPath objects
1593
 *        to be cached per slot
1594
 *        There are two slots for node-set and misc objects.
1595
 *        Use <0 for the default number (100).
1596
 *   Other values for @options have currently no effect.
1597
 *
1598
 * Returns 0 if the setting succeeded, and -1 on API or internal errors.
1599
 */
1600
int
1601
xmlXPathContextSetCache(xmlXPathContextPtr ctxt,
1602
      int active,
1603
      int value,
1604
      int options)
1605
0
{
1606
0
    if (ctxt == NULL)
1607
0
  return(-1);
1608
0
    if (active) {
1609
0
  xmlXPathContextCachePtr cache;
1610
1611
0
  if (ctxt->cache == NULL) {
1612
0
      ctxt->cache = xmlXPathNewCache();
1613
0
      if (ctxt->cache == NULL) {
1614
0
                xmlXPathErrMemory(ctxt);
1615
0
    return(-1);
1616
0
            }
1617
0
  }
1618
0
  cache = (xmlXPathContextCachePtr) ctxt->cache;
1619
0
  if (options == 0) {
1620
0
      if (value < 0)
1621
0
    value = 100;
1622
0
      cache->maxNodeset = value;
1623
0
      cache->maxMisc = value;
1624
0
  }
1625
0
    } else if (ctxt->cache != NULL) {
1626
0
  xmlXPathFreeCache((xmlXPathContextCachePtr) ctxt->cache);
1627
0
  ctxt->cache = NULL;
1628
0
    }
1629
0
    return(0);
1630
0
}
1631
1632
/**
1633
 * xmlXPathCacheWrapNodeSet:
1634
 * @pctxt: the XPath context
1635
 * @val:  the NodePtr value
1636
 *
1637
 * This is the cached version of xmlXPathWrapNodeSet().
1638
 * Wrap the Nodeset @val in a new xmlXPathObjectPtr
1639
 *
1640
 * Returns the created or reused object.
1641
 *
1642
 * In case of error the node set is destroyed and NULL is returned.
1643
 */
1644
static xmlXPathObjectPtr
1645
xmlXPathCacheWrapNodeSet(xmlXPathParserContextPtr pctxt, xmlNodeSetPtr val)
1646
917
{
1647
917
    xmlXPathObjectPtr ret;
1648
917
    xmlXPathContextPtr ctxt = pctxt->context;
1649
1650
917
    if ((ctxt != NULL) && (ctxt->cache != NULL)) {
1651
0
  xmlXPathContextCachePtr cache =
1652
0
      (xmlXPathContextCachePtr) ctxt->cache;
1653
1654
0
  if (cache->miscObjs != NULL) {
1655
0
      ret = cache->miscObjs;
1656
0
            cache->miscObjs = (void *) ret->stringval;
1657
0
            cache->numMisc -= 1;
1658
0
            ret->stringval = NULL;
1659
0
      ret->type = XPATH_NODESET;
1660
0
      ret->nodesetval = val;
1661
0
      return(ret);
1662
0
  }
1663
0
    }
1664
1665
917
    ret = xmlXPathWrapNodeSet(val);
1666
917
    if (ret == NULL)
1667
0
        xmlXPathPErrMemory(pctxt);
1668
917
    return(ret);
1669
917
}
1670
1671
/**
1672
 * xmlXPathCacheWrapString:
1673
 * @pctxt the XPath context
1674
 * @val:  the xmlChar * value
1675
 *
1676
 * This is the cached version of xmlXPathWrapString().
1677
 * Wraps the @val string into an XPath object.
1678
 *
1679
 * Returns the created or reused object.
1680
 */
1681
static xmlXPathObjectPtr
1682
xmlXPathCacheWrapString(xmlXPathParserContextPtr pctxt, xmlChar *val)
1683
93
{
1684
93
    xmlXPathObjectPtr ret;
1685
93
    xmlXPathContextPtr ctxt = pctxt->context;
1686
1687
93
    if ((ctxt != NULL) && (ctxt->cache != NULL)) {
1688
0
  xmlXPathContextCachePtr cache = (xmlXPathContextCachePtr) ctxt->cache;
1689
1690
0
  if (cache->miscObjs != NULL) {
1691
0
      ret = cache->miscObjs;
1692
0
            cache->miscObjs = (void *) ret->stringval;
1693
0
            cache->numMisc -= 1;
1694
0
      ret->type = XPATH_STRING;
1695
0
      ret->stringval = val;
1696
0
      return(ret);
1697
0
  }
1698
0
    }
1699
1700
93
    ret = xmlXPathWrapString(val);
1701
93
    if (ret == NULL)
1702
0
        xmlXPathPErrMemory(pctxt);
1703
93
    return(ret);
1704
93
}
1705
1706
/**
1707
 * xmlXPathCacheNewNodeSet:
1708
 * @pctxt the XPath context
1709
 * @val:  the NodePtr value
1710
 *
1711
 * This is the cached version of xmlXPathNewNodeSet().
1712
 * Acquire an xmlXPathObjectPtr of type NodeSet and initialize
1713
 * it with the single Node @val
1714
 *
1715
 * Returns the created or reused object.
1716
 */
1717
static xmlXPathObjectPtr
1718
xmlXPathCacheNewNodeSet(xmlXPathParserContextPtr pctxt, xmlNodePtr val)
1719
633
{
1720
633
    xmlXPathObjectPtr ret;
1721
633
    xmlXPathContextPtr ctxt = pctxt->context;
1722
1723
633
    if ((ctxt != NULL) && (ctxt->cache != NULL)) {
1724
0
  xmlXPathContextCachePtr cache = (xmlXPathContextCachePtr) ctxt->cache;
1725
1726
0
  if (cache->nodesetObjs != NULL) {
1727
      /*
1728
      * Use the nodeset-cache.
1729
      */
1730
0
      ret = cache->nodesetObjs;
1731
0
            cache->nodesetObjs = (void *) ret->stringval;
1732
0
            cache->numNodeset -= 1;
1733
0
            ret->stringval = NULL;
1734
0
      ret->type = XPATH_NODESET;
1735
0
      ret->boolval = 0;
1736
0
      if (val) {
1737
0
    if ((ret->nodesetval->nodeMax == 0) ||
1738
0
        (val->type == XML_NAMESPACE_DECL))
1739
0
    {
1740
0
        if (xmlXPathNodeSetAddUnique(ret->nodesetval, val) < 0)
1741
0
                        xmlXPathPErrMemory(pctxt);
1742
0
    } else {
1743
0
        ret->nodesetval->nodeTab[0] = val;
1744
0
        ret->nodesetval->nodeNr = 1;
1745
0
    }
1746
0
      }
1747
0
      return(ret);
1748
0
  } else if (cache->miscObjs != NULL) {
1749
0
            xmlNodeSetPtr set;
1750
      /*
1751
      * Fallback to misc-cache.
1752
      */
1753
1754
0
      set = xmlXPathNodeSetCreate(val);
1755
0
      if (set == NULL) {
1756
0
                xmlXPathPErrMemory(pctxt);
1757
0
    return(NULL);
1758
0
      }
1759
1760
0
      ret = cache->miscObjs;
1761
0
            cache->miscObjs = (void *) ret->stringval;
1762
0
            cache->numMisc -= 1;
1763
0
            ret->stringval = NULL;
1764
0
      ret->type = XPATH_NODESET;
1765
0
      ret->boolval = 0;
1766
0
      ret->nodesetval = set;
1767
0
      return(ret);
1768
0
  }
1769
0
    }
1770
633
    ret = xmlXPathNewNodeSet(val);
1771
633
    if (ret == NULL)
1772
0
        xmlXPathPErrMemory(pctxt);
1773
633
    return(ret);
1774
633
}
1775
1776
/**
1777
 * xmlXPathCacheNewString:
1778
 * @pctxt the XPath context
1779
 * @val:  the xmlChar * value
1780
 *
1781
 * This is the cached version of xmlXPathNewString().
1782
 * Acquire an xmlXPathObjectPtr of type string and of value @val
1783
 *
1784
 * Returns the created or reused object.
1785
 */
1786
static xmlXPathObjectPtr
1787
xmlXPathCacheNewString(xmlXPathParserContextPtr pctxt, const xmlChar *val)
1788
0
{
1789
0
    xmlXPathObjectPtr ret;
1790
0
    xmlXPathContextPtr ctxt = pctxt->context;
1791
1792
0
    if ((ctxt != NULL) && (ctxt->cache != NULL)) {
1793
0
  xmlXPathContextCachePtr cache = (xmlXPathContextCachePtr) ctxt->cache;
1794
1795
0
  if (cache->miscObjs != NULL) {
1796
0
            xmlChar *copy;
1797
1798
0
            if (val == NULL)
1799
0
                val = BAD_CAST "";
1800
0
            copy = xmlStrdup(val);
1801
0
            if (copy == NULL) {
1802
0
                xmlXPathPErrMemory(pctxt);
1803
0
                return(NULL);
1804
0
            }
1805
1806
0
      ret = cache->miscObjs;
1807
0
            cache->miscObjs = (void *) ret->stringval;
1808
0
            cache->numMisc -= 1;
1809
0
      ret->type = XPATH_STRING;
1810
0
            ret->stringval = copy;
1811
0
      return(ret);
1812
0
  }
1813
0
    }
1814
1815
0
    ret = xmlXPathNewString(val);
1816
0
    if (ret == NULL)
1817
0
        xmlXPathPErrMemory(pctxt);
1818
0
    return(ret);
1819
0
}
1820
1821
/**
1822
 * xmlXPathCacheNewCString:
1823
 * @pctxt the XPath context
1824
 * @val:  the char * value
1825
 *
1826
 * This is the cached version of xmlXPathNewCString().
1827
 * Acquire an xmlXPathObjectPtr of type string and of value @val
1828
 *
1829
 * Returns the created or reused object.
1830
 */
1831
static xmlXPathObjectPtr
1832
xmlXPathCacheNewCString(xmlXPathParserContextPtr pctxt, const char *val)
1833
0
{
1834
0
    return xmlXPathCacheNewString(pctxt, BAD_CAST val);
1835
0
}
1836
1837
/**
1838
 * xmlXPathCacheNewBoolean:
1839
 * @pctxt the XPath context
1840
 * @val:  the boolean value
1841
 *
1842
 * This is the cached version of xmlXPathNewBoolean().
1843
 * Acquires an xmlXPathObjectPtr of type boolean and of value @val
1844
 *
1845
 * Returns the created or reused object.
1846
 */
1847
static xmlXPathObjectPtr
1848
xmlXPathCacheNewBoolean(xmlXPathParserContextPtr pctxt, int val)
1849
0
{
1850
0
    xmlXPathObjectPtr ret;
1851
0
    xmlXPathContextPtr ctxt = pctxt->context;
1852
1853
0
    if ((ctxt != NULL) && (ctxt->cache != NULL)) {
1854
0
  xmlXPathContextCachePtr cache = (xmlXPathContextCachePtr) ctxt->cache;
1855
1856
0
  if (cache->miscObjs != NULL) {
1857
0
      ret = cache->miscObjs;
1858
0
            cache->miscObjs = (void *) ret->stringval;
1859
0
            cache->numMisc -= 1;
1860
0
            ret->stringval = NULL;
1861
0
      ret->type = XPATH_BOOLEAN;
1862
0
      ret->boolval = (val != 0);
1863
0
      return(ret);
1864
0
  }
1865
0
    }
1866
1867
0
    ret = xmlXPathNewBoolean(val);
1868
0
    if (ret == NULL)
1869
0
        xmlXPathPErrMemory(pctxt);
1870
0
    return(ret);
1871
0
}
1872
1873
/**
1874
 * xmlXPathCacheNewFloat:
1875
 * @pctxt the XPath context
1876
 * @val:  the double value
1877
 *
1878
 * This is the cached version of xmlXPathNewFloat().
1879
 * Acquires an xmlXPathObjectPtr of type double and of value @val
1880
 *
1881
 * Returns the created or reused object.
1882
 */
1883
static xmlXPathObjectPtr
1884
xmlXPathCacheNewFloat(xmlXPathParserContextPtr pctxt, double val)
1885
1.08k
{
1886
1.08k
    xmlXPathObjectPtr ret;
1887
1.08k
    xmlXPathContextPtr ctxt = pctxt->context;
1888
1889
1.08k
    if ((ctxt != NULL) && (ctxt->cache != NULL)) {
1890
0
  xmlXPathContextCachePtr cache = (xmlXPathContextCachePtr) ctxt->cache;
1891
1892
0
  if (cache->miscObjs != NULL) {
1893
0
      ret = cache->miscObjs;
1894
0
            cache->miscObjs = (void *) ret->stringval;
1895
0
            cache->numMisc -= 1;
1896
0
            ret->stringval = NULL;
1897
0
      ret->type = XPATH_NUMBER;
1898
0
      ret->floatval = val;
1899
0
      return(ret);
1900
0
  }
1901
0
    }
1902
1903
1.08k
    ret = xmlXPathNewFloat(val);
1904
1.08k
    if (ret == NULL)
1905
0
        xmlXPathPErrMemory(pctxt);
1906
1.08k
    return(ret);
1907
1.08k
}
1908
1909
/**
1910
 * xmlXPathCacheObjectCopy:
1911
 * @pctxt the XPath context
1912
 * @val:  the original object
1913
 *
1914
 * This is the cached version of xmlXPathObjectCopy().
1915
 * Acquire a copy of a given object
1916
 *
1917
 * Returns a created or reused created object.
1918
 */
1919
static xmlXPathObjectPtr
1920
xmlXPathCacheObjectCopy(xmlXPathParserContextPtr pctxt, xmlXPathObjectPtr val)
1921
0
{
1922
0
    xmlXPathObjectPtr ret;
1923
0
    xmlXPathContextPtr ctxt = pctxt->context;
1924
1925
0
    if (val == NULL)
1926
0
  return(NULL);
1927
1928
0
    if ((ctxt != NULL) && (ctxt->cache != NULL)) {
1929
0
  switch (val->type) {
1930
0
            case XPATH_NODESET: {
1931
0
                xmlNodeSetPtr set;
1932
1933
0
                set = xmlXPathNodeSetMerge(NULL, val->nodesetval);
1934
0
                if (set == NULL) {
1935
0
                    xmlXPathPErrMemory(pctxt);
1936
0
                    return(NULL);
1937
0
                }
1938
0
                return(xmlXPathCacheWrapNodeSet(pctxt, set));
1939
0
            }
1940
0
      case XPATH_STRING:
1941
0
    return(xmlXPathCacheNewString(pctxt, val->stringval));
1942
0
      case XPATH_BOOLEAN:
1943
0
    return(xmlXPathCacheNewBoolean(pctxt, val->boolval));
1944
0
      case XPATH_NUMBER:
1945
0
    return(xmlXPathCacheNewFloat(pctxt, val->floatval));
1946
0
      default:
1947
0
    break;
1948
0
  }
1949
0
    }
1950
0
    ret = xmlXPathObjectCopy(val);
1951
0
    if (ret == NULL)
1952
0
        xmlXPathPErrMemory(pctxt);
1953
0
    return(ret);
1954
0
}
1955
1956
/************************************************************************
1957
 *                  *
1958
 *    Parser stacks related functions and macros    *
1959
 *                  *
1960
 ************************************************************************/
1961
1962
/**
1963
 * xmlXPathCastToNumberInternal:
1964
 * @ctxt:  parser context
1965
 * @val:  an XPath object
1966
 *
1967
 * Converts an XPath object to its number value
1968
 *
1969
 * Returns the number value
1970
 */
1971
static double
1972
xmlXPathCastToNumberInternal(xmlXPathParserContextPtr ctxt,
1973
0
                             xmlXPathObjectPtr val) {
1974
0
    double ret = 0.0;
1975
1976
0
    if (val == NULL)
1977
0
  return(xmlXPathNAN);
1978
0
    switch (val->type) {
1979
0
    case XPATH_UNDEFINED:
1980
0
  ret = xmlXPathNAN;
1981
0
  break;
1982
0
    case XPATH_NODESET:
1983
0
    case XPATH_XSLT_TREE: {
1984
0
        xmlChar *str;
1985
1986
0
  str = xmlXPathCastNodeSetToString(val->nodesetval);
1987
0
        if (str == NULL) {
1988
0
            xmlXPathPErrMemory(ctxt);
1989
0
            ret = xmlXPathNAN;
1990
0
        } else {
1991
0
      ret = xmlXPathCastStringToNumber(str);
1992
0
            xmlFree(str);
1993
0
        }
1994
0
  break;
1995
0
    }
1996
0
    case XPATH_STRING:
1997
0
  ret = xmlXPathCastStringToNumber(val->stringval);
1998
0
  break;
1999
0
    case XPATH_NUMBER:
2000
0
  ret = val->floatval;
2001
0
  break;
2002
0
    case XPATH_BOOLEAN:
2003
0
  ret = xmlXPathCastBooleanToNumber(val->boolval);
2004
0
  break;
2005
0
    case XPATH_USERS:
2006
  /* TODO */
2007
0
  ret = xmlXPathNAN;
2008
0
  break;
2009
0
    }
2010
0
    return(ret);
2011
0
}
2012
2013
/**
2014
 * xmlXPathValuePop:
2015
 * @ctxt: an XPath evaluation context
2016
 *
2017
 * Pops the top XPath object from the value stack
2018
 *
2019
 * Returns the XPath object just removed
2020
 */
2021
xmlXPathObjectPtr
2022
xmlXPathValuePop(xmlXPathParserContextPtr ctxt)
2023
1.99k
{
2024
1.99k
    xmlXPathObjectPtr ret;
2025
2026
1.99k
    if ((ctxt == NULL) || (ctxt->valueNr <= 0))
2027
0
        return (NULL);
2028
2029
1.99k
    ctxt->valueNr--;
2030
1.99k
    if (ctxt->valueNr > 0)
2031
0
        ctxt->value = ctxt->valueTab[ctxt->valueNr - 1];
2032
1.99k
    else
2033
1.99k
        ctxt->value = NULL;
2034
1.99k
    ret = ctxt->valueTab[ctxt->valueNr];
2035
1.99k
    ctxt->valueTab[ctxt->valueNr] = NULL;
2036
1.99k
    return (ret);
2037
1.99k
}
2038
2039
/**
2040
 * xmlXPathValuePush:
2041
 * @ctxt:  an XPath evaluation context
2042
 * @value:  the XPath object
2043
 *
2044
 * Pushes a new XPath object on top of the value stack. If value is NULL,
2045
 * a memory error is recorded in the parser context.
2046
 *
2047
 * Returns the number of items on the value stack, or -1 in case of error.
2048
 *
2049
 * The object is destroyed in case of error.
2050
 */
2051
int
2052
xmlXPathValuePush(xmlXPathParserContextPtr ctxt, xmlXPathObjectPtr value)
2053
1.99k
{
2054
1.99k
    if (ctxt == NULL) return(-1);
2055
1.99k
    if (value == NULL) {
2056
        /*
2057
         * A NULL value typically indicates that a memory allocation failed.
2058
         */
2059
0
        xmlXPathPErrMemory(ctxt);
2060
0
        return(-1);
2061
0
    }
2062
1.99k
    if (ctxt->valueNr >= ctxt->valueMax) {
2063
0
        xmlXPathObjectPtr *tmp;
2064
0
        int newSize;
2065
2066
0
        newSize = xmlGrowCapacity(ctxt->valueMax, sizeof(tmp[0]),
2067
0
                                  10, XPATH_MAX_STACK_DEPTH);
2068
0
        if (newSize < 0) {
2069
0
            xmlXPathPErrMemory(ctxt);
2070
0
            xmlXPathFreeObject(value);
2071
0
            return (-1);
2072
0
        }
2073
0
        tmp = xmlRealloc(ctxt->valueTab, newSize * sizeof(tmp[0]));
2074
0
        if (tmp == NULL) {
2075
0
            xmlXPathPErrMemory(ctxt);
2076
0
            xmlXPathFreeObject(value);
2077
0
            return (-1);
2078
0
        }
2079
0
  ctxt->valueTab = tmp;
2080
0
        ctxt->valueMax = newSize;
2081
0
    }
2082
1.99k
    ctxt->valueTab[ctxt->valueNr] = value;
2083
1.99k
    ctxt->value = value;
2084
1.99k
    return (ctxt->valueNr++);
2085
1.99k
}
2086
2087
/**
2088
 * xmlXPathPopBoolean:
2089
 * @ctxt:  an XPath parser context
2090
 *
2091
 * Pops a boolean from the stack, handling conversion if needed.
2092
 * Check error with #xmlXPathCheckError.
2093
 *
2094
 * Returns the boolean
2095
 */
2096
int
2097
0
xmlXPathPopBoolean (xmlXPathParserContextPtr ctxt) {
2098
0
    xmlXPathObjectPtr obj;
2099
0
    int ret;
2100
2101
0
    obj = xmlXPathValuePop(ctxt);
2102
0
    if (obj == NULL) {
2103
0
  xmlXPathSetError(ctxt, XPATH_INVALID_OPERAND);
2104
0
  return(0);
2105
0
    }
2106
0
    if (obj->type != XPATH_BOOLEAN)
2107
0
  ret = xmlXPathCastToBoolean(obj);
2108
0
    else
2109
0
        ret = obj->boolval;
2110
0
    xmlXPathReleaseObject(ctxt->context, obj);
2111
0
    return(ret);
2112
0
}
2113
2114
/**
2115
 * xmlXPathPopNumber:
2116
 * @ctxt:  an XPath parser context
2117
 *
2118
 * Pops a number from the stack, handling conversion if needed.
2119
 * Check error with #xmlXPathCheckError.
2120
 *
2121
 * Returns the number
2122
 */
2123
double
2124
0
xmlXPathPopNumber (xmlXPathParserContextPtr ctxt) {
2125
0
    xmlXPathObjectPtr obj;
2126
0
    double ret;
2127
2128
0
    obj = xmlXPathValuePop(ctxt);
2129
0
    if (obj == NULL) {
2130
0
  xmlXPathSetError(ctxt, XPATH_INVALID_OPERAND);
2131
0
  return(0);
2132
0
    }
2133
0
    if (obj->type != XPATH_NUMBER)
2134
0
  ret = xmlXPathCastToNumberInternal(ctxt, obj);
2135
0
    else
2136
0
        ret = obj->floatval;
2137
0
    xmlXPathReleaseObject(ctxt->context, obj);
2138
0
    return(ret);
2139
0
}
2140
2141
/**
2142
 * xmlXPathPopString:
2143
 * @ctxt:  an XPath parser context
2144
 *
2145
 * Pops a string from the stack, handling conversion if needed.
2146
 * Check error with #xmlXPathCheckError.
2147
 *
2148
 * Returns the string
2149
 */
2150
xmlChar *
2151
0
xmlXPathPopString (xmlXPathParserContextPtr ctxt) {
2152
0
    xmlXPathObjectPtr obj;
2153
0
    xmlChar * ret;
2154
2155
0
    obj = xmlXPathValuePop(ctxt);
2156
0
    if (obj == NULL) {
2157
0
  xmlXPathSetError(ctxt, XPATH_INVALID_OPERAND);
2158
0
  return(NULL);
2159
0
    }
2160
0
    ret = xmlXPathCastToString(obj);
2161
0
    if (ret == NULL)
2162
0
        xmlXPathPErrMemory(ctxt);
2163
0
    xmlXPathReleaseObject(ctxt->context, obj);
2164
0
    return(ret);
2165
0
}
2166
2167
/**
2168
 * xmlXPathPopNodeSet:
2169
 * @ctxt:  an XPath parser context
2170
 *
2171
 * Pops a node-set from the stack, handling conversion if needed.
2172
 * Check error with #xmlXPathCheckError.
2173
 *
2174
 * Returns the node-set
2175
 */
2176
xmlNodeSetPtr
2177
0
xmlXPathPopNodeSet (xmlXPathParserContextPtr ctxt) {
2178
0
    xmlXPathObjectPtr obj;
2179
0
    xmlNodeSetPtr ret;
2180
2181
0
    if (ctxt == NULL) return(NULL);
2182
0
    if (ctxt->value == NULL) {
2183
0
  xmlXPathSetError(ctxt, XPATH_INVALID_OPERAND);
2184
0
  return(NULL);
2185
0
    }
2186
0
    if (!xmlXPathStackIsNodeSet(ctxt)) {
2187
0
  xmlXPathSetTypeError(ctxt);
2188
0
  return(NULL);
2189
0
    }
2190
0
    obj = xmlXPathValuePop(ctxt);
2191
0
    ret = obj->nodesetval;
2192
0
    obj->nodesetval = NULL;
2193
0
    xmlXPathReleaseObject(ctxt->context, obj);
2194
0
    return(ret);
2195
0
}
2196
2197
/**
2198
 * xmlXPathPopExternal:
2199
 * @ctxt:  an XPath parser context
2200
 *
2201
 * Pops an external object from the stack, handling conversion if needed.
2202
 * Check error with #xmlXPathCheckError.
2203
 *
2204
 * Returns the object
2205
 */
2206
void *
2207
0
xmlXPathPopExternal (xmlXPathParserContextPtr ctxt) {
2208
0
    xmlXPathObjectPtr obj;
2209
0
    void * ret;
2210
2211
0
    if ((ctxt == NULL) || (ctxt->value == NULL)) {
2212
0
  xmlXPathSetError(ctxt, XPATH_INVALID_OPERAND);
2213
0
  return(NULL);
2214
0
    }
2215
0
    if (ctxt->value->type != XPATH_USERS) {
2216
0
  xmlXPathSetTypeError(ctxt);
2217
0
  return(NULL);
2218
0
    }
2219
0
    obj = xmlXPathValuePop(ctxt);
2220
0
    ret = obj->user;
2221
0
    obj->user = NULL;
2222
0
    xmlXPathReleaseObject(ctxt->context, obj);
2223
0
    return(ret);
2224
0
}
2225
2226
/*
2227
 * Macros for accessing the content. Those should be used only by the parser,
2228
 * and not exported.
2229
 *
2230
 * Dirty macros, i.e. one need to make assumption on the context to use them
2231
 *
2232
 *   CUR_PTR return the current pointer to the xmlChar to be parsed.
2233
 *   CUR     returns the current xmlChar value, i.e. a 8 bit value
2234
 *           in ISO-Latin or UTF-8.
2235
 *           This should be used internally by the parser
2236
 *           only to compare to ASCII values otherwise it would break when
2237
 *           running with UTF-8 encoding.
2238
 *   NXT(n)  returns the n'th next xmlChar. Same as CUR is should be used only
2239
 *           to compare on ASCII based substring.
2240
 *   SKIP(n) Skip n xmlChar, and must also be used only to skip ASCII defined
2241
 *           strings within the parser.
2242
 *   CURRENT Returns the current char value, with the full decoding of
2243
 *           UTF-8 if we are using this mode. It returns an int.
2244
 *   NEXT    Skip to the next character, this does the proper decoding
2245
 *           in UTF-8 mode. It also pop-up unfinished entities on the fly.
2246
 *           It returns the pointer to the current xmlChar.
2247
 */
2248
2249
69.9k
#define CUR (*ctxt->cur)
2250
0
#define SKIP(val) ctxt->cur += (val)
2251
1.73k
#define NXT(val) ctxt->cur[(val)]
2252
0
#define CUR_PTR ctxt->cur
2253
2.04k
#define CUR_CHAR(l) xmlXPathCurrentChar(ctxt, &l)
2254
2255
#define COPY_BUF(b, i, v)           \
2256
1.11k
    if (v < 0x80) b[i++] = v;           \
2257
1.11k
    else i += xmlCopyCharMultiByte(&b[i],v)
2258
2259
1.67k
#define NEXTL(l)  ctxt->cur += l
2260
2261
#define SKIP_BLANKS             \
2262
34.0k
    while (IS_BLANK_CH(*(ctxt->cur))) NEXT
2263
2264
#define CURRENT (*ctxt->cur)
2265
29.7k
#define NEXT ((*ctxt->cur) ?  ctxt->cur++: ctxt->cur)
2266
2267
2268
#ifndef DBL_DIG
2269
#define DBL_DIG 16
2270
#endif
2271
#ifndef DBL_EPSILON
2272
#define DBL_EPSILON 1E-9
2273
#endif
2274
2275
0
#define UPPER_DOUBLE 1E9
2276
0
#define LOWER_DOUBLE 1E-5
2277
#define LOWER_DOUBLE_EXP 5
2278
2279
#define INTEGER_DIGITS DBL_DIG
2280
#define FRACTION_DIGITS (DBL_DIG + 1 + (LOWER_DOUBLE_EXP))
2281
0
#define EXPONENT_DIGITS (3 + 2)
2282
2283
/**
2284
 * xmlXPathFormatNumber:
2285
 * @number:     number to format
2286
 * @buffer:     output buffer
2287
 * @buffersize: size of output buffer
2288
 *
2289
 * Convert the number into a string representation.
2290
 */
2291
static void
2292
xmlXPathFormatNumber(double number, char buffer[], int buffersize)
2293
0
{
2294
0
    switch (xmlXPathIsInf(number)) {
2295
0
    case 1:
2296
0
  if (buffersize > (int)sizeof("Infinity"))
2297
0
      snprintf(buffer, buffersize, "Infinity");
2298
0
  break;
2299
0
    case -1:
2300
0
  if (buffersize > (int)sizeof("-Infinity"))
2301
0
      snprintf(buffer, buffersize, "-Infinity");
2302
0
  break;
2303
0
    default:
2304
0
  if (xmlXPathIsNaN(number)) {
2305
0
      if (buffersize > (int)sizeof("NaN"))
2306
0
    snprintf(buffer, buffersize, "NaN");
2307
0
  } else if (number == 0) {
2308
            /* Omit sign for negative zero. */
2309
0
      snprintf(buffer, buffersize, "0");
2310
0
  } else if ((number > INT_MIN) && (number < INT_MAX) &&
2311
0
                   (number == (int) number)) {
2312
0
      char work[30];
2313
0
      char *ptr, *cur;
2314
0
      int value = (int) number;
2315
2316
0
            ptr = &buffer[0];
2317
0
      if (value == 0) {
2318
0
    *ptr++ = '0';
2319
0
      } else {
2320
0
    snprintf(work, 29, "%d", value);
2321
0
    cur = &work[0];
2322
0
    while ((*cur) && (ptr - buffer < buffersize)) {
2323
0
        *ptr++ = *cur++;
2324
0
    }
2325
0
      }
2326
0
      if (ptr - buffer < buffersize) {
2327
0
    *ptr = 0;
2328
0
      } else if (buffersize > 0) {
2329
0
    ptr--;
2330
0
    *ptr = 0;
2331
0
      }
2332
0
  } else {
2333
      /*
2334
        For the dimension of work,
2335
            DBL_DIG is number of significant digits
2336
      EXPONENT is only needed for "scientific notation"
2337
            3 is sign, decimal point, and terminating zero
2338
      LOWER_DOUBLE_EXP is max number of leading zeroes in fraction
2339
        Note that this dimension is slightly (a few characters)
2340
        larger than actually necessary.
2341
      */
2342
0
      char work[DBL_DIG + EXPONENT_DIGITS + 3 + LOWER_DOUBLE_EXP];
2343
0
      int integer_place, fraction_place;
2344
0
      char *ptr;
2345
0
      char *after_fraction;
2346
0
      double absolute_value;
2347
0
      int size;
2348
2349
0
      absolute_value = fabs(number);
2350
2351
      /*
2352
       * First choose format - scientific or regular floating point.
2353
       * In either case, result is in work, and after_fraction points
2354
       * just past the fractional part.
2355
      */
2356
0
      if ( ((absolute_value > UPPER_DOUBLE) ||
2357
0
      (absolute_value < LOWER_DOUBLE)) &&
2358
0
     (absolute_value != 0.0) ) {
2359
    /* Use scientific notation */
2360
0
    integer_place = DBL_DIG + EXPONENT_DIGITS + 1;
2361
0
    fraction_place = DBL_DIG - 1;
2362
0
    size = snprintf(work, sizeof(work),"%*.*e",
2363
0
       integer_place, fraction_place, number);
2364
0
    while ((size > 0) && (work[size] != 'e')) size--;
2365
2366
0
      }
2367
0
      else {
2368
    /* Use regular notation */
2369
0
    if (absolute_value > 0.0) {
2370
0
        integer_place = (int)log10(absolute_value);
2371
0
        if (integer_place > 0)
2372
0
            fraction_place = DBL_DIG - integer_place - 1;
2373
0
        else
2374
0
            fraction_place = DBL_DIG - integer_place;
2375
0
    } else {
2376
0
        fraction_place = 1;
2377
0
    }
2378
0
    size = snprintf(work, sizeof(work), "%0.*f",
2379
0
        fraction_place, number);
2380
0
      }
2381
2382
      /* Remove leading spaces sometimes inserted by snprintf */
2383
0
      while (work[0] == ' ') {
2384
0
          for (ptr = &work[0];(ptr[0] = ptr[1]);ptr++);
2385
0
    size--;
2386
0
      }
2387
2388
      /* Remove fractional trailing zeroes */
2389
0
      after_fraction = work + size;
2390
0
      ptr = after_fraction;
2391
0
      while (*(--ptr) == '0')
2392
0
    ;
2393
0
      if (*ptr != '.')
2394
0
          ptr++;
2395
0
      while ((*ptr++ = *after_fraction++) != 0);
2396
2397
      /* Finally copy result back to caller */
2398
0
      size = strlen(work) + 1;
2399
0
      if (size > buffersize) {
2400
0
    work[buffersize - 1] = 0;
2401
0
    size = buffersize;
2402
0
      }
2403
0
      memmove(buffer, work, size);
2404
0
  }
2405
0
  break;
2406
0
    }
2407
0
}
2408
2409
2410
/************************************************************************
2411
 *                  *
2412
 *      Routines to handle NodeSets     *
2413
 *                  *
2414
 ************************************************************************/
2415
2416
/**
2417
 * xmlXPathOrderDocElems:
2418
 * @doc:  an input document
2419
 *
2420
 * Call this routine to speed up XPath computation on static documents.
2421
 * This stamps all the element nodes with the document order
2422
 * Like for line information, the order is kept in the element->content
2423
 * field, the value stored is actually - the node number (starting at -1)
2424
 * to be able to differentiate from line numbers.
2425
 *
2426
 * Returns the number of elements found in the document or -1 in case
2427
 *    of error.
2428
 */
2429
long
2430
0
xmlXPathOrderDocElems(xmlDocPtr doc) {
2431
0
    XML_INTPTR_T count = 0;
2432
0
    xmlNodePtr cur;
2433
2434
0
    if (doc == NULL)
2435
0
  return(-1);
2436
0
    cur = doc->children;
2437
0
    while (cur != NULL) {
2438
0
  if (cur->type == XML_ELEMENT_NODE) {
2439
0
            count += 1;
2440
0
            cur->content = XML_INT_TO_PTR(-count);
2441
0
      if (cur->children != NULL) {
2442
0
    cur = cur->children;
2443
0
    continue;
2444
0
      }
2445
0
  }
2446
0
  if (cur->next != NULL) {
2447
0
      cur = cur->next;
2448
0
      continue;
2449
0
  }
2450
0
  do {
2451
0
      cur = cur->parent;
2452
0
      if (cur == NULL)
2453
0
    break;
2454
0
      if (cur == (xmlNodePtr) doc) {
2455
0
    cur = NULL;
2456
0
    break;
2457
0
      }
2458
0
      if (cur->next != NULL) {
2459
0
    cur = cur->next;
2460
0
    break;
2461
0
      }
2462
0
  } while (cur != NULL);
2463
0
    }
2464
0
    return(count);
2465
0
}
2466
2467
/**
2468
 * xmlXPathCmpNodes:
2469
 * @node1:  the first node
2470
 * @node2:  the second node
2471
 *
2472
 * Compare two nodes w.r.t document order
2473
 *
2474
 * Returns -2 in case of error 1 if first point < second point, 0 if
2475
 *         it's the same node, -1 otherwise
2476
 */
2477
int
2478
0
xmlXPathCmpNodes(xmlNodePtr node1, xmlNodePtr node2) {
2479
0
    int depth1, depth2;
2480
0
    int attr1 = 0, attr2 = 0;
2481
0
    xmlNodePtr attrNode1 = NULL, attrNode2 = NULL;
2482
0
    xmlNodePtr cur, root;
2483
2484
0
    if ((node1 == NULL) || (node2 == NULL))
2485
0
  return(-2);
2486
    /*
2487
     * a couple of optimizations which will avoid computations in most cases
2488
     */
2489
0
    if (node1 == node2)   /* trivial case */
2490
0
  return(0);
2491
0
    if (node1->type == XML_ATTRIBUTE_NODE) {
2492
0
  attr1 = 1;
2493
0
  attrNode1 = node1;
2494
0
  node1 = node1->parent;
2495
0
    }
2496
0
    if (node2->type == XML_ATTRIBUTE_NODE) {
2497
0
  attr2 = 1;
2498
0
  attrNode2 = node2;
2499
0
  node2 = node2->parent;
2500
0
    }
2501
0
    if (node1 == node2) {
2502
0
  if (attr1 == attr2) {
2503
      /* not required, but we keep attributes in order */
2504
0
      if (attr1 != 0) {
2505
0
          cur = attrNode2->prev;
2506
0
    while (cur != NULL) {
2507
0
        if (cur == attrNode1)
2508
0
            return (1);
2509
0
        cur = cur->prev;
2510
0
    }
2511
0
    return (-1);
2512
0
      }
2513
0
      return(0);
2514
0
  }
2515
0
  if (attr2 == 1)
2516
0
      return(1);
2517
0
  return(-1);
2518
0
    }
2519
0
    if ((node1->type == XML_NAMESPACE_DECL) ||
2520
0
        (node2->type == XML_NAMESPACE_DECL))
2521
0
  return(1);
2522
0
    if (node1 == node2->prev)
2523
0
  return(1);
2524
0
    if (node1 == node2->next)
2525
0
  return(-1);
2526
2527
    /*
2528
     * Speedup using document order if available.
2529
     */
2530
0
    if ((node1->type == XML_ELEMENT_NODE) &&
2531
0
  (node2->type == XML_ELEMENT_NODE) &&
2532
0
  (0 > XML_NODE_SORT_VALUE(node1)) &&
2533
0
  (0 > XML_NODE_SORT_VALUE(node2)) &&
2534
0
  (node1->doc == node2->doc)) {
2535
0
  XML_INTPTR_T l1, l2;
2536
2537
0
  l1 = -XML_NODE_SORT_VALUE(node1);
2538
0
  l2 = -XML_NODE_SORT_VALUE(node2);
2539
0
  if (l1 < l2)
2540
0
      return(1);
2541
0
  if (l1 > l2)
2542
0
      return(-1);
2543
0
    }
2544
2545
    /*
2546
     * compute depth to root
2547
     */
2548
0
    for (depth2 = 0, cur = node2;cur->parent != NULL;cur = cur->parent) {
2549
0
  if (cur->parent == node1)
2550
0
      return(1);
2551
0
  depth2++;
2552
0
    }
2553
0
    root = cur;
2554
0
    for (depth1 = 0, cur = node1;cur->parent != NULL;cur = cur->parent) {
2555
0
  if (cur->parent == node2)
2556
0
      return(-1);
2557
0
  depth1++;
2558
0
    }
2559
    /*
2560
     * Distinct document (or distinct entities :-( ) case.
2561
     */
2562
0
    if (root != cur) {
2563
0
  return(-2);
2564
0
    }
2565
    /*
2566
     * get the nearest common ancestor.
2567
     */
2568
0
    while (depth1 > depth2) {
2569
0
  depth1--;
2570
0
  node1 = node1->parent;
2571
0
    }
2572
0
    while (depth2 > depth1) {
2573
0
  depth2--;
2574
0
  node2 = node2->parent;
2575
0
    }
2576
0
    while (node1->parent != node2->parent) {
2577
0
  node1 = node1->parent;
2578
0
  node2 = node2->parent;
2579
  /* should not happen but just in case ... */
2580
0
  if ((node1 == NULL) || (node2 == NULL))
2581
0
      return(-2);
2582
0
    }
2583
    /*
2584
     * Find who's first.
2585
     */
2586
0
    if (node1 == node2->prev)
2587
0
  return(1);
2588
0
    if (node1 == node2->next)
2589
0
  return(-1);
2590
    /*
2591
     * Speedup using document order if available.
2592
     */
2593
0
    if ((node1->type == XML_ELEMENT_NODE) &&
2594
0
  (node2->type == XML_ELEMENT_NODE) &&
2595
0
  (0 > XML_NODE_SORT_VALUE(node1)) &&
2596
0
  (0 > XML_NODE_SORT_VALUE(node2)) &&
2597
0
  (node1->doc == node2->doc)) {
2598
0
  XML_INTPTR_T l1, l2;
2599
2600
0
  l1 = -XML_NODE_SORT_VALUE(node1);
2601
0
  l2 = -XML_NODE_SORT_VALUE(node2);
2602
0
  if (l1 < l2)
2603
0
      return(1);
2604
0
  if (l1 > l2)
2605
0
      return(-1);
2606
0
    }
2607
2608
0
    for (cur = node1->next;cur != NULL;cur = cur->next)
2609
0
  if (cur == node2)
2610
0
      return(1);
2611
0
    return(-1); /* assume there is no sibling list corruption */
2612
0
}
2613
2614
/**
2615
 * xmlXPathNodeSetSort:
2616
 * @set:  the node set
2617
 *
2618
 * Sort the node set in document order
2619
 */
2620
void
2621
0
xmlXPathNodeSetSort(xmlNodeSetPtr set) {
2622
#ifndef WITH_TIM_SORT
2623
    int i, j, incr, len;
2624
    xmlNodePtr tmp;
2625
#endif
2626
2627
0
    if (set == NULL)
2628
0
  return;
2629
2630
#ifndef WITH_TIM_SORT
2631
    /*
2632
     * Use the old Shell's sort implementation to sort the node-set
2633
     * Timsort ought to be quite faster
2634
     */
2635
    len = set->nodeNr;
2636
    for (incr = len / 2; incr > 0; incr /= 2) {
2637
  for (i = incr; i < len; i++) {
2638
      j = i - incr;
2639
      while (j >= 0) {
2640
#ifdef XP_OPTIMIZED_NON_ELEM_COMPARISON
2641
    if (xmlXPathCmpNodesExt(set->nodeTab[j],
2642
      set->nodeTab[j + incr]) == -1)
2643
#else
2644
    if (xmlXPathCmpNodes(set->nodeTab[j],
2645
      set->nodeTab[j + incr]) == -1)
2646
#endif
2647
    {
2648
        tmp = set->nodeTab[j];
2649
        set->nodeTab[j] = set->nodeTab[j + incr];
2650
        set->nodeTab[j + incr] = tmp;
2651
        j -= incr;
2652
    } else
2653
        break;
2654
      }
2655
  }
2656
    }
2657
#else /* WITH_TIM_SORT */
2658
0
    libxml_domnode_tim_sort(set->nodeTab, set->nodeNr);
2659
0
#endif /* WITH_TIM_SORT */
2660
0
}
2661
2662
2.46k
#define XML_NODESET_DEFAULT 10
2663
/**
2664
 * xmlXPathNodeSetDupNs:
2665
 * @node:  the parent node of the namespace XPath node
2666
 * @ns:  the libxml namespace declaration node.
2667
 *
2668
 * Namespace node in libxml don't match the XPath semantic. In a node set
2669
 * the namespace nodes are duplicated and the next pointer is set to the
2670
 * parent node in the XPath semantic.
2671
 *
2672
 * Returns the newly created object.
2673
 */
2674
static xmlNodePtr
2675
0
xmlXPathNodeSetDupNs(xmlNodePtr node, xmlNsPtr ns) {
2676
0
    xmlNsPtr cur;
2677
2678
0
    if ((ns == NULL) || (ns->type != XML_NAMESPACE_DECL))
2679
0
  return(NULL);
2680
0
    if ((node == NULL) || (node->type == XML_NAMESPACE_DECL))
2681
0
  return((xmlNodePtr) ns);
2682
2683
    /*
2684
     * Allocate a new Namespace and fill the fields.
2685
     */
2686
0
    cur = (xmlNsPtr) xmlMalloc(sizeof(xmlNs));
2687
0
    if (cur == NULL)
2688
0
  return(NULL);
2689
0
    memset(cur, 0, sizeof(xmlNs));
2690
0
    cur->type = XML_NAMESPACE_DECL;
2691
0
    if (ns->href != NULL) {
2692
0
  cur->href = xmlStrdup(ns->href);
2693
0
        if (cur->href == NULL) {
2694
0
            xmlFree(cur);
2695
0
            return(NULL);
2696
0
        }
2697
0
    }
2698
0
    if (ns->prefix != NULL) {
2699
0
  cur->prefix = xmlStrdup(ns->prefix);
2700
0
        if (cur->prefix == NULL) {
2701
0
            xmlFree((xmlChar *) cur->href);
2702
0
            xmlFree(cur);
2703
0
            return(NULL);
2704
0
        }
2705
0
    }
2706
0
    cur->next = (xmlNsPtr) node;
2707
0
    return((xmlNodePtr) cur);
2708
0
}
2709
2710
/**
2711
 * xmlXPathNodeSetFreeNs:
2712
 * @ns:  the XPath namespace node found in a nodeset.
2713
 *
2714
 * Namespace nodes in libxml don't match the XPath semantic. In a node set
2715
 * the namespace nodes are duplicated and the next pointer is set to the
2716
 * parent node in the XPath semantic. Check if such a node needs to be freed
2717
 */
2718
void
2719
0
xmlXPathNodeSetFreeNs(xmlNsPtr ns) {
2720
0
    if ((ns == NULL) || (ns->type != XML_NAMESPACE_DECL))
2721
0
  return;
2722
2723
0
    if ((ns->next != NULL) && (ns->next->type != XML_NAMESPACE_DECL)) {
2724
0
  if (ns->href != NULL)
2725
0
      xmlFree((xmlChar *)ns->href);
2726
0
  if (ns->prefix != NULL)
2727
0
      xmlFree((xmlChar *)ns->prefix);
2728
0
  xmlFree(ns);
2729
0
    }
2730
0
}
2731
2732
/**
2733
 * xmlXPathNodeSetCreate:
2734
 * @val:  an initial xmlNodePtr, or NULL
2735
 *
2736
 * Create a new xmlNodeSetPtr of type double and of value @val
2737
 *
2738
 * Returns the newly created object.
2739
 */
2740
xmlNodeSetPtr
2741
1.55k
xmlXPathNodeSetCreate(xmlNodePtr val) {
2742
1.55k
    xmlNodeSetPtr ret;
2743
2744
1.55k
    ret = (xmlNodeSetPtr) xmlMalloc(sizeof(xmlNodeSet));
2745
1.55k
    if (ret == NULL)
2746
0
  return(NULL);
2747
1.55k
    memset(ret, 0 , sizeof(xmlNodeSet));
2748
1.55k
    if (val != NULL) {
2749
633
        ret->nodeTab = (xmlNodePtr *) xmlMalloc(XML_NODESET_DEFAULT *
2750
633
               sizeof(xmlNodePtr));
2751
633
  if (ret->nodeTab == NULL) {
2752
0
      xmlFree(ret);
2753
0
      return(NULL);
2754
0
  }
2755
633
  memset(ret->nodeTab, 0 ,
2756
633
         XML_NODESET_DEFAULT * sizeof(xmlNodePtr));
2757
633
        ret->nodeMax = XML_NODESET_DEFAULT;
2758
633
  if (val->type == XML_NAMESPACE_DECL) {
2759
0
      xmlNsPtr ns = (xmlNsPtr) val;
2760
0
            xmlNodePtr nsNode = xmlXPathNodeSetDupNs((xmlNodePtr) ns->next, ns);
2761
2762
0
            if (nsNode == NULL) {
2763
0
                xmlXPathFreeNodeSet(ret);
2764
0
                return(NULL);
2765
0
            }
2766
0
      ret->nodeTab[ret->nodeNr++] = nsNode;
2767
0
  } else
2768
633
      ret->nodeTab[ret->nodeNr++] = val;
2769
633
    }
2770
1.55k
    return(ret);
2771
1.55k
}
2772
2773
/**
2774
 * xmlXPathNodeSetContains:
2775
 * @cur:  the node-set
2776
 * @val:  the node
2777
 *
2778
 * checks whether @cur contains @val
2779
 *
2780
 * Returns true (1) if @cur contains @val, false (0) otherwise
2781
 */
2782
int
2783
0
xmlXPathNodeSetContains (xmlNodeSetPtr cur, xmlNodePtr val) {
2784
0
    int i;
2785
2786
0
    if ((cur == NULL) || (val == NULL)) return(0);
2787
0
    if (val->type == XML_NAMESPACE_DECL) {
2788
0
  for (i = 0; i < cur->nodeNr; i++) {
2789
0
      if (cur->nodeTab[i]->type == XML_NAMESPACE_DECL) {
2790
0
    xmlNsPtr ns1, ns2;
2791
2792
0
    ns1 = (xmlNsPtr) val;
2793
0
    ns2 = (xmlNsPtr) cur->nodeTab[i];
2794
0
    if (ns1 == ns2)
2795
0
        return(1);
2796
0
    if ((ns1->next != NULL) && (ns2->next == ns1->next) &&
2797
0
              (xmlStrEqual(ns1->prefix, ns2->prefix)))
2798
0
        return(1);
2799
0
      }
2800
0
  }
2801
0
    } else {
2802
0
  for (i = 0; i < cur->nodeNr; i++) {
2803
0
      if (cur->nodeTab[i] == val)
2804
0
    return(1);
2805
0
  }
2806
0
    }
2807
0
    return(0);
2808
0
}
2809
2810
static int
2811
568
xmlXPathNodeSetGrow(xmlNodeSetPtr cur) {
2812
568
    xmlNodePtr *temp;
2813
568
    int newSize;
2814
2815
568
    newSize = xmlGrowCapacity(cur->nodeMax, sizeof(temp[0]),
2816
568
                              XML_NODESET_DEFAULT, XPATH_MAX_NODESET_LENGTH);
2817
568
    if (newSize < 0)
2818
0
        return(-1);
2819
568
    temp = xmlRealloc(cur->nodeTab, newSize * sizeof(temp[0]));
2820
568
    if (temp == NULL)
2821
0
        return(-1);
2822
568
    cur->nodeMax = newSize;
2823
568
    cur->nodeTab = temp;
2824
2825
568
    return(0);
2826
568
}
2827
2828
/**
2829
 * xmlXPathNodeSetAddNs:
2830
 * @cur:  the initial node set
2831
 * @node:  the hosting node
2832
 * @ns:  a the namespace node
2833
 *
2834
 * add a new namespace node to an existing NodeSet
2835
 *
2836
 * Returns 0 in case of success and -1 in case of error
2837
 */
2838
int
2839
0
xmlXPathNodeSetAddNs(xmlNodeSetPtr cur, xmlNodePtr node, xmlNsPtr ns) {
2840
0
    int i;
2841
0
    xmlNodePtr nsNode;
2842
2843
0
    if ((cur == NULL) || (ns == NULL) || (node == NULL) ||
2844
0
        (ns->type != XML_NAMESPACE_DECL) ||
2845
0
  (node->type != XML_ELEMENT_NODE))
2846
0
  return(-1);
2847
2848
    /* @@ with_ns to check whether namespace nodes should be looked at @@ */
2849
    /*
2850
     * prevent duplicates
2851
     */
2852
0
    for (i = 0;i < cur->nodeNr;i++) {
2853
0
        if ((cur->nodeTab[i] != NULL) &&
2854
0
      (cur->nodeTab[i]->type == XML_NAMESPACE_DECL) &&
2855
0
      (((xmlNsPtr)cur->nodeTab[i])->next == (xmlNsPtr) node) &&
2856
0
      (xmlStrEqual(ns->prefix, ((xmlNsPtr)cur->nodeTab[i])->prefix)))
2857
0
      return(0);
2858
0
    }
2859
2860
    /*
2861
     * grow the nodeTab if needed
2862
     */
2863
0
    if (cur->nodeNr >= cur->nodeMax) {
2864
0
        if (xmlXPathNodeSetGrow(cur) < 0)
2865
0
            return(-1);
2866
0
    }
2867
0
    nsNode = xmlXPathNodeSetDupNs(node, ns);
2868
0
    if(nsNode == NULL)
2869
0
        return(-1);
2870
0
    cur->nodeTab[cur->nodeNr++] = nsNode;
2871
0
    return(0);
2872
0
}
2873
2874
/**
2875
 * xmlXPathNodeSetAdd:
2876
 * @cur:  the initial node set
2877
 * @val:  a new xmlNodePtr
2878
 *
2879
 * add a new xmlNodePtr to an existing NodeSet
2880
 *
2881
 * Returns 0 in case of success, and -1 in case of error
2882
 */
2883
int
2884
0
xmlXPathNodeSetAdd(xmlNodeSetPtr cur, xmlNodePtr val) {
2885
0
    int i;
2886
2887
0
    if ((cur == NULL) || (val == NULL)) return(-1);
2888
2889
    /* @@ with_ns to check whether namespace nodes should be looked at @@ */
2890
    /*
2891
     * prevent duplicates
2892
     */
2893
0
    for (i = 0;i < cur->nodeNr;i++)
2894
0
        if (cur->nodeTab[i] == val) return(0);
2895
2896
    /*
2897
     * grow the nodeTab if needed
2898
     */
2899
0
    if (cur->nodeNr >= cur->nodeMax) {
2900
0
        if (xmlXPathNodeSetGrow(cur) < 0)
2901
0
            return(-1);
2902
0
    }
2903
2904
0
    if (val->type == XML_NAMESPACE_DECL) {
2905
0
  xmlNsPtr ns = (xmlNsPtr) val;
2906
0
        xmlNodePtr nsNode = xmlXPathNodeSetDupNs((xmlNodePtr) ns->next, ns);
2907
2908
0
        if (nsNode == NULL)
2909
0
            return(-1);
2910
0
  cur->nodeTab[cur->nodeNr++] = nsNode;
2911
0
    } else
2912
0
  cur->nodeTab[cur->nodeNr++] = val;
2913
0
    return(0);
2914
0
}
2915
2916
/**
2917
 * xmlXPathNodeSetAddUnique:
2918
 * @cur:  the initial node set
2919
 * @val:  a new xmlNodePtr
2920
 *
2921
 * add a new xmlNodePtr to an existing NodeSet, optimized version
2922
 * when we are sure the node is not already in the set.
2923
 *
2924
 * Returns 0 in case of success and -1 in case of failure
2925
 */
2926
int
2927
568
xmlXPathNodeSetAddUnique(xmlNodeSetPtr cur, xmlNodePtr val) {
2928
568
    if ((cur == NULL) || (val == NULL)) return(-1);
2929
2930
    /* @@ with_ns to check whether namespace nodes should be looked at @@ */
2931
    /*
2932
     * grow the nodeTab if needed
2933
     */
2934
568
    if (cur->nodeNr >= cur->nodeMax) {
2935
568
        if (xmlXPathNodeSetGrow(cur) < 0)
2936
0
            return(-1);
2937
568
    }
2938
2939
568
    if (val->type == XML_NAMESPACE_DECL) {
2940
0
  xmlNsPtr ns = (xmlNsPtr) val;
2941
0
        xmlNodePtr nsNode = xmlXPathNodeSetDupNs((xmlNodePtr) ns->next, ns);
2942
2943
0
        if (nsNode == NULL)
2944
0
            return(-1);
2945
0
  cur->nodeTab[cur->nodeNr++] = nsNode;
2946
0
    } else
2947
568
  cur->nodeTab[cur->nodeNr++] = val;
2948
568
    return(0);
2949
568
}
2950
2951
/**
2952
 * xmlXPathNodeSetMerge:
2953
 * @val1:  the first NodeSet or NULL
2954
 * @val2:  the second NodeSet
2955
 *
2956
 * Merges two nodesets, all nodes from @val2 are added to @val1
2957
 * if @val1 is NULL, a new set is created and copied from @val2
2958
 *
2959
 * Returns @val1 once extended or NULL in case of error.
2960
 *
2961
 * Frees @val1 in case of error.
2962
 */
2963
xmlNodeSetPtr
2964
0
xmlXPathNodeSetMerge(xmlNodeSetPtr val1, xmlNodeSetPtr val2) {
2965
0
    int i, j, initNr, skip;
2966
0
    xmlNodePtr n1, n2;
2967
2968
0
    if (val1 == NULL) {
2969
0
  val1 = xmlXPathNodeSetCreate(NULL);
2970
0
        if (val1 == NULL)
2971
0
            return (NULL);
2972
0
    }
2973
0
    if (val2 == NULL)
2974
0
        return(val1);
2975
2976
    /* @@ with_ns to check whether namespace nodes should be looked at @@ */
2977
0
    initNr = val1->nodeNr;
2978
2979
0
    for (i = 0;i < val2->nodeNr;i++) {
2980
0
  n2 = val2->nodeTab[i];
2981
  /*
2982
   * check against duplicates
2983
   */
2984
0
  skip = 0;
2985
0
  for (j = 0; j < initNr; j++) {
2986
0
      n1 = val1->nodeTab[j];
2987
0
      if (n1 == n2) {
2988
0
    skip = 1;
2989
0
    break;
2990
0
      } else if ((n1->type == XML_NAMESPACE_DECL) &&
2991
0
           (n2->type == XML_NAMESPACE_DECL)) {
2992
0
    if ((((xmlNsPtr) n1)->next == ((xmlNsPtr) n2)->next) &&
2993
0
        (xmlStrEqual(((xmlNsPtr) n1)->prefix,
2994
0
      ((xmlNsPtr) n2)->prefix)))
2995
0
    {
2996
0
        skip = 1;
2997
0
        break;
2998
0
    }
2999
0
      }
3000
0
  }
3001
0
  if (skip)
3002
0
      continue;
3003
3004
  /*
3005
   * grow the nodeTab if needed
3006
   */
3007
0
        if (val1->nodeNr >= val1->nodeMax) {
3008
0
            if (xmlXPathNodeSetGrow(val1) < 0)
3009
0
                goto error;
3010
0
        }
3011
0
  if (n2->type == XML_NAMESPACE_DECL) {
3012
0
      xmlNsPtr ns = (xmlNsPtr) n2;
3013
0
            xmlNodePtr nsNode = xmlXPathNodeSetDupNs((xmlNodePtr) ns->next, ns);
3014
3015
0
            if (nsNode == NULL)
3016
0
                goto error;
3017
0
      val1->nodeTab[val1->nodeNr++] = nsNode;
3018
0
  } else
3019
0
      val1->nodeTab[val1->nodeNr++] = n2;
3020
0
    }
3021
3022
0
    return(val1);
3023
3024
0
error:
3025
0
    xmlXPathFreeNodeSet(val1);
3026
0
    return(NULL);
3027
0
}
3028
3029
3030
/**
3031
 * xmlXPathNodeSetMergeAndClear:
3032
 * @set1:  the first NodeSet or NULL
3033
 * @set2:  the second NodeSet
3034
 *
3035
 * Merges two nodesets, all nodes from @set2 are added to @set1.
3036
 * Checks for duplicate nodes. Clears set2.
3037
 *
3038
 * Returns @set1 once extended or NULL in case of error.
3039
 *
3040
 * Frees @set1 in case of error.
3041
 */
3042
static xmlNodeSetPtr
3043
xmlXPathNodeSetMergeAndClear(xmlNodeSetPtr set1, xmlNodeSetPtr set2)
3044
0
{
3045
0
    {
3046
0
  int i, j, initNbSet1;
3047
0
  xmlNodePtr n1, n2;
3048
3049
0
  initNbSet1 = set1->nodeNr;
3050
0
  for (i = 0;i < set2->nodeNr;i++) {
3051
0
      n2 = set2->nodeTab[i];
3052
      /*
3053
      * Skip duplicates.
3054
      */
3055
0
      for (j = 0; j < initNbSet1; j++) {
3056
0
    n1 = set1->nodeTab[j];
3057
0
    if (n1 == n2) {
3058
0
        goto skip_node;
3059
0
    } else if ((n1->type == XML_NAMESPACE_DECL) &&
3060
0
        (n2->type == XML_NAMESPACE_DECL))
3061
0
    {
3062
0
        if ((((xmlNsPtr) n1)->next == ((xmlNsPtr) n2)->next) &&
3063
0
      (xmlStrEqual(((xmlNsPtr) n1)->prefix,
3064
0
      ((xmlNsPtr) n2)->prefix)))
3065
0
        {
3066
      /*
3067
      * Free the namespace node.
3068
      */
3069
0
      xmlXPathNodeSetFreeNs((xmlNsPtr) n2);
3070
0
      goto skip_node;
3071
0
        }
3072
0
    }
3073
0
      }
3074
      /*
3075
      * grow the nodeTab if needed
3076
      */
3077
0
            if (set1->nodeNr >= set1->nodeMax) {
3078
0
                if (xmlXPathNodeSetGrow(set1) < 0)
3079
0
                    goto error;
3080
0
            }
3081
0
      set1->nodeTab[set1->nodeNr++] = n2;
3082
0
skip_node:
3083
0
            set2->nodeTab[i] = NULL;
3084
0
  }
3085
0
    }
3086
0
    set2->nodeNr = 0;
3087
0
    return(set1);
3088
3089
0
error:
3090
0
    xmlXPathFreeNodeSet(set1);
3091
0
    xmlXPathNodeSetClear(set2, 1);
3092
0
    return(NULL);
3093
0
}
3094
3095
/**
3096
 * xmlXPathNodeSetMergeAndClearNoDupls:
3097
 * @set1:  the first NodeSet or NULL
3098
 * @set2:  the second NodeSet
3099
 *
3100
 * Merges two nodesets, all nodes from @set2 are added to @set1.
3101
 * Doesn't check for duplicate nodes. Clears set2.
3102
 *
3103
 * Returns @set1 once extended or NULL in case of error.
3104
 *
3105
 * Frees @set1 in case of error.
3106
 */
3107
static xmlNodeSetPtr
3108
xmlXPathNodeSetMergeAndClearNoDupls(xmlNodeSetPtr set1, xmlNodeSetPtr set2)
3109
0
{
3110
0
    {
3111
0
  int i;
3112
0
  xmlNodePtr n2;
3113
3114
0
  for (i = 0;i < set2->nodeNr;i++) {
3115
0
      n2 = set2->nodeTab[i];
3116
0
            if (set1->nodeNr >= set1->nodeMax) {
3117
0
                if (xmlXPathNodeSetGrow(set1) < 0)
3118
0
                    goto error;
3119
0
            }
3120
0
      set1->nodeTab[set1->nodeNr++] = n2;
3121
0
            set2->nodeTab[i] = NULL;
3122
0
  }
3123
0
    }
3124
0
    set2->nodeNr = 0;
3125
0
    return(set1);
3126
3127
0
error:
3128
0
    xmlXPathFreeNodeSet(set1);
3129
0
    xmlXPathNodeSetClear(set2, 1);
3130
0
    return(NULL);
3131
0
}
3132
3133
/**
3134
 * xmlXPathNodeSetDel:
3135
 * @cur:  the initial node set
3136
 * @val:  an xmlNodePtr
3137
 *
3138
 * Removes an xmlNodePtr from an existing NodeSet
3139
 */
3140
void
3141
0
xmlXPathNodeSetDel(xmlNodeSetPtr cur, xmlNodePtr val) {
3142
0
    int i;
3143
3144
0
    if (cur == NULL) return;
3145
0
    if (val == NULL) return;
3146
3147
    /*
3148
     * find node in nodeTab
3149
     */
3150
0
    for (i = 0;i < cur->nodeNr;i++)
3151
0
        if (cur->nodeTab[i] == val) break;
3152
3153
0
    if (i >= cur->nodeNr) { /* not found */
3154
0
        return;
3155
0
    }
3156
0
    if ((cur->nodeTab[i] != NULL) &&
3157
0
  (cur->nodeTab[i]->type == XML_NAMESPACE_DECL))
3158
0
  xmlXPathNodeSetFreeNs((xmlNsPtr) cur->nodeTab[i]);
3159
0
    cur->nodeNr--;
3160
0
    for (;i < cur->nodeNr;i++)
3161
0
        cur->nodeTab[i] = cur->nodeTab[i + 1];
3162
0
    cur->nodeTab[cur->nodeNr] = NULL;
3163
0
}
3164
3165
/**
3166
 * xmlXPathNodeSetRemove:
3167
 * @cur:  the initial node set
3168
 * @val:  the index to remove
3169
 *
3170
 * Removes an entry from an existing NodeSet list.
3171
 */
3172
void
3173
0
xmlXPathNodeSetRemove(xmlNodeSetPtr cur, int val) {
3174
0
    if (cur == NULL) return;
3175
0
    if (val >= cur->nodeNr) return;
3176
0
    if ((cur->nodeTab[val] != NULL) &&
3177
0
  (cur->nodeTab[val]->type == XML_NAMESPACE_DECL))
3178
0
  xmlXPathNodeSetFreeNs((xmlNsPtr) cur->nodeTab[val]);
3179
0
    cur->nodeNr--;
3180
0
    for (;val < cur->nodeNr;val++)
3181
0
        cur->nodeTab[val] = cur->nodeTab[val + 1];
3182
0
    cur->nodeTab[cur->nodeNr] = NULL;
3183
0
}
3184
3185
/**
3186
 * xmlXPathFreeNodeSet:
3187
 * @obj:  the xmlNodeSetPtr to free
3188
 *
3189
 * Free the NodeSet compound (not the actual nodes !).
3190
 */
3191
void
3192
1.55k
xmlXPathFreeNodeSet(xmlNodeSetPtr obj) {
3193
1.55k
    if (obj == NULL) return;
3194
1.55k
    if (obj->nodeTab != NULL) {
3195
1.20k
  int i;
3196
3197
  /* @@ with_ns to check whether namespace nodes should be looked at @@ */
3198
2.40k
  for (i = 0;i < obj->nodeNr;i++)
3199
1.20k
      if ((obj->nodeTab[i] != NULL) &&
3200
1.20k
    (obj->nodeTab[i]->type == XML_NAMESPACE_DECL))
3201
0
    xmlXPathNodeSetFreeNs((xmlNsPtr) obj->nodeTab[i]);
3202
1.20k
  xmlFree(obj->nodeTab);
3203
1.20k
    }
3204
1.55k
    xmlFree(obj);
3205
1.55k
}
3206
3207
/**
3208
 * xmlXPathNodeSetClearFromPos:
3209
 * @set: the node set to be cleared
3210
 * @pos: the start position to clear from
3211
 *
3212
 * Clears the list from temporary XPath objects (e.g. namespace nodes
3213
 * are feed) starting with the entry at @pos, but does *not* free the list
3214
 * itself. Sets the length of the list to @pos.
3215
 */
3216
static void
3217
xmlXPathNodeSetClearFromPos(xmlNodeSetPtr set, int pos, int hasNsNodes)
3218
0
{
3219
0
    if ((set == NULL) || (pos >= set->nodeNr))
3220
0
  return;
3221
0
    else if ((hasNsNodes)) {
3222
0
  int i;
3223
0
  xmlNodePtr node;
3224
3225
0
  for (i = pos; i < set->nodeNr; i++) {
3226
0
      node = set->nodeTab[i];
3227
0
      if ((node != NULL) &&
3228
0
    (node->type == XML_NAMESPACE_DECL))
3229
0
    xmlXPathNodeSetFreeNs((xmlNsPtr) node);
3230
0
  }
3231
0
    }
3232
0
    set->nodeNr = pos;
3233
0
}
3234
3235
/**
3236
 * xmlXPathNodeSetClear:
3237
 * @set:  the node set to clear
3238
 *
3239
 * Clears the list from all temporary XPath objects (e.g. namespace nodes
3240
 * are feed), but does *not* free the list itself. Sets the length of the
3241
 * list to 0.
3242
 */
3243
static void
3244
xmlXPathNodeSetClear(xmlNodeSetPtr set, int hasNsNodes)
3245
0
{
3246
0
    xmlXPathNodeSetClearFromPos(set, 0, hasNsNodes);
3247
0
}
3248
3249
/**
3250
 * xmlXPathNodeSetKeepLast:
3251
 * @set: the node set to be cleared
3252
 *
3253
 * Move the last node to the first position and clear temporary XPath objects
3254
 * (e.g. namespace nodes) from all other nodes. Sets the length of the list
3255
 * to 1.
3256
 */
3257
static void
3258
xmlXPathNodeSetKeepLast(xmlNodeSetPtr set)
3259
0
{
3260
0
    int i;
3261
0
    xmlNodePtr node;
3262
3263
0
    if ((set == NULL) || (set->nodeNr <= 1))
3264
0
  return;
3265
0
    for (i = 0; i < set->nodeNr - 1; i++) {
3266
0
        node = set->nodeTab[i];
3267
0
        if ((node != NULL) &&
3268
0
            (node->type == XML_NAMESPACE_DECL))
3269
0
            xmlXPathNodeSetFreeNs((xmlNsPtr) node);
3270
0
    }
3271
0
    set->nodeTab[0] = set->nodeTab[set->nodeNr-1];
3272
0
    set->nodeNr = 1;
3273
0
}
3274
3275
/**
3276
 * xmlXPathNewNodeSet:
3277
 * @val:  the NodePtr value
3278
 *
3279
 * Create a new xmlXPathObjectPtr of type NodeSet and initialize
3280
 * it with the single Node @val
3281
 *
3282
 * Returns the newly created object.
3283
 */
3284
xmlXPathObjectPtr
3285
633
xmlXPathNewNodeSet(xmlNodePtr val) {
3286
633
    xmlXPathObjectPtr ret;
3287
3288
633
    ret = (xmlXPathObjectPtr) xmlMalloc(sizeof(xmlXPathObject));
3289
633
    if (ret == NULL)
3290
0
  return(NULL);
3291
633
    memset(ret, 0 , sizeof(xmlXPathObject));
3292
633
    ret->type = XPATH_NODESET;
3293
633
    ret->boolval = 0;
3294
633
    ret->nodesetval = xmlXPathNodeSetCreate(val);
3295
633
    if (ret->nodesetval == NULL) {
3296
0
        xmlFree(ret);
3297
0
        return(NULL);
3298
0
    }
3299
    /* @@ with_ns to check whether namespace nodes should be looked at @@ */
3300
633
    return(ret);
3301
633
}
3302
3303
/**
3304
 * xmlXPathNewValueTree:
3305
 * @val:  the NodePtr value
3306
 *
3307
 * Create a new xmlXPathObjectPtr of type Value Tree (XSLT) and initialize
3308
 * it with the tree root @val
3309
 *
3310
 * Returns the newly created object.
3311
 */
3312
xmlXPathObjectPtr
3313
0
xmlXPathNewValueTree(xmlNodePtr val) {
3314
0
    xmlXPathObjectPtr ret;
3315
3316
0
    ret = xmlXPathNewNodeSet(val);
3317
0
    if (ret == NULL)
3318
0
  return(NULL);
3319
0
    ret->type = XPATH_XSLT_TREE;
3320
3321
0
    return(ret);
3322
0
}
3323
3324
/**
3325
 * xmlXPathNewNodeSetList:
3326
 * @val:  an existing NodeSet
3327
 *
3328
 * Create a new xmlXPathObjectPtr of type NodeSet and initialize
3329
 * it with the Nodeset @val
3330
 *
3331
 * Returns the newly created object.
3332
 */
3333
xmlXPathObjectPtr
3334
xmlXPathNewNodeSetList(xmlNodeSetPtr val)
3335
0
{
3336
0
    xmlXPathObjectPtr ret;
3337
3338
0
    if (val == NULL)
3339
0
        ret = NULL;
3340
0
    else if (val->nodeTab == NULL)
3341
0
        ret = xmlXPathNewNodeSet(NULL);
3342
0
    else {
3343
0
        ret = xmlXPathNewNodeSet(val->nodeTab[0]);
3344
0
        if (ret) {
3345
0
            ret->nodesetval = xmlXPathNodeSetMerge(NULL, val);
3346
0
            if (ret->nodesetval == NULL) {
3347
0
                xmlFree(ret);
3348
0
                return(NULL);
3349
0
            }
3350
0
        }
3351
0
    }
3352
3353
0
    return (ret);
3354
0
}
3355
3356
/**
3357
 * xmlXPathWrapNodeSet:
3358
 * @val:  the NodePtr value
3359
 *
3360
 * Wrap the Nodeset @val in a new xmlXPathObjectPtr
3361
 *
3362
 * Returns the newly created object.
3363
 *
3364
 * In case of error the node set is destroyed and NULL is returned.
3365
 */
3366
xmlXPathObjectPtr
3367
917
xmlXPathWrapNodeSet(xmlNodeSetPtr val) {
3368
917
    xmlXPathObjectPtr ret;
3369
3370
917
    ret = (xmlXPathObjectPtr) xmlMalloc(sizeof(xmlXPathObject));
3371
917
    if (ret == NULL) {
3372
0
        xmlXPathFreeNodeSet(val);
3373
0
  return(NULL);
3374
0
    }
3375
917
    memset(ret, 0 , sizeof(xmlXPathObject));
3376
917
    ret->type = XPATH_NODESET;
3377
917
    ret->nodesetval = val;
3378
917
    return(ret);
3379
917
}
3380
3381
/**
3382
 * xmlXPathFreeNodeSetList:
3383
 * @obj:  an existing NodeSetList object
3384
 *
3385
 * Free up the xmlXPathObjectPtr @obj but don't deallocate the objects in
3386
 * the list contrary to xmlXPathFreeObject().
3387
 */
3388
void
3389
0
xmlXPathFreeNodeSetList(xmlXPathObjectPtr obj) {
3390
0
    if (obj == NULL) return;
3391
0
    xmlFree(obj);
3392
0
}
3393
3394
/**
3395
 * xmlXPathDifference:
3396
 * @nodes1:  a node-set
3397
 * @nodes2:  a node-set
3398
 *
3399
 * Implements the EXSLT - Sets difference() function:
3400
 *    node-set set:difference (node-set, node-set)
3401
 *
3402
 * Returns the difference between the two node sets, or nodes1 if
3403
 *         nodes2 is empty
3404
 */
3405
xmlNodeSetPtr
3406
0
xmlXPathDifference (xmlNodeSetPtr nodes1, xmlNodeSetPtr nodes2) {
3407
0
    xmlNodeSetPtr ret;
3408
0
    int i, l1;
3409
0
    xmlNodePtr cur;
3410
3411
0
    if (xmlXPathNodeSetIsEmpty(nodes2))
3412
0
  return(nodes1);
3413
3414
0
    ret = xmlXPathNodeSetCreate(NULL);
3415
0
    if (ret == NULL)
3416
0
        return(NULL);
3417
0
    if (xmlXPathNodeSetIsEmpty(nodes1))
3418
0
  return(ret);
3419
3420
0
    l1 = xmlXPathNodeSetGetLength(nodes1);
3421
3422
0
    for (i = 0; i < l1; i++) {
3423
0
  cur = xmlXPathNodeSetItem(nodes1, i);
3424
0
  if (!xmlXPathNodeSetContains(nodes2, cur)) {
3425
0
      if (xmlXPathNodeSetAddUnique(ret, cur) < 0) {
3426
0
                xmlXPathFreeNodeSet(ret);
3427
0
          return(NULL);
3428
0
            }
3429
0
  }
3430
0
    }
3431
0
    return(ret);
3432
0
}
3433
3434
/**
3435
 * xmlXPathIntersection:
3436
 * @nodes1:  a node-set
3437
 * @nodes2:  a node-set
3438
 *
3439
 * Implements the EXSLT - Sets intersection() function:
3440
 *    node-set set:intersection (node-set, node-set)
3441
 *
3442
 * Returns a node set comprising the nodes that are within both the
3443
 *         node sets passed as arguments
3444
 */
3445
xmlNodeSetPtr
3446
0
xmlXPathIntersection (xmlNodeSetPtr nodes1, xmlNodeSetPtr nodes2) {
3447
0
    xmlNodeSetPtr ret = xmlXPathNodeSetCreate(NULL);
3448
0
    int i, l1;
3449
0
    xmlNodePtr cur;
3450
3451
0
    if (ret == NULL)
3452
0
        return(ret);
3453
0
    if (xmlXPathNodeSetIsEmpty(nodes1))
3454
0
  return(ret);
3455
0
    if (xmlXPathNodeSetIsEmpty(nodes2))
3456
0
  return(ret);
3457
3458
0
    l1 = xmlXPathNodeSetGetLength(nodes1);
3459
3460
0
    for (i = 0; i < l1; i++) {
3461
0
  cur = xmlXPathNodeSetItem(nodes1, i);
3462
0
  if (xmlXPathNodeSetContains(nodes2, cur)) {
3463
0
      if (xmlXPathNodeSetAddUnique(ret, cur) < 0) {
3464
0
                xmlXPathFreeNodeSet(ret);
3465
0
          return(NULL);
3466
0
            }
3467
0
  }
3468
0
    }
3469
0
    return(ret);
3470
0
}
3471
3472
/**
3473
 * xmlXPathDistinctSorted:
3474
 * @nodes:  a node-set, sorted by document order
3475
 *
3476
 * Implements the EXSLT - Sets distinct() function:
3477
 *    node-set set:distinct (node-set)
3478
 *
3479
 * Returns a subset of the nodes contained in @nodes, or @nodes if
3480
 *         it is empty
3481
 */
3482
xmlNodeSetPtr
3483
0
xmlXPathDistinctSorted (xmlNodeSetPtr nodes) {
3484
0
    xmlNodeSetPtr ret;
3485
0
    xmlHashTablePtr hash;
3486
0
    int i, l;
3487
0
    xmlChar * strval;
3488
0
    xmlNodePtr cur;
3489
3490
0
    if (xmlXPathNodeSetIsEmpty(nodes))
3491
0
  return(nodes);
3492
3493
0
    ret = xmlXPathNodeSetCreate(NULL);
3494
0
    if (ret == NULL)
3495
0
        return(ret);
3496
0
    l = xmlXPathNodeSetGetLength(nodes);
3497
0
    hash = xmlHashCreate (l);
3498
0
    for (i = 0; i < l; i++) {
3499
0
  cur = xmlXPathNodeSetItem(nodes, i);
3500
0
  strval = xmlXPathCastNodeToString(cur);
3501
0
  if (xmlHashLookup(hash, strval) == NULL) {
3502
0
      if (xmlHashAddEntry(hash, strval, strval) < 0) {
3503
0
                xmlFree(strval);
3504
0
                goto error;
3505
0
            }
3506
0
      if (xmlXPathNodeSetAddUnique(ret, cur) < 0)
3507
0
          goto error;
3508
0
  } else {
3509
0
      xmlFree(strval);
3510
0
  }
3511
0
    }
3512
0
    xmlHashFree(hash, xmlHashDefaultDeallocator);
3513
0
    return(ret);
3514
3515
0
error:
3516
0
    xmlHashFree(hash, xmlHashDefaultDeallocator);
3517
0
    xmlXPathFreeNodeSet(ret);
3518
0
    return(NULL);
3519
0
}
3520
3521
/**
3522
 * xmlXPathDistinct:
3523
 * @nodes:  a node-set
3524
 *
3525
 * Implements the EXSLT - Sets distinct() function:
3526
 *    node-set set:distinct (node-set)
3527
 * @nodes is sorted by document order, then #exslSetsDistinctSorted
3528
 * is called with the sorted node-set
3529
 *
3530
 * Returns a subset of the nodes contained in @nodes, or @nodes if
3531
 *         it is empty
3532
 */
3533
xmlNodeSetPtr
3534
0
xmlXPathDistinct (xmlNodeSetPtr nodes) {
3535
0
    if (xmlXPathNodeSetIsEmpty(nodes))
3536
0
  return(nodes);
3537
3538
0
    xmlXPathNodeSetSort(nodes);
3539
0
    return(xmlXPathDistinctSorted(nodes));
3540
0
}
3541
3542
/**
3543
 * xmlXPathHasSameNodes:
3544
 * @nodes1:  a node-set
3545
 * @nodes2:  a node-set
3546
 *
3547
 * Implements the EXSLT - Sets has-same-nodes function:
3548
 *    boolean set:has-same-node(node-set, node-set)
3549
 *
3550
 * Returns true (1) if @nodes1 shares any node with @nodes2, false (0)
3551
 *         otherwise
3552
 */
3553
int
3554
0
xmlXPathHasSameNodes (xmlNodeSetPtr nodes1, xmlNodeSetPtr nodes2) {
3555
0
    int i, l;
3556
0
    xmlNodePtr cur;
3557
3558
0
    if (xmlXPathNodeSetIsEmpty(nodes1) ||
3559
0
  xmlXPathNodeSetIsEmpty(nodes2))
3560
0
  return(0);
3561
3562
0
    l = xmlXPathNodeSetGetLength(nodes1);
3563
0
    for (i = 0; i < l; i++) {
3564
0
  cur = xmlXPathNodeSetItem(nodes1, i);
3565
0
  if (xmlXPathNodeSetContains(nodes2, cur))
3566
0
      return(1);
3567
0
    }
3568
0
    return(0);
3569
0
}
3570
3571
/**
3572
 * xmlXPathNodeLeadingSorted:
3573
 * @nodes: a node-set, sorted by document order
3574
 * @node: a node
3575
 *
3576
 * Implements the EXSLT - Sets leading() function:
3577
 *    node-set set:leading (node-set, node-set)
3578
 *
3579
 * Returns the nodes in @nodes that precede @node in document order,
3580
 *         @nodes if @node is NULL or an empty node-set if @nodes
3581
 *         doesn't contain @node
3582
 */
3583
xmlNodeSetPtr
3584
0
xmlXPathNodeLeadingSorted (xmlNodeSetPtr nodes, xmlNodePtr node) {
3585
0
    int i, l;
3586
0
    xmlNodePtr cur;
3587
0
    xmlNodeSetPtr ret;
3588
3589
0
    if (node == NULL)
3590
0
  return(nodes);
3591
3592
0
    ret = xmlXPathNodeSetCreate(NULL);
3593
0
    if (ret == NULL)
3594
0
        return(ret);
3595
0
    if (xmlXPathNodeSetIsEmpty(nodes) ||
3596
0
  (!xmlXPathNodeSetContains(nodes, node)))
3597
0
  return(ret);
3598
3599
0
    l = xmlXPathNodeSetGetLength(nodes);
3600
0
    for (i = 0; i < l; i++) {
3601
0
  cur = xmlXPathNodeSetItem(nodes, i);
3602
0
  if (cur == node)
3603
0
      break;
3604
0
  if (xmlXPathNodeSetAddUnique(ret, cur) < 0) {
3605
0
            xmlXPathFreeNodeSet(ret);
3606
0
      return(NULL);
3607
0
        }
3608
0
    }
3609
0
    return(ret);
3610
0
}
3611
3612
/**
3613
 * xmlXPathNodeLeading:
3614
 * @nodes:  a node-set
3615
 * @node:  a node
3616
 *
3617
 * Implements the EXSLT - Sets leading() function:
3618
 *    node-set set:leading (node-set, node-set)
3619
 * @nodes is sorted by document order, then #exslSetsNodeLeadingSorted
3620
 * is called.
3621
 *
3622
 * Returns the nodes in @nodes that precede @node in document order,
3623
 *         @nodes if @node is NULL or an empty node-set if @nodes
3624
 *         doesn't contain @node
3625
 */
3626
xmlNodeSetPtr
3627
0
xmlXPathNodeLeading (xmlNodeSetPtr nodes, xmlNodePtr node) {
3628
0
    xmlXPathNodeSetSort(nodes);
3629
0
    return(xmlXPathNodeLeadingSorted(nodes, node));
3630
0
}
3631
3632
/**
3633
 * xmlXPathLeadingSorted:
3634
 * @nodes1:  a node-set, sorted by document order
3635
 * @nodes2:  a node-set, sorted by document order
3636
 *
3637
 * Implements the EXSLT - Sets leading() function:
3638
 *    node-set set:leading (node-set, node-set)
3639
 *
3640
 * Returns the nodes in @nodes1 that precede the first node in @nodes2
3641
 *         in document order, @nodes1 if @nodes2 is NULL or empty or
3642
 *         an empty node-set if @nodes1 doesn't contain @nodes2
3643
 */
3644
xmlNodeSetPtr
3645
0
xmlXPathLeadingSorted (xmlNodeSetPtr nodes1, xmlNodeSetPtr nodes2) {
3646
0
    if (xmlXPathNodeSetIsEmpty(nodes2))
3647
0
  return(nodes1);
3648
0
    return(xmlXPathNodeLeadingSorted(nodes1,
3649
0
             xmlXPathNodeSetItem(nodes2, 1)));
3650
0
}
3651
3652
/**
3653
 * xmlXPathLeading:
3654
 * @nodes1:  a node-set
3655
 * @nodes2:  a node-set
3656
 *
3657
 * Implements the EXSLT - Sets leading() function:
3658
 *    node-set set:leading (node-set, node-set)
3659
 * @nodes1 and @nodes2 are sorted by document order, then
3660
 * #exslSetsLeadingSorted is called.
3661
 *
3662
 * Returns the nodes in @nodes1 that precede the first node in @nodes2
3663
 *         in document order, @nodes1 if @nodes2 is NULL or empty or
3664
 *         an empty node-set if @nodes1 doesn't contain @nodes2
3665
 */
3666
xmlNodeSetPtr
3667
0
xmlXPathLeading (xmlNodeSetPtr nodes1, xmlNodeSetPtr nodes2) {
3668
0
    if (xmlXPathNodeSetIsEmpty(nodes2))
3669
0
  return(nodes1);
3670
0
    if (xmlXPathNodeSetIsEmpty(nodes1))
3671
0
  return(xmlXPathNodeSetCreate(NULL));
3672
0
    xmlXPathNodeSetSort(nodes1);
3673
0
    xmlXPathNodeSetSort(nodes2);
3674
0
    return(xmlXPathNodeLeadingSorted(nodes1,
3675
0
             xmlXPathNodeSetItem(nodes2, 1)));
3676
0
}
3677
3678
/**
3679
 * xmlXPathNodeTrailingSorted:
3680
 * @nodes: a node-set, sorted by document order
3681
 * @node: a node
3682
 *
3683
 * Implements the EXSLT - Sets trailing() function:
3684
 *    node-set set:trailing (node-set, node-set)
3685
 *
3686
 * Returns the nodes in @nodes that follow @node in document order,
3687
 *         @nodes if @node is NULL or an empty node-set if @nodes
3688
 *         doesn't contain @node
3689
 */
3690
xmlNodeSetPtr
3691
0
xmlXPathNodeTrailingSorted (xmlNodeSetPtr nodes, xmlNodePtr node) {
3692
0
    int i, l;
3693
0
    xmlNodePtr cur;
3694
0
    xmlNodeSetPtr ret;
3695
3696
0
    if (node == NULL)
3697
0
  return(nodes);
3698
3699
0
    ret = xmlXPathNodeSetCreate(NULL);
3700
0
    if (ret == NULL)
3701
0
        return(ret);
3702
0
    if (xmlXPathNodeSetIsEmpty(nodes) ||
3703
0
  (!xmlXPathNodeSetContains(nodes, node)))
3704
0
  return(ret);
3705
3706
0
    l = xmlXPathNodeSetGetLength(nodes);
3707
0
    for (i = l - 1; i >= 0; i--) {
3708
0
  cur = xmlXPathNodeSetItem(nodes, i);
3709
0
  if (cur == node)
3710
0
      break;
3711
0
  if (xmlXPathNodeSetAddUnique(ret, cur) < 0) {
3712
0
            xmlXPathFreeNodeSet(ret);
3713
0
      return(NULL);
3714
0
        }
3715
0
    }
3716
0
    xmlXPathNodeSetSort(ret); /* bug 413451 */
3717
0
    return(ret);
3718
0
}
3719
3720
/**
3721
 * xmlXPathNodeTrailing:
3722
 * @nodes:  a node-set
3723
 * @node:  a node
3724
 *
3725
 * Implements the EXSLT - Sets trailing() function:
3726
 *    node-set set:trailing (node-set, node-set)
3727
 * @nodes is sorted by document order, then #xmlXPathNodeTrailingSorted
3728
 * is called.
3729
 *
3730
 * Returns the nodes in @nodes that follow @node in document order,
3731
 *         @nodes if @node is NULL or an empty node-set if @nodes
3732
 *         doesn't contain @node
3733
 */
3734
xmlNodeSetPtr
3735
0
xmlXPathNodeTrailing (xmlNodeSetPtr nodes, xmlNodePtr node) {
3736
0
    xmlXPathNodeSetSort(nodes);
3737
0
    return(xmlXPathNodeTrailingSorted(nodes, node));
3738
0
}
3739
3740
/**
3741
 * xmlXPathTrailingSorted:
3742
 * @nodes1:  a node-set, sorted by document order
3743
 * @nodes2:  a node-set, sorted by document order
3744
 *
3745
 * Implements the EXSLT - Sets trailing() function:
3746
 *    node-set set:trailing (node-set, node-set)
3747
 *
3748
 * Returns the nodes in @nodes1 that follow the first node in @nodes2
3749
 *         in document order, @nodes1 if @nodes2 is NULL or empty or
3750
 *         an empty node-set if @nodes1 doesn't contain @nodes2
3751
 */
3752
xmlNodeSetPtr
3753
0
xmlXPathTrailingSorted (xmlNodeSetPtr nodes1, xmlNodeSetPtr nodes2) {
3754
0
    if (xmlXPathNodeSetIsEmpty(nodes2))
3755
0
  return(nodes1);
3756
0
    return(xmlXPathNodeTrailingSorted(nodes1,
3757
0
              xmlXPathNodeSetItem(nodes2, 0)));
3758
0
}
3759
3760
/**
3761
 * xmlXPathTrailing:
3762
 * @nodes1:  a node-set
3763
 * @nodes2:  a node-set
3764
 *
3765
 * Implements the EXSLT - Sets trailing() function:
3766
 *    node-set set:trailing (node-set, node-set)
3767
 * @nodes1 and @nodes2 are sorted by document order, then
3768
 * #xmlXPathTrailingSorted is called.
3769
 *
3770
 * Returns the nodes in @nodes1 that follow the first node in @nodes2
3771
 *         in document order, @nodes1 if @nodes2 is NULL or empty or
3772
 *         an empty node-set if @nodes1 doesn't contain @nodes2
3773
 */
3774
xmlNodeSetPtr
3775
0
xmlXPathTrailing (xmlNodeSetPtr nodes1, xmlNodeSetPtr nodes2) {
3776
0
    if (xmlXPathNodeSetIsEmpty(nodes2))
3777
0
  return(nodes1);
3778
0
    if (xmlXPathNodeSetIsEmpty(nodes1))
3779
0
  return(xmlXPathNodeSetCreate(NULL));
3780
0
    xmlXPathNodeSetSort(nodes1);
3781
0
    xmlXPathNodeSetSort(nodes2);
3782
0
    return(xmlXPathNodeTrailingSorted(nodes1,
3783
0
              xmlXPathNodeSetItem(nodes2, 0)));
3784
0
}
3785
3786
/************************************************************************
3787
 *                  *
3788
 *    Routines to handle extra functions      *
3789
 *                  *
3790
 ************************************************************************/
3791
3792
/**
3793
 * xmlXPathRegisterFunc:
3794
 * @ctxt:  the XPath context
3795
 * @name:  the function name
3796
 * @f:  the function implementation or NULL
3797
 *
3798
 * Register a new function. If @f is NULL it unregisters the function
3799
 *
3800
 * Returns 0 in case of success, -1 in case of error
3801
 */
3802
int
3803
xmlXPathRegisterFunc(xmlXPathContextPtr ctxt, const xmlChar *name,
3804
0
         xmlXPathFunction f) {
3805
0
    return(xmlXPathRegisterFuncNS(ctxt, name, NULL, f));
3806
0
}
3807
3808
/**
3809
 * xmlXPathRegisterFuncNS:
3810
 * @ctxt:  the XPath context
3811
 * @name:  the function name
3812
 * @ns_uri:  the function namespace URI
3813
 * @f:  the function implementation or NULL
3814
 *
3815
 * Register a new function. If @f is NULL it unregisters the function
3816
 *
3817
 * Returns 0 in case of success, -1 in case of error
3818
 */
3819
int
3820
xmlXPathRegisterFuncNS(xmlXPathContextPtr ctxt, const xmlChar *name,
3821
0
           const xmlChar *ns_uri, xmlXPathFunction f) {
3822
0
    int ret;
3823
0
    void *payload;
3824
3825
0
    if (ctxt == NULL)
3826
0
  return(-1);
3827
0
    if (name == NULL)
3828
0
  return(-1);
3829
3830
0
    if (ctxt->funcHash == NULL)
3831
0
  ctxt->funcHash = xmlHashCreate(0);
3832
0
    if (ctxt->funcHash == NULL) {
3833
0
        xmlXPathErrMemory(ctxt);
3834
0
  return(-1);
3835
0
    }
3836
0
    if (f == NULL)
3837
0
        return(xmlHashRemoveEntry2(ctxt->funcHash, name, ns_uri, NULL));
3838
0
    memcpy(&payload, &f, sizeof(f));
3839
0
    ret = xmlHashAddEntry2(ctxt->funcHash, name, ns_uri, payload);
3840
0
    if (ret < 0) {
3841
0
        xmlXPathErrMemory(ctxt);
3842
0
        return(-1);
3843
0
    }
3844
3845
0
    return(0);
3846
0
}
3847
3848
/**
3849
 * xmlXPathRegisterFuncLookup:
3850
 * @ctxt:  the XPath context
3851
 * @f:  the lookup function
3852
 * @funcCtxt:  the lookup data
3853
 *
3854
 * Registers an external mechanism to do function lookup.
3855
 */
3856
void
3857
xmlXPathRegisterFuncLookup (xmlXPathContextPtr ctxt,
3858
          xmlXPathFuncLookupFunc f,
3859
0
          void *funcCtxt) {
3860
0
    if (ctxt == NULL)
3861
0
  return;
3862
0
    ctxt->funcLookupFunc = f;
3863
0
    ctxt->funcLookupData = funcCtxt;
3864
0
}
3865
3866
/**
3867
 * xmlXPathFunctionLookup:
3868
 * @ctxt:  the XPath context
3869
 * @name:  the function name
3870
 *
3871
 * Search in the Function array of the context for the given
3872
 * function.
3873
 *
3874
 * Returns the xmlXPathFunction or NULL if not found
3875
 */
3876
xmlXPathFunction
3877
93
xmlXPathFunctionLookup(xmlXPathContextPtr ctxt, const xmlChar *name) {
3878
93
    return(xmlXPathFunctionLookupNS(ctxt, name, NULL));
3879
93
}
3880
3881
/**
3882
 * xmlXPathFunctionLookupNS:
3883
 * @ctxt:  the XPath context
3884
 * @name:  the function name
3885
 * @ns_uri:  the function namespace URI
3886
 *
3887
 * Search in the Function array of the context for the given
3888
 * function.
3889
 *
3890
 * Returns the xmlXPathFunction or NULL if not found
3891
 */
3892
xmlXPathFunction
3893
xmlXPathFunctionLookupNS(xmlXPathContextPtr ctxt, const xmlChar *name,
3894
93
       const xmlChar *ns_uri) {
3895
93
    xmlXPathFunction ret;
3896
93
    void *payload;
3897
3898
93
    if (ctxt == NULL)
3899
0
  return(NULL);
3900
93
    if (name == NULL)
3901
0
  return(NULL);
3902
3903
93
    if (ns_uri == NULL) {
3904
93
        int bucketIndex = xmlXPathSFComputeHash(name) % SF_HASH_SIZE;
3905
3906
93
        while (xmlXPathSFHash[bucketIndex] != UCHAR_MAX) {
3907
93
            int funcIndex = xmlXPathSFHash[bucketIndex];
3908
3909
93
            if (strcmp(xmlXPathStandardFunctions[funcIndex].name,
3910
93
                       (char *) name) == 0)
3911
93
                return(xmlXPathStandardFunctions[funcIndex].func);
3912
3913
0
            bucketIndex += 1;
3914
0
            if (bucketIndex >= SF_HASH_SIZE)
3915
0
                bucketIndex = 0;
3916
0
        }
3917
93
    }
3918
3919
0
    if (ctxt->funcLookupFunc != NULL) {
3920
0
  xmlXPathFuncLookupFunc f;
3921
3922
0
  f = ctxt->funcLookupFunc;
3923
0
  ret = f(ctxt->funcLookupData, name, ns_uri);
3924
0
  if (ret != NULL)
3925
0
      return(ret);
3926
0
    }
3927
3928
0
    if (ctxt->funcHash == NULL)
3929
0
  return(NULL);
3930
3931
0
    payload = xmlHashLookup2(ctxt->funcHash, name, ns_uri);
3932
0
    memcpy(&ret, &payload, sizeof(payload));
3933
3934
0
    return(ret);
3935
0
}
3936
3937
/**
3938
 * xmlXPathRegisteredFuncsCleanup:
3939
 * @ctxt:  the XPath context
3940
 *
3941
 * Cleanup the XPath context data associated to registered functions
3942
 */
3943
void
3944
633
xmlXPathRegisteredFuncsCleanup(xmlXPathContextPtr ctxt) {
3945
633
    if (ctxt == NULL)
3946
0
  return;
3947
3948
633
    xmlHashFree(ctxt->funcHash, NULL);
3949
633
    ctxt->funcHash = NULL;
3950
633
}
3951
3952
/************************************************************************
3953
 *                  *
3954
 *      Routines to handle Variables      *
3955
 *                  *
3956
 ************************************************************************/
3957
3958
/**
3959
 * xmlXPathRegisterVariable:
3960
 * @ctxt:  the XPath context
3961
 * @name:  the variable name
3962
 * @value:  the variable value or NULL
3963
 *
3964
 * Register a new variable value. If @value is NULL it unregisters
3965
 * the variable
3966
 *
3967
 * Returns 0 in case of success, -1 in case of error
3968
 */
3969
int
3970
xmlXPathRegisterVariable(xmlXPathContextPtr ctxt, const xmlChar *name,
3971
0
       xmlXPathObjectPtr value) {
3972
0
    return(xmlXPathRegisterVariableNS(ctxt, name, NULL, value));
3973
0
}
3974
3975
/**
3976
 * xmlXPathRegisterVariableNS:
3977
 * @ctxt:  the XPath context
3978
 * @name:  the variable name
3979
 * @ns_uri:  the variable namespace URI
3980
 * @value:  the variable value or NULL
3981
 *
3982
 * Register a new variable value. If @value is NULL it unregisters
3983
 * the variable
3984
 *
3985
 * Returns 0 in case of success, -1 in case of error
3986
 */
3987
int
3988
xmlXPathRegisterVariableNS(xmlXPathContextPtr ctxt, const xmlChar *name,
3989
         const xmlChar *ns_uri,
3990
0
         xmlXPathObjectPtr value) {
3991
0
    if (ctxt == NULL)
3992
0
  return(-1);
3993
0
    if (name == NULL)
3994
0
  return(-1);
3995
3996
0
    if (ctxt->varHash == NULL)
3997
0
  ctxt->varHash = xmlHashCreate(0);
3998
0
    if (ctxt->varHash == NULL)
3999
0
  return(-1);
4000
0
    if (value == NULL)
4001
0
        return(xmlHashRemoveEntry2(ctxt->varHash, name, ns_uri,
4002
0
                             xmlXPathFreeObjectEntry));
4003
0
    return(xmlHashUpdateEntry2(ctxt->varHash, name, ns_uri,
4004
0
             (void *) value, xmlXPathFreeObjectEntry));
4005
0
}
4006
4007
/**
4008
 * xmlXPathRegisterVariableLookup:
4009
 * @ctxt:  the XPath context
4010
 * @f:  the lookup function
4011
 * @data:  the lookup data
4012
 *
4013
 * register an external mechanism to do variable lookup
4014
 */
4015
void
4016
xmlXPathRegisterVariableLookup(xmlXPathContextPtr ctxt,
4017
0
   xmlXPathVariableLookupFunc f, void *data) {
4018
0
    if (ctxt == NULL)
4019
0
  return;
4020
0
    ctxt->varLookupFunc = f;
4021
0
    ctxt->varLookupData = data;
4022
0
}
4023
4024
/**
4025
 * xmlXPathVariableLookup:
4026
 * @ctxt:  the XPath context
4027
 * @name:  the variable name
4028
 *
4029
 * Search in the Variable array of the context for the given
4030
 * variable value.
4031
 *
4032
 * Returns a copy of the value or NULL if not found
4033
 */
4034
xmlXPathObjectPtr
4035
0
xmlXPathVariableLookup(xmlXPathContextPtr ctxt, const xmlChar *name) {
4036
0
    if (ctxt == NULL)
4037
0
  return(NULL);
4038
4039
0
    if (ctxt->varLookupFunc != NULL) {
4040
0
  xmlXPathObjectPtr ret;
4041
4042
0
  ret = ((xmlXPathVariableLookupFunc)ctxt->varLookupFunc)
4043
0
          (ctxt->varLookupData, name, NULL);
4044
0
  return(ret);
4045
0
    }
4046
0
    return(xmlXPathVariableLookupNS(ctxt, name, NULL));
4047
0
}
4048
4049
/**
4050
 * xmlXPathVariableLookupNS:
4051
 * @ctxt:  the XPath context
4052
 * @name:  the variable name
4053
 * @ns_uri:  the variable namespace URI
4054
 *
4055
 * Search in the Variable array of the context for the given
4056
 * variable value.
4057
 *
4058
 * Returns the a copy of the value or NULL if not found
4059
 */
4060
xmlXPathObjectPtr
4061
xmlXPathVariableLookupNS(xmlXPathContextPtr ctxt, const xmlChar *name,
4062
0
       const xmlChar *ns_uri) {
4063
0
    if (ctxt == NULL)
4064
0
  return(NULL);
4065
4066
0
    if (ctxt->varLookupFunc != NULL) {
4067
0
  xmlXPathObjectPtr ret;
4068
4069
0
  ret = ((xmlXPathVariableLookupFunc)ctxt->varLookupFunc)
4070
0
          (ctxt->varLookupData, name, ns_uri);
4071
0
  if (ret != NULL) return(ret);
4072
0
    }
4073
4074
0
    if (ctxt->varHash == NULL)
4075
0
  return(NULL);
4076
0
    if (name == NULL)
4077
0
  return(NULL);
4078
4079
0
    return(xmlXPathObjectCopy(xmlHashLookup2(ctxt->varHash, name, ns_uri)));
4080
0
}
4081
4082
/**
4083
 * xmlXPathRegisteredVariablesCleanup:
4084
 * @ctxt:  the XPath context
4085
 *
4086
 * Cleanup the XPath context data associated to registered variables
4087
 */
4088
void
4089
633
xmlXPathRegisteredVariablesCleanup(xmlXPathContextPtr ctxt) {
4090
633
    if (ctxt == NULL)
4091
0
  return;
4092
4093
633
    xmlHashFree(ctxt->varHash, xmlXPathFreeObjectEntry);
4094
633
    ctxt->varHash = NULL;
4095
633
}
4096
4097
/**
4098
 * xmlXPathRegisterNs:
4099
 * @ctxt:  the XPath context
4100
 * @prefix:  the namespace prefix cannot be NULL or empty string
4101
 * @ns_uri:  the namespace name
4102
 *
4103
 * Register a new namespace. If @ns_uri is NULL it unregisters
4104
 * the namespace
4105
 *
4106
 * Returns 0 in case of success, -1 in case of error
4107
 */
4108
int
4109
xmlXPathRegisterNs(xmlXPathContextPtr ctxt, const xmlChar *prefix,
4110
1.03k
         const xmlChar *ns_uri) {
4111
1.03k
    xmlChar *copy;
4112
4113
1.03k
    if (ctxt == NULL)
4114
0
  return(-1);
4115
1.03k
    if (prefix == NULL)
4116
0
  return(-1);
4117
1.03k
    if (prefix[0] == 0)
4118
0
  return(-1);
4119
4120
1.03k
    if (ctxt->nsHash == NULL)
4121
633
  ctxt->nsHash = xmlHashCreate(10);
4122
1.03k
    if (ctxt->nsHash == NULL) {
4123
0
        xmlXPathErrMemory(ctxt);
4124
0
  return(-1);
4125
0
    }
4126
1.03k
    if (ns_uri == NULL)
4127
0
        return(xmlHashRemoveEntry(ctxt->nsHash, prefix,
4128
0
                            xmlHashDefaultDeallocator));
4129
4130
1.03k
    copy = xmlStrdup(ns_uri);
4131
1.03k
    if (copy == NULL) {
4132
0
        xmlXPathErrMemory(ctxt);
4133
0
        return(-1);
4134
0
    }
4135
1.03k
    if (xmlHashUpdateEntry(ctxt->nsHash, prefix, copy,
4136
1.03k
                           xmlHashDefaultDeallocator) < 0) {
4137
0
        xmlXPathErrMemory(ctxt);
4138
0
        xmlFree(copy);
4139
0
        return(-1);
4140
0
    }
4141
4142
1.03k
    return(0);
4143
1.03k
}
4144
4145
/**
4146
 * xmlXPathNsLookup:
4147
 * @ctxt:  the XPath context
4148
 * @prefix:  the namespace prefix value
4149
 *
4150
 * Search in the namespace declaration array of the context for the given
4151
 * namespace name associated to the given prefix
4152
 *
4153
 * Returns the value or NULL if not found
4154
 */
4155
const xmlChar *
4156
1.26k
xmlXPathNsLookup(xmlXPathContextPtr ctxt, const xmlChar *prefix) {
4157
1.26k
    if (ctxt == NULL)
4158
0
  return(NULL);
4159
1.26k
    if (prefix == NULL)
4160
0
  return(NULL);
4161
4162
1.26k
    if (xmlStrEqual(prefix, (const xmlChar *) "xml"))
4163
0
  return(XML_XML_NAMESPACE);
4164
4165
1.26k
    if (ctxt->namespaces != NULL) {
4166
0
  int i;
4167
4168
0
  for (i = 0;i < ctxt->nsNr;i++) {
4169
0
      if ((ctxt->namespaces[i] != NULL) &&
4170
0
    (xmlStrEqual(ctxt->namespaces[i]->prefix, prefix)))
4171
0
    return(ctxt->namespaces[i]->href);
4172
0
  }
4173
0
    }
4174
4175
1.26k
    return((const xmlChar *) xmlHashLookup(ctxt->nsHash, prefix));
4176
1.26k
}
4177
4178
/**
4179
 * xmlXPathRegisteredNsCleanup:
4180
 * @ctxt:  the XPath context
4181
 *
4182
 * Cleanup the XPath context data associated to registered variables
4183
 */
4184
void
4185
633
xmlXPathRegisteredNsCleanup(xmlXPathContextPtr ctxt) {
4186
633
    if (ctxt == NULL)
4187
0
  return;
4188
4189
633
    xmlHashFree(ctxt->nsHash, xmlHashDefaultDeallocator);
4190
633
    ctxt->nsHash = NULL;
4191
633
}
4192
4193
/************************************************************************
4194
 *                  *
4195
 *      Routines to handle Values     *
4196
 *                  *
4197
 ************************************************************************/
4198
4199
/* Allocations are terrible, one needs to optimize all this !!! */
4200
4201
/**
4202
 * xmlXPathNewFloat:
4203
 * @val:  the double value
4204
 *
4205
 * Create a new xmlXPathObjectPtr of type double and of value @val
4206
 *
4207
 * Returns the newly created object.
4208
 */
4209
xmlXPathObjectPtr
4210
1.08k
xmlXPathNewFloat(double val) {
4211
1.08k
    xmlXPathObjectPtr ret;
4212
4213
1.08k
    ret = (xmlXPathObjectPtr) xmlMalloc(sizeof(xmlXPathObject));
4214
1.08k
    if (ret == NULL)
4215
0
  return(NULL);
4216
1.08k
    memset(ret, 0 , sizeof(xmlXPathObject));
4217
1.08k
    ret->type = XPATH_NUMBER;
4218
1.08k
    ret->floatval = val;
4219
1.08k
    return(ret);
4220
1.08k
}
4221
4222
/**
4223
 * xmlXPathNewBoolean:
4224
 * @val:  the boolean value
4225
 *
4226
 * Create a new xmlXPathObjectPtr of type boolean and of value @val
4227
 *
4228
 * Returns the newly created object.
4229
 */
4230
xmlXPathObjectPtr
4231
0
xmlXPathNewBoolean(int val) {
4232
0
    xmlXPathObjectPtr ret;
4233
4234
0
    ret = (xmlXPathObjectPtr) xmlMalloc(sizeof(xmlXPathObject));
4235
0
    if (ret == NULL)
4236
0
  return(NULL);
4237
0
    memset(ret, 0 , sizeof(xmlXPathObject));
4238
0
    ret->type = XPATH_BOOLEAN;
4239
0
    ret->boolval = (val != 0);
4240
0
    return(ret);
4241
0
}
4242
4243
/**
4244
 * xmlXPathNewString:
4245
 * @val:  the xmlChar * value
4246
 *
4247
 * Create a new xmlXPathObjectPtr of type string and of value @val
4248
 *
4249
 * Returns the newly created object.
4250
 */
4251
xmlXPathObjectPtr
4252
0
xmlXPathNewString(const xmlChar *val) {
4253
0
    xmlXPathObjectPtr ret;
4254
4255
0
    ret = (xmlXPathObjectPtr) xmlMalloc(sizeof(xmlXPathObject));
4256
0
    if (ret == NULL)
4257
0
  return(NULL);
4258
0
    memset(ret, 0 , sizeof(xmlXPathObject));
4259
0
    ret->type = XPATH_STRING;
4260
0
    if (val == NULL)
4261
0
        val = BAD_CAST "";
4262
0
    ret->stringval = xmlStrdup(val);
4263
0
    if (ret->stringval == NULL) {
4264
0
        xmlFree(ret);
4265
0
        return(NULL);
4266
0
    }
4267
0
    return(ret);
4268
0
}
4269
4270
/**
4271
 * xmlXPathWrapString:
4272
 * @val:  the xmlChar * value
4273
 *
4274
 * Wraps the @val string into an XPath object.
4275
 *
4276
 * Returns the newly created object.
4277
 *
4278
 * Frees @val in case of error.
4279
 */
4280
xmlXPathObjectPtr
4281
93
xmlXPathWrapString (xmlChar *val) {
4282
93
    xmlXPathObjectPtr ret;
4283
4284
93
    ret = (xmlXPathObjectPtr) xmlMalloc(sizeof(xmlXPathObject));
4285
93
    if (ret == NULL) {
4286
0
        xmlFree(val);
4287
0
  return(NULL);
4288
0
    }
4289
93
    memset(ret, 0 , sizeof(xmlXPathObject));
4290
93
    ret->type = XPATH_STRING;
4291
93
    ret->stringval = val;
4292
93
    return(ret);
4293
93
}
4294
4295
/**
4296
 * xmlXPathNewCString:
4297
 * @val:  the char * value
4298
 *
4299
 * Create a new xmlXPathObjectPtr of type string and of value @val
4300
 *
4301
 * Returns the newly created object.
4302
 */
4303
xmlXPathObjectPtr
4304
0
xmlXPathNewCString(const char *val) {
4305
0
    return(xmlXPathNewString(BAD_CAST val));
4306
0
}
4307
4308
/**
4309
 * xmlXPathWrapCString:
4310
 * @val:  the char * value
4311
 *
4312
 * Wraps a string into an XPath object.
4313
 *
4314
 * Returns the newly created object.
4315
 */
4316
xmlXPathObjectPtr
4317
0
xmlXPathWrapCString (char * val) {
4318
0
    return(xmlXPathWrapString((xmlChar *)(val)));
4319
0
}
4320
4321
/**
4322
 * xmlXPathWrapExternal:
4323
 * @val:  the user data
4324
 *
4325
 * Wraps the @val data into an XPath object.
4326
 *
4327
 * Returns the newly created object.
4328
 */
4329
xmlXPathObjectPtr
4330
0
xmlXPathWrapExternal (void *val) {
4331
0
    xmlXPathObjectPtr ret;
4332
4333
0
    ret = (xmlXPathObjectPtr) xmlMalloc(sizeof(xmlXPathObject));
4334
0
    if (ret == NULL)
4335
0
  return(NULL);
4336
0
    memset(ret, 0 , sizeof(xmlXPathObject));
4337
0
    ret->type = XPATH_USERS;
4338
0
    ret->user = val;
4339
0
    return(ret);
4340
0
}
4341
4342
/**
4343
 * xmlXPathObjectCopy:
4344
 * @val:  the original object
4345
 *
4346
 * allocate a new copy of a given object
4347
 *
4348
 * Returns the newly created object.
4349
 */
4350
xmlXPathObjectPtr
4351
0
xmlXPathObjectCopy(xmlXPathObjectPtr val) {
4352
0
    xmlXPathObjectPtr ret;
4353
4354
0
    if (val == NULL)
4355
0
  return(NULL);
4356
4357
0
    ret = (xmlXPathObjectPtr) xmlMalloc(sizeof(xmlXPathObject));
4358
0
    if (ret == NULL)
4359
0
  return(NULL);
4360
0
    memcpy(ret, val , sizeof(xmlXPathObject));
4361
0
    switch (val->type) {
4362
0
  case XPATH_BOOLEAN:
4363
0
  case XPATH_NUMBER:
4364
0
      break;
4365
0
  case XPATH_STRING:
4366
0
      ret->stringval = xmlStrdup(val->stringval);
4367
0
            if (ret->stringval == NULL) {
4368
0
                xmlFree(ret);
4369
0
                return(NULL);
4370
0
            }
4371
0
      break;
4372
0
  case XPATH_XSLT_TREE:
4373
0
  case XPATH_NODESET:
4374
0
      ret->nodesetval = xmlXPathNodeSetMerge(NULL, val->nodesetval);
4375
0
            if (ret->nodesetval == NULL) {
4376
0
                xmlFree(ret);
4377
0
                return(NULL);
4378
0
            }
4379
      /* Do not deallocate the copied tree value */
4380
0
      ret->boolval = 0;
4381
0
      break;
4382
0
        case XPATH_USERS:
4383
0
      ret->user = val->user;
4384
0
      break;
4385
0
        default:
4386
0
            xmlFree(ret);
4387
0
            ret = NULL;
4388
0
      break;
4389
0
    }
4390
0
    return(ret);
4391
0
}
4392
4393
/**
4394
 * xmlXPathFreeObject:
4395
 * @obj:  the object to free
4396
 *
4397
 * Free up an xmlXPathObjectPtr object.
4398
 */
4399
void
4400
2.72k
xmlXPathFreeObject(xmlXPathObjectPtr obj) {
4401
2.72k
    if (obj == NULL) return;
4402
2.72k
    if ((obj->type == XPATH_NODESET) || (obj->type == XPATH_XSLT_TREE)) {
4403
1.55k
        if (obj->nodesetval != NULL)
4404
1.55k
            xmlXPathFreeNodeSet(obj->nodesetval);
4405
1.55k
    } else if (obj->type == XPATH_STRING) {
4406
93
  if (obj->stringval != NULL)
4407
93
      xmlFree(obj->stringval);
4408
93
    }
4409
2.72k
    xmlFree(obj);
4410
2.72k
}
4411
4412
static void
4413
0
xmlXPathFreeObjectEntry(void *obj, const xmlChar *name ATTRIBUTE_UNUSED) {
4414
0
    xmlXPathFreeObject((xmlXPathObjectPtr) obj);
4415
0
}
4416
4417
/**
4418
 * xmlXPathReleaseObject:
4419
 * @obj:  the xmlXPathObjectPtr to free or to cache
4420
 *
4421
 * Depending on the state of the cache this frees the given
4422
 * XPath object or stores it in the cache.
4423
 */
4424
static void
4425
xmlXPathReleaseObject(xmlXPathContextPtr ctxt, xmlXPathObjectPtr obj)
4426
1.01k
{
4427
1.01k
    if (obj == NULL)
4428
0
  return;
4429
1.01k
    if ((ctxt == NULL) || (ctxt->cache == NULL)) {
4430
1.01k
   xmlXPathFreeObject(obj);
4431
1.01k
    } else {
4432
0
  xmlXPathContextCachePtr cache =
4433
0
      (xmlXPathContextCachePtr) ctxt->cache;
4434
4435
0
  switch (obj->type) {
4436
0
      case XPATH_NODESET:
4437
0
      case XPATH_XSLT_TREE:
4438
0
    if (obj->nodesetval != NULL) {
4439
0
        if ((obj->nodesetval->nodeMax <= 40) &&
4440
0
      (cache->numNodeset < cache->maxNodeset)) {
4441
0
                        obj->stringval = (void *) cache->nodesetObjs;
4442
0
                        cache->nodesetObjs = obj;
4443
0
                        cache->numNodeset += 1;
4444
0
      goto obj_cached;
4445
0
        } else {
4446
0
      xmlXPathFreeNodeSet(obj->nodesetval);
4447
0
      obj->nodesetval = NULL;
4448
0
        }
4449
0
    }
4450
0
    break;
4451
0
      case XPATH_STRING:
4452
0
    if (obj->stringval != NULL)
4453
0
        xmlFree(obj->stringval);
4454
0
                obj->stringval = NULL;
4455
0
    break;
4456
0
      case XPATH_BOOLEAN:
4457
0
      case XPATH_NUMBER:
4458
0
    break;
4459
0
      default:
4460
0
    goto free_obj;
4461
0
  }
4462
4463
  /*
4464
  * Fallback to adding to the misc-objects slot.
4465
  */
4466
0
        if (cache->numMisc >= cache->maxMisc)
4467
0
      goto free_obj;
4468
0
        obj->stringval = (void *) cache->miscObjs;
4469
0
        cache->miscObjs = obj;
4470
0
        cache->numMisc += 1;
4471
4472
0
obj_cached:
4473
0
        obj->boolval = 0;
4474
0
  if (obj->nodesetval != NULL) {
4475
0
      xmlNodeSetPtr tmpset = obj->nodesetval;
4476
4477
      /*
4478
      * Due to those nasty ns-nodes, we need to traverse
4479
      * the list and free the ns-nodes.
4480
      */
4481
0
      if (tmpset->nodeNr > 0) {
4482
0
    int i;
4483
0
    xmlNodePtr node;
4484
4485
0
    for (i = 0; i < tmpset->nodeNr; i++) {
4486
0
        node = tmpset->nodeTab[i];
4487
0
        if ((node != NULL) &&
4488
0
      (node->type == XML_NAMESPACE_DECL))
4489
0
        {
4490
0
      xmlXPathNodeSetFreeNs((xmlNsPtr) node);
4491
0
        }
4492
0
    }
4493
0
      }
4494
0
      tmpset->nodeNr = 0;
4495
0
        }
4496
4497
0
  return;
4498
4499
0
free_obj:
4500
  /*
4501
  * Cache is full; free the object.
4502
  */
4503
0
  if (obj->nodesetval != NULL)
4504
0
      xmlXPathFreeNodeSet(obj->nodesetval);
4505
0
  xmlFree(obj);
4506
0
    }
4507
1.01k
}
4508
4509
4510
/************************************************************************
4511
 *                  *
4512
 *      Type Casting Routines       *
4513
 *                  *
4514
 ************************************************************************/
4515
4516
/**
4517
 * xmlXPathCastBooleanToString:
4518
 * @val:  a boolean
4519
 *
4520
 * Converts a boolean to its string value.
4521
 *
4522
 * Returns a newly allocated string.
4523
 */
4524
xmlChar *
4525
0
xmlXPathCastBooleanToString (int val) {
4526
0
    xmlChar *ret;
4527
0
    if (val)
4528
0
  ret = xmlStrdup((const xmlChar *) "true");
4529
0
    else
4530
0
  ret = xmlStrdup((const xmlChar *) "false");
4531
0
    return(ret);
4532
0
}
4533
4534
/**
4535
 * xmlXPathCastNumberToString:
4536
 * @val:  a number
4537
 *
4538
 * Converts a number to its string value.
4539
 *
4540
 * Returns a newly allocated string.
4541
 */
4542
xmlChar *
4543
0
xmlXPathCastNumberToString (double val) {
4544
0
    xmlChar *ret;
4545
0
    switch (xmlXPathIsInf(val)) {
4546
0
    case 1:
4547
0
  ret = xmlStrdup((const xmlChar *) "Infinity");
4548
0
  break;
4549
0
    case -1:
4550
0
  ret = xmlStrdup((const xmlChar *) "-Infinity");
4551
0
  break;
4552
0
    default:
4553
0
  if (xmlXPathIsNaN(val)) {
4554
0
      ret = xmlStrdup((const xmlChar *) "NaN");
4555
0
  } else if (val == 0) {
4556
            /* Omit sign for negative zero. */
4557
0
      ret = xmlStrdup((const xmlChar *) "0");
4558
0
  } else {
4559
      /* could be improved */
4560
0
      char buf[100];
4561
0
      xmlXPathFormatNumber(val, buf, 99);
4562
0
      buf[99] = 0;
4563
0
      ret = xmlStrdup((const xmlChar *) buf);
4564
0
  }
4565
0
    }
4566
0
    return(ret);
4567
0
}
4568
4569
/**
4570
 * xmlXPathCastNodeToString:
4571
 * @node:  a node
4572
 *
4573
 * Converts a node to its string value.
4574
 *
4575
 * Returns a newly allocated string.
4576
 */
4577
xmlChar *
4578
475
xmlXPathCastNodeToString (xmlNodePtr node) {
4579
475
    return(xmlNodeGetContent(node));
4580
475
}
4581
4582
/**
4583
 * xmlXPathCastNodeSetToString:
4584
 * @ns:  a node-set
4585
 *
4586
 * Converts a node-set to its string value.
4587
 *
4588
 * Returns a newly allocated string.
4589
 */
4590
xmlChar *
4591
475
xmlXPathCastNodeSetToString (xmlNodeSetPtr ns) {
4592
475
    if ((ns == NULL) || (ns->nodeNr == 0) || (ns->nodeTab == NULL))
4593
0
  return(xmlStrdup((const xmlChar *) ""));
4594
4595
475
    if (ns->nodeNr > 1)
4596
0
  xmlXPathNodeSetSort(ns);
4597
475
    return(xmlXPathCastNodeToString(ns->nodeTab[0]));
4598
475
}
4599
4600
/**
4601
 * xmlXPathCastToString:
4602
 * @val:  an XPath object
4603
 *
4604
 * Converts an existing object to its string() equivalent
4605
 *
4606
 * Returns the allocated string value of the object, NULL in case of error.
4607
 *         It's up to the caller to free the string memory with xmlFree().
4608
 */
4609
xmlChar *
4610
661
xmlXPathCastToString(xmlXPathObjectPtr val) {
4611
661
    xmlChar *ret = NULL;
4612
4613
661
    if (val == NULL)
4614
0
  return(xmlStrdup((const xmlChar *) ""));
4615
661
    switch (val->type) {
4616
0
  case XPATH_UNDEFINED:
4617
0
      ret = xmlStrdup((const xmlChar *) "");
4618
0
      break;
4619
475
        case XPATH_NODESET:
4620
475
        case XPATH_XSLT_TREE:
4621
475
      ret = xmlXPathCastNodeSetToString(val->nodesetval);
4622
475
      break;
4623
186
  case XPATH_STRING:
4624
186
      return(xmlStrdup(val->stringval));
4625
0
        case XPATH_BOOLEAN:
4626
0
      ret = xmlXPathCastBooleanToString(val->boolval);
4627
0
      break;
4628
0
  case XPATH_NUMBER: {
4629
0
      ret = xmlXPathCastNumberToString(val->floatval);
4630
0
      break;
4631
475
  }
4632
0
  case XPATH_USERS:
4633
      /* TODO */
4634
0
      ret = xmlStrdup((const xmlChar *) "");
4635
0
      break;
4636
661
    }
4637
475
    return(ret);
4638
661
}
4639
4640
/**
4641
 * xmlXPathConvertString:
4642
 * @val:  an XPath object
4643
 *
4644
 * Converts an existing object to its string() equivalent
4645
 *
4646
 * Returns the new object, the old one is freed (or the operation
4647
 *         is done directly on @val)
4648
 */
4649
xmlXPathObjectPtr
4650
0
xmlXPathConvertString(xmlXPathObjectPtr val) {
4651
0
    xmlChar *res = NULL;
4652
4653
0
    if (val == NULL)
4654
0
  return(xmlXPathNewCString(""));
4655
4656
0
    switch (val->type) {
4657
0
    case XPATH_UNDEFINED:
4658
0
  break;
4659
0
    case XPATH_NODESET:
4660
0
    case XPATH_XSLT_TREE:
4661
0
  res = xmlXPathCastNodeSetToString(val->nodesetval);
4662
0
  break;
4663
0
    case XPATH_STRING:
4664
0
  return(val);
4665
0
    case XPATH_BOOLEAN:
4666
0
  res = xmlXPathCastBooleanToString(val->boolval);
4667
0
  break;
4668
0
    case XPATH_NUMBER:
4669
0
  res = xmlXPathCastNumberToString(val->floatval);
4670
0
  break;
4671
0
    case XPATH_USERS:
4672
  /* TODO */
4673
0
  break;
4674
0
    }
4675
0
    xmlXPathFreeObject(val);
4676
0
    if (res == NULL)
4677
0
  return(xmlXPathNewCString(""));
4678
0
    return(xmlXPathWrapString(res));
4679
0
}
4680
4681
/**
4682
 * xmlXPathCastBooleanToNumber:
4683
 * @val:  a boolean
4684
 *
4685
 * Converts a boolean to its number value
4686
 *
4687
 * Returns the number value
4688
 */
4689
double
4690
0
xmlXPathCastBooleanToNumber(int val) {
4691
0
    if (val)
4692
0
  return(1.0);
4693
0
    return(0.0);
4694
0
}
4695
4696
/**
4697
 * xmlXPathCastStringToNumber:
4698
 * @val:  a string
4699
 *
4700
 * Converts a string to its number value
4701
 *
4702
 * Returns the number value
4703
 */
4704
double
4705
0
xmlXPathCastStringToNumber(const xmlChar * val) {
4706
0
    return(xmlXPathStringEvalNumber(val));
4707
0
}
4708
4709
/**
4710
 * xmlXPathNodeToNumberInternal:
4711
 * @node:  a node
4712
 *
4713
 * Converts a node to its number value
4714
 *
4715
 * Returns the number value
4716
 */
4717
static double
4718
0
xmlXPathNodeToNumberInternal(xmlXPathParserContextPtr ctxt, xmlNodePtr node) {
4719
0
    xmlChar *strval;
4720
0
    double ret;
4721
4722
0
    if (node == NULL)
4723
0
  return(xmlXPathNAN);
4724
0
    strval = xmlXPathCastNodeToString(node);
4725
0
    if (strval == NULL) {
4726
0
        xmlXPathPErrMemory(ctxt);
4727
0
  return(xmlXPathNAN);
4728
0
    }
4729
0
    ret = xmlXPathCastStringToNumber(strval);
4730
0
    xmlFree(strval);
4731
4732
0
    return(ret);
4733
0
}
4734
4735
/**
4736
 * xmlXPathCastNodeToNumber:
4737
 * @node:  a node
4738
 *
4739
 * Converts a node to its number value
4740
 *
4741
 * Returns the number value
4742
 */
4743
double
4744
0
xmlXPathCastNodeToNumber (xmlNodePtr node) {
4745
0
    return(xmlXPathNodeToNumberInternal(NULL, node));
4746
0
}
4747
4748
/**
4749
 * xmlXPathCastNodeSetToNumber:
4750
 * @ns:  a node-set
4751
 *
4752
 * Converts a node-set to its number value
4753
 *
4754
 * Returns the number value
4755
 */
4756
double
4757
0
xmlXPathCastNodeSetToNumber (xmlNodeSetPtr ns) {
4758
0
    xmlChar *str;
4759
0
    double ret;
4760
4761
0
    if (ns == NULL)
4762
0
  return(xmlXPathNAN);
4763
0
    str = xmlXPathCastNodeSetToString(ns);
4764
0
    ret = xmlXPathCastStringToNumber(str);
4765
0
    xmlFree(str);
4766
0
    return(ret);
4767
0
}
4768
4769
/**
4770
 * xmlXPathCastToNumber:
4771
 * @val:  an XPath object
4772
 *
4773
 * Converts an XPath object to its number value
4774
 *
4775
 * Returns the number value
4776
 */
4777
double
4778
0
xmlXPathCastToNumber(xmlXPathObjectPtr val) {
4779
0
    return(xmlXPathCastToNumberInternal(NULL, val));
4780
0
}
4781
4782
/**
4783
 * xmlXPathConvertNumber:
4784
 * @val:  an XPath object
4785
 *
4786
 * Converts an existing object to its number() equivalent
4787
 *
4788
 * Returns the new object, the old one is freed (or the operation
4789
 *         is done directly on @val)
4790
 */
4791
xmlXPathObjectPtr
4792
0
xmlXPathConvertNumber(xmlXPathObjectPtr val) {
4793
0
    xmlXPathObjectPtr ret;
4794
4795
0
    if (val == NULL)
4796
0
  return(xmlXPathNewFloat(0.0));
4797
0
    if (val->type == XPATH_NUMBER)
4798
0
  return(val);
4799
0
    ret = xmlXPathNewFloat(xmlXPathCastToNumber(val));
4800
0
    xmlXPathFreeObject(val);
4801
0
    return(ret);
4802
0
}
4803
4804
/**
4805
 * xmlXPathCastNumberToBoolean:
4806
 * @val:  a number
4807
 *
4808
 * Converts a number to its boolean value
4809
 *
4810
 * Returns the boolean value
4811
 */
4812
int
4813
0
xmlXPathCastNumberToBoolean (double val) {
4814
0
     if (xmlXPathIsNaN(val) || (val == 0.0))
4815
0
   return(0);
4816
0
     return(1);
4817
0
}
4818
4819
/**
4820
 * xmlXPathCastStringToBoolean:
4821
 * @val:  a string
4822
 *
4823
 * Converts a string to its boolean value
4824
 *
4825
 * Returns the boolean value
4826
 */
4827
int
4828
0
xmlXPathCastStringToBoolean (const xmlChar *val) {
4829
0
    if ((val == NULL) || (xmlStrlen(val) == 0))
4830
0
  return(0);
4831
0
    return(1);
4832
0
}
4833
4834
/**
4835
 * xmlXPathCastNodeSetToBoolean:
4836
 * @ns:  a node-set
4837
 *
4838
 * Converts a node-set to its boolean value
4839
 *
4840
 * Returns the boolean value
4841
 */
4842
int
4843
0
xmlXPathCastNodeSetToBoolean (xmlNodeSetPtr ns) {
4844
0
    if ((ns == NULL) || (ns->nodeNr == 0))
4845
0
  return(0);
4846
0
    return(1);
4847
0
}
4848
4849
/**
4850
 * xmlXPathCastToBoolean:
4851
 * @val:  an XPath object
4852
 *
4853
 * Converts an XPath object to its boolean value
4854
 *
4855
 * Returns the boolean value
4856
 */
4857
int
4858
0
xmlXPathCastToBoolean (xmlXPathObjectPtr val) {
4859
0
    int ret = 0;
4860
4861
0
    if (val == NULL)
4862
0
  return(0);
4863
0
    switch (val->type) {
4864
0
    case XPATH_UNDEFINED:
4865
0
  ret = 0;
4866
0
  break;
4867
0
    case XPATH_NODESET:
4868
0
    case XPATH_XSLT_TREE:
4869
0
  ret = xmlXPathCastNodeSetToBoolean(val->nodesetval);
4870
0
  break;
4871
0
    case XPATH_STRING:
4872
0
  ret = xmlXPathCastStringToBoolean(val->stringval);
4873
0
  break;
4874
0
    case XPATH_NUMBER:
4875
0
  ret = xmlXPathCastNumberToBoolean(val->floatval);
4876
0
  break;
4877
0
    case XPATH_BOOLEAN:
4878
0
  ret = val->boolval;
4879
0
  break;
4880
0
    case XPATH_USERS:
4881
  /* TODO */
4882
0
  ret = 0;
4883
0
  break;
4884
0
    }
4885
0
    return(ret);
4886
0
}
4887
4888
4889
/**
4890
 * xmlXPathConvertBoolean:
4891
 * @val:  an XPath object
4892
 *
4893
 * Converts an existing object to its boolean() equivalent
4894
 *
4895
 * Returns the new object, the old one is freed (or the operation
4896
 *         is done directly on @val)
4897
 */
4898
xmlXPathObjectPtr
4899
0
xmlXPathConvertBoolean(xmlXPathObjectPtr val) {
4900
0
    xmlXPathObjectPtr ret;
4901
4902
0
    if (val == NULL)
4903
0
  return(xmlXPathNewBoolean(0));
4904
0
    if (val->type == XPATH_BOOLEAN)
4905
0
  return(val);
4906
0
    ret = xmlXPathNewBoolean(xmlXPathCastToBoolean(val));
4907
0
    xmlXPathFreeObject(val);
4908
0
    return(ret);
4909
0
}
4910
4911
/************************************************************************
4912
 *                  *
4913
 *    Routines to handle XPath contexts     *
4914
 *                  *
4915
 ************************************************************************/
4916
4917
/**
4918
 * xmlXPathNewContext:
4919
 * @doc:  the XML document
4920
 *
4921
 * Create a new xmlXPathContext
4922
 *
4923
 * Returns the xmlXPathContext just allocated. The caller will need to free it.
4924
 */
4925
xmlXPathContextPtr
4926
633
xmlXPathNewContext(xmlDocPtr doc) {
4927
633
    xmlXPathContextPtr ret;
4928
4929
633
    ret = (xmlXPathContextPtr) xmlMalloc(sizeof(xmlXPathContext));
4930
633
    if (ret == NULL)
4931
0
  return(NULL);
4932
633
    memset(ret, 0 , sizeof(xmlXPathContext));
4933
633
    ret->doc = doc;
4934
633
    ret->node = NULL;
4935
4936
633
    ret->varHash = NULL;
4937
4938
633
    ret->nb_types = 0;
4939
633
    ret->max_types = 0;
4940
633
    ret->types = NULL;
4941
4942
633
    ret->nb_axis = 0;
4943
633
    ret->max_axis = 0;
4944
633
    ret->axis = NULL;
4945
4946
633
    ret->nsHash = NULL;
4947
633
    ret->user = NULL;
4948
4949
633
    ret->contextSize = -1;
4950
633
    ret->proximityPosition = -1;
4951
4952
#ifdef XP_DEFAULT_CACHE_ON
4953
    if (xmlXPathContextSetCache(ret, 1, -1, 0) == -1) {
4954
  xmlXPathFreeContext(ret);
4955
  return(NULL);
4956
    }
4957
#endif
4958
4959
633
    return(ret);
4960
633
}
4961
4962
/**
4963
 * xmlXPathFreeContext:
4964
 * @ctxt:  the context to free
4965
 *
4966
 * Free up an xmlXPathContext
4967
 */
4968
void
4969
633
xmlXPathFreeContext(xmlXPathContextPtr ctxt) {
4970
633
    if (ctxt == NULL) return;
4971
4972
633
    if (ctxt->cache != NULL)
4973
0
  xmlXPathFreeCache((xmlXPathContextCachePtr) ctxt->cache);
4974
633
    xmlXPathRegisteredNsCleanup(ctxt);
4975
633
    xmlXPathRegisteredFuncsCleanup(ctxt);
4976
633
    xmlXPathRegisteredVariablesCleanup(ctxt);
4977
633
    xmlResetError(&ctxt->lastError);
4978
633
    xmlFree(ctxt);
4979
633
}
4980
4981
/**
4982
 * xmlXPathSetErrorHandler:
4983
 * @ctxt:  the XPath context
4984
 * @handler:  error handler
4985
 * @data:  user data which will be passed to the handler
4986
 *
4987
 * Register a callback function that will be called on errors and
4988
 * warnings. If handler is NULL, the error handler will be deactivated.
4989
 *
4990
 * Available since 2.13.0.
4991
 */
4992
void
4993
xmlXPathSetErrorHandler(xmlXPathContextPtr ctxt,
4994
0
                        xmlStructuredErrorFunc handler, void *data) {
4995
0
    if (ctxt == NULL)
4996
0
        return;
4997
4998
0
    ctxt->error = handler;
4999
0
    ctxt->userData = data;
5000
0
}
5001
5002
/************************************************************************
5003
 *                  *
5004
 *    Routines to handle XPath parser contexts    *
5005
 *                  *
5006
 ************************************************************************/
5007
5008
/**
5009
 * xmlXPathNewParserContext:
5010
 * @str:  the XPath expression
5011
 * @ctxt:  the XPath context
5012
 *
5013
 * Create a new xmlXPathParserContext
5014
 *
5015
 * Returns the xmlXPathParserContext just allocated.
5016
 */
5017
xmlXPathParserContextPtr
5018
633
xmlXPathNewParserContext(const xmlChar *str, xmlXPathContextPtr ctxt) {
5019
633
    xmlXPathParserContextPtr ret;
5020
5021
633
    ret = (xmlXPathParserContextPtr) xmlMalloc(sizeof(xmlXPathParserContext));
5022
633
    if (ret == NULL) {
5023
0
        xmlXPathErrMemory(ctxt);
5024
0
  return(NULL);
5025
0
    }
5026
633
    memset(ret, 0 , sizeof(xmlXPathParserContext));
5027
633
    ret->cur = ret->base = str;
5028
633
    ret->context = ctxt;
5029
5030
633
    ret->comp = xmlXPathNewCompExpr();
5031
633
    if (ret->comp == NULL) {
5032
0
        xmlXPathErrMemory(ctxt);
5033
0
  xmlFree(ret->valueTab);
5034
0
  xmlFree(ret);
5035
0
  return(NULL);
5036
0
    }
5037
633
    if ((ctxt != NULL) && (ctxt->dict != NULL)) {
5038
0
        ret->comp->dict = ctxt->dict;
5039
0
  xmlDictReference(ret->comp->dict);
5040
0
    }
5041
5042
633
    return(ret);
5043
633
}
5044
5045
/**
5046
 * xmlXPathCompParserContext:
5047
 * @comp:  the XPath compiled expression
5048
 * @ctxt:  the XPath context
5049
 *
5050
 * Create a new xmlXPathParserContext when processing a compiled expression
5051
 *
5052
 * Returns the xmlXPathParserContext just allocated.
5053
 */
5054
static xmlXPathParserContextPtr
5055
0
xmlXPathCompParserContext(xmlXPathCompExprPtr comp, xmlXPathContextPtr ctxt) {
5056
0
    xmlXPathParserContextPtr ret;
5057
5058
0
    ret = (xmlXPathParserContextPtr) xmlMalloc(sizeof(xmlXPathParserContext));
5059
0
    if (ret == NULL) {
5060
0
        xmlXPathErrMemory(ctxt);
5061
0
  return(NULL);
5062
0
    }
5063
0
    memset(ret, 0 , sizeof(xmlXPathParserContext));
5064
5065
    /* Allocate the value stack */
5066
0
#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
5067
0
    ret->valueMax = 1;
5068
#else
5069
    ret->valueMax = 10;
5070
#endif
5071
0
    ret->valueTab = xmlMalloc(ret->valueMax * sizeof(xmlXPathObjectPtr));
5072
0
    if (ret->valueTab == NULL) {
5073
0
  xmlFree(ret);
5074
0
  xmlXPathErrMemory(ctxt);
5075
0
  return(NULL);
5076
0
    }
5077
0
    ret->valueNr = 0;
5078
0
    ret->value = NULL;
5079
5080
0
    ret->context = ctxt;
5081
0
    ret->comp = comp;
5082
5083
0
    return(ret);
5084
0
}
5085
5086
/**
5087
 * xmlXPathFreeParserContext:
5088
 * @ctxt:  the context to free
5089
 *
5090
 * Free up an xmlXPathParserContext
5091
 */
5092
void
5093
633
xmlXPathFreeParserContext(xmlXPathParserContextPtr ctxt) {
5094
633
    int i;
5095
5096
633
    if (ctxt->valueTab != NULL) {
5097
633
        for (i = 0; i < ctxt->valueNr; i++) {
5098
0
            if (ctxt->context)
5099
0
                xmlXPathReleaseObject(ctxt->context, ctxt->valueTab[i]);
5100
0
            else
5101
0
                xmlXPathFreeObject(ctxt->valueTab[i]);
5102
0
        }
5103
633
        xmlFree(ctxt->valueTab);
5104
633
    }
5105
633
    if (ctxt->comp != NULL) {
5106
#ifdef XPATH_STREAMING
5107
  if (ctxt->comp->stream != NULL) {
5108
      xmlFreePatternList(ctxt->comp->stream);
5109
      ctxt->comp->stream = NULL;
5110
  }
5111
#endif
5112
633
  xmlXPathFreeCompExpr(ctxt->comp);
5113
633
    }
5114
633
    xmlFree(ctxt);
5115
633
}
5116
5117
/************************************************************************
5118
 *                  *
5119
 *    The implicit core function library      *
5120
 *                  *
5121
 ************************************************************************/
5122
5123
/**
5124
 * xmlXPathNodeValHash:
5125
 * @node:  a node pointer
5126
 *
5127
 * Function computing the beginning of the string value of the node,
5128
 * used to speed up comparisons
5129
 *
5130
 * Returns an int usable as a hash
5131
 */
5132
static unsigned int
5133
0
xmlXPathNodeValHash(xmlNodePtr node) {
5134
0
    int len = 2;
5135
0
    const xmlChar * string = NULL;
5136
0
    xmlNodePtr tmp = NULL;
5137
0
    unsigned int ret = 0;
5138
5139
0
    if (node == NULL)
5140
0
  return(0);
5141
5142
0
    if (node->type == XML_DOCUMENT_NODE) {
5143
0
  tmp = xmlDocGetRootElement((xmlDocPtr) node);
5144
0
  if (tmp == NULL)
5145
0
      node = node->children;
5146
0
  else
5147
0
      node = tmp;
5148
5149
0
  if (node == NULL)
5150
0
      return(0);
5151
0
    }
5152
5153
0
    switch (node->type) {
5154
0
  case XML_COMMENT_NODE:
5155
0
  case XML_PI_NODE:
5156
0
  case XML_CDATA_SECTION_NODE:
5157
0
  case XML_TEXT_NODE:
5158
0
      string = node->content;
5159
0
      if (string == NULL)
5160
0
    return(0);
5161
0
      if (string[0] == 0)
5162
0
    return(0);
5163
0
      return(string[0] + (string[1] << 8));
5164
0
  case XML_NAMESPACE_DECL:
5165
0
      string = ((xmlNsPtr)node)->href;
5166
0
      if (string == NULL)
5167
0
    return(0);
5168
0
      if (string[0] == 0)
5169
0
    return(0);
5170
0
      return(string[0] + (string[1] << 8));
5171
0
  case XML_ATTRIBUTE_NODE:
5172
0
      tmp = ((xmlAttrPtr) node)->children;
5173
0
      break;
5174
0
  case XML_ELEMENT_NODE:
5175
0
      tmp = node->children;
5176
0
      break;
5177
0
  default:
5178
0
      return(0);
5179
0
    }
5180
0
    while (tmp != NULL) {
5181
0
  switch (tmp->type) {
5182
0
      case XML_CDATA_SECTION_NODE:
5183
0
      case XML_TEXT_NODE:
5184
0
    string = tmp->content;
5185
0
    break;
5186
0
      default:
5187
0
                string = NULL;
5188
0
    break;
5189
0
  }
5190
0
  if ((string != NULL) && (string[0] != 0)) {
5191
0
      if (len == 1) {
5192
0
    return(ret + (string[0] << 8));
5193
0
      }
5194
0
      if (string[1] == 0) {
5195
0
    len = 1;
5196
0
    ret = string[0];
5197
0
      } else {
5198
0
    return(string[0] + (string[1] << 8));
5199
0
      }
5200
0
  }
5201
  /*
5202
   * Skip to next node
5203
   */
5204
0
        if ((tmp->children != NULL) &&
5205
0
            (tmp->type != XML_DTD_NODE) &&
5206
0
            (tmp->type != XML_ENTITY_REF_NODE) &&
5207
0
            (tmp->children->type != XML_ENTITY_DECL)) {
5208
0
            tmp = tmp->children;
5209
0
            continue;
5210
0
  }
5211
0
  if (tmp == node)
5212
0
      break;
5213
5214
0
  if (tmp->next != NULL) {
5215
0
      tmp = tmp->next;
5216
0
      continue;
5217
0
  }
5218
5219
0
  do {
5220
0
      tmp = tmp->parent;
5221
0
      if (tmp == NULL)
5222
0
    break;
5223
0
      if (tmp == node) {
5224
0
    tmp = NULL;
5225
0
    break;
5226
0
      }
5227
0
      if (tmp->next != NULL) {
5228
0
    tmp = tmp->next;
5229
0
    break;
5230
0
      }
5231
0
  } while (tmp != NULL);
5232
0
    }
5233
0
    return(ret);
5234
0
}
5235
5236
/**
5237
 * xmlXPathStringHash:
5238
 * @string:  a string
5239
 *
5240
 * Function computing the beginning of the string value of the node,
5241
 * used to speed up comparisons
5242
 *
5243
 * Returns an int usable as a hash
5244
 */
5245
static unsigned int
5246
0
xmlXPathStringHash(const xmlChar * string) {
5247
0
    if (string == NULL)
5248
0
  return(0);
5249
0
    if (string[0] == 0)
5250
0
  return(0);
5251
0
    return(string[0] + (string[1] << 8));
5252
0
}
5253
5254
/**
5255
 * xmlXPathCompareNodeSetFloat:
5256
 * @ctxt:  the XPath Parser context
5257
 * @inf:  less than (1) or greater than (0)
5258
 * @strict:  is the comparison strict
5259
 * @arg:  the node set
5260
 * @f:  the value
5261
 *
5262
 * Implement the compare operation between a nodeset and a number
5263
 *     @ns < @val    (1, 1, ...
5264
 *     @ns <= @val   (1, 0, ...
5265
 *     @ns > @val    (0, 1, ...
5266
 *     @ns >= @val   (0, 0, ...
5267
 *
5268
 * If one object to be compared is a node-set and the other is a number,
5269
 * then the comparison will be true if and only if there is a node in the
5270
 * node-set such that the result of performing the comparison on the number
5271
 * to be compared and on the result of converting the string-value of that
5272
 * node to a number using the number function is true.
5273
 *
5274
 * Returns 0 or 1 depending on the results of the test.
5275
 */
5276
static int
5277
xmlXPathCompareNodeSetFloat(xmlXPathParserContextPtr ctxt, int inf, int strict,
5278
0
                      xmlXPathObjectPtr arg, xmlXPathObjectPtr f) {
5279
0
    int i, ret = 0;
5280
0
    xmlNodeSetPtr ns;
5281
0
    xmlChar *str2;
5282
5283
0
    if ((f == NULL) || (arg == NULL) ||
5284
0
  ((arg->type != XPATH_NODESET) && (arg->type != XPATH_XSLT_TREE))) {
5285
0
  xmlXPathReleaseObject(ctxt->context, arg);
5286
0
  xmlXPathReleaseObject(ctxt->context, f);
5287
0
        return(0);
5288
0
    }
5289
0
    ns = arg->nodesetval;
5290
0
    if (ns != NULL) {
5291
0
  for (i = 0;i < ns->nodeNr;i++) {
5292
0
       str2 = xmlXPathCastNodeToString(ns->nodeTab[i]);
5293
0
       if (str2 != NULL) {
5294
0
     xmlXPathValuePush(ctxt, xmlXPathCacheNewString(ctxt, str2));
5295
0
     xmlFree(str2);
5296
0
     xmlXPathNumberFunction(ctxt, 1);
5297
0
     xmlXPathValuePush(ctxt, xmlXPathCacheObjectCopy(ctxt, f));
5298
0
     ret = xmlXPathCompareValues(ctxt, inf, strict);
5299
0
     if (ret)
5300
0
         break;
5301
0
       } else {
5302
0
                 xmlXPathPErrMemory(ctxt);
5303
0
             }
5304
0
  }
5305
0
    }
5306
0
    xmlXPathReleaseObject(ctxt->context, arg);
5307
0
    xmlXPathReleaseObject(ctxt->context, f);
5308
0
    return(ret);
5309
0
}
5310
5311
/**
5312
 * xmlXPathCompareNodeSetString:
5313
 * @ctxt:  the XPath Parser context
5314
 * @inf:  less than (1) or greater than (0)
5315
 * @strict:  is the comparison strict
5316
 * @arg:  the node set
5317
 * @s:  the value
5318
 *
5319
 * Implement the compare operation between a nodeset and a string
5320
 *     @ns < @val    (1, 1, ...
5321
 *     @ns <= @val   (1, 0, ...
5322
 *     @ns > @val    (0, 1, ...
5323
 *     @ns >= @val   (0, 0, ...
5324
 *
5325
 * If one object to be compared is a node-set and the other is a string,
5326
 * then the comparison will be true if and only if there is a node in
5327
 * the node-set such that the result of performing the comparison on the
5328
 * string-value of the node and the other string is true.
5329
 *
5330
 * Returns 0 or 1 depending on the results of the test.
5331
 */
5332
static int
5333
xmlXPathCompareNodeSetString(xmlXPathParserContextPtr ctxt, int inf, int strict,
5334
0
                      xmlXPathObjectPtr arg, xmlXPathObjectPtr s) {
5335
0
    int i, ret = 0;
5336
0
    xmlNodeSetPtr ns;
5337
0
    xmlChar *str2;
5338
5339
0
    if ((s == NULL) || (arg == NULL) ||
5340
0
  ((arg->type != XPATH_NODESET) && (arg->type != XPATH_XSLT_TREE))) {
5341
0
  xmlXPathReleaseObject(ctxt->context, arg);
5342
0
  xmlXPathReleaseObject(ctxt->context, s);
5343
0
        return(0);
5344
0
    }
5345
0
    ns = arg->nodesetval;
5346
0
    if (ns != NULL) {
5347
0
  for (i = 0;i < ns->nodeNr;i++) {
5348
0
       str2 = xmlXPathCastNodeToString(ns->nodeTab[i]);
5349
0
       if (str2 != NULL) {
5350
0
     xmlXPathValuePush(ctxt,
5351
0
         xmlXPathCacheNewString(ctxt, str2));
5352
0
     xmlFree(str2);
5353
0
     xmlXPathValuePush(ctxt, xmlXPathCacheObjectCopy(ctxt, s));
5354
0
     ret = xmlXPathCompareValues(ctxt, inf, strict);
5355
0
     if (ret)
5356
0
         break;
5357
0
       } else {
5358
0
                 xmlXPathPErrMemory(ctxt);
5359
0
             }
5360
0
  }
5361
0
    }
5362
0
    xmlXPathReleaseObject(ctxt->context, arg);
5363
0
    xmlXPathReleaseObject(ctxt->context, s);
5364
0
    return(ret);
5365
0
}
5366
5367
/**
5368
 * xmlXPathCompareNodeSets:
5369
 * @inf:  less than (1) or greater than (0)
5370
 * @strict:  is the comparison strict
5371
 * @arg1:  the first node set object
5372
 * @arg2:  the second node set object
5373
 *
5374
 * Implement the compare operation on nodesets:
5375
 *
5376
 * If both objects to be compared are node-sets, then the comparison
5377
 * will be true if and only if there is a node in the first node-set
5378
 * and a node in the second node-set such that the result of performing
5379
 * the comparison on the string-values of the two nodes is true.
5380
 * ....
5381
 * When neither object to be compared is a node-set and the operator
5382
 * is <=, <, >= or >, then the objects are compared by converting both
5383
 * objects to numbers and comparing the numbers according to IEEE 754.
5384
 * ....
5385
 * The number function converts its argument to a number as follows:
5386
 *  - a string that consists of optional whitespace followed by an
5387
 *    optional minus sign followed by a Number followed by whitespace
5388
 *    is converted to the IEEE 754 number that is nearest (according
5389
 *    to the IEEE 754 round-to-nearest rule) to the mathematical value
5390
 *    represented by the string; any other string is converted to NaN
5391
 *
5392
 * Conclusion all nodes need to be converted first to their string value
5393
 * and then the comparison must be done when possible
5394
 */
5395
static int
5396
xmlXPathCompareNodeSets(xmlXPathParserContextPtr ctxt, int inf, int strict,
5397
0
                  xmlXPathObjectPtr arg1, xmlXPathObjectPtr arg2) {
5398
0
    int i, j, init = 0;
5399
0
    double val1;
5400
0
    double *values2;
5401
0
    int ret = 0;
5402
0
    xmlNodeSetPtr ns1;
5403
0
    xmlNodeSetPtr ns2;
5404
5405
0
    if ((arg1 == NULL) ||
5406
0
  ((arg1->type != XPATH_NODESET) && (arg1->type != XPATH_XSLT_TREE))) {
5407
0
  xmlXPathFreeObject(arg2);
5408
0
        return(0);
5409
0
    }
5410
0
    if ((arg2 == NULL) ||
5411
0
  ((arg2->type != XPATH_NODESET) && (arg2->type != XPATH_XSLT_TREE))) {
5412
0
  xmlXPathFreeObject(arg1);
5413
0
  xmlXPathFreeObject(arg2);
5414
0
        return(0);
5415
0
    }
5416
5417
0
    ns1 = arg1->nodesetval;
5418
0
    ns2 = arg2->nodesetval;
5419
5420
0
    if ((ns1 == NULL) || (ns1->nodeNr <= 0)) {
5421
0
  xmlXPathFreeObject(arg1);
5422
0
  xmlXPathFreeObject(arg2);
5423
0
  return(0);
5424
0
    }
5425
0
    if ((ns2 == NULL) || (ns2->nodeNr <= 0)) {
5426
0
  xmlXPathFreeObject(arg1);
5427
0
  xmlXPathFreeObject(arg2);
5428
0
  return(0);
5429
0
    }
5430
5431
0
    values2 = (double *) xmlMalloc(ns2->nodeNr * sizeof(double));
5432
0
    if (values2 == NULL) {
5433
0
        xmlXPathPErrMemory(ctxt);
5434
0
  xmlXPathFreeObject(arg1);
5435
0
  xmlXPathFreeObject(arg2);
5436
0
  return(0);
5437
0
    }
5438
0
    for (i = 0;i < ns1->nodeNr;i++) {
5439
0
  val1 = xmlXPathNodeToNumberInternal(ctxt, ns1->nodeTab[i]);
5440
0
  if (xmlXPathIsNaN(val1))
5441
0
      continue;
5442
0
  for (j = 0;j < ns2->nodeNr;j++) {
5443
0
      if (init == 0) {
5444
0
    values2[j] = xmlXPathNodeToNumberInternal(ctxt,
5445
0
                                                          ns2->nodeTab[j]);
5446
0
      }
5447
0
      if (xmlXPathIsNaN(values2[j]))
5448
0
    continue;
5449
0
      if (inf && strict)
5450
0
    ret = (val1 < values2[j]);
5451
0
      else if (inf && !strict)
5452
0
    ret = (val1 <= values2[j]);
5453
0
      else if (!inf && strict)
5454
0
    ret = (val1 > values2[j]);
5455
0
      else if (!inf && !strict)
5456
0
    ret = (val1 >= values2[j]);
5457
0
      if (ret)
5458
0
    break;
5459
0
  }
5460
0
  if (ret)
5461
0
      break;
5462
0
  init = 1;
5463
0
    }
5464
0
    xmlFree(values2);
5465
0
    xmlXPathFreeObject(arg1);
5466
0
    xmlXPathFreeObject(arg2);
5467
0
    return(ret);
5468
0
}
5469
5470
/**
5471
 * xmlXPathCompareNodeSetValue:
5472
 * @ctxt:  the XPath Parser context
5473
 * @inf:  less than (1) or greater than (0)
5474
 * @strict:  is the comparison strict
5475
 * @arg:  the node set
5476
 * @val:  the value
5477
 *
5478
 * Implement the compare operation between a nodeset and a value
5479
 *     @ns < @val    (1, 1, ...
5480
 *     @ns <= @val   (1, 0, ...
5481
 *     @ns > @val    (0, 1, ...
5482
 *     @ns >= @val   (0, 0, ...
5483
 *
5484
 * If one object to be compared is a node-set and the other is a boolean,
5485
 * then the comparison will be true if and only if the result of performing
5486
 * the comparison on the boolean and on the result of converting
5487
 * the node-set to a boolean using the boolean function is true.
5488
 *
5489
 * Returns 0 or 1 depending on the results of the test.
5490
 */
5491
static int
5492
xmlXPathCompareNodeSetValue(xmlXPathParserContextPtr ctxt, int inf, int strict,
5493
0
                      xmlXPathObjectPtr arg, xmlXPathObjectPtr val) {
5494
0
    if ((val == NULL) || (arg == NULL) ||
5495
0
  ((arg->type != XPATH_NODESET) && (arg->type != XPATH_XSLT_TREE)))
5496
0
        return(0);
5497
5498
0
    switch(val->type) {
5499
0
        case XPATH_NUMBER:
5500
0
      return(xmlXPathCompareNodeSetFloat(ctxt, inf, strict, arg, val));
5501
0
        case XPATH_NODESET:
5502
0
        case XPATH_XSLT_TREE:
5503
0
      return(xmlXPathCompareNodeSets(ctxt, inf, strict, arg, val));
5504
0
        case XPATH_STRING:
5505
0
      return(xmlXPathCompareNodeSetString(ctxt, inf, strict, arg, val));
5506
0
        case XPATH_BOOLEAN:
5507
0
      xmlXPathValuePush(ctxt, arg);
5508
0
      xmlXPathBooleanFunction(ctxt, 1);
5509
0
      xmlXPathValuePush(ctxt, val);
5510
0
      return(xmlXPathCompareValues(ctxt, inf, strict));
5511
0
  default:
5512
0
            xmlXPathReleaseObject(ctxt->context, arg);
5513
0
            xmlXPathReleaseObject(ctxt->context, val);
5514
0
            XP_ERROR0(XPATH_INVALID_TYPE);
5515
0
    }
5516
0
    return(0);
5517
0
}
5518
5519
/**
5520
 * xmlXPathEqualNodeSetString:
5521
 * @arg:  the nodeset object argument
5522
 * @str:  the string to compare to.
5523
 * @neq:  flag to show whether for '=' (0) or '!=' (1)
5524
 *
5525
 * Implement the equal operation on XPath objects content: @arg1 == @arg2
5526
 * If one object to be compared is a node-set and the other is a string,
5527
 * then the comparison will be true if and only if there is a node in
5528
 * the node-set such that the result of performing the comparison on the
5529
 * string-value of the node and the other string is true.
5530
 *
5531
 * Returns 0 or 1 depending on the results of the test.
5532
 */
5533
static int
5534
xmlXPathEqualNodeSetString(xmlXPathParserContextPtr ctxt,
5535
                           xmlXPathObjectPtr arg, const xmlChar * str, int neq)
5536
0
{
5537
0
    int i;
5538
0
    xmlNodeSetPtr ns;
5539
0
    xmlChar *str2;
5540
0
    unsigned int hash;
5541
5542
0
    if ((str == NULL) || (arg == NULL) ||
5543
0
        ((arg->type != XPATH_NODESET) && (arg->type != XPATH_XSLT_TREE)))
5544
0
        return (0);
5545
0
    ns = arg->nodesetval;
5546
    /*
5547
     * A NULL nodeset compared with a string is always false
5548
     * (since there is no node equal, and no node not equal)
5549
     */
5550
0
    if ((ns == NULL) || (ns->nodeNr <= 0) )
5551
0
        return (0);
5552
0
    hash = xmlXPathStringHash(str);
5553
0
    for (i = 0; i < ns->nodeNr; i++) {
5554
0
        if (xmlXPathNodeValHash(ns->nodeTab[i]) == hash) {
5555
0
            str2 = xmlNodeGetContent(ns->nodeTab[i]);
5556
0
            if (str2 == NULL) {
5557
0
                xmlXPathPErrMemory(ctxt);
5558
0
                return(0);
5559
0
            }
5560
0
            if (xmlStrEqual(str, str2)) {
5561
0
                xmlFree(str2);
5562
0
    if (neq)
5563
0
        continue;
5564
0
                return (1);
5565
0
            } else if (neq) {
5566
0
    xmlFree(str2);
5567
0
    return (1);
5568
0
      }
5569
0
            xmlFree(str2);
5570
0
        } else if (neq)
5571
0
      return (1);
5572
0
    }
5573
0
    return (0);
5574
0
}
5575
5576
/**
5577
 * xmlXPathEqualNodeSetFloat:
5578
 * @arg:  the nodeset object argument
5579
 * @f:  the float to compare to
5580
 * @neq:  flag to show whether to compare '=' (0) or '!=' (1)
5581
 *
5582
 * Implement the equal operation on XPath objects content: @arg1 == @arg2
5583
 * If one object to be compared is a node-set and the other is a number,
5584
 * then the comparison will be true if and only if there is a node in
5585
 * the node-set such that the result of performing the comparison on the
5586
 * number to be compared and on the result of converting the string-value
5587
 * of that node to a number using the number function is true.
5588
 *
5589
 * Returns 0 or 1 depending on the results of the test.
5590
 */
5591
static int
5592
xmlXPathEqualNodeSetFloat(xmlXPathParserContextPtr ctxt,
5593
0
    xmlXPathObjectPtr arg, double f, int neq) {
5594
0
  int i, ret=0;
5595
0
  xmlNodeSetPtr ns;
5596
0
  xmlChar *str2;
5597
0
  xmlXPathObjectPtr val;
5598
0
  double v;
5599
5600
0
    if ((arg == NULL) ||
5601
0
  ((arg->type != XPATH_NODESET) && (arg->type != XPATH_XSLT_TREE)))
5602
0
        return(0);
5603
5604
0
    ns = arg->nodesetval;
5605
0
    if (ns != NULL) {
5606
0
  for (i=0;i<ns->nodeNr;i++) {
5607
0
      str2 = xmlXPathCastNodeToString(ns->nodeTab[i]);
5608
0
      if (str2 != NULL) {
5609
0
    xmlXPathValuePush(ctxt, xmlXPathCacheNewString(ctxt, str2));
5610
0
    xmlFree(str2);
5611
0
    xmlXPathNumberFunction(ctxt, 1);
5612
0
                CHECK_ERROR0;
5613
0
    val = xmlXPathValuePop(ctxt);
5614
0
    v = val->floatval;
5615
0
    xmlXPathReleaseObject(ctxt->context, val);
5616
0
    if (!xmlXPathIsNaN(v)) {
5617
0
        if ((!neq) && (v==f)) {
5618
0
      ret = 1;
5619
0
      break;
5620
0
        } else if ((neq) && (v!=f)) {
5621
0
      ret = 1;
5622
0
      break;
5623
0
        }
5624
0
    } else { /* NaN is unequal to any value */
5625
0
        if (neq)
5626
0
      ret = 1;
5627
0
    }
5628
0
      } else {
5629
0
                xmlXPathPErrMemory(ctxt);
5630
0
            }
5631
0
  }
5632
0
    }
5633
5634
0
    return(ret);
5635
0
}
5636
5637
5638
/**
5639
 * xmlXPathEqualNodeSets:
5640
 * @arg1:  first nodeset object argument
5641
 * @arg2:  second nodeset object argument
5642
 * @neq:   flag to show whether to test '=' (0) or '!=' (1)
5643
 *
5644
 * Implement the equal / not equal operation on XPath nodesets:
5645
 * @arg1 == @arg2  or  @arg1 != @arg2
5646
 * If both objects to be compared are node-sets, then the comparison
5647
 * will be true if and only if there is a node in the first node-set and
5648
 * a node in the second node-set such that the result of performing the
5649
 * comparison on the string-values of the two nodes is true.
5650
 *
5651
 * (needless to say, this is a costly operation)
5652
 *
5653
 * Returns 0 or 1 depending on the results of the test.
5654
 */
5655
static int
5656
xmlXPathEqualNodeSets(xmlXPathParserContextPtr ctxt, xmlXPathObjectPtr arg1,
5657
0
                      xmlXPathObjectPtr arg2, int neq) {
5658
0
    int i, j;
5659
0
    unsigned int *hashs1;
5660
0
    unsigned int *hashs2;
5661
0
    xmlChar **values1;
5662
0
    xmlChar **values2;
5663
0
    int ret = 0;
5664
0
    xmlNodeSetPtr ns1;
5665
0
    xmlNodeSetPtr ns2;
5666
5667
0
    if ((arg1 == NULL) ||
5668
0
  ((arg1->type != XPATH_NODESET) && (arg1->type != XPATH_XSLT_TREE)))
5669
0
        return(0);
5670
0
    if ((arg2 == NULL) ||
5671
0
  ((arg2->type != XPATH_NODESET) && (arg2->type != XPATH_XSLT_TREE)))
5672
0
        return(0);
5673
5674
0
    ns1 = arg1->nodesetval;
5675
0
    ns2 = arg2->nodesetval;
5676
5677
0
    if ((ns1 == NULL) || (ns1->nodeNr <= 0))
5678
0
  return(0);
5679
0
    if ((ns2 == NULL) || (ns2->nodeNr <= 0))
5680
0
  return(0);
5681
5682
    /*
5683
     * for equal, check if there is a node pertaining to both sets
5684
     */
5685
0
    if (neq == 0)
5686
0
  for (i = 0;i < ns1->nodeNr;i++)
5687
0
      for (j = 0;j < ns2->nodeNr;j++)
5688
0
    if (ns1->nodeTab[i] == ns2->nodeTab[j])
5689
0
        return(1);
5690
5691
0
    values1 = (xmlChar **) xmlMalloc(ns1->nodeNr * sizeof(xmlChar *));
5692
0
    if (values1 == NULL) {
5693
0
        xmlXPathPErrMemory(ctxt);
5694
0
  return(0);
5695
0
    }
5696
0
    hashs1 = (unsigned int *) xmlMalloc(ns1->nodeNr * sizeof(unsigned int));
5697
0
    if (hashs1 == NULL) {
5698
0
        xmlXPathPErrMemory(ctxt);
5699
0
  xmlFree(values1);
5700
0
  return(0);
5701
0
    }
5702
0
    memset(values1, 0, ns1->nodeNr * sizeof(xmlChar *));
5703
0
    values2 = (xmlChar **) xmlMalloc(ns2->nodeNr * sizeof(xmlChar *));
5704
0
    if (values2 == NULL) {
5705
0
        xmlXPathPErrMemory(ctxt);
5706
0
  xmlFree(hashs1);
5707
0
  xmlFree(values1);
5708
0
  return(0);
5709
0
    }
5710
0
    hashs2 = (unsigned int *) xmlMalloc(ns2->nodeNr * sizeof(unsigned int));
5711
0
    if (hashs2 == NULL) {
5712
0
        xmlXPathPErrMemory(ctxt);
5713
0
  xmlFree(hashs1);
5714
0
  xmlFree(values1);
5715
0
  xmlFree(values2);
5716
0
  return(0);
5717
0
    }
5718
0
    memset(values2, 0, ns2->nodeNr * sizeof(xmlChar *));
5719
0
    for (i = 0;i < ns1->nodeNr;i++) {
5720
0
  hashs1[i] = xmlXPathNodeValHash(ns1->nodeTab[i]);
5721
0
  for (j = 0;j < ns2->nodeNr;j++) {
5722
0
      if (i == 0)
5723
0
    hashs2[j] = xmlXPathNodeValHash(ns2->nodeTab[j]);
5724
0
      if (hashs1[i] != hashs2[j]) {
5725
0
    if (neq) {
5726
0
        ret = 1;
5727
0
        break;
5728
0
    }
5729
0
      }
5730
0
      else {
5731
0
    if (values1[i] == NULL) {
5732
0
        values1[i] = xmlNodeGetContent(ns1->nodeTab[i]);
5733
0
                    if (values1[i] == NULL)
5734
0
                        xmlXPathPErrMemory(ctxt);
5735
0
                }
5736
0
    if (values2[j] == NULL) {
5737
0
        values2[j] = xmlNodeGetContent(ns2->nodeTab[j]);
5738
0
                    if (values2[j] == NULL)
5739
0
                        xmlXPathPErrMemory(ctxt);
5740
0
                }
5741
0
    ret = xmlStrEqual(values1[i], values2[j]) ^ neq;
5742
0
    if (ret)
5743
0
        break;
5744
0
      }
5745
0
  }
5746
0
  if (ret)
5747
0
      break;
5748
0
    }
5749
0
    for (i = 0;i < ns1->nodeNr;i++)
5750
0
  if (values1[i] != NULL)
5751
0
      xmlFree(values1[i]);
5752
0
    for (j = 0;j < ns2->nodeNr;j++)
5753
0
  if (values2[j] != NULL)
5754
0
      xmlFree(values2[j]);
5755
0
    xmlFree(values1);
5756
0
    xmlFree(values2);
5757
0
    xmlFree(hashs1);
5758
0
    xmlFree(hashs2);
5759
0
    return(ret);
5760
0
}
5761
5762
static int
5763
xmlXPathEqualValuesCommon(xmlXPathParserContextPtr ctxt,
5764
0
  xmlXPathObjectPtr arg1, xmlXPathObjectPtr arg2) {
5765
0
    int ret = 0;
5766
    /*
5767
     *At this point we are assured neither arg1 nor arg2
5768
     *is a nodeset, so we can just pick the appropriate routine.
5769
     */
5770
0
    switch (arg1->type) {
5771
0
        case XPATH_UNDEFINED:
5772
0
      break;
5773
0
        case XPATH_BOOLEAN:
5774
0
      switch (arg2->type) {
5775
0
          case XPATH_UNDEFINED:
5776
0
        break;
5777
0
    case XPATH_BOOLEAN:
5778
0
        ret = (arg1->boolval == arg2->boolval);
5779
0
        break;
5780
0
    case XPATH_NUMBER:
5781
0
        ret = (arg1->boolval ==
5782
0
         xmlXPathCastNumberToBoolean(arg2->floatval));
5783
0
        break;
5784
0
    case XPATH_STRING:
5785
0
        if ((arg2->stringval == NULL) ||
5786
0
      (arg2->stringval[0] == 0)) ret = 0;
5787
0
        else
5788
0
      ret = 1;
5789
0
        ret = (arg1->boolval == ret);
5790
0
        break;
5791
0
    case XPATH_USERS:
5792
        /* TODO */
5793
0
        break;
5794
0
    case XPATH_NODESET:
5795
0
    case XPATH_XSLT_TREE:
5796
0
        break;
5797
0
      }
5798
0
      break;
5799
0
        case XPATH_NUMBER:
5800
0
      switch (arg2->type) {
5801
0
          case XPATH_UNDEFINED:
5802
0
        break;
5803
0
    case XPATH_BOOLEAN:
5804
0
        ret = (arg2->boolval==
5805
0
         xmlXPathCastNumberToBoolean(arg1->floatval));
5806
0
        break;
5807
0
    case XPATH_STRING:
5808
0
        xmlXPathValuePush(ctxt, arg2);
5809
0
        xmlXPathNumberFunction(ctxt, 1);
5810
0
        arg2 = xmlXPathValuePop(ctxt);
5811
0
                    if (ctxt->error)
5812
0
                        break;
5813
                    /* Falls through. */
5814
0
    case XPATH_NUMBER:
5815
        /* Hand check NaN and Infinity equalities */
5816
0
        if (xmlXPathIsNaN(arg1->floatval) ||
5817
0
          xmlXPathIsNaN(arg2->floatval)) {
5818
0
            ret = 0;
5819
0
        } else if (xmlXPathIsInf(arg1->floatval) == 1) {
5820
0
            if (xmlXPathIsInf(arg2->floatval) == 1)
5821
0
          ret = 1;
5822
0
      else
5823
0
          ret = 0;
5824
0
        } else if (xmlXPathIsInf(arg1->floatval) == -1) {
5825
0
      if (xmlXPathIsInf(arg2->floatval) == -1)
5826
0
          ret = 1;
5827
0
      else
5828
0
          ret = 0;
5829
0
        } else if (xmlXPathIsInf(arg2->floatval) == 1) {
5830
0
      if (xmlXPathIsInf(arg1->floatval) == 1)
5831
0
          ret = 1;
5832
0
      else
5833
0
          ret = 0;
5834
0
        } else if (xmlXPathIsInf(arg2->floatval) == -1) {
5835
0
      if (xmlXPathIsInf(arg1->floatval) == -1)
5836
0
          ret = 1;
5837
0
      else
5838
0
          ret = 0;
5839
0
        } else {
5840
0
            ret = (arg1->floatval == arg2->floatval);
5841
0
        }
5842
0
        break;
5843
0
    case XPATH_USERS:
5844
        /* TODO */
5845
0
        break;
5846
0
    case XPATH_NODESET:
5847
0
    case XPATH_XSLT_TREE:
5848
0
        break;
5849
0
      }
5850
0
      break;
5851
0
        case XPATH_STRING:
5852
0
      switch (arg2->type) {
5853
0
          case XPATH_UNDEFINED:
5854
0
        break;
5855
0
    case XPATH_BOOLEAN:
5856
0
        if ((arg1->stringval == NULL) ||
5857
0
      (arg1->stringval[0] == 0)) ret = 0;
5858
0
        else
5859
0
      ret = 1;
5860
0
        ret = (arg2->boolval == ret);
5861
0
        break;
5862
0
    case XPATH_STRING:
5863
0
        ret = xmlStrEqual(arg1->stringval, arg2->stringval);
5864
0
        break;
5865
0
    case XPATH_NUMBER:
5866
0
        xmlXPathValuePush(ctxt, arg1);
5867
0
        xmlXPathNumberFunction(ctxt, 1);
5868
0
        arg1 = xmlXPathValuePop(ctxt);
5869
0
                    if (ctxt->error)
5870
0
                        break;
5871
        /* Hand check NaN and Infinity equalities */
5872
0
        if (xmlXPathIsNaN(arg1->floatval) ||
5873
0
          xmlXPathIsNaN(arg2->floatval)) {
5874
0
            ret = 0;
5875
0
        } else if (xmlXPathIsInf(arg1->floatval) == 1) {
5876
0
      if (xmlXPathIsInf(arg2->floatval) == 1)
5877
0
          ret = 1;
5878
0
      else
5879
0
          ret = 0;
5880
0
        } else if (xmlXPathIsInf(arg1->floatval) == -1) {
5881
0
      if (xmlXPathIsInf(arg2->floatval) == -1)
5882
0
          ret = 1;
5883
0
      else
5884
0
          ret = 0;
5885
0
        } else if (xmlXPathIsInf(arg2->floatval) == 1) {
5886
0
      if (xmlXPathIsInf(arg1->floatval) == 1)
5887
0
          ret = 1;
5888
0
      else
5889
0
          ret = 0;
5890
0
        } else if (xmlXPathIsInf(arg2->floatval) == -1) {
5891
0
      if (xmlXPathIsInf(arg1->floatval) == -1)
5892
0
          ret = 1;
5893
0
      else
5894
0
          ret = 0;
5895
0
        } else {
5896
0
            ret = (arg1->floatval == arg2->floatval);
5897
0
        }
5898
0
        break;
5899
0
    case XPATH_USERS:
5900
        /* TODO */
5901
0
        break;
5902
0
    case XPATH_NODESET:
5903
0
    case XPATH_XSLT_TREE:
5904
0
        break;
5905
0
      }
5906
0
      break;
5907
0
        case XPATH_USERS:
5908
      /* TODO */
5909
0
      break;
5910
0
  case XPATH_NODESET:
5911
0
  case XPATH_XSLT_TREE:
5912
0
      break;
5913
0
    }
5914
0
    xmlXPathReleaseObject(ctxt->context, arg1);
5915
0
    xmlXPathReleaseObject(ctxt->context, arg2);
5916
0
    return(ret);
5917
0
}
5918
5919
/**
5920
 * xmlXPathEqualValues:
5921
 * @ctxt:  the XPath Parser context
5922
 *
5923
 * Implement the equal operation on XPath objects content: @arg1 == @arg2
5924
 *
5925
 * Returns 0 or 1 depending on the results of the test.
5926
 */
5927
int
5928
0
xmlXPathEqualValues(xmlXPathParserContextPtr ctxt) {
5929
0
    xmlXPathObjectPtr arg1, arg2, argtmp;
5930
0
    int ret = 0;
5931
5932
0
    if ((ctxt == NULL) || (ctxt->context == NULL)) return(0);
5933
0
    arg2 = xmlXPathValuePop(ctxt);
5934
0
    arg1 = xmlXPathValuePop(ctxt);
5935
0
    if ((arg1 == NULL) || (arg2 == NULL)) {
5936
0
  if (arg1 != NULL)
5937
0
      xmlXPathReleaseObject(ctxt->context, arg1);
5938
0
  else
5939
0
      xmlXPathReleaseObject(ctxt->context, arg2);
5940
0
  XP_ERROR0(XPATH_INVALID_OPERAND);
5941
0
    }
5942
5943
0
    if (arg1 == arg2) {
5944
0
  xmlXPathFreeObject(arg1);
5945
0
        return(1);
5946
0
    }
5947
5948
    /*
5949
     *If either argument is a nodeset, it's a 'special case'
5950
     */
5951
0
    if ((arg2->type == XPATH_NODESET) || (arg2->type == XPATH_XSLT_TREE) ||
5952
0
      (arg1->type == XPATH_NODESET) || (arg1->type == XPATH_XSLT_TREE)) {
5953
  /*
5954
   *Hack it to assure arg1 is the nodeset
5955
   */
5956
0
  if ((arg1->type != XPATH_NODESET) && (arg1->type != XPATH_XSLT_TREE)) {
5957
0
    argtmp = arg2;
5958
0
    arg2 = arg1;
5959
0
    arg1 = argtmp;
5960
0
  }
5961
0
  switch (arg2->type) {
5962
0
      case XPATH_UNDEFINED:
5963
0
    break;
5964
0
      case XPATH_NODESET:
5965
0
      case XPATH_XSLT_TREE:
5966
0
    ret = xmlXPathEqualNodeSets(ctxt, arg1, arg2, 0);
5967
0
    break;
5968
0
      case XPATH_BOOLEAN:
5969
0
    if ((arg1->nodesetval == NULL) ||
5970
0
      (arg1->nodesetval->nodeNr == 0)) ret = 0;
5971
0
    else
5972
0
        ret = 1;
5973
0
    ret = (ret == arg2->boolval);
5974
0
    break;
5975
0
      case XPATH_NUMBER:
5976
0
    ret = xmlXPathEqualNodeSetFloat(ctxt, arg1, arg2->floatval, 0);
5977
0
    break;
5978
0
      case XPATH_STRING:
5979
0
    ret = xmlXPathEqualNodeSetString(ctxt, arg1,
5980
0
                                                 arg2->stringval, 0);
5981
0
    break;
5982
0
      case XPATH_USERS:
5983
    /* TODO */
5984
0
    break;
5985
0
  }
5986
0
  xmlXPathReleaseObject(ctxt->context, arg1);
5987
0
  xmlXPathReleaseObject(ctxt->context, arg2);
5988
0
  return(ret);
5989
0
    }
5990
5991
0
    return (xmlXPathEqualValuesCommon(ctxt, arg1, arg2));
5992
0
}
5993
5994
/**
5995
 * xmlXPathNotEqualValues:
5996
 * @ctxt:  the XPath Parser context
5997
 *
5998
 * Implement the equal operation on XPath objects content: @arg1 == @arg2
5999
 *
6000
 * Returns 0 or 1 depending on the results of the test.
6001
 */
6002
int
6003
0
xmlXPathNotEqualValues(xmlXPathParserContextPtr ctxt) {
6004
0
    xmlXPathObjectPtr arg1, arg2, argtmp;
6005
0
    int ret = 0;
6006
6007
0
    if ((ctxt == NULL) || (ctxt->context == NULL)) return(0);
6008
0
    arg2 = xmlXPathValuePop(ctxt);
6009
0
    arg1 = xmlXPathValuePop(ctxt);
6010
0
    if ((arg1 == NULL) || (arg2 == NULL)) {
6011
0
  if (arg1 != NULL)
6012
0
      xmlXPathReleaseObject(ctxt->context, arg1);
6013
0
  else
6014
0
      xmlXPathReleaseObject(ctxt->context, arg2);
6015
0
  XP_ERROR0(XPATH_INVALID_OPERAND);
6016
0
    }
6017
6018
0
    if (arg1 == arg2) {
6019
0
  xmlXPathReleaseObject(ctxt->context, arg1);
6020
0
        return(0);
6021
0
    }
6022
6023
    /*
6024
     *If either argument is a nodeset, it's a 'special case'
6025
     */
6026
0
    if ((arg2->type == XPATH_NODESET) || (arg2->type == XPATH_XSLT_TREE) ||
6027
0
      (arg1->type == XPATH_NODESET) || (arg1->type == XPATH_XSLT_TREE)) {
6028
  /*
6029
   *Hack it to assure arg1 is the nodeset
6030
   */
6031
0
  if ((arg1->type != XPATH_NODESET) && (arg1->type != XPATH_XSLT_TREE)) {
6032
0
    argtmp = arg2;
6033
0
    arg2 = arg1;
6034
0
    arg1 = argtmp;
6035
0
  }
6036
0
  switch (arg2->type) {
6037
0
      case XPATH_UNDEFINED:
6038
0
    break;
6039
0
      case XPATH_NODESET:
6040
0
      case XPATH_XSLT_TREE:
6041
0
    ret = xmlXPathEqualNodeSets(ctxt, arg1, arg2, 1);
6042
0
    break;
6043
0
      case XPATH_BOOLEAN:
6044
0
    if ((arg1->nodesetval == NULL) ||
6045
0
      (arg1->nodesetval->nodeNr == 0)) ret = 0;
6046
0
    else
6047
0
        ret = 1;
6048
0
    ret = (ret != arg2->boolval);
6049
0
    break;
6050
0
      case XPATH_NUMBER:
6051
0
    ret = xmlXPathEqualNodeSetFloat(ctxt, arg1, arg2->floatval, 1);
6052
0
    break;
6053
0
      case XPATH_STRING:
6054
0
    ret = xmlXPathEqualNodeSetString(ctxt, arg1,
6055
0
                                                 arg2->stringval, 1);
6056
0
    break;
6057
0
      case XPATH_USERS:
6058
    /* TODO */
6059
0
    break;
6060
0
  }
6061
0
  xmlXPathReleaseObject(ctxt->context, arg1);
6062
0
  xmlXPathReleaseObject(ctxt->context, arg2);
6063
0
  return(ret);
6064
0
    }
6065
6066
0
    return (!xmlXPathEqualValuesCommon(ctxt, arg1, arg2));
6067
0
}
6068
6069
/**
6070
 * xmlXPathCompareValues:
6071
 * @ctxt:  the XPath Parser context
6072
 * @inf:  less than (1) or greater than (0)
6073
 * @strict:  is the comparison strict
6074
 *
6075
 * Implement the compare operation on XPath objects:
6076
 *     @arg1 < @arg2    (1, 1, ...
6077
 *     @arg1 <= @arg2   (1, 0, ...
6078
 *     @arg1 > @arg2    (0, 1, ...
6079
 *     @arg1 >= @arg2   (0, 0, ...
6080
 *
6081
 * When neither object to be compared is a node-set and the operator is
6082
 * <=, <, >=, >, then the objects are compared by converted both objects
6083
 * to numbers and comparing the numbers according to IEEE 754. The <
6084
 * comparison will be true if and only if the first number is less than the
6085
 * second number. The <= comparison will be true if and only if the first
6086
 * number is less than or equal to the second number. The > comparison
6087
 * will be true if and only if the first number is greater than the second
6088
 * number. The >= comparison will be true if and only if the first number
6089
 * is greater than or equal to the second number.
6090
 *
6091
 * Returns 1 if the comparison succeeded, 0 if it failed
6092
 */
6093
int
6094
0
xmlXPathCompareValues(xmlXPathParserContextPtr ctxt, int inf, int strict) {
6095
0
    int ret = 0, arg1i = 0, arg2i = 0;
6096
0
    xmlXPathObjectPtr arg1, arg2;
6097
6098
0
    if ((ctxt == NULL) || (ctxt->context == NULL)) return(0);
6099
0
    arg2 = xmlXPathValuePop(ctxt);
6100
0
    arg1 = xmlXPathValuePop(ctxt);
6101
0
    if ((arg1 == NULL) || (arg2 == NULL)) {
6102
0
  if (arg1 != NULL)
6103
0
      xmlXPathReleaseObject(ctxt->context, arg1);
6104
0
  else
6105
0
      xmlXPathReleaseObject(ctxt->context, arg2);
6106
0
  XP_ERROR0(XPATH_INVALID_OPERAND);
6107
0
    }
6108
6109
0
    if ((arg2->type == XPATH_NODESET) || (arg2->type == XPATH_XSLT_TREE) ||
6110
0
      (arg1->type == XPATH_NODESET) || (arg1->type == XPATH_XSLT_TREE)) {
6111
  /*
6112
   * If either argument is a XPATH_NODESET or XPATH_XSLT_TREE the two arguments
6113
   * are not freed from within this routine; they will be freed from the
6114
   * called routine, e.g. xmlXPathCompareNodeSets or xmlXPathCompareNodeSetValue
6115
   */
6116
0
  if (((arg2->type == XPATH_NODESET) || (arg2->type == XPATH_XSLT_TREE)) &&
6117
0
    ((arg1->type == XPATH_NODESET) || (arg1->type == XPATH_XSLT_TREE))){
6118
0
      ret = xmlXPathCompareNodeSets(ctxt, inf, strict, arg1, arg2);
6119
0
  } else {
6120
0
      if ((arg1->type == XPATH_NODESET) || (arg1->type == XPATH_XSLT_TREE)) {
6121
0
    ret = xmlXPathCompareNodeSetValue(ctxt, inf, strict,
6122
0
                                arg1, arg2);
6123
0
      } else {
6124
0
    ret = xmlXPathCompareNodeSetValue(ctxt, !inf, strict,
6125
0
                                arg2, arg1);
6126
0
      }
6127
0
  }
6128
0
  return(ret);
6129
0
    }
6130
6131
0
    if (arg1->type != XPATH_NUMBER) {
6132
0
  xmlXPathValuePush(ctxt, arg1);
6133
0
  xmlXPathNumberFunction(ctxt, 1);
6134
0
  arg1 = xmlXPathValuePop(ctxt);
6135
0
    }
6136
0
    if (arg2->type != XPATH_NUMBER) {
6137
0
  xmlXPathValuePush(ctxt, arg2);
6138
0
  xmlXPathNumberFunction(ctxt, 1);
6139
0
  arg2 = xmlXPathValuePop(ctxt);
6140
0
    }
6141
0
    if (ctxt->error)
6142
0
        goto error;
6143
    /*
6144
     * Add tests for infinity and nan
6145
     * => feedback on 3.4 for Inf and NaN
6146
     */
6147
    /* Hand check NaN and Infinity comparisons */
6148
0
    if (xmlXPathIsNaN(arg1->floatval) || xmlXPathIsNaN(arg2->floatval)) {
6149
0
  ret=0;
6150
0
    } else {
6151
0
  arg1i=xmlXPathIsInf(arg1->floatval);
6152
0
  arg2i=xmlXPathIsInf(arg2->floatval);
6153
0
  if (inf && strict) {
6154
0
      if ((arg1i == -1 && arg2i != -1) ||
6155
0
    (arg2i == 1 && arg1i != 1)) {
6156
0
    ret = 1;
6157
0
      } else if (arg1i == 0 && arg2i == 0) {
6158
0
    ret = (arg1->floatval < arg2->floatval);
6159
0
      } else {
6160
0
    ret = 0;
6161
0
      }
6162
0
  }
6163
0
  else if (inf && !strict) {
6164
0
      if (arg1i == -1 || arg2i == 1) {
6165
0
    ret = 1;
6166
0
      } else if (arg1i == 0 && arg2i == 0) {
6167
0
    ret = (arg1->floatval <= arg2->floatval);
6168
0
      } else {
6169
0
    ret = 0;
6170
0
      }
6171
0
  }
6172
0
  else if (!inf && strict) {
6173
0
      if ((arg1i == 1 && arg2i != 1) ||
6174
0
    (arg2i == -1 && arg1i != -1)) {
6175
0
    ret = 1;
6176
0
      } else if (arg1i == 0 && arg2i == 0) {
6177
0
    ret = (arg1->floatval > arg2->floatval);
6178
0
      } else {
6179
0
    ret = 0;
6180
0
      }
6181
0
  }
6182
0
  else if (!inf && !strict) {
6183
0
      if (arg1i == 1 || arg2i == -1) {
6184
0
    ret = 1;
6185
0
      } else if (arg1i == 0 && arg2i == 0) {
6186
0
    ret = (arg1->floatval >= arg2->floatval);
6187
0
      } else {
6188
0
    ret = 0;
6189
0
      }
6190
0
  }
6191
0
    }
6192
0
error:
6193
0
    xmlXPathReleaseObject(ctxt->context, arg1);
6194
0
    xmlXPathReleaseObject(ctxt->context, arg2);
6195
0
    return(ret);
6196
0
}
6197
6198
/**
6199
 * xmlXPathValueFlipSign:
6200
 * @ctxt:  the XPath Parser context
6201
 *
6202
 * Implement the unary - operation on an XPath object
6203
 * The numeric operators convert their operands to numbers as if
6204
 * by calling the number function.
6205
 */
6206
void
6207
0
xmlXPathValueFlipSign(xmlXPathParserContextPtr ctxt) {
6208
0
    if ((ctxt == NULL) || (ctxt->context == NULL)) return;
6209
0
    CAST_TO_NUMBER;
6210
0
    CHECK_TYPE(XPATH_NUMBER);
6211
0
    ctxt->value->floatval = -ctxt->value->floatval;
6212
0
}
6213
6214
/**
6215
 * xmlXPathAddValues:
6216
 * @ctxt:  the XPath Parser context
6217
 *
6218
 * Implement the add operation on XPath objects:
6219
 * The numeric operators convert their operands to numbers as if
6220
 * by calling the number function.
6221
 */
6222
void
6223
0
xmlXPathAddValues(xmlXPathParserContextPtr ctxt) {
6224
0
    xmlXPathObjectPtr arg;
6225
0
    double val;
6226
6227
0
    arg = xmlXPathValuePop(ctxt);
6228
0
    if (arg == NULL)
6229
0
  XP_ERROR(XPATH_INVALID_OPERAND);
6230
0
    val = xmlXPathCastToNumberInternal(ctxt, arg);
6231
0
    xmlXPathReleaseObject(ctxt->context, arg);
6232
0
    CAST_TO_NUMBER;
6233
0
    CHECK_TYPE(XPATH_NUMBER);
6234
0
    ctxt->value->floatval += val;
6235
0
}
6236
6237
/**
6238
 * xmlXPathSubValues:
6239
 * @ctxt:  the XPath Parser context
6240
 *
6241
 * Implement the subtraction operation on XPath objects:
6242
 * The numeric operators convert their operands to numbers as if
6243
 * by calling the number function.
6244
 */
6245
void
6246
0
xmlXPathSubValues(xmlXPathParserContextPtr ctxt) {
6247
0
    xmlXPathObjectPtr arg;
6248
0
    double val;
6249
6250
0
    arg = xmlXPathValuePop(ctxt);
6251
0
    if (arg == NULL)
6252
0
  XP_ERROR(XPATH_INVALID_OPERAND);
6253
0
    val = xmlXPathCastToNumberInternal(ctxt, arg);
6254
0
    xmlXPathReleaseObject(ctxt->context, arg);
6255
0
    CAST_TO_NUMBER;
6256
0
    CHECK_TYPE(XPATH_NUMBER);
6257
0
    ctxt->value->floatval -= val;
6258
0
}
6259
6260
/**
6261
 * xmlXPathMultValues:
6262
 * @ctxt:  the XPath Parser context
6263
 *
6264
 * Implement the multiply operation on XPath objects:
6265
 * The numeric operators convert their operands to numbers as if
6266
 * by calling the number function.
6267
 */
6268
void
6269
0
xmlXPathMultValues(xmlXPathParserContextPtr ctxt) {
6270
0
    xmlXPathObjectPtr arg;
6271
0
    double val;
6272
6273
0
    arg = xmlXPathValuePop(ctxt);
6274
0
    if (arg == NULL)
6275
0
  XP_ERROR(XPATH_INVALID_OPERAND);
6276
0
    val = xmlXPathCastToNumberInternal(ctxt, arg);
6277
0
    xmlXPathReleaseObject(ctxt->context, arg);
6278
0
    CAST_TO_NUMBER;
6279
0
    CHECK_TYPE(XPATH_NUMBER);
6280
0
    ctxt->value->floatval *= val;
6281
0
}
6282
6283
/**
6284
 * xmlXPathDivValues:
6285
 * @ctxt:  the XPath Parser context
6286
 *
6287
 * Implement the div operation on XPath objects @arg1 / @arg2:
6288
 * The numeric operators convert their operands to numbers as if
6289
 * by calling the number function.
6290
 */
6291
ATTRIBUTE_NO_SANITIZE("float-divide-by-zero")
6292
void
6293
0
xmlXPathDivValues(xmlXPathParserContextPtr ctxt) {
6294
0
    xmlXPathObjectPtr arg;
6295
0
    double val;
6296
6297
0
    arg = xmlXPathValuePop(ctxt);
6298
0
    if (arg == NULL)
6299
0
  XP_ERROR(XPATH_INVALID_OPERAND);
6300
0
    val = xmlXPathCastToNumberInternal(ctxt, arg);
6301
0
    xmlXPathReleaseObject(ctxt->context, arg);
6302
0
    CAST_TO_NUMBER;
6303
0
    CHECK_TYPE(XPATH_NUMBER);
6304
0
    ctxt->value->floatval /= val;
6305
0
}
6306
6307
/**
6308
 * xmlXPathModValues:
6309
 * @ctxt:  the XPath Parser context
6310
 *
6311
 * Implement the mod operation on XPath objects: @arg1 / @arg2
6312
 * The numeric operators convert their operands to numbers as if
6313
 * by calling the number function.
6314
 */
6315
void
6316
0
xmlXPathModValues(xmlXPathParserContextPtr ctxt) {
6317
0
    xmlXPathObjectPtr arg;
6318
0
    double arg1, arg2;
6319
6320
0
    arg = xmlXPathValuePop(ctxt);
6321
0
    if (arg == NULL)
6322
0
  XP_ERROR(XPATH_INVALID_OPERAND);
6323
0
    arg2 = xmlXPathCastToNumberInternal(ctxt, arg);
6324
0
    xmlXPathReleaseObject(ctxt->context, arg);
6325
0
    CAST_TO_NUMBER;
6326
0
    CHECK_TYPE(XPATH_NUMBER);
6327
0
    arg1 = ctxt->value->floatval;
6328
0
    if (arg2 == 0)
6329
0
  ctxt->value->floatval = xmlXPathNAN;
6330
0
    else {
6331
0
  ctxt->value->floatval = fmod(arg1, arg2);
6332
0
    }
6333
0
}
6334
6335
/************************************************************************
6336
 *                  *
6337
 *    The traversal functions         *
6338
 *                  *
6339
 ************************************************************************/
6340
6341
/*
6342
 * A traversal function enumerates nodes along an axis.
6343
 * Initially it must be called with NULL, and it indicates
6344
 * termination on the axis by returning NULL.
6345
 */
6346
typedef xmlNodePtr (*xmlXPathTraversalFunction)
6347
                    (xmlXPathParserContextPtr ctxt, xmlNodePtr cur);
6348
6349
/*
6350
 * xmlXPathTraversalFunctionExt:
6351
 * A traversal function enumerates nodes along an axis.
6352
 * Initially it must be called with NULL, and it indicates
6353
 * termination on the axis by returning NULL.
6354
 * The context node of the traversal is specified via @contextNode.
6355
 */
6356
typedef xmlNodePtr (*xmlXPathTraversalFunctionExt)
6357
                    (xmlNodePtr cur, xmlNodePtr contextNode);
6358
6359
/*
6360
 * xmlXPathNodeSetMergeFunction:
6361
 * Used for merging node sets in xmlXPathCollectAndTest().
6362
 */
6363
typedef xmlNodeSetPtr (*xmlXPathNodeSetMergeFunction)
6364
        (xmlNodeSetPtr, xmlNodeSetPtr);
6365
6366
6367
/**
6368
 * xmlXPathNextSelf:
6369
 * @ctxt:  the XPath Parser context
6370
 * @cur:  the current node in the traversal
6371
 *
6372
 * Traversal function for the "self" direction
6373
 * The self axis contains just the context node itself
6374
 *
6375
 * Returns the next element following that axis
6376
 */
6377
xmlNodePtr
6378
0
xmlXPathNextSelf(xmlXPathParserContextPtr ctxt, xmlNodePtr cur) {
6379
0
    if ((ctxt == NULL) || (ctxt->context == NULL)) return(NULL);
6380
0
    if (cur == NULL)
6381
0
        return(ctxt->context->node);
6382
0
    return(NULL);
6383
0
}
6384
6385
/**
6386
 * xmlXPathNextChild:
6387
 * @ctxt:  the XPath Parser context
6388
 * @cur:  the current node in the traversal
6389
 *
6390
 * Traversal function for the "child" direction
6391
 * The child axis contains the children of the context node in document order.
6392
 *
6393
 * Returns the next element following that axis
6394
 */
6395
xmlNodePtr
6396
0
xmlXPathNextChild(xmlXPathParserContextPtr ctxt, xmlNodePtr cur) {
6397
0
    if ((ctxt == NULL) || (ctxt->context == NULL)) return(NULL);
6398
0
    if (cur == NULL) {
6399
0
  if (ctxt->context->node == NULL) return(NULL);
6400
0
  switch (ctxt->context->node->type) {
6401
0
            case XML_ELEMENT_NODE:
6402
0
            case XML_TEXT_NODE:
6403
0
            case XML_CDATA_SECTION_NODE:
6404
0
            case XML_ENTITY_REF_NODE:
6405
0
            case XML_ENTITY_NODE:
6406
0
            case XML_PI_NODE:
6407
0
            case XML_COMMENT_NODE:
6408
0
            case XML_NOTATION_NODE:
6409
0
            case XML_DTD_NODE:
6410
0
    return(ctxt->context->node->children);
6411
0
            case XML_DOCUMENT_NODE:
6412
0
            case XML_DOCUMENT_TYPE_NODE:
6413
0
            case XML_DOCUMENT_FRAG_NODE:
6414
0
            case XML_HTML_DOCUMENT_NODE:
6415
0
    return(((xmlDocPtr) ctxt->context->node)->children);
6416
0
      case XML_ELEMENT_DECL:
6417
0
      case XML_ATTRIBUTE_DECL:
6418
0
      case XML_ENTITY_DECL:
6419
0
            case XML_ATTRIBUTE_NODE:
6420
0
      case XML_NAMESPACE_DECL:
6421
0
      case XML_XINCLUDE_START:
6422
0
      case XML_XINCLUDE_END:
6423
0
    return(NULL);
6424
0
  }
6425
0
  return(NULL);
6426
0
    }
6427
0
    if ((cur->type == XML_DOCUMENT_NODE) ||
6428
0
        (cur->type == XML_HTML_DOCUMENT_NODE))
6429
0
  return(NULL);
6430
0
    return(cur->next);
6431
0
}
6432
6433
/**
6434
 * xmlXPathNextChildElement:
6435
 * @ctxt:  the XPath Parser context
6436
 * @cur:  the current node in the traversal
6437
 *
6438
 * Traversal function for the "child" direction and nodes of type element.
6439
 * The child axis contains the children of the context node in document order.
6440
 *
6441
 * Returns the next element following that axis
6442
 */
6443
static xmlNodePtr
6444
2.50k
xmlXPathNextChildElement(xmlXPathParserContextPtr ctxt, xmlNodePtr cur) {
6445
2.50k
    if ((ctxt == NULL) || (ctxt->context == NULL)) return(NULL);
6446
2.50k
    if (cur == NULL) {
6447
824
  cur = ctxt->context->node;
6448
824
  if (cur == NULL) return(NULL);
6449
  /*
6450
  * Get the first element child.
6451
  */
6452
824
  switch (cur->type) {
6453
191
            case XML_ELEMENT_NODE:
6454
191
      case XML_DOCUMENT_FRAG_NODE:
6455
191
      case XML_ENTITY_REF_NODE: /* URGENT TODO: entify-refs as well? */
6456
191
            case XML_ENTITY_NODE:
6457
191
    cur = cur->children;
6458
191
    if (cur != NULL) {
6459
191
        if (cur->type == XML_ELEMENT_NODE)
6460
191
      return(cur);
6461
0
        do {
6462
0
      cur = cur->next;
6463
0
        } while ((cur != NULL) &&
6464
0
      (cur->type != XML_ELEMENT_NODE));
6465
0
        return(cur);
6466
191
    }
6467
0
    return(NULL);
6468
633
            case XML_DOCUMENT_NODE:
6469
633
            case XML_HTML_DOCUMENT_NODE:
6470
633
    return(xmlDocGetRootElement((xmlDocPtr) cur));
6471
0
      default:
6472
0
    return(NULL);
6473
824
  }
6474
0
  return(NULL);
6475
824
    }
6476
    /*
6477
    * Get the next sibling element node.
6478
    */
6479
1.68k
    switch (cur->type) {
6480
1.68k
  case XML_ELEMENT_NODE:
6481
1.68k
  case XML_TEXT_NODE:
6482
1.68k
  case XML_ENTITY_REF_NODE:
6483
1.68k
  case XML_ENTITY_NODE:
6484
1.68k
  case XML_CDATA_SECTION_NODE:
6485
1.68k
  case XML_PI_NODE:
6486
1.68k
  case XML_COMMENT_NODE:
6487
1.68k
  case XML_XINCLUDE_END:
6488
1.68k
      break;
6489
  /* case XML_DTD_NODE: */ /* URGENT TODO: DTD-node as well? */
6490
0
  default:
6491
0
      return(NULL);
6492
1.68k
    }
6493
1.68k
    if (cur->next != NULL) {
6494
1.24k
  if (cur->next->type == XML_ELEMENT_NODE)
6495
1.24k
      return(cur->next);
6496
0
  cur = cur->next;
6497
0
  do {
6498
0
      cur = cur->next;
6499
0
  } while ((cur != NULL) && (cur->type != XML_ELEMENT_NODE));
6500
0
  return(cur);
6501
1.24k
    }
6502
442
    return(NULL);
6503
1.68k
}
6504
6505
/**
6506
 * xmlXPathNextDescendant:
6507
 * @ctxt:  the XPath Parser context
6508
 * @cur:  the current node in the traversal
6509
 *
6510
 * Traversal function for the "descendant" direction
6511
 * the descendant axis contains the descendants of the context node in document
6512
 * order; a descendant is a child or a child of a child and so on.
6513
 *
6514
 * Returns the next element following that axis
6515
 */
6516
xmlNodePtr
6517
0
xmlXPathNextDescendant(xmlXPathParserContextPtr ctxt, xmlNodePtr cur) {
6518
0
    if ((ctxt == NULL) || (ctxt->context == NULL)) return(NULL);
6519
0
    if (cur == NULL) {
6520
0
  if (ctxt->context->node == NULL)
6521
0
      return(NULL);
6522
0
  if ((ctxt->context->node->type == XML_ATTRIBUTE_NODE) ||
6523
0
      (ctxt->context->node->type == XML_NAMESPACE_DECL))
6524
0
      return(NULL);
6525
6526
0
        if (ctxt->context->node == (xmlNodePtr) ctxt->context->doc)
6527
0
      return(ctxt->context->doc->children);
6528
0
        return(ctxt->context->node->children);
6529
0
    }
6530
6531
0
    if (cur->type == XML_NAMESPACE_DECL)
6532
0
        return(NULL);
6533
0
    if (cur->children != NULL) {
6534
  /*
6535
   * Do not descend on entities declarations
6536
   */
6537
0
  if (cur->children->type != XML_ENTITY_DECL) {
6538
0
      cur = cur->children;
6539
      /*
6540
       * Skip DTDs
6541
       */
6542
0
      if (cur->type != XML_DTD_NODE)
6543
0
    return(cur);
6544
0
  }
6545
0
    }
6546
6547
0
    if (cur == ctxt->context->node) return(NULL);
6548
6549
0
    while (cur->next != NULL) {
6550
0
  cur = cur->next;
6551
0
  if ((cur->type != XML_ENTITY_DECL) &&
6552
0
      (cur->type != XML_DTD_NODE))
6553
0
      return(cur);
6554
0
    }
6555
6556
0
    do {
6557
0
        cur = cur->parent;
6558
0
  if (cur == NULL) break;
6559
0
  if (cur == ctxt->context->node) return(NULL);
6560
0
  if (cur->next != NULL) {
6561
0
      cur = cur->next;
6562
0
      return(cur);
6563
0
  }
6564
0
    } while (cur != NULL);
6565
0
    return(cur);
6566
0
}
6567
6568
/**
6569
 * xmlXPathNextDescendantOrSelf:
6570
 * @ctxt:  the XPath Parser context
6571
 * @cur:  the current node in the traversal
6572
 *
6573
 * Traversal function for the "descendant-or-self" direction
6574
 * the descendant-or-self axis contains the context node and the descendants
6575
 * of the context node in document order; thus the context node is the first
6576
 * node on the axis, and the first child of the context node is the second node
6577
 * on the axis
6578
 *
6579
 * Returns the next element following that axis
6580
 */
6581
xmlNodePtr
6582
0
xmlXPathNextDescendantOrSelf(xmlXPathParserContextPtr ctxt, xmlNodePtr cur) {
6583
0
    if ((ctxt == NULL) || (ctxt->context == NULL)) return(NULL);
6584
0
    if (cur == NULL)
6585
0
        return(ctxt->context->node);
6586
6587
0
    if (ctxt->context->node == NULL)
6588
0
        return(NULL);
6589
0
    if ((ctxt->context->node->type == XML_ATTRIBUTE_NODE) ||
6590
0
        (ctxt->context->node->type == XML_NAMESPACE_DECL))
6591
0
        return(NULL);
6592
6593
0
    return(xmlXPathNextDescendant(ctxt, cur));
6594
0
}
6595
6596
/**
6597
 * xmlXPathNextParent:
6598
 * @ctxt:  the XPath Parser context
6599
 * @cur:  the current node in the traversal
6600
 *
6601
 * Traversal function for the "parent" direction
6602
 * The parent axis contains the parent of the context node, if there is one.
6603
 *
6604
 * Returns the next element following that axis
6605
 */
6606
xmlNodePtr
6607
0
xmlXPathNextParent(xmlXPathParserContextPtr ctxt, xmlNodePtr cur) {
6608
0
    if ((ctxt == NULL) || (ctxt->context == NULL)) return(NULL);
6609
    /*
6610
     * the parent of an attribute or namespace node is the element
6611
     * to which the attribute or namespace node is attached
6612
     * Namespace handling !!!
6613
     */
6614
0
    if (cur == NULL) {
6615
0
  if (ctxt->context->node == NULL) return(NULL);
6616
0
  switch (ctxt->context->node->type) {
6617
0
            case XML_ELEMENT_NODE:
6618
0
            case XML_TEXT_NODE:
6619
0
            case XML_CDATA_SECTION_NODE:
6620
0
            case XML_ENTITY_REF_NODE:
6621
0
            case XML_ENTITY_NODE:
6622
0
            case XML_PI_NODE:
6623
0
            case XML_COMMENT_NODE:
6624
0
            case XML_NOTATION_NODE:
6625
0
            case XML_DTD_NODE:
6626
0
      case XML_ELEMENT_DECL:
6627
0
      case XML_ATTRIBUTE_DECL:
6628
0
      case XML_XINCLUDE_START:
6629
0
      case XML_XINCLUDE_END:
6630
0
      case XML_ENTITY_DECL:
6631
0
    if (ctxt->context->node->parent == NULL)
6632
0
        return((xmlNodePtr) ctxt->context->doc);
6633
0
    if ((ctxt->context->node->parent->type == XML_ELEMENT_NODE) &&
6634
0
        ((ctxt->context->node->parent->name[0] == ' ') ||
6635
0
         (xmlStrEqual(ctxt->context->node->parent->name,
6636
0
         BAD_CAST "fake node libxslt"))))
6637
0
        return(NULL);
6638
0
    return(ctxt->context->node->parent);
6639
0
            case XML_ATTRIBUTE_NODE: {
6640
0
    xmlAttrPtr att = (xmlAttrPtr) ctxt->context->node;
6641
6642
0
    return(att->parent);
6643
0
      }
6644
0
            case XML_DOCUMENT_NODE:
6645
0
            case XML_DOCUMENT_TYPE_NODE:
6646
0
            case XML_DOCUMENT_FRAG_NODE:
6647
0
            case XML_HTML_DOCUMENT_NODE:
6648
0
                return(NULL);
6649
0
      case XML_NAMESPACE_DECL: {
6650
0
    xmlNsPtr ns = (xmlNsPtr) ctxt->context->node;
6651
6652
0
    if ((ns->next != NULL) &&
6653
0
        (ns->next->type != XML_NAMESPACE_DECL))
6654
0
        return((xmlNodePtr) ns->next);
6655
0
                return(NULL);
6656
0
      }
6657
0
  }
6658
0
    }
6659
0
    return(NULL);
6660
0
}
6661
6662
/**
6663
 * xmlXPathNextAncestor:
6664
 * @ctxt:  the XPath Parser context
6665
 * @cur:  the current node in the traversal
6666
 *
6667
 * Traversal function for the "ancestor" direction
6668
 * the ancestor axis contains the ancestors of the context node; the ancestors
6669
 * of the context node consist of the parent of context node and the parent's
6670
 * parent and so on; the nodes are ordered in reverse document order; thus the
6671
 * parent is the first node on the axis, and the parent's parent is the second
6672
 * node on the axis
6673
 *
6674
 * Returns the next element following that axis
6675
 */
6676
xmlNodePtr
6677
0
xmlXPathNextAncestor(xmlXPathParserContextPtr ctxt, xmlNodePtr cur) {
6678
0
    if ((ctxt == NULL) || (ctxt->context == NULL)) return(NULL);
6679
    /*
6680
     * the parent of an attribute or namespace node is the element
6681
     * to which the attribute or namespace node is attached
6682
     * !!!!!!!!!!!!!
6683
     */
6684
0
    if (cur == NULL) {
6685
0
  if (ctxt->context->node == NULL) return(NULL);
6686
0
  switch (ctxt->context->node->type) {
6687
0
            case XML_ELEMENT_NODE:
6688
0
            case XML_TEXT_NODE:
6689
0
            case XML_CDATA_SECTION_NODE:
6690
0
            case XML_ENTITY_REF_NODE:
6691
0
            case XML_ENTITY_NODE:
6692
0
            case XML_PI_NODE:
6693
0
            case XML_COMMENT_NODE:
6694
0
      case XML_DTD_NODE:
6695
0
      case XML_ELEMENT_DECL:
6696
0
      case XML_ATTRIBUTE_DECL:
6697
0
      case XML_ENTITY_DECL:
6698
0
            case XML_NOTATION_NODE:
6699
0
      case XML_XINCLUDE_START:
6700
0
      case XML_XINCLUDE_END:
6701
0
    if (ctxt->context->node->parent == NULL)
6702
0
        return((xmlNodePtr) ctxt->context->doc);
6703
0
    if ((ctxt->context->node->parent->type == XML_ELEMENT_NODE) &&
6704
0
        ((ctxt->context->node->parent->name[0] == ' ') ||
6705
0
         (xmlStrEqual(ctxt->context->node->parent->name,
6706
0
         BAD_CAST "fake node libxslt"))))
6707
0
        return(NULL);
6708
0
    return(ctxt->context->node->parent);
6709
0
            case XML_ATTRIBUTE_NODE: {
6710
0
    xmlAttrPtr tmp = (xmlAttrPtr) ctxt->context->node;
6711
6712
0
    return(tmp->parent);
6713
0
      }
6714
0
            case XML_DOCUMENT_NODE:
6715
0
            case XML_DOCUMENT_TYPE_NODE:
6716
0
            case XML_DOCUMENT_FRAG_NODE:
6717
0
            case XML_HTML_DOCUMENT_NODE:
6718
0
                return(NULL);
6719
0
      case XML_NAMESPACE_DECL: {
6720
0
    xmlNsPtr ns = (xmlNsPtr) ctxt->context->node;
6721
6722
0
    if ((ns->next != NULL) &&
6723
0
        (ns->next->type != XML_NAMESPACE_DECL))
6724
0
        return((xmlNodePtr) ns->next);
6725
    /* Bad, how did that namespace end up here ? */
6726
0
                return(NULL);
6727
0
      }
6728
0
  }
6729
0
  return(NULL);
6730
0
    }
6731
0
    if (cur == ctxt->context->doc->children)
6732
0
  return((xmlNodePtr) ctxt->context->doc);
6733
0
    if (cur == (xmlNodePtr) ctxt->context->doc)
6734
0
  return(NULL);
6735
0
    switch (cur->type) {
6736
0
  case XML_ELEMENT_NODE:
6737
0
  case XML_TEXT_NODE:
6738
0
  case XML_CDATA_SECTION_NODE:
6739
0
  case XML_ENTITY_REF_NODE:
6740
0
  case XML_ENTITY_NODE:
6741
0
  case XML_PI_NODE:
6742
0
  case XML_COMMENT_NODE:
6743
0
  case XML_NOTATION_NODE:
6744
0
  case XML_DTD_NODE:
6745
0
        case XML_ELEMENT_DECL:
6746
0
        case XML_ATTRIBUTE_DECL:
6747
0
        case XML_ENTITY_DECL:
6748
0
  case XML_XINCLUDE_START:
6749
0
  case XML_XINCLUDE_END:
6750
0
      if (cur->parent == NULL)
6751
0
    return(NULL);
6752
0
      if ((cur->parent->type == XML_ELEMENT_NODE) &&
6753
0
    ((cur->parent->name[0] == ' ') ||
6754
0
     (xmlStrEqual(cur->parent->name,
6755
0
            BAD_CAST "fake node libxslt"))))
6756
0
    return(NULL);
6757
0
      return(cur->parent);
6758
0
  case XML_ATTRIBUTE_NODE: {
6759
0
      xmlAttrPtr att = (xmlAttrPtr) cur;
6760
6761
0
      return(att->parent);
6762
0
  }
6763
0
  case XML_NAMESPACE_DECL: {
6764
0
      xmlNsPtr ns = (xmlNsPtr) cur;
6765
6766
0
      if ((ns->next != NULL) &&
6767
0
          (ns->next->type != XML_NAMESPACE_DECL))
6768
0
          return((xmlNodePtr) ns->next);
6769
      /* Bad, how did that namespace end up here ? */
6770
0
            return(NULL);
6771
0
  }
6772
0
  case XML_DOCUMENT_NODE:
6773
0
  case XML_DOCUMENT_TYPE_NODE:
6774
0
  case XML_DOCUMENT_FRAG_NODE:
6775
0
  case XML_HTML_DOCUMENT_NODE:
6776
0
      return(NULL);
6777
0
    }
6778
0
    return(NULL);
6779
0
}
6780
6781
/**
6782
 * xmlXPathNextAncestorOrSelf:
6783
 * @ctxt:  the XPath Parser context
6784
 * @cur:  the current node in the traversal
6785
 *
6786
 * Traversal function for the "ancestor-or-self" direction
6787
 * he ancestor-or-self axis contains the context node and ancestors of
6788
 * the context node in reverse document order; thus the context node is
6789
 * the first node on the axis, and the context node's parent the second;
6790
 * parent here is defined the same as with the parent axis.
6791
 *
6792
 * Returns the next element following that axis
6793
 */
6794
xmlNodePtr
6795
0
xmlXPathNextAncestorOrSelf(xmlXPathParserContextPtr ctxt, xmlNodePtr cur) {
6796
0
    if ((ctxt == NULL) || (ctxt->context == NULL)) return(NULL);
6797
0
    if (cur == NULL)
6798
0
        return(ctxt->context->node);
6799
0
    return(xmlXPathNextAncestor(ctxt, cur));
6800
0
}
6801
6802
/**
6803
 * xmlXPathNextFollowingSibling:
6804
 * @ctxt:  the XPath Parser context
6805
 * @cur:  the current node in the traversal
6806
 *
6807
 * Traversal function for the "following-sibling" direction
6808
 * The following-sibling axis contains the following siblings of the context
6809
 * node in document order.
6810
 *
6811
 * Returns the next element following that axis
6812
 */
6813
xmlNodePtr
6814
0
xmlXPathNextFollowingSibling(xmlXPathParserContextPtr ctxt, xmlNodePtr cur) {
6815
0
    if ((ctxt == NULL) || (ctxt->context == NULL)) return(NULL);
6816
0
    if ((ctxt->context->node->type == XML_ATTRIBUTE_NODE) ||
6817
0
  (ctxt->context->node->type == XML_NAMESPACE_DECL))
6818
0
  return(NULL);
6819
0
    if (cur == (xmlNodePtr) ctxt->context->doc)
6820
0
        return(NULL);
6821
0
    if (cur == NULL)
6822
0
        return(ctxt->context->node->next);
6823
0
    return(cur->next);
6824
0
}
6825
6826
/**
6827
 * xmlXPathNextPrecedingSibling:
6828
 * @ctxt:  the XPath Parser context
6829
 * @cur:  the current node in the traversal
6830
 *
6831
 * Traversal function for the "preceding-sibling" direction
6832
 * The preceding-sibling axis contains the preceding siblings of the context
6833
 * node in reverse document order; the first preceding sibling is first on the
6834
 * axis; the sibling preceding that node is the second on the axis and so on.
6835
 *
6836
 * Returns the next element following that axis
6837
 */
6838
xmlNodePtr
6839
0
xmlXPathNextPrecedingSibling(xmlXPathParserContextPtr ctxt, xmlNodePtr cur) {
6840
0
    if ((ctxt == NULL) || (ctxt->context == NULL)) return(NULL);
6841
0
    if ((ctxt->context->node->type == XML_ATTRIBUTE_NODE) ||
6842
0
  (ctxt->context->node->type == XML_NAMESPACE_DECL))
6843
0
  return(NULL);
6844
0
    if (cur == (xmlNodePtr) ctxt->context->doc)
6845
0
        return(NULL);
6846
0
    if (cur == NULL)
6847
0
        return(ctxt->context->node->prev);
6848
0
    if ((cur->prev != NULL) && (cur->prev->type == XML_DTD_NODE)) {
6849
0
  cur = cur->prev;
6850
0
  if (cur == NULL)
6851
0
      return(ctxt->context->node->prev);
6852
0
    }
6853
0
    return(cur->prev);
6854
0
}
6855
6856
/**
6857
 * xmlXPathNextFollowing:
6858
 * @ctxt:  the XPath Parser context
6859
 * @cur:  the current node in the traversal
6860
 *
6861
 * Traversal function for the "following" direction
6862
 * The following axis contains all nodes in the same document as the context
6863
 * node that are after the context node in document order, excluding any
6864
 * descendants and excluding attribute nodes and namespace nodes; the nodes
6865
 * are ordered in document order
6866
 *
6867
 * Returns the next element following that axis
6868
 */
6869
xmlNodePtr
6870
0
xmlXPathNextFollowing(xmlXPathParserContextPtr ctxt, xmlNodePtr cur) {
6871
0
    if ((ctxt == NULL) || (ctxt->context == NULL)) return(NULL);
6872
0
    if ((cur != NULL) && (cur->type  != XML_ATTRIBUTE_NODE) &&
6873
0
        (cur->type != XML_NAMESPACE_DECL) && (cur->children != NULL))
6874
0
        return(cur->children);
6875
6876
0
    if (cur == NULL) {
6877
0
        cur = ctxt->context->node;
6878
0
        if (cur->type == XML_ATTRIBUTE_NODE) {
6879
0
            cur = cur->parent;
6880
0
        } else if (cur->type == XML_NAMESPACE_DECL) {
6881
0
            xmlNsPtr ns = (xmlNsPtr) cur;
6882
6883
0
            if ((ns->next == NULL) ||
6884
0
                (ns->next->type == XML_NAMESPACE_DECL))
6885
0
                return (NULL);
6886
0
            cur = (xmlNodePtr) ns->next;
6887
0
        }
6888
0
    }
6889
0
    if (cur == NULL) return(NULL) ; /* ERROR */
6890
0
    if (cur->next != NULL) return(cur->next) ;
6891
0
    do {
6892
0
        cur = cur->parent;
6893
0
        if (cur == NULL) break;
6894
0
        if (cur == (xmlNodePtr) ctxt->context->doc) return(NULL);
6895
0
        if (cur->next != NULL) return(cur->next);
6896
0
    } while (cur != NULL);
6897
0
    return(cur);
6898
0
}
6899
6900
/*
6901
 * xmlXPathIsAncestor:
6902
 * @ancestor:  the ancestor node
6903
 * @node:  the current node
6904
 *
6905
 * Check that @ancestor is a @node's ancestor
6906
 *
6907
 * returns 1 if @ancestor is a @node's ancestor, 0 otherwise.
6908
 */
6909
static int
6910
0
xmlXPathIsAncestor(xmlNodePtr ancestor, xmlNodePtr node) {
6911
0
    if ((ancestor == NULL) || (node == NULL)) return(0);
6912
0
    if (node->type == XML_NAMESPACE_DECL)
6913
0
        return(0);
6914
0
    if (ancestor->type == XML_NAMESPACE_DECL)
6915
0
        return(0);
6916
    /* nodes need to be in the same document */
6917
0
    if (ancestor->doc != node->doc) return(0);
6918
    /* avoid searching if ancestor or node is the root node */
6919
0
    if (ancestor == (xmlNodePtr) node->doc) return(1);
6920
0
    if (node == (xmlNodePtr) ancestor->doc) return(0);
6921
0
    while (node->parent != NULL) {
6922
0
        if (node->parent == ancestor)
6923
0
            return(1);
6924
0
  node = node->parent;
6925
0
    }
6926
0
    return(0);
6927
0
}
6928
6929
/**
6930
 * xmlXPathNextPreceding:
6931
 * @ctxt:  the XPath Parser context
6932
 * @cur:  the current node in the traversal
6933
 *
6934
 * Traversal function for the "preceding" direction
6935
 * the preceding axis contains all nodes in the same document as the context
6936
 * node that are before the context node in document order, excluding any
6937
 * ancestors and excluding attribute nodes and namespace nodes; the nodes are
6938
 * ordered in reverse document order
6939
 *
6940
 * Returns the next element following that axis
6941
 */
6942
xmlNodePtr
6943
xmlXPathNextPreceding(xmlXPathParserContextPtr ctxt, xmlNodePtr cur)
6944
0
{
6945
0
    if ((ctxt == NULL) || (ctxt->context == NULL)) return(NULL);
6946
0
    if (cur == NULL) {
6947
0
        cur = ctxt->context->node;
6948
0
        if (cur->type == XML_ATTRIBUTE_NODE) {
6949
0
            cur = cur->parent;
6950
0
        } else if (cur->type == XML_NAMESPACE_DECL) {
6951
0
            xmlNsPtr ns = (xmlNsPtr) cur;
6952
6953
0
            if ((ns->next == NULL) ||
6954
0
                (ns->next->type == XML_NAMESPACE_DECL))
6955
0
                return (NULL);
6956
0
            cur = (xmlNodePtr) ns->next;
6957
0
        }
6958
0
    }
6959
0
    if ((cur == NULL) || (cur->type == XML_NAMESPACE_DECL))
6960
0
  return (NULL);
6961
0
    if ((cur->prev != NULL) && (cur->prev->type == XML_DTD_NODE))
6962
0
  cur = cur->prev;
6963
0
    do {
6964
0
        if (cur->prev != NULL) {
6965
0
            for (cur = cur->prev; cur->last != NULL; cur = cur->last) ;
6966
0
            return (cur);
6967
0
        }
6968
6969
0
        cur = cur->parent;
6970
0
        if (cur == NULL)
6971
0
            return (NULL);
6972
0
        if (cur == ctxt->context->doc->children)
6973
0
            return (NULL);
6974
0
    } while (xmlXPathIsAncestor(cur, ctxt->context->node));
6975
0
    return (cur);
6976
0
}
6977
6978
/**
6979
 * xmlXPathNextPrecedingInternal:
6980
 * @ctxt:  the XPath Parser context
6981
 * @cur:  the current node in the traversal
6982
 *
6983
 * Traversal function for the "preceding" direction
6984
 * the preceding axis contains all nodes in the same document as the context
6985
 * node that are before the context node in document order, excluding any
6986
 * ancestors and excluding attribute nodes and namespace nodes; the nodes are
6987
 * ordered in reverse document order
6988
 * This is a faster implementation but internal only since it requires a
6989
 * state kept in the parser context: ctxt->ancestor.
6990
 *
6991
 * Returns the next element following that axis
6992
 */
6993
static xmlNodePtr
6994
xmlXPathNextPrecedingInternal(xmlXPathParserContextPtr ctxt,
6995
                              xmlNodePtr cur)
6996
0
{
6997
0
    if ((ctxt == NULL) || (ctxt->context == NULL)) return(NULL);
6998
0
    if (cur == NULL) {
6999
0
        cur = ctxt->context->node;
7000
0
        if (cur == NULL)
7001
0
            return (NULL);
7002
0
        if (cur->type == XML_ATTRIBUTE_NODE) {
7003
0
            cur = cur->parent;
7004
0
        } else if (cur->type == XML_NAMESPACE_DECL) {
7005
0
            xmlNsPtr ns = (xmlNsPtr) cur;
7006
7007
0
            if ((ns->next == NULL) ||
7008
0
                (ns->next->type == XML_NAMESPACE_DECL))
7009
0
                return (NULL);
7010
0
            cur = (xmlNodePtr) ns->next;
7011
0
        }
7012
0
        ctxt->ancestor = cur->parent;
7013
0
    }
7014
0
    if (cur->type == XML_NAMESPACE_DECL)
7015
0
        return(NULL);
7016
0
    if ((cur->prev != NULL) && (cur->prev->type == XML_DTD_NODE))
7017
0
  cur = cur->prev;
7018
0
    while (cur->prev == NULL) {
7019
0
        cur = cur->parent;
7020
0
        if (cur == NULL)
7021
0
            return (NULL);
7022
0
        if (cur == ctxt->context->doc->children)
7023
0
            return (NULL);
7024
0
        if (cur != ctxt->ancestor)
7025
0
            return (cur);
7026
0
        ctxt->ancestor = cur->parent;
7027
0
    }
7028
0
    cur = cur->prev;
7029
0
    while (cur->last != NULL)
7030
0
        cur = cur->last;
7031
0
    return (cur);
7032
0
}
7033
7034
/**
7035
 * xmlXPathNextNamespace:
7036
 * @ctxt:  the XPath Parser context
7037
 * @cur:  the current attribute in the traversal
7038
 *
7039
 * Traversal function for the "namespace" direction
7040
 * the namespace axis contains the namespace nodes of the context node;
7041
 * the order of nodes on this axis is implementation-defined; the axis will
7042
 * be empty unless the context node is an element
7043
 *
7044
 * We keep the XML namespace node at the end of the list.
7045
 *
7046
 * Returns the next element following that axis
7047
 */
7048
xmlNodePtr
7049
0
xmlXPathNextNamespace(xmlXPathParserContextPtr ctxt, xmlNodePtr cur) {
7050
0
    if ((ctxt == NULL) || (ctxt->context == NULL)) return(NULL);
7051
0
    if (ctxt->context->node->type != XML_ELEMENT_NODE) return(NULL);
7052
0
    if (cur == NULL) {
7053
0
        if (ctxt->context->tmpNsList != NULL)
7054
0
      xmlFree(ctxt->context->tmpNsList);
7055
0
  ctxt->context->tmpNsNr = 0;
7056
0
        if (xmlGetNsListSafe(ctxt->context->doc, ctxt->context->node,
7057
0
                             &ctxt->context->tmpNsList) < 0) {
7058
0
            xmlXPathPErrMemory(ctxt);
7059
0
            return(NULL);
7060
0
        }
7061
0
        if (ctxt->context->tmpNsList != NULL) {
7062
0
            while (ctxt->context->tmpNsList[ctxt->context->tmpNsNr] != NULL) {
7063
0
                ctxt->context->tmpNsNr++;
7064
0
            }
7065
0
        }
7066
0
  return((xmlNodePtr) xmlXPathXMLNamespace);
7067
0
    }
7068
0
    if (ctxt->context->tmpNsNr > 0) {
7069
0
  return (xmlNodePtr)ctxt->context->tmpNsList[--ctxt->context->tmpNsNr];
7070
0
    } else {
7071
0
  if (ctxt->context->tmpNsList != NULL)
7072
0
      xmlFree(ctxt->context->tmpNsList);
7073
0
  ctxt->context->tmpNsList = NULL;
7074
0
  return(NULL);
7075
0
    }
7076
0
}
7077
7078
/**
7079
 * xmlXPathNextAttribute:
7080
 * @ctxt:  the XPath Parser context
7081
 * @cur:  the current attribute in the traversal
7082
 *
7083
 * Traversal function for the "attribute" direction
7084
 * TODO: support DTD inherited default attributes
7085
 *
7086
 * Returns the next element following that axis
7087
 */
7088
xmlNodePtr
7089
186
xmlXPathNextAttribute(xmlXPathParserContextPtr ctxt, xmlNodePtr cur) {
7090
186
    if ((ctxt == NULL) || (ctxt->context == NULL)) return(NULL);
7091
186
    if (ctxt->context->node == NULL)
7092
0
  return(NULL);
7093
186
    if (ctxt->context->node->type != XML_ELEMENT_NODE)
7094
0
  return(NULL);
7095
186
    if (cur == NULL) {
7096
93
        if (ctxt->context->node == (xmlNodePtr) ctxt->context->doc)
7097
0
      return(NULL);
7098
93
        return((xmlNodePtr)ctxt->context->node->properties);
7099
93
    }
7100
93
    return((xmlNodePtr)cur->next);
7101
186
}
7102
7103
/************************************************************************
7104
 *                  *
7105
 *    NodeTest Functions          *
7106
 *                  *
7107
 ************************************************************************/
7108
7109
#define IS_FUNCTION     200
7110
7111
7112
/************************************************************************
7113
 *                  *
7114
 *    Implicit tree core function library     *
7115
 *                  *
7116
 ************************************************************************/
7117
7118
/**
7119
 * xmlXPathRoot:
7120
 * @ctxt:  the XPath Parser context
7121
 *
7122
 * Initialize the context to the root of the document
7123
 */
7124
void
7125
633
xmlXPathRoot(xmlXPathParserContextPtr ctxt) {
7126
633
    if ((ctxt == NULL) || (ctxt->context == NULL))
7127
0
  return;
7128
633
    xmlXPathValuePush(ctxt, xmlXPathCacheNewNodeSet(ctxt,
7129
633
                                            (xmlNodePtr) ctxt->context->doc));
7130
633
}
7131
7132
/************************************************************************
7133
 *                  *
7134
 *    The explicit core function library      *
7135
 *http://www.w3.org/Style/XSL/Group/1999/07/xpath-19990705.html#corelib *
7136
 *                  *
7137
 ************************************************************************/
7138
7139
7140
/**
7141
 * xmlXPathLastFunction:
7142
 * @ctxt:  the XPath Parser context
7143
 * @nargs:  the number of arguments
7144
 *
7145
 * Implement the last() XPath function
7146
 *    number last()
7147
 * The last function returns the number of nodes in the context node list.
7148
 */
7149
void
7150
0
xmlXPathLastFunction(xmlXPathParserContextPtr ctxt, int nargs) {
7151
0
    CHECK_ARITY(0);
7152
0
    if (ctxt->context->contextSize >= 0) {
7153
0
  xmlXPathValuePush(ctxt,
7154
0
      xmlXPathCacheNewFloat(ctxt, (double) ctxt->context->contextSize));
7155
0
    } else {
7156
0
  XP_ERROR(XPATH_INVALID_CTXT_SIZE);
7157
0
    }
7158
0
}
7159
7160
/**
7161
 * xmlXPathPositionFunction:
7162
 * @ctxt:  the XPath Parser context
7163
 * @nargs:  the number of arguments
7164
 *
7165
 * Implement the position() XPath function
7166
 *    number position()
7167
 * The position function returns the position of the context node in the
7168
 * context node list. The first position is 1, and so the last position
7169
 * will be equal to last().
7170
 */
7171
void
7172
0
xmlXPathPositionFunction(xmlXPathParserContextPtr ctxt, int nargs) {
7173
0
    CHECK_ARITY(0);
7174
0
    if (ctxt->context->proximityPosition >= 0) {
7175
0
  xmlXPathValuePush(ctxt, xmlXPathCacheNewFloat(ctxt,
7176
0
            (double) ctxt->context->proximityPosition));
7177
0
    } else {
7178
0
  XP_ERROR(XPATH_INVALID_CTXT_POSITION);
7179
0
    }
7180
0
}
7181
7182
/**
7183
 * xmlXPathCountFunction:
7184
 * @ctxt:  the XPath Parser context
7185
 * @nargs:  the number of arguments
7186
 *
7187
 * Implement the count() XPath function
7188
 *    number count(node-set)
7189
 */
7190
void
7191
0
xmlXPathCountFunction(xmlXPathParserContextPtr ctxt, int nargs) {
7192
0
    xmlXPathObjectPtr cur;
7193
7194
0
    CHECK_ARITY(1);
7195
0
    if ((ctxt->value == NULL) ||
7196
0
  ((ctxt->value->type != XPATH_NODESET) &&
7197
0
   (ctxt->value->type != XPATH_XSLT_TREE)))
7198
0
  XP_ERROR(XPATH_INVALID_TYPE);
7199
0
    cur = xmlXPathValuePop(ctxt);
7200
7201
0
    if ((cur == NULL) || (cur->nodesetval == NULL))
7202
0
  xmlXPathValuePush(ctxt, xmlXPathCacheNewFloat(ctxt, 0.0));
7203
0
    else
7204
0
  xmlXPathValuePush(ctxt, xmlXPathCacheNewFloat(ctxt,
7205
0
      (double) cur->nodesetval->nodeNr));
7206
0
    xmlXPathReleaseObject(ctxt->context, cur);
7207
0
}
7208
7209
/**
7210
 * xmlXPathGetElementsByIds:
7211
 * @doc:  the document
7212
 * @ids:  a whitespace separated list of IDs
7213
 *
7214
 * Selects elements by their unique ID.
7215
 *
7216
 * Returns a node-set of selected elements.
7217
 */
7218
static xmlNodeSetPtr
7219
0
xmlXPathGetElementsByIds (xmlDocPtr doc, const xmlChar *ids) {
7220
0
    xmlNodeSetPtr ret;
7221
0
    const xmlChar *cur = ids;
7222
0
    xmlChar *ID;
7223
0
    xmlAttrPtr attr;
7224
0
    xmlNodePtr elem = NULL;
7225
7226
0
    if (ids == NULL) return(NULL);
7227
7228
0
    ret = xmlXPathNodeSetCreate(NULL);
7229
0
    if (ret == NULL)
7230
0
        return(ret);
7231
7232
0
    while (IS_BLANK_CH(*cur)) cur++;
7233
0
    while (*cur != 0) {
7234
0
  while ((!IS_BLANK_CH(*cur)) && (*cur != 0))
7235
0
      cur++;
7236
7237
0
        ID = xmlStrndup(ids, cur - ids);
7238
0
  if (ID == NULL) {
7239
0
            xmlXPathFreeNodeSet(ret);
7240
0
            return(NULL);
7241
0
        }
7242
        /*
7243
         * We used to check the fact that the value passed
7244
         * was an NCName, but this generated much troubles for
7245
         * me and Aleksey Sanin, people blatantly violated that
7246
         * constraint, like Visa3D spec.
7247
         * if (xmlValidateNCName(ID, 1) == 0)
7248
         */
7249
0
        attr = xmlGetID(doc, ID);
7250
0
        xmlFree(ID);
7251
0
        if (attr != NULL) {
7252
0
            if (attr->type == XML_ATTRIBUTE_NODE)
7253
0
                elem = attr->parent;
7254
0
            else if (attr->type == XML_ELEMENT_NODE)
7255
0
                elem = (xmlNodePtr) attr;
7256
0
            else
7257
0
                elem = NULL;
7258
0
            if (elem != NULL) {
7259
0
                if (xmlXPathNodeSetAdd(ret, elem) < 0) {
7260
0
                    xmlXPathFreeNodeSet(ret);
7261
0
                    return(NULL);
7262
0
                }
7263
0
            }
7264
0
        }
7265
7266
0
  while (IS_BLANK_CH(*cur)) cur++;
7267
0
  ids = cur;
7268
0
    }
7269
0
    return(ret);
7270
0
}
7271
7272
/**
7273
 * xmlXPathIdFunction:
7274
 * @ctxt:  the XPath Parser context
7275
 * @nargs:  the number of arguments
7276
 *
7277
 * Implement the id() XPath function
7278
 *    node-set id(object)
7279
 * The id function selects elements by their unique ID
7280
 * (see [5.2.1 Unique IDs]). When the argument to id is of type node-set,
7281
 * then the result is the union of the result of applying id to the
7282
 * string value of each of the nodes in the argument node-set. When the
7283
 * argument to id is of any other type, the argument is converted to a
7284
 * string as if by a call to the string function; the string is split
7285
 * into a whitespace-separated list of tokens (whitespace is any sequence
7286
 * of characters matching the production S); the result is a node-set
7287
 * containing the elements in the same document as the context node that
7288
 * have a unique ID equal to any of the tokens in the list.
7289
 */
7290
void
7291
0
xmlXPathIdFunction(xmlXPathParserContextPtr ctxt, int nargs) {
7292
0
    xmlChar *tokens;
7293
0
    xmlNodeSetPtr ret;
7294
0
    xmlXPathObjectPtr obj;
7295
7296
0
    CHECK_ARITY(1);
7297
0
    obj = xmlXPathValuePop(ctxt);
7298
0
    if (obj == NULL) XP_ERROR(XPATH_INVALID_OPERAND);
7299
0
    if ((obj->type == XPATH_NODESET) || (obj->type == XPATH_XSLT_TREE)) {
7300
0
  xmlNodeSetPtr ns;
7301
0
  int i;
7302
7303
0
  ret = xmlXPathNodeSetCreate(NULL);
7304
0
        if (ret == NULL)
7305
0
            xmlXPathPErrMemory(ctxt);
7306
7307
0
  if (obj->nodesetval != NULL) {
7308
0
      for (i = 0; i < obj->nodesetval->nodeNr; i++) {
7309
0
    tokens =
7310
0
        xmlXPathCastNodeToString(obj->nodesetval->nodeTab[i]);
7311
0
                if (tokens == NULL)
7312
0
                    xmlXPathPErrMemory(ctxt);
7313
0
    ns = xmlXPathGetElementsByIds(ctxt->context->doc, tokens);
7314
0
                if (ns == NULL)
7315
0
                    xmlXPathPErrMemory(ctxt);
7316
0
    ret = xmlXPathNodeSetMerge(ret, ns);
7317
0
                if (ret == NULL)
7318
0
                    xmlXPathPErrMemory(ctxt);
7319
0
    xmlXPathFreeNodeSet(ns);
7320
0
    if (tokens != NULL)
7321
0
        xmlFree(tokens);
7322
0
      }
7323
0
  }
7324
0
  xmlXPathReleaseObject(ctxt->context, obj);
7325
0
  xmlXPathValuePush(ctxt, xmlXPathCacheWrapNodeSet(ctxt, ret));
7326
0
  return;
7327
0
    }
7328
0
    tokens = xmlXPathCastToString(obj);
7329
0
    if (tokens == NULL)
7330
0
        xmlXPathPErrMemory(ctxt);
7331
0
    xmlXPathReleaseObject(ctxt->context, obj);
7332
0
    ret = xmlXPathGetElementsByIds(ctxt->context->doc, tokens);
7333
0
    if (ret == NULL)
7334
0
        xmlXPathPErrMemory(ctxt);
7335
0
    xmlFree(tokens);
7336
0
    xmlXPathValuePush(ctxt, xmlXPathCacheWrapNodeSet(ctxt, ret));
7337
0
}
7338
7339
/**
7340
 * xmlXPathLocalNameFunction:
7341
 * @ctxt:  the XPath Parser context
7342
 * @nargs:  the number of arguments
7343
 *
7344
 * Implement the local-name() XPath function
7345
 *    string local-name(node-set?)
7346
 * The local-name function returns a string containing the local part
7347
 * of the name of the node in the argument node-set that is first in
7348
 * document order. If the node-set is empty or the first node has no
7349
 * name, an empty string is returned. If the argument is omitted it
7350
 * defaults to the context node.
7351
 */
7352
void
7353
0
xmlXPathLocalNameFunction(xmlXPathParserContextPtr ctxt, int nargs) {
7354
0
    xmlXPathObjectPtr cur;
7355
7356
0
    if (ctxt == NULL) return;
7357
7358
0
    if (nargs == 0) {
7359
0
  xmlXPathValuePush(ctxt, xmlXPathCacheNewNodeSet(ctxt, ctxt->context->node));
7360
0
  nargs = 1;
7361
0
    }
7362
7363
0
    CHECK_ARITY(1);
7364
0
    if ((ctxt->value == NULL) ||
7365
0
  ((ctxt->value->type != XPATH_NODESET) &&
7366
0
   (ctxt->value->type != XPATH_XSLT_TREE)))
7367
0
  XP_ERROR(XPATH_INVALID_TYPE);
7368
0
    cur = xmlXPathValuePop(ctxt);
7369
7370
0
    if ((cur->nodesetval == NULL) || (cur->nodesetval->nodeNr == 0)) {
7371
0
  xmlXPathValuePush(ctxt, xmlXPathCacheNewCString(ctxt, ""));
7372
0
    } else {
7373
0
  int i = 0; /* Should be first in document order !!!!! */
7374
0
  switch (cur->nodesetval->nodeTab[i]->type) {
7375
0
  case XML_ELEMENT_NODE:
7376
0
  case XML_ATTRIBUTE_NODE:
7377
0
  case XML_PI_NODE:
7378
0
      if (cur->nodesetval->nodeTab[i]->name[0] == ' ')
7379
0
    xmlXPathValuePush(ctxt, xmlXPathCacheNewCString(ctxt, ""));
7380
0
      else
7381
0
    xmlXPathValuePush(ctxt, xmlXPathCacheNewString(ctxt,
7382
0
      cur->nodesetval->nodeTab[i]->name));
7383
0
      break;
7384
0
  case XML_NAMESPACE_DECL:
7385
0
      xmlXPathValuePush(ctxt, xmlXPathCacheNewString(ctxt,
7386
0
      ((xmlNsPtr)cur->nodesetval->nodeTab[i])->prefix));
7387
0
      break;
7388
0
  default:
7389
0
      xmlXPathValuePush(ctxt, xmlXPathCacheNewCString(ctxt, ""));
7390
0
  }
7391
0
    }
7392
0
    xmlXPathReleaseObject(ctxt->context, cur);
7393
0
}
7394
7395
/**
7396
 * xmlXPathNamespaceURIFunction:
7397
 * @ctxt:  the XPath Parser context
7398
 * @nargs:  the number of arguments
7399
 *
7400
 * Implement the namespace-uri() XPath function
7401
 *    string namespace-uri(node-set?)
7402
 * The namespace-uri function returns a string containing the
7403
 * namespace URI of the expanded name of the node in the argument
7404
 * node-set that is first in document order. If the node-set is empty,
7405
 * the first node has no name, or the expanded name has no namespace
7406
 * URI, an empty string is returned. If the argument is omitted it
7407
 * defaults to the context node.
7408
 */
7409
void
7410
0
xmlXPathNamespaceURIFunction(xmlXPathParserContextPtr ctxt, int nargs) {
7411
0
    xmlXPathObjectPtr cur;
7412
7413
0
    if (ctxt == NULL) return;
7414
7415
0
    if (nargs == 0) {
7416
0
  xmlXPathValuePush(ctxt, xmlXPathCacheNewNodeSet(ctxt, ctxt->context->node));
7417
0
  nargs = 1;
7418
0
    }
7419
0
    CHECK_ARITY(1);
7420
0
    if ((ctxt->value == NULL) ||
7421
0
  ((ctxt->value->type != XPATH_NODESET) &&
7422
0
   (ctxt->value->type != XPATH_XSLT_TREE)))
7423
0
  XP_ERROR(XPATH_INVALID_TYPE);
7424
0
    cur = xmlXPathValuePop(ctxt);
7425
7426
0
    if ((cur->nodesetval == NULL) || (cur->nodesetval->nodeNr == 0)) {
7427
0
  xmlXPathValuePush(ctxt, xmlXPathCacheNewCString(ctxt, ""));
7428
0
    } else {
7429
0
  int i = 0; /* Should be first in document order !!!!! */
7430
0
  switch (cur->nodesetval->nodeTab[i]->type) {
7431
0
  case XML_ELEMENT_NODE:
7432
0
  case XML_ATTRIBUTE_NODE:
7433
0
      if (cur->nodesetval->nodeTab[i]->ns == NULL)
7434
0
    xmlXPathValuePush(ctxt, xmlXPathCacheNewCString(ctxt, ""));
7435
0
      else
7436
0
    xmlXPathValuePush(ctxt, xmlXPathCacheNewString(ctxt,
7437
0
        cur->nodesetval->nodeTab[i]->ns->href));
7438
0
      break;
7439
0
  default:
7440
0
      xmlXPathValuePush(ctxt, xmlXPathCacheNewCString(ctxt, ""));
7441
0
  }
7442
0
    }
7443
0
    xmlXPathReleaseObject(ctxt->context, cur);
7444
0
}
7445
7446
/**
7447
 * xmlXPathNameFunction:
7448
 * @ctxt:  the XPath Parser context
7449
 * @nargs:  the number of arguments
7450
 *
7451
 * Implement the name() XPath function
7452
 *    string name(node-set?)
7453
 * The name function returns a string containing a QName representing
7454
 * the name of the node in the argument node-set that is first in document
7455
 * order. The QName must represent the name with respect to the namespace
7456
 * declarations in effect on the node whose name is being represented.
7457
 * Typically, this will be the form in which the name occurred in the XML
7458
 * source. This need not be the case if there are namespace declarations
7459
 * in effect on the node that associate multiple prefixes with the same
7460
 * namespace. However, an implementation may include information about
7461
 * the original prefix in its representation of nodes; in this case, an
7462
 * implementation can ensure that the returned string is always the same
7463
 * as the QName used in the XML source. If the argument it omitted it
7464
 * defaults to the context node.
7465
 * Libxml keep the original prefix so the "real qualified name" used is
7466
 * returned.
7467
 */
7468
static void
7469
xmlXPathNameFunction(xmlXPathParserContextPtr ctxt, int nargs)
7470
0
{
7471
0
    xmlXPathObjectPtr cur;
7472
7473
0
    if (nargs == 0) {
7474
0
  xmlXPathValuePush(ctxt, xmlXPathCacheNewNodeSet(ctxt, ctxt->context->node));
7475
0
        nargs = 1;
7476
0
    }
7477
7478
0
    CHECK_ARITY(1);
7479
0
    if ((ctxt->value == NULL) ||
7480
0
        ((ctxt->value->type != XPATH_NODESET) &&
7481
0
         (ctxt->value->type != XPATH_XSLT_TREE)))
7482
0
        XP_ERROR(XPATH_INVALID_TYPE);
7483
0
    cur = xmlXPathValuePop(ctxt);
7484
7485
0
    if ((cur->nodesetval == NULL) || (cur->nodesetval->nodeNr == 0)) {
7486
0
        xmlXPathValuePush(ctxt, xmlXPathCacheNewCString(ctxt, ""));
7487
0
    } else {
7488
0
        int i = 0;              /* Should be first in document order !!!!! */
7489
7490
0
        switch (cur->nodesetval->nodeTab[i]->type) {
7491
0
            case XML_ELEMENT_NODE:
7492
0
            case XML_ATTRIBUTE_NODE:
7493
0
    if (cur->nodesetval->nodeTab[i]->name[0] == ' ')
7494
0
        xmlXPathValuePush(ctxt,
7495
0
      xmlXPathCacheNewCString(ctxt, ""));
7496
0
    else if ((cur->nodesetval->nodeTab[i]->ns == NULL) ||
7497
0
                         (cur->nodesetval->nodeTab[i]->ns->prefix == NULL)) {
7498
0
        xmlXPathValuePush(ctxt, xmlXPathCacheNewString(ctxt,
7499
0
          cur->nodesetval->nodeTab[i]->name));
7500
0
    } else {
7501
0
        xmlChar *fullname;
7502
7503
0
        fullname = xmlBuildQName(cur->nodesetval->nodeTab[i]->name,
7504
0
             cur->nodesetval->nodeTab[i]->ns->prefix,
7505
0
             NULL, 0);
7506
0
        if (fullname == cur->nodesetval->nodeTab[i]->name)
7507
0
      fullname = xmlStrdup(cur->nodesetval->nodeTab[i]->name);
7508
0
        if (fullname == NULL)
7509
0
                        xmlXPathPErrMemory(ctxt);
7510
0
        xmlXPathValuePush(ctxt, xmlXPathCacheWrapString(ctxt, fullname));
7511
0
                }
7512
0
                break;
7513
0
            default:
7514
0
    xmlXPathValuePush(ctxt, xmlXPathCacheNewNodeSet(ctxt,
7515
0
        cur->nodesetval->nodeTab[i]));
7516
0
                xmlXPathLocalNameFunction(ctxt, 1);
7517
0
        }
7518
0
    }
7519
0
    xmlXPathReleaseObject(ctxt->context, cur);
7520
0
}
7521
7522
7523
/**
7524
 * xmlXPathStringFunction:
7525
 * @ctxt:  the XPath Parser context
7526
 * @nargs:  the number of arguments
7527
 *
7528
 * Implement the string() XPath function
7529
 *    string string(object?)
7530
 * The string function converts an object to a string as follows:
7531
 *    - A node-set is converted to a string by returning the value of
7532
 *      the node in the node-set that is first in document order.
7533
 *      If the node-set is empty, an empty string is returned.
7534
 *    - A number is converted to a string as follows
7535
 *      + NaN is converted to the string NaN
7536
 *      + positive zero is converted to the string 0
7537
 *      + negative zero is converted to the string 0
7538
 *      + positive infinity is converted to the string Infinity
7539
 *      + negative infinity is converted to the string -Infinity
7540
 *      + if the number is an integer, the number is represented in
7541
 *        decimal form as a Number with no decimal point and no leading
7542
 *        zeros, preceded by a minus sign (-) if the number is negative
7543
 *      + otherwise, the number is represented in decimal form as a
7544
 *        Number including a decimal point with at least one digit
7545
 *        before the decimal point and at least one digit after the
7546
 *        decimal point, preceded by a minus sign (-) if the number
7547
 *        is negative; there must be no leading zeros before the decimal
7548
 *        point apart possibly from the one required digit immediately
7549
 *        before the decimal point; beyond the one required digit
7550
 *        after the decimal point there must be as many, but only as
7551
 *        many, more digits as are needed to uniquely distinguish the
7552
 *        number from all other IEEE 754 numeric values.
7553
 *    - The boolean false value is converted to the string false.
7554
 *      The boolean true value is converted to the string true.
7555
 *
7556
 * If the argument is omitted, it defaults to a node-set with the
7557
 * context node as its only member.
7558
 */
7559
void
7560
93
xmlXPathStringFunction(xmlXPathParserContextPtr ctxt, int nargs) {
7561
93
    xmlXPathObjectPtr cur;
7562
93
    xmlChar *stringval;
7563
7564
93
    if (ctxt == NULL) return;
7565
93
    if (nargs == 0) {
7566
0
        stringval = xmlXPathCastNodeToString(ctxt->context->node);
7567
0
        if (stringval == NULL)
7568
0
            xmlXPathPErrMemory(ctxt);
7569
0
        xmlXPathValuePush(ctxt, xmlXPathCacheWrapString(ctxt, stringval));
7570
0
  return;
7571
0
    }
7572
7573
372
    CHECK_ARITY(1);
7574
372
    cur = xmlXPathValuePop(ctxt);
7575
372
    if (cur == NULL) XP_ERROR(XPATH_INVALID_OPERAND);
7576
93
    if (cur->type != XPATH_STRING) {
7577
93
        stringval = xmlXPathCastToString(cur);
7578
93
        if (stringval == NULL)
7579
0
            xmlXPathPErrMemory(ctxt);
7580
93
        xmlXPathReleaseObject(ctxt->context, cur);
7581
93
        cur = xmlXPathCacheWrapString(ctxt, stringval);
7582
93
    }
7583
93
    xmlXPathValuePush(ctxt, cur);
7584
93
}
7585
7586
/**
7587
 * xmlXPathStringLengthFunction:
7588
 * @ctxt:  the XPath Parser context
7589
 * @nargs:  the number of arguments
7590
 *
7591
 * Implement the string-length() XPath function
7592
 *    number string-length(string?)
7593
 * The string-length returns the number of characters in the string
7594
 * (see [3.6 Strings]). If the argument is omitted, it defaults to
7595
 * the context node converted to a string, in other words the value
7596
 * of the context node.
7597
 */
7598
void
7599
0
xmlXPathStringLengthFunction(xmlXPathParserContextPtr ctxt, int nargs) {
7600
0
    xmlXPathObjectPtr cur;
7601
7602
0
    if (nargs == 0) {
7603
0
        if ((ctxt == NULL) || (ctxt->context == NULL))
7604
0
      return;
7605
0
  if (ctxt->context->node == NULL) {
7606
0
      xmlXPathValuePush(ctxt, xmlXPathCacheNewFloat(ctxt, 0));
7607
0
  } else {
7608
0
      xmlChar *content;
7609
7610
0
      content = xmlXPathCastNodeToString(ctxt->context->node);
7611
0
            if (content == NULL)
7612
0
                xmlXPathPErrMemory(ctxt);
7613
0
      xmlXPathValuePush(ctxt, xmlXPathCacheNewFloat(ctxt,
7614
0
    xmlUTF8Strlen(content)));
7615
0
      xmlFree(content);
7616
0
  }
7617
0
  return;
7618
0
    }
7619
0
    CHECK_ARITY(1);
7620
0
    CAST_TO_STRING;
7621
0
    CHECK_TYPE(XPATH_STRING);
7622
0
    cur = xmlXPathValuePop(ctxt);
7623
0
    xmlXPathValuePush(ctxt, xmlXPathCacheNewFloat(ctxt,
7624
0
  xmlUTF8Strlen(cur->stringval)));
7625
0
    xmlXPathReleaseObject(ctxt->context, cur);
7626
0
}
7627
7628
/**
7629
 * xmlXPathConcatFunction:
7630
 * @ctxt:  the XPath Parser context
7631
 * @nargs:  the number of arguments
7632
 *
7633
 * Implement the concat() XPath function
7634
 *    string concat(string, string, string*)
7635
 * The concat function returns the concatenation of its arguments.
7636
 */
7637
void
7638
0
xmlXPathConcatFunction(xmlXPathParserContextPtr ctxt, int nargs) {
7639
0
    xmlXPathObjectPtr cur, newobj;
7640
0
    xmlChar *tmp;
7641
7642
0
    if (ctxt == NULL) return;
7643
0
    if (nargs < 2) {
7644
0
  CHECK_ARITY(2);
7645
0
    }
7646
7647
0
    CAST_TO_STRING;
7648
0
    cur = xmlXPathValuePop(ctxt);
7649
0
    if ((cur == NULL) || (cur->type != XPATH_STRING)) {
7650
0
  xmlXPathReleaseObject(ctxt->context, cur);
7651
0
  return;
7652
0
    }
7653
0
    nargs--;
7654
7655
0
    while (nargs > 0) {
7656
0
  CAST_TO_STRING;
7657
0
  newobj = xmlXPathValuePop(ctxt);
7658
0
  if ((newobj == NULL) || (newobj->type != XPATH_STRING)) {
7659
0
      xmlXPathReleaseObject(ctxt->context, newobj);
7660
0
      xmlXPathReleaseObject(ctxt->context, cur);
7661
0
      XP_ERROR(XPATH_INVALID_TYPE);
7662
0
  }
7663
0
  tmp = xmlStrcat(newobj->stringval, cur->stringval);
7664
0
        if (tmp == NULL)
7665
0
            xmlXPathPErrMemory(ctxt);
7666
0
  newobj->stringval = cur->stringval;
7667
0
  cur->stringval = tmp;
7668
0
  xmlXPathReleaseObject(ctxt->context, newobj);
7669
0
  nargs--;
7670
0
    }
7671
0
    xmlXPathValuePush(ctxt, cur);
7672
0
}
7673
7674
/**
7675
 * xmlXPathContainsFunction:
7676
 * @ctxt:  the XPath Parser context
7677
 * @nargs:  the number of arguments
7678
 *
7679
 * Implement the contains() XPath function
7680
 *    boolean contains(string, string)
7681
 * The contains function returns true if the first argument string
7682
 * contains the second argument string, and otherwise returns false.
7683
 */
7684
void
7685
0
xmlXPathContainsFunction(xmlXPathParserContextPtr ctxt, int nargs) {
7686
0
    xmlXPathObjectPtr hay, needle;
7687
7688
0
    CHECK_ARITY(2);
7689
0
    CAST_TO_STRING;
7690
0
    CHECK_TYPE(XPATH_STRING);
7691
0
    needle = xmlXPathValuePop(ctxt);
7692
0
    CAST_TO_STRING;
7693
0
    hay = xmlXPathValuePop(ctxt);
7694
7695
0
    if ((hay == NULL) || (hay->type != XPATH_STRING)) {
7696
0
  xmlXPathReleaseObject(ctxt->context, hay);
7697
0
  xmlXPathReleaseObject(ctxt->context, needle);
7698
0
  XP_ERROR(XPATH_INVALID_TYPE);
7699
0
    }
7700
0
    if (xmlStrstr(hay->stringval, needle->stringval))
7701
0
  xmlXPathValuePush(ctxt, xmlXPathCacheNewBoolean(ctxt, 1));
7702
0
    else
7703
0
  xmlXPathValuePush(ctxt, xmlXPathCacheNewBoolean(ctxt, 0));
7704
0
    xmlXPathReleaseObject(ctxt->context, hay);
7705
0
    xmlXPathReleaseObject(ctxt->context, needle);
7706
0
}
7707
7708
/**
7709
 * xmlXPathStartsWithFunction:
7710
 * @ctxt:  the XPath Parser context
7711
 * @nargs:  the number of arguments
7712
 *
7713
 * Implement the starts-with() XPath function
7714
 *    boolean starts-with(string, string)
7715
 * The starts-with function returns true if the first argument string
7716
 * starts with the second argument string, and otherwise returns false.
7717
 */
7718
void
7719
0
xmlXPathStartsWithFunction(xmlXPathParserContextPtr ctxt, int nargs) {
7720
0
    xmlXPathObjectPtr hay, needle;
7721
0
    int n;
7722
7723
0
    CHECK_ARITY(2);
7724
0
    CAST_TO_STRING;
7725
0
    CHECK_TYPE(XPATH_STRING);
7726
0
    needle = xmlXPathValuePop(ctxt);
7727
0
    CAST_TO_STRING;
7728
0
    hay = xmlXPathValuePop(ctxt);
7729
7730
0
    if ((hay == NULL) || (hay->type != XPATH_STRING)) {
7731
0
  xmlXPathReleaseObject(ctxt->context, hay);
7732
0
  xmlXPathReleaseObject(ctxt->context, needle);
7733
0
  XP_ERROR(XPATH_INVALID_TYPE);
7734
0
    }
7735
0
    n = xmlStrlen(needle->stringval);
7736
0
    if (xmlStrncmp(hay->stringval, needle->stringval, n))
7737
0
        xmlXPathValuePush(ctxt, xmlXPathCacheNewBoolean(ctxt, 0));
7738
0
    else
7739
0
        xmlXPathValuePush(ctxt, xmlXPathCacheNewBoolean(ctxt, 1));
7740
0
    xmlXPathReleaseObject(ctxt->context, hay);
7741
0
    xmlXPathReleaseObject(ctxt->context, needle);
7742
0
}
7743
7744
/**
7745
 * xmlXPathSubstringFunction:
7746
 * @ctxt:  the XPath Parser context
7747
 * @nargs:  the number of arguments
7748
 *
7749
 * Implement the substring() XPath function
7750
 *    string substring(string, number, number?)
7751
 * The substring function returns the substring of the first argument
7752
 * starting at the position specified in the second argument with
7753
 * length specified in the third argument. For example,
7754
 * substring("12345",2,3) returns "234". If the third argument is not
7755
 * specified, it returns the substring starting at the position specified
7756
 * in the second argument and continuing to the end of the string. For
7757
 * example, substring("12345",2) returns "2345".  More precisely, each
7758
 * character in the string (see [3.6 Strings]) is considered to have a
7759
 * numeric position: the position of the first character is 1, the position
7760
 * of the second character is 2 and so on. The returned substring contains
7761
 * those characters for which the position of the character is greater than
7762
 * or equal to the second argument and, if the third argument is specified,
7763
 * less than the sum of the second and third arguments; the comparisons
7764
 * and addition used for the above follow the standard IEEE 754 rules. Thus:
7765
 *  - substring("12345", 1.5, 2.6) returns "234"
7766
 *  - substring("12345", 0, 3) returns "12"
7767
 *  - substring("12345", 0 div 0, 3) returns ""
7768
 *  - substring("12345", 1, 0 div 0) returns ""
7769
 *  - substring("12345", -42, 1 div 0) returns "12345"
7770
 *  - substring("12345", -1 div 0, 1 div 0) returns ""
7771
 */
7772
void
7773
0
xmlXPathSubstringFunction(xmlXPathParserContextPtr ctxt, int nargs) {
7774
0
    xmlXPathObjectPtr str, start, len;
7775
0
    double le=0, in;
7776
0
    int i = 1, j = INT_MAX;
7777
7778
0
    if (nargs < 2) {
7779
0
  CHECK_ARITY(2);
7780
0
    }
7781
0
    if (nargs > 3) {
7782
0
  CHECK_ARITY(3);
7783
0
    }
7784
    /*
7785
     * take care of possible last (position) argument
7786
    */
7787
0
    if (nargs == 3) {
7788
0
  CAST_TO_NUMBER;
7789
0
  CHECK_TYPE(XPATH_NUMBER);
7790
0
  len = xmlXPathValuePop(ctxt);
7791
0
  le = len->floatval;
7792
0
  xmlXPathReleaseObject(ctxt->context, len);
7793
0
    }
7794
7795
0
    CAST_TO_NUMBER;
7796
0
    CHECK_TYPE(XPATH_NUMBER);
7797
0
    start = xmlXPathValuePop(ctxt);
7798
0
    in = start->floatval;
7799
0
    xmlXPathReleaseObject(ctxt->context, start);
7800
0
    CAST_TO_STRING;
7801
0
    CHECK_TYPE(XPATH_STRING);
7802
0
    str = xmlXPathValuePop(ctxt);
7803
7804
0
    if (!(in < INT_MAX)) { /* Logical NOT to handle NaNs */
7805
0
        i = INT_MAX;
7806
0
    } else if (in >= 1.0) {
7807
0
        i = (int)in;
7808
0
        if (in - floor(in) >= 0.5)
7809
0
            i += 1;
7810
0
    }
7811
7812
0
    if (nargs == 3) {
7813
0
        double rin, rle, end;
7814
7815
0
        rin = floor(in);
7816
0
        if (in - rin >= 0.5)
7817
0
            rin += 1.0;
7818
7819
0
        rle = floor(le);
7820
0
        if (le - rle >= 0.5)
7821
0
            rle += 1.0;
7822
7823
0
        end = rin + rle;
7824
0
        if (!(end >= 1.0)) { /* Logical NOT to handle NaNs */
7825
0
            j = 1;
7826
0
        } else if (end < INT_MAX) {
7827
0
            j = (int)end;
7828
0
        }
7829
0
    }
7830
7831
0
    i -= 1;
7832
0
    j -= 1;
7833
7834
0
    if ((i < j) && (i < xmlUTF8Strlen(str->stringval))) {
7835
0
        xmlChar *ret = xmlUTF8Strsub(str->stringval, i, j - i);
7836
0
        if (ret == NULL)
7837
0
            xmlXPathPErrMemory(ctxt);
7838
0
  xmlXPathValuePush(ctxt, xmlXPathCacheNewString(ctxt, ret));
7839
0
  xmlFree(ret);
7840
0
    } else {
7841
0
  xmlXPathValuePush(ctxt, xmlXPathCacheNewCString(ctxt, ""));
7842
0
    }
7843
7844
0
    xmlXPathReleaseObject(ctxt->context, str);
7845
0
}
7846
7847
/**
7848
 * xmlXPathSubstringBeforeFunction:
7849
 * @ctxt:  the XPath Parser context
7850
 * @nargs:  the number of arguments
7851
 *
7852
 * Implement the substring-before() XPath function
7853
 *    string substring-before(string, string)
7854
 * The substring-before function returns the substring of the first
7855
 * argument string that precedes the first occurrence of the second
7856
 * argument string in the first argument string, or the empty string
7857
 * if the first argument string does not contain the second argument
7858
 * string. For example, substring-before("1999/04/01","/") returns 1999.
7859
 */
7860
void
7861
0
xmlXPathSubstringBeforeFunction(xmlXPathParserContextPtr ctxt, int nargs) {
7862
0
    xmlXPathObjectPtr str = NULL;
7863
0
    xmlXPathObjectPtr find = NULL;
7864
0
    const xmlChar *point;
7865
0
    xmlChar *result;
7866
7867
0
    CHECK_ARITY(2);
7868
0
    CAST_TO_STRING;
7869
0
    find = xmlXPathValuePop(ctxt);
7870
0
    CAST_TO_STRING;
7871
0
    str = xmlXPathValuePop(ctxt);
7872
0
    if (ctxt->error != 0)
7873
0
        goto error;
7874
7875
0
    point = xmlStrstr(str->stringval, find->stringval);
7876
0
    if (point == NULL) {
7877
0
        result = xmlStrdup(BAD_CAST "");
7878
0
    } else {
7879
0
        result = xmlStrndup(str->stringval, point - str->stringval);
7880
0
    }
7881
0
    if (result == NULL) {
7882
0
        xmlXPathPErrMemory(ctxt);
7883
0
        goto error;
7884
0
    }
7885
0
    xmlXPathValuePush(ctxt, xmlXPathCacheWrapString(ctxt, result));
7886
7887
0
error:
7888
0
    xmlXPathReleaseObject(ctxt->context, str);
7889
0
    xmlXPathReleaseObject(ctxt->context, find);
7890
0
}
7891
7892
/**
7893
 * xmlXPathSubstringAfterFunction:
7894
 * @ctxt:  the XPath Parser context
7895
 * @nargs:  the number of arguments
7896
 *
7897
 * Implement the substring-after() XPath function
7898
 *    string substring-after(string, string)
7899
 * The substring-after function returns the substring of the first
7900
 * argument string that follows the first occurrence of the second
7901
 * argument string in the first argument string, or the empty string
7902
 * if the first argument string does not contain the second argument
7903
 * string. For example, substring-after("1999/04/01","/") returns 04/01,
7904
 * and substring-after("1999/04/01","19") returns 99/04/01.
7905
 */
7906
void
7907
0
xmlXPathSubstringAfterFunction(xmlXPathParserContextPtr ctxt, int nargs) {
7908
0
    xmlXPathObjectPtr str = NULL;
7909
0
    xmlXPathObjectPtr find = NULL;
7910
0
    const xmlChar *point;
7911
0
    xmlChar *result;
7912
7913
0
    CHECK_ARITY(2);
7914
0
    CAST_TO_STRING;
7915
0
    find = xmlXPathValuePop(ctxt);
7916
0
    CAST_TO_STRING;
7917
0
    str = xmlXPathValuePop(ctxt);
7918
0
    if (ctxt->error != 0)
7919
0
        goto error;
7920
7921
0
    point = xmlStrstr(str->stringval, find->stringval);
7922
0
    if (point == NULL) {
7923
0
        result = xmlStrdup(BAD_CAST "");
7924
0
    } else {
7925
0
        result = xmlStrdup(point + xmlStrlen(find->stringval));
7926
0
    }
7927
0
    if (result == NULL) {
7928
0
        xmlXPathPErrMemory(ctxt);
7929
0
        goto error;
7930
0
    }
7931
0
    xmlXPathValuePush(ctxt, xmlXPathCacheWrapString(ctxt, result));
7932
7933
0
error:
7934
0
    xmlXPathReleaseObject(ctxt->context, str);
7935
0
    xmlXPathReleaseObject(ctxt->context, find);
7936
0
}
7937
7938
/**
7939
 * xmlXPathNormalizeFunction:
7940
 * @ctxt:  the XPath Parser context
7941
 * @nargs:  the number of arguments
7942
 *
7943
 * Implement the normalize-space() XPath function
7944
 *    string normalize-space(string?)
7945
 * The normalize-space function returns the argument string with white
7946
 * space normalized by stripping leading and trailing whitespace
7947
 * and replacing sequences of whitespace characters by a single
7948
 * space. Whitespace characters are the same allowed by the S production
7949
 * in XML. If the argument is omitted, it defaults to the context
7950
 * node converted to a string, in other words the value of the context node.
7951
 */
7952
void
7953
0
xmlXPathNormalizeFunction(xmlXPathParserContextPtr ctxt, int nargs) {
7954
0
    xmlChar *source, *target;
7955
0
    int blank;
7956
7957
0
    if (ctxt == NULL) return;
7958
0
    if (nargs == 0) {
7959
        /* Use current context node */
7960
0
        source = xmlXPathCastNodeToString(ctxt->context->node);
7961
0
        if (source == NULL)
7962
0
            xmlXPathPErrMemory(ctxt);
7963
0
        xmlXPathValuePush(ctxt, xmlXPathCacheWrapString(ctxt, source));
7964
0
        nargs = 1;
7965
0
    }
7966
7967
0
    CHECK_ARITY(1);
7968
0
    CAST_TO_STRING;
7969
0
    CHECK_TYPE(XPATH_STRING);
7970
0
    source = ctxt->value->stringval;
7971
0
    if (source == NULL)
7972
0
        return;
7973
0
    target = source;
7974
7975
    /* Skip leading whitespaces */
7976
0
    while (IS_BLANK_CH(*source))
7977
0
        source++;
7978
7979
    /* Collapse intermediate whitespaces, and skip trailing whitespaces */
7980
0
    blank = 0;
7981
0
    while (*source) {
7982
0
        if (IS_BLANK_CH(*source)) {
7983
0
      blank = 1;
7984
0
        } else {
7985
0
            if (blank) {
7986
0
                *target++ = 0x20;
7987
0
                blank = 0;
7988
0
            }
7989
0
            *target++ = *source;
7990
0
        }
7991
0
        source++;
7992
0
    }
7993
0
    *target = 0;
7994
0
}
7995
7996
/**
7997
 * xmlXPathTranslateFunction:
7998
 * @ctxt:  the XPath Parser context
7999
 * @nargs:  the number of arguments
8000
 *
8001
 * Implement the translate() XPath function
8002
 *    string translate(string, string, string)
8003
 * The translate function returns the first argument string with
8004
 * occurrences of characters in the second argument string replaced
8005
 * by the character at the corresponding position in the third argument
8006
 * string. For example, translate("bar","abc","ABC") returns the string
8007
 * BAr. If there is a character in the second argument string with no
8008
 * character at a corresponding position in the third argument string
8009
 * (because the second argument string is longer than the third argument
8010
 * string), then occurrences of that character in the first argument
8011
 * string are removed. For example, translate("--aaa--","abc-","ABC")
8012
 * returns "AAA". If a character occurs more than once in second
8013
 * argument string, then the first occurrence determines the replacement
8014
 * character. If the third argument string is longer than the second
8015
 * argument string, then excess characters are ignored.
8016
 */
8017
void
8018
0
xmlXPathTranslateFunction(xmlXPathParserContextPtr ctxt, int nargs) {
8019
0
    xmlXPathObjectPtr str = NULL;
8020
0
    xmlXPathObjectPtr from = NULL;
8021
0
    xmlXPathObjectPtr to = NULL;
8022
0
    xmlBufPtr target;
8023
0
    int offset, max;
8024
0
    int ch;
8025
0
    const xmlChar *point;
8026
0
    xmlChar *cptr, *content;
8027
8028
0
    CHECK_ARITY(3);
8029
8030
0
    CAST_TO_STRING;
8031
0
    to = xmlXPathValuePop(ctxt);
8032
0
    CAST_TO_STRING;
8033
0
    from = xmlXPathValuePop(ctxt);
8034
0
    CAST_TO_STRING;
8035
0
    str = xmlXPathValuePop(ctxt);
8036
0
    if (ctxt->error != 0)
8037
0
        goto error;
8038
8039
    /*
8040
     * Account for quadratic runtime
8041
     */
8042
0
    if (ctxt->context->opLimit != 0) {
8043
0
        unsigned long f1 = xmlStrlen(from->stringval);
8044
0
        unsigned long f2 = xmlStrlen(str->stringval);
8045
8046
0
        if ((f1 > 0) && (f2 > 0)) {
8047
0
            unsigned long p;
8048
8049
0
            f1 = f1 / 10 + 1;
8050
0
            f2 = f2 / 10 + 1;
8051
0
            p = f1 > ULONG_MAX / f2 ? ULONG_MAX : f1 * f2;
8052
0
            if (xmlXPathCheckOpLimit(ctxt, p) < 0)
8053
0
                goto error;
8054
0
        }
8055
0
    }
8056
8057
0
    target = xmlBufCreate(50);
8058
0
    if (target == NULL) {
8059
0
        xmlXPathPErrMemory(ctxt);
8060
0
        goto error;
8061
0
    }
8062
8063
0
    max = xmlUTF8Strlen(to->stringval);
8064
0
    for (cptr = str->stringval; (ch=*cptr); ) {
8065
0
        offset = xmlUTF8Strloc(from->stringval, cptr);
8066
0
        if (offset >= 0) {
8067
0
            if (offset < max) {
8068
0
                point = xmlUTF8Strpos(to->stringval, offset);
8069
0
                if (point)
8070
0
                    xmlBufAdd(target, point, xmlUTF8Strsize(point, 1));
8071
0
            }
8072
0
        } else
8073
0
            xmlBufAdd(target, cptr, xmlUTF8Strsize(cptr, 1));
8074
8075
        /* Step to next character in input */
8076
0
        cptr++;
8077
0
        if ( ch & 0x80 ) {
8078
            /* if not simple ascii, verify proper format */
8079
0
            if ( (ch & 0xc0) != 0xc0 ) {
8080
0
                xmlXPathErr(ctxt, XPATH_INVALID_CHAR_ERROR);
8081
0
                break;
8082
0
            }
8083
            /* then skip over remaining bytes for this char */
8084
0
            while ( (ch <<= 1) & 0x80 )
8085
0
                if ( (*cptr++ & 0xc0) != 0x80 ) {
8086
0
                    xmlXPathErr(ctxt, XPATH_INVALID_CHAR_ERROR);
8087
0
                    break;
8088
0
                }
8089
0
            if (ch & 0x80) /* must have had error encountered */
8090
0
                break;
8091
0
        }
8092
0
    }
8093
8094
0
    content = xmlBufDetach(target);
8095
0
    if (content == NULL)
8096
0
        xmlXPathPErrMemory(ctxt);
8097
0
    else
8098
0
        xmlXPathValuePush(ctxt, xmlXPathCacheWrapString(ctxt, content));
8099
0
    xmlBufFree(target);
8100
0
error:
8101
0
    xmlXPathReleaseObject(ctxt->context, str);
8102
0
    xmlXPathReleaseObject(ctxt->context, from);
8103
0
    xmlXPathReleaseObject(ctxt->context, to);
8104
0
}
8105
8106
/**
8107
 * xmlXPathBooleanFunction:
8108
 * @ctxt:  the XPath Parser context
8109
 * @nargs:  the number of arguments
8110
 *
8111
 * Implement the boolean() XPath function
8112
 *    boolean boolean(object)
8113
 * The boolean function converts its argument to a boolean as follows:
8114
 *    - a number is true if and only if it is neither positive or
8115
 *      negative zero nor NaN
8116
 *    - a node-set is true if and only if it is non-empty
8117
 *    - a string is true if and only if its length is non-zero
8118
 */
8119
void
8120
0
xmlXPathBooleanFunction(xmlXPathParserContextPtr ctxt, int nargs) {
8121
0
    xmlXPathObjectPtr cur;
8122
8123
0
    CHECK_ARITY(1);
8124
0
    cur = xmlXPathValuePop(ctxt);
8125
0
    if (cur == NULL) XP_ERROR(XPATH_INVALID_OPERAND);
8126
0
    if (cur->type != XPATH_BOOLEAN) {
8127
0
        int boolval = xmlXPathCastToBoolean(cur);
8128
8129
0
        xmlXPathReleaseObject(ctxt->context, cur);
8130
0
        cur = xmlXPathCacheNewBoolean(ctxt, boolval);
8131
0
    }
8132
0
    xmlXPathValuePush(ctxt, cur);
8133
0
}
8134
8135
/**
8136
 * xmlXPathNotFunction:
8137
 * @ctxt:  the XPath Parser context
8138
 * @nargs:  the number of arguments
8139
 *
8140
 * Implement the not() XPath function
8141
 *    boolean not(boolean)
8142
 * The not function returns true if its argument is false,
8143
 * and false otherwise.
8144
 */
8145
void
8146
0
xmlXPathNotFunction(xmlXPathParserContextPtr ctxt, int nargs) {
8147
0
    CHECK_ARITY(1);
8148
0
    CAST_TO_BOOLEAN;
8149
0
    CHECK_TYPE(XPATH_BOOLEAN);
8150
0
    ctxt->value->boolval = ! ctxt->value->boolval;
8151
0
}
8152
8153
/**
8154
 * xmlXPathTrueFunction:
8155
 * @ctxt:  the XPath Parser context
8156
 * @nargs:  the number of arguments
8157
 *
8158
 * Implement the true() XPath function
8159
 *    boolean true()
8160
 */
8161
void
8162
0
xmlXPathTrueFunction(xmlXPathParserContextPtr ctxt, int nargs) {
8163
0
    CHECK_ARITY(0);
8164
0
    xmlXPathValuePush(ctxt, xmlXPathCacheNewBoolean(ctxt, 1));
8165
0
}
8166
8167
/**
8168
 * xmlXPathFalseFunction:
8169
 * @ctxt:  the XPath Parser context
8170
 * @nargs:  the number of arguments
8171
 *
8172
 * Implement the false() XPath function
8173
 *    boolean false()
8174
 */
8175
void
8176
0
xmlXPathFalseFunction(xmlXPathParserContextPtr ctxt, int nargs) {
8177
0
    CHECK_ARITY(0);
8178
0
    xmlXPathValuePush(ctxt, xmlXPathCacheNewBoolean(ctxt, 0));
8179
0
}
8180
8181
/**
8182
 * xmlXPathLangFunction:
8183
 * @ctxt:  the XPath Parser context
8184
 * @nargs:  the number of arguments
8185
 *
8186
 * Implement the lang() XPath function
8187
 *    boolean lang(string)
8188
 * The lang function returns true or false depending on whether the
8189
 * language of the context node as specified by xml:lang attributes
8190
 * is the same as or is a sublanguage of the language specified by
8191
 * the argument string. The language of the context node is determined
8192
 * by the value of the xml:lang attribute on the context node, or, if
8193
 * the context node has no xml:lang attribute, by the value of the
8194
 * xml:lang attribute on the nearest ancestor of the context node that
8195
 * has an xml:lang attribute. If there is no such attribute, then lang
8196
 * returns false. If there is such an attribute, then lang returns
8197
 * true if the attribute value is equal to the argument ignoring case,
8198
 * or if there is some suffix starting with - such that the attribute
8199
 * value is equal to the argument ignoring that suffix of the attribute
8200
 * value and ignoring case.
8201
 */
8202
void
8203
0
xmlXPathLangFunction(xmlXPathParserContextPtr ctxt, int nargs) {
8204
0
    xmlXPathObjectPtr val;
8205
0
    xmlNodePtr cur;
8206
0
    xmlChar *theLang;
8207
0
    const xmlChar *lang;
8208
0
    int ret = 0;
8209
0
    int i;
8210
8211
0
    CHECK_ARITY(1);
8212
0
    CAST_TO_STRING;
8213
0
    CHECK_TYPE(XPATH_STRING);
8214
0
    val = xmlXPathValuePop(ctxt);
8215
0
    lang = val->stringval;
8216
0
    cur = ctxt->context->node;
8217
0
    while (cur != NULL) {
8218
0
        if (xmlNodeGetAttrValue(cur, BAD_CAST "lang", XML_XML_NAMESPACE,
8219
0
                                &theLang) < 0)
8220
0
            xmlXPathPErrMemory(ctxt);
8221
0
        if (theLang != NULL)
8222
0
            break;
8223
0
        cur = cur->parent;
8224
0
    }
8225
0
    if ((theLang != NULL) && (lang != NULL)) {
8226
0
        for (i = 0;lang[i] != 0;i++)
8227
0
            if (toupper(lang[i]) != toupper(theLang[i]))
8228
0
                goto not_equal;
8229
0
        if ((theLang[i] == 0) || (theLang[i] == '-'))
8230
0
            ret = 1;
8231
0
    }
8232
0
not_equal:
8233
0
    if (theLang != NULL)
8234
0
  xmlFree((void *)theLang);
8235
8236
0
    xmlXPathReleaseObject(ctxt->context, val);
8237
0
    xmlXPathValuePush(ctxt, xmlXPathCacheNewBoolean(ctxt, ret));
8238
0
}
8239
8240
/**
8241
 * xmlXPathNumberFunction:
8242
 * @ctxt:  the XPath Parser context
8243
 * @nargs:  the number of arguments
8244
 *
8245
 * Implement the number() XPath function
8246
 *    number number(object?)
8247
 */
8248
void
8249
0
xmlXPathNumberFunction(xmlXPathParserContextPtr ctxt, int nargs) {
8250
0
    xmlXPathObjectPtr cur;
8251
0
    double res;
8252
8253
0
    if (ctxt == NULL) return;
8254
0
    if (nargs == 0) {
8255
0
  if (ctxt->context->node == NULL) {
8256
0
      xmlXPathValuePush(ctxt, xmlXPathCacheNewFloat(ctxt, 0.0));
8257
0
  } else {
8258
0
      xmlChar* content = xmlNodeGetContent(ctxt->context->node);
8259
0
            if (content == NULL)
8260
0
                xmlXPathPErrMemory(ctxt);
8261
8262
0
      res = xmlXPathStringEvalNumber(content);
8263
0
      xmlXPathValuePush(ctxt, xmlXPathCacheNewFloat(ctxt, res));
8264
0
      xmlFree(content);
8265
0
  }
8266
0
  return;
8267
0
    }
8268
8269
0
    CHECK_ARITY(1);
8270
0
    cur = xmlXPathValuePop(ctxt);
8271
0
    if (cur->type != XPATH_NUMBER) {
8272
0
        double floatval;
8273
8274
0
        floatval = xmlXPathCastToNumberInternal(ctxt, cur);
8275
0
        xmlXPathReleaseObject(ctxt->context, cur);
8276
0
        cur = xmlXPathCacheNewFloat(ctxt, floatval);
8277
0
    }
8278
0
    xmlXPathValuePush(ctxt, cur);
8279
0
}
8280
8281
/**
8282
 * xmlXPathSumFunction:
8283
 * @ctxt:  the XPath Parser context
8284
 * @nargs:  the number of arguments
8285
 *
8286
 * Implement the sum() XPath function
8287
 *    number sum(node-set)
8288
 * The sum function returns the sum of the values of the nodes in
8289
 * the argument node-set.
8290
 */
8291
void
8292
0
xmlXPathSumFunction(xmlXPathParserContextPtr ctxt, int nargs) {
8293
0
    xmlXPathObjectPtr cur;
8294
0
    int i;
8295
0
    double res = 0.0;
8296
8297
0
    CHECK_ARITY(1);
8298
0
    if ((ctxt->value == NULL) ||
8299
0
  ((ctxt->value->type != XPATH_NODESET) &&
8300
0
   (ctxt->value->type != XPATH_XSLT_TREE)))
8301
0
  XP_ERROR(XPATH_INVALID_TYPE);
8302
0
    cur = xmlXPathValuePop(ctxt);
8303
8304
0
    if ((cur->nodesetval != NULL) && (cur->nodesetval->nodeNr != 0)) {
8305
0
  for (i = 0; i < cur->nodesetval->nodeNr; i++) {
8306
0
      res += xmlXPathNodeToNumberInternal(ctxt,
8307
0
                                                cur->nodesetval->nodeTab[i]);
8308
0
  }
8309
0
    }
8310
0
    xmlXPathValuePush(ctxt, xmlXPathCacheNewFloat(ctxt, res));
8311
0
    xmlXPathReleaseObject(ctxt->context, cur);
8312
0
}
8313
8314
/**
8315
 * xmlXPathFloorFunction:
8316
 * @ctxt:  the XPath Parser context
8317
 * @nargs:  the number of arguments
8318
 *
8319
 * Implement the floor() XPath function
8320
 *    number floor(number)
8321
 * The floor function returns the largest (closest to positive infinity)
8322
 * number that is not greater than the argument and that is an integer.
8323
 */
8324
void
8325
0
xmlXPathFloorFunction(xmlXPathParserContextPtr ctxt, int nargs) {
8326
0
    CHECK_ARITY(1);
8327
0
    CAST_TO_NUMBER;
8328
0
    CHECK_TYPE(XPATH_NUMBER);
8329
8330
0
    ctxt->value->floatval = floor(ctxt->value->floatval);
8331
0
}
8332
8333
/**
8334
 * xmlXPathCeilingFunction:
8335
 * @ctxt:  the XPath Parser context
8336
 * @nargs:  the number of arguments
8337
 *
8338
 * Implement the ceiling() XPath function
8339
 *    number ceiling(number)
8340
 * The ceiling function returns the smallest (closest to negative infinity)
8341
 * number that is not less than the argument and that is an integer.
8342
 */
8343
void
8344
0
xmlXPathCeilingFunction(xmlXPathParserContextPtr ctxt, int nargs) {
8345
0
    CHECK_ARITY(1);
8346
0
    CAST_TO_NUMBER;
8347
0
    CHECK_TYPE(XPATH_NUMBER);
8348
8349
#ifdef _AIX
8350
    /* Work around buggy ceil() function on AIX */
8351
    ctxt->value->floatval = copysign(ceil(ctxt->value->floatval), ctxt->value->floatval);
8352
#else
8353
0
    ctxt->value->floatval = ceil(ctxt->value->floatval);
8354
0
#endif
8355
0
}
8356
8357
/**
8358
 * xmlXPathRoundFunction:
8359
 * @ctxt:  the XPath Parser context
8360
 * @nargs:  the number of arguments
8361
 *
8362
 * Implement the round() XPath function
8363
 *    number round(number)
8364
 * The round function returns the number that is closest to the
8365
 * argument and that is an integer. If there are two such numbers,
8366
 * then the one that is closest to positive infinity is returned.
8367
 */
8368
void
8369
0
xmlXPathRoundFunction(xmlXPathParserContextPtr ctxt, int nargs) {
8370
0
    double f;
8371
8372
0
    CHECK_ARITY(1);
8373
0
    CAST_TO_NUMBER;
8374
0
    CHECK_TYPE(XPATH_NUMBER);
8375
8376
0
    f = ctxt->value->floatval;
8377
8378
0
    if ((f >= -0.5) && (f < 0.5)) {
8379
        /* Handles negative zero. */
8380
0
        ctxt->value->floatval *= 0.0;
8381
0
    }
8382
0
    else {
8383
0
        double rounded = floor(f);
8384
0
        if (f - rounded >= 0.5)
8385
0
            rounded += 1.0;
8386
0
        ctxt->value->floatval = rounded;
8387
0
    }
8388
0
}
8389
8390
/************************************************************************
8391
 *                  *
8392
 *      The Parser          *
8393
 *                  *
8394
 ************************************************************************/
8395
8396
/*
8397
 * a few forward declarations since we use a recursive call based
8398
 * implementation.
8399
 */
8400
static void xmlXPathCompileExpr(xmlXPathParserContextPtr ctxt, int sort);
8401
static void xmlXPathCompPredicate(xmlXPathParserContextPtr ctxt, int filter);
8402
static void xmlXPathCompLocationPath(xmlXPathParserContextPtr ctxt);
8403
static void xmlXPathCompRelativeLocationPath(xmlXPathParserContextPtr ctxt);
8404
static xmlChar * xmlXPathParseNameComplex(xmlXPathParserContextPtr ctxt,
8405
                                    int qualified);
8406
8407
/**
8408
 * xmlXPathCurrentChar:
8409
 * @ctxt:  the XPath parser context
8410
 * @cur:  pointer to the beginning of the char
8411
 * @len:  pointer to the length of the char read
8412
 *
8413
 * The current char value, if using UTF-8 this may actually span multiple
8414
 * bytes in the input buffer.
8415
 *
8416
 * Returns the current char value and its length
8417
 */
8418
8419
static int
8420
2.04k
xmlXPathCurrentChar(xmlXPathParserContextPtr ctxt, int *len) {
8421
2.04k
    unsigned char c;
8422
2.04k
    unsigned int val;
8423
2.04k
    const xmlChar *cur;
8424
8425
2.04k
    if (ctxt == NULL)
8426
0
  return(0);
8427
2.04k
    cur = ctxt->cur;
8428
8429
    /*
8430
     * We are supposed to handle UTF8, check it's valid
8431
     * From rfc2044: encoding of the Unicode values on UTF-8:
8432
     *
8433
     * UCS-4 range (hex.)           UTF-8 octet sequence (binary)
8434
     * 0000 0000-0000 007F   0xxxxxxx
8435
     * 0000 0080-0000 07FF   110xxxxx 10xxxxxx
8436
     * 0000 0800-0000 FFFF   1110xxxx 10xxxxxx 10xxxxxx
8437
     *
8438
     * Check for the 0x110000 limit too
8439
     */
8440
2.04k
    c = *cur;
8441
2.04k
    if (c & 0x80) {
8442
0
  if ((cur[1] & 0xc0) != 0x80)
8443
0
      goto encoding_error;
8444
0
  if ((c & 0xe0) == 0xe0) {
8445
8446
0
      if ((cur[2] & 0xc0) != 0x80)
8447
0
    goto encoding_error;
8448
0
      if ((c & 0xf0) == 0xf0) {
8449
0
    if (((c & 0xf8) != 0xf0) ||
8450
0
        ((cur[3] & 0xc0) != 0x80))
8451
0
        goto encoding_error;
8452
    /* 4-byte code */
8453
0
    *len = 4;
8454
0
    val = (cur[0] & 0x7) << 18;
8455
0
    val |= (cur[1] & 0x3f) << 12;
8456
0
    val |= (cur[2] & 0x3f) << 6;
8457
0
    val |= cur[3] & 0x3f;
8458
0
      } else {
8459
        /* 3-byte code */
8460
0
    *len = 3;
8461
0
    val = (cur[0] & 0xf) << 12;
8462
0
    val |= (cur[1] & 0x3f) << 6;
8463
0
    val |= cur[2] & 0x3f;
8464
0
      }
8465
0
  } else {
8466
    /* 2-byte code */
8467
0
      *len = 2;
8468
0
      val = (cur[0] & 0x1f) << 6;
8469
0
      val |= cur[1] & 0x3f;
8470
0
  }
8471
0
  if (!IS_CHAR(val)) {
8472
0
      XP_ERROR0(XPATH_INVALID_CHAR_ERROR);
8473
0
  }
8474
0
  return(val);
8475
2.04k
    } else {
8476
  /* 1-byte code */
8477
2.04k
  *len = 1;
8478
2.04k
  return(*cur);
8479
2.04k
    }
8480
0
encoding_error:
8481
    /*
8482
     * If we detect an UTF8 error that probably means that the
8483
     * input encoding didn't get properly advertised in the
8484
     * declaration header. Report the error and switch the encoding
8485
     * to ISO-Latin-1 (if you don't like this policy, just declare the
8486
     * encoding !)
8487
     */
8488
0
    *len = 0;
8489
0
    XP_ERROR0(XPATH_ENCODING_ERROR);
8490
0
}
8491
8492
/**
8493
 * xmlXPathParseNCName:
8494
 * @ctxt:  the XPath Parser context
8495
 *
8496
 * parse an XML namespace non qualified name.
8497
 *
8498
 * [NS 3] NCName ::= (Letter | '_') (NCNameChar)*
8499
 *
8500
 * [NS 4] NCNameChar ::= Letter | Digit | '.' | '-' | '_' |
8501
 *                       CombiningChar | Extender
8502
 *
8503
 * Returns the namespace name or NULL
8504
 */
8505
8506
xmlChar *
8507
2.71k
xmlXPathParseNCName(xmlXPathParserContextPtr ctxt) {
8508
2.71k
    const xmlChar *in;
8509
2.71k
    xmlChar *ret;
8510
2.71k
    int count = 0;
8511
8512
2.71k
    if ((ctxt == NULL) || (ctxt->cur == NULL)) return(NULL);
8513
    /*
8514
     * Accelerator for simple ASCII names
8515
     */
8516
2.71k
    in = ctxt->cur;
8517
2.71k
    if (((*in >= 0x61) && (*in <= 0x7A)) ||
8518
365
  ((*in >= 0x41) && (*in <= 0x5A)) ||
8519
2.62k
  (*in == '_')) {
8520
2.62k
  in++;
8521
17.9k
  while (((*in >= 0x61) && (*in <= 0x7A)) ||
8522
4.79k
         ((*in >= 0x41) && (*in <= 0x5A)) ||
8523
3.70k
         ((*in >= 0x30) && (*in <= 0x39)) ||
8524
2.62k
         (*in == '_') || (*in == '.') ||
8525
2.62k
         (*in == '-'))
8526
15.2k
      in++;
8527
2.62k
  if ((*in == ' ') || (*in == '>') || (*in == '/') ||
8528
2.53k
            (*in == '[') || (*in == ']') || (*in == ':') ||
8529
2.43k
            (*in == '@') || (*in == '*')) {
8530
2.43k
      count = in - ctxt->cur;
8531
2.43k
      if (count == 0)
8532
0
    return(NULL);
8533
2.43k
      ret = xmlStrndup(ctxt->cur, count);
8534
2.43k
            if (ret == NULL)
8535
0
                xmlXPathPErrMemory(ctxt);
8536
2.43k
      ctxt->cur = in;
8537
2.43k
      return(ret);
8538
2.43k
  }
8539
2.62k
    }
8540
279
    return(xmlXPathParseNameComplex(ctxt, 0));
8541
2.71k
}
8542
8543
8544
/**
8545
 * xmlXPathParseQName:
8546
 * @ctxt:  the XPath Parser context
8547
 * @prefix:  a xmlChar **
8548
 *
8549
 * parse an XML qualified name
8550
 *
8551
 * [NS 5] QName ::= (Prefix ':')? LocalPart
8552
 *
8553
 * [NS 6] Prefix ::= NCName
8554
 *
8555
 * [NS 7] LocalPart ::= NCName
8556
 *
8557
 * Returns the function returns the local part, and prefix is updated
8558
 *   to get the Prefix if any.
8559
 */
8560
8561
static xmlChar *
8562
93
xmlXPathParseQName(xmlXPathParserContextPtr ctxt, xmlChar **prefix) {
8563
93
    xmlChar *ret = NULL;
8564
8565
93
    *prefix = NULL;
8566
93
    ret = xmlXPathParseNCName(ctxt);
8567
93
    if (ret && CUR == ':') {
8568
0
        *prefix = ret;
8569
0
  NEXT;
8570
0
  ret = xmlXPathParseNCName(ctxt);
8571
0
    }
8572
93
    return(ret);
8573
93
}
8574
8575
/**
8576
 * xmlXPathParseName:
8577
 * @ctxt:  the XPath Parser context
8578
 *
8579
 * parse an XML name
8580
 *
8581
 * [4] NameChar ::= Letter | Digit | '.' | '-' | '_' | ':' |
8582
 *                  CombiningChar | Extender
8583
 *
8584
 * [5] Name ::= (Letter | '_' | ':') (NameChar)*
8585
 *
8586
 * Returns the namespace name or NULL
8587
 */
8588
8589
xmlChar *
8590
0
xmlXPathParseName(xmlXPathParserContextPtr ctxt) {
8591
0
    const xmlChar *in;
8592
0
    xmlChar *ret;
8593
0
    size_t count = 0;
8594
8595
0
    if ((ctxt == NULL) || (ctxt->cur == NULL)) return(NULL);
8596
    /*
8597
     * Accelerator for simple ASCII names
8598
     */
8599
0
    in = ctxt->cur;
8600
0
    if (((*in >= 0x61) && (*in <= 0x7A)) ||
8601
0
  ((*in >= 0x41) && (*in <= 0x5A)) ||
8602
0
  (*in == '_') || (*in == ':')) {
8603
0
  in++;
8604
0
  while (((*in >= 0x61) && (*in <= 0x7A)) ||
8605
0
         ((*in >= 0x41) && (*in <= 0x5A)) ||
8606
0
         ((*in >= 0x30) && (*in <= 0x39)) ||
8607
0
         (*in == '_') || (*in == '-') ||
8608
0
         (*in == ':') || (*in == '.'))
8609
0
      in++;
8610
0
  if ((*in > 0) && (*in < 0x80)) {
8611
0
      count = in - ctxt->cur;
8612
0
            if (count > XML_MAX_NAME_LENGTH) {
8613
0
                ctxt->cur = in;
8614
0
                XP_ERRORNULL(XPATH_EXPR_ERROR);
8615
0
            }
8616
0
      ret = xmlStrndup(ctxt->cur, count);
8617
0
            if (ret == NULL)
8618
0
                xmlXPathPErrMemory(ctxt);
8619
0
      ctxt->cur = in;
8620
0
      return(ret);
8621
0
  }
8622
0
    }
8623
0
    return(xmlXPathParseNameComplex(ctxt, 1));
8624
0
}
8625
8626
static xmlChar *
8627
279
xmlXPathParseNameComplex(xmlXPathParserContextPtr ctxt, int qualified) {
8628
279
    xmlChar *ret;
8629
279
    xmlChar buf[XML_MAX_NAMELEN + 5];
8630
279
    int len = 0, l;
8631
279
    int c;
8632
8633
    /*
8634
     * Handler for more complex cases
8635
     */
8636
279
    c = CUR_CHAR(l);
8637
279
    if ((c == ' ') || (c == '>') || (c == '/') || /* accelerators */
8638
279
        (c == '[') || (c == ']') || (c == '@') || /* accelerators */
8639
186
        (c == '*') || /* accelerators */
8640
186
  (!IS_LETTER(c) && (c != '_') &&
8641
93
         ((!qualified) || (c != ':')))) {
8642
93
  return(NULL);
8643
93
    }
8644
8645
1.30k
    while ((c != ' ') && (c != '>') && (c != '/') && /* test bigname.xml */
8646
1.30k
     ((IS_LETTER(c)) || (IS_DIGIT(c)) ||
8647
186
            (c == '.') || (c == '-') ||
8648
186
      (c == '_') || ((qualified) && (c == ':')) ||
8649
186
      (IS_COMBINING(c)) ||
8650
1.11k
      (IS_EXTENDER(c)))) {
8651
1.11k
  COPY_BUF(buf,len,c);
8652
1.11k
  NEXTL(l);
8653
1.11k
  c = CUR_CHAR(l);
8654
1.11k
  if (len >= XML_MAX_NAMELEN) {
8655
      /*
8656
       * Okay someone managed to make a huge name, so he's ready to pay
8657
       * for the processing speed.
8658
       */
8659
0
      xmlChar *buffer;
8660
0
      int max = len * 2;
8661
8662
0
            if (len > XML_MAX_NAME_LENGTH) {
8663
0
                XP_ERRORNULL(XPATH_EXPR_ERROR);
8664
0
            }
8665
0
      buffer = xmlMalloc(max);
8666
0
      if (buffer == NULL) {
8667
0
                xmlXPathPErrMemory(ctxt);
8668
0
                return(NULL);
8669
0
      }
8670
0
      memcpy(buffer, buf, len);
8671
0
      while ((IS_LETTER(c)) || (IS_DIGIT(c)) || /* test bigname.xml */
8672
0
       (c == '.') || (c == '-') ||
8673
0
       (c == '_') || ((qualified) && (c == ':')) ||
8674
0
       (IS_COMBINING(c)) ||
8675
0
       (IS_EXTENDER(c))) {
8676
0
    if (len + 10 > max) {
8677
0
                    xmlChar *tmp;
8678
0
                    int newSize;
8679
8680
0
                    newSize = xmlGrowCapacity(max, 1, 1, XML_MAX_NAME_LENGTH);
8681
0
                    if (newSize < 0) {
8682
0
                        xmlFree(buffer);
8683
0
                        xmlXPathErr(ctxt, XPATH_EXPR_ERROR);
8684
0
                        return(NULL);
8685
0
                    }
8686
0
        tmp = xmlRealloc(buffer, newSize);
8687
0
        if (tmp == NULL) {
8688
0
                        xmlFree(buffer);
8689
0
                        xmlXPathPErrMemory(ctxt);
8690
0
                        return(NULL);
8691
0
        }
8692
0
                    buffer = tmp;
8693
0
        max = newSize;
8694
0
    }
8695
0
    COPY_BUF(buffer,len,c);
8696
0
    NEXTL(l);
8697
0
    c = CUR_CHAR(l);
8698
0
      }
8699
0
      buffer[len] = 0;
8700
0
      return(buffer);
8701
0
  }
8702
1.11k
    }
8703
186
    if (len == 0)
8704
0
  return(NULL);
8705
186
    ret = xmlStrndup(buf, len);
8706
186
    if (ret == NULL)
8707
0
        xmlXPathPErrMemory(ctxt);
8708
186
    return(ret);
8709
186
}
8710
8711
0
#define MAX_FRAC 20
8712
8713
/**
8714
 * xmlXPathStringEvalNumber:
8715
 * @str:  A string to scan
8716
 *
8717
 *  [30a]  Float  ::= Number ('e' Digits?)?
8718
 *
8719
 *  [30]   Number ::=   Digits ('.' Digits?)?
8720
 *                    | '.' Digits
8721
 *  [31]   Digits ::=   [0-9]+
8722
 *
8723
 * Compile a Number in the string
8724
 * In complement of the Number expression, this function also handles
8725
 * negative values : '-' Number.
8726
 *
8727
 * Returns the double value.
8728
 */
8729
double
8730
0
xmlXPathStringEvalNumber(const xmlChar *str) {
8731
0
    const xmlChar *cur = str;
8732
0
    double ret;
8733
0
    int ok = 0;
8734
0
    int isneg = 0;
8735
0
    int exponent = 0;
8736
0
    int is_exponent_negative = 0;
8737
0
#ifdef __GNUC__
8738
0
    unsigned long tmp = 0;
8739
0
    double temp;
8740
0
#endif
8741
0
    if (cur == NULL) return(0);
8742
0
    while (IS_BLANK_CH(*cur)) cur++;
8743
0
    if (*cur == '-') {
8744
0
  isneg = 1;
8745
0
  cur++;
8746
0
    }
8747
0
    if ((*cur != '.') && ((*cur < '0') || (*cur > '9'))) {
8748
0
        return(xmlXPathNAN);
8749
0
    }
8750
8751
0
#ifdef __GNUC__
8752
    /*
8753
     * tmp/temp is a workaround against a gcc compiler bug
8754
     * http://veillard.com/gcc.bug
8755
     */
8756
0
    ret = 0;
8757
0
    while ((*cur >= '0') && (*cur <= '9')) {
8758
0
  ret = ret * 10;
8759
0
  tmp = (*cur - '0');
8760
0
  ok = 1;
8761
0
  cur++;
8762
0
  temp = (double) tmp;
8763
0
  ret = ret + temp;
8764
0
    }
8765
#else
8766
    ret = 0;
8767
    while ((*cur >= '0') && (*cur <= '9')) {
8768
  ret = ret * 10 + (*cur - '0');
8769
  ok = 1;
8770
  cur++;
8771
    }
8772
#endif
8773
8774
0
    if (*cur == '.') {
8775
0
  int v, frac = 0, max;
8776
0
  double fraction = 0;
8777
8778
0
        cur++;
8779
0
  if (((*cur < '0') || (*cur > '9')) && (!ok)) {
8780
0
      return(xmlXPathNAN);
8781
0
  }
8782
0
        while (*cur == '0') {
8783
0
      frac = frac + 1;
8784
0
      cur++;
8785
0
        }
8786
0
        max = frac + MAX_FRAC;
8787
0
  while (((*cur >= '0') && (*cur <= '9')) && (frac < max)) {
8788
0
      v = (*cur - '0');
8789
0
      fraction = fraction * 10 + v;
8790
0
      frac = frac + 1;
8791
0
      cur++;
8792
0
  }
8793
0
  fraction /= pow(10.0, frac);
8794
0
  ret = ret + fraction;
8795
0
  while ((*cur >= '0') && (*cur <= '9'))
8796
0
      cur++;
8797
0
    }
8798
0
    if ((*cur == 'e') || (*cur == 'E')) {
8799
0
      cur++;
8800
0
      if (*cur == '-') {
8801
0
  is_exponent_negative = 1;
8802
0
  cur++;
8803
0
      } else if (*cur == '+') {
8804
0
        cur++;
8805
0
      }
8806
0
      while ((*cur >= '0') && (*cur <= '9')) {
8807
0
        if (exponent < 1000000)
8808
0
    exponent = exponent * 10 + (*cur - '0');
8809
0
  cur++;
8810
0
      }
8811
0
    }
8812
0
    while (IS_BLANK_CH(*cur)) cur++;
8813
0
    if (*cur != 0) return(xmlXPathNAN);
8814
0
    if (isneg) ret = -ret;
8815
0
    if (is_exponent_negative) exponent = -exponent;
8816
0
    ret *= pow(10.0, (double)exponent);
8817
0
    return(ret);
8818
0
}
8819
8820
/**
8821
 * xmlXPathCompNumber:
8822
 * @ctxt:  the XPath Parser context
8823
 *
8824
 *  [30]   Number ::=   Digits ('.' Digits?)?
8825
 *                    | '.' Digits
8826
 *  [31]   Digits ::=   [0-9]+
8827
 *
8828
 * Compile a Number, then push it on the stack
8829
 *
8830
 */
8831
static void
8832
xmlXPathCompNumber(xmlXPathParserContextPtr ctxt)
8833
1.08k
{
8834
1.08k
    double ret = 0.0;
8835
1.08k
    int ok = 0;
8836
1.08k
    int exponent = 0;
8837
1.08k
    int is_exponent_negative = 0;
8838
1.08k
    xmlXPathObjectPtr num;
8839
1.08k
#ifdef __GNUC__
8840
1.08k
    unsigned long tmp = 0;
8841
1.08k
    double temp;
8842
1.08k
#endif
8843
8844
1.08k
    CHECK_ERROR;
8845
1.08k
    if ((CUR != '.') && ((CUR < '0') || (CUR > '9'))) {
8846
0
        XP_ERROR(XPATH_NUMBER_ERROR);
8847
0
    }
8848
1.08k
#ifdef __GNUC__
8849
    /*
8850
     * tmp/temp is a workaround against a gcc compiler bug
8851
     * http://veillard.com/gcc.bug
8852
     */
8853
1.08k
    ret = 0;
8854
2.16k
    while ((CUR >= '0') && (CUR <= '9')) {
8855
1.08k
  ret = ret * 10;
8856
1.08k
  tmp = (CUR - '0');
8857
1.08k
        ok = 1;
8858
1.08k
        NEXT;
8859
1.08k
  temp = (double) tmp;
8860
1.08k
  ret = ret + temp;
8861
1.08k
    }
8862
#else
8863
    ret = 0;
8864
    while ((CUR >= '0') && (CUR <= '9')) {
8865
  ret = ret * 10 + (CUR - '0');
8866
  ok = 1;
8867
  NEXT;
8868
    }
8869
#endif
8870
1.08k
    if (CUR == '.') {
8871
0
  int v, frac = 0, max;
8872
0
  double fraction = 0;
8873
8874
0
        NEXT;
8875
0
        if (((CUR < '0') || (CUR > '9')) && (!ok)) {
8876
0
            XP_ERROR(XPATH_NUMBER_ERROR);
8877
0
        }
8878
0
        while (CUR == '0') {
8879
0
            frac = frac + 1;
8880
0
            NEXT;
8881
0
        }
8882
0
        max = frac + MAX_FRAC;
8883
0
        while ((CUR >= '0') && (CUR <= '9') && (frac < max)) {
8884
0
      v = (CUR - '0');
8885
0
      fraction = fraction * 10 + v;
8886
0
      frac = frac + 1;
8887
0
            NEXT;
8888
0
        }
8889
0
        fraction /= pow(10.0, frac);
8890
0
        ret = ret + fraction;
8891
0
        while ((CUR >= '0') && (CUR <= '9'))
8892
0
            NEXT;
8893
0
    }
8894
1.08k
    if ((CUR == 'e') || (CUR == 'E')) {
8895
0
        NEXT;
8896
0
        if (CUR == '-') {
8897
0
            is_exponent_negative = 1;
8898
0
            NEXT;
8899
0
        } else if (CUR == '+') {
8900
0
      NEXT;
8901
0
  }
8902
0
        while ((CUR >= '0') && (CUR <= '9')) {
8903
0
            if (exponent < 1000000)
8904
0
                exponent = exponent * 10 + (CUR - '0');
8905
0
            NEXT;
8906
0
        }
8907
0
        if (is_exponent_negative)
8908
0
            exponent = -exponent;
8909
0
        ret *= pow(10.0, (double) exponent);
8910
0
    }
8911
1.08k
    num = xmlXPathCacheNewFloat(ctxt, ret);
8912
1.08k
    if (num == NULL) {
8913
0
  ctxt->error = XPATH_MEMORY_ERROR;
8914
1.08k
    } else if (PUSH_LONG_EXPR(XPATH_OP_VALUE, XPATH_NUMBER, 0, 0, num,
8915
1.08k
                              NULL) == -1) {
8916
0
        xmlXPathReleaseObject(ctxt->context, num);
8917
0
    }
8918
1.08k
}
8919
8920
/**
8921
 * xmlXPathParseLiteral:
8922
 * @ctxt:  the XPath Parser context
8923
 *
8924
 * Parse a Literal
8925
 *
8926
 *  [29]   Literal ::=   '"' [^"]* '"'
8927
 *                    | "'" [^']* "'"
8928
 *
8929
 * Returns the value found or NULL in case of error
8930
 */
8931
static xmlChar *
8932
0
xmlXPathParseLiteral(xmlXPathParserContextPtr ctxt) {
8933
0
    const xmlChar *q;
8934
0
    xmlChar *ret = NULL;
8935
0
    int quote;
8936
8937
0
    if (CUR == '"') {
8938
0
        quote = '"';
8939
0
    } else if (CUR == '\'') {
8940
0
        quote = '\'';
8941
0
    } else {
8942
0
  XP_ERRORNULL(XPATH_START_LITERAL_ERROR);
8943
0
    }
8944
8945
0
    NEXT;
8946
0
    q = CUR_PTR;
8947
0
    while (CUR != quote) {
8948
0
        int ch;
8949
0
        int len = 4;
8950
8951
0
        if (CUR == 0)
8952
0
            XP_ERRORNULL(XPATH_UNFINISHED_LITERAL_ERROR);
8953
0
        ch = xmlGetUTF8Char(CUR_PTR, &len);
8954
0
        if ((ch < 0) || (IS_CHAR(ch) == 0))
8955
0
            XP_ERRORNULL(XPATH_INVALID_CHAR_ERROR);
8956
0
        CUR_PTR += len;
8957
0
    }
8958
0
    ret = xmlStrndup(q, CUR_PTR - q);
8959
0
    if (ret == NULL)
8960
0
        xmlXPathPErrMemory(ctxt);
8961
0
    NEXT;
8962
0
    return(ret);
8963
0
}
8964
8965
/**
8966
 * xmlXPathCompLiteral:
8967
 * @ctxt:  the XPath Parser context
8968
 *
8969
 * Parse a Literal and push it on the stack.
8970
 *
8971
 *  [29]   Literal ::=   '"' [^"]* '"'
8972
 *                    | "'" [^']* "'"
8973
 *
8974
 * TODO: xmlXPathCompLiteral memory allocation could be improved.
8975
 */
8976
static void
8977
0
xmlXPathCompLiteral(xmlXPathParserContextPtr ctxt) {
8978
0
    xmlChar *ret = NULL;
8979
0
    xmlXPathObjectPtr lit;
8980
8981
0
    ret = xmlXPathParseLiteral(ctxt);
8982
0
    if (ret == NULL)
8983
0
        return;
8984
0
    lit = xmlXPathCacheNewString(ctxt, ret);
8985
0
    if (lit == NULL) {
8986
0
        ctxt->error = XPATH_MEMORY_ERROR;
8987
0
    } else if (PUSH_LONG_EXPR(XPATH_OP_VALUE, XPATH_STRING, 0, 0, lit,
8988
0
                              NULL) == -1) {
8989
0
        xmlXPathReleaseObject(ctxt->context, lit);
8990
0
    }
8991
0
    xmlFree(ret);
8992
0
}
8993
8994
/**
8995
 * xmlXPathCompVariableReference:
8996
 * @ctxt:  the XPath Parser context
8997
 *
8998
 * Parse a VariableReference, evaluate it and push it on the stack.
8999
 *
9000
 * The variable bindings consist of a mapping from variable names
9001
 * to variable values. The value of a variable is an object, which can be
9002
 * of any of the types that are possible for the value of an expression,
9003
 * and may also be of additional types not specified here.
9004
 *
9005
 * Early evaluation is possible since:
9006
 * The variable bindings [...] used to evaluate a subexpression are
9007
 * always the same as those used to evaluate the containing expression.
9008
 *
9009
 *  [36]   VariableReference ::=   '$' QName
9010
 */
9011
static void
9012
0
xmlXPathCompVariableReference(xmlXPathParserContextPtr ctxt) {
9013
0
    xmlChar *name;
9014
0
    xmlChar *prefix;
9015
9016
0
    SKIP_BLANKS;
9017
0
    if (CUR != '$') {
9018
0
  XP_ERROR(XPATH_VARIABLE_REF_ERROR);
9019
0
    }
9020
0
    NEXT;
9021
0
    name = xmlXPathParseQName(ctxt, &prefix);
9022
0
    if (name == NULL) {
9023
0
        xmlFree(prefix);
9024
0
  XP_ERROR(XPATH_VARIABLE_REF_ERROR);
9025
0
    }
9026
0
    ctxt->comp->last = -1;
9027
0
    if (PUSH_LONG_EXPR(XPATH_OP_VARIABLE, 0, 0, 0, name, prefix) == -1) {
9028
0
        xmlFree(prefix);
9029
0
        xmlFree(name);
9030
0
    }
9031
0
    SKIP_BLANKS;
9032
0
    if ((ctxt->context != NULL) && (ctxt->context->flags & XML_XPATH_NOVAR)) {
9033
0
  XP_ERROR(XPATH_FORBID_VARIABLE_ERROR);
9034
0
    }
9035
0
}
9036
9037
/**
9038
 * xmlXPathIsNodeType:
9039
 * @name:  a name string
9040
 *
9041
 * Is the name given a NodeType one.
9042
 *
9043
 *  [38]   NodeType ::=   'comment'
9044
 *                    | 'text'
9045
 *                    | 'processing-instruction'
9046
 *                    | 'node'
9047
 *
9048
 * Returns 1 if true 0 otherwise
9049
 */
9050
int
9051
93
xmlXPathIsNodeType(const xmlChar *name) {
9052
93
    if (name == NULL)
9053
0
  return(0);
9054
9055
93
    if (xmlStrEqual(name, BAD_CAST "node"))
9056
0
  return(1);
9057
93
    if (xmlStrEqual(name, BAD_CAST "text"))
9058
0
  return(1);
9059
93
    if (xmlStrEqual(name, BAD_CAST "comment"))
9060
0
  return(1);
9061
93
    if (xmlStrEqual(name, BAD_CAST "processing-instruction"))
9062
0
  return(1);
9063
93
    return(0);
9064
93
}
9065
9066
/**
9067
 * xmlXPathCompFunctionCall:
9068
 * @ctxt:  the XPath Parser context
9069
 *
9070
 *  [16]   FunctionCall ::=   FunctionName '(' ( Argument ( ',' Argument)*)? ')'
9071
 *  [17]   Argument ::=   Expr
9072
 *
9073
 * Compile a function call, the evaluation of all arguments are
9074
 * pushed on the stack
9075
 */
9076
static void
9077
93
xmlXPathCompFunctionCall(xmlXPathParserContextPtr ctxt) {
9078
93
    xmlChar *name;
9079
93
    xmlChar *prefix;
9080
93
    int nbargs = 0;
9081
93
    int sort = 1;
9082
9083
93
    name = xmlXPathParseQName(ctxt, &prefix);
9084
93
    if (name == NULL) {
9085
0
  xmlFree(prefix);
9086
0
  XP_ERROR(XPATH_EXPR_ERROR);
9087
0
    }
9088
93
    SKIP_BLANKS;
9089
9090
93
    if (CUR != '(') {
9091
0
  xmlFree(name);
9092
0
  xmlFree(prefix);
9093
0
  XP_ERROR(XPATH_EXPR_ERROR);
9094
0
    }
9095
93
    NEXT;
9096
93
    SKIP_BLANKS;
9097
9098
    /*
9099
    * Optimization for count(): we don't need the node-set to be sorted.
9100
    */
9101
93
    if ((prefix == NULL) && (name[0] == 'c') &&
9102
0
  xmlStrEqual(name, BAD_CAST "count"))
9103
0
    {
9104
0
  sort = 0;
9105
0
    }
9106
93
    ctxt->comp->last = -1;
9107
93
    if (CUR != ')') {
9108
93
  while (CUR != 0) {
9109
93
      int op1 = ctxt->comp->last;
9110
93
      ctxt->comp->last = -1;
9111
93
      xmlXPathCompileExpr(ctxt, sort);
9112
93
      if (ctxt->error != XPATH_EXPRESSION_OK) {
9113
0
    xmlFree(name);
9114
0
    xmlFree(prefix);
9115
0
    return;
9116
0
      }
9117
93
      PUSH_BINARY_EXPR(XPATH_OP_ARG, op1, ctxt->comp->last, 0, 0);
9118
93
      nbargs++;
9119
93
      if (CUR == ')') break;
9120
0
      if (CUR != ',') {
9121
0
    xmlFree(name);
9122
0
    xmlFree(prefix);
9123
0
    XP_ERROR(XPATH_EXPR_ERROR);
9124
0
      }
9125
0
      NEXT;
9126
0
      SKIP_BLANKS;
9127
0
  }
9128
93
    }
9129
93
    if (PUSH_LONG_EXPR(XPATH_OP_FUNCTION, nbargs, 0, 0, name, prefix) == -1) {
9130
0
        xmlFree(prefix);
9131
0
        xmlFree(name);
9132
0
    }
9133
93
    NEXT;
9134
93
    SKIP_BLANKS;
9135
93
}
9136
9137
/**
9138
 * xmlXPathCompPrimaryExpr:
9139
 * @ctxt:  the XPath Parser context
9140
 *
9141
 *  [15]   PrimaryExpr ::=   VariableReference
9142
 *                | '(' Expr ')'
9143
 *                | Literal
9144
 *                | Number
9145
 *                | FunctionCall
9146
 *
9147
 * Compile a primary expression.
9148
 */
9149
static void
9150
1.17k
xmlXPathCompPrimaryExpr(xmlXPathParserContextPtr ctxt) {
9151
1.17k
    SKIP_BLANKS;
9152
1.17k
    if (CUR == '$') xmlXPathCompVariableReference(ctxt);
9153
1.17k
    else if (CUR == '(') {
9154
0
  NEXT;
9155
0
  SKIP_BLANKS;
9156
0
  xmlXPathCompileExpr(ctxt, 1);
9157
0
  CHECK_ERROR;
9158
0
  if (CUR != ')') {
9159
0
      XP_ERROR(XPATH_EXPR_ERROR);
9160
0
  }
9161
0
  NEXT;
9162
0
  SKIP_BLANKS;
9163
1.17k
    } else if (IS_ASCII_DIGIT(CUR) || (CUR == '.' && IS_ASCII_DIGIT(NXT(1)))) {
9164
1.08k
  xmlXPathCompNumber(ctxt);
9165
1.08k
    } else if ((CUR == '\'') || (CUR == '"')) {
9166
0
  xmlXPathCompLiteral(ctxt);
9167
93
    } else {
9168
93
  xmlXPathCompFunctionCall(ctxt);
9169
93
    }
9170
1.17k
    SKIP_BLANKS;
9171
1.17k
}
9172
9173
/**
9174
 * xmlXPathCompFilterExpr:
9175
 * @ctxt:  the XPath Parser context
9176
 *
9177
 *  [20]   FilterExpr ::=   PrimaryExpr
9178
 *               | FilterExpr Predicate
9179
 *
9180
 * Compile a filter expression.
9181
 * Square brackets are used to filter expressions in the same way that
9182
 * they are used in location paths. It is an error if the expression to
9183
 * be filtered does not evaluate to a node-set. The context node list
9184
 * used for evaluating the expression in square brackets is the node-set
9185
 * to be filtered listed in document order.
9186
 */
9187
9188
static void
9189
1.17k
xmlXPathCompFilterExpr(xmlXPathParserContextPtr ctxt) {
9190
1.17k
    xmlXPathCompPrimaryExpr(ctxt);
9191
1.17k
    CHECK_ERROR;
9192
1.17k
    SKIP_BLANKS;
9193
9194
1.17k
    while (CUR == '[') {
9195
0
  xmlXPathCompPredicate(ctxt, 1);
9196
0
  SKIP_BLANKS;
9197
0
    }
9198
9199
9200
1.17k
}
9201
9202
/**
9203
 * xmlXPathScanName:
9204
 * @ctxt:  the XPath Parser context
9205
 *
9206
 * Trickery: parse an XML name but without consuming the input flow
9207
 * Needed to avoid insanity in the parser state.
9208
 *
9209
 * [4] NameChar ::= Letter | Digit | '.' | '-' | '_' | ':' |
9210
 *                  CombiningChar | Extender
9211
 *
9212
 * [5] Name ::= (Letter | '_' | ':') (NameChar)*
9213
 *
9214
 * [6] Names ::= Name (S Name)*
9215
 *
9216
 * Returns the Name parsed or NULL
9217
 */
9218
9219
static xmlChar *
9220
93
xmlXPathScanName(xmlXPathParserContextPtr ctxt) {
9221
93
    int l;
9222
93
    int c;
9223
93
    const xmlChar *cur;
9224
93
    xmlChar *ret;
9225
9226
93
    cur = ctxt->cur;
9227
9228
93
    c = CUR_CHAR(l);
9229
93
    if ((c == ' ') || (c == '>') || (c == '/') || /* accelerators */
9230
93
  (!IS_LETTER(c) && (c != '_') &&
9231
0
         (c != ':'))) {
9232
0
  return(NULL);
9233
0
    }
9234
9235
651
    while ((c != ' ') && (c != '>') && (c != '/') && /* test bigname.xml */
9236
651
     ((IS_LETTER(c)) || (IS_DIGIT(c)) ||
9237
93
            (c == '.') || (c == '-') ||
9238
93
      (c == '_') || (c == ':') ||
9239
93
      (IS_COMBINING(c)) ||
9240
558
      (IS_EXTENDER(c)))) {
9241
558
  NEXTL(l);
9242
558
  c = CUR_CHAR(l);
9243
558
    }
9244
93
    ret = xmlStrndup(cur, ctxt->cur - cur);
9245
93
    if (ret == NULL)
9246
0
        xmlXPathPErrMemory(ctxt);
9247
93
    ctxt->cur = cur;
9248
93
    return(ret);
9249
93
}
9250
9251
/**
9252
 * xmlXPathCompPathExpr:
9253
 * @ctxt:  the XPath Parser context
9254
 *
9255
 *  [19]   PathExpr ::=   LocationPath
9256
 *               | FilterExpr
9257
 *               | FilterExpr '/' RelativeLocationPath
9258
 *               | FilterExpr '//' RelativeLocationPath
9259
 *
9260
 * Compile a path expression.
9261
 * The / operator and // operators combine an arbitrary expression
9262
 * and a relative location path. It is an error if the expression
9263
 * does not evaluate to a node-set.
9264
 * The / operator does composition in the same way as when / is
9265
 * used in a location path. As in location paths, // is short for
9266
 * /descendant-or-self::node()/.
9267
 */
9268
9269
static void
9270
1.80k
xmlXPathCompPathExpr(xmlXPathParserContextPtr ctxt) {
9271
1.80k
    int lc = 1;           /* Should we branch to LocationPath ?         */
9272
1.80k
    xmlChar *name = NULL; /* we may have to preparse a name to find out */
9273
9274
1.80k
    SKIP_BLANKS;
9275
1.80k
    if ((CUR == '$') || (CUR == '(') ||
9276
1.80k
  (IS_ASCII_DIGIT(CUR)) ||
9277
726
        (CUR == '\'') || (CUR == '"') ||
9278
1.08k
  (CUR == '.' && IS_ASCII_DIGIT(NXT(1)))) {
9279
1.08k
  lc = 0;
9280
1.08k
    } else if (CUR == '*') {
9281
  /* relative or absolute location path */
9282
0
  lc = 1;
9283
726
    } else if (CUR == '/') {
9284
  /* relative or absolute location path */
9285
633
  lc = 1;
9286
633
    } else if (CUR == '@') {
9287
  /* relative abbreviated attribute location path */
9288
0
  lc = 1;
9289
93
    } else if (CUR == '.') {
9290
  /* relative abbreviated attribute location path */
9291
0
  lc = 1;
9292
93
    } else {
9293
  /*
9294
   * Problem is finding if we have a name here whether it's:
9295
   *   - a nodetype
9296
   *   - a function call in which case it's followed by '('
9297
   *   - an axis in which case it's followed by ':'
9298
   *   - a element name
9299
   * We do an a priori analysis here rather than having to
9300
   * maintain parsed token content through the recursive function
9301
   * calls. This looks uglier but makes the code easier to
9302
   * read/write/debug.
9303
   */
9304
93
  SKIP_BLANKS;
9305
93
  name = xmlXPathScanName(ctxt);
9306
93
  if ((name != NULL) && (xmlStrstr(name, (xmlChar *) "::") != NULL)) {
9307
0
      lc = 1;
9308
0
      xmlFree(name);
9309
93
  } else if (name != NULL) {
9310
93
      int len =xmlStrlen(name);
9311
9312
9313
93
      while (NXT(len) != 0) {
9314
93
    if (NXT(len) == '/') {
9315
        /* element name */
9316
0
        lc = 1;
9317
0
        break;
9318
93
    } else if (IS_BLANK_CH(NXT(len))) {
9319
        /* ignore blanks */
9320
0
        ;
9321
93
    } else if (NXT(len) == ':') {
9322
0
        lc = 1;
9323
0
        break;
9324
93
    } else if ((NXT(len) == '(')) {
9325
        /* Node Type or Function */
9326
93
        if (xmlXPathIsNodeType(name)) {
9327
0
      lc = 1;
9328
93
        } else {
9329
93
      lc = 0;
9330
93
        }
9331
93
                    break;
9332
93
    } else if ((NXT(len) == '[')) {
9333
        /* element name */
9334
0
        lc = 1;
9335
0
        break;
9336
0
    } else if ((NXT(len) == '<') || (NXT(len) == '>') ||
9337
0
         (NXT(len) == '=')) {
9338
0
        lc = 1;
9339
0
        break;
9340
0
    } else {
9341
0
        lc = 1;
9342
0
        break;
9343
0
    }
9344
0
    len++;
9345
0
      }
9346
93
      if (NXT(len) == 0) {
9347
    /* element name */
9348
0
    lc = 1;
9349
0
      }
9350
93
      xmlFree(name);
9351
93
  } else {
9352
      /* make sure all cases are covered explicitly */
9353
0
      XP_ERROR(XPATH_EXPR_ERROR);
9354
0
  }
9355
93
    }
9356
9357
1.80k
    if (lc) {
9358
633
  if (CUR == '/') {
9359
633
      PUSH_LEAVE_EXPR(XPATH_OP_ROOT, 0, 0);
9360
633
  } else {
9361
0
      PUSH_LEAVE_EXPR(XPATH_OP_NODE, 0, 0);
9362
0
  }
9363
633
  xmlXPathCompLocationPath(ctxt);
9364
1.17k
    } else {
9365
1.17k
  xmlXPathCompFilterExpr(ctxt);
9366
1.17k
  CHECK_ERROR;
9367
1.17k
  if ((CUR == '/') && (NXT(1) == '/')) {
9368
0
      SKIP(2);
9369
0
      SKIP_BLANKS;
9370
9371
0
      PUSH_LONG_EXPR(XPATH_OP_COLLECT, AXIS_DESCENDANT_OR_SELF,
9372
0
        NODE_TEST_TYPE, NODE_TYPE_NODE, NULL, NULL);
9373
9374
0
      xmlXPathCompRelativeLocationPath(ctxt);
9375
1.17k
  } else if (CUR == '/') {
9376
0
      xmlXPathCompRelativeLocationPath(ctxt);
9377
0
  }
9378
1.17k
    }
9379
1.80k
    SKIP_BLANKS;
9380
1.80k
}
9381
9382
/**
9383
 * xmlXPathCompUnionExpr:
9384
 * @ctxt:  the XPath Parser context
9385
 *
9386
 *  [18]   UnionExpr ::=   PathExpr
9387
 *               | UnionExpr '|' PathExpr
9388
 *
9389
 * Compile an union expression.
9390
 */
9391
9392
static void
9393
1.80k
xmlXPathCompUnionExpr(xmlXPathParserContextPtr ctxt) {
9394
1.80k
    xmlXPathCompPathExpr(ctxt);
9395
1.80k
    CHECK_ERROR;
9396
1.80k
    SKIP_BLANKS;
9397
1.80k
    while (CUR == '|') {
9398
0
  int op1 = ctxt->comp->last;
9399
0
  PUSH_LEAVE_EXPR(XPATH_OP_NODE, 0, 0);
9400
9401
0
  NEXT;
9402
0
  SKIP_BLANKS;
9403
0
  xmlXPathCompPathExpr(ctxt);
9404
9405
0
  PUSH_BINARY_EXPR(XPATH_OP_UNION, op1, ctxt->comp->last, 0, 0);
9406
9407
0
  SKIP_BLANKS;
9408
0
    }
9409
1.80k
}
9410
9411
/**
9412
 * xmlXPathCompUnaryExpr:
9413
 * @ctxt:  the XPath Parser context
9414
 *
9415
 *  [27]   UnaryExpr ::=   UnionExpr
9416
 *                   | '-' UnaryExpr
9417
 *
9418
 * Compile an unary expression.
9419
 */
9420
9421
static void
9422
1.80k
xmlXPathCompUnaryExpr(xmlXPathParserContextPtr ctxt) {
9423
1.80k
    int minus = 0;
9424
1.80k
    int found = 0;
9425
9426
1.80k
    SKIP_BLANKS;
9427
1.80k
    while (CUR == '-') {
9428
0
        minus = 1 - minus;
9429
0
  found = 1;
9430
0
  NEXT;
9431
0
  SKIP_BLANKS;
9432
0
    }
9433
9434
1.80k
    xmlXPathCompUnionExpr(ctxt);
9435
1.80k
    CHECK_ERROR;
9436
1.80k
    if (found) {
9437
0
  if (minus)
9438
0
      PUSH_UNARY_EXPR(XPATH_OP_PLUS, ctxt->comp->last, 2, 0);
9439
0
  else
9440
0
      PUSH_UNARY_EXPR(XPATH_OP_PLUS, ctxt->comp->last, 3, 0);
9441
0
    }
9442
1.80k
}
9443
9444
/**
9445
 * xmlXPathCompMultiplicativeExpr:
9446
 * @ctxt:  the XPath Parser context
9447
 *
9448
 *  [26]   MultiplicativeExpr ::=   UnaryExpr
9449
 *                   | MultiplicativeExpr MultiplyOperator UnaryExpr
9450
 *                   | MultiplicativeExpr 'div' UnaryExpr
9451
 *                   | MultiplicativeExpr 'mod' UnaryExpr
9452
 *  [34]   MultiplyOperator ::=   '*'
9453
 *
9454
 * Compile an Additive expression.
9455
 */
9456
9457
static void
9458
1.80k
xmlXPathCompMultiplicativeExpr(xmlXPathParserContextPtr ctxt) {
9459
1.80k
    xmlXPathCompUnaryExpr(ctxt);
9460
1.80k
    CHECK_ERROR;
9461
1.80k
    SKIP_BLANKS;
9462
1.80k
    while ((CUR == '*') ||
9463
1.80k
           ((CUR == 'd') && (NXT(1) == 'i') && (NXT(2) == 'v')) ||
9464
1.80k
           ((CUR == 'm') && (NXT(1) == 'o') && (NXT(2) == 'd'))) {
9465
0
  int op = -1;
9466
0
  int op1 = ctxt->comp->last;
9467
9468
0
        if (CUR == '*') {
9469
0
      op = 0;
9470
0
      NEXT;
9471
0
  } else if (CUR == 'd') {
9472
0
      op = 1;
9473
0
      SKIP(3);
9474
0
  } else if (CUR == 'm') {
9475
0
      op = 2;
9476
0
      SKIP(3);
9477
0
  }
9478
0
  SKIP_BLANKS;
9479
0
        xmlXPathCompUnaryExpr(ctxt);
9480
0
  CHECK_ERROR;
9481
0
  PUSH_BINARY_EXPR(XPATH_OP_MULT, op1, ctxt->comp->last, op, 0);
9482
0
  SKIP_BLANKS;
9483
0
    }
9484
1.80k
}
9485
9486
/**
9487
 * xmlXPathCompAdditiveExpr:
9488
 * @ctxt:  the XPath Parser context
9489
 *
9490
 *  [25]   AdditiveExpr ::=   MultiplicativeExpr
9491
 *                   | AdditiveExpr '+' MultiplicativeExpr
9492
 *                   | AdditiveExpr '-' MultiplicativeExpr
9493
 *
9494
 * Compile an Additive expression.
9495
 */
9496
9497
static void
9498
1.80k
xmlXPathCompAdditiveExpr(xmlXPathParserContextPtr ctxt) {
9499
9500
1.80k
    xmlXPathCompMultiplicativeExpr(ctxt);
9501
1.80k
    CHECK_ERROR;
9502
1.80k
    SKIP_BLANKS;
9503
1.80k
    while ((CUR == '+') || (CUR == '-')) {
9504
0
  int plus;
9505
0
  int op1 = ctxt->comp->last;
9506
9507
0
        if (CUR == '+') plus = 1;
9508
0
  else plus = 0;
9509
0
  NEXT;
9510
0
  SKIP_BLANKS;
9511
0
        xmlXPathCompMultiplicativeExpr(ctxt);
9512
0
  CHECK_ERROR;
9513
0
  PUSH_BINARY_EXPR(XPATH_OP_PLUS, op1, ctxt->comp->last, plus, 0);
9514
0
  SKIP_BLANKS;
9515
0
    }
9516
1.80k
}
9517
9518
/**
9519
 * xmlXPathCompRelationalExpr:
9520
 * @ctxt:  the XPath Parser context
9521
 *
9522
 *  [24]   RelationalExpr ::=   AdditiveExpr
9523
 *                 | RelationalExpr '<' AdditiveExpr
9524
 *                 | RelationalExpr '>' AdditiveExpr
9525
 *                 | RelationalExpr '<=' AdditiveExpr
9526
 *                 | RelationalExpr '>=' AdditiveExpr
9527
 *
9528
 *  A <= B > C is allowed ? Answer from James, yes with
9529
 *  (AdditiveExpr <= AdditiveExpr) > AdditiveExpr
9530
 *  which is basically what got implemented.
9531
 *
9532
 * Compile a Relational expression, then push the result
9533
 * on the stack
9534
 */
9535
9536
static void
9537
1.80k
xmlXPathCompRelationalExpr(xmlXPathParserContextPtr ctxt) {
9538
1.80k
    xmlXPathCompAdditiveExpr(ctxt);
9539
1.80k
    CHECK_ERROR;
9540
1.80k
    SKIP_BLANKS;
9541
1.80k
    while ((CUR == '<') || (CUR == '>')) {
9542
0
  int inf, strict;
9543
0
  int op1 = ctxt->comp->last;
9544
9545
0
        if (CUR == '<') inf = 1;
9546
0
  else inf = 0;
9547
0
  if (NXT(1) == '=') strict = 0;
9548
0
  else strict = 1;
9549
0
  NEXT;
9550
0
  if (!strict) NEXT;
9551
0
  SKIP_BLANKS;
9552
0
        xmlXPathCompAdditiveExpr(ctxt);
9553
0
  CHECK_ERROR;
9554
0
  PUSH_BINARY_EXPR(XPATH_OP_CMP, op1, ctxt->comp->last, inf, strict);
9555
0
  SKIP_BLANKS;
9556
0
    }
9557
1.80k
}
9558
9559
/**
9560
 * xmlXPathCompEqualityExpr:
9561
 * @ctxt:  the XPath Parser context
9562
 *
9563
 *  [23]   EqualityExpr ::=   RelationalExpr
9564
 *                 | EqualityExpr '=' RelationalExpr
9565
 *                 | EqualityExpr '!=' RelationalExpr
9566
 *
9567
 *  A != B != C is allowed ? Answer from James, yes with
9568
 *  (RelationalExpr = RelationalExpr) = RelationalExpr
9569
 *  (RelationalExpr != RelationalExpr) != RelationalExpr
9570
 *  which is basically what got implemented.
9571
 *
9572
 * Compile an Equality expression.
9573
 *
9574
 */
9575
static void
9576
1.80k
xmlXPathCompEqualityExpr(xmlXPathParserContextPtr ctxt) {
9577
1.80k
    xmlXPathCompRelationalExpr(ctxt);
9578
1.80k
    CHECK_ERROR;
9579
1.80k
    SKIP_BLANKS;
9580
1.80k
    while ((CUR == '=') || ((CUR == '!') && (NXT(1) == '='))) {
9581
0
  int eq;
9582
0
  int op1 = ctxt->comp->last;
9583
9584
0
        if (CUR == '=') eq = 1;
9585
0
  else eq = 0;
9586
0
  NEXT;
9587
0
  if (!eq) NEXT;
9588
0
  SKIP_BLANKS;
9589
0
        xmlXPathCompRelationalExpr(ctxt);
9590
0
  CHECK_ERROR;
9591
0
  PUSH_BINARY_EXPR(XPATH_OP_EQUAL, op1, ctxt->comp->last, eq, 0);
9592
0
  SKIP_BLANKS;
9593
0
    }
9594
1.80k
}
9595
9596
/**
9597
 * xmlXPathCompAndExpr:
9598
 * @ctxt:  the XPath Parser context
9599
 *
9600
 *  [22]   AndExpr ::=   EqualityExpr
9601
 *                 | AndExpr 'and' EqualityExpr
9602
 *
9603
 * Compile an AND expression.
9604
 *
9605
 */
9606
static void
9607
1.80k
xmlXPathCompAndExpr(xmlXPathParserContextPtr ctxt) {
9608
1.80k
    xmlXPathCompEqualityExpr(ctxt);
9609
1.80k
    CHECK_ERROR;
9610
1.80k
    SKIP_BLANKS;
9611
1.80k
    while ((CUR == 'a') && (NXT(1) == 'n') && (NXT(2) == 'd')) {
9612
0
  int op1 = ctxt->comp->last;
9613
0
        SKIP(3);
9614
0
  SKIP_BLANKS;
9615
0
        xmlXPathCompEqualityExpr(ctxt);
9616
0
  CHECK_ERROR;
9617
0
  PUSH_BINARY_EXPR(XPATH_OP_AND, op1, ctxt->comp->last, 0, 0);
9618
0
  SKIP_BLANKS;
9619
0
    }
9620
1.80k
}
9621
9622
/**
9623
 * xmlXPathCompileExpr:
9624
 * @ctxt:  the XPath Parser context
9625
 *
9626
 *  [14]   Expr ::=   OrExpr
9627
 *  [21]   OrExpr ::=   AndExpr
9628
 *                 | OrExpr 'or' AndExpr
9629
 *
9630
 * Parse and compile an expression
9631
 */
9632
static void
9633
1.80k
xmlXPathCompileExpr(xmlXPathParserContextPtr ctxt, int sort) {
9634
1.80k
    xmlXPathContextPtr xpctxt = ctxt->context;
9635
9636
1.80k
    if (xpctxt != NULL) {
9637
1.80k
        if (xpctxt->depth >= XPATH_MAX_RECURSION_DEPTH)
9638
1.80k
            XP_ERROR(XPATH_RECURSION_LIMIT_EXCEEDED);
9639
        /*
9640
         * Parsing a single '(' pushes about 10 functions on the call stack
9641
         * before recursing!
9642
         */
9643
1.80k
        xpctxt->depth += 10;
9644
1.80k
    }
9645
9646
1.80k
    xmlXPathCompAndExpr(ctxt);
9647
1.80k
    CHECK_ERROR;
9648
1.80k
    SKIP_BLANKS;
9649
1.80k
    while ((CUR == 'o') && (NXT(1) == 'r')) {
9650
0
  int op1 = ctxt->comp->last;
9651
0
        SKIP(2);
9652
0
  SKIP_BLANKS;
9653
0
        xmlXPathCompAndExpr(ctxt);
9654
0
  CHECK_ERROR;
9655
0
  PUSH_BINARY_EXPR(XPATH_OP_OR, op1, ctxt->comp->last, 0, 0);
9656
0
  SKIP_BLANKS;
9657
0
    }
9658
1.80k
    if ((sort) && (ctxt->comp->steps[ctxt->comp->last].op != XPATH_OP_VALUE)) {
9659
  /* more ops could be optimized too */
9660
  /*
9661
  * This is the main place to eliminate sorting for
9662
  * operations which don't require a sorted node-set.
9663
  * E.g. count().
9664
  */
9665
726
  PUSH_UNARY_EXPR(XPATH_OP_SORT, ctxt->comp->last , 0, 0);
9666
726
    }
9667
9668
1.80k
    if (xpctxt != NULL)
9669
1.80k
        xpctxt->depth -= 10;
9670
1.80k
}
9671
9672
/**
9673
 * xmlXPathCompPredicate:
9674
 * @ctxt:  the XPath Parser context
9675
 * @filter:  act as a filter
9676
 *
9677
 *  [8]   Predicate ::=   '[' PredicateExpr ']'
9678
 *  [9]   PredicateExpr ::=   Expr
9679
 *
9680
 * Compile a predicate expression
9681
 */
9682
static void
9683
1.08k
xmlXPathCompPredicate(xmlXPathParserContextPtr ctxt, int filter) {
9684
1.08k
    int op1 = ctxt->comp->last;
9685
9686
1.08k
    SKIP_BLANKS;
9687
1.08k
    if (CUR != '[') {
9688
0
  XP_ERROR(XPATH_INVALID_PREDICATE_ERROR);
9689
0
    }
9690
1.08k
    NEXT;
9691
1.08k
    SKIP_BLANKS;
9692
9693
1.08k
    ctxt->comp->last = -1;
9694
    /*
9695
    * This call to xmlXPathCompileExpr() will deactivate sorting
9696
    * of the predicate result.
9697
    * TODO: Sorting is still activated for filters, since I'm not
9698
    *  sure if needed. Normally sorting should not be needed, since
9699
    *  a filter can only diminish the number of items in a sequence,
9700
    *  but won't change its order; so if the initial sequence is sorted,
9701
    *  subsequent sorting is not needed.
9702
    */
9703
1.08k
    if (! filter)
9704
1.08k
  xmlXPathCompileExpr(ctxt, 0);
9705
0
    else
9706
0
  xmlXPathCompileExpr(ctxt, 1);
9707
1.08k
    CHECK_ERROR;
9708
9709
1.08k
    if (CUR != ']') {
9710
0
  XP_ERROR(XPATH_INVALID_PREDICATE_ERROR);
9711
0
    }
9712
9713
1.08k
    if (filter)
9714
0
  PUSH_BINARY_EXPR(XPATH_OP_FILTER, op1, ctxt->comp->last, 0, 0);
9715
1.08k
    else
9716
1.08k
  PUSH_BINARY_EXPR(XPATH_OP_PREDICATE, op1, ctxt->comp->last, 0, 0);
9717
9718
1.08k
    NEXT;
9719
1.08k
    SKIP_BLANKS;
9720
1.08k
}
9721
9722
/**
9723
 * xmlXPathCompNodeTest:
9724
 * @ctxt:  the XPath Parser context
9725
 * @test:  pointer to a xmlXPathTestVal
9726
 * @type:  pointer to a xmlXPathTypeVal
9727
 * @prefix:  placeholder for a possible name prefix
9728
 *
9729
 * [7] NodeTest ::=   NameTest
9730
 *        | NodeType '(' ')'
9731
 *        | 'processing-instruction' '(' Literal ')'
9732
 *
9733
 * [37] NameTest ::=  '*'
9734
 *        | NCName ':' '*'
9735
 *        | QName
9736
 * [38] NodeType ::= 'comment'
9737
 *       | 'text'
9738
 *       | 'processing-instruction'
9739
 *       | 'node'
9740
 *
9741
 * Returns the name found and updates @test, @type and @prefix appropriately
9742
 */
9743
static xmlChar *
9744
xmlXPathCompNodeTest(xmlXPathParserContextPtr ctxt, xmlXPathTestVal *test,
9745
               xmlXPathTypeVal *type, xmlChar **prefix,
9746
1.26k
         xmlChar *name) {
9747
1.26k
    int blanks;
9748
9749
1.26k
    if ((test == NULL) || (type == NULL) || (prefix == NULL)) {
9750
0
  return(NULL);
9751
0
    }
9752
1.26k
    *type = (xmlXPathTypeVal) 0;
9753
1.26k
    *test = (xmlXPathTestVal) 0;
9754
1.26k
    *prefix = NULL;
9755
1.26k
    SKIP_BLANKS;
9756
9757
1.26k
    if ((name == NULL) && (CUR == '*')) {
9758
  /*
9759
   * All elements
9760
   */
9761
0
  NEXT;
9762
0
  *test = NODE_TEST_ALL;
9763
0
  return(NULL);
9764
0
    }
9765
9766
1.26k
    if (name == NULL)
9767
93
  name = xmlXPathParseNCName(ctxt);
9768
1.26k
    if (name == NULL) {
9769
0
  XP_ERRORNULL(XPATH_EXPR_ERROR);
9770
0
    }
9771
9772
1.26k
    blanks = IS_BLANK_CH(CUR);
9773
1.26k
    SKIP_BLANKS;
9774
1.26k
    if (CUR == '(') {
9775
0
  NEXT;
9776
  /*
9777
   * NodeType or PI search
9778
   */
9779
0
  if (xmlStrEqual(name, BAD_CAST "comment"))
9780
0
      *type = NODE_TYPE_COMMENT;
9781
0
  else if (xmlStrEqual(name, BAD_CAST "node"))
9782
0
      *type = NODE_TYPE_NODE;
9783
0
  else if (xmlStrEqual(name, BAD_CAST "processing-instruction"))
9784
0
      *type = NODE_TYPE_PI;
9785
0
  else if (xmlStrEqual(name, BAD_CAST "text"))
9786
0
      *type = NODE_TYPE_TEXT;
9787
0
  else {
9788
0
      if (name != NULL)
9789
0
    xmlFree(name);
9790
0
      XP_ERRORNULL(XPATH_EXPR_ERROR);
9791
0
  }
9792
9793
0
  *test = NODE_TEST_TYPE;
9794
9795
0
  SKIP_BLANKS;
9796
0
  if (*type == NODE_TYPE_PI) {
9797
      /*
9798
       * Specific case: search a PI by name.
9799
       */
9800
0
      if (name != NULL)
9801
0
    xmlFree(name);
9802
0
      name = NULL;
9803
0
      if (CUR != ')') {
9804
0
    name = xmlXPathParseLiteral(ctxt);
9805
0
    *test = NODE_TEST_PI;
9806
0
    SKIP_BLANKS;
9807
0
      }
9808
0
  }
9809
0
  if (CUR != ')') {
9810
0
      if (name != NULL)
9811
0
    xmlFree(name);
9812
0
      XP_ERRORNULL(XPATH_UNCLOSED_ERROR);
9813
0
  }
9814
0
  NEXT;
9815
0
  return(name);
9816
0
    }
9817
1.26k
    *test = NODE_TEST_NAME;
9818
1.26k
    if ((!blanks) && (CUR == ':')) {
9819
1.26k
  NEXT;
9820
9821
  /*
9822
   * Since currently the parser context don't have a
9823
   * namespace list associated:
9824
   * The namespace name for this prefix can be computed
9825
   * only at evaluation time. The compilation is done
9826
   * outside of any context.
9827
   */
9828
1.26k
  *prefix = name;
9829
9830
1.26k
  if (CUR == '*') {
9831
      /*
9832
       * All elements
9833
       */
9834
0
      NEXT;
9835
0
      *test = NODE_TEST_ALL;
9836
0
      return(NULL);
9837
0
  }
9838
9839
1.26k
  name = xmlXPathParseNCName(ctxt);
9840
1.26k
  if (name == NULL) {
9841
0
      XP_ERRORNULL(XPATH_EXPR_ERROR);
9842
0
  }
9843
1.26k
    }
9844
1.26k
    return(name);
9845
1.26k
}
9846
9847
/**
9848
 * xmlXPathIsAxisName:
9849
 * @name:  a preparsed name token
9850
 *
9851
 * [6] AxisName ::=   'ancestor'
9852
 *                  | 'ancestor-or-self'
9853
 *                  | 'attribute'
9854
 *                  | 'child'
9855
 *                  | 'descendant'
9856
 *                  | 'descendant-or-self'
9857
 *                  | 'following'
9858
 *                  | 'following-sibling'
9859
 *                  | 'namespace'
9860
 *                  | 'parent'
9861
 *                  | 'preceding'
9862
 *                  | 'preceding-sibling'
9863
 *                  | 'self'
9864
 *
9865
 * Returns the axis or 0
9866
 */
9867
static xmlXPathAxisVal
9868
1.17k
xmlXPathIsAxisName(const xmlChar *name) {
9869
1.17k
    xmlXPathAxisVal ret = (xmlXPathAxisVal) 0;
9870
1.17k
    switch (name[0]) {
9871
0
  case 'a':
9872
0
      if (xmlStrEqual(name, BAD_CAST "ancestor"))
9873
0
    ret = AXIS_ANCESTOR;
9874
0
      if (xmlStrEqual(name, BAD_CAST "ancestor-or-self"))
9875
0
    ret = AXIS_ANCESTOR_OR_SELF;
9876
0
      if (xmlStrEqual(name, BAD_CAST "attribute"))
9877
0
    ret = AXIS_ATTRIBUTE;
9878
0
      break;
9879
0
  case 'c':
9880
0
      if (xmlStrEqual(name, BAD_CAST "child"))
9881
0
    ret = AXIS_CHILD;
9882
0
      break;
9883
93
  case 'd':
9884
93
      if (xmlStrEqual(name, BAD_CAST "descendant"))
9885
0
    ret = AXIS_DESCENDANT;
9886
93
      if (xmlStrEqual(name, BAD_CAST "descendant-or-self"))
9887
0
    ret = AXIS_DESCENDANT_OR_SELF;
9888
93
      break;
9889
0
  case 'f':
9890
0
      if (xmlStrEqual(name, BAD_CAST "following"))
9891
0
    ret = AXIS_FOLLOWING;
9892
0
      if (xmlStrEqual(name, BAD_CAST "following-sibling"))
9893
0
    ret = AXIS_FOLLOWING_SIBLING;
9894
0
      break;
9895
1.08k
  case 'n':
9896
1.08k
      if (xmlStrEqual(name, BAD_CAST "namespace"))
9897
0
    ret = AXIS_NAMESPACE;
9898
1.08k
      break;
9899
0
  case 'p':
9900
0
      if (xmlStrEqual(name, BAD_CAST "parent"))
9901
0
    ret = AXIS_PARENT;
9902
0
      if (xmlStrEqual(name, BAD_CAST "preceding"))
9903
0
    ret = AXIS_PRECEDING;
9904
0
      if (xmlStrEqual(name, BAD_CAST "preceding-sibling"))
9905
0
    ret = AXIS_PRECEDING_SIBLING;
9906
0
      break;
9907
0
  case 's':
9908
0
      if (xmlStrEqual(name, BAD_CAST "self"))
9909
0
    ret = AXIS_SELF;
9910
0
      break;
9911
1.17k
    }
9912
1.17k
    return(ret);
9913
1.17k
}
9914
9915
/**
9916
 * xmlXPathCompStep:
9917
 * @ctxt:  the XPath Parser context
9918
 *
9919
 * [4] Step ::=   AxisSpecifier NodeTest Predicate*
9920
 *                  | AbbreviatedStep
9921
 *
9922
 * [12] AbbreviatedStep ::=   '.' | '..'
9923
 *
9924
 * [5] AxisSpecifier ::= AxisName '::'
9925
 *                  | AbbreviatedAxisSpecifier
9926
 *
9927
 * [13] AbbreviatedAxisSpecifier ::= '@'?
9928
 *
9929
 * Modified for XPtr range support as:
9930
 *
9931
 *  [4xptr] Step ::= AxisSpecifier NodeTest Predicate*
9932
 *                     | AbbreviatedStep
9933
 *                     | 'range-to' '(' Expr ')' Predicate*
9934
 *
9935
 * Compile one step in a Location Path
9936
 * A location step of . is short for self::node(). This is
9937
 * particularly useful in conjunction with //. For example, the
9938
 * location path .//para is short for
9939
 * self::node()/descendant-or-self::node()/child::para
9940
 * and so will select all para descendant elements of the context
9941
 * node.
9942
 * Similarly, a location step of .. is short for parent::node().
9943
 * For example, ../title is short for parent::node()/child::title
9944
 * and so will select the title children of the parent of the context
9945
 * node.
9946
 */
9947
static void
9948
1.26k
xmlXPathCompStep(xmlXPathParserContextPtr ctxt) {
9949
1.26k
    SKIP_BLANKS;
9950
1.26k
    if ((CUR == '.') && (NXT(1) == '.')) {
9951
0
  SKIP(2);
9952
0
  SKIP_BLANKS;
9953
0
  PUSH_LONG_EXPR(XPATH_OP_COLLECT, AXIS_PARENT,
9954
0
        NODE_TEST_TYPE, NODE_TYPE_NODE, NULL, NULL);
9955
1.26k
    } else if (CUR == '.') {
9956
0
  NEXT;
9957
0
  SKIP_BLANKS;
9958
1.26k
    } else {
9959
1.26k
  xmlChar *name = NULL;
9960
1.26k
  xmlChar *prefix = NULL;
9961
1.26k
  xmlXPathTestVal test = (xmlXPathTestVal) 0;
9962
1.26k
  xmlXPathAxisVal axis = (xmlXPathAxisVal) 0;
9963
1.26k
  xmlXPathTypeVal type = (xmlXPathTypeVal) 0;
9964
1.26k
  int op1;
9965
9966
1.26k
  if (CUR == '*') {
9967
0
      axis = AXIS_CHILD;
9968
1.26k
  } else {
9969
1.26k
      if (name == NULL)
9970
1.26k
    name = xmlXPathParseNCName(ctxt);
9971
1.26k
      if (name != NULL) {
9972
1.17k
    axis = xmlXPathIsAxisName(name);
9973
1.17k
    if (axis != 0) {
9974
0
        SKIP_BLANKS;
9975
0
        if ((CUR == ':') && (NXT(1) == ':')) {
9976
0
      SKIP(2);
9977
0
      xmlFree(name);
9978
0
      name = NULL;
9979
0
        } else {
9980
      /* an element name can conflict with an axis one :-\ */
9981
0
      axis = AXIS_CHILD;
9982
0
        }
9983
1.17k
    } else {
9984
1.17k
        axis = AXIS_CHILD;
9985
1.17k
    }
9986
1.17k
      } else if (CUR == '@') {
9987
93
    NEXT;
9988
93
    axis = AXIS_ATTRIBUTE;
9989
93
      } else {
9990
0
    axis = AXIS_CHILD;
9991
0
      }
9992
1.26k
  }
9993
9994
1.26k
        if (ctxt->error != XPATH_EXPRESSION_OK) {
9995
0
            xmlFree(name);
9996
0
            return;
9997
0
        }
9998
9999
1.26k
  name = xmlXPathCompNodeTest(ctxt, &test, &type, &prefix, name);
10000
1.26k
  if (test == 0)
10001
0
      return;
10002
10003
1.26k
        if ((prefix != NULL) && (ctxt->context != NULL) &&
10004
1.26k
      (ctxt->context->flags & XML_XPATH_CHECKNS)) {
10005
0
      if (xmlXPathNsLookup(ctxt->context, prefix) == NULL) {
10006
0
    xmlXPathErr(ctxt, XPATH_UNDEF_PREFIX_ERROR);
10007
0
      }
10008
0
  }
10009
10010
1.26k
  op1 = ctxt->comp->last;
10011
1.26k
  ctxt->comp->last = -1;
10012
10013
1.26k
  SKIP_BLANKS;
10014
2.34k
  while (CUR == '[') {
10015
1.08k
      xmlXPathCompPredicate(ctxt, 0);
10016
1.08k
  }
10017
10018
1.26k
        if (PUSH_FULL_EXPR(XPATH_OP_COLLECT, op1, ctxt->comp->last, axis,
10019
1.26k
                           test, type, (void *)prefix, (void *)name) == -1) {
10020
0
            xmlFree(prefix);
10021
0
            xmlFree(name);
10022
0
        }
10023
1.26k
    }
10024
1.26k
}
10025
10026
/**
10027
 * xmlXPathCompRelativeLocationPath:
10028
 * @ctxt:  the XPath Parser context
10029
 *
10030
 *  [3]   RelativeLocationPath ::=   Step
10031
 *                     | RelativeLocationPath '/' Step
10032
 *                     | AbbreviatedRelativeLocationPath
10033
 *  [11]  AbbreviatedRelativeLocationPath ::=   RelativeLocationPath '//' Step
10034
 *
10035
 * Compile a relative location path.
10036
 */
10037
static void
10038
xmlXPathCompRelativeLocationPath
10039
633
(xmlXPathParserContextPtr ctxt) {
10040
633
    SKIP_BLANKS;
10041
633
    if ((CUR == '/') && (NXT(1) == '/')) {
10042
0
  SKIP(2);
10043
0
  SKIP_BLANKS;
10044
0
  PUSH_LONG_EXPR(XPATH_OP_COLLECT, AXIS_DESCENDANT_OR_SELF,
10045
0
             NODE_TEST_TYPE, NODE_TYPE_NODE, NULL, NULL);
10046
633
    } else if (CUR == '/') {
10047
0
      NEXT;
10048
0
  SKIP_BLANKS;
10049
0
    }
10050
633
    xmlXPathCompStep(ctxt);
10051
633
    CHECK_ERROR;
10052
633
    SKIP_BLANKS;
10053
1.26k
    while (CUR == '/') {
10054
633
  if ((CUR == '/') && (NXT(1) == '/')) {
10055
0
      SKIP(2);
10056
0
      SKIP_BLANKS;
10057
0
      PUSH_LONG_EXPR(XPATH_OP_COLLECT, AXIS_DESCENDANT_OR_SELF,
10058
0
           NODE_TEST_TYPE, NODE_TYPE_NODE, NULL, NULL);
10059
0
      xmlXPathCompStep(ctxt);
10060
633
  } else if (CUR == '/') {
10061
633
      NEXT;
10062
633
      SKIP_BLANKS;
10063
633
      xmlXPathCompStep(ctxt);
10064
633
  }
10065
633
  SKIP_BLANKS;
10066
633
    }
10067
633
}
10068
10069
/**
10070
 * xmlXPathCompLocationPath:
10071
 * @ctxt:  the XPath Parser context
10072
 *
10073
 *  [1]   LocationPath ::=   RelativeLocationPath
10074
 *                     | AbsoluteLocationPath
10075
 *  [2]   AbsoluteLocationPath ::=   '/' RelativeLocationPath?
10076
 *                     | AbbreviatedAbsoluteLocationPath
10077
 *  [10]   AbbreviatedAbsoluteLocationPath ::=
10078
 *                           '//' RelativeLocationPath
10079
 *
10080
 * Compile a location path
10081
 *
10082
 * // is short for /descendant-or-self::node()/. For example,
10083
 * //para is short for /descendant-or-self::node()/child::para and
10084
 * so will select any para element in the document (even a para element
10085
 * that is a document element will be selected by //para since the
10086
 * document element node is a child of the root node); div//para is
10087
 * short for div/descendant-or-self::node()/child::para and so will
10088
 * select all para descendants of div children.
10089
 */
10090
static void
10091
633
xmlXPathCompLocationPath(xmlXPathParserContextPtr ctxt) {
10092
633
    SKIP_BLANKS;
10093
633
    if (CUR != '/') {
10094
0
        xmlXPathCompRelativeLocationPath(ctxt);
10095
633
    } else {
10096
1.26k
  while (CUR == '/') {
10097
633
      if ((CUR == '/') && (NXT(1) == '/')) {
10098
0
    SKIP(2);
10099
0
    SKIP_BLANKS;
10100
0
    PUSH_LONG_EXPR(XPATH_OP_COLLECT, AXIS_DESCENDANT_OR_SELF,
10101
0
           NODE_TEST_TYPE, NODE_TYPE_NODE, NULL, NULL);
10102
0
    xmlXPathCompRelativeLocationPath(ctxt);
10103
633
      } else if (CUR == '/') {
10104
633
    NEXT;
10105
633
    SKIP_BLANKS;
10106
633
    if ((CUR != 0) &&
10107
633
        ((IS_ASCII_LETTER(CUR)) || (CUR >= 0x80) ||
10108
0
                     (CUR == '_') || (CUR == '.') ||
10109
0
         (CUR == '@') || (CUR == '*')))
10110
633
        xmlXPathCompRelativeLocationPath(ctxt);
10111
633
      }
10112
633
      CHECK_ERROR;
10113
633
  }
10114
633
    }
10115
633
}
10116
10117
/************************************************************************
10118
 *                  *
10119
 *    XPath precompiled expression evaluation     *
10120
 *                  *
10121
 ************************************************************************/
10122
10123
static int
10124
xmlXPathCompOpEval(xmlXPathParserContextPtr ctxt, xmlXPathStepOpPtr op);
10125
10126
/**
10127
 * xmlXPathNodeSetFilter:
10128
 * @ctxt:  the XPath Parser context
10129
 * @set: the node set to filter
10130
 * @filterOpIndex: the index of the predicate/filter op
10131
 * @minPos: minimum position in the filtered set (1-based)
10132
 * @maxPos: maximum position in the filtered set (1-based)
10133
 * @hasNsNodes: true if the node set may contain namespace nodes
10134
 *
10135
 * Filter a node set, keeping only nodes for which the predicate expression
10136
 * matches. Afterwards, keep only nodes between minPos and maxPos in the
10137
 * filtered result.
10138
 */
10139
static void
10140
xmlXPathNodeSetFilter(xmlXPathParserContextPtr ctxt,
10141
          xmlNodeSetPtr set,
10142
          int filterOpIndex,
10143
                      int minPos, int maxPos,
10144
          int hasNsNodes)
10145
0
{
10146
0
    xmlXPathContextPtr xpctxt;
10147
0
    xmlNodePtr oldnode;
10148
0
    xmlDocPtr olddoc;
10149
0
    xmlXPathStepOpPtr filterOp;
10150
0
    int oldcs, oldpp;
10151
0
    int i, j, pos;
10152
10153
0
    if ((set == NULL) || (set->nodeNr == 0))
10154
0
        return;
10155
10156
    /*
10157
    * Check if the node set contains a sufficient number of nodes for
10158
    * the requested range.
10159
    */
10160
0
    if (set->nodeNr < minPos) {
10161
0
        xmlXPathNodeSetClear(set, hasNsNodes);
10162
0
        return;
10163
0
    }
10164
10165
0
    xpctxt = ctxt->context;
10166
0
    oldnode = xpctxt->node;
10167
0
    olddoc = xpctxt->doc;
10168
0
    oldcs = xpctxt->contextSize;
10169
0
    oldpp = xpctxt->proximityPosition;
10170
0
    filterOp = &ctxt->comp->steps[filterOpIndex];
10171
10172
0
    xpctxt->contextSize = set->nodeNr;
10173
10174
0
    for (i = 0, j = 0, pos = 1; i < set->nodeNr; i++) {
10175
0
        xmlNodePtr node = set->nodeTab[i];
10176
0
        int res;
10177
10178
0
        xpctxt->node = node;
10179
0
        xpctxt->proximityPosition = i + 1;
10180
10181
        /*
10182
        * Also set the xpath document in case things like
10183
        * key() are evaluated in the predicate.
10184
        *
10185
        * TODO: Get real doc for namespace nodes.
10186
        */
10187
0
        if ((node->type != XML_NAMESPACE_DECL) &&
10188
0
            (node->doc != NULL))
10189
0
            xpctxt->doc = node->doc;
10190
10191
0
        res = xmlXPathCompOpEvalToBoolean(ctxt, filterOp, 1);
10192
10193
0
        if (ctxt->error != XPATH_EXPRESSION_OK)
10194
0
            break;
10195
0
        if (res < 0) {
10196
            /* Shouldn't happen */
10197
0
            xmlXPathErr(ctxt, XPATH_EXPR_ERROR);
10198
0
            break;
10199
0
        }
10200
10201
0
        if ((res != 0) && ((pos >= minPos) && (pos <= maxPos))) {
10202
0
            if (i != j) {
10203
0
                set->nodeTab[j] = node;
10204
0
                set->nodeTab[i] = NULL;
10205
0
            }
10206
10207
0
            j += 1;
10208
0
        } else {
10209
            /* Remove the entry from the initial node set. */
10210
0
            set->nodeTab[i] = NULL;
10211
0
            if (node->type == XML_NAMESPACE_DECL)
10212
0
                xmlXPathNodeSetFreeNs((xmlNsPtr) node);
10213
0
        }
10214
10215
0
        if (res != 0) {
10216
0
            if (pos == maxPos) {
10217
0
                i += 1;
10218
0
                break;
10219
0
            }
10220
10221
0
            pos += 1;
10222
0
        }
10223
0
    }
10224
10225
    /* Free remaining nodes. */
10226
0
    if (hasNsNodes) {
10227
0
        for (; i < set->nodeNr; i++) {
10228
0
            xmlNodePtr node = set->nodeTab[i];
10229
0
            if ((node != NULL) && (node->type == XML_NAMESPACE_DECL))
10230
0
                xmlXPathNodeSetFreeNs((xmlNsPtr) node);
10231
0
        }
10232
0
    }
10233
10234
0
    set->nodeNr = j;
10235
10236
    /* If too many elements were removed, shrink table to preserve memory. */
10237
0
    if ((set->nodeMax > XML_NODESET_DEFAULT) &&
10238
0
        (set->nodeNr < set->nodeMax / 2)) {
10239
0
        xmlNodePtr *tmp;
10240
0
        int nodeMax = set->nodeNr;
10241
10242
0
        if (nodeMax < XML_NODESET_DEFAULT)
10243
0
            nodeMax = XML_NODESET_DEFAULT;
10244
0
        tmp = (xmlNodePtr *) xmlRealloc(set->nodeTab,
10245
0
                nodeMax * sizeof(xmlNodePtr));
10246
0
        if (tmp == NULL) {
10247
0
            xmlXPathPErrMemory(ctxt);
10248
0
        } else {
10249
0
            set->nodeTab = tmp;
10250
0
            set->nodeMax = nodeMax;
10251
0
        }
10252
0
    }
10253
10254
0
    xpctxt->node = oldnode;
10255
0
    xpctxt->doc = olddoc;
10256
0
    xpctxt->contextSize = oldcs;
10257
0
    xpctxt->proximityPosition = oldpp;
10258
0
}
10259
10260
/**
10261
 * xmlXPathCompOpEvalPredicate:
10262
 * @ctxt:  the XPath Parser context
10263
 * @op: the predicate op
10264
 * @set: the node set to filter
10265
 * @minPos: minimum position in the filtered set (1-based)
10266
 * @maxPos: maximum position in the filtered set (1-based)
10267
 * @hasNsNodes: true if the node set may contain namespace nodes
10268
 *
10269
 * Filter a node set, keeping only nodes for which the sequence of predicate
10270
 * expressions matches. Afterwards, keep only nodes between minPos and maxPos
10271
 * in the filtered result.
10272
 */
10273
static void
10274
xmlXPathCompOpEvalPredicate(xmlXPathParserContextPtr ctxt,
10275
          xmlXPathStepOpPtr op,
10276
          xmlNodeSetPtr set,
10277
                            int minPos, int maxPos,
10278
          int hasNsNodes)
10279
0
{
10280
0
    if (op->ch1 != -1) {
10281
0
  xmlXPathCompExprPtr comp = ctxt->comp;
10282
  /*
10283
  * Process inner predicates first.
10284
  */
10285
0
  if (comp->steps[op->ch1].op != XPATH_OP_PREDICATE) {
10286
0
            XP_ERROR(XPATH_INVALID_OPERAND);
10287
0
  }
10288
0
        if (ctxt->context->depth >= XPATH_MAX_RECURSION_DEPTH)
10289
0
            XP_ERROR(XPATH_RECURSION_LIMIT_EXCEEDED);
10290
0
        ctxt->context->depth += 1;
10291
0
  xmlXPathCompOpEvalPredicate(ctxt, &comp->steps[op->ch1], set,
10292
0
                                    1, set->nodeNr, hasNsNodes);
10293
0
        ctxt->context->depth -= 1;
10294
0
  CHECK_ERROR;
10295
0
    }
10296
10297
0
    if (op->ch2 != -1)
10298
0
        xmlXPathNodeSetFilter(ctxt, set, op->ch2, minPos, maxPos, hasNsNodes);
10299
0
}
10300
10301
static int
10302
xmlXPathIsPositionalPredicate(xmlXPathParserContextPtr ctxt,
10303
          xmlXPathStepOpPtr op,
10304
          int *maxPos)
10305
731
{
10306
10307
731
    xmlXPathStepOpPtr exprOp;
10308
10309
    /*
10310
    * BIG NOTE: This is not intended for XPATH_OP_FILTER yet!
10311
    */
10312
10313
    /*
10314
    * If not -1, then ch1 will point to:
10315
    * 1) For predicates (XPATH_OP_PREDICATE):
10316
    *    - an inner predicate operator
10317
    * 2) For filters (XPATH_OP_FILTER):
10318
    *    - an inner filter operator OR
10319
    *    - an expression selecting the node set.
10320
    *      E.g. "key('a', 'b')" or "(//foo | //bar)".
10321
    */
10322
731
    if ((op->op != XPATH_OP_PREDICATE) && (op->op != XPATH_OP_FILTER))
10323
0
  return(0);
10324
10325
731
    if (op->ch2 != -1) {
10326
731
  exprOp = &ctxt->comp->steps[op->ch2];
10327
731
    } else
10328
0
  return(0);
10329
10330
731
    if ((exprOp != NULL) &&
10331
731
  (exprOp->op == XPATH_OP_VALUE) &&
10332
731
  (exprOp->value4 != NULL) &&
10333
731
  (((xmlXPathObjectPtr) exprOp->value4)->type == XPATH_NUMBER))
10334
731
    {
10335
731
        double floatval = ((xmlXPathObjectPtr) exprOp->value4)->floatval;
10336
10337
  /*
10338
  * We have a "[n]" predicate here.
10339
  * TODO: Unfortunately this simplistic test here is not
10340
  * able to detect a position() predicate in compound
10341
  * expressions like "[@attr = 'a" and position() = 1],
10342
  * and even not the usage of position() in
10343
  * "[position() = 1]"; thus - obviously - a position-range,
10344
  * like it "[position() < 5]", is also not detected.
10345
  * Maybe we could rewrite the AST to ease the optimization.
10346
  */
10347
10348
731
        if ((floatval > INT_MIN) && (floatval < INT_MAX)) {
10349
731
      *maxPos = (int) floatval;
10350
731
            if (floatval == (double) *maxPos)
10351
731
                return(1);
10352
731
        }
10353
731
    }
10354
0
    return(0);
10355
731
}
10356
10357
static int
10358
xmlXPathNodeCollectAndTest(xmlXPathParserContextPtr ctxt,
10359
                           xmlXPathStepOpPtr op,
10360
         xmlNodePtr * first, xmlNodePtr * last,
10361
         int toBool)
10362
1.26k
{
10363
10364
1.26k
#define XP_TEST_HIT \
10365
1.26k
    if (hasAxisRange != 0) { \
10366
382
  if (++pos == maxPos) { \
10367
382
      if (addNode(seq, cur) < 0) \
10368
382
          xmlXPathPErrMemory(ctxt); \
10369
382
      goto axis_range_end; } \
10370
382
    } else { \
10371
186
  if (addNode(seq, cur) < 0) \
10372
186
      xmlXPathPErrMemory(ctxt); \
10373
186
  if (breakOnFirstHit) goto first_hit; }
10374
10375
1.26k
#define XP_TEST_HIT_NS \
10376
1.26k
    if (hasAxisRange != 0) { \
10377
0
  if (++pos == maxPos) { \
10378
0
      hasNsNodes = 1; \
10379
0
      if (xmlXPathNodeSetAddNs(seq, xpctxt->node, (xmlNsPtr) cur) < 0) \
10380
0
          xmlXPathPErrMemory(ctxt); \
10381
0
  goto axis_range_end; } \
10382
0
    } else { \
10383
0
  hasNsNodes = 1; \
10384
0
  if (xmlXPathNodeSetAddNs(seq, xpctxt->node, (xmlNsPtr) cur) < 0) \
10385
0
      xmlXPathPErrMemory(ctxt); \
10386
0
  if (breakOnFirstHit) goto first_hit; }
10387
10388
1.26k
    xmlXPathAxisVal axis = (xmlXPathAxisVal) op->value;
10389
1.26k
    xmlXPathTestVal test = (xmlXPathTestVal) op->value2;
10390
1.26k
    xmlXPathTypeVal type = (xmlXPathTypeVal) op->value3;
10391
1.26k
    const xmlChar *prefix = op->value4;
10392
1.26k
    const xmlChar *name = op->value5;
10393
1.26k
    const xmlChar *URI = NULL;
10394
10395
1.26k
    int total = 0, hasNsNodes = 0;
10396
    /* The popped object holding the context nodes */
10397
1.26k
    xmlXPathObjectPtr obj;
10398
    /* The set of context nodes for the node tests */
10399
1.26k
    xmlNodeSetPtr contextSeq;
10400
1.26k
    int contextIdx;
10401
1.26k
    xmlNodePtr contextNode;
10402
    /* The final resulting node set wrt to all context nodes */
10403
1.26k
    xmlNodeSetPtr outSeq;
10404
    /*
10405
    * The temporary resulting node set wrt 1 context node.
10406
    * Used to feed predicate evaluation.
10407
    */
10408
1.26k
    xmlNodeSetPtr seq;
10409
1.26k
    xmlNodePtr cur;
10410
    /* First predicate operator */
10411
1.26k
    xmlXPathStepOpPtr predOp;
10412
1.26k
    int maxPos; /* The requested position() (when a "[n]" predicate) */
10413
1.26k
    int hasPredicateRange, hasAxisRange, pos;
10414
1.26k
    int breakOnFirstHit;
10415
10416
1.26k
    xmlXPathTraversalFunction next = NULL;
10417
1.26k
    int (*addNode) (xmlNodeSetPtr, xmlNodePtr);
10418
1.26k
    xmlXPathNodeSetMergeFunction mergeAndClear;
10419
1.26k
    xmlNodePtr oldContextNode;
10420
1.26k
    xmlXPathContextPtr xpctxt = ctxt->context;
10421
10422
10423
1.26k
    CHECK_TYPE0(XPATH_NODESET);
10424
1.26k
    obj = xmlXPathValuePop(ctxt);
10425
    /*
10426
    * Setup namespaces.
10427
    */
10428
1.26k
    if (prefix != NULL) {
10429
1.26k
        URI = xmlXPathNsLookup(xpctxt, prefix);
10430
1.26k
        if (URI == NULL) {
10431
0
      xmlXPathReleaseObject(xpctxt, obj);
10432
0
            XP_ERROR0(XPATH_UNDEF_PREFIX_ERROR);
10433
0
  }
10434
1.26k
    }
10435
    /*
10436
    * Setup axis.
10437
    *
10438
    * MAYBE FUTURE TODO: merging optimizations:
10439
    * - If the nodes to be traversed wrt to the initial nodes and
10440
    *   the current axis cannot overlap, then we could avoid searching
10441
    *   for duplicates during the merge.
10442
    *   But the question is how/when to evaluate if they cannot overlap.
10443
    *   Example: if we know that for two initial nodes, the one is
10444
    *   not in the ancestor-or-self axis of the other, then we could safely
10445
    *   avoid a duplicate-aware merge, if the axis to be traversed is e.g.
10446
    *   the descendant-or-self axis.
10447
    */
10448
1.26k
    mergeAndClear = xmlXPathNodeSetMergeAndClear;
10449
1.26k
    switch (axis) {
10450
0
        case AXIS_ANCESTOR:
10451
0
            first = NULL;
10452
0
            next = xmlXPathNextAncestor;
10453
0
            break;
10454
0
        case AXIS_ANCESTOR_OR_SELF:
10455
0
            first = NULL;
10456
0
            next = xmlXPathNextAncestorOrSelf;
10457
0
            break;
10458
93
        case AXIS_ATTRIBUTE:
10459
93
            first = NULL;
10460
93
      last = NULL;
10461
93
            next = xmlXPathNextAttribute;
10462
93
      mergeAndClear = xmlXPathNodeSetMergeAndClearNoDupls;
10463
93
            break;
10464
1.17k
        case AXIS_CHILD:
10465
1.17k
      last = NULL;
10466
1.17k
      if (((test == NODE_TEST_NAME) || (test == NODE_TEST_ALL)) &&
10467
1.17k
    (type == NODE_TYPE_NODE))
10468
1.17k
      {
10469
    /*
10470
    * Optimization if an element node type is 'element'.
10471
    */
10472
1.17k
    next = xmlXPathNextChildElement;
10473
1.17k
      } else
10474
0
    next = xmlXPathNextChild;
10475
1.17k
      mergeAndClear = xmlXPathNodeSetMergeAndClearNoDupls;
10476
1.17k
            break;
10477
0
        case AXIS_DESCENDANT:
10478
0
      last = NULL;
10479
0
            next = xmlXPathNextDescendant;
10480
0
            break;
10481
0
        case AXIS_DESCENDANT_OR_SELF:
10482
0
      last = NULL;
10483
0
            next = xmlXPathNextDescendantOrSelf;
10484
0
            break;
10485
0
        case AXIS_FOLLOWING:
10486
0
      last = NULL;
10487
0
            next = xmlXPathNextFollowing;
10488
0
            break;
10489
0
        case AXIS_FOLLOWING_SIBLING:
10490
0
      last = NULL;
10491
0
            next = xmlXPathNextFollowingSibling;
10492
0
            break;
10493
0
        case AXIS_NAMESPACE:
10494
0
            first = NULL;
10495
0
      last = NULL;
10496
0
            next = (xmlXPathTraversalFunction) xmlXPathNextNamespace;
10497
0
      mergeAndClear = xmlXPathNodeSetMergeAndClearNoDupls;
10498
0
            break;
10499
0
        case AXIS_PARENT:
10500
0
            first = NULL;
10501
0
            next = xmlXPathNextParent;
10502
0
            break;
10503
0
        case AXIS_PRECEDING:
10504
0
            first = NULL;
10505
0
            next = xmlXPathNextPrecedingInternal;
10506
0
            break;
10507
0
        case AXIS_PRECEDING_SIBLING:
10508
0
            first = NULL;
10509
0
            next = xmlXPathNextPrecedingSibling;
10510
0
            break;
10511
0
        case AXIS_SELF:
10512
0
            first = NULL;
10513
0
      last = NULL;
10514
0
            next = xmlXPathNextSelf;
10515
0
      mergeAndClear = xmlXPathNodeSetMergeAndClearNoDupls;
10516
0
            break;
10517
1.26k
    }
10518
10519
1.26k
    if (next == NULL) {
10520
0
  xmlXPathReleaseObject(xpctxt, obj);
10521
0
        return(0);
10522
0
    }
10523
1.26k
    contextSeq = obj->nodesetval;
10524
1.26k
    if ((contextSeq == NULL) || (contextSeq->nodeNr <= 0)) {
10525
349
        xmlXPathValuePush(ctxt, obj);
10526
349
        return(0);
10527
349
    }
10528
    /*
10529
    * Predicate optimization ---------------------------------------------
10530
    * If this step has a last predicate, which contains a position(),
10531
    * then we'll optimize (although not exactly "position()", but only
10532
    * the  short-hand form, i.e., "[n]".
10533
    *
10534
    * Example - expression "/foo[parent::bar][1]":
10535
    *
10536
    * COLLECT 'child' 'name' 'node' foo    -- op (we are here)
10537
    *   ROOT                               -- op->ch1
10538
    *   PREDICATE                          -- op->ch2 (predOp)
10539
    *     PREDICATE                          -- predOp->ch1 = [parent::bar]
10540
    *       SORT
10541
    *         COLLECT  'parent' 'name' 'node' bar
10542
    *           NODE
10543
    *     ELEM Object is a number : 1        -- predOp->ch2 = [1]
10544
    *
10545
    */
10546
917
    maxPos = 0;
10547
917
    predOp = NULL;
10548
917
    hasPredicateRange = 0;
10549
917
    hasAxisRange = 0;
10550
917
    if (op->ch2 != -1) {
10551
  /*
10552
  * There's at least one predicate. 16 == XPATH_OP_PREDICATE
10553
  */
10554
731
  predOp = &ctxt->comp->steps[op->ch2];
10555
731
  if (xmlXPathIsPositionalPredicate(ctxt, predOp, &maxPos)) {
10556
731
      if (predOp->ch1 != -1) {
10557
    /*
10558
    * Use the next inner predicate operator.
10559
    */
10560
0
    predOp = &ctxt->comp->steps[predOp->ch1];
10561
0
    hasPredicateRange = 1;
10562
731
      } else {
10563
    /*
10564
    * There's no other predicate than the [n] predicate.
10565
    */
10566
731
    predOp = NULL;
10567
731
    hasAxisRange = 1;
10568
731
      }
10569
731
  }
10570
731
    }
10571
917
    breakOnFirstHit = ((toBool) && (predOp == NULL)) ? 1 : 0;
10572
    /*
10573
    * Axis traversal -----------------------------------------------------
10574
    */
10575
    /*
10576
     * 2.3 Node Tests
10577
     *  - For the attribute axis, the principal node type is attribute.
10578
     *  - For the namespace axis, the principal node type is namespace.
10579
     *  - For other axes, the principal node type is element.
10580
     *
10581
     * A node test * is true for any node of the
10582
     * principal node type. For example, child::* will
10583
     * select all element children of the context node
10584
     */
10585
917
    oldContextNode = xpctxt->node;
10586
917
    addNode = xmlXPathNodeSetAddUnique;
10587
917
    outSeq = NULL;
10588
917
    seq = NULL;
10589
917
    contextNode = NULL;
10590
917
    contextIdx = 0;
10591
10592
10593
1.83k
    while (((contextIdx < contextSeq->nodeNr) || (contextNode != NULL)) &&
10594
917
           (ctxt->error == XPATH_EXPRESSION_OK)) {
10595
917
  xpctxt->node = contextSeq->nodeTab[contextIdx++];
10596
10597
917
  if (seq == NULL) {
10598
917
      seq = xmlXPathNodeSetCreate(NULL);
10599
917
      if (seq == NULL) {
10600
0
                xmlXPathPErrMemory(ctxt);
10601
0
    total = 0;
10602
0
    goto error;
10603
0
      }
10604
917
  }
10605
  /*
10606
  * Traverse the axis and test the nodes.
10607
  */
10608
917
  pos = 0;
10609
917
  cur = NULL;
10610
917
  hasNsNodes = 0;
10611
2.69k
        do {
10612
2.69k
            if (OP_LIMIT_EXCEEDED(ctxt, 1))
10613
0
                goto error;
10614
10615
2.69k
            cur = next(ctxt, cur);
10616
2.69k
            if (cur == NULL)
10617
535
                break;
10618
10619
      /*
10620
      * QUESTION TODO: What does the "first" and "last" stuff do?
10621
      */
10622
2.16k
            if ((first != NULL) && (*first != NULL)) {
10623
0
    if (*first == cur)
10624
0
        break;
10625
0
    if (((total % 256) == 0) &&
10626
0
#ifdef XP_OPTIMIZED_NON_ELEM_COMPARISON
10627
0
        (xmlXPathCmpNodesExt(*first, cur) >= 0))
10628
#else
10629
        (xmlXPathCmpNodes(*first, cur) >= 0))
10630
#endif
10631
0
    {
10632
0
        break;
10633
0
    }
10634
0
      }
10635
2.16k
      if ((last != NULL) && (*last != NULL)) {
10636
0
    if (*last == cur)
10637
0
        break;
10638
0
    if (((total % 256) == 0) &&
10639
0
#ifdef XP_OPTIMIZED_NON_ELEM_COMPARISON
10640
0
        (xmlXPathCmpNodesExt(cur, *last) >= 0))
10641
#else
10642
        (xmlXPathCmpNodes(cur, *last) >= 0))
10643
#endif
10644
0
    {
10645
0
        break;
10646
0
    }
10647
0
      }
10648
10649
2.16k
            total++;
10650
10651
2.16k
      switch (test) {
10652
0
                case NODE_TEST_NONE:
10653
0
        total = 0;
10654
0
        goto error;
10655
0
                case NODE_TEST_TYPE:
10656
0
        if (type == NODE_TYPE_NODE) {
10657
0
      switch (cur->type) {
10658
0
          case XML_DOCUMENT_NODE:
10659
0
          case XML_HTML_DOCUMENT_NODE:
10660
0
          case XML_ELEMENT_NODE:
10661
0
          case XML_ATTRIBUTE_NODE:
10662
0
          case XML_PI_NODE:
10663
0
          case XML_COMMENT_NODE:
10664
0
          case XML_CDATA_SECTION_NODE:
10665
0
          case XML_TEXT_NODE:
10666
0
        XP_TEST_HIT
10667
0
        break;
10668
0
          case XML_NAMESPACE_DECL: {
10669
0
        if (axis == AXIS_NAMESPACE) {
10670
0
            XP_TEST_HIT_NS
10671
0
        } else {
10672
0
                              hasNsNodes = 1;
10673
0
            XP_TEST_HIT
10674
0
        }
10675
0
        break;
10676
0
                            }
10677
0
          default:
10678
0
        break;
10679
0
      }
10680
0
        } else if (cur->type == (xmlElementType) type) {
10681
0
      if (cur->type == XML_NAMESPACE_DECL)
10682
0
          XP_TEST_HIT_NS
10683
0
      else
10684
0
          XP_TEST_HIT
10685
0
        } else if ((type == NODE_TYPE_TEXT) &&
10686
0
       (cur->type == XML_CDATA_SECTION_NODE))
10687
0
        {
10688
0
      XP_TEST_HIT
10689
0
        }
10690
0
        break;
10691
0
                case NODE_TEST_PI:
10692
0
                    if ((cur->type == XML_PI_NODE) &&
10693
0
                        ((name == NULL) || xmlStrEqual(name, cur->name)))
10694
0
        {
10695
0
      XP_TEST_HIT
10696
0
                    }
10697
0
                    break;
10698
0
                case NODE_TEST_ALL:
10699
0
                    if (axis == AXIS_ATTRIBUTE) {
10700
0
                        if (cur->type == XML_ATTRIBUTE_NODE)
10701
0
      {
10702
0
                            if (prefix == NULL)
10703
0
          {
10704
0
        XP_TEST_HIT
10705
0
                            } else if ((cur->ns != NULL) &&
10706
0
        (xmlStrEqual(URI, cur->ns->href)))
10707
0
          {
10708
0
        XP_TEST_HIT
10709
0
                            }
10710
0
                        }
10711
0
                    } else if (axis == AXIS_NAMESPACE) {
10712
0
                        if (cur->type == XML_NAMESPACE_DECL)
10713
0
      {
10714
0
          XP_TEST_HIT_NS
10715
0
                        }
10716
0
                    } else {
10717
0
                        if (cur->type == XML_ELEMENT_NODE) {
10718
0
                            if (prefix == NULL)
10719
0
          {
10720
0
        XP_TEST_HIT
10721
10722
0
                            } else if ((cur->ns != NULL) &&
10723
0
        (xmlStrEqual(URI, cur->ns->href)))
10724
0
          {
10725
0
        XP_TEST_HIT
10726
0
                            }
10727
0
                        }
10728
0
                    }
10729
0
                    break;
10730
0
                case NODE_TEST_NS:{
10731
                        /* TODO */
10732
0
                        break;
10733
0
                    }
10734
2.16k
                case NODE_TEST_NAME:
10735
2.16k
                    if (axis == AXIS_ATTRIBUTE) {
10736
93
                        if (cur->type != XML_ATTRIBUTE_NODE)
10737
0
          break;
10738
2.06k
        } else if (axis == AXIS_NAMESPACE) {
10739
0
                        if (cur->type != XML_NAMESPACE_DECL)
10740
0
          break;
10741
2.06k
        } else {
10742
2.06k
            if (cur->type != XML_ELEMENT_NODE)
10743
0
          break;
10744
2.06k
        }
10745
2.16k
                    switch (cur->type) {
10746
2.06k
                        case XML_ELEMENT_NODE:
10747
2.06k
                            if (xmlStrEqual(name, cur->name)) {
10748
475
                                if (prefix == NULL) {
10749
0
                                    if (cur->ns == NULL)
10750
0
            {
10751
0
          XP_TEST_HIT
10752
0
                                    }
10753
475
                                } else {
10754
475
                                    if ((cur->ns != NULL) &&
10755
475
                                        (xmlStrEqual(URI, cur->ns->href)))
10756
475
            {
10757
475
          XP_TEST_HIT
10758
475
                                    }
10759
475
                                }
10760
475
                            }
10761
1.68k
                            break;
10762
1.68k
                        case XML_ATTRIBUTE_NODE:{
10763
93
                                xmlAttrPtr attr = (xmlAttrPtr) cur;
10764
10765
93
                                if (xmlStrEqual(name, attr->name)) {
10766
93
                                    if (prefix == NULL) {
10767
0
                                        if ((attr->ns == NULL) ||
10768
0
                                            (attr->ns->prefix == NULL))
10769
0
          {
10770
0
              XP_TEST_HIT
10771
0
                                        }
10772
93
                                    } else {
10773
93
                                        if ((attr->ns != NULL) &&
10774
93
                                            (xmlStrEqual(URI,
10775
93
                attr->ns->href)))
10776
93
          {
10777
93
              XP_TEST_HIT
10778
93
                                        }
10779
93
                                    }
10780
93
                                }
10781
93
                                break;
10782
93
                            }
10783
93
                        case XML_NAMESPACE_DECL:
10784
0
                            if (cur->type == XML_NAMESPACE_DECL) {
10785
0
                                xmlNsPtr ns = (xmlNsPtr) cur;
10786
10787
0
                                if ((ns->prefix != NULL) && (name != NULL)
10788
0
                                    && (xmlStrEqual(ns->prefix, name)))
10789
0
        {
10790
0
            XP_TEST_HIT_NS
10791
0
                                }
10792
0
                            }
10793
0
                            break;
10794
0
                        default:
10795
0
                            break;
10796
2.16k
                    }
10797
1.77k
                    break;
10798
2.16k
      } /* switch(test) */
10799
2.16k
        } while ((cur != NULL) && (ctxt->error == XPATH_EXPRESSION_OK));
10800
10801
535
  goto apply_predicates;
10802
10803
535
axis_range_end: /* ----------------------------------------------------- */
10804
  /*
10805
  * We have a "/foo[n]", and position() = n was reached.
10806
  * Note that we can have as well "/foo/::parent::foo[1]", so
10807
  * a duplicate-aware merge is still needed.
10808
  * Merge with the result.
10809
  */
10810
382
  if (outSeq == NULL) {
10811
382
      outSeq = seq;
10812
382
      seq = NULL;
10813
382
  } else {
10814
0
      outSeq = mergeAndClear(outSeq, seq);
10815
0
            if (outSeq == NULL)
10816
0
                xmlXPathPErrMemory(ctxt);
10817
0
        }
10818
  /*
10819
  * Break if only a true/false result was requested.
10820
  */
10821
382
  if (toBool)
10822
0
      break;
10823
382
  continue;
10824
10825
382
first_hit: /* ---------------------------------------------------------- */
10826
  /*
10827
  * Break if only a true/false result was requested and
10828
  * no predicates existed and a node test succeeded.
10829
  */
10830
0
  if (outSeq == NULL) {
10831
0
      outSeq = seq;
10832
0
      seq = NULL;
10833
0
  } else {
10834
0
      outSeq = mergeAndClear(outSeq, seq);
10835
0
            if (outSeq == NULL)
10836
0
                xmlXPathPErrMemory(ctxt);
10837
0
        }
10838
0
  break;
10839
10840
535
apply_predicates: /* --------------------------------------------------- */
10841
535
        if (ctxt->error != XPATH_EXPRESSION_OK)
10842
0
      goto error;
10843
10844
        /*
10845
  * Apply predicates.
10846
  */
10847
535
        if ((predOp != NULL) && (seq->nodeNr > 0)) {
10848
      /*
10849
      * E.g. when we have a "/foo[some expression][n]".
10850
      */
10851
      /*
10852
      * QUESTION TODO: The old predicate evaluation took into
10853
      *  account location-sets.
10854
      *  (E.g. ctxt->value->type == XPATH_LOCATIONSET)
10855
      *  Do we expect such a set here?
10856
      *  All what I learned now from the evaluation semantics
10857
      *  does not indicate that a location-set will be processed
10858
      *  here, so this looks OK.
10859
      */
10860
      /*
10861
      * Iterate over all predicates, starting with the outermost
10862
      * predicate.
10863
      * TODO: Problem: we cannot execute the inner predicates first
10864
      *  since we cannot go back *up* the operator tree!
10865
      *  Options we have:
10866
      *  1) Use of recursive functions (like is it currently done
10867
      *     via xmlXPathCompOpEval())
10868
      *  2) Add a predicate evaluation information stack to the
10869
      *     context struct
10870
      *  3) Change the way the operators are linked; we need a
10871
      *     "parent" field on xmlXPathStepOp
10872
      *
10873
      * For the moment, I'll try to solve this with a recursive
10874
      * function: xmlXPathCompOpEvalPredicate().
10875
      */
10876
0
      if (hasPredicateRange != 0)
10877
0
    xmlXPathCompOpEvalPredicate(ctxt, predOp, seq, maxPos, maxPos,
10878
0
              hasNsNodes);
10879
0
      else
10880
0
    xmlXPathCompOpEvalPredicate(ctxt, predOp, seq, 1, seq->nodeNr,
10881
0
              hasNsNodes);
10882
10883
0
      if (ctxt->error != XPATH_EXPRESSION_OK) {
10884
0
    total = 0;
10885
0
    goto error;
10886
0
      }
10887
0
        }
10888
10889
535
        if (seq->nodeNr > 0) {
10890
      /*
10891
      * Add to result set.
10892
      */
10893
186
      if (outSeq == NULL) {
10894
186
    outSeq = seq;
10895
186
    seq = NULL;
10896
186
      } else {
10897
0
    outSeq = mergeAndClear(outSeq, seq);
10898
0
                if (outSeq == NULL)
10899
0
                    xmlXPathPErrMemory(ctxt);
10900
0
      }
10901
10902
186
            if (toBool)
10903
0
                break;
10904
186
  }
10905
535
    }
10906
10907
917
error:
10908
917
    if ((obj->boolval) && (obj->user != NULL)) {
10909
  /*
10910
  * QUESTION TODO: What does this do and why?
10911
  * TODO: Do we have to do this also for the "error"
10912
  * cleanup further down?
10913
  */
10914
0
  ctxt->value->boolval = 1;
10915
0
  ctxt->value->user = obj->user;
10916
0
  obj->user = NULL;
10917
0
  obj->boolval = 0;
10918
0
    }
10919
917
    xmlXPathReleaseObject(xpctxt, obj);
10920
10921
    /*
10922
    * Ensure we return at least an empty set.
10923
    */
10924
917
    if (outSeq == NULL) {
10925
349
  if ((seq != NULL) && (seq->nodeNr == 0)) {
10926
349
      outSeq = seq;
10927
349
        } else {
10928
0
      outSeq = xmlXPathNodeSetCreate(NULL);
10929
0
            if (outSeq == NULL)
10930
0
                xmlXPathPErrMemory(ctxt);
10931
0
        }
10932
349
    }
10933
917
    if ((seq != NULL) && (seq != outSeq)) {
10934
0
   xmlXPathFreeNodeSet(seq);
10935
0
    }
10936
    /*
10937
    * Hand over the result. Better to push the set also in
10938
    * case of errors.
10939
    */
10940
917
    xmlXPathValuePush(ctxt, xmlXPathCacheWrapNodeSet(ctxt, outSeq));
10941
    /*
10942
    * Reset the context node.
10943
    */
10944
917
    xpctxt->node = oldContextNode;
10945
    /*
10946
    * When traversing the namespace axis in "toBool" mode, it's
10947
    * possible that tmpNsList wasn't freed.
10948
    */
10949
917
    if (xpctxt->tmpNsList != NULL) {
10950
0
        xmlFree(xpctxt->tmpNsList);
10951
0
        xpctxt->tmpNsList = NULL;
10952
0
    }
10953
10954
917
    return(total);
10955
917
}
10956
10957
static int
10958
xmlXPathCompOpEvalFilterFirst(xmlXPathParserContextPtr ctxt,
10959
            xmlXPathStepOpPtr op, xmlNodePtr * first);
10960
10961
/**
10962
 * xmlXPathCompOpEvalFirst:
10963
 * @ctxt:  the XPath parser context with the compiled expression
10964
 * @op:  an XPath compiled operation
10965
 * @first:  the first elem found so far
10966
 *
10967
 * Evaluate the Precompiled XPath operation searching only the first
10968
 * element in document order
10969
 *
10970
 * Returns the number of examined objects.
10971
 */
10972
static int
10973
xmlXPathCompOpEvalFirst(xmlXPathParserContextPtr ctxt,
10974
                        xmlXPathStepOpPtr op, xmlNodePtr * first)
10975
0
{
10976
0
    int total = 0, cur;
10977
0
    xmlXPathCompExprPtr comp;
10978
0
    xmlXPathObjectPtr arg1, arg2;
10979
10980
0
    CHECK_ERROR0;
10981
0
    if (OP_LIMIT_EXCEEDED(ctxt, 1))
10982
0
        return(0);
10983
0
    if (ctxt->context->depth >= XPATH_MAX_RECURSION_DEPTH)
10984
0
        XP_ERROR0(XPATH_RECURSION_LIMIT_EXCEEDED);
10985
0
    ctxt->context->depth += 1;
10986
0
    comp = ctxt->comp;
10987
0
    switch (op->op) {
10988
0
        case XPATH_OP_END:
10989
0
            break;
10990
0
        case XPATH_OP_UNION:
10991
0
            total =
10992
0
                xmlXPathCompOpEvalFirst(ctxt, &comp->steps[op->ch1],
10993
0
                                        first);
10994
0
      CHECK_ERROR0;
10995
0
            if ((ctxt->value != NULL)
10996
0
                && (ctxt->value->type == XPATH_NODESET)
10997
0
                && (ctxt->value->nodesetval != NULL)
10998
0
                && (ctxt->value->nodesetval->nodeNr >= 1)) {
10999
                /*
11000
                 * limit tree traversing to first node in the result
11001
                 */
11002
    /*
11003
    * OPTIMIZE TODO: This implicitly sorts
11004
    *  the result, even if not needed. E.g. if the argument
11005
    *  of the count() function, no sorting is needed.
11006
    * OPTIMIZE TODO: How do we know if the node-list wasn't
11007
    *  already sorted?
11008
    */
11009
0
    if (ctxt->value->nodesetval->nodeNr > 1)
11010
0
        xmlXPathNodeSetSort(ctxt->value->nodesetval);
11011
0
                *first = ctxt->value->nodesetval->nodeTab[0];
11012
0
            }
11013
0
            cur =
11014
0
                xmlXPathCompOpEvalFirst(ctxt, &comp->steps[op->ch2],
11015
0
                                        first);
11016
0
      CHECK_ERROR0;
11017
11018
0
            arg2 = xmlXPathValuePop(ctxt);
11019
0
            arg1 = xmlXPathValuePop(ctxt);
11020
0
            if ((arg1 == NULL) || (arg1->type != XPATH_NODESET) ||
11021
0
                (arg2 == NULL) || (arg2->type != XPATH_NODESET)) {
11022
0
          xmlXPathReleaseObject(ctxt->context, arg1);
11023
0
          xmlXPathReleaseObject(ctxt->context, arg2);
11024
0
                XP_ERROR0(XPATH_INVALID_TYPE);
11025
0
            }
11026
0
            if ((ctxt->context->opLimit != 0) &&
11027
0
                (((arg1->nodesetval != NULL) &&
11028
0
                  (xmlXPathCheckOpLimit(ctxt,
11029
0
                                        arg1->nodesetval->nodeNr) < 0)) ||
11030
0
                 ((arg2->nodesetval != NULL) &&
11031
0
                  (xmlXPathCheckOpLimit(ctxt,
11032
0
                                        arg2->nodesetval->nodeNr) < 0)))) {
11033
0
          xmlXPathReleaseObject(ctxt->context, arg1);
11034
0
          xmlXPathReleaseObject(ctxt->context, arg2);
11035
0
                break;
11036
0
            }
11037
11038
0
            if ((arg2->nodesetval != NULL) &&
11039
0
                (arg2->nodesetval->nodeNr != 0)) {
11040
0
                arg1->nodesetval = xmlXPathNodeSetMerge(arg1->nodesetval,
11041
0
                                                        arg2->nodesetval);
11042
0
                if (arg1->nodesetval == NULL)
11043
0
                    xmlXPathPErrMemory(ctxt);
11044
0
            }
11045
0
            xmlXPathValuePush(ctxt, arg1);
11046
0
      xmlXPathReleaseObject(ctxt->context, arg2);
11047
0
            total += cur;
11048
0
            break;
11049
0
        case XPATH_OP_ROOT:
11050
0
            xmlXPathRoot(ctxt);
11051
0
            break;
11052
0
        case XPATH_OP_NODE:
11053
0
            if (op->ch1 != -1)
11054
0
                total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]);
11055
0
      CHECK_ERROR0;
11056
0
            if (op->ch2 != -1)
11057
0
                total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]);
11058
0
      CHECK_ERROR0;
11059
0
      xmlXPathValuePush(ctxt, xmlXPathCacheNewNodeSet(ctxt,
11060
0
    ctxt->context->node));
11061
0
            break;
11062
0
        case XPATH_OP_COLLECT:{
11063
0
                if (op->ch1 == -1)
11064
0
                    break;
11065
11066
0
                total = xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]);
11067
0
    CHECK_ERROR0;
11068
11069
0
                total += xmlXPathNodeCollectAndTest(ctxt, op, first, NULL, 0);
11070
0
                break;
11071
0
            }
11072
0
        case XPATH_OP_VALUE:
11073
0
            xmlXPathValuePush(ctxt, xmlXPathCacheObjectCopy(ctxt, op->value4));
11074
0
            break;
11075
0
        case XPATH_OP_SORT:
11076
0
            if (op->ch1 != -1)
11077
0
                total +=
11078
0
                    xmlXPathCompOpEvalFirst(ctxt, &comp->steps[op->ch1],
11079
0
                                            first);
11080
0
      CHECK_ERROR0;
11081
0
            if ((ctxt->value != NULL)
11082
0
                && (ctxt->value->type == XPATH_NODESET)
11083
0
                && (ctxt->value->nodesetval != NULL)
11084
0
    && (ctxt->value->nodesetval->nodeNr > 1))
11085
0
                xmlXPathNodeSetSort(ctxt->value->nodesetval);
11086
0
            break;
11087
0
#ifdef XP_OPTIMIZED_FILTER_FIRST
11088
0
  case XPATH_OP_FILTER:
11089
0
                total += xmlXPathCompOpEvalFilterFirst(ctxt, op, first);
11090
0
            break;
11091
0
#endif
11092
0
        default:
11093
0
            total += xmlXPathCompOpEval(ctxt, op);
11094
0
            break;
11095
0
    }
11096
11097
0
    ctxt->context->depth -= 1;
11098
0
    return(total);
11099
0
}
11100
11101
/**
11102
 * xmlXPathCompOpEvalLast:
11103
 * @ctxt:  the XPath parser context with the compiled expression
11104
 * @op:  an XPath compiled operation
11105
 * @last:  the last elem found so far
11106
 *
11107
 * Evaluate the Precompiled XPath operation searching only the last
11108
 * element in document order
11109
 *
11110
 * Returns the number of nodes traversed
11111
 */
11112
static int
11113
xmlXPathCompOpEvalLast(xmlXPathParserContextPtr ctxt, xmlXPathStepOpPtr op,
11114
                       xmlNodePtr * last)
11115
0
{
11116
0
    int total = 0, cur;
11117
0
    xmlXPathCompExprPtr comp;
11118
0
    xmlXPathObjectPtr arg1, arg2;
11119
11120
0
    CHECK_ERROR0;
11121
0
    if (OP_LIMIT_EXCEEDED(ctxt, 1))
11122
0
        return(0);
11123
0
    if (ctxt->context->depth >= XPATH_MAX_RECURSION_DEPTH)
11124
0
        XP_ERROR0(XPATH_RECURSION_LIMIT_EXCEEDED);
11125
0
    ctxt->context->depth += 1;
11126
0
    comp = ctxt->comp;
11127
0
    switch (op->op) {
11128
0
        case XPATH_OP_END:
11129
0
            break;
11130
0
        case XPATH_OP_UNION:
11131
0
            total =
11132
0
                xmlXPathCompOpEvalLast(ctxt, &comp->steps[op->ch1], last);
11133
0
      CHECK_ERROR0;
11134
0
            if ((ctxt->value != NULL)
11135
0
                && (ctxt->value->type == XPATH_NODESET)
11136
0
                && (ctxt->value->nodesetval != NULL)
11137
0
                && (ctxt->value->nodesetval->nodeNr >= 1)) {
11138
                /*
11139
                 * limit tree traversing to first node in the result
11140
                 */
11141
0
    if (ctxt->value->nodesetval->nodeNr > 1)
11142
0
        xmlXPathNodeSetSort(ctxt->value->nodesetval);
11143
0
                *last =
11144
0
                    ctxt->value->nodesetval->nodeTab[ctxt->value->
11145
0
                                                     nodesetval->nodeNr -
11146
0
                                                     1];
11147
0
            }
11148
0
            cur =
11149
0
                xmlXPathCompOpEvalLast(ctxt, &comp->steps[op->ch2], last);
11150
0
      CHECK_ERROR0;
11151
0
            if ((ctxt->value != NULL)
11152
0
                && (ctxt->value->type == XPATH_NODESET)
11153
0
                && (ctxt->value->nodesetval != NULL)
11154
0
                && (ctxt->value->nodesetval->nodeNr >= 1)) { /* TODO: NOP ? */
11155
0
            }
11156
11157
0
            arg2 = xmlXPathValuePop(ctxt);
11158
0
            arg1 = xmlXPathValuePop(ctxt);
11159
0
            if ((arg1 == NULL) || (arg1->type != XPATH_NODESET) ||
11160
0
                (arg2 == NULL) || (arg2->type != XPATH_NODESET)) {
11161
0
          xmlXPathReleaseObject(ctxt->context, arg1);
11162
0
          xmlXPathReleaseObject(ctxt->context, arg2);
11163
0
                XP_ERROR0(XPATH_INVALID_TYPE);
11164
0
            }
11165
0
            if ((ctxt->context->opLimit != 0) &&
11166
0
                (((arg1->nodesetval != NULL) &&
11167
0
                  (xmlXPathCheckOpLimit(ctxt,
11168
0
                                        arg1->nodesetval->nodeNr) < 0)) ||
11169
0
                 ((arg2->nodesetval != NULL) &&
11170
0
                  (xmlXPathCheckOpLimit(ctxt,
11171
0
                                        arg2->nodesetval->nodeNr) < 0)))) {
11172
0
          xmlXPathReleaseObject(ctxt->context, arg1);
11173
0
          xmlXPathReleaseObject(ctxt->context, arg2);
11174
0
                break;
11175
0
            }
11176
11177
0
            if ((arg2->nodesetval != NULL) &&
11178
0
                (arg2->nodesetval->nodeNr != 0)) {
11179
0
                arg1->nodesetval = xmlXPathNodeSetMerge(arg1->nodesetval,
11180
0
                                                        arg2->nodesetval);
11181
0
                if (arg1->nodesetval == NULL)
11182
0
                    xmlXPathPErrMemory(ctxt);
11183
0
            }
11184
0
            xmlXPathValuePush(ctxt, arg1);
11185
0
      xmlXPathReleaseObject(ctxt->context, arg2);
11186
0
            total += cur;
11187
0
            break;
11188
0
        case XPATH_OP_ROOT:
11189
0
            xmlXPathRoot(ctxt);
11190
0
            break;
11191
0
        case XPATH_OP_NODE:
11192
0
            if (op->ch1 != -1)
11193
0
                total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]);
11194
0
      CHECK_ERROR0;
11195
0
            if (op->ch2 != -1)
11196
0
                total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]);
11197
0
      CHECK_ERROR0;
11198
0
      xmlXPathValuePush(ctxt, xmlXPathCacheNewNodeSet(ctxt,
11199
0
    ctxt->context->node));
11200
0
            break;
11201
0
        case XPATH_OP_COLLECT:{
11202
0
                if (op->ch1 == -1)
11203
0
                    break;
11204
11205
0
                total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]);
11206
0
    CHECK_ERROR0;
11207
11208
0
                total += xmlXPathNodeCollectAndTest(ctxt, op, NULL, last, 0);
11209
0
                break;
11210
0
            }
11211
0
        case XPATH_OP_VALUE:
11212
0
            xmlXPathValuePush(ctxt, xmlXPathCacheObjectCopy(ctxt, op->value4));
11213
0
            break;
11214
0
        case XPATH_OP_SORT:
11215
0
            if (op->ch1 != -1)
11216
0
                total +=
11217
0
                    xmlXPathCompOpEvalLast(ctxt, &comp->steps[op->ch1],
11218
0
                                           last);
11219
0
      CHECK_ERROR0;
11220
0
            if ((ctxt->value != NULL)
11221
0
                && (ctxt->value->type == XPATH_NODESET)
11222
0
                && (ctxt->value->nodesetval != NULL)
11223
0
    && (ctxt->value->nodesetval->nodeNr > 1))
11224
0
                xmlXPathNodeSetSort(ctxt->value->nodesetval);
11225
0
            break;
11226
0
        default:
11227
0
            total += xmlXPathCompOpEval(ctxt, op);
11228
0
            break;
11229
0
    }
11230
11231
0
    ctxt->context->depth -= 1;
11232
0
    return (total);
11233
0
}
11234
11235
#ifdef XP_OPTIMIZED_FILTER_FIRST
11236
static int
11237
xmlXPathCompOpEvalFilterFirst(xmlXPathParserContextPtr ctxt,
11238
            xmlXPathStepOpPtr op, xmlNodePtr * first)
11239
0
{
11240
0
    int total = 0;
11241
0
    xmlXPathCompExprPtr comp;
11242
0
    xmlXPathObjectPtr obj;
11243
0
    xmlNodeSetPtr set;
11244
11245
0
    CHECK_ERROR0;
11246
0
    comp = ctxt->comp;
11247
    /*
11248
    * Optimization for ()[last()] selection i.e. the last elem
11249
    */
11250
0
    if ((op->ch1 != -1) && (op->ch2 != -1) &&
11251
0
  (comp->steps[op->ch1].op == XPATH_OP_SORT) &&
11252
0
  (comp->steps[op->ch2].op == XPATH_OP_SORT)) {
11253
0
  int f = comp->steps[op->ch2].ch1;
11254
11255
0
  if ((f != -1) &&
11256
0
      (comp->steps[f].op == XPATH_OP_FUNCTION) &&
11257
0
      (comp->steps[f].value5 == NULL) &&
11258
0
      (comp->steps[f].value == 0) &&
11259
0
      (comp->steps[f].value4 != NULL) &&
11260
0
      (xmlStrEqual
11261
0
      (comp->steps[f].value4, BAD_CAST "last"))) {
11262
0
      xmlNodePtr last = NULL;
11263
11264
0
      total +=
11265
0
    xmlXPathCompOpEvalLast(ctxt,
11266
0
        &comp->steps[op->ch1],
11267
0
        &last);
11268
0
      CHECK_ERROR0;
11269
      /*
11270
      * The nodeset should be in document order,
11271
      * Keep only the last value
11272
      */
11273
0
      if ((ctxt->value != NULL) &&
11274
0
    (ctxt->value->type == XPATH_NODESET) &&
11275
0
    (ctxt->value->nodesetval != NULL) &&
11276
0
    (ctxt->value->nodesetval->nodeTab != NULL) &&
11277
0
    (ctxt->value->nodesetval->nodeNr > 1)) {
11278
0
                xmlXPathNodeSetKeepLast(ctxt->value->nodesetval);
11279
0
    *first = *(ctxt->value->nodesetval->nodeTab);
11280
0
      }
11281
0
      return (total);
11282
0
  }
11283
0
    }
11284
11285
0
    if (op->ch1 != -1)
11286
0
  total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]);
11287
0
    CHECK_ERROR0;
11288
0
    if (op->ch2 == -1)
11289
0
  return (total);
11290
0
    if (ctxt->value == NULL)
11291
0
  return (total);
11292
11293
    /*
11294
     * In case of errors, xmlXPathNodeSetFilter can pop additional nodes from
11295
     * the stack. We have to temporarily remove the nodeset object from the
11296
     * stack to avoid freeing it prematurely.
11297
     */
11298
0
    CHECK_TYPE0(XPATH_NODESET);
11299
0
    obj = xmlXPathValuePop(ctxt);
11300
0
    set = obj->nodesetval;
11301
0
    if (set != NULL) {
11302
0
        xmlXPathNodeSetFilter(ctxt, set, op->ch2, 1, 1, 1);
11303
0
        if (set->nodeNr > 0)
11304
0
            *first = set->nodeTab[0];
11305
0
    }
11306
0
    xmlXPathValuePush(ctxt, obj);
11307
11308
0
    return (total);
11309
0
}
11310
#endif /* XP_OPTIMIZED_FILTER_FIRST */
11311
11312
/**
11313
 * xmlXPathCompOpEval:
11314
 * @ctxt:  the XPath parser context with the compiled expression
11315
 * @op:  an XPath compiled operation
11316
 *
11317
 * Evaluate the Precompiled XPath operation
11318
 * Returns the number of nodes traversed
11319
 */
11320
static int
11321
xmlXPathCompOpEval(xmlXPathParserContextPtr ctxt, xmlXPathStepOpPtr op)
11322
2.81k
{
11323
2.81k
    int total = 0;
11324
2.81k
    int equal, ret;
11325
2.81k
    xmlXPathCompExprPtr comp;
11326
2.81k
    xmlXPathObjectPtr arg1, arg2;
11327
11328
2.81k
    CHECK_ERROR0;
11329
2.81k
    if (OP_LIMIT_EXCEEDED(ctxt, 1))
11330
0
        return(0);
11331
2.81k
    if (ctxt->context->depth >= XPATH_MAX_RECURSION_DEPTH)
11332
2.81k
        XP_ERROR0(XPATH_RECURSION_LIMIT_EXCEEDED);
11333
2.81k
    ctxt->context->depth += 1;
11334
2.81k
    comp = ctxt->comp;
11335
2.81k
    switch (op->op) {
11336
0
        case XPATH_OP_END:
11337
0
            break;
11338
0
        case XPATH_OP_AND:
11339
0
            total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]);
11340
0
      CHECK_ERROR0;
11341
0
            xmlXPathBooleanFunction(ctxt, 1);
11342
0
            if ((ctxt->value == NULL) || (ctxt->value->boolval == 0))
11343
0
                break;
11344
0
            arg2 = xmlXPathValuePop(ctxt);
11345
0
            total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]);
11346
0
      if (ctxt->error) {
11347
0
    xmlXPathFreeObject(arg2);
11348
0
    break;
11349
0
      }
11350
0
            xmlXPathBooleanFunction(ctxt, 1);
11351
0
            if (ctxt->value != NULL)
11352
0
                ctxt->value->boolval &= arg2->boolval;
11353
0
      xmlXPathReleaseObject(ctxt->context, arg2);
11354
0
            break;
11355
0
        case XPATH_OP_OR:
11356
0
            total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]);
11357
0
      CHECK_ERROR0;
11358
0
            xmlXPathBooleanFunction(ctxt, 1);
11359
0
            if ((ctxt->value == NULL) || (ctxt->value->boolval == 1))
11360
0
                break;
11361
0
            arg2 = xmlXPathValuePop(ctxt);
11362
0
            total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]);
11363
0
      if (ctxt->error) {
11364
0
    xmlXPathFreeObject(arg2);
11365
0
    break;
11366
0
      }
11367
0
            xmlXPathBooleanFunction(ctxt, 1);
11368
0
            if (ctxt->value != NULL)
11369
0
                ctxt->value->boolval |= arg2->boolval;
11370
0
      xmlXPathReleaseObject(ctxt->context, arg2);
11371
0
            break;
11372
0
        case XPATH_OP_EQUAL:
11373
0
            total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]);
11374
0
      CHECK_ERROR0;
11375
0
            total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]);
11376
0
      CHECK_ERROR0;
11377
0
      if (op->value)
11378
0
    equal = xmlXPathEqualValues(ctxt);
11379
0
      else
11380
0
    equal = xmlXPathNotEqualValues(ctxt);
11381
0
      xmlXPathValuePush(ctxt, xmlXPathCacheNewBoolean(ctxt, equal));
11382
0
            break;
11383
0
        case XPATH_OP_CMP:
11384
0
            total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]);
11385
0
      CHECK_ERROR0;
11386
0
            total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]);
11387
0
      CHECK_ERROR0;
11388
0
            ret = xmlXPathCompareValues(ctxt, op->value, op->value2);
11389
0
      xmlXPathValuePush(ctxt, xmlXPathCacheNewBoolean(ctxt, ret));
11390
0
            break;
11391
0
        case XPATH_OP_PLUS:
11392
0
            total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]);
11393
0
      CHECK_ERROR0;
11394
0
            if (op->ch2 != -1) {
11395
0
                total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]);
11396
0
      }
11397
0
      CHECK_ERROR0;
11398
0
            if (op->value == 0)
11399
0
                xmlXPathSubValues(ctxt);
11400
0
            else if (op->value == 1)
11401
0
                xmlXPathAddValues(ctxt);
11402
0
            else if (op->value == 2)
11403
0
                xmlXPathValueFlipSign(ctxt);
11404
0
            else if (op->value == 3) {
11405
0
                CAST_TO_NUMBER;
11406
0
                CHECK_TYPE0(XPATH_NUMBER);
11407
0
            }
11408
0
            break;
11409
0
        case XPATH_OP_MULT:
11410
0
            total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]);
11411
0
      CHECK_ERROR0;
11412
0
            total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]);
11413
0
      CHECK_ERROR0;
11414
0
            if (op->value == 0)
11415
0
                xmlXPathMultValues(ctxt);
11416
0
            else if (op->value == 1)
11417
0
                xmlXPathDivValues(ctxt);
11418
0
            else if (op->value == 2)
11419
0
                xmlXPathModValues(ctxt);
11420
0
            break;
11421
0
        case XPATH_OP_UNION:
11422
0
            total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]);
11423
0
      CHECK_ERROR0;
11424
0
            total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]);
11425
0
      CHECK_ERROR0;
11426
11427
0
            arg2 = xmlXPathValuePop(ctxt);
11428
0
            arg1 = xmlXPathValuePop(ctxt);
11429
0
            if ((arg1 == NULL) || (arg1->type != XPATH_NODESET) ||
11430
0
                (arg2 == NULL) || (arg2->type != XPATH_NODESET)) {
11431
0
          xmlXPathReleaseObject(ctxt->context, arg1);
11432
0
          xmlXPathReleaseObject(ctxt->context, arg2);
11433
0
                XP_ERROR0(XPATH_INVALID_TYPE);
11434
0
            }
11435
0
            if ((ctxt->context->opLimit != 0) &&
11436
0
                (((arg1->nodesetval != NULL) &&
11437
0
                  (xmlXPathCheckOpLimit(ctxt,
11438
0
                                        arg1->nodesetval->nodeNr) < 0)) ||
11439
0
                 ((arg2->nodesetval != NULL) &&
11440
0
                  (xmlXPathCheckOpLimit(ctxt,
11441
0
                                        arg2->nodesetval->nodeNr) < 0)))) {
11442
0
          xmlXPathReleaseObject(ctxt->context, arg1);
11443
0
          xmlXPathReleaseObject(ctxt->context, arg2);
11444
0
                break;
11445
0
            }
11446
11447
0
      if (((arg2->nodesetval != NULL) &&
11448
0
     (arg2->nodesetval->nodeNr != 0)))
11449
0
      {
11450
0
    arg1->nodesetval = xmlXPathNodeSetMerge(arg1->nodesetval,
11451
0
              arg2->nodesetval);
11452
0
                if (arg1->nodesetval == NULL)
11453
0
                    xmlXPathPErrMemory(ctxt);
11454
0
      }
11455
11456
0
            xmlXPathValuePush(ctxt, arg1);
11457
0
      xmlXPathReleaseObject(ctxt->context, arg2);
11458
0
            break;
11459
633
        case XPATH_OP_ROOT:
11460
633
            xmlXPathRoot(ctxt);
11461
633
            break;
11462
0
        case XPATH_OP_NODE:
11463
0
            if (op->ch1 != -1)
11464
0
                total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]);
11465
0
      CHECK_ERROR0;
11466
0
            if (op->ch2 != -1)
11467
0
                total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]);
11468
0
      CHECK_ERROR0;
11469
0
      xmlXPathValuePush(ctxt, xmlXPathCacheNewNodeSet(ctxt,
11470
0
                                                    ctxt->context->node));
11471
0
            break;
11472
1.26k
        case XPATH_OP_COLLECT:{
11473
1.26k
                if (op->ch1 == -1)
11474
0
                    break;
11475
11476
1.26k
                total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]);
11477
1.26k
    CHECK_ERROR0;
11478
11479
1.26k
                total += xmlXPathNodeCollectAndTest(ctxt, op, NULL, NULL, 0);
11480
1.26k
                break;
11481
1.26k
            }
11482
0
        case XPATH_OP_VALUE:
11483
0
            xmlXPathValuePush(ctxt, xmlXPathCacheObjectCopy(ctxt, op->value4));
11484
0
            break;
11485
0
        case XPATH_OP_VARIABLE:{
11486
0
    xmlXPathObjectPtr val;
11487
11488
0
                if (op->ch1 != -1)
11489
0
                    total +=
11490
0
                        xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]);
11491
0
                if (op->value5 == NULL) {
11492
0
        val = xmlXPathVariableLookup(ctxt->context, op->value4);
11493
0
        if (val == NULL)
11494
0
      XP_ERROR0(XPATH_UNDEF_VARIABLE_ERROR);
11495
0
                    xmlXPathValuePush(ctxt, val);
11496
0
    } else {
11497
0
                    const xmlChar *URI;
11498
11499
0
                    URI = xmlXPathNsLookup(ctxt->context, op->value5);
11500
0
                    if (URI == NULL) {
11501
0
                        XP_ERROR0(XPATH_UNDEF_PREFIX_ERROR);
11502
0
                        break;
11503
0
                    }
11504
0
        val = xmlXPathVariableLookupNS(ctxt->context,
11505
0
                                                       op->value4, URI);
11506
0
        if (val == NULL)
11507
0
      XP_ERROR0(XPATH_UNDEF_VARIABLE_ERROR);
11508
0
                    xmlXPathValuePush(ctxt, val);
11509
0
                }
11510
0
                break;
11511
0
            }
11512
93
        case XPATH_OP_FUNCTION:{
11513
93
                xmlXPathFunction func;
11514
93
                const xmlChar *oldFunc, *oldFuncURI;
11515
93
    int i;
11516
93
                int frame;
11517
11518
93
                frame = ctxt->valueNr;
11519
93
                if (op->ch1 != -1) {
11520
93
                    total +=
11521
93
                        xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]);
11522
93
                    if (ctxt->error != XPATH_EXPRESSION_OK)
11523
0
                        break;
11524
93
                }
11525
93
    if (ctxt->valueNr < frame + op->value)
11526
93
        XP_ERROR0(XPATH_INVALID_OPERAND);
11527
186
    for (i = 0; i < op->value; i++) {
11528
93
        if (ctxt->valueTab[(ctxt->valueNr - 1) - i] == NULL)
11529
93
      XP_ERROR0(XPATH_INVALID_OPERAND);
11530
93
                }
11531
93
                if (op->cache != NULL)
11532
0
                    func = op->cache;
11533
93
                else {
11534
93
                    const xmlChar *URI = NULL;
11535
11536
93
                    if (op->value5 == NULL)
11537
93
                        func =
11538
93
                            xmlXPathFunctionLookup(ctxt->context,
11539
93
                                                   op->value4);
11540
0
                    else {
11541
0
                        URI = xmlXPathNsLookup(ctxt->context, op->value5);
11542
0
                        if (URI == NULL)
11543
0
                            XP_ERROR0(XPATH_UNDEF_PREFIX_ERROR);
11544
0
                        func = xmlXPathFunctionLookupNS(ctxt->context,
11545
0
                                                        op->value4, URI);
11546
0
                    }
11547
93
                    if (func == NULL)
11548
93
                        XP_ERROR0(XPATH_UNKNOWN_FUNC_ERROR);
11549
93
                    op->cache = func;
11550
93
                    op->cacheURI = (void *) URI;
11551
93
                }
11552
93
                oldFunc = ctxt->context->function;
11553
93
                oldFuncURI = ctxt->context->functionURI;
11554
93
                ctxt->context->function = op->value4;
11555
93
                ctxt->context->functionURI = op->cacheURI;
11556
93
                func(ctxt, op->value);
11557
93
                ctxt->context->function = oldFunc;
11558
93
                ctxt->context->functionURI = oldFuncURI;
11559
93
                if ((ctxt->error == XPATH_EXPRESSION_OK) &&
11560
93
                    (ctxt->valueNr != frame + 1))
11561
93
                    XP_ERROR0(XPATH_STACK_ERROR);
11562
93
                break;
11563
93
            }
11564
93
        case XPATH_OP_ARG:
11565
93
            if (op->ch1 != -1) {
11566
0
                total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]);
11567
0
          CHECK_ERROR0;
11568
0
            }
11569
93
            if (op->ch2 != -1) {
11570
93
                total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]);
11571
93
          CHECK_ERROR0;
11572
93
      }
11573
93
            break;
11574
93
        case XPATH_OP_PREDICATE:
11575
0
        case XPATH_OP_FILTER:{
11576
0
                xmlXPathObjectPtr obj;
11577
0
                xmlNodeSetPtr set;
11578
11579
                /*
11580
                 * Optimization for ()[1] selection i.e. the first elem
11581
                 */
11582
0
                if ((op->ch1 != -1) && (op->ch2 != -1) &&
11583
0
#ifdef XP_OPTIMIZED_FILTER_FIRST
11584
        /*
11585
        * FILTER TODO: Can we assume that the inner processing
11586
        *  will result in an ordered list if we have an
11587
        *  XPATH_OP_FILTER?
11588
        *  What about an additional field or flag on
11589
        *  xmlXPathObject like @sorted ? This way we wouldn't need
11590
        *  to assume anything, so it would be more robust and
11591
        *  easier to optimize.
11592
        */
11593
0
                    ((comp->steps[op->ch1].op == XPATH_OP_SORT) || /* 18 */
11594
0
         (comp->steps[op->ch1].op == XPATH_OP_FILTER)) && /* 17 */
11595
#else
11596
        (comp->steps[op->ch1].op == XPATH_OP_SORT) &&
11597
#endif
11598
0
                    (comp->steps[op->ch2].op == XPATH_OP_VALUE)) { /* 12 */
11599
0
                    xmlXPathObjectPtr val;
11600
11601
0
                    val = comp->steps[op->ch2].value4;
11602
0
                    if ((val != NULL) && (val->type == XPATH_NUMBER) &&
11603
0
                        (val->floatval == 1.0)) {
11604
0
                        xmlNodePtr first = NULL;
11605
11606
0
                        total +=
11607
0
                            xmlXPathCompOpEvalFirst(ctxt,
11608
0
                                                    &comp->steps[op->ch1],
11609
0
                                                    &first);
11610
0
      CHECK_ERROR0;
11611
                        /*
11612
                         * The nodeset should be in document order,
11613
                         * Keep only the first value
11614
                         */
11615
0
                        if ((ctxt->value != NULL) &&
11616
0
                            (ctxt->value->type == XPATH_NODESET) &&
11617
0
                            (ctxt->value->nodesetval != NULL) &&
11618
0
                            (ctxt->value->nodesetval->nodeNr > 1))
11619
0
                            xmlXPathNodeSetClearFromPos(ctxt->value->nodesetval,
11620
0
                                                        1, 1);
11621
0
                        break;
11622
0
                    }
11623
0
                }
11624
                /*
11625
                 * Optimization for ()[last()] selection i.e. the last elem
11626
                 */
11627
0
                if ((op->ch1 != -1) && (op->ch2 != -1) &&
11628
0
                    (comp->steps[op->ch1].op == XPATH_OP_SORT) &&
11629
0
                    (comp->steps[op->ch2].op == XPATH_OP_SORT)) {
11630
0
                    int f = comp->steps[op->ch2].ch1;
11631
11632
0
                    if ((f != -1) &&
11633
0
                        (comp->steps[f].op == XPATH_OP_FUNCTION) &&
11634
0
                        (comp->steps[f].value5 == NULL) &&
11635
0
                        (comp->steps[f].value == 0) &&
11636
0
                        (comp->steps[f].value4 != NULL) &&
11637
0
                        (xmlStrEqual
11638
0
                         (comp->steps[f].value4, BAD_CAST "last"))) {
11639
0
                        xmlNodePtr last = NULL;
11640
11641
0
                        total +=
11642
0
                            xmlXPathCompOpEvalLast(ctxt,
11643
0
                                                   &comp->steps[op->ch1],
11644
0
                                                   &last);
11645
0
      CHECK_ERROR0;
11646
                        /*
11647
                         * The nodeset should be in document order,
11648
                         * Keep only the last value
11649
                         */
11650
0
                        if ((ctxt->value != NULL) &&
11651
0
                            (ctxt->value->type == XPATH_NODESET) &&
11652
0
                            (ctxt->value->nodesetval != NULL) &&
11653
0
                            (ctxt->value->nodesetval->nodeTab != NULL) &&
11654
0
                            (ctxt->value->nodesetval->nodeNr > 1))
11655
0
                            xmlXPathNodeSetKeepLast(ctxt->value->nodesetval);
11656
0
                        break;
11657
0
                    }
11658
0
                }
11659
    /*
11660
    * Process inner predicates first.
11661
    * Example "index[parent::book][1]":
11662
    * ...
11663
    *   PREDICATE   <-- we are here "[1]"
11664
    *     PREDICATE <-- process "[parent::book]" first
11665
    *       SORT
11666
    *         COLLECT  'parent' 'name' 'node' book
11667
    *           NODE
11668
    *     ELEM Object is a number : 1
11669
    */
11670
0
                if (op->ch1 != -1)
11671
0
                    total +=
11672
0
                        xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]);
11673
0
    CHECK_ERROR0;
11674
0
                if (op->ch2 == -1)
11675
0
                    break;
11676
0
                if (ctxt->value == NULL)
11677
0
                    break;
11678
11679
                /*
11680
                 * In case of errors, xmlXPathNodeSetFilter can pop additional
11681
                 * nodes from the stack. We have to temporarily remove the
11682
                 * nodeset object from the stack to avoid freeing it
11683
                 * prematurely.
11684
                 */
11685
0
                CHECK_TYPE0(XPATH_NODESET);
11686
0
                obj = xmlXPathValuePop(ctxt);
11687
0
                set = obj->nodesetval;
11688
0
                if (set != NULL)
11689
0
                    xmlXPathNodeSetFilter(ctxt, set, op->ch2,
11690
0
                                          1, set->nodeNr, 1);
11691
0
                xmlXPathValuePush(ctxt, obj);
11692
0
                break;
11693
0
            }
11694
726
        case XPATH_OP_SORT:
11695
726
            if (op->ch1 != -1)
11696
726
                total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]);
11697
726
      CHECK_ERROR0;
11698
726
            if ((ctxt->value != NULL) &&
11699
726
                (ctxt->value->type == XPATH_NODESET) &&
11700
633
                (ctxt->value->nodesetval != NULL) &&
11701
633
    (ctxt->value->nodesetval->nodeNr > 1))
11702
0
      {
11703
0
                xmlXPathNodeSetSort(ctxt->value->nodesetval);
11704
0
      }
11705
726
            break;
11706
0
        default:
11707
0
            XP_ERROR0(XPATH_INVALID_OPERAND);
11708
0
            break;
11709
2.81k
    }
11710
11711
2.81k
    ctxt->context->depth -= 1;
11712
2.81k
    return (total);
11713
2.81k
}
11714
11715
/**
11716
 * xmlXPathCompOpEvalToBoolean:
11717
 * @ctxt:  the XPath parser context
11718
 *
11719
 * Evaluates if the expression evaluates to true.
11720
 *
11721
 * Returns 1 if true, 0 if false and -1 on API or internal errors.
11722
 */
11723
static int
11724
xmlXPathCompOpEvalToBoolean(xmlXPathParserContextPtr ctxt,
11725
          xmlXPathStepOpPtr op,
11726
          int isPredicate)
11727
0
{
11728
0
    xmlXPathObjectPtr resObj = NULL;
11729
11730
0
start:
11731
0
    if (OP_LIMIT_EXCEEDED(ctxt, 1))
11732
0
        return(0);
11733
    /* comp = ctxt->comp; */
11734
0
    switch (op->op) {
11735
0
        case XPATH_OP_END:
11736
0
            return (0);
11737
0
  case XPATH_OP_VALUE:
11738
0
      resObj = (xmlXPathObjectPtr) op->value4;
11739
0
      if (isPredicate)
11740
0
    return(xmlXPathEvaluatePredicateResult(ctxt, resObj));
11741
0
      return(xmlXPathCastToBoolean(resObj));
11742
0
  case XPATH_OP_SORT:
11743
      /*
11744
      * We don't need sorting for boolean results. Skip this one.
11745
      */
11746
0
            if (op->ch1 != -1) {
11747
0
    op = &ctxt->comp->steps[op->ch1];
11748
0
    goto start;
11749
0
      }
11750
0
      return(0);
11751
0
  case XPATH_OP_COLLECT:
11752
0
      if (op->ch1 == -1)
11753
0
    return(0);
11754
11755
0
            xmlXPathCompOpEval(ctxt, &ctxt->comp->steps[op->ch1]);
11756
0
      if (ctxt->error != XPATH_EXPRESSION_OK)
11757
0
    return(-1);
11758
11759
0
            xmlXPathNodeCollectAndTest(ctxt, op, NULL, NULL, 1);
11760
0
      if (ctxt->error != XPATH_EXPRESSION_OK)
11761
0
    return(-1);
11762
11763
0
      resObj = xmlXPathValuePop(ctxt);
11764
0
      if (resObj == NULL)
11765
0
    return(-1);
11766
0
      break;
11767
0
  default:
11768
      /*
11769
      * Fallback to call xmlXPathCompOpEval().
11770
      */
11771
0
      xmlXPathCompOpEval(ctxt, op);
11772
0
      if (ctxt->error != XPATH_EXPRESSION_OK)
11773
0
    return(-1);
11774
11775
0
      resObj = xmlXPathValuePop(ctxt);
11776
0
      if (resObj == NULL)
11777
0
    return(-1);
11778
0
      break;
11779
0
    }
11780
11781
0
    if (resObj) {
11782
0
  int res;
11783
11784
0
  if (resObj->type == XPATH_BOOLEAN) {
11785
0
      res = resObj->boolval;
11786
0
  } else if (isPredicate) {
11787
      /*
11788
      * For predicates a result of type "number" is handled
11789
      * differently:
11790
      * SPEC XPath 1.0:
11791
      * "If the result is a number, the result will be converted
11792
      *  to true if the number is equal to the context position
11793
      *  and will be converted to false otherwise;"
11794
      */
11795
0
      res = xmlXPathEvaluatePredicateResult(ctxt, resObj);
11796
0
  } else {
11797
0
      res = xmlXPathCastToBoolean(resObj);
11798
0
  }
11799
0
  xmlXPathReleaseObject(ctxt->context, resObj);
11800
0
  return(res);
11801
0
    }
11802
11803
0
    return(0);
11804
0
}
11805
11806
#ifdef XPATH_STREAMING
11807
/**
11808
 * xmlXPathRunStreamEval:
11809
 * @pctxt:  the XPath parser context with the compiled expression
11810
 *
11811
 * Evaluate the Precompiled Streamable XPath expression in the given context.
11812
 */
11813
static int
11814
xmlXPathRunStreamEval(xmlXPathParserContextPtr pctxt, xmlPatternPtr comp,
11815
          xmlXPathObjectPtr *resultSeq, int toBool)
11816
{
11817
    int max_depth, min_depth;
11818
    int from_root;
11819
    int ret, depth;
11820
    int eval_all_nodes;
11821
    xmlNodePtr cur = NULL, limit = NULL;
11822
    xmlStreamCtxtPtr patstream = NULL;
11823
    xmlXPathContextPtr ctxt = pctxt->context;
11824
11825
    if ((ctxt == NULL) || (comp == NULL))
11826
        return(-1);
11827
    max_depth = xmlPatternMaxDepth(comp);
11828
    if (max_depth == -1)
11829
        return(-1);
11830
    if (max_depth == -2)
11831
        max_depth = 10000;
11832
    min_depth = xmlPatternMinDepth(comp);
11833
    if (min_depth == -1)
11834
        return(-1);
11835
    from_root = xmlPatternFromRoot(comp);
11836
    if (from_root < 0)
11837
        return(-1);
11838
11839
    if (! toBool) {
11840
  if (resultSeq == NULL)
11841
      return(-1);
11842
  *resultSeq = xmlXPathCacheNewNodeSet(pctxt, NULL);
11843
  if (*resultSeq == NULL)
11844
      return(-1);
11845
    }
11846
11847
    /*
11848
     * handle the special cases of "/" amd "." being matched
11849
     */
11850
    if (min_depth == 0) {
11851
        int res;
11852
11853
  if (from_root) {
11854
      /* Select "/" */
11855
      if (toBool)
11856
    return(1);
11857
            res = xmlXPathNodeSetAddUnique((*resultSeq)->nodesetval,
11858
                                           (xmlNodePtr) ctxt->doc);
11859
  } else {
11860
      /* Select "self::node()" */
11861
      if (toBool)
11862
    return(1);
11863
            res = xmlXPathNodeSetAddUnique((*resultSeq)->nodesetval,
11864
                                           ctxt->node);
11865
  }
11866
11867
        if (res < 0)
11868
            xmlXPathPErrMemory(pctxt);
11869
    }
11870
    if (max_depth == 0) {
11871
  return(0);
11872
    }
11873
11874
    if (from_root) {
11875
        cur = (xmlNodePtr)ctxt->doc;
11876
    } else if (ctxt->node != NULL) {
11877
        switch (ctxt->node->type) {
11878
            case XML_ELEMENT_NODE:
11879
            case XML_DOCUMENT_NODE:
11880
            case XML_DOCUMENT_FRAG_NODE:
11881
            case XML_HTML_DOCUMENT_NODE:
11882
          cur = ctxt->node;
11883
    break;
11884
            case XML_ATTRIBUTE_NODE:
11885
            case XML_TEXT_NODE:
11886
            case XML_CDATA_SECTION_NODE:
11887
            case XML_ENTITY_REF_NODE:
11888
            case XML_ENTITY_NODE:
11889
            case XML_PI_NODE:
11890
            case XML_COMMENT_NODE:
11891
            case XML_NOTATION_NODE:
11892
            case XML_DTD_NODE:
11893
            case XML_DOCUMENT_TYPE_NODE:
11894
            case XML_ELEMENT_DECL:
11895
            case XML_ATTRIBUTE_DECL:
11896
            case XML_ENTITY_DECL:
11897
            case XML_NAMESPACE_DECL:
11898
            case XML_XINCLUDE_START:
11899
            case XML_XINCLUDE_END:
11900
    break;
11901
  }
11902
  limit = cur;
11903
    }
11904
    if (cur == NULL) {
11905
        return(0);
11906
    }
11907
11908
    patstream = xmlPatternGetStreamCtxt(comp);
11909
    if (patstream == NULL) {
11910
        xmlXPathPErrMemory(pctxt);
11911
  return(-1);
11912
    }
11913
11914
    eval_all_nodes = xmlStreamWantsAnyNode(patstream);
11915
11916
    if (from_root) {
11917
  ret = xmlStreamPush(patstream, NULL, NULL);
11918
  if (ret < 0) {
11919
  } else if (ret == 1) {
11920
      if (toBool)
11921
    goto return_1;
11922
      if (xmlXPathNodeSetAddUnique((*resultSeq)->nodesetval, cur) < 0)
11923
                xmlXPathPErrMemory(pctxt);
11924
  }
11925
    }
11926
    depth = 0;
11927
    goto scan_children;
11928
next_node:
11929
    do {
11930
        if (ctxt->opLimit != 0) {
11931
            if (ctxt->opCount >= ctxt->opLimit) {
11932
                xmlXPathErr(ctxt, XPATH_RECURSION_LIMIT_EXCEEDED);
11933
                xmlFreeStreamCtxt(patstream);
11934
                return(-1);
11935
            }
11936
            ctxt->opCount++;
11937
        }
11938
11939
  switch (cur->type) {
11940
      case XML_ELEMENT_NODE:
11941
      case XML_TEXT_NODE:
11942
      case XML_CDATA_SECTION_NODE:
11943
      case XML_COMMENT_NODE:
11944
      case XML_PI_NODE:
11945
    if (cur->type == XML_ELEMENT_NODE) {
11946
        ret = xmlStreamPush(patstream, cur->name,
11947
        (cur->ns ? cur->ns->href : NULL));
11948
    } else if (eval_all_nodes)
11949
        ret = xmlStreamPushNode(patstream, NULL, NULL, cur->type);
11950
    else
11951
        break;
11952
11953
    if (ret < 0) {
11954
        xmlXPathPErrMemory(pctxt);
11955
    } else if (ret == 1) {
11956
        if (toBool)
11957
      goto return_1;
11958
        if (xmlXPathNodeSetAddUnique((*resultSeq)->nodesetval,
11959
                                                 cur) < 0)
11960
                        xmlXPathPErrMemory(pctxt);
11961
    }
11962
    if ((cur->children == NULL) || (depth >= max_depth)) {
11963
        ret = xmlStreamPop(patstream);
11964
        while (cur->next != NULL) {
11965
      cur = cur->next;
11966
      if ((cur->type != XML_ENTITY_DECL) &&
11967
          (cur->type != XML_DTD_NODE))
11968
          goto next_node;
11969
        }
11970
    }
11971
      default:
11972
    break;
11973
  }
11974
11975
scan_children:
11976
  if (cur->type == XML_NAMESPACE_DECL) break;
11977
  if ((cur->children != NULL) && (depth < max_depth)) {
11978
      /*
11979
       * Do not descend on entities declarations
11980
       */
11981
      if (cur->children->type != XML_ENTITY_DECL) {
11982
    cur = cur->children;
11983
    depth++;
11984
    /*
11985
     * Skip DTDs
11986
     */
11987
    if (cur->type != XML_DTD_NODE)
11988
        continue;
11989
      }
11990
  }
11991
11992
  if (cur == limit)
11993
      break;
11994
11995
  while (cur->next != NULL) {
11996
      cur = cur->next;
11997
      if ((cur->type != XML_ENTITY_DECL) &&
11998
    (cur->type != XML_DTD_NODE))
11999
    goto next_node;
12000
  }
12001
12002
  do {
12003
      cur = cur->parent;
12004
      depth--;
12005
      if ((cur == NULL) || (cur == limit) ||
12006
                (cur->type == XML_DOCUMENT_NODE))
12007
          goto done;
12008
      if (cur->type == XML_ELEMENT_NODE) {
12009
    ret = xmlStreamPop(patstream);
12010
      } else if ((eval_all_nodes) &&
12011
    ((cur->type == XML_TEXT_NODE) ||
12012
     (cur->type == XML_CDATA_SECTION_NODE) ||
12013
     (cur->type == XML_COMMENT_NODE) ||
12014
     (cur->type == XML_PI_NODE)))
12015
      {
12016
    ret = xmlStreamPop(patstream);
12017
      }
12018
      if (cur->next != NULL) {
12019
    cur = cur->next;
12020
    break;
12021
      }
12022
  } while (cur != NULL);
12023
12024
    } while ((cur != NULL) && (depth >= 0));
12025
12026
done:
12027
12028
    if (patstream)
12029
  xmlFreeStreamCtxt(patstream);
12030
    return(0);
12031
12032
return_1:
12033
    if (patstream)
12034
  xmlFreeStreamCtxt(patstream);
12035
    return(1);
12036
}
12037
#endif /* XPATH_STREAMING */
12038
12039
/**
12040
 * xmlXPathRunEval:
12041
 * @ctxt:  the XPath parser context with the compiled expression
12042
 * @toBool:  evaluate to a boolean result
12043
 *
12044
 * Evaluate the Precompiled XPath expression in the given context.
12045
 */
12046
static int
12047
xmlXPathRunEval(xmlXPathParserContextPtr ctxt, int toBool)
12048
633
{
12049
633
    xmlXPathCompExprPtr comp;
12050
633
    int oldDepth;
12051
12052
633
    if ((ctxt == NULL) || (ctxt->comp == NULL))
12053
0
  return(-1);
12054
12055
633
    if (ctxt->valueTab == NULL) {
12056
633
#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
12057
633
        int valueMax = 1;
12058
#else
12059
        int valueMax = 10;
12060
#endif
12061
12062
  /* Allocate the value stack */
12063
633
  ctxt->valueTab = xmlMalloc(valueMax * sizeof(xmlXPathObjectPtr));
12064
633
  if (ctxt->valueTab == NULL) {
12065
0
      xmlXPathPErrMemory(ctxt);
12066
0
      return(-1);
12067
0
  }
12068
633
  ctxt->valueNr = 0;
12069
633
  ctxt->valueMax = valueMax;
12070
633
  ctxt->value = NULL;
12071
633
    }
12072
#ifdef XPATH_STREAMING
12073
    if (ctxt->comp->stream) {
12074
  int res;
12075
12076
  if (toBool) {
12077
      /*
12078
      * Evaluation to boolean result.
12079
      */
12080
      res = xmlXPathRunStreamEval(ctxt, ctxt->comp->stream, NULL, 1);
12081
      if (res != -1)
12082
    return(res);
12083
  } else {
12084
      xmlXPathObjectPtr resObj = NULL;
12085
12086
      /*
12087
      * Evaluation to a sequence.
12088
      */
12089
      res = xmlXPathRunStreamEval(ctxt, ctxt->comp->stream, &resObj, 0);
12090
12091
      if ((res != -1) && (resObj != NULL)) {
12092
    xmlXPathValuePush(ctxt, resObj);
12093
    return(0);
12094
      }
12095
      if (resObj != NULL)
12096
    xmlXPathReleaseObject(ctxt->context, resObj);
12097
  }
12098
  /*
12099
  * QUESTION TODO: This falls back to normal XPath evaluation
12100
  * if res == -1. Is this intended?
12101
  */
12102
    }
12103
#endif
12104
633
    comp = ctxt->comp;
12105
633
    if (comp->last < 0) {
12106
0
        xmlXPathErr(ctxt, XPATH_STACK_ERROR);
12107
0
  return(-1);
12108
0
    }
12109
633
    oldDepth = ctxt->context->depth;
12110
633
    if (toBool)
12111
0
  return(xmlXPathCompOpEvalToBoolean(ctxt,
12112
0
      &comp->steps[comp->last], 0));
12113
633
    else
12114
633
  xmlXPathCompOpEval(ctxt, &comp->steps[comp->last]);
12115
633
    ctxt->context->depth = oldDepth;
12116
12117
633
    return(0);
12118
633
}
12119
12120
/************************************************************************
12121
 *                  *
12122
 *      Public interfaces       *
12123
 *                  *
12124
 ************************************************************************/
12125
12126
/**
12127
 * xmlXPathEvalPredicate:
12128
 * @ctxt:  the XPath context
12129
 * @res:  the Predicate Expression evaluation result
12130
 *
12131
 * Evaluate a predicate result for the current node.
12132
 * A PredicateExpr is evaluated by evaluating the Expr and converting
12133
 * the result to a boolean. If the result is a number, the result will
12134
 * be converted to true if the number is equal to the position of the
12135
 * context node in the context node list (as returned by the position
12136
 * function) and will be converted to false otherwise; if the result
12137
 * is not a number, then the result will be converted as if by a call
12138
 * to the boolean function.
12139
 *
12140
 * Returns 1 if predicate is true, 0 otherwise
12141
 */
12142
int
12143
0
xmlXPathEvalPredicate(xmlXPathContextPtr ctxt, xmlXPathObjectPtr res) {
12144
0
    if ((ctxt == NULL) || (res == NULL)) return(0);
12145
0
    switch (res->type) {
12146
0
        case XPATH_BOOLEAN:
12147
0
      return(res->boolval);
12148
0
        case XPATH_NUMBER:
12149
0
      return(res->floatval == ctxt->proximityPosition);
12150
0
        case XPATH_NODESET:
12151
0
        case XPATH_XSLT_TREE:
12152
0
      if (res->nodesetval == NULL)
12153
0
    return(0);
12154
0
      return(res->nodesetval->nodeNr != 0);
12155
0
        case XPATH_STRING:
12156
0
      return((res->stringval != NULL) &&
12157
0
             (xmlStrlen(res->stringval) != 0));
12158
0
        default:
12159
0
      break;
12160
0
    }
12161
0
    return(0);
12162
0
}
12163
12164
/**
12165
 * xmlXPathEvaluatePredicateResult:
12166
 * @ctxt:  the XPath Parser context
12167
 * @res:  the Predicate Expression evaluation result
12168
 *
12169
 * Evaluate a predicate result for the current node.
12170
 * A PredicateExpr is evaluated by evaluating the Expr and converting
12171
 * the result to a boolean. If the result is a number, the result will
12172
 * be converted to true if the number is equal to the position of the
12173
 * context node in the context node list (as returned by the position
12174
 * function) and will be converted to false otherwise; if the result
12175
 * is not a number, then the result will be converted as if by a call
12176
 * to the boolean function.
12177
 *
12178
 * Returns 1 if predicate is true, 0 otherwise
12179
 */
12180
int
12181
xmlXPathEvaluatePredicateResult(xmlXPathParserContextPtr ctxt,
12182
0
                                xmlXPathObjectPtr res) {
12183
0
    if ((ctxt == NULL) || (res == NULL)) return(0);
12184
0
    switch (res->type) {
12185
0
        case XPATH_BOOLEAN:
12186
0
      return(res->boolval);
12187
0
        case XPATH_NUMBER:
12188
#if defined(__BORLANDC__) || (defined(_MSC_VER) && (_MSC_VER == 1200))
12189
      return((res->floatval == ctxt->context->proximityPosition) &&
12190
             (!xmlXPathIsNaN(res->floatval))); /* MSC pbm Mark Vakoc !*/
12191
#else
12192
0
      return(res->floatval == ctxt->context->proximityPosition);
12193
0
#endif
12194
0
        case XPATH_NODESET:
12195
0
        case XPATH_XSLT_TREE:
12196
0
      if (res->nodesetval == NULL)
12197
0
    return(0);
12198
0
      return(res->nodesetval->nodeNr != 0);
12199
0
        case XPATH_STRING:
12200
0
      return((res->stringval != NULL) && (res->stringval[0] != 0));
12201
0
        default:
12202
0
      break;
12203
0
    }
12204
0
    return(0);
12205
0
}
12206
12207
#ifdef XPATH_STREAMING
12208
/**
12209
 * xmlXPathTryStreamCompile:
12210
 * @ctxt: an XPath context
12211
 * @str:  the XPath expression
12212
 *
12213
 * Try to compile the XPath expression as a streamable subset.
12214
 *
12215
 * Returns the compiled expression or NULL if failed to compile.
12216
 */
12217
static xmlXPathCompExprPtr
12218
xmlXPathTryStreamCompile(xmlXPathContextPtr ctxt, const xmlChar *str) {
12219
    /*
12220
     * Optimization: use streaming patterns when the XPath expression can
12221
     * be compiled to a stream lookup
12222
     */
12223
    xmlPatternPtr stream;
12224
    xmlXPathCompExprPtr comp;
12225
    xmlDictPtr dict = NULL;
12226
    const xmlChar **namespaces = NULL;
12227
    xmlNsPtr ns;
12228
    int i, j;
12229
12230
    if ((!xmlStrchr(str, '[')) && (!xmlStrchr(str, '(')) &&
12231
        (!xmlStrchr(str, '@'))) {
12232
  const xmlChar *tmp;
12233
        int res;
12234
12235
  /*
12236
   * We don't try to handle expressions using the verbose axis
12237
   * specifiers ("::"), just the simplified form at this point.
12238
   * Additionally, if there is no list of namespaces available and
12239
   *  there's a ":" in the expression, indicating a prefixed QName,
12240
   *  then we won't try to compile either. xmlPatterncompile() needs
12241
   *  to have a list of namespaces at compilation time in order to
12242
   *  compile prefixed name tests.
12243
   */
12244
  tmp = xmlStrchr(str, ':');
12245
  if ((tmp != NULL) &&
12246
      ((ctxt == NULL) || (ctxt->nsNr == 0) || (tmp[1] == ':')))
12247
      return(NULL);
12248
12249
  if (ctxt != NULL) {
12250
      dict = ctxt->dict;
12251
      if (ctxt->nsNr > 0) {
12252
    namespaces = xmlMalloc(2 * (ctxt->nsNr + 1) * sizeof(xmlChar*));
12253
    if (namespaces == NULL) {
12254
        xmlXPathErrMemory(ctxt);
12255
        return(NULL);
12256
    }
12257
    for (i = 0, j = 0; (j < ctxt->nsNr); j++) {
12258
        ns = ctxt->namespaces[j];
12259
        namespaces[i++] = ns->href;
12260
        namespaces[i++] = ns->prefix;
12261
    }
12262
    namespaces[i++] = NULL;
12263
    namespaces[i] = NULL;
12264
      }
12265
  }
12266
12267
  res = xmlPatternCompileSafe(str, dict, XML_PATTERN_XPATH, namespaces,
12268
                                    &stream);
12269
  if (namespaces != NULL) {
12270
      xmlFree((xmlChar **)namespaces);
12271
  }
12272
        if (res < 0) {
12273
            xmlXPathErrMemory(ctxt);
12274
            return(NULL);
12275
        }
12276
  if ((stream != NULL) && (xmlPatternStreamable(stream) == 1)) {
12277
      comp = xmlXPathNewCompExpr();
12278
      if (comp == NULL) {
12279
    xmlXPathErrMemory(ctxt);
12280
          xmlFreePattern(stream);
12281
    return(NULL);
12282
      }
12283
      comp->stream = stream;
12284
      comp->dict = dict;
12285
      if (comp->dict)
12286
    xmlDictReference(comp->dict);
12287
      return(comp);
12288
  }
12289
  xmlFreePattern(stream);
12290
    }
12291
    return(NULL);
12292
}
12293
#endif /* XPATH_STREAMING */
12294
12295
static void
12296
xmlXPathOptimizeExpression(xmlXPathParserContextPtr pctxt,
12297
                           xmlXPathStepOpPtr op)
12298
4.97k
{
12299
4.97k
    xmlXPathCompExprPtr comp = pctxt->comp;
12300
4.97k
    xmlXPathContextPtr ctxt;
12301
12302
    /*
12303
    * Try to rewrite "descendant-or-self::node()/foo" to an optimized
12304
    * internal representation.
12305
    */
12306
12307
4.97k
    if ((op->op == XPATH_OP_COLLECT /* 11 */) &&
12308
1.26k
        (op->ch1 != -1) &&
12309
1.26k
        (op->ch2 == -1 /* no predicate */))
12310
186
    {
12311
186
        xmlXPathStepOpPtr prevop = &comp->steps[op->ch1];
12312
12313
186
        if ((prevop->op == XPATH_OP_COLLECT /* 11 */) &&
12314
93
            ((xmlXPathAxisVal) prevop->value ==
12315
93
                AXIS_DESCENDANT_OR_SELF) &&
12316
0
            (prevop->ch2 == -1) &&
12317
0
            ((xmlXPathTestVal) prevop->value2 == NODE_TEST_TYPE) &&
12318
0
            ((xmlXPathTypeVal) prevop->value3 == NODE_TYPE_NODE))
12319
0
        {
12320
            /*
12321
            * This is a "descendant-or-self::node()" without predicates.
12322
            * Try to eliminate it.
12323
            */
12324
12325
0
            switch ((xmlXPathAxisVal) op->value) {
12326
0
                case AXIS_CHILD:
12327
0
                case AXIS_DESCENDANT:
12328
                    /*
12329
                    * Convert "descendant-or-self::node()/child::" or
12330
                    * "descendant-or-self::node()/descendant::" to
12331
                    * "descendant::"
12332
                    */
12333
0
                    op->ch1   = prevop->ch1;
12334
0
                    op->value = AXIS_DESCENDANT;
12335
0
                    break;
12336
0
                case AXIS_SELF:
12337
0
                case AXIS_DESCENDANT_OR_SELF:
12338
                    /*
12339
                    * Convert "descendant-or-self::node()/self::" or
12340
                    * "descendant-or-self::node()/descendant-or-self::" to
12341
                    * to "descendant-or-self::"
12342
                    */
12343
0
                    op->ch1   = prevop->ch1;
12344
0
                    op->value = AXIS_DESCENDANT_OR_SELF;
12345
0
                    break;
12346
0
                default:
12347
0
                    break;
12348
0
            }
12349
0
  }
12350
186
    }
12351
12352
    /* OP_VALUE has invalid ch1. */
12353
4.97k
    if (op->op == XPATH_OP_VALUE)
12354
1.08k
        return;
12355
12356
    /* Recurse */
12357
3.89k
    ctxt = pctxt->context;
12358
3.89k
    if (ctxt != NULL) {
12359
3.89k
        if (ctxt->depth >= XPATH_MAX_RECURSION_DEPTH)
12360
0
            return;
12361
3.89k
        ctxt->depth += 1;
12362
3.89k
    }
12363
3.89k
    if (op->ch1 != -1)
12364
2.08k
        xmlXPathOptimizeExpression(pctxt, &comp->steps[op->ch1]);
12365
3.89k
    if (op->ch2 != -1)
12366
2.25k
  xmlXPathOptimizeExpression(pctxt, &comp->steps[op->ch2]);
12367
3.89k
    if (ctxt != NULL)
12368
3.89k
        ctxt->depth -= 1;
12369
3.89k
}
12370
12371
/**
12372
 * xmlXPathCtxtCompile:
12373
 * @ctxt: an XPath context
12374
 * @str:  the XPath expression
12375
 *
12376
 * Compile an XPath expression
12377
 *
12378
 * Returns the xmlXPathCompExprPtr resulting from the compilation or NULL.
12379
 *         the caller has to free the object.
12380
 */
12381
xmlXPathCompExprPtr
12382
0
xmlXPathCtxtCompile(xmlXPathContextPtr ctxt, const xmlChar *str) {
12383
0
    xmlXPathParserContextPtr pctxt;
12384
0
    xmlXPathContextPtr tmpctxt = NULL;
12385
0
    xmlXPathCompExprPtr comp;
12386
0
    int oldDepth = 0;
12387
12388
#ifdef XPATH_STREAMING
12389
    comp = xmlXPathTryStreamCompile(ctxt, str);
12390
    if (comp != NULL)
12391
        return(comp);
12392
#endif
12393
12394
0
    xmlInitParser();
12395
12396
    /*
12397
     * We need an xmlXPathContext for the depth check.
12398
     */
12399
0
    if (ctxt == NULL) {
12400
0
        tmpctxt = xmlXPathNewContext(NULL);
12401
0
        if (tmpctxt == NULL)
12402
0
            return(NULL);
12403
0
        ctxt = tmpctxt;
12404
0
    }
12405
12406
0
    pctxt = xmlXPathNewParserContext(str, ctxt);
12407
0
    if (pctxt == NULL) {
12408
0
        if (tmpctxt != NULL)
12409
0
            xmlXPathFreeContext(tmpctxt);
12410
0
        return NULL;
12411
0
    }
12412
12413
0
    oldDepth = ctxt->depth;
12414
0
    xmlXPathCompileExpr(pctxt, 1);
12415
0
    ctxt->depth = oldDepth;
12416
12417
0
    if( pctxt->error != XPATH_EXPRESSION_OK )
12418
0
    {
12419
0
        xmlXPathFreeParserContext(pctxt);
12420
0
        if (tmpctxt != NULL)
12421
0
            xmlXPathFreeContext(tmpctxt);
12422
0
        return(NULL);
12423
0
    }
12424
12425
0
    if (*pctxt->cur != 0) {
12426
  /*
12427
   * aleksey: in some cases this line prints *second* error message
12428
   * (see bug #78858) and probably this should be fixed.
12429
   * However, we are not sure that all error messages are printed
12430
   * out in other places. It's not critical so we leave it as-is for now
12431
   */
12432
0
  xmlXPatherror(pctxt, __FILE__, __LINE__, XPATH_EXPR_ERROR);
12433
0
  comp = NULL;
12434
0
    } else {
12435
0
  comp = pctxt->comp;
12436
0
  if ((comp->nbStep > 1) && (comp->last >= 0)) {
12437
0
            if (ctxt != NULL)
12438
0
                oldDepth = ctxt->depth;
12439
0
      xmlXPathOptimizeExpression(pctxt, &comp->steps[comp->last]);
12440
0
            if (ctxt != NULL)
12441
0
                ctxt->depth = oldDepth;
12442
0
  }
12443
0
  pctxt->comp = NULL;
12444
0
    }
12445
0
    xmlXPathFreeParserContext(pctxt);
12446
0
    if (tmpctxt != NULL)
12447
0
        xmlXPathFreeContext(tmpctxt);
12448
12449
0
    if (comp != NULL) {
12450
0
  comp->expr = xmlStrdup(str);
12451
0
    }
12452
0
    return(comp);
12453
0
}
12454
12455
/**
12456
 * xmlXPathCompile:
12457
 * @str:  the XPath expression
12458
 *
12459
 * Compile an XPath expression
12460
 *
12461
 * Returns the xmlXPathCompExprPtr resulting from the compilation or NULL.
12462
 *         the caller has to free the object.
12463
 */
12464
xmlXPathCompExprPtr
12465
0
xmlXPathCompile(const xmlChar *str) {
12466
0
    return(xmlXPathCtxtCompile(NULL, str));
12467
0
}
12468
12469
/**
12470
 * xmlXPathCompiledEvalInternal:
12471
 * @comp:  the compiled XPath expression
12472
 * @ctxt:  the XPath context
12473
 * @resObj: the resulting XPath object or NULL
12474
 * @toBool: 1 if only a boolean result is requested
12475
 *
12476
 * Evaluate the Precompiled XPath expression in the given context.
12477
 * The caller has to free @resObj.
12478
 *
12479
 * Returns the xmlXPathObjectPtr resulting from the evaluation or NULL.
12480
 *         the caller has to free the object.
12481
 */
12482
static int
12483
xmlXPathCompiledEvalInternal(xmlXPathCompExprPtr comp,
12484
           xmlXPathContextPtr ctxt,
12485
           xmlXPathObjectPtr *resObjPtr,
12486
           int toBool)
12487
0
{
12488
0
    xmlXPathParserContextPtr pctxt;
12489
0
    xmlXPathObjectPtr resObj = NULL;
12490
0
    int res;
12491
12492
0
    if (comp == NULL)
12493
0
  return(-1);
12494
0
    xmlInitParser();
12495
12496
0
    xmlResetError(&ctxt->lastError);
12497
12498
0
    pctxt = xmlXPathCompParserContext(comp, ctxt);
12499
0
    if (pctxt == NULL)
12500
0
        return(-1);
12501
0
    res = xmlXPathRunEval(pctxt, toBool);
12502
12503
0
    if (pctxt->error == XPATH_EXPRESSION_OK) {
12504
0
        if (pctxt->valueNr != ((toBool) ? 0 : 1))
12505
0
            xmlXPathErr(pctxt, XPATH_STACK_ERROR);
12506
0
        else if (!toBool)
12507
0
            resObj = xmlXPathValuePop(pctxt);
12508
0
    }
12509
12510
0
    if (resObjPtr)
12511
0
        *resObjPtr = resObj;
12512
0
    else
12513
0
        xmlXPathReleaseObject(ctxt, resObj);
12514
12515
0
    pctxt->comp = NULL;
12516
0
    xmlXPathFreeParserContext(pctxt);
12517
12518
0
    return(res);
12519
0
}
12520
12521
/**
12522
 * xmlXPathCompiledEval:
12523
 * @comp:  the compiled XPath expression
12524
 * @ctx:  the XPath context
12525
 *
12526
 * Evaluate the Precompiled XPath expression in the given context.
12527
 *
12528
 * Returns the xmlXPathObjectPtr resulting from the evaluation or NULL.
12529
 *         the caller has to free the object.
12530
 */
12531
xmlXPathObjectPtr
12532
xmlXPathCompiledEval(xmlXPathCompExprPtr comp, xmlXPathContextPtr ctx)
12533
0
{
12534
0
    xmlXPathObjectPtr res = NULL;
12535
12536
0
    xmlXPathCompiledEvalInternal(comp, ctx, &res, 0);
12537
0
    return(res);
12538
0
}
12539
12540
/**
12541
 * xmlXPathCompiledEvalToBoolean:
12542
 * @comp:  the compiled XPath expression
12543
 * @ctxt:  the XPath context
12544
 *
12545
 * Applies the XPath boolean() function on the result of the given
12546
 * compiled expression.
12547
 *
12548
 * Returns 1 if the expression evaluated to true, 0 if to false and
12549
 *         -1 in API and internal errors.
12550
 */
12551
int
12552
xmlXPathCompiledEvalToBoolean(xmlXPathCompExprPtr comp,
12553
            xmlXPathContextPtr ctxt)
12554
0
{
12555
0
    return(xmlXPathCompiledEvalInternal(comp, ctxt, NULL, 1));
12556
0
}
12557
12558
/**
12559
 * xmlXPathEvalExpr:
12560
 * @ctxt:  the XPath Parser context
12561
 *
12562
 * DEPRECATED: Internal function, don't use.
12563
 *
12564
 * Parse and evaluate an XPath expression in the given context,
12565
 * then push the result on the context stack
12566
 */
12567
void
12568
633
xmlXPathEvalExpr(xmlXPathParserContextPtr ctxt) {
12569
#ifdef XPATH_STREAMING
12570
    xmlXPathCompExprPtr comp;
12571
#endif
12572
633
    int oldDepth = 0;
12573
12574
633
    if ((ctxt == NULL) || (ctxt->context == NULL))
12575
0
        return;
12576
633
    if (ctxt->context->lastError.code != 0)
12577
0
        return;
12578
12579
#ifdef XPATH_STREAMING
12580
    comp = xmlXPathTryStreamCompile(ctxt->context, ctxt->base);
12581
    if ((comp == NULL) &&
12582
        (ctxt->context->lastError.code == XML_ERR_NO_MEMORY)) {
12583
        xmlXPathPErrMemory(ctxt);
12584
        return;
12585
    }
12586
    if (comp != NULL) {
12587
        if (ctxt->comp != NULL)
12588
      xmlXPathFreeCompExpr(ctxt->comp);
12589
        ctxt->comp = comp;
12590
    } else
12591
#endif
12592
633
    {
12593
633
        if (ctxt->context != NULL)
12594
633
            oldDepth = ctxt->context->depth;
12595
633
  xmlXPathCompileExpr(ctxt, 1);
12596
633
        if (ctxt->context != NULL)
12597
633
            ctxt->context->depth = oldDepth;
12598
633
        CHECK_ERROR;
12599
12600
        /* Check for trailing characters. */
12601
633
        if (*ctxt->cur != 0)
12602
633
            XP_ERROR(XPATH_EXPR_ERROR);
12603
12604
633
  if ((ctxt->comp->nbStep > 1) && (ctxt->comp->last >= 0)) {
12605
633
            if (ctxt->context != NULL)
12606
633
                oldDepth = ctxt->context->depth;
12607
633
      xmlXPathOptimizeExpression(ctxt,
12608
633
    &ctxt->comp->steps[ctxt->comp->last]);
12609
633
            if (ctxt->context != NULL)
12610
633
                ctxt->context->depth = oldDepth;
12611
633
        }
12612
633
    }
12613
12614
0
    xmlXPathRunEval(ctxt, 0);
12615
633
}
12616
12617
/**
12618
 * xmlXPathEval:
12619
 * @str:  the XPath expression
12620
 * @ctx:  the XPath context
12621
 *
12622
 * Evaluate the XPath Location Path in the given context.
12623
 *
12624
 * Returns the xmlXPathObjectPtr resulting from the evaluation or NULL.
12625
 *         the caller has to free the object.
12626
 */
12627
xmlXPathObjectPtr
12628
633
xmlXPathEval(const xmlChar *str, xmlXPathContextPtr ctx) {
12629
633
    xmlXPathParserContextPtr ctxt;
12630
633
    xmlXPathObjectPtr res;
12631
12632
633
    if (ctx == NULL)
12633
0
        return(NULL);
12634
12635
633
    xmlInitParser();
12636
12637
633
    xmlResetError(&ctx->lastError);
12638
12639
633
    ctxt = xmlXPathNewParserContext(str, ctx);
12640
633
    if (ctxt == NULL)
12641
0
        return NULL;
12642
633
    xmlXPathEvalExpr(ctxt);
12643
12644
633
    if (ctxt->error != XPATH_EXPRESSION_OK) {
12645
0
  res = NULL;
12646
633
    } else if (ctxt->valueNr != 1) {
12647
0
        xmlXPathErr(ctxt, XPATH_STACK_ERROR);
12648
0
  res = NULL;
12649
633
    } else {
12650
633
  res = xmlXPathValuePop(ctxt);
12651
633
    }
12652
12653
633
    xmlXPathFreeParserContext(ctxt);
12654
633
    return(res);
12655
633
}
12656
12657
/**
12658
 * xmlXPathSetContextNode:
12659
 * @node: the node to to use as the context node
12660
 * @ctx:  the XPath context
12661
 *
12662
 * Sets 'node' as the context node. The node must be in the same
12663
 * document as that associated with the context.
12664
 *
12665
 * Returns -1 in case of error or 0 if successful
12666
 */
12667
int
12668
0
xmlXPathSetContextNode(xmlNodePtr node, xmlXPathContextPtr ctx) {
12669
0
    if ((node == NULL) || (ctx == NULL))
12670
0
        return(-1);
12671
12672
0
    if (node->doc == ctx->doc) {
12673
0
        ctx->node = node;
12674
0
  return(0);
12675
0
    }
12676
0
    return(-1);
12677
0
}
12678
12679
/**
12680
 * xmlXPathNodeEval:
12681
 * @node: the node to to use as the context node
12682
 * @str:  the XPath expression
12683
 * @ctx:  the XPath context
12684
 *
12685
 * Evaluate the XPath Location Path in the given context. The node 'node'
12686
 * is set as the context node. The context node is not restored.
12687
 *
12688
 * Returns the xmlXPathObjectPtr resulting from the evaluation or NULL.
12689
 *         the caller has to free the object.
12690
 */
12691
xmlXPathObjectPtr
12692
0
xmlXPathNodeEval(xmlNodePtr node, const xmlChar *str, xmlXPathContextPtr ctx) {
12693
0
    if (str == NULL)
12694
0
        return(NULL);
12695
0
    if (xmlXPathSetContextNode(node, ctx) < 0)
12696
0
        return(NULL);
12697
0
    return(xmlXPathEval(str, ctx));
12698
0
}
12699
12700
/**
12701
 * xmlXPathEvalExpression:
12702
 * @str:  the XPath expression
12703
 * @ctxt:  the XPath context
12704
 *
12705
 * Alias for xmlXPathEval().
12706
 *
12707
 * Returns the xmlXPathObjectPtr resulting from the evaluation or NULL.
12708
 *         the caller has to free the object.
12709
 */
12710
xmlXPathObjectPtr
12711
0
xmlXPathEvalExpression(const xmlChar *str, xmlXPathContextPtr ctxt) {
12712
0
    return(xmlXPathEval(str, ctxt));
12713
0
}
12714
12715
/**
12716
 * xmlXPathRegisterAllFunctions:
12717
 * @ctxt:  the XPath context
12718
 *
12719
 * DEPRECATED: No-op since 2.14.0.
12720
 *
12721
 * Registers all default XPath functions in this context
12722
 */
12723
void
12724
xmlXPathRegisterAllFunctions(xmlXPathContextPtr ctxt ATTRIBUTE_UNUSED)
12725
0
{
12726
0
}
12727
12728
#endif /* LIBXML_XPATH_ENABLED */