Coverage Report

Created: 2025-11-11 07:03

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