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