Coverage Report

Created: 2026-12-01 06:44

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/qpdf/libqpdf/QPDFObjectHandle.cc
Line
Count
Source
1
#include <qpdf/QPDFObjectHandle_private.hh>
2
3
#include <qpdf/JSON_writer.hh>
4
#include <qpdf/Pipeline_private.hh>
5
#include <qpdf/Pl_Buffer.hh>
6
#include <qpdf/Pl_QPDFTokenizer.hh>
7
#include <qpdf/QIntC.hh>
8
#include <qpdf/QPDF.hh>
9
#include <qpdf/QPDFExc.hh>
10
#include <qpdf/QPDFLogger.hh>
11
#include <qpdf/QPDFMatrix.hh>
12
#include <qpdf/QPDFObject_private.hh>
13
#include <qpdf/QPDFPageObjectHelper.hh>
14
#include <qpdf/QPDFParser.hh>
15
#include <qpdf/QTC.hh>
16
#include <qpdf/Util.hh>
17
18
#include <array>
19
#include <cctype>
20
#include <climits>
21
#include <cstdlib>
22
#include <cstring>
23
#include <stdexcept>
24
#include <string_view>
25
26
using namespace std::literals;
27
using namespace qpdf;
28
29
using Parser = impl::Parser;
30
31
const Null Null::temp_;
32
33
BaseHandle::
34
operator QPDFObjGen() const
35
0
{
36
0
    return obj ? obj->getObjGen() : QPDFObjGen();
37
0
}
38
39
namespace
40
{
41
    class TerminateParsing
42
    {
43
    };
44
} // namespace
45
46
QPDFObjectHandle::StreamDataProvider::StreamDataProvider(bool supports_retry) :
47
14.7k
    supports_retry(supports_retry)
48
14.7k
{
49
14.7k
}
50
51
QPDFObjectHandle::StreamDataProvider::~StreamDataProvider() // NOLINT (modernize-use-equals-default)
52
14.7k
{
53
    // Must be explicit and not inline -- see QPDF_DLL_CLASS in README-maintainer
54
14.7k
}
55
56
void
57
QPDFObjectHandle::StreamDataProvider::provideStreamData(QPDFObjGen const& og, Pipeline* pipeline)
58
0
{
59
0
    return provideStreamData(og.getObj(), og.getGen(), pipeline);
60
0
}
61
62
bool
63
QPDFObjectHandle::StreamDataProvider::provideStreamData(
64
    QPDFObjGen const& og, Pipeline* pipeline, bool suppress_warnings, bool will_retry)
65
0
{
66
0
    return provideStreamData(og.getObj(), og.getGen(), pipeline, suppress_warnings, will_retry);
67
0
}
68
69
void
70
QPDFObjectHandle::StreamDataProvider::provideStreamData(
71
    int objid, int generation, Pipeline* pipeline)
72
0
{
73
0
    throw std::logic_error("you must override provideStreamData -- see QPDFObjectHandle.hh");
74
0
}
75
76
bool
77
QPDFObjectHandle::StreamDataProvider::provideStreamData(
78
    int objid, int generation, Pipeline* pipeline, bool suppress_warnings, bool will_retry)
