Coverage Report

Created: 2026-01-09 06:28

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
111k
        objects(qpdf ? &qpdf->m->objects : nullptr)
27
111k
    {
28
111k
        if (objects) {
29
111k
            objects->inParse(true);
30
111k
        }
31
111k
    }
32
33
    static std::shared_ptr<QPDFObject>
34
    getObject(QPDF* qpdf, int id, int gen, bool parse_pdf)
35
204k
    {
36
204k
        return qpdf->m->objects.getObjectForParser(id, gen, parse_pdf);
37
204k
    }
38
39
    ~ParseGuard()
40
111k
    {
41
111k
        if (objects) {
42
111k
            objects->inParse(false);
43
111k
        }
44
111k
    }
45
    QPDF::Doc::Objects* objects;
46
};
47
48
using ParseGuard = QPDF::Doc::ParseGuard;
49
50
QPDFObjectHandle
51
QPDFParser::parse(InputSource& input, std::string const& object_description, QPDF* context)
52
0
{
53
0
    qpdf::Tokenizer tokenizer;
54
0
    if (auto result = QPDFParser(
55
0
                          input,
56
0
                          make_description(input.getName(), object_description),
57
0
                          object_description,
58
0
                          tokenizer,
59
0
                          nullptr,
60
0
                          context,
61
0
                          false)
62
0
                          .parse()) {
63
0
        return result;
64
0
    }
65
0
    return {QPDFObject::create<QPDF_Null>()};
66
0
}
67
68
QPDFObjectHandle
69
QPDFParser::parse_content(
70
    InputSource& input,
71
    std::shared_ptr<QPDFObject::Description> sp_description,
72
    qpdf::Tokenizer& tokenizer,
73
    QPDF* context)
74
0
{
75
0
    static const std::string content("content"); // GCC12 - make constexpr
76
0
    auto p = QPDFParser(
77
0
        input,
78
0
        std::move(sp_description),
79
0
        content,
80
0
        tokenizer,
81
0
        nullptr,
82
0
        context,
83
0
        true,
84
0
        0,
85
0
        0,
86
0
        context && context->doc().reconstructed_xref());
87
0
    auto result = p.parse(true);
88
0
    if (result || p.empty_) {
89
        // In content stream mode, leave object uninitialized to indicate EOF
90
0
        return result;
91
0
    }
92
0
    return {QPDFObject::create<QPDF_Null>()};
93
0
}
94
95
QPDFObjectHandle
96
QPDFParser::parse(
97
    InputSource& input,
98
    std::string const& object_description,
99
    QPDFTokenizer& tokenizer,
100
    bool& empty,
101
    QPDFObjectHandle::StringDecrypter* decrypter,
102
    QPDF* context)
103
0
{
104
    // ABI: This parse overload is only used by the deprecated QPDFObjectHandle::parse. It is the
105
    // only user of the 'empty' member. When removing this overload also remove 'empty'.
106
0
    auto p = QPDFParser(
107
0
        input,
108
0
        make_description(input.getName(), object_description),
109
0
        object_description,
110
0
        *tokenizer.m,
111
0
        decrypter,
112
0
        context,
113
0
        false);
114
0
    auto result = p.parse();
115
0
    empty = p.empty_;
116
0
    if (result) {
117
0
        return result;
118
0
    }
119
0
    return {QPDFObject::create<QPDF_Null>()};
120
0
}
121
122
QPDFObjectHandle
123
QPDFParser::parse(
124
    InputSource& input,
125
    std::string const& object_description,
126
    qpdf::Tokenizer& tokenizer,
127
    QPDFObjectHandle::StringDecrypter* decrypter,
128
    QPDF& context,
129
    bool sanity_checks)
