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
166k
        objects(qpdf ? &qpdf->m->objects : nullptr)
27
166k
    {
28
166k
        if (objects) {
29
166k
            objects->inParse(true);
30
166k
        }
31
166k
    }
32
33
    static std::shared_ptr<QPDFObject>
34
    getObject(QPDF* qpdf, int id, int gen, bool parse_pdf)
35
331k
    {
36
331k
        return qpdf->m->objects.getObjectForParser(id, gen, parse_pdf);
37
331k
    }
38
39
    ~ParseGuard()
40
166k
    {
41
166k
        if (objects) {
42
166k
            objects->inParse(false);
43
166k
        }
44
166k
    }
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
31
{
53
31
    qpdf::Tokenizer tokenizer;
54
31
    if (auto result = QPDFParser(
55
31
                          input,
56
31
                          make_description(input.getName(), object_description),
57
31
                          object_description,
58
31
                          tokenizer,
59
31
                          nullptr,
60
31
                          context,
61
31
                          false)
62
31
                          .parse()) {
63
31
        return result;
64
31
    }
65
0
    return {QPDFObject::create<QPDF_Null>()};
66
31
}
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
129k
{
131
129k
    return QPDFParser(
132
129k
               input,
133
129k
               make_description(input.getName(), object_description),
134
129k
               object_description,
135
129k
               tokenizer,
136
129k
               decrypter,
137
129k
               &context,
138
129k
               true,
139
129k
               0,
140
129k
               0,
141
129k
               sanity_checks)
142
129k
        .parse();
143
129k
}
144
145
QPDFObjectHandle
146
QPDFParser::parse(
147
    is::OffsetBuffer& input, int stream_id, int obj_id, qpdf::Tokenizer& tokenizer, QPDF& context)