79
0
{
80
0
    throw std::logic_error("you must override provideStreamData -- see QPDFObjectHandle.hh");
81
0
    return false;
82
0
}
83
84
bool
85
QPDFObjectHandle::StreamDataProvider::supportsRetry()
86
0
{
87
0
    return supports_retry;
88
0
}
89
90
namespace
91
{
92
    class CoalesceProvider: public QPDFObjectHandle::StreamDataProvider
93
    {
94
      public:
95
        CoalesceProvider(QPDFObjectHandle containing_page, QPDFObjectHandle old_contents) :
96
0
            containing_page(containing_page),
97
0
            old_contents(old_contents)
98
0
        {
99
0
        }
100
0
        ~CoalesceProvider() override = default;
101
        void provideStreamData(QPDFObjGen const&, Pipeline* pipeline) override;
102
103
      private:
104
        QPDFObjectHandle containing_page;
105
        QPDFObjectHandle old_contents;
106
    };
107
} // namespace
108
109
void
110
CoalesceProvider::provideStreamData(QPDFObjGen const&, Pipeline* p)
111
0
{
112
0
    QTC::TC("qpdf", "QPDFObjectHandle coalesce provide stream data");
113
0
    std::string description = "page object " + containing_page.getObjGen().unparse(' ');
114
0
    std::string all_description;
115
0
    old_contents.pipeContentStreams(p, description, all_description);
116
0
}
117
118
void
119
QPDFObjectHandle::TokenFilter::handleEOF()
120
0
{
121
0
}
122
123
void
124
QPDFObjectHandle::TokenFilter::setPipeline(Pipeline* p)
125
0
{
126
0
    pipeline = p;
127
0
}
128
129
void
130
QPDFObjectHandle::TokenFilter::write(char const* data, size_t len)
131
0
{
132
0
    if (!pipeline) {
133
0
        return;
134
0
    }
135
0
    if (len) {
136
0
        pipeline->write(data, len);
137
0
    }
138
0
}
139
140
void
141
QPDFObjectHandle::TokenFilter::write(std::string const& str)
142
0
{
143
0
    write(str.c_str(), str.length());
144
0
}
145
146
void
147
QPDFObjectHandle::TokenFilter::writeToken(QPDFTokenizer::Token const& token)
148
0
{
149
0
    std::string const& value = token.getRawValue();
150
0
    write(value.c_str(), value.length());
151
0
}
152
153
void
154
QPDFObjectHandle::ParserCallbacks::handleObject(QPDFObjectHandle)
155
0
{
156
0
    throw std::logic_error("You must override one of the handleObject methods in ParserCallbacks");
157
0
}
158
159
void
160
QPDFObjectHandle::ParserCallbacks::handleObject(QPDFObjectHandle oh, size_t, size_t)
161
0
{
162
    // This version of handleObject was added in qpdf 9. If the developer did not override it, fall
163
    // back to the older interface.
164
0
    handleObject(oh);
165
0
}
166
167
void
168
QPDFObjectHandle::ParserCallbacks::contentSize(size_t)
169
0
{
170
    // Ignore by default; overriding this is optional.
171
0
}
172
173
void
174
QPDFObjectHandle::ParserCallbacks::terminateParsing()
175
0
{
176
0
    throw TerminateParsing();
177
0
}
178
179
std::pair<bool, bool>
180
Name::analyzeJSONEncoding(std::string_view name)
181
0
{
182
    // Accept exactly the well-formed byte sequences of Table 3-7 in chapter 3 of the Unicode
183
    // Standard. This excludes overlong encodings, surrogates (U+D800 through U+DFFF), and values
184
    // above U+10FFFF. This is also used by QPDF_String::writeJSON to validate explicit UTF-8
185
    // strings.
186
0
    int tail = 0; // Number of continuation bytes expected.
187
    // Allowed range of the next continuation byte. Only the first continuation byte after some
188
    // lead bytes is narrower than the full range.
189
0
    unsigned char lo = 0x80;
190
0
    unsigned char hi = 0xbf;
191
0
    bool needs_escaping = false;
192
0
    for (auto const& it: name) {
193
0
        auto c = static_cast<unsigned char>(it);
194
0
        if (tail) {
195
0
            if (c < lo || c > hi) {
196
0
                return {false, false};
197
0
            }
198
0
            lo = 0x80;
199
0
            hi = 0xbf;
200
0
            --tail;
201
0
        } else if (c < 0x80) {
202
0
            if (!needs_escaping) {
203
0
                needs_escaping = !((c > 34 && c != '\\') || c == ' ' || c == 33);
204
0
            }
205
0
        } else if (c < 0xc2) {
206
            // Continuation byte without a lead byte, or overlong 2-byte sequence.
207
0
            return {false, false};
208
0
        } else if (c < 0xe0) {
209
0
            tail = 1;
210
0
        } else if (c < 0xf0) {
211
0
            if (c == 0xe0) {
212
0
                lo = 0xa0; // overlong
213
0
            } else if (c == 0xed) {
214
0
                hi = 0x9f; // surrogate
215
0
            }
216
0
            tail = 2;
217
0
        } else if (c < 0xf5) {
218
0
            if (c == 0xf0) {
219
0
                lo = 0x90; // overlong
220
0
            } else if (c == 0xf4) {
221
0
                hi = 0x8f; // above U+10FFFF
222
0
            }
223
0
            tail = 3;
224
0
        } else {
225
0
            return {false, false};
226
0
        }
227
0
    }
228
0
    return {tail == 0, !needs_escaping};
229
0
}
230
231
std::string
232
Name::normalize(std::string const& name)
233
0
{
234
0
    if (name.empty()) {
235
0
        return name;
236
0
    }
237
0
    std::string result;
238
0
    result += name.at(0);
239
0
    for (size_t i = 1; i < name.length(); ++i) {
240
0
        char ch = name.at(i);
241
        // Don't use locale/ctype here; follow PDF spec guidelines.
242
0
        if (ch == '\0') {
243
            // QPDFTokenizer embeds a null character to encode an invalid #.
244
0
            result += "#";
245
0
        } else if (
246
0
            ch < 33 || ch == '#' || ch == '/' || ch == '(' || ch == ')' || ch == '{' || ch == '}' ||
247
0
            ch == '<' || ch == '>' || ch == '[' || ch == ']' || ch == '%' || ch > 126) {
248
0
            result += util::hex_encode_char(ch);
249
0
        } else {
250
0
            result += ch;
251
0
        }
252
0
    }
253
0
    return result;
254
0
}
255
256
std::shared_ptr<QPDFObject>
257
BaseHandle::copy(bool shallow) const
258
0
{
259
0
    switch (resolved_type_code()) {
260
0
    case ::ot_uninitialized:
261
0
        throw std::logic_error("QPDFObjectHandle: attempting to copy an uninitialized object");
262
0
        return {}; // does not return
263
0
    case ::ot_reserved:
264
0
        return QPDFObject::create<QPDF_Reserved>();
265
0
    case ::ot_null:
266
0
        return QPDFObject::create<QPDF_Null>();
267
0
    case ::ot_boolean:
268
0
        return QPDFObject::create<QPDF_Bool>(std::get<QPDF_Bool>(obj->value).val);
269
0
    case ::ot_integer:
270
0
        return QPDFObject::create<QPDF_Integer>(std::get<QPDF_Integer>(obj->value).val);
271
0
    case ::ot_real:
272
0
        return QPDFObject::create<QPDF_Real>(std::get<QPDF_Real>(obj->value).val);
273
0
    case ::ot_string:
274
0
        return QPDFObject::create<QPDF_String>(std::get<QPDF_String>(obj->value).val);
275
0
    case ::ot_name:
276
0
        return QPDFObject::create<QPDF_Name>(std::get<QPDF_Name>(obj->value).name);
277
0
    case ::ot_array:
278
0
        {
279
0
            auto const& a = std::get<QPDF_Array>(obj->value);
280
0
            if (shallow) {
281
0
                return QPDFObject::create<QPDF_Array>(a);
282
0
            } else {
283
0
                QTC::TC("qpdf", "QPDF_Array copy", a.sp ? 0 : 1);
284
0
                if (a.sp) {
285
0
                    QPDF_Array result;
286
0
                    result.sp = std::make_unique<QPDF_Array::Sparse>();
287
0
                    result.sp->size = a.sp->size;
288
0
                    for (auto const& [idx, oh]: a.sp->elements) {
289
0
                        result.sp->elements[idx] = oh.indirect() ? oh : oh.copy();
290
0
                    }
291
0
                    return QPDFObject::create<QPDF_Array>(std::move(result));
292
0
                } else {
293
0
                    std::vector<QPDFObjectHandle> result;
294
0
                    result.reserve(a.elements.size());
295
0
                    for (auto const& element: a.elements) {
296
0
                        result.emplace_back(
297
0
                            element ? (element.indirect() ? element : element.copy()) : element);
298
0
                    }
299
0
                    return QPDFObject::create<QPDF_Array>(std::move(result), false);
300
0
                }
301
0
            }
302
0
        }
303
0
    case ::ot_dictionary:
304
0
        {
305
0
            auto const& d = std::get<QPDF_Dictionary>(obj->value);
306
0
            if (shallow) {
307
0
                return QPDFObject::create<QPDF_Dictionary>(d.items);
308
0
            } else {
309
0
                std::map<std::string, QPDFObjectHandle> new_items;
310
0
                for (auto const& [key, val]: d.items) {
311
0
                    new_items[key] = val.indirect() ? val : val.copy();
312
0
                }
313
0
                return QPDFObject::create<QPDF_Dictionary>(new_items);
314
0
            }
315
0
        }
316
0
    case ::ot_stream:
317
0
        QTC::TC("qpdf", "QPDF_Stream ERR shallow copy stream");
318
0
        throw std::runtime_error("stream objects cannot be cloned");
319
0
        return {}; // does not return
320
0
    case ::ot_operator:
321
0
        return QPDFObject::create<QPDF_Operator>(std::get<QPDF_Operator>(obj->value).val);
322
0
    case ::ot_inlineimage:
323
0
        return QPDFObject::create<QPDF_InlineImage>(std::get<QPDF_InlineImage>(obj->value).val);
324
0
    case ::ot_unresolved:
325
0
        throw std::logic_error("QPDFObjectHandle: attempting to unparse a reserved object");
326
0
        return {}; // does not return
327
0
    case ::ot_destroyed:
328
0
        throw std::logic_error("attempted to shallow copy QPDFObjectHandle from destroyed QPDF");
329
0
        return {}; // does not return
330
0
    case ::ot_reference:
331
0
        return referenced_object().obj_sp();
332
0
    }
333
0
    return {}; // unreachable
334
0
}
335
336
// This method determines structural equivalence up to a given depth.
337
// The default depth is 10.
338
//
339
// Nomenclature note: ISO 32000-2 Annex J uses the term "equal" for this
340
// strict recursive comparison (J.4.1). We use "equivalent_to" here to
341
// implement Annex J's "equality", distinguishing it from C++ shallow
342
// pointer equality.
343
//
344
// Implementation notes:
345
//
346
// (1) We deviate from Annex J by comparing raw streams only, without
347
// decoding.
348
//
349
// (2) Loop detection is expensive and is avoided. If either object has
350
// a cycle in its forward orbit, this implementation will return false.
351
352
bool
353
BaseHandle::equivalent_to(BaseHandle const& other, int depth) const
354
0
{
355
    // A. Identity, size & limit checks
356
0
    if (obj == other.obj) {
357
0
        return true;
358
0
    }
359
0
    if (depth < 0) {
360
0
        return false;
361
0
    }
362
0
    size_t size1 = size();
363
0
    size_t size2 = other.size();
364
0
    if (size1 != size2) {
365
0
        return false;
366
0
    }
367
    // B. Structural comparison
368
0
    qpdf_object_type_e t1 = resolved_type_code();
369
0
    qpdf_object_type_e t2 = other.resolved_type_code();
370
0
    if (t1 == ::ot_reference) {
371
0
        return referenced_object().equivalent_to(other, depth - 1);
372
0
    }
373
0
    if (t2 == ::ot_reference) {
374
0
        return equivalent_to(other.referenced_object(), depth - 1);
375
0
    }
376
0
    if (t1 != t2) {
377
0
        if ((t1 == ::ot_integer || t1 == ::ot_real) && (t2 == ::ot_integer || t2 == ::ot_real)) {
378
            // Numeric equivalence per Annex J
379
0
            return oh().getNumericValue() == other.oh().getNumericValue();
380
0
        }
381
        // normalize uninitialized and null
382
0
        return (t1 == ::ot_uninitialized && t2 == ::ot_null) ||
383
0
            (t2 == ::ot_uninitialized && t1 == ::ot_null);
384
0
    }
385
0
    switch (t1) {
386
0
    case ::ot_uninitialized:
387
0
    case ::ot_null:
388
0
        return true;
389
0
    case ::ot_boolean:
390
0
        return std::get<QPDF_Bool>(obj->value).val == std::get<QPDF_Bool>(other.obj->value).val;
391
0
    case ::ot_string:
392
0
        return std::get<QPDF_String>(obj->value).val == std::get<QPDF_String>(other.obj->value).val;
393
0
    case ::ot_name:
394
0
        return std::get<QPDF_Name>(obj->value).name == std::get<QPDF_Name>(other.obj->value).name;
395
0
    case ::ot_array:
396
0
        {
397
0
            auto const& a1 = std::get<QPDF_Array>(obj->value);
398
0
            auto const& a2 = std::get<QPDF_Array>(other.obj->value);
399
            // sizes size1, size2 were calculated above and checked to be equal
400
0
            if (!a1.sp && !a2.sp) {
401
0
                for (size_t i = 0; i < size1; ++i) {
402
0
                    if (!a1.elements[i].equivalent_to(a2.elements[i], depth - 1)) {
403
0
                        return false;
404
0
                    }
405
0
                }
406
0
                return true;
407
0
            }
408
            // at least one array is sparse
409
0
            auto get_item = [](QPDF_Array const& arr, size_t idx) -> BaseHandle const& {
410
0
                if (arr.sp) {
411
0
                    auto it = arr.sp->elements.find(idx);
412
0
                    if (it == arr.sp->elements.end()) {
413
0
                        static QPDFObjectHandle null_oh = Null();
414
0
                        return null_oh;
415
0
                    }
416
0
                    return it->second;
417
0
                }
418
0
                return arr.elements[idx];
419
0
            };
420
0
            for (size_t i = 0; i < size1; ++i) {
421
0
                if (!get_item(a1, i).equivalent_to(get_item(a2, i), depth - 1)) {
422
0
                    return false;
423
0
                }
424
0
            }
425
0
            return true;
426
0
        }
427
0
    case ::ot_dictionary:
428
0
        {
429
0
            auto const& map1 = std::get<QPDF_Dictionary>(obj->value).items;
430
0
            auto const& map2 = std::get<QPDF_Dictionary>(other.obj->value).items;
431
0
            auto it2 = map2.begin();
432
0
            auto end2 = map2.end();
433
0
            for (auto const& [key1, value1]: map1) {
434
0
                if (value1.null()) {
435
0
                    continue;
436
0
                }
437
0
                while (it2 != end2 && it2->second.null()) {
438
0
                    ++it2;
439
0
                }
440
0
                if (it2 == end2 || key1 != it2->first ||
441
0
                    !value1.equivalent_to(it2->second, depth - 1)) {
442
0
                    return false;
443
0
                }
444
0
                ++it2;
445
0
            }
446
0
            while (it2 != end2 && it2->second.null()) {
447
0
                ++it2;
448
0
            }
449
0
            return it2 == end2;
450
0
        }
451
0
    case ::ot_stream:
452
0
        {
453
0
            auto const& s1 = std::get<QPDF_Stream>(obj->value);
454
0
            auto const& s2 = std::get<QPDF_Stream>(other.obj->value);
455
0
            if (!s1.m->stream_dict.equivalent_to(s2.m->stream_dict, depth - 1)) {
456
0
                return false;
457
0
            }
458
0
            return s1.m->stream_data->view() == s2.m->stream_data->view();
459
0
        }
460
0
    case ::ot_operator:
461
0
        throw std::logic_error("Internal error in BaseHandle::equivalent_to: found ot_operator");
462
0
    case ::ot_inlineimage:
463
0
        throw std::logic_error("Internal error in BaseHandle::equivalent_to: found ot_inlineimage");
464
0
    case ::ot_integer:
465
0
        return std::get<QPDF_Integer>(obj->value).val ==
466
0
            std::get<QPDF_Integer>(other.obj->value).val;
467
0
    case ::ot_real:
468
0
        return oh().getNumericValue() == other.oh().getNumericValue();
469
0
    case ::ot_unresolved: // cannot determine equivalence so return false
470
0
    case ::ot_reference:  // handled above
471
0
    case ::ot_destroyed:  // should not happen
472
0
    case ::ot_reserved:   // should not happen
473
0
        return false;
474
0
    }
475
0
    return false; // unreachable
476
0
}
477
478
std::string
479
BaseHandle::unparse() const
480
0
{
481
0
    switch (resolved_type_code()) {
482
0
    case ::ot_uninitialized:
483
0
        throw std::logic_error("QPDFObjectHandle: attempting to unparse an uninitialized object");
484
0
        return ""; // does not return
485
0
    case ::ot_reserved:
486
0
        throw std::logic_error("QPDFObjectHandle: attempting to unparse a reserved object");
487
0
        return ""; // does not return
488
0
    case ::ot_null:
489
0
        return "null";
490
0
    case ::ot_boolean:
491
0
        return std::get<QPDF_Bool>(obj->value).val ? "true" : "false";
492
0
    case ::ot_integer:
493
0
        return std::to_string(std::get<QPDF_Integer>(obj->value).val);
494
0
    case ::ot_real:
495
0
        return std::get<QPDF_Real>(obj->value).val;
496
0
    case ::ot_string:
497
0
        return std::get<QPDF_String>(obj->value).unparse(false);
498
0
    case ::ot_name:
499
0
        return Name::normalize(std::get<QPDF_Name>(obj->value).name);
500
0
    case ::ot_array:
501
0
        {
502
0
            auto const& a = std::get<QPDF_Array>(obj->value);
503
0
            std::string result = "[ ";
504
0
            if (a.sp) {
505
0
                size_t next = 0;
506
0
                for (auto& [key, value]: a.sp->elements) {
507
0
                    for (size_t j = next; j < key; ++j) {
508
0
                        result += "null ";
509
0
                    }
510
0
                    result += value.unparse() + " ";
511
0
                    next = key + 1;
512
0
                }
513
0
                for (size_t j = next; j < a.sp->size; ++j) {
514
0
                    result += "null ";
515
0
                }
516
0
            } else {
517
0
                for (auto const& item: a.elements) {
518
0
                    result += item.unparse() + " ";
519
0
                }
520
0
            }
521
0
            result += "]";
522
0
            return result;
523
0
        }
524
0
    case ::ot_dictionary:
525
0
        {
526
0
            auto const& items = std::get<QPDF_Dictionary>(obj->value).items;
527
0
            std::string result = "<< ";
528
0
            for (auto& iter: items) {
529
0
                if (!iter.second.null()) {
530
0
                    result += Name::normalize(iter.first) + " " + iter.second.unparse() + " ";
531
0
                }
532
0
            }
533
0
            result += ">>";
534
0
            return result;
535
0
        }
536
0
    case ::ot_stream:
537
0
        return obj->og.unparse(' ') + " R";
538
0
    case ::ot_operator:
539
0
        return std::get<QPDF_Operator>(obj->value).val;
540
0
    case ::ot_inlineimage:
541
0
        return std::get<QPDF_InlineImage>(obj->value).val;
542
0
    case ::ot_unresolved:
543
0
        throw std::logic_error("QPDFObjectHandle: attempting to unparse a unresolved object");
544
0
        return ""; // does not return
545
0
    case ::ot_destroyed:
546
0
        throw std::logic_error("attempted to unparse a QPDFObjectHandle from a destroyed QPDF");
547
0
        return ""; // does not return
548
0
    case ::ot_reference:
549
0
        return obj->og.unparse(' ') + " R";
550
0
    }
551
0
    return {}; // unreachable
552
0
}
553
554
namespace
555
{
556
    void
557
    write_json_name(int json_version, JSON::Writer& p, std::string const& name)
558
0
    {
559
0
        if (json_version == 1) {
560
0
            p << "\"" << JSON::Writer::encode_string(Name::normalize(name)) << "\"";
561
0
        } else if (auto res = Name::analyzeJSONEncoding(name); res.first) {
562
0
            if (res.second) {
563
0
                p << "\"" << name << "\"";
564
0
            } else {
565
0
                p << "\"" << JSON::Writer::encode_string(name) << "\"";
566
0
            }
567
0
        } else {
568
0
            p << "\"n:" << JSON::Writer::encode_string(Name::normalize(name)) << "\"";
569
0
        }
570
0
    }
571
} // namespace
572
573
void
574
BaseHandle::write_json(int json_version, JSON::Writer& p) const
575
0
{
576
0
    switch (resolved_type_code()) {
577
0
    case ::ot_uninitialized:
578
0
        throw std::logic_error(
579
0
            "QPDFObjectHandle: attempting to get JSON from a uninitialized object");
580
0
        break; // unreachable
581
0
    case ::ot_null:
582
0
    case ::ot_operator:
583
0
    case ::ot_inlineimage:
584
0
        p << "null";
585
0
        break;
586
0
    case ::ot_boolean:
587
0
        p << std::get<QPDF_Bool>(obj->value).val;
588
0
        break;
589
0
    case ::ot_integer:
590
0
        p << std::to_string(std::get<QPDF_Integer>(obj->value).val);
591
0
        break;
592
0
    case ::ot_real:
593
0
        {
594
0
            std::string_view val = std::get<QPDF_Real>(obj->value).val;
595
0
            if (!val.empty() && (val.at(0) == '-' || val.at(0) == '+')) {
596
0
                if (val.at(0) == '-') {
597
0
                    p << "-";
598
0
                }
599
0
                val.remove_prefix(1);
600
0
            }
601
0
            if (val.empty()) {
602
                // Can't really happen...
603
0
                p << "0";
604
0
            } else if (val.at(0) == '.') {
605
0
                p << "0" << val;
606
0
            } else if (val.at(0) == '0') {
607
0
                auto i = val.find_first_not_of('0');
608
0
                if (i == std::string_view::npos) {
609
0
                    p << "0";
610
0
                } else if (val.at(i) == '.') {
611
0
                    p << "0" << val.substr(i);
612
0
                } else {
613
0
                    p << val.substr(i);
614
0
                }
615
0
            } else {
616
0
                p << val;
617
0
            }
618
0
            if (!val.empty() && val.back() == '.') {
619
0
                p << "0";
620
0
            }
621
0
        }
622
0
        break;
623
0
    case ::ot_string:
624
0
        std::get<QPDF_String>(obj->value).writeJSON(json_version, p);
625
0
        break;
626
0
    case ::ot_name:
627
0
        write_json_name(json_version, p, std::get<QPDF_Name>(obj->value).name);
628
0
        break;
629
0
    case ::ot_array:
630
0
        {
631
0
            auto const& a = std::get<QPDF_Array>(obj->value);
632
0
            p.writeStart('[');
633
0
            if (a.sp) {
634
0
                size_t next = 0;
635
0
                for (auto& [key, value]: a.sp->elements) {
636
0
                    for (size_t j = next; j < key; ++j) {
637
0
                        p.writeNext() << "null";
638
0
                    }
639
0
                    p.writeNext();
640
0
                    auto item_og = value.id_gen();
641
0
                    if (item_og.isIndirect()) {
642
0
                        p << "\"" << item_og.unparse(' ') << " R\"";
643
0
                    } else {
644
0
                        value.write_json(json_version, p);
645
0
                    }
646
0
                    next = key + 1;
647
0
                }
648
0
                for (size_t j = next; j < a.sp->size; ++j) {
649
0
                    p.writeNext() << "null";
650
0
                }
651
0
            } else {
652
0
                for (auto const& item: a.elements) {
653
0
                    p.writeNext();
654
0
                    auto item_og = item.id_gen();
655
0
                    if (item_og.isIndirect()) {
656
0
                        p << "\"" << item_og.unparse(' ') << " R\"";
657
0
                    } else {
658
0
                        item.write_json(json_version, p);
659
0
                    }
660
0
                }
661
0
            }
662
0
            p.writeEnd(']');
663
0
        }
664
0
        break;
665
0
    case ::ot_dictionary:
666
0
        {
667
0
            auto const& d = std::get<QPDF_Dictionary>(obj->value);
668
0
            p.writeStart('{');
669
0
            for (auto& iter: d.items) {
670
0
                if (!iter.second.null()) {
671
0
                    p.writeNext();
672
0
                    write_json_name(json_version, p, iter.first);
673
0
                    p << ": ";
674
0
                    iter.second.writeJSON(json_version, p);
675
0
                }
676
0
            }
677
0
            p.writeEnd('}');
678
0
        }
679
0
        break;
680
0
    case ::ot_stream:
681
0
        std::get<QPDF_Stream>(obj->value).m->stream_dict.writeJSON(json_version, p);
682
0
        break;
683
0
    case ::ot_reference:
684
0
        p << "\"" << obj->og.unparse(' ') << " R\"";
685
0
        break;
686
0
    default:
687
0
        throw std::logic_error("attempted to write an unsuitable object as JSON");
688
0
    }
689
0
}
690
691
void
692
BaseHandle::disconnect(bool only_direct)
693
2.32M
{
694
    // QPDF::~QPDF() calls disconnect for indirect objects, so we don't do that here.
695
2.32M
    if (only_direct && indirect()) {
696
463k
        return;
697
463k
    }
698
699
1.85M
    switch (raw_type_code()) {
700
11.9k
    case ::ot_array:
701
11.9k
        {
702
11.9k
            auto& a = std::get<QPDF_Array>(obj->value);
703
11.9k
            if (a.sp) {
704
0
                for (auto& item: a.sp->elements) {
705
0
                    item.second.disconnect();
706
0
                }
707
11.9k
            } else {
708
2.22M
                for (auto& oh: a.elements) {
709
2.22M
                    oh.disconnect();
710
2.22M
                }
711
11.9k
            }
712
11.9k
        }
713
11.9k
        break;
714
22.1k
    case ::ot_dictionary:
715
78.0k
        for (auto& iter: std::get<QPDF_Dictionary>(obj->value).items) {
716
78.0k
            iter.second.disconnect();
717
78.0k
        }
718
22.1k
        break;
719
2.36k
    case ::ot_stream:
720
2.36k
        {
721
2.36k
            auto& s = std::get<QPDF_Stream>(obj->value);
722
2.36k
            s.m->stream_provider = nullptr;
723
2.36k
            s.m->stream_dict.disconnect();
724
2.36k
        }
725
2.36k
        break;
726
0
    case ::ot_uninitialized:
727
0
        return;
728
1.82M
    default:
729
1.82M
        break;
730
1.85M
    }
731
1.85M
    obj->qpdf = nullptr;
732
1.85M
    obj->og = QPDFObjGen();
733
1.85M
}
734
735
bool
736
QPDFObjectHandle::isSameObjectAs(QPDFObjectHandle const& rhs) const
737
0
{
738
0
    return obj == rhs.obj;
739
0
}
740
741
qpdf_object_type_e
742
QPDFObjectHandle::getTypeCode() const
743
0
{
744
0
    return type_code();
745
0
}
746
747
char const*
748
BaseHandle::type_name() const
749
0
{
750
0
    static constexpr std::array<char const*, 16> tn{
751
0
        "uninitialized",
752
0
        "reserved",
753
0
        "null",
754
0
        "boolean",
755
0
        "integer",
756
0
        "real",
757
0
        "string",
758
0
        "name",
759
0
        "array",
760
0
        "dictionary",
761
0
        "stream",
762
0
        "operator",
763
0
        "inline-image",
764
0
        "unresolved",
765
0
        "destroyed",
766
0
        "reference"};
767
0
    return tn[type_code()];
768
0
}
769
770
char const*
771
QPDFObjectHandle::getTypeName() const
772
0
{
773
0
    return type_name();
774
0
}
775
776
bool
777
QPDFObjectHandle::isDestroyed() const
778
0
{
779
0
    return type_code() == ::ot_destroyed;
780
0
}
781
782
bool
783
QPDFObjectHandle::isBool() const
784
0
{
785
0
    return type_code() == ::ot_boolean;
786
0
}
787
788
bool
789
QPDFObjectHandle::isDirectNull() const
790
0
{
791
    // Don't call dereference() -- this is a const method, and we know
792
    // objid == 0, so there's nothing to resolve.
793
0
    return !indirect() && raw_type_code() == ::ot_null;
794
0
}
795
796
bool
797
QPDFObjectHandle::isNull() const
798
0
{
799
0
    return type_code() == ::ot_null;
800
0
}
801
802
bool
803
QPDFObjectHandle::isInteger() const
804
7.55k
{
805
7.55k
    return type_code() == ::ot_integer;
806
7.55k
}
807
808
bool
809
QPDFObjectHandle::isReal() const
810
0
{
811
0
    return type_code() == ::ot_real;
812
0
}
813
814
bool
815
QPDFObjectHandle::isNumber() const
816
0
{
817
0
    return (isInteger() || isReal());
818
0
}
819
820
double
821
QPDFObjectHandle::getNumericValue() const
822
0
{
823
0
    if (isInteger()) {
824
0
        return static_cast<double>(getIntValue());
825
0
    } else if (isReal()) {
826
0
        return util::string_to_double(getRealValue()).value_or(0.0);
827
0
    } else {
828
0
        typeWarning("number", "returning 0");
829
0
        QTC::TC("qpdf", "QPDFObjectHandle numeric non-numeric");
830
0
        return 0;
831
0
    }
832
0
}
833
834
bool
835
QPDFObjectHandle::getValueAsNumber(double& value) const
836
0
{
837
0
    if (!isNumber()) {
838
0
        return false;
839
0
    }
840
0
    value = getNumericValue();
841
0
    return true;
842
0
}
843
844
bool
845
QPDFObjectHandle::isName() const
846
0
{
847
0
    return type_code() == ::ot_name;
848
0
}
849
850
bool
851
QPDFObjectHandle::isString() const
852
0
{
853
0
    return type_code() == ::ot_string;
854
0
}
855
856
bool
857
QPDFObjectHandle::isOperator() const
858
0
{
859
0
    return type_code() == ::ot_operator;
860
0
}
861
862
bool
863
QPDFObjectHandle::isInlineImage() const
864
0
{
865
0
    return type_code() == ::ot_inlineimage;
866
0
}
867
868
bool
869
QPDFObjectHandle::isArray() const
870
0
{
871
0
    return type_code() == ::ot_array;
872
0
}
873
874
bool
875
QPDFObjectHandle::isDictionary() const
876
164k
{
877
164k
    return type_code() == ::ot_dictionary;
878
164k
}
879
880
bool
881
QPDFObjectHandle::isStream() const
882
164k
{
883
164k
    return type_code() == ::ot_stream;
884
164k
}
885
886
bool
887
QPDFObjectHandle::isReserved() const
888
0
{
889
0
    return type_code() == ::ot_reserved;
890
0
}
891
892
bool
893
QPDFObjectHandle::isScalar() const
894
0
{
895
0
    return isBool() || isInteger() || isName() || isNull() || isReal() || isString();
896
0
}
897
898
bool
899
QPDFObjectHandle::isNameAndEquals(std::string const& name) const
900
0
{
901
0
    return Name(*this) == name;
902
0
}
903
904
bool
905
QPDFObjectHandle::isDictionaryOfType(std::string const& type, std::string const& subtype) const
906
0
{
907
0
    return isDictionary() && (type.empty() || Name((*this)["/Type"]) == type) &&
908
0
        (subtype.empty() || Name((*this)["/Subtype"]) == subtype);
909
0
}
910
911
bool
912
QPDFObjectHandle::isStreamOfType(std::string const& type, std::string const& subtype) const
913
0
{
914
0
    if (auto stream = as_stream()) {
915
0
        return stream && (type.empty() || stream.Type() == type) &&
916
0
            (subtype.empty() || stream.Subtype() == subtype);
917
0
    }
918
0
    return false;
919
0
}
920
921
// Bool accessors
922
923
bool
924
QPDFObjectHandle::getBoolValue() const
925
0
{
926
0
    if (auto boolean = as<QPDF_Bool>()) {
927
0
        return boolean->val;
928
0
    } else {
929
0
        typeWarning("boolean", "returning false");
930
0
        QTC::TC("qpdf", "QPDFObjectHandle boolean returning false");
931
0
        return false;
932
0
    }
933
0
}
934
935
bool
936
QPDFObjectHandle::getValueAsBool(bool& value) const
937
0
{
938
0
    if (auto boolean = as<QPDF_Bool>()) {
939
0
        value = boolean->val;
940
0
        return true;
941
0
    }
942
0
    return false;
943
0
}
944
945
// Integer methods
946
947
Integer::Integer(long long value) :
948
0
    BaseHandle(QPDFObject::create<QPDF_Integer>(value))
