Coverage Report

Created: 2025-11-11 07:02

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
112k
        objects(qpdf ? &qpdf->m->objects : nullptr)
27
112k
    {
28
112k
        if (objects) {
29
112k
            objects->inParse(true);
30
112k
        }
31
112k
    }
32
33
    static std::shared_ptr<QPDFObject>
34
    getObject(QPDF* qpdf, int id, int gen, bool parse_pdf)
35
186k
    {
36
186k
        return qpdf->m->objects.getObjectForParser(id, gen, parse_pdf);
37
186k
    }
38
39
    ~ParseGuard()
40
112k
    {
41
112k
        if (objects) {
42
112k
            objects->inParse(false);
43
112k
        }
44
112k
    }
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
92.6k
{
131
92.6k
    return QPDFParser(
132
92.6k
               input,
133
92.6k
               make_description(input.getName(), object_description),
134
92.6k
               object_description,
135
92.6k
               tokenizer,
136
92.6k
               decrypter,
137
92.6k
               &context,
138
92.6k
               true,
139
92.6k
               0,
140
92.6k
               0,
141
92.6k
               sanity_checks)
142
92.6k
        .parse();
143
92.6k
}
144
145
QPDFObjectHandle
146
QPDFParser::parse(
147
    is::OffsetBuffer& input, int stream_id, int obj_id, qpdf::Tokenizer& tokenizer, QPDF& context)
148
20.3k
{
149
20.3k
    return QPDFParser(
150
20.3k
               input,
151
20.3k
               std::make_shared<QPDFObject::Description>(
152
20.3k
                   QPDFObject::ObjStreamDescr(stream_id, obj_id)),
153
20.3k
               "",
154
20.3k
               tokenizer,
155
20.3k
               nullptr,
156
20.3k
               &context,
157
20.3k
               true,
158
20.3k
               stream_id,
159
20.3k
               obj_id)
160
20.3k
        .parse();
161
20.3k
}
162
163
QPDFObjectHandle
164
QPDFParser::parse(bool content_stream)
165
112k
{
166
112k
    try {
167
112k
        return parse_first(content_stream);
168
112k
    } catch (Error&) {
169
6.42k
        return {};
170
6.42k
    } catch (QPDFExc& e) {
171
3.16k
        throw e;
172
3.16k
    } catch (std::logic_error& e) {
173
1
        throw e;
174
827
    } catch (std::exception& e) {
175
827
        warn("treating object as null because of error during parsing : "s + e.what());
176
827
        return {};
177
827
    }
178
112k
}
179
180
QPDFObjectHandle
181
QPDFParser::parse_first(bool content_stream)
182
112k
{
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
112k
    QPDF::Doc::ParseGuard pg(context);
189
112k
    start = input.tell();
190
112k
    if (!tokenizer.nextToken(input, object_description)) {
191
1.77k
        warn(tokenizer.getErrorMessage());
192
1.77k
    }
193
194
112k
    switch (tokenizer.getType()) {
195
642
    case QPDFTokenizer::tt_eof:
196
642
        if (content_stream) {
197
            // In content stream mode, leave object uninitialized to indicate EOF
198
0
            empty_ = true;
199
0
            return {};
200
0
        }
201
642
        warn("unexpected EOF");
202
642
        return {};
203
204
1.84k
    case QPDFTokenizer::tt_bad:
205
1.84k
        return {};
206
207
87
    case QPDFTokenizer::tt_brace_open:
208
173
    case QPDFTokenizer::tt_brace_close:
209
173
        warn("treating unexpected brace token as null");
210
173
        return {};
211
212
331
    case QPDFTokenizer::tt_array_close:
213
331
        warn("treating unexpected array close token as null");
214
331
        return {};
215
216
317
    case QPDFTokenizer::tt_dict_close:
217
317
        warn("unexpected dictionary close token");
218
317
        return {};
219
220
8.98k
    case QPDFTokenizer::tt_array_open:
221
89.0k
    case QPDFTokenizer::tt_dict_open:
222
89.0k
        stack.clear();
223
89.0k
        stack.emplace_back(
224
89.0k
            input,
225
89.0k
            (tokenizer.getType() == QPDFTokenizer::tt_array_open) ? st_array : st_dictionary_key);
226
89.0k
        frame = &stack.back();
227
89.0k
        return parseRemainder(content_stream);
228
229
414
    case QPDFTokenizer::tt_bool:
230
414
        return withDescription<QPDF_Bool>(tokenizer.getValue() == "true");
231
232
86
    case QPDFTokenizer::tt_null:
233
86
        return {QPDFObject::create<QPDF_Null>()};
234
235
8.71k
    case QPDFTokenizer::tt_integer:
236
8.71k
        return withDescription<QPDF_Integer>(QUtil::string_to_ll(tokenizer.getValue().c_str()));
237
238
856
    case QPDFTokenizer::tt_real:
239
856
        return withDescription<QPDF_Real>(tokenizer.getValue());
240
241
1.84k
    case QPDFTokenizer::tt_name:
242
1.84k
        return withDescription<QPDF_Name>(tokenizer.getValue());
243
244
7.96k
    case QPDFTokenizer::tt_word:
245
7.96k
        {
246
7.96k
            auto const& value = tokenizer.getValue();
247
7.96k
            if (content_stream) {
248
0
                return withDescription<QPDF_Operator>(value);
249
7.96k
            } 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
278
                empty_ = true;
255
278
                input.seek(input.getLastOffset(), SEEK_SET);
256
278
                if (!content_stream) {
257
278
                    warn("empty object treated as null");
258
278
                }
259
278
                return {};
260
7.68k
            } else {
261
7.68k
                warn("unknown token while reading object; treating as string");
262
7.68k
                return withDescription<QPDF_String>(value);
263
7.68k
            }
264
7.96k
        }
265
266
711
    case QPDFTokenizer::tt_string:
267
711
        if (decrypter) {
268
172
            std::string s{tokenizer.getValue()};
269
172
            decrypter->decryptString(s);
270
172
            return withDescription<QPDF_String>(s);
271
539
        } else {
272
539
            return withDescription<QPDF_String>(tokenizer.getValue());
273
539
        }
274
275
0
    default:
276
0
        warn("treating unknown token type as null while reading object");
277
0
        return {};
278
112k
    }
