Coverage Report

Created: 2025-11-09 06:21

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::objects_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
203k
        objects(qpdf ? &qpdf->m->objects : nullptr)
27
203k
    {
28
203k
        if (objects) {
29
189k
            objects->inParse(true);
30
189k
        }
31
203k
    }
32
33
    static std::shared_ptr<QPDFObject>
34
    getObject(QPDF* qpdf, int id, int gen, bool parse_pdf)
35
465k
    {
36
465k
        return qpdf->m->objects.getObjectForParser(id, gen, parse_pdf);
37
465k
    }
38
39
    ~ParseGuard()
40
203k
    {
41
203k
        if (objects) {
42
189k
            objects->inParse(false);
43
189k
        }
44
203k
    }
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
14.8k
{
53
14.8k
    qpdf::Tokenizer tokenizer;
54
14.8k
    if (auto result = QPDFParser(
55
14.8k
                          input,
56
14.8k
                          make_description(input.getName(), object_description),
57
14.8k
                          object_description,
58
14.8k
                          tokenizer,
59
14.8k
                          nullptr,
60
14.8k
                          context,
61
14.8k
                          false)
62
14.8k
                          .parse()) {
63
14.8k
        return result;
64
14.8k
    }
65
0
    return {QPDFObject::create<QPDF_Null>()};
66
14.8k
}
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
140k
{
131
140k
    return QPDFParser(
132
140k
               input,
133
140k
               make_description(input.getName(), object_description),
134
140k
               object_description,
135
140k
               tokenizer,
136
140k
               decrypter,
137
140k
               &context,
138
140k
               true,
139
140k
               0,
140
140k
               0,
141
140k
               sanity_checks)
142
140k
        .parse();
143
140k
}
144
145
QPDFObjectHandle
146
QPDFParser::parse(
147
    is::OffsetBuffer& input, int stream_id, int obj_id, qpdf::Tokenizer& tokenizer, QPDF& context)
