Coverage Report

Created: 2026-05-16 06:27

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/glib/glib/gmarkup.c
Line
Count
Source
1
/* gmarkup.c - Simple XML-like parser
2
 *
3
 *  Copyright 2000, 2003 Red Hat, Inc.
4
 *  Copyright 2007, 2008 Ryan Lortie <desrt@desrt.ca>
5
 *
6
 * SPDX-License-Identifier: LGPL-2.1-or-later
7
 *
8
 * This library is free software; you can redistribute it and/or
9
 * modify it under the terms of the GNU Lesser General Public
10
 * License as published by the Free Software Foundation; either
11
 * version 2.1 of the License, or (at your option) any later version.
12
 *
13
 * This library is distributed in the hope that it will be useful,
14
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16
 * Lesser General Public License for more details.
17
 *
18
 * You should have received a copy of the GNU Lesser General Public License
19
 * along with this library; if not, see <http://www.gnu.org/licenses/>.
20
 */
21
22
#include "config.h"
23
24
#include <stdarg.h>
25
#include <string.h>
26
#include <stdio.h>
27
#include <stdlib.h>
28
#include <errno.h>
29
30
#include "gmarkup.h"
31
32
#include "gatomic.h"
33
#include "gslice.h"
34
#include "galloca.h"
35
#include "gstrfuncs.h"
36
#include "gstring.h"
37
#include "gtestutils.h"
38
#include "glibintl.h"
39
#include "gthread.h"
40
41
G_DEFINE_QUARK (g-markup-error-quark, g_markup_error)
42
43
typedef enum
44
{
45
  STATE_INITIAL,
46
  STATE_AFTER_BOM1,
47
  STATE_AFTER_BOM2,
48
  STATE_START,
49
  STATE_AFTER_OPEN_ANGLE,
50
  STATE_AFTER_CLOSE_ANGLE,
51
  STATE_AFTER_ELISION_SLASH, /* the slash that obviates need for end element */
52
  STATE_INSIDE_OPEN_TAG_NAME,
53
  STATE_INSIDE_ATTRIBUTE_NAME,
54
  STATE_AFTER_ATTRIBUTE_NAME,
55
  STATE_BETWEEN_ATTRIBUTES,
56
  STATE_AFTER_ATTRIBUTE_EQUALS_SIGN,
57
  STATE_INSIDE_ATTRIBUTE_VALUE_SQ,
58
  STATE_INSIDE_ATTRIBUTE_VALUE_DQ,
59
  STATE_INSIDE_TEXT,
60
  STATE_AFTER_CLOSE_TAG_SLASH,
61
  STATE_INSIDE_CLOSE_TAG_NAME,
62
  STATE_AFTER_CLOSE_TAG_NAME,
63
  STATE_INSIDE_PASSTHROUGH,
64
  STATE_ERROR
65
} GMarkupParseState;
66
67
typedef struct
68
{
69
  const char *prev_element;
70
  const GMarkupParser *prev_parser;
71
  gpointer prev_user_data;
72
} GMarkupRecursionTracker;
73
74
typedef struct
75
{
76
  size_t lines; /* 1-based, in characters */
77
  size_t chars; /* 1-based, in characters */
78
  size_t offset; /* 0-based, in bytes */
79
} MarkupLocation;
80
81
struct _GMarkupParseContext
82
{
83
  const GMarkupParser *parser;
84
85
  gint ref_count;  /* (atomic) */
86
87
  GMarkupParseFlags flags;
88
89
  MarkupLocation pos;
90
  MarkupLocation tag_start;
91
  MarkupLocation attr_start;
92
93
  GMarkupParseState state;
94
95
  gpointer user_data;
96
  GDestroyNotify dnotify;
97
98
  /* A piece of character data or an element that
99
   * hasn't "ended" yet so we haven't yet called
100
   * the callback for it.
101
   */
102
  GString *partial_chunk;
103
  GSList *spare_chunks;
104
105
  GSList *tag_stack;
106
  GSList *tag_stack_gstr;
107
  GSList *spare_list_nodes;
108
109
  GString **attr_names;
110
  GString **attr_values;
111
  MarkupLocation *attr_pos; /* nullable, owned */
112
  MarkupLocation *attr_end; /* nullable, owned */
113
  gint cur_attr;
114
  gint alloc_attrs;
115
116
  const gchar *current_text;
117
  gssize       current_text_len;
118
  const gchar *current_text_end;
119
120
  /* used to save the start of the last interesting thingy */
121
  const gchar *start;
122
123
  const gchar *iter;
124
125
  guint document_empty : 1;
126
  guint parsing : 1;
127
  guint awaiting_pop : 1;
128
  gint balance;
129
130
  /* subparser support */
131
  GSList *subparser_stack; /* (GMarkupRecursionTracker *) */
132
  const char *subparser_element;
133
  gpointer held_user_data;
134
};
135
136
/*
137
 * Helpers to reduce our allocation overhead, we have
138
 * a well defined allocation lifecycle.
139
 */
140
static GSList *
141
get_list_node (GMarkupParseContext *context, gpointer data)
142
0
{
143
0
  GSList *node;
144
0
  if (context->spare_list_nodes != NULL)
145
0
    {
146
0
      node = context->spare_list_nodes;
147
0
      context->spare_list_nodes = g_slist_remove_link (context->spare_list_nodes, node);
148
0
    }
149
0
  else
150
0
    node = g_slist_alloc();
151
0
  node->data = data;
152
0
  return node;
153
0
}
154
155
static void
156
free_list_node (GMarkupParseContext *context, GSList *node)
157
0
{
158
0
  node->data = NULL;
159
0
  context->spare_list_nodes = g_slist_concat (node, context->spare_list_nodes);
160
0
}
161
162
/**
163
 * g_markup_parse_context_new:
164
 * @parser: a #GMarkupParser
165
 * @flags: one or more #GMarkupParseFlags
166
 * @user_data: user data to pass to #GMarkupParser functions
167
 * @user_data_dnotify: user data destroy notifier called when
168
 *     the parse context is freed
169
 *
170
 * Creates a new parse context. A parse context is used to parse
171
 * marked-up documents. You can feed any number of documents into
172
 * a context, as long as no errors occur; once an error occurs,
173
 * the parse context can't continue to parse text (you have to
174
 * free it and create a new parse context).
175
 *
176
 * Returns: a new #GMarkupParseContext
177
 **/
178
GMarkupParseContext *
179
g_markup_parse_context_new (const GMarkupParser *parser,
180
                            GMarkupParseFlags    flags,
181
                            gpointer             user_data,
182
                            GDestroyNotify       user_data_dnotify)
183
0
{
184
0
  GMarkupParseContext *context;
185
186
0
  g_return_val_if_fail (parser != NULL, NULL);
187
188
0
  context = g_new (GMarkupParseContext, 1);
189
190
0
  context->ref_count = 1;
191
0
  context->parser = parser;
192
0
  context->flags = flags;
193
0
  context->user_data = user_data;
194
0
  context->dnotify = user_data_dnotify;
195
196
0
  context->pos.lines = 1;
197
0
  context->pos.chars = 1;
198
0
  context->pos.offset = 0;
199
200
0
  context->tag_start.lines = 1;
201
0
  context->tag_start.chars = 1;
202
0
  context->tag_start.offset = 0;
203
204
0
  context->partial_chunk = NULL;
205
0
  context->spare_chunks = NULL;
206
0
  context->spare_list_nodes = NULL;
207
208
0
  context->state = STATE_INITIAL;
209
0
  context->tag_stack = NULL;
210
0
  context->tag_stack_gstr = NULL;
211
0
  context->attr_names = NULL;
212
0
  context->attr_values = NULL;
213
0
  context->attr_pos = NULL;
214
0
  context->attr_end = NULL;
215
0
  context->cur_attr = -1;
216
0
  context->alloc_attrs = 0;
217
218
0
  context->current_text = NULL;
219
0
  context->current_text_len = -1;
220
0
  context->current_text_end = NULL;
221
222
0
  context->start = NULL;
223
0
  context->iter = NULL;
224
225
0
  context->document_empty = TRUE;
226
0
  context->parsing = FALSE;
227
228
0
  context->awaiting_pop = FALSE;
229
0
  context->subparser_stack = NULL;
230
0
  context->subparser_element = NULL;
231
232
  /* this is only looked at if awaiting_pop = TRUE.  initialise anyway. */
233
0
  context->held_user_data = NULL;
234
235
0
  context->balance = 0;
236
237
0
  return context;
238
0
}
239
240
/**
241
 * g_markup_parse_context_ref:
242
 * @context: a #GMarkupParseContext
243
 *
244
 * Increases the reference count of @context.
245
 *
246
 * Returns: the same @context
247
 *
248
 * Since: 2.36
249
 **/
250
GMarkupParseContext *
251
g_markup_parse_context_ref (GMarkupParseContext *context)
252
0
{
253
0
  g_return_val_if_fail (context != NULL, NULL);
254
0
  g_return_val_if_fail (context->ref_count > 0, NULL);
255
256
0
  g_atomic_int_inc (&context->ref_count);
257
258
0
  return context;
259
0
}
260
261
/**
262
 * g_markup_parse_context_unref:
263
 * @context: a #GMarkupParseContext
264
 *
265
 * Decreases the reference count of @context.  When its reference count
266
 * drops to 0, it is freed.
267
 *
268
 * Since: 2.36
269
 **/
270
void
271
g_markup_parse_context_unref (GMarkupParseContext *context)
272
0
{
273
0
  g_return_if_fail (context != NULL);
274
0
  g_return_if_fail (context->ref_count > 0);
275
276
0
  if (g_atomic_int_dec_and_test (&context->ref_count))
277
0
    g_markup_parse_context_free (context);
278
0
}
279
280
static void
281
string_full_free (gpointer ptr)
282
0
{
283
0
  g_string_free (ptr, TRUE);
284
0
}
285
286
static void clear_attributes (GMarkupParseContext *context);
287
288
/**
289
 * g_markup_parse_context_free:
290
 * @context: a #GMarkupParseContext
291
 *
292
 * Frees a #GMarkupParseContext.
293
 *
294
 * This function can't be called from inside one of the
295
 * #GMarkupParser functions or while a subparser is pushed.
296
 */
297
void
298
g_markup_parse_context_free (GMarkupParseContext *context)
299
0
{
300
0
  g_return_if_fail (context != NULL);
301
0
  g_return_if_fail (!context->parsing);
302
0
  g_return_if_fail (!context->subparser_stack);
303
0
  g_return_if_fail (!context->awaiting_pop);
304
305
0
  if (context->dnotify)
306
0
    (* context->dnotify) (context->user_data);
307
308
0
  clear_attributes (context);
309
0
  g_free (context->attr_names);
310
0
  g_free (context->attr_values);
311
0
  g_free (context->attr_pos);
312
0
  g_free (context->attr_end);
313
314
0
  g_slist_free_full (context->tag_stack_gstr, string_full_free);
315
0
  g_slist_free (context->tag_stack);
316
317
0
  g_slist_free_full (context->spare_chunks, string_full_free);
318
0
  g_slist_free (context->spare_list_nodes);
319
320
0
  if (context->partial_chunk)
321
0
    g_string_free (context->partial_chunk, TRUE);
322
323
0
  g_free (context);
324
0
}
325
326
static void pop_subparser_stack (GMarkupParseContext *context);
327
328
static void
329
mark_error (GMarkupParseContext *context,
330
            GError              *error)
331
0
{
332
0
  context->state = STATE_ERROR;
333
334
0
  if (context->parser->error)
335
0
    (*context->parser->error) (context, error, context->user_data);
336
337
  /* report the error all the way up to free all the user-data */
338
0
  while (context->subparser_stack)
339
0
    {
340
0
      pop_subparser_stack (context);
341
0
      context->awaiting_pop = FALSE; /* already been freed */
342
343
0
      if (context->parser->error)
344
0
        (*context->parser->error) (context, error, context->user_data);
345
0
    }
346
0
}
347
348
static void
349
set_error (GMarkupParseContext  *context,
350
           GError              **error,
351
           GMarkupError          code,
352
           const gchar          *format,
353
           ...) G_GNUC_PRINTF (4, 5);
354
355
static void
356
set_error_literal (GMarkupParseContext  *context,
357
                   GError              **error,
358
                   GMarkupError          code,
359
                   const gchar          *message)
360
0
{
361
0
  GError *tmp_error;
362
363
0
  tmp_error = g_error_new_literal (G_MARKUP_ERROR, code, message);
364
365
0
  g_prefix_error (&tmp_error,
366
0
                  _("Error on line %" G_GSIZE_FORMAT " char %" G_GSIZE_FORMAT ": "),
367
0
                  context->pos.lines,
368
0
                  context->pos.chars);
369
370
0
  mark_error (context, tmp_error);
371
372
0
  g_propagate_error (error, tmp_error);
373
0
}
374
375
G_GNUC_PRINTF(4, 5)
376
static void
377
set_error (GMarkupParseContext  *context,
378
           GError              **error,
379
           GMarkupError          code,
380
           const gchar          *format,
381
           ...)
382
0
{
383
0
  gchar *s;
384
0
  gchar *s_valid;
385
0
  va_list args;
386
387
0
  va_start (args, format);
388
0
  s = g_strdup_vprintf (format, args);
389
0
  va_end (args);
390
391
  /* Make sure that the GError message is valid UTF-8
392
   * even if it is complaining about invalid UTF-8 in the markup
393
   */
394
0
  s_valid = g_utf8_make_valid (s, -1);
395
0
  set_error_literal (context, error, code, s);
396
397
0
  g_free (s);
398
0
  g_free (s_valid);
399
0
}
400
401
static void
402
propagate_error (GMarkupParseContext  *context,
403
                 GError              **dest,
404
                 GError               *src)
405
0
{
406
0
  if (context->flags & G_MARKUP_PREFIX_ERROR_POSITION)
407
0
    g_prefix_error (&src,
408
0
                    _("Error on line %" G_GSIZE_FORMAT " char %" G_GSIZE_FORMAT ": "),
409
0
                    context->pos.lines,
410
0
                    context->pos.chars);
411
412
0
  mark_error (context, src);
413
414
0
  g_propagate_error (dest, src);
415
0
}
416
417
#define IS_COMMON_NAME_END_CHAR(c) \
418
0
  ((c) == '=' || (c) == '/' || (c) == '>' || (c) == ' ')
419
420
static gboolean
421
slow_name_validate (GMarkupParseContext  *context,
422
                    const gchar          *name,
423
                    GError              **error)
