Coverage Report

Created: 2026-02-26 06:40

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/qpdf/libqpdf/QPDF_objects.cc
Line
Count
Source
1
#include <qpdf/qpdf-config.h> // include first for large file support
2
3
#include <qpdf/QPDF_private.hh>
4
5
#include <qpdf/InputSource_private.hh>
6
#include <qpdf/OffsetInputSource.hh>
7
#include <qpdf/Pipeline.hh>
8
#include <qpdf/QPDFExc.hh>
9
#include <qpdf/QPDFLogger.hh>
10
#include <qpdf/QPDFObjectHandle_private.hh>
11
#include <qpdf/QPDFObject_private.hh>
12
#include <qpdf/QPDFParser.hh>
13
#include <qpdf/QTC.hh>
14
#include <qpdf/QUtil.hh>
15
#include <qpdf/Util.hh>
16
17
#include <array>
18
#include <atomic>
19
#include <cstring>
20
#include <limits>
21
#include <map>
22
#include <vector>
23
24
using namespace qpdf;
25
using namespace std::literals;
26
27
using Objects = QPDF::Doc::Objects;
28
using Parser = impl::Parser;
29
30
4.63M
QPDFXRefEntry::QPDFXRefEntry() = default;
31
32
QPDFXRefEntry::QPDFXRefEntry(int type, qpdf_offset_t field1, int field2) :
33
0
    type(type),
34
0
    field1(field1),
35
0
    field2(field2)
