Coverage Report

Created: 2025-07-18 07:01

/src/qpdf/libqpdf/QPDF_optimization.cc
Line
Count
Source (jump to first uncovered line)
1
// See the "Optimization" section of the manual.
2
3
#include <qpdf/assert_debug.h>
4
5
#include <qpdf/QPDF_private.hh>
6
7
#include <qpdf/QPDFExc.hh>
8
#include <qpdf/QPDFObjectHandle_private.hh>
9
#include <qpdf/QPDFWriter_private.hh>
10
#include <qpdf/QTC.hh>
11
12
QPDF::ObjUser::ObjUser(user_e type) :
13
8.81k
    ou_type(type)
14
8.81k
{
15
8.81k
    qpdf_assert_debug(type == ou_root);
16
8.81k
}
17
18
QPDF::ObjUser::ObjUser(user_e type, int pageno) :
19
37.1k
    ou_type(type),
20
37.1k
    pageno(pageno)
21
37.1k
{
22
37.1k
    qpdf_assert_debug((type == ou_page) || (type == ou_thumb));
23
37.1k
}
24
25
QPDF::ObjUser::ObjUser(user_e type, std::string const& key) :
26
55.1k
    ou_type(type),
27
55.1k
    key(key)
28
55.1k
{
29
55.1k
    qpdf_assert_debug((type == ou_trailer_key) || (type == ou_root_key));
30
55.1k
}
31
32
bool
33
QPDF::ObjUser::operator<(ObjUser const& rhs) const
34
11.1M
{
35
11.1M
    if (ou_type < rhs.ou_type) {
36
541k
        return true;
37
541k
    }
38
10.5M
    if (ou_type == rhs.ou_type) {
39
9.99M
        if (pageno < rhs.pageno) {
40
2.51M
            return true;
41
2.51M
        }
42
7.48M
        if (pageno == rhs.pageno) {
43
4.78M
            return key < rhs.key;
44
4.78M
        }
45
7.48M
    }
46
3.26M
    return false;
47
10.5M
}
48
49
QPDF::UpdateObjectMapsFrame::UpdateObjectMapsFrame(
50
    QPDF::ObjUser const& ou, QPDFObjectHandle oh, bool top) :
51
3.66M
    ou(ou),
52
3.66M
    oh(oh),
53
3.66M
    top(top)
54
3.66M
{
55
3.66M
}
56
57
void
58
QPDF::optimize(
59
    std::map<int, int> const& object_stream_data,
60
    bool allow_changes,
61
    std::function<int(QPDFObjectHandle&)> skip_stream_parameters)
62
0
{
63
0
    optimize_internal(object_stream_data, allow_changes, skip_stream_parameters);
64
0
}
65
66
void
67
QPDF::optimize(
68
    QPDFWriter::ObjTable const& obj, std::function<int(QPDFObjectHandle&)> skip_stream_parameters)
69
8.85k
{
70
8.85k
    optimize_internal(obj, true, skip_stream_parameters);
71
8.85k
}
72
73
template <typename T>
74
void
75
QPDF::optimize_internal(
76
    T const& object_stream_data,
77
    bool allow_changes,
78
    std::function<int(QPDFObjectHandle&)> skip_stream_parameters)