424
0
{
425
0
  const gchar *p = name;
426
427
0
  if (!g_utf8_validate (name, -1, NULL))
428
0
    {
429
0
      set_error (context, error, G_MARKUP_ERROR_BAD_UTF8,
430
0
                 _("Invalid UTF-8 encoded text in name — not valid “%s”"), name);
431
0
      return FALSE;
432
0
    }
433
434
0
  if (!(g_ascii_isalpha (*p) ||
435
0
        (!IS_COMMON_NAME_END_CHAR (*p) &&
436
0
         (*p == '_' ||
437
0
          *p == ':' ||
438
0
          g_unichar_isalpha (g_utf8_get_char (p))))))
439
0
    {
440
0
      set_error (context, error, G_MARKUP_ERROR_PARSE,
441
0
                 _("“%s” is not a valid name"), name);
442
0
      return FALSE;
443
0
    }
444
445
0
  for (p = g_utf8_next_char (name); *p != '\0'; p = g_utf8_next_char (p))
446
0
    {
447
      /* is_name_char */
448
0
      if (!(g_ascii_isalnum (*p) ||
449
0
            (!IS_COMMON_NAME_END_CHAR (*p) &&
450
0
             (*p == '.' ||
451
0
              *p == '-' ||
452
0
              *p == '_' ||
453
0
              *p == ':' ||
454
0
              g_unichar_isalpha (g_utf8_get_char (p))))))
455
0
        {
456
0
          set_error (context, error, G_MARKUP_ERROR_PARSE,
457
0
                     _("“%s” is not a valid name: “%c”"), name, *p);
458
0
          return FALSE;
459
0
        }
460
0
    }
461
0
  return TRUE;
462
0
}
463
464
/*
465
 * Use me for elements, attributes etc.
466
 */
467
static gboolean
468
name_validate (GMarkupParseContext  *context,
469
               const gchar          *name,
470
               GError              **error)
471
0
{
472
0
  char mask;
473
0
  const char *p;
474
475
  /* name start char */
476
0
  p = name;
477
0
  if (G_UNLIKELY (IS_COMMON_NAME_END_CHAR (*p) ||
478
0
                  !(g_ascii_isalpha (*p) || *p == '_' || *p == ':')))
479
0
    goto slow_validate;
480
481
0
  for (mask = *p++; *p != '\0'; p++)
482
0
    {
483
0
      mask |= *p;
484
485
      /* is_name_char */
486
0
      if (G_UNLIKELY (!(g_ascii_isalnum (*p) ||
487
0
                        (!IS_COMMON_NAME_END_CHAR (*p) &&
488
0
                         (*p == '.' ||
489
0
                          *p == '-' ||
490
0
                          *p == '_' ||
491
0
                          *p == ':')))))
492
0
        goto slow_validate;
493
0
    }
494
495
0
  if (mask & 0x80) /* un-common / non-ascii */
496
0
    goto slow_validate;
497
498
0
  return TRUE;
499
500
0
 slow_validate:
501
0
  return slow_name_validate (context, name, error);
502
0
}
503
504
static gboolean
505
text_validate (GMarkupParseContext  *context,
506
               const gchar          *p,
507
               gsize                 len,
508
               GError              **error)
509
0
{
510
0
  if (!g_utf8_validate_len (p, len, NULL))
511
0
    {
512
0
      set_error (context, error, G_MARKUP_ERROR_BAD_UTF8,
513
0
                 _("Invalid UTF-8 encoded text in name — not valid “%s”"), p);
514
0
      return FALSE;
515
0
    }
516
0
  else
517
0
    return TRUE;
518
0
}
519
520
static gchar*
521
char_str (gunichar c,
522
          gchar   *buf)
523
0
{
524
0
  memset (buf, 0, 8);
525
0
  g_unichar_to_utf8 (c, buf);
526
0
  return buf;
527
0
}
528
529
/* Format the next UTF-8 character as a gchar* for printing in error output
530
 * when we encounter a syntax error. This correctly handles invalid UTF-8,
531
 * emitting it as hex escapes. */
532
static gchar*
533
utf8_str (const gchar *utf8,
534
          gsize        max_len,
535
          gchar       *buf)
536
0
{
537
0
  gunichar c = g_utf8_get_char_validated (utf8, max_len);
538
0
  if (c == (gunichar) -1 || c == (gunichar) -2)
539
0
    {
540
0
      guchar ch = (max_len > 0) ? (guchar) *utf8 : 0;
541
0
      gchar *temp = g_strdup_printf ("\\x%02x", (guint) ch);
542
0
      memset (buf, 0, 8);
543
0
      memcpy (buf, temp, strlen (temp));
544
0
      g_free (temp);
545
0
    }
546
0
  else
547
0
    char_str (c, buf);
548
0
  return buf;
549
0
}
550
551
G_GNUC_PRINTF(5, 6)
552
static void
553
set_unescape_error (GMarkupParseContext  *context,
554
                    GError              **error,
555
                    const gchar          *remaining_text,
556
                    GMarkupError          code,
557
                    const gchar          *format,
558
                    ...)
559
0
{
560
0
  GError *tmp_error;
561
0
  gchar *s;
562
0
  va_list args;
563
0
  gint remaining_newlines;
564
0
  const gchar *p;
565
566
0
  remaining_newlines = 0;
567
0
  p = remaining_text;
568
0
  while (*p != '\0')
569
0
    {
570
0
      if (*p == '\n')
571
0
        ++remaining_newlines;
572
0
      ++p;
573
0
    }
574
575
0
  va_start (args, format);
576
0
  s = g_strdup_vprintf (format, args);
577
0
  va_end (args);
578
579
0
  tmp_error = g_error_new (G_MARKUP_ERROR,
580
0
                           code,
581
0
                           _("Error on line %" G_GSIZE_FORMAT ": %s"),
582
0
                           context->pos.lines - remaining_newlines,
583
0
                           s);
584
585
0
  g_free (s);
586
587
0
  mark_error (context, tmp_error);
588
589
0
  g_propagate_error (error, tmp_error);
590
0
}
591
592
/*
593
 * re-write the GString in-place, unescaping anything that escaped.
594
 * most XML does not contain entities, or escaping.
595
 */
596
static gboolean
597
unescape_gstring_inplace (GMarkupParseContext  *context,
598
                          GString              *string,
599
                          gboolean             *is_ascii,
600
                          GError              **error)
601
0
{
602
0
  char mask, *to;
603
0
  const char *from;
604
0
  gboolean normalize_attribute;
605
606
0
  *is_ascii = FALSE;
607
608
  /* are we unescaping an attribute or not ? */
609
0
  if (context->state == STATE_INSIDE_ATTRIBUTE_VALUE_SQ ||
610
0
      context->state == STATE_INSIDE_ATTRIBUTE_VALUE_DQ)
611
0
    normalize_attribute = TRUE;
612
0
  else
613
0
    normalize_attribute = FALSE;
614
615
  /*
616
   * Meeks' theorem: unescaping can only shrink text.
617
   * for &lt; etc. this is obvious, for &#xffff; more
618
   * thought is required, but this is patently so.
619
   */
620
0
  mask = 0;
621
0
  for (from = to = string->str; *from != '\0'; from++, to++)
622
0
    {
623
0
      *to = *from;
624
625
0
      mask |= *to;
626
0
      if (normalize_attribute && (*to == '\t' || *to == '\n'))
627
0
        *to = ' ';
628
0
      if (*to == '\r')
629
0
        {
630
0
          *to = normalize_attribute ? ' ' : '\n';
631
0
          if (from[1] == '\n')
632
0
            from++;
633
0
        }
634
0
      if (*from == '&')
635
0
        {
636
0
          from++;
637
0
          if (*from == '#')
638
0
            {
639
0
              gint base = 10;
640
0
              gulong l;
641
0
              gchar *end = NULL;
642
643
0
              from++;
644
645
0
              if (*from == 'x')
646
0
                {
647
0
                  base = 16;
648
0
                  from++;
649
0
                }
650
651
0
              errno = 0;
652
0
              l = strtoul (from, &end, base);
653
654
0
              if (end == from || errno != 0)
655
0
                {
656
0
                  set_unescape_error (context, error,
657
0
                                      from, G_MARKUP_ERROR_PARSE,
658
0
                                      _("Failed to parse “%-.*s”, which "
659
0
                                        "should have been a digit "
660
0
                                        "inside a character reference "
661
0
                                        "(&#234; for example) — perhaps "
662
0
                                        "the digit is too large"),
663
0
                                      (int)(end - from), from);
664
0
                  return FALSE;
665
0
                }
666
0
              else if (*end != ';')
667
0
                {
668
0
                  set_unescape_error (context, error,
669
0
                                      from, G_MARKUP_ERROR_PARSE,
670
0
                                      _("Character reference did not end with a "
671
0
                                        "semicolon; "
672
0
                                        "most likely you used an ampersand "
673
0
                                        "character without intending to start "
674
0
                                        "an entity — escape ampersand as &amp;"));
675
0
                  return FALSE;
676
0
                }
677
0
              else
678
0
                {
679
                  /* characters XML 1.1 permits */
680
0
                  if ((0 < l && l <= 0xD7FF) ||
681
0
                      (0xE000 <= l && l <= 0xFFFD) ||
682
0
                      (0x10000 <= l && l <= 0x10FFFF))
683
0
                    {
684
0
                      gchar buf[8];
685
0
                      char_str (l, buf);
686
0
                      strcpy (to, buf);
687
0
                      to += strlen (buf) - 1;
688
0
                      from = end;
689
0
                      if (l >= 0x80) /* not ascii */
690
0
                        mask |= 0x80;
691
0
                    }
692
0
                  else
693
0
                    {
694
0
                      set_unescape_error (context, error,
695
0
                                          from, G_MARKUP_ERROR_PARSE,
696
0
                                          _("Character reference “%-.*s” does not "
697
0
                                            "encode a permitted character"),
698
0
                                          (int)(end - from), from);
699
0
                      return FALSE;
700
0
                    }
701
0
                }
702
0
            }
703
704
0
          else if (strncmp (from, "lt;", 3) == 0)
705
0
            {
706
0
              *to = '<';
707
0
              from += 2;
708
0
            }
709
0
          else if (strncmp (from, "gt;", 3) == 0)
710
0
            {
711
0
              *to = '>';
712
0
              from += 2;
713
0
            }
714
0
          else if (strncmp (from, "amp;", 4) == 0)
715
0
            {
716
0
              *to = '&';
717
0
              from += 3;
718
0
            }
719
0
          else if (strncmp (from, "quot;", 5) == 0)
720
0
            {
721
0
              *to = '"';
722
0
              from += 4;
723
0
            }
724
0
          else if (strncmp (from, "apos;", 5) == 0)
725
0
            {
726
0
              *to = '\'';
727
0
              from += 4;
728
0
            }
729
0
          else
730
0
            {
731
0
              if (*from == ';')
732
0
                set_unescape_error (context, error,
733
0
                                    from, G_MARKUP_ERROR_PARSE,
734
0
                                    _("Empty entity “&;” seen; valid "
735
0
                                      "entities are: &amp; &quot; &lt; &gt; &apos;"));
736
0
              else
737
0
                {
738
0
                  const char *end = strchr (from, ';');
739
0
                  if (end)
740
0
                    set_unescape_error (context, error,
741
0
                                        from, G_MARKUP_ERROR_PARSE,
742
0
                                        _("Entity name “%-.*s” is not known"),
743
0
                                        (int)(end - from), from);
744
0
                  else
745
0
                    set_unescape_error (context, error,
746
0
                                        from, G_MARKUP_ERROR_PARSE,
747
0
                                        _("Entity did not end with a semicolon; "
748
0
                                          "most likely you used an ampersand "
749
0
                                          "character without intending to start "
750
0
                                          "an entity — escape ampersand as &amp;"));
751
0
                }
752
0
              return FALSE;
753
0
            }
754
0
        }
755
0
    }
756
757
0
  g_assert (to - string->str <= (gssize) string->len);
758
0
  if (to - string->str != (gssize) string->len)
759
0
    g_string_truncate (string, to - string->str);
760
761
0
  *is_ascii = !(mask & 0x80);
762
763
0
  return TRUE;
764
0
}
765
766
static inline gboolean
767
advance_char (GMarkupParseContext *context)
768
0
{
769
0
  context->iter++;
770
0
  context->pos.chars++;
771
0
  context->pos.offset++;
772
773
0
  if (G_UNLIKELY (context->iter == context->current_text_end))
774
0
      return FALSE;
775
776
0
  else if (G_UNLIKELY (*context->iter == '\n'))
777
0
    {
778
0
      context->pos.lines++;
779
0
      context->pos.chars = 1;
780
0
    }
781
782
0
  return TRUE;
783
0
}
784
785
static inline gboolean
786
xml_isspace (char c)
787
0
{
788
0
  return c == ' ' || c == '\t' || c == '\n' || c == '\r';
789
0
}
790
791
static void
792
skip_spaces (GMarkupParseContext *context)
793
0
{
794
0
  do
795
0
    {
796
0
      if (!xml_isspace (*context->iter))
797
0
        return;
798
0
    }
799
0
  while (advance_char (context));
800
0
}
801
802
static void
803
advance_to_name_end (GMarkupParseContext *context)
804
0
{
805
0
  do
806
0
    {
807
0
      if (IS_COMMON_NAME_END_CHAR (*(context->iter)))
808
0
        return;
809
0
      if (xml_isspace (*(context->iter)))
810
0
        return;
811
0
    }
812
0
  while (advance_char (context));
813
0
}
814
815
static void
816
release_chunk (GMarkupParseContext *context, GString *str)
817
0
{
818
0
  GSList *node;
819
0
  if (!str)
820
0
    return;
821
0
  if (str->allocated_len > 256)
822
0
    { /* large strings are unusual and worth freeing */
823
0
      g_string_free (str, TRUE);
824
0
      return;
825
0
    }
826
0
  g_string_truncate (str, 0);
827
0
  node = get_list_node (context, str);
828
0
  context->spare_chunks = g_slist_concat (node, context->spare_chunks);
829
0
}
830
831
static void
832
add_to_partial (GMarkupParseContext *context,
833
                const gchar         *text_start,
834
                const gchar         *text_end)