36
0
{
37
0
    util::assertion(type == 1 || type == 2, "invalid xref type " + std::to_string(type));
38
0
}
39
40
int
41
QPDFXRefEntry::getType() const
42
1.64M
{
43
1.64M
    return type;
44
1.64M
}
45
46
qpdf_offset_t
47
QPDFXRefEntry::getOffset() const
48
1.10M
{
49
1.10M
    util::assertion(type == 1, "getOffset called for xref entry of type != 1");
50
1.10M
    return this->field1;
51
1.10M
}
52
53
int
54
QPDFXRefEntry::getObjStreamNumber() const
55
369k
{
56
369k
    util::assertion(type == 2, "getObjStreamNumber called for xref entry of type != 2");
57
369k
    return QIntC::to_int(field1);
58
369k
}
59
60
int
61
QPDFXRefEntry::getObjStreamIndex() const
62
48.1k
{
63
48.1k
    util::assertion(type == 2, "getObjStreamIndex called for xref entry of type != 2");
64
48.1k
    return field2;
65
48.1k
}
66
67
namespace
68
{
69
    class InvalidInputSource: public InputSource
70
    {
71
      public:
72
        ~InvalidInputSource() override = default;
73
        qpdf_offset_t
74
        findAndSkipNextEOL() override
75
0
        {
76
0
            throwException();
77
0
            return 0;
78
0
        }
79
        std::string const&
80
        getName() const override
81
0
        {
82
0
            static std::string name("closed input source");
83
0
            return name;
84
0
        }
85
        qpdf_offset_t
86
        tell() override
87
0
        {
88
0
            throwException();
89
0
            return 0;
90
0
        }
91
        void
92
        seek(qpdf_offset_t offset, int whence) override
93
0
        {
94
0
            throwException();
95
0
        }
96
        void
97
        rewind() override
98
0
        {
99
0
            throwException();
100
0
        }
101
        size_t
102
        read(char* buffer, size_t length) override
103
0
        {
104
0
            throwException();
105
0
            return 0;
106
0
        }
107
        void
108
        unreadCh(char ch) override
109
0
        {
110
0
            throwException();
111
0
        }
112
113
      private:
114
        void
115
        throwException()
116
0
        {
117
0
            throw std::logic_error(
118
0
                "QPDF operation attempted on a QPDF object with no input "
119
0
                "source. QPDF operations are invalid before processFile (or "
120
0
                "another process method) or after closeInputSource");
121
0
        }
122
    };
123
} // namespace
124
125
class QPDF::ResolveRecorder final
126
{
127
  public:
128
    ResolveRecorder(QPDF& qpdf, QPDFObjGen const& og) :
129
473k
        qpdf(qpdf),
130
473k
        iter(qpdf.m->resolving.insert(og).first)
131
473k
    {
132
473k
    }
133
    ~ResolveRecorder()
134
473k
    {
135
473k
        qpdf.m->resolving.erase(iter);
136
473k
    }
137
138
  private:
139
    QPDF& qpdf;
140
    std::set<QPDFObjGen>::const_iterator iter;
141
};
142
143
class Objects::PatternFinder final: public InputSource::Finder
144
{
145
  public:
146
    PatternFinder(Objects& o, bool (Objects::*checker)()) :
147
62.1k
        o(o),
148
62.1k
        checker(checker)
149
62.1k
    {
150
62.1k
    }
151
    ~PatternFinder() final = default;
152
    bool
153
    check() final
154
48.3k
    {
155
48.3k
        return (this->o.*checker)();
156
48.3k
    }
157
158
  private:
159
    Objects& o;
160
    bool (Objects::*checker)();
161
};
162
163
bool
164
Objects::validatePDFVersion(char const*& p, std::string& version)
165
7.48k
{
166
7.48k
    if (!util::is_digit(*p)) {
167
2.45k
        return false;
168
2.45k
    }
169
12.4k
    while (util::is_digit(*p)) {
170
7.37k
        version.append(1, *p++);
171
7.37k
    }
172
5.03k
    if (!(*p == '.' && util::is_digit(*(p + 1)))) {
173
1.01k
        return false;
174
1.01k
    }
175
4.01k
    version.append(1, *p++);
176
9.90k
    while (util::is_digit(*p)) {
177
5.88k
        version.append(1, *p++);
178
5.88k
    }
179
4.01k
    return true;
180
5.03k
}
181
182
bool
183
Objects::findHeader()
184
7.49k
{
185
7.49k
    qpdf_offset_t global_offset = m->file->tell();
186
7.49k
    std::string line = m->file->readLine(1024);
187
7.49k
    char const* p = line.data();
188
7.49k
    util::assertion(strncmp(p, "%PDF-", 5) == 0, "findHeader is not looking at %PDF-");
189
7.49k
    p += 5;
190
7.49k
    std::string version;
191
    // Note: The string returned by line.data() is always null-terminated. The code below never
192
    // overruns the buffer because a null character always short-circuits further advancement.
193
7.49k
    if (!validatePDFVersion(p, version)) {
194
3.47k
        return false;
195
3.47k
    }
196
4.02k
    m->pdf_version = version;
197
4.02k
    if (global_offset != 0) {
198
        // Empirical evidence strongly suggests (codified in PDF 2.0 spec) that when there is
199
        // leading material prior to the PDF header, all explicit offsets in the file are such that
200
        // 0 points to the beginning of the header.
201
2.31k
        m->file = std::make_shared<OffsetInputSource>(m->file, global_offset);
202
2.31k
    }
203
4.02k
    return true;
204
7.49k
}
205
206
bool
207
Objects::findStartxref()
208
7.83k
{
209
7.83k
    if (readToken(*m->file).isWord("startxref") && readToken(*m->file).isInteger()) {
210
        // Position in front of offset token
211
5.16k
        m->file->seek(m->file->getLastOffset(), SEEK_SET);
212
5.16k
        return true;
213
5.16k
    }
214
2.67k
    return false;
215
7.83k
}
216
217
void
218
Objects::parse(char const* password)
219
19.6k
{
220
19.6k
    if (password) {
221
0
        m->encp->provided_password = password;
222
0
    }
223
224
    // Find the header anywhere in the first 1024 bytes of the file.
225
19.6k
    PatternFinder hf(*this, &Objects::findHeader);
226
19.6k
    if (!m->file->findFirst("%PDF-", 0, 1024, hf)) {
227
15.6k
        warn(damagedPDF("", -1, "can't find PDF header"));
228
        // QPDFWriter writes files that usually require at least version 1.2 for /FlateDecode
229
15.6k
        m->pdf_version = "1.2";
230
15.6k
    }
231
232
    // PDF spec says %%EOF must be found within the last 1024 bytes of/ the file.  We add an extra
233
    // 30 characters to leave room for the startxref stuff.
234
19.6k
    m->file->seek(0, SEEK_END);
235
19.6k
    qpdf_offset_t end_offset = m->file->tell();
236
19.6k
    m->xref_table_max_offset = end_offset;
237
    // Sanity check on object ids. All objects must appear in xref table / stream. In all realistic
238
    // scenarios at least 3 bytes are required.
239
19.6k
    if (m->xref_table_max_id > m->xref_table_max_offset / 3) {
240
19.6k
        m->xref_table_max_id = static_cast<int>(m->xref_table_max_offset / 3);
241
19.6k
    }
242
19.6k
    qpdf_offset_t start_offset = (end_offset > 1054 ? end_offset - 1054 : 0);
243
19.6k
    PatternFinder sf(*this, &Objects::findStartxref);
244
19.6k
    qpdf_offset_t xref_offset = 0;
245
19.6k
    if (m->file->findLast("startxref", start_offset, 0, sf)) {
246
4.68k
        xref_offset = QUtil::string_to_ll(readToken(*m->file).getValue().c_str());
247
4.68k
    }
248
249
19.6k
    try {
250
19.6k
        if (xref_offset == 0) {
251
15.0k
            throw damagedPDF("", -1, "can't find startxref");
252
15.0k
        }
253
4.58k
        try {
254
4.58k
            read_xref(xref_offset);
255
4.58k
        } catch (QPDFExc&) {
256
3.68k
            throw;
257
3.68k
        } catch (std::exception& e) {
258
334
            throw damagedPDF("", -1, std::string("error reading xref: ") + e.what());
259
334
        }
260
19.0k
    } catch (QPDFExc& e) {
261
19.0k
        if (global::Options::inspection_mode()) {
262
0
            try {
263
0
                reconstruct_xref(e, xref_offset > 0);
264
0
            } catch (std::exception& er) {
265
0
                warn(damagedPDF("", -1, "error reconstructing xref: "s + er.what()));
266
0
            }
267
0
            if (!m->trailer) {
268
0
                m->trailer = Dictionary::empty();
269
0
            }
270
0
            return;
271
0
        }
272
19.0k
        if (cf.surpress_recovery()) {
273
0
            throw;
274
0
        }
275
19.0k
        reconstruct_xref(e, xref_offset > 0);
276
19.0k
    }
277
278
9.05k
    m->encp->initialize(qpdf);
279
9.05k
    m->parsed = true;
280
9.05k
    if (!m->xref_table.empty() && !qpdf.getRoot().getKey("/Pages").isDictionary()) {
281
        // QPDFs created from JSON have an empty xref table and no root object yet.
282
5
        throw damagedPDF("", -1, "unable to find page tree");
283
5
    }
284
9.05k
}
285
286
void
287
Objects::inParse(bool v)
288
376k
{
289
376k
    util::internal_error_if(
290
376k
        m->in_parse == v, "QPDF: re-entrant parsing detected"
291
        // This happens if QPDFParser::parse tries to resolve an indirect object while it is
292
        // parsing.
293
376k
    );
294
376k
    m->in_parse = v;
295
376k
}
296
297
void
298
Objects::setTrailer(QPDFObjectHandle obj)
299
6.12k
{
300
6.12k
    if (m->trailer) {
301
305
        return;
302
305
    }
303
5.81k
    m->trailer = obj;
304
5.81k
}
305
306
void
307
Objects::reconstruct_xref(QPDFExc& e, bool found_startxref)
308
19.3k
{
309
19.3k
    if (m->reconstructed_xref) {
310
        // Avoid xref reconstruction infinite loops. This is getting very hard to reproduce because
311
        // qpdf is throwing many fewer exceptions while parsing. Most situations are warnings now.
312
165
        throw e;
313
165
    }
314
315
    // If recovery generates more than 1000 warnings, the file is so severely damaged that there
316
    // probably is no point trying to continue.
317
19.1k
    const auto max_warnings = m->warnings.size() + 1000U;
318
3.19M
    auto check_warnings = [this, max_warnings]() {
319
3.19M
        if (m->warnings.size() > max_warnings) {
320
0
            throw damagedPDF("", -1, "too many errors while reconstructing cross-reference table");
321
0
        }
322
3.19M
    };
323
324
19.1k
    m->reconstructed_xref = true;
325
    // We may find more objects, which may contain dangling references.
326
19.1k
    m->fixed_dangling_refs = false;
327
328
19.1k
    warn(damagedPDF("", -1, "file is damaged"));
329
19.1k
    warn(e);
330
19.1k
    warn(damagedPDF("", -1, "Attempting to reconstruct cross-reference table"));
331
332
    // Delete all references to type 1 (uncompressed) objects
333
19.1k
    std::vector<QPDFObjGen> to_delete;
334
81.4k
    for (auto const& iter: m->xref_table) {
335
81.4k
        if (iter.second.getType() == 1) {
336
60.4k
            to_delete.emplace_back(iter.first);
337
60.4k
        }
338
81.4k
    }
339
60.4k
    for (auto const& iter: to_delete) {
340
60.4k
        m->xref_table.erase(iter);
341
60.4k
    }
342
343
19.1k
    std::vector<std::tuple<int, int, qpdf_offset_t>> found_objects;
344
19.1k
    std::vector<qpdf_offset_t> trailers;
345
19.1k
    std::vector<qpdf_offset_t> startxrefs;
346
347
19.1k
    m->file->seek(0, SEEK_END);
348
19.1k
    qpdf_offset_t eof = m->file->tell();
349
19.1k
    m->file->seek(0, SEEK_SET);
350
    // Don't allow very long tokens here during recovery. All the interesting tokens are covered.
351
19.1k
    static size_t const MAX_LEN = 10;
352
3.01M
    while (m->file->tell() < eof) {
353
3.00M
        QPDFTokenizer::Token t1 = m->objects.readToken(*m->file, MAX_LEN);
354
3.00M
        qpdf_offset_t token_start = m->file->tell() - toO(t1.getValue().length());
355
3.00M
        if (t1.isInteger()) {
356
548k
            auto pos = m->file->tell();
357
548k
            auto t2 = m->objects.readToken(*m->file, MAX_LEN);
358
548k
            if (t2.isInteger() && m->objects.readToken(*m->file, MAX_LEN).isWord("obj")) {
359
152k
                int obj = QUtil::string_to_int(t1.getValue().c_str());
360
152k
                int gen = QUtil::string_to_int(t2.getValue().c_str());
361
152k
                if (obj <= m->xref_table_max_id) {
362
151k
                    found_objects.emplace_back(obj, gen, token_start);
363
151k
                } else {
364
1.11k
                    warn(damagedPDF(
365
1.11k
                        "", -1, "ignoring object with impossibly large id " + std::to_string(obj)));
366
1.11k
                }
367
152k
            }
368
548k
            m->file->seek(pos, SEEK_SET);
369
2.45M
        } else if (!m->trailer && t1.isWord("trailer")) {
370
34.5k
            trailers.emplace_back(m->file->tell());
371
2.41M
        } else if (!found_startxref && t1.isWord("startxref")) {
372
19.1k
            startxrefs.emplace_back(m->file->tell());
373
19.1k
        }
374
3.00M
        check_warnings();
375
3.00M
        m->file->findAndSkipNextEOL();
376
3.00M
    }
377
378
19.1k
    if (!found_startxref && !startxrefs.empty() && !found_objects.empty() &&
379
764
        startxrefs.back() > std::get<2>(found_objects.back())) {
380
316
        auto xref_backup{m->xref_table};
381
316
        try {
382
316
            m->file->seek(startxrefs.back(), SEEK_SET);
383
316
            if (auto offset = QUtil::string_to_ll(readToken(*m->file).getValue().data())) {
384
160
                read_xref(offset);
385
386
160
                if (qpdf.getRoot().getKey("/Pages").isDictionary()) {
387
3
                    warn(damagedPDF(
388
3
                        "", -1, "startxref was more than 1024 bytes before end of file"));
389
3
                    m->encp->initialize(qpdf);
390
3
                    m->parsed = true;
391
3
                    m->reconstructed_xref = false;
392
3
                    return;
393
3
                }
394
160
            }
395
316
        } catch (...) {
396
            // ok, bad luck. Do recovery.
397
157
        }
398
313
        m->xref_table = std::move(xref_backup);
399
313
    }
400
401
19.1k
    auto rend = found_objects.rend();
402
170k
    for (auto it = found_objects.rbegin(); it != rend; it++) {
403
151k
        auto [obj, gen, token_start] = *it;
404
151k
        insertXrefEntry(obj, 1, token_start, gen);
405
151k
        check_warnings();
406
151k
    }
407
19.1k
    m->deleted_objects.clear();
408
409
    // Search at most the last 100 trailer candidates. If none of them are valid, odds are this file
410
    // is deliberately broken.
411
19.1k
    int end_index = trailers.size() > 100 ? static_cast<int>(trailers.size()) - 100 : 0;
412
32.9k
    for (auto it = trailers.rbegin(); it != std::prev(trailers.rend(), end_index); it++) {
413
15.6k
        m->file->seek(*it, SEEK_SET);
414
15.6k
        auto t = readTrailer();
415
15.6k
        if (!t.isDictionary()) {
416
            // Oh well.  It was worth a try.
417
13.0k
        } else {
418
2.66k
            if (t.hasKey("/Root")) {
419
1.87k
                m->trailer = t;
420
1.87k
                break;
421
1.87k
            }
422
783
            warn(damagedPDF("trailer", *it, "recovered trailer has no /Root entry"));
423
783
        }
424
13.7k
        check_warnings();
425
13.7k
    }
426
427
19.1k
    if (!m->trailer) {
428
16.6k
        qpdf_offset_t max_offset{0};
429
16.6k
        size_t max_size{0};
430
        // If there are any xref streams, take the last one to appear.
431
77.6k
        for (auto const& iter: m->xref_table) {
432
77.6k
            auto entry = iter.second;
433
77.6k
            if (entry.getType() != 1) {
434
594
                continue;
435
594
            }
436
77.0k
            auto oh = qpdf.getObject(iter.first);
437
77.0k
            try {
438
77.0k
                if (!oh.isStreamOfType("/XRef")) {
439
69.0k
                    continue;
440
69.0k
                }
441
77.0k
            } catch (std::exception&) {
442
2.75k
                continue;
443
2.75k
            }
444
5.16k
            auto offset = entry.getOffset();
445
5.16k
            auto size = oh.getDict().getKey("/Size").getUIntValueAsUInt();
446
5.16k
            if (size > max_size || (size == max_size && offset > max_offset)) {
447
5.11k
                max_offset = offset;
448
5.11k
                setTrailer(oh.getDict());
449
5.11k
            }
450
5.16k
            check_warnings();
451
5.16k
        }
452
16.6k
        if (max_offset > 0) {
453
4.80k
            try {
454
4.80k
                read_xref(max_offset, true);
455
4.80k
            } catch (std::exception&) {
456
2.65k
                warn(damagedPDF(
457
2.65k
                    "", -1, "error decoding candidate xref stream while recovering damaged file"));
458
2.65k
            }
459
4.80k
            QTC::TC("qpdf", "QPDF recover xref stream");
460
4.77k
        }
461
16.6k
    }
462
463
19.1k
    if (!m->trailer || (!m->parsed && !m->trailer.getKey("/Root").isDictionary())) {
464
        // Try to find a Root dictionary. As a quick fix try the one with the highest object id.
465
16.9k
        QPDFObjectHandle root;
466
238k
        for (auto const& iter: m->obj_cache) {
467
238k
            try {
468
238k
                if (QPDFObjectHandle(iter.second.object).isDictionaryOfType("/Catalog")) {
469
7.73k
                    root = iter.second.object;
470
7.73k
                }
471
238k
            } catch (std::exception&) {
472
3.59k
                continue;
473
3.59k
            }
474
238k
        }
475
16.9k
        if (root) {
476
7.43k
            if (!m->trailer) {
477
5.82k
                warn(damagedPDF(
478
5.82k
                    "", -1, "unable to find trailer dictionary while recovering damaged file"));
479
5.82k
                m->trailer = QPDFObjectHandle::newDictionary();
480
5.82k
            }
481
7.43k
            m->trailer.replaceKey("/Root", root);
482
7.43k
        }
483
16.9k
    }
484
485
19.1k
    if (!m->trailer) {
486
        // We could check the last encountered object to see if it was an xref stream.  If so, we
487
        // could try to get the trailer from there.  This may make it possible to recover files with
488
        // bad startxref pointers even when they have object streams.
489
490
6.05k
        throw damagedPDF("", -1, "unable to find trailer dictionary while recovering damaged file");
491
6.05k
    }
492
13.1k
    if (m->xref_table.empty()) {
493
        // We cannot check for an empty xref table in parse because empty tables are valid when
494
        // creating QPDF objects from JSON.
495
252
        throw damagedPDF("", -1, "unable to find objects while recovering damaged file");
496
252
    }
497
12.8k
    check_warnings();
498
12.8k
    if (!m->parsed) {
499
12.6k
        m->parsed = !m->pages.empty();
500
12.6k
        if (!m->parsed) {
501
499
            throw damagedPDF("", -1, "unable to find any pages while recovering damaged file");
502
499
        }
503
12.1k
        check_warnings();
504
12.1k
    }
505
506
    // We could iterate through the objects looking for streams and try to find objects inside of
507
    // them, but it's probably not worth the trouble.  Acrobat can't recover files with any errors
508
    // in an xref stream, and this would be a real long shot anyway.  If we wanted to do anything
509
    // that involved looking at stream contents, we'd also have to call initializeEncryption() here.
510
    // It's safe to call it more than once.
511
12.8k
}
512
513
void
514
Objects::read_xref(qpdf_offset_t xref_offset, bool in_stream_recovery)
515
9.54k
{
516
9.54k
    std::map<int, int> free_table;
517
9.54k
    std::set<qpdf_offset_t> visited;
518
19.7k
    while (xref_offset) {
519
10.3k
        visited.insert(xref_offset);
520
10.3k
        char buf[7];
521
10.3k
        memset(buf, 0, sizeof(buf));
522
10.3k
        m->file->seek(xref_offset, SEEK_SET);
523
        // Some files miss the mark a little with startxref. We could do a better job of searching
524
        // in the neighborhood for something that looks like either an xref table or stream, but the
525
        // simple heuristic of skipping whitespace can help with the xref table case and is harmless
526
        // with the stream case.
527
10.3k
        bool done = false;
528
10.3k
        bool skipped_space = false;
529
25.1k
        while (!done) {
530
14.7k
            char ch;
531
14.7k
            if (1 == m->file->read(&ch, 1)) {
532
13.9k
                if (util::is_space(ch)) {
533
4.60k
                    skipped_space = true;
534
9.34k
                } else {
535
9.34k
                    m->file->unreadCh(ch);
536
9.34k
                    done = true;
537
9.34k
                }
538
13.9k
            } else {
539
840
                QTC::TC("qpdf", "QPDF eof skipping spaces before xref", skipped_space ? 0 : 1);
540
840
                done = true;
541
840
            }
542
14.7k
        }
543
544
10.3k
        m->file->read(buf, sizeof(buf) - 1);
545
        // The PDF spec says xref must be followed by a line terminator, but files exist in the wild
546
        // where it is terminated by arbitrary whitespace.
547
10.3k
        if ((strncmp(buf, "xref", 4) == 0) && util::is_space(buf[4])) {
548
1.39k
            if (skipped_space) {
549
94
                warn(damagedPDF("", -1, "extraneous whitespace seen before xref"));
550
94
            }
551
1.39k
            QTC::TC(
552
1.39k
                "qpdf",
553
1.39k
                "QPDF xref space",
554
1.39k
                ((buf[4] == '\n')       ? 0
555
1.39k
                     : (buf[4] == '\r') ? 1
556
1.00k
                     : (buf[4] == ' ')  ? 2
557
280
                                        : 9999));
558
1.39k
            int skip = 4;
559
            // buf is null-terminated, and util::is_space('\0') is false, so this won't overrun.
560
2.96k
            while (util::is_space(buf[skip])) {
561
1.56k
                ++skip;
562
1.56k
            }
563
1.39k
            xref_offset = read_xrefTable(xref_offset + skip);
564
8.99k
        } else {
565
8.99k
            xref_offset = read_xrefStream(xref_offset, in_stream_recovery);
566
8.99k
        }
567
10.3k
        if (visited.contains(xref_offset)) {
568
197
            throw damagedPDF("", -1, "loop detected following xref tables");
569
197
        }
570
10.3k
    }
571
572
9.34k
    if (!m->trailer) {
573
0
        throw damagedPDF("", -1, "unable to find trailer while reading xref");
574
0
    }
575
9.34k
    int size = m->trailer.getKey("/Size").getIntValueAsInt();
576
9.34k
    int max_obj = 0;
577
9.34k
    if (!m->xref_table.empty()) {
578
2.43k
        max_obj = m->xref_table.rbegin()->first.getObj();
579
2.43k
    }
580
9.34k
    if (!m->deleted_objects.empty()) {
581
1.25k
        max_obj = std::max(max_obj, *(m->deleted_objects.rbegin()));
582
1.25k
    }
583
9.34k
    if (size < 1 || (size - 1) != max_obj) {
584
1.97k
        if (size == (max_obj + 2) && qpdf.getObject(max_obj + 1, 0).isStreamOfType("/XRef")) {
585
1
            warn(damagedPDF(
586
1
                "",
587
1
                -1,
588
1
                "xref entry for the xref stream itself is missing - a common error handled "
589
1
                "correctly by qpdf and most other applications"));
590
1.96k
        } else {
591
1.96k
            warn(damagedPDF(
592
1.96k
                "",
593
1.96k
                -1,
594
1.96k
                ("reported number of objects (" + std::to_string(size) +
595
1.96k
                 ") is not one plus the highest object number (" + std::to_string(max_obj) + ")")));
596
1.96k
        }
597
1.97k
    }
598
599
    // We no longer need the deleted_objects table, so go ahead and clear it out to make sure we
600
    // never depend on its being set.
601
9.34k
    m->deleted_objects.clear();
602
603
    // Make sure we keep only the highest generation for any object.
604
9.34k
    QPDFObjGen last_og{-1, 0};
605
368k
    for (auto const& item: m->xref_table) {
606
368k
        auto id = item.first.getObj();
607
368k
        if (id == last_og.getObj() && id > 0) {
608
3.47k
            qpdf.removeObject(last_og);
609
3.47k
        }
610
368k
        last_og = item.first;
611
368k
    }
612
9.34k
}
613
614
bool
615
Objects::parse_xrefFirst(std::string const& line, int& obj, int& num, int& bytes)
616
7.54k
{
617
    // is_space and is_digit both return false on '\0', so this will not overrun the null-terminated
618
    // buffer.
619
7.54k
    char const* p = line.c_str();
620
7.54k
    char const* start = line.c_str();
621
622
    // Skip zero or more spaces
623
9.62k
    while (util::is_space(*p)) {
624
2.07k
        ++p;
625
2.07k
    }
626
    // Require digit
627
7.54k
    if (!util::is_digit(*p)) {
628
147
        return false;
629
147
    }
630
    // Gather digits
631
7.39k
    std::string obj_str;
632
33.1k
    while (util::is_digit(*p)) {
633
25.7k
        obj_str.append(1, *p++);
634
25.7k
    }
635
    // Require space
636
7.39k
    if (!util::is_space(*p)) {
637
80
        return false;
638
80
    }
639
    // Skip spaces
640
26.1k
    while (util::is_space(*p)) {
641
18.8k
        ++p;
642
18.8k
    }
643
    // Require digit
644
7.31k
    if (!util::is_digit(*p)) {
645
80
        return false;
646
80
    }
647
    // Gather digits
648
7.23k
    std::string num_str;
649
35.3k
    while (util::is_digit(*p)) {
650
28.1k
        num_str.append(1, *p++);
651
28.1k
    }
652
    // Skip any space including line terminators
653
21.9k
    while (util::is_space(*p)) {
654
14.7k
        ++p;
655
14.7k
    }
656
7.23k
    bytes = toI(p - start);
657
7.23k
    obj = QUtil::string_to_int(obj_str.c_str());
658
7.23k
    num = QUtil::string_to_int(num_str.c_str());
659
7.23k
    return true;
660
7.31k
}
661
662
bool
663
Objects::read_bad_xrefEntry(qpdf_offset_t& f1, int& f2, char& type)
664
6.83k
{
665
    // Reposition after initial read attempt and reread.
666
6.83k
    m->file->seek(m->file->getLastOffset(), SEEK_SET);
667
6.83k
    auto line = m->file->readLine(30);
668
669
    // is_space and is_digit both return false on '\0', so this will not overrun the null-terminated
670
    // buffer.
671
6.83k
    char const* p = line.data();
672
673
    // Skip zero or more spaces. There aren't supposed to be any.
674
6.83k
    bool invalid = false;
675
16.2k
    while (util::is_space(*p)) {
676
9.45k
        ++p;
677
9.45k
        invalid = true;
678
9.45k
    }
679
    // Require digit
680
6.83k
    if (!util::is_digit(*p)) {
681
21
        return false;
682
21
    }
683
    // Gather digits
684
6.81k
    std::string f1_str;
685
34.2k
    while (util::is_digit(*p)) {
686
27.4k
        f1_str.append(1, *p++);
687
27.4k
    }
688
    // Require space
689
6.81k
    if (!util::is_space(*p)) {
690
23
        return false;
691
23
    }
692
6.79k
    if (util::is_space(*(p + 1))) {
693
1.66k
        invalid = true;
694
1.66k
    }
695
    // Skip spaces
696
21.5k
    while (util::is_space(*p)) {
697
14.7k
        ++p;
698
14.7k
    }
699
    // Require digit
700
6.79k
    if (!util::is_digit(*p)) {
701
29
        return false;
702
29
    }
703
    // Gather digits
704
6.76k
    std::string f2_str;
705
27.7k
    while (util::is_digit(*p)) {
706
20.9k
        f2_str.append(1, *p++);
707
20.9k
    }
708
    // Require space
709
6.76k
    if (!util::is_space(*p)) {
710
41
        return false;
711
41
    }
712
6.72k
    if (util::is_space(*(p + 1))) {
713
1.22k
        invalid = true;
714
1.22k
    }
715
    // Skip spaces
716
15.6k
    while (util::is_space(*p)) {
717
8.93k
        ++p;
718
8.93k
    }
719
6.72k
    if ((*p == 'f') || (*p == 'n')) {
720
6.62k
        type = *p;
721
6.62k
    } else {
722
101
        return false;
723
101
    }
724
6.62k
    if ((f1_str.length() != 10) || (f2_str.length() != 5)) {
725
6.23k
        invalid = true;
726
6.23k
    }
727
728
6.62k
    if (invalid) {
729
6.25k
        warn(damagedPDF("xref table", "accepting invalid xref table entry"));
730
6.25k
    }
731
732
6.62k
    f1 = QUtil::string_to_ll(f1_str.c_str());
733
6.62k
    f2 = QUtil::string_to_int(f2_str.c_str());
734
735
6.62k
    return true;
736
6.72k
}
737
738
// Optimistically read and parse xref entry. If entry is bad, call read_bad_xrefEntry and return
739
// result.
740
bool
741
Objects::read_xrefEntry(qpdf_offset_t& f1, int& f2, char& type)
742
15.6k
{
743
15.6k
    std::array<char, 21> line;
744
15.6k
    if (m->file->read(line.data(), 20) != 20) {
745
        // C++20: [[unlikely]]
746
172
        return false;
747
172
    }
748
15.5k
    line[20] = '\0';
749
15.5k
    char const* p = line.data();
750
751
15.5k
    int f1_len = 0;
752
15.5k
    int f2_len = 0;
753
754
    // is_space and is_digit both return false on '\0', so this will not overrun the null-terminated
755
    // buffer.
756
757
    // Gather f1 digits. NB No risk of overflow as 9'999'999'999 < max long long.
758
73.9k
    while (*p == '0') {
759
58.4k
        ++f1_len;
760
58.4k
        ++p;
761
58.4k
    }
762
59.2k
    while (util::is_digit(*p) && f1_len++ < 10) {
763
43.6k
        f1 *= 10;
764
43.6k
        f1 += *p++ - '0';
765
43.6k
    }
766
    // Require space
767
15.5k
    if (!util::is_space(*p++)) {
768
        // Entry doesn't start with space or digit.
769
        // C++20: [[unlikely]]
770
65
        return false;
771
65
    }
772
    // Gather digits. NB No risk of overflow as 99'999 < max int.
773
51.3k
    while (*p == '0') {
774
35.9k
        ++f2_len;
775
35.9k
        ++p;
776
35.9k
    }
777
38.8k
    while (util::is_digit(*p) && f2_len++ < 5) {
778
23.3k
        f2 *= 10;
779
23.3k
        f2 += static_cast<int>(*p++ - '0');
780
23.3k
    }
781
15.4k
    if (util::is_space(*p++) && (*p == 'f' || *p == 'n')) {
782
        // C++20: [[likely]]
783
11.9k
        type = *p;
784
        // No test for valid line[19].
785
11.9k
        if (*(++p) && *(++p) && (*p == '\n' || *p == '\r') && f1_len == 10 && f2_len == 5) {
786
            // C++20: [[likely]]
787
8.62k
            return true;
788
8.62k
        }
789
11.9k
    }
790
6.83k
    return read_bad_xrefEntry(f1, f2, type);
791
15.4k
}
792
793
// Read a single cross-reference table section and associated trailer.
794
qpdf_offset_t
795
Objects::read_xrefTable(qpdf_offset_t xref_offset)
796
1.39k
{
797
1.39k
    m->file->seek(xref_offset, SEEK_SET);
798
1.39k
    std::string line;
799
7.57k
    while (true) {
800
7.54k
        line.assign(50, '\0');
801
7.54k
        m->file->read(line.data(), line.size());
802
7.54k
        int obj = 0;
803
7.54k
        int num = 0;
804
7.54k
        int bytes = 0;
805
7.54k
        if (!parse_xrefFirst(line, obj, num, bytes)) {
806
307
            throw damagedPDF("xref table", "xref syntax invalid");
807
307
        }
808
7.23k
        m->file->seek(m->file->getLastOffset() + bytes, SEEK_SET);
809
22.4k
        for (qpdf_offset_t i = obj; i - num < obj; ++i) {
810
15.6k
            if (i == 0) {
811
                // This is needed by checkLinearization()
812
480
                first_xref_item_offset_ = m->file->tell();
813
480
            }
814
            // For xref_table, these will always be small enough to be ints
815
15.6k
            qpdf_offset_t f1 = 0;
816
15.6k
            int f2 = 0;
817
15.6k
            char type = '\0';
818
15.6k
            if (!read_xrefEntry(f1, f2, type)) {
819
452
                throw damagedPDF(
820
452
                    "xref table", "invalid xref entry (obj=" + std::to_string(i) + ")");
821
452
            }
822
15.2k
            if (type == 'f') {
823
5.43k
                insertFreeXrefEntry(QPDFObjGen(toI(i), f2));
824
9.81k
            } else {
825
9.81k
                insertXrefEntry(toI(i), 1, f1, f2);
826
9.81k
            }
827
15.2k
        }
828
6.78k
        qpdf_offset_t pos = m->file->tell();
829
6.78k
        if (readToken(*m->file).isWord("trailer")) {
830
605
            break;
831
6.17k
        } else {
832
6.17k
            m->file->seek(pos, SEEK_SET);
833
6.17k
        }
834
6.78k
    }
835
836
    // Set offset to previous xref table if any
837
639
    QPDFObjectHandle cur_trailer = m->objects.readTrailer();
838
639
    if (!cur_trailer.isDictionary()) {
839
69
        throw damagedPDF("", "expected trailer dictionary");
840
69
    }
841
842
570
    if (!m->trailer) {
843
480
        setTrailer(cur_trailer);
844
845
480
        if (!m->trailer.hasKey("/Size")) {
846
157
            throw damagedPDF("trailer", "trailer dictionary lacks /Size key");
847
157
        }
848
323
        if (!m->trailer.getKey("/Size").isInteger()) {
849
7
            throw damagedPDF("trailer", "/Size key in trailer dictionary is not an integer");
850
7
        }
851
323
    }
852
853
406
    if (cur_trailer.hasKey("/XRefStm")) {
854
29
        if (cf.ignore_xref_streams()) {
855
0
            QTC::TC("qpdf", "QPDF ignoring XRefStm in trailer");
856
29
        } else {
857
29
            if (cur_trailer.getKey("/XRefStm").isInteger()) {
858
                // Read the xref stream but disregard any return value -- we'll use our trailer's
859
                // /Prev key instead of the xref stream's.
860
28
                (void)read_xrefStream(cur_trailer.getKey("/XRefStm").getIntValue());
861
28
            } else {
862
1
                throw damagedPDF("xref stream", xref_offset, "invalid /XRefStm");
863
1
            }
864
29
        }
865
29
    }
866
867
405
    if (cur_trailer.hasKey("/Prev")) {
868
118
        if (!cur_trailer.getKey("/Prev").isInteger()) {
869
1
            throw damagedPDF("trailer", "/Prev key in trailer dictionary is not an integer");
870
1
        }
871
117
        return cur_trailer.getKey("/Prev").getIntValue();
872
118
    }
873
874
287
    return 0;
875
405
}
876
877
// Read a single cross-reference stream.
878
qpdf_offset_t
879
Objects::read_xrefStream(qpdf_offset_t xref_offset, bool in_stream_recovery)
880
8.81k
{
881
8.81k
    if (!cf.ignore_xref_streams()) {
882
8.81k
        QPDFObjectHandle xref_obj;
883
8.81k
        try {
884
8.81k
            m->in_read_xref_stream = true;
885
8.81k
            xref_obj = readObjectAtOffset(xref_offset, "xref stream", true);
886
8.81k
        } catch (QPDFExc&) {
887
            // ignore -- report error below
888
1.73k
        }
889
8.81k
        m->in_read_xref_stream = false;
890
8.77k
        if (xref_obj.isStreamOfType("/XRef")) {
891
6.24k
            return processXRefStream(xref_offset, xref_obj, in_stream_recovery);
892
6.24k
        }
893
8.77k
    }
894
895
2.52k
    throw damagedPDF("", xref_offset, "xref not found");
896
0
    return 0; // unreachable
897
8.81k
}
898
899
// Return the entry size of the xref stream and the processed W array.
900
std::pair<int, std::array<int, 3>>
901
Objects::processXRefW(QPDFObjectHandle& dict, std::function<QPDFExc(std::string_view)> damaged)
902
6.24k
{
903
6.24k
    auto W_obj = dict.getKey("/W");
904
6.24k
    if (!(W_obj.size() >= 3 && W_obj.getArrayItem(0).isInteger() &&
905
6.02k
          W_obj.getArrayItem(1).isInteger() && W_obj.getArrayItem(2).isInteger())) {
906
283
        throw damaged("Cross-reference stream does not have a proper /W key");
907
283
    }
908
909
5.96k
    std::array<int, 3> W;
910
5.96k
    int entry_size = 0;
911
5.96k
    auto w_vector = W_obj.getArrayAsVector();
912
5.96k
    int max_bytes = sizeof(qpdf_offset_t);
913
23.7k
    for (size_t i = 0; i < 3; ++i) {
914
17.8k
        W[i] = w_vector[i].getIntValueAsInt();
915
17.8k
        if (W[i] > max_bytes) {
916
21
            throw damaged("Cross-reference stream's /W contains impossibly large values");
917
21
        }
918
17.7k
        if (W[i] < 0) {
919
48
            throw damaged("Cross-reference stream's /W contains negative values");
920
48
        }
921
17.7k
        entry_size += W[i];
922
17.7k
    }
923
5.89k
    if (entry_size == 0) {
924
5
        throw damaged("Cross-reference stream's /W indicates entry size of 0");
925
5
    }
926
5.89k
    return {entry_size, W};
927
5.89k
}
928
929
// Validate Size key and return the maximum number of entries that the xref stream can contain.
930
int
931
Objects::processXRefSize(
932
    QPDFObjectHandle& dict, int entry_size, std::function<QPDFExc(std::string_view)> damaged)
