Coverage Report

Created: 2025-12-14 06:36

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/qpdf/libqpdf/QPDFTokenizer.cc
Line
Count
Source
1
#include <qpdf/QPDFTokenizer_private.hh>
2
3
// DO NOT USE ctype -- it is locale dependent for some things, and it's not worth the risk of
4
// including it in case it may accidentally be used.
5
6
#include <qpdf/InputSource_private.hh>
7
#include <qpdf/QIntC.hh>
8
#include <qpdf/QPDFExc.hh>
9
#include <qpdf/QPDFObjectHandle.hh>
10
#include <qpdf/QTC.hh>
11
#include <qpdf/QUtil.hh>
12
#include <qpdf/Util.hh>
13
14
#include <cstdlib>
15
#include <cstring>
16
#include <stdexcept>
17
18
using namespace qpdf;
19
20
using Token = QPDFTokenizer::Token;
21
using tt = QPDFTokenizer::token_type_e;
22
23
static inline bool
24
is_delimiter(char ch)
25
152M
{
26
152M
    return (
27
152M
        ch == ' ' || ch == '\n' || ch == '/' || ch == '(' || ch == ')' || ch == '{' || ch == '}' ||
28
144M
        ch == '<' || ch == '>' || ch == '[' || ch == ']' || ch == '%' || ch == '\t' || ch == '\r' ||
29
143M
        ch == '\v' || ch == '\f' || ch == 0);
30
152M
}
31
32
namespace
33
{
34
    class QPDFWordTokenFinder: public InputSource::Finder
35
    {
36
      public:
37
        QPDFWordTokenFinder(InputSource& is, std::string const& str) :
38
12.9k
            is(is),
39
12.9k
            str(str)
40
12.9k
        {
41
12.9k
        }
42
12.9k
        ~QPDFWordTokenFinder() override = default;
43
        bool check() override;
44
45
      private:
46
        InputSource& is;
47
        std::string str;
48
    };
49
} // namespace
50
51
bool
52
QPDFWordTokenFinder::check()
53
123k
{
54
    // Find a word token matching the given string, preceded by a delimiter, and followed by a
55
    // delimiter or EOF.
56
123k
    Tokenizer tokenizer;
57
123k
    tokenizer.nextToken(is, "finder", str.size() + 2);
58
123k
    qpdf_offset_t pos = is.tell();
59
123k
    if (tokenizer.getType() != tt::tt_word || tokenizer.getValue() != str) {
60
110k
        QTC::TC("qpdf", "QPDFTokenizer finder found wrong word");
61
110k
        return false;
62
110k
    }
63
12.3k
    qpdf_offset_t token_start = is.getLastOffset();
64
12.3k
    char next;
65
12.3k
    bool next_okay = false;
66
12.3k
    if (is.read(&next, 1) == 0) {
67
2
        QTC::TC("qpdf", "QPDFTokenizer inline image at EOF");
68
2
        next_okay = true;
69
12.3k
    } else {
70
12.3k
        next_okay = is_delimiter(next);
71
12.3k
    }
72
12.3k
    is.seek(pos, SEEK_SET);
73
12.3k
    if (!next_okay) {
74
0
        return false;
75
0
    }
76
12.3k
    if (token_start == 0) {
77
        // Can't actually happen...we never start the search at the beginning of the input.
78
0
        return false;
79
0
    }
80
12.3k
    return true;
81
12.3k
}
82
83
void
84
Tokenizer::reset()
85
18.9M
{
86
18.9M
    state = st_before_token;
87
18.9M
    type = tt::tt_bad;
88
18.9M
    val.clear();
89
18.9M
    raw_val.clear();
90
18.9M
    error_message = "";
91
18.9M
    before_token = true;
92
18.9M
    in_token = false;
93
18.9M
    char_to_unread = '\0';
94
18.9M
    inline_image_bytes = 0;
95
18.9M
    string_depth = 0;
96
18.9M
    bad = false;
97
18.9M
}
98
99
QPDFTokenizer::Token::Token(token_type_e type, std::string const& value) :
100
587
    type(type),
101
587
    value(value),
102
587
    raw_value(value)
103
587
{
104
587
    if (type == tt_string) {
105
0
        raw_value = QPDFObjectHandle::newString(value).unparse();
106
587
    } else if (type == tt_name) {
107
0
        raw_value = QPDFObjectHandle::newName(value).unparse();
108
0
    }
109
587
}
110
111
QPDFTokenizer::QPDFTokenizer() :
112
5.45k
    m(std::make_unique<qpdf::Tokenizer>())