949
0
{
950
0
}
951
952
QPDFObjectHandle
953
QPDFObjectHandle::newInteger(long long value)
954
1.80M
{
955
1.80M
    return {QPDFObject::create<QPDF_Integer>(value)};
956
1.80M
}
957
958
int64_t
959
Integer::value() const
960
7.55k
{
961
7.55k
    auto* i = as<QPDF_Integer>();
962
7.55k
    if (!i) {
963
0
        throw invalid_error("Integer");
964
0
    }
965
7.55k
    return i->val;
966
7.55k
}
967
968
long long
969
QPDFObjectHandle::getIntValue() const
970
0
{
971
0
    if (auto const integer = Integer(*this)) {
972
0
        return integer;
973
0
    } else {
974
0
        typeWarning("integer", "returning 0");
975
0
        return 0;
976
0
    }
977
0
}
978
979
bool
980
QPDFObjectHandle::getValueAsInt(long long& value) const
981
0
{
982
0
    if (auto const integer = Integer(*this)) {
983
0
        value = integer;
984
0
        return true;
985
0
    }
986
0
    return false;
987
0
}
988
989
int
990
QPDFObjectHandle::getIntValueAsInt() const
991
7.55k
{
992
7.55k
    try {
993
7.55k
        return Integer(*this).value<int>();
994
7.55k
    } catch (std::invalid_argument&) {
995
0
        typeWarning("integer", "returning 0");
996
0
        return 0;
997
0
    }
998
7.55k
}
999
1000
bool
1001
QPDFObjectHandle::getValueAsInt(int& value) const
1002
0
{
1003
0
    if (!isInteger()) {
1004
0
        return false;
1005
0
    }
1006
0
    value = getIntValueAsInt();
1007
0
    return true;
1008
0
}
1009
1010
unsigned long long
1011
QPDFObjectHandle::getUIntValue() const
1012
0
{
1013
0
    try {
1014
0
        return Integer(*this).value<unsigned long long>();
1015
0
    } catch (std::invalid_argument&) {
1016
0
        typeWarning("integer", "returning 0");
1017
0
        return 0;
1018
0
    }
1019
0
}
1020
1021
bool
1022
QPDFObjectHandle::getValueAsUInt(unsigned long long& value) const
1023
0
{
1024
0
    if (!isInteger()) {
1025
0
        return false;
1026
0
    }
1027
0
    value = getUIntValue();
1028
0
    return true;
1029
0
}
1030
1031
unsigned int
1032
QPDFObjectHandle::getUIntValueAsUInt() const
1033
0
{
1034
0
    try {
1035
0
        return Integer(*this).value<unsigned int>();
1036
0
    } catch (std::invalid_argument&) {
1037
0
        typeWarning("integer", "returning 0");
1038
0
        return 0;
1039
0
    }
1040
0
}
1041
1042
bool
1043
QPDFObjectHandle::getValueAsUInt(unsigned int& value) const
1044
0
{
1045
0
    if (!isInteger()) {
1046
0
        return false;
1047
0
    }
1048
0
    value = getUIntValueAsUInt();
1049
0
    return true;
1050
0
}
1051
1052
// Real accessors
1053
1054
std::string
1055
QPDFObjectHandle::getRealValue() const
1056
0
{
1057
0
    if (auto* real = as<QPDF_Real>()) {
1058
0
        return real->val;
1059
0
    }
1060
0
    typeWarning("real", "returning 0.0");
1061
0
    return "0.0";
1062
0
}
1063
1064
bool
1065
QPDFObjectHandle::getValueAsReal(std::string& value) const
1066
0
{
1067
0
    if (auto* real = as<QPDF_Real>()) {
1068
0
        value = real->val;
1069
0
        return true;
1070
0
    }
1071
0
    return false;
1072
0
}
1073
1074
// Name methods
1075
1076
QPDFObjectHandle
1077
QPDFObjectHandle::newName(std::string const& name)
1078
13.3k
{
1079
13.3k
    return {QPDFObject::create<QPDF_Name>(name)};
1080
13.3k
}
1081
1082
Name::Name(std::string const& name) :
1083
0
    BaseHandle(QPDFObject::create<QPDF_Name>(name))