933
5.89k
{
934
    // Number of entries is limited by the highest possible object id and stream size.
935
5.89k
    auto max_num_entries = std::numeric_limits<int>::max();
936
5.89k
    if (max_num_entries > (std::numeric_limits<qpdf_offset_t>::max() / entry_size)) {
937
0
        max_num_entries = toI(std::numeric_limits<qpdf_offset_t>::max() / entry_size);
938
0
    }
939
940
5.89k
    auto Size_obj = dict.getKey("/Size");
941
5.89k
    long long size;
942
5.89k
    if (!dict.getKey("/Size").getValueAsInt(size)) {
943
72
        throw damaged("Cross-reference stream does not have a proper /Size key");
944
5.81k
    } else if (size < 0) {
945
47
        throw damaged("Cross-reference stream has a negative /Size key");
946
5.77k
    } else if (size >= max_num_entries) {
947
68
        throw damaged("Cross-reference stream has an impossibly large /Size key");
948
68
    }
949
    // We are not validating that Size <= (Size key of parent xref / trailer).
950
5.70k
    return max_num_entries;
951
5.89k
}
952
953
// Return the number of entries of the xref stream and the processed Index array.
954
std::pair<int, std::vector<std::pair<int, int>>>
955
Objects::processXRefIndex(
956
    QPDFObjectHandle& dict, int max_num_entries, std::function<QPDFExc(std::string_view)> damaged)
