Coverage Report

Created: 2025-07-14 06:20

/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
32.3k
    ou_type(type)
14
32.3k
{
15
32.3k
    qpdf_assert_debug(type == ou_root);
16
32.3k
}
17
18
QPDF::ObjUser::ObjUser(user_e type, int pageno) :
19
122k
    ou_type(type),
20
122k
    pageno(pageno)
21
122k
{
22
122k
    qpdf_assert_debug((type == ou_page) || (type == ou_thumb));
23
122k
}
24
25
QPDF::ObjUser::ObjUser(user_e type, std::string const& key) :
26
208k
    ou_type(type),
27
208k
    key(key)
28
208k
{
29
208k
    qpdf_assert_debug((type == ou_trailer_key) || (type == ou_root_key));
30
208k
}
31
32
bool
33
QPDF::ObjUser::operator<(ObjUser const& rhs) const
34
50.2M
{
35
50.2M
    if (ou_type < rhs.ou_type) {
36
1.58M
        return true;
37
1.58M
    }
38
48.6M
    if (ou_type == rhs.ou_type) {
39
46.9M
        if (pageno < rhs.pageno) {
40
6.66M
            return true;
41
6.66M
        }
42
40.3M
        if (pageno == rhs.pageno) {
43
33.2M
            return key < rhs.key;
44
33.2M
        }
45
40.3M
    }
46
8.73M
    return false;
47
48.6M
}
48
49
QPDF::UpdateObjectMapsFrame::UpdateObjectMapsFrame(
50
    QPDF::ObjUser const& ou, QPDFObjectHandle oh, bool top) :
51
12.1M
    ou(ou),
52
12.1M
    oh(oh),
53
12.1M
    top(top)
54
12.1M
{
55
12.1M
}
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
32.4k
{
70
32.4k
    optimize_internal(obj, true, skip_stream_parameters);
71
32.4k
}
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
32.4k
{
80
32.4k
    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
32.4k
    QPDFObjectHandle root = getRoot();
88
32.4k
    if (root.getKey("/Outlines").isDictionary()) {
89
1.17k
        QPDFObjectHandle outlines = root.getKey("/Outlines");
90
1.17k
        if (!outlines.isIndirect()) {
91
64
            QTC::TC("qpdf", "QPDF_optimization indirect outlines");
92
64
            root.replaceKey("/Outlines", makeIndirectObject(outlines));
93
64
        }
94
1.17k
    }
95
96
    // Traverse pages tree pushing all inherited resources down to the page level.  This also
97
    // initializes m->all_pages.
98
32.4k
    pushInheritedAttributesToPage(allow_changes, false);
99
100
    // Traverse pages
101
32.4k
    int n = toI(m->all_pages.size());
102
92.4k
    for (int pageno = 0; pageno < n; ++pageno) {
103
59.9k
        updateObjectMaps(
104
59.9k
            ObjUser(ObjUser::ou_page, pageno),
105
59.9k
            m->all_pages.at(toS(pageno)),
106
59.9k
            skip_stream_parameters);
107
59.9k
    }
108
109
    // Traverse document-level items
110
113k
    for (auto const& [key, value]: m->trailer.as_dictionary()) {
111
113k
        if (key == "/Root") {
112
            // handled separately
113
80.7k
        } else {
114
80.7k
            if (!value.null()) {
115
60.8k
                updateObjectMaps(
116
60.8k
                    ObjUser(ObjUser::ou_trailer_key, key), value, skip_stream_parameters);
117
60.8k
            }
118
80.7k
        }
119
113k
    }
120
121
144k
    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
144k
        if (!value.null()) {
127
118k
            updateObjectMaps(ObjUser(ObjUser::ou_root_key, key), value, skip_stream_parameters);
128
118k
        }
129
144k
    }
130
131
32.4k
    ObjUser root_ou = ObjUser(ObjUser::ou_root);
132
32.4k
    auto root_og = QPDFObjGen(root.getObjGen());
133
32.4k
    m->obj_user_to_objects[root_ou].insert(root_og);
134
32.4k
    m->object_to_obj_users[root_og].insert(root_ou);
135
136
32.4k
    filterCompressedObjects(object_stream_data);
