Coverage Report

Created: 2026-07-16 06:54

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
19.0k
        objects(qpdf ? &qpdf->m->objects : nullptr)
27
19.0k
    {
28
19.0k
        if (objects) {
29
7.84k
            objects->inParse(true);
30
7.84k
        }
31
19.0k
    }
32
33
    static std::shared_ptr<QPDFObject>
34
    getObject(QPDF* qpdf, int id, int gen, bool parse_pdf)
35
0
    {
36
0
        return qpdf->m->objects.getObjectForParser(id, gen, parse_pdf);
37
0
    }
38
39
    ~ParseGuard()
40
19.0k
    {
41
19.0k
        if (objects) {
42
7.84k
            objects->inParse(false);
43
7.84k
        }
44
19.0k
    }
45
    QPDF::Doc::Objects* objects;
46
};
47
48
using ParseGuard = QPDF::Doc::ParseGuard;
49
using Parser = qpdf::impl::Parser;
50
51
QPDFObjectHandle
52
Parser::parse(InputSource& input, std::string const& object_description, QPDF* context)
53
11.1k
{
54
11.1k
    qpdf::Tokenizer tokenizer;
55
11.1k
    if (auto result = Parser(
56
11.1k
                          input,
57
11.1k
                          make_description(input.getName(), object_description),
58
11.1k
                          object_description,
59
11.1k
                          tokenizer,
60
11.1k
                          nullptr,
61
11.1k
                          context,
62
11.1k
                          false)
63
11.1k
                          .parse()) {
64
10.8k
        return result;
65
10.8k
    }
66
344
    return {QPDFObject::create<QPDF_Null>()};
67
11.1k
}
68
69
std::pair<QPDFObjectHandle, bool>
70
Parser::parse_content(
71
    InputSource& input,
72
    std::shared_ptr<QPDFObject::Description> sp_description,
73
    qpdf::Tokenizer& tokenizer,
74
    QPDF* context)
75
0
{
76
0
    static const std::string content("content"); // GCC12 - make constexpr
77
0
    auto p = Parser(
78
0
        input,
79
0
        std::move(sp_description),
80
0
        content,
81
0
        tokenizer,
82
0
        nullptr,
83
0
        context,
84
0
        true,
85
0
        0,
86
0
        0,
87
0
        context && context->doc().reconstructed_xref());
88
0
    if (auto result = p.parse(true)) {
89
0
        return {result, false};
90
0
    }
91
0
    return {{}, p.empty_};
92
0
}
93
94
QPDFObjectHandle
95
Parser::parse(
96
    InputSource& input,
97
    std::string const& object_description,
98
    QPDFTokenizer& tokenizer,
99
    bool& empty,
100
    QPDFObjectHandle::StringDecrypter* decrypter,
101
    QPDF* context)
102
0
{
103
    // ABI: This parse overload is only used by the deprecated QPDFObjectHandle::parse. It is the
104
    // only user of the 'empty' member. When removing this overload also remove 'empty'.
105
0
    auto p = Parser(
106
0
        input,
107
0
        make_description(input.getName(), object_description),
108
0
        object_description,
109
0
        *tokenizer.m,
110
0
        decrypter,
111
0
        context,
112
0
        false);
113
0
    auto result = p.parse();
114
0
    empty = p.empty_;
115
0
    if (result) {
116
0
        return result;
117
0
    }
118
0
    return {QPDFObject::create<QPDF_Null>()};
119
0
}
120
121
QPDFObjectHandle
122
Parser::parse(
123
    InputSource& input,
124
    std::string const& object_description,
125
    qpdf::Tokenizer& tokenizer,
126
    QPDFObjectHandle::StringDecrypter* decrypter,
127
    QPDF& context,
128
    bool sanity_checks)
129
7.84k
{
130
7.84k
    return Parser(
131
7.84k
               input,
132
7.84k
               make_description(input.getName(), object_description),
133
7.84k
               object_description,
134
7.84k
               tokenizer,
135
7.84k
               decrypter,
136
7.84k
               &context,
137
7.84k
               true,
138
7.84k
               0,
139
7.84k
               0,
140
7.84k
               sanity_checks)
141
7.84k
        .parse();
142
7.84k
}
143
144
QPDFObjectHandle
145
Parser::parse(
146
    is::OffsetBuffer& input, int stream_id, int obj_id, qpdf::Tokenizer& tokenizer, QPDF& context)
