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
310k
        qpdf(qpdf),
92
310k
        iter(qpdf.m->resolving.insert(og).first)
93
310k
    {
94
310k
    }
95
    ~ResolveRecorder()
96
310k
    {
97
310k
        qpdf.m->resolving.erase(iter);
98
310k
    }
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
75.4k
        o(o),
110
75.4k
        checker(checker)
111
75.4k
    {
112
75.4k
    }
113
    ~PatternFinder() final = default;
114
    bool
115
    check() final
116
44.0k
    {
117
44.0k
        return (this->o.*checker)();
118
44.0k
    }
119
120
  private:
121
    Objects& o;
122
    bool (Objects::*checker)();
123
};
124
125
bool
126
Objects::validatePDFVersion(char const*& p, std::string& version)
127
5.57k
{
128
5.57k
    if (!util::is_digit(*p)) {
129
2.63k
        return false;
130
2.63k
    }
131
8.36k
    while (util::is_digit(*p)) {
132
5.41k
        version.append(1, *p++);
133
5.41k
    }
134
2.94k
    if (!(*p == '.' && util::is_digit(*(p + 1)))) {
135
867
        return false;
136
867
    }
137
2.07k
    version.append(1, *p++);
138
7.23k
    while (util::is_digit(*p)) {
139
5.16k
        version.append(1, *p++);
140
5.16k
    }
141
2.07k
    return true;
142
2.94k
}
143
144
bool
145
Objects::findHeader()
146
5.58k
{
147
5.58k
    qpdf_offset_t global_offset = m->file->tell();
148
5.58k
    std::string line = m->file->readLine(1024);
149
5.58k
    char const* p = line.data();
150
5.58k
    util::assertion(strncmp(p, "%PDF-", 5) == 0, "findHeader is not looking at %PDF-");
151
5.58k
    p += 5;
152
5.58k
    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
5.58k
    if (!validatePDFVersion(p, version)) {
156
3.50k
        return false;
157
3.50k
    }
158
2.08k
    m->pdf_version = version;
159
2.08k
    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
1.23k
        m->file = std::make_shared<OffsetInputSource>(m->file, global_offset);
164
1.23k
    }
165
2.08k
    return true;
166
5.58k
}
167
168
bool
169
Objects ::findStartxref()
170
7.31k
{
171
7.31k
    if (readToken(*m->file).isWord("startxref") && readToken(*m->file).isInteger()) {
172
        // Position in front of offset token
173
5.59k
        m->file->seek(m->file->getLastOffset(), SEEK_SET);
174
5.59k
        return true;
175
5.59k
    }
176
1.72k
    return false;
177
7.31k
}
178
179
void
180
Objects::parse(char const* password)
181
24.1k
{
182
24.1k
    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
24.1k
    PatternFinder hf(*this, &Objects::findHeader);
188
24.1k
    if (!m->file->findFirst("%PDF-", 0, 1024, hf)) {
189
22.0k
        warn(damagedPDF("", -1, "can't find PDF header"));
190
        // QPDFWriter writes files that usually require at least version 1.2 for /FlateDecode
191
22.0k
        m->pdf_version = "1.2";
192
22.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
24.1k
    m->file->seek(0, SEEK_END);
197
24.1k
    qpdf_offset_t end_offset = m->file->tell();
198
24.1k
    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
24.1k
    if (m->xref_table_max_id > m->xref_table_max_offset / 3) {
202
24.1k
        m->xref_table_max_id = static_cast<int>(m->xref_table_max_offset / 3);
203
24.1k
    }
204
24.1k
    qpdf_offset_t start_offset = (end_offset > 1054 ? end_offset - 1054 : 0);
205
24.1k
    PatternFinder sf(*this, &Objects::findStartxref);
206
24.1k
    qpdf_offset_t xref_offset = 0;
207
24.1k
    if (m->file->findLast("startxref", start_offset, 0, sf)) {
208
5.28k
        xref_offset = QUtil::string_to_ll(readToken(*m->file).getValue().c_str());
209
5.28k
    }
210
211
24.1k
    try {
212
24.1k
        if (xref_offset == 0) {
213
18.9k
            throw damagedPDF("", -1, "can't find startxref");
214
18.9k
        }
215
5.17k
        try {
216
5.17k
            read_xref(xref_offset);
217
5.17k
        } catch (QPDFExc&) {
218
4.07k
            throw;
219
4.07k
        } catch (std::exception& e) {
220
462
            throw damagedPDF("", -1, std::string("error reading xref: ") + e.what());
221
462
        }
222
23.5k
    } catch (QPDFExc& e) {
223
23.5k
        if (!cf.surpress_recovery()) {
224
23.5k
            reconstruct_xref(e, xref_offset > 0);
225
23.5k
        } else {
226
0
            throw;
227
0
        }
228
23.5k
    }
229
230
23.5k
    m->encp->initialize(qpdf);
231
10.1k
    m->parsed = true;
232
10.1k
    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
5
        throw damagedPDF("", -1, "unable to find page tree");
235
5
    }
236
10.1k
}
237
238
void
239
Objects::inParse(bool v)
240
306k
{
241
306k
    util::internal_error_if(
242
306k
        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
306k
    );
246
306k
    m->in_parse = v;
247
306k
}
248
249
void
250
Objects::setTrailer(QPDFObjectHandle obj)
251
6.90k
{
252
6.90k
    if (m->trailer) {
253
137
        return;
254
137
    }
255
6.77k
    m->trailer = obj;
256
6.77k
}
257
258
void
259
Objects::reconstruct_xref(QPDFExc& e, bool found_startxref)
260
27.9k
{
261
27.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
4.28k
        throw e;
265
4.28k
    }
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
23.6k
    const auto max_warnings = m->warnings.size() + 1000U;
270
1.26M
    auto check_warnings = [this, max_warnings]() {
271
1.26M
        if (m->warnings.size() > max_warnings) {
272
0
            throw damagedPDF("", -1, "too many errors while reconstructing cross-reference table");
273
0
        }
274
1.26M
    };
275
276
23.6k
    m->reconstructed_xref = true;
277
    // We may find more objects, which may contain dangling references.
278
23.6k
    m->fixed_dangling_refs = false;
279
280
23.6k
    warn(damagedPDF("", -1, "file is damaged"));
281
23.6k
    warn(e);
282
23.6k
    warn(damagedPDF("", -1, "Attempting to reconstruct cross-reference table"));
283
284
    // Delete all references to type 1 (uncompressed) objects
285
23.6k
    std::vector<QPDFObjGen> to_delete;
286
90.4k
    for (auto const& iter: m->xref_table) {
287
90.4k
        if (iter.second.getType() == 1) {
288
82.0k
            to_delete.emplace_back(iter.first);
289
82.0k
        }
290
90.4k
    }
291
82.0k
    for (auto const& iter: to_delete) {
292
82.0k
        m->xref_table.erase(iter);
293
82.0k
    }
294
295
23.6k
    std::vector<std::tuple<int, int, qpdf_offset_t>> found_objects;
296
23.6k
    std::vector<qpdf_offset_t> trailers;
297
23.6k
    std::vector<qpdf_offset_t> startxrefs;
298
299
23.6k
    m->file->seek(0, SEEK_END);
300
23.6k
    qpdf_offset_t eof = m->file->tell();
301
23.6k
    m->file->seek(0, SEEK_SET);
302
    // Don't allow very long tokens here during recovery. All the interesting tokens are covered.
303
23.6k
    static size_t const MAX_LEN = 10;
304
1.13M
    while (m->file->tell() < eof) {
305
1.11M
        QPDFTokenizer::Token t1 = m->objects.readToken(*m->file, MAX_LEN);
306
1.11M
        qpdf_offset_t token_start = m->file->tell() - toO(t1.getValue().length());
307
1.11M
        if (t1.isInteger()) {
308
205k
            auto pos = m->file->tell();
309
205k
            auto t2 = m->objects.readToken(*m->file, MAX_LEN);
310
205k
            if (t2.isInteger() && m->objects.readToken(*m->file, MAX_LEN).isWord("obj")) {
311
111k
                int obj = QUtil::string_to_int(t1.getValue().c_str());
312
111k
                int gen = QUtil::string_to_int(t2.getValue().c_str());
313
111k
                if (obj <= m->xref_table_max_id) {
314
110k
                    found_objects.emplace_back(obj, gen, token_start);
315
110k
                } else {
316
1.03k
                    warn(damagedPDF(
317
1.03k
                        "", -1, "ignoring object with impossibly large id " + std::to_string(obj)));
318
1.03k
                }
319
111k
            }
320
205k
            m->file->seek(pos, SEEK_SET);
321
907k
        } else if (!m->trailer && t1.isWord("trailer")) {
322
36.9k
            trailers.emplace_back(m->file->tell());
323
870k
        } else if (!found_startxref && t1.isWord("startxref")) {
324
1.48k
            startxrefs.emplace_back(m->file->tell());
325
1.48k
        }
326
1.11M
        check_warnings();
327
1.11M
        m->file->findAndSkipNextEOL();
328
1.11M
    }
329
330
23.6k
    if (!found_startxref && !startxrefs.empty() && !found_objects.empty() &&
331
683
        startxrefs.back() > std::get<2>(found_objects.back())) {
332
417
        auto xref_backup{m->xref_table};
333
417
        try {
334
417
            m->file->seek(startxrefs.back(), SEEK_SET);
335
417
            if (auto offset = QUtil::string_to_ll(readToken(*m->file).getValue().data())) {
336
279
                read_xref(offset);
337
338
279
                if (qpdf.getRoot().getKey("/Pages").isDictionary()) {
339
8
                    warn(damagedPDF(
340
8
                        "", -1, "startxref was more than 1024 bytes before end of file"));
341
8
                    m->encp->initialize(qpdf);
342
8
                    m->parsed = true;
343
8
                    m->reconstructed_xref = false;
344
8
                    return;
345
8
                }
346
279
            }
347
417
        } catch (...) {
348
            // ok, bad luck. Do recovery.
349
270
        }
350
409
        m->xref_table = std::move(xref_backup);
351
409
    }