957
5.70k
{
958
5.70k
    auto size = dict.getKey("/Size").getIntValueAsInt();
959
5.70k
    auto Index_obj = dict.getKey("/Index");
960
961
5.70k
    if (Index_obj.isArray()) {
962
1.13k
        std::vector<std::pair<int, int>> indx;
963
1.13k
        int num_entries = 0;
964
1.13k
        auto index_vec = Index_obj.getArrayAsVector();
965
1.13k
        if ((index_vec.size() % 2) || index_vec.size() < 2) {
966
17
            throw damaged("Cross-reference stream's /Index has an invalid number of values");
967
17
        }
968
969
1.11k
        int i = 0;
970
1.11k
        long long first = 0;
971
5.79k
        for (auto& val: index_vec) {
972
5.79k
            if (val.isInteger()) {
973
5.77k
                if (i % 2) {
974
2.84k
                    auto count = val.getIntValue();
975
2.84k
                    if (count <= 0) {
976
55
                        throw damaged(
977
55
                            "Cross-reference stream section claims to contain " +
978
55
                            std::to_string(count) + " entries");
979
55
                    }
980
                    // We are guarding against the possibility of num_entries * entry_size
981
                    // overflowing. We are not checking that entries are in ascending order as
982
                    // required by the spec, which probably should generate a warning. We are also
983
                    // not checking that for each subsection first object number + number of entries
984
                    // <= /Size. The spec requires us to ignore object number > /Size.
985
2.78k
                    if (first > (max_num_entries - count) ||
986
2.74k
                        count > (max_num_entries - num_entries)) {
987
67
                        throw damaged(
988
67
                            "Cross-reference stream claims to contain too many entries: " +
989
67
                            std::to_string(first) + " " + std::to_string(max_num_entries) + " " +
990
67
                            std::to_string(num_entries));
991
67
                    }
992
2.72k
                    indx.emplace_back(static_cast<int>(first), static_cast<int>(count));
993
2.72k
                    num_entries += static_cast<int>(count);
994
2.93k
                } else {
995
2.93k
                    first = val.getIntValue();
996
2.93k
                    if (first < 0) {
997
38
                        throw damaged(
998
38
                            "Cross-reference stream's /Index contains a negative object id");
999
2.89k
                    } else if (first > max_num_entries) {
1000
43
                        throw damaged(
1001
43
                            "Cross-reference stream's /Index contains an impossibly "
1002
43
                            "large object id");
1003
43
                    }
1004
2.93k
                }
1005
5.77k
            } else {
1006
16
                throw damaged(
1007
16
                    "Cross-reference stream's /Index's item " + std::to_string(i) +
1008
16
                    " is not an integer");
1009
16
            }
1010
5.57k
            i++;
1011
5.57k
        }
1012
894
        QTC::TC("qpdf", "QPDF xref /Index is array", index_vec.size() == 2 ? 0 : 1);
1013
894
        return {num_entries, indx};
1014
4.57k
    } else if (Index_obj.null()) {
1015
4.56k
        return {size, {{0, size}}};
1016
4.56k
    } else {
1017
4
        throw damaged("Cross-reference stream does not have a proper /Index key");
1018
4
    }
1019
5.70k
}
1020
1021
qpdf_offset_t
1022
Objects::processXRefStream(
1023
    qpdf_offset_t xref_offset, QPDFObjectHandle& xref_obj, bool in_stream_recovery)
