Coverage Report

Created: 2025-08-26 07:10

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