113
5.45k
{
114
5.45k
}
115
116
5.45k
QPDFTokenizer::~QPDFTokenizer() = default;
117
118
Tokenizer::Tokenizer()
119
182k
{
120
182k
    reset();
121
182k
}
122
123
void
124
QPDFTokenizer::allowEOF()
125
5.45k
{
126
5.45k
    m->allowEOF();
127
5.45k
}
128
129
void
130
Tokenizer::allowEOF()
131
46.8k
{
132
46.8k
    allow_eof = true;
133
46.8k
}
134
135
void
136
QPDFTokenizer::includeIgnorable()
137
5.45k
{
138
5.45k
    m->includeIgnorable();
139
5.45k
}
140
141
void
142
Tokenizer::includeIgnorable()
143
5.45k
{
144
5.45k
    include_ignorable = true;
145
5.45k
}
146
147
bool
148
Tokenizer::isSpace(char ch)
149
29.3M
{
150
29.3M
    return (ch == '\0' || util::is_space(ch));
151
29.3M
}
152
153
bool
154
Tokenizer::isDelimiter(char ch)
155
152M
{
156
152M
    return is_delimiter(ch);
157
152M
}
158
159
void
160
QPDFTokenizer::presentCharacter(char ch)
161
0
{
162
0
    m->presentCharacter(ch);
163
0
}
164
165
void
166
Tokenizer::presentCharacter(char ch)
167
22.7k
{
168
22.7k
    handleCharacter(ch);
169
170
22.7k
    if (in_token) {
171
0
        raw_val += ch;
172
0
    }
173
22.7k
}
174
175
void
176
Tokenizer::handleCharacter(char ch)
177
298M
{
178
    // In some cases, functions called below may call a second handler. This happens whenever you
179
    // have to use a character from the next token to detect the end of the current token.
180
181
298M
    switch (state) {
182
0
    case st_top:
183
0
        inTop(ch);
184
0
        return;
185
186
125k
    case st_in_space:
187
125k
        inSpace(ch);
188
125k
        return;
189
190
3.53M
    case st_in_comment:
191
3.53M
        inComment(ch);
192
3.53M
        return;
193
194
745k
    case st_lt:
195
745k
        inLt(ch);
196
745k
        return;
197
198
357k
    case st_gt:
199
357k
        inGt(ch);
200
357k
        return;
201
202
94.6M
    case st_in_string:
203
94.6M
        inString(ch);
204
94.6M
        return;
205
206
90.3M
    case st_name:
207
90.3M
        inName(ch);
208
90.3M
        return;
209
210
11.9M
    case st_number:
211
11.9M
        inNumber(ch);
212
11.9M
        return;
213
214
965k
    case st_real:
215
965k
        inReal(ch);
216
965k
        return;
217
218
109k
    case st_string_after_cr:
219
109k
        inStringAfterCR(ch);
220
109k
        return;
221
222
373k
    case st_string_escape:
223
373k
        inStringEscape(ch);
224
373k
        return;
225
226
59.1k
    case st_char_code:
227
59.1k
        inCharCode(ch);
228
59.1k
        return;
229
230
57.6M
    case st_literal:
231
57.6M
        inLiteral(ch);
232
57.6M
        return;
233
234
6.05M
    case st_inline_image:
235
6.05M
        inInlineImage(ch);
236
6.05M
        return;
237
238
649k
    case st_in_hexstring:
239
649k
        inHexstring(ch);
240
649k
        return;
241
242
632k
    case st_in_hexstring_2nd:
243
632k
        inHexstring2nd(ch);
244
632k
        return;
245
246
961k
    case st_name_hex1:
247
961k
        inNameHex1(ch);
248
961k
        return;
249
250
13.1k
    case st_name_hex2:
251
13.1k
        inNameHex2(ch);
252
13.1k
        return;
253
254
193k
    case st_sign:
255
193k
        inSign(ch);
256
193k
        return;
257
258
30.8k
    case st_decimal:
259
30.8k
        inDecimal(ch);
260
30.8k
        return;
261
262
29.0M
    case (st_before_token):
263
29.0M
        inBeforeToken(ch);
264
29.0M
        return;
265
266
0
    case (st_token_ready):
267
0
        inTokenReady(ch);
268
0
        return;
269
270
0
    default:
271
0
        throw std::logic_error("INTERNAL ERROR: invalid state while reading token");
272
298M
    }
273
298M
}
274
275
void
276
Tokenizer::inTokenReady(char ch)
277
0
{
278
0
    throw std::logic_error(
279
0
        "INTERNAL ERROR: QPDF tokenizer presented character while token is waiting");
280
0
}
281
282
void
283
Tokenizer::inBeforeToken(char ch)
284
29.0M
{
285
    // Note: we specifically do not use ctype here.  It is locale-dependent.
286
29.0M
    if (isSpace(ch)) {
287
14.9M
        before_token = !include_ignorable;
288
14.9M
        in_token = include_ignorable;
289
14.9M
        if (include_ignorable) {
290
88.6k
            state = st_in_space;
291
88.6k
        }
292
14.9M
    } else if (ch == '%') {
293
39.7k
        before_token = !include_ignorable;
294
39.7k
        in_token = include_ignorable;
295
39.7k
        state = st_in_comment;
296
14.0M
    } else {
297
14.0M
        before_token = false;
298
14.0M
        in_token = true;
299
14.0M
        inTop(ch);
300
14.0M
    }
301
29.0M
}
302
303
void
304
Tokenizer::inTop(char ch)
305
14.0M
{
306
14.0M
    switch (ch) {
307
303k
    case '(':
308
303k
        string_depth = 1;
309
303k
        state = st_in_string;
310
303k
        return;
311
312
756k
    case '<':
313
756k
        state = st_lt;
314
756k
        return;
315
316
359k
    case '>':
317
359k
        state = st_gt;
318
359k
        return;
319
320
25.8k
    case (')'):
321
25.8k
        type = tt::tt_bad;
322
25.8k
        QTC::TC("qpdf", "QPDFTokenizer bad )");
323
25.8k
        error_message = "unexpected )";
324
25.8k
        state = st_token_ready;
325
25.8k
        return;
326
327
301k
    case '[':
328
301k
        type = tt::tt_array_open;
329
301k
        state = st_token_ready;
330
301k
        return;
331
332
208k
    case ']':
333
208k
        type = tt::tt_array_close;
334
208k
        state = st_token_ready;
335
208k
        return;
336
337
1.07M
    case '{':
338
1.07M
        type = tt::tt_brace_open;
339
1.07M
        state = st_token_ready;
340
1.07M
        return;
341
342
8.11k
    case '}':
343
8.11k
        type = tt::tt_brace_close;
344
8.11k
        state = st_token_ready;
345
8.11k
        return;
346
347
3.18M
    case '/':
348
3.18M
        state = st_name;
349
3.18M
        val += ch;
350
3.18M
        return;
351
352
1.47M
    case '0':
353
2.31M
    case '1':
354
2.65M
    case '2':
355
2.85M
    case '3':
356
3.13M
    case '4':
357
3.34M
    case '5':
358
3.52M
    case '6':
359
3.68M
    case '7':
360
3.88M
    case '8':
361
3.95M
    case '9':
362
3.95M
        state = st_number;
363
3.95M
        return;
364
365
11.8k
    case '+':
366
206k
    case '-':
367
206k
        state = st_sign;
368
206k
        return;
369
370
44.6k
    case '.':
371
44.6k
        state = st_decimal;
372
44.6k
        return;
373
374
3.66M
    default:
375
3.66M
        state = st_literal;
376
3.66M
        return;
377
14.0M
    }
378
14.0M
}
379
380
void
381
Tokenizer::inSpace(char ch)
382
125k
{
383
    // We only enter this state if include_ignorable is true.
384
125k
    if (!isSpace(ch)) {
385
88.5k
        type = tt::tt_space;
386
88.5k
        in_token = false;
387
88.5k
        char_to_unread = ch;
388
88.5k
        state = st_token_ready;
389
88.5k
    }
390
125k
}
391
392
void
393
Tokenizer::inComment(char ch)
394
3.53M
{
395
3.53M
    if ((ch == '\r') || (ch == '\n')) {
396
38.7k
        if (include_ignorable) {
397
423
            type = tt::tt_comment;
398
423
            in_token = false;
399
423
            char_to_unread = ch;
400
423
            state = st_token_ready;
401
38.3k
        } else {
402
38.3k
            state = st_before_token;
403
38.3k
        }
404
38.7k
    }
405
3.53M
}
406
407
void
408
Tokenizer::inString(char ch)
409
94.7M
{
410
94.7M
    switch (ch) {
411
373k
    case '\\':
412
373k
        state = st_string_escape;
413
373k
        return;
414
415
100k
    case '(':
416
100k
        val += ch;
417
100k
        ++string_depth;
418
100k
        return;
419
420
340k
    case ')':
421
340k
        if (--string_depth == 0) {
422
288k
            type = tt::tt_string;
423
288k
            state = st_token_ready;
424
288k
            return;
425
288k
        }
426
427
52.2k
        val += ch;
428
52.2k
        return;
429
430
109k
    case '\r':
431
        // CR by itself is converted to LF
432
109k
        val += '\n';
433
109k
        state = st_string_after_cr;
434
109k
        return;
435
436
750k
    case '\n':
437
750k
        val += ch;
438
750k
        return;
439
440
93.0M
    default:
441
93.0M
        val += ch;
442
93.0M
        return;
443
94.7M
    }
444
94.7M
}
445
446
void
447
Tokenizer::inName(char ch)
448
91.2M
{
449
91.2M
    if (isDelimiter(ch)) {
450
        // A C-locale whitespace character or delimiter terminates token.  It is important to unread
451
        // the whitespace character even though it is ignored since it may be the newline after a
452
        // stream keyword.  Removing it here could make the stream-reading code break on some files,
453
        // though not on any files in the test suite as of this
454
        // writing.
455
456
3.04M
        type = bad ? tt::tt_bad : tt::tt_name;
457
3.04M
        in_token = false;
458
3.04M
        char_to_unread = ch;
459
3.04M
        state = st_token_ready;
460
88.2M
    } else if (ch == '#') {
461
961k
        char_code = 0;
462
961k
        state = st_name_hex1;
463
87.2M
    } else {
464
87.2M
        val += ch;
465
87.2M
    }
466
91.2M
}
467
468
void
469
Tokenizer::inNameHex1(char ch)
470
961k
{
471
961k
    hex_char = ch;
472
473
961k
    if (char hval = util::hex_decode_char(ch); hval < '\20') {
474
13.1k
        char_code = int(hval) << 4;
475
13.1k
        state = st_name_hex2;
476
948k
    } else {
477
948k
        QTC::TC("qpdf", "QPDFTokenizer bad name 1");
478
948k
        error_message = "name with stray # will not work with PDF >= 1.2";
479
        // Use null to encode a bad # -- this is reversed in QPDF_Name::normalizeName.
480
948k
        val += '\0';
481
948k
        state = st_name;
482
948k
        inName(ch);
483
948k
    }
484
961k
}
485
486
void
487
Tokenizer::inNameHex2(char ch)
488
13.1k
{
489
13.1k
    if (char hval = util::hex_decode_char(ch); hval < '\20') {
490
3.36k
        char_code |= int(hval);
491
9.77k
    } else {
492
9.77k
        QTC::TC("qpdf", "QPDFTokenizer bad name 2");
493
9.77k
        error_message = "name with stray # will not work with PDF >= 1.2";
494
        // Use null to encode a bad # -- this is reversed in QPDF_Name::normalizeName.
495
9.77k
        val += '\0';
496
9.77k
        val += hex_char;
497
9.77k
        state = st_name;
498
9.77k
        inName(ch);
499
9.77k
        return;
500
9.77k
    }
501
3.36k
    if (char_code == 0) {
502
606
        QTC::TC("qpdf", "QPDFTokenizer null in name");
503
606
        error_message = "null character not allowed in name token";
504
606
        val += "#00";
505
606
        state = st_name;
506
606
        bad = true;
507
2.75k
    } else {
508
2.75k
        val += char(char_code);
509
2.75k
        state = st_name;
510
2.75k
    }
511
3.36k
}
512
513
void
514
Tokenizer::inSign(char ch)
515
193k
{
516
193k
    if (util::is_digit(ch)) {
517
182k
        state = st_number;
518
182k
    } else if (ch == '.') {
519
540
        state = st_decimal;
520
9.86k
    } else {
521
9.86k
        state = st_literal;
522
9.86k
        inLiteral(ch);
523
9.86k
    }
524
193k
}
525
526
void
527
Tokenizer::inDecimal(char ch)
528
30.8k
{
529
30.8k
    if (util::is_digit(ch)) {
530
10.9k
        state = st_real;
531
19.8k
    } else {
532
19.8k
        state = st_literal;
533
19.8k
        inLiteral(ch);
534
19.8k
    }
535
30.8k
}
536
537
void
538
Tokenizer::inNumber(char ch)
539
11.9M
{
540
11.9M
    if (util::is_digit(ch)) {
541
8.06M
    } else if (ch == '.') {
542
314k
        state = st_real;
543
3.54M
    } else if (isDelimiter(ch)) {
544
3.47M
        type = tt::tt_integer;
545
3.47M
        state = st_token_ready;
546
3.47M
        in_token = false;
547
3.47M
        char_to_unread = ch;
548
3.47M
    } else {
549
71.0k
        state = st_literal;
550
71.0k
    }
551
11.9M
}
552
553
void
554
Tokenizer::inReal(char ch)
555
965k
{
556
965k
    if (util::is_digit(ch)) {
557
639k
    } else if (isDelimiter(ch)) {
558
288k
        type = tt::tt_real;
559
288k
        state = st_token_ready;
560
288k
        in_token = false;
561
288k
        char_to_unread = ch;
562
288k
    } else {
563
36.7k
        state = st_literal;
564
36.7k
    }
565
965k
}
566
void
567
Tokenizer::inStringEscape(char ch)
568
373k
{
569
373k
    state = st_in_string;
570
373k
    switch (ch) {
571
11.1k
    case '0':
572
11.8k
    case '1':
573
20.6k
    case '2':
574
29.5k
    case '3':
575
30.0k
    case '4':
576
30.4k
    case '5':
577
30.9k
    case '6':
578
31.5k
    case '7':
579
31.5k
        state = st_char_code;
580
31.5k
        char_code = 0;
581
31.5k
        digit_count = 0;
582
31.5k
        inCharCode(ch);
583
31.5k
        return;
584
585
1.48k
    case 'n':
586
1.48k
        val += '\n';
587
1.48k
        return;
588
589
2.33k
    case 'r':
590
2.33k
        val += '\r';
591
2.33k
        return;
592
593
149k
    case 't':
594
149k
        val += '\t';
595
149k
        return;
596
597
472
    case 'b':
598
472
        val += '\b';
599
472
        return;
600
601
138k
    case 'f':
602
138k
        val += '\f';
603
138k
        return;
604
605
1.09k
    case '\n':
606
1.09k
        return;
607
608
390
    case '\r':
609
390
        state = st_string_after_cr;
610
390
        return;
611
612
48.5k
    default:
613
        // PDF spec says backslash is ignored before anything else
614
48.5k
        val += ch;
615
48.5k
        return;
616
373k
    }
617
373k
}
618
619
void
620
Tokenizer::inStringAfterCR(char ch)
621
109k
{
622
109k
    state = st_in_string;
623
109k
    if (ch != '\n') {
624
69.6k
        inString(ch);
625
69.6k
    }
626
109k
}
627
628
void
629
Tokenizer::inLt(char ch)
630
745k
{
631
745k
    if (ch == '<') {
632
449k
        type = tt::tt_dict_open;
633
449k
        state = st_token_ready;
634
449k
        return;
635
449k
    }
636
637
296k
    state = st_in_hexstring;
638
296k
    inHexstring(ch);
639
296k
}
640
641
void
642
Tokenizer::inGt(char ch)
643
357k
{
644
357k
    if (ch == '>') {
645
335k
        type = tt::tt_dict_close;
646
335k
        state = st_token_ready;
647
335k
    } else {
648
22.2k
        type = tt::tt_bad;
649
22.2k
        QTC::TC("qpdf", "QPDFTokenizer bad >");
650
22.2k
        error_message = "unexpected >";
651
22.2k
        in_token = false;
652
22.2k
        char_to_unread = ch;
653
22.2k
        state = st_token_ready;
654
22.2k
    }
655
357k
}
656
657
void
658
Tokenizer::inLiteral(char ch)
659
57.7M
{
660
57.7M
    if (isDelimiter(ch)) {
661
        // A C-locale whitespace character or delimiter terminates token.  It is important to unread
662
        // the whitespace character even though it is ignored since it may be the newline after a
663
        // stream keyword.  Removing it here could make the stream-reading code break on some files,
664
        // though not on any files in the test suite as of this writing.
665
666
2.90M
        in_token = false;
667
2.90M
        char_to_unread = ch;
668
2.90M
        state = st_token_ready;
669
2.90M
        type = (raw_val == "true") || (raw_val == "false")
670
2.90M
            ? tt::tt_bool
671
2.90M
            : (raw_val == "null" ? tt::tt_null : tt::tt_word);
672
2.90M
    }
673
57.7M
}
674
675
void
676
Tokenizer::inHexstring(char ch)
677
946k
{
678
946k
    if (char hval = util::hex_decode_char(ch); hval < '\20') {
679
623k
        char_code = int(hval) << 4;
680
623k
        state = st_in_hexstring_2nd;
681
682
623k
    } else if (ch == '>') {
683
254k
        type = tt::tt_string;
684
254k
        state = st_token_ready;
685
686
254k
    } else if (isSpace(ch)) {
687
        // ignore
688
689
42.9k
    } else {
690
25.1k
        type = tt::tt_bad;
691
25.1k
        QTC::TC("qpdf", "QPDFTokenizer bad hexstring character");
692
25.1k
        error_message = std::string("invalid character (") + ch + ") in hexstring";
693
25.1k
        state = st_token_ready;
694
25.1k
    }
695
946k
}
696
697
void
698
Tokenizer::inHexstring2nd(char ch)
699
632k
{
700
632k
    if (char hval = util::hex_decode_char(ch); hval < '\20') {
701
607k
        val += char(char_code) | hval;
702
607k
        state = st_in_hexstring;
703
704
607k
    } else if (ch == '>') {
705
        // PDF spec says odd hexstrings have implicit trailing 0.
706
5.11k
        val += char(char_code);
707
5.11k
        type = tt::tt_string;
708
5.11k
        state = st_token_ready;
709
710
20.1k
    } else if (isSpace(ch)) {
711
        // ignore
712
713
13.5k
    } else {
714
6.56k
        type = tt::tt_bad;
715
6.56k
        QTC::TC("qpdf", "QPDFTokenizer bad hexstring 2nd character");
716
6.56k
        error_message = std::string("invalid character (") + ch + ") in hexstring";
717
6.56k
        state = st_token_ready;
718
6.56k
    }
719
632k
}
720
721
void
722
Tokenizer::inCharCode(char ch)
723
90.7k
{
724
90.7k
    bool handled = false;
725
90.7k
    if (('0' <= ch) && (ch <= '7')) {
726
85.8k
        char_code = 8 * char_code + (int(ch) - int('0'));
727
85.8k
        if (++(digit_count) < 3) {
728
59.3k
            return;
729
59.3k
        }
730
26.4k
        handled = true;
731
26.4k
    }
732
    // We've accumulated \ddd or we have \d or \dd followed by other than an octal digit. The PDF
733
    // Spec says to ignore high-order overflow.
734
31.3k
    val += char(char_code % 256);
735
31.3k
    state = st_in_string;
736
31.3k
    if (!handled) {
737
4.88k
        inString(ch);
738
4.88k
    }
739
31.3k
}
740
741
void
742
Tokenizer::inInlineImage(char ch)
743
6.05M
{
744
6.05M
    if ((raw_val.length() + 1) == inline_image_bytes) {
745
2.22k
        QTC::TC("qpdf", "QPDFTokenizer found EI by byte count");
746
2.22k
        type = tt::tt_inline_image;
747
2.22k
        inline_image_bytes = 0;
748
2.22k
        state = st_token_ready;
749
2.22k
    }
750
6.05M
}
751
752
void
753
QPDFTokenizer::presentEOF()
754
0
{
755
0
    m->presentEOF();
756
0
}
757
758
void
759
Tokenizer::presentEOF()
760
57.8k
{
761
57.8k
    switch (state) {
762
2.51k
    case st_name:
763
2.70k
    case st_name_hex1:
764
2.81k
    case st_name_hex2:
765
10.3k
    case st_number:
766
10.6k
    case st_real:
767
10.8k
    case st_sign:
768
10.9k
    case st_decimal:
769
22.7k
    case st_literal:
770
22.7k
        QTC::TC("qpdf", "QPDFTokenizer EOF reading appendable token");
771
        // Push any delimiter to the state machine to finish off the final token.
772
22.7k
        presentCharacter('\f');
773
22.7k
        in_token = true;
774
22.7k
        break;
775
776
0
    case st_top:
777
29.3k
    case st_before_token:
778
29.3k
        type = tt::tt_eof;
779
29.3k
        break;
780
781
103
    case st_in_space:
782
103
        type = include_ignorable ? tt::tt_space : tt::tt_eof;
783
103
        break;
784
785
1.00k
    case st_in_comment:
786
1.00k
        type = include_ignorable ? tt::tt_comment : tt::tt_bad;
787
1.00k
        break;
788
789
0
    case st_token_ready:
790
0
        break;
791
792
4.66k
    default:
793
4.66k
        QTC::TC("qpdf", "QPDFTokenizer EOF reading token");
794
4.66k
        type = tt::tt_bad;
795
4.66k
        error_message = "EOF while reading token";
796
57.8k
    }
797
57.8k
    state = st_token_ready;
798
57.8k
}
799
800
void
801
QPDFTokenizer::expectInlineImage(std::shared_ptr<InputSource> input)
802
0
{
803
0
    m->expectInlineImage(*input);
804
0
}
805
806
void
807
QPDFTokenizer::expectInlineImage(InputSource& input)
808
587
{
809
587
    m->expectInlineImage(input);
810
587
}
811
812
void
813
Tokenizer::expectInlineImage(InputSource& input)
814
2.34k
{
815
2.34k
    if (state == st_token_ready) {
816
1.75k
        reset();
817
1.75k
    } else if (state != st_before_token) {
818
0
        throw std::logic_error(
819
0
            "QPDFTokenizer::expectInlineImage called when tokenizer is in improper state");
820
0
    }
821
2.34k
    findEI(input);
822
2.34k
    before_token = false;
823
2.34k
    in_token = true;
824
2.34k
    state = st_inline_image;
825
2.34k
}
826
827
void
828
Tokenizer::findEI(InputSource& input)
829
2.34k
{
830
2.34k
    qpdf_offset_t last_offset = input.getLastOffset();
831
2.34k
    qpdf_offset_t pos = input.tell();
832
833
    // Use QPDFWordTokenFinder to find EI surrounded by delimiters. Then read the next several
834
    // tokens or up to EOF. If we find any suspicious-looking or tokens, this is probably still part
835
    // of the image data, so keep looking for EI. Stop at the first EI that passes. If we get to the
836
    // end without finding one, return the last EI we found. Store the number of bytes expected in
837
    // the inline image including the EI and use that to break out of inline image, falling back to
838
    // the old method if needed.
839
840
2.34k
    bool okay = false;
841
2.34k
    bool first_try = true;
842
14.6k
    while (!okay) {
843
12.9k
        QPDFWordTokenFinder f(input, "EI");
844
12.9k
        if (!input.findFirst("EI", input.tell(), 0, f)) {
845
644
            break;
846
644
        }
847
12.3k
        inline_image_bytes = QIntC::to_size(input.tell() - pos - 2);
848
849
12.3k
        Tokenizer check;
850
12.3k
        bool found_bad = false;
851
        // Look at the next 10 tokens or up to EOF. The next inline image's image data would look
852
        // like bad tokens, but there will always be at least 10 tokens between one inline image's
853
        // EI and the next valid one's ID since width, height, bits per pixel, and color space are
854
        // all required as well as a BI and ID. If we get 10 good tokens in a row or hit EOF, we can
855
        // be pretty sure we've found the actual EI.
856
42.0k
        for (int i = 0; i < 10; ++i) {
857
40.3k
            check.nextToken(input, "checker");
858
40.3k
            auto typ = check.getType();
859
40.3k
            if (typ == tt::tt_eof) {
860
0
                okay = true;
861
40.3k
            } else if (typ == tt::tt_bad) {
862
2.74k
                found_bad = true;
863
37.6k
            } else if (typ == tt::tt_word) {
864
                // The qpdf tokenizer lumps alphabetic and otherwise uncategorized characters into
865
                // "words". We recognize strings of alphabetic characters as potential valid
866
                // operators for purposes of telling whether we're in valid content or not. It's not
867
                // perfect, but it should work more reliably than what we used to do, which was
868
                // already good enough for the vast majority of files.
869
20.7k
                bool found_alpha = false;
870
20.7k
                bool found_non_printable = false;
871
20.7k
                bool found_other = false;
872
75.7k
                for (char ch: check.getValue()) {
873
75.7k
                    if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || (ch == '*')) {
874
                        // Treat '*' as alpha since there are valid PDF operators that contain *
875
                        // along with alphabetic characters.
876
41.8k
                        found_alpha = true;
877
41.8k
                    } else if (static_cast<signed char>(ch) < 32 && !isSpace(ch)) {
878
                        // Compare ch as a signed char so characters outside of 7-bit will be < 0.
879
3.76k
                        found_non_printable = true;
880
3.76k
                        break;
881
30.1k
                    } else {
882
30.1k
                        found_other = true;
883
30.1k
                    }
884
75.7k
                }
885
20.7k
                if (found_non_printable || (found_alpha && found_other)) {
886
7.88k
                    found_bad = true;
887
7.88k
                }
888
20.7k
            }
889
40.3k
            if (okay || found_bad) {
890
10.6k
                break;
891
10.6k
            }
892
40.3k
        }
893
12.3k
        if (!found_bad) {
894
1.70k
            okay = true;
895
1.70k
        }
896
12.3k
        if (!okay) {
897
10.6k
            first_try = false;
898
10.6k
        }
899
12.3k
    }
