Coverage Report

Created: 2025-11-24 06:51

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