1084
0
{
1085
0
}
1086
1087
Name::Name(std::string&& name) :
1088
0
    BaseHandle(QPDFObject::create<QPDF_Name>(std::move(name)))
1089
0
{
1090
0
}
1091
1092
std::string const&
1093
Name::value() const
1094
0
{
1095
0
    auto* n = as<QPDF_Name>();
1096
0
    if (!n) {
1097
0
        throw invalid_error("Name");
1098
0
    }
1099
0
    return n->name;
1100
0
}
1101
1102
std::string
1103
QPDFObjectHandle::getName() const
1104
2.76k
{
1105
2.76k
    if (auto* name = as<QPDF_Name>()) {
1106
2.76k
        return name->name;
1107
2.76k
    }
1108
0
    typeWarning("name", "returning dummy name");
1109
0
    return "/QPDFFakeName";
1110
2.76k
}
1111
1112
bool
1113
QPDFObjectHandle::getValueAsName(std::string& value) const
1114
0
{
1115
0
    if (auto* name = as<QPDF_Name>()) {
1116
0
        value = name->name;
1117
0
        return true;
1118
0
    }
1119
0
    return false;
1120
0
}
1121
1122
// String methods
1123
1124
QPDFObjectHandle
1125
QPDFObjectHandle::newString(std::string const& str)
1126
1.44k
{
1127
1.44k
    return {QPDFObject::create<QPDF_String>(str)};
1128
1.44k
}
1129
1130
QPDFObjectHandle
1131
QPDFObjectHandle::newUnicodeString(std::string const& utf8_str)
1132
5.36k
{
1133
5.36k
    return {String::utf16(utf8_str).obj_sp()};
1134
5.36k
}
1135
1136
String::String(std::string const& str) :
1137
1.45k
    BaseHandle(QPDFObject::create<QPDF_String>(str))
1138
1.45k
{
1139
1.45k
}
1140
1141
String::String(std::string&& str) :
1142
3.91k
    BaseHandle(QPDFObject::create<QPDF_String>(std::move(str)))
1143
3.91k
{
1144
3.91k
}
1145
1146
String
1147
String::utf16(std::string const& utf8_str)
1148
5.36k
{
1149
5.36k
    std::string result;
1150
5.36k
    if (QUtil::utf8_to_pdf_doc(utf8_str, result, '?')) {
1151
1.45k
        return String(result);
1152
1.45k
    }
1153
3.91k
    return String(QUtil::utf8_to_utf16(utf8_str));
1154
5.36k
}
1155
1156
std::string const&
1157
String::value() const
1158
0
{
1159
0
    auto* s = as<QPDF_String>();
1160
0
    if (!s) {
1161
0
        throw invalid_error("String");
1162
0
    }
1163
0
    return s->val;
1164
0
}
1165
1166
std::string
1167
String::utf8_value() const
1168
0
{
1169
0
    auto* s = as<QPDF_String>();
1170
0
    if (!s) {
1171
0
        throw invalid_error("String");
1172
0
    }
1173
0
    if (util::is_utf16(s->val)) {
1174
0
        return QUtil::utf16_to_utf8(s->val);
1175
0
    }
1176
0
    if (util::is_explicit_utf8(s->val)) {
1177
        // PDF 2.0 allows UTF-8 strings when explicitly prefixed with the three-byte representation
1178
        // of U+FEFF.
1179
0
        return s->val.substr(3);
1180
0
    }
1181
0
    return QUtil::pdf_doc_to_utf8(s->val);
1182
0
}
1183
1184
std::string
1185
QPDFObjectHandle::getStringValue() const
1186
0
{
1187
0
    try {
1188
0
        return String(obj).value();
1189
0
    } catch (std::invalid_argument&) {
1190
0
        typeWarning("string", "returning empty string");
1191
0
        return {};
1192
0
    }
1193
0
}
1194
1195
bool
1196
QPDFObjectHandle::getValueAsString(std::string& value) const
1197
0
{
1198
0
    try {
1199
0
        value = String(obj).value();
1200
0
        return true;
1201
0
    } catch (std::invalid_argument&) {
1202
0
        return false;
1203
0
    }
1204
0
}
1205
1206
std::string
1207
QPDFObjectHandle::getUTF8Value() const
1208
0
{
1209
0
    try {
1210
0
        return String(obj).utf8_value();
1211
0
    } catch (std::invalid_argument&) {
1212
0
        typeWarning("string", "returning empty string");
1213
0
        return {};
1214
0
    }
1215
0
}
1216
1217
bool
1218
QPDFObjectHandle::getValueAsUTF8(std::string& value) const
1219
0
{
1220
0
    try {
1221
0
        value = String(obj).utf8_value();
1222
0
        return true;
1223
0
    } catch (std::invalid_argument&) {
1224
0
        return false;
1225
0
    }
1226
0
}
1227
1228
// Operator and Inline Image accessors
1229
1230
std::string
1231
QPDFObjectHandle::getOperatorValue() const
1232
0
{
1233
0
    if (auto* op = as<QPDF_Operator>()) {
1234
0
        return op->val;
1235
0
    }
1236
0
    typeWarning("operator", "returning fake value");
1237
0
    return "QPDFFAKE";
1238
0
}
1239
1240
bool
1241
QPDFObjectHandle::getValueAsOperator(std::string& value) const
1242
0
{
1243
0
    if (auto* op = as<QPDF_Operator>()) {
1244
0
        value = op->val;
1245
0
        return true;
1246
0
    }
1247
0
    return false;
1248
0
}
1249
1250
std::string
1251
QPDFObjectHandle::getInlineImageValue() const
1252
0
{
1253
0
    if (auto* ii = as<QPDF_InlineImage>()) {
1254
0
        return ii->val;
1255
0
    }
1256
0
    typeWarning("inlineimage", "returning empty data");
1257
0
    return {};
1258
0
}
1259
1260
bool
1261
QPDFObjectHandle::getValueAsInlineImage(std::string& value) const
1262
0
{
1263
0
    if (auto* ii = as<QPDF_InlineImage>()) {
1264
0
        value = ii->val;
1265
0
        return true;
1266
0
    }
1267
0
    return false;
1268
0
}
1269
1270
// Array accessors and mutators are in QPDF_Array.cc
1271
1272
QPDFObjectHandle::QPDFArrayItems
1273
QPDFObjectHandle::aitems()
1274
0
{
1275
0
    return *this;
1276
0
}
1277
1278
// Dictionary accessors are in QPDF_Dictionary.cc
1279
1280
QPDFObjectHandle::QPDFDictItems
1281
QPDFObjectHandle::ditems()
1282
0
{
1283
0
    return {*this};
1284
0
}
1285
1286
// Array and Name accessors
1287
1288
bool
1289
QPDFObjectHandle::isOrHasName(std::string const& value) const
1290
0
{
1291
0
    if (isNameAndEquals(value)) {
1292
0
        return true;
1293
0
    } else if (isArray()) {
1294
0
        for (auto& item: getArrayAsVector()) {
1295
0
            if (item.isNameAndEquals(value)) {
1296
0
                return true;
1297
0
            }
1298
0
        }
1299
0
    }
1300
0
    return false;
1301
0
}
1302
1303
void
1304
QPDFObjectHandle::makeResourcesIndirect(QPDF& owning_qpdf)
1305
0
{
1306
0
    for (auto const& i1: as_dictionary()) {
1307
0
        for (auto& i2: i1.second.as_dictionary()) {
1308
0
            if (!i2.second.null() && !i2.second.isIndirect()) {
1309
0
                i2.second = owning_qpdf.makeIndirectObject(i2.second);
1310
0
            }
1311
0
        }
1312
0
    }
1313
0
}
1314
1315
void
1316
QPDFObjectHandle::mergeResources(
1317
    QPDFObjectHandle other, std::map<std::string, std::map<std::string, std::string>>* conflicts)