130
91.0k
{
131
91.0k
    return QPDFParser(
132
91.0k
               input,
133
91.0k
               make_description(input.getName(), object_description),
134
91.0k
               object_description,
135
91.0k
               tokenizer,
136
91.0k
               decrypter,
137
91.0k
               &context,
138
91.0k
               true,
139
91.0k
               0,
140
91.0k
               0,
141
91.0k
               sanity_checks)
142
91.0k
        .parse();
143
91.0k
}
144
145
QPDFObjectHandle
146
QPDFParser::parse(
147
    is::OffsetBuffer& input, int stream_id, int obj_id, qpdf::Tokenizer& tokenizer, QPDF& context)
148
20.4k
{
149
20.4k
    return QPDFParser(
150
20.4k
               input,
151
20.4k
               std::make_shared<QPDFObject::Description>(
152
20.4k
                   QPDFObject::ObjStreamDescr(stream_id, obj_id)),
153
20.4k
               "",
154
20.4k
               tokenizer,
155
20.4k
               nullptr,
156
20.4k
               &context,
157
20.4k
               true,
158
20.4k
               stream_id,
159
20.4k
               obj_id)
160
20.4k
        .parse();
161
20.4k
}
162
163
QPDFObjectHandle
164
QPDFParser::parse(bool content_stream)
165
111k
{
166
111k
    try {
167
111k
        return parse_first(content_stream);
168
111k
    } catch (Error&) {
169
6.23k
        return {};
170
6.23k
    } catch (QPDFExc& e) {
171
3.51k
        throw e;
172
3.51k
    } catch (std::logic_error& e) {
173
1
        throw e;
174
1.04k
    } catch (std::exception& e) {
175
1.04k
        warn("treating object as null because of error during parsing: "s + e.what());
176
1.04k
        return {};
177
1.04k
    }
178
111k
}
179
180
QPDFObjectHandle
181
QPDFParser::parse_first(bool content_stream)
182
111k
{
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
111k
    QPDF::Doc::ParseGuard pg(context);
189
111k
    start = input.tell();
190
111k
    if (!tokenizer.nextToken(input, object_description)) {
191
1.60k
        warn(tokenizer.getErrorMessage());
192
1.60k
    }
193
194
111k
    switch (tokenizer.getType()) {
195
667
    case QPDFTokenizer::tt_eof:
196
667
        if (content_stream) {
197
            // In content stream mode, leave object uninitialized to indicate EOF
198
0
            empty_ = true;
199
0
            return {};
200
0
        }
201
667
        warn("unexpected EOF");
202
667
        return {};
203
204
1.66k
    case QPDFTokenizer::tt_bad:
205
1.66k
        return {};
206
207
135
    case QPDFTokenizer::tt_brace_open:
208
204
    case QPDFTokenizer::tt_brace_close:
209
204
        warn("treating unexpected brace token as null");
210
204
        return {};
211
212
367
    case QPDFTokenizer::tt_array_close:
213
367
        warn("treating unexpected array close token as null");
214
367
        return {};
215
216
326
    case QPDFTokenizer::tt_dict_close:
217
326
        warn("unexpected dictionary close token");
218
326
        return {};
219
220
9.36k
    case QPDFTokenizer::tt_array_open:
221
87.8k
    case QPDFTokenizer::tt_dict_open:
222
87.8k
        stack.clear();
223
87.8k
        stack.emplace_back(
224
87.8k
            input,
225
87.8k
            (tokenizer.getType() == QPDFTokenizer::tt_array_open) ? st_array : st_dictionary_key);
226
87.8k
        frame = &stack.back();
227
87.8k
        return parseRemainder(content_stream);
228
229
390
    case QPDFTokenizer::tt_bool:
230
390
        return withDescription<QPDF_Bool>(tokenizer.getValue() == "true");
231
232
176
    case QPDFTokenizer::tt_null:
233
176
        return {QPDFObject::create<QPDF_Null>()};
234
235
7.08k
    case QPDFTokenizer::tt_integer:
236
7.08k
        return withDescription<QPDF_Integer>(QUtil::string_to_ll(tokenizer.getValue().c_str()));
237
238
1.40k
    case QPDFTokenizer::tt_real:
239
1.40k
        return withDescription<QPDF_Real>(tokenizer.getValue());
240
241
1.92k
    case QPDFTokenizer::tt_name:
242
1.92k
        return withDescription<QPDF_Name>(tokenizer.getValue());
243
244
8.78k
    case QPDFTokenizer::tt_word:
245
8.78k
        {
246
8.78k
            auto const& value = tokenizer.getValue();
247
8.78k
            if (content_stream) {
248
0
                return withDescription<QPDF_Operator>(value);
249
8.78k
            } 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
225
                empty_ = true;
255
225
                input.seek(input.getLastOffset(), SEEK_SET);
256
225
                if (!content_stream) {
257
225
                    warn("empty object treated as null");
258
225
                }
259
225
                return {};
260
8.56k
            } else {
261
8.56k
                warn("unknown token while reading object; treating as string");
262
8.56k
                return withDescription<QPDF_String>(value);
263
8.56k
            }
264
8.78k
        }
265
266
589
    case QPDFTokenizer::tt_string:
267
589
        if (decrypter) {
268
129
            std::string s{tokenizer.getValue()};
269
129
            decrypter->decryptString(s);
270
129
            return withDescription<QPDF_String>(s);
271
460
        } else {
272
460
            return withDescription<QPDF_String>(tokenizer.getValue());
273
460
        }
274
275
0
    default:
276
0
        warn("treating unknown token type as null while reading object");
277
0
        return {};
278
111k
    }