352
353
23.6k
    auto rend = found_objects.rend();
354
134k
    for (auto it = found_objects.rbegin(); it != rend; it++) {
355
110k
        auto [obj, gen, token_start] = *it;
356
110k
        insertXrefEntry(obj, 1, token_start, gen);
357
110k
        check_warnings();
358
110k
    }
359
23.6k
    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
23.6k
    int end_index = trailers.size() > 100 ? static_cast<int>(trailers.size()) - 100 : 0;
364
36.5k
    for (auto it = trailers.rbegin(); it != std::prev(trailers.rend(), end_index); it++) {
365
15.6k
        m->file->seek(*it, SEEK_SET);
366
15.6k
        auto t = readTrailer();
367
15.6k
        if (!t.isDictionary()) {
368
            // Oh well.  It was worth a try.
369
12.1k
        } else {
370
3.50k
            if (t.hasKey("/Root")) {
371
2.77k
                m->trailer = t;
372
2.77k
                break;
373
2.77k
            }
374
732
            warn(damagedPDF("trailer", *it, "recovered trailer has no /Root entry"));
375
732
        }
376
12.9k
        check_warnings();
377
12.9k
    }
378
379
23.6k
    if (!m->trailer) {
380
20.1k
        qpdf_offset_t max_offset{0};
381
20.1k
        size_t max_size{0};
382
        // If there are any xref streams, take the last one to appear.
383
66.6k
        for (auto const& iter: m->xref_table) {
384
66.6k
            auto entry = iter.second;
385
66.6k
            if (entry.getType() != 1) {
386
1.10k
                continue;
387
1.10k
            }
388
65.5k
            auto oh = qpdf.getObject(iter.first);
389
65.5k
            try {
390
65.5k
                if (!oh.isStreamOfType("/XRef")) {
391
57.3k
                    continue;
392
57.3k
                }
393
65.5k
            } catch (std::exception&) {
394
2.37k
                continue;
395
2.37k
            }
396
5.78k
            auto offset = entry.getOffset();
397
5.78k
            auto size = oh.getDict().getKey("/Size").getUIntValueAsUInt();
398
5.78k
            if (size > max_size || (size == max_size && offset > max_offset)) {
399
5.73k
                max_offset = offset;
400
5.73k
                setTrailer(oh.getDict());
401
5.73k
            }
402
5.78k
            check_warnings();
403
5.78k
        }
404
20.1k
        if (max_offset > 0) {
405
5.59k
            try {
406
5.59k
                read_xref(max_offset, true);
407
5.59k
            } catch (std::exception&) {
408
3.28k
                warn(damagedPDF(
409
3.28k
                    "", -1, "error decoding candidate xref stream while recovering damaged file"));
410
3.28k
            }
411
5.59k
            QTC::TC("qpdf", "QPDF recover xref stream");
412
5.56k
        }
413
20.1k
    }
414
415
23.6k
    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
20.5k
        QPDFObjectHandle root;
418
149k
        for (auto const& iter: m->obj_cache) {
419
149k
            try {
420
149k
                if (QPDFObjectHandle(iter.second.object).isDictionaryOfType("/Catalog")) {
421
7.96k
                    root = iter.second.object;
422
7.96k
                }
423
149k
            } catch (std::exception&) {
424
4.79k
                continue;
425
4.79k
            }
426
149k
        }
427
20.5k
        if (root) {
428
7.85k
            if (!m->trailer) {
429
6.68k
                warn(damagedPDF(
430
6.68k
                    "", -1, "unable to find trailer dictionary while recovering damaged file"));
431
6.68k
                m->trailer = QPDFObjectHandle::newDictionary();
432
6.68k
            }
433
7.85k
            m->trailer.replaceKey("/Root", root);
434
7.85k
        }
435
20.5k
    }
436
437
23.6k
    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
7.87k
        throw damagedPDF("", -1, "unable to find trailer dictionary while recovering damaged file");
443
7.87k
    }
444
15.7k
    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
398
        throw damagedPDF("", -1, "unable to find objects while recovering damaged file");
448
398
    }
449
15.3k
    check_warnings();