1318
0
{
1319
0
    if (!(isDictionary() && other.isDictionary())) {
1320
0
        QTC::TC("qpdf", "QPDFObjectHandle merge top type mismatch");
1321
0
        return;
1322
0
    }
1323
1324
0
    auto make_og_to_name = [](QPDFObjectHandle& dict,
1325
0
                              std::map<QPDFObjGen, std::string>& og_to_name) {
1326
0
        for (auto const& [key, value]: dict.as_dictionary()) {
1327
0
            if (!value.null() && value.isIndirect()) {
1328
0
                og_to_name.insert_or_assign(value.getObjGen(), key);
1329
0
            }
1330
0
        }
1331
0
    };
1332
1333
    // This algorithm is described in comments in QPDFObjectHandle.hh
1334
    // above the declaration of mergeResources.
1335
0
    for (auto const& [rtype, value1]: other.as_dictionary()) {
1336
0
        auto other_val = value1;
1337
0
        if (hasKey(rtype)) {
1338
0
            QPDFObjectHandle this_val = getKey(rtype);
1339
0
            if (this_val.isDictionary() && other_val.isDictionary()) {
1340
0
                if (this_val.isIndirect()) {
1341
                    // Do this even if there are no keys. Various places in the code call
1342
                    // mergeResources with resource dictionaries that contain empty subdictionaries
1343
                    // just to get this shallow copy functionality.
1344
0
                    QTC::TC("qpdf", "QPDFObjectHandle replace with copy");
1345
0
                    this_val = replaceKeyAndGetNew(rtype, this_val.shallowCopy());
1346
0
                }
1347
0
                std::map<QPDFObjGen, std::string> og_to_name;
1348
0
                std::set<std::string> rnames;
1349
0
                int min_suffix = 1;
1350
0
                bool initialized_maps = false;
1351
0
                for (auto const& [key, value2]: other_val.as_dictionary()) {
1352
0
                    QPDFObjectHandle rval = value2;
1353
0
                    if (!this_val.hasKey(key)) {
1354
0
                        if (!rval.isIndirect()) {
1355
0
                            QTC::TC("qpdf", "QPDFObjectHandle merge shallow copy");
1356
0
                            rval = rval.shallowCopy();
1357
0
                        }
1358
0
                        this_val.replaceKey(key, rval);
1359
0
                    } else if (conflicts) {
1360
0
                        if (!initialized_maps) {
1361
0
                            make_og_to_name(this_val, og_to_name);
1362
0
                            rnames = this_val.getResourceNames();
1363
0
                            initialized_maps = true;
1364
0
                        }
1365
0
                        auto rval_og = rval.getObjGen();
1366
0
                        if (rval.isIndirect() && og_to_name.contains(rval_og)) {
1367
0
                            QTC::TC("qpdf", "QPDFObjectHandle merge reuse");
1368
0
                            auto new_key = og_to_name[rval_og];
1369
0
                            if (new_key != key) {
1370
0
                                (*conflicts)[rtype][key] = new_key;
1371
0
                            }
1372
0
                        } else {
1373
0
                            QTC::TC("qpdf", "QPDFObjectHandle merge generate");
1374
0
                            std::string new_key =
1375
0
                                getUniqueResourceName(key + "_", min_suffix, &rnames);
1376
0
                            (*conflicts)[rtype][key] = new_key;
1377
0
                            this_val.replaceKey(new_key, rval);
1378
0
                        }
1379
0
                    }
1380
0
                }
1381
0
            } else if (this_val.isArray() && other_val.isArray()) {
1382
0
                std::set<std::string> scalars;
1383
0
                for (auto this_item: this_val.aitems()) {
1384
0
                    if (this_item.isScalar()) {
1385
0
                        scalars.insert(this_item.unparse());
1386
0
                    }
1387
0
                }
1388
0
                for (auto other_item: other_val.aitems()) {
1389
0
                    if (other_item.isScalar()) {
1390
0
                        if (!scalars.contains(other_item.unparse())) {
1391
0
                            QTC::TC("qpdf", "QPDFObjectHandle merge array");
1392
0
                            this_val.appendItem(other_item);
1393
0
                        } else {
1394
0
                            QTC::TC("qpdf", "QPDFObjectHandle merge array dup");
1395
0
                        }
1396
0
                    }
1397
0
                }
1398
0
            }
1399
0
        } else {
1400
0
            QTC::TC("qpdf", "QPDFObjectHandle merge copy from other");
1401
0
            replaceKey(rtype, other_val.shallowCopy());
1402
0
        }
1403
0
    }
1404
0
}
1405
1406
std::set<std::string>
1407
QPDFObjectHandle::getResourceNames() const
1408
0
{
1409
    // Return second-level dictionary keys
1410
0
    std::set<std::string> result;
1411
0
    for (auto const& item: as_dictionary(strict)) {
1412
0
        for (auto const& [key2, val2]: item.second.as_dictionary(strict)) {
1413
0
            if (!val2.null()) {
1414
0
                result.insert(key2);
1415
0
            }
1416
0
        }
1417
0
    }
1418
0
    return result;
1419
0
}
1420
1421
std::string
1422
QPDFObjectHandle::getUniqueResourceName(
1423
    std::string const& prefix, int& min_suffix, std::set<std::string>* namesp) const
1424
0
{
1425
0
    std::set<std::string> names = (namesp ? *namesp : getResourceNames());
1426
0
    int max_suffix = min_suffix + QIntC::to_int(names.size());
1427
0
    while (min_suffix <= max_suffix) {
1428
0
        std::string candidate = prefix + std::to_string(min_suffix);
1429
0
        if (!names.contains(candidate)) {
1430
0
            return candidate;
1431
0
        }
1432
        // Increment after return; min_suffix should be the value
1433
        // used, not the next value.
1434
0
        ++min_suffix;
1435
0
    }
1436
    // This could only happen if there is a coding error.
1437
    // The number of candidates we test is more than the
1438
    // number of keys we're checking against.
1439
0
    throw std::logic_error(
1440
0
        "unable to find unconflicting name in QPDFObjectHandle::getUniqueResourceName");
1441
0
}
1442
1443
// Dictionary mutators are in QPDF_Dictionary.cc
1444
1445
// Stream accessors are in QPDF_Stream.cc
1446
1447
std::map<std::string, QPDFObjectHandle>
1448
QPDFObjectHandle::getPageImages()
1449
0
{
1450
0
    return QPDFPageObjectHelper(*this).getImages();
1451
0
}
1452
1453
std::vector<QPDFObjectHandle>
1454
QPDFObjectHandle::arrayOrStreamToStreamArray(
1455
    std::string const& description, std::string& all_description)
1456
0
{
1457
0
    all_description = description;
1458
0
    std::vector<QPDFObjectHandle> result;
1459
0
    if (auto array = as_array(strict)) {
1460
0
        int n_items = static_cast<int>(array.size());
1461
0
        for (int i = 0; i < n_items; ++i) {
1462
0
            QPDFObjectHandle item = array[i];
1463
0
            if (item.isStream()) {
1464
0
                result.emplace_back(item);
1465
0
            } else {
1466
0
                item.warn(
1467
0
                    {qpdf_e_damaged_pdf,
1468
0
                     "",
1469
0
                     description + ": item index " + std::to_string(i) + " (from 0)",
1470
0
                     0,
1471
0
                     "ignoring non-stream in an array of streams"});
1472
0
            }
1473
0
        }
1474
0
    } else if (isStream()) {
1475
0
        result.emplace_back(*this);
1476
0
    } else if (!null()) {
1477
0
        warn(
1478
0
            {qpdf_e_damaged_pdf,
1479
0
             "",
1480
0
             description,
1481
0
             0,
1482
0
             " object is supposed to be a stream or an array of streams but is neither"});
1483
0
    }
1484
1485
0
    bool first = true;
1486
0
    for (auto const& item: result) {
1487
0
        if (first) {
1488
0
            first = false;
1489
0
        } else {
1490
0
            all_description += ",";
1491
0
        }
1492
0
        all_description += " stream " + item.getObjGen().unparse(' ');
1493
0
    }
1494
1495
0
    return result;
1496
0
}
1497
1498
std::vector<QPDFObjectHandle>
1499
QPDFObjectHandle::getPageContents()
1500
0
{
1501
0
    std::string description = "page object " + getObjGen().unparse(' ');
1502
0
    std::string all_description;
1503
0
    return getKey("/Contents").arrayOrStreamToStreamArray(description, all_description);
1504
0
}
1505
1506
void
1507
QPDFObjectHandle::addPageContents(QPDFObjectHandle new_contents, bool first)
1508
0
{
1509
0
    new_contents.assertStream();
1510
1511
0
    std::vector<QPDFObjectHandle> content_streams;
1512
0
    if (first) {
1513
0
        QTC::TC("qpdf", "QPDFObjectHandle prepend page contents");
1514
0
        content_streams.push_back(new_contents);
1515
0
    }
1516
0
    for (auto const& iter: getPageContents()) {
1517
0
        QTC::TC("qpdf", "QPDFObjectHandle append page contents");
1518
0
        content_streams.push_back(iter);
1519
0
    }
1520
0
    if (!first) {
1521
0
        content_streams.push_back(new_contents);
1522
0
    }
1523
1524
0
    replaceKey("/Contents", newArray(content_streams));
1525
0
}
1526
1527
void
1528
QPDFObjectHandle::rotatePage(int angle, bool relative)
1529
0
{
1530
0
    if ((angle % 90) != 0) {
1531
0
        throw std::runtime_error(
1532
0
            "QPDF::rotatePage called with an angle that is not a multiple of 90");
1533
0
    }
1534
0
    int new_angle = angle;
1535
0
    if (relative) {
1536
0
        int old_angle = 0;
1537
0
        QPDFObjectHandle cur_obj = *this;
1538
0
        QPDFObjGen::set visited;
1539
0
        while (visited.add(cur_obj)) {
1540
            // Don't get stuck in an infinite loop
1541
0
            if (cur_obj.getKey("/Rotate").getValueAsInt(old_angle)) {
1542
0
                break;
1543
0
            } else if (cur_obj.getKey("/Parent").isDictionary()) {
1544
0
                cur_obj = cur_obj.getKey("/Parent");
1545
0
            } else {
1546
0
                break;
1547
0
            }
1548
0
        }
1549
0
        QTC::TC("qpdf", "QPDFObjectHandle found old angle", visited.size() > 1 ? 0 : 1);
1550
0
        if ((old_angle % 90) != 0) {
1551
0
            old_angle = 0;
1552
0
        }
1553
0
        new_angle += old_angle;
1554
0
    }
1555
0
    new_angle = (new_angle + 360) % 360;
1556
    // Make this explicit even with new_angle == 0 since /Rotate can be inherited.
1557
0
    replaceKey("/Rotate", Integer(new_angle));
1558
0
}
1559
1560
void
1561
QPDFObjectHandle::coalesceContentStreams()
1562
0
{
1563
0
    QPDFObjectHandle contents = getKey("/Contents");
1564
0
    if (contents.isStream()) {
1565
0
        QTC::TC("qpdf", "QPDFObjectHandle coalesce called on stream");
1566
0
        return;
1567
0
    } else if (!contents.isArray()) {
1568
        // /Contents is optional for pages, and some very damaged files may have pages that are
1569
        // invalid in other ways.
1570
0
        return;
1571
0
    }
1572
    // Should not be possible for a page object to not have an owning PDF unless it was manually
1573
    // constructed in some incorrect way. However, it can happen in a PDF file whose page structure
1574
    // is direct, which is against spec but still possible to hand construct, as in fuzz issue
1575
    // 27393.
1576
0
    QPDF& qpdf = getQPDF("coalesceContentStreams called on object  with no associated PDF file");
1577
1578
0
    QPDFObjectHandle new_contents = newStream(&qpdf);
1579
0
    replaceKey("/Contents", new_contents);
1580
1581
0
    auto provider = std::shared_ptr<StreamDataProvider>(new CoalesceProvider(*this, contents));
1582
0
    new_contents.replaceStreamData(provider, newNull(), newNull());
1583
0
}
1584
1585
std::string
1586
QPDFObjectHandle::unparse() const
1587
0
{
1588
0
    if (isIndirect()) {
1589
0
        return getObjGen().unparse(' ') + " R";
1590
0
    } else {
1591
0
        return unparseResolved();
1592
0
    }
1593
0
}
1594
1595
std::string
1596
QPDFObjectHandle::unparseResolved() const
1597
0
{
1598
0
    if (!obj) {
1599
0
        throw std::logic_error("attempted to dereference an uninitialized QPDFObjectHandle");
1600
0
    }
1601
0
    return BaseHandle::unparse();
1602
0
}
1603
1604
std::string
1605
QPDFObjectHandle::unparseBinary() const
1606
0
{
1607
0
    if (auto str = as<QPDF_String>()) {
1608
0
        return str->unparse(true);
1609
0
    } else {
1610
0
        return unparse();
1611
0
    }
1612
0
}
1613
1614
JSON
1615
QPDFObjectHandle::getJSON(int json_version, bool dereference_indirect) const
1616
0
{
1617
0
    if ((!dereference_indirect) && isIndirect()) {
1618
0
        return JSON::makeString(unparse());
1619
0
    } else if (!obj) {
1620
0
        throw std::logic_error("attempted to dereference an uninitialized QPDFObjectHandle");
1621
0
    } else {
1622
0
        Pl_Buffer p{"json"};
1623
0
        JSON::Writer jw{&p, 0};
1624
0
        writeJSON(json_version, jw, dereference_indirect);
1625
0
        p.finish();
1626
0
        return JSON::parse(p.getString());
1627
0
    }
1628
0
}
1629
1630
void
1631
QPDFObjectHandle::writeJSON(int json_version, JSON::Writer& p, bool dereference_indirect) const
1632
0
{
1633
0
    if (!dereference_indirect && isIndirect()) {
1634
0
        p << "\"" << getObjGen().unparse(' ') << " R\"";
1635
0
    } else if (!obj) {
1636
0
        throw std::logic_error("attempted to dereference an uninitialized QPDFObjectHandle");
1637
0
    } else {
1638
0
        write_json(json_version, p);
1639
0
    }
1640
0
}
1641
1642
void
1643
QPDFObjectHandle::writeJSON(
1644
    int json_version, Pipeline* p, bool dereference_indirect, size_t depth) const