279
111k
}
280
281
QPDFObjectHandle
282
QPDFParser::parseRemainder(bool content_stream)
283
87.8k
{
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
87.8k
    bad_count = 0;
290
87.8k
    bool b_contents = false;
291
292
9.83M
    while (true) {
293
9.82M
        if (!tokenizer.nextToken(input, object_description)) {
294
31.7k
            warn(tokenizer.getErrorMessage());
295
31.7k
        }
296
9.82M
        ++good_count; // optimistically
297
298
9.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
5.91M
            if (tokenizer.getType() == QPDFTokenizer::tt_integer) {
302
5.58M
                if (++int_count > 2) {
303
                    // Process the oldest buffered integer.
304
5.33M
                    addInt(int_count);
305
5.33M
                }
306
5.58M
                last_offset_buffer[int_count % 2] = input.getLastOffset();
307
5.58M
                int_buffer[int_count % 2] = QUtil::string_to_ll(tokenizer.getValue().c_str());
308
5.58M
                continue;
309
310
5.58M
            } else if (
311
333k
                int_count >= 2 && tokenizer.getType() == QPDFTokenizer::tt_word &&
312
219k
                tokenizer.getValue() == "R") {
313
206k
                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
206k
                auto id = QIntC::to_int(int_buffer[(int_count - 1) % 2]);
319
206k
                auto gen = QIntC::to_int(int_buffer[(int_count) % 2]);
320
206k
                if (!(id < 1 || gen < 0 || gen >= 65535)) {
321
204k
                    add(ParseGuard::getObject(context, id, gen, parse_pdf));
322
204k
                } else {
323
2.24k
                    add_bad_null(
324
2.24k
                        "treating bad indirect reference (" + std::to_string(id) + " " +
325
2.24k
                        std::to_string(gen) + " R) as null");
326
2.24k
                }
327
206k
                int_count = 0;
328
206k
                continue;
329
330
206k
            } else if (int_count > 0) {
331
                // Process the buffered integers before processing the current token.
332
127k
                if (int_count > 1) {
333
39.4k
                    addInt(int_count - 1);
334
39.4k
                }
335
127k
                addInt(int_count);
336
127k
                int_count = 0;
337
127k
            }
338
5.91M
        }
339
340
4.03M
        switch (tokenizer.getType()) {
341
7.81k
        case QPDFTokenizer::tt_eof:
342
7.81k
            warn("parse error while reading object");
343
7.81k
            if (content_stream) {
344
                // In content stream mode, leave object uninitialized to indicate EOF
345
0
                return {};
346
0
            }
347
7.81k
            warn("unexpected EOF");
348
7.81k
            return {};
349
350
24.8k
        case QPDFTokenizer::tt_bad:
351
24.8k
            check_too_many_bad_tokens();
352
24.8k
            addNull();
353
24.8k
            continue;
354
355
1.70k
        case QPDFTokenizer::tt_brace_open:
356
3.49k
        case QPDFTokenizer::tt_brace_close:
357
3.49k
            add_bad_null("treating unexpected brace token as null");
358
3.49k
            continue;
359
360
46.9k
        case QPDFTokenizer::tt_array_close:
361
46.9k
            if (frame->state == st_array) {
362
45.4k
                auto object = frame->null_count > 100
363
45.4k
                    ? QPDFObject::create<QPDF_Array>(std::move(frame->olist), true)
364
45.4k
                    : QPDFObject::create<QPDF_Array>(std::move(frame->olist));
365
45.4k
                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
45.4k
                if (stack.size() <= 1) {
371
1.15k
                    return object;
372
1.15k
                }
373
44.3k
                stack.pop_back();
374
44.3k
                frame = &stack.back();
375
44.3k
                add(std::move(object));
376
44.3k
            } else {
377
1.48k
                if (sanity_checks) {
378
                    // During sanity checks, assume nesting of containers is corrupt and object is
379
                    // unusable.
380
906
                    warn("unexpected array close token; giving up on reading object");
381
906
                    return {};
382
906
                }
383
583
                add_bad_null("treating unexpected array close token as null");
384
583
            }
385
44.9k
            continue;
386
387
97.0k
        case QPDFTokenizer::tt_dict_close:
388
97.0k
            if (frame->state <= st_dictionary_value) {
389
                // Attempt to recover more or less gracefully from invalid dictionaries.
390
96.1k
                auto& dict = frame->dict;
391
392
96.1k
                if (frame->state == st_dictionary_value) {
393
6.78k
                    warn(
394
6.78k
                        frame->offset,
395
6.78k
                        "dictionary ended prematurely; using null as value for last key");
396
6.78k
                    dict[frame->key] = QPDFObject::create<QPDF_Null>();
397
6.78k
                }
398
96.1k
                if (!frame->olist.empty()) {
399
32.8k
                    if (sanity_checks) {
400
30.3k
                        warn(
401
30.3k
                            frame->offset,
402
30.3k
                            "expected dictionary keys but found non-name objects; ignoring");
403
30.3k
                    } else {
404
2.51k
                        fixMissingKeys();
405
2.51k
                    }
406
32.8k
                }
407
408
96.1k
                if (!frame->contents_string.empty() && dict.contains("/Type") &&
409
202
                    dict["/Type"].isNameAndEquals("/Sig") && dict.contains("/ByteRange") &&
410
36
                    dict.contains("/Contents") && dict["/Contents"].isString()) {
411
35
                    dict["/Contents"] = QPDFObjectHandle::newString(frame->contents_string);
412
35
                    dict["/Contents"].setParsedOffset(frame->contents_offset);
413
35
                }
414
96.1k
                auto object = QPDFObject::create<QPDF_Dictionary>(std::move(dict));
415
96.1k
                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
96.1k
                if (stack.size() <= 1) {
421
67.1k
                    return object;
422
67.1k
                }
423
29.0k
                stack.pop_back();
424
29.0k
                frame = &stack.back();
425
29.0k
                add(std::move(object));
426
29.0k
            } else {
427
844
                if (sanity_checks) {
428
                    // During sanity checks, assume nesting of containers is corrupt and object is
429
                    // unusable.
430
552
                    warn("unexpected dictionary close token; giving up on reading object");
431
552
                    return {};
432
552
                }
433
292
                add_bad_null("unexpected dictionary close token");
434
292
            }
435
29.3k
            continue;
436
437
124k
        case QPDFTokenizer::tt_array_open:
438
185k
        case QPDFTokenizer::tt_dict_open:
439
185k
            if (stack.size() > max_nesting) {
440
114
                limits_error(
441
114
                    "parser-max-nesting", "ignoring excessively deeply nested data structure");
442
114
            }
443
185k
            b_contents = false;
444
185k
            stack.emplace_back(
445
185k
                input,
446
185k
                (tokenizer.getType() == QPDFTokenizer::tt_array_open) ? st_array
447
185k
                                                                      : st_dictionary_key);
448
185k
            frame = &stack.back();
449
185k
            continue;
450
451
6.24k
        case QPDFTokenizer::tt_bool:
452
6.24k
            addScalar<QPDF_Bool>(tokenizer.getValue() == "true");
453
6.24k
            continue;
454
455
53.3k
        case QPDFTokenizer::tt_null:
456
53.3k
            addNull();
457
53.3k
            continue;
458
459
334k
        case QPDFTokenizer::tt_integer:
460
334k
            if (!content_stream) {
461
                // Buffer token in case it is part of an indirect reference.
462
334k
                last_offset_buffer[1] = input.getLastOffset();
463
334k
                int_buffer[1] = QUtil::string_to_ll(tokenizer.getValue().c_str());
464
334k
                int_count = 1;
465
334k
            } else {
466
0
                addScalar<QPDF_Integer>(QUtil::string_to_ll(tokenizer.getValue().c_str()));
467
0
            }
468
334k
            continue;
469
470
14.6k
        case QPDFTokenizer::tt_real:
471
14.6k
            addScalar<QPDF_Real>(tokenizer.getValue());
472
14.6k
            continue;
473
474
3.01M
        case QPDFTokenizer::tt_name:
475
3.01M
            if (frame->state == st_dictionary_key) {
476
384k
                frame->key = tokenizer.getValue();
477
384k
                frame->state = st_dictionary_value;
478
384k
                b_contents = decrypter && frame->key == "/Contents";
479
384k
                continue;
480
2.63M
            } else {
481
2.63M
                addScalar<QPDF_Name>(tokenizer.getValue());
482
2.63M
            }
483
2.63M
            continue;
484
485
2.63M
        case QPDFTokenizer::tt_word:
486
145k
            if (content_stream) {
487
0
                addScalar<QPDF_Operator>(tokenizer.getValue());
488
0
                continue;
489
0
            }
490
491
145k
            if (sanity_checks) {
492
139k
                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
1.01k
                    warn(
496
1.01k
                        "unexpected 'endobj' or 'endstream' while reading object; giving up on "
497
1.01k
                        "reading object");
498
1.01k
                    return {};
499
1.01k
                }
500
501
138k
                add_bad_null("unknown token while reading object; treating as null");
502
138k
                continue;
503
139k
            }
504
505
5.20k
            warn("unknown token while reading object; treating as string");
506
5.20k
            check_too_many_bad_tokens();
507
5.20k
            addScalar<QPDF_String>(tokenizer.getValue());
508
509
5.20k
            continue;
510
511
96.7k
        case QPDFTokenizer::tt_string:
512
96.7k
            {
513
96.7k
                auto const& val = tokenizer.getValue();
514
96.7k
                if (decrypter) {
515
29.3k
                    if (b_contents) {
516
1.01k
                        frame->contents_string = val;
517
1.01k
                        frame->contents_offset = input.getLastOffset();
518
1.01k
                        b_contents = false;
519
1.01k
                    }
520
29.3k
                    std::string s{val};
521
29.3k
                    decrypter->decryptString(s);
522
29.3k
                    addScalar<QPDF_String>(s);
523
67.4k
                } else {
524
67.4k
                    addScalar<QPDF_String>(val);
525
67.4k
                }
526
96.7k
            }
527
96.7k
            continue;
528
529
0
        default:
530
0
            add_bad_null("treating unknown token type as null while reading object");
531
4.03M
        }