79
8.85k
{
80
8.85k
    if (!m->obj_user_to_objects.empty()) {
81
        // already optimized
82
0
        return;
83
0
    }
84
85
    // The PDF specification indicates that /Outlines is supposed to be an indirect reference. Force
86
    // it to be so if it exists and is direct.  (This has been seen in the wild.)
87
8.85k
    QPDFObjectHandle root = getRoot();
88
8.85k
    if (root.getKey("/Outlines").isDictionary()) {
89
252
        QPDFObjectHandle outlines = root.getKey("/Outlines");
90
252
        if (!outlines.isIndirect()) {
91
27
            QTC::TC("qpdf", "QPDF_optimization indirect outlines");
92
27
            root.replaceKey("/Outlines", makeIndirectObject(outlines));
93
27
        }
94
252
    }
95
96
    // Traverse pages tree pushing all inherited resources down to the page level.  This also
97
    // initializes m->all_pages.
98
8.85k
    pushInheritedAttributesToPage(allow_changes, false);
99
100
    // Traverse pages
101
8.85k
    int n = toI(m->all_pages.size());
102
26.2k
    for (int pageno = 0; pageno < n; ++pageno) {
103
17.3k
        updateObjectMaps(
104
17.3k
            ObjUser(ObjUser::ou_page, pageno),
105
17.3k
            m->all_pages.at(toS(pageno)),
106
17.3k
            skip_stream_parameters);
107
17.3k
    }
108
109
    // Traverse document-level items
110
25.9k
    for (auto const& [key, value]: m->trailer.as_dictionary()) {
111
25.9k
        if (key == "/Root") {
112
            // handled separately
113
17.1k
        } else {
114
17.1k
            if (!value.null()) {
115
12.5k
                updateObjectMaps(
116
12.5k
                    ObjUser(ObjUser::ou_trailer_key, key), value, skip_stream_parameters);
117
12.5k
            }
118
17.1k
        }
119
25.9k
    }
120
121
42.2k
    for (auto const& [key, value]: root.as_dictionary()) {
122
        // Technically, /I keys from /Thread dictionaries are supposed to be handled separately, but
123
        // we are going to disregard that specification for now.  There is loads of evidence that
124
        // pdlin and Acrobat both disregard things like this from time to time, so this is almost
125
        // certain not to cause any problems.
126
42.2k
        if (!value.null()) {
127
35.1k
            updateObjectMaps(ObjUser(ObjUser::ou_root_key, key), value, skip_stream_parameters);
128
35.1k
        }
129
42.2k
    }
130
131
8.85k
    ObjUser root_ou = ObjUser(ObjUser::ou_root);
132
8.85k
    auto root_og = QPDFObjGen(root.getObjGen());
133
8.85k
    m->obj_user_to_objects[root_ou].insert(root_og);
134
8.85k
    m->object_to_obj_users[root_og].insert(root_ou);
135
136
8.85k
    filterCompressedObjects(object_stream_data);
137
8.85k
}
Unexecuted instantiation: void QPDF::optimize_internal<std::__1::map<int, int, std::__1::less<int>, std::__1::allocator<std::__1::pair<int const, int> > > >(std::__1::map<int, int, std::__1::less<int>, std::__1::allocator<std::__1::pair<int const, int> > > const&, bool, std::__1::function<int (QPDFObjectHandle&)>)
void QPDF::optimize_internal<QPDFWriter::ObjTable>(QPDFWriter::ObjTable const&, bool, std::__1::function<int (QPDFObjectHandle&)>)
Line
Count
Source
79
8.85k
{
80
8.85k
    if (!m->obj_user_to_objects.empty()) {
81
        // already optimized
82
0
        return;
83
0
    }
84
85
    // The PDF specification indicates that /Outlines is supposed to be an indirect reference. Force
86
    // it to be so if it exists and is direct.  (This has been seen in the wild.)
87
8.85k
    QPDFObjectHandle root = getRoot();
88
8.85k
    if (root.getKey("/Outlines").isDictionary()) {
89
252
        QPDFObjectHandle outlines = root.getKey("/Outlines");
90
252
        if (!outlines.isIndirect()) {
91
27
            QTC::TC("qpdf", "QPDF_optimization indirect outlines");
92
27
            root.replaceKey("/Outlines", makeIndirectObject(outlines));
93
27
        }
94
252
    }
95
96
    // Traverse pages tree pushing all inherited resources down to the page level.  This also
97
    // initializes m->all_pages.
98
8.85k
    pushInheritedAttributesToPage(allow_changes, false);
99
100
    // Traverse pages
101
8.85k
    int n = toI(m->all_pages.size());
102
26.2k
    for (int pageno = 0; pageno < n; ++pageno) {
103
17.3k
        updateObjectMaps(
104
17.3k
            ObjUser(ObjUser::ou_page, pageno),
105
17.3k
            m->all_pages.at(toS(pageno)),
106
17.3k
            skip_stream_parameters);
107
17.3k
    }
108
109
    // Traverse document-level items
110
25.9k
    for (auto const& [key, value]: m->trailer.as_dictionary()) {
111
25.9k
        if (key == "/Root") {
112
            // handled separately
113
17.1k
        } else {
114
17.1k
            if (!value.null()) {
115
12.5k
                updateObjectMaps(
116
12.5k
                    ObjUser(ObjUser::ou_trailer_key, key), value, skip_stream_parameters);
117
12.5k
            }
118
17.1k
        }
119
25.9k
    }
120
121
42.2k
    for (auto const& [key, value]: root.as_dictionary()) {
122
        // Technically, /I keys from /Thread dictionaries are supposed to be handled separately, but
123
        // we are going to disregard that specification for now.  There is loads of evidence that
124
        // pdlin and Acrobat both disregard things like this from time to time, so this is almost
125
        // certain not to cause any problems.
126
42.2k
        if (!value.null()) {
127
35.1k
            updateObjectMaps(ObjUser(ObjUser::ou_root_key, key), value, skip_stream_parameters);
128
35.1k
        }
129
42.2k
    }
130
131
8.85k
    ObjUser root_ou = ObjUser(ObjUser::ou_root);
132
8.85k
    auto root_og = QPDFObjGen(root.getObjGen());
133
8.85k
    m->obj_user_to_objects[root_ou].insert(root_og);
134
8.85k
    m->object_to_obj_users[root_og].insert(root_ou);
135
136
8.85k
    filterCompressedObjects(object_stream_data);
137
8.85k
}
138
139
void
140
QPDF::pushInheritedAttributesToPage()
141
0
{
142
    // Public API should not have access to allow_changes.
143
0
    pushInheritedAttributesToPage(true, false);
144
0
}
145
146
void
147
QPDF::pushInheritedAttributesToPage(bool allow_changes, bool warn_skipped_keys)
148
14.8k
{
149
    // Traverse pages tree pushing all inherited resources down to the page level.
150
151
    // The record of whether we've done this is cleared by updateAllPagesCache().  If we're warning
152
    // for skipped keys, re-traverse unconditionally.
153
14.8k
    if (m->pushed_inherited_attributes_to_pages && (!warn_skipped_keys)) {
154
5.20k
        return;
155
5.20k
    }
156
157
    // Calling getAllPages() resolves any duplicated page objects, repairs broken nodes, and detects
158
    // loops, so we don't have to do those activities here.
159
9.69k
    getAllPages();
160
161
    // key_ancestors is a mapping of page attribute keys to a stack of Pages nodes that contain
162
    // values for them.
163
9.69k
    std::map<std::string, std::vector<QPDFObjectHandle>> key_ancestors;
164
9.69k
    pushInheritedAttributesToPageInternal(
165
9.69k
        m->trailer.getKey("/Root").getKey("/Pages"),
166
9.69k
        key_ancestors,
167
9.69k
        allow_changes,
168
9.69k
        warn_skipped_keys);
169
9.69k
    if (!key_ancestors.empty()) {
170
0
        throw std::logic_error(
171
0
            "key_ancestors not empty after pushing inherited attributes to pages");
172
0
    }
173
9.69k
    m->pushed_inherited_attributes_to_pages = true;
174
9.69k
    m->ever_pushed_inherited_attributes_to_pages = true;
175
9.69k
}
176
177
void
178
QPDF::pushInheritedAttributesToPageInternal(
179
    QPDFObjectHandle cur_pages,
180
    std::map<std::string, std::vector<QPDFObjectHandle>>& key_ancestors,
181
    bool allow_changes,
182
    bool warn_skipped_keys)