835
0
{
836
0
  if (context->partial_chunk == NULL)
837
0
    { /* allocate a new chunk to parse into */
838
839
0
      if (context->spare_chunks != NULL)
840
0
        {
841
0
          GSList *node = context->spare_chunks;
842
0
          context->spare_chunks = g_slist_remove_link (context->spare_chunks, node);
843
0
          context->partial_chunk = node->data;
844
0
          free_list_node (context, node);
845
0
        }
846
0
      else
847
0
        context->partial_chunk = g_string_sized_new (MAX (28, text_end - text_start));
848
0
    }
849
850
0
  if (text_start != text_end)
851
0
    g_string_append_len (context->partial_chunk,
852
0
                         text_start, text_end - text_start);
853
0
}
854
855
static inline void
856
truncate_partial (GMarkupParseContext *context)
857
0
{
858
0
  if (context->partial_chunk != NULL)
859
0
    g_string_truncate (context->partial_chunk, 0);
860
0
}
861
862
static inline const gchar*
863
current_element (GMarkupParseContext *context)
864
0
{
865
0
  return context->tag_stack->data;
866
0
}
867
868
static void
869
pop_subparser_stack (GMarkupParseContext *context)
870
0
{
871
0
  GMarkupRecursionTracker *tracker;
872
873
0
  g_assert (context->subparser_stack);
874
875
0
  tracker = context->subparser_stack->data;
876
877
0
  context->awaiting_pop = TRUE;
878
0
  context->held_user_data = context->user_data;
879
880
0
  context->user_data = tracker->prev_user_data;
881
0
  context->parser = tracker->prev_parser;
882
0
  context->subparser_element = tracker->prev_element;
883
0
  g_slice_free (GMarkupRecursionTracker, tracker);
884
885
0
  context->subparser_stack = g_slist_delete_link (context->subparser_stack,
886
0
                                                  context->subparser_stack);
887
0
}
888
889
static void
890
push_partial_as_tag (GMarkupParseContext *context)
891
0
{
892
0
  GString *str = context->partial_chunk;
893
894
  /* sadly, this is exported by gmarkup_get_element_stack as-is */
895
0
  context->tag_stack = g_slist_concat (get_list_node (context, str->str), context->tag_stack);
896
0
  context->tag_stack_gstr = g_slist_concat (get_list_node (context, str), context->tag_stack_gstr);
897
898
0
  context->partial_chunk = NULL;
899
0
}
900
901
static void
902
pop_tag (GMarkupParseContext *context)
903
0
{
904
0
  GSList *nodea, *nodeb;
905
906
0
  nodea = context->tag_stack;
907
0
  nodeb = context->tag_stack_gstr;
908
0
  release_chunk (context, nodeb->data);
909
0
  context->tag_stack = g_slist_remove_link (context->tag_stack, nodea);
910
0
  context->tag_stack_gstr = g_slist_remove_link (context->tag_stack_gstr, nodeb);
911
0
  free_list_node (context, nodea);
912
0
  free_list_node (context, nodeb);
913
0
}
914
915
static void
916
possibly_finish_subparser (GMarkupParseContext *context)
917
0
{
918
0
  if (current_element (context) == context->subparser_element)
919
0
    pop_subparser_stack (context);
920
0
}
921
922
static void
923
ensure_no_outstanding_subparser (GMarkupParseContext *context)
924
0
{
925
0
  if (context->awaiting_pop)
926
0
    g_critical ("During the first end_element call after invoking a "
927
0
                "subparser you must pop the subparser stack and handle "
928
0
                "the freeing of the subparser user_data.  This can be "
929
0
                "done by calling the end function of the subparser.  "
930
0
                "Very probably, your program just leaked memory.");
931
932
  /* let valgrind watch the pointer disappear... */
933
0
  context->held_user_data = NULL;
934
0
  context->awaiting_pop = FALSE;
935
0
}
936
937
static const gchar*
938
current_attribute (GMarkupParseContext *context)
939
0
{
940
0
  g_assert (context->cur_attr >= 0);
941
0
  return context->attr_names[context->cur_attr]->str;
942
0
}
943
944
static gboolean
945
add_attribute (GMarkupParseContext *context, GString *str)
946
0
{
947
  /* Sanity check on the number of attributes. */
948
0
  if (context->cur_attr >= 1000)
949
0
    return FALSE;
950
951
0
  if (context->cur_attr + 2 >= context->alloc_attrs)
952
0
    {
953
0
      context->alloc_attrs += 5; /* silly magic number */
954
0
      context->attr_names = g_realloc_n (context->attr_names, context->alloc_attrs, sizeof (GString*));
955
0
      context->attr_values = g_realloc_n (context->attr_values, context->alloc_attrs, sizeof (GString*));
956
0
      context->attr_pos = g_realloc_n (context->attr_pos, context->alloc_attrs, sizeof (MarkupLocation));
957
0
      context->attr_end = g_realloc_n (context->attr_end, context->alloc_attrs, sizeof (MarkupLocation));
958
0
    }
959
0
  context->cur_attr++;
960
0
  context->attr_names[context->cur_attr] = str;
961
0
  context->attr_values[context->cur_attr] = NULL;
962
0
  context->attr_names[context->cur_attr+1] = NULL;
963
0
  context->attr_values[context->cur_attr+1] = NULL;
964
0
  context->attr_pos[context->cur_attr] = context->attr_start;
965
0
  context->attr_end[context->cur_attr] = context->pos; /* Will be overwritten later */
966
967
0
  return TRUE;
968
0
}
969
970
static void
971
clear_attributes (GMarkupParseContext *context)
972
0
{
973
  /* Go ahead and free the attributes. */
974
0
  for (; context->cur_attr >= 0; context->cur_attr--)
975
0
    {
976
0
      int pos = context->cur_attr;
977
0
      release_chunk (context, context->attr_names[pos]);
978
0
      release_chunk (context, context->attr_values[pos]);
979
0
      context->attr_names[pos] = context->attr_values[pos] = NULL;
980
0
    }
981
0
  g_assert (context->cur_attr == -1);
982
0
  g_assert (context->attr_names == NULL ||
983
0
            context->attr_names[0] == NULL);
984
0
  g_assert (context->attr_values == NULL ||
985
0
            context->attr_values[0] == NULL);
986
0
}
987
988
/* This has to be a separate function to ensure the alloca's
989
 * are unwound on exit - otherwise we grow & blow the stack
990
 * with large documents
991
 */
992
static inline void
993
emit_start_element (GMarkupParseContext  *context,
994
                    GError              **error)
995
0
{
996
0
  int i, j = 0;
997
0
  const gchar *start_name;
998
0
  const gchar **attr_names;
999
0
  const gchar **attr_values;
1000
0
  GError *tmp_error;
1001
1002
  /* In case we want to ignore qualified tags and we see that we have
1003
   * one here, we push a subparser.  This will ignore all tags inside of
1004
   * the qualified tag.
1005
   *
1006
   * We deal with the end of the subparser from emit_end_element.
1007
   */
1008
0
  if ((context->flags & G_MARKUP_IGNORE_QUALIFIED) && strchr (current_element (context), ':'))
1009
0
    {
1010
0
      static const GMarkupParser ignore_parser = { 0 };
1011
0
      g_markup_parse_context_push (context, &ignore_parser, NULL);
1012
0
      clear_attributes (context);
1013
0
      return;
1014
0
    }
1015
1016
0
  attr_names = g_newa (const gchar *, context->cur_attr + 2);
1017
0
  attr_values = g_newa (const gchar *, context->cur_attr + 2);
1018
0
  for (i = 0; i < context->cur_attr + 1; i++)
1019
0
    {
1020
      /* Possibly omit qualified attribute names from the list */
1021
0
      if ((context->flags & G_MARKUP_IGNORE_QUALIFIED) && strchr (context->attr_names[i]->str, ':'))
1022
0
        continue;
1023
1024
0
      attr_names[j] = context->attr_names[i]->str;
1025
0
      attr_values[j] = context->attr_values[i]->str;
1026
0
      context->attr_pos[j] = context->attr_pos[i];
1027
0
      context->attr_end[j] = context->attr_end[i];
1028
0
      j++;
1029
0
    }
1030
0
  attr_names[j] = NULL;
1031
0
  attr_values[j] = NULL;
1032
1033
  /* Call user callback for element start */
1034
0
  tmp_error = NULL;
1035
0
  start_name = current_element (context);
1036
1037
0
  if (!name_validate (context, start_name, error))
1038
0
    return;
1039
1040
0
  if (context->parser->start_element)
1041
0
    (* context->parser->start_element) (context,
1042
0
                                        start_name,
1043
0
                                        (const gchar **)attr_names,
1044
0
                                        (const gchar **)attr_values,
1045
0
                                        context->user_data,
1046
0
                                        &tmp_error);
1047
1048
0
  clear_attributes (context);
1049
1050
0
  if (tmp_error != NULL)
1051
0
    propagate_error (context, error, tmp_error);
1052
0
}
1053
1054
static void
1055
emit_end_element (GMarkupParseContext  *context,
1056
                  GError              **error)
1057
0
{
1058
  /* We need to pop the tag stack and call the end_element
1059
   * function, since this is the close tag
1060
   */
1061
0
  GError *tmp_error = NULL;
1062
1063
0
  g_assert (context->tag_stack != NULL);
1064
1065
0
  possibly_finish_subparser (context);
1066
1067
  /* We might have just returned from our ignore subparser */
1068
0
  if ((context->flags & G_MARKUP_IGNORE_QUALIFIED) && strchr (current_element (context), ':'))
1069
0
    {
1070
0
      g_markup_parse_context_pop (context);
1071
0
      pop_tag (context);
1072
0
      return;
1073
0
    }
1074
1075
0
  tmp_error = NULL;
1076
0
  if (context->parser->end_element)
1077
0
    (* context->parser->end_element) (context,
1078
0
                                      current_element (context),
1079
0
                                      context->user_data,
1080
0
                                      &tmp_error);
1081
1082
0
  ensure_no_outstanding_subparser (context);
1083
1084
0
  if (tmp_error)
1085
0
    {
1086
0
      mark_error (context, tmp_error);
1087
0
      g_propagate_error (error, tmp_error);
1088
0
    }
1089
1090
0
  pop_tag (context);
1091
0
}
1092
1093
/**
1094
 * g_markup_parse_context_parse:
1095
 * @context: a #GMarkupParseContext
1096
 * @text: chunk of text to parse
1097
 * @text_len: length of @text in bytes
1098
 * @error: return location for a #GError
1099
 *
1100
 * Feed some data to the #GMarkupParseContext.
1101
 *
1102
 * The data need not be valid UTF-8; an error will be signaled if
1103
 * it's invalid. The data need not be an entire document; you can
1104
 * feed a document into the parser incrementally, via multiple calls
1105
 * to this function. Typically, as you receive data from a network
1106
 * connection or file, you feed each received chunk of data into this
1107
 * function, aborting the process if an error occurs. Once an error
1108
 * is reported, no further data may be fed to the #GMarkupParseContext;
1109
 * all errors are fatal.
1110
 *
1111
 * Returns: %FALSE if an error occurred, %TRUE on success
1112
 */
1113
gboolean
1114
g_markup_parse_context_parse (GMarkupParseContext  *context,
1115
                              const gchar          *text,
1116
                              gssize                text_len,
1117
                              GError              **error)