1645
0
{
1646
0
    JSON::Writer jw{p, depth};
1647
0
    writeJSON(json_version, jw, dereference_indirect);
1648
0
}
1649
1650
QPDFObjectHandle
1651
QPDFObjectHandle::wrapInArray()
1652
0
{
1653
0
    if (isArray()) {
1654
0
        return *this;
1655
0
    }
1656
0
    QPDFObjectHandle result = QPDFObjectHandle::newArray();
1657
0
    result.appendItem(*this);
1658
0
    return result;
1659
0
}
1660
1661
QPDFObjectHandle
1662
QPDFObjectHandle::parse(std::string const& object_str, std::string const& object_description)
1663
11.0k
{
1664
11.0k
    return parse(nullptr, object_str, object_description);
1665
11.0k
}
1666
1667
QPDFObjectHandle
1668
QPDFObjectHandle::parse(
1669
    QPDF* context, std::string const& object_str, std::string const& object_description)
1670
11.0k
{
1671
11.0k
    auto input = is::OffsetBuffer("parsed object", object_str);
1672
11.0k
    auto result = Parser::parse(input, object_description, context);
1673
11.0k
    size_t offset = QIntC::to_size(input.tell());
1674
767k
    while (offset < object_str.length()) {
1675
756k
        if (!isspace(object_str.at(offset))) {
1676
75
            QTC::TC("qpdf", "QPDFObjectHandle trailing data in parse");
1677
75
            throw QPDFExc(
1678
75
                qpdf_e_damaged_pdf,
1679
75
                "parsed object",
1680
75
                object_description,
1681
75
                input.getLastOffset(),
1682
75
                "trailing data found parsing object from string");
1683
75
        }
1684
756k
        ++offset;
1685
756k
    }
1686
10.9k
    return result;
1687
11.0k
}
1688
1689
void
1690
QPDFObjectHandle::pipePageContents(Pipeline* p)
1691
0
{
1692
0
    std::string description = "page object " + getObjGen().unparse(' ');
1693
0
    std::string all_description;
1694
0
    getKey("/Contents").pipeContentStreams(p, description, all_description);
1695
0
}
1696
1697
void
1698
QPDFObjectHandle::pipeContentStreams(
1699
    Pipeline* p, std::string const& description, std::string& all_description)
1700
0
{
1701
0
    bool need_newline = false;
1702
0
    std::string buffer;
1703
0
    pl::String buf(buffer);
1704
0
    for (auto stream: arrayOrStreamToStreamArray(description, all_description)) {
1705
0
        if (need_newline) {
1706
0
            buf.writeCStr("\n");
1707
0
        }
1708
0
        if (!stream.pipeStreamData(&buf, 0, qpdf_dl_specialized)) {
1709
0
            QTC::TC("qpdf", "QPDFObjectHandle errors in parsecontent");
1710
0
            throw QPDFExc(
1711
0
                qpdf_e_damaged_pdf,
1712
0
                "content stream",
1713
0
                "content stream object " + stream.getObjGen().unparse(' '),
1714
0
                0,
1715
0
                "errors while decoding content stream");
1716
0
        }
1717
0
        need_newline = buffer.empty() || buffer.back() != '\n';
1718
0
        QTC::TC("qpdf", "QPDFObjectHandle need_newline", need_newline ? 0 : 1);
1719
0
        p->writeString(buffer);
1720
0
        buffer.clear();
1721
0
    }
1722
0
    p->finish();
1723
0
}
1724
1725
void
1726
QPDFObjectHandle::parsePageContents(ParserCallbacks* callbacks)
1727
0
{
1728
0
    std::string description = "page object " + getObjGen().unparse(' ');
1729
0
    getKey("/Contents").parseContentStream_internal(description, callbacks);
1730
0
}
1731
1732
void
1733
QPDFObjectHandle::parseAsContents(ParserCallbacks* callbacks)
1734
0
{
1735
0
    std::string description = "object " + getObjGen().unparse(' ');
1736
0
    parseContentStream_internal(description, callbacks);
1737
0
}
1738
1739
void
1740
QPDFObjectHandle::filterPageContents(TokenFilter* filter, Pipeline* next)
1741
0
{
1742
0
    auto description = "token filter for page object " + getObjGen().unparse(' ');
1743
0
    Pl_QPDFTokenizer token_pipeline(description.c_str(), filter, next);
1744
0
    pipePageContents(&token_pipeline);
1745
0
}
1746
1747
void
1748
QPDFObjectHandle::filterAsContents(TokenFilter* filter, Pipeline* next)
1749
0
{
1750
0
    auto description = "token filter for object " + getObjGen().unparse(' ');
1751
0
    Pl_QPDFTokenizer token_pipeline(description.c_str(), filter, next);
1752
0
    pipeStreamData(&token_pipeline, 0, qpdf_dl_specialized);
1753
0
}
1754
1755
void
1756
QPDFObjectHandle::parseContentStream(QPDFObjectHandle stream_or_array, ParserCallbacks* callbacks)
1757
0
{
1758
0
    stream_or_array.parseContentStream_internal("content stream objects", callbacks);
1759
0
}
1760
1761
void
1762
QPDFObjectHandle::parseContentStream_internal(
1763
    std::string const& description, ParserCallbacks* callbacks)
1764
0
{
1765
0
    std::string stream_data;
1766
0
    pl::String buf(stream_data);
1767
0
    std::string all_description;
1768
0
    pipeContentStreams(&buf, description, all_description);
1769
0
    if (callbacks) {
1770
0
        callbacks->contentSize(stream_data.size());
1771
0
    }
1772
0
    try {
1773
0
        parseContentStream_data(stream_data, all_description, callbacks, getOwningQPDF());
1774
0
    } catch (TerminateParsing&) {
1775
0
        return;
1776
0
    }
1777
0
    if (callbacks) {
1778
0
        callbacks->handleEOF();
1779
0
    }
1780
0
}
1781
1782
void
1783
QPDFObjectHandle::parseContentStream_data(
1784
    std::string_view stream_data,
1785
    std::string const& description,
1786
    ParserCallbacks* callbacks,
1787
    QPDF* context)
1788
0
{
1789
0
    size_t stream_length = stream_data.size();
1790
0
    auto input = is::OffsetBuffer(description, stream_data);
1791
0
    Tokenizer tokenizer;
1792
0
    tokenizer.allowEOF();
1793
0
    auto max_bad_count = Limits::parser_max_errors();
1794
0
    auto sp_description = Parser::make_description(description, "content");
1795
0
    while (QIntC::to_size(input.tell()) < stream_length) {
1796
        // Read a token and seek to the beginning. The offset we get from this process is the
1797
        // beginning of the next non-ignorable (space, comment) token. This way, the offset and
1798
        // don't including ignorable content.
1799
0
        tokenizer.nextToken(input, "content", true);
1800
0
        qpdf_offset_t offset = input.getLastOffset();
1801
0
        input.seek(offset, SEEK_SET);
1802
0
        auto [obj, empty] = Parser::parse_content(input, sp_description, tokenizer, context);
1803
0
        if (empty) {
1804
            // EOF
1805
0
            return;
1806
0
        }
1807
0
        if (!obj) {
1808
0
            if (max_bad_count && --max_bad_count == 0) {
1809
0
                Limits::error();
1810
0
                warn(
1811
0
                    context,
1812
0
                    {qpdf_e_damaged_pdf,
1813
0
                     description,
1814
0
                     "stream data",
1815
0
                     input.tell(),
1816
0
                     "limits error(parser-max-errors): too many errors during content stream "
1817
0
                     "parsing"});
1818
0
                return;
1819
0
            }
1820
0
            obj = newNull();
1821
0
        }
1822
0
        size_t length = QIntC::to_size(input.tell() - offset);
1823
0
        if (callbacks) {
1824
0
            callbacks->handleObject(obj, QIntC::to_size(offset), length);
1825
0
        }
1826
0
        if (obj.isOperator() && obj.getOperatorValue() == "ID") {
1827
            // Discard next character; it is the space after ID that terminated the token.  Read
1828
            // until end of inline image.
1829
0
            char ch;
1830
0
            input.read(&ch, 1);
1831
0
            tokenizer.expectInlineImage(input);
1832
0
            tokenizer.nextToken(input, description);
1833
0
            offset = input.getLastOffset();
1834
0
            length = QIntC::to_size(input.tell() - offset);
1835
0
            if (tokenizer.getType() == QPDFTokenizer::tt_bad) {
1836
0
                QTC::TC("qpdf", "QPDFObjectHandle EOF in inline image");
1837
0
                warn(
1838
0
                    context,
1839
0
                    {qpdf_e_damaged_pdf,
1840
0
                     description,
1841
0
                     "stream data",
1842
0
                     input.tell(),
1843
0
                     "EOF found while reading inline image"});
1844
0
            } else {
1845
0
                QTC::TC("qpdf", "QPDFObjectHandle inline image token");
1846
0
                if (callbacks) {
1847
0
                    callbacks->handleObject(
1848
0
                        QPDFObjectHandle::newInlineImage(tokenizer.getValue()),
1849
0
                        QIntC::to_size(offset),
1850
0
                        length);
1851
0
                }
1852
0
            }
1853
0
        }
1854
0
    }
1855
0
}
1856
1857
void
1858
QPDFObjectHandle::addContentTokenFilter(std::shared_ptr<TokenFilter> filter)
1859
0
{
1860
0
    coalesceContentStreams();
1861
0
    getKey("/Contents").addTokenFilter(filter);
1862
0
}
1863
1864
void
1865
QPDFObjectHandle::addTokenFilter(std::shared_ptr<TokenFilter> filter)
1866
0
{
1867
0
    return as_stream(error).addTokenFilter(filter);
1868
0
}
1869
1870
QPDFObjectHandle
1871
QPDFObjectHandle::parse(
1872
    std::shared_ptr<InputSource> input,
1873
    std::string const& object_description,
1874
    QPDFTokenizer& tokenizer,
1875
    bool& empty,
1876
    StringDecrypter* decrypter,
1877
    QPDF* context)