183
10.2k
{
184
    // Make a list of inheritable keys. Only the keys /MediaBox, /CropBox, /Resources, and /Rotate
185
    // are inheritable attributes. Push this object onto the stack of pages nodes that have values
186
    // for this attribute.
187
188
10.2k
    std::set<std::string> inheritable_keys;
189
40.5k
    for (auto const& key: cur_pages.getKeys()) {
190
40.5k
        if ((key == "/MediaBox") || (key == "/CropBox") || (key == "/Resources") ||
191
40.5k
            (key == "/Rotate")) {
192
2.92k
            if (!allow_changes) {
193
0
                throw QPDFExc(
194
0
                    qpdf_e_internal,
195
0
                    m->file->getName(),
196
0
                    m->last_object_description,
197
0
                    m->file->getLastOffset(),
198
0
                    "optimize detected an inheritable attribute when called in no-change mode");
199
0
            }
200
201
            // This is an inheritable resource
202
2.92k
            inheritable_keys.insert(key);
203
2.92k
            QPDFObjectHandle oh = cur_pages.getKey(key);
204
2.92k
            QTC::TC("qpdf", "QPDF opt direct pages resource", oh.isIndirect() ? 0 : 1);
205
2.92k
            if (!oh.isIndirect()) {
206
2.53k
                if (!oh.isScalar()) {
207
                    // Replace shared direct object non-scalar resources with indirect objects to
208
                    // avoid copying large structures around.
209
2.41k
                    cur_pages.replaceKey(key, makeIndirectObject(oh));
210
2.41k
                    oh = cur_pages.getKey(key);
211
2.41k
                } else {
212
                    // It's okay to copy scalars.
213
125
                    QTC::TC("qpdf", "QPDF opt inherited scalar");
214
125
                }
215
2.53k
            }
216
2.92k
            key_ancestors[key].push_back(oh);
217
2.92k
            if (key_ancestors[key].size() > 1) {
218
54
                QTC::TC("qpdf", "QPDF opt key ancestors depth > 1");
219
54
            }
220
            // Remove this resource from this node.  It will be reattached at the page level.
221
2.92k
            cur_pages.removeKey(key);
222
37.5k
        } else if (!((key == "/Type") || (key == "/Parent") || (key == "/Kids") ||
223
37.5k
                     (key == "/Count"))) {
224
            // Warn when flattening, but not if the key is at the top level (i.e. "/Parent" not
225
            // set), as we don't change these; but flattening removes intermediate /Pages nodes.
226
8.39k
            if ((warn_skipped_keys) && (cur_pages.hasKey("/Parent"))) {
227
476
                QTC::TC("qpdf", "QPDF unknown key not inherited");
228
476
                setLastObjectDescription("Pages object", cur_pages.getObjGen());
229
476
                warn(
230
476
                    qpdf_e_pages,
231
476
                    m->last_object_description,
232
476
                    0,
233
476
                    ("Unknown key " + key +
234
476
                     " in /Pages object is being discarded as a result of flattening the /Pages "
235
476
                     "tree"));
236
476
            }
237
8.39k
        }
238
40.5k
    }
239
240
    // Process descendant nodes. This method does not perform loop detection because all code paths
241
    // that lead here follow a call to getAllPages, which already throws an exception in the event
242
    // of a loop in the pages tree.
243
103k
    for (auto& kid: cur_pages.getKey("/Kids").aitems()) {
244
103k
        if (kid.isDictionaryOfType("/Pages")) {
245
598
            pushInheritedAttributesToPageInternal(
246
598
                kid, key_ancestors, allow_changes, warn_skipped_keys);
247
102k
        } else {
248
            // Add all available inheritable attributes not present in this object to this object.
249
102k
            for (auto const& iter: key_ancestors) {
250
12.0k
                std::string const& key = iter.first;
251
12.0k
                if (!kid.hasKey(key)) {
252
4.60k
                    QTC::TC("qpdf", "QPDF opt resource inherited");
253
4.60k
                    kid.replaceKey(key, iter.second.back());
254
7.43k
                } else {
255
7.43k
                    QTC::TC("qpdf", "QPDF opt page resource hides ancestor");
256
7.43k
                }
257
12.0k
            }
258
102k
        }
259
103k
    }
260
261
    // For each inheritable key, pop the stack.  If the stack becomes empty, remove it from the map.
262
    // That way, the invariant that the list of keys in key_ancestors is exactly those keys for
263
    // which inheritable attributes are available.
264
265
10.2k
    if (!inheritable_keys.empty()) {
266
2.27k
        QTC::TC("qpdf", "QPDF opt inheritable keys");
267
2.74k
        for (auto const& key: inheritable_keys) {
268
2.74k
            key_ancestors[key].pop_back();
269
2.74k
            if (key_ancestors[key].empty()) {
270
2.69k
                QTC::TC("qpdf", "QPDF opt erase empty key ancestor");
271
2.69k
                key_ancestors.erase(key);
272
2.69k
            }
273
2.74k
        }
274
8.01k
    } else {
275
8.01k
        QTC::TC("qpdf", "QPDF opt no inheritable keys");
276
8.01k
    }
277
10.2k
}
278
279
void
280
QPDF::updateObjectMaps(
281
    ObjUser const& first_ou,
282
    QPDFObjectHandle first_oh,
283
    std::function<int(QPDFObjectHandle&)> skip_stream_parameters)