279
112k
}
280
281
QPDFObjectHandle
282
QPDFParser::parseRemainder(bool content_stream)
283
89.0k
{
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
89.0k
    bad_count = 0;
290
89.0k
    bool b_contents = false;
291
292
7.17M
    while (true) {
293
7.16M
        if (!tokenizer.nextToken(input, object_description)) {
294
29.9k
            warn(tokenizer.getErrorMessage());
295
29.9k
        }
296
7.16M
        ++good_count; // optimistically
297
298
7.16M
        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.33M
            if (tokenizer.getType() == QPDFTokenizer::tt_integer) {
302
4.00M
                if (++int_count > 2) {
303
                    // Process the oldest buffered integer.
304
3.77M
                    addInt(int_count);
305
3.77M
                }
306
4.00M
                last_offset_buffer[int_count % 2] = input.getLastOffset();
307
4.00M
                int_buffer[int_count % 2] = QUtil::string_to_ll(tokenizer.getValue().c_str());
308
4.00M
                continue;
309
310
4.00M
            } else if (
311
325k
                int_count >= 2 && tokenizer.getType() == QPDFTokenizer::tt_word &&
312
203k
                tokenizer.getValue() == "R") {
313
188k
                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
188k
                auto id = QIntC::to_int(int_buffer[(int_count - 1) % 2]);
319
188k
                auto gen = QIntC::to_int(int_buffer[(int_count) % 2]);
320
188k
                if (!(id < 1 || gen < 0 || gen >= 65535)) {
321
186k
                    add(ParseGuard::getObject(context, id, gen, parse_pdf));
322
186k
                } else {
323
1.77k
                    add_bad_null(
324
1.77k
                        "treating bad indirect reference (" + std::to_string(id) + " " +
325
1.77k
                        std::to_string(gen) + " R) as null");
326
1.77k
                }
327
188k
                int_count = 0;
328
188k
                continue;
329
330
188k
            } else if (int_count > 0) {
331
                // Process the buffered integers before processing the current token.
332
137k
                if (int_count > 1) {
333
41.4k
                    addInt(int_count - 1);
334
41.4k
                }
335
137k
                addInt(int_count);
336
137k
                int_count = 0;
337
137k
            }
338
4.33M
        }
339
340
2.97M
        switch (tokenizer.getType()) {
341
7.65k
        case QPDFTokenizer::tt_eof:
342
7.65k
            warn("parse error while reading object");
343
7.65k
            if (content_stream) {
344
                // In content stream mode, leave object uninitialized to indicate EOF
345
0
                return {};
346
0
            }
347
7.65k
            warn("unexpected EOF");
348
7.65k
            return {};
349
350
23.4k
        case QPDFTokenizer::tt_bad:
351
23.4k
            check_too_many_bad_tokens();
352
23.4k
            addNull();
353
23.4k
            continue;
354
355
2.21k
        case QPDFTokenizer::tt_brace_open:
356
3.94k
        case QPDFTokenizer::tt_brace_close:
357
3.94k
            add_bad_null("treating unexpected brace token as null");
358
3.94k
            continue;
359
360
47.6k
        case QPDFTokenizer::tt_array_close:
361
47.6k
            if (frame->state == st_array) {
362
46.3k
                auto object = frame->null_count > 100
363
46.3k
                    ? QPDFObject::create<QPDF_Array>(std::move(frame->olist), true)
364
46.3k
                    : QPDFObject::create<QPDF_Array>(std::move(frame->olist));
365
46.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
46.3k
                if (stack.size() <= 1) {
371
824
                    return object;
372
824
                }
373
45.4k
                stack.pop_back();
374
45.4k
                frame = &stack.back();
375
45.4k
                add(std::move(object));
376
45.4k
            } else {
377
1.35k
                if (sanity_checks) {
378
                    // During sanity checks, assume nesting of containers is corrupt and object is
379
                    // unusable.
380
764
                    warn("unexpected array close token; giving up on reading object");
381
764
                    return {};
382
764
                }
383
591
                add_bad_null("treating unexpected array close token as null");
384
591
            }
385
46.0k
            continue;
386
387
100k
        case QPDFTokenizer::tt_dict_close:
388
100k
            if (frame->state <= st_dictionary_value) {
389
                // Attempt to recover more or less gracefully from invalid dictionaries.
390
99.6k
                auto& dict = frame->dict;
391
392
99.6k
                if (frame->state == st_dictionary_value) {
393
5.93k
                    warn(
394
5.93k
                        frame->offset,
395
5.93k
                        "dictionary ended prematurely; using null as value for last key");
396
5.93k
                    dict[frame->key] = QPDFObject::create<QPDF_Null>();
397
5.93k
                }
398
99.6k
                if (!frame->olist.empty()) {
399
31.9k
                    if (sanity_checks) {
400
29.4k
                        warn(
401
29.4k
                            frame->offset,
402
29.4k
                            "expected dictionary keys but found non-name objects; ignoring");
403
29.4k
                    } else {
404
2.50k
                        fixMissingKeys();
405
2.50k
                    }
406
31.9k
                }
407
408
99.6k
                if (!frame->contents_string.empty() && dict.contains("/Type") &&
409
120
                    dict["/Type"].isNameAndEquals("/Sig") && dict.contains("/ByteRange") &&
410
24
                    dict.contains("/Contents") && dict["/Contents"].isString()) {
411
24
                    dict["/Contents"] = QPDFObjectHandle::newString(frame->contents_string);
412
24
                    dict["/Contents"].setParsedOffset(frame->contents_offset);
413
24
                }
414
99.6k
                auto object = QPDFObject::create<QPDF_Dictionary>(std::move(dict));
415
99.6k
                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
99.6k
                if (stack.size() <= 1) {
421
68.9k
                    return object;
422
68.9k
                }
423
30.6k
                stack.pop_back();
424
30.6k
                frame = &stack.back();
425
30.6k
                add(std::move(object));
426
30.6k
            } else {
427
911
                if (sanity_checks) {
428
                    // During sanity checks, assume nesting of containers is corrupt and object is
429
                    // unusable.
430
654
                    warn("unexpected dictionary close token; giving up on reading object");
431
654
                    return {};
432
654
                }
433
257
                add_bad_null("unexpected dictionary close token");
434
257
            }
435
30.8k
            continue;
436
437
132k
        case QPDFTokenizer::tt_array_open:
438
217k
        case QPDFTokenizer::tt_dict_open:
439
217k
            if (stack.size() > max_nesting) {
440
151
                warn("ignoring excessively deeply nested data structure");
441
151
                return {};
442
216k
            } else {
443
216k
                b_contents = false;
444
216k
                stack.emplace_back(
445
216k
                    input,
446
216k
                    (tokenizer.getType() == QPDFTokenizer::tt_array_open) ? st_array
447
216k
                                                                          : st_dictionary_key);
448
216k
                frame = &stack.back();
449
216k
                continue;
450
216k
            }
451
452
2.70k
        case QPDFTokenizer::tt_bool:
453
2.70k
            addScalar<QPDF_Bool>(tokenizer.getValue() == "true");
454
2.70k
            continue;
455
456
44.1k
        case QPDFTokenizer::tt_null:
457
44.1k
            addNull();
458
44.1k
            continue;
459
460
325k
        case QPDFTokenizer::tt_integer:
461
325k
            if (!content_stream) {
462
                // Buffer token in case it is part of an indirect reference.
463
325k
                last_offset_buffer[1] = input.getLastOffset();
464
325k
                int_buffer[1] = QUtil::string_to_ll(tokenizer.getValue().c_str());
465
325k
                int_count = 1;
466
325k
            } else {
467
0
                addScalar<QPDF_Integer>(QUtil::string_to_ll(tokenizer.getValue().c_str()));
468
0
            }
469
325k
            continue;
470
471
22.8k
        case QPDFTokenizer::tt_real:
472
22.8k
            addScalar<QPDF_Real>(tokenizer.getValue());
473
22.8k
            continue;
474
475
1.93M
        case QPDFTokenizer::tt_name:
476
1.93M
            if (frame->state == st_dictionary_key) {
477
394k
                frame->key = tokenizer.getValue();
478
394k
                frame->state = st_dictionary_value;
479
394k
                b_contents = decrypter && frame->key == "/Contents";
480
394k
                continue;
481
1.53M
            } else {
482
1.53M
                addScalar<QPDF_Name>(tokenizer.getValue());
483
1.53M
            }
484
1.53M
            continue;
485
486
1.53M
        case QPDFTokenizer::tt_word:
487
155k
            if (content_stream) {
488
0
                addScalar<QPDF_Operator>(tokenizer.getValue());
489
0
                continue;
490
0
            }
491
492
155k
            if (sanity_checks) {
493
150k
                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
977
                    warn(
497
977
                        "unexpected 'endobj' or 'endstream' while reading object; giving up on "
498
977
                        "reading object");
499
977
                    return {};
500
977
                }
501
502
149k
                add_bad_null("unknown token while reading object; treating as null");
503
149k
                continue;
504
150k
            }
505
506
4.97k
            warn("unknown token while reading object; treating as string");
507
4.97k
            check_too_many_bad_tokens();
508
4.97k
            addScalar<QPDF_String>(tokenizer.getValue());
509
510
4.97k
            continue;
511
512
88.0k
        case QPDFTokenizer::tt_string:
513
88.0k
            {
514
88.0k
                auto const& val = tokenizer.getValue();
515
88.0k
                if (decrypter) {
516
12.7k
                    if (b_contents) {
517
417
                        frame->contents_string = val;
518
417
                        frame->contents_offset = input.getLastOffset();
519
417
                        b_contents = false;
520
417
                    }
521
12.7k
                    std::string s{val};
522
12.7k
                    decrypter->decryptString(s);
523
12.7k
                    addScalar<QPDF_String>(s);
524
75.2k
                } else {
525
75.2k
                    addScalar<QPDF_String>(val);
526
75.2k
                }
527
88.0k
            }
528
88.0k
            continue;
529
530
0
        default:
531
0
            add_bad_null("treating unknown token type as null while reading object");
532
2.97M
        }