137
32.4k
}
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
32.4k
{
80
32.4k
    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
32.4k
    QPDFObjectHandle root = getRoot();
88
32.4k
    if (root.getKey("/Outlines").isDictionary()) {
89
1.17k
        QPDFObjectHandle outlines = root.getKey("/Outlines");
90
1.17k
        if (!outlines.isIndirect()) {
91
64
            QTC::TC("qpdf", "QPDF_optimization indirect outlines");
92
64
            root.replaceKey("/Outlines", makeIndirectObject(outlines));
93
64
        }
94
1.17k
    }
95
96
    // Traverse pages tree pushing all inherited resources down to the page level.  This also
97
    // initializes m->all_pages.
98
32.4k
    pushInheritedAttributesToPage(allow_changes, false);
99
100
    // Traverse pages
101
32.4k
    int n = toI(m->all_pages.size());
102
92.4k
    for (int pageno = 0; pageno < n; ++pageno) {
103
59.9k
        updateObjectMaps(
104
59.9k
            ObjUser(ObjUser::ou_page, pageno),
105
59.9k
            m->all_pages.at(toS(pageno)),
106
59.9k
            skip_stream_parameters);
107
59.9k
    }
108
109
    // Traverse document-level items
110
113k
    for (auto const& [key, value]: m->trailer.as_dictionary()) {
111
113k
        if (key == "/Root") {
112
            // handled separately
113
80.7k
        } else {
114
80.7k
            if (!value.null()) {
115
60.8k
                updateObjectMaps(
116
60.8k
                    ObjUser(ObjUser::ou_trailer_key, key), value, skip_stream_parameters);
117
60.8k
            }
118
80.7k
        }
119
113k
    }
120
121
144k
    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
144k
        if (!value.null()) {
127
118k
            updateObjectMaps(ObjUser(ObjUser::ou_root_key, key), value, skip_stream_parameters);
128
118k
        }
129
144k
    }
130
131
32.4k
    ObjUser root_ou = ObjUser(ObjUser::ou_root);
132
32.4k
    auto root_og = QPDFObjGen(root.getObjGen());
133
32.4k
    m->obj_user_to_objects[root_ou].insert(root_og);
134
32.4k
    m->object_to_obj_users[root_og].insert(root_ou);
135
136
32.4k
    filterCompressedObjects(object_stream_data);