148
36.1k
{
149
36.1k
    return QPDFParser(
150
36.1k
               input,
151
36.1k
               std::make_shared<QPDFObject::Description>(
152
36.1k
                   QPDFObject::ObjStreamDescr(stream_id, obj_id)),
153
36.1k
               "",
154
36.1k
               tokenizer,
155
36.1k
               nullptr,
156
36.1k
               &context,
157
36.1k
               true,
158
36.1k
               stream_id,
159
36.1k
               obj_id)
160
36.1k
        .parse();
161
36.1k
}
162
163
QPDFObjectHandle
164
QPDFParser::parse(bool content_stream)
165
166k
{
166
166k
    try {
167
166k
        return parse_first(content_stream);
168
166k
    } catch (Error&) {
169
5.93k
        return {};
170
5.93k
    } catch (QPDFExc& e) {
171
2.21k
        throw e;
172
2.21k
    } catch (std::logic_error& e) {
173
0
        throw e;
174
903
    } catch (std::exception& e) {
175
903
        warn("treating object as null because of error during parsing : "s + e.what());
176
903
        return {};
177
903
    }
178
166k
}
179
180
QPDFObjectHandle
181
QPDFParser::parse_first(bool content_stream)
182
166k
{
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
166k
    QPDF::Doc::ParseGuard pg(context);
189
166k
    start = input.tell();
190
166k
    if (!tokenizer.nextToken(input, object_description)) {
191
1.43k
        warn(tokenizer.getErrorMessage());
192
1.43k
    }
193
194
166k
    switch (tokenizer.getType()) {
195
452
    case QPDFTokenizer::tt_eof:
196
452
        if (content_stream) {
197
            // In content stream mode, leave object uninitialized to indicate EOF
198
0
            empty_ = true;
199
0
            return {};
200
0
        }
201
452
        warn("unexpected EOF");
202
452
        return {};
203
204
1.39k
    case QPDFTokenizer::tt_bad:
205
1.39k
        return {};
206
207
102
    case QPDFTokenizer::tt_brace_open:
208
181
    case QPDFTokenizer::tt_brace_close:
209
181
        warn("treating unexpected brace token as null");
210
181
        return {};
211
212
390
    case QPDFTokenizer::tt_array_close:
213
390
        warn("treating unexpected array close token as null");
214
390
        return {};
215
216
411
    case QPDFTokenizer::tt_dict_close:
217
411
        warn("unexpected dictionary close token");
218
411
        return {};
219
220
8.12k
    case QPDFTokenizer::tt_array_open:
221
142k
    case QPDFTokenizer::tt_dict_open:
222
142k
        stack.clear();
223
142k
        stack.emplace_back(
224
142k
            input,
225
142k
            (tokenizer.getType() == QPDFTokenizer::tt_array_open) ? st_array : st_dictionary_key);
226
142k
        frame = &stack.back();
227
142k
        return parseRemainder(content_stream);
228
229
496
    case QPDFTokenizer::tt_bool:
230
496
        return withDescription<QPDF_Bool>(tokenizer.getValue() == "true");
231
232
132
    case QPDFTokenizer::tt_null:
233
132
        return {QPDFObject::create<QPDF_Null>()};
234
235
9.58k
    case QPDFTokenizer::tt_integer:
236
9.58k
        return withDescription<QPDF_Integer>(QUtil::string_to_ll(tokenizer.getValue().c_str()));
237
238
652
    case QPDFTokenizer::tt_real:
239
652
        return withDescription<QPDF_Real>(tokenizer.getValue());
240
241
2.44k
    case QPDFTokenizer::tt_name:
242
2.44k
        return withDescription<QPDF_Name>(tokenizer.getValue());
243
244
6.99k
    case QPDFTokenizer::tt_word:
245
6.99k
        {
246
6.99k
            auto const& value = tokenizer.getValue();
247
6.99k
            if (content_stream) {
248
0
                return withDescription<QPDF_Operator>(value);
249
6.99k
            } 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
239
                empty_ = true;
255
239
                input.seek(input.getLastOffset(), SEEK_SET);
256
239
                if (!content_stream) {
257
239
                    warn("empty object treated as null");
258
239
                }
259
239
                return {};
260
6.75k
            } else {
261
6.75k
                warn("unknown token while reading object; treating as string");
262
6.75k
                return withDescription<QPDF_String>(value);
263
6.75k
            }
264
6.99k
        }
265
266
434
    case QPDFTokenizer::tt_string:
267
434
        if (decrypter) {
268
101
            std::string s{tokenizer.getValue()};
269
101
            decrypter->decryptString(s);
270
101
            return withDescription<QPDF_String>(s);
271
333
        } else {
272
333
            return withDescription<QPDF_String>(tokenizer.getValue());
273
333
        }
274
275
0
    default:
276
0
        warn("treating unknown token type as null while reading object");
277
0
        return {};
278
166k
    }