1878
0
{
1879
0
    return Parser::parse(*input, object_description, tokenizer, empty, decrypter, context);
1880
0
}
1881
1882
qpdf_offset_t
1883
QPDFObjectHandle::getParsedOffset() const
1884
0
{
1885
0
    return offset();
1886
0
}
1887
1888
QPDFObjectHandle
1889
QPDFObjectHandle::newBool(bool value)
1890
758
{
1891
758
    return {QPDFObject::create<QPDF_Bool>(value)};
1892
758
}
1893
1894
QPDFObjectHandle
1895
QPDFObjectHandle::newNull()
1896
21.0k
{
1897
21.0k
    return {QPDFObject::create<QPDF_Null>()};
1898
21.0k
}
1899
1900
QPDFObjectHandle
1901
QPDFObjectHandle::newReal(std::string const& value)
1902
6.69k
{
1903
6.69k
    return {QPDFObject::create<QPDF_Real>(value)};
1904
6.69k
}
1905
1906
QPDFObjectHandle
1907
QPDFObjectHandle::newReal(double value, int decimal_places, bool trim_trailing_zeroes)
1908
0
{
1909
0
    return {QPDFObject::create<QPDF_Real>(value, decimal_places, trim_trailing_zeroes)};
1910
0
}
1911
1912
QPDFObjectHandle
1913
QPDFObjectHandle::newOperator(std::string const& value)
1914
0
{
1915
0
    return {QPDFObject::create<QPDF_Operator>(value)};
1916
0
}
1917
1918
QPDFObjectHandle
1919
QPDFObjectHandle::newInlineImage(std::string const& value)
1920
0
{
1921
0
    return {QPDFObject::create<QPDF_InlineImage>(value)};
1922
0
}
1923
1924
QPDFObjectHandle
1925
QPDFObjectHandle::newArray()
1926
13.1k
{
1927
13.1k
    return newArray(std::vector<QPDFObjectHandle>());
1928
13.1k
}
1929
1930
QPDFObjectHandle
1931
QPDFObjectHandle::newArray(std::vector<QPDFObjectHandle> const& items)
1932
13.1k
{
1933
13.1k
    return {QPDFObject::create<QPDF_Array>(items)};
1934
13.1k
}
1935
1936
QPDFObjectHandle
1937
QPDFObjectHandle::newArray(Rectangle const& rect)
1938
0
{
1939
0
    return newArray({newReal(rect.llx), newReal(rect.lly), newReal(rect.urx), newReal(rect.ury)});
1940
0
}
1941
1942
QPDFObjectHandle
1943
QPDFObjectHandle::newArray(Matrix const& matrix)
1944
0
{
1945
0
    return newArray(
1946
0
        {newReal(matrix.a),
1947
0
         newReal(matrix.b),
1948
0
         newReal(matrix.c),
1949
0
         newReal(matrix.d),
1950
0
         newReal(matrix.e),
1951
0
         newReal(matrix.f)});
1952
0
}
1953
1954
QPDFObjectHandle
1955
QPDFObjectHandle::newArray(QPDFMatrix const& matrix)
1956
0
{
1957
0
    return newArray(
1958
0
        {newReal(matrix.a),
1959
0
         newReal(matrix.b),
1960
0
         newReal(matrix.c),
1961
0
         newReal(matrix.d),
1962
0
         newReal(matrix.e),
1963
0
         newReal(matrix.f)});
1964
0
}
1965
1966
QPDFObjectHandle
1967
QPDFObjectHandle::newFromRectangle(Rectangle const& rect)
1968
0
{
1969
0
    return newArray(rect);
1970
0
}
1971
1972
QPDFObjectHandle
1973
QPDFObjectHandle::newFromMatrix(Matrix const& m)
1974
0
{
1975
0
    return newArray(m);
1976
0
}
1977
1978
QPDFObjectHandle
1979
QPDFObjectHandle::newFromMatrix(QPDFMatrix const& m)
1980
0
{
1981
0
    return newArray(m);
1982
0
}
1983
1984
QPDFObjectHandle
1985
QPDFObjectHandle::newDictionary()
1986
42.5k
{
1987
42.5k
    return newDictionary(std::map<std::string, QPDFObjectHandle>());
1988
42.5k
}
1989
1990
QPDFObjectHandle
1991
QPDFObjectHandle::newDictionary(std::map<std::string, QPDFObjectHandle> const& items)
1992
42.5k
{
1993
42.5k
    return {QPDFObject::create<QPDF_Dictionary>(items)};
1994
42.5k
}
1995
1996
QPDFObjectHandle
1997
QPDFObjectHandle::newStream(QPDF* qpdf)
1998
0
{
1999
0
    if (qpdf == nullptr) {
2000
0
        throw std::runtime_error("attempt to create stream in null qpdf object");
2001
0
    }
2002
0
    QTC::TC("qpdf", "QPDFObjectHandle newStream");
2003
0
    return qpdf->newStream();
2004
0
}
2005
2006
QPDFObjectHandle
2007
QPDFObjectHandle::newStream(QPDF* qpdf, std::shared_ptr<Buffer> data)
2008
0
{
2009
0
    if (qpdf == nullptr) {
2010
0
        throw std::runtime_error("attempt to create stream in null qpdf object");
2011
0
    }
2012
0
    QTC::TC("qpdf", "QPDFObjectHandle newStream with data");
2013
0
    return qpdf->newStream(data);
2014
0
}
2015
2016
QPDFObjectHandle
2017
QPDFObjectHandle::newStream(QPDF* qpdf, std::string const& data)
2018
0
{
2019
0
    if (qpdf == nullptr) {
2020
0
        throw std::runtime_error("attempt to create stream in null qpdf object");
2021
0
    }
2022
0
    QTC::TC("qpdf", "QPDFObjectHandle newStream with string");
2023
0
    return qpdf->newStream(data);
2024
0
}
2025
2026
QPDFObjectHandle
2027
QPDFObjectHandle::newReserved(QPDF* qpdf)
2028
0
{
2029
0
    if (qpdf == nullptr) {
2030
0
        throw std::runtime_error("attempt to create reserved object in null qpdf object");
2031
0
    }
2032
0
    return qpdf->newReserved();
2033
0
}
2034
2035
std::string
2036
BaseHandle::description() const
2037
0
{
2038
0
    return obj ? obj->getDescription() : ""s;
2039
0
}
2040
2041
void
2042
QPDFObjectHandle::setObjectDescription(QPDF* owning_qpdf, std::string const& object_description)
2043
3.32k
{
2044
3.32k
    if (obj) {
2045
3.32k
        auto descr = std::make_shared<QPDFObject::Description>(object_description);
2046
3.32k
        obj->setDescription(owning_qpdf, descr);
2047
3.32k
    }
2048
3.32k
}
2049
2050
bool
2051
QPDFObjectHandle::hasObjectDescription() const
2052
2.49M
{
2053
2.49M
    return obj && obj->hasDescription();
2054
2.49M
}
2055
2056
QPDFObjectHandle
2057
QPDFObjectHandle::shallowCopy()
2058
0
{
2059
0
    if (!obj) {
2060
0
        throw std::logic_error("operation attempted on uninitialized QPDFObjectHandle");
2061
0
    }
2062
0
    return {copy()};
2063
0
}
2064
2065
QPDFObjectHandle
2066
QPDFObjectHandle::unsafeShallowCopy()
2067
0
{
2068
0
    if (!obj) {
2069
0
        throw std::logic_error("operation attempted on uninitialized QPDFObjectHandle");
2070
0
    }
2071
0
    return {copy(true)};
2072
0
}
2073
2074
void
2075
QPDFObjectHandle::makeDirect(uint32_t level, QPDFObjGen::set& visited, bool stop_at_streams)
2076
0
{
2077
0
    static uint32_t constexpr max_nesting = 500;
2078
0
    if (++level > max_nesting + 1) {
2079
0
        throw std::runtime_error("QPDFObjectHandle::makeDirect exceeded maximum nesting level");
2080
0
    }
2081
0
    assertInitialized();
2082
2083
0
    auto cur_og = getObjGen();
2084
0
    if (!visited.add(cur_og)) {
2085
0
        throw std::runtime_error("loop detected while converting object from indirect to direct");
2086
0
    }
2087
2088
0
    if (isBool() || isInteger() || isName() || isNull() || isReal() || isString()) {
2089
0
        obj = copy(true);
2090
0
    } else if (auto a = as_array(strict)) {
2091
0
        std::vector<QPDFObjectHandle> items;
2092
0
        for (auto const& item: a) {
2093
0
            items.emplace_back(item);
2094
0
            items.back().makeDirect(level, visited, stop_at_streams);
2095
0
        }
2096
0
        obj = QPDFObject::create<QPDF_Array>(items);
2097
0
    } else if (isDictionary()) {
2098
0
        std::map<std::string, QPDFObjectHandle> items;
2099
0
        for (auto const& [key, value]: as_dictionary(strict)) {
2100
0
            if (!value.null()) {
2101
0
                items.insert({key, value});
2102
0
                items[key].makeDirect(level, visited, stop_at_streams);
2103
0
            }
2104
0
        }
2105
0
        obj = QPDFObject::create<QPDF_Dictionary>(items);
2106
0
    } else if (isStream()) {
2107
0
        QTC::TC("qpdf", "QPDFObjectHandle copy stream", stop_at_streams ? 0 : 1);
2108
0
        if (!stop_at_streams) {
2109
0
            throw std::runtime_error("attempt to make a stream into a direct object");
2110
0
        }
2111
0
    } else if (isReserved()) {
2112
0
        throw std::logic_error(
2113
0
            "QPDFObjectHandle: attempting to make a reserved object handle direct");
2114
0
    } else {
2115
0
        throw std::logic_error("QPDFObjectHandle::makeDirectInternal: unknown object type");
2116
0
    }
2117
2118
0
    visited.erase(cur_og);
2119
0
}
2120
2121
void
2122
QPDFObjectHandle::makeDirect(bool allow_streams)
2123
0
{
2124
0
    QPDFObjGen::set visited;
2125
0
    makeDirect(0, visited, allow_streams);
2126
0
}
2127
2128
void
2129
QPDFObjectHandle::assertInitialized() const
2130
0
{
2131
0
    if (!obj) {
2132
0
        throw std::logic_error("operation attempted on uninitialized QPDFObjectHandle");
2133
0
    }
2134
0
}
2135
2136
std::invalid_argument
2137
BaseHandle::invalid_error(std::string const& method) const
2138
0
{
2139
0
    return std::invalid_argument(method + " operation attempted on invalid object");
2140
0
}
2141
std::runtime_error
2142
BaseHandle::type_error(char const* expected_type) const
2143
0
{
2144
0
    return std::runtime_error(
2145
0
        "operation for "s + expected_type + " attempted on object of type " + type_name());
2146
0
}
2147
2148
QPDFExc
2149
BaseHandle::type_error(char const* expected_type, std::string const& message) const
2150
0
{
2151
0
    return {
2152
0
        qpdf_e_object,
2153
0
        "",
2154
0
        description(),
2155
0
        0,
2156
0
        "operation for "s + expected_type + " attempted on object of type " + type_name() + ": " +
2157
0
            message};
2158
0
}
2159
2160
void
2161
QPDFObjectHandle::typeWarning(char const* expected_type, std::string const& message) const
2162
0
{
2163
0
    if (!obj) {
2164
0
        throw std::logic_error("attempted to dereference an uninitialized QPDFObjectHandle");
2165
0
    }
2166
0
    warn(type_error(expected_type, message));
2167
0
}
2168
2169
void
2170
QPDFObjectHandle::warnIfPossible(std::string const& warning) const
2171
0
{
2172
0
    warn(warning);
2173
0
}
2174
2175
void
2176
QPDFObjectHandle::objectWarning(std::string const& warning) const
2177
0
{
2178
0
    warn({qpdf_e_object, "", description(), 0, warning});
2179
0
}
2180
2181
void
2182
QPDFObjectHandle::assertType(char const* type_name, bool istype) const
2183
0
{
2184
0
    if (!istype) {
2185
0
        throw type_error(type_name);
2186
0
    }
2187
0
}
2188
2189
void
2190
QPDFObjectHandle::assertNull() const
2191
0
{
2192
0
    assertType("null", isNull());
2193
0
}
2194
2195
void
2196
QPDFObjectHandle::assertBool() const
2197
0
{
2198
0
    assertType("boolean", isBool());
2199
0
}
2200
2201
void
2202
QPDFObjectHandle::assertInteger() const
2203
0
{
2204
0
    assertType("integer", isInteger());
2205
0
}
2206
2207
void
2208
QPDFObjectHandle::assertReal() const
2209
0
{
2210
0
    assertType("real", isReal());
2211
0
}
2212
2213
void
2214
QPDFObjectHandle::assertName() const
2215
0
{
2216
0
    assertType("name", isName());
2217
0
}
2218
2219
void
2220
QPDFObjectHandle::assertString() const
2221
0
{
2222
0
    assertType("string", isString());
2223
0
}
2224
2225
void
2226
QPDFObjectHandle::assertOperator() const
2227
0
{
2228
0
    assertType("operator", isOperator());
2229
0
}
2230
2231
void
2232
QPDFObjectHandle::assertInlineImage() const
2233
0
{
2234
0
    assertType("inlineimage", isInlineImage());
2235
0
}
2236
2237
void
2238
QPDFObjectHandle::assertArray() const
2239
0
{
2240
0
    assertType("array", isArray());
2241
0
}
2242
2243
void
2244
QPDFObjectHandle::assertDictionary() const
2245
0
{
2246
0
    assertType("dictionary", isDictionary());
2247
0
}
2248
2249
void
2250
QPDFObjectHandle::assertStream() const
2251
0
{
2252
0
    assertType("stream", isStream());
2253
0
}
2254
2255
void
2256
QPDFObjectHandle::assertReserved() const
2257
0
{
2258
0
    assertType("reserved", isReserved());
2259
0
}
2260
2261
void
2262
QPDFObjectHandle::assertIndirect() const
2263
0
{
2264
0
    if (!isIndirect()) {
2265
0
        throw std::logic_error("operation for indirect object attempted on direct object");
2266
0
    }
2267
0
}
2268
2269
void
2270
QPDFObjectHandle::assertScalar() const
2271
0
{
2272
0
    assertType("scalar", isScalar());
2273
0
}
2274
2275
void
2276
QPDFObjectHandle::assertNumber() const
2277
0
{
2278
0
    assertType("number", isNumber());
2279
0
}
2280
2281
bool
2282
QPDFObjectHandle::isPageObject() const
2283
0
{
2284
    // See comments in QPDFObjectHandle.hh.
2285
0
    if (!qpdf()) {
2286
0
        return false;
2287
0
    }
2288
    // getAllPages repairs /Type when traversing the page tree.
2289
0
    (void)qpdf()->doc().pages().all();
2290
0
    return isDictionaryOfType("/Page");
2291
0
}
2292
2293
bool
2294
QPDFObjectHandle::isPagesObject() const
2295
0
{
2296
0
    if (!qpdf()) {
2297
0
        return false;
2298
0
    }
2299
    // getAllPages repairs /Type when traversing the page tree.
2300
0
    (void)qpdf()->doc().pages().all();
2301
0
    return isDictionaryOfType("/Pages");
2302
0
}
2303
2304
bool
2305
QPDFObjectHandle::isFormXObject() const
2306
0
{
2307
0
    return isStreamOfType("", "/Form");
2308
0
}
2309
2310
bool
2311
QPDFObjectHandle::isImage(bool exclude_imagemask) const
2312
0
{
2313
0
    return (
2314
0
        isStreamOfType("", "/Image") &&
2315
0
        ((!exclude_imagemask) ||
2316
0
         (!(getDict().getKey("/ImageMask").isBool() &&
2317
0
            getDict().getKey("/ImageMask").getBoolValue()))));
2318
0
}
2319
2320
void
2321
QPDFObjectHandle::assertPageObject() const
2322
0
{
2323
0
    if (!isPageObject()) {
2324
0
        throw std::runtime_error("page operation called on non-Page object");
2325
0
    }
2326
0
}
2327
2328
void
2329
BaseHandle::warn(QPDF* qpdf, QPDFExc&& e)
2330
0
{
2331
0
    if (!qpdf) {
2332
0
        throw std::move(e);
2333
0
    }
2334
0
    qpdf->warn(std::move(e));
2335
0
}
2336
2337
void
2338
BaseHandle::warn(QPDFExc&& e) const
2339
0
{
2340
0
    if (!qpdf()) {
2341
0
        throw std::move(e);
2342
0
    }
2343
0
    qpdf()->warn(std::move(e));
2344
0
}
2345
2346
void
2347
BaseHandle::warn(std::string const& warning) const
2348
0
{
2349
0
    if (qpdf()) {
2350
0
        warn({qpdf_e_damaged_pdf, "", description(), 0, warning});
2351
0
    } else {
2352
0
        *QPDFLogger::defaultLogger()->getError() << warning << "\n";
2353
0
    }
2354
0
}
2355
2356
QPDFObjectHandle::QPDFDictItems::QPDFDictItems(QPDFObjectHandle const& oh) :
2357
0
    oh(oh)
