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