279
166k
}
280
281
QPDFObjectHandle
282
QPDFParser::parseRemainder(bool content_stream)
283
142k
{
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
142k
    bad_count = 0;
290
142k
    bool b_contents = false;
291
292
15.6M
    while (true) {
293
15.6M
        if (!tokenizer.nextToken(input, object_description)) {
294
32.5k
            warn(tokenizer.getErrorMessage());
295
32.5k
        }
296
15.6M
        ++good_count; // optimistically
297
298
15.6M
        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.57M
            if (tokenizer.getType() == QPDFTokenizer::tt_integer) {
302
1.00M
                if (++int_count > 2) {
303
                    // Process the oldest buffered integer.
304
606k
                    addInt(int_count);
305
606k
                }
306
1.00M
                last_offset_buffer[int_count % 2] = input.getLastOffset();
307
1.00M
                int_buffer[int_count % 2] = QUtil::string_to_ll(tokenizer.getValue().c_str());
308
1.00M
                continue;
309
310
1.00M
            } else if (
311
571k
                int_count >= 2 && tokenizer.getType() == QPDFTokenizer::tt_word &&
312
353k
                tokenizer.getValue() == "R") {
313
333k
                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
333k
                auto id = QIntC::to_int(int_buffer[(int_count - 1) % 2]);
319
333k
                auto gen = QIntC::to_int(int_buffer[(int_count) % 2]);
320
333k
                if (!(id < 1 || gen < 0 || gen >= 65535)) {
321
331k
                    add(ParseGuard::getObject(context, id, gen, parse_pdf));
322
331k
                } else {
323
1.88k
                    add_bad_null(
324
1.88k
                        "treating bad indirect reference (" + std::to_string(id) + " " +
325
1.88k
                        std::to_string(gen) + " R) as null");
326
1.88k
                }
327
333k
                int_count = 0;
328
333k
                continue;
329
330
333k
            } else if (int_count > 0) {
331
                // Process the buffered integers before processing the current token.
332
237k
                if (int_count > 1) {
333
63.4k
                    addInt(int_count - 1);
334
63.4k
                }
335
237k
                addInt(int_count);
336
237k
                int_count = 0;
337
237k
            }
338
1.57M
        }
339
340
14.2M
        switch (tokenizer.getType()) {
341
7.36k
        case QPDFTokenizer::tt_eof:
342
7.36k
            warn("parse error while reading object");
343
7.36k
            if (content_stream) {
344
                // In content stream mode, leave object uninitialized to indicate EOF
345
0
                return {};
346
0
            }
347
7.36k
            warn("unexpected EOF");
348
7.36k
            return {};
349
350
27.1k
        case QPDFTokenizer::tt_bad:
351
27.1k
            check_too_many_bad_tokens();
352
27.1k
            addNull();
353
27.1k
            continue;
354
355
2.86k
        case QPDFTokenizer::tt_brace_open:
356
3.93k
        case QPDFTokenizer::tt_brace_close:
357
3.93k
            add_bad_null("treating unexpected brace token as null");
358
3.93k
            continue;
359
360
99.1k
        case QPDFTokenizer::tt_array_close:
361
99.1k
            if (frame->state == st_array) {
362
97.3k
                auto object = frame->null_count > 100
363
97.3k
                    ? QPDFObject::create<QPDF_Array>(std::move(frame->olist), true)
364
97.3k
                    : QPDFObject::create<QPDF_Array>(std::move(frame->olist));
365
97.3k
                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
97.3k
                if (stack.size() <= 1) {
371
1.77k
                    return object;
372
1.77k
                }
373
95.5k
                stack.pop_back();
374
95.5k
                frame = &stack.back();
375
95.5k
                add(std::move(object));
376
95.5k
            } else {
377
1.73k
                if (sanity_checks) {
378
                    // During sanity checks, assume nesting of containers is corrupt and object is
379
                    // unusable.
380
1.04k
                    warn("unexpected array close token; giving up on reading object");
381
1.04k
                    return {};
382
1.04k
                }
383
696
                add_bad_null("treating unexpected array close token as null");
384
696
            }
385
96.2k
            continue;
386
387
182k
        case QPDFTokenizer::tt_dict_close:
388
182k
            if (frame->state <= st_dictionary_value) {
389
                // Attempt to recover more or less gracefully from invalid dictionaries.
390
180k
                auto& dict = frame->dict;
391
392
180k
                if (frame->state == st_dictionary_value) {
393
11.6k
                    warn(
394
11.6k
                        frame->offset,
395
11.6k
                        "dictionary ended prematurely; using null as value for last key");
396
11.6k
                    dict[frame->key] = QPDFObject::create<QPDF_Null>();
397
11.6k
                }
398
180k
                if (!frame->olist.empty()) {
399
46.3k
                    if (sanity_checks) {
400
42.3k
                        warn(
401
42.3k
                            frame->offset,
402
42.3k
                            "expected dictionary keys but found non-name objects; ignoring");
403
42.3k
                    } else {
404
3.97k
                        fixMissingKeys();
405
3.97k
                    }
406
46.3k
                }
407
408
180k
                if (!frame->contents_string.empty() && dict.contains("/Type") &&
409
82
                    dict["/Type"].isNameAndEquals("/Sig") && dict.contains("/ByteRange") &&
410
10
                    dict.contains("/Contents") && dict["/Contents"].isString()) {
411
10
                    dict["/Contents"] = QPDFObjectHandle::newString(frame->contents_string);
412
10
                    dict["/Contents"].setParsedOffset(frame->contents_offset);
413
10
                }
414
180k
                auto object = QPDFObject::create<QPDF_Dictionary>(std::move(dict));
415
180k
                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
180k
                if (stack.size() <= 1) {
421
121k
                    return object;
422
121k
                }
423
59.2k
                stack.pop_back();
424
59.2k
                frame = &stack.back();
425
59.2k
                add(std::move(object));
426
59.2k
            } else {
427
1.33k
                if (sanity_checks) {
428
                    // During sanity checks, assume nesting of containers is corrupt and object is
429
                    // unusable.
430
851
                    warn("unexpected dictionary close token; giving up on reading object");
431
851
                    return {};
432
851
                }
433
485
                add_bad_null("unexpected dictionary close token");
434
485
            }
435
59.6k
            continue;
436
437
130k
        case QPDFTokenizer::tt_array_open:
438
241k
        case QPDFTokenizer::tt_dict_open:
439
241k
            if (stack.size() > max_nesting) {
440
73
                limits_error(
441
73
                    "parser-max-nesting", "ignoring excessively deeply nested data structure");
442
73
            }
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
10.9k
        case QPDFTokenizer::tt_bool:
452
10.9k
            addScalar<QPDF_Bool>(tokenizer.getValue() == "true");
453
10.9k
            continue;
454
455
172k
        case QPDFTokenizer::tt_null:
456
172k
            addNull();
457
172k
            continue;
458
459
571k
        case QPDFTokenizer::tt_integer:
460
571k
            if (!content_stream) {
461
                // Buffer token in case it is part of an indirect reference.
462
571k
                last_offset_buffer[1] = input.getLastOffset();
463
571k
                int_buffer[1] = QUtil::string_to_ll(tokenizer.getValue().c_str());
464
571k
                int_count = 1;
465
571k
            } else {
466
0
                addScalar<QPDF_Integer>(QUtil::string_to_ll(tokenizer.getValue().c_str()));
467
0
            }
468
571k
            continue;
469
470
69.4k
        case QPDFTokenizer::tt_real:
471
69.4k
            addScalar<QPDF_Real>(tokenizer.getValue());
472
69.4k
            continue;
473
474
12.6M
        case QPDFTokenizer::tt_name:
475
12.6M
            if (frame->state == st_dictionary_key) {
476
821k
                frame->key = tokenizer.getValue();
477
821k
                frame->state = st_dictionary_value;
478
821k
                b_contents = decrypter && frame->key == "/Contents";
479
821k
                continue;
480
11.8M
            } else {
481
11.8M
                addScalar<QPDF_Name>(tokenizer.getValue());
482
11.8M
            }
483
11.8M
            continue;
484
485
11.8M
        case QPDFTokenizer::tt_word:
486
166k
            if (content_stream) {
487
0
                addScalar<QPDF_Operator>(tokenizer.getValue());
488
0
                continue;
489
0
            }
490
491
166k
            if (sanity_checks) {
492
157k
                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.95k
                    warn(
496
1.95k
                        "unexpected 'endobj' or 'endstream' while reading object; giving up on "
497
1.95k
                        "reading object");
498
1.95k
                    return {};
499
1.95k
                }
500
501
155k
                add_bad_null("unknown token while reading object; treating as null");
502
155k
                continue;
503
157k
            }
504
505
8.81k
            warn("unknown token while reading object; treating as string");
506
8.81k
            check_too_many_bad_tokens();
507
8.81k
            addScalar<QPDF_String>(tokenizer.getValue());
508
509
8.81k
            continue;
510
511
60.2k
        case QPDFTokenizer::tt_string:
512
60.2k
            {
513
60.2k
                auto const& val = tokenizer.getValue();
514
60.2k
                if (decrypter) {
515
16.6k
                    if (b_contents) {
516
1.54k
                        frame->contents_string = val;
517
1.54k
                        frame->contents_offset = input.getLastOffset();
518
1.54k
                        b_contents = false;
519
1.54k
                    }
520
16.6k
                    std::string s{val};
521
16.6k
                    decrypter->decryptString(s);
522
16.6k
                    addScalar<QPDF_String>(s);
523
43.6k
                } else {
524
43.6k
                    addScalar<QPDF_String>(val);
525
43.6k
                }
526
60.2k
            }
527
60.2k
            continue;
528
529
0
        default:
530
0
            add_bad_null("treating unknown token type as null while reading object");
531
14.2M
        }