532
4.03M
    }
533
87.8k
}
534
535
void
536
QPDFParser::add(std::shared_ptr<QPDFObject>&& obj)
537
8.53M
{
538
8.53M
    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
8.19M
        frame->olist.emplace_back(std::move(obj));
542
8.19M
    } else {
543
345k
        if (auto res = frame->dict.insert_or_assign(frame->key, std::move(obj)); !res.second) {
544
44.4k
            warnDuplicateKey();
545
44.4k
        }
546
345k
        frame->state = st_dictionary_key;
547
345k
    }
548
8.53M
}
549
550
void
551
QPDFParser::addNull()
552
216k
{
553
216k
    const static ObjectPtr null_obj = QPDFObject::create<QPDF_Null>();
554
555
216k
    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
189k
        frame->olist.emplace_back(null_obj);
559
189k
    } else {
560
26.6k
        if (auto res = frame->dict.insert_or_assign(frame->key, null_obj); !res.second) {
561
6.27k
            warnDuplicateKey();
562
6.27k
        }
563
26.6k
        frame->state = st_dictionary_key;
564
26.6k
    }
565
216k
    ++frame->null_count;
566
216k
}
567
568
void
569
QPDFParser::add_bad_null(std::string const& msg)
570
144k
{
571
144k
    warn(msg);
572
144k
    check_too_many_bad_tokens();
573
144k
    addNull();
574
144k
}
575
576
void
577
QPDFParser::addInt(int count)
578
5.50M
{
579
5.50M
    auto obj = QPDFObject::create<QPDF_Integer>(int_buffer[count % 2]);
580
5.50M
    obj->setDescription(context, description, last_offset_buffer[count % 2]);
581
5.50M
    add(std::move(obj));
582
5.50M
}
583
584
template <typename T, typename... Args>
585
void
586
QPDFParser::addScalar(Args&&... args)
587
2.75M
{
588
2.75M
    auto limit = Limits::parser_max_container_size(bad_count || sanity_checks);
589
2.75M
    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
468
        max_bad_count = 1;
593
468
        check_too_many_bad_tokens(); // always throws Error()
594
468
    }