450
15.3k
    if (!m->parsed) {
451
15.1k
        m->parsed = !m->pages.empty();
452
15.1k
        if (!m->parsed) {
453
789
            throw damagedPDF("", -1, "unable to find any pages while recovering damaged file");
454
789
        }
455
14.3k
        check_warnings();
456
14.3k
    }
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
15.3k
}
464
465
void
466
Objects::read_xref(qpdf_offset_t xref_offset, bool in_stream_recovery)
467
11.0k
{
468
11.0k
    std::map<int, int> free_table;
469
11.0k
    std::set<qpdf_offset_t> visited;
470
22.7k
    while (xref_offset) {
471
11.9k
        visited.insert(xref_offset);
472
11.9k
        char buf[7];
473
11.9k
        memset(buf, 0, sizeof(buf));
474
11.9k
        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
11.9k
        bool done = false;
480
11.9k
        bool skipped_space = false;
481
26.9k
        while (!done) {
482
15.0k
            char ch;
483
15.0k
            if (1 == m->file->read(&ch, 1)) {
484
14.4k
                if (util::is_space(ch)) {
485
3.44k
                    skipped_space = true;
486
10.9k
                } else {
487
10.9k
                    m->file->unreadCh(ch);
488
10.9k
                    done = true;
489
10.9k
                }
490
14.4k
            } else {
491
587
                QTC::TC("qpdf", "QPDF eof skipping spaces before xref", skipped_space ? 0 : 1);
492
587
                done = true;
493
587
            }
494
15.0k
        }
495
496
11.9k
        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
11.9k
        if ((strncmp(buf, "xref", 4) == 0) && util::is_space(buf[4])) {
500
1.58k
            if (skipped_space) {
501
107
                warn(damagedPDF("", -1, "extraneous whitespace seen before xref"));
502
107
            }
503
1.58k
            QTC::TC(
504
1.58k
                "qpdf",
505
1.58k
                "QPDF xref space",
506
1.58k
                ((buf[4] == '\n')       ? 0
507
1.58k
                     : (buf[4] == '\r') ? 1
508
1.22k
                     : (buf[4] == ' ')  ? 2
509
548
                                        : 9999));
510
1.58k
            int skip = 4;
511
            // buf is null-terminated, and util::is_space('\0') is false, so this won't overrun.
512
3.39k
            while (util::is_space(buf[skip])) {
513
1.80k
                ++skip;
514
1.80k
            }
515
1.58k
            xref_offset = read_xrefTable(xref_offset + skip);
516
10.3k
        } else {
517
10.3k
            xref_offset = read_xrefStream(xref_offset, in_stream_recovery);
518
10.3k
        }
519
11.9k
        if (visited.contains(xref_offset)) {
520
212
            throw damagedPDF("", -1, "loop detected following xref tables");
521
212
        }
522
11.9k
    }
523
524
10.8k
    if (!m->trailer) {
525
0
        throw damagedPDF("", -1, "unable to find trailer while reading xref");
526
0
    }
527
10.8k
    int size = m->trailer.getKey("/Size").getIntValueAsInt();
528
10.8k
    int max_obj = 0;
529
10.8k
    if (!m->xref_table.empty()) {
530
2.74k
        max_obj = m->xref_table.rbegin()->first.getObj();
531
2.74k
    }
532
10.8k
    if (!m->deleted_objects.empty()) {
533
922
        max_obj = std::max(max_obj, *(m->deleted_objects.rbegin()));
534
922
    }
535
10.8k
    if (size < 1 || (size - 1) != max_obj) {
536
2.26k
        if (size == (max_obj + 2) && qpdf.getObject(max_obj + 1, 0).isStreamOfType("/XRef")) {
537
2
            warn(damagedPDF(
538
2
                "",
539
2
                -1,
540
2
                "xref entry for the xref stream itself is missing - a common error handled "
541
2
                "correctly by qpdf and most other applications"));
542
2.26k
        } else {
543
2.26k
            warn(damagedPDF(
544
2.26k
                "",
545
2.26k
                -1,
546
2.26k
                ("reported number of objects (" + std::to_string(size) +
547
2.26k
                 ") is not one plus the highest object number (" + std::to_string(max_obj) + ")")));
548
2.26k
        }
549
2.26k
    }
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
10.8k
    m->deleted_objects.clear();
554
555
    // Make sure we keep only the highest generation for any object.
556
10.8k
    QPDFObjGen last_og{-1, 0};
557
292k
    for (auto const& item: m->xref_table) {
558
292k
        auto id = item.first.getObj();
559
292k
        if (id == last_og.getObj() && id > 0) {
560
16.7k
            qpdf.removeObject(last_og);
561
16.7k
        }
562
292k
        last_og = item.first;
563
292k
    }
564
10.8k
}
565
566
bool
567
Objects::parse_xrefFirst(std::string const& line, int& obj, int& num, int& bytes)
568
6.99k
{
569
    // is_space and is_digit both return false on '\0', so this will not overrun the null-terminated
570
    // buffer.
571
6.99k
    char const* p = line.c_str();
572
6.99k
    char const* start = line.c_str();
573
574
    // Skip zero or more spaces
575
8.36k
    while (util::is_space(*p)) {
576
1.36k
        ++p;
577
1.36k
    }
578
    // Require digit
579
6.99k
    if (!util::is_digit(*p)) {
580
163
        return false;
581
163
    }
582
    // Gather digits
583
6.83k
    std::string obj_str;
584
31.2k
    while (util::is_digit(*p)) {
585
24.4k
        obj_str.append(1, *p++);
586
24.4k
    }
587
    // Require space
588
6.83k
    if (!util::is_space(*p)) {
589
127
        return false;
590
127
    }
591
    // Skip spaces
592
17.8k
    while (util::is_space(*p)) {
593
11.1k
        ++p;
594
11.1k
    }
595
    // Require digit
596
6.70k
    if (!util::is_digit(*p)) {
597
114
        return false;
598
114
    }
599
    // Gather digits
600
6.59k
    std::string num_str;
601
20.9k
    while (util::is_digit(*p)) {
602
14.3k
        num_str.append(1, *p++);
603
14.3k
    }
604
    // Skip any space including line terminators
605
19.4k
    while (util::is_space(*p)) {
606
12.8k
        ++p;
607
12.8k
    }
608
6.59k
    bytes = toI(p - start);
609
6.59k
    obj = QUtil::string_to_int(obj_str.c_str());
610
6.59k
    num = QUtil::string_to_int(num_str.c_str());
611
6.59k
    return true;
612
6.70k
}
613
614
bool
615
Objects::read_bad_xrefEntry(qpdf_offset_t& f1, int& f2, char& type)
616
7.50k
{
617
    // Reposition after initial read attempt and reread.
618
7.50k
    m->file->seek(m->file->getLastOffset(), SEEK_SET);
619
7.50k
    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
7.50k
    char const* p = line.data();
624
625
    // Skip zero or more spaces. There aren't supposed to be any.
626
7.50k
    bool invalid = false;
627
18.6k
    while (util::is_space(*p)) {
628
11.1k
        ++p;
629
11.1k
        invalid = true;
630
11.1k
    }
631
    // Require digit
632
7.50k
    if (!util::is_digit(*p)) {
633
13
        return false;
634
13
    }
635
    // Gather digits
636
7.49k
    std::string f1_str;
637
26.4k
    while (util::is_digit(*p)) {
638
19.0k
        f1_str.append(1, *p++);
639
19.0k
    }
640
    // Require space
641
7.49k
    if (!util::is_space(*p)) {
642
20
        return false;
643
20
    }
644
7.47k
    if (util::is_space(*(p + 1))) {
645
1.97k
        invalid = true;
646
1.97k
    }
647
    // Skip spaces
648
17.9k
    while (util::is_space(*p)) {
649
10.4k
        ++p;
650
10.4k
    }
651
    // Require digit
652
7.47k
    if (!util::is_digit(*p)) {
653
73
        return false;
654
73
    }
655
    // Gather digits
656
7.39k
    std::string f2_str;
657
31.9k
    while (util::is_digit(*p)) {
658
24.5k
        f2_str.append(1, *p++);
659
24.5k
    }
660
    // Require space
661
7.39k
    if (!util::is_space(*p)) {
662
28
        return false;
663
28
    }
664
7.37k
    if (util::is_space(*(p + 1))) {
665
1.55k
        invalid = true;
666
1.55k
    }
667
    // Skip spaces
668
17.6k
    while (util::is_space(*p)) {
669
10.2k
        ++p;
670
10.2k
    }
671
7.37k
    if ((*p == 'f') || (*p == 'n')) {
672
7.21k
        type = *p;
673
7.21k
    } else {
674
157
        return false;
675
157
    }
676
7.21k
    if ((f1_str.length() != 10) || (f2_str.length() != 5)) {
677
7.01k
        invalid = true;
678
7.01k
    }
679
680
7.21k
    if (invalid) {
681
7.03k
        warn(damagedPDF("xref table", "accepting invalid xref table entry"));
682
7.03k
    }
683
684
7.21k
    f1 = QUtil::string_to_ll(f1_str.c_str());
685
7.21k
    f2 = QUtil::string_to_int(f2_str.c_str());
686
687
7.21k
    return true;
688
7.37k
}
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
17.9k
{
695
17.9k
    std::array<char, 21> line;
696
17.9k
    if (m->file->read(line.data(), 20) != 20) {
697
        // C++20: [[unlikely]]
698
213
        return false;
699
213
    }
700
17.7k
    line[20] = '\0';
701
17.7k
    char const* p = line.data();
702
703
17.7k
    int f1_len = 0;
704
17.7k
    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
76.9k
    while (*p == '0') {
711
59.2k
        ++f1_len;
712
59.2k
        ++p;
713
59.2k
    }
714
75.5k
    while (util::is_digit(*p) && f1_len++ < 10) {
715
57.8k
        f1 *= 10;
716
57.8k
        f1 += *p++ - '0';
717
57.8k
    }
718
    // Require space
719
17.7k
    if (!util::is_space(*p++)) {
720
        // Entry doesn't start with space or digit.
721
        // C++20: [[unlikely]]
722
92
        return false;
723
92
    }
724
    // Gather digits. NB No risk of overflow as 99'999 < max int.
725
73.1k
    while (*p == '0') {
726
55.4k
        ++f2_len;
727
55.4k
        ++p;
728
55.4k
    }
729
23.2k
    while (util::is_digit(*p) && f2_len++ < 5) {
730
5.55k
        f2 *= 10;
731
5.55k
        f2 += static_cast<int>(*p++ - '0');
732
5.55k
    }
733
17.6k
    if (util::is_space(*p++) && (*p == 'f' || *p == 'n')) {
734
        // C++20: [[likely]]
735
13.2k
        type = *p;
736
        // No test for valid line[19].
737
13.2k
        if (*(++p) && *(++p) && (*p == '\n' || *p == '\r') && f1_len == 10 && f2_len == 5) {
738
            // C++20: [[likely]]
739
10.1k
            return true;
740
10.1k
        }
741
13.2k
    }
742
7.50k
    return read_bad_xrefEntry(f1, f2, type);
743
17.6k
}
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.58k
{
749
1.58k
    m->file->seek(xref_offset, SEEK_SET);
750
1.58k
    std::string line;
751
7.02k
    while (true) {
752
6.99k
        line.assign(50, '\0');
753
6.99k
        m->file->read(line.data(), line.size());
754
6.99k
        int obj = 0;
755
6.99k
        int num = 0;
756
6.99k
        int bytes = 0;
757
6.99k
        if (!parse_xrefFirst(line, obj, num, bytes)) {
758
404
            throw damagedPDF("xref table", "xref syntax invalid");
759
404
        }
760
6.59k
        m->file->seek(m->file->getLastOffset() + bytes, SEEK_SET);
761
23.9k
        for (qpdf_offset_t i = obj; i - num < obj; ++i) {
762
17.9k
            if (i == 0) {
763
                // This is needed by checkLinearization()
764
453
                first_xref_item_offset_ = m->file->tell();
765
453
            }
766
            // For xref_table, these will always be small enough to be ints
767
17.9k
            qpdf_offset_t f1 = 0;
768
17.9k
            int f2 = 0;
769
17.9k
            char type = '\0';
770
17.9k
            if (!read_xrefEntry(f1, f2, type)) {
771
596
                throw damagedPDF(
772
596
                    "xref table", "invalid xref entry (obj=" + std::to_string(i) + ")");
773
596
            }
774
17.3k
            if (type == 'f') {
775
2.01k
                insertFreeXrefEntry(QPDFObjGen(toI(i), f2));
776
15.3k
            } else {
777
15.3k
                insertXrefEntry(toI(i), 1, f1, f2);
778
15.3k
            }
779
17.3k
        }
780
5.99k
        qpdf_offset_t pos = m->file->tell();
781
5.99k
        if (readToken(*m->file).isWord("trailer")) {
782
556
            break;
783
5.43k
        } else {
784
5.43k
            m->file->seek(pos, SEEK_SET);
785
5.43k
        }
786
5.99k
    }
787
788
    // Set offset to previous xref table if any
789
588
    QPDFObjectHandle cur_trailer = m->objects.readTrailer();
790
588
    if (!cur_trailer.isDictionary()) {
791
116
        throw damagedPDF("", "expected trailer dictionary");
792
116
    }
793
794
472
    if (!m->trailer) {
795
393
        setTrailer(cur_trailer);
796
797
393
        if (!m->trailer.hasKey("/Size")) {
798
135
            throw damagedPDF("trailer", "trailer dictionary lacks /Size key");
799
135
        }
800
258
        if (!m->trailer.getKey("/Size").isInteger()) {
801
4
            throw damagedPDF("trailer", "/Size key in trailer dictionary is not an integer");
802
4
        }
803
258
    }
804
805
333
    if (cur_trailer.hasKey("/XRefStm")) {
806
25
        if (cf.ignore_xref_streams()) {
807
0
            QTC::TC("qpdf", "QPDF ignoring XRefStm in trailer");
808
25
        } else {
809
25
            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
24
                (void)read_xrefStream(cur_trailer.getKey("/XRefStm").getIntValue());
813
24
            } else {
814
1
                throw damagedPDF("xref stream", xref_offset, "invalid /XRefStm");
815
1
            }
816
25
        }
817
25
    }
818
819
332
    if (cur_trailer.hasKey("/Prev")) {
820
57
        if (!cur_trailer.getKey("/Prev").isInteger()) {
821
1
            throw damagedPDF("trailer", "/Prev key in trailer dictionary is not an integer");
822
1
        }
823
56
        return cur_trailer.getKey("/Prev").getIntValue();
824
57
    }
825
826
275
    return 0;