148
48.3k
{
149
48.3k
    return QPDFParser(
150
48.3k
               input,
151
48.3k
               std::make_shared<QPDFObject::Description>(
152
48.3k
                   QPDFObject::ObjStreamDescr(stream_id, obj_id)),
153
48.3k
               "",
154
48.3k
               tokenizer,
155
48.3k
               nullptr,
156
48.3k
               &context,
157
48.3k
               true,
158
48.3k
               stream_id,
159
48.3k
               obj_id)
160
48.3k
        .parse();
161
48.3k
}
162
163
QPDFObjectHandle
164
QPDFParser::parse(bool content_stream)
165
203k
{
166
203k
    try {
167
203k
        return parse_first(content_stream);
168
203k
    } catch (Error&) {
169
6.48k
        return {};
170
6.48k
    } catch (QPDFExc& e) {
171
2.76k
        throw e;
172
2.76k
    } catch (std::logic_error& e) {
173
2
        throw e;
174
550
    } catch (std::exception& e) {
175
550
        warn("treating object as null because of error during parsing : "s + e.what());
176
550
        return {};
177
550
    }
178
203k
}
179
180
QPDFObjectHandle
181
QPDFParser::parse_first(bool content_stream)
182
203k
{
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
203k
    QPDF::Doc::ParseGuard pg(context);
189
203k
    start = input.tell();
190
203k
    if (!tokenizer.nextToken(input, object_description)) {
191
1.67k
        warn(tokenizer.getErrorMessage());
192
1.67k
    }
193
194
203k
    switch (tokenizer.getType()) {
195
929
    case QPDFTokenizer::tt_eof:
196
929
        if (content_stream) {
197
            // In content stream mode, leave object uninitialized to indicate EOF
198
0
            empty_ = true;
199
0
            return {};
200
0
        }
201
929
        warn("unexpected EOF");
202
929
        return {};
203
204
1.71k
    case QPDFTokenizer::tt_bad:
205
1.71k
        return {};
206
207
94
    case QPDFTokenizer::tt_brace_open:
208
184
    case QPDFTokenizer::tt_brace_close:
209
184
        warn("treating unexpected brace token as null");
210
184
        return {};
211
212
577
    case QPDFTokenizer::tt_array_close:
213
577
        warn("treating unexpected array close token as null");
214
577
        return {};
215
216
532
    case QPDFTokenizer::tt_dict_close:
217
532
        warn("unexpected dictionary close token");
218
532
        return {};
219
220
9.70k
    case QPDFTokenizer::tt_array_open:
221
174k
    case QPDFTokenizer::tt_dict_open:
222
174k
        stack.clear();
223
174k
        stack.emplace_back(
224
174k
            input,
225
174k
            (tokenizer.getType() == QPDFTokenizer::tt_array_open) ? st_array : st_dictionary_key);
226
174k
        frame = &stack.back();
227
174k
        return parseRemainder(content_stream);
228
229
486
    case QPDFTokenizer::tt_bool:
230
486
        return withDescription<QPDF_Bool>(tokenizer.getValue() == "true");
231
232
135
    case QPDFTokenizer::tt_null:
233
135
        return {QPDFObject::create<QPDF_Null>()};
234
235
12.4k
    case QPDFTokenizer::tt_integer:
236
12.4k
        return withDescription<QPDF_Integer>(QUtil::string_to_ll(tokenizer.getValue().c_str()));
237
238
634
    case QPDFTokenizer::tt_real:
239
634
        return withDescription<QPDF_Real>(tokenizer.getValue());
240
241
1.51k
    case QPDFTokenizer::tt_name:
242
1.51k
        return withDescription<QPDF_Name>(tokenizer.getValue());
243
244
10.1k
    case QPDFTokenizer::tt_word:
245
10.1k
        {
246
10.1k
            auto const& value = tokenizer.getValue();
247
10.1k
            if (content_stream) {
248
0
                return withDescription<QPDF_Operator>(value);
249
10.1k
            } 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
185
                empty_ = true;
255
185
                input.seek(input.getLastOffset(), SEEK_SET);
256
185
                if (!content_stream) {
257
185
                    warn("empty object treated as null");
258
185
                }
259
185
                return {};
260
9.92k
            } else {
261
9.92k
                warn("unknown token while reading object; treating as string");
262
9.92k
                return withDescription<QPDF_String>(value);
263
9.92k
            }
264
10.1k
        }
265
266
417
    case QPDFTokenizer::tt_string:
267
417
        if (decrypter) {
268
47
            std::string s{tokenizer.getValue()};
269
47
            decrypter->decryptString(s);
270
47
            return withDescription<QPDF_String>(s);
271
370
        } else {
272
370
            return withDescription<QPDF_String>(tokenizer.getValue());
273
370
        }
274
275
0
    default:
276
0
        warn("treating unknown token type as null while reading object");
277
0
        return {};
278
203k
    }