595
2.75M
    auto obj = QPDFObject::create<T>(std::forward<Args>(args)...);
596
2.75M
    obj->setDescription(context, description, input.getLastOffset());
597
2.75M
    add(std::move(obj));
598
2.75M
}
void QPDFParser::addScalar<QPDF_Bool, bool>(bool&&)
Line
Count
Source
587
6.24k
{
588
6.24k
    auto limit = Limits::parser_max_container_size(bad_count || sanity_checks);
589
6.24k
    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
71
        max_bad_count = 1;
593
71
        check_too_many_bad_tokens(); // always throws Error()
594
71
    }
595
6.24k
    auto obj = QPDFObject::create<T>(std::forward<Args>(args)...);
596
6.24k
    obj->setDescription(context, description, input.getLastOffset());
597
6.24k
    add(std::move(obj));
598
6.24k
}
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
14.6k
{
588
14.6k
    auto limit = Limits::parser_max_container_size(bad_count || sanity_checks);
589
14.6k
    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
78
        max_bad_count = 1;
593
78
        check_too_many_bad_tokens(); // always throws Error()
594
78
    }
595
14.6k
    auto obj = QPDFObject::create<T>(std::forward<Args>(args)...);
596
14.6k
    obj->setDescription(context, description, input.getLastOffset());