827
332
}
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.0k
{
833
10.0k
    if (!cf.ignore_xref_streams()) {
834
10.0k
        QPDFObjectHandle xref_obj;
835
10.0k
        try {
836
10.0k
            m->in_read_xref_stream = true;
837
10.0k
            xref_obj = readObjectAtOffset(xref_offset, "xref stream", true);
838
10.0k
        } catch (QPDFExc&) {
839
            // ignore -- report error below
840
1.20k
        }
841
10.0k
        m->in_read_xref_stream = false;
842
9.95k
        if (xref_obj.isStreamOfType("/XRef")) {
843
7.74k
            return processXRefStream(xref_offset, xref_obj, in_stream_recovery);
844
7.74k
        }
845
9.95k
    }
846
847
2.21k
    throw damagedPDF("", xref_offset, "xref not found");
848
0
    return 0; // unreachable
849
10.0k
}
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
7.74k
{
855
7.74k
    auto W_obj = dict.getKey("/W");
856
7.74k
    if (!(W_obj.size() >= 3 && W_obj.getArrayItem(0).isInteger() &&
857
7.49k
          W_obj.getArrayItem(1).isInteger() && W_obj.getArrayItem(2).isInteger())) {
858
271
        throw damaged("Cross-reference stream does not have a proper /W key");
859
271
    }
860
861
7.47k
    std::array<int, 3> W;
862
7.47k
    int entry_size = 0;
863
7.47k
    auto w_vector = W_obj.getArrayAsVector();
864
7.47k
    int max_bytes = sizeof(qpdf_offset_t);
865
29.7k
    for (size_t i = 0; i < 3; ++i) {
866
22.3k
        W[i] = w_vector[i].getIntValueAsInt();
867
22.3k
        if (W[i] > max_bytes) {
868
23
            throw damaged("Cross-reference stream's /W contains impossibly large values");
869
23
        }
870
22.3k
        if (W[i] < 0) {
871
45
            throw damaged("Cross-reference stream's /W contains negative values");
872
45
        }
873
22.2k
        entry_size += W[i];
874
22.2k
    }
875
7.40k
    if (entry_size == 0) {
876
4
        throw damaged("Cross-reference stream's /W indicates entry size of 0");
877
4
    }
878
7.39k
    return {entry_size, W};
879
7.40k
}
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.39k
{
886
    // Number of entries is limited by the highest possible object id and stream size.
887
7.39k
    auto max_num_entries = std::numeric_limits<int>::max();
888
7.39k
    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.39k
    auto Size_obj = dict.getKey("/Size");
893
7.39k
    long long size;
894
7.39k
    if (!dict.getKey("/Size").getValueAsInt(size)) {
895
96
        throw damaged("Cross-reference stream does not have a proper /Size key");
896
7.30k
    } else if (size < 0) {
897
72
        throw damaged("Cross-reference stream has a negative /Size key");
898
7.22k
    } else if (size >= max_num_entries) {
899
66
        throw damaged("Cross-reference stream has an impossibly large /Size key");
900
66
    }
901
    // We are not validating that Size <= (Size key of parent xref / trailer).
902
7.16k
    return max_num_entries;
903
7.39k
}
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.16k
{
910
7.16k
    auto size = dict.getKey("/Size").getIntValueAsInt();
911
7.16k
    auto Index_obj = dict.getKey("/Index");
912
913
7.16k
    if (Index_obj.isArray()) {
914
1.19k
        std::vector<std::pair<int, int>> indx;
915
1.19k
        int num_entries = 0;
916
1.19k
        auto index_vec = Index_obj.getArrayAsVector();
917
1.19k
        if ((index_vec.size() % 2) || index_vec.size() < 2) {
918
14
            throw damaged("Cross-reference stream's /Index has an invalid number of values");
919
14
        }
920
921
1.17k
        int i = 0;
922
1.17k
        long long first = 0;
923
20.7k
        for (auto& val: index_vec) {
924
20.7k
            if (val.isInteger()) {
925
20.7k
                if (i % 2) {
926
10.3k
                    auto count = val.getIntValue();
927
10.3k
                    if (count <= 0) {
928
72
                        throw damaged(
929
72
                            "Cross-reference stream section claims to contain " +
930
72
                            std::to_string(count) + " entries");
931
72
                    }
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
10.2k
                    if (first > (max_num_entries - count) ||
938
10.1k
                        count > (max_num_entries - num_entries)) {
939
85
                        throw damaged(
940
85
                            "Cross-reference stream claims to contain too many entries: " +
941
85
                            std::to_string(first) + " " + std::to_string(max_num_entries) + " " +
942
85
                            std::to_string(num_entries));
943
85
                    }
944
10.1k
                    indx.emplace_back(static_cast<int>(first), static_cast<int>(count));
945
10.1k
                    num_entries += static_cast<int>(count);
946
10.4k
                } else {
947
10.4k
                    first = val.getIntValue();
948
10.4k
                    if (first < 0) {
949
46
                        throw damaged(
950
46
                            "Cross-reference stream's /Index contains a negative object id");
951
10.3k
                    } else if (first > max_num_entries) {
952
73
                        throw damaged(
953
73
                            "Cross-reference stream's /Index contains an impossibly "
954
73
                            "large object id");
955
73
                    }
956
10.4k
                }
957
20.7k
            } else {
958
9
                throw damaged(
959
9
                    "Cross-reference stream's /Index's item " + std::to_string(i) +
960
9
                    " is not an integer");
961
9
            }
962
20.4k
            i++;
963
20.4k
        }
964
893
        QTC::TC("qpdf", "QPDF xref /Index is array", index_vec.size() == 2 ? 0 : 1);
965
893
        return {num_entries, indx};
966
5.97k
    } else if (Index_obj.null()) {
967
5.96k
        return {size, {{0, size}}};
968
5.96k
    } else {
969
5
        throw damaged("Cross-reference stream does not have a proper /Index key");
970
5
    }
971
7.16k
}
972
973
qpdf_offset_t
974
Objects::processXRefStream(
975
    qpdf_offset_t xref_offset, QPDFObjectHandle& xref_obj, bool in_stream_recovery)
976
7.74k
{
977
7.74k
    auto damaged = [this, xref_offset](std::string_view msg) -> QPDFExc {
978
4.55k
        return damagedPDF("xref stream", xref_offset, msg.data());
979
4.55k
    };
980
981
7.74k
    auto dict = xref_obj.getDict();
982
983
7.74k
    auto [entry_size, W] = processXRefW(dict, damaged);
984
7.74k
    int max_num_entries = processXRefSize(dict, entry_size, damaged);
985
7.74k
    auto [num_entries, indx] = processXRefIndex(dict, max_num_entries, damaged);
986
987
7.74k
    std::shared_ptr<Buffer> bp = xref_obj.getStreamData(qpdf_dl_specialized);
988
7.74k
    size_t actual_size = bp->getSize();
989
7.74k
    auto expected_size = toS(entry_size) * toS(num_entries);
990
991
7.74k
    if (expected_size != actual_size) {
992
3.67k
        QPDFExc x = damaged(
993
3.67k
            "Cross-reference stream data has the wrong size; expected = " +
994
3.67k
            std::to_string(expected_size) + "; actual = " + std::to_string(actual_size));
995
3.67k
        if (expected_size > actual_size) {
996
791
            throw x;
997
2.88k
        } else {
998
2.88k
            warn(x);
999
2.88k
        }
1000
3.67k
    }
1001
1002
6.95k
    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
6.95k
    auto p = bp->getBuffer();
1007
6.95k
    for (auto [obj, sec_entries]: indx) {
1008
        // Process a subsection.
1009
752k
        for (int i = 0; i < sec_entries; ++i) {
1010
            // Read this entry
1011
746k
            std::array<qpdf_offset_t, 3> fields{};
1012
746k
            if (W[0] == 0) {
1013
187k
                fields[0] = 1;
1014
187k
            }
1015
2.98M
            for (size_t j = 0; j < 3; ++j) {
1016
4.80M
                for (int k = 0; k < W[j]; ++k) {
1017
2.56M
                    fields[j] <<= 8;
1018
2.56M
                    fields[j] |= *p++;
1019
2.56M
                }
1020
2.23M
            }
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
746k
            if (saw_first_compressed_object) {
1025
525k
                if (fields[0] != 2) {
1026
196k
                    uncompressed_after_compressed_ = true;
1027
196k
                }
1028
525k
            } else if (fields[0] == 2) {
1029
2.09k
                saw_first_compressed_object = true;
1030
2.09k
            }
1031
746k
            if (obj == 0) {
1032
                // This is needed by checkLinearization()
1033
3.05k
                first_xref_item_offset_ = xref_offset;
1034
743k
            } 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
76.8k
                insertFreeXrefEntry(QPDFObjGen(obj, 0));
1039
666k
            } else {
1040
666k
                auto typ = toI(fields[0]);
1041
666k
                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
604k
                    insertXrefEntry(obj, toI(fields[0]), fields[1], toI(fields[2]));
1046
604k
                }
1047
666k
            }
1048
746k
            ++obj;
1049
746k
        }
1050
5.76k
    }
1051
1052
6.95k
    if (!m->trailer) {
1053
776
        setTrailer(dict);
1054
776
    }
1055
1056
6.95k
    if (dict.hasKey("/Prev")) {
1057
1.16k
        if (!dict.getKey("/Prev").isInteger()) {
1058
86
            throw damagedPDF(
1059
86
                "xref stream", "/Prev key in xref stream dictionary is not an integer");
1060
86
        }
1061
1.07k
        return dict.getKey("/Prev").getIntValue();
1062
5.79k
    } else {
1063
5.79k
        return 0;
1064
5.79k
    }
1065
6.95k
}
1066
1067
void
1068
Objects::insertXrefEntry(int obj, int f0, qpdf_offset_t f1, int f2)
1069
729k
{
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
729k
    int new_gen = f0 == 2 ? 0 : f2;
1077
1078
729k
    if (!(f0 == 1 || f0 == 2)) {
1079
41.8k
        return;
1080
41.8k
    }
1081
1082
687k
    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
184k
        return;
1088
184k
    }
1089
1090
502k
    if (m->deleted_objects.contains(obj)) {
1091
640
        return;
1092
640
    }
1093
1094
502k
    if (f0 == 2) {
1095
272k
        if (f1 == obj) {
1096
645
            warn(
1097
645
                damagedPDF("xref stream", "self-referential object stream " + std::to_string(obj)));
1098
645
            return;
1099
645
        }
1100
272k
        if (f1 > m->xref_table_max_id) {
1101
            // ignore impossibly large object stream ids
1102
8.73k
            warn(damagedPDF(
1103
8.73k
                "xref stream",
1104
8.73k
                "object stream id " + std::to_string(f1) + " for object " + std::to_string(obj) +
1105
8.73k
                    " is impossibly large"));
1106
8.73k
            return;
1107
8.73k
        }
1108
272k
    }