1024
6.24k
{
1025
6.24k
    auto damaged = [this, xref_offset](std::string_view msg) -> QPDFExc {
1026
4.04k
        return damagedPDF("xref stream", xref_offset, msg.data());
1027
4.04k
    };
1028
1029
6.24k
    auto dict = xref_obj.getDict();
1030
1031
6.24k
    auto [entry_size, W] = processXRefW(dict, damaged);
1032
6.24k
    int max_num_entries = processXRefSize(dict, entry_size, damaged);
1033
6.24k
    auto [num_entries, indx] = processXRefIndex(dict, max_num_entries, damaged);
1034
1035
6.24k
    std::shared_ptr<Buffer> bp = xref_obj.getStreamData(qpdf_dl_specialized);
1036
6.24k
    size_t actual_size = bp->getSize();
1037
6.24k
    auto expected_size = toS(entry_size) * toS(num_entries);
1038
1039
6.24k
    if (expected_size != actual_size) {
1040
3.26k
        QPDFExc x = damaged(
1041
3.26k
            "Cross-reference stream data has the wrong size; expected = " +
1042
3.26k
            std::to_string(expected_size) + "; actual = " + std::to_string(actual_size));
1043
3.26k
        if (expected_size > actual_size) {
1044
489
            throw x;
1045
2.77k
        } else {
1046
2.77k
            warn(x);
1047
2.77k
        }
1048
3.26k
    }
1049
1050
5.76k
    bool saw_first_compressed_object = false;
1051
1052
    // Actual size vs. expected size check above ensures that we will not overflow any buffers here.
1053
    // We know that entry_size * num_entries is less or equal to the size of the buffer.
1054
5.76k
    auto p = bp->getBuffer();
1055
5.76k
    for (auto [obj, sec_entries]: indx) {
1056
        // Process a subsection.
1057
958k
        for (int i = 0; i < sec_entries; ++i) {
1058
            // Read this entry
1059
953k
            std::array<qpdf_offset_t, 3> fields{};
1060
953k
            if (W[0] == 0) {
1061
94.1k
                fields[0] = 1;
1062
94.1k
            }
1063
3.81M
            for (size_t j = 0; j < 3; ++j) {
1064
6.85M
                for (int k = 0; k < W[j]; ++k) {
1065
3.99M
                    fields[j] <<= 8;
1066
3.99M
                    fields[j] |= *p++;
1067
3.99M
                }
1068
2.86M
            }
1069
1070
            // Get the generation number.  The generation number is 0 unless this is an uncompressed
1071
            // object record, in which case the generation number appears as the third field.
1072
953k
            if (saw_first_compressed_object) {
1073
801k
                if (fields[0] != 2) {
1074
352k
                    uncompressed_after_compressed_ = true;
1075
352k
                }
1076
801k
            } else if (fields[0] == 2) {
1077
2.23k
                saw_first_compressed_object = true;
1078
2.23k
            }
1079
953k
            if (obj == 0) {
1080
                // This is needed by checkLinearization()
1081
2.84k
                first_xref_item_offset_ = xref_offset;
1082
951k
            } else if (fields[0] == 0) {
1083
                // Ignore fields[2], which we don't care about in this case. This works around the
1084
                // issue of some PDF files that put invalid values, like -1, here for deleted
1085
                // objects.
1086
174k
                insertFreeXrefEntry(QPDFObjGen(obj, 0));
1087
776k
            } else {
1088
776k
                auto typ = toI(fields[0]);
1089
776k
                if (!in_stream_recovery || typ == 2) {
1090
                    // If we are in xref stream recovery all actual uncompressed objects have
1091
                    // already been inserted into the xref table. Avoid adding junk data into the
1092
                    // xref table.
1093
607k
                    insertXrefEntry(obj, toI(fields[0]), fields[1], toI(fields[2]));
1094
607k
                }
1095
776k
            }
1096
953k
            ++obj;
1097
953k
        }
1098
4.39k
    }
1099
1100
5.76k
    if (!m->trailer) {
1101
528
        setTrailer(dict);
1102
528
    }
1103
1104
5.76k
    if (dict.hasKey("/Prev")) {
1105
982
        if (!dict.getKey("/Prev").isInteger()) {
1106
39
            throw damagedPDF(
1107
39
                "xref stream", "/Prev key in xref stream dictionary is not an integer");
1108
39
        }
1109
943
        return dict.getKey("/Prev").getIntValue();
1110
4.77k
    } else {
1111
4.77k
        return 0;
1112
4.77k
    }
1113
5.76k
}
1114
1115
void
1116
Objects::insertXrefEntry(int obj, int f0, qpdf_offset_t f1, int f2)
1117
768k
{
1118
    // Populate the xref table in such a way that the first reference to an object that we see,
1119
    // which is the one in the latest xref table in which it appears, is the one that gets stored.
1120
    // This works because we are reading more recent appends before older ones.
1121
1122
    // If there is already an entry for this object and generation in the table, it means that a
1123
    // later xref table has registered this object.  Disregard this one.
1124
768k
    int new_gen = f0 == 2 ? 0 : f2;
1125
1126
768k
    if (!(f0 == 1 || f0 == 2)) {
1127
20.2k
        return;
1128
20.2k
    }
1129
1130
748k
    if (!(obj > 0 && obj <= m->xref_table_max_id && 0 <= f2 && new_gen < 65535)) {
1131
        // We are ignoring invalid objgens. Most will arrive here from xref reconstruction. There
1132
        // is probably no point having another warning but we could count invalid items in order to
1133
        // decide when to give up.
1134
        // ignore impossibly large object ids or object ids > Size.
1135
143k
        return;
1136
143k
    }
1137
1138
605k
    if (m->deleted_objects.contains(obj)) {
1139
1.64k
        return;
1140
1.64k
    }
1141
1142
603k
    if (f0 == 2) {
1143
374k
        if (f1 == obj) {
1144
558
            warn(
1145
558
                damagedPDF("xref stream", "self-referential object stream " + std::to_string(obj)));
1146
558
            return;
1147
558
        }
1148
374k
        if (f1 > m->xref_table_max_id) {
1149
            // ignore impossibly large object stream ids
1150
9.81k
            warn(damagedPDF(
1151
9.81k
                "xref stream",
1152
9.81k
                "object stream id " + std::to_string(f1) + " for object " + std::to_string(obj) +
1153
9.81k
                    " is impossibly large"));
1154
9.81k
            return;
1155
9.81k
        }
1156
374k
    }
1157
1158
593k
    auto [iter, created] = m->xref_table.try_emplace(QPDFObjGen(obj, (f0 == 2 ? 0 : f2)));
1159
593k
    if (!created) {
1160
53.0k
        return;
1161
53.0k
    }
1162
1163
540k
    switch (f0) {
1164
184k
    case 1:
1165
        // f2 is generation
1166
184k
        QTC::TC("qpdf", "QPDF xref gen > 0", ((f2 > 0) ? 1 : 0));
1167
184k
        iter->second = QPDFXRefEntry(f1);
1168
184k
        break;
1169
1170
356k
    case 2:
1171
356k
        iter->second = QPDFXRefEntry(toI(f1), f2);
1172
356k
        break;
1173
1174
0
    default:
1175
0
        throw damagedPDF("xref stream", "unknown xref stream entry type " + std::to_string(f0));
1176
0
        break;
1177
540k
    }
1178
540k
}
1179
1180
void
1181
Objects::insertFreeXrefEntry(QPDFObjGen og)
1182
180k
{
1183
180k
    if (!m->xref_table.contains(og) && og.getObj() <= m->xref_table_max_id) {
1184
77.8k
        m->deleted_objects.insert(og.getObj());
1185
77.8k
    }
1186
180k
}
1187
1188
void
1189
QPDF::showXRefTable()
1190
0
{
1191
0
    auto& cout = *m->cf.log()->getInfo();
1192
0
    for (auto const& iter: m->xref_table) {
1193
0
        QPDFObjGen const& og = iter.first;
1194
0
        QPDFXRefEntry const& entry = iter.second;
1195
0
        cout << og.unparse('/') << ": ";
1196
0
        switch (entry.getType()) {
1197
0
        case 1:
1198
0
            cout << "uncompressed; offset = " << entry.getOffset();
1199
0
            break;
1200
1201
0
        case 2:
1202
0
            *m->cf.log()->getInfo() << "compressed; stream = " << entry.getObjStreamNumber()
1203
0
                                    << ", index = " << entry.getObjStreamIndex();
1204
0
            break;
1205
1206
0
        default:
1207
0
            throw std::logic_error("unknown cross-reference table type while showing xref_table");
1208
0
            break;
1209
0
        }
1210
0
        m->cf.log()->info("\n");
1211
0
    }
1212
0
}
1213
1214
// Resolve all objects in the xref table. If this triggers a xref table reconstruction abort and
1215
// return false. Otherwise return true.
1216
bool
1217
Objects::resolveXRefTable()
1218
8.70k
{
1219
8.70k
    bool may_change = !m->reconstructed_xref;
1220
339k
    for (auto& iter: m->xref_table) {
1221
339k
        if (isUnresolved(iter.first)) {
1222
220k
            resolve(iter.first);
1223
220k
            if (may_change && m->reconstructed_xref) {
1224
41
                return false;
1225
41
            }
1226
220k
        }
1227
339k
    }
1228
8.66k
    return true;
1229
8.70k
}
1230
1231
// Ensure all objects in the pdf file, including those in indirect references, appear in the object
1232
// cache.
1233
void
1234
QPDF::fixDanglingReferences(bool force)
1235
20.3k
{
1236
20.3k
    if (m->fixed_dangling_refs) {
1237
11.7k
        return;
1238
11.7k
    }
1239
8.66k
    if (!m->objects.resolveXRefTable()) {
1240
41
        m->objects.resolveXRefTable();
1241
41
    }
1242
8.66k
    m->fixed_dangling_refs = true;
1243
8.66k
}
1244
1245
size_t
1246
QPDF::getObjectCount()
1247
12.1k
{
1248
    // This method returns the next available indirect object number. makeIndirectObject uses it for
1249
    // this purpose. After fixDanglingReferences is called, all objects in the xref table will also
1250
    // be in obj_cache.
1251
12.1k
    fixDanglingReferences();
1252
12.1k
    QPDFObjGen og;
1253
12.1k
    if (!m->obj_cache.empty()) {
1254
12.0k
        og = (*(m->obj_cache.rbegin())).first;
1255
12.0k
    }
1256
12.1k
    return QIntC::to_size(og.getObj());
1257
12.1k
}
1258
1259
std::vector<QPDFObjectHandle>
1260
QPDF::getAllObjects()
1261
0
{
1262
    // After fixDanglingReferences is called, all objects are in the object cache.
1263
0
    fixDanglingReferences();
1264
0
    std::vector<QPDFObjectHandle> result;
1265
0
    for (auto const& iter: m->obj_cache) {
1266
0
        result.emplace_back(m->objects.newIndirect(iter.first, iter.second.object));
1267
0
    }
1268
0
    return result;
1269
0
}
1270
1271
void
1272
Objects::setLastObjectDescription(std::string const& description, QPDFObjGen og)
1273
241k
{
1274
241k
    m->last_object_description.clear();
1275
241k
    if (!description.empty()) {
1276
7.10k
        m->last_object_description += description;
1277
7.10k
        if (og.isIndirect()) {
1278
7.10k
            m->last_object_description += ": ";
1279
7.10k
        }
1280
7.10k
    }
1281
241k
    if (og.isIndirect()) {
1282
241k
        m->last_object_description += "object " + og.unparse(' ');
1283
241k
    }
1284
241k
}
1285
1286
QPDFObjectHandle
1287
Objects::readTrailer()
1288
16.2k
{
1289
16.2k
    qpdf_offset_t offset = m->file->tell();
1290
16.2k
    auto object =
1291
16.2k
        Parser::parse(*m->file, "trailer", m->tokenizer, nullptr, qpdf, m->reconstructed_xref);
1292
16.2k
    if (object.isDictionary() && m->objects.readToken(*m->file).isWord("stream")) {
1293
183
        warn(damagedPDF("trailer", m->file->tell(), "stream keyword found in trailer"));
1294
183
    }
1295
    // Override last_offset so that it points to the beginning of the object we just read
1296
16.2k
    m->file->setLastOffset(offset);
1297
16.2k
    return object;
1298
16.2k
}
1299
1300
QPDFObjectHandle
1301
Objects::readObject(std::string const& description, QPDFObjGen og)
1302
124k
{
1303
124k
    setLastObjectDescription(description, og);
1304
124k
    qpdf_offset_t offset = m->file->tell();
1305
1306
124k
    StringDecrypter decrypter{&qpdf, og};
1307
124k
    StringDecrypter* decrypter_ptr = m->encp->encrypted ? &decrypter : nullptr;
1308
124k
    auto object = Parser::parse(
1309
124k
        *m->file,
1310
124k
        m->last_object_description,
1311
124k
        m->tokenizer,
1312
124k
        decrypter_ptr,
1313
124k
        qpdf,
1314
124k
        m->reconstructed_xref || m->in_read_xref_stream);
1315
124k
    if (!object) {
1316
9.16k
        return {};
1317
9.16k
    }
1318
115k
    auto token = readToken(*m->file);
1319
115k
    if (object.isDictionary() && token.isWord("stream")) {
1320
51.2k
        readStream(object, og, offset);
1321
51.2k
        token = readToken(*m->file);
1322
51.2k
    }
1323
115k
    if (!token.isWord("endobj")) {
1324
25.5k
        warn(damagedPDF("expected endobj"));
1325
25.5k
    }
1326
115k
    return object;
1327
124k
}
1328
1329
// After reading stream dictionary and stream keyword, read rest of stream.
1330
void
1331
Objects::readStream(QPDFObjectHandle& object, QPDFObjGen og, qpdf_offset_t offset)
1332
51.2k
{
1333
51.2k
    validateStreamLineEnd(object, og, offset);
1334
1335
    // Must get offset before accessing any additional objects since resolving a previously
1336
    // unresolved indirect object will change file position.
1337
51.2k
    qpdf_offset_t stream_offset = m->file->tell();
1338
51.2k
    size_t length = 0;
1339
1340
51.2k
    try {
1341
51.2k
        auto length_obj = object.getKey("/Length");
1342
1343
51.2k
        if (!length_obj.isInteger()) {
1344
15.4k
            if (length_obj.null()) {
1345
15.1k
                throw damagedPDF(offset, "stream dictionary lacks /Length key");
1346
15.1k
            }
1347
244
            throw damagedPDF(offset, "/Length key in stream dictionary is not an integer");
1348
15.4k
        }
1349
1350
35.8k
        length = toS(length_obj.getUIntValue());
1351
        // Seek in two steps to avoid potential integer overflow
1352
35.8k
        m->file->seek(stream_offset, SEEK_SET);
1353
35.8k
        m->file->seek(toO(length), SEEK_CUR);
1354
35.8k
        if (!readToken(*m->file).isWord("endstream")) {
1355
8.60k
            throw damagedPDF("expected endstream");
1356
8.60k
        }
1357
35.8k
    } catch (QPDFExc& e) {
1358
30.9k
        if (!cf.surpress_recovery()) {
1359
30.9k
            warn(e);
1360
30.9k
            length = recoverStreamLength(m->file, og, stream_offset);
1361
30.9k
        } else {
1362
0
            throw;
1363
0
        }
1364
30.9k
    }
1365
42.9k
    object = QPDFObjectHandle(qpdf::Stream(qpdf, og, object, stream_offset, length));
1366
42.9k
}
1367
1368
void
1369
Objects::validateStreamLineEnd(QPDFObjectHandle& object, QPDFObjGen og, qpdf_offset_t offset)
1370
51.2k
{
1371
    // The PDF specification states that the word "stream" should be followed by either a carriage
1372
    // return and a newline or by a newline alone.  It specifically disallowed following it by a
1373
    // carriage return alone since, in that case, there would be no way to tell whether the NL in a
1374
    // CR NL sequence was part of the stream data.  However, some readers, including Adobe reader,
1375
    // accept a carriage return by itself when followed by a non-newline character, so that's what
1376
    // we do here. We have also seen files that have extraneous whitespace between the stream
1377
    // keyword and the newline.
1378
56.5k
    while (true) {
1379
56.4k
        char ch;
1380
56.4k
        if (m->file->read(&ch, 1) == 0) {
1381
            // A premature EOF here will result in some other problem that will get reported at
1382
            // another time.
1383
126
            return;
1384
126
        }
1385
56.3k
        if (ch == '\n') {
1386
            // ready to read stream data
1387
29.5k
            return;
1388
29.5k
        }
1389
26.7k
        if (ch == '\r') {
1390
            // Read another character
1391
17.5k
            if (m->file->read(&ch, 1) != 0) {
1392
17.5k
                if (ch == '\n') {
1393
                    // Ready to read stream data
1394
16.6k
                    QTC::TC("qpdf", "QPDF stream with CRNL");
1395
16.6k
                } else {
1396
                    // Treat the \r by itself as the whitespace after endstream and start reading
1397
                    // stream data in spite of not having seen a newline.
1398
864
                    m->file->unreadCh(ch);
1399
864
                    warn(damagedPDF(
1400
864
                        m->file->tell(), "stream keyword followed by carriage return only"));
1401
864
                }
1402
17.5k
            }
1403
17.5k
            return;
1404
17.5k
        }
1405
9.19k
        if (!util::is_space(ch)) {
1406
3.90k
            m->file->unreadCh(ch);
1407
3.90k
            warn(damagedPDF(
1408
3.90k
                m->file->tell(), "stream keyword not followed by proper line terminator"));
1409
3.90k
            return;
1410
3.90k
        }
1411
5.29k
        warn(damagedPDF(m->file->tell(), "stream keyword followed by extraneous whitespace"));
1412
5.29k
    }
1413
51.2k
}
1414
1415
bool
1416
Objects::findEndstream()
1417
32.9k
{
1418
    // Find endstream or endobj. Position the input at that token.
1419
32.9k
    auto t = readToken(*m->file, 20);
1420
32.9k
    if (t.isWord("endobj") || t.isWord("endstream")) {
1421
22.1k
        m->file->seek(m->file->getLastOffset(), SEEK_SET);
1422
22.1k
        return true;
1423
22.1k
    }
1424
10.8k
    return false;
1425
32.9k
}
1426
1427
size_t
1428
Objects::recoverStreamLength(
1429
    std::shared_ptr<InputSource> input, QPDFObjGen og, qpdf_offset_t stream_offset)