279
203k
}
280
281
QPDFObjectHandle
282
QPDFParser::parseRemainder(bool content_stream)
283
174k
{
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
174k
    bad_count = 0;
290
174k
    bool b_contents = false;
291
292
5.79M
    while (true) {
293
5.78M
        if (!tokenizer.nextToken(input, object_description)) {
294
31.9k
            warn(tokenizer.getErrorMessage());
295
31.9k
        }
296
5.78M
        ++good_count; // optimistically
297
298
5.78M
        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.64M
            if (tokenizer.getType() == QPDFTokenizer::tt_integer) {
302
895k
                if (++int_count > 2) {
303
                    // Process the oldest buffered integer.
304
357k
                    addInt(int_count);
305
357k
                }
306
895k
                last_offset_buffer[int_count % 2] = input.getLastOffset();
307
895k
                int_buffer[int_count % 2] = QUtil::string_to_ll(tokenizer.getValue().c_str());
308
895k
                continue;
309
310
895k
            } else if (
311
747k
                int_count >= 2 && tokenizer.getType() == QPDFTokenizer::tt_word &&
312
487k
                tokenizer.getValue() == "R") {
313
467k
                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
467k
                auto id = QIntC::to_int(int_buffer[(int_count - 1) % 2]);
319
467k
                auto gen = QIntC::to_int(int_buffer[(int_count) % 2]);
320
467k
                if (!(id < 1 || gen < 0 || gen >= 65535)) {
321
465k
                    add(ParseGuard::getObject(context, id, gen, parse_pdf));
322
465k
                } else {
323
2.22k
                    add_bad_null(
324
2.22k
                        "treating bad indirect reference (" + std::to_string(id) + " " +
325
2.22k
                        std::to_string(gen) + " R) as null");
326
2.22k
                }
327
467k
                int_count = 0;
328
467k
                continue;
329
330
467k
            } else if (int_count > 0) {
331
                // Process the buffered integers before processing the current token.
332
280k
                if (int_count > 1) {
333
70.2k
                    addInt(int_count - 1);
334
70.2k
                }
335
280k
                addInt(int_count);
336
280k
                int_count = 0;
337
280k
            }
338
1.64M
        }
339
340
4.41M
        switch (tokenizer.getType()) {
341
8.07k
        case QPDFTokenizer::tt_eof:
342
8.07k
            warn("parse error while reading object");
343
8.07k
            if (content_stream) {
344
                // In content stream mode, leave object uninitialized to indicate EOF
345
0
                return {};
346
0
            }
347
8.07k
            warn("unexpected EOF");
348
8.07k
            return {};
349
350
26.0k
        case QPDFTokenizer::tt_bad:
351
26.0k
            check_too_many_bad_tokens();
352
26.0k
            addNull();
353
26.0k
            continue;
354
355
2.59k
        case QPDFTokenizer::tt_brace_open:
356
4.17k
        case QPDFTokenizer::tt_brace_close:
357
4.17k
            add_bad_null("treating unexpected brace token as null");
358
4.17k
            continue;
359
360
122k
        case QPDFTokenizer::tt_array_close:
361
122k
            if (frame->state == st_array) {
362
121k
                auto object = frame->null_count > 100
363
121k
                    ? QPDFObject::create<QPDF_Array>(std::move(frame->olist), true)
364
121k
                    : QPDFObject::create<QPDF_Array>(std::move(frame->olist));
365
121k
                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
121k
                if (stack.size() <= 1) {
371
1.93k
                    return object;
372
1.93k
                }
373
119k
                stack.pop_back();
374
119k
                frame = &stack.back();
375
119k
                add(std::move(object));
376
119k
            } else {
377
1.68k
                if (sanity_checks) {
378
                    // During sanity checks, assume nesting of containers is corrupt and object is
379
                    // unusable.
380
1.24k
                    warn("unexpected array close token; giving up on reading object");
381
1.24k
                    return {};
382
1.24k
                }
383
442
                add_bad_null("treating unexpected array close token as null");
384
442
            }
385
119k
            continue;
386
387
226k
        case QPDFTokenizer::tt_dict_close:
388
226k
            if (frame->state <= st_dictionary_value) {
389
                // Attempt to recover more or less gracefully from invalid dictionaries.
390
224k
                auto& dict = frame->dict;
391
392
224k
                if (frame->state == st_dictionary_value) {
393
8.55k
                    warn(
394
8.55k
                        frame->offset,
395
8.55k
                        "dictionary ended prematurely; using null as value for last key");
396
8.55k
                    dict[frame->key] = QPDFObject::create<QPDF_Null>();
397
8.55k
                }
398
224k
                if (!frame->olist.empty()) {
399
41.8k
                    if (sanity_checks) {
400
40.1k
                        warn(
401
40.1k
                            frame->offset,
402
40.1k
                            "expected dictionary keys but found non-name objects; ignoring");
403
40.1k
                    } else {
404
1.69k
                        fixMissingKeys();
405
1.69k
                    }
406
41.8k
                }
407
408
224k
                if (!frame->contents_string.empty() && dict.contains("/Type") &&
409
89
                    dict["/Type"].isNameAndEquals("/Sig") && dict.contains("/ByteRange") &&
410
30
                    dict.contains("/Contents") && dict["/Contents"].isString()) {
411
30
                    dict["/Contents"] = QPDFObjectHandle::newString(frame->contents_string);
412
30
                    dict["/Contents"].setParsedOffset(frame->contents_offset);
413
30
                }
414
224k
                auto object = QPDFObject::create<QPDF_Dictionary>(std::move(dict));
415
224k
                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
224k
                if (stack.size() <= 1) {
421
150k
                    return object;
422
150k
                }
423
74.6k
                stack.pop_back();
424
74.6k
                frame = &stack.back();
425
74.6k
                add(std::move(object));
426
74.6k
            } else {
427
1.75k
                if (sanity_checks) {
428
                    // During sanity checks, assume nesting of containers is corrupt and object is
429
                    // unusable.
430
1.18k
                    warn("unexpected dictionary close token; giving up on reading object");
431
1.18k
                    return {};
432
1.18k
                }
433
570
                add_bad_null("unexpected dictionary close token");
434
570
            }
435
75.1k
            continue;
436
437
173k
        case QPDFTokenizer::tt_array_open:
438
302k
        case QPDFTokenizer::tt_dict_open:
439
302k
            if (stack.size() > max_nesting) {
440
106
                warn("ignoring excessively deeply nested data structure");
441
106
                return {};
442
302k
            } else {
443
302k
                b_contents = false;
444
302k
                stack.emplace_back(
445
302k
                    input,
446
302k
                    (tokenizer.getType() == QPDFTokenizer::tt_array_open) ? st_array
447
302k
                                                                          : st_dictionary_key);
448
302k
                frame = &stack.back();
449
302k
                continue;
450
302k
            }
451
452
11.9k
        case QPDFTokenizer::tt_bool:
453
11.9k
            addScalar<QPDF_Bool>(tokenizer.getValue() == "true");
454
11.9k
            continue;
455
456
81.8k
        case QPDFTokenizer::tt_null:
457
81.8k
            addNull();
458
81.8k
            continue;
459
460
747k
        case QPDFTokenizer::tt_integer:
461
747k
            if (!content_stream) {
462
                // Buffer token in case it is part of an indirect reference.
463
747k
                last_offset_buffer[1] = input.getLastOffset();
464
747k
                int_buffer[1] = QUtil::string_to_ll(tokenizer.getValue().c_str());
465
747k
                int_count = 1;
466
747k
            } else {
467
0
                addScalar<QPDF_Integer>(QUtil::string_to_ll(tokenizer.getValue().c_str()));
468
0
            }
469
747k
            continue;
470
471
87.6k
        case QPDFTokenizer::tt_real:
472
87.6k
            addScalar<QPDF_Real>(tokenizer.getValue());
473
87.6k
            continue;
474
475
2.56M
        case QPDFTokenizer::tt_name:
476
2.56M
            if (frame->state == st_dictionary_key) {
477
935k
                frame->key = tokenizer.getValue();
478
935k
                frame->state = st_dictionary_value;
479
935k
                b_contents = decrypter && frame->key == "/Contents";
480
935k
                continue;
481
1.62M
            } else {
482
1.62M
                addScalar<QPDF_Name>(tokenizer.getValue());
483
1.62M
            }
484
1.62M
            continue;
485
486
1.62M
        case QPDFTokenizer::tt_word:
487
186k
            if (content_stream) {
488
0
                addScalar<QPDF_Operator>(tokenizer.getValue());
489
0
                continue;
490
0
            }
491
492
186k
            if (sanity_checks) {
493
180k
                if (tokenizer.getValue() == "endobj" || tokenizer.getValue() == "endstream") {
494
                    // During sanity checks, assume an unexpected endobj or endstream indicates that
495
                    // we are parsing past the end of the object.
496
2.61k
                    warn(
497
2.61k
                        "unexpected 'endobj' or 'endstream' while reading object; giving up on "
498
2.61k
                        "reading object");
499
2.61k
                    return {};
500
2.61k
                }
501
502
178k
                add_bad_null("unknown token while reading object; treating as null");
503
178k
                continue;
504
180k
            }
505
506
5.74k
            warn("unknown token while reading object; treating as string");
507
5.74k
            check_too_many_bad_tokens();
508
5.74k
            addScalar<QPDF_String>(tokenizer.getValue());
509
510
5.74k
            continue;
511
512
51.8k
        case QPDFTokenizer::tt_string:
513
51.8k
            {
514
51.8k
                auto const& val = tokenizer.getValue();
515
51.8k
                if (decrypter) {
516
9.84k
                    if (b_contents) {
517
670
                        frame->contents_string = val;
518
670
                        frame->contents_offset = input.getLastOffset();
519
670
                        b_contents = false;
520
670
                    }
521
9.84k
                    std::string s{val};
522
9.84k
                    decrypter->decryptString(s);
523
9.84k
                    addScalar<QPDF_String>(s);
524
42.0k
                } else {
525
42.0k
                    addScalar<QPDF_String>(val);
526
42.0k
                }
527
51.8k
            }
528
51.8k
            continue;
529
530
0
        default:
531
0
            add_bad_null("treating unknown token type as null while reading object");
532
4.41M
        }
533
4.41M
    }