137
32.4k
}
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
74.5k
{
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
74.5k
    if (m->pushed_inherited_attributes_to_pages && (!warn_skipped_keys)) {
154
11.4k
        return;
155
11.4k
    }
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
63.1k
    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
63.1k
    std::map<std::string, std::vector<QPDFObjectHandle>> key_ancestors;
164
63.1k
    pushInheritedAttributesToPageInternal(
165
63.1k
        m->trailer.getKey("/Root").getKey("/Pages"),
166
63.1k
        key_ancestors,
167
63.1k
        allow_changes,
168
63.1k
        warn_skipped_keys);
169
63.1k
    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
63.1k
    m->pushed_inherited_attributes_to_pages = true;
174
63.1k
    m->ever_pushed_inherited_attributes_to_pages = true;
175
63.1k
}
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
73.5k
{
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
73.5k
    std::set<std::string> inheritable_keys;
189
285k
    for (auto const& key: cur_pages.getKeys()) {
190
285k
        if ((key == "/MediaBox") || (key == "/CropBox") || (key == "/Resources") ||
191
285k
            (key == "/Rotate")) {
192
17.2k
            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
17.2k
            inheritable_keys.insert(key);
203
17.2k
            QPDFObjectHandle oh = cur_pages.getKey(key);
204
17.2k
            QTC::TC("qpdf", "QPDF opt direct pages resource", oh.isIndirect() ? 0 : 1);
205
17.2k
            if (!oh.isIndirect()) {
206
15.1k
                if (!oh.isScalar()) {
207
                    // Replace shared direct object non-scalar resources with indirect objects to
208
                    // avoid copying large structures around.
209
11.0k
                    cur_pages.replaceKey(key, makeIndirectObject(oh));
210
11.0k
                    oh = cur_pages.getKey(key);
211
11.0k
                } else {
212
                    // It's okay to copy scalars.
213
4.05k
                    QTC::TC("qpdf", "QPDF opt inherited scalar");
214
4.05k
                }
215
15.1k
            }
216
17.2k
            key_ancestors[key].push_back(oh);
217
17.2k
            if (key_ancestors[key].size() > 1) {
218
1.18k
                QTC::TC("qpdf", "QPDF opt key ancestors depth > 1");
219
1.18k
            }
220
            // Remove this resource from this node.  It will be reattached at the page level.
221
17.2k
            cur_pages.removeKey(key);
222
268k
        } else if (!((key == "/Type") || (key == "/Parent") || (key == "/Kids") ||
223
268k
                     (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
66.7k
            if ((warn_skipped_keys) && (cur_pages.hasKey("/Parent"))) {
227
9.09k
                QTC::TC("qpdf", "QPDF unknown key not inherited");
228
9.09k
                setLastObjectDescription("Pages object", cur_pages.getObjGen());
229
9.09k
                warn(
230
9.09k
                    qpdf_e_pages,
231
9.09k
                    m->last_object_description,
232
9.09k
                    0,
233
9.09k
                    ("Unknown key " + key +
234
9.09k
                     " in /Pages object is being discarded as a result of flattening the /Pages "
235
9.09k
                     "tree"));
236
9.09k
            }
237
66.7k
        }
238
285k
    }
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
727k
    for (auto& kid: cur_pages.getKey("/Kids").aitems()) {
244
727k
        if (kid.isDictionaryOfType("/Pages")) {
245
10.4k
            pushInheritedAttributesToPageInternal(
246
10.4k
                kid, key_ancestors, allow_changes, warn_skipped_keys);
247
716k
        } else {
248
            // Add all available inheritable attributes not present in this object to this object.
249
716k
            for (auto const& iter: key_ancestors) {
250
92.1k
                std::string const& key = iter.first;
251
92.1k
                if (!kid.hasKey(key)) {
252
57.5k
                    QTC::TC("qpdf", "QPDF opt resource inherited");
253
57.5k
                    kid.replaceKey(key, iter.second.back());
254
57.5k
                } else {
255
34.6k
                    QTC::TC("qpdf", "QPDF opt page resource hides ancestor");
256
34.6k
                }
257
92.1k
            }
258
716k
        }
259
727k
    }
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
73.5k
    if (!inheritable_keys.empty()) {
266
10.4k
        QTC::TC("qpdf", "QPDF opt inheritable keys");
267
14.1k
        for (auto const& key: inheritable_keys) {
268
14.1k
            key_ancestors[key].pop_back();
269
14.1k
            if (key_ancestors[key].empty()) {
270
13.0k
                QTC::TC("qpdf", "QPDF opt erase empty key ancestor");
271
13.0k
                key_ancestors.erase(key);
272
13.0k
            }
273
14.1k
        }
274
63.1k
    } else {
275
63.1k
        QTC::TC("qpdf", "QPDF opt no inheritable keys");
276
63.1k
    }
277
73.5k
}
278
279
void
280
QPDF::updateObjectMaps(
281
    ObjUser const& first_ou,
282
    QPDFObjectHandle first_oh,
283
    std::function<int(QPDFObjectHandle&)> skip_stream_parameters)
284
239k
{
285
239k
    QPDFObjGen::set visited;
286
239k
    std::vector<UpdateObjectMapsFrame> pending;
287
239k
    pending.emplace_back(first_ou, first_oh, true);
288
    // Traverse the object tree from this point taking care to avoid crossing page boundaries.
289
239k
    std::unique_ptr<ObjUser> thumb_ou;
290
12.3M
    while (!pending.empty()) {
291
12.1M
        auto cur = pending.back();
292
12.1M
        pending.pop_back();
293
294
12.1M
        bool is_page_node = false;
295
296
12.1M
        if (cur.oh.isDictionaryOfType("/Page")) {
297
344k
            is_page_node = true;
298
344k
            if (!cur.top) {
299
281k
                continue;
300
281k
            }
301
344k
        }
302
303
11.8M
        if (cur.oh.isIndirect()) {
304
2.66M
            QPDFObjGen og(cur.oh.getObjGen());
305
2.66M
            if (!visited.add(og)) {
306
936k
                QTC::TC("qpdf", "QPDF opt loop detected");
307
936k
                continue;
308
936k
            }
309
1.73M
            m->obj_user_to_objects[cur.ou].insert(og);
310
1.73M
            m->object_to_obj_users[og].insert(cur.ou);
311
1.73M
        }
312
313
10.8M
        if (cur.oh.isArray()) {
314
7.40M
            for (auto const& item: cur.oh.as_array()) {
315
7.40M
                pending.emplace_back(cur.ou, item, false);
316
7.40M
            }
317
10.3M
        } else if (cur.oh.isDictionary() || cur.oh.isStream()) {
318
1.15M
            QPDFObjectHandle dict = cur.oh;
319
1.15M
            bool is_stream = cur.oh.isStream();
320
1.15M
            int ssp = 0;
321
1.15M
            if (is_stream) {
322
225k
                dict = cur.oh.getDict();
323
225k
                if (skip_stream_parameters) {
324
225k
                    ssp = skip_stream_parameters(cur.oh);
325
225k
                }
326
225k
            }
327
328
5.69M
            for (auto& [key, value]: dict.as_dictionary()) {
329
5.69M
                if (value.null()) {
330
920k
                    continue;
331
920k
                }
332
333
4.77M
                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
5.52k
                    thumb_ou = std::make_unique<ObjUser>(ObjUser::ou_thumb, cur.ou.pageno);
337
5.52k
                    pending.emplace_back(*thumb_ou, dict.getKey(key), false);
338
4.76M
                } else if (is_page_node && (key == "/Parent")) {
339
                    // Don't traverse back up the page tree
340
4.71M
                } else if (
341
4.71M
                    ((ssp >= 1) && (key == "/Length")) ||
342
4.71M
                    ((ssp >= 2) && ((key == "/Filter") || (key == "/DecodeParms")))) {
343
                    // Don't traverse into stream parameters that we are not going to write.
344
4.45M
                } else {
345
4.45M
                    pending.emplace_back(cur.ou, value, false);
346
4.45M
                }
347
4.77M
            }
348
1.15M
        }
349
10.8M
    }
350
239k
}
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
32.3k
{
399
32.3k
    if (obj.getStreamsEmpty()) {
400
14.4k
        return;
401
14.4k
    }
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
17.9k
    std::map<ObjUser, std::set<QPDFObjGen>> t_obj_user_to_objects;
408
17.9k
    std::map<QPDFObjGen, std::set<ObjUser>> t_object_to_obj_users;
409
410
115k
    for (auto const& i1: m->obj_user_to_objects) {
411
115k
        ObjUser const& ou = i1.first;
412
        // Loop over objects.
413
1.43M
        for (auto const& og: i1.second) {
414
1.43M
            if (obj.contains(og)) {
415
1.41M
                if (auto const& i2 = obj[og].object_stream; i2 <= 0) {
416
513k
                    t_obj_user_to_objects[ou].insert(og);
417
901k
                } else {
418
901k
                    t_obj_user_to_objects[ou].insert(QPDFObjGen(i2, 0));
419
901k
                }
420
1.41M
            }
421
1.43M
        }
422
115k
    }
423
424
559k
    for (auto const& i1: m->object_to_obj_users) {
425
559k
        QPDFObjGen const& og = i1.first;
426
559k
        if (obj.contains(og)) {
427
            // Loop over obj_users.
428
1.41M
            for (auto const& ou: i1.second) {
429
1.41M
                if (auto i2 = obj[og].object_stream; i2 <= 0) {
430
513k
                    t_object_to_obj_users[og].insert(ou);
431
901k
                } else {
432
901k
                    t_object_to_obj_users[QPDFObjGen(i2, 0)].insert(ou);
433
901k
                }
434
1.41M
            }
435
553k
        }
436
559k
    }
437
438
17.9k
    m->obj_user_to_objects = t_obj_user_to_objects;
439
17.9k
    m->object_to_obj_users = t_object_to_obj_users;
440
17.9k
}