Coverage Report

Created: 2025-11-11 07:06

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