1118
0
{
1119
0
  g_return_val_if_fail (context != NULL, FALSE);
1120
0
  g_return_val_if_fail (text != NULL, FALSE);
1121
0
  g_return_val_if_fail (context->state != STATE_ERROR, FALSE);
1122
0
  g_return_val_if_fail (!context->parsing, FALSE);
1123
1124
0
  if (text_len < 0)
1125
0
    text_len = strlen (text);
1126
1127
0
  if (text_len == 0)
1128
0
    return TRUE;
1129
1130
0
  context->parsing = TRUE;
1131
1132
0
  context->current_text = text;
1133
0
  context->current_text_len = text_len;
1134
0
  context->current_text_end = context->current_text + text_len;
1135
0
  context->iter = context->current_text;
1136
0
  context->start = context->iter;
1137
1138
0
  while (context->iter != context->current_text_end)
1139
0
    {
1140
0
      switch (context->state)
1141
0
        {
1142
0
        case STATE_INITIAL:
1143
0
          if ((guchar) *context->iter == 0xef)
1144
0
            {
1145
0
              advance_char (context);
1146
0
              context->state = STATE_AFTER_BOM1;
1147
0
            }
1148
0
          else
1149
0
            {
1150
0
              context->state = STATE_START;
1151
0
            }
1152
0
          break;
1153
1154
0
        case STATE_AFTER_BOM1:
1155
0
          if ((guchar) *context->iter == 0xbb)
1156
0
            {
1157
0
              advance_char (context);
1158
0
              context->state = STATE_AFTER_BOM2;
1159
0
            }
1160
0
          else
1161
0
            {
1162
0
              set_error_literal (context,
1163
0
                                 error,
1164
0
                                 G_MARKUP_ERROR_PARSE,
1165
0
                                 _("Invalid byte order mark"));
1166
0
            }
1167
0
          break;
1168
1169
0
        case STATE_AFTER_BOM2:
1170
0
          if ((guchar) *context->iter == 0xbf)
1171
0
            {
1172
0
              advance_char (context);
1173
0
              context->state = STATE_START;
1174
0
            }
1175
0
          else
1176
0
            {
1177
0
              set_error_literal (context,
1178
0
                                 error,
1179
0
                                 G_MARKUP_ERROR_PARSE,
1180
0
                                 _("Invalid byte order mark"));
1181
0
            }
1182
0
          break;
1183
1184
0
        case STATE_START:
1185
          /* Possible next state: AFTER_OPEN_ANGLE */
1186
1187
0
          g_assert (context->tag_stack == NULL);
1188
1189
          /* whitespace is ignored outside of any elements */
1190
0
          skip_spaces (context);
1191
1192
0
          if (context->iter != context->current_text_end)
1193
0
            {
1194
0
              if (*context->iter == '<')
1195
0
                {
1196
                  /* Move after the open angle */
1197
0
                  advance_char (context);
1198
1199
0
                  context->state = STATE_AFTER_OPEN_ANGLE;
1200
1201
                  /* this could start a passthrough */
1202
0
                  context->start = context->iter;
1203
1204
                  /* document is now non-empty */
1205
0
                  context->document_empty = FALSE;
1206
0
                }
1207
0
              else
1208
0
                {
1209
0
                  set_error_literal (context,
1210
0
                                     error,
1211
0
                                     G_MARKUP_ERROR_PARSE,
1212
0
                                     _("Document must begin with an element (e.g. <book>)"));
1213
0
                }
1214
0
            }
1215
0
          break;
1216
1217
0
        case STATE_AFTER_OPEN_ANGLE:
1218
          /* Possible next states: INSIDE_OPEN_TAG_NAME,
1219
           *  AFTER_CLOSE_TAG_SLASH, INSIDE_PASSTHROUGH
1220
           */
1221
0
          context->tag_start.lines = context->pos.lines;
1222
0
          context->tag_start.chars = context->pos.chars - 1;
1223
0
          context->tag_start.offset = context->pos.offset - 1;
1224
1225
0
          if (*context->iter == '?' ||
1226
0
              *context->iter == '!')
1227
0
            {
1228
              /* include < in the passthrough */
1229
0
              const gchar *openangle = "<";
1230
0
              add_to_partial (context, openangle, openangle + 1);
1231
0
              context->start = context->iter;
1232
0
              context->balance = 1;
1233
0
              context->state = STATE_INSIDE_PASSTHROUGH;
1234
0
            }
1235
0
          else if (*context->iter == '/')
1236
0
            {
1237
              /* move after it */
1238
0
              advance_char (context);
1239
1240
0
              context->state = STATE_AFTER_CLOSE_TAG_SLASH;
1241
0
            }
1242
0
          else if (!IS_COMMON_NAME_END_CHAR (*(context->iter)))
1243
0
            {
1244
0
              context->state = STATE_INSIDE_OPEN_TAG_NAME;
1245
1246
              /* start of tag name */
1247
0
              context->start = context->iter;
1248
0
            }
1249
0
          else
1250
0
            {
1251
0
              gchar buf[8];
1252
1253
0
              set_error (context,
1254
0
                         error,
1255
0
                         G_MARKUP_ERROR_PARSE,
1256
0
                         _("“%s” is not a valid character following "
1257
0
                           "a “<” character; it may not begin an "
1258
0
                           "element name"),
1259
0
                         utf8_str (context->iter,
1260
0
                                   context->current_text_end - context->iter, buf));
1261
0
            }
1262
0
          break;
1263
1264
          /* The AFTER_CLOSE_ANGLE state is actually sort of
1265
           * broken, because it doesn't correspond to a range
1266
           * of characters in the input stream as the others do,
1267
           * and thus makes things harder to conceptualize
1268
           */
1269
0
        case STATE_AFTER_CLOSE_ANGLE:
1270
          /* Possible next states: INSIDE_TEXT, STATE_START */
1271
0
          if (context->tag_stack == NULL)
1272
0
            {
1273
0
              context->start = NULL;
1274
0
              context->state = STATE_START;
1275
0
            }
1276
0
          else
1277
0
            {
1278
0
              context->start = context->iter;
1279
0
              context->state = STATE_INSIDE_TEXT;
1280
0
            }
1281
0
          break;
1282
1283
0
        case STATE_AFTER_ELISION_SLASH:
1284
          /* Possible next state: AFTER_CLOSE_ANGLE */
1285
0
          if (*context->iter == '>')
1286
0
            {
1287
              /* move after the close angle */
1288
0
              advance_char (context);
1289
0
              context->state = STATE_AFTER_CLOSE_ANGLE;
1290
0
              emit_end_element (context, error);
1291
0
            }
1292
0
          else
1293
0
            {
1294
0
              gchar buf[8];
1295
1296
0
              set_error (context,
1297
0
                         error,
1298
0
                         G_MARKUP_ERROR_PARSE,
1299
0
                         _("Odd character “%s”, expected a “>” character "
1300
0
                           "to end the empty-element tag “%s”"),
1301
0
                         utf8_str (context->iter,
1302
0
                                   context->current_text_end - context->iter, buf),
1303
0
                         current_element (context));
1304
0
            }
1305
0
          break;
1306
1307
0
        case STATE_INSIDE_OPEN_TAG_NAME:
1308
          /* Possible next states: BETWEEN_ATTRIBUTES */
1309
1310
          /* if there's a partial chunk then it's the first part of the
1311
           * tag name. If there's a context->start then it's the start
1312
           * of the tag name in current_text, the partial chunk goes
1313
           * before that start though.
1314
           */
1315
0
          advance_to_name_end (context);
1316
1317
0
          if (context->iter == context->current_text_end)
1318
0
            {
1319
              /* The name hasn't necessarily ended. Merge with
1320
               * partial chunk, leave state unchanged.
1321
               */
1322
0
              add_to_partial (context, context->start, context->iter);
1323
0
            }
1324
0
          else
1325
0
            {
1326
              /* The name has ended. Combine it with the partial chunk
1327
               * if any; push it on the stack; enter next state.
1328
               */
1329
0
              add_to_partial (context, context->start, context->iter);
1330
0
              push_partial_as_tag (context);
1331
1332
0
              context->state = STATE_BETWEEN_ATTRIBUTES;
1333
0
              context->start = NULL;
1334
0
            }
1335
0
          break;
1336
1337
0
        case STATE_INSIDE_ATTRIBUTE_NAME:
1338
          /* Possible next states: AFTER_ATTRIBUTE_NAME */
1339
1340
0
          if (!context->partial_chunk || context->partial_chunk->len == 0)
1341
0
            context->attr_start = context->pos;
1342
1343
0
          advance_to_name_end (context);
1344
0
          add_to_partial (context, context->start, context->iter);
1345
1346
          /* read the full name, if we enter the equals sign state
1347
           * then add the attribute to the list (without the value),
1348
           * otherwise store a partial chunk to be prepended later.
1349
           */
1350
0
          if (context->iter != context->current_text_end)
1351
0
            context->state = STATE_AFTER_ATTRIBUTE_NAME;
1352
0
          break;
1353
1354
0
        case STATE_AFTER_ATTRIBUTE_NAME:
1355
          /* Possible next states: AFTER_ATTRIBUTE_EQUALS_SIGN */
1356
1357
0
          skip_spaces (context);
1358
1359
0
          if (context->iter != context->current_text_end)
1360
0
            {
1361
              /* The name has ended. Combine it with the partial chunk
1362
               * if any; push it on the stack; enter next state.
1363
               */
1364
0
              if (!name_validate (context, context->partial_chunk->str, error))
1365
0
                break;
1366
1367
0
              if (!add_attribute (context, context->partial_chunk))
1368
0
                {
1369
0
                  set_error (context,
1370
0
                             error,
1371
0
                             G_MARKUP_ERROR_PARSE,
1372
0
                             _("Too many attributes in element “%s”"),
1373
0
                             current_element (context));
1374
0
                  break;
1375
0
                }
1376
1377
0
              context->partial_chunk = NULL;
1378
0
              context->start = NULL;
1379
1380
0
              if (*context->iter == '=')
1381
0
                {
1382
0
                  advance_char (context);
1383
0
                  context->state = STATE_AFTER_ATTRIBUTE_EQUALS_SIGN;
1384
0
                }
1385
0
              else
1386
0
                {
1387
0
                  gchar buf[8];
1388
1389
0
                  set_error (context,
1390
0
                             error,
1391
0
                             G_MARKUP_ERROR_PARSE,
1392
0
                             _("Odd character “%s”, expected a “=” after "
1393
0
                               "attribute name “%s” of element “%s”"),
1394
0
                             utf8_str (context->iter,
1395
0
                                       context->current_text_end - context->iter, buf),
1396
0
                             current_attribute (context),
1397
0
                             current_element (context));
1398
1399
0
                }
1400
0
            }
1401
0
          break;
1402
1403
0
        case STATE_BETWEEN_ATTRIBUTES:
1404
          /* Possible next states: AFTER_CLOSE_ANGLE,
1405
           * AFTER_ELISION_SLASH, INSIDE_ATTRIBUTE_NAME
1406
           */
1407
0
          skip_spaces (context);
1408
1409
0
          if (context->iter != context->current_text_end)
1410
0
            {
1411
0
              if (*context->iter == '/')
1412
0
                {
1413
0
                  advance_char (context);
1414
0
                  context->state = STATE_AFTER_ELISION_SLASH;
1415
0
                }
1416
0
              else if (*context->iter == '>')
1417
0
                {
1418
0
                  advance_char (context);
1419
0
                  context->state = STATE_AFTER_CLOSE_ANGLE;
1420
0
                }
1421
0
              else if (!IS_COMMON_NAME_END_CHAR (*(context->iter)))
1422
0
                {
1423
0
                  context->state = STATE_INSIDE_ATTRIBUTE_NAME;
1424
                  /* start of attribute name */
1425
0
                  context->start = context->iter;
1426
0
                }
1427
0
              else
1428
0
                {
1429
0
                  gchar buf[8];
1430
1431
0
                  set_error (context,
1432
0
                             error,
1433
0
                             G_MARKUP_ERROR_PARSE,
1434
0
                             _("Odd character “%s”, expected a “>” or “/” "
1435
0
                               "character to end the start tag of "
1436
0
                               "element “%s”, or optionally an attribute; "
1437
0
                               "perhaps you used an invalid character in "
1438
0
                               "an attribute name"),
1439
0
                             utf8_str (context->iter,
1440
0
                                       context->current_text_end - context->iter, buf),
1441
0
                             current_element (context));
1442
0
                }
1443
1444
              /* If we're done with attributes, invoke
1445
               * the start_element callback
1446
               */
1447
0
              if (context->state == STATE_AFTER_ELISION_SLASH ||
1448
0
                  context->state == STATE_AFTER_CLOSE_ANGLE)
1449
0
                emit_start_element (context, error);
1450
0
            }
1451
0
          break;
1452
1453
0
        case STATE_AFTER_ATTRIBUTE_EQUALS_SIGN:
1454
          /* Possible next state: INSIDE_ATTRIBUTE_VALUE_[SQ/DQ] */
1455
1456
0
          skip_spaces (context);
1457
1458
0
          if (context->iter != context->current_text_end)
1459
0
            {
1460
0
              if (*context->iter == '"')
1461
0
                {
1462
0
                  advance_char (context);
1463
0
                  context->state = STATE_INSIDE_ATTRIBUTE_VALUE_DQ;
1464
0
                  context->start = context->iter;
1465
0
                }
1466
0
              else if (*context->iter == '\'')
1467
0
                {
1468
0
                  advance_char (context);
1469
0
                  context->state = STATE_INSIDE_ATTRIBUTE_VALUE_SQ;
1470
0
                  context->start = context->iter;
1471
0
                }
1472
0
              else
1473
0
                {
1474
0
                  gchar buf[8];
1475
1476
0
                  set_error (context,
1477
0
                             error,
1478
0
                             G_MARKUP_ERROR_PARSE,
1479
0
                             _("Odd character “%s”, expected an open quote mark "
1480
0
                               "after the equals sign when giving value for "
1481
0
                               "attribute “%s” of element “%s”"),
1482
0
                             utf8_str (context->iter,
1483
0
                                       context->current_text_end - context->iter, buf),
1484
0
                             current_attribute (context),
1485
0
                             current_element (context));
1486
0
                }
1487
0
            }
1488
0
          break;
1489
1490
0
        case STATE_INSIDE_ATTRIBUTE_VALUE_SQ:
1491
0
        case STATE_INSIDE_ATTRIBUTE_VALUE_DQ:
1492
          /* Possible next states: BETWEEN_ATTRIBUTES */
1493
0
          {
1494
0
            gchar delim;
1495
1496
0
            if (context->state == STATE_INSIDE_ATTRIBUTE_VALUE_SQ)
1497
0
              {
1498
0
                delim = '\'';
1499
0
              }
1500
0
            else
1501
0
              {
1502
0
                delim = '"';
1503
0
              }
1504
1505
0
            do
1506
0
              {
1507
0
                if (*context->iter == delim)
1508
0
                  break;
1509
0
              }
1510
0
            while (advance_char (context));
1511
0
          }
1512
0
          if (context->iter == context->current_text_end)
1513
0
            {
1514
              /* The value hasn't necessarily ended. Merge with
1515
               * partial chunk, leave state unchanged.
1516
               */
1517
0
              add_to_partial (context, context->start, context->iter);
1518
0
            }
1519
0
          else
1520
0
            {
1521
0
              gboolean is_ascii;
1522
              /* The value has ended at the quote mark. Combine it
1523
               * with the partial chunk if any; set it for the current
1524
               * attribute.
1525
               */
1526
0
              add_to_partial (context, context->start, context->iter);
1527
1528
0
              g_assert (context->cur_attr >= 0);
1529
1530
0
              if (unescape_gstring_inplace (context, context->partial_chunk, &is_ascii, error) &&
1531
0
                  (is_ascii || text_validate (context, context->partial_chunk->str,
1532
0
                                              context->partial_chunk->len, error)))
1533
0
                {
1534
                  /* success, advance past quote and set state. */
1535
0
                  context->attr_values[context->cur_attr] = context->partial_chunk;
1536
0
                  context->partial_chunk = NULL;
1537
0
                  advance_char (context);
1538
0
                  context->attr_end[context->cur_attr] = context->pos;
1539
0
                  context->state = STATE_BETWEEN_ATTRIBUTES;
1540
0
                  context->start = NULL;
1541
0
                }
1542
1543
0
              truncate_partial (context);
1544
0
            }
1545
0
          break;
1546
1547
0
        case STATE_INSIDE_TEXT:
1548
          /* Possible next states: AFTER_OPEN_ANGLE */
1549
0
          do
1550
0
            {
1551
0
              if (*context->iter == '<')
1552
0
                break;
1553
0
            }
1554
0
          while (advance_char (context));
1555
1556
          /* The text hasn't necessarily ended. Merge with
1557
           * partial chunk, leave state unchanged.
1558
           */
1559
1560
0
          add_to_partial (context, context->start, context->iter);
1561
1562
0
          if (context->iter != context->current_text_end)
1563
0
            {
1564
0
              gboolean is_ascii;
1565
1566
              /* The text has ended at the open angle. Call the text
1567
               * callback.
1568
               */
1569
0
              if (unescape_gstring_inplace (context, context->partial_chunk, &is_ascii, error) &&
1570
0
                  (is_ascii || text_validate (context, context->partial_chunk->str,
1571
0
                                              context->partial_chunk->len, error)))
1572
0
                {
1573
0
                  GError *tmp_error = NULL;
1574
1575
0
                  if (context->parser->text)
1576
0
                    (*context->parser->text) (context,
1577
0
                                              context->partial_chunk->str,
1578
0
                                              context->partial_chunk->len,
1579
0
                                              context->user_data,
1580
0
                                              &tmp_error);
1581
1582
0
                  if (tmp_error == NULL)
1583
0
                    {
1584
                      /* advance past open angle and set state. */
1585
0
                      advance_char (context);
1586
0
                      context->state = STATE_AFTER_OPEN_ANGLE;
1587
                      /* could begin a passthrough */
1588
0
                      context->start = context->iter;
1589
0
                    }
1590
0
                  else
1591
0
                    propagate_error (context, error, tmp_error);
1592
0
                }
1593
1594
0
              truncate_partial (context);
1595
0
            }
1596
0
          break;
1597
1598
0
        case STATE_AFTER_CLOSE_TAG_SLASH:
1599
          /* Possible next state: INSIDE_CLOSE_TAG_NAME */
1600
0
          if (!IS_COMMON_NAME_END_CHAR (*(context->iter)))
1601
0
            {
1602
0
              context->state = STATE_INSIDE_CLOSE_TAG_NAME;
1603
1604
              /* start of tag name */
1605
0
              context->start = context->iter;
1606
0
            }
1607
0
          else
1608
0
            {
1609
0
              gchar buf[8];
1610
1611
0
              set_error (context,
1612
0
                         error,
1613
0
                         G_MARKUP_ERROR_PARSE,
1614
0
                         _("“%s” is not a valid character following "
1615
0
                           "the characters “</”; “%s” may not begin an "
1616
0
                           "element name"),
1617
0
                         utf8_str (context->iter,
1618
0
                                   context->current_text_end - context->iter, buf),
1619
0
                         utf8_str (context->iter,
1620
0
                                   context->current_text_end - context->iter, buf));
1621
0
            }
1622
0
          break;
1623
1624
0
        case STATE_INSIDE_CLOSE_TAG_NAME:
1625
          /* Possible next state: AFTER_CLOSE_TAG_NAME */
1626
0
          advance_to_name_end (context);
1627
0
          add_to_partial (context, context->start, context->iter);
1628
1629
0
          if (context->iter != context->current_text_end)
1630
0
            context->state = STATE_AFTER_CLOSE_TAG_NAME;
1631
0
          break;
1632
1633
0
        case STATE_AFTER_CLOSE_TAG_NAME:
1634
          /* Possible next state: AFTER_CLOSE_TAG_SLASH */
1635
1636
0
          skip_spaces (context);
1637
1638
0
          if (context->iter != context->current_text_end)
1639
0
            {
1640
0
              GString *close_name;
1641
1642
0
              close_name = context->partial_chunk;
1643
0
              context->partial_chunk = NULL;
1644
1645
0
              if (*context->iter != '>')
1646
0
                {
1647
0
                  gchar buf[8];
1648
1649
0
                  set_error (context,
1650
0
                             error,
1651
0
                             G_MARKUP_ERROR_PARSE,
1652
0
                             _("“%s” is not a valid character following "
1653
0
                               "the close element name “%s”; the allowed "
1654
0
                               "character is “>”"),
1655
0
                             utf8_str (context->iter,
1656
0
                                       context->current_text_end - context->iter, buf),
1657
0
                             close_name->str);
1658
0
                }
1659
0
              else if (context->tag_stack == NULL)
1660
0
                {
1661
0
                  set_error (context,
1662
0
                             error,
1663
0
                             G_MARKUP_ERROR_PARSE,
1664
0
                             _("Element “%s” was closed, no element "
1665
0
                               "is currently open"),
1666
0
                             close_name->str);
1667
0
                }
1668
0
              else if (strcmp (close_name->str, current_element (context)) != 0)
1669
0
                {
1670
0
                  set_error (context,
1671
0
                             error,
1672
0
                             G_MARKUP_ERROR_PARSE,
1673
0
                             _("Element “%s” was closed, but the currently "
1674
0
                               "open element is “%s”"),
1675
0
                             close_name->str,
1676
0
                             current_element (context));
1677
0
                }
1678
0
              else
1679
0
                {
1680
0
                  advance_char (context);
1681
0
                  context->state = STATE_AFTER_CLOSE_ANGLE;
1682
0
                  context->start = NULL;
1683
1684
0
                  emit_end_element (context, error);
1685
0
                }
1686
0
              context->partial_chunk = close_name;
1687
0
              truncate_partial (context);
1688
0
            }
1689
0
          break;
1690
1691
0
        case STATE_INSIDE_PASSTHROUGH:
1692
          /* Possible next state: AFTER_CLOSE_ANGLE */
1693
0
          do
1694
0
            {
1695
0
              if (*context->iter == '<')
1696
0
                context->balance++;
1697
0
              if (*context->iter == '>')
1698
0
                {
1699
0
                  gchar *str;
1700
0
                  gsize len;
1701
1702
0
                  context->balance--;
1703
0
                  add_to_partial (context, context->start, context->iter);
1704
0
                  context->start = context->iter;
1705
1706
0
                  str = context->partial_chunk->str;
1707
0
                  len = context->partial_chunk->len;
1708
1709
0
                  if (str[1] == '?' && str[len - 1] == '?')
1710
0
                    break;
1711
0
                  if (strncmp (str, "<!--", 4) == 0 &&
1712
0
                      strcmp (str + len - 2, "--") == 0)
1713
0
                    break;
1714
0
                  if (strncmp (str, "<![CDATA[", 9) == 0 &&
1715
0
                      strcmp (str + len - 2, "]]") == 0)
1716
0
                    break;
1717
0
                  if (strncmp (str, "<!DOCTYPE", 9) == 0 &&
1718
0
                      context->balance == 0)
1719
0
                    break;
1720
0
                }
1721
0
            }
1722
0
          while (advance_char (context));
1723
1724
0
          if (context->iter == context->current_text_end)
1725
0
            {
1726
              /* The passthrough hasn't necessarily ended. Merge with
1727
               * partial chunk, leave state unchanged.
1728
               */
1729
0
               add_to_partial (context, context->start, context->iter);
1730
0
            }
1731
0
          else
1732
0
            {
1733
              /* The passthrough has ended at the close angle. Combine
1734
               * it with the partial chunk if any. Call the passthrough
1735
               * callback. Note that the open/close angles are
1736
               * included in the text of the passthrough.
1737
               */
1738
0
              GError *tmp_error = NULL;
1739
1740
0
              advance_char (context); /* advance past close angle */
1741
0
              add_to_partial (context, context->start, context->iter);
1742
1743
0
              if (context->flags & G_MARKUP_TREAT_CDATA_AS_TEXT &&
1744
0
                  strncmp (context->partial_chunk->str, "<![CDATA[", 9) == 0)
1745
0
                {
1746
0
                  if (context->parser->text &&
1747
0
                      text_validate (context,
1748
0
                                     context->partial_chunk->str + 9,
1749
0
                                     context->partial_chunk->len - 12,
1750
0
                                     error))
1751
0
                    (*context->parser->text) (context,
1752
0
                                              context->partial_chunk->str + 9,
1753
0
                                              context->partial_chunk->len - 12,
1754
0
                                              context->user_data,
1755
0
                                              &tmp_error);
1756
0
                }
1757
0
              else if (context->parser->passthrough &&
1758
0
                       text_validate (context,
1759
0
                                      context->partial_chunk->str,
1760
0
                                      context->partial_chunk->len,
1761
0
                                      error))
1762
0
                (*context->parser->passthrough) (context,
1763
0
                                                 context->partial_chunk->str,
1764
0
                                                 context->partial_chunk->len,
1765
0
                                                 context->user_data,
1766
0
                                                 &tmp_error);
1767
1768
0
              truncate_partial (context);
1769
1770
0
              if (tmp_error == NULL)
1771
0
                {
1772
0
                  context->state = STATE_AFTER_CLOSE_ANGLE;
1773
0
                  context->start = context->iter; /* could begin text */
1774
0
                }
1775
0
              else
1776
0
                propagate_error (context, error, tmp_error);
1777
0
            }
1778
0
          break;
1779
1780
0
        case STATE_ERROR:
1781
0
          goto finished;
1782
0
          break;
1783
1784
0
        default:
1785
0
          g_assert_not_reached ();
1786
0
          break;
1787
0
        }
1788
0
    }
1789
1790
0
 finished:
1791
0
  context->parsing = FALSE;
1792
1793
0
  return context->state != STATE_ERROR;
1794
0
}
1795
1796
/**
1797
 * g_markup_parse_context_end_parse:
1798
 * @context: a #GMarkupParseContext
1799
 * @error: return location for a #GError
1800
 *
1801
 * Signals to the #GMarkupParseContext that all data has been
1802
 * fed into the parse context with g_markup_parse_context_parse().
1803
 *
1804
 * This function reports an error if the document isn't complete,
1805
 * for example if elements are still open.
1806
 *
1807
 * Returns: %TRUE on success, %FALSE if an error was set
1808
 */