284
65.1k
{
285
65.1k
    QPDFObjGen::set visited;
286
65.1k
    std::vector<UpdateObjectMapsFrame> pending;
287
65.1k
    pending.emplace_back(first_ou, first_oh, true);
288
    // Traverse the object tree from this point taking care to avoid crossing page boundaries.
289
65.1k
    std::unique_ptr<ObjUser> thumb_ou;
290
3.72M
    while (!pending.empty()) {
291
3.66M
        auto cur = pending.back();
292
3.66M
        pending.pop_back();
293
294
3.66M
        bool is_page_node = false;
295
296
3.66M
        if (cur.oh.isDictionaryOfType("/Page")) {
297
106k
            is_page_node = true;
298
106k
            if (!cur.top) {
299
87.5k
                continue;
300
87.5k
            }
301
106k
        }
302
303
3.57M
        if (cur.oh.isIndirect()) {
304
516k
            QPDFObjGen og(cur.oh.getObjGen());
305
516k
            if (!visited.add(og)) {
306
95.9k
                QTC::TC("qpdf", "QPDF opt loop detected");
307
95.9k
                continue;
308
95.9k
            }
309
420k
            m->obj_user_to_objects[cur.ou].insert(og);
310
420k
            m->object_to_obj_users[og].insert(cur.ou);
311
420k
        }
312
313
3.47M
        if (cur.oh.isArray()) {
314
2.58M
            for (auto const& item: cur.oh.as_array()) {
315
2.58M
                pending.emplace_back(cur.ou, item, false);
316
2.58M
            }
317
3.33M
        } else if (cur.oh.isDictionary() || cur.oh.isStream()) {
318
275k
            QPDFObjectHandle dict = cur.oh;
319
275k
            bool is_stream = cur.oh.isStream();
320
275k
            int ssp = 0;
321
275k
            if (is_stream) {
322
70.9k
                dict = cur.oh.getDict();
323
70.9k
                if (skip_stream_parameters) {
324
70.9k
                    ssp = skip_stream_parameters(cur.oh);
325
70.9k
                }
326
70.9k
            }
327
328
1.27M
            for (auto& [key, value]: dict.as_dictionary()) {
329
1.27M
                if (value.null()) {
330
154k
                    continue;
331
154k
                }
332
333
1.11M
                if (is_page_node && (key == "/Thumb")) {
334
                    // Traverse page thumbnail dictionaries as a special case. There can only ever
335
                    // be one /Thumb key on a page, and we see at most one page node per call.
336
1.80k
                    thumb_ou = std::make_unique<ObjUser>(ObjUser::ou_thumb, cur.ou.pageno);
337
1.80k
                    pending.emplace_back(*thumb_ou, dict.getKey(key), false);
338
1.11M
                } else if (is_page_node && (key == "/Parent")) {
339
                    // Don't traverse back up the page tree
340
1.10M
                } else if (
341
1.10M
                    ((ssp >= 1) && (key == "/Length")) ||
342
1.10M
                    ((ssp >= 2) && ((key == "/Filter") || (key == "/DecodeParms")))) {
343
                    // Don't traverse into stream parameters that we are not going to write.
344
1.01M
                } else {
345
1.01M
                    pending.emplace_back(cur.ou, value, false);
346
1.01M
                }
347
1.11M
            }
348
275k
        }
349
3.47M
    }
350
65.1k
}
351
352
void
353
QPDF::filterCompressedObjects(std::map<int, int> const& object_stream_data)
354
0
{
355
0
    if (object_stream_data.empty()) {
356
0
        return;
357
0
    }
358
359
    // Transform object_to_obj_users and obj_user_to_objects so that they refer only to uncompressed
360
    // objects.  If something is a user of a compressed object, then it is really a user of the
361
    // object stream that contains it.
362
363
0
    std::map<ObjUser, std::set<QPDFObjGen>> t_obj_user_to_objects;
364
0
    std::map<QPDFObjGen, std::set<ObjUser>> t_object_to_obj_users;
365
366
0
    for (auto const& i1: m->obj_user_to_objects) {
367
0
        ObjUser const& ou = i1.first;
368
        // Loop over objects.
369
0
        for (auto const& og: i1.second) {
370
0
            auto i2 = object_stream_data.find(og.getObj());
371
0
            if (i2 == object_stream_data.end()) {
372
0
                t_obj_user_to_objects[ou].insert(og);
373
0
            } else {
374
0
                t_obj_user_to_objects[ou].insert(QPDFObjGen(i2->second, 0));
375
0
            }
376
0
        }
377
0
    }
378
379
0
    for (auto const& i1: m->object_to_obj_users) {
380
0
        QPDFObjGen const& og = i1.first;
381
        // Loop over obj_users.
382
0
        for (auto const& ou: i1.second) {
383
0
            auto i2 = object_stream_data.find(og.getObj());
384
0
            if (i2 == object_stream_data.end()) {
385
0
                t_object_to_obj_users[og].insert(ou);
386
0
            } else {
387
0
                t_object_to_obj_users[QPDFObjGen(i2->second, 0)].insert(ou);
388
0
            }
389
0
        }
390
0
    }
391
392
0
    m->obj_user_to_objects = t_obj_user_to_objects;
393
0
    m->object_to_obj_users = t_object_to_obj_users;
394
0
}
395
396
void
397
QPDF::filterCompressedObjects(QPDFWriter::ObjTable const& obj)
398
8.81k
{
399
8.81k
    if (obj.getStreamsEmpty()) {
400
544
        return;
401
544
    }
402
403
    // Transform object_to_obj_users and obj_user_to_objects so that they refer only to uncompressed
404
    // objects.  If something is a user of a compressed object, then it is really a user of the
405
    // object stream that contains it.
406
407
8.27k
    std::map<ObjUser, std::set<QPDFObjGen>> t_obj_user_to_objects;
408
8.27k
    std::map<QPDFObjGen, std::set<ObjUser>> t_object_to_obj_users;
409
410
47.4k
    for (auto const& i1: m->obj_user_to_objects) {
411
47.4k
        ObjUser const& ou = i1.first;
412
        // Loop over objects.
413
415k
        for (auto const& og: i1.second) {
414
415k
            if (obj.contains(og)) {
415
413k
                if (auto const& i2 = obj[og].object_stream; i2 <= 0) {
416
158k
                    t_obj_user_to_objects[ou].insert(og);
417
254k
                } else {
418
254k
                    t_obj_user_to_objects[ou].insert(QPDFObjGen(i2, 0));
419
254k
                }
420
413k
            }
421
415k
        }
422
47.4k
    }
423
424
194k
    for (auto const& i1: m->object_to_obj_users) {
425
194k
        QPDFObjGen const& og = i1.first;
426
194k
        if (obj.contains(og)) {
427
            // Loop over obj_users.
428
413k
            for (auto const& ou: i1.second) {
429
413k
                if (auto i2 = obj[og].object_stream; i2 <= 0) {
430
158k
                    t_object_to_obj_users[og].insert(ou);
431
254k
                } else {
432
254k
                    t_object_to_obj_users[QPDFObjGen(i2, 0)].insert(ou);
433
254k
                }
434
413k
            }
435
192k
        }
436
194k
    }
437
438
8.27k
    m->obj_user_to_objects = t_obj_user_to_objects;
439
8.27k
    m->object_to_obj_users = t_object_to_obj_users;
440
8.27k
}