597
14.6k
    add(std::move(obj));
598
14.6k
}
void QPDFParser::addScalar<QPDF_Name, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&>(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)
Line
Count
Source
587
2.63M
{
588
2.63M
    auto limit = Limits::parser_max_container_size(bad_count || sanity_checks);
589
2.63M
    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
236
        max_bad_count = 1;
593
236
        check_too_many_bad_tokens(); // always throws Error()
594
236
    }
595
2.63M
    auto obj = QPDFObject::create<T>(std::forward<Args>(args)...);
596
2.63M
    obj->setDescription(context, description, input.getLastOffset());
597
2.63M
    add(std::move(obj));
598
2.63M
}
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
72.4k
{
588
72.4k
    auto limit = Limits::parser_max_container_size(bad_count || sanity_checks);
589
72.4k
    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
82
        max_bad_count = 1;
593
82
        check_too_many_bad_tokens(); // always throws Error()
594
82
    }
595
72.4k
    auto obj = QPDFObject::create<T>(std::forward<Args>(args)...);
596
72.4k
    obj->setDescription(context, description, input.getLastOffset());
597
72.4k
    add(std::move(obj));
598
72.4k
}
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
29.3k
{
588
29.3k
    auto limit = Limits::parser_max_container_size(bad_count || sanity_checks);
589
29.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
1
        max_bad_count = 1;
593
1
        check_too_many_bad_tokens(); // always throws Error()
594
1
    }