1430
22.8k
{
1431
    // Try to reconstruct stream length by looking for endstream or endobj
1432
22.8k
    warn(damagedPDF(*input, stream_offset, "attempting to recover stream length"));
1433
1434
22.8k
    PatternFinder ef(*this, &Objects::findEndstream);
1435
22.8k
    size_t length = 0;
1436
22.8k
    if (m->file->findFirst("end", stream_offset, 0, ef)) {
1437
22.1k
        length = toS(m->file->tell() - stream_offset);
1438
        // Reread endstream but, if it was endobj, don't skip that.
1439
22.1k
        QPDFTokenizer::Token t = readToken(*m->file);
1440
22.1k
        if (t.getValue() == "endobj") {
1441
12.1k
            m->file->seek(m->file->getLastOffset(), SEEK_SET);
1442
12.1k
        }
1443
22.1k
    }
1444
1445
22.8k
    if (length) {
1446
21.8k
        auto end = stream_offset + toO(length);
1447
21.8k
        qpdf_offset_t found_offset = 0;
1448
21.8k
        QPDFObjGen found_og;
1449
1450
        // Make sure this is inside this object
1451
654k
        for (auto const& [current_og, entry]: m->xref_table) {
1452
654k
            if (entry.getType() == 1) {
1453
594k
                qpdf_offset_t obj_offset = entry.getOffset();
1454
594k
                if (found_offset < obj_offset && obj_offset < end) {
1455
141k
                    found_offset = obj_offset;
1456
141k
                    found_og = current_og;
1457
141k
                }
1458
594k
            }
1459
654k
        }
1460
21.8k
        if (!found_offset || found_og == og) {
1461
            // If we are trying to recover an XRef stream the xref table will not contain and
1462
            // won't contain any entries, therefore we cannot check the found length. Otherwise we
1463
            // found endstream\nendobj within the space allowed for this object, so we're probably
1464
            // in good shape.
1465
20.2k
        } else {
1466
1.64k
            length = 0;
1467
1.64k
        }
1468
21.8k
    }
1469
1470
22.8k
    if (length == 0) {
1471
2.61k
        warn(damagedPDF(
1472
2.61k
            *input, stream_offset, "unable to recover stream data; treating stream as empty"));
1473
20.2k
    } else {
1474
20.2k
        warn(damagedPDF(
1475
20.2k
            *input, stream_offset, "recovered stream length: " + std::to_string(length)));
1476
20.2k
    }
1477
1478
22.8k
    return length;
1479
22.8k
}
1480
1481
QPDFTokenizer::Token
1482
Objects::readToken(InputSource& input, size_t max_len)
1483
4.70M
{
1484
4.70M
    return m->tokenizer.readToken(input, m->last_object_description, true, max_len);
1485
4.70M
}
1486
1487
QPDFObjGen
1488
Objects::read_object_start(qpdf_offset_t offset)
1489
126k
{
1490
126k
    m->file->seek(offset, SEEK_SET);
1491
126k
    QPDFTokenizer::Token tobjid = readToken(*m->file);
1492
126k
    bool objidok = tobjid.isInteger();
1493
126k
    if (!objidok) {
1494
1.70k
        throw damagedPDF(offset, "expected n n obj");
1495
1.70k
    }
1496
124k
    QPDFTokenizer::Token tgen = readToken(*m->file);
1497
124k
    bool genok = tgen.isInteger();
1498
124k
    if (!genok) {
1499
86
        throw damagedPDF(offset, "expected n n obj");
1500
86
    }
1501
124k
    QPDFTokenizer::Token tobj = readToken(*m->file);
1502
1503
124k
    bool objok = tobj.isWord("obj");
1504
1505
124k
    if (!objok) {
1506
132
        throw damagedPDF(offset, "expected n n obj");
1507
132
    }
1508
124k
    int objid = QUtil::string_to_int(tobjid.getValue().c_str());
1509
124k
    int generation = QUtil::string_to_int(tgen.getValue().c_str());
1510
124k
    if (objid == 0) {
1511
9
        throw damagedPDF(offset, "object with ID 0");
1512
9
    }
1513
124k
    return {objid, generation};
1514
124k
}
1515
1516
void
1517
Objects::readObjectAtOffset(
1518
    bool try_recovery, qpdf_offset_t offset, std::string const& description, QPDFObjGen exp_og)
1519
117k
{
1520
117k
    QPDFObjGen og;
1521
117k
    setLastObjectDescription(description, exp_og);
1522
1523
117k
    if (cf.surpress_recovery()) {
1524
0
        try_recovery = false;
1525
0
    }
1526
1527
    // Special case: if offset is 0, just return null.  Some PDF writers, in particular
1528
    // "Mac OS X 10.7.5 Quartz PDFContext", may store deleted objects in the xref table as
1529
    // "0000000000 00000 n", which is not correct, but it won't hurt anything for us to ignore
1530
    // these.
1531
117k
    if (offset == 0) {
1532
135
        warn(damagedPDF(
1533
135
            -1,
1534
135
            "object has offset 0 - a common error handled correctly by qpdf and most other "
1535
135
            "applications"));
1536
135
        return;
1537
135
    }
1538
1539
117k
    try {
1540
117k
        og = read_object_start(offset);
1541
117k
        if (exp_og != og) {
1542
29
            QPDFExc e = damagedPDF(offset, "expected " + exp_og.unparse(' ') + " obj");
1543
29
            if (try_recovery) {
1544
                // Will be retried below
1545
29
                throw e;
1546
29
            } else {
1547
                // We can try reading the object anyway even if the ID doesn't match.
1548
0
                warn(e);
1549
0
            }
1550
29
        }
1551
117k
    } catch (QPDFExc& e) {
1552
294
        if (!try_recovery) {
1553
0
            throw;
1554
0
        }
1555
        // Try again after reconstructing xref table
1556
294
        reconstruct_xref(e);
1557
294
        if (m->xref_table.contains(exp_og) && m->xref_table[exp_og].getType() == 1) {
1558
39
            qpdf_offset_t new_offset = m->xref_table[exp_og].getOffset();
1559
39
            readObjectAtOffset(false, new_offset, description, exp_og);
1560
39
            return;
1561
39
        }
1562
255
        warn(damagedPDF(
1563
255
            "",
1564
255
            -1,
1565
255
            ("object " + exp_og.unparse(' ') +
1566
255
             " not found in file after regenerating cross reference table")));
1567
255
        return;
1568
294
    }
1569
1570
117k
    if (auto oh = readObject(description, og)) {
1571
        // Determine the end offset of this object before and after white space.  We use these
1572
        // numbers to validate linearization hint tables.  Offsets and lengths of objects may imply
1573
        // the end of an object to be anywhere between these values.
1574
95.8k
        qpdf_offset_t end_before_space = m->file->tell();
1575
1576
        // skip over spaces
1577
214k
        while (true) {
1578
214k
            char ch;
1579
214k
            if (!m->file->read(&ch, 1)) {
1580
802
                throw damagedPDF(m->file->tell(), "EOF after endobj");
1581
802
            }
1582
213k
            if (!isspace(static_cast<unsigned char>(ch))) {
1583
95.0k
                m->file->seek(-1, SEEK_CUR);
1584
95.0k
                break;
1585
95.0k
            }
1586
213k
        }
1587
95.0k
        m->objects.updateCache(og, oh.obj_sp(), end_before_space, m->file->tell());
1588
95.0k
    }
1589
117k
}
1590
1591
QPDFObjectHandle
1592
Objects::readObjectAtOffset(
1593
    qpdf_offset_t offset, std::string const& description, bool skip_cache_if_in_xref)