900
2.34k
    if (okay && (!first_try)) {
901
143
        QTC::TC("qpdf", "QPDFTokenizer found EI after more than one try");
902
143
    }
903
904
2.34k
    input.seek(pos, SEEK_SET);
905
2.34k
    input.setLastOffset(last_offset);
906
2.34k
}
907
908
bool
909
QPDFTokenizer::getToken(Token& token, bool& unread_char, char& ch)
910
0
{
911
0
    return m->getToken(token, unread_char, ch);
912
0
}
913
914
bool
915
Tokenizer::getToken(Token& token, bool& unread_char, char& ch)
916
4.55M
{
917
4.55M
    bool ready = (state == st_token_ready);
918
4.55M
    unread_char = !in_token && !before_token;
919
4.55M
    ch = char_to_unread;
920
4.55M
    if (ready) {
921
4.55M
        token = (!(type == tt::tt_name || type == tt::tt_string))
922
4.55M
            ? Token(type, raw_val, raw_val, error_message)
923
4.55M
            : Token(type, val, raw_val, error_message);
924
925
4.55M
        reset();
926
4.55M
    }
927
4.55M
    return ready;
928
4.55M
}
929
930
bool
931
QPDFTokenizer::betweenTokens()
932
0
{
933
0
    return m->betweenTokens();
934
0
}
935
936
bool
937
Tokenizer::betweenTokens()
938
0
{
939
0
    return before_token;
940
0
}
941
942
QPDFTokenizer::Token
943
QPDFTokenizer::readToken(
944
    InputSource& input, std::string const& context, bool allow_bad, size_t max_len)