595
29.3k
    auto obj = QPDFObject::create<T>(std::forward<Args>(args)...);
596
29.3k
    obj->setDescription(context, description, input.getLastOffset());
597
29.3k
    add(std::move(obj));
598
29.3k
}
599
600
template <typename T, typename... Args>
601
QPDFObjectHandle
602
QPDFParser::withDescription(Args&&... args)
603
19.2k
{
604
19.2k
    auto obj = QPDFObject::create<T>(std::forward<Args>(args)...);
605
19.2k
    obj->setDescription(context, description, start);
606
19.2k
    return {obj};
607
19.2k
}
QPDFObjectHandle QPDFParser::withDescription<QPDF_Bool, bool>(bool&&)
Line
Count
Source
603
390
{
604
390
    auto obj = QPDFObject::create<T>(std::forward<Args>(args)...);
605
390
    obj->setDescription(context, description, start);
606
390
    return {obj};
607
390
}
QPDFObjectHandle QPDFParser::withDescription<QPDF_Integer, long long>(long long&&)
Line
Count
Source
603
6.85k
{
604
6.85k
    auto obj = QPDFObject::create<T>(std::forward<Args>(args)...);
605
6.85k
    obj->setDescription(context, description, start);
606
6.85k
    return {obj};
607
6.85k
}
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
1.40k
{
604
1.40k
    auto obj = QPDFObject::create<T>(std::forward<Args>(args)...);
605
1.40k
    obj->setDescription(context, description, start);
606
1.40k
    return {obj};
607
1.40k
}
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.92k
{
604
1.92k
    auto obj = QPDFObject::create<T>(std::forward<Args>(args)...);
605
1.92k
    obj->setDescription(context, description, start);
606
1.92k
    return {obj};
607
1.92k
}
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
8.52k
{
604
8.52k
    auto obj = QPDFObject::create<T>(std::forward<Args>(args)...);
605
8.52k
    obj->setDescription(context, description, start);
606
8.52k
    return {obj};
607
8.52k
}
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
127
{
604
127
    auto obj = QPDFObject::create<T>(std::forward<Args>(args)...);
605
127
    obj->setDescription(context, description, start);
606
127
    return {obj};
607
127
}
608
609
void
610
QPDFParser::setDescription(ObjectPtr& obj, qpdf_offset_t parsed_offset)
611
141k
{
612
141k
    if (obj) {
613
141k
        obj->setDescription(context, description, parsed_offset);
614
141k
    }
615
141k
}
616
617
void
618
QPDFParser::fixMissingKeys()
619
2.51k
{
620
2.51k
    std::set<std::string> names;
621
9.04k
    for (auto& obj: frame->olist) {
622
9.04k
        if (obj.raw_type_code() == ::ot_name) {
623
609
            names.insert(obj.obj_sp()->getStringValue());
624
609
        }
625
9.04k
    }
626
2.51k
    int next_fake_key = 1;
627
8.52k
    for (auto const& item: frame->olist) {
628
8.61k
        while (true) {
629
8.61k
            const std::string key = "/QPDFFake" + std::to_string(next_fake_key++);
630
8.61k
            const bool found_fake = !frame->dict.contains(key) && !names.contains(key);
631
8.61k
            QTC::TC("qpdf", "QPDFParser found fake", (found_fake ? 0 : 1));
632
8.61k
            if (found_fake) {
633
8.52k
                warn(
634
8.52k
                    frame->offset,
635
8.52k
                    "expected dictionary key but found non-name object; inserting key " + key);
636
8.52k
                frame->dict[key] = item;
637
8.52k
                break;
638
8.52k
            }
639
8.61k
        }
640
8.52k
    }
641
2.51k
}
642
643
void
644
QPDFParser::check_too_many_bad_tokens()
645
174k
{
646
174k
    auto limit = Limits::parser_max_container_size(bad_count || sanity_checks);
647
174k
    if (frame->olist.size() >= limit || frame->dict.size() >= limit) {
648
482
        if (bad_count) {
649
415
            limits_error(
650
415
                "parser-max-container-size-damaged",
651
415
                "encountered errors while parsing an array or dictionary with more than " +
652
415
                    std::to_string(limit) + " elements; giving up on reading object");
653
415
        }
654
482
        limits_error(
655
482
            "parser-max-container-size",
656
482
            "encountered an array or dictionary with more than " + std::to_string(limit) +
657
482
                " elements during xref recovery; giving up on reading object");
658
482
    }
659
174k
    if (max_bad_count && --max_bad_count == 0) {
660
1.01k
        limits_error(
661
1.01k
            "parser-max-errors", "too many errors during parsing; treating object as null");
662
1.01k
    }
663
174k
    if (good_count > 4) {
664
58.4k
        good_count = 0;
665
58.4k
        bad_count = 1;
666
58.4k
        return;
667
58.4k
    }
668
115k
    if (++bad_count > 5 ||
669
111k
        (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
4.70k
        warn("too many errors; giving up on reading object");
673
4.70k
        throw Error();
674
4.70k
    }
675
111k
    good_count = 0;
676
111k
}
677
678
void
679
QPDFParser::limits_error(std::string const& limit, std::string const& msg)
680
1.61k
{
681
1.61k
    Limits::error();
682
1.61k
    warn("limits error("s + limit + "): " + msg);
683
1.61k
    throw Error();
684
1.61k
}
685
686
void
687
QPDFParser::warn(QPDFExc const& e) const
688
315k
{
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
315k
    if (context) {
693
315k
        context->warn(e);
694
315k
    } else {
695
0
        throw e;
696
0
    }
697
315k
}
698
699
void
700
QPDFParser::warnDuplicateKey()
701
50.6k
{
702
50.6k
    warn(
703
50.6k
        frame->offset,
704
50.6k
        "dictionary has duplicated key " + frame->key + "; last occurrence overrides earlier ones");
705
50.6k
}
706
707
void
708
QPDFParser::warn(qpdf_offset_t offset, std::string const& msg) const
709
315k
{
710
315k
    if (stream_id) {
711
14.3k
        std::string descr = "object "s + std::to_string(obj_id) + " 0";
712
14.3k
        std::string name = context->getFilename() + " object stream " + std::to_string(stream_id);
713
14.3k
        warn(QPDFExc(qpdf_e_damaged_pdf, name, descr, offset, msg));
714
301k
    } else {
715
301k
        warn(QPDFExc(qpdf_e_damaged_pdf, input.getName(), object_description, offset, msg));
716
301k
    }
717
315k
}
718
719
void
720
QPDFParser::warn(std::string const& msg) const
721
219k
{
722
219k
    warn(input.getLastOffset(), msg);
723
219k
}