1594
8.81k
{
1595
8.81k
    auto og = read_object_start(offset);
1596
8.81k
    auto oh = readObject(description, og);
1597
1598
8.81k
    if (!oh || !m->objects.isUnresolved(og)) {
1599
5.06k
        return oh;
1600
5.06k
    }
1601
1602
3.75k
    if (skip_cache_if_in_xref && m->xref_table.contains(og)) {
1603
        // In the special case of the xref stream and linearization hint tables, the offset comes
1604
        // from another source. For the specific case of xref streams, the xref stream is read and
1605
        // loaded into the object cache very early in parsing. Ordinarily, when a file is updated by
1606
        // appending, items inserted into the xref table in later updates take precedence over
1607
        // earlier items. In the special case of reusing the object number previously used as the
1608
        // xref stream, we have the following order of events:
1609
        //
1610
        // * reused object gets loaded into the xref table
1611
        // * old object is read here while reading xref streams
1612
        // * original xref entry is ignored (since already in xref table)
1613
        //
1614
        // It is the second step that causes a problem. Even though the xref table is correct in
1615
        // this case, the old object is already in the cache and so effectively prevails over the
1616
        // reused object. To work around this issue, we have a special case for the xref stream (via
1617
        // the skip_cache_if_in_xref): if the object is already in the xref stream, don't cache what
1618
        // we read here.
1619
        //
1620
        // It is likely that the same bug may exist for linearization hint tables, but the existing
1621
        // code uses end_before_space and end_after_space from the cache, so fixing that would
1622
        // require more significant rework. The chances of a linearization hint stream being reused
1623
        // seems smaller because the xref stream is probably the highest object in the file and the
1624
        // linearization hint stream would be some random place in the middle, so I'm leaving that
1625
        // bug unfixed for now. If the bug were to be fixed, we could use !check_og in place of
1626
        // skip_cache_if_in_xref.
1627
13
        QTC::TC("qpdf", "QPDF skipping cache for known unchecked object");
1628
13
        return oh;
1629
13
    }
1630
1631
    // Determine the end offset of this object before and after white space.  We use these
1632
    // numbers to validate linearization hint tables.  Offsets and lengths of objects may imply
1633
    // the end of an object to be anywhere between these values.
1634
3.74k
    qpdf_offset_t end_before_space = m->file->tell();
1635
1636
    // skip over spaces
1637
6.07k
    while (true) {
1638
4.34k
        char ch;
1639
4.34k
        if (!m->file->read(&ch, 1)) {
1640
53
            throw damagedPDF(m->file->tell(), "EOF after endobj");
1641
53
        }
1642
4.29k
        if (!isspace(static_cast<unsigned char>(ch))) {
1643
1.96k
            m->file->seek(-1, SEEK_CUR);
1644
1.96k
            break;
1645
1.96k
        }
1646
4.29k
    }
1647
3.69k
    m->objects.updateCache(og, oh.obj_sp(), end_before_space, m->file->tell());
1648
1649
3.69k
    return oh;
1650
3.74k
}
1651
1652
std::shared_ptr<QPDFObject> const&
1653
Objects::resolve(QPDFObjGen og)
1654
473k
{
1655
473k
    if (!isUnresolved(og)) {
1656
0
        return m->obj_cache[og].object;
1657
0
    }
1658
1659
473k
    if (m->resolving.contains(og)) {
1660
        // This can happen if an object references itself directly or indirectly in some key that
1661
        // has to be resolved during object parsing, such as stream length.
1662
98
        warn(damagedPDF("", "loop detected resolving object " + og.unparse(' ')));
1663
98
        updateCache(og, QPDFObject::create<QPDF_Null>(), -1, -1);
1664
98
        return m->obj_cache[og].object;
1665
98
    }
1666
473k
    ResolveRecorder rr(qpdf, og);
1667
1668
473k
    if (m->xref_table.contains(og)) {
1669
356k
        QPDFXRefEntry const& entry = m->xref_table[og];
1670
356k
        try {
1671
356k
            switch (entry.getType()) {
1672
117k
            case 1:
1673
                // Object stored in cache by readObjectAtOffset
1674
117k
                readObjectAtOffset(true, entry.getOffset(), "", og);
1675
117k
                break;
1676
1677
238k
            case 2:
1678
238k
                resolveObjectsInStream(entry.getObjStreamNumber());
1679
238k
                break;
1680
1681
3
            default:
1682
3
                throw damagedPDF(
1683
3
                    "", -1, ("object " + og.unparse('/') + " has unexpected xref entry type"));
1684
356k
            }
1685
356k
        } catch (QPDFExc& e) {
1686
34.7k
            warn(e);
1687
34.7k
        } catch (std::exception& e) {
1688
150
            warn(damagedPDF(
1689
150
                "", -1, ("object " + og.unparse('/') + ": error reading object: " + e.what())));
1690
150
        }
1691
356k
    }
1692
1693
456k
    if (isUnresolved(og)) {
1694
        // PDF spec says unknown objects resolve to the null object.
1695
360k
        updateCache(og, QPDFObject::create<QPDF_Null>(), -1, -1);
1696
360k
    }
1697
1698
456k
    auto& result(m->obj_cache[og].object);
1699
456k
    result->setDefaultDescription(&qpdf, og);
1700
456k
    return result;
1701
473k
}
1702
1703
void
1704
Objects::resolveObjectsInStream(int obj_stream_number)
1705
238k
{
1706
238k
    auto damaged =
1707
238k
        [this, obj_stream_number](int id, qpdf_offset_t offset, std::string const& msg) -> QPDFExc {
1708
18.6k
        return {
1709
18.6k
            qpdf_e_damaged_pdf,
1710
18.6k
            m->file->getName() + " object stream " + std::to_string(obj_stream_number),
1711
18.6k
            +"object " + std::to_string(id) + " 0",
1712
18.6k
            offset,
1713
18.6k
            msg,
1714
18.6k
            true};
1715
18.6k
    };
1716
1717
238k
    if (m->resolved_object_streams.contains(obj_stream_number)) {
1718
216k
        return;
1719
216k
    }
1720
22.5k
    m->resolved_object_streams.insert(obj_stream_number);
1721
    // Force resolution of object stream
1722
22.5k
    Stream obj_stream = qpdf.getObject(obj_stream_number, 0);
1723
22.5k
    if (!obj_stream) {
1724
17.6k
        throw damagedPDF(
1725
17.6k
            "object " + std::to_string(obj_stream_number) + " 0",
1726
17.6k
            "supposed object stream " + std::to_string(obj_stream_number) + " is not a stream");
1727
17.6k
    }
1728
1729
    // For linearization data in the object, use the data from the object stream for the objects in
1730
    // the stream.
1731
4.95k
    QPDFObjGen stream_og(obj_stream_number, 0);
1732
4.95k
    qpdf_offset_t end_before_space = m->obj_cache[stream_og].end_before_space;
1733
4.95k
    qpdf_offset_t end_after_space = m->obj_cache[stream_og].end_after_space;
1734
1735
4.95k
    QPDFObjectHandle dict = obj_stream.getDict();
1736
4.95k
    if (!dict.isDictionaryOfType("/ObjStm")) {
1737
618
        warn(damagedPDF(
1738
618
            "object " + std::to_string(obj_stream_number) + " 0",
1739
618
            "supposed object stream " + std::to_string(obj_stream_number) + " has wrong type"));
1740
618
    }
1741
1742
4.95k
    unsigned int n{0};
1743
4.95k
    int first{0};
1744
4.95k
    if (!(dict.getKey("/N").getValueAsUInt(n) && dict.getKey("/First").getValueAsInt(first))) {
1745
232
        throw damagedPDF(
1746
232
            "object " + std::to_string(obj_stream_number) + " 0",
1747
232
            "object stream " + std::to_string(obj_stream_number) + " has incorrect keys");
1748
232
    }
1749
1750
    // id, offset, size
1751
4.71k
    std::vector<std::tuple<int, qpdf_offset_t, size_t>> offsets;
1752
1753
4.71k
    auto stream_data = obj_stream.getStreamData(qpdf_dl_specialized);
1754
1755
4.71k
    is::OffsetBuffer input("", stream_data);
1756
1757
4.71k
    const auto b_size = stream_data.size();
1758
4.71k
    const auto end_offset = static_cast<qpdf_offset_t>(b_size);
1759
4.71k
    auto b_start = stream_data.data();
1760
1761
4.71k
    if (first >= end_offset) {
1762
40
        throw damagedPDF(
1763
40
            "object " + std::to_string(obj_stream_number) + " 0",
1764
40
            "object stream " + std::to_string(obj_stream_number) + " has invalid /First entry");
1765
40
    }
1766
1767
4.67k
    int id = 0;
1768
4.67k
    long long last_offset = -1;
1769
4.67k
    bool is_first = true;
1770
80.2k
    for (unsigned int i = 0; i < n; ++i) {
1771
75.7k
        auto tnum = readToken(input);
1772
75.7k
        auto id_offset = input.getLastOffset();
1773
75.7k
        auto toffset = readToken(input);
1774
75.7k
        if (!(tnum.isInteger() && toffset.isInteger())) {
1775
146
            throw damaged(0, input.getLastOffset(), "expected integer in object stream header");
1776
146
        }
1777
1778
75.6k
        int num = QUtil::string_to_int(tnum.getValue().c_str());
1779
75.6k
        long long offset = QUtil::string_to_int(toffset.getValue().c_str());
1780
1781
75.6k
        if (num == obj_stream_number) {
1782
394
            warn(damaged(num, id_offset, "object stream claims to contain itself"));
1783
394
            continue;
1784
394
        }
1785
1786
75.2k
        if (num < 1) {
1787
884
            warn(damaged(num, id_offset, "object id is invalid"s));
1788
884
            continue;
1789
884
        }
1790
1791
74.3k
        if (offset <= last_offset) {
1792
7.29k
            warn(damaged(
1793
7.29k
                num,
1794
7.29k
                input.getLastOffset(),
1795
7.29k
                "offset " + std::to_string(offset) +
1796
7.29k
                    " is invalid (must be larger than previous offset " +
1797
7.29k
                    std::to_string(last_offset) + ")"));
1798
7.29k
            continue;
1799
7.29k
        }
1800
1801
67.0k
        if (num > m->xref_table_max_id) {
1802
1.75k
            continue;
1803
1.75k
        }
1804
1805
65.2k
        if (first + offset >= end_offset) {
1806
9.91k
            warn(damaged(
1807
9.91k
                num, input.getLastOffset(), "offset " + std::to_string(offset) + " is too large"));
1808
9.91k
            continue;
1809
9.91k
        }
1810
1811
55.3k
        if (is_first) {
1812
1.24k
            is_first = false;
1813
54.1k
        } else {
1814
54.1k
            offsets.emplace_back(
1815
54.1k
                id, last_offset + first, static_cast<size_t>(offset - last_offset));
1816
54.1k
        }
1817
1818
55.3k
        last_offset = offset;
1819
55.3k
        id = num;
1820
55.3k
    }
1821
1822
4.53k
    if (!is_first) {
1823
        // We found at least one valid entry.
1824
1.07k
        offsets.emplace_back(
1825
1.07k
            id, last_offset + first, b_size - static_cast<size_t>(last_offset + first));
1826
1.07k
    }
1827
1828
    // To avoid having to read the object stream multiple times, store all objects that would be
1829
    // found here in the cache.  Remember that some objects stored here might have been overridden
1830
    // by new objects appended to the file, so it is necessary to recheck the xref table and only
1831
    // cache what would actually be resolved here.
1832
50.0k
    for (auto const& [obj_id, obj_offset, obj_size]: offsets) {
1833
50.0k
        QPDFObjGen og(obj_id, 0);
1834
50.0k
        auto entry = m->xref_table.find(og);
1835
50.0k
        if (entry != m->xref_table.end() && entry->second.getType() == 2 &&
1836
48.1k
            entry->second.getObjStreamNumber() == obj_stream_number) {
1837
47.5k
            is::OffsetBuffer in("", {b_start + obj_offset, obj_size}, obj_offset);
1838
47.5k
            if (auto oh = Parser::parse(in, obj_stream_number, obj_id, m->tokenizer, qpdf)) {
1839
43.4k
                updateCache(og, oh.obj_sp(), end_before_space, end_after_space);
1840
43.4k
            }
1841
47.5k
        } else {
1842
2.55k
            QTC::TC("qpdf", "QPDF not caching overridden objstm object");
1843
2.55k
        }
1844
50.0k
    }
1845
4.53k
}
1846
1847
QPDFObjectHandle
1848
Objects::newIndirect(QPDFObjGen og, std::shared_ptr<QPDFObject> const& obj)
1849
2.69k
{
1850
2.69k
    obj->setDefaultDescription(&qpdf, og);
1851
2.69k
    return {obj};
1852
2.69k
}
1853
1854
void
1855
Objects::updateCache(
1856
    QPDFObjGen og,
1857
    std::shared_ptr<QPDFObject> const& object,
1858
    qpdf_offset_t end_before_space,
1859
    qpdf_offset_t end_after_space,
1860
    bool destroy)