1109
1110
492k
    auto [iter, created] = m->xref_table.try_emplace(QPDFObjGen(obj, (f0 == 2 ? 0 : f2)));
1111
492k
    if (!created) {
1112
25.4k
        return;
1113
25.4k
    }
1114
1115
467k
    switch (f0) {
1116
206k
    case 1:
1117
        // f2 is generation
1118
206k
        QTC::TC("qpdf", "QPDF xref gen > 0", ((f2 > 0) ? 1 : 0));
1119
206k
        iter->second = QPDFXRefEntry(f1);
1120
206k
        break;
1121
1122
261k
    case 2:
1123
261k
        iter->second = QPDFXRefEntry(toI(f1), f2);
1124
261k
        break;
1125
1126
0
    default:
1127
0
        throw damagedPDF("xref stream", "unknown xref stream entry type " + std::to_string(f0));
1128
0
        break;
1129
467k
    }
1130
467k
}
1131
1132
void
1133
Objects::insertFreeXrefEntry(QPDFObjGen og)
1134
78.8k
{
1135
78.8k
    if (!m->xref_table.contains(og) && og.getObj() <= m->xref_table_max_id) {
1136
37.9k
        m->deleted_objects.insert(og.getObj());
1137
37.9k
    }
1138
78.8k
}
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
9.77k
{
1171
9.77k
    bool may_change = !m->reconstructed_xref;
1172
222k
    for (auto& iter: m->xref_table) {
1173
222k
        if (isUnresolved(iter.first)) {
1174
137k
            resolve(iter.first);
1175
137k
            if (may_change && m->reconstructed_xref) {
1176
50
                return false;
1177
50
            }
1178
137k
        }
1179
222k
    }
1180
9.72k
    return true;
1181
9.77k
}
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
23.0k
{
1188
23.0k
    if (m->fixed_dangling_refs) {
1189
13.3k
        return;
1190
13.3k
    }
1191
9.72k
    if (!m->objects.resolveXRefTable()) {
1192
50
        m->objects.resolveXRefTable();
1193
50
    }
1194
9.72k
    m->fixed_dangling_refs = true;
1195
9.72k
}
1196
1197
size_t
1198
QPDF::getObjectCount()
1199
13.8k
{
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
13.8k
    fixDanglingReferences();
1204
13.8k
    QPDFObjGen og;
1205
13.8k
    if (!m->obj_cache.empty()) {
1206
13.8k
        og = (*(m->obj_cache.rbegin())).first;
1207
13.8k
    }
1208
13.8k
    return QIntC::to_size(og.getObj());
1209
13.8k
}
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
214k
{
1226
214k
    m->last_object_description.clear();
1227
214k
    if (!description.empty()) {
1228
8.82k
        m->last_object_description += description;
1229
8.82k
        if (og.isIndirect()) {
1230
8.82k
            m->last_object_description += ": ";
1231
8.82k
        }
1232
8.82k
    }
1233
214k
    if (og.isIndirect()) {
1234
214k
        m->last_object_description += "object " + og.unparse(' ');
1235
214k
    }
1236
214k
}
1237
1238
QPDFObjectHandle
1239
Objects::readTrailer()
1240
16.2k
{
1241
16.2k
    qpdf_offset_t offset = m->file->tell();
1242
16.2k
    auto object =
1243
16.2k
        QPDFParser::parse(*m->file, "trailer", m->tokenizer, nullptr, qpdf, m->reconstructed_xref);
1244
16.2k
    if (object.isDictionary() && m->objects.readToken(*m->file).isWord("stream")) {
1245
123
        warn(damagedPDF("trailer", m->file->tell(), "stream keyword found in trailer"));
1246
123
    }
1247
    // Override last_offset so that it points to the beginning of the object we just read
1248
16.2k
    m->file->setLastOffset(offset);
1249
16.2k
    return object;
1250
16.2k
}
1251
1252
QPDFObjectHandle
1253
Objects::readObject(std::string const& description, QPDFObjGen og)
1254
108k
{
1255
108k
    setLastObjectDescription(description, og);
1256
108k
    qpdf_offset_t offset = m->file->tell();
1257
1258
108k
    StringDecrypter decrypter{&qpdf, og};
1259
108k
    StringDecrypter* decrypter_ptr = m->encp->encrypted ? &decrypter : nullptr;
1260
108k
    auto object = QPDFParser::parse(
1261
108k
        *m->file,
1262
108k
        m->last_object_description,
1263
108k
        m->tokenizer,
1264
108k
        decrypter_ptr,
1265
108k
        qpdf,
1266
108k
        m->reconstructed_xref || m->in_read_xref_stream);
1267
108k
    if (!object) {
1268
7.98k
        return {};
1269
7.98k
    }
1270
100k
    auto token = readToken(*m->file);
1271
100k
    if (object.isDictionary() && token.isWord("stream")) {
1272
47.5k
        readStream(object, og, offset);
1273
47.5k
        token = readToken(*m->file);
1274
47.5k
    }
1275
100k
    if (!token.isWord("endobj")) {
1276
31.9k
        warn(damagedPDF("expected endobj"));
1277
31.9k
    }
1278
100k
    return object;
1279
108k
}
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
47.5k
{
1285
47.5k
    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
47.5k
    qpdf_offset_t stream_offset = m->file->tell();
1290
47.5k
    size_t length = 0;
1291
1292
47.5k
    try {
1293
47.5k
        auto length_obj = object.getKey("/Length");
1294
1295
47.5k
        if (!length_obj.isInteger()) {
1296
21.3k
            if (length_obj.null()) {
1297
21.1k
                throw damagedPDF(offset, "stream dictionary lacks /Length key");
1298
21.1k
            }
1299
225
            throw damagedPDF(offset, "/Length key in stream dictionary is not an integer");
1300
21.3k
        }
1301
1302
26.1k
        length = toS(length_obj.getUIntValue());
1303
        // Seek in two steps to avoid potential integer overflow
1304
26.1k
        m->file->seek(stream_offset, SEEK_SET);
1305
26.1k
        m->file->seek(toO(length), SEEK_CUR);
1306
26.1k
        if (!readToken(*m->file).isWord("endstream")) {
1307
7.05k
            throw damagedPDF("expected endstream");
1308
7.05k
        }
1309
34.8k
    } catch (QPDFExc& e) {
1310
34.8k
        if (!cf.surpress_recovery()) {
1311
34.8k
            warn(e);
1312
34.8k
            length = recoverStreamLength(m->file, og, stream_offset);
1313
34.8k
        } else {
1314
0
            throw;
1315
0
        }
1316
34.8k
    }
1317
39.6k
    object = QPDFObjectHandle(qpdf::Stream(qpdf, og, object, stream_offset, length));
1318
39.6k
}
1319
1320
void
1321
Objects::validateStreamLineEnd(QPDFObjectHandle& object, QPDFObjGen og, qpdf_offset_t offset)
1322
47.5k
{
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
54.2k
    while (true) {
1331
54.2k
        char ch;
1332
54.2k
        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
191
            return;
1336
191
        }
1337
54.0k
        if (ch == '\n') {
1338
            // ready to read stream data
1339
25.0k
            return;
1340
25.0k
        }
1341
28.9k
        if (ch == '\r') {
1342
            // Read another character
1343
17.5k
            if (m->file->read(&ch, 1) != 0) {
1344
17.5k
                if (ch == '\n') {
1345
                    // Ready to read stream data
1346
14.6k
                    QTC::TC("qpdf", "QPDF stream with CRNL");
1347
14.6k
                } 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.92k
                    m->file->unreadCh(ch);
1351
2.92k
                    warn(damagedPDF(
1352
2.92k
                        m->file->tell(), "stream keyword followed by carriage return only"));
1353
2.92k
                }
1354
17.5k
            }
1355
17.5k
            return;
1356
17.5k
        }
1357
11.3k
        if (!util::is_space(ch)) {
1358
4.61k
            m->file->unreadCh(ch);
1359
4.61k
            warn(damagedPDF(
1360
4.61k
                m->file->tell(), "stream keyword not followed by proper line terminator"));
1361
4.61k
            return;
1362
4.61k
        }
1363
6.74k
        warn(damagedPDF(m->file->tell(), "stream keyword followed by extraneous whitespace"));
1364
6.74k
    }
1365
47.5k
}
1366
1367
bool
1368
Objects ::findEndstream()
1369
31.1k
{
1370
    // Find endstream or endobj. Position the input at that token.
1371
31.1k
    auto t = readToken(*m->file, 20);
1372
31.1k
    if (t.isWord("endobj") || t.isWord("endstream")) {
1373
26.5k
        m->file->seek(m->file->getLastOffset(), SEEK_SET);
1374
26.5k
        return true;
1375
26.5k
    }
1376
4.56k
    return false;
1377
31.1k
}
1378
1379
size_t
1380
Objects::recoverStreamLength(
1381
    std::shared_ptr<InputSource> input, QPDFObjGen og, qpdf_offset_t stream_offset)
1382
27.1k
{
1383
    // Try to reconstruct stream length by looking for endstream or endobj
1384
27.1k
    warn(damagedPDF(*input, stream_offset, "attempting to recover stream length"));
1385
1386
27.1k
    PatternFinder ef(*this, &Objects::findEndstream);
1387
27.1k
    size_t length = 0;
1388
27.1k
    if (m->file->findFirst("end", stream_offset, 0, ef)) {
1389
26.5k
        length = toS(m->file->tell() - stream_offset);
1390
        // Reread endstream but, if it was endobj, don't skip that.
1391
26.5k
        QPDFTokenizer::Token t = readToken(*m->file);
1392
26.5k
        if (t.getValue() == "endobj") {
1393
19.1k
            m->file->seek(m->file->getLastOffset(), SEEK_SET);
1394
19.1k
        }
1395
26.5k
    }
1396
1397
27.1k
    if (length) {
1398
25.4k
        auto end = stream_offset + toO(length);
1399
25.4k
        qpdf_offset_t found_offset = 0;
1400
25.4k
        QPDFObjGen found_og;
1401
1402
        // Make sure this is inside this object
1403
440k
        for (auto const& [current_og, entry]: m->xref_table) {
1404
440k
            if (entry.getType() == 1) {
1405
428k
                qpdf_offset_t obj_offset = entry.getOffset();
1406
428k
                if (found_offset < obj_offset && obj_offset < end) {
1407
126k
                    found_offset = obj_offset;
1408
126k
                    found_og = current_og;
1409
126k
                }
1410
428k
            }
1411
440k
        }
1412
25.4k
        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
23.7k
        } else {
1418
1.71k
            length = 0;
1419
1.71k
        }
1420
25.4k
    }
