Coverage Report

Created: 2025-12-05 06:54

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/qpdf/libqpdf/QPDFParser.cc
Line
Count
Source
1
#include <qpdf/QPDFParser.hh>
2
3
#include <qpdf/QPDF.hh>
4
#include <qpdf/QPDFObjGen.hh>
5
#include <qpdf/QPDFObjectHandle.hh>
6
#include <qpdf/QPDFObject_private.hh>
7
#include <qpdf/QPDFTokenizer_private.hh>
8
#include <qpdf/QTC.hh>
9
#include <qpdf/QUtil.hh>
10
11
#include <memory>
12
13
using namespace std::literals;
14
using namespace qpdf;
15
16
using ObjectPtr = std::shared_ptr<QPDFObject>;
17
18
static uint32_t const& max_nesting{global::Limits::parser_max_nesting()};
19
20
// The ParseGuard class allows QPDFParser to detect re-entrant parsing. It also provides
21
// special access to allow the parser to create unresolved objects and dangling references.
22
class QPDF::Doc::ParseGuard
23
{
24
  public:
25
    ParseGuard(QPDF* qpdf) :
26
153k
        objects(qpdf ? &qpdf->m->objects : nullptr)
27
153k
    {
28
153k
        if (objects) {
29
153k
            objects->inParse(true);
30
153k
        }
31
153k
    }
32
33
    static std::shared_ptr<QPDFObject>
34
    getObject(QPDF* qpdf, int id, int gen, bool parse_pdf)
35
286k
    {
36
286k
        return qpdf->m->objects.getObjectForParser(id, gen, parse_pdf);
37
286k
    }
38
39
    ~ParseGuard()
40
153k
    {
41
153k
        if (objects) {
42
153k
            objects->inParse(false);
43
153k
        }
44
153k
    }
45
    QPDF::Doc::Objects* objects;
46
};
47
48
using ParseGuard = QPDF::Doc::ParseGuard;
49
50
QPDFObjectHandle
51
QPDFParser::parse(InputSource& input, std::string const& object_description, QPDF* context)
52
30
{
53
30
    qpdf::Tokenizer tokenizer;
54
30
    if (auto result = QPDFParser(
55
30
                          input,
56
30
                          make_description(input.getName(), object_description),
57
30
                          object_description,
58
30
                          tokenizer,
59
30
                          nullptr,
60
30
                          context,
61
30
                          false)
62
30
                          .parse()) {
63
30
        return result;
64
30
    }
65
0
    return {QPDFObject::create<QPDF_Null>()};
66
30
}
67
68
QPDFObjectHandle
69
QPDFParser::parse_content(
70
    InputSource& input,
71
    std::shared_ptr<QPDFObject::Description> sp_description,
72
    qpdf::Tokenizer& tokenizer,
73
    QPDF* context)
74
0
{
75
0
    static const std::string content("content"); // GCC12 - make constexpr
76
0
    auto p = QPDFParser(
77
0
        input,
78
0
        std::move(sp_description),
79
0
        content,
80
0
        tokenizer,
81
0
        nullptr,
82
0
        context,
83
0
        true,
84
0
        0,
85
0
        0,
86
0
        context && context->doc().reconstructed_xref());
87
0
    auto result = p.parse(true);
88
0
    if (result || p.empty_) {
89
        // In content stream mode, leave object uninitialized to indicate EOF
90
0
        return result;
91
0
    }
92
0
    return {QPDFObject::create<QPDF_Null>()};
93
0
}
94
95
QPDFObjectHandle
96
QPDFParser::parse(
97
    InputSource& input,
98
    std::string const& object_description,
99
    QPDFTokenizer& tokenizer,
100
    bool& empty,
101
    QPDFObjectHandle::StringDecrypter* decrypter,
102
    QPDF* context)
103
0
{
104
    // ABI: This parse overload is only used by the deprecated QPDFObjectHandle::parse. It is the
105
    // only user of the 'empty' member. When removing this overload also remove 'empty'.
106
0
    auto p = QPDFParser(
107
0
        input,
108
0
        make_description(input.getName(), object_description),
109
0
        object_description,
110
0
        *tokenizer.m,
111
0
        decrypter,
112
0
        context,
113
0
        false);
114
0
    auto result = p.parse();
115
0
    empty = p.empty_;
116
0
    if (result) {
117
0
        return result;
118
0
    }
119
0
    return {QPDFObject::create<QPDF_Null>()};
120
0
}
121
122
QPDFObjectHandle
123
QPDFParser::parse(
124
    InputSource& input,
125
    std::string const& object_description,
126
    qpdf::Tokenizer& tokenizer,
127
    QPDFObjectHandle::StringDecrypter* decrypter,
128
    QPDF& context,
129
    bool sanity_checks)