534
174k
}
535
536
void
537
QPDFParser::add(std::shared_ptr<QPDFObject>&& obj)
538
3.14M
{
539
3.14M
    if (frame->state != st_dictionary_value) {
540
        // If state is st_dictionary_key then there is a missing key. Push onto olist for
541
        // processing once the tt_dict_close token has been found.
542
2.26M
        frame->olist.emplace_back(std::move(obj));
543
2.26M
    } else {
544
881k
        if (auto res = frame->dict.insert_or_assign(frame->key, std::move(obj)); !res.second) {
545
30.9k
            warnDuplicateKey();
546
30.9k
        }
547
881k
        frame->state = st_dictionary_key;
548
881k
    }
549
3.14M
}
550
551
void
552
QPDFParser::addNull()
553
286k
{
554
286k
    const static ObjectPtr null_obj = QPDFObject::create<QPDF_Null>();
555
556
286k
    if (frame->state != st_dictionary_value) {
557
        // If state is st_dictionary_key then there is a missing key. Push onto olist for
558
        // processing once the tt_dict_close token has been found.
559
249k
        frame->olist.emplace_back(null_obj);
560
249k
    } else {
561
36.5k
        if (auto res = frame->dict.insert_or_assign(frame->key, null_obj); !res.second) {
562
3.72k
            warnDuplicateKey();
563
3.72k
        }
564
36.5k
        frame->state = st_dictionary_key;
565
36.5k
    }
566
286k
    ++frame->null_count;
567
286k
}
568
569
void
570
QPDFParser::add_bad_null(std::string const& msg)
571
185k
{
572
185k
    warn(msg);
573
185k
    check_too_many_bad_tokens();
574
185k
    addNull();
575
185k
}
576
577
void
578
QPDFParser::addInt(int count)
579
707k
{
580
707k
    auto obj = QPDFObject::create<QPDF_Integer>(int_buffer[count % 2]);
581
707k
    obj->setDescription(context, description, last_offset_buffer[count % 2]);
582
707k
    add(std::move(obj));
583
707k
}
584
585
template <typename T, typename... Args>
586
void
587
QPDFParser::addScalar(Args&&... args)
588
1.78M
{
589
1.78M
    auto limit = Limits::objects_max_container_size(bad_count || sanity_checks);
590
1.78M
    if (frame->olist.size() > limit || frame->dict.size() > limit) {
591
        // Stop adding scalars. We are going to abort when the close token or a bad token is
592
        // encountered.
593
234
        max_bad_count = 0;
594
234
        check_too_many_bad_tokens(); // always throws Error()
595
234
    }
596
1.78M
    auto obj = QPDFObject::create<T>(std::forward<Args>(args)...);
597
1.78M
    obj->setDescription(context, description, input.getLastOffset());
598
1.78M
    add(std::move(obj));
599
1.78M
}
void QPDFParser::addScalar<QPDF_Bool, bool>(bool&&)
Line
Count
Source
588
11.9k
{
589
11.9k
    auto limit = Limits::objects_max_container_size(bad_count || sanity_checks);
590
11.9k
    if (frame->olist.size() > limit || frame->dict.size() > limit) {
591
        // Stop adding scalars. We are going to abort when the close token or a bad token is
592
        // encountered.
593
3
        max_bad_count = 0;
594
3
        check_too_many_bad_tokens(); // always throws Error()
595
3
    }
596
11.9k
    auto obj = QPDFObject::create<T>(std::forward<Args>(args)...);
597
11.9k
    obj->setDescription(context, description, input.getLastOffset());
598
11.9k
    add(std::move(obj));
599
11.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
588
87.6k
{
589
87.6k
    auto limit = Limits::objects_max_container_size(bad_count || sanity_checks);
590
87.6k
    if (frame->olist.size() > limit || frame->dict.size() > limit) {
591
        // Stop adding scalars. We are going to abort when the close token or a bad token is
592
        // encountered.
593
7
        max_bad_count = 0;
594
7
        check_too_many_bad_tokens(); // always throws Error()
595
7
    }
596
87.6k
    auto obj = QPDFObject::create<T>(std::forward<Args>(args)...);
597
87.6k
    obj->setDescription(context, description, input.getLastOffset());
598
87.6k
    add(std::move(obj));
599
87.6k
}
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
588
1.62M
{
589
1.62M
    auto limit = Limits::objects_max_container_size(bad_count || sanity_checks);
590
1.62M
    if (frame->olist.size() > limit || frame->dict.size() > limit) {
591
        // Stop adding scalars. We are going to abort when the close token or a bad token is
592
        // encountered.
593
215
        max_bad_count = 0;
594
215
        check_too_many_bad_tokens(); // always throws Error()
595
215
    }
596
1.62M
    auto obj = QPDFObject::create<T>(std::forward<Args>(args)...);
597
1.62M
    obj->setDescription(context, description, input.getLastOffset());
598
1.62M
    add(std::move(obj));
599
1.62M
}
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
588
47.5k
{
589
47.5k
    auto limit = Limits::objects_max_container_size(bad_count || sanity_checks);
590
47.5k
    if (frame->olist.size() > limit || frame->dict.size() > limit) {
591
        // Stop adding scalars. We are going to abort when the close token or a bad token is
592
        // encountered.
593
8
        max_bad_count = 0;
594
8
        check_too_many_bad_tokens(); // always throws Error()
595
8
    }
596
47.5k
    auto obj = QPDFObject::create<T>(std::forward<Args>(args)...);
597
47.5k
    obj->setDescription(context, description, input.getLastOffset());
598
47.5k
    add(std::move(obj));
599
47.5k
}
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
588
9.84k
{
589
9.84k
    auto limit = Limits::objects_max_container_size(bad_count || sanity_checks);
590
9.84k
    if (frame->olist.size() > limit || frame->dict.size() > limit) {
591
        // Stop adding scalars. We are going to abort when the close token or a bad token is
592
        // encountered.
593
1
        max_bad_count = 0;
594
1
        check_too_many_bad_tokens(); // always throws Error()
595
1
    }
596
9.84k
    auto obj = QPDFObject::create<T>(std::forward<Args>(args)...);
597
9.84k
    obj->setDescription(context, description, input.getLastOffset());
598
9.84k
    add(std::move(obj));
599
9.84k
}
600
601
template <typename T, typename... Args>
602
QPDFObjectHandle
603
QPDFParser::withDescription(Args&&... args)
604
25.1k
{
605
25.1k
    auto obj = QPDFObject::create<T>(std::forward<Args>(args)...);
606
25.1k
    obj->setDescription(context, description, start);
607
25.1k
    return {obj};
608
25.1k
}
QPDFObjectHandle QPDFParser::withDescription<QPDF_Bool, bool>(bool&&)
Line
Count
Source
604
486
{
605
486
    auto obj = QPDFObject::create<T>(std::forward<Args>(args)...);
606
486
    obj->setDescription(context, description, start);
607
486
    return {obj};
608
486
}
QPDFObjectHandle QPDFParser::withDescription<QPDF_Integer, long long>(long long&&)
Line
Count
Source
604
12.3k
{
605
12.3k
    auto obj = QPDFObject::create<T>(std::forward<Args>(args)...);
606
12.3k
    obj->setDescription(context, description, start);
607
12.3k
    return {obj};
608
12.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
604
634
{
605
634
    auto obj = QPDFObject::create<T>(std::forward<Args>(args)...);
606
634
    obj->setDescription(context, description, start);
607
634
    return {obj};
608
634
}
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
604
1.51k
{
605
1.51k
    auto obj = QPDFObject::create<T>(std::forward<Args>(args)...);
606
1.51k
    obj->setDescription(context, description, start);
607
1.51k
    return {obj};
608
1.51k
}
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
604
10.0k
{
605
10.0k
    auto obj = QPDFObject::create<T>(std::forward<Args>(args)...);
606
10.0k
    obj->setDescription(context, description, start);
607
10.0k
    return {obj};
608
10.0k
}
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
604
47
{
605
47
    auto obj = QPDFObject::create<T>(std::forward<Args>(args)...);
606
47
    obj->setDescription(context, description, start);
607
47
    return {obj};
608
47
}
609
610
void
611
QPDFParser::setDescription(ObjectPtr& obj, qpdf_offset_t parsed_offset)
612
345k
{
613
345k
    if (obj) {
614
345k
        obj->setDescription(context, description, parsed_offset);
615
345k
    }
616
345k
}
617
618
void
619
QPDFParser::fixMissingKeys()
620
1.69k
{
621
1.69k
    std::set<std::string> names;
622
6.14k
    for (auto& obj: frame->olist) {
623
6.14k
        if (obj.raw_type_code() == ::ot_name) {
624
144
            names.insert(obj.obj_sp()->getStringValue());
625
144
        }
626
6.14k
    }
627
1.69k
    int next_fake_key = 1;
628
6.09k
    for (auto const& item: frame->olist) {
629
6.10k
        while (true) {
630
6.10k
            const std::string key = "/QPDFFake" + std::to_string(next_fake_key++);
631
6.10k
            const bool found_fake = !frame->dict.contains(key) && !names.contains(key);
632
6.10k
            QTC::TC("qpdf", "QPDFParser found fake", (found_fake ? 0 : 1));
633
6.10k
            if (found_fake) {
634
6.09k
                warn(
635
6.09k
                    frame->offset,
636
6.09k
                    "expected dictionary key but found non-name object; inserting key " + key);
637
6.09k
                frame->dict[key] = item;
638
6.09k
                break;
639
6.09k
            }
640
6.10k
        }
641
6.09k
    }
642
1.69k
}
643
644
void
645
QPDFParser::check_too_many_bad_tokens()
646
216k
{
647
216k
    auto limit = Limits::objects_max_container_size(bad_count || sanity_checks);
648
216k
    if (frame->olist.size() > limit || frame->dict.size() > limit) {
649
248
        if (bad_count) {
650
195
            warn(
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
            throw Error();
654
195
        }
655
53
        warn(
656
53
            "encountered an array or dictionary with more than " + std::to_string(limit) +
657
53
            " elements during xref recovery; giving up on reading object");
658
53
    }
659
216k
    if (max_bad_count && --max_bad_count > 0 && good_count > 4) {
660
80.6k
        good_count = 0;
661
80.6k
        bad_count = 1;
662
80.6k
        return;
663
80.6k
    }
664
135k
    if (++bad_count > 5 ||
665
130k
        (frame->state != st_array && QIntC::to_size(max_bad_count) < frame->olist.size())) {
666
        // Give up after 5 errors in close proximity or if the number of missing dictionary keys
667
        // exceeds the remaining number of allowable total errors.
668
6.30k
        warn("too many errors; giving up on reading object");
669
6.30k
        throw Error();
670
6.30k
    }
671
129k
    good_count = 0;
672
129k
}
673
674
void
675
QPDFParser::warn(QPDFExc const& e) const
676
354k
{
677
    // If parsing on behalf of a QPDF object and want to give a warning, we can warn through the
678
    // object. If parsing for some other reason, such as an explicit creation of an object from a
679
    // string, then just throw the exception.
680
354k
    if (context) {
681
354k
        context->warn(e);
682
354k
    } else {
683
0
        throw e;
684
0
    }
685
354k
}
686
687
void
688
QPDFParser::warnDuplicateKey()
689
34.6k
{
690
34.6k
    warn(
691
34.6k
        frame->offset,
692
34.6k
        "dictionary has duplicated key " + frame->key + "; last occurrence overrides earlier ones");
693
34.6k
}
694
695
void
696
QPDFParser::warn(qpdf_offset_t offset, std::string const& msg) const
697
354k
{
698
354k
    if (stream_id) {
699
20.8k
        std::string descr = "object "s + std::to_string(obj_id) + " 0";
700
20.8k
        std::string name = context->getFilename() + " object stream " + std::to_string(stream_id);
701
20.8k
        warn(QPDFExc(qpdf_e_damaged_pdf, name, descr, offset, msg));
702
334k
    } else {
703
334k
        warn(QPDFExc(qpdf_e_damaged_pdf, input.getName(), object_description, offset, msg));
704
334k
    }
705
354k
}
706
707
void
708
QPDFParser::warn(std::string const& msg) const
709
265k
{
710
265k
    warn(input.getLastOffset(), msg);
711
265k
}