1809
gboolean
1810
g_markup_parse_context_end_parse (GMarkupParseContext  *context,
1811
                                  GError              **error)
1812
0
{
1813
0
  g_return_val_if_fail (context != NULL, FALSE);
1814
0
  g_return_val_if_fail (!context->parsing, FALSE);
1815
0
  g_return_val_if_fail (context->state != STATE_ERROR, FALSE);
1816
1817
0
  if (context->partial_chunk != NULL)
1818
0
    {
1819
0
      g_string_free (context->partial_chunk, TRUE);
1820
0
      context->partial_chunk = NULL;
1821
0
    }
1822
1823
0
  if (context->document_empty)
1824
0
    {
1825
0
      set_error_literal (context, error, G_MARKUP_ERROR_EMPTY,
1826
0
                         _("Document was empty or contained only whitespace"));
1827
0
      return FALSE;
1828
0
    }
1829
1830
0
  context->parsing = TRUE;
1831
1832
0
  switch (context->state)
1833
0
    {
1834
0
    case STATE_START:
1835
      /* Nothing to do */
1836
0
      break;
1837
1838
0
    case STATE_AFTER_OPEN_ANGLE:
1839
0
      set_error_literal (context, error, G_MARKUP_ERROR_PARSE,
1840
0
                         _("Document ended unexpectedly just after an open angle bracket “<”"));
1841
0
      break;
1842
1843
0
    case STATE_AFTER_CLOSE_ANGLE:
1844
0
      if (context->tag_stack != NULL)
1845
0
        {
1846
          /* Error message the same as for INSIDE_TEXT */
1847
0
          set_error (context, error, G_MARKUP_ERROR_PARSE,
1848
0
                     _("Document ended unexpectedly with elements still open — "
1849
0
                       "“%s” was the last element opened"),
1850
0
                     current_element (context));
1851
0
        }
1852
0
      break;
1853
1854
0
    case STATE_AFTER_ELISION_SLASH:
1855
0
      set_error (context, error, G_MARKUP_ERROR_PARSE,
1856
0
                 _("Document ended unexpectedly, expected to see a close angle "
1857
0
                   "bracket ending the tag <%s/>"), current_element (context));
1858
0
      break;
1859
1860
0
    case STATE_INSIDE_OPEN_TAG_NAME:
1861
0
      set_error_literal (context, error, G_MARKUP_ERROR_PARSE,
1862
0
                         _("Document ended unexpectedly inside an element name"));
1863
0
      break;
1864
1865
0
    case STATE_INSIDE_ATTRIBUTE_NAME:
1866
0
    case STATE_AFTER_ATTRIBUTE_NAME:
1867
0
      set_error_literal (context, error, G_MARKUP_ERROR_PARSE,
1868
0
                         _("Document ended unexpectedly inside an attribute name"));
1869
0
      break;
1870
1871
0
    case STATE_BETWEEN_ATTRIBUTES:
1872
0
      set_error_literal (context, error, G_MARKUP_ERROR_PARSE,
1873
0
                         _("Document ended unexpectedly inside an element-opening "
1874
0
                           "tag."));
1875
0
      break;
1876
1877
0
    case STATE_AFTER_ATTRIBUTE_EQUALS_SIGN:
1878
0
      set_error_literal (context, error, G_MARKUP_ERROR_PARSE,
1879
0
                         _("Document ended unexpectedly after the equals sign "
1880
0
                           "following an attribute name; no attribute value"));
1881
0
      break;
1882
1883
0
    case STATE_INSIDE_ATTRIBUTE_VALUE_SQ:
1884
0
    case STATE_INSIDE_ATTRIBUTE_VALUE_DQ:
1885
0
      set_error_literal (context, error, G_MARKUP_ERROR_PARSE,
1886
0
                         _("Document ended unexpectedly while inside an attribute "
1887
0
                           "value"));
1888
0
      break;
1889
1890
0
    case STATE_INSIDE_TEXT:
1891
0
      g_assert (context->tag_stack != NULL);
1892
0
      set_error (context, error, G_MARKUP_ERROR_PARSE,
1893
0
                 _("Document ended unexpectedly with elements still open — "
1894
0
                   "“%s” was the last element opened"),
1895
0
                 current_element (context));
1896
0
      break;
1897
1898
0
    case STATE_AFTER_CLOSE_TAG_SLASH:
1899
0
    case STATE_INSIDE_CLOSE_TAG_NAME:
1900
0
    case STATE_AFTER_CLOSE_TAG_NAME:
1901
0
      if (context->tag_stack != NULL)
1902
0
        set_error (context, error, G_MARKUP_ERROR_PARSE,
1903
0
                   _("Document ended unexpectedly inside the close tag for "
1904
0
                     "element “%s”"), current_element (context));
1905
0
      else
1906
0
        set_error (context, error, G_MARKUP_ERROR_PARSE,
1907
0
                   _("Document ended unexpectedly inside the close tag for an "
1908
0
                     "unopened element"));
1909
0
      break;
1910
1911
0
    case STATE_INSIDE_PASSTHROUGH:
1912
0
      set_error_literal (context, error, G_MARKUP_ERROR_PARSE,
1913
0
                         _("Document ended unexpectedly inside a comment or "
1914
0
                           "processing instruction"));
1915
0
      break;
1916
1917
0
    case STATE_ERROR:
1918
0
    default:
1919
0
      g_assert_not_reached ();
1920
0
      break;
1921
0
    }
1922
1923
0
  context->parsing = FALSE;
1924
1925
0
  return context->state != STATE_ERROR;
1926
0
}
1927
1928
/**
1929
 * g_markup_parse_context_get_element:
1930
 * @context: a #GMarkupParseContext
1931
 *
1932
 * Retrieves the name of the currently open element.
1933
 *
1934
 * If called from the start_element or end_element handlers this will
1935
 * give the element_name as passed to those functions. For the parent
1936
 * elements, see g_markup_parse_context_get_element_stack().
1937
 *
1938
 * Returns: the name of the currently open element, or %NULL
1939
 *
1940
 * Since: 2.2
1941
 */
1942
const gchar *
1943
g_markup_parse_context_get_element (GMarkupParseContext *context)
1944
0
{
1945
0
  g_return_val_if_fail (context != NULL, NULL);
1946
1947
0
  if (context->tag_stack == NULL)
1948
0
    return NULL;
1949
0
  else
1950
0
    return current_element (context);
1951
0
}
1952
1953
/**
1954
 * g_markup_parse_context_get_element_stack:
1955
 * @context: a #GMarkupParseContext
1956
 *
1957
 * Retrieves the element stack from the internal state of the parser.
1958
 *
1959
 * The returned #GSList is a list of strings where the first item is
1960
 * the currently open tag (as would be returned by
1961
 * g_markup_parse_context_get_element()) and the next item is its
1962
 * immediate parent.
1963
 *
1964
 * This function is intended to be used in the start_element and
1965
 * end_element handlers where g_markup_parse_context_get_element()
1966
 * would merely return the name of the element that is being
1967
 * processed.
1968
 *
1969
 * Returns: (element-type utf8): the element stack, which must not be modified
1970
 *
1971
 * Since: 2.16
1972
 */