130
123k
{
131
123k
    return QPDFParser(
132
123k
               input,
133
123k
               make_description(input.getName(), object_description),
134
123k
               object_description,
135
123k
               tokenizer,
136
123k
               decrypter,
137
123k
               &context,
138
123k
               true,
139
123k
               0,
140
123k
               0,
141
123k
               sanity_checks)
142
123k
        .parse();
143
123k
}
144
145
QPDFObjectHandle
146
QPDFParser::parse(
147
    is::OffsetBuffer& input, int stream_id, int obj_id, qpdf::Tokenizer& tokenizer, QPDF& context)
148
30.1k
{
149
30.1k
    return QPDFParser(
150
30.1k
               input,
151
30.1k
               std::make_shared<QPDFObject::Description>(
152
30.1k
                   QPDFObject::ObjStreamDescr(stream_id, obj_id)),
153
30.1k
               "",
154
30.1k
               tokenizer,
155
30.1k
               nullptr,
156
30.1k
               &context,
157
30.1k
               true,
158
30.1k
               stream_id,
159
30.1k
               obj_id)
160
30.1k
        .parse();
161
30.1k
}
162
163
QPDFObjectHandle
164
QPDFParser::parse(bool content_stream)
165
153k
{
166
153k
    try {
167
153k
        return parse_first(content_stream);
168
153k
    } catch (Error&) {
169
4.94k
        return {};
170
4.94k
    } catch (QPDFExc& e) {
171
2.39k
        throw e;
172
2.39k
    } catch (std::logic_error& e) {
173
0
        throw e;
174
949
    } catch (std::exception& e) {
175
949
        warn("treating object as null because of error during parsing : "s + e.what());
176
949
        return {};
177
949
    }
178
153k
}
179
180
QPDFObjectHandle
181
QPDFParser::parse_first(bool content_stream)
182
153k
{
183
    // This method must take care not to resolve any objects. Don't check the type of any object
184
    // without first ensuring that it is a direct object. Otherwise, doing so may have the side
185
    // effect of reading the object and changing the file pointer. If you do this, it will cause a
186
    // logic error to be thrown from QPDF::inParse().
187
188
153k
    QPDF::Doc::ParseGuard pg(context);
189
153k
    start = input.tell();
190
153k
    if (!tokenizer.nextToken(input, object_description)) {
191
1.28k
        warn(tokenizer.getErrorMessage());
192
1.28k
    }
193
194
153k
    switch (tokenizer.getType()) {
195
525
    case QPDFTokenizer::tt_eof:
196
525
        if (content_stream) {
197
            // In content stream mode, leave object uninitialized to indicate EOF
198
0
            empty_ = true;
199
0
            return {};
200
0
        }
201
525
        warn("unexpected EOF");
202
525
        return {};
203
204
1.23k
    case QPDFTokenizer::tt_bad:
205
1.23k
        return {};
206
207
71
    case QPDFTokenizer::tt_brace_open:
208
169
    case QPDFTokenizer::tt_brace_close:
209
169
        warn("treating unexpected brace token as null");
210
169
        return {};
211
212
682
    case QPDFTokenizer::tt_array_close:
213
682
        warn("treating unexpected array close token as null");
214
682
        return {};
215
216
390
    case QPDFTokenizer::tt_dict_close:
217
390
        warn("unexpected dictionary close token");
218
390
        return {};
219
220
9.00k
    case QPDFTokenizer::tt_array_open:
221
127k
    case QPDFTokenizer::tt_dict_open:
222
127k
        stack.clear();
223
127k
        stack.emplace_back(
224
127k
            input,
225
127k
            (tokenizer.getType() == QPDFTokenizer::tt_array_open) ? st_array : st_dictionary_key);
226
127k
        frame = &stack.back();
227
127k
        return parseRemainder(content_stream);
228
229
338
    case QPDFTokenizer::tt_bool:
230
338
        return withDescription<QPDF_Bool>(tokenizer.getValue() == "true");
231
232
73
    case QPDFTokenizer::tt_null:
233
73
        return {QPDFObject::create<QPDF_Null>()};
234
235
11.7k
    case QPDFTokenizer::tt_integer:
236
11.7k
        return withDescription<QPDF_Integer>(QUtil::string_to_ll(tokenizer.getValue().c_str()));
237
238
887
    case QPDFTokenizer::tt_real:
239
887
        return withDescription<QPDF_Real>(tokenizer.getValue());
240
241
3.02k
    case QPDFTokenizer::tt_name:
242
3.02k
        return withDescription<QPDF_Name>(tokenizer.getValue());
243
244
6.60k
    case QPDFTokenizer::tt_word:
245
6.60k
        {
246
6.60k
            auto const& value = tokenizer.getValue();
247
6.60k
            if (content_stream) {
248
0
                return withDescription<QPDF_Operator>(value);
249
6.60k
            } else if (value == "endobj") {
250
                // We just saw endobj without having read anything. Nothing in the PDF spec appears
251
                // to allow empty objects, but they have been encountered in actual PDF files and
252
                // Adobe Reader appears to ignore them. Treat this as a null and do not move the
253
                // input source's offset.
254
439
                empty_ = true;
255
439
                input.seek(input.getLastOffset(), SEEK_SET);
256
439
                if (!content_stream) {
257
439
                    warn("empty object treated as null");
258
439
                }
259
439
                return {};
260
6.16k
            } else {
261
6.16k
                warn("unknown token while reading object; treating as string");
262
6.16k
                return withDescription<QPDF_String>(value);
263
6.16k
            }
264
6.60k
        }
265
266
478
    case QPDFTokenizer::tt_string:
267
478
        if (decrypter) {
268
106
            std::string s{tokenizer.getValue()};
269
106
            decrypter->decryptString(s);
270
106
            return withDescription<QPDF_String>(s);
271
372
        } else {
272
372
            return withDescription<QPDF_String>(tokenizer.getValue());
273
372
        }
274
275
0
    default:
276
0
        warn("treating unknown token type as null while reading object");
277
0
        return {};
278
153k
    }
279
153k
}
280
281
QPDFObjectHandle
282
QPDFParser::parseRemainder(bool content_stream)
283
127k
{
284
    // This method must take care not to resolve any objects. Don't check the type of any object
285
    // without first ensuring that it is a direct object. Otherwise, doing so may have the side
286
    // effect of reading the object and changing the file pointer. If you do this, it will cause a
287
    // logic error to be thrown from QPDF::inParse().
288
289
127k
    bad_count = 0;
290
127k
    bool b_contents = false;
291
292
6.25M
    while (true) {
293
6.24M
        if (!tokenizer.nextToken(input, object_description)) {
294
29.8k
            warn(tokenizer.getErrorMessage());
295
29.8k
        }
296
6.24M
        ++good_count; // optimistically
297
298
6.24M
        if (int_count != 0) {
299
            // Special handling of indirect references. Treat integer tokens as part of an indirect
300
            // reference until proven otherwise.
301
1.14M
            if (tokenizer.getType() == QPDFTokenizer::tt_integer) {
302
633k
                if (++int_count > 2) {
303
                    // Process the oldest buffered integer.
304
282k
                    addInt(int_count);
305
282k
                }
306
633k
                last_offset_buffer[int_count % 2] = input.getLastOffset();
307
633k
                int_buffer[int_count % 2] = QUtil::string_to_ll(tokenizer.getValue().c_str());
308
633k
                continue;
309
310
633k
            } else if (
311
508k
                int_count >= 2 && tokenizer.getType() == QPDFTokenizer::tt_word &&
312
308k
                tokenizer.getValue() == "R") {
313
288k
                if (!context) {
314
0
                    throw std::logic_error(
315
0
                        "QPDFParser::parse called without context on an object with indirect "
316
0
                        "references");
317
0
                }
318
288k
                auto id = QIntC::to_int(int_buffer[(int_count - 1) % 2]);
319
288k
                auto gen = QIntC::to_int(int_buffer[(int_count) % 2]);
320
288k
                if (!(id < 1 || gen < 0 || gen >= 65535)) {
321
286k
                    add(ParseGuard::getObject(context, id, gen, parse_pdf));
322
286k
                } else {
323
1.80k
                    add_bad_null(
324
1.80k
                        "treating bad indirect reference (" + std::to_string(id) + " " +
325
1.80k
                        std::to_string(gen) + " R) as null");
326
1.80k
                }
327
288k
                int_count = 0;
328
288k
                continue;
329
330
288k
            } else if (int_count > 0) {
331
                // Process the buffered integers before processing the current token.
332
220k
                if (int_count > 1) {
333
62.4k
                    addInt(int_count - 1);
334
62.4k
                }
335
220k
                addInt(int_count);
336
220k
                int_count = 0;
337
220k
            }
338
1.14M
        }
339
340
5.32M
        switch (tokenizer.getType()) {
341
7.46k
        case QPDFTokenizer::tt_eof:
342
7.46k
            warn("parse error while reading object");
343
7.46k
            if (content_stream) {
344
                // In content stream mode, leave object uninitialized to indicate EOF
345
0
                return {};
346
0
            }
347
7.46k
            warn("unexpected EOF");
348
7.46k
            return {};
349
350
24.6k
        case QPDFTokenizer::tt_bad:
351
24.6k
            check_too_many_bad_tokens();
352
24.6k
            addNull();
353
24.6k
            continue;
354
355
1.19k
        case QPDFTokenizer::tt_brace_open:
356
2.84k
        case QPDFTokenizer::tt_brace_close:
357
2.84k
            add_bad_null("treating unexpected brace token as null");
358
2.84k
            continue;
359
360
97.9k
        case QPDFTokenizer::tt_array_close:
361
97.9k
            if (frame->state == st_array) {
362
96.5k
                auto object = frame->null_count > 100
363
96.5k
                    ? QPDFObject::create<QPDF_Array>(std::move(frame->olist), true)
364
96.5k
                    : QPDFObject::create<QPDF_Array>(std::move(frame->olist));
365
96.5k
                setDescription(object, frame->offset - 1);
366
                // The `offset` points to the next of "[".  Set the rewind offset to point to the
367
                // beginning of "[". This has been explicitly tested with whitespace surrounding the
368
                // array start delimiter. getLastOffset points to the array end token and therefore
369
                // can't be used here.
370
96.5k
                if (stack.size() <= 1) {
371
1.60k
                    return object;
372
1.60k
                }
373
94.9k
                stack.pop_back();
374
94.9k
                frame = &stack.back();
375
94.9k
                add(std::move(object));
376
94.9k
            } else {
377
1.44k
                if (sanity_checks) {
378
                    // During sanity checks, assume nesting of containers is corrupt and object is
379
                    // unusable.
380
923
                    warn("unexpected array close token; giving up on reading object");
381
923
                    return {};
382
923
                }
383
524
                add_bad_null("treating unexpected array close token as null");
384
524
            }
385
95.4k
            continue;
386
387
157k
        case QPDFTokenizer::tt_dict_close:
388
157k
            if (frame->state <= st_dictionary_value) {
389
                // Attempt to recover more or less gracefully from invalid dictionaries.
390
156k
                auto& dict = frame->dict;
391
392
156k
                if (frame->state == st_dictionary_value) {
393
12.9k
                    warn(
394
12.9k
                        frame->offset,
395
12.9k
                        "dictionary ended prematurely; using null as value for last key");
396
12.9k
                    dict[frame->key] = QPDFObject::create<QPDF_Null>();
397
12.9k
                }
398
156k
                if (!frame->olist.empty()) {
399
45.9k
                    if (sanity_checks) {
400
44.1k
                        warn(
401
44.1k
                            frame->offset,
402
44.1k
                            "expected dictionary keys but found non-name objects; ignoring");
403
44.1k
                    } else {
404
1.84k
                        fixMissingKeys();
405
1.84k
                    }
406
45.9k
                }
407
408
156k
                if (!frame->contents_string.empty() && dict.contains("/Type") &&
409
50
                    dict["/Type"].isNameAndEquals("/Sig") && dict.contains("/ByteRange") &&
410
11
                    dict.contains("/Contents") && dict["/Contents"].isString()) {
411
11
                    dict["/Contents"] = QPDFObjectHandle::newString(frame->contents_string);
412
11
                    dict["/Contents"].setParsedOffset(frame->contents_offset);
413
11
                }
414
156k
                auto object = QPDFObject::create<QPDF_Dictionary>(std::move(dict));
415
156k
                setDescription(object, frame->offset - 2);
416
                // The `offset` points to the next of "<<". Set the rewind offset to point to the
417
                // beginning of "<<". This has been explicitly tested with whitespace surrounding
418
                // the dictionary start delimiter. getLastOffset points to the dictionary end token
419
                // and therefore can't be used here.
420
156k
                if (stack.size() <= 1) {
421
107k
                    return object;
422
107k
                }
423
48.4k
                stack.pop_back();
424
48.4k
                frame = &stack.back();
425
48.4k
                add(std::move(object));
426
48.4k
            } else {
427
1.08k
                if (sanity_checks) {
428
                    // During sanity checks, assume nesting of containers is corrupt and object is
429
                    // unusable.
430
717
                    warn("unexpected dictionary close token; giving up on reading object");
431
717
                    return {};
432
717
                }
433
367
                add_bad_null("unexpected dictionary close token");
434
367
            }
435
48.8k
            continue;
436
437
155k
        case QPDFTokenizer::tt_array_open:
438
241k
        case QPDFTokenizer::tt_dict_open:
439
241k
            if (stack.size() > max_nesting) {
440
106
                limits_error(
441
106
                    "parser-max-nesting", "ignoring excessively deeply nested data structure");
442
106
            }
443
241k
            b_contents = false;
444
241k
            stack.emplace_back(
445
241k
                input,
446
241k
                (tokenizer.getType() == QPDFTokenizer::tt_array_open) ? st_array
447
241k
                                                                      : st_dictionary_key);
448
241k
            frame = &stack.back();
449
241k
            continue;
450
451
5.85k
        case QPDFTokenizer::tt_bool:
452
5.85k
            addScalar<QPDF_Bool>(tokenizer.getValue() == "true");
453
5.85k
            continue;
454
455
60.5k
        case QPDFTokenizer::tt_null:
456
60.5k
            addNull();
457
60.5k
            continue;
458
459
509k
        case QPDFTokenizer::tt_integer:
460
509k
            if (!content_stream) {
461
                // Buffer token in case it is part of an indirect reference.
462
509k
                last_offset_buffer[1] = input.getLastOffset();
463
509k
                int_buffer[1] = QUtil::string_to_ll(tokenizer.getValue().c_str());
464
509k
                int_count = 1;
465
509k
            } else {
466
0
                addScalar<QPDF_Integer>(QUtil::string_to_ll(tokenizer.getValue().c_str()));
467
0
            }
468
509k
            continue;
469
470
58.2k
        case QPDFTokenizer::tt_real:
471
58.2k
            addScalar<QPDF_Real>(tokenizer.getValue());
472
58.2k
            continue;
473
474
3.92M
        case QPDFTokenizer::tt_name:
475
3.92M
            if (frame->state == st_dictionary_key) {
476
693k
                frame->key = tokenizer.getValue();
477
693k
                frame->state = st_dictionary_value;
478
693k
                b_contents = decrypter && frame->key == "/Contents";
479
693k
                continue;
480
3.22M
            } else {
481
3.22M
                addScalar<QPDF_Name>(tokenizer.getValue());
482
3.22M
            }
483
3.22M
            continue;
484
485
3.22M
        case QPDFTokenizer::tt_word:
486
161k
            if (content_stream) {
487
0
                addScalar<QPDF_Operator>(tokenizer.getValue());
488
0
                continue;
489
0
            }
490
491
161k
            if (sanity_checks) {
492
156k
                if (tokenizer.getValue() == "endobj" || tokenizer.getValue() == "endstream") {
493
                    // During sanity checks, assume an unexpected endobj or endstream indicates that
494
                    // we are parsing past the end of the object.
495
1.75k
                    warn(
496
1.75k
                        "unexpected 'endobj' or 'endstream' while reading object; giving up on "
497
1.75k
                        "reading object");
498
1.75k
                    return {};
499
1.75k
                }
500
501
154k
                add_bad_null("unknown token while reading object; treating as null");
502
154k
                continue;
503
156k
            }
504
505
5.29k
            warn("unknown token while reading object; treating as string");
506
5.29k
            check_too_many_bad_tokens();
507
5.29k
            addScalar<QPDF_String>(tokenizer.getValue());
508
509
5.29k
            continue;
510
511
76.9k
        case QPDFTokenizer::tt_string:
512
76.9k
            {
513
76.9k
                auto const& val = tokenizer.getValue();
514
76.9k
                if (decrypter) {
515
12.1k
                    if (b_contents) {
516
304
                        frame->contents_string = val;
517
304
                        frame->contents_offset = input.getLastOffset();
518
304
                        b_contents = false;
519
304
                    }
520
12.1k
                    std::string s{val};
521
12.1k
                    decrypter->decryptString(s);
522
12.1k
                    addScalar<QPDF_String>(s);
523
64.7k
                } else {
524
64.7k
                    addScalar<QPDF_String>(val);
525
64.7k
                }
526
76.9k
            }
527
76.9k
            continue;
528
529
0
        default:
530
0
            add_bad_null("treating unknown token type as null while reading object");
531
5.32M
        }
532
5.32M
    }
533
127k
}
534
535
void
536
QPDFParser::add(std::shared_ptr<QPDFObject>&& obj)
537
4.36M
{
538
4.36M
    if (frame->state != st_dictionary_value) {
539
        // If state is st_dictionary_key then there is a missing key. Push onto olist for
540
        // processing once the tt_dict_close token has been found.
541
3.72M
        frame->olist.emplace_back(std::move(obj));
542
3.72M
    } else {
543
643k
        if (auto res = frame->dict.insert_or_assign(frame->key, std::move(obj)); !res.second) {
544
41.9k
            warnDuplicateKey();
545
41.9k
        }
546
643k
        frame->state = st_dictionary_key;
547
643k
    }
548
4.36M
}
549
550
void
551
QPDFParser::addNull()
552
239k
{
553
239k
    const static ObjectPtr null_obj = QPDFObject::create<QPDF_Null>();
554
555
239k
    if (frame->state != st_dictionary_value) {
556
        // If state is st_dictionary_key then there is a missing key. Push onto olist for
557
        // processing once the tt_dict_close token has been found.
558
209k
        frame->olist.emplace_back(null_obj);
559
209k
    } else {
560
30.3k
        if (auto res = frame->dict.insert_or_assign(frame->key, null_obj); !res.second) {
561
2.48k
            warnDuplicateKey();
562
2.48k
        }
563
30.3k
        frame->state = st_dictionary_key;
564
30.3k
    }
565
239k
    ++frame->null_count;
566
239k
}
567
568
void
569
QPDFParser::add_bad_null(std::string const& msg)
570
159k
{
571
159k
    warn(msg);
572
159k
    check_too_many_bad_tokens();
573
159k
    addNull();
574
159k
}
575
576
void
577
QPDFParser::addInt(int count)
578
564k
{
579
564k
    auto obj = QPDFObject::create<QPDF_Integer>(int_buffer[count % 2]);
580
564k
    obj->setDescription(context, description, last_offset_buffer[count % 2]);
581
564k
    add(std::move(obj));
582
564k
}
583
584
template <typename T, typename... Args>
585
void
586
QPDFParser::addScalar(Args&&... args)
587
3.37M
{
588
3.37M
    auto limit = Limits::parser_max_container_size(bad_count || sanity_checks);
589
3.37M
    if (frame->olist.size() >= limit || frame->dict.size() >= limit) {
590
        // Stop adding scalars. We are going to abort when the close token or a bad token is
591
        // encountered.
592
248
        max_bad_count = 1;
593
248
        check_too_many_bad_tokens(); // always throws Error()
594
248
    }
595
3.37M
    auto obj = QPDFObject::create<T>(std::forward<Args>(args)...);
596
3.37M
    obj->setDescription(context, description, input.getLastOffset());
597
3.37M
    add(std::move(obj));
598
3.37M
}
void QPDFParser::addScalar<QPDF_Bool, bool>(bool&&)
Line
Count
Source
587
5.85k
{
588
5.85k
    auto limit = Limits::parser_max_container_size(bad_count || sanity_checks);
589
5.85k
    if (frame->olist.size() >= limit || frame->dict.size() >= limit) {
590
        // Stop adding scalars. We are going to abort when the close token or a bad token is
591
        // encountered.
592
7
        max_bad_count = 1;
593
7
        check_too_many_bad_tokens(); // always throws Error()
594
7
    }
595
5.85k
    auto obj = QPDFObject::create<T>(std::forward<Args>(args)...);
596
5.85k
    obj->setDescription(context, description, input.getLastOffset());
597
5.85k
    add(std::move(obj));
598
5.85k
}
Unexecuted instantiation: void QPDFParser::addScalar<QPDF_Integer, long long>(long long&&)
void QPDFParser::addScalar<QPDF_Real, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&>(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)
Line
Count
Source
587
58.2k
{
588
58.2k
    auto limit = Limits::parser_max_container_size(bad_count || sanity_checks);
589
58.2k
    if (frame->olist.size() >= limit || frame->dict.size() >= limit) {
590
        // Stop adding scalars. We are going to abort when the close token or a bad token is
591
        // encountered.
592
12
        max_bad_count = 1;
593
12
        check_too_many_bad_tokens(); // always throws Error()
594
12
    }
595
58.2k
    auto obj = QPDFObject::create<T>(std::forward<Args>(args)...);
596
58.2k
    obj->setDescription(context, description, input.getLastOffset());
597
58.2k
    add(std::move(obj));
598
58.2k
}
void QPDFParser::addScalar<QPDF_Name, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&>(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)
Line
Count
Source
587
3.22M
{
588
3.22M
    auto limit = Limits::parser_max_container_size(bad_count || sanity_checks);
589
3.22M
    if (frame->olist.size() >= limit || frame->dict.size() >= limit) {
590
        // Stop adding scalars. We are going to abort when the close token or a bad token is
591
        // encountered.
592
202
        max_bad_count = 1;
593
202
        check_too_many_bad_tokens(); // always throws Error()
594
202
    }
595
3.22M
    auto obj = QPDFObject::create<T>(std::forward<Args>(args)...);
596
3.22M
    obj->setDescription(context, description, input.getLastOffset());
597
3.22M
    add(std::move(obj));
598
3.22M
}
Unexecuted instantiation: void QPDFParser::addScalar<QPDF_Operator, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&>(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)
void QPDFParser::addScalar<QPDF_String, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&>(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)
Line
Count
Source
587
69.8k
{
588
69.8k
    auto limit = Limits::parser_max_container_size(bad_count || sanity_checks);
589
69.8k
    if (frame->olist.size() >= limit || frame->dict.size() >= limit) {
590
        // Stop adding scalars. We are going to abort when the close token or a bad token is
591
        // encountered.
592
21
        max_bad_count = 1;
593
21
        check_too_many_bad_tokens(); // always throws Error()
594
21
    }
595
69.8k
    auto obj = QPDFObject::create<T>(std::forward<Args>(args)...);
596
69.8k
    obj->setDescription(context, description, input.getLastOffset());
597
69.8k
    add(std::move(obj));
598
69.8k
}
void QPDFParser::addScalar<QPDF_String, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >&>(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >&)
Line
Count
Source
587
12.1k
{
588
12.1k
    auto limit = Limits::parser_max_container_size(bad_count || sanity_checks);
589
12.1k
    if (frame->olist.size() >= limit || frame->dict.size() >= limit) {
590
        // Stop adding scalars. We are going to abort when the close token or a bad token is
591
        // encountered.
592
6
        max_bad_count = 1;
593
6
        check_too_many_bad_tokens(); // always throws Error()
594
6
    }
595
12.1k
    auto obj = QPDFObject::create<T>(std::forward<Args>(args)...);
596
12.1k
    obj->setDescription(context, description, input.getLastOffset());
597
12.1k
    add(std::move(obj));
598
12.1k
}
599
600
template <typename T, typename... Args>
601
QPDFObjectHandle
602
QPDFParser::withDescription(Args&&... args)
603
21.9k
{
604
21.9k
    auto obj = QPDFObject::create<T>(std::forward<Args>(args)...);
605
21.9k
    obj->setDescription(context, description, start);
606
21.9k
    return {obj};
607
21.9k
}
QPDFObjectHandle QPDFParser::withDescription<QPDF_Bool, bool>(bool&&)
Line
Count
Source
603
338
{
604
338
    auto obj = QPDFObject::create<T>(std::forward<Args>(args)...);
605
338
    obj->setDescription(context, description, start);
606
338
    return {obj};
607
338
}
QPDFObjectHandle QPDFParser::withDescription<QPDF_Integer, long long>(long long&&)
Line
Count
Source
603
11.3k
{
604
11.3k
    auto obj = QPDFObject::create<T>(std::forward<Args>(args)...);
605
11.3k
    obj->setDescription(context, description, start);
606
11.3k
    return {obj};
607
11.3k
}
QPDFObjectHandle QPDFParser::withDescription<QPDF_Real, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&>(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)
Line
Count
Source
603
887
{
604
887
    auto obj = QPDFObject::create<T>(std::forward<Args>(args)...);
605
887
    obj->setDescription(context, description, start);
606
887
    return {obj};
607
887
}
QPDFObjectHandle QPDFParser::withDescription<QPDF_Name, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&>(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)
Line
Count
Source
603
3.02k
{
604
3.02k
    auto obj = QPDFObject::create<T>(std::forward<Args>(args)...);
605
3.02k
    obj->setDescription(context, description, start);
606
3.02k
    return {obj};
607
3.02k
}
Unexecuted instantiation: QPDFObjectHandle QPDFParser::withDescription<QPDF_Operator, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&>(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)
QPDFObjectHandle QPDFParser::withDescription<QPDF_String, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&>(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)
Line
Count
Source
603
6.26k
{
604
6.26k
    auto obj = QPDFObject::create<T>(std::forward<Args>(args)...);
605
6.26k
    obj->setDescription(context, description, start);
606
6.26k
    return {obj};
607
6.26k
}
QPDFObjectHandle QPDFParser::withDescription<QPDF_String, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >&>(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >&)
Line
Count
Source
603
106
{
604
106
    auto obj = QPDFObject::create<T>(std::forward<Args>(args)...);
605
106
    obj->setDescription(context, description, start);
606
106
    return {obj};
607
106
}
608
609
void
610
QPDFParser::setDescription(ObjectPtr& obj, qpdf_offset_t parsed_offset)
611
252k
{
612
252k
    if (obj) {
613
252k
        obj->setDescription(context, description, parsed_offset);
614
252k
    }
615
252k
}
616
617
void
618
QPDFParser::fixMissingKeys()
619
1.84k
{
620
1.84k
    std::set<std::string> names;
621
5.80k
    for (auto& obj: frame->olist) {
622
5.80k
        if (obj.raw_type_code() == ::ot_name) {
623
436
            names.insert(obj.obj_sp()->getStringValue());
624
436
        }
625
5.80k
    }
626
1.84k
    int next_fake_key = 1;
627
5.78k
    for (auto const& item: frame->olist) {
628
5.84k
        while (true) {
629
5.84k
            const std::string key = "/QPDFFake" + std::to_string(next_fake_key++);
630
5.84k
            const bool found_fake = !frame->dict.contains(key) && !names.contains(key);
631
5.84k
            QTC::TC("qpdf", "QPDFParser found fake", (found_fake ? 0 : 1));
632
5.84k
            if (found_fake) {
633
5.78k
                warn(
634
5.78k
                    frame->offset,
635
5.78k
                    "expected dictionary key but found non-name object; inserting key " + key);
636
5.78k
                frame->dict[key] = item;
637
5.78k
                break;
638
5.78k
            }
639
5.84k
        }
640
5.78k
    }
641
1.84k
}
642
643
void
644
QPDFParser::check_too_many_bad_tokens()
645
189k
{
646
189k
    auto limit = Limits::parser_max_container_size(bad_count || sanity_checks);
647
189k
    if (frame->olist.size() >= limit || frame->dict.size() >= limit) {
648
248
        if (bad_count) {
649
146
            limits_error(
650
146
                "parser-max-container-size-damaged",
651
146
                "encountered errors while parsing an array or dictionary with more than " +
652
146
                    std::to_string(limit) + " elements; giving up on reading object");
653
146
        }
654
248
        limits_error(
655
248
            "parser-max-container-size",
656
248
            "encountered an array or dictionary with more than " + std::to_string(limit) +
657
248
                " elements during xref recovery; giving up on reading object");
658
248
    }
659
189k
    if (max_bad_count && --max_bad_count == 0) {
660
802
        limits_error(
661
802
            "parser-max-errors", "too many errors during parsing; treating object as null");
662
802
    }
663
189k
    if (good_count > 4) {
664
73.4k
        good_count = 0;
665
73.4k
        bad_count = 1;
666
73.4k
        return;
667
73.4k
    }
668
115k
    if (++bad_count > 5 ||
669
111k
        (frame->state != st_array && std::cmp_less(max_bad_count, frame->olist.size()))) {
670
        // Give up after 5 errors in close proximity or if the number of missing dictionary keys
671
        // exceeds the remaining number of allowable total errors.
672
3.85k
        warn("too many errors; giving up on reading object");
673
3.85k
        throw Error();
674
3.85k
    }
675
111k
    good_count = 0;
676
111k
}
677
678
void
679
QPDFParser::limits_error(std::string const& limit, std::string const& msg)
680
1.15k
{
681
1.15k
    Limits::error();
682
1.15k
    warn("limits error("s + limit + "): " + msg);
683
1.15k
    throw Error();
684
1.15k
}
685
686
void
687
QPDFParser::warn(QPDFExc const& e) const
688
336k
{
689
    // If parsing on behalf of a QPDF object and want to give a warning, we can warn through the
690
    // object. If parsing for some other reason, such as an explicit creation of an object from a
691
    // string, then just throw the exception.
692
336k
    if (context) {
693
336k
        context->warn(e);
694
336k
    } else {
695
0
        throw e;
696
0
    }
697
336k
}
698
699
void
700
QPDFParser::warnDuplicateKey()
701
44.3k
{
702
44.3k
    warn(
703
44.3k
        frame->offset,
704
44.3k
        "dictionary has duplicated key " + frame->key + "; last occurrence overrides earlier ones");
705
44.3k
}
706
707
void
708
QPDFParser::warn(qpdf_offset_t offset, std::string const& msg) const
709
336k
{
710
336k
    if (stream_id) {
711
17.2k
        std::string descr = "object "s + std::to_string(obj_id) + " 0";
712
17.2k
        std::string name = context->getFilename() + " object stream " + std::to_string(stream_id);
713
17.2k
        warn(QPDFExc(qpdf_e_damaged_pdf, name, descr, offset, msg));
714
318k
    } else {
715
318k
        warn(QPDFExc(qpdf_e_damaged_pdf, input.getName(), object_description, offset, msg));
716
318k
    }
717
336k
}
718
719
void
720
QPDFParser::warn(std::string const& msg) const
721
228k
{
722
228k
    warn(input.getLastOffset(), msg);
723
228k
}