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