Coverage Report

Created: 2025-11-09 06:21

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
1.34G
{
26
1.34G
    return (
27
1.34G
        ch == ' ' || ch == '\n' || ch == '/' || ch == '(' || ch == ')' || ch == '{' || ch == '}' ||
28
1.24G
        ch == '<' || ch == '>' || ch == '[' || ch == ']' || ch == '%' || ch == '\t' || ch == '\r' ||
29
1.22G
        ch == '\v' || ch == '\f' || ch == 0);
30
1.34G
}
31
32
namespace
33
{
34
    class QPDFWordTokenFinder: public InputSource::Finder
35
    {
36
      public:
37
        QPDFWordTokenFinder(InputSource& is, std::string const& str) :
38
80.4k
            is(is),
39
80.4k
            str(str)
40
80.4k
        {
41
80.4k
        }
42
80.4k
        ~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
201k
{
54
    // Find a word token matching the given string, preceded by a delimiter, and followed by a
55
    // delimiter or EOF.
56
201k
    Tokenizer tokenizer;
57
201k
    tokenizer.nextToken(is, "finder", str.size() + 2);
58
201k
    qpdf_offset_t pos = is.tell();
59
201k
    if (tokenizer.getType() != tt::tt_word || tokenizer.getValue() != str) {
60
126k
        QTC::TC("qpdf", "QPDFTokenizer finder found wrong word");
61
126k
        return false;
62
126k
    }
63
75.3k
    qpdf_offset_t token_start = is.getLastOffset();
64
75.3k
    char next;
65
75.3k
    bool next_okay = false;
66
75.3k
    if (is.read(&next, 1) == 0) {
67
18
        QTC::TC("qpdf", "QPDFTokenizer inline image at EOF");
68
18
        next_okay = true;
69
75.3k
    } else {
70
75.3k
        next_okay = is_delimiter(next);
71
75.3k
    }
72
75.3k
    is.seek(pos, SEEK_SET);
73
75.3k
    if (!next_okay) {
74
0
        return false;
75
0
    }
76
75.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
75.3k
    return true;
81
75.3k
}
82
83
void
84
Tokenizer::reset()
85
341M
{
86
341M
    state = st_before_token;
87
341M
    type = tt::tt_bad;
88
341M
    val.clear();
89
341M
    raw_val.clear();
90
341M
    error_message = "";
91
341M
    before_token = true;
92
341M
    in_token = false;
93
341M
    char_to_unread = '\0';
94
341M
    inline_image_bytes = 0;
95
341M
    string_depth = 0;
96
341M
    bad = false;
97
341M
}
98
99
QPDFTokenizer::Token::Token(token_type_e type, std::string const& value) :
100
6.02k
    type(type),
101
6.02k
    value(value),
102
6.02k
    raw_value(value)
103
6.02k
{
104
6.02k
    if (type == tt_string) {
105
0
        raw_value = QPDFObjectHandle::newString(value).unparse();
106
6.02k
    } else if (type == tt_name) {
107
0
        raw_value = QPDFObjectHandle::newName(value).unparse();
108
0
    }
109
6.02k
}
110
111
QPDFTokenizer::QPDFTokenizer() :
112
16.3k
    m(std::make_unique<qpdf::Tokenizer>())
113
16.3k
{
114
16.3k
}
115
116
16.3k
QPDFTokenizer::~QPDFTokenizer() = default;
117
118
Tokenizer::Tokenizer()
119
661k
{
120
661k
    reset();
121
661k
}
122
123
void
124
QPDFTokenizer::allowEOF()
125
16.3k
{
126
16.3k
    m->allowEOF();
127
16.3k
}
128
129
void
130
Tokenizer::allowEOF()
131
333k
{
132
333k
    allow_eof = true;
133
333k
}
134
135
void
136
QPDFTokenizer::includeIgnorable()
137
16.3k
{
138
16.3k
    m->includeIgnorable();
139
16.3k
}
140
141
void
142
Tokenizer::includeIgnorable()
143
16.3k
{
144
16.3k
    include_ignorable = true;
145
16.3k
}
146
147
bool
148
Tokenizer::isSpace(char ch)
149
428M
{
150
428M
    return (ch == '\0' || util::is_space(ch));
151
428M
}
152
153
bool
154
Tokenizer::isDelimiter(char ch)
155
1.34G
{
156
1.34G
    return is_delimiter(ch);
157
1.34G
}
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
229k
{
168
229k
    handleCharacter(ch);
169
170
229k
    if (in_token) {
171
0
        raw_val += ch;
172
0
    }
173
229k
}
174
175
void
176
Tokenizer::handleCharacter(char ch)
177
3.55G
{
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
3.55G
    switch (state) {
182
0
    case st_top:
183
0
        inTop(ch);
184
0
        return;
185
186
81.8M
    case st_in_space:
187
81.8M
        inSpace(ch);
188
81.8M
        return;
189
190
231M
    case st_in_comment:
191
231M
        inComment(ch);
192
231M
        return;
193
194
5.94M
    case st_lt:
195
5.94M
        inLt(ch);
196
5.94M
        return;
197
198
4.31M
    case st_gt:
199
4.31M
        inGt(ch);
200
4.31M
        return;
201
202
1.32G
    case st_in_string:
203
1.32G
        inString(ch);
204
1.32G
        return;
205
206
738M
    case st_name:
207
738M
        inName(ch);
208
738M
        return;
209
210
100M
    case st_number:
211
100M
        inNumber(ch);
212
100M
        return;
213
214
5.10M
    case st_real:
215
5.10M
        inReal(ch);
216
5.10M
        return;
217
218
3.51M
    case st_string_after_cr:
219
3.51M
        inStringAfterCR(ch);
220
3.51M
        return;
221
222
5.09M
    case st_string_escape:
223
5.09M
        inStringEscape(ch);
224
5.09M
        return;
225
226
997k
    case st_char_code:
227
997k
        inCharCode(ch);
228
997k
        return;
229
230
557M
    case st_literal:
231
557M
        inLiteral(ch);
232
557M
        return;
233
234
136M
    case st_inline_image:
235
136M
        inInlineImage(ch);
236
136M
        return;
237
238
5.42M
    case st_in_hexstring:
239
5.42M
        inHexstring(ch);
240
5.42M
        return;
241
242
5.39M
    case st_in_hexstring_2nd:
243
5.39M
        inHexstring2nd(ch);
244
5.39M
        return;
245
246
3.41M
    case st_name_hex1:
247
3.41M
        inNameHex1(ch);
248
3.41M
        return;
249
250
726k
    case st_name_hex2:
251
726k
        inNameHex2(ch);
252
726k
        return;
253
254
1.04M
    case st_sign:
255
1.04M
        inSign(ch);
256
1.04M
        return;
257
258
449k
    case st_decimal:
259
449k
        inDecimal(ch);
260
449k
        return;
261
262
344M
    case (st_before_token):
263
344M
        inBeforeToken(ch);
264
344M
        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
3.55G
    }
273
3.55G
}
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
344M
{
285
    // Note: we specifically do not use ctype here.  It is locale-dependent.
286
344M
    if (isSpace(ch)) {
287
169M
        before_token = !include_ignorable;
288
169M
        in_token = include_ignorable;
289
169M
        if (include_ignorable) {
290
40.2M
            state = st_in_space;
291
40.2M
        }
292
175M
    } else if (ch == '%') {
293
787k
        before_token = !include_ignorable;
294
787k
        in_token = include_ignorable;
295
787k
        state = st_in_comment;
296
175M
    } else {
297
175M
        before_token = false;
298
175M
        in_token = true;
299
175M
        inTop(ch);
300
175M
    }
301
344M
}
302
303
void
304
Tokenizer::inTop(char ch)
305
175M
{
306
175M
    switch (ch) {
307
1.64M
    case '(':
308
1.64M
        string_depth = 1;
309
1.64M
        state = st_in_string;
310
1.64M
        return;
311
312
5.97M
    case '<':
313
5.97M
        state = st_lt;
314
5.97M
        return;
315
316
4.32M
    case '>':
317
4.32M
        state = st_gt;
318
4.32M
        return;
319
320
1.75M
    case (')'):
321
1.75M
        type = tt::tt_bad;
322
1.75M
        QTC::TC("qpdf", "QPDFTokenizer bad )");
323
1.75M
        error_message = "unexpected )";
324
1.75M
        state = st_token_ready;
325
1.75M
        return;
326
327
2.81M
    case '[':
328
2.81M
        type = tt::tt_array_open;
329
2.81M
        state = st_token_ready;
330
2.81M
        return;
331
332
3.29M
    case ']':
333
3.29M
        type = tt::tt_array_close;
334
3.29M
        state = st_token_ready;
335
3.29M
        return;
336
337
1.52M
    case '{':
338
1.52M
        type = tt::tt_brace_open;
339
1.52M
        state = st_token_ready;
340
1.52M
        return;
341
342
494k
    case '}':
343
494k
        type = tt::tt_brace_close;
344
494k
        state = st_token_ready;
345
494k
        return;
346
347
46.6M
    case '/':
348
46.6M
        state = st_name;
349
46.6M
        val += ch;
350
46.6M
        return;
351
352
12.1M
    case '0':
353
22.2M
    case '1':
354
25.8M
    case '2':
355
27.9M
    case '3':
356
29.9M
    case '4':
357
32.2M
    case '5':
358
34.5M
    case '6':
359
39.2M
    case '7':
360
40.8M
    case '8':
361
41.9M
    case '9':
362
41.9M
        state = st_number;
363
41.9M
        return;
364
365
290k
    case '+':
366
1.06M
    case '-':
367
1.06M
        state = st_sign;
368
1.06M
        return;
369
370
461k
    case '.':
371
461k
        state = st_decimal;
372
461k
        return;
373
374
63.2M
    default:
375
63.2M
        state = st_literal;
376
63.2M
        return;
377
175M
    }
378
175M
}
379
380
void
381
Tokenizer::inSpace(char ch)
382
81.8M
{
383
    // We only enter this state if include_ignorable is true.
384
81.8M
    if (!isSpace(ch)) {
385
40.2M
        type = tt::tt_space;
386
40.2M
        in_token = false;
387
40.2M
        char_to_unread = ch;
388
40.2M
        state = st_token_ready;
389
40.2M
    }
390
81.8M
}
391
392
void
393
Tokenizer::inComment(char ch)
394
231M
{
395
231M
    if ((ch == '\r') || (ch == '\n')) {
396
773k
        if (include_ignorable) {
397
176k
            type = tt::tt_comment;
398
176k
            in_token = false;
399
176k
            char_to_unread = ch;
400
176k
            state = st_token_ready;
401
597k
        } else {
402
597k
            state = st_before_token;
403
597k
        }
404
773k
    }
405
231M
}
406
407
void
408
Tokenizer::inString(char ch)
409
1.32G
{
410
1.32G
    switch (ch) {
411
5.09M
    case '\\':
412
5.09M
        state = st_string_escape;
413
5.09M
        return;
414
415
4.27M
    case '(':
416
4.27M
        val += ch;
417
4.27M
        ++string_depth;
418
4.27M
        return;
419
420
3.55M
    case ')':
421
3.55M
        if (--string_depth == 0) {
422
1.52M
            type = tt::tt_string;
423
1.52M
            state = st_token_ready;
424
1.52M
            return;
425
1.52M
        }
426
427
2.02M
        val += ch;
428
2.02M
        return;
429
430
3.51M
    case '\r':
431
        // CR by itself is converted to LF
432
3.51M
        val += '\n';
433
3.51M
        state = st_string_after_cr;
434
3.51M
        return;
435
436
9.08M
    case '\n':
437
9.08M
        val += ch;
438
9.08M
        return;
439
440
1.30G
    default:
441
1.30G
        val += ch;
442
1.30G
        return;
443
1.32G
    }
444
1.32G
}
445
446
void
447
Tokenizer::inName(char ch)
448
741M
{
449
741M
    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
46.1M
        type = bad ? tt::tt_bad : tt::tt_name;
457
46.1M
        in_token = false;
458
46.1M
        char_to_unread = ch;
459
46.1M
        state = st_token_ready;
460
694M
    } else if (ch == '#') {
461
3.41M
        char_code = 0;
462
3.41M
        state = st_name_hex1;
463
691M
    } else {
464
691M
        val += ch;
465
691M
    }
466
741M
}
467
468
void
469
Tokenizer::inNameHex1(char ch)
470
3.41M
{
471
3.41M
    hex_char = ch;
472
473
3.41M
    if (char hval = util::hex_decode_char(ch); hval < '\20') {
474
726k
        char_code = int(hval) << 4;
475
726k
        state = st_name_hex2;
476
2.68M
    } else {
477
2.68M
        QTC::TC("qpdf", "QPDFTokenizer bad name 1");
478
2.68M
        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
2.68M
        val += '\0';
481
2.68M
        state = st_name;
482
2.68M
        inName(ch);
483
2.68M
    }
484
3.41M
}
485
486
void
487
Tokenizer::inNameHex2(char ch)
488
726k
{
489
726k
    if (char hval = util::hex_decode_char(ch); hval < '\20') {
490
528k
        char_code |= int(hval);
491
528k
    } else {
492
197k
        QTC::TC("qpdf", "QPDFTokenizer bad name 2");
493
197k
        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
197k
        val += '\0';
496
197k
        val += hex_char;
497
197k
        state = st_name;
498
197k
        inName(ch);
499
197k
        return;
500
197k
    }
501
528k
    if (char_code == 0) {
502
400k
        QTC::TC("qpdf", "QPDFTokenizer null in name");
503
400k
        error_message = "null character not allowed in name token";
504
400k
        val += "#00";
505
400k
        state = st_name;
506
400k
        bad = true;
507
400k
    } else {
508
128k
        val += char(char_code);
509
128k
        state = st_name;
510
128k
    }
511
528k
}
512
513
void
514
Tokenizer::inSign(char ch)
515
1.04M
{
516
1.04M
    if (util::is_digit(ch)) {
517
568k
        state = st_number;
518
568k
    } else if (ch == '.') {
519
10.0k
        state = st_decimal;
520
462k
    } else {
521
462k
        state = st_literal;
522
462k
        inLiteral(ch);
523
462k
    }
524
1.04M
}
525
526
void
527
Tokenizer::inDecimal(char ch)
528
449k
{
529
449k
    if (util::is_digit(ch)) {
530
93.0k
        state = st_real;
531
356k
    } else {
532
356k
        state = st_literal;
533
356k
        inLiteral(ch);
534
356k
    }
535
449k
}
536
537
void
538
Tokenizer::inNumber(char ch)
539
100M
{
540
100M
    if (util::is_digit(ch)) {
541
58.9M
    } else if (ch == '.') {
542
1.56M
        state = st_real;
543
39.8M
    } else if (isDelimiter(ch)) {
544
37.3M
        type = tt::tt_integer;
545
37.3M
        state = st_token_ready;
546
37.3M
        in_token = false;
547
37.3M
        char_to_unread = ch;
548
37.3M
    } else {
549
2.46M
        state = st_literal;
550
2.46M
    }
551
100M
}
552
553
void
554
Tokenizer::inReal(char ch)
555
5.10M
{
556
5.10M
    if (util::is_digit(ch)) {
557
3.45M
    } else if (isDelimiter(ch)) {
558
1.41M
        type = tt::tt_real;
559
1.41M
        state = st_token_ready;
560
1.41M
        in_token = false;
561
1.41M
        char_to_unread = ch;
562
1.41M
    } else {
563
234k
        state = st_literal;
564
234k
    }
565
5.10M
}
566
void
567
Tokenizer::inStringEscape(char ch)
568
5.09M
{
569
5.09M
    state = st_in_string;
570
5.09M
    switch (ch) {
571
116k
    case '0':
572
137k
    case '1':
573
334k
    case '2':
574
499k
    case '3':
575
517k
    case '4':
576
527k
    case '5':
577
542k
    case '6':
578
553k
    case '7':
579
553k
        state = st_char_code;
580
553k
        char_code = 0;
581
553k
        digit_count = 0;
582
553k
        inCharCode(ch);
583
553k
        return;
584
585
105k
    case 'n':
586
105k
        val += '\n';
587
105k
        return;
588
589
305k
    case 'r':
590
305k
        val += '\r';
591
305k
        return;
592
593
526k
    case 't':
594
526k
        val += '\t';
595
526k
        return;
596
597
123k
    case 'b':
598
123k
        val += '\b';
599
123k
        return;
600
601
688k
    case 'f':
602
688k
        val += '\f';
603
688k
        return;
604
605
9.78k
    case '\n':
606
9.78k
        return;
607
608
6.73k
    case '\r':
609
6.73k
        state = st_string_after_cr;
610
6.73k
        return;
611
612
2.77M
    default:
613
        // PDF spec says backslash is ignored before anything else
614
2.77M
        val += ch;
615
2.77M
        return;
616
5.09M
    }
617
5.09M
}
618
619
void
620
Tokenizer::inStringAfterCR(char ch)
621
3.51M
{
622
3.51M
    state = st_in_string;
623
3.51M
    if (ch != '\n') {
624
2.86M
        inString(ch);
625
2.86M
    }
626
3.51M
}
627
628
void
629
Tokenizer::inLt(char ch)
630
5.94M
{
631
5.94M
    if (ch == '<') {
632
4.14M
        type = tt::tt_dict_open;
633
4.14M
        state = st_token_ready;
634
4.14M
        return;
635
4.14M
    }
636
637
1.79M
    state = st_in_hexstring;
638
1.79M
    inHexstring(ch);
639
1.79M
}
640
641
void
642
Tokenizer::inGt(char ch)
643
4.31M
{
644
4.31M
    if (ch == '>') {
645
2.96M
        type = tt::tt_dict_close;
646
2.96M
        state = st_token_ready;
647
2.96M
    } else {
648
1.34M
        type = tt::tt_bad;
649
1.34M
        QTC::TC("qpdf", "QPDFTokenizer bad >");
650
1.34M
        error_message = "unexpected >";
651
1.34M
        in_token = false;
652
1.34M
        char_to_unread = ch;
653
1.34M
        state = st_token_ready;
654
1.34M
    }
655
4.31M
}
656
657
void
658
Tokenizer::inLiteral(char ch)
659
557M
{
660
557M
    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
63.7M
        in_token = false;
667
63.7M
        char_to_unread = ch;
668
63.7M
        state = st_token_ready;
669
63.7M
        type = (raw_val == "true") || (raw_val == "false")
670
63.7M
            ? tt::tt_bool
671
63.7M
            : (raw_val == "null" ? tt::tt_null : tt::tt_word);
672
63.7M
    }
673
557M
}
674
675
void
676
Tokenizer::inHexstring(char ch)
677
7.22M
{
678
7.22M
    if (char hval = util::hex_decode_char(ch); hval < '\20') {
679
5.23M
        char_code = int(hval) << 4;
680
5.23M
        state = st_in_hexstring_2nd;
681
682
5.23M
    } else if (ch == '>') {
683
657k
        type = tt::tt_string;
684
657k
        state = st_token_ready;
685
686
1.33M
    } else if (isSpace(ch)) {
687
        // ignore
688
689
885k
    } else {
690
885k
        type = tt::tt_bad;
691
885k
        QTC::TC("qpdf", "QPDFTokenizer bad hexstring character");
692
885k
        error_message = std::string("invalid character (") + ch + ") in hexstring";
693
885k
        state = st_token_ready;
694
885k
    }
695
7.22M
}
696
697
void
698
Tokenizer::inHexstring2nd(char ch)
699
5.39M
{
700
5.39M
    if (char hval = util::hex_decode_char(ch); hval < '\20') {
701
4.98M
        val += char(char_code) | hval;
702
4.98M
        state = st_in_hexstring;
703
704
4.98M
    } else if (ch == '>') {
705
        // PDF spec says odd hexstrings have implicit trailing 0.
706
59.5k
        val += char(char_code);
707
59.5k
        type = tt::tt_string;
708
59.5k
        state = st_token_ready;
709
710
356k
    } else if (isSpace(ch)) {
711
        // ignore
712
713
185k
    } else {
714
171k
        type = tt::tt_bad;
715
171k
        QTC::TC("qpdf", "QPDFTokenizer bad hexstring 2nd character");
716
171k
        error_message = std::string("invalid character (") + ch + ") in hexstring";
717
171k
        state = st_token_ready;
718
171k
    }
719
5.39M
}
720
721
void
722
Tokenizer::inCharCode(char ch)
723
1.55M
{
724
1.55M
    bool handled = false;
725
1.55M
    if (('0' <= ch) && (ch <= '7')) {
726
1.43M
        char_code = 8 * char_code + (int(ch) - int('0'));
727
1.43M
        if (++(digit_count) < 3) {
728
1.00M
            return;
729
1.00M
        }
730
432k
        handled = true;
731
432k
    }
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
547k
    val += char(char_code % 256);
735
547k
    state = st_in_string;
736
547k
    if (!handled) {
737
115k
        inString(ch);
738
115k
    }
739
547k
}
740
741
void
742
Tokenizer::inInlineImage(char ch)
743
136M
{
744
136M
    if ((raw_val.length() + 1) == inline_image_bytes) {
745
8.98k
        QTC::TC("qpdf", "QPDFTokenizer found EI by byte count");
746
8.98k
        type = tt::tt_inline_image;
747
8.98k
        inline_image_bytes = 0;
748
8.98k
        state = st_token_ready;
749
8.98k
    }
750
136M
}
751
752
void
753
QPDFTokenizer::presentEOF()
754
0
{
755
0
    m->presentEOF();
756
0
}
757
758
void
759
Tokenizer::presentEOF()
760
519k
{
761
519k
    switch (state) {
762
43.7k
    case st_name:
763
45.8k
    case st_name_hex1:
764
47.2k
    case st_name_hex2:
765
118k
    case st_number:
766
121k
    case st_real:
767
124k
    case st_sign:
768
125k
    case st_decimal:
769
229k
    case st_literal:
770
229k
        QTC::TC("qpdf", "QPDFTokenizer EOF reading appendable token");
771
        // Push any delimiter to the state machine to finish off the final token.
772
229k
        presentCharacter('\f');
773
229k
        in_token = true;
774
229k
        break;
775
776
0
    case st_top:
777
232k
    case st_before_token:
778
232k
        type = tt::tt_eof;
779
232k
        break;
780
781
2.58k
    case st_in_space:
782
2.58k
        type = include_ignorable ? tt::tt_space : tt::tt_eof;
783
2.58k
        break;
784
785
13.8k
    case st_in_comment:
786
13.8k
        type = include_ignorable ? tt::tt_comment : tt::tt_bad;
787
13.8k
        break;
788
789
0
    case st_token_ready:
790
0
        break;
791
792
41.0k
    default:
793
41.0k
        QTC::TC("qpdf", "QPDFTokenizer EOF reading token");
794
41.0k
        type = tt::tt_bad;
795
41.0k
        error_message = "EOF while reading token";
796
519k
    }
797
519k
    state = st_token_ready;
798
519k
}
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
6.02k
{
809
6.02k
    m->expectInlineImage(input);
810
6.02k
}
811
812
void
813
Tokenizer::expectInlineImage(InputSource& input)
814
9.32k
{
815
9.32k
    if (state == st_token_ready) {
816
3.29k
        reset();
817
6.02k
    } 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
9.32k
    findEI(input);
822
9.32k
    before_token = false;
823
9.32k
    in_token = true;
824
9.32k
    state = st_inline_image;
825
9.32k
}
826
827
void
828
Tokenizer::findEI(InputSource& input)
829
9.32k
{
830
9.32k
    qpdf_offset_t last_offset = input.getLastOffset();
831
9.32k
    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
9.32k
    bool okay = false;
841
9.32k
    bool first_try = true;
842
84.7k
    while (!okay) {
843
80.4k
        QPDFWordTokenFinder f(input, "EI");
844
80.4k
        if (!input.findFirst("EI", input.tell(), 0, f)) {
845
5.10k
            break;
846
5.10k
        }
847
75.3k
        inline_image_bytes = QIntC::to_size(input.tell() - pos - 2);
848
849
75.3k
        Tokenizer check;
850
75.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
185k
        for (int i = 0; i < 10; ++i) {
857
181k
            check.nextToken(input, "checker");
858
181k
            auto typ = check.getType();
859
181k
            if (typ == tt::tt_eof) {
860
0
                okay = true;
861
181k
            } else if (typ == tt::tt_bad) {
862
12.6k
                found_bad = true;
863
168k
            } 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
106k
                bool found_alpha = false;
870
106k
                bool found_non_printable = false;
871
106k
                bool found_other = false;
872
328k
                for (char ch: check.getValue()) {
873
328k
                    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
185k
                        found_alpha = true;
877
185k
                    } 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
27.8k
                        found_non_printable = true;
880
27.8k
                        break;
881
115k
                    } else {
882
115k
                        found_other = true;
883
115k
                    }
884
328k
                }
885
106k
                if (found_non_printable || (found_alpha && found_other)) {
886
58.5k
                    found_bad = true;
887
58.5k
                }
888
106k
            }