945
1.28M
{
946
1.28M
    return m->readToken(input, context, allow_bad, max_len);
947
1.28M
}
948
949
QPDFTokenizer::Token
950
QPDFTokenizer::readToken(
951
    std::shared_ptr<InputSource> input, std::string const& context, bool allow_bad, size_t max_len)
952
0
{
953
0
    return m->readToken(*input, context, allow_bad, max_len);
954
0
}
955
956
QPDFTokenizer::Token
957
Tokenizer::readToken(InputSource& input, std::string const& context, bool allow_bad, size_t max_len)
958
4.55M
{
959
4.55M
    nextToken(input, context, max_len);
960
961
4.55M
    Token token;
962
4.55M
    bool unread_char;
963
4.55M
    char char_to_unread;
964
4.55M
    getToken(token, unread_char, char_to_unread);
965
966
4.55M
    if (token.getType() == tt::tt_bad) {
967
213k
        if (allow_bad) {
968
213k
            QTC::TC("qpdf", "QPDFTokenizer allowing bad token");
969
213k
        } else {
970
0
            throw QPDFExc(
971
0
                qpdf_e_damaged_pdf,
972
0
                input.getName(),
973
0
                context.empty() ? "offset " + std::to_string(input.getLastOffset()) : context,
974
0
                input.getLastOffset(),
975
0
                token.getErrorMessage());
976
0
        }
977
213k
    }
978
4.55M
    return token;
979
4.55M
}
980
981
bool
982
Tokenizer::nextToken(InputSource& input, std::string const& context, size_t max_len)
983
14.2M
{
984
14.2M
    if (state != st_inline_image) {
985
14.2M
        reset();
986
14.2M
    }
987
14.2M
    qpdf_offset_t offset = input.fastTell();
988
989
312M
    while (state != st_token_ready) {
990
298M
        char ch;
991
298M
        if (!input.fastRead(ch)) {
992
57.8k
            presentEOF();
993
994
57.8k
            if ((type == tt::tt_eof) && (!allow_eof)) {
995
                // Nothing in the qpdf library calls readToken without allowEOF anymore, so this
996
                // case is not exercised.
997
57
                type = tt::tt_bad;
998
57
                error_message = "unexpected EOF";
999
57
                offset = input.getLastOffset();
1000
57
            }
1001
298M
        } else {
1002
298M
            handleCharacter(ch);
1003
298M
            if (before_token) {
1004
17.5M
                ++offset;
1005
17.5M
            }
1006
298M
            if (in_token) {
1007
271M
                raw_val += ch;
1008
271M
            }
1009
298M
            if (max_len && (raw_val.length() >= max_len) && (state != st_token_ready)) {
1010
                // terminate this token now
1011
1.37M
                QTC::TC("qpdf", "QPDFTokenizer block long token");
1012
1.37M
                type = tt::tt_bad;
1013
1.37M
                state = st_token_ready;
1014
1.37M
                error_message = "exceeded allowable length while reading token";
1015
1.37M
            }
1016
298M
        }
1017
298M
    }
1018
1019
14.2M
    input.fastUnread(!in_token && !before_token);
1020
1021
14.2M
    if (type != tt::tt_eof) {
1022
14.1M
        input.setLastOffset(offset);
1023
14.1M
    }
1024
1025
14.2M
    return error_message.empty();
1026
14.2M
}