532
14.2M
    }
533
142k
}
534
535
void
536
QPDFParser::add(std::shared_ptr<QPDFObject>&& obj)
537
13.3M
{
538
13.3M
    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
12.6M
        frame->olist.emplace_back(std::move(obj));
542
12.6M
    } else {
543
769k
        if (auto res = frame->dict.insert_or_assign(frame->key, std::move(obj)); !res.second) {
544
38.9k
            warnDuplicateKey();
545
38.9k
        }
546
769k
        frame->state = st_dictionary_key;
547
769k
    }
548
13.3M
}
549
550
void
551
QPDFParser::addNull()
552
355k
{
553
355k
    const static ObjectPtr null_obj = QPDFObject::create<QPDF_Null>();
554
555
355k
    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
323k
        frame->olist.emplace_back(null_obj);
559
323k
    } else {
560
32.1k
        if (auto res = frame->dict.insert_or_assign(frame->key, null_obj); !res.second) {
561
2.78k
            warnDuplicateKey();
562
2.78k
        }
563
32.1k
        frame->state = st_dictionary_key;
564
32.1k
    }
565
355k
    ++frame->null_count;
566
355k
}
567
568
void
569
QPDFParser::add_bad_null(std::string const& msg)
570
161k
{
571
161k
    warn(msg);
572
161k
    check_too_many_bad_tokens();
573
161k
    addNull();
574
161k
}
575
576
void
577
QPDFParser::addInt(int count)
578
907k
{
579
907k
    auto obj = QPDFObject::create<QPDF_Integer>(int_buffer[count % 2]);
580
907k
    obj->setDescription(context, description, last_offset_buffer[count % 2]);
581
907k
    add(std::move(obj));
582
907k
}
583
584
template <typename T, typename... Args>
585
void
586
QPDFParser::addScalar(Args&&... args)
587
11.9M
{
588
11.9M
    auto limit = Limits::parser_max_container_size(bad_count || sanity_checks);
589
11.9M
    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
11.9M
    auto obj = QPDFObject::create<T>(std::forward<Args>(args)...);
596
11.9M
    obj->setDescription(context, description, input.getLastOffset());
597
11.9M
    add(std::move(obj));
598
11.9M
}
void QPDFParser::addScalar<QPDF_Bool, bool>(bool&&)
Line
Count
Source
587
10.9k
{
588
10.9k
    auto limit = Limits::parser_max_container_size(bad_count || sanity_checks);
589
10.9k
    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
0
        max_bad_count = 1;
593
0
        check_too_many_bad_tokens(); // always throws Error()
594
0
    }