1973
const GSList *
1974
g_markup_parse_context_get_element_stack (GMarkupParseContext *context)
1975
0
{
1976
0
  g_return_val_if_fail (context != NULL, NULL);
1977
0
  return context->tag_stack;
1978
0
}
1979
1980
/**
1981
 * g_markup_parse_context_get_position:
1982
 * @context: a #GMarkupParseContext
1983
 * @line_number: (out) (optional): return location for a line number, or %NULL
1984
 * @char_number: (out) (optional): return location for a char-on-line number, or %NULL
1985
 *
1986
 * Retrieves the current line number and the number of the character on
1987
 * that line. Intended for use in error messages; there are no strict
1988
 * semantics for what constitutes the "current" line number other than
1989
 * "the best number we could come up with for error messages."
1990
 */
1991
void
1992
g_markup_parse_context_get_position (GMarkupParseContext *context,
1993
                                     gint                *line_number,
1994
                                     gint                *char_number)
1995
0
{
1996
0
  g_return_if_fail (context != NULL);
1997
1998
0
  if (line_number)
1999
0
    *line_number = context->pos.lines;
2000
2001
0
  if (char_number)
2002
0
    *char_number = context->pos.chars;
2003
0
}
2004
2005
/**
2006
 * g_markup_parse_context_get_offset:
2007
 * @context: a #GMarkupParseContext
2008
 *
2009
 * Retrieves the current offset from the beginning of the document,
2010
 * in bytes.
2011
 *
2012
 * The information is meant to accompany the values returned by
2013
 * [method@GLib.MarkupParseContext.get_position], and comes with the
2014
 * same accuracy guarantees.
2015
 *
2016
 * Returns: the offset
2017
 *
2018
 * Since: 2.88
2019
 */
2020
gsize
2021
g_markup_parse_context_get_offset (GMarkupParseContext *context)
2022
0
{
2023
0
  g_return_val_if_fail (context != NULL, 0);
2024
2025
0
  return context->pos.offset;
2026
0
}
2027
2028
/**
2029
 * g_markup_parse_context_get_tag_start:
2030
 * @context: a #GMarkupParseContext
2031
 * @line_number: (out): return location for the line number
2032
 * @char_number: (out): return location for the character number
2033
 * @offset: (out): return location for offset from the beginning of the document
2034
 *
2035
 * Retrieves the start position of the current start or end tag.
2036
 *
2037
 * This function can be used in the `start_element` or `end_element`
2038
 * callbacks to obtain location information for error reporting.
2039
 *
2040
 * Calling it outside of these callbacks has undefined results.
2041
 *
2042
 * Note that @line_number and @char_number are intended for human
2043
 * readable error messages and are therefore 1-based and in Unicode
2044
 * characters. @offset on the other hand is meant for programmatic
2045
 * use, and thus is 0-based and in bytes.
2046
 *
2047
 * The information is meant to accompany the values returned by
2048
 * [method@GLib.MarkupParseContext.get_position], and comes with the
2049
 * same accuracy guarantees.
2050
 *
2051
 * Since: 2.88
2052
 */
2053
void
2054
g_markup_parse_context_get_tag_start (GMarkupParseContext *context,
2055
                                      gsize               *line_number,
2056
                                      gsize               *char_number,
2057
                                      gsize               *offset)
2058
0
{
2059
0
  g_return_if_fail (context != NULL);
2060
0
  g_return_if_fail (line_number != NULL);
2061
0
  g_return_if_fail (char_number != NULL);
2062
0
  g_return_if_fail (offset != NULL);
2063
2064
0
  *line_number = context->tag_start.lines;
2065
0
  *char_number = context->tag_start.chars;
2066
0
  *offset = context->tag_start.offset;
2067
0
}
2068
2069
/**
2070
 * g_markup_parse_context_get_attribute_position:
2071
 * @context: a #GMarkupParseContext
2072
 * @attr: the index of the attribute to query
2073
 * @start_lines: (out) (optional): return location for the line number of the attribute assignment start
2074
 * @start_chars: (out) (optional): return location for the character number of the attribute assignment start
2075
 * @start_offset: (out) (optional): return location for offset of the attribute assignment
2076
 * @end_lines: (out) (optional): return location for the line number of the attribute assignment end
2077
 * @end_chars: (out) (optional): return location for the character number of the attribute assignment end
2078
 * @end_offset: (out) (optional): return location for offset of the attribute assignment end
2079
 *
2080
 * Retrieves the start and end positions of an attribute assignment
2081
 * in a start tag.
2082
 *
2083
 * This function can be used in the `start_element` callback to
2084
 * obtain location information for error reporting.
2085
 *
2086
 * Calling it outside of the `start_element` callback
2087
 * has undefined results.
2088
 *
2089
 * Note that @line_number and @char_number are intended for human
2090
 * readable error messages and are therefore 1-based and in Unicode
2091
 * characters. @offset on the other hand is meant for programmatic
2092
 * use, and thus is 0-based and in bytes.
2093
 *
2094
 * The information is meant to accompany the values returned by
2095
 * [method@GLib.MarkupParseContext.get_position], and comes with the
2096
 * same accuracy guarantees.
2097
 *
2098
 * Since: 2.90
2099
 */
2100
void
2101
g_markup_parse_context_get_attribute_position (GMarkupParseContext *context,
2102
                                               unsigned int         attr,
2103
                                               size_t              *start_lines,
2104
                                               size_t              *start_chars,
2105
                                               size_t              *start_offset,
2106
                                               size_t              *end_lines,
2107
                                               size_t              *end_chars,
2108
                                               size_t              *end_offset)
2109
0
{
2110
0
  g_return_if_fail (context != NULL);
2111
0
  g_return_if_fail (context->cur_attr >= 0 && attr <= (unsigned int) context->cur_attr);
2112
2113
0
  if (start_lines)
2114
0
    *start_lines = context->attr_pos[attr].lines;
2115
0
  if (start_chars)
2116
0
    *start_chars = context->attr_pos[attr].chars;
2117
0
  if (start_offset)
2118
0
    *start_offset = context->attr_pos[attr].offset;
2119
0
  if (end_lines)
2120
0
    *end_lines = context->attr_end[attr].lines;
2121
0
  if (end_chars)
2122
0
    *end_chars = context->attr_end[attr].chars;
2123
0
  if (end_offset)
2124
0
    *end_offset = context->attr_end[attr].offset;
2125
0
}
2126
2127
/**
2128
 * g_markup_parse_context_get_user_data:
2129
 * @context: a #GMarkupParseContext
2130
 *
2131
 * Returns the user_data associated with @context.
2132
 *
2133
 * This will either be the user_data that was provided to
2134
 * g_markup_parse_context_new() or to the most recent call
2135
 * of g_markup_parse_context_push().
2136
 *
2137
 * Returns: the provided user_data. The returned data belongs to
2138
 *     the markup context and will be freed when
2139
 *     g_markup_parse_context_free() is called.
2140
 *
2141
 * Since: 2.18
2142
 */
2143
gpointer
2144
g_markup_parse_context_get_user_data (GMarkupParseContext *context)
2145
0
{
2146
0
  return context->user_data;
2147
0
}
2148
2149
/**
2150
 * g_markup_parse_context_push:
2151
 * @context: a #GMarkupParseContext
2152
 * @parser: a #GMarkupParser
2153
 * @user_data: user data to pass to #GMarkupParser functions
2154
 *
2155
 * Temporarily redirects markup data to a sub-parser.
2156
 *
2157
 * This function may only be called from the start_element handler of
2158
 * a #GMarkupParser. It must be matched with a corresponding call to
2159
 * g_markup_parse_context_pop() in the matching end_element handler
2160
 * (except in the case that the parser aborts due to an error).
2161
 *
2162
 * All tags, text and other data between the matching tags is
2163
 * redirected to the subparser given by @parser. @user_data is used
2164
 * as the user_data for that parser. @user_data is also passed to the
2165
 * error callback in the event that an error occurs. This includes
2166
 * errors that occur in subparsers of the subparser.
2167
 *
2168
 * The end tag matching the start tag for which this call was made is
2169
 * handled by the previous parser (which is given its own user_data)
2170
 * which is why g_markup_parse_context_pop() is provided to allow "one
2171
 * last access" to the @user_data provided to this function. In the
2172
 * case of error, the @user_data provided here is passed directly to
2173
 * the error callback of the subparser and g_markup_parse_context_pop()
2174
 * should not be called. In either case, if @user_data was allocated
2175
 * then it ought to be freed from both of these locations.
2176
 *
2177
 * This function is not intended to be directly called by users
2178
 * interested in invoking subparsers. Instead, it is intended to be
2179
 * used by the subparsers themselves to implement a higher-level
2180
 * interface.
2181
 *
2182
 * As an example, see the following implementation of a simple
2183
 * parser that counts the number of tags encountered.
2184
 *
2185
 * |[<!-- language="C" --> 
2186
 * typedef struct
2187
 * {
2188
 *   gint tag_count;
2189
 * } CounterData;
2190
 *
2191
 * static void
2192
 * counter_start_element (GMarkupParseContext  *context,
2193
 *                        const gchar          *element_name,
2194
 *                        const gchar         **attribute_names,
2195
 *                        const gchar         **attribute_values,
2196
 *                        gpointer              user_data,
2197
 *                        GError              **error)
2198
 * {
2199
 *   CounterData *data = user_data;
2200
 *
2201
 *   data->tag_count++;
2202
 * }
2203
 *
2204
 * static void
2205
 * counter_error (GMarkupParseContext *context,
2206
 *                GError              *error,
2207
 *                gpointer             user_data)
2208
 * {
2209
 *   CounterData *data = user_data;
2210
 *
2211
 *   g_slice_free (CounterData, data);
2212
 * }
2213
 *
2214
 * static GMarkupParser counter_subparser =
2215
 * {
2216
 *   counter_start_element,
2217
 *   NULL,
2218
 *   NULL,
2219
 *   NULL,
2220
 *   counter_error
2221
 * };
2222
 * ]|
2223
 *
2224
 * In order to allow this parser to be easily used as a subparser, the
2225
 * following interface is provided:
2226
 *
2227
 * |[<!-- language="C" --> 
2228
 * void
2229
 * start_counting (GMarkupParseContext *context)
2230
 * {
2231
 *   CounterData *data = g_slice_new (CounterData);
2232
 *
2233
 *   data->tag_count = 0;
2234
 *   g_markup_parse_context_push (context, &counter_subparser, data);
2235
 * }
2236
 *
2237
 * gint
2238
 * end_counting (GMarkupParseContext *context)
2239
 * {
2240
 *   CounterData *data = g_markup_parse_context_pop (context);
2241
 *   int result;
2242
 *
2243
 *   result = data->tag_count;
2244
 *   g_slice_free (CounterData, data);
2245
 *
2246
 *   return result;
2247
 * }
2248
 * ]|
2249
 *
2250
 * The subparser would then be used as follows:
2251
 *
2252
 * |[<!-- language="C" --> 
2253
 * static void start_element (context, element_name, ...)
2254
 * {
2255
 *   if (strcmp (element_name, "count-these") == 0)
2256
 *     start_counting (context);
2257
 *
2258
 *   // else, handle other tags...
2259
 * }
2260
 *
2261
 * static void end_element (context, element_name, ...)
2262
 * {
2263
 *   if (strcmp (element_name, "count-these") == 0)
2264
 *     g_print ("Counted %d tags\n", end_counting (context));
2265
 *
2266
 *   // else, handle other tags...
2267
 * }
2268
 * ]|
2269
 *
2270
 * Since: 2.18
2271
 **/
2272
void
2273
g_markup_parse_context_push (GMarkupParseContext *context,
2274
                             const GMarkupParser *parser,
2275
                             gpointer             user_data)
2276
0
{
2277
0
  GMarkupRecursionTracker *tracker;
2278
2279
0
  tracker = g_slice_new (GMarkupRecursionTracker);
2280
0
  tracker->prev_element = context->subparser_element;
2281
0
  tracker->prev_parser = context->parser;
2282
0
  tracker->prev_user_data = context->user_data;
2283
2284
0
  context->subparser_element = current_element (context);
2285
0
  context->parser = parser;
2286
0
  context->user_data = user_data;
2287
2288
0
  context->subparser_stack = g_slist_prepend (context->subparser_stack,
2289
0
                                              tracker);
2290
0
}
2291
2292
/**
2293
 * g_markup_parse_context_pop:
2294
 * @context: a #GMarkupParseContext
2295
 *
2296
 * Completes the process of a temporary sub-parser redirection.
2297
 *
2298
 * This function exists to collect the user_data allocated by a
2299
 * matching call to g_markup_parse_context_push(). It must be called
2300
 * in the end_element handler corresponding to the start_element
2301
 * handler during which g_markup_parse_context_push() was called.
2302
 * You must not call this function from the error callback -- the
2303
 * @user_data is provided directly to the callback in that case.
2304
 *
2305
 * This function is not intended to be directly called by users
2306
 * interested in invoking subparsers. Instead, it is intended to
2307
 * be used by the subparsers themselves to implement a higher-level
2308
 * interface.
2309
 *
2310
 * Returns: the user data passed to g_markup_parse_context_push()
2311
 *
2312
 * Since: 2.18
2313
 */
2314
gpointer
2315
g_markup_parse_context_pop (GMarkupParseContext *context)
2316
0
{
2317
0
  gpointer user_data;
2318
2319
0
  if (!context->awaiting_pop)
2320
0
    possibly_finish_subparser (context);
2321
2322
0
  g_assert (context->awaiting_pop);
2323
2324
0
  context->awaiting_pop = FALSE;
2325
2326
  /* valgrind friendliness */
2327
0
  user_data = context->held_user_data;
2328
0
  context->held_user_data = NULL;
2329
2330
0
  return user_data;
2331
0
}
2332
2333
#define APPEND_TEXT_AND_SEEK(_str, _start, _end)          \
2334
161M
  G_STMT_START {                                          \
2335
161M
    if (_end > _start)                                    \
2336
161M
      g_string_append_len (_str, _start, _end - _start);  \
2337
161M
    _start = ++_end;                                      \
2338
161M
  } G_STMT_END
2339
2340
/*
2341
 * https://www.w3.org/TR/REC-xml/ defines the set of valid
2342
 * characters as:
2343
 *   #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF]
2344
 *
2345
 * That is, from non-ASCII UTF-8 character set, only 0xC27F - 0xC284 and
2346
 * 0xC286 - 0xC29F have to be escaped (excluding the surrogate blocks).
2347
 * Corresponding Unicode code points are [0x7F-0x84] and [0x86-0x9F].
2348
 *
2349
 * So instead of using costly g_utf8_next_char or similar UTF8 functions, it's
2350
 * better to read each byte, and make an exception for 0xC2XX.
2351
 */
2352
static void
2353
append_escaped_text (GString     *str,
2354
                     const gchar *text,
2355
                     gssize       length)
