aboutsummaryrefslogtreecommitdiffstats
path: root/libqpdf/QPDFParser.cc
blob: 8e3d0019dd4533a80952caf9402f2fc6f06d2f37 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
#include <qpdf/QPDFParser.hh>

#include <qpdf/QPDF.hh>
#include <qpdf/QPDFObjGen.hh>
#include <qpdf/QPDFObjectHandle.hh>
#include <qpdf/QPDFObject_private.hh>
#include <qpdf/QPDF_Array.hh>
#include <qpdf/QPDF_Bool.hh>
#include <qpdf/QPDF_Dictionary.hh>
#include <qpdf/QPDF_InlineImage.hh>
#include <qpdf/QPDF_Integer.hh>
#include <qpdf/QPDF_Name.hh>
#include <qpdf/QPDF_Null.hh>
#include <qpdf/QPDF_Operator.hh>
#include <qpdf/QPDF_Real.hh>
#include <qpdf/QPDF_Reserved.hh>
#include <qpdf/QPDF_Stream.hh>
#include <qpdf/QPDF_String.hh>
#include <qpdf/QTC.hh>
#include <qpdf/QUtil.hh>

#include <memory>


QPDFObjectHandle
QPDFParser::parse(bool& empty, bool content_stream)
{
    // This method must take care not to resolve any objects. Don't check the type of any object
    // without first ensuring that it is a direct object. Otherwise, doing so may have the side
    // effect of reading the object and changing the file pointer. If you do this, it will cause a
    // logic error to be thrown from QPDF::inParse().

    const static std::shared_ptr<QPDFObject> null_oh = QPDF_Null::create();
    QPDF::ParseGuard pg(context);

    empty = false;

    std::shared_ptr<QPDFObject> object;
    bool set_offset = false;

//    std::vector<StackFrame> stack{{input, st_top}};
    stack.clear(); // NEW
    stack.emplace_back(input, st_top); // NEW
    bool done = false;
    bool b_contents = false;
    bool is_null = false;
    frame = &stack.back(); // CHANGED

    while (!done) {
        bool indirect_ref = false;
        is_null = false;
        object = nullptr;
        set_offset = false;

        if (!tokenizer.nextToken(*input, object_description)) {
            warn(tokenizer.getErrorMessage());
        }
        ++good_count; // optimistically

        switch (tokenizer.getType()) {
        case QPDFTokenizer::tt_eof:
            if (stack.size() > 1) {
                warn("parse error while reading object");
            }
            if (content_stream) {
                // In content stream mode, leave object uninitialized to indicate EOF
                return {};
            }
//            QTC::TC("qpdf", "QPDFParser eof in parse");
            warn("unexpected EOF");
            return {QPDF_Null::create()};

        case QPDFTokenizer::tt_bad:
//            QTC::TC("qpdf", "QPDFParser bad token in parse");
            if (tooManyBadTokens()) {
                return {QPDF_Null::create()};
            }
            is_null = true;
            break;

        case QPDFTokenizer::tt_brace_open:
        case QPDFTokenizer::tt_brace_close:
//            QTC::TC("qpdf", "QPDFParser bad brace");
            warn("treating unexpected brace token as null");
            if (tooManyBadTokens()) {
                return {QPDF_Null::create()};
            }
            is_null = true;
            break;

        case QPDFTokenizer::tt_array_close:
            if (frame->state == st_array) {
                if (stack.size() < 2) {
                    throw std::logic_error("QPDFParser::parseInternal: st_stop encountered with "
                                           "insufficient elements in stack");
                }
                object = QPDF_Array::create(std::move(frame->olist), frame->null_count > 100);
                setDescription(object, frame->offset - 1);
                // The `offset` points to the next of "[".  Set the rewind offset to point to the
                // beginning of "[". This has been explicitly tested with whitespace surrounding the
                // array start delimiter. getLastOffset points to the array end token and therefore
                // can't be used here.
                set_offset = true;
                stack.pop_back();
                frame = &stack.back();
            } else {
//                QTC::TC("qpdf", "QPDFParser bad array close");
                warn("treating unexpected array close token as null");
                if (tooManyBadTokens()) {
                    return {QPDF_Null::create()};
                }
                is_null = true;
            }
            break;

        case QPDFTokenizer::tt_dict_close:
            if (frame->state == st_dictionary) {
                if (stack.size() < 2) {
                    throw std::logic_error("QPDFParser::parseInternal: st_stop encountered with "
                                           "insufficient elements in stack");
                }

                // Convert list to map. Alternating elements are keys.  Attempt to recover more or
                // less gracefully from invalid dictionaries.
                std::set<std::string> names;
                for (auto& obj: frame->olist) {
                    if (obj) {
                        if (obj->getTypeCode() == ::ot_name) {
                            names.insert(obj->getStringValue());
                        }
                    }
                }

                std::map<std::string, QPDFObjectHandle> dict;
                int next_fake_key = 1;
                for (auto iter = frame->olist.begin(); iter != frame->olist.end();) {
                    // Calculate key.
                    std::string key;
                    if (*iter && (*iter)->getTypeCode() == ::ot_name) {
                        key = (*iter)->getStringValue();
                        ++iter;
                    } else {
                        for (bool found_fake = false; !found_fake;) {
                            key = "/QPDFFake" + std::to_string(next_fake_key++);
                            found_fake = (names.count(key) == 0);
//                            QTC::TC("qpdf", "QPDFParser found fake", (found_fake ? 0 : 1));
                        }
                        warn(
                            frame->offset,
                            "expected dictionary key but found non-name object; inserting key " +
                                key);
                    }
                    if (dict.count(key) > 0) {
//                        QTC::TC("qpdf", "QPDFParser duplicate dict key");
                        warn(
                            frame->offset,
                            "dictionary has duplicated key " + key +
                                "; last occurrence overrides earlier ones");
                    }

                    // Calculate value.
                    std::shared_ptr<QPDFObject> val;
                    if (iter != frame->olist.end()) {
                        val = *iter;
                        ++iter;
                    } else {
//                        QTC::TC("qpdf", "QPDFParser no val for last key");
                        warn(
                            frame->offset,
                            "dictionary ended prematurely; using null as value for last key");
                        val = QPDF_Null::create();
                    }

                    dict[std::move(key)] = std::move(val);
                }
                if (!frame->contents_string.empty() && dict.count("/Type") &&
                    dict["/Type"].isNameAndEquals("/Sig") && dict.count("/ByteRange") &&
                    dict.count("/Contents") && dict["/Contents"].isString()) {
                    dict["/Contents"] = QPDFObjectHandle::newString(frame->contents_string);
                    dict["/Contents"].setParsedOffset(frame->contents_offset);
                }
                object = QPDF_Dictionary::create(std::move(dict));
                setDescription(object, frame->offset - 2);
                // The `offset` points to the next of "<<". Set the rewind offset to point to the
                // beginning of "<<". This has been explicitly tested with whitespace surrounding
                // the dictionary start delimiter. getLastOffset points to the dictionary end token
                // and therefore can't be used here.
                set_offset = true;
                stack.pop_back();
                frame = &stack.back();
            } else {
//                QTC::TC("qpdf", "QPDFParser bad dictionary close");
                warn("unexpected dictionary close token");
                if (tooManyBadTokens()) {
                    return {QPDF_Null::create()};
                }
                is_null = true;
            }
            break;

        case QPDFTokenizer::tt_array_open:
        case QPDFTokenizer::tt_dict_open:
            if (stack.size() > 500) {
//                QTC::TC("qpdf", "QPDFParser too deep");
                warn("ignoring excessively deeply nested data structure");
                return {QPDF_Null::create()};
            } else {
                b_contents = false;
                stack.emplace_back(
                    input,
                    (tokenizer.getType() == QPDFTokenizer::tt_array_open) ? st_array
                                                                          : st_dictionary);
                frame = &stack.back();
                return parseRemainder(content_stream); // NEW
                continue;
            }

        case QPDFTokenizer::tt_bool:
            object = QPDF_Bool::create((tokenizer.getValue() == "true"));
            break;

        case QPDFTokenizer::tt_null:
            is_null = true;
            ++frame->null_count;

            break;

        case QPDFTokenizer::tt_integer:
            object = QPDF_Integer::create(QUtil::string_to_ll(tokenizer.getValue().c_str()));
            break;

        case QPDFTokenizer::tt_real:
            object = QPDF_Real::create(tokenizer.getValue());
            break;

        case QPDFTokenizer::tt_name:
            {
                auto const& name = tokenizer.getValue();
                object = QPDF_Name::create(name);

                if (name == "/Contents") {
                    b_contents = true;
                } else {
                    b_contents = false;
                }
            }
            break;

        case QPDFTokenizer::tt_word:
            {
                auto const& value = tokenizer.getValue();
                auto size = frame->olist.size();
                if (content_stream) {
                    object = QPDF_Operator::create(value);
                } else if (
                    value == "R" && frame->state != st_top && size >= 2 && frame->olist.back() &&
                    frame->olist.back()->getTypeCode() == ::ot_integer &&
                    !frame->olist.back()->getObjGen().isIndirect() && frame->olist.at(size - 2) &&
                    frame->olist.at(size - 2)->getTypeCode() == ::ot_integer &&
                    !frame->olist.at(size - 2)->getObjGen().isIndirect()) {
                    if (context == nullptr) {
//                        QTC::TC("qpdf", "QPDFParser indirect without context");
                        throw std::logic_error("QPDFObjectHandle::parse called without context on "
                                               "an object with indirect references");
                    }
                    auto ref_og = QPDFObjGen(
                        QPDFObjectHandle(frame->olist.at(size - 2)).getIntValueAsInt(),
                        QPDFObjectHandle(frame->olist.back()).getIntValueAsInt());
                    if (ref_og.isIndirect()) {
                        // This action has the desirable side effect of causing dangling references
                        // (references to indirect objects that don't appear in the PDF) in any
                        // parsed object to appear in the object cache.
                        object = context->getObject(ref_og).obj;
                        indirect_ref = true;
                    } else {
//                        QTC::TC("qpdf", "QPDFParser indirect with 0 objid");
                        is_null = true;
                    }
                    frame->olist.pop_back();
                    frame->olist.pop_back();
                } else if ((value == "endobj") && (frame->state == st_top)) {
                    // We just saw endobj without having read anything.  Treat this as a null and do
                    // not move the input source's offset.
                    is_null = true;
                    input->seek(input->getLastOffset(), SEEK_SET);
                    empty = true;
                } else {
//                    QTC::TC("qpdf", "QPDFParser treat word as string");
                    warn("unknown token while reading object; treating as string");
                    if (tooManyBadTokens()) {
                        return {QPDF_Null::create()};
                    }
                    object = QPDF_String::create(value);
                }
            }
            break;

        case QPDFTokenizer::tt_string:
            {
                auto const& val = tokenizer.getValue();
                if (decrypter) {
                    if (b_contents) {
                        frame->contents_string = val;
                        frame->contents_offset = input->getLastOffset();
                        b_contents = false;
                    }
                    std::string s{val};
                    decrypter->decryptString(s);
                    object = QPDF_String::create(s);
                } else {
                    object = QPDF_String::create(val);
                }
            }
            break;

        default:
            warn("treating unknown token type as null while reading object");
            if (tooManyBadTokens()) {
                return {QPDF_Null::create()};
            }
            is_null = true;
            break;
        }

        if (object == nullptr && !is_null) {
            throw std::logic_error("QPDFParser:parseInternal: unexpected uninitialized object");
        }

        switch (frame->state) {
        case st_dictionary:
        case st_array:
            if (is_null) {
                object = null_oh;
                // No need to set description for direct nulls - they probably will become implicit.
            } else if (!indirect_ref && !set_offset) {
                setDescription(object, input->getLastOffset());
            }
            set_offset = true;
            frame->olist.push_back(object);
            break;

        case st_top:
            done = true;
            break;
        }
    }

    if (is_null) {
        object = QPDF_Null::create();
    }
    if (!set_offset) {
        setDescription(object, frame->offset);
    }
    return object;
}

