Coverage Report

Created: 2025-11-24 06:47

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