1421
1422
27.1k
    if (length == 0) {
1423
3.44k
        warn(damagedPDF(
1424
3.44k
            *input, stream_offset, "unable to recover stream data; treating stream as empty"));
1425
23.7k
    } else {
1426
23.7k
        warn(damagedPDF(
1427
23.7k
            *input, stream_offset, "recovered stream length: " + std::to_string(length)));
1428
23.7k
    }
1429
1430
27.1k
    return length;
1431
27.1k
}
1432
1433
QPDFTokenizer::Token
1434
Objects::readToken(InputSource& input, size_t max_len)
1435
2.19M
{
1436
2.19M
    return m->tokenizer.readToken(input, m->last_object_description, true, max_len);
1437
2.19M
}
1438
1439
QPDFObjGen
1440
Objects::read_object_start(qpdf_offset_t offset)
1441
115k
{
1442
115k
    m->file->seek(offset, SEEK_SET);
1443
115k
    QPDFTokenizer::Token tobjid = readToken(*m->file);
1444
115k
    bool objidok = tobjid.isInteger();
1445
115k
    if (!objidok) {
1446
3.58k
        throw damagedPDF(offset, "expected n n obj");
1447
3.58k
    }
1448
111k
    QPDFTokenizer::Token tgen = readToken(*m->file);
1449
111k
    bool genok = tgen.isInteger();
1450
111k
    if (!genok) {
1451
555
        throw damagedPDF(offset, "expected n n obj");
1452
555
    }
1453
110k
    QPDFTokenizer::Token tobj = readToken(*m->file);
1454
1455
110k
    bool objok = tobj.isWord("obj");
1456
1457
110k
    if (!objok) {
1458
885
        throw damagedPDF(offset, "expected n n obj");
1459
885
    }
1460
110k
    int objid = QUtil::string_to_int(tobjid.getValue().c_str());
1461
110k
    int generation = QUtil::string_to_int(tgen.getValue().c_str());
1462
110k
    if (objid == 0) {
1463
194
        throw damagedPDF(offset, "object with ID 0");
1464
194
    }
1465
109k
    return {objid, generation};
1466
110k
}
1467
1468
void
1469
Objects::readObjectAtOffset(
1470
    bool try_recovery, qpdf_offset_t offset, std::string const& description, QPDFObjGen exp_og)
1471
105k
{
1472
105k
    QPDFObjGen og;
1473
105k
    setLastObjectDescription(description, exp_og);
1474
1475
105k
    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
105k
    if (offset == 0) {
1484
294
        warn(damagedPDF(
1485
294
            -1,
1486
294
            "object has offset 0 - a common error handled correctly by qpdf and most other "
1487
294
            "applications"));
1488
294
        return;
1489
294
    }
1490
1491
105k
    try {
1492
105k
        og = read_object_start(offset);
1493
105k
        if (exp_og != og) {
1494
355
            QPDFExc e = damagedPDF(offset, "expected " + exp_og.unparse(' ') + " obj");
1495
355
            if (try_recovery) {
1496
                // Will be retried below
1497
355
                throw e;
1498
355
            } else {
1499
                // We can try reading the object anyway even if the ID doesn't match.
1500
0
                warn(e);
1501
0
            }
1502
355
        }
1503
105k
    } catch (QPDFExc& e) {
1504
4.43k
        if (!try_recovery) {
1505
0
            throw;
1506
0
        }
1507
        // Try again after reconstructing xref table
1508
4.43k
        reconstruct_xref(e);
1509
4.43k
        if (m->xref_table.contains(exp_og) && m->xref_table[exp_og].getType() == 1) {
1510
63
            qpdf_offset_t new_offset = m->xref_table[exp_og].getOffset();
1511
63
            readObjectAtOffset(false, new_offset, description, exp_og);
1512
63
            return;
1513
63
        }
1514
4.37k
        warn(damagedPDF(
1515
4.37k
            "",
1516
4.37k
            -1,
1517
4.37k
            ("object " + exp_og.unparse(' ') +
1518
4.37k
             " not found in file after regenerating cross reference table")));
1519
4.37k
        return;
1520
4.43k
    }
1521
1522
99.9k
    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
81.0k
        qpdf_offset_t end_before_space = m->file->tell();
1527
1528
        // skip over spaces
1529
177k
        while (true) {
1530
177k
            char ch;
1531
177k
            if (!m->file->read(&ch, 1)) {
1532
803
                throw damagedPDF(m->file->tell(), "EOF after endobj");
1533
803
            }
1534
177k
            if (!isspace(static_cast<unsigned char>(ch))) {
1535
80.2k
                m->file->seek(-1, SEEK_CUR);
1536
80.2k
                break;
1537
80.2k
            }
1538
177k
        }
1539
80.2k
        m->objects.updateCache(og, oh.obj_sp(), end_before_space, m->file->tell());
1540
80.2k
    }
1541
99.9k
}
1542
1543
QPDFObjectHandle
1544
Objects::readObjectAtOffset(
1545
    qpdf_offset_t offset, std::string const& description, bool skip_cache_if_in_xref)
1546
10.0k
{
1547
10.0k
    auto og = read_object_start(offset);
1548
10.0k
    auto oh = readObject(description, og);
1549
1550
10.0k
    if (!oh || !m->objects.isUnresolved(og)) {
1551
5.76k
        return oh;
1552
5.76k
    }
1553
1554
4.24k
    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
12
        QTC::TC("qpdf", "QPDF skipping cache for known unchecked object");
1580
12
        return oh;
1581
12
    }
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
4.23k
    qpdf_offset_t end_before_space = m->file->tell();
1587
1588
    // skip over spaces
1589
7.45k
    while (true) {
1590
6.25k
        char ch;
1591
6.25k
        if (!m->file->read(&ch, 1)) {
1592
56
            throw damagedPDF(m->file->tell(), "EOF after endobj");
1593
56
        }
1594
6.19k
        if (!isspace(static_cast<unsigned char>(ch))) {
1595
2.97k
            m->file->seek(-1, SEEK_CUR);
1596
2.97k
            break;
1597
2.97k
        }
1598
6.19k
    }
1599
4.17k
    m->objects.updateCache(og, oh.obj_sp(), end_before_space, m->file->tell());
1600
1601
4.17k
    return oh;
1602
4.23k
}
1603
1604
std::shared_ptr<QPDFObject> const&
1605
Objects::resolve(QPDFObjGen og)
1606
310k
{
1607
310k
    if (!isUnresolved(og)) {
1608
0
        return m->obj_cache[og].object;
1609
0
    }
1610
1611
310k
    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
212
        warn(damagedPDF("", "loop detected resolving object " + og.unparse(' ')));
1615
212
        updateCache(og, QPDFObject::create<QPDF_Null>(), -1, -1);
1616
212
        return m->obj_cache[og].object;
1617
212
    }
1618
310k
    ResolveRecorder rr(qpdf, og);
1619
1620
310k
    if (m->xref_table.contains(og)) {
1621
257k
        QPDFXRefEntry const& entry = m->xref_table[og];
1622
257k
        try {
1623
257k
            switch (entry.getType()) {
1624
105k
            case 1:
1625
                // Object stored in cache by readObjectAtOffset
1626
105k
                readObjectAtOffset(true, entry.getOffset(), "", og);
1627
105k
                break;
1628
1629
151k
            case 2:
1630
151k
                resolveObjectsInStream(entry.getObjStreamNumber());
1631
151k
                break;
1632
1633
10
            default:
1634
10
                throw damagedPDF(
1635
10
                    "", -1, ("object " + og.unparse('/') + " has unexpected xref entry type"));
1636
257k
            }
1637
257k
        } catch (QPDFExc& e) {
1638
42.4k
            warn(e);
1639
42.4k
        } catch (std::exception& e) {
1640
801
            warn(damagedPDF(
1641
801
                "", -1, ("object " + og.unparse('/') + ": error reading object: " + e.what())));
1642
801
        }
1643
257k
    }
1644
1645
296k
    if (isUnresolved(og)) {
1646
        // PDF spec says unknown objects resolve to the null object.
1647
215k
        updateCache(og, QPDFObject::create<QPDF_Null>(), -1, -1);
1648
215k
    }
1649
1650
296k
    auto& result(m->obj_cache[og].object);
1651
296k
    result->setDefaultDescription(&qpdf, og);
1652
296k
    return result;