147
0
{
148
0
    return Parser(
149
0
               input,
150
0
               std::make_shared<QPDFObject::Description>(
151
0
                   QPDFObject::ObjStreamDescr(stream_id, obj_id)),
152
0
               "",
153
0
               tokenizer,
154
0
               nullptr,
155
0
               &context,
156
0
               true,
157
0
               stream_id,
158
0
               obj_id)
159
0
        .parse();
160
0
}
161
162
QPDFObjectHandle
163
Parser::parse(bool content_stream)
164
19.0k
{
165
19.0k
    try {
166
19.0k
        return parse_first(content_stream);
167
19.0k
    } catch (Error&) {
168
0
        return {};
169
344
    } catch (QPDFExc& e) {
170
344
        throw e;
171
344
    } catch (std::logic_error& e) {
172
0
        throw e;
173
0
    } catch (std::exception& e) {
174
0
        warn("treating object as null because of error during parsing: "s + e.what());
175
0
        return {};
176
0
    }
177
19.0k
}
178
179
QPDFObjectHandle
180
Parser::parse_first(bool content_stream)
181
19.0k
{
182
    // This method must take care not to resolve any objects. Don't check the type of any object
183
    // without first ensuring that it is a direct object. Otherwise, doing so may have the side
184
    // effect of reading the object and changing the file pointer. If you do this, it will cause a
185
    // logic error to be thrown from QPDF::inParse().
186
187
19.0k
    QPDF::Doc::ParseGuard pg(context_);
188
19.0k
    start_ = input_.tell();
189
19.0k
    if (!tokenizer_.nextToken(input_, object_description_)) {
190
344
        warn(tokenizer_.getErrorMessage());
191
344
    }
192
193
19.0k
    switch (tokenizer_.getType()) {
194
0
    case QPDFTokenizer::tt_eof:
195
0
        if (content_stream) {
196
            // In content stream mode, leave object uninitialized to indicate EOF
197
0
            empty_ = true;
198
0
            return {};
199
0
        }
200
0
        warn("unexpected EOF");
201
0
        return {};
202
203
0
    case QPDFTokenizer::tt_bad:
204
0
        return {};
205
206
0
    case QPDFTokenizer::tt_brace_open:
207
0
    case QPDFTokenizer::tt_brace_close:
208
0
        warn("treating unexpected brace token as null");
209
0
        return {};
210
211
0
    case QPDFTokenizer::tt_array_close:
212
0
        warn("treating unexpected array close token as null");
213
0
        return {};
214
215
0
    case QPDFTokenizer::tt_dict_close:
216
0
        warn("unexpected dictionary close token");
217
0
        return {};
218
219
0
    case QPDFTokenizer::tt_array_open:
220
7.84k
    case QPDFTokenizer::tt_dict_open:
221
7.84k
        stack_.clear();
222
7.84k
        stack_.emplace_back(
223
7.84k
            input_,
224
7.84k
            (tokenizer_.getType() == QPDFTokenizer::tt_array_open) ? st_array : st_dictionary_key);
225
7.84k
        frame_ = &stack_.back();
226
7.84k
        return parse_remainder(content_stream);
227
228
0
    case QPDFTokenizer::tt_bool:
229
0
        return with_description<QPDF_Bool>(tokenizer_.getValue() == "true");
230
231
0
    case QPDFTokenizer::tt_null:
232
0
        return {QPDFObject::create<QPDF_Null>()};
233
234
0
    case QPDFTokenizer::tt_integer:
235
0
        return with_description<QPDF_Integer>(QUtil::string_to_ll(tokenizer_.getValue().c_str()));
236
237
0
    case QPDFTokenizer::tt_real:
238
0
        return with_description<QPDF_Real>(tokenizer_.getValue());
239
240
10.8k
    case QPDFTokenizer::tt_name:
241
10.8k
        return with_description<QPDF_Name>(tokenizer_.getValue());
242
243
0
    case QPDFTokenizer::tt_word:
244
0
        {
245
0
            auto const& value = tokenizer_.getValue();
246
0
            if (content_stream) {
247
0
                return with_description<QPDF_Operator>(value);
248
0
            } else if (value == "endobj") {
249
                // We just saw endobj without having read anything. Nothing in the PDF spec appears
250
                // to allow empty objects, but they have been encountered in actual PDF files and
251
                // Adobe Reader appears to ignore them. Treat this as a null and do not move the
252
                // input source's offset.
253
0
                empty_ = true;
254
0
                input_.seek(input_.getLastOffset(), SEEK_SET);
255
0
                if (!content_stream) {
256
0
                    warn("empty object treated as null");
257
0
                }
258
0
                return {};
259
0
            } else {
260
0
                warn("unknown token while reading object; treating as string");
261
0
                return with_description<QPDF_String>(value);
262
0
            }
263
0
        }
264
265
0
    case QPDFTokenizer::tt_string:
266
0
        if (decrypter_) {
267
0
            std::string s{tokenizer_.getValue()};
268
0
            decrypter_->decryptString(s);
269
0
            return with_description<QPDF_String>(s);
270
0
        } else {
271
0
            return with_description<QPDF_String>(tokenizer_.getValue());
272
0
        }
273
274
0
    default:
275
0
        warn("treating unknown token type as null while reading object");
276
0
        return {};
277
19.0k
    }
278
19.0k
}
279
280
QPDFObjectHandle
281
Parser::parse_remainder(bool content_stream)
282
7.84k
{
283
    // This method must take care not to resolve any objects. Don't check the type of any object
284
    // without first ensuring that it is a direct object. Otherwise, doing so may have the side
285
    // effect of reading the object and changing the file pointer. If you do this, it will cause a
286
    // logic error to be thrown from QPDF::inParse().
287
288
7.84k
    bad_count_ = 0;
289
7.84k
    bool b_contents = false;
290
291
23.5k
    while (true) {
292
23.5k
        if (!tokenizer_.nextToken(input_, object_description_)) {
293
0
            warn(tokenizer_.getErrorMessage());
294
0
        }
295
23.5k
        ++good_count_; // optimistically
296
297
23.5k
        if (int_count_ != 0) {
298
            // Special handling of indirect references. Treat integer tokens as part of an indirect
299
            // reference until proven otherwise.
300
7.84k
            if (tokenizer_.getType() == QPDFTokenizer::tt_integer) {
301
0
                if (++int_count_ > 2) {
302
                    // Process the oldest buffered integer.
303
0
                    add_int(int_count_);
304
0
                }
305
0
                last_offset_buffer_[int_count_ % 2] = input_.getLastOffset();
306
0
                int_buffer_[int_count_ % 2] = QUtil::string_to_ll(tokenizer_.getValue().c_str());
307
0
                continue;
308
309
7.84k
            } else if (
310
7.84k
                int_count_ >= 2 && tokenizer_.getType() == QPDFTokenizer::tt_word &&
311
0
                tokenizer_.getValue() == "R") {
312
0
                if (!context_) {
313
0
                    throw std::logic_error(
314
0
                        "Parser::parse called without context on an object with indirect "
315
0
                        "references");
316
0
                }
317
0
                auto id = QIntC::to_int(int_buffer_[(int_count_ - 1) % 2]);
318
0
                auto gen = QIntC::to_int(int_buffer_[(int_count_) % 2]);
319
0
                if (!(id < 1 || gen < 0 || gen >= 65535)) {
320
0
                    add(ParseGuard::getObject(context_, id, gen, parse_pdf_));
321
0
                } else {
322
0
                    add_bad_null(
323
0
                        "treating bad indirect reference (" + std::to_string(id) + " " +
324
0
                        std::to_string(gen) + " R) as null");
325
0
                }
326
0
                int_count_ = 0;
327
0
                continue;
328
329
7.84k
            } else if (int_count_ > 0) {
330
                // Process the buffered integers before processing the current token.
331
7.84k
                if (int_count_ > 1) {
332
0
                    add_int(int_count_ - 1);
333
0
                }
334
7.84k
                add_int(int_count_);
335
7.84k
                int_count_ = 0;
336
7.84k
            }
337
7.84k
        }
338
339
23.5k
        switch (tokenizer_.getType()) {
340
0
        case QPDFTokenizer::tt_eof:
341
0
            warn("parse error while reading object");
342
0
            if (content_stream) {
343
                // In content stream mode, leave object uninitialized to indicate EOF
344
0
                return {};
345
0
            }
346
0
            warn("unexpected EOF");
347
0
            return {};
348
349
0
        case QPDFTokenizer::tt_bad:
350
0
            check_too_many_bad_tokens();
351
0
            add_null();
352
0
            continue;
353
354
0
        case QPDFTokenizer::tt_brace_open:
355
0
        case QPDFTokenizer::tt_brace_close:
356
0
            add_bad_null("treating unexpected brace token as null");
357
0
            continue;
358
359
0
        case QPDFTokenizer::tt_array_close:
360
0
            if (frame_->state == st_array) {
361
0
                auto object = frame_->null_count > 100
362
0
                    ? QPDFObject::create<QPDF_Array>(std::move(frame_->olist), true)
363
0
                    : QPDFObject::create<QPDF_Array>(std::move(frame_->olist));
364
0
                set_description(object, frame_->offset - 1);
365
                // The `offset` points to the next of "[".  Set the rewind offset to point to the
366
                // beginning of "[". This has been explicitly tested with whitespace surrounding the
367
                // array start delimiter. getLastOffset points to the array end token and therefore
368
                // can't be used here.
369
0
                if (stack_.size() <= 1) {
370
0
                    return object;
371
0
                }
372
0
                stack_.pop_back();
373
0
                frame_ = &stack_.back();
374
0
                add(std::move(object));
375
0
            } else {
376
0
                if (sanity_checks_) {
377
                    // During sanity checks, assume nesting of containers is corrupt and object is
378
                    // unusable.
379
0
                    warn("unexpected array close token; giving up on reading object");
380
0
                    return {};
381
0
                }
382
0
                add_bad_null("treating unexpected array close token as null");
383
0
            }
384
0
            continue;
385
386
7.84k
        case QPDFTokenizer::tt_dict_close:
387
7.84k
            if (frame_->state <= st_dictionary_value) {
388
                // Attempt to recover more or less gracefully from invalid dictionaries.
389
7.84k
                auto& dict = frame_->dict;
390
391
7.84k
                if (frame_->state == st_dictionary_value) {
392
0
                    warn(
393
0
                        frame_->offset,
394
0
                        "dictionary ended prematurely; using null as value for last key");
395
0
                    dict[frame_->key] = QPDFObject::create<QPDF_Null>();
396
0
                }
397
7.84k
                if (!frame_->olist.empty()) {
398
0
                    if (sanity_checks_) {
399
0
                        warn(
400
0
                            frame_->offset,
401
0
                            "expected dictionary keys but found non-name objects; ignoring");
402
0
                    } else {
403
0
                        fix_missing_keys();
404
0
                    }
405
0
                }
406
407
7.84k
                if (!frame_->contents_string.empty() && dict.contains("/Type") &&
408
0
                    dict["/Type"].isNameAndEquals("/Sig") && dict.contains("/ByteRange") &&
409
0
                    dict.contains("/Contents") && dict["/Contents"].isString()) {
410
0
                    dict["/Contents"] = QPDFObjectHandle::newString(frame_->contents_string);
411
0
                    dict["/Contents"].setParsedOffset(frame_->contents_offset);
412
0
                }
413
7.84k
                auto object = QPDFObject::create<QPDF_Dictionary>(std::move(dict));
414
7.84k
                set_description(object, frame_->offset - 2);
415
                // The `offset` points to the next of "<<". Set the rewind offset to point to the
416
                // beginning of "<<". This has been explicitly tested with whitespace surrounding
417
                // the dictionary start delimiter. getLastOffset points to the dictionary end token
418
                // and therefore can't be used here.
419
7.84k
                if (stack_.size() <= 1) {
420
7.84k
                    return object;
421
7.84k
                }
422
0
                stack_.pop_back();
423
0
                frame_ = &stack_.back();
424
0
                add(std::move(object));
425
0
            } else {
426
0
                if (sanity_checks_) {
427
                    // During sanity checks, assume nesting of containers is corrupt and object is
428
                    // unusable.
429
0
                    warn("unexpected dictionary close token; giving up on reading object");
430
0
                    return {};
431
0
                }
432
0
                add_bad_null("unexpected dictionary close token");
433
0
            }
434
0
            continue;
435
436
0
        case QPDFTokenizer::tt_array_open:
437
0
        case QPDFTokenizer::tt_dict_open:
438
0
            if (stack_.size() > max_nesting) {
439
0
                limits_error(
440
0
                    "parser-max-nesting", "ignoring excessively deeply nested data structure");
441
0
            }
442
0
            b_contents = false;
443
0
            stack_.emplace_back(
444
0
                input_,
445
0
                (tokenizer_.getType() == QPDFTokenizer::tt_array_open) ? st_array
446
0
                                                                       : st_dictionary_key);
447
0
            frame_ = &stack_.back();
448
0
            continue;
449
450
0
        case QPDFTokenizer::tt_bool:
451
0
            add_scalar<QPDF_Bool>(tokenizer_.getValue() == "true");
452
0
            continue;
453
454
0
        case QPDFTokenizer::tt_null:
455
0
            add_null();
456
0
            continue;
457
458
7.84k
        case QPDFTokenizer::tt_integer:
459
7.84k
            if (!content_stream) {
460
                // Buffer token in case it is part of an indirect reference.
461
7.84k
                last_offset_buffer_[1] = input_.getLastOffset();
462
7.84k
                int_buffer_[1] = QUtil::string_to_ll(tokenizer_.getValue().c_str());
463
7.84k
                int_count_ = 1;
464
7.84k
            } else {
465
0
                add_scalar<QPDF_Integer>(QUtil::string_to_ll(tokenizer_.getValue().c_str()));
466
0
            }
467
7.84k
            continue;
468
469
0
        case QPDFTokenizer::tt_real:
470
0
            add_scalar<QPDF_Real>(tokenizer_.getValue());
471
0
            continue;
472
473
7.84k
        case QPDFTokenizer::tt_name:
474
7.84k
            if (frame_->state == st_dictionary_key) {
475
7.84k
                frame_->key = tokenizer_.getValue();
476
7.84k
                frame_->state = st_dictionary_value;
477
7.84k
                b_contents = decrypter_ && frame_->key == "/Contents";
478
7.84k
                continue;
479
7.84k
            } else {
480
0
                add_scalar<QPDF_Name>(tokenizer_.getValue());
481
0
            }
482
0
            continue;
483
484
0
        case QPDFTokenizer::tt_word:
485
0
            if (content_stream) {
486
0
                add_scalar<QPDF_Operator>(tokenizer_.getValue());
487
0
                continue;
488
0
            }
489
490
0
            if (sanity_checks_) {
491
0
                if (tokenizer_.getValue() == "endobj" || tokenizer_.getValue() == "endstream") {
492
                    // During sanity checks, assume an unexpected endobj or endstream indicates that
493
                    // we are parsing past the end of the object.
494
0
                    warn(
495
0
                        "unexpected 'endobj' or 'endstream' while reading object; giving up on "
496
0
                        "reading object");
497
0
                    return {};
498
0
                }
499
500
0
                add_bad_null("unknown token while reading object; treating as null");
501
0
                continue;
502
0
            }
503
504
0
            warn("unknown token while reading object; treating as string");
505
0
            check_too_many_bad_tokens();
506
0
            add_scalar<QPDF_String>(tokenizer_.getValue());
507
508
0
            continue;
509
510
0
        case QPDFTokenizer::tt_string:
511
0
            {
512
0
                auto const& val = tokenizer_.getValue();
513
0
                if (decrypter_) {
514
0
                    if (b_contents) {
515
0
                        frame_->contents_string = val;
516
0
                        frame_->contents_offset = input_.getLastOffset();
517
0
                        b_contents = false;
518
0
                    }
519
0
                    std::string s{val};
520
0
                    decrypter_->decryptString(s);
521
0
                    add_scalar<QPDF_String>(s);
522
0
                } else {
523
0
                    add_scalar<QPDF_String>(val);
524
0
                }
525
0
            }
526
0
            continue;
527
528
0
        default:
529
0
            add_bad_null("treating unknown token type as null while reading object");
530
23.5k
        }
531
23.5k
    }
532
7.84k
}
533
534
void
535
Parser::add(std::shared_ptr<QPDFObject>&& obj)
536
7.84k
{
537
7.84k
    if (frame_->state != st_dictionary_value) {
538
        // If state is st_dictionary_key then there is a missing key. Push onto olist for
539
        // processing once the tt_dict_close token has been found.
540
0
        frame_->olist.emplace_back(std::move(obj));
541
7.84k
    } else {
542
7.84k
        if (auto res = frame_->dict.insert_or_assign(frame_->key, std::move(obj)); !res.second) {
543
0
            warn_duplicate_key();
544
0
        }
545
7.84k
        frame_->state = st_dictionary_key;
546
7.84k
    }
547
7.84k
}
548
549
void
550
Parser::add_null()
551
0
{
552
0
    const static ObjectPtr null_obj = QPDFObject::create<QPDF_Null>();
553
554
0
    if (frame_->state != st_dictionary_value) {
555
        // If state is st_dictionary_key then there is a missing key. Push onto olist for
556
        // processing once the tt_dict_close token has been found.
557
0
        frame_->olist.emplace_back(null_obj);
558
0
    } else {
559
0
        if (auto res = frame_->dict.insert_or_assign(frame_->key, null_obj); !res.second) {
560
0
            warn_duplicate_key();
561
0
        }
562
0
        frame_->state = st_dictionary_key;
563
0
    }
564
0
    ++frame_->null_count;
565
0
}
566
567
void
568
Parser::add_bad_null(std::string const& msg)
569
0
{
570
0
    warn(msg);
571
0
    check_too_many_bad_tokens();
572
0
    add_null();
573
0
}
574
575
void
576
Parser::add_int(int count)
577
7.84k
{
578
7.84k
    auto obj = QPDFObject::create<QPDF_Integer>(int_buffer_[count % 2]);
579
7.84k
    obj->setDescription(context_, description_, last_offset_buffer_[count % 2]);
580
7.84k
    add(std::move(obj));
581
7.84k
}
582
583
template <typename T, typename... Args>
584
void
585
Parser::add_scalar(Args&&... args)
586
0
{
587
0
    auto limit = Limits::parser_max_container_size(bad_count_ || sanity_checks_);
588
0
    if (frame_->olist.size() >= limit || frame_->dict.size() >= limit) {
589
        // Stop adding scalars. We are going to abort when the close token or a bad token is
590
        // encountered.
591
0
        max_bad_count_ = 1;
592
0
        check_too_many_bad_tokens(); // always throws Error()
593
0
    }
594
0
    auto obj = QPDFObject::create<T>(std::forward<Args>(args)...);
595
0
    obj->setDescription(context_, description_, input_.getLastOffset());
596
0
    add(std::move(obj));
597
0
}
Unexecuted instantiation: void qpdf::impl::Parser::add_scalar<QPDF_Bool, bool>(bool&&)
Unexecuted instantiation: void qpdf::impl::Parser::add_scalar<QPDF_Integer, long long>(long long&&)
Unexecuted instantiation: void qpdf::impl::Parser::add_scalar<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&)
Unexecuted instantiation: void qpdf::impl::Parser::add_scalar<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&)
Unexecuted instantiation: void qpdf::impl::Parser::add_scalar<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&)
Unexecuted instantiation: void qpdf::impl::Parser::add_scalar<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&)
Unexecuted instantiation: void qpdf::impl::Parser::add_scalar<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> >&)
598
599
template <typename T, typename... Args>
600
QPDFObjectHandle
601
Parser::with_description(Args&&... args)
602
10.8k
{
603
10.8k
    auto obj = QPDFObject::create<T>(std::forward<Args>(args)...);
604
10.8k
    obj->setDescription(context_, description_, start_);
605
10.8k
    return {obj};
606
10.8k
}
Unexecuted instantiation: QPDFObjectHandle qpdf::impl::Parser::with_description<QPDF_Bool, bool>(bool&&)
Unexecuted instantiation: QPDFObjectHandle qpdf::impl::Parser::with_description<QPDF_Integer, long long>(long long&&)
Unexecuted instantiation: QPDFObjectHandle qpdf::impl::Parser::with_description<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&)
QPDFObjectHandle qpdf::impl::Parser::with_description<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
602
10.8k
{
603
10.8k
    auto obj = QPDFObject::create<T>(std::forward<Args>(args)...);
604
10.8k
    obj->setDescription(context_, description_, start_);
605
10.8k
    return {obj};
606
10.8k
}
Unexecuted instantiation: QPDFObjectHandle qpdf::impl::Parser::with_description<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&)
Unexecuted instantiation: QPDFObjectHandle qpdf::impl::Parser::with_description<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&)
Unexecuted instantiation: QPDFObjectHandle qpdf::impl::Parser::with_description<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> >&)
607
608
void
609
Parser::set_description(ObjectPtr& obj, qpdf_offset_t parsed_offset)
610
7.84k
{
611
7.84k
    if (obj) {
612
7.84k
        obj->setDescription(context_, description_, parsed_offset);
613
7.84k
    }
614
7.84k
}
615
616
void
617
Parser::fix_missing_keys()
618
0
{
619
0
    std::set<std::string> names;
620
0
    for (auto& obj: frame_->olist) {
621
0
        if (obj.raw_type_code() == ::ot_name) {
622
0
            names.insert(obj.getName());
623
0
        }
624
0
    }
625
0
    int next_fake_key = 1;
626
0
    for (auto const& item: frame_->olist) {
627
0
        while (true) {
628
0
            const std::string key = "/QPDFFake" + std::to_string(next_fake_key++);
629
0
            const bool found_fake = !frame_->dict.contains(key) && !names.contains(key);
630
0
            QTC::TC("qpdf", "QPDFParser found fake", (found_fake ? 0 : 1));
631
0
            if (found_fake) {
632
0
                warn(
633
0
                    frame_->offset,
634
0
                    "expected dictionary key but found non-name object; inserting key " + key);
635
0
                frame_->dict[key] = item;
636
0
                break;
637
0
            }
638
0
        }
639
0
    }
640
0
}
641
642
void
643
Parser::check_too_many_bad_tokens()
644
0
{
645
0
    auto limit = Limits::parser_max_container_size(bad_count_ || sanity_checks_);
646
0
    if (frame_->olist.size() >= limit || frame_->dict.size() >= limit) {
647
0
        if (bad_count_) {
648
0
            limits_error(
649
0
                "parser-max-container-size-damaged",
650
0
                "encountered errors while parsing an array or dictionary with more than " +
651
0
                    std::to_string(limit) + " elements; giving up on reading object");
652
0
        }
653
0
        limits_error(
654
0
            "parser-max-container-size",
655
0
            "encountered an array or dictionary with more than " + std::to_string(limit) +
656
0
                " elements during xref recovery; giving up on reading object");
657
0
    }
658
0
    if (max_bad_count_ && --max_bad_count_ == 0) {
659
0
        limits_error(
660
0
            "parser-max-errors", "too many errors during parsing; treating object as null");
661
0
    }
662
0
    if (good_count_ > 4) {
663
0
        good_count_ = 0;
664
0
        bad_count_ = 1;
665
0
        return;
666
0
    }
667
0
    if (++bad_count_ > 5 ||
668
0
        (frame_->state != st_array && std::cmp_less(max_bad_count_, frame_->olist.size()))) {
669
        // Give up after 5 errors in close proximity or if the number of missing dictionary keys
670
        // exceeds the remaining number of allowable total errors.
671
0
        warn("too many errors; giving up on reading object");
672
0
        throw Error();
673
0
    }
674
0
    good_count_ = 0;
675
0
}
676
677
void
678
Parser::limits_error(std::string const& limit, std::string const& msg)
679
0
{
680
0
    Limits::error();
681
0
    warn("limits error("s + limit + "): " + msg);
682
0
    throw Error();
683
0
}
684
685
void
686
Parser::warn(QPDFExc const& e) const
687
344
{
688
    // If parsing on behalf of a QPDF object and want to give a warning, we can warn through the
689
    // object. If parsing for some other reason, such as an explicit creation of an object from a
690
    // string, then just throw the exception.
691
344
    if (context_) {
692
0
        context_->warn(e);
693
344
    } else {
694
344
        throw e;
695
344
    }
696
344
}
697
698
void
699
Parser::warn_duplicate_key()
700
0
{
701
0
    warn(
702
0
        frame_->offset,
703
0
        "dictionary has duplicated key " + frame_->key +
704
0
            "; last occurrence overrides earlier ones");
705
0
    check_too_many_bad_tokens();
706
0
}
707
708
void
709
Parser::warn(qpdf_offset_t offset, std::string const& msg) const
710
344
{
711
344
    if (stream_id_) {
712
0
        std::string descr = "object "s + std::to_string(obj_id_) + " 0";
713
0
        std::string name = context_->getFilename() + " object stream " + std::to_string(stream_id_);
714
0
        warn(QPDFExc(qpdf_e_damaged_pdf, name, descr, offset, msg));
715
344
    } else {
716
344
        warn(QPDFExc(qpdf_e_damaged_pdf, input_.getName(), object_description_, offset, msg));
717
344
    }
718
344
}
719
720
void
721
Parser::warn(std::string const& msg) const
722
344
{
723
344
    warn(input_.getLastOffset(), msg);
724
344
}