595
10.9k
    auto obj = QPDFObject::create<T>(std::forward<Args>(args)...);
596
10.9k
    obj->setDescription(context, description, input.getLastOffset());
597
10.9k
    add(std::move(obj));
598
10.9k
}
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
69.4k
{
588
69.4k
    auto limit = Limits::parser_max_container_size(bad_count || sanity_checks);
589
69.4k
    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
45
        max_bad_count = 1;
593
45
        check_too_many_bad_tokens(); // always throws Error()
594
45
    }
595
69.4k
    auto obj = QPDFObject::create<T>(std::forward<Args>(args)...);
596
69.4k
    obj->setDescription(context, description, input.getLastOffset());
597
69.4k
    add(std::move(obj));
598
69.4k
}
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
11.8M
{
588
11.8M
    auto limit = Limits::parser_max_container_size(bad_count || sanity_checks);
589
11.8M
    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
158
        max_bad_count = 1;
593
158
        check_too_many_bad_tokens(); // always throws Error()
594
158
    }
595
11.8M
    auto obj = QPDFObject::create<T>(std::forward<Args>(args)...);
596
11.8M
    obj->setDescription(context, description, input.getLastOffset());
597
11.8M
    add(std::move(obj));
598
11.8M
}
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
52.1k
{
588
52.1k
    auto limit = Limits::parser_max_container_size(bad_count || sanity_checks);
589
52.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
39
        max_bad_count = 1;
593
39
        check_too_many_bad_tokens(); // always throws Error()
594
39
    }