2358
0
{
2359
0
}
2360
2361
QPDFObjectHandle::QPDFDictItems::iterator&
2362
QPDFObjectHandle::QPDFDictItems::iterator::operator++()
2363
0
{
2364
0
    ++m->iter;
2365
0
    updateIValue();
2366
0
    return *this;
2367
0
}
2368
2369
QPDFObjectHandle::QPDFDictItems::iterator&
2370
QPDFObjectHandle::QPDFDictItems::iterator::operator--()
2371
0
{
2372
0
    --m->iter;
2373
0
    updateIValue();
2374
0
    return *this;
2375
0
}
2376
2377
QPDFObjectHandle::QPDFDictItems::iterator::reference
2378
QPDFObjectHandle::QPDFDictItems::iterator::operator*()
2379
0
{
2380
0
    updateIValue();
2381
0
    return ivalue;
2382
0
}
2383
2384
QPDFObjectHandle::QPDFDictItems::iterator::pointer
2385
QPDFObjectHandle::QPDFDictItems::iterator::operator->()
2386
0
{
2387
0
    updateIValue();
2388
0
    return &ivalue;
2389
0
}
2390
2391
bool
2392
QPDFObjectHandle::QPDFDictItems::iterator::operator==(iterator const& other) const
2393
0
{
2394
0
    if (m->is_end && other.m->is_end) {
2395
0
        return true;
2396
0
    }
2397
0
    if (m->is_end || other.m->is_end) {
2398
0
        return false;
2399
0
    }
2400
0
    return (ivalue.first == other.ivalue.first);
2401
0
}
2402
2403
QPDFObjectHandle::QPDFDictItems::iterator::iterator(QPDFObjectHandle& oh, bool for_begin) :
2404
0
    m(new Members(oh, for_begin))
2405
0
{
2406
0
    updateIValue();
2407
0
}
2408
2409
void
2410
QPDFObjectHandle::QPDFDictItems::iterator::updateIValue()
2411
0
{
2412
0
    m->is_end = (m->iter == m->keys.end());
2413
0
    if (m->is_end) {
2414
0
        ivalue.first = "";
2415
0
        ivalue.second = QPDFObjectHandle();
2416
0
    } else {
2417
0
        ivalue.first = *(m->iter);
2418
0
        ivalue.second = m->oh.getKey(ivalue.first);
2419
0
    }
2420
0
}
2421
2422
QPDFObjectHandle::QPDFDictItems::iterator::Members::Members(QPDFObjectHandle& oh, bool for_begin) :
2423
0
    oh(oh)
2424
0
{
2425
0
    keys = oh.getKeys();
2426
0
    iter = for_begin ? keys.begin() : keys.end();
2427
0
}
2428
2429
QPDFObjectHandle::QPDFDictItems::iterator
2430
QPDFObjectHandle::QPDFDictItems::begin()
2431
0
{
2432
0
    return {oh, true};
2433
0
}
2434
2435
QPDFObjectHandle::QPDFDictItems::iterator
2436
QPDFObjectHandle::QPDFDictItems::end()
2437
0
{
2438
0
    return {oh, false};
2439
0
}
2440
2441
QPDFObjectHandle::QPDFArrayItems::QPDFArrayItems(QPDFObjectHandle const& oh) :
2442
0
    oh(oh)
2443
0
{
2444
0
}
2445
2446
QPDFObjectHandle::QPDFArrayItems::iterator&
2447
QPDFObjectHandle::QPDFArrayItems::iterator::operator++()
2448
0
{
2449
0
    if (!m->is_end) {
2450
0
        ++m->item_number;
2451
0
        updateIValue();
2452
0
    }
2453
0
    return *this;
2454
0
}
2455
2456
QPDFObjectHandle::QPDFArrayItems::iterator&
2457
QPDFObjectHandle::QPDFArrayItems::iterator::operator--()
2458
0
{
2459
0
    if (m->item_number > 0) {
2460
0
        --m->item_number;
2461
0
        updateIValue();
2462
0
    }
2463
0
    return *this;
2464
0
}
2465
2466
QPDFObjectHandle::QPDFArrayItems::iterator::reference
2467
QPDFObjectHandle::QPDFArrayItems::iterator::operator*()
2468
0
{
2469
0
    updateIValue();
2470
0
    return ivalue;
2471
0
}
2472
2473
QPDFObjectHandle::QPDFArrayItems::iterator::pointer
2474
QPDFObjectHandle::QPDFArrayItems::iterator::operator->()
2475
0
{
2476
0
    updateIValue();
2477
0
    return &ivalue;
2478
0
}
2479
2480
bool
2481
QPDFObjectHandle::QPDFArrayItems::iterator::operator==(iterator const& other) const
2482
0
{
2483
0
    return (m->item_number == other.m->item_number);
2484
0
}
2485
2486
QPDFObjectHandle::QPDFArrayItems::iterator::iterator(QPDFObjectHandle& oh, bool for_begin) :
2487
0
    m(new Members(oh, for_begin))
2488
0
{
2489
0
    updateIValue();
2490
0
}
2491
2492
void
2493
QPDFObjectHandle::QPDFArrayItems::iterator::updateIValue()
2494
0
{
2495
0
    m->is_end = (m->item_number >= m->oh.getArrayNItems());
2496
0
    if (m->is_end) {
2497
0
        ivalue = QPDFObjectHandle();
2498
0
    } else {
2499
0
        ivalue = m->oh.getArrayItem(m->item_number);
2500
0
    }
2501
0
}
2502
2503
QPDFObjectHandle::QPDFArrayItems::iterator::Members::Members(QPDFObjectHandle& oh, bool for_begin) :
2504
0
    oh(oh)
2505
0
{
2506
0
    item_number = for_begin ? 0 : oh.getArrayNItems();
2507
0
}
2508
2509
QPDFObjectHandle::QPDFArrayItems::iterator
2510
QPDFObjectHandle::QPDFArrayItems::begin()
2511
0
{
2512
0
    return {oh, true};
2513
0
}
2514
2515
QPDFObjectHandle::QPDFArrayItems::iterator
2516
QPDFObjectHandle::QPDFArrayItems::end()
2517
0
{
2518
0
    return {oh, false};
2519
0
}
2520
2521
QPDFObjGen
2522
QPDFObjectHandle::getObjGen() const
2523
69.2k
{
2524
69.2k
    return obj ? obj->getObjGen() : QPDFObjGen();
2525
69.2k
}
2526
2527
int
2528
QPDFObjectHandle::getObjectID() const
2529
38.7k
{
2530
38.7k
    return getObjGen().getObj();
2531
38.7k
}
2532
2533
int
2534
QPDFObjectHandle::getGeneration() const
2535
0
{
2536
0
    return getObjGen().getGen();
2537
0
}
2538
2539
bool
2540
QPDFObjectHandle::isIndirect() const
2541
38.7k
{
2542
38.7k
    return getObjectID() != 0;
2543
38.7k
}
2544
2545
// Indirect object accessors
2546
QPDF*
2547
QPDFObjectHandle::getOwningQPDF() const
2548
272k
{
2549
272k
    return obj ? obj->getQPDF() : nullptr;
2550
272k
}
2551
2552
QPDF&
2553
QPDFObjectHandle::getQPDF(std::string const& error_msg) const
2554
0
{
2555
0
    if (auto result = obj ? obj->getQPDF() : nullptr) {
2556
0
        return *result;
2557
0
    }
2558
0
    throw std::runtime_error(error_msg.empty() ? "attempt to use a null qpdf object" : error_msg);
2559
0
}
2560
2561
void
2562
QPDFObjectHandle::setParsedOffset(qpdf_offset_t offset)
2563
0
{
2564
0
    if (obj) {
2565
0
        obj->setParsedOffset(offset);
2566
0
    }
2567
0
}
2568
2569
QPDFObjectHandle
2570
operator""_qpdf(char const* v, size_t len)
2571
0
{
2572
0
    return QPDFObjectHandle::parse(std::string(v, len), "QPDFObjectHandle literal");
2573
0
}