889
181k
            if (okay || found_bad) {
890
71.1k
                break;
891
71.1k
            }
892
181k
        }
893
75.3k
        if (!found_bad) {
894
4.22k
            okay = true;
895
4.22k
        }
896
75.3k
        if (!okay) {
897
71.1k
            first_try = false;
898
71.1k
        }
899
75.3k
    }
900
9.32k
    if (okay && (!first_try)) {
901
602
        QTC::TC("qpdf", "QPDFTokenizer found EI after more than one try");
902
602
    }
903
904
9.32k
    input.seek(pos, SEEK_SET);
905
9.32k
    input.setLastOffset(last_offset);
906
9.32k
}
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
125M
{
917
125M
    bool ready = (state == st_token_ready);
918
125M
    unread_char = !in_token && !before_token;
919
125M
    ch = char_to_unread;
920
125M
    if (ready) {
921
125M
        token = (!(type == tt::tt_name || type == tt::tt_string))
922
125M
            ? Token(type, raw_val, raw_val, error_message)
923
125M
            : Token(type, val, raw_val, error_message);
924
925
125M
        reset();
926
125M
    }
927
125M
    return ready;
928
125M
}
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
92.7M
{
946
92.7M
    return m->readToken(input, context, allow_bad, max_len);
947
92.7M
}
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
125M
{
959
125M
    nextToken(input, context, max_len);
960
961
125M
    Token token;
962
125M
    bool unread_char;
963
125M
    char char_to_unread;
964
125M
    getToken(token, unread_char, char_to_unread);
965
966
125M
    if (token.getType() == tt::tt_bad) {
967
6.08M
        if (allow_bad) {
968
6.08M
            QTC::TC("qpdf", "QPDFTokenizer allowing bad token");
969
6.08M
        } 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
6.08M
    }
978
125M
    return token;
979
125M
}
980
981
bool
982
Tokenizer::nextToken(InputSource& input, std::string const& context, size_t max_len)
983
215M
{
984
215M
    if (state != st_inline_image) {
985
215M
        reset();
986
215M
    }
987
215M
    qpdf_offset_t offset = input.fastTell();
988
989
3.77G
    while (state != st_token_ready) {
990
3.55G
        char ch;
991
3.55G
        if (!input.fastRead(ch)) {
992
519k
            presentEOF();
993
994
519k
            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
2.03k
                type = tt::tt_bad;
998
2.03k
                error_message = "unexpected EOF";
999
2.03k
                offset = input.getLastOffset();
1000
2.03k
            }
1001
3.55G
        } else {
1002
3.55G
            handleCharacter(ch);
1003
3.55G
            if (before_token) {
1004
171M
                ++offset;
1005
171M
            }
1006
3.55G
            if (in_token) {
1007
3.19G
                raw_val += ch;
1008
3.19G
            }
1009
3.55G
            if (max_len && (raw_val.length() >= max_len) && (state != st_token_ready)) {
1010
                // terminate this token now
1011
4.78M
                QTC::TC("qpdf", "QPDFTokenizer block long token");
1012
4.78M
                type = tt::tt_bad;
1013
4.78M
                state = st_token_ready;
1014
4.78M
                error_message = "exceeded allowable length while reading token";
1015
4.78M
            }
1016
3.55G
        }
1017
3.55G
    }
1018
1019
215M
    input.fastUnread(!in_token && !before_token);
1020
1021
215M
    if (type != tt::tt_eof) {
1022
215M
        input.setLastOffset(offset);
1023
215M
    }
1024
1025
215M
    return error_message.empty();
1026
215M
}