2356
3.74M
{
2357
3.74M
  const gchar *p, *pending;
2358
3.74M
  const gchar *end;
2359
2360
3.74M
  p = pending = text;
2361
3.74M
  end = text + length;
2362
2363
304M
  while (p < end && pending < end)
2364
300M
    {
2365
300M
      guchar c = (guchar) *pending;
2366
2367
300M
      switch (c)
2368
300M
        {
2369
107M
        case '&':
2370
107M
          APPEND_TEXT_AND_SEEK (str, p, pending);
2371
107M
          g_string_append (str, "&amp;");
2372
107M
          break;
2373
2374
22.5M
        case '<':
2375
22.5M
          APPEND_TEXT_AND_SEEK (str, p, pending);
2376
22.5M
          g_string_append (str, "&lt;");
2377
22.5M
          break;
2378
2379
9.74M
        case '>':
2380
9.74M
          APPEND_TEXT_AND_SEEK (str, p, pending);
2381
9.74M
          g_string_append (str, "&gt;");
2382
9.74M
          break;
2383
2384
2.19M
        case '\'':
2385
2.19M
          APPEND_TEXT_AND_SEEK (str, p, pending);
2386
2.19M
          g_string_append (str, "&apos;");
2387
2.19M
          break;
2388
2389
2.71M
        case '"':
2390
2.71M
          APPEND_TEXT_AND_SEEK (str, p, pending);
2391
2.71M
          g_string_append (str, "&quot;");
2392
2.71M
          break;
2393
2394
155M
        default:
2395
155M
          if ((0x1 <= c && c <= 0x8) ||
2396
154M
              (0xb <= c && c  <= 0xc) ||
2397
154M
              (0xe <= c && c <= 0x1f) ||
2398
138M
              (c == 0x7f))
2399
17.2M
            {
2400
17.2M
              APPEND_TEXT_AND_SEEK (str, p, pending);
2401
17.2M
              g_string_append_printf (str, "&#x%x;", c);
2402
17.2M
            }
2403
          /* The utf-8 control characters to escape begins with 0xc2 byte */
2404
138M
          else if (c == 0xc2)
2405
246k
            {
2406
246k
              gunichar u = g_utf8_get_char_validated (pending, end - pending);
2407
2408
246k
              if ((0x7f < u && u <= 0x84) ||
2409
226k
                  (0x86 <= u && u <= 0x9f))
2410
23.7k
                {
2411
23.7k
                  APPEND_TEXT_AND_SEEK (str, p, pending);
2412
23.7k
                  g_string_append_printf (str, "&#x%x;", u);
2413
2414
                  /*
2415
                   * We have appended a two byte character above, which
2416
                   * is one byte ahead of what we read on every loop.
2417
                   * Increment to skip 0xc2 and point to the right location.
2418
                   */
2419
23.7k
                  p++;
2420
23.7k
                }
2421
223k
              else
2422
223k
                {
2423
                  /* Not the UTF-8 control characters we’re looking for, or an
2424
                   * invalid or partial encoding. Pass it through. */
2425
223k
                  pending++;
2426
223k
                }
2427
246k
            }
2428
138M
          else
2429
138M
            pending++;
2430
155M
          break;
2431
300M
        }
2432
300M
    }
2433
2434
3.74M
  if (pending > p)
2435
815k
    g_string_append_len (str, p, pending - p);
2436
3.74M
}
2437
2438
#undef APPEND_TEXT_AND_SEEK
2439
2440
/**
2441
 * g_markup_escape_text:
2442
 * @text: some valid UTF-8 text
2443
 * @length: length of @text in bytes, or -1 if the text is nul-terminated
2444
 *
2445
 * Escapes text so that the markup parser will parse it verbatim.
2446
 * Less than, greater than, ampersand, etc. are replaced with the
2447
 * corresponding entities. This function would typically be used
2448
 * when writing out a file to be parsed with the markup parser.
2449
 *
2450
 * Note that this function doesn't protect whitespace and line endings
2451
 * from being processed according to the XML rules for normalization
2452
 * of line endings and attribute values.
2453
 *
2454
 * Note also that this function will produce character references in
2455
 * the range of &#x1; ... &#x1f; for all control sequences
2456
 * except for tabstop, newline and carriage return.  The character
2457
 * references in this range are not valid XML 1.0, but they are
2458
 * valid XML 1.1 and will be accepted by the GMarkup parser.
2459
 *
2460
 * Returns: a newly allocated string with the escaped text
2461
 */
2462
gchar*
2463
g_markup_escape_text (const gchar *text,
2464
                      gssize       length)
2465
3.74M
{
2466
3.74M
  GString *str;
2467
2468
3.74M
  g_return_val_if_fail (text != NULL, NULL);
2469
2470
3.74M
  if (length < 0)
2471
3.74M
    length = strlen (text);
2472
2473
  /* prealloc at least as long as original text */
2474
3.74M
  str = g_string_sized_new (length);
2475
3.74M
  append_escaped_text (str, text, length);
2476
2477
3.74M
  return g_string_free (str, FALSE);
2478
3.74M
}
2479
2480
/*
2481
 * find_conversion:
2482
 * @format: a printf-style format string
2483
 * @after: location to store a pointer to the character after
2484
 *     the returned conversion. On a %NULL return, returns the
2485
 *     pointer to the trailing NUL in the string
2486
 *
2487
 * Find the next conversion in a printf-style format string.
2488
 * Partially based on code from printf-parser.c,
2489
 * Copyright (C) 1999-2000, 2002-2003 Free Software Foundation, Inc.
2490
 *
2491
 * Returns: pointer to the next conversion in @format,
2492
 *  or %NULL, if none.
2493
 */
2494
static const char *
2495
find_conversion (const char  *format,
2496
                 const char **after)
2497
0
{
2498
0
  const char *start = format;
2499
0
  const char *cp;
2500
2501
0
  while (*start != '\0' && *start != '%')
2502
0
    start++;
2503
2504
0
  if (*start == '\0')
2505
0
    {
2506
0
      *after = start;
2507
0
      return NULL;
2508
0
    }
2509
2510
0
  cp = start + 1;
2511
2512
0
  if (*cp == '\0')
2513
0
    {
2514
0
      *after = cp;
2515
0
      return NULL;
2516
0
    }
2517
2518
  /* Test for positional argument.  */
2519
0
  if (*cp >= '0' && *cp <= '9')
2520
0
    {
2521
0
      const char *np;
2522
2523
0
      for (np = cp; *np >= '0' && *np <= '9'; np++)
2524
0
        ;
2525
0
      if (*np == '$')
2526
0
        cp = np + 1;
2527
0
    }
2528
2529
  /* Skip the flags.  */
2530
0
  for (;;)
2531
0
    {
2532
0
      if (*cp == '\'' ||
2533
0
          *cp == '-' ||
2534
0
          *cp == '+' ||
2535
0
          *cp == ' ' ||
2536
0
          *cp == '#' ||
2537
0
          *cp == '0')
2538
0
        cp++;
2539
0
      else
2540
0
        break;
2541
0
    }
2542
2543
  /* Skip the field width.  */
2544
0
  if (*cp == '*')
2545
0
    {
2546
0
      cp++;
2547
2548
      /* Test for positional argument.  */
2549
0
      if (*cp >= '0' && *cp <= '9')
2550
0
        {
2551
0
          const char *np;
2552
2553
0
          for (np = cp; *np >= '0' && *np <= '9'; np++)
2554
0
            ;
2555
0
          if (*np == '$')
2556
0
            cp = np + 1;
2557
0
        }
2558
0
    }
2559
0
  else
2560
0
    {
2561
0
      for (; *cp >= '0' && *cp <= '9'; cp++)
2562
0
        ;
2563
0
    }
2564
2565
  /* Skip the precision.  */
2566
0
  if (*cp == '.')
2567
0
    {
2568
0
      cp++;
2569
0
      if (*cp == '*')
2570
0
        {
2571
          /* Test for positional argument.  */
2572
0
          if (*cp >= '0' && *cp <= '9')
2573
0
            {
2574
0
              const char *np;
2575
2576
0
              for (np = cp; *np >= '0' && *np <= '9'; np++)
2577
0
                ;
2578
0
              if (*np == '$')
2579
0
                cp = np + 1;
2580
0
            }
2581
0
        }
2582
0
      else
2583
0
        {
2584
0
          for (; *cp >= '0' && *cp <= '9'; cp++)
2585
0
            ;
2586
0
        }
2587
0
    }
2588
2589
  /* Skip argument type/size specifiers.  */
2590
0
  while (*cp == 'h' ||
2591
0
         *cp == 'L' ||
2592
0
         *cp == 'l' ||
2593
0
         *cp == 'j' ||
2594
0
         *cp == 'z' ||
2595
0
         *cp == 'Z' ||
2596
0
         *cp == 't')
2597
0
    cp++;
2598
2599
  /* Skip the conversion character.  */
2600
0
  cp++;
2601
2602
0
  *after = cp;
2603
0
  return start;
2604
0
}
2605
2606
/**
2607
 * g_markup_vprintf_escaped:
2608
 * @format: printf() style format string
2609
 * @args: variable argument list, similar to vprintf()
2610
 *
2611
 * Formats the data in @args according to @format, escaping
2612
 * all string and character arguments in the fashion
2613
 * of g_markup_escape_text(). See g_markup_printf_escaped().
2614
 *
2615
 * Returns: newly allocated result from formatting
2616
 *  operation. Free with g_free().
2617
 *
2618
 * Since: 2.4
2619
 */
2620
#pragma GCC diagnostic push
2621
#pragma GCC diagnostic ignored "-Wformat-nonliteral"
2622
2623
gchar *
2624
g_markup_vprintf_escaped (const gchar *format,
2625
                          va_list      args)
2626
0
{
2627
0
  GString *format1;
2628
0
  GString *format2;
2629
0
  GString *result = NULL;
2630
0
  gchar *output1 = NULL;
2631
0
  gchar *output2 = NULL;
2632
0
  const char *p, *op1, *op2;
2633
0
  va_list args2;
2634
2635
  /* The technique here, is that we make two format strings that
2636
   * have the identical conversions in the identical order to the
2637
   * original strings, but differ in the text in-between. We
2638
   * then use the normal g_strdup_vprintf() to format the arguments
2639
   * with the two new format strings. By comparing the results,
2640
   * we can figure out what segments of the output come from
2641
   * the original format string, and what from the arguments,
2642
   * and thus know what portions of the string to escape.
2643
   *
2644
   * For instance, for:
2645
   *
2646
   *  g_markup_printf_escaped ("%s ate %d apples", "Susan & Fred", 5);
2647
   *
2648
   * We form the two format strings "%sX%dX" and %sY%sY". The results
2649
   * of formatting with those two strings are
2650
   *
2651
   * "%sX%dX" => "Susan & FredX5X"
2652
   * "%sY%dY" => "Susan & FredY5Y"
2653
   *
2654
   * To find the span of the first argument, we find the first position
2655
   * where the two arguments differ, which tells us that the first
2656
   * argument formatted to "Susan & Fred". We then escape that
2657
   * to "Susan & Fred" and join up with the intermediate portions
2658
   * of the format string and the second argument to get
2659
   * "Susan & Fred ate 5 apples".
2660
   */
2661
2662
  /* Create the two modified format strings
2663
   */
2664
0
  format1 = g_string_new (NULL);
2665
0
  format2 = g_string_new (NULL);
2666
0
  p = format;
2667
0
  while (TRUE)
2668
0
    {
2669
0
      const char *after;
2670
0
      const char *conv = find_conversion (p, &after);
2671
0
      if (!conv)
2672
0
        break;
2673
2674
0
      g_string_append_len (format1, conv, after - conv);
2675
0
      g_string_append_c (format1, 'X');
2676
0
      g_string_append_len (format2, conv, after - conv);
2677
0
      g_string_append_c (format2, 'Y');
2678
2679
0
      p = after;
2680
0
    }
2681
2682
  /* Use them to format the arguments
2683
   */
2684
0
  va_copy (args2, args);
2685
2686
0
  output1 = g_strdup_vprintf (format1->str, args);
2687
2688
0
  if (!output1)
2689
0
    {
2690
0
      va_end (args2);
2691
0
      goto cleanup;
2692
0
    }
2693
2694
0
  output2 = g_strdup_vprintf (format2->str, args2);
2695
0
  va_end (args2);
2696
0
  if (!output2)
2697
0
    goto cleanup;
2698
0
  result = g_string_new (NULL);
2699
2700
  /* Iterate through the original format string again,
2701
   * copying the non-conversion portions and the escaped
2702
   * converted arguments to the output string.
2703
   */
2704
0
  op1 = output1;
2705
0
  op2 = output2;
2706
0
  p = format;
2707
0
  while (TRUE)
2708
0
    {
2709
0
      const char *after;
2710
0
      const char *output_start;
2711
0
      const char *conv = find_conversion (p, &after);
2712
0
      char *escaped;
2713
2714
0
      if (!conv)        /* The end, after points to the trailing \0 */
2715
0
        {
2716
0
          g_string_append_len (result, p, after - p);
2717
0
          break;
2718
0
        }
2719
2720
0
      g_string_append_len (result, p, conv - p);
2721
0
      output_start = op1;
2722
0
      while (*op1 == *op2)
2723
0
        {
2724
0
          op1++;
2725
0
          op2++;
2726
0
        }
2727
2728
0
      escaped = g_markup_escape_text (output_start, op1 - output_start);
2729
0
      g_string_append (result, escaped);
2730
0
      g_free (escaped);
2731
2732
0
      p = after;
2733
0
      op1++;
2734
0
      op2++;
2735
0
    }
2736
2737
0
 cleanup:
2738
0
  g_string_free (format1, TRUE);
2739
0
  g_string_free (format2, TRUE);
2740
0
  g_free (output1);
2741
0
  g_free (output2);
2742
2743
0
  if (result)
2744
0
    return g_string_free (result, FALSE);
2745
0
  else
2746
0
    return NULL;
2747
0
}
2748
2749
#pragma GCC diagnostic pop
2750
2751
/**
2752
 * g_markup_printf_escaped:
2753
 * @format: printf() style format string
2754
 * @...: the arguments to insert in the format string
2755
 *
2756
 * Formats arguments according to @format, escaping
2757
 * all string and character arguments in the fashion
2758
 * of g_markup_escape_text(). This is useful when you
2759
 * want to insert literal strings into XML-style markup
2760
 * output, without having to worry that the strings
2761
 * might themselves contain markup.
2762
 *
2763
 * |[<!-- language="C" --> 
2764
 * const char *store = "Fortnum & Mason";
2765
 * const char *item = "Tea";
2766
 * char *output;
2767
 * 
2768
 * output = g_markup_printf_escaped ("<purchase>"
2769
 *                                   "<store>%s</store>"
2770
 *                                   "<item>%s</item>"
2771
 *                                   "</purchase>",
2772
 *                                   store, item);
2773
 * ]|
2774
 *
2775
 * Returns: newly allocated result from formatting
2776
 *    operation. Free with g_free().
2777
 *
2778
 * Since: 2.4
2779
 */