1653
310k
}
1654
1655
void
1656
Objects::resolveObjectsInStream(int obj_stream_number)
1657
151k
{
1658
151k
    auto damaged =
1659
151k
        [this, obj_stream_number](int id, qpdf_offset_t offset, std::string const& msg) -> QPDFExc {
1660
20.7k
        return {
1661
20.7k
            qpdf_e_damaged_pdf,
1662
20.7k
            m->file->getName() + " object stream " + std::to_string(obj_stream_number),
1663
20.7k
            +"object " + std::to_string(id) + " 0",
1664
20.7k
            offset,
1665
20.7k
            msg,
1666
20.7k
            true};
1667
20.7k
    };
1668
1669
151k
    if (m->resolved_object_streams.contains(obj_stream_number)) {
1670
124k
        return;
1671
124k
    }
1672
27.0k
    m->resolved_object_streams.insert(obj_stream_number);
1673
    // Force resolution of object stream
1674
27.0k
    Stream obj_stream = qpdf.getObject(obj_stream_number, 0);
1675
27.0k
    if (!obj_stream) {
1676
24.0k
        throw damagedPDF(
1677
24.0k
            "object " + std::to_string(obj_stream_number) + " 0",
1678
24.0k
            "supposed object stream " + std::to_string(obj_stream_number) + " is not a stream");
1679
24.0k
    }
1680
1681
    // For linearization data in the object, use the data from the object stream for the objects in
1682
    // the stream.
1683
3.03k
    QPDFObjGen stream_og(obj_stream_number, 0);
1684
3.03k
    qpdf_offset_t end_before_space = m->obj_cache[stream_og].end_before_space;
1685
3.03k
    qpdf_offset_t end_after_space = m->obj_cache[stream_og].end_after_space;
1686
1687
3.03k
    QPDFObjectHandle dict = obj_stream.getDict();
1688
3.03k
    if (!dict.isDictionaryOfType("/ObjStm")) {
1689
953
        warn(damagedPDF(
1690
953
            "object " + std::to_string(obj_stream_number) + " 0",
1691
953
            "supposed object stream " + std::to_string(obj_stream_number) + " has wrong type"));
1692
953
    }
1693
1694
3.03k
    unsigned int n{0};
1695
3.03k
    int first{0};
1696
3.03k
    if (!(dict.getKey("/N").getValueAsUInt(n) && dict.getKey("/First").getValueAsInt(first))) {
1697
273
        throw damagedPDF(
1698
273
            "object " + std::to_string(obj_stream_number) + " 0",
1699
273
            "object stream " + std::to_string(obj_stream_number) + " has incorrect keys");
1700
273
    }
1701
1702
    // id, offset, size
1703
2.75k
    std::vector<std::tuple<int, qpdf_offset_t, size_t>> offsets;
1704
1705
2.75k
    auto stream_data = obj_stream.getStreamData(qpdf_dl_specialized);
1706
1707
2.75k
    is::OffsetBuffer input("", stream_data);
1708
1709
2.75k
    const auto b_size = stream_data.size();
1710
2.75k
    const auto end_offset = static_cast<qpdf_offset_t>(b_size);
1711
2.75k
    auto b_start = stream_data.data();
1712
1713
2.75k
    if (first >= end_offset) {
1714
77
        throw damagedPDF(
1715
77
            "object " + std::to_string(obj_stream_number) + " 0",
1716
77
            "object stream " + std::to_string(obj_stream_number) + " has invalid /First entry");
1717
77
    }
1718
1719
2.68k
    int id = 0;
1720
2.68k
    long long last_offset = -1;
1721
2.68k
    bool is_first = true;
1722
64.3k
    for (unsigned int i = 0; i < n; ++i) {
1723
61.8k
        auto tnum = readToken(input);
1724
61.8k
        auto id_offset = input.getLastOffset();
1725
61.8k
        auto toffset = readToken(input);
1726
61.8k
        if (!(tnum.isInteger() && toffset.isInteger())) {
1727
151
            throw damaged(0, input.getLastOffset(), "expected integer in object stream header");
1728
151
        }
1729
1730
61.6k
        int num = QUtil::string_to_int(tnum.getValue().c_str());
1731
61.6k
        long long offset = QUtil::string_to_int(toffset.getValue().c_str());
1732
1733
61.6k
        if (num == obj_stream_number) {
1734
400
            warn(damaged(num, id_offset, "object stream claims to contain itself"));
1735
400
            continue;
1736
400
        }
1737
1738
61.2k
        if (num < 1) {
1739
1.16k
            warn(damaged(num, id_offset, "object id is invalid"s));
1740
1.16k
            continue;
1741
1.16k
        }
1742
1743
60.0k
        if (offset <= last_offset) {
1744
10.4k
            warn(damaged(
1745
10.4k
                num,
1746
10.4k
                input.getLastOffset(),
1747
10.4k
                "offset " + std::to_string(offset) +
1748
10.4k
                    " is invalid (must be larger than previous offset " +
1749
10.4k
                    std::to_string(last_offset) + ")"));
1750
10.4k
            continue;
1751
10.4k
        }
1752
1753
49.6k
        if (num > m->xref_table_max_id) {
1754
1.58k
            continue;
1755
1.58k
        }
1756
1757
48.0k
        if (first + offset >= end_offset) {
1758
8.51k
            warn(damaged(
1759
8.51k
                num, input.getLastOffset(), "offset " + std::to_string(offset) + " is too large"));
1760
8.51k
            continue;
1761
8.51k
        }
1762
1763
39.5k
        if (is_first) {
1764
988
            is_first = false;
1765
38.5k
        } else {
1766
38.5k
            offsets.emplace_back(
1767
38.5k
                id, last_offset + first, static_cast<size_t>(offset - last_offset));
1768
38.5k
        }
1769
1770
39.5k
        last_offset = offset;
1771
39.5k
        id = num;
1772
39.5k
    }
1773
1774
2.53k
    if (!is_first) {
1775
        // We found at least one valid entry.
1776
851
        offsets.emplace_back(
1777
851
            id, last_offset + first, b_size - static_cast<size_t>(last_offset + first));
1778
851
    }
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
34.6k
    for (auto const& [obj_id, obj_offset, obj_size]: offsets) {
1785
34.6k
        QPDFObjGen og(obj_id, 0);
1786
34.6k
        auto entry = m->xref_table.find(og);
1787
34.6k
        if (entry != m->xref_table.end() && entry->second.getType() == 2 &&
1788
33.4k
            entry->second.getObjStreamNumber() == obj_stream_number) {
1789
28.3k
            is::OffsetBuffer in("", {b_start + obj_offset, obj_size}, obj_offset);
1790
28.3k
            if (auto oh = QPDFParser::parse(in, obj_stream_number, obj_id, m->tokenizer, qpdf)) {
1791
25.0k
                updateCache(og, oh.obj_sp(), end_before_space, end_after_space);
1792
25.0k
            }
1793
28.3k
        } else {
1794
6.31k
            QTC::TC("qpdf", "QPDF not caching overridden objstm object");
1795
6.31k
        }
1796
34.6k
    }
1797
2.53k
}
1798
1799
QPDFObjectHandle
1800
Objects::newIndirect(QPDFObjGen og, std::shared_ptr<QPDFObject> const& obj)
1801
3.78k
{
1802
3.78k
    obj->setDefaultDescription(&qpdf, og);
1803
3.78k
    return {obj};
1804
3.78k
}
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
323k
{
1814
323k
    object->setObjGen(&qpdf, og);
1815
323k
    if (isCached(og)) {
1816
180k
        auto& cache = m->obj_cache[og];
1817
180k
        object->move_to(cache.object, destroy);
1818
180k
        cache.end_before_space = end_before_space;
1819
180k
        cache.end_after_space = end_after_space;
1820
180k
    } else {
1821
143k
        m->obj_cache[og] = ObjCache(object, end_before_space, end_after_space);
1822
143k
    }
1823
323k
}
1824
1825
bool
1826
Objects::isCached(QPDFObjGen og)
1827
1.16M
{
1828
1.16M
    return m->obj_cache.contains(og);
1829
1.16M
}
1830
1831
bool
1832
Objects::isUnresolved(QPDFObjGen og)
1833
838k
{
1834
838k
    return !isCached(og) || m->obj_cache[og].object->isUnresolved();
1835
838k
}
1836
1837
QPDFObjGen
1838
Objects::nextObjGen()
1839
3.78k
{
1840
3.78k
    int max_objid = toI(qpdf.getObjectCount());
1841
3.78k
    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.78k
    return {max_objid + 1, 0};
1845
3.78k
}
1846
1847
QPDFObjectHandle
1848
Objects::makeIndirectFromQPDFObject(std::shared_ptr<QPDFObject> const& obj)
1849
3.78k
{
1850
3.78k
    QPDFObjGen next{nextObjGen()};
1851
3.78k
    m->obj_cache[next] = ObjCache(obj, -1, -1);
1852
3.78k
    return newIndirect(next, m->obj_cache[next].object);
1853
3.78k
}
1854
1855
QPDFObjectHandle
1856
QPDF::makeIndirectObject(QPDFObjectHandle oh)
1857
3.78k
{
1858
3.78k
    if (!oh) {
1859
0
        throw std::logic_error("attempted to make an uninitialized QPDFObjectHandle indirect");
1860
0
    }
1861
3.78k
    return m->objects.makeIndirectFromQPDFObject(oh.obj_sp());
1862
3.78k
}
1863
1864
std::shared_ptr<QPDFObject>
1865
Objects::getObjectForParser(int id, int gen, bool parse_pdf)
1866
245k
{
1867
    // This method is called by the parser and therefore must not resolve any objects.
1868
245k
    auto og = QPDFObjGen(id, gen);
1869
245k
    if (auto iter = m->obj_cache.find(og); iter != m->obj_cache.end()) {
1870
89.1k
        return iter->second.object;
1871
89.1k
    }
1872
155k
    if (m->xref_table.contains(og) || (!m->parsed && og.getObj() < m->xref_table_max_id)) {
1873
143k
        return m->obj_cache.insert({og, QPDFObject::create<QPDF_Unresolved>(&qpdf, og)})
1874
143k
            .first->second.object;
1875
143k
    }
1876
12.1k
    if (parse_pdf) {
1877
12.1k
        return QPDFObject::create<QPDF_Null>();
1878
12.1k
    }
1879
0
    return m->obj_cache.insert({og, QPDFObject::create<QPDF_Null>(&qpdf, og)}).first->second.object;
1880
12.1k
}
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
107k
{
1899
107k
    if (auto it = m->obj_cache.find(og); it != m->obj_cache.end()) {
1900
54.5k
        return {it->second.object};
1901
54.5k
    } else if (m->parsed && !m->xref_table.contains(og)) {
1902
5.24k
        return QPDFObject::create<QPDF_Null>();
1903
47.7k
    } else {
1904
47.7k
        auto result =
1905
47.7k
            m->obj_cache.try_emplace(og, QPDFObject::create<QPDF_Unresolved>(this, og), -1, -1);
1906
47.7k
        return {result.first->second.object};
1907
47.7k
    }
1908
107k
}
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
17.2k
{
1928
17.2k
    m->xref_table.erase(og);
1929
17.2k
    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
737
        cached->second.object->assign_null();
1932
737
        cached->second.object->setObjGen(nullptr, QPDFObjGen());
1933
737
        m->obj_cache.erase(cached);
1934
737
    }
