Coverage Report

Created: 2025-12-05 06:58

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/qpdf/libqpdf/QPDFParser.cc
Line
Count
Source
1
#include <qpdf/QPDFParser.hh>
2
3
#include <qpdf/QPDF.hh>
4
#include <qpdf/QPDFObjGen.hh>
5
#include <qpdf/QPDFObjectHandle.hh>
6
#include <qpdf/QPDFObject_private.hh>
7
#include <qpdf/QPDFTokenizer_private.hh>
8
#include <qpdf/QTC.hh>
9
#include <qpdf/QUtil.hh>
10
11
#include <memory>
12
13
using namespace std::literals;
14
using namespace qpdf;
15
16
using ObjectPtr = std::shared_ptr<QPDFObject>;
17
18
static uint32_t const& max_nesting{global::Limits::parser_max_nesting()};
19
20
// The ParseGuard class allows QPDFParser to detect re-entrant parsing. It also provides
21
// special access to allow the parser to create unresolved objects and dangling references.
22
class QPDF::Doc::ParseGuard
23
{
24
  public:
25
    ParseGuard(QPDF* qpdf) :
26
211k
        objects(qpdf ? &qpdf->m->objects : nullptr)
27
211k
    {
28
211k
        if (objects) {
29
195k
            objects->inParse(true);
30
195k
        }
31
211k
    }
32
33
    static std::shared_ptr<QPDFObject>
34
    getObject(QPDF* qpdf, int id, int gen, bool parse_pdf)
35
471k
    {
36
471k
        return qpdf->m->objects.getObjectForParser(id, gen, parse_pdf);
37
471k
    }
38
39
    ~ParseGuard()
40
211k
    {
41
211k
        if (objects) {
42
195k
            objects->inParse(false);
43
195k
        }
44
211k
    }
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.4k
{
53
15.4k
    qpdf::Tokenizer tokenizer;
54
15.4k
    if (auto result = QPDFParser(
55
15.4k
                          input,
56
15.4k
                          make_description(input.getName(), object_description),
57
15.4k
                          object_description,
58
15.4k
                          tokenizer,
59
15.4k
                          nullptr,
60
15.4k
                          context,
61
15.4k
                          false)
62
15.4k
                          .parse()) {
63
15.4k
        return result;
64
15.4k
    }
65
0
    return {QPDFObject::create<QPDF_Null>()};
66
15.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
144k
{
131
144k
    return QPDFParser(
132
144k
               input,
133
144k
               make_description(input.getName(), object_description),
134
144k
               object_description,
135
144k
               tokenizer,
136
144k
               decrypter,
137
144k
               &context,
138
144k
               true,
139
144k
               0,
140
144k
               0,
141
144k
               sanity_checks)
142
144k
        .parse();
143
144k
}
144
145
QPDFObjectHandle
146
QPDFParser::parse(
147
    is::OffsetBuffer& input, int stream_id, int obj_id, qpdf::Tokenizer& tokenizer, QPDF& context)
148
50.7k
{
149
50.7k
    return QPDFParser(
150
50.7k
               input,
151
50.7k
               std::make_shared<QPDFObject::Description>(
152
50.7k
                   QPDFObject::ObjStreamDescr(stream_id, obj_id)),
153
50.7k
               "",
154
50.7k
               tokenizer,
155
50.7k
               nullptr,
156
50.7k
               &context,
157
50.7k
               true,
158
50.7k
               stream_id,
159
50.7k
               obj_id)
160
50.7k
        .parse();
161
50.7k
}
162
163
QPDFObjectHandle
164
QPDFParser::parse(bool content_stream)
165
211k
{
166
211k
    try {
167
211k
        return parse_first(content_stream);
168
211k
    } catch (Error&) {
169
6.95k
        return {};
170
6.95k
    } catch (QPDFExc& e) {
171
3.08k
        throw e;
172
3.08k
    } catch (std::logic_error& e) {
173
1
        throw e;
174
934
    } catch (std::exception& e) {
175
934
        warn("treating object as null because of error during parsing : "s + e.what());
176
934
        return {};
177
934
    }
178
211k
}
179
180
QPDFObjectHandle
181
QPDFParser::parse_first(bool content_stream)
182
211k
{
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
211k
    QPDF::Doc::ParseGuard pg(context);
189
211k
    start = input.tell();
190
211k
    if (!tokenizer.nextToken(input, object_description)) {
191
1.77k
        warn(tokenizer.getErrorMessage());
192
1.77k
    }
193
194
211k
    switch (tokenizer.getType()) {
195
706
    case QPDFTokenizer::tt_eof:
196
706
        if (content_stream) {
197
            // In content stream mode, leave object uninitialized to indicate EOF
198
0
            empty_ = true;
199
0
            return {};
200
0
        }
201
706
        warn("unexpected EOF");
202
706
        return {};
203
204
1.81k
    case QPDFTokenizer::tt_bad:
205
1.81k
        return {};
206
207
85
    case QPDFTokenizer::tt_brace_open:
208
209
    case QPDFTokenizer::tt_brace_close:
209
209
        warn("treating unexpected brace token as null");
210
209
        return {};
211
212
632
    case QPDFTokenizer::tt_array_close:
213
632
        warn("treating unexpected array close token as null");
214
632
        return {};
215
216
590
    case QPDFTokenizer::tt_dict_close:
217
590
        warn("unexpected dictionary close token");
218
590
        return {};
219
220
10.3k
    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
435
    case QPDFTokenizer::tt_bool:
230
435
        return withDescription<QPDF_Bool>(tokenizer.getValue() == "true");
231
232
264
    case QPDFTokenizer::tt_null:
233
264
        return {QPDFObject::create<QPDF_Null>()};
234
235
12.9k
    case QPDFTokenizer::tt_integer:
236
12.9k
        return withDescription<QPDF_Integer>(QUtil::string_to_ll(tokenizer.getValue().c_str()));
237
238
666
    case QPDFTokenizer::tt_real:
239
666
        return withDescription<QPDF_Real>(tokenizer.getValue());
240
241
1.70k
    case QPDFTokenizer::tt_name:
242
1.70k
        return withDescription<QPDF_Name>(tokenizer.getValue());
243
244
11.1k
    case QPDFTokenizer::tt_word:
245
11.1k
        {
246
11.1k
            auto const& value = tokenizer.getValue();
247
11.1k
            if (content_stream) {
248
0
                return withDescription<QPDF_Operator>(value);
249
11.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
170
                empty_ = true;
255
170
                input.seek(input.getLastOffset(), SEEK_SET);
256
170
                if (!content_stream) {
257
170
                    warn("empty object treated as null");
258
170
                }
259
170
                return {};
260
10.9k
            } else {
261
10.9k
                warn("unknown token while reading object; treating as string");
262
10.9k
                return withDescription<QPDF_String>(value);
263
10.9k
            }
264
11.1k
        }
265
266
389
    case QPDFTokenizer::tt_string:
267
389
        if (decrypter) {
268
39
            std::string s{tokenizer.getValue()};
269
39
            decrypter->decryptString(s);
270
39
            return withDescription<QPDF_String>(s);
271
350
        } else {
272
350
            return withDescription<QPDF_String>(tokenizer.getValue());
273
350
        }
274
275
0
    default:
276
0
        warn("treating unknown token type as null while reading object");
277
0
        return {};
278
211k
    }
279
211k
}
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.93M
    while (true) {
293
5.92M
        if (!tokenizer.nextToken(input, object_description)) {
294
31.7k
            warn(tokenizer.getErrorMessage());
295
31.7k
        }
296
5.92M
        ++good_count; // optimistically
297
298
5.92M
        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.97M
            if (tokenizer.getType() == QPDFTokenizer::tt_integer) {
302
1.20M
                if (++int_count > 2) {
303
                    // Process the oldest buffered integer.
304
660k
                    addInt(int_count);
305
660k
                }
306
1.20M
                last_offset_buffer[int_count % 2] = input.getLastOffset();
307
1.20M
                int_buffer[int_count % 2] = QUtil::string_to_ll(tokenizer.getValue().c_str());
308
1.20M
                continue;
309
310
1.20M
            } else if (
311
767k
                int_count >= 2 && tokenizer.getType() == QPDFTokenizer::tt_word &&
312
493k
                tokenizer.getValue() == "R") {
313
473k
                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
473k
                auto id = QIntC::to_int(int_buffer[(int_count - 1) % 2]);
319
473k
                auto gen = QIntC::to_int(int_buffer[(int_count) % 2]);
320
473k
                if (!(id < 1 || gen < 0 || gen >= 65535)) {
321
471k
                    add(ParseGuard::getObject(context, id, gen, parse_pdf));
322
471k
                } else {
323
2.32k
                    add_bad_null(
324
2.32k
                        "treating bad indirect reference (" + std::to_string(id) + " " +
325
2.32k
                        std::to_string(gen) + " R) as null");
326
2.32k
                }
327
473k
                int_count = 0;
328
473k
                continue;
329
330
473k
            } else if (int_count > 0) {
331
                // Process the buffered integers before processing the current token.
332
293k
                if (int_count > 1) {
333
72.1k
                    addInt(int_count - 1);
334
72.1k
                }
335
293k
                addInt(int_count);
336
293k
                int_count = 0;
337
293k
            }
338
1.97M
        }
339
340
4.24M
        switch (tokenizer.getType()) {
341
7.64k
        case QPDFTokenizer::tt_eof:
342
7.64k
            warn("parse error while reading object");
343
7.64k
            if (content_stream) {
344
                // In content stream mode, leave object uninitialized to indicate EOF
345
0
                return {};
346
0
            }
347
7.64k
            warn("unexpected EOF");
348
7.64k
            return {};
349
350
25.7k
        case QPDFTokenizer::tt_bad:
351
25.7k
            check_too_many_bad_tokens();
352
25.7k
            addNull();
353
25.7k
            continue;
354
355
2.22k
        case QPDFTokenizer::tt_brace_open:
356
3.70k
        case QPDFTokenizer::tt_brace_close:
357
3.70k
            add_bad_null("treating unexpected brace token as null");
358
3.70k
            continue;
359
360
129k
        case QPDFTokenizer::tt_array_close:
361
129k
            if (frame->state == st_array) {
362
127k
                auto object = frame->null_count > 100
363
127k
                    ? QPDFObject::create<QPDF_Array>(std::move(frame->olist), true)
364
127k
                    : QPDFObject::create<QPDF_Array>(std::move(frame->olist));
365
127k
                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
127k
                if (stack.size() <= 1) {
371
2.11k
                    return object;
372
2.11k
                }
373
125k
                stack.pop_back();
374
125k
                frame = &stack.back();
375
125k
                add(std::move(object));
376
125k
            } else {
377
1.75k
                if (sanity_checks) {
378
                    // During sanity checks, assume nesting of containers is corrupt and object is
379
                    // unusable.
380
1.28k
                    warn("unexpected array close token; giving up on reading object");
381
1.28k
                    return {};
382
1.28k
                }
383
475
                add_bad_null("treating unexpected array close token as null");
384
475
            }
385
125k
            continue;
386
387
232k
        case QPDFTokenizer::tt_dict_close:
388
232k
            if (frame->state <= st_dictionary_value) {
389
                // Attempt to recover more or less gracefully from invalid dictionaries.
390
230k
                auto& dict = frame->dict;
391
392
230k
                if (frame->state == st_dictionary_value) {
393
8.85k
                    warn(
394
8.85k
                        frame->offset,
395
8.85k
                        "dictionary ended prematurely; using null as value for last key");
396
8.85k
                    dict[frame->key] = QPDFObject::create<QPDF_Null>();
397
8.85k
                }
398
230k
                if (!frame->olist.empty()) {
399
43.9k
                    if (sanity_checks) {
400
42.1k
                        warn(
401
42.1k
                            frame->offset,
402
42.1k
                            "expected dictionary keys but found non-name objects; ignoring");
403
42.1k
                    } else {
404
1.81k
                        fixMissingKeys();
405
1.81k
                    }
406
43.9k
                }
407
408
230k
                if (!frame->contents_string.empty() && dict.contains("/Type") &&
409
98
                    dict["/Type"].isNameAndEquals("/Sig") && dict.contains("/ByteRange") &&
410
33
                    dict.contains("/Contents") && dict["/Contents"].isString()) {
411
33
                    dict["/Contents"] = QPDFObjectHandle::newString(frame->contents_string);
412
33
                    dict["/Contents"].setParsedOffset(frame->contents_offset);
413
33
                }
414
230k
                auto object = QPDFObject::create<QPDF_Dictionary>(std::move(dict));
415
230k
                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
230k
                if (stack.size() <= 1) {
421
155k
                    return object;
422
155k
                }
423
75.7k
                stack.pop_back();
424
75.7k
                frame = &stack.back();
425
75.7k
                add(std::move(object));
426
75.7k
            } else {
427
1.70k
                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
492
                add_bad_null("unexpected dictionary close token");
434
492
            }
435
76.2k
            continue;
436
437
168k
        case QPDFTokenizer::tt_array_open:
438
297k
        case QPDFTokenizer::tt_dict_open:
439
297k
            if (stack.size() > max_nesting) {
440
91
                limits_error(
441
91
                    "parser-max-nesting", "ignoring excessively deeply nested data structure");
442
91
            }
443
297k
            b_contents = false;
444
297k
            stack.emplace_back(
445
297k
                input,
446
297k
                (tokenizer.getType() == QPDFTokenizer::tt_array_open) ? st_array
447
297k
                                                                      : st_dictionary_key);
448
297k
            frame = &stack.back();
449
297k
            continue;
450
451
12.2k
        case QPDFTokenizer::tt_bool:
452
12.2k
            addScalar<QPDF_Bool>(tokenizer.getValue() == "true");
453
12.2k
            continue;
454
455
72.2k
        case QPDFTokenizer::tt_null:
456
72.2k
            addNull();
457
72.2k
            continue;
458
459
767k
        case QPDFTokenizer::tt_integer:
460
767k
            if (!content_stream) {
461
                // Buffer token in case it is part of an indirect reference.
462
767k
                last_offset_buffer[1] = input.getLastOffset();
463
767k
                int_buffer[1] = QUtil::string_to_ll(tokenizer.getValue().c_str());
464
767k
                int_count = 1;
465
767k
            } else {
466
0
                addScalar<QPDF_Integer>(QUtil::string_to_ll(tokenizer.getValue().c_str()));
467
0
            }
468
767k
            continue;
469
470
98.3k
        case QPDFTokenizer::tt_real:
471
98.3k
            addScalar<QPDF_Real>(tokenizer.getValue());
472
98.3k
            continue;
473
474
2.34M
        case QPDFTokenizer::tt_name:
475
2.34M
            if (frame->state == st_dictionary_key) {
476
961k
                frame->key = tokenizer.getValue();
477
961k
                frame->state = st_dictionary_value;
478
961k
                b_contents = decrypter && frame->key == "/Contents";
479
961k
                continue;
480
1.38M
            } else {
481
1.38M
                addScalar<QPDF_Name>(tokenizer.getValue());
482
1.38M
            }
483
1.38M
            continue;
484
485
1.38M
        case QPDFTokenizer::tt_word:
486
188k
            if (content_stream) {
487
0
                addScalar<QPDF_Operator>(tokenizer.getValue());
488
0
                continue;
489
0
            }
490
491
188k
            if (sanity_checks) {
492
182k
                if (tokenizer.getValue() == "endobj" || tokenizer.getValue() == "endstream") {
493
                    // During sanity checks, assume an unexpected endobj or endstream indicates that
494
                    // we are parsing past the end of the object.
495
2.67k
                    warn(
496
2.67k
                        "unexpected 'endobj' or 'endstream' while reading object; giving up on "
497
2.67k
                        "reading object");
498
2.67k
                    return {};
499
2.67k
                }
500
501
179k
                add_bad_null("unknown token while reading object; treating as null");
502
179k
                continue;
503
182k
            }
504
505
6.26k
            warn("unknown token while reading object; treating as string");
506
6.26k
            check_too_many_bad_tokens();
507
6.26k
            addScalar<QPDF_String>(tokenizer.getValue());
508
509
6.26k
            continue;
510
511
63.6k
        case QPDFTokenizer::tt_string:
512
63.6k
            {
513
63.6k
                auto const& val = tokenizer.getValue();
514
63.6k
                if (decrypter) {
515
10.2k
                    if (b_contents) {
516
614
                        frame->contents_string = val;
517
614
                        frame->contents_offset = input.getLastOffset();
518
614
                        b_contents = false;
519
614
                    }
520
10.2k
                    std::string s{val};
521
10.2k
                    decrypter->decryptString(s);
522
10.2k
                    addScalar<QPDF_String>(s);
523
53.3k
                } else {
524
53.3k
                    addScalar<QPDF_String>(val);
525
53.3k
                }
526
63.6k
            }
527
63.6k
            continue;
528
529
0
        default:
530
0
            add_bad_null("treating unknown token type as null while reading object");
531
4.24M
        }
532
4.24M
    }
533
179k
}
534
535
void
536
QPDFParser::add(std::shared_ptr<QPDFObject>&& obj)
537
3.26M
{
538
3.26M
    if (frame->state != st_dictionary_value) {
539
        // If state is st_dictionary_key then there is a missing key. Push onto olist for
540
        // processing once the tt_dict_close token has been found.
541
2.35M
        frame->olist.emplace_back(std::move(obj));
542
2.35M
    } else {
543
907k
        if (auto res = frame->dict.insert_or_assign(frame->key, std::move(obj)); !res.second) {
544
33.1k
            warnDuplicateKey();
545
33.1k
        }
546
907k
        frame->state = st_dictionary_key;
547
907k
    }
548
3.26M
}
549
550
void
551
QPDFParser::addNull()
552
276k
{
553
276k
    const static ObjectPtr null_obj = QPDFObject::create<QPDF_Null>();
554
555
276k
    if (frame->state != st_dictionary_value) {
556
        // If state is st_dictionary_key then there is a missing key. Push onto olist for
557
        // processing once the tt_dict_close token has been found.
558
239k
        frame->olist.emplace_back(null_obj);
559
239k
    } else {
560
36.5k
        if (auto res = frame->dict.insert_or_assign(frame->key, null_obj); !res.second) {
561
3.75k
            warnDuplicateKey();
562
3.75k
        }
563
36.5k
        frame->state = st_dictionary_key;
564
36.5k
    }
565
276k
    ++frame->null_count;
566
276k
}
567
568
void
569
QPDFParser::add_bad_null(std::string const& msg)
570
185k
{
571
185k
    warn(msg);
572
185k
    check_too_many_bad_tokens();
573
185k
    addNull();
574
185k
}
575
576
void
577
QPDFParser::addInt(int count)
578
1.02M
{
579
1.02M
    auto obj = QPDFObject::create<QPDF_Integer>(int_buffer[count % 2]);
580
1.02M
    obj->setDescription(context, description, last_offset_buffer[count % 2]);
581
1.02M
    add(std::move(obj));
582
1.02M
}
583
584
template <typename T, typename... Args>
585
void
586
QPDFParser::addScalar(Args&&... args)
587
1.56M
{
588
1.56M
    auto limit = Limits::parser_max_container_size(bad_count || sanity_checks);
589
1.56M
    if (frame->olist.size() >= limit || frame->dict.size() >= limit) {
590
        // Stop adding scalars. We are going to abort when the close token or a bad token is
591
        // encountered.
592
195
        max_bad_count = 1;
593
195
        check_too_many_bad_tokens(); // always throws Error()
594
195
    }
595
1.56M
    auto obj = QPDFObject::create<T>(std::forward<Args>(args)...);
596
1.56M
    obj->setDescription(context, description, input.getLastOffset());
597
1.56M
    add(std::move(obj));
598
1.56M
}
void QPDFParser::addScalar<QPDF_Bool, bool>(bool&&)
Line
Count
Source
587
12.2k
{
588
12.2k
    auto limit = Limits::parser_max_container_size(bad_count || sanity_checks);
589
12.2k
    if (frame->olist.size() >= limit || frame->dict.size() >= limit) {
590
        // Stop adding scalars. We are going to abort when the close token or a bad token is
591
        // encountered.
592
3
        max_bad_count = 1;
593
3
        check_too_many_bad_tokens(); // always throws Error()
594
3
    }
595
12.2k
    auto obj = QPDFObject::create<T>(std::forward<Args>(args)...);
596
12.2k
    obj->setDescription(context, description, input.getLastOffset());
597
12.2k
    add(std::move(obj));
598
12.2k
}
Unexecuted instantiation: void QPDFParser::addScalar<QPDF_Integer, long long>(long long&&)
void QPDFParser::addScalar<QPDF_Real, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&>(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)
Line
Count
Source
587
98.3k
{
588
98.3k
    auto limit = Limits::parser_max_container_size(bad_count || sanity_checks);
589
98.3k
    if (frame->olist.size() >= limit || frame->dict.size() >= limit) {
590
        // Stop adding scalars. We are going to abort when the close token or a bad token is
591
        // encountered.
592
35
        max_bad_count = 1;
593
35
        check_too_many_bad_tokens(); // always throws Error()
594
35
    }
595
98.3k
    auto obj = QPDFObject::create<T>(std::forward<Args>(args)...);
596
98.3k
    obj->setDescription(context, description, input.getLastOffset());
597
98.3k
    add(std::move(obj));
598
98.3k
}
void QPDFParser::addScalar<QPDF_Name, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&>(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)
Line
Count
Source
587
1.38M
{
588
1.38M
    auto limit = Limits::parser_max_container_size(bad_count || sanity_checks);
589
1.38M
    if (frame->olist.size() >= limit || frame->dict.size() >= limit) {
590
        // Stop adding scalars. We are going to abort when the close token or a bad token is
591
        // encountered.
592
145
        max_bad_count = 1;
593
145
        check_too_many_bad_tokens(); // always throws Error()
594
145
    }
595
1.38M
    auto obj = QPDFObject::create<T>(std::forward<Args>(args)...);
596
1.38M
    obj->setDescription(context, description, input.getLastOffset());
597
1.38M
    add(std::move(obj));
598
1.38M
}
Unexecuted instantiation: void QPDFParser::addScalar<QPDF_Operator, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&>(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)
void QPDFParser::addScalar<QPDF_String, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&>(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)
Line
Count
Source
587
59.3k
{
588
59.3k
    auto limit = Limits::parser_max_container_size(bad_count || sanity_checks);
589
59.3k
    if (frame->olist.size() >= limit || frame->dict.size() >= limit) {
590
        // Stop adding scalars. We are going to abort when the close token or a bad token is
591
        // encountered.
592
6
        max_bad_count = 1;
593
6
        check_too_many_bad_tokens(); // always throws Error()
594
6
    }
595
59.3k
    auto obj = QPDFObject::create<T>(std::forward<Args>(args)...);
596
59.3k
    obj->setDescription(context, description, input.getLastOffset());
597
59.3k
    add(std::move(obj));
598
59.3k
}
void QPDFParser::addScalar<QPDF_String, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >&>(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >&)
Line
Count
Source
587
10.2k
{
588
10.2k
    auto limit = Limits::parser_max_container_size(bad_count || sanity_checks);
589
10.2k
    if (frame->olist.size() >= limit || frame->dict.size() >= limit) {
590
        // Stop adding scalars. We are going to abort when the close token or a bad token is
591
        // encountered.
592
6
        max_bad_count = 1;
593
6
        check_too_many_bad_tokens(); // always throws Error()
594
6
    }
595
10.2k
    auto obj = QPDFObject::create<T>(std::forward<Args>(args)...);
596
10.2k
    obj->setDescription(context, description, input.getLastOffset());
597
10.2k
    add(std::move(obj));
598
10.2k
}
599
600
template <typename T, typename... Args>
601
QPDFObjectHandle
602
QPDFParser::withDescription(Args&&... args)
603
26.3k
{
604
26.3k
    auto obj = QPDFObject::create<T>(std::forward<Args>(args)...);
605
26.3k
    obj->setDescription(context, description, start);
606
26.3k
    return {obj};
607
26.3k
}
QPDFObjectHandle QPDFParser::withDescription<QPDF_Bool, bool>(bool&&)
Line
Count
Source
603
435
{
604
435
    auto obj = QPDFObject::create<T>(std::forward<Args>(args)...);
605
435
    obj->setDescription(context, description, start);
606
435
    return {obj};
607
435
}
QPDFObjectHandle QPDFParser::withDescription<QPDF_Integer, long long>(long long&&)
Line
Count
Source
603
12.7k
{
604
12.7k
    auto obj = QPDFObject::create<T>(std::forward<Args>(args)...);
605
12.7k
    obj->setDescription(context, description, start);
606
12.7k
    return {obj};
607
12.7k
}
QPDFObjectHandle QPDFParser::withDescription<QPDF_Real, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&>(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)
Line
Count
Source
603
666
{
604
666
    auto obj = QPDFObject::create<T>(std::forward<Args>(args)...);
605
666
    obj->setDescription(context, description, start);
606
666
    return {obj};
607
666
}
QPDFObjectHandle QPDFParser::withDescription<QPDF_Name, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&>(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)
Line
Count
Source
603
1.70k
{
604
1.70k
    auto obj = QPDFObject::create<T>(std::forward<Args>(args)...);
605
1.70k
    obj->setDescription(context, description, start);
606
1.70k
    return {obj};
607
1.70k
}
Unexecuted instantiation: QPDFObjectHandle QPDFParser::withDescription<QPDF_Operator, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&>(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)
QPDFObjectHandle QPDFParser::withDescription<QPDF_String, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&>(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)
Line
Count
Source
603
10.7k
{
604
10.7k
    auto obj = QPDFObject::create<T>(std::forward<Args>(args)...);
605
10.7k
    obj->setDescription(context, description, start);
606
10.7k
    return {obj};
607
10.7k
}
QPDFObjectHandle QPDFParser::withDescription<QPDF_String, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >&>(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >&)
Line
Count
Source
603
39
{
604
39
    auto obj = QPDFObject::create<T>(std::forward<Args>(args)...);
605
39
    obj->setDescription(context, description, start);
606
39
    return {obj};
607
39
}
608
609
void
610
QPDFParser::setDescription(ObjectPtr& obj, qpdf_offset_t parsed_offset)
611
358k
{
612
358k
    if (obj) {
613
358k
        obj->setDescription(context, description, parsed_offset);
614
358k
    }
615
358k
}
616
617
void
618
QPDFParser::fixMissingKeys()
619
1.81k
{
620
1.81k
    std::set<std::string> names;
621
6.19k
    for (auto& obj: frame->olist) {
622
6.19k
        if (obj.raw_type_code() == ::ot_name) {
623
144
            names.insert(obj.obj_sp()->getStringValue());
624
144
        }
625
6.19k
    }
626
1.81k
    int next_fake_key = 1;
627
6.17k
    for (auto const& item: frame->olist) {
628
6.19k
        while (true) {
629
6.19k
            const std::string key = "/QPDFFake" + std::to_string(next_fake_key++);
630
6.19k
            const bool found_fake = !frame->dict.contains(key) && !names.contains(key);
631
6.19k
            QTC::TC("qpdf", "QPDFParser found fake", (found_fake ? 0 : 1));
632
6.19k
            if (found_fake) {
633
6.17k
                warn(
634
6.17k
                    frame->offset,
635
6.17k
                    "expected dictionary key but found non-name object; inserting key " + key);
636
6.17k
                frame->dict[key] = item;
637
6.17k
                break;
638
6.17k
            }
639
6.19k
        }
640
6.17k
    }
641
1.81k
}
642
643
void
644
QPDFParser::check_too_many_bad_tokens()
645
216k
{
646
216k
    auto limit = Limits::parser_max_container_size(bad_count || sanity_checks);
647
216k
    if (frame->olist.size() >= limit || frame->dict.size() >= limit) {
648
200
        if (bad_count) {
649
155
            limits_error(
650
155
                "parser-max-container-size-damaged",
651
155
                "encountered errors while parsing an array or dictionary with more than " +
652
155
                    std::to_string(limit) + " elements; giving up on reading object");
653
155
        }
654
200
        limits_error(
655
200
            "parser-max-container-size",
656
200
            "encountered an array or dictionary with more than " + std::to_string(limit) +
657
200
                " elements during xref recovery; giving up on reading object");
658
200
    }
659
216k
    if (max_bad_count && --max_bad_count == 0) {
660
797
        limits_error(
661
797
            "parser-max-errors", "too many errors during parsing; treating object as null");
662
797
    }
663
216k
    if (good_count > 4) {
664
80.7k
        good_count = 0;
665
80.7k
        bad_count = 1;
666
80.7k
        return;
667
80.7k
    }
668
136k
    if (++bad_count > 5 ||
669
130k
        (frame->state != st_array && std::cmp_less(max_bad_count, frame->olist.size()))) {
670
        // Give up after 5 errors in close proximity or if the number of missing dictionary keys
671
        // exceeds the remaining number of allowable total errors.
672
5.95k
        warn("too many errors; giving up on reading object");
673
5.95k
        throw Error();
674
5.95k
    }
675
130k
    good_count = 0;
676
130k
}
677
678
void
679
QPDFParser::limits_error(std::string const& limit, std::string const& msg)
680
1.08k
{
681
1.08k
    Limits::error();
682
1.08k
    warn("limits error("s + limit + "): " + msg);
683
1.08k
    throw Error();
684
1.08k
}
685
686
void
687
QPDFParser::warn(QPDFExc const& e) const
688
361k
{
689
    // If parsing on behalf of a QPDF object and want to give a warning, we can warn through the
690
    // object. If parsing for some other reason, such as an explicit creation of an object from a
691
    // string, then just throw the exception.
692
361k
    if (context) {
693
361k
        context->warn(e);
694
361k
    } else {
695
0
        throw e;
696
0
    }
697
361k
}
698
699
void
700
QPDFParser::warnDuplicateKey()
701
36.8k
{
702
36.8k
    warn(
703
36.8k
        frame->offset,
704
36.8k
        "dictionary has duplicated key " + frame->key + "; last occurrence overrides earlier ones");
705
36.8k
}
706
707
void
708
QPDFParser::warn(qpdf_offset_t offset, std::string const& msg) const
709
361k
{
710
361k
    if (stream_id) {
711
22.3k
        std::string descr = "object "s + std::to_string(obj_id) + " 0";
712
22.3k
        std::string name = context->getFilename() + " object stream " + std::to_string(stream_id);
713
22.3k
        warn(QPDFExc(qpdf_e_damaged_pdf, name, descr, offset, msg));
714
338k
    } else {
715
338k
        warn(QPDFExc(qpdf_e_damaged_pdf, input.getName(), object_description, offset, msg));
716
338k
    }
717
361k
}
718
719
void
720
QPDFParser::warn(std::string const& msg) const
721
267k
{
722
267k
    warn(input.getLastOffset(), msg);
723
267k
}