533
2.97M
    }
534
89.0k
}
535
536
void
537
QPDFParser::add(std::shared_ptr<QPDFObject>&& obj)
538
5.87M
{
539
5.87M
    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
5.52M
        frame->olist.emplace_back(std::move(obj));
543
5.52M
    } else {
544
355k
        if (auto res = frame->dict.insert_or_assign(frame->key, std::move(obj)); !res.second) {
545
32.2k
            warnDuplicateKey();
546
32.2k
        }
547
355k
        frame->state = st_dictionary_key;
548
355k
    }
549
5.87M
}
550
551
void
552
QPDFParser::addNull()
553
215k
{
554
215k
    const static ObjectPtr null_obj = QPDFObject::create<QPDF_Null>();
555
556
215k
    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
188k
        frame->olist.emplace_back(null_obj);
560
188k
    } else {
561
27.2k
        if (auto res = frame->dict.insert_or_assign(frame->key, null_obj); !res.second) {
562
6.16k
            warnDuplicateKey();
563
6.16k
        }
564
27.2k
        frame->state = st_dictionary_key;
565
27.2k
    }
566
215k
    ++frame->null_count;
567
215k
}
568
569
void
570
QPDFParser::add_bad_null(std::string const& msg)
571
155k
{
572
155k
    warn(msg);
573
155k
    check_too_many_bad_tokens();
574
155k
    addNull();
575
155k
}
576
577
void
578
QPDFParser::addInt(int count)
579
3.95M
{
580
3.95M
    auto obj = QPDFObject::create<QPDF_Integer>(int_buffer[count % 2]);
581
3.95M
    obj->setDescription(context, description, last_offset_buffer[count % 2]);
582
3.95M
    add(std::move(obj));
583
3.95M
}
584
585
template <typename T, typename... Args>
586
void
587
QPDFParser::addScalar(Args&&... args)
588
1.65M
{
589
1.65M
    auto limit = Limits::objects_max_container_size(bad_count || sanity_checks);
590
1.65M
    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
336
        max_bad_count = 0;
594
336
        check_too_many_bad_tokens(); // always throws Error()
595
336
    }