1935
17.2k
}
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
9.25k
{
1966
    // If obj_cache is dense, accommodate all object in tables,else accommodate only original
1967
    // objects.
1968
9.25k
    auto max_xref = !m->xref_table.empty() ? m->xref_table.crbegin()->first.getObj() : 0;
1969
9.25k
    auto max_obj = !m->obj_cache.empty() ? m->obj_cache.crbegin()->first.getObj() : 0;
1970
9.25k
    auto max_id = std::numeric_limits<int>::max() - 1;
1971
9.25k
    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
1
        stopOnError("Impossibly large object id encountered.");
1976
1
    }
1977
9.25k
    if (max_obj < 1.1 * std::max(toI(m->obj_cache.size()), max_xref)) {
1978
7.77k
        return toS(++max_obj);
1979
7.77k
    }
1980
1.48k
    return toS(++max_xref);
1981
9.25k
}
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
887
{
1992
887
    return compressible<bool>();
1993
887
}
1994
1995
template <typename T>
1996
std::vector<T>
1997
Objects::compressible()
1998
887
{
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
887
    QPDFObjectHandle encryption_dict = m->trailer.getKey("/Encrypt");
2007
887
    QPDFObjGen encryption_dict_og = encryption_dict.getObjGen();
2008
2009
887
    const size_t max_obj = qpdf.getObjectCount();
2010
887
    std::vector<bool> visited(max_obj, false);
2011
887
    std::vector<QPDFObjectHandle> queue;
2012
887
    queue.reserve(512);
2013
887
    queue.emplace_back(m->trailer);
2014
887
    std::vector<T> result;
2015
887
    if constexpr (std::is_same_v<T, QPDFObjGen>) {
2016
0
        result.reserve(m->obj_cache.size());
2017
887
    } else {
2018
887
        qpdf_static_expect(std::is_same_v<T, bool>);
2019
887
        result.resize(max_obj + 1U, false);
2020
887
    }
2021
334k
    while (!queue.empty()) {
2022
334k
        auto obj = queue.back();
2023
334k
        queue.pop_back();
2024
334k
        if (obj.getObjectID() > 0) {
2025
36.5k
            QPDFObjGen og = obj.getObjGen();
2026
36.5k
            const size_t id = toS(og.getObj() - 1);
2027
36.5k
            if (id >= max_obj) {
2028
0
                throw std::logic_error(
2029
0
                    "unexpected object id encountered in getCompressibleObjGens");
2030
0
            }
2031
36.5k
            if (visited[id]) {
2032
10.8k
                continue;
2033
10.8k
            }
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
25.7k
            auto upper = m->obj_cache.upper_bound(og);
2039
25.7k
            if (upper != m->obj_cache.end() && upper->first.getObj() == og.getObj()) {
2040
494
                qpdf.removeObject(og);
2041
494
                continue;
2042
494
            }
2043
2044
25.2k
            visited[id] = true;
2045
2046
25.2k
            if (og == encryption_dict_og) {
2047
25
                QTC::TC("qpdf", "QPDF exclude encryption dictionary");
2048
25.1k
            } else if (!(obj.isStream() ||
2049
22.4k
                         (obj.isDictionaryOfType("/Sig") && obj.hasKey("/ByteRange") &&
2050
22.4k
                          obj.hasKey("/Contents")))) {
2051
22.4k
                if constexpr (std::is_same_v<T, QPDFObjGen>) {
2052
0
                    result.push_back(og);
2053
22.4k
                } else if constexpr (std::is_same_v<T, bool>) {
2054
22.4k
                    result[id + 1U] = true;
2055
22.4k
                }
2056
22.4k
            }
2057
25.2k
        }
2058
322k
        if (obj.isStream()) {
2059
2.73k
            auto dict = obj.getDict().as_dictionary();
2060
2.73k
            auto end = dict.crend();
2061
20.6k
            for (auto iter = dict.crbegin(); iter != end; ++iter) {
2062
17.8k
                std::string const& key = iter->first;
2063
17.8k
                QPDFObjectHandle const& value = iter->second;
2064
17.8k
                if (!value.null()) {
2065
16.0k
                    if (key == "/Length") {
2066
                        // omit stream lengths
2067
2.38k
                        if (value.isIndirect()) {
2068
219
                            QTC::TC("qpdf", "QPDF exclude indirect length");
2069
219
                        }
2070
13.7k
                    } else {
2071
13.7k
                        queue.emplace_back(value);
2072
13.7k
                    }
2073
16.0k
                }
2074
17.8k
            }
2075
319k
        } else if (obj.isDictionary()) {
2076
16.7k
            auto dict = obj.as_dictionary();
2077
16.7k
            auto end = dict.crend();
2078
85.2k
            for (auto iter = dict.crbegin(); iter != end; ++iter) {
2079
68.4k
                if (!iter->second.null()) {
2080
60.5k
                    queue.emplace_back(iter->second);
2081
60.5k
                }
2082
68.4k
            }
2083
303k
        } else if (auto items = obj.as_array()) {
2084
303k
            queue.insert(queue.end(), items.crbegin(), items.crend());
2085
303k
        }
2086
322k
    }
2087
2088
887
    return result;
2089
887
}
Unexecuted instantiation: std::__1::vector<QPDFObjGen, std::__1::allocator<QPDFObjGen> > QPDF::Doc::Objects::compressible<QPDFObjGen>()
std::__1::vector<bool, std::__1::allocator<bool> > QPDF::Doc::Objects::compressible<bool>()
Line
Count
Source
1998
887
{
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
887
    QPDFObjectHandle encryption_dict = m->trailer.getKey("/Encrypt");
2007
887
    QPDFObjGen encryption_dict_og = encryption_dict.getObjGen();
2008
2009
887
    const size_t max_obj = qpdf.getObjectCount();
2010
887
    std::vector<bool> visited(max_obj, false);
2011
887
    std::vector<QPDFObjectHandle> queue;
2012
887
    queue.reserve(512);
2013
887
    queue.emplace_back(m->trailer);
2014
887
    std::vector<T> result;
2015
    if constexpr (std::is_same_v<T, QPDFObjGen>) {
2016
        result.reserve(m->obj_cache.size());
2017
887
    } else {
2018
887
        qpdf_static_expect(std::is_same_v<T, bool>);
2019
887
        result.resize(max_obj + 1U, false);
2020
887
    }
2021
334k
    while (!queue.empty()) {
2022
334k
        auto obj = queue.back();
2023
334k
        queue.pop_back();
2024
334k
        if (obj.getObjectID() > 0) {
2025
36.5k
            QPDFObjGen og = obj.getObjGen();
2026
36.5k
            const size_t id = toS(og.getObj() - 1);
2027
36.5k
            if (id >= max_obj) {
2028
0
                throw std::logic_error(
2029
0
                    "unexpected object id encountered in getCompressibleObjGens");
2030
0
            }
2031
36.5k
            if (visited[id]) {
2032
10.8k
                continue;
2033
10.8k
            }
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
25.7k
            auto upper = m->obj_cache.upper_bound(og);
2039
25.7k
            if (upper != m->obj_cache.end() && upper->first.getObj() == og.getObj()) {
2040
494
                qpdf.removeObject(og);
2041
494
                continue;
2042
494
            }
2043
2044
25.2k
            visited[id] = true;
2045
2046
25.2k
            if (og == encryption_dict_og) {
2047
25
                QTC::TC("qpdf", "QPDF exclude encryption dictionary");
2048
25.1k
            } else if (!(obj.isStream() ||
2049
22.4k
                         (obj.isDictionaryOfType("/Sig") && obj.hasKey("/ByteRange") &&
2050
22.4k
                          obj.hasKey("/Contents")))) {
2051
                if constexpr (std::is_same_v<T, QPDFObjGen>) {
2052
                    result.push_back(og);
2053
22.4k
                } else if constexpr (std::is_same_v<T, bool>) {
2054
22.4k
                    result[id + 1U] = true;
2055
22.4k
                }
2056
22.4k
            }
2057
25.2k
        }
2058
322k
        if (obj.isStream()) {
2059
2.73k
            auto dict = obj.getDict().as_dictionary();
2060
2.73k
            auto end = dict.crend();
2061
20.6k
            for (auto iter = dict.crbegin(); iter != end; ++iter) {
2062
17.8k
                std::string const& key = iter->first;
2063
17.8k
                QPDFObjectHandle const& value = iter->second;
2064
17.8k
                if (!value.null()) {
2065
16.0k
                    if (key == "/Length") {
2066
                        // omit stream lengths
2067
2.38k
                        if (value.isIndirect()) {
2068
219
                            QTC::TC("qpdf", "QPDF exclude indirect length");
2069
219
                        }
2070
13.7k
                    } else {
2071
13.7k
                        queue.emplace_back(value);
2072
13.7k
                    }
2073
16.0k
                }
2074
17.8k
            }
2075
319k
        } else if (obj.isDictionary()) {
2076
16.7k
            auto dict = obj.as_dictionary();
2077
16.7k
            auto end = dict.crend();
2078
85.2k
            for (auto iter = dict.crbegin(); iter != end; ++iter) {
2079
68.4k
                if (!iter->second.null()) {
2080
60.5k
                    queue.emplace_back(iter->second);
2081
60.5k
                }
2082
68.4k
            }
2083
303k
        } else if (auto items = obj.as_array()) {
2084
303k
            queue.insert(queue.end(), items.crbegin(), items.crend());
2085
303k
        }
2086
322k
    }
2087
2088
887
    return result;
2089
887
}