QPDFObjectHandle
QPDFParser::parseRemainder(bool content_stream)
{
    // This method must take care not to resolve any objects. Don't check the type of any object
    // without first ensuring that it is a direct object. Otherwise, doing so may have the side
    // effect of reading the object and changing the file pointer. If you do this, it will cause a
    // logic error to be thrown from QPDF::inParse().

    const static std::shared_ptr<QPDFObject> null_oh = QPDF_Null::create();
//    QPDF::ParseGuard pg(context);

//    empty = false;

    std::shared_ptr<QPDFObject> object;
    bool set_offset = false;

//    std::vector<StackFrame> stack{{input, st_top},};
    bool done = false;
    bool b_contents = false;
    bool is_null = false;
    frame = &stack.back(); // CHANGED

    while (!done) {
        bool indirect_ref = false;
        is_null = false;
        object = nullptr;
        set_offset = false;

        if (!tokenizer.nextToken(*input, object_description)) {
            warn(tokenizer.getErrorMessage());
        }
        ++good_count; // optimistically

        switch (tokenizer.getType()) {
        case QPDFTokenizer::tt_eof:
            if (stack.size() > 1) {
                warn("parse error while reading object");
            }
            if (content_stream) {
                // In content stream mode, leave object uninitialized to indicate EOF
                return {};
            }
            QTC::TC("qpdf", "QPDFParser eof in parse");
            warn("unexpected EOF");
            return {QPDF_Null::create()};

        case QPDFTokenizer::tt_bad:
            QTC::TC("qpdf", "QPDFParser bad token in parse");
            if (tooManyBadTokens()) {
                return {QPDF_Null::create()};
            }
            is_null = true;
            break;

        case QPDFTokenizer::tt_brace_open:
        case QPDFTokenizer::tt_brace_close:
            QTC::TC("qpdf", "QPDFParser bad brace");
            warn("treating unexpected brace token as null");
            if (tooManyBadTokens()) {
                return {QPDF_Null::create()};
            }
            is_null = true;
            break;

        case QPDFTokenizer::tt_array_close:
            if (frame->state == st_array) {
                if (stack.size() < 2) {
                    throw std::logic_error("QPDFParser::parseInternal: st_stop encountered with "
                                           "insufficient elements in stack");
                }
                object = QPDF_Array::create(std::move(frame->olist), frame->null_count > 100);
                setDescription(object, frame->offset - 1);
                // The `offset` points to the next of "[".  Set the rewind offset to point to the
                // beginning of "[". This has been explicitly tested with whitespace surrounding the
                // array start delimiter. getLastOffset points to the array end token and therefore
                // can't be used here.
                set_offset = true;
                stack.pop_back();
                frame = &stack.back();
            } else {
                QTC::TC("qpdf", "QPDFParser bad array close");
                warn("treating unexpected array close token as null");
                if (tooManyBadTokens()) {
                    return {QPDF_Null::create()};
                }
                is_null = true;
            }
            break;

        case QPDFTokenizer::tt_dict_close:
            if (frame->state == st_dictionary) {
                if (stack.size() < 2) {
                    throw std::logic_error("QPDFParser::parseInternal: st_stop encountered with "
                                           "insufficient elements in stack");
                }

                // Convert list to map. Alternating elements are keys.  Attempt to recover more or
                // less gracefully from invalid dictionaries.
                std::set<std::string> names;
                for (auto& obj: frame->olist) {
                    if (obj) {
                        if (obj->getTypeCode() == ::ot_name) {
                            names.insert(obj->getStringValue());
                        }
                    }
                }

                std::map<std::string, QPDFObjectHandle> dict;
                int next_fake_key = 1;
                for (auto iter = frame->olist.begin(); iter != frame->olist.end();) {
                    // Calculate key.
                    std::string key;
                    if (*iter && (*iter)->getTypeCode() == ::ot_name) {
                        key = (*iter)->getStringValue();
                        ++iter;
                    } else {
                        for (bool found_fake = false; !found_fake;) {
                            key = "/QPDFFake" + std::to_string(next_fake_key++);
                            found_fake = (names.count(key) == 0);
                            QTC::TC("qpdf", "QPDFParser found fake", (found_fake ? 0 : 1));
                        }
                        warn(
                            frame->offset,
                            "expected dictionary key but found non-name object; inserting key " +
                                key);
                    }
                    if (dict.count(key) > 0) {
                        QTC::TC("qpdf", "QPDFParser duplicate dict key");
                        warn(
                            frame->offset,
                            "dictionary has duplicated key " + key +
                                "; last occurrence overrides earlier ones");
                    }

                    // Calculate value.
                    std::shared_ptr<QPDFObject> val;
                    if (iter != frame->olist.end()) {
                        val = *iter;
                        ++iter;
                    } else {
                        QTC::TC("qpdf", "QPDFParser no val for last key");
                        warn(
                            frame->offset,
                            "dictionary ended prematurely; using null as value for last key");
                        val = QPDF_Null::create();
                    }

                    dict[std::move(key)] = std::move(val);
                }
                if (!frame->contents_string.empty() && dict.count("/Type") &&
                    dict["/Type"].isNameAndEquals("/Sig") && dict.count("/ByteRange") &&
                    dict.count("/Contents") && dict["/Contents"].isString()) {
                    dict["/Contents"] = QPDFObjectHandle::newString(frame->contents_string);
                    dict["/Contents"].setParsedOffset(frame->contents_offset);
                }
                object = QPDF_Dictionary::create(std::move(dict));
                setDescription(object, frame->offset - 2);
                // The `offset` points to the next of "<<". Set the rewind offset to point to the
                // beginning of "<<". This has been explicitly tested with whitespace surrounding
                // the dictionary start delimiter. getLastOffset points to the dictionary end token
                // and therefore can't be used here.
                set_offset = true;
                stack.pop_back();
                frame = &stack.back();
            } else {
                QTC::TC("qpdf", "QPDFParser bad dictionary close");
                warn("unexpected dictionary close token");
                if (tooManyBadTokens()) {
                    return {QPDF_Null::create()};
                }
                is_null = true;
            }
            break;

        case QPDFTokenizer::tt_array_open:
        case QPDFTokenizer::tt_dict_open:
            if (stack.size() > 500) {
                QTC::TC("qpdf", "QPDFParser too deep");
                warn("ignoring excessively deeply nested data structure");
                return {QPDF_Null::create()};
            } else {
                b_contents = false;
                stack.emplace_back(
                    input,
                    (tokenizer.getType() == QPDFTokenizer::tt_array_open) ? st_array
                                                                          : st_dictionary);
                frame = &stack.back();
                continue;
            }

        case QPDFTokenizer::tt_bool:
            object = QPDF_Bool::create((tokenizer.getValue() == "true"));
            break;

        case QPDFTokenizer::tt_null:
            is_null = true;
            ++frame->null_count;

            break;

        case QPDFTokenizer::tt_integer:
            object = QPDF_Integer::create(QUtil::string_to_ll(tokenizer.getValue().c_str()));
            break;

        case QPDFTokenizer::tt_real:
            object = QPDF_Real::create(tokenizer.getValue());
            break;

        case QPDFTokenizer::tt_name:
            {
                auto const& name = tokenizer.getValue();
                object = QPDF_Name::create(name);

                if (name == "/Contents") {
                    b_contents = true;
                } else {
                    b_contents = false;
                }
            }
            break;

        case QPDFTokenizer::tt_word:
            {
                auto const& value = tokenizer.getValue();
                auto size = frame->olist.size();
                if (content_stream) {
                    object = QPDF_Operator::create(value);
                } else if (
                    value == "R" && frame->state != st_top && size >= 2 && frame->olist.back() &&
                    frame->olist.back()->getTypeCode() == ::ot_integer &&
                    !frame->olist.back()->getObjGen().isIndirect() && frame->olist.at(size - 2) &&
                    frame->olist.at(size - 2)->getTypeCode() == ::ot_integer &&
                    !frame->olist.at(size - 2)->getObjGen().isIndirect()) {
                    if (context == nullptr) {
                        QTC::TC("qpdf", "QPDFParser indirect without context");
                        throw std::logic_error("QPDFObjectHandle::parse called without context on "
                                               "an object with indirect references");
                    }
                    auto ref_og = QPDFObjGen(
                        QPDFObjectHandle(frame->olist.at(size - 2)).getIntValueAsInt(),
                        QPDFObjectHandle(frame->olist.back()).getIntValueAsInt());
                    if (ref_og.isIndirect()) {
                        // This action has the desirable side effect of causing dangling references
                        // (references to indirect objects that don't appear in the PDF) in any
                        // parsed object to appear in the object cache.
                        object = context->getObject(ref_og).obj;
                        indirect_ref = true;
                    } else {
                        QTC::TC("qpdf", "QPDFParser indirect with 0 objid");
                        is_null = true;
                    }
                    frame->olist.pop_back();
                    frame->olist.pop_back();
                } else if ((value == "endobj") && (frame->state == st_top)) {
                    // We just saw endobj without having read anything.  Treat this as a null and do
                    // not move the input source's offset.
                    is_null = true;
                    input->seek(input->getLastOffset(), SEEK_SET);
//                    empty = true;
                } else {
                    QTC::TC("qpdf", "QPDFParser treat word as string");
                    warn("unknown token while reading object; treating as string");
                    if (tooManyBadTokens()) {
                        return {QPDF_Null::create()};
                    }
                    object = QPDF_String::create(value);
                }
            }
            break;

        case QPDFTokenizer::tt_string:
            {
                auto const& val = tokenizer.getValue();
                if (decrypter) {
                    if (b_contents) {
                        frame->contents_string = val;
                        frame->contents_offset = input->getLastOffset();
                        b_contents = false;
                    }
                    std::string s{val};
                    decrypter->decryptString(s);
                    object = QPDF_String::create(s);
                } else {
                    object = QPDF_String::create(val);
                }
            }
            break;

        default:
            warn("treating unknown token type as null while reading object");
            if (tooManyBadTokens()) {
                return {QPDF_Null::create()};
            }
            is_null = true;
            break;
        }

        if (object == nullptr && !is_null) {
            throw std::logic_error("QPDFParser:parseInternal: unexpected uninitialized object");
        }

        switch (frame->state) {
        case st_dictionary:
        case st_array:
            if (is_null) {
                object = null_oh;
                // No need to set description for direct nulls - they probably will become implicit.
            } else if (!indirect_ref && !set_offset) {
                setDescription(object, input->getLastOffset());
            }
            set_offset = true;
            frame->olist.push_back(object);
            break;

        case st_top:
            done = true;
            break;
        }
    }

    if (is_null) {
        object = QPDF_Null::create();
    }
    if (!set_offset) {
        setDescription(object, frame->offset);
    }
    return object;
}

void
QPDFParser::setDescription(std::shared_ptr<QPDFObject>& obj, qpdf_offset_t parsed_offset)
{
    if (obj) {
        obj->setDescription(context, description, parsed_offset);
    }
}

bool
QPDFParser::tooManyBadTokens()
{
    if (good_count <= 4) {
        if (++bad_count > 5) {
            warn("too many errors; giving up on reading object");
            return true;
        }
    } else {
        bad_count = 1;
    }
    good_count = 0;
    return false;
}

void
QPDFParser::warn(QPDFExc const& e) const
{
    // If parsing on behalf of a QPDF object and want to give a warning, we can warn through the
    // object. If parsing for some other reason, such as an explicit creation of an object from a
    // string, then just throw the exception.
    if (context) {
        context->warn(e);
    } else {
        throw e;
    }
}

void
QPDFParser::warn(qpdf_offset_t offset, std::string const& msg) const
{
    warn(QPDFExc(qpdf_e_damaged_pdf, input->getName(), object_description, offset, msg));
}

void
QPDFParser::warn(std::string const& msg) const
{
    warn(input->getLastOffset(), msg);
}