1861
501k
{
1862
501k
    object->setObjGen(&qpdf, og);
1863
501k
    if (isCached(og)) {
1864
280k
        auto& cache = m->obj_cache[og];
1865
280k
        object->move_to(cache.object, destroy);
1866
280k
        cache.end_before_space = end_before_space;
1867
280k
        cache.end_after_space = end_after_space;
1868
280k
    } else {
1869
220k
        m->obj_cache[og] = ObjCache(object, end_before_space, end_after_space);
1870
220k
    }
1871
501k
}
1872
1873
bool
1874
Objects::isCached(QPDFObjGen og)
1875
1.77M
{
1876
1.77M
    return m->obj_cache.contains(og);
1877
1.77M
}
1878
1879
bool
1880
Objects::isUnresolved(QPDFObjGen og)
1881
1.27M
{
1882
1.27M
    return !isCached(og) || m->obj_cache[og].object->isUnresolved();
1883
1.27M
}
1884
1885
QPDFObjGen
1886
Objects::nextObjGen()
1887
2.70k
{
1888
2.70k
    int max_objid = toI(qpdf.getObjectCount());
1889
2.70k
    if (max_objid == std::numeric_limits<int>::max()) {
1890
1
        throw std::range_error("max object id is too high to create new objects");
1891
1
    }
1892
2.69k
    return {max_objid + 1, 0};
1893
2.70k
}
1894
1895
QPDFObjectHandle
1896
Objects::makeIndirectFromQPDFObject(std::shared_ptr<QPDFObject> const& obj)
1897
2.70k
{
1898
2.70k
    QPDFObjGen next{nextObjGen()};
1899
2.70k
    m->obj_cache[next] = ObjCache(obj, -1, -1);
1900
2.70k
    return newIndirect(next, m->obj_cache[next].object);
1901
2.70k
}
1902
1903
QPDFObjectHandle
1904
QPDF::makeIndirectObject(QPDFObjectHandle oh)
1905
2.70k
{
1906
2.70k
    if (!oh) {
1907
0
        throw std::logic_error("attempted to make an uninitialized QPDFObjectHandle indirect");
1908
0
    }
1909
2.70k
    return m->objects.makeIndirectFromQPDFObject(oh.obj_sp());
1910
2.70k
}
1911
1912
std::shared_ptr<QPDFObject>
1913
Objects::getObjectForParser(int id, int gen, bool parse_pdf)
1914
474k
{
1915
    // This method is called by the parser and therefore must not resolve any objects.
1916
474k
    auto og = QPDFObjGen(id, gen);
1917
474k
    if (auto iter = m->obj_cache.find(og); iter != m->obj_cache.end()) {
1918
219k
        return iter->second.object;
1919
219k
    }
1920
255k
    if (m->xref_table.contains(og) || (!m->parsed && og.getObj() < m->xref_table_max_id)) {
1921
235k
        return m->obj_cache.insert({og, QPDFObject::create<QPDF_Unresolved>(&qpdf, og)})
1922
235k
            .first->second.object;
1923
235k
    }
1924
19.1k
    if (parse_pdf) {
1925
19.1k
        return QPDFObject::create<QPDF_Null>();
1926
19.1k
    }
1927
0
    return m->obj_cache.insert({og, QPDFObject::create<QPDF_Null>(&qpdf, og)}).first->second.object;
1928
19.1k
}
1929
1930
std::shared_ptr<QPDFObject>
1931
Objects::getObjectForJSON(int id, int gen)
1932
0
{
1933
0
    auto og = QPDFObjGen(id, gen);
1934
0
    auto [it, inserted] = m->obj_cache.try_emplace(og);
1935
0
    auto& obj = it->second.object;
1936
0
    if (inserted) {
1937
0
        obj = (m->parsed && !m->xref_table.contains(og))
1938
0
            ? QPDFObject::create<QPDF_Null>(&qpdf, og)
1939
0
            : QPDFObject::create<QPDF_Unresolved>(&qpdf, og);
1940
0
    }
1941
0
    return obj;
1942
0
}
1943
1944
QPDFObjectHandle
1945
QPDF::getObject(QPDFObjGen og)
1946
248k
{
1947
248k
    if (auto it = m->obj_cache.find(og); it != m->obj_cache.end()) {
1948
188k
        return {it->second.object};
1949
188k
    } else if (m->parsed && !m->xref_table.contains(og)) {
1950
5.14k
        return QPDFObject::create<QPDF_Null>();
1951
54.3k
    } else {
1952
54.3k
        auto result =
1953
54.3k
            m->obj_cache.try_emplace(og, QPDFObject::create<QPDF_Unresolved>(this, og), -1, -1);
1954
54.3k
        return {result.first->second.object};
1955
54.3k
    }
1956
248k
}
1957
1958
void
1959
QPDF::replaceObject(int objid, int generation, QPDFObjectHandle oh)
1960
0
{
1961
0
    replaceObject(QPDFObjGen(objid, generation), oh);
1962
0
}
1963
1964
void
1965
QPDF::replaceObject(QPDFObjGen og, QPDFObjectHandle oh)
1966
0
{
1967
0
    if (!oh || (oh.isIndirect() && !(oh.isStream() && oh.getObjGen() == og))) {
1968
0
        throw std::logic_error("QPDF::replaceObject called with indirect object handle");
1969
0
    }
1970
0
    m->objects.updateCache(og, oh.obj_sp(), -1, -1, false);
1971
0
}
1972
1973
void
1974
QPDF::removeObject(QPDFObjGen og)
1975
4.83k
{
1976
4.83k
    m->xref_table.erase(og);
1977
4.83k
    if (auto cached = m->obj_cache.find(og); cached != m->obj_cache.end()) {
1978
        // Take care of any object handles that may be floating around.
1979
1.71k
        cached->second.object->assign_null();
1980
1.71k
        cached->second.object->setObjGen(nullptr, QPDFObjGen());
1981
1.71k
        m->obj_cache.erase(cached);
1982
1.71k
    }
1983
4.83k
}
1984
1985
void
1986
QPDF::replaceReserved(QPDFObjectHandle reserved, QPDFObjectHandle replacement)
1987
0
{
1988
0
    QTC::TC("qpdf", "QPDF replaceReserved");
1989
0
    auto tc = reserved.getTypeCode();
1990
0
    if (!(tc == ::ot_reserved || tc == ::ot_null)) {
1991
0
        throw std::logic_error("replaceReserved called with non-reserved object");
1992
0
    }
1993
0
    replaceObject(reserved.getObjGen(), replacement);
1994
0
}
1995
1996
void
1997
QPDF::swapObjects(int objid1, int generation1, int objid2, int generation2)
1998
0
{
1999
0
    swapObjects(QPDFObjGen(objid1, generation1), QPDFObjGen(objid2, generation2));
2000
0
}
2001
2002
void
2003
QPDF::swapObjects(QPDFObjGen og1, QPDFObjGen og2)
2004
0
{
2005
    // Force objects to be read from the input source if needed, then swap them in the cache.
2006
0
    m->objects.resolve(og1);
2007
0
    m->objects.resolve(og2);
2008
0
    m->obj_cache[og1].object->swapWith(m->obj_cache[og2].object);
2009
0
}
2010
2011
size_t
2012
Objects::table_size()
2013
8.36k
{
2014
    // If obj_cache is dense, accommodate all object in tables,else accommodate only original
2015
    // objects.
2016
8.36k
    auto max_xref = !m->xref_table.empty() ? m->xref_table.crbegin()->first.getObj() : 0;
2017
8.36k
    auto max_obj = !m->obj_cache.empty() ? m->obj_cache.crbegin()->first.getObj() : 0;
2018
8.36k
    auto max_id = std::numeric_limits<int>::max() - 1;
2019
8.36k
    if (max_obj >= max_id || max_xref >= max_id) {
2020
        // Temporary fix. Long-term solution is
2021
        // - QPDFObjGen to enforce objgens are valid and sensible
2022
        // - xref table and obj cache to protect against insertion of impossibly large obj ids
2023
1
        stopOnError("Impossibly large object id encountered.");
2024
1
    }
2025
8.36k
    if (max_obj < 1.1 * std::max(toI(m->obj_cache.size()), max_xref)) {
2026
6.43k
        return toS(++max_obj);
2027
6.43k
    }
2028
1.92k
    return toS(++max_xref);
2029
8.36k
}
2030
2031
std::vector<QPDFObjGen>
2032
Objects::compressible_vector()
2033
0
{
2034
0
    return compressible<QPDFObjGen>();
2035
0
}
2036
2037
std::vector<bool>
2038
Objects::compressible_set()
2039
1.11k
{
2040
1.11k
    return compressible<bool>();
2041
1.11k
}
2042
2043
template <typename T>
2044
std::vector<T>
2045
Objects::compressible()
2046
1.11k
{
2047
    // Return a list of objects that are allowed to be in object streams.  Walk through the objects
2048
    // by traversing the document from the root, including a traversal of the pages tree.  This
2049
    // makes that objects that are on the same page are more likely to be in the same object stream,
2050
    // which is slightly more efficient, particularly with linearized files.  This is better than
2051
    // iterating through the xref table since it avoids preserving orphaned items.
2052
2053
    // Exclude encryption dictionary, if any
2054
1.11k
    QPDFObjectHandle encryption_dict = m->trailer.getKey("/Encrypt");
2055
1.11k
    QPDFObjGen encryption_dict_og = encryption_dict.getObjGen();
2056
2057
1.11k
    const size_t max_obj = qpdf.getObjectCount();
2058
1.11k
    std::vector<bool> visited(max_obj, false);
2059
1.11k
    std::vector<QPDFObjectHandle> queue;
2060
1.11k
    queue.reserve(512);
2061
1.11k
    queue.emplace_back(m->trailer);
2062
1.11k
    std::vector<T> result;
2063
1.11k
    if constexpr (std::is_same_v<T, QPDFObjGen>) {
2064
0
        result.reserve(m->obj_cache.size());
2065
1.11k
    } else {
2066
1.11k
        qpdf_static_expect(std::is_same_v<T, bool>);
2067
1.11k
        result.resize(max_obj + 1U, false);
2068
1.11k
    }
2069
498k
    while (!queue.empty()) {
2070
497k
        auto obj = queue.back();
2071
497k
        queue.pop_back();
2072
497k
        if (obj.getObjectID() > 0) {
2073
94.3k
            QPDFObjGen og = obj.getObjGen();
2074
94.3k
            const size_t id = toS(og.getObj() - 1);
2075
94.3k
            if (id >= max_obj) {
2076
0
                throw std::logic_error(
2077
0
                    "unexpected object id encountered in getCompressibleObjGens");
2078
0
            }
2079
94.3k
            if (visited[id]) {
2080
29.7k
                continue;
2081
29.7k
            }
2082
2083
            // Check whether this is the current object. If not, remove it (which changes it into a
2084
            // direct null and therefore stops us from revisiting it) and move on to the next object
2085
            // in the queue.
2086
64.6k
            auto upper = m->obj_cache.upper_bound(og);
2087
64.6k
            if (upper != m->obj_cache.end() && upper->first.getObj() == og.getObj()) {
2088
1.35k
                qpdf.removeObject(og);
2089
1.35k
                continue;
2090
1.35k
            }
2091
2092
63.3k
            visited[id] = true;
2093
2094
63.3k
            if (og == encryption_dict_og) {
2095
124
                QTC::TC("qpdf", "QPDF exclude encryption dictionary");
2096
63.1k
            } else if (!(obj.isStream() ||
2097
58.6k
                         (obj.isDictionaryOfType("/Sig") && obj.hasKey("/ByteRange") &&
2098
58.6k
                          obj.hasKey("/Contents")))) {
2099
58.6k
                if constexpr (std::is_same_v<T, QPDFObjGen>) {
2100
0
                    result.push_back(og);
2101
58.6k
                } else if constexpr (std::is_same_v<T, bool>) {
2102
58.6k
                    result[id + 1U] = true;
2103
58.6k
                }
2104
58.6k
            }
2105
63.3k
        }
2106
466k
        if (obj.isStream()) {
2107
4.54k
            auto dict = obj.getDict().as_dictionary();
2108
4.54k
            auto end = dict.crend();
2109
34.0k
            for (auto iter = dict.crbegin(); iter != end; ++iter) {
2110
29.5k
                std::string const& key = iter->first;
2111
29.5k
                QPDFObjectHandle const& value = iter->second;
2112
29.5k
                if (!value.null()) {
2113
26.1k
                    if (key == "/Length") {
2114
                        // omit stream lengths
2115
4.10k
                        if (value.isIndirect()) {
2116
174
                            QTC::TC("qpdf", "QPDF exclude indirect length");
2117
174
                        }
2118
22.0k
                    } else {
2119
22.0k
                        queue.emplace_back(value);
2120
22.0k
                    }
2121
26.1k
                }
2122
29.5k
            }
2123
461k
        } else if (obj.isDictionary()) {
2124
38.1k
            auto dict = obj.as_dictionary();
2125
38.1k
            auto end = dict.crend();
2126
192k
            for (auto iter = dict.crbegin(); iter != end; ++iter) {
2127
154k
                if (!iter->second.null()) {
2128
131k
                    queue.emplace_back(iter->second);
2129
131k
                }
2130
154k
            }
2131
423k
        } else if (auto items = obj.as_array()) {
2132
423k
            queue.insert(queue.end(), items.crbegin(), items.crend());
2133
423k
        }
2134
466k
    }
2135
2136
1.11k
    return result;
2137
1.11k
}
Unexecuted instantiation: std::__1::vector<QPDFObjGen, std::__1::allocator<QPDFObjGen> > QPDF::Doc::Objects::compressible<QPDFObjGen>()
std::__1::vector<bool, std::__1::allocator<bool> > QPDF::Doc::Objects::compressible<bool>()
Line
Count
Source
2046
1.11k
{
2047
    // Return a list of objects that are allowed to be in object streams.  Walk through the objects
2048
    // by traversing the document from the root, including a traversal of the pages tree.  This
2049
    // makes that objects that are on the same page are more likely to be in the same object stream,
2050
    // which is slightly more efficient, particularly with linearized files.  This is better than
2051
    // iterating through the xref table since it avoids preserving orphaned items.
2052
2053
    // Exclude encryption dictionary, if any
2054
1.11k
    QPDFObjectHandle encryption_dict = m->trailer.getKey("/Encrypt");
2055
1.11k
    QPDFObjGen encryption_dict_og = encryption_dict.getObjGen();
2056
2057
1.11k
    const size_t max_obj = qpdf.getObjectCount();
2058
1.11k
    std::vector<bool> visited(max_obj, false);
2059
1.11k
    std::vector<QPDFObjectHandle> queue;
2060
1.11k
    queue.reserve(512);
2061
1.11k
    queue.emplace_back(m->trailer);
2062
1.11k
    std::vector<T> result;
2063
    if constexpr (std::is_same_v<T, QPDFObjGen>) {
2064
        result.reserve(m->obj_cache.size());
2065
1.11k
    } else {
2066
1.11k
        qpdf_static_expect(std::is_same_v<T, bool>);
2067
1.11k
        result.resize(max_obj + 1U, false);
2068
1.11k
    }
2069
498k
    while (!queue.empty()) {
2070
497k
        auto obj = queue.back();
2071
497k
        queue.pop_back();
2072
497k
        if (obj.getObjectID() > 0) {
2073
94.3k
            QPDFObjGen og = obj.getObjGen();
2074
94.3k
            const size_t id = toS(og.getObj() - 1);
2075
94.3k
            if (id >= max_obj) {
2076
0
                throw std::logic_error(
2077
0
                    "unexpected object id encountered in getCompressibleObjGens");
2078
0
            }
2079
94.3k
            if (visited[id]) {
2080
29.7k
                continue;
2081
29.7k
            }
2082
2083
            // Check whether this is the current object. If not, remove it (which changes it into a
2084
            // direct null and therefore stops us from revisiting it) and move on to the next object
2085
            // in the queue.
2086
64.6k
            auto upper = m->obj_cache.upper_bound(og);
2087
64.6k
            if (upper != m->obj_cache.end() && upper->first.getObj() == og.getObj()) {
2088
1.35k
                qpdf.removeObject(og);
2089
1.35k
                continue;
2090
1.35k
            }
2091
2092
63.3k
            visited[id] = true;
2093
2094
63.3k
            if (og == encryption_dict_og) {
2095
124
                QTC::TC("qpdf", "QPDF exclude encryption dictionary");
2096
63.1k
            } else if (!(obj.isStream() ||
2097
58.6k
                         (obj.isDictionaryOfType("/Sig") && obj.hasKey("/ByteRange") &&
2098
58.6k
                          obj.hasKey("/Contents")))) {
2099
                if constexpr (std::is_same_v<T, QPDFObjGen>) {
2100
                    result.push_back(og);
2101
58.6k
                } else if constexpr (std::is_same_v<T, bool>) {
2102
58.6k
                    result[id + 1U] = true;
2103
58.6k
                }
2104
58.6k
            }
2105
63.3k
        }
2106
466k
        if (obj.isStream()) {
2107
4.54k
            auto dict = obj.getDict().as_dictionary();
2108
4.54k
            auto end = dict.crend();
2109
34.0k
            for (auto iter = dict.crbegin(); iter != end; ++iter) {
2110
29.5k
                std::string const& key = iter->first;
2111
29.5k
                QPDFObjectHandle const& value = iter->second;
2112
29.5k
                if (!value.null()) {
2113
26.1k
                    if (key == "/Length") {
2114
                        // omit stream lengths
2115
4.10k
                        if (value.isIndirect()) {
2116
174
                            QTC::TC("qpdf", "QPDF exclude indirect length");
2117
174
                        }
2118
22.0k
                    } else {
2119
22.0k
                        queue.emplace_back(value);
2120
22.0k
                    }
2121
26.1k
                }
2122
29.5k
            }
2123
461k
        } else if (obj.isDictionary()) {
2124
38.1k
            auto dict = obj.as_dictionary();
2125
38.1k
            auto end = dict.crend();
2126
192k
            for (auto iter = dict.crbegin(); iter != end; ++iter) {
2127
154k
                if (!iter->second.null()) {
2128
131k
                    queue.emplace_back(iter->second);
2129
131k
                }
2130
154k
            }
2131
423k
        } else if (auto items = obj.as_array()) {
2132
423k
            queue.insert(queue.end(), items.crbegin(), items.crend());
2133
423k
        }
2134
466k
    }
2135
2136
1.11k
    return result;
2137
1.11k
}