2780
gchar *
2781
g_markup_printf_escaped (const gchar *format, ...)
2782
0
{
2783
0
  char *result;
2784
0
  va_list args;
2785
2786
0
  va_start (args, format);
2787
0
  result = g_markup_vprintf_escaped (format, args);
2788
0
  va_end (args);
2789
2790
0
  return result;
2791
0
}
2792
2793
static gboolean
2794
g_markup_parse_boolean (const char  *string,
2795
                        gboolean    *value)
2796
0
{
2797
0
  char const * const falses[] = { "false", "f", "no", "n", "0" };
2798
0
  char const * const trues[] = { "true", "t", "yes", "y", "1" };
2799
0
  gsize i;
2800
2801
0
  for (i = 0; i < G_N_ELEMENTS (falses); i++)
2802
0
    {
2803
0
      if (g_ascii_strcasecmp (string, falses[i]) == 0)
2804
0
        {
2805
0
          if (value != NULL)
2806
0
            *value = FALSE;
2807
2808
0
          return TRUE;
2809
0
        }
2810
0
    }
2811
2812
0
  for (i = 0; i < G_N_ELEMENTS (trues); i++)
2813
0
    {
2814
0
      if (g_ascii_strcasecmp (string, trues[i]) == 0)
2815
0
        {
2816
0
          if (value != NULL)
2817
0
            *value = TRUE;
2818
2819
0
          return TRUE;
2820
0
        }
2821
0
    }
2822
2823
0
  return FALSE;
2824
0
}
2825
2826
/**
2827
 * GMarkupCollectType:
2828
 * @G_MARKUP_COLLECT_INVALID: used to terminate the list of attributes
2829
 *     to collect
2830
 * @G_MARKUP_COLLECT_STRING: collect the string pointer directly from
2831
 *     the attribute_values[] array. Expects a parameter of type (const
2832
 *     char **). If %G_MARKUP_COLLECT_OPTIONAL is specified and the
2833
 *     attribute isn't present then the pointer will be set to %NULL
2834
 * @G_MARKUP_COLLECT_STRDUP: as with %G_MARKUP_COLLECT_STRING, but
2835
 *     expects a parameter of type (char **) and g_strdup()s the
2836
 *     returned pointer. The pointer must be freed with g_free()
2837
 * @G_MARKUP_COLLECT_BOOLEAN: expects a parameter of type (`gboolean *`)
2838
 *     and parses the attribute value as a boolean. Sets %FALSE if the
2839
 *     attribute isn't present. Valid boolean values consist of
2840
 *     (case-insensitive) "false", "f", "no", "n", "0" and "true", "t",
2841
 *     "yes", "y", "1"
2842
 * @G_MARKUP_COLLECT_TRISTATE: as with %G_MARKUP_COLLECT_BOOLEAN, but
2843
 *     in the case of a missing attribute a value is set that compares
2844
 *     equal to neither %FALSE nor %TRUE %G_MARKUP_COLLECT_OPTIONAL is
2845
 *     implied
2846
 * @G_MARKUP_COLLECT_OPTIONAL: can be bitwise ORed with the other fields.
2847
 *     If present, allows the attribute not to appear. A default value
2848
 *     is set depending on what value type is used
2849
 *
2850
 * A mixed enumerated type and flags field. You must specify one type
2851
 * (string, strdup, boolean, tristate).  Additionally, you may  optionally
2852
 * bitwise OR the type with the flag %G_MARKUP_COLLECT_OPTIONAL.
2853
 *
2854
 * It is likely that this enum will be extended in the future to
2855
 * support other types.
2856
 */
2857
2858
/**
2859
 * g_markup_collect_attributes:
2860
 * @element_name: the current tag name
2861
 * @attribute_names: the attribute names
2862
 * @attribute_values: the attribute values
2863
 * @error: a pointer to a #GError or %NULL
2864
 * @first_type: the #GMarkupCollectType of the first attribute
2865
 * @first_attr: the name of the first attribute
2866
 * @...: a pointer to the storage location of the first attribute
2867
 *     (or %NULL), followed by more types names and pointers, ending
2868
 *     with %G_MARKUP_COLLECT_INVALID
2869
 *
2870
 * Collects the attributes of the element from the data passed to the
2871
 * #GMarkupParser start_element function, dealing with common error
2872
 * conditions and supporting boolean values.
2873
 *
2874
 * This utility function is not required to write a parser but can save
2875
 * a lot of typing.
2876
 *
2877
 * The @element_name, @attribute_names, @attribute_values and @error
2878
 * parameters passed to the start_element callback should be passed
2879
 * unmodified to this function.
2880
 *
2881
 * Following these arguments is a list of "supported" attributes to collect.
2882
 * It is an error to specify multiple attributes with the same name. If any
2883
 * attribute not in the list appears in the @attribute_names array then an
2884
 * unknown attribute error will result.
2885
 *
2886
 * The #GMarkupCollectType field allows specifying the type of collection
2887
 * to perform and if a given attribute must appear or is optional.
2888
 *
2889
 * The attribute name is simply the name of the attribute to collect.
2890
 *
2891
 * The pointer should be of the appropriate type (see the descriptions
2892
 * under #GMarkupCollectType) and may be %NULL in case a particular
2893
 * attribute is to be allowed but ignored.
2894
 *
2895
 * This function deals with issuing errors for missing attributes
2896
 * (of type %G_MARKUP_ERROR_MISSING_ATTRIBUTE), unknown attributes
2897
 * (of type %G_MARKUP_ERROR_UNKNOWN_ATTRIBUTE) and duplicate
2898
 * attributes (of type %G_MARKUP_ERROR_INVALID_CONTENT) as well
2899
 * as parse errors for boolean-valued attributes (again of type
2900
 * %G_MARKUP_ERROR_INVALID_CONTENT). In all of these cases %FALSE
2901
 * will be returned and @error will be set as appropriate.
2902
 *
2903
 * Returns: %TRUE if successful
2904
 *
2905
 * Since: 2.16
2906
 **/
2907
gboolean
2908
g_markup_collect_attributes (const gchar         *element_name,
2909
                             const gchar        **attribute_names,
2910
                             const gchar        **attribute_values,
2911
                             GError             **error,
2912
                             GMarkupCollectType   first_type,
2913
                             const gchar         *first_attr,
2914
                             ...)
2915
0
{
2916
0
  GMarkupCollectType type;
2917
0
  const gchar *attr;
2918
0
  guint64 collected;
2919
0
  int written;
2920
0
  va_list ap;
2921
0
  int i;
2922
2923
0
  type = first_type;
2924
0
  attr = first_attr;
2925
0
  collected = 0;
2926
0
  written = 0;
2927
2928
0
  va_start (ap, first_attr);
2929
0
  while (type != G_MARKUP_COLLECT_INVALID)
2930
0
    {
2931
0
      gboolean mandatory;
2932
0
      const gchar *value;
2933
2934
0
      mandatory = !(type & G_MARKUP_COLLECT_OPTIONAL);
2935
0
      type &= (G_MARKUP_COLLECT_OPTIONAL - 1);
2936
2937
      /* tristate records a value != TRUE and != FALSE
2938
       * for the case where the attribute is missing
2939
       */
2940
0
      if (type == G_MARKUP_COLLECT_TRISTATE)
2941
0
        mandatory = FALSE;
2942
2943
0
      for (i = 0; attribute_names[i]; i++)
2944
0
        if (i >= 40 || !(collected & (G_GUINT64_CONSTANT(1) << i)))
2945
0
          if (!strcmp (attribute_names[i], attr))
2946
0
            break;
2947
2948
      /* ISO C99 only promises that the user can pass up to 127 arguments.
2949
       * Subtracting the first 4 arguments plus the final NULL and dividing
2950
       * by 3 arguments per collected attribute, we are left with a maximum
2951
       * number of supported attributes of (127 - 5) / 3 = 40.
2952
       *
2953
       * In reality, nobody is ever going to call us with anywhere close to
2954
       * 40 attributes to collect, so it is safe to assume that if i > 40
2955
       * then the user has given some invalid or repeated arguments.  These
2956
       * problems will be caught and reported at the end of the function.
2957
       *
2958
       * We know at this point that we have an error, but we don't know
2959
       * what error it is, so just continue...
2960
       */
2961
0
      if (i < 40)
2962
0
        collected |= (G_GUINT64_CONSTANT(1) << i);
2963
2964
0
      value = attribute_values[i];
2965
2966
0
      if (value == NULL && mandatory)
2967
0
        {
2968
0
          g_set_error (error, G_MARKUP_ERROR,
2969
0
                       G_MARKUP_ERROR_MISSING_ATTRIBUTE,
2970
0
                       "element '%s' requires attribute '%s'",
2971
0
                       element_name, attr);
2972
2973
0
          va_end (ap);
2974
0
          goto failure;
2975
0
        }
2976
2977
0
      switch (type)
2978
0
        {
2979
0
        case G_MARKUP_COLLECT_STRING:
2980
0
          {
2981
0
            const char **str_ptr;
2982
2983
0
            str_ptr = va_arg (ap, const char **);
2984
2985
0
            if (str_ptr != NULL)
2986
0
              *str_ptr = value;
2987
0
          }
2988
0
          break;
2989
2990
0
        case G_MARKUP_COLLECT_STRDUP:
2991
0
          {
2992
0
            char **str_ptr;
2993
2994
0
            str_ptr = va_arg (ap, char **);
2995
2996
0
            if (str_ptr != NULL)
2997
0
              *str_ptr = g_strdup (value);
2998
0
          }
2999
0
          break;
3000
3001
0
        case G_MARKUP_COLLECT_BOOLEAN:
3002
0
        case G_MARKUP_COLLECT_TRISTATE:
3003
0
          if (value == NULL)
3004
0
            {
3005
0
              gboolean *bool_ptr;
3006
3007
0
              bool_ptr = va_arg (ap, gboolean *);
3008
3009
0
              if (bool_ptr != NULL)
3010
0
                {
3011
0
                  if (type == G_MARKUP_COLLECT_TRISTATE)
3012
                    /* constructivists rejoice!
3013
                     * neither false nor true...
3014
                     */
3015
0
                    *bool_ptr = -1;
3016
3017
0
                  else /* G_MARKUP_COLLECT_BOOLEAN */
3018
0
                    *bool_ptr = FALSE;
3019
0
                }
3020
0
            }
3021
0
          else
3022
0
            {
3023
0
              if (!g_markup_parse_boolean (value, va_arg (ap, gboolean *)))
3024
0
                {
3025
0
                  g_set_error (error, G_MARKUP_ERROR,
3026
0
                               G_MARKUP_ERROR_INVALID_CONTENT,
3027
0
                               "element '%s', attribute '%s', value '%s' "
3028
0
                               "cannot be parsed as a boolean value",
3029
0
                               element_name, attr, value);
3030
3031
0
                  va_end (ap);
3032
0
                  goto failure;
3033
0
                }
3034
0
            }
3035
3036
0
          break;
3037
3038
0
        default:
3039
0
          g_assert_not_reached ();
3040
0
        }
3041
3042
0
      written++;
3043
0
      type = va_arg (ap, GMarkupCollectType);
3044
0
      if (type != G_MARKUP_COLLECT_INVALID)
3045
0
        attr = va_arg (ap, const char *);
3046
0
    }
3047
0
  va_end (ap);
3048
3049
  /* ensure we collected all the arguments */
3050
0
  for (i = 0; attribute_names[i]; i++)
3051
0
    if ((collected & (G_GUINT64_CONSTANT(1) << i)) == 0)
3052
0
      {
3053
        /* attribute not collected:  could be caused by two things.
3054
         *
3055
         * 1) it doesn't exist in our list of attributes
3056
         * 2) it existed but was matched by a duplicate attribute earlier
3057
         *
3058
         * find out.
3059
         */
3060
0
        int j;
3061
3062
0
        for (j = 0; j < i; j++)
3063
0
          if (strcmp (attribute_names[i], attribute_names[j]) == 0)
3064
            /* duplicate! */
3065
0
            break;
3066
3067
        /* j is now the first occurrence of attribute_names[i] */
3068
0
        if (i == j)
3069
0
          g_set_error (error, G_MARKUP_ERROR,
3070
0
                       G_MARKUP_ERROR_UNKNOWN_ATTRIBUTE,
3071
0
                       "attribute '%s' invalid for element '%s'",
3072
0
                       attribute_names[i], element_name);
3073
0
        else
3074
0
          g_set_error (error, G_MARKUP_ERROR,
3075
0
                       G_MARKUP_ERROR_INVALID_CONTENT,
3076
0
                       "attribute '%s' given multiple times for element '%s'",
3077
0
                       attribute_names[i], element_name);
3078
3079
0
        goto failure;
3080
0
      }
3081
3082
0
  return TRUE;
3083
3084
0
failure:
3085
  /* replay the above to free allocations */
3086
0
  type = first_type;
3087
3088
0
  va_start (ap, first_attr);
3089
0
  while (type != G_MARKUP_COLLECT_INVALID)
3090
0
    {
3091
0
      gpointer ptr;
3092
3093
0
      ptr = va_arg (ap, gpointer);
3094
3095
0
      if (ptr != NULL)
3096
0
        {
3097
0
          switch (type & (G_MARKUP_COLLECT_OPTIONAL - 1))
3098
0
            {
3099
0
            case G_MARKUP_COLLECT_STRDUP:
3100
0
              if (written)
3101
0
                g_free (*(char **) ptr);
3102
0
              *(char **) ptr = NULL;
3103
0
              break;
3104
3105
0
            case G_MARKUP_COLLECT_STRING:
3106
0
              *(char **) ptr = NULL;
3107
0
              break;
3108
3109
0
            case G_MARKUP_COLLECT_BOOLEAN:
3110
0
              *(gboolean *) ptr = FALSE;
3111
0
              break;
3112
3113
0
            case G_MARKUP_COLLECT_TRISTATE:
3114
0
              *(gboolean *) ptr = -1;
3115
0
              break;
3116
0
            }
3117
0
        }
3118
3119
0
      type = va_arg (ap, GMarkupCollectType);
3120
0
      if (type != G_MARKUP_COLLECT_INVALID)
3121
0
        {
3122
0
          attr = va_arg (ap, const char *);
3123
0
          (void) attr;
3124
0
        }
3125
0
    }
3126
0
  va_end (ap);
3127
3128
0
  return FALSE;
3129
0
}