595
52.1k
    auto obj = QPDFObject::create<T>(std::forward<Args>(args)...);
596
52.1k
    obj->setDescription(context, description, input.getLastOffset());
597
52.1k
    add(std::move(obj));
598
52.1k
}
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
16.6k
{
588
16.6k
    auto limit = Limits::parser_max_container_size(bad_count || sanity_checks);
589
16.6k
    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
16.6k
    auto obj = QPDFObject::create<T>(std::forward<Args>(args)...);
596
16.6k
    obj->setDescription(context, description, input.getLastOffset());
597
16.6k
    add(std::move(obj));
598
16.6k
}
599
600
template <typename T, typename... Args>
601
QPDFObjectHandle
602
QPDFParser::withDescription(Args&&... args)
603
19.6k
{
604
19.6k
    auto obj = QPDFObject::create<T>(std::forward<Args>(args)...);
605
19.6k
    obj->setDescription(context, description, start);
606
19.6k
    return {obj};
607
19.6k
}
QPDFObjectHandle QPDFParser::withDescription<QPDF_Bool, bool>(bool&&)
Line
Count
Source
603
496
{
604
496
    auto obj = QPDFObject::create<T>(std::forward<Args>(args)...);
605
496
    obj->setDescription(context, description, start);
606
496
    return {obj};
607
496
}
QPDFObjectHandle QPDFParser::withDescription<QPDF_Integer, long long>(long long&&)
Line
Count
Source
603
9.28k
{
604
9.28k
    auto obj = QPDFObject::create<T>(std::forward<Args>(args)...);
605
9.28k
    obj->setDescription(context, description, start);
606
9.28k
    return {obj};
607
9.28k
}
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
652
{
604
652
    auto obj = QPDFObject::create<T>(std::forward<Args>(args)...);
605
652
    obj->setDescription(context, description, start);
606
652
    return {obj};
607
652
}
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
2.44k
{
604
2.44k
    auto obj = QPDFObject::create<T>(std::forward<Args>(args)...);
605
2.44k
    obj->setDescription(context, description, start);
606
2.44k
    return {obj};
607
2.44k
}
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.64k
{
604
6.64k
    auto obj = QPDFObject::create<T>(std::forward<Args>(args)...);
605
6.64k
    obj->setDescription(context, description, start);
606
6.64k
    return {obj};
607
6.64k
}
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
99
{
604
99
    auto obj = QPDFObject::create<T>(std::forward<Args>(args)...);
605
99
    obj->setDescription(context, description, start);
606
99
    return {obj};
607
99
}
608
609
void
610
QPDFParser::setDescription(ObjectPtr& obj, qpdf_offset_t parsed_offset)
611
278k
{
612
278k
    if (obj) {
613
278k
        obj->setDescription(context, description, parsed_offset);
614
278k
    }
615
278k
}
616
617
void
618
QPDFParser::fixMissingKeys()
619
3.97k
{
620
3.97k
    std::set<std::string> names;
621
15.6k
    for (auto& obj: frame->olist) {
622
15.6k
        if (obj.raw_type_code() == ::ot_name) {
623
234
            names.insert(obj.obj_sp()->getStringValue());
624
234
        }
625
15.6k
    }
626
3.97k
    int next_fake_key = 1;
627
15.6k
    for (auto const& item: frame->olist) {
628
15.6k
        while (true) {
629
15.6k
            const std::string key = "/QPDFFake" + std::to_string(next_fake_key++);
630
15.6k
            const bool found_fake = !frame->dict.contains(key) && !names.contains(key);
631
15.6k
            QTC::TC("qpdf", "QPDFParser found fake", (found_fake ? 0 : 1));
632
15.6k
            if (found_fake) {
633
15.6k
                warn(
634
15.6k
                    frame->offset,
635
15.6k
                    "expected dictionary key but found non-name object; inserting key " + key);
636
15.6k
                frame->dict[key] = item;
637
15.6k
                break;
638
15.6k
            }
639
15.6k
        }
640
15.6k
    }
641
3.97k
}
642
643
void
644
QPDFParser::check_too_many_bad_tokens()
645
197k
{
646
197k
    auto limit = Limits::parser_max_container_size(bad_count || sanity_checks);
647
197k
    if (frame->olist.size() >= limit || frame->dict.size() >= limit) {
648
253
        if (bad_count) {
649
195
            limits_error(
650
195
                "parser-max-container-size-damaged",
651
195
                "encountered errors while parsing an array or dictionary with more than " +
652
195
                    std::to_string(limit) + " elements; giving up on reading object");
653
195
        }
654
253
        limits_error(
655
253
            "parser-max-container-size",
656
253
            "encountered an array or dictionary with more than " + std::to_string(limit) +
657
253
                " elements during xref recovery; giving up on reading object");
658
253
    }
659
197k
    if (max_bad_count && --max_bad_count == 0) {
660
835
        limits_error(
661
835
            "parser-max-errors", "too many errors during parsing; treating object as null");
662
835
    }
663
197k
    if (good_count > 4) {
664
72.9k
        good_count = 0;
665
72.9k
        bad_count = 1;
666
72.9k
        return;
667
72.9k
    }
668
124k
    if (++bad_count > 5 ||
669
120k
        (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
4.81k
        warn("too many errors; giving up on reading object");
673
4.81k
        throw Error();
674
4.81k
    }
675
119k
    good_count = 0;
676
119k
}
677
678
void
679
QPDFParser::limits_error(std::string const& limit, std::string const& msg)
680
1.16k
{
681
1.16k
    Limits::error();
682
1.16k
    warn("limits error("s + limit + "): " + msg);
683
1.16k
    throw Error();
684
1.16k
}
685
686
void
687
QPDFParser::warn(QPDFExc const& e) const
688
349k
{
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
349k
    if (context) {
693
349k
        context->warn(e);
694
349k
    } else {
695
0
        throw e;
696
0
    }
697
349k
}
698
699
void
700
QPDFParser::warnDuplicateKey()
701
41.7k
{
702
41.7k
    warn(
703
41.7k
        frame->offset,
704
41.7k
        "dictionary has duplicated key " + frame->key + "; last occurrence overrides earlier ones");
705
41.7k
}
706
707
void
708
QPDFParser::warn(qpdf_offset_t offset, std::string const& msg) const
709
349k
{
710
349k
    if (stream_id) {
711
15.2k
        std::string descr = "object "s + std::to_string(obj_id) + " 0";
712
15.2k
        std::string name = context->getFilename() + " object stream " + std::to_string(stream_id);
713
15.2k
        warn(QPDFExc(qpdf_e_damaged_pdf, name, descr, offset, msg));
714
334k
    } else {
715
334k
        warn(QPDFExc(qpdf_e_damaged_pdf, input.getName(), object_description, offset, msg));
716
334k
    }
717
349k
}
718
719
void
720
QPDFParser::warn(std::string const& msg) const
721
238k
{
722
238k
    warn(input.getLastOffset(), msg);
723
238k
}