596
1.65M
    auto obj = QPDFObject::create<T>(std::forward<Args>(args)...);
597
1.65M
    obj->setDescription(context, description, input.getLastOffset());
598
1.65M
    add(std::move(obj));
599
1.65M
}
void QPDFParser::addScalar<QPDF_Bool, bool>(bool&&)
Line
Count
Source
588
2.70k
{
589
2.70k
    auto limit = Limits::objects_max_container_size(bad_count || sanity_checks);
590
2.70k
    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
21
        max_bad_count = 0;
594
21
        check_too_many_bad_tokens(); // always throws Error()
595
21
    }
596
2.70k
    auto obj = QPDFObject::create<T>(std::forward<Args>(args)...);
597
2.70k
    obj->setDescription(context, description, input.getLastOffset());
598
2.70k
    add(std::move(obj));
599
2.70k
}
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
22.8k
{
589
22.8k
    auto limit = Limits::objects_max_container_size(bad_count || sanity_checks);
590
22.8k
    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
57
        max_bad_count = 0;
594
57
        check_too_many_bad_tokens(); // always throws Error()
595
57
    }
596
22.8k
    auto obj = QPDFObject::create<T>(std::forward<Args>(args)...);
597
22.8k
    obj->setDescription(context, description, input.getLastOffset());
598
22.8k
    add(std::move(obj));
599
22.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
588
1.53M
{
589
1.53M
    auto limit = Limits::objects_max_container_size(bad_count || sanity_checks);
590
1.53M
    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
174
        max_bad_count = 0;
594
174
        check_too_many_bad_tokens(); // always throws Error()
595
174
    }
596
1.53M
    auto obj = QPDFObject::create<T>(std::forward<Args>(args)...);
597
1.53M
    obj->setDescription(context, description, input.getLastOffset());
598
1.53M
    add(std::move(obj));
599
1.53M
}
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
80.1k
{
589
80.1k
    auto limit = Limits::objects_max_container_size(bad_count || sanity_checks);
590
80.1k
    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
83
        max_bad_count = 0;
594
83
        check_too_many_bad_tokens(); // always throws Error()
595
83
    }
596
80.1k
    auto obj = QPDFObject::create<T>(std::forward<Args>(args)...);
597
80.1k
    obj->setDescription(context, description, input.getLastOffset());
598
80.1k
    add(std::move(obj));
599
80.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
588
12.7k
{
589
12.7k
    auto limit = Limits::objects_max_container_size(bad_count || sanity_checks);
590
12.7k
    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
12.7k
    auto obj = QPDFObject::create<T>(std::forward<Args>(args)...);
597
12.7k
    obj->setDescription(context, description, input.getLastOffset());
598
12.7k
    add(std::move(obj));
599
12.7k
}
600
601
template <typename T, typename... Args>
602
QPDFObjectHandle
603
QPDFParser::withDescription(Args&&... args)
604
19.5k
{
605
19.5k
    auto obj = QPDFObject::create<T>(std::forward<Args>(args)...);
606
19.5k
    obj->setDescription(context, description, start);
607
19.5k
    return {obj};
608
19.5k
}
QPDFObjectHandle QPDFParser::withDescription<QPDF_Bool, bool>(bool&&)
Line
Count
Source
604
414
{
605
414
    auto obj = QPDFObject::create<T>(std::forward<Args>(args)...);
606
414
    obj->setDescription(context, description, start);
607
414
    return {obj};
608
414
}
QPDFObjectHandle QPDFParser::withDescription<QPDF_Integer, long long>(long long&&)
Line
Count
Source
604
8.43k
{
605
8.43k
    auto obj = QPDFObject::create<T>(std::forward<Args>(args)...);
606
8.43k
    obj->setDescription(context, description, start);
607
8.43k
    return {obj};
608
8.43k
}
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
856
{
605
856
    auto obj = QPDFObject::create<T>(std::forward<Args>(args)...);
606
856
    obj->setDescription(context, description, start);
607
856
    return {obj};
608
856
}
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.84k
{
605
1.84k
    auto obj = QPDFObject::create<T>(std::forward<Args>(args)...);
606
1.84k
    obj->setDescription(context, description, start);
607
1.84k
    return {obj};
608
1.84k
}
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
7.79k
{
605
7.79k
    auto obj = QPDFObject::create<T>(std::forward<Args>(args)...);
606
7.79k
    obj->setDescription(context, description, start);
607
7.79k
    return {obj};
608
7.79k
}
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
170
{
605
170
    auto obj = QPDFObject::create<T>(std::forward<Args>(args)...);
606
170
    obj->setDescription(context, description, start);
607
170
    return {obj};
608
170
}
609
610
void
611
QPDFParser::setDescription(ObjectPtr& obj, qpdf_offset_t parsed_offset)
612
145k
{
613
145k
    if (obj) {
614
145k
        obj->setDescription(context, description, parsed_offset);
615
145k
    }
616
145k
}
617
618
void
619
QPDFParser::fixMissingKeys()
620
2.50k
{
621
2.50k
    std::set<std::string> names;
622
7.89k
    for (auto& obj: frame->olist) {
623
7.89k
        if (obj.raw_type_code() == ::ot_name) {
624
353
            names.insert(obj.obj_sp()->getStringValue());
625
353
        }
626
7.89k
    }
627
2.50k
    int next_fake_key = 1;
628
7.87k
    for (auto const& item: frame->olist) {
629
7.95k
        while (true) {
630
7.95k
            const std::string key = "/QPDFFake" + std::to_string(next_fake_key++);
631
7.95k
            const bool found_fake = !frame->dict.contains(key) && !names.contains(key);
632
7.95k
            QTC::TC("qpdf", "QPDFParser found fake", (found_fake ? 0 : 1));
633
7.95k
            if (found_fake) {
634
7.87k
                warn(
635
7.87k
                    frame->offset,
636
7.87k
                    "expected dictionary key but found non-name object; inserting key " + key);
637
7.87k
                frame->dict[key] = item;
638
7.87k
                break;
639
7.87k
            }
640
7.95k
        }
641
7.87k
    }
642
2.50k
}
643
644
void
645
QPDFParser::check_too_many_bad_tokens()
646
183k
{
647
183k
    auto limit = Limits::objects_max_container_size(bad_count || sanity_checks);
648
183k
    if (frame->olist.size() > limit || frame->dict.size() > limit) {
649
353
        if (bad_count) {
650
316
            warn(
651
316
                "encountered errors while parsing an array or dictionary with more than " +
652
316
                std::to_string(limit) + " elements; giving up on reading object");
653
316
            throw Error();
654
316
        }
655
37
        warn(
656
37
            "encountered an array or dictionary with more than " + std::to_string(limit) +
657
37
            " elements during xref recovery; giving up on reading object");
658
37
    }
659
182k
    if (max_bad_count && --max_bad_count > 0 && good_count > 4) {
660
60.5k
        good_count = 0;
661
60.5k
        bad_count = 1;
662
60.5k
        return;
663
60.5k
    }
664
122k
    if (++bad_count > 5 ||
665
118k
        (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.13k
        warn("too many errors; giving up on reading object");
669
6.13k
        throw Error();
670
6.13k
    }
671
116k
    good_count = 0;
672
116k
}
673
674
void
675
QPDFParser::warn(QPDFExc const& e) const
676
308k
{
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
308k
    if (context) {
681
308k
        context->warn(e);
682
308k
    } else {
683
0
        throw e;
684
0
    }
685
308k
}
686
687
void
688
QPDFParser::warnDuplicateKey()
689
38.4k
{
690
38.4k
    warn(
691
38.4k
        frame->offset,
692
38.4k
        "dictionary has duplicated key " + frame->key + "; last occurrence overrides earlier ones");
693
38.4k
}
694
695
void
696
QPDFParser::warn(qpdf_offset_t offset, std::string const& msg) const
697
308k
{
698
308k
    if (stream_id) {
699
13.1k
        std::string descr = "object "s + std::to_string(obj_id) + " 0";
700
13.1k
        std::string name = context->getFilename() + " object stream " + std::to_string(stream_id);
701
13.1k
        warn(QPDFExc(qpdf_e_damaged_pdf, name, descr, offset, msg));
702
295k
    } else {
703
295k
        warn(QPDFExc(qpdf_e_damaged_pdf, input.getName(), object_description, offset, msg));
704
295k
    }
705
308k
}
706
707
void
708
QPDFParser::warn(std::string const& msg) const
709
226k
{
710
226k
    warn(input.getLastOffset(), msg);
711
226k
}