/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 | 5.60M | 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 | 2.04M | { |
43 | 2.04M | return type; |
44 | 2.04M | } |
45 | | |
46 | | qpdf_offset_t |
47 | | QPDFXRefEntry::getOffset() const |
48 | 1.38M | { |
49 | 1.38M | util::assertion(type == 1, "getOffset called for xref entry of type != 1"); |
50 | 1.38M | return this->field1; |
51 | 1.38M | } |
52 | | |
53 | | int |
54 | | QPDFXRefEntry::getObjStreamNumber() const |
55 | 492k | { |
56 | 492k | util::assertion(type == 2, "getObjStreamNumber called for xref entry of type != 2"); |
57 | 492k | return QIntC::to_int(field1); |
58 | 492k | } |
59 | | |
60 | | int |
61 | | QPDFXRefEntry::getObjStreamIndex() const |
62 | 74.3k | { |
63 | 74.3k | util::assertion(type == 2, "getObjStreamIndex called for xref entry of type != 2"); |
64 | 74.3k | return field2; |
65 | 74.3k | } |
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 | 547k | qpdf(qpdf), |
130 | 547k | iter(qpdf.m->resolving.insert(og).first) |
131 | 547k | { |
132 | 547k | } |
133 | | ~ResolveRecorder() |
134 | 547k | { |
135 | 547k | qpdf.m->resolving.erase(iter); |
136 | 547k | } |
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 | 66.1k | o(o), |
148 | 66.1k | checker(checker) |
149 | 66.1k | { |
150 | 66.1k | } |
151 | | ~PatternFinder() final = default; |
152 | | bool |
153 | | check() final |
154 | 45.9k | { |
155 | 45.9k | return (this->o.*checker)(); |
156 | 45.9k | } |
157 | | |
158 | | private: |
159 | | Objects& o; |
160 | | bool (Objects::*checker)(); |
161 | | }; |
162 | | |
163 | | bool |
164 | | Objects::validatePDFVersion(char const*& p, std::string& version) |
165 | 6.10k | { |
166 | 6.10k | if (!util::is_digit(*p)) { |
167 | 1.79k | return false; |
168 | 1.79k | } |
169 | 11.2k | while (util::is_digit(*p)) { |
170 | 6.93k | version.append(1, *p++); |
171 | 6.93k | } |
172 | 4.31k | if (!(*p == '.' && util::is_digit(*(p + 1)))) { |
173 | 1.06k | return false; |
174 | 1.06k | } |
175 | 3.24k | version.append(1, *p++); |
176 | 9.57k | while (util::is_digit(*p)) { |
177 | 6.33k | version.append(1, *p++); |
178 | 6.33k | } |
179 | 3.24k | return true; |
180 | 4.31k | } |
181 | | |
182 | | bool |
183 | | Objects::findHeader() |
184 | 6.10k | { |
185 | 6.10k | qpdf_offset_t global_offset = m->file->tell(); |
186 | 6.10k | std::string line = m->file->readLine(1024); |
187 | 6.10k | char const* p = line.data(); |
188 | 6.10k | util::assertion(strncmp(p, "%PDF-", 5) == 0, "findHeader is not looking at %PDF-"); |
189 | 6.10k | p += 5; |
190 | 6.10k | 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 | 6.10k | if (!validatePDFVersion(p, version)) { |
194 | 2.86k | return false; |
195 | 2.86k | } |
196 | 3.24k | m->pdf_version = version; |
197 | 3.24k | 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.71k | m->file = std::make_shared<OffsetInputSource>(m->file, global_offset); |
202 | 1.71k | } |
203 | 3.24k | return true; |
204 | 6.10k | } |
205 | | |
206 | | bool |
207 | | Objects::findStartxref() |
208 | 8.62k | { |
209 | 8.62k | if (readToken(*m->file).isWord("startxref") && readToken(*m->file).isInteger()) { |
210 | | // Position in front of offset token |
211 | 4.40k | m->file->seek(m->file->getLastOffset(), SEEK_SET); |
212 | 4.40k | return true; |
213 | 4.40k | } |
214 | 4.22k | return false; |
215 | 8.62k | } |
216 | | |
217 | | void |
218 | | Objects::parse(char const* password) |
219 | 20.0k | { |
220 | 20.0k | 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 | 20.0k | PatternFinder hf(*this, &Objects::findHeader); |
226 | 20.0k | if (!m->file->findFirst("%PDF-", 0, 1024, hf)) { |
227 | 16.8k | warn(damagedPDF("", -1, "can't find PDF header")); |
228 | | // QPDFWriter writes files that usually require at least version 1.2 for /FlateDecode |
229 | 16.8k | m->pdf_version = "1.2"; |
230 | 16.8k | } |
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 | 20.0k | m->file->seek(0, SEEK_END); |
235 | 20.0k | qpdf_offset_t end_offset = m->file->tell(); |
236 | 20.0k | 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 | 20.0k | if (m->xref_table_max_id > m->xref_table_max_offset / 3) { |
240 | 20.0k | m->xref_table_max_id = static_cast<int>(m->xref_table_max_offset / 3); |
241 | 20.0k | } |
242 | 20.0k | qpdf_offset_t start_offset = (end_offset > 1054 ? end_offset - 1054 : 0); |
243 | 20.0k | PatternFinder sf(*this, &Objects::findStartxref); |
244 | 20.0k | qpdf_offset_t xref_offset = 0; |
245 | 20.0k | if (m->file->findLast("startxref", start_offset, 0, sf)) { |
246 | 4.04k | xref_offset = QUtil::string_to_ll(readToken(*m->file).getValue().c_str()); |
247 | 4.04k | } |
248 | | |
249 | 20.0k | try { |
250 | 20.0k | if (xref_offset == 0) { |
251 | 16.0k | throw damagedPDF("", -1, "can't find startxref"); |
252 | 16.0k | } |
253 | 3.95k | try { |
254 | 3.95k | read_xref(xref_offset); |
255 | 3.95k | } catch (QPDFExc&) { |
256 | 3.13k | throw; |
257 | 3.13k | } catch (std::exception& e) { |
258 | 411 | throw damagedPDF("", -1, std::string("error reading xref: ") + e.what()); |
259 | 411 | } |
260 | 19.6k | } catch (QPDFExc& e) { |
261 | 19.6k | 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 | 19.6k | if (cf.surpress_recovery()) { |
273 | 0 | throw; |
274 | 0 | } |
275 | 19.6k | reconstruct_xref(e, xref_offset > 0); |
276 | 19.6k | } |
277 | | |
278 | 9.02k | m->encp->initialize(qpdf); |
279 | 9.02k | m->parsed = true; |
280 | 9.02k | 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 | 4 | throw damagedPDF("", -1, "unable to find page tree"); |
283 | 4 | } |
284 | 9.01k | if (m->cf.max_warnings()) { |
285 | 8.57k | if (m->pages.empty()) { |
286 | 8 | throw damagedPDF("", -1, "no pages found"); |
287 | 8 | } |
288 | 8.56k | (void)m->cf.max_warnings(0); |
289 | 8.56k | } |
290 | 9.01k | } |
291 | | |
292 | | void |
293 | | Objects::inParse(bool v) |
294 | 433k | { |
295 | 433k | util::internal_error_if( |
296 | 433k | 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 | 433k | ); |
300 | 433k | m->in_parse = v; |
301 | 433k | } |
302 | | |
303 | | void |
304 | | Objects::setTrailer(QPDFObjectHandle obj) |
305 | 6.37k | { |
306 | 6.37k | if (m->trailer) { |
307 | 431 | return; |
308 | 431 | } |
309 | 5.94k | m->trailer = obj; |
310 | 5.94k | } |
311 | | |
312 | | void |
313 | | Objects::reconstruct_xref(QPDFExc& e, bool found_startxref) |
314 | 20.6k | { |
315 | 20.6k | 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 | 925 | throw e; |
319 | 925 | } |
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 | 19.7k | const auto max_warnings = m->warnings.size() + 1000U; |
324 | 5.32M | auto check_warnings = [this, max_warnings]() { |
325 | 5.32M | if (m->warnings.size() > max_warnings) { |
326 | 0 | throw damagedPDF("", -1, "too many errors while reconstructing cross-reference table"); |
327 | 0 | } |
328 | 5.32M | }; |
329 | | |
330 | 19.7k | m->reconstructed_xref = true; |
331 | | // We may find more objects, which may contain dangling references. |
332 | 19.7k | m->fixed_dangling_refs = false; |
333 | | |
334 | 19.7k | warn(damagedPDF("", -1, "file is damaged")); |
335 | 19.7k | warn(e); |
336 | 19.7k | warn(damagedPDF("", -1, "Attempting to reconstruct cross-reference table")); |
337 | | |
338 | | // Delete all references to type 1 (uncompressed) objects |
339 | 19.7k | std::vector<QPDFObjGen> to_delete; |
340 | 53.0k | for (auto const& iter: m->xref_table) { |
341 | 53.0k | if (iter.second.getType() == 1) { |
342 | 41.7k | to_delete.emplace_back(iter.first); |
343 | 41.7k | } |
344 | 53.0k | } |
345 | 41.7k | for (auto const& iter: to_delete) { |
346 | 41.7k | m->xref_table.erase(iter); |
347 | 41.7k | } |
348 | | |
349 | 19.7k | std::vector<std::tuple<int, int, qpdf_offset_t>> found_objects; |
350 | 19.7k | std::vector<qpdf_offset_t> trailers; |
351 | 19.7k | std::vector<qpdf_offset_t> startxrefs; |
352 | | |
353 | 19.7k | m->file->seek(0, SEEK_END); |
354 | 19.7k | qpdf_offset_t eof = m->file->tell(); |
355 | 19.7k | m->file->seek(0, SEEK_SET); |
356 | | // Don't allow very long tokens here during recovery. All the interesting tokens are covered. |
357 | 19.7k | static size_t const MAX_LEN = 10; |
358 | 5.14M | while (m->file->tell() < eof) { |
359 | 5.12M | QPDFTokenizer::Token t1 = m->objects.readToken(*m->file, MAX_LEN); |
360 | 5.12M | qpdf_offset_t token_start = m->file->tell() - toO(t1.getValue().length()); |
361 | 5.12M | if (t1.isInteger()) { |
362 | 2.24M | auto pos = m->file->tell(); |
363 | 2.24M | auto t2 = m->objects.readToken(*m->file, MAX_LEN); |
364 | 2.24M | if (t2.isInteger() && m->objects.readToken(*m->file, MAX_LEN).isWord("obj")) { |
365 | 168k | int obj = QUtil::string_to_int(t1.getValue().c_str()); |
366 | 168k | if (obj > 0) { |
367 | 167k | int gen = QUtil::string_to_int(t2.getValue().c_str()); |
368 | 167k | if (0 <= gen && gen < 65535) { |
369 | 167k | if (obj <= m->xref_table_max_id) { |
370 | 166k | found_objects.emplace_back(obj, gen, token_start); |
371 | 166k | } else { |
372 | 956 | warn(damagedPDF( |
373 | 956 | "", |
374 | 956 | -1, |
375 | 956 | "ignoring object with impossibly large id " + std::to_string(obj))); |
376 | 956 | } |
377 | 167k | } |
378 | 167k | } |
379 | 168k | } |
380 | 2.24M | m->file->seek(pos, SEEK_SET); |
381 | 2.87M | } else if (!m->trailer && t1.isWord("trailer")) { |
382 | 23.2k | trailers.emplace_back(m->file->tell()); |
383 | 2.85M | } else if (!found_startxref && t1.isWord("startxref")) { |
384 | 2.27k | startxrefs.emplace_back(m->file->tell()); |
385 | 2.27k | } |
386 | 5.12M | check_warnings(); |
387 | 5.12M | m->file->findAndSkipNextEOL(); |
388 | 5.12M | } |
389 | | |
390 | 19.7k | if (!found_startxref && !startxrefs.empty() && !found_objects.empty() && |
391 | 979 | startxrefs.back() > std::get<2>(found_objects.back())) { |
392 | 526 | auto xref_backup{m->xref_table}; |
393 | 526 | try { |
394 | 526 | m->file->seek(startxrefs.back(), SEEK_SET); |
395 | 526 | if (auto offset = QUtil::string_to_ll(readToken(*m->file).getValue().data())) { |
396 | 321 | read_xref(offset); |
397 | | |
398 | 321 | if (qpdf.getRoot().getKey("/Pages").isDictionary()) { |
399 | 4 | warn(damagedPDF( |
400 | 4 | "", -1, "startxref was more than 1024 bytes before end of file")); |
401 | 4 | m->encp->initialize(qpdf); |
402 | 4 | m->parsed = true; |
403 | 4 | m->reconstructed_xref = false; |
404 | 4 | return; |
405 | 4 | } |
406 | 321 | } |
407 | 526 | } catch (...) { |
408 | | // ok, bad luck. Do recovery. |
409 | 319 | } |
410 | 522 | m->xref_table = std::move(xref_backup); |
411 | 522 | } |
412 | | |
413 | 19.7k | auto rend = found_objects.rend(); |
414 | 185k | for (auto it = found_objects.rbegin(); it != rend; it++) { |
415 | 166k | auto [obj, gen, token_start] = *it; |
416 | 166k | insertXrefEntry(obj, 1, token_start, gen); |
417 | 166k | check_warnings(); |
418 | 166k | } |
419 | 19.7k | 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 | 19.7k | int end_index = trailers.size() > 100 ? static_cast<int>(trailers.size()) - 100 : 0; |
424 | 35.0k | for (auto it = trailers.rbegin(); it != std::prev(trailers.rend(), end_index); it++) { |
425 | 17.4k | m->file->seek(*it, SEEK_SET); |
426 | 17.4k | auto t = readTrailer(); |
427 | 17.4k | if (!t.isDictionary()) { |
428 | | // Oh well. It was worth a try. |
429 | 14.4k | } else { |
430 | 2.95k | if (t.hasKey("/Root")) { |
431 | 2.05k | m->trailer = t; |
432 | 2.05k | break; |
433 | 2.05k | } |
434 | 901 | warn(damagedPDF("trailer", *it, "recovered trailer has no /Root entry")); |
435 | 901 | } |
436 | 15.3k | check_warnings(); |
437 | 15.3k | } |
438 | | |
439 | 19.7k | if (!m->trailer) { |
440 | 17.0k | qpdf_offset_t max_offset{0}; |
441 | 17.0k | size_t max_size{0}; |
442 | | // If there are any xref streams, take the last one to appear. |
443 | 88.5k | for (auto const& iter: m->xref_table) { |
444 | 88.5k | auto entry = iter.second; |
445 | 88.5k | if (entry.getType() != 1) { |
446 | 652 | continue; |
447 | 652 | } |
448 | 87.8k | auto oh = qpdf.getObject(iter.first); |
449 | 87.8k | try { |
450 | 87.8k | if (!oh.isStreamOfType("/XRef")) { |
451 | 78.8k | continue; |
452 | 78.8k | } |
453 | 87.8k | } catch (std::exception&) { |
454 | 3.42k | continue; |
455 | 3.42k | } |
456 | 5.55k | auto offset = entry.getOffset(); |
457 | 5.55k | auto size = oh.getDict().getKey("/Size").getUIntValueAsUInt(); |
458 | 5.55k | if (size > max_size || (size == max_size && offset > max_offset)) { |
459 | 5.50k | max_offset = offset; |
460 | 5.50k | setTrailer(oh.getDict()); |
461 | 5.50k | } |
462 | 5.55k | check_warnings(); |
463 | 5.55k | } |
464 | 17.0k | if (max_offset > 0) { |
465 | 5.06k | try { |
466 | 5.06k | read_xref(max_offset, true); |
467 | 5.06k | } catch (std::exception&) { |
468 | 2.71k | warn(damagedPDF( |
469 | 2.71k | "", -1, "error decoding candidate xref stream while recovering damaged file")); |
470 | 2.71k | } |
471 | 5.06k | QTC::TC("qpdf", "QPDF recover xref stream"); |
472 | 5.03k | } |
473 | 17.0k | } |
474 | | |
475 | 19.6k | 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 | 17.3k | QPDFObjectHandle root; |
478 | 289k | for (auto const& iter: m->obj_cache) { |
479 | 289k | try { |
480 | 289k | if (QPDFObjectHandle(iter.second.object).isDictionaryOfType("/Catalog")) { |
481 | 7.77k | root = iter.second.object; |
482 | 7.77k | } |
483 | 289k | } catch (std::exception&) { |
484 | 4.65k | continue; |
485 | 4.65k | } |
486 | 289k | } |
487 | 17.3k | if (root) { |
488 | 7.40k | if (!m->trailer) { |
489 | 5.74k | warn(damagedPDF( |
490 | 5.74k | "", -1, "unable to find trailer dictionary while recovering damaged file")); |
491 | 5.74k | m->trailer = QPDFObjectHandle::newDictionary(); |
492 | 5.74k | } |
493 | 7.40k | m->trailer.replaceKey("/Root", root); |
494 | 7.40k | } |
495 | 17.3k | } |
496 | | |
497 | 19.6k | 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 | 6.25k | throw damagedPDF("", -1, "unable to find trailer dictionary while recovering damaged file"); |
503 | 6.25k | } |
504 | 13.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 | 199 | throw damagedPDF("", -1, "unable to find objects while recovering damaged file"); |
508 | 199 | } |
509 | 13.2k | check_warnings(); |
510 | 13.2k | if (!m->parsed) { |
511 | 13.0k | m->parsed = !m->pages.empty(); |
512 | 13.0k | if (!m->parsed) { |
513 | 529 | throw damagedPDF("", -1, "unable to find any pages while recovering damaged file"); |
514 | 529 | } |
515 | 12.5k | check_warnings(); |
516 | 12.5k | } |
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 | 13.2k | } |
524 | | |
525 | | void |
526 | | Objects::read_xref(qpdf_offset_t xref_offset, bool in_stream_recovery) |
527 | 9.34k | { |
528 | 9.34k | std::map<int, int> free_table; |
529 | 9.34k | std::set<qpdf_offset_t> visited; |
530 | 19.3k | while (xref_offset) { |
531 | 10.1k | visited.insert(xref_offset); |
532 | 10.1k | char buf[7]; |
533 | 10.1k | memset(buf, 0, sizeof(buf)); |
534 | 10.1k | 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 | 10.1k | bool done = false; |
540 | 10.1k | bool skipped_space = false; |
541 | 24.7k | while (!done) { |
542 | 14.5k | char ch; |
543 | 14.5k | if (1 == m->file->read(&ch, 1)) { |
544 | 13.7k | if (util::is_space(ch)) { |
545 | 4.73k | skipped_space = true; |
546 | 9.05k | } else { |
547 | 9.05k | m->file->unreadCh(ch); |
548 | 9.05k | done = true; |
549 | 9.05k | } |
550 | 13.7k | } else { |
551 | 776 | QTC::TC("qpdf", "QPDF eof skipping spaces before xref", skipped_space ? 0 : 1); |
552 | 776 | done = true; |
553 | 776 | } |
554 | 14.5k | } |
555 | | |
556 | 10.1k | 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 | 10.1k | if ((strncmp(buf, "xref", 4) == 0) && util::is_space(buf[4])) { |
560 | 1.45k | if (skipped_space) { |
561 | 84 | warn(damagedPDF("", -1, "extraneous whitespace seen before xref")); |
562 | 84 | } |
563 | 1.45k | QTC::TC( |
564 | 1.45k | "qpdf", |
565 | 1.45k | "QPDF xref space", |
566 | 1.45k | ((buf[4] == '\n') ? 0 |
567 | 1.45k | : (buf[4] == '\r') ? 1 |
568 | 1.09k | : (buf[4] == ' ') ? 2 |
569 | 230 | : 9999)); |
570 | 1.45k | int skip = 4; |
571 | | // buf is null-terminated, and util::is_space('\0') is false, so this won't overrun. |
572 | 3.14k | while (util::is_space(buf[skip])) { |
573 | 1.69k | ++skip; |
574 | 1.69k | } |
575 | 1.45k | xref_offset = read_xrefTable(xref_offset + skip); |
576 | 8.71k | } else { |
577 | 8.71k | xref_offset = read_xrefStream(xref_offset, in_stream_recovery); |
578 | 8.71k | } |
579 | 10.1k | if (visited.contains(xref_offset)) { |
580 | 189 | throw damagedPDF("", -1, "loop detected following xref tables"); |
581 | 189 | } |
582 | 10.1k | } |
583 | | |
584 | 9.15k | if (!m->trailer) { |
585 | 0 | throw damagedPDF("", -1, "unable to find trailer while reading xref"); |
586 | 0 | } |
587 | 9.15k | int size = m->trailer.getKey("/Size").getIntValueAsInt(); |
588 | 9.15k | int max_obj = 0; |
589 | 9.15k | if (!m->xref_table.empty()) { |
590 | 2.55k | max_obj = m->xref_table.rbegin()->first.getObj(); |
591 | 2.55k | } |
592 | 9.15k | if (!m->deleted_objects.empty()) { |
593 | 1.26k | max_obj = std::max(max_obj, *(m->deleted_objects.rbegin())); |
594 | 1.26k | } |
595 | 9.15k | if (size < 1 || (size - 1) != max_obj) { |
596 | 2.09k | if (size == (max_obj + 2) && qpdf.getObject(max_obj + 1, 0).isStreamOfType("/XRef")) { |
597 | 3 | warn(damagedPDF( |
598 | 3 | "", |
599 | 3 | -1, |
600 | 3 | "xref entry for the xref stream itself is missing - a common error handled " |
601 | 3 | "correctly by qpdf and most other applications")); |
602 | 2.09k | } else { |
603 | 2.09k | warn(damagedPDF( |
604 | 2.09k | "", |
605 | 2.09k | -1, |
606 | 2.09k | ("reported number of objects (" + std::to_string(size) + |
607 | 2.09k | ") is not one plus the highest object number (" + std::to_string(max_obj) + ")"))); |
608 | 2.09k | } |
609 | 2.09k | } |
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 | 9.15k | m->deleted_objects.clear(); |
614 | | |
615 | | // Make sure we keep only the highest generation for any object. |
616 | 9.15k | QPDFObjGen last_og{-1, 0}; |
617 | 454k | for (auto const& item: m->xref_table) { |
618 | 454k | auto id = item.first.getObj(); |
619 | 454k | if (id == last_og.getObj() && id > 0) { |
620 | 3.40k | qpdf.removeObject(last_og); |
621 | 3.40k | } |
622 | 454k | last_og = item.first; |
623 | 454k | } |
624 | 9.15k | } |
625 | | |
626 | | bool |
627 | | Objects::parse_xrefFirst(std::string const& line, int& obj, int& num, int& bytes) |
628 | 8.83k | { |
629 | | // is_space and is_digit both return false on '\0', so this will not overrun the null-terminated |
630 | | // buffer. |
631 | 8.83k | char const* p = line.c_str(); |
632 | 8.83k | char const* start = line.c_str(); |
633 | | |
634 | | // Skip zero or more spaces |
635 | 10.5k | while (util::is_space(*p)) { |
636 | 1.70k | ++p; |
637 | 1.70k | } |
638 | | // Require digit |
639 | 8.83k | if (!util::is_digit(*p)) { |
640 | 166 | return false; |
641 | 166 | } |
642 | | // Gather digits |
643 | 8.66k | std::string obj_str; |
644 | 42.9k | while (util::is_digit(*p)) { |
645 | 34.3k | obj_str.append(1, *p++); |
646 | 34.3k | } |
647 | | // Require space |
648 | 8.66k | if (!util::is_space(*p)) { |
649 | 95 | return false; |
650 | 95 | } |
651 | | // Skip spaces |
652 | 31.1k | while (util::is_space(*p)) { |
653 | 22.5k | ++p; |
654 | 22.5k | } |
655 | | // Require digit |
656 | 8.57k | if (!util::is_digit(*p)) { |
657 | 94 | return false; |
658 | 94 | } |
659 | | // Gather digits |
660 | 8.47k | std::string num_str; |
661 | 40.6k | while (util::is_digit(*p)) { |
662 | 32.1k | num_str.append(1, *p++); |
663 | 32.1k | } |
664 | | // Skip any space including line terminators |
665 | 23.3k | while (util::is_space(*p)) { |
666 | 14.8k | ++p; |
667 | 14.8k | } |
668 | 8.47k | bytes = toI(p - start); |
669 | 8.47k | obj = QUtil::string_to_int(obj_str.c_str()); |
670 | 8.47k | num = QUtil::string_to_int(num_str.c_str()); |
671 | 8.47k | return true; |
672 | 8.57k | } |
673 | | |
674 | | bool |
675 | | Objects::read_bad_xrefEntry(qpdf_offset_t& f1, int& f2, char& type) |
676 | 5.94k | { |
677 | | // Reposition after initial read attempt and reread. |
678 | 5.94k | m->file->seek(m->file->getLastOffset(), SEEK_SET); |
679 | 5.94k | 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 | 5.94k | char const* p = line.data(); |
684 | | |
685 | | // Skip zero or more spaces. There aren't supposed to be any. |
686 | 5.94k | bool invalid = false; |
687 | 6.42k | while (util::is_space(*p)) { |
688 | 481 | ++p; |
689 | 481 | invalid = true; |
690 | 481 | } |
691 | | // Require digit |
692 | 5.94k | if (!util::is_digit(*p)) { |
693 | 29 | return false; |
694 | 29 | } |
695 | | // Gather digits |
696 | 5.91k | std::string f1_str; |
697 | 24.7k | while (util::is_digit(*p)) { |
698 | 18.8k | f1_str.append(1, *p++); |
699 | 18.8k | } |
700 | | // Require space |
701 | 5.91k | if (!util::is_space(*p)) { |
702 | 29 | return false; |
703 | 29 | } |
704 | 5.88k | if (util::is_space(*(p + 1))) { |
705 | 260 | invalid = true; |
706 | 260 | } |
707 | | // Skip spaces |
708 | 12.3k | while (util::is_space(*p)) { |
709 | 6.44k | ++p; |
710 | 6.44k | } |
711 | | // Require digit |
712 | 5.88k | if (!util::is_digit(*p)) { |
713 | 59 | return false; |
714 | 59 | } |
715 | | // Gather digits |
716 | 5.82k | std::string f2_str; |
717 | 25.1k | while (util::is_digit(*p)) { |
718 | 19.3k | f2_str.append(1, *p++); |
719 | 19.3k | } |
720 | | // Require space |
721 | 5.82k | if (!util::is_space(*p)) { |
722 | 58 | return false; |
723 | 58 | } |
724 | 5.76k | if (util::is_space(*(p + 1))) { |
725 | 1.11k | invalid = true; |
726 | 1.11k | } |
727 | | // Skip spaces |
728 | 12.9k | while (util::is_space(*p)) { |
729 | 7.21k | ++p; |
730 | 7.21k | } |
731 | 5.76k | if ((*p == 'f') || (*p == 'n')) { |
732 | 5.68k | type = *p; |
733 | 5.68k | } else { |
734 | 79 | return false; |
735 | 79 | } |
736 | 5.68k | if ((f1_str.length() != 10) || (f2_str.length() != 5)) { |
737 | 5.41k | invalid = true; |
738 | 5.41k | } |
739 | | |
740 | 5.68k | if (invalid) { |
741 | 5.42k | warn(damagedPDF("xref table", "accepting invalid xref table entry")); |
742 | 5.42k | } |
743 | | |
744 | 5.68k | f1 = QUtil::string_to_ll(f1_str.c_str()); |
745 | 5.68k | f2 = QUtil::string_to_int(f2_str.c_str()); |
746 | | |
747 | 5.68k | return true; |
748 | 5.76k | } |
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.8k | { |
755 | 16.8k | std::array<char, 21> line; |
756 | 16.8k | if (m->file->read(line.data(), 20) != 20) { |
757 | | // C++20: [[unlikely]] |
758 | 202 | return false; |
759 | 202 | } |
760 | 16.6k | line[20] = '\0'; |
761 | 16.6k | char const* p = line.data(); |
762 | | |
763 | 16.6k | int f1_len = 0; |
764 | 16.6k | 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 | 85.6k | while (*p == '0') { |
771 | 69.0k | ++f1_len; |
772 | 69.0k | ++p; |
773 | 69.0k | } |
774 | 71.2k | while (util::is_digit(*p) && f1_len++ < 10) { |
775 | 54.6k | f1 *= 10; |
776 | 54.6k | f1 += *p++ - '0'; |
777 | 54.6k | } |
778 | | // Require space |
779 | 16.6k | if (!util::is_space(*p++)) { |
780 | | // Entry doesn't start with space or digit. |
781 | | // C++20: [[unlikely]] |
782 | 71 | return false; |
783 | 71 | } |
784 | | // Gather digits. NB No risk of overflow as 99'999 < max int. |
785 | 63.6k | while (*p == '0') { |
786 | 47.0k | ++f2_len; |
787 | 47.0k | ++p; |
788 | 47.0k | } |
789 | 40.2k | while (util::is_digit(*p) && f2_len++ < 5) { |
790 | 23.6k | f2 *= 10; |
791 | 23.6k | f2 += static_cast<int>(*p++ - '0'); |
792 | 23.6k | } |
793 | 16.6k | if (util::is_space(*p++) && (*p == 'f' || *p == 'n')) { |
794 | | // C++20: [[likely]] |
795 | 14.3k | type = *p; |
796 | | // No test for valid line[19]. |
797 | 14.3k | if (*(++p) && *(++p) && (*p == '\n' || *p == '\r') && f1_len == 10 && f2_len == 5) { |
798 | | // C++20: [[likely]] |
799 | 10.6k | return true; |
800 | 10.6k | } |
801 | 14.3k | } |
802 | 5.94k | return read_bad_xrefEntry(f1, f2, type); |
803 | 16.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.45k | { |
809 | 1.45k | m->file->seek(xref_offset, SEEK_SET); |
810 | 1.45k | std::string line; |
811 | 8.86k | while (true) { |
812 | 8.83k | line.assign(50, '\0'); |
813 | 8.83k | m->file->read(line.data(), line.size()); |
814 | 8.83k | int obj = 0; |
815 | 8.83k | int num = 0; |
816 | 8.83k | int bytes = 0; |
817 | 8.83k | if (!parse_xrefFirst(line, obj, num, bytes)) { |
818 | 355 | throw damagedPDF("xref table", "xref syntax invalid"); |
819 | 355 | } |
820 | 8.47k | m->file->seek(m->file->getLastOffset() + bytes, SEEK_SET); |
821 | 24.8k | for (qpdf_offset_t i = obj; i - num < obj; ++i) { |
822 | 16.8k | if (i == 0) { |
823 | | // This is needed by checkLinearization() |
824 | 860 | first_xref_item_offset_ = m->file->tell(); |
825 | 860 | } |
826 | | // For xref_table, these will always be small enough to be ints |
827 | 16.8k | qpdf_offset_t f1 = 0; |
828 | 16.8k | int f2 = 0; |
829 | 16.8k | char type = '\0'; |
830 | 16.8k | if (!read_xrefEntry(f1, f2, type)) { |
831 | 527 | throw damagedPDF( |
832 | 527 | "xref table", "invalid xref entry (obj=" + std::to_string(i) + ")"); |
833 | 527 | } |
834 | 16.3k | if (type == 'f') { |
835 | 5.12k | insertFreeXrefEntry(QPDFObjGen(toI(i), f2)); |
836 | 11.2k | } else { |
837 | 11.2k | insertXrefEntry(toI(i), 1, f1, f2); |
838 | 11.2k | } |
839 | 16.3k | } |
840 | 7.94k | qpdf_offset_t pos = m->file->tell(); |
841 | 7.94k | if (readToken(*m->file).isWord("trailer")) { |
842 | 536 | break; |
843 | 7.41k | } else { |
844 | 7.41k | m->file->seek(pos, SEEK_SET); |
845 | 7.41k | } |
846 | 7.94k | } |
847 | | |
848 | | // Set offset to previous xref table if any |
849 | 569 | QPDFObjectHandle cur_trailer = m->objects.readTrailer(); |
850 | 569 | if (!cur_trailer.isDictionary()) { |
851 | 52 | throw damagedPDF("", "expected trailer dictionary"); |
852 | 52 | } |
853 | | |
854 | 517 | if (!m->trailer) { |
855 | 413 | setTrailer(cur_trailer); |
856 | | |
857 | 413 | if (!m->trailer.hasKey("/Size")) { |
858 | 174 | throw damagedPDF("trailer", "trailer dictionary lacks /Size key"); |
859 | 174 | } |
860 | 239 | if (!m->trailer.getKey("/Size").isInteger()) { |
861 | 2 | throw damagedPDF("trailer", "/Size key in trailer dictionary is not an integer"); |
862 | 2 | } |
863 | 239 | } |
864 | | |
865 | 341 | if (cur_trailer.hasKey("/XRefStm")) { |
866 | 38 | if (cf.ignore_xref_streams()) { |
867 | 0 | QTC::TC("qpdf", "QPDF ignoring XRefStm in trailer"); |
868 | 38 | } else { |
869 | 38 | 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 | 37 | (void)read_xrefStream(cur_trailer.getKey("/XRefStm").getIntValue()); |
873 | 37 | } else { |
874 | 1 | throw damagedPDF("xref stream", xref_offset, "invalid /XRefStm"); |
875 | 1 | } |
876 | 38 | } |
877 | 38 | } |
878 | | |
879 | 340 | if (cur_trailer.hasKey("/Prev")) { |
880 | 125 | if (!cur_trailer.getKey("/Prev").isInteger()) { |
881 | 3 | throw damagedPDF("trailer", "/Prev key in trailer dictionary is not an integer"); |
882 | 3 | } |
883 | 122 | return cur_trailer.getKey("/Prev").getIntValue(); |
884 | 125 | } |
885 | | |
886 | 215 | return 0; |
887 | 340 | } |
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 | 8.41k | { |
893 | 8.41k | if (!cf.ignore_xref_streams()) { |
894 | 8.41k | QPDFObjectHandle xref_obj; |
895 | 8.41k | try { |
896 | 8.41k | m->in_read_xref_stream = true; |
897 | 8.41k | xref_obj = readObjectAtOffset(xref_offset, "xref stream", true); |
898 | 8.41k | } catch (QPDFExc&) { |
899 | | // ignore -- report error below |
900 | 1.77k | } |
901 | 8.41k | m->in_read_xref_stream = false; |
902 | 8.36k | if (xref_obj.isStreamOfType("/XRef")) { |
903 | 6.39k | return processXRefStream(xref_offset, xref_obj, in_stream_recovery); |
904 | 6.39k | } |
905 | 8.36k | } |
906 | | |
907 | 1.97k | throw damagedPDF("", xref_offset, "xref not found"); |
908 | 0 | return 0; // unreachable |
909 | 8.41k | } |
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 | 6.39k | { |
915 | 6.39k | auto W_obj = dict.getKey("/W"); |
916 | 6.39k | if (!(W_obj.size() >= 3 && W_obj.getArrayItem(0).isInteger() && |
917 | 6.22k | W_obj.getArrayItem(1).isInteger() && W_obj.getArrayItem(2).isInteger())) { |
918 | 202 | throw damaged("Cross-reference stream does not have a proper /W key"); |
919 | 202 | } |
920 | | |
921 | 6.19k | std::array<int, 3> W; |
922 | 6.19k | int entry_size = 0; |
923 | 6.19k | auto w_vector = W_obj.getArrayAsVector(); |
924 | 6.19k | int max_bytes = sizeof(qpdf_offset_t); |
925 | 24.5k | for (size_t i = 0; i < 3; ++i) { |
926 | 18.4k | W[i] = w_vector[i].getIntValueAsInt(); |
927 | 18.4k | if (W[i] > max_bytes) { |
928 | 34 | throw damaged("Cross-reference stream's /W contains impossibly large values"); |
929 | 34 | } |
930 | 18.4k | if (W[i] < 0) { |
931 | 55 | throw damaged("Cross-reference stream's /W contains negative values"); |
932 | 55 | } |
933 | 18.3k | entry_size += W[i]; |
934 | 18.3k | } |
935 | 6.10k | if (entry_size == 0) { |
936 | 4 | throw damaged("Cross-reference stream's /W indicates entry size of 0"); |
937 | 4 | } |
938 | 6.09k | return {entry_size, W}; |
939 | 6.10k | } |
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 | 6.09k | { |
946 | | // Number of entries is limited by the highest possible object id and stream size. |
947 | 6.09k | auto max_num_entries = std::numeric_limits<int>::max(); |
948 | 6.09k | 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 | 6.09k | auto Size_obj = dict.getKey("/Size"); |
953 | 6.09k | long long size; |
954 | 6.09k | if (!dict.getKey("/Size").getValueAsInt(size)) { |
955 | 83 | throw damaged("Cross-reference stream does not have a proper /Size key"); |
956 | 6.01k | } else if (size < 0) { |
957 | 60 | throw damaged("Cross-reference stream has a negative /Size key"); |
958 | 5.95k | } else if (size >= max_num_entries) { |
959 | 80 | throw damaged("Cross-reference stream has an impossibly large /Size key"); |
960 | 80 | } |
961 | | // We are not validating that Size <= (Size key of parent xref / trailer). |
962 | 5.87k | return max_num_entries; |
963 | 6.09k | } |
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 | 5.87k | { |
970 | 5.87k | auto size = dict.getKey("/Size").getIntValueAsInt(); |
971 | 5.87k | auto Index_obj = dict.getKey("/Index"); |
972 | | |
973 | 5.87k | if (Index_obj.isArray()) { |
974 | 1.00k | std::vector<std::pair<int, int>> indx; |
975 | 1.00k | int num_entries = 0; |
976 | 1.00k | auto index_vec = Index_obj.getArrayAsVector(); |
977 | 1.00k | if ((index_vec.size() % 2) || index_vec.size() < 2) { |
978 | 23 | throw damaged("Cross-reference stream's /Index has an invalid number of values"); |
979 | 23 | } |
980 | | |
981 | 979 | int i = 0; |
982 | 979 | long long first = 0; |
983 | 5.14k | for (auto& val: index_vec) { |
984 | 5.14k | if (val.isInteger()) { |
985 | 5.12k | if (i % 2) { |
986 | 2.53k | auto count = val.getIntValue(); |
987 | 2.53k | if (count <= 0) { |
988 | 40 | throw damaged( |
989 | 40 | "Cross-reference stream section claims to contain " + |
990 | 40 | std::to_string(count) + " entries"); |
991 | 40 | } |
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 | 2.49k | if (first > (max_num_entries - count) || |
998 | 2.45k | count > (max_num_entries - num_entries)) { |
999 | 45 | throw damaged( |
1000 | 45 | "Cross-reference stream claims to contain too many entries: " + |
1001 | 45 | std::to_string(first) + " " + std::to_string(max_num_entries) + " " + |
1002 | 45 | std::to_string(num_entries)); |
1003 | 45 | } |
1004 | 2.45k | indx.emplace_back(static_cast<int>(first), static_cast<int>(count)); |
1005 | 2.45k | num_entries += static_cast<int>(count); |
1006 | 2.58k | } else { |
1007 | 2.58k | first = val.getIntValue(); |
1008 | 2.58k | if (first < 0) { |
1009 | 40 | throw damaged( |
1010 | 40 | "Cross-reference stream's /Index contains a negative object id"); |
1011 | 2.54k | } else if (first > max_num_entries) { |
1012 | 5 | throw damaged( |
1013 | 5 | "Cross-reference stream's /Index contains an impossibly " |
1014 | 5 | "large object id"); |
1015 | 5 | } |
1016 | 2.58k | } |
1017 | 5.12k | } else { |
1018 | 17 | throw damaged( |
1019 | 17 | "Cross-reference stream's /Index's item " + std::to_string(i) + |
1020 | 17 | " is not an integer"); |
1021 | 17 | } |
1022 | 4.99k | i++; |
1023 | 4.99k | } |
1024 | 832 | QTC::TC("qpdf", "QPDF xref /Index is array", index_vec.size() == 2 ? 0 : 1); |
1025 | 832 | return {num_entries, indx}; |
1026 | 4.86k | } else if (Index_obj.null()) { |
1027 | 4.86k | return {size, {{0, size}}}; |
1028 | 4.86k | } else { |
1029 | 3 | throw damaged("Cross-reference stream does not have a proper /Index key"); |
1030 | 3 | } |
1031 | 5.87k | } |
1032 | | |
1033 | | qpdf_offset_t |
1034 | | Objects::processXRefStream( |
1035 | | qpdf_offset_t xref_offset, QPDFObjectHandle& xref_obj, bool in_stream_recovery) |
1036 | 6.39k | { |
1037 | 6.39k | auto damaged = [this, xref_offset](std::string_view msg) -> QPDFExc { |
1038 | 4.10k | return damagedPDF("xref stream", xref_offset, msg.data()); |
1039 | 4.10k | }; |
1040 | | |
1041 | 6.39k | auto dict = xref_obj.getDict(); |
1042 | | |
1043 | 6.39k | auto [entry_size, W] = processXRefW(dict, damaged); |
1044 | 6.39k | int max_num_entries = processXRefSize(dict, entry_size, damaged); |
1045 | 6.39k | auto [num_entries, indx] = processXRefIndex(dict, max_num_entries, damaged); |
1046 | | |
1047 | 6.39k | std::shared_ptr<Buffer> bp = xref_obj.getStreamData(qpdf_dl_specialized); |
1048 | 6.39k | size_t actual_size = bp->getSize(); |
1049 | 6.39k | auto expected_size = toS(entry_size) * toS(num_entries); |
1050 | | |
1051 | 6.39k | if (expected_size != actual_size) { |
1052 | 3.41k | QPDFExc x = damaged( |
1053 | 3.41k | "Cross-reference stream data has the wrong size; expected = " + |
1054 | 3.41k | std::to_string(expected_size) + "; actual = " + std::to_string(actual_size)); |
1055 | 3.41k | if (expected_size > actual_size) { |
1056 | 511 | throw x; |
1057 | 2.90k | } else { |
1058 | 2.90k | warn(x); |
1059 | 2.90k | } |
1060 | 3.41k | } |
1061 | | |
1062 | 5.88k | 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 | 5.88k | auto p = bp->getBuffer(); |
1067 | 5.88k | for (auto [obj, sec_entries]: indx) { |
1068 | | // Process a subsection. |
1069 | 1.08M | for (int i = 0; i < sec_entries; ++i) { |
1070 | | // Read this entry |
1071 | 1.08M | std::array<qpdf_offset_t, 3> fields{}; |
1072 | 1.08M | if (W[0] == 0) { |
1073 | 93.6k | fields[0] = 1; |
1074 | 93.6k | } |
1075 | 4.33M | for (size_t j = 0; j < 3; ++j) { |
1076 | 7.66M | for (int k = 0; k < W[j]; ++k) { |
1077 | 4.40M | fields[j] <<= 8; |
1078 | 4.40M | fields[j] |= *p++; |
1079 | 4.40M | } |
1080 | 3.25M | } |
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 | 1.08M | if (saw_first_compressed_object) { |
1085 | 918k | if (fields[0] != 2) { |
1086 | 380k | uncompressed_after_compressed_ = true; |
1087 | 380k | } |
1088 | 918k | } else if (fields[0] == 2) { |
1089 | 2.41k | saw_first_compressed_object = true; |
1090 | 2.41k | } |
1091 | 1.08M | if (obj == 0) { |
1092 | | // This is needed by checkLinearization() |
1093 | 3.14k | first_xref_item_offset_ = xref_offset; |
1094 | 1.08M | } 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 | 182k | insertFreeXrefEntry(QPDFObjGen(obj, 0)); |
1099 | 898k | } else { |
1100 | 898k | auto typ = toI(fields[0]); |
1101 | 898k | 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 | 718k | insertXrefEntry(obj, toI(fields[0]), fields[1], toI(fields[2])); |
1106 | 718k | } |
1107 | 898k | } |
1108 | 1.08M | ++obj; |
1109 | 1.08M | } |
1110 | 4.58k | } |
1111 | | |
1112 | 5.88k | if (!m->trailer) { |
1113 | 458 | setTrailer(dict); |
1114 | 458 | } |
1115 | | |
1116 | 5.88k | if (dict.hasKey("/Prev")) { |
1117 | 931 | if (!dict.getKey("/Prev").isInteger()) { |
1118 | 30 | throw damagedPDF( |
1119 | 30 | "xref stream", "/Prev key in xref stream dictionary is not an integer"); |
1120 | 30 | } |
1121 | 901 | return dict.getKey("/Prev").getIntValue(); |
1122 | 4.95k | } else { |
1123 | 4.95k | return 0; |
1124 | 4.95k | } |
1125 | 5.88k | } |
1126 | | |
1127 | | void |
1128 | | Objects::insertXrefEntry(int obj, int f0, qpdf_offset_t f1, int f2) |
1129 | 895k | { |
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 | 895k | int new_gen = f0 == 2 ? 0 : f2; |
1137 | | |
1138 | 895k | if (!(f0 == 1 || f0 == 2)) { |
1139 | 25.4k | return; |
1140 | 25.4k | } |
1141 | | |
1142 | 869k | 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 | 176k | return; |
1148 | 176k | } |
1149 | | |
1150 | 693k | if (m->deleted_objects.contains(obj)) { |
1151 | 2.09k | return; |
1152 | 2.09k | } |
1153 | | |
1154 | 691k | if (f0 == 2) { |
1155 | 466k | if (f1 == obj) { |
1156 | 446 | warn( |
1157 | 446 | damagedPDF("xref stream", "self-referential object stream " + std::to_string(obj))); |
1158 | 446 | return; |
1159 | 446 | } |
1160 | 466k | if (f1 > m->xref_table_max_id) { |
1161 | | // ignore impossibly large object stream ids |
1162 | 13.1k | warn(damagedPDF( |
1163 | 13.1k | "xref stream", |
1164 | 13.1k | "object stream id " + std::to_string(f1) + " for object " + std::to_string(obj) + |
1165 | 13.1k | " is impossibly large")); |
1166 | 13.1k | return; |
1167 | 13.1k | } |
1168 | 466k | } |
1169 | | |
1170 | 678k | auto [iter, created] = m->xref_table.try_emplace(QPDFObjGen(obj, (f0 == 2 ? 0 : f2))); |
1171 | 678k | if (!created) { |
1172 | 53.5k | return; |
1173 | 53.5k | } |
1174 | | |
1175 | 624k | switch (f0) { |
1176 | 181k | case 1: |
1177 | | // f2 is generation |
1178 | 181k | QTC::TC("qpdf", "QPDF xref gen > 0", ((f2 > 0) ? 1 : 0)); |
1179 | 181k | iter->second = QPDFXRefEntry(f1); |
1180 | 181k | break; |
1181 | | |
1182 | 443k | case 2: |
1183 | 443k | iter->second = QPDFXRefEntry(toI(f1), f2); |
1184 | 443k | break; |
1185 | | |
1186 | 0 | default: |
1187 | 0 | throw damagedPDF("xref stream", "unknown xref stream entry type " + std::to_string(f0)); |
1188 | 0 | break; |
1189 | 624k | } |
1190 | 624k | } |
1191 | | |
1192 | | void |
1193 | | Objects::insertFreeXrefEntry(QPDFObjGen og) |
1194 | 187k | { |
1195 | 187k | if (!m->xref_table.contains(og) && og.getObj() <= m->xref_table_max_id) { |
1196 | 75.7k | m->deleted_objects.insert(og.getObj()); |
1197 | 75.7k | } |
1198 | 187k | } |
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 | 8.73k | { |
1231 | 8.73k | bool may_change = !m->reconstructed_xref; |
1232 | 413k | for (auto& iter: m->xref_table) { |
1233 | 413k | if (isUnresolved(iter.first)) { |
1234 | 250k | resolve(iter.first); |
1235 | 250k | if (may_change && m->reconstructed_xref) { |
1236 | 29 | return false; |
1237 | 29 | } |
1238 | 250k | } |
1239 | 413k | } |
1240 | 8.70k | return true; |
1241 | 8.73k | } |
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 | 30.6k | { |
1248 | 30.6k | if (m->fixed_dangling_refs) { |
1249 | 21.9k | return; |
1250 | 21.9k | } |
1251 | 8.70k | if (!m->objects.resolveXRefTable()) { |
1252 | 29 | m->objects.resolveXRefTable(); |
1253 | 29 | } |
1254 | 8.70k | m->fixed_dangling_refs = true; |
1255 | 8.70k | } |
1256 | | |
1257 | | size_t |
1258 | | QPDF::getObjectCount() |
1259 | 22.2k | { |
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 | 22.2k | fixDanglingReferences(); |
1264 | 22.2k | QPDFObjGen og; |
1265 | 22.2k | if (!m->obj_cache.empty()) { |
1266 | 22.2k | og = (*(m->obj_cache.rbegin())).first; |
1267 | 22.2k | } |
1268 | 22.2k | return QIntC::to_size(og.getObj()); |
1269 | 22.2k | } |
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 | 257k | { |
1286 | 257k | m->last_object_description.clear(); |
1287 | 257k | if (!description.empty()) { |
1288 | 6.66k | m->last_object_description += description; |
1289 | 6.66k | if (og.isIndirect()) { |
1290 | 6.66k | m->last_object_description += ": "; |
1291 | 6.66k | } |
1292 | 6.66k | } |
1293 | 257k | if (og.isIndirect()) { |
1294 | 257k | m->last_object_description += "object " + og.unparse(' '); |
1295 | 257k | } |
1296 | 257k | } |
1297 | | |
1298 | | QPDFObjectHandle |
1299 | | Objects::readTrailer() |
1300 | 17.9k | { |
1301 | 17.9k | qpdf_offset_t offset = m->file->tell(); |
1302 | 17.9k | auto object = |
1303 | 17.9k | Parser::parse(*m->file, "trailer", m->tokenizer, nullptr, qpdf, m->reconstructed_xref); |
1304 | 17.9k | if (object.isDictionary() && m->objects.readToken(*m->file).isWord("stream")) { |
1305 | 178 | warn(damagedPDF("trailer", m->file->tell(), "stream keyword found in trailer")); |
1306 | 178 | } |
1307 | | // Override last_offset so that it points to the beginning of the object we just read |
1308 | 17.9k | m->file->setLastOffset(offset); |
1309 | 17.9k | return object; |
1310 | 17.9k | } |
1311 | | |
1312 | | QPDFObjectHandle |
1313 | | Objects::readObject(std::string const& description, QPDFObjGen og) |
1314 | 131k | { |
1315 | 131k | setLastObjectDescription(description, og); |
1316 | 131k | qpdf_offset_t offset = m->file->tell(); |
1317 | | |
1318 | 131k | StringDecrypter decrypter{&qpdf, og}; |
1319 | 131k | StringDecrypter* decrypter_ptr = m->encp->encrypted ? &decrypter : nullptr; |
1320 | 131k | auto object = Parser::parse( |
1321 | 131k | *m->file, |
1322 | 131k | m->last_object_description, |
1323 | 131k | m->tokenizer, |
1324 | 131k | decrypter_ptr, |
1325 | 131k | qpdf, |
1326 | 131k | m->reconstructed_xref || m->in_read_xref_stream); |
1327 | 131k | if (!object) { |
1328 | 10.0k | return {}; |
1329 | 10.0k | } |
1330 | 121k | auto token = readToken(*m->file); |
1331 | 121k | if (object.isDictionary() && token.isWord("stream")) { |
1332 | 52.9k | readStream(object, og, offset); |
1333 | 52.9k | token = readToken(*m->file); |
1334 | 52.9k | } |
1335 | 121k | if (!token.isWord("endobj")) { |
1336 | 27.8k | warn(damagedPDF("expected endobj")); |
1337 | 27.8k | } |
1338 | 121k | return object; |
1339 | 131k | } |
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 | 52.9k | { |
1345 | 52.9k | 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 | 52.9k | qpdf_offset_t stream_offset = m->file->tell(); |
1350 | 52.9k | size_t length = 0; |
1351 | | |
1352 | 52.9k | try { |
1353 | 52.9k | auto length_obj = object.getKey("/Length"); |
1354 | | |
1355 | 52.9k | if (!length_obj.isInteger()) { |
1356 | 16.6k | if (length_obj.null()) { |
1357 | 16.3k | throw damagedPDF(offset, "stream dictionary lacks /Length key"); |
1358 | 16.3k | } |
1359 | 294 | throw damagedPDF(offset, "/Length key in stream dictionary is not an integer"); |
1360 | 16.6k | } |
1361 | | |
1362 | 36.3k | length = toS(length_obj.getUIntValue()); |
1363 | | // Seek in two steps to avoid potential integer overflow |
1364 | 36.3k | m->file->seek(stream_offset, SEEK_SET); |
1365 | 36.3k | m->file->seek(toO(length), SEEK_CUR); |
1366 | 36.3k | if (!readToken(*m->file).isWord("endstream")) { |
1367 | 10.2k | throw damagedPDF("expected endstream"); |
1368 | 10.2k | } |
1369 | 36.3k | } catch (QPDFExc& e) { |
1370 | 30.3k | if (!cf.surpress_recovery()) { |
1371 | 30.3k | warn(e); |
1372 | 30.3k | length = recoverStreamLength(m->file, og, stream_offset); |
1373 | 30.3k | } else { |
1374 | 0 | throw; |
1375 | 0 | } |
1376 | 30.3k | } |
1377 | 48.4k | object = QPDFObjectHandle(qpdf::Stream(qpdf, og, object, stream_offset, length)); |
1378 | 48.4k | } |
1379 | | |
1380 | | void |
1381 | | Objects::validateStreamLineEnd(QPDFObjectHandle& object, QPDFObjGen og, qpdf_offset_t offset) |
1382 | 52.9k | { |
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 | 60.9k | while (true) { |
1391 | 60.8k | char ch; |
1392 | 60.8k | 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 | 107 | return; |
1396 | 107 | } |
1397 | 60.7k | if (ch == '\n') { |
1398 | | // ready to read stream data |
1399 | 26.9k | return; |
1400 | 26.9k | } |
1401 | 33.7k | if (ch == '\r') { |
1402 | | // Read another character |
1403 | 21.4k | if (m->file->read(&ch, 1) != 0) { |
1404 | 21.4k | if (ch == '\n') { |
1405 | | // Ready to read stream data |
1406 | 20.3k | QTC::TC("qpdf", "QPDF stream with CRNL"); |
1407 | 20.3k | } 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 | 1.03k | m->file->unreadCh(ch); |
1411 | 1.03k | warn(damagedPDF( |
1412 | 1.03k | m->file->tell(), "stream keyword followed by carriage return only")); |
1413 | 1.03k | } |
1414 | 21.4k | } |
1415 | 21.4k | return; |
1416 | 21.4k | } |
1417 | 12.3k | if (!util::is_space(ch)) { |
1418 | 4.41k | m->file->unreadCh(ch); |
1419 | 4.41k | warn(damagedPDF( |
1420 | 4.41k | m->file->tell(), "stream keyword not followed by proper line terminator")); |
1421 | 4.41k | return; |
1422 | 4.41k | } |
1423 | 7.91k | warn(damagedPDF(m->file->tell(), "stream keyword followed by extraneous whitespace")); |
1424 | 7.91k | } |
1425 | 52.9k | } |
1426 | | |
1427 | | bool |
1428 | | Objects::findEndstream() |
1429 | 31.1k | { |
1430 | | // Find endstream or endobj. Position the input at that token. |
1431 | 31.1k | auto t = readToken(*m->file, 20); |
1432 | 31.1k | if (t.isWord("endobj") || t.isWord("endstream")) { |
1433 | 25.3k | m->file->seek(m->file->getLastOffset(), SEEK_SET); |
1434 | 25.3k | return true; |
1435 | 25.3k | } |
1436 | 5.83k | return false; |
1437 | 31.1k | } |
1438 | | |
1439 | | size_t |
1440 | | Objects::recoverStreamLength( |
1441 | | std::shared_ptr<InputSource> input, QPDFObjGen og, qpdf_offset_t stream_offset) |
1442 | 26.0k | { |
1443 | | // Try to reconstruct stream length by looking for endstream or endobj |
1444 | 26.0k | warn(damagedPDF(*input, stream_offset, "attempting to recover stream length")); |
1445 | | |
1446 | 26.0k | PatternFinder ef(*this, &Objects::findEndstream); |
1447 | 26.0k | size_t length = 0; |
1448 | 26.0k | if (m->file->findFirst("end", stream_offset, 0, ef)) { |
1449 | 25.3k | length = toS(m->file->tell() - stream_offset); |
1450 | | // Reread endstream but, if it was endobj, don't skip that. |
1451 | 25.3k | QPDFTokenizer::Token t = readToken(*m->file); |
1452 | 25.3k | if (t.getValue() == "endobj") { |
1453 | 14.0k | m->file->seek(m->file->getLastOffset(), SEEK_SET); |
1454 | 14.0k | } |
1455 | 25.3k | } |
1456 | | |
1457 | 26.0k | if (length) { |
1458 | 25.0k | auto end = stream_offset + toO(length); |
1459 | 25.0k | qpdf_offset_t found_offset = 0; |
1460 | 25.0k | QPDFObjGen found_og; |
1461 | | |
1462 | | // Make sure this is inside this object |
1463 | 854k | for (auto const& [current_og, entry]: m->xref_table) { |
1464 | 854k | if (entry.getType() == 1) { |
1465 | 828k | qpdf_offset_t obj_offset = entry.getOffset(); |
1466 | 828k | if (found_offset < obj_offset && obj_offset < end) { |
1467 | 166k | found_offset = obj_offset; |
1468 | 166k | found_og = current_og; |
1469 | 166k | } |
1470 | 828k | } |
1471 | 854k | } |
1472 | 25.0k | 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 | 23.2k | } else { |
1478 | 1.79k | length = 0; |
1479 | 1.79k | } |
1480 | 25.0k | } |
1481 | | |
1482 | 26.0k | if (length == 0) { |
1483 | 2.81k | warn(damagedPDF( |
1484 | 2.81k | *input, stream_offset, "unable to recover stream data; treating stream as empty")); |
1485 | 23.2k | } else { |
1486 | 23.2k | warn(damagedPDF( |
1487 | 23.2k | *input, stream_offset, "recovered stream length: " + std::to_string(length))); |
1488 | 23.2k | } |
1489 | | |
1490 | 26.0k | return length; |
1491 | 26.0k | } |
1492 | | |
1493 | | QPDFTokenizer::Token |
1494 | | Objects::readToken(InputSource& input, size_t max_len) |
1495 | 9.29M | { |
1496 | 9.29M | return m->tokenizer.readToken(input, m->last_object_description, true, max_len); |
1497 | 9.29M | } |
1498 | | |
1499 | | QPDFObjGen |
1500 | | Objects::read_object_start(qpdf_offset_t offset) |
1501 | 134k | { |
1502 | 134k | m->file->seek(offset, SEEK_SET); |
1503 | 134k | QPDFTokenizer::Token tobjid = readToken(*m->file); |
1504 | 134k | bool objidok = tobjid.isInteger(); |
1505 | 134k | if (!objidok) { |
1506 | 2.06k | throw damagedPDF(offset, "expected n n obj"); |
1507 | 2.06k | } |
1508 | 132k | QPDFTokenizer::Token tgen = readToken(*m->file); |
1509 | 132k | bool genok = tgen.isInteger(); |
1510 | 132k | if (!genok) { |
1511 | 167 | throw damagedPDF(offset, "expected n n obj"); |
1512 | 167 | } |
1513 | 131k | QPDFTokenizer::Token tobj = readToken(*m->file); |
1514 | | |
1515 | 131k | bool objok = tobj.isWord("obj"); |
1516 | | |
1517 | 131k | if (!objok) { |
1518 | 270 | throw damagedPDF(offset, "expected n n obj"); |
1519 | 270 | } |
1520 | 131k | int objid = QUtil::string_to_int(tobjid.getValue().c_str()); |
1521 | 131k | int generation = QUtil::string_to_int(tgen.getValue().c_str()); |
1522 | 131k | if (objid <= 0 || objid >= m->xref_table_max_id || generation < 0 || generation >= 65535) { |
1523 | 177 | throw damagedPDF( |
1524 | 177 | offset, |
1525 | 177 | "object " + std::to_string(objid) + " " + std::to_string(generation) + |
1526 | 177 | " has an invalid or impossibly large ID or generation"); |
1527 | 177 | } |
1528 | 131k | return {objid, generation}; |
1529 | 131k | } |
1530 | | |
1531 | | void |
1532 | | Objects::readObjectAtOffset( |
1533 | | bool try_recovery, qpdf_offset_t offset, std::string const& description, QPDFObjGen exp_og) |
1534 | 125k | { |
1535 | 125k | QPDFObjGen og; |
1536 | 125k | setLastObjectDescription(description, exp_og); |
1537 | | |
1538 | 125k | 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 | 125k | if (offset == 0) { |
1547 | 229 | warn(damagedPDF( |
1548 | 229 | -1, |
1549 | 229 | "object has offset 0 - a common error handled correctly by qpdf and most other " |
1550 | 229 | "applications")); |
1551 | 229 | return; |
1552 | 229 | } |
1553 | | |
1554 | 125k | try { |
1555 | 125k | og = read_object_start(offset); |
1556 | 125k | if (exp_og != og) { |
1557 | 48 | QPDFExc e = damagedPDF(offset, "expected " + exp_og.unparse(' ') + " obj"); |
1558 | 48 | if (try_recovery) { |
1559 | | // Will be retried below |
1560 | 48 | throw e; |
1561 | 48 | } else { |
1562 | | // We can try reading the object anyway even if the ID doesn't match. |
1563 | 0 | warn(e); |
1564 | 0 | } |
1565 | 48 | } |
1566 | 125k | } catch (QPDFExc& e) { |
1567 | 1.02k | if (!try_recovery) { |
1568 | 0 | throw; |
1569 | 0 | } |
1570 | | // Try again after reconstructing xref table |
1571 | 1.02k | reconstruct_xref(e); |
1572 | 1.02k | if (m->xref_table.contains(exp_og) && m->xref_table[exp_og].getType() == 1) { |
1573 | 25 | qpdf_offset_t new_offset = m->xref_table[exp_og].getOffset(); |
1574 | 25 | readObjectAtOffset(false, new_offset, description, exp_og); |
1575 | 25 | return; |
1576 | 25 | } |
1577 | 996 | warn(damagedPDF( |
1578 | 996 | "", |
1579 | 996 | -1, |
1580 | 996 | ("object " + exp_og.unparse(' ') + |
1581 | 996 | " not found in file after regenerating cross reference table"))); |
1582 | 996 | return; |
1583 | 1.02k | } |
1584 | | |
1585 | 124k | 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 | 104k | qpdf_offset_t end_before_space = m->file->tell(); |
1590 | | |
1591 | | // skip over spaces |
1592 | 243k | while (true) { |
1593 | 243k | char ch; |
1594 | 243k | if (!m->file->read(&ch, 1)) { |
1595 | 841 | throw damagedPDF(m->file->tell(), "EOF after endobj"); |
1596 | 841 | } |
1597 | 242k | if (!isspace(static_cast<unsigned char>(ch))) { |
1598 | 103k | m->file->seek(-1, SEEK_CUR); |
1599 | 103k | break; |
1600 | 103k | } |
1601 | 242k | } |
1602 | 103k | m->objects.updateCache(og, oh.obj_sp(), end_before_space, m->file->tell()); |
1603 | 103k | } |
1604 | 124k | } |
1605 | | |
1606 | | QPDFObjectHandle |
1607 | | Objects::readObjectAtOffset( |
1608 | | qpdf_offset_t offset, std::string const& description, bool skip_cache_if_in_xref) |
1609 | 8.41k | { |
1610 | 8.41k | auto og = read_object_start(offset); |
1611 | 8.41k | auto oh = readObject(description, og); |
1612 | | |
1613 | 8.41k | if (!oh || !m->objects.isUnresolved(og)) { |
1614 | 5.29k | return oh; |
1615 | 5.29k | } |
1616 | | |
1617 | 3.11k | 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 | 18 | QTC::TC("qpdf", "QPDF skipping cache for known unchecked object"); |
1643 | 18 | return oh; |
1644 | 18 | } |
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.10k | qpdf_offset_t end_before_space = m->file->tell(); |
1650 | | |
1651 | | // skip over spaces |
1652 | 4.74k | while (true) { |
1653 | 2.97k | char ch; |
1654 | 2.97k | if (!m->file->read(&ch, 1)) { |
1655 | 49 | throw damagedPDF(m->file->tell(), "EOF after endobj"); |
1656 | 49 | } |
1657 | 2.92k | if (!isspace(static_cast<unsigned char>(ch))) { |
1658 | 1.28k | m->file->seek(-1, SEEK_CUR); |
1659 | 1.28k | break; |
1660 | 1.28k | } |
1661 | 2.92k | } |
1662 | 3.05k | m->objects.updateCache(og, oh.obj_sp(), end_before_space, m->file->tell()); |
1663 | | |
1664 | 3.05k | return oh; |
1665 | 3.10k | } |
1666 | | |
1667 | | std::shared_ptr<QPDFObject> const& |
1668 | | Objects::resolve(QPDFObjGen og) |
1669 | 547k | { |
1670 | 547k | if (!isUnresolved(og)) { |
1671 | 0 | return m->obj_cache[og].object; |
1672 | 0 | } |
1673 | | |
1674 | 547k | 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 | 96 | warn(damagedPDF("", "loop detected resolving object " + og.unparse(' '))); |
1678 | 96 | updateCache(og, QPDFObject::create<QPDF_Null>(), -1, -1); |
1679 | 96 | return m->obj_cache[og].object; |
1680 | 96 | } |
1681 | 547k | ResolveRecorder rr(qpdf, og); |
1682 | | |
1683 | 547k | if (m->xref_table.contains(og)) { |
1684 | 418k | QPDFXRefEntry const& entry = m->xref_table[og]; |
1685 | 418k | try { |
1686 | 418k | switch (entry.getType()) { |
1687 | 125k | case 1: |
1688 | | // Object stored in cache by readObjectAtOffset |
1689 | 125k | readObjectAtOffset(true, entry.getOffset(), "", og); |
1690 | 125k | break; |
1691 | | |
1692 | 292k | case 2: |
1693 | 292k | resolveObjectsInStream(entry.getObjStreamNumber()); |
1694 | 292k | break; |
1695 | | |
1696 | 13 | default: |
1697 | 13 | throw damagedPDF( |
1698 | 13 | "", -1, ("object " + og.unparse('/') + " has unexpected xref entry type")); |
1699 | 418k | } |
1700 | 418k | } catch (QPDFExc& e) { |
1701 | 53.1k | warn(e); |
1702 | 53.1k | } catch (std::exception& e) { |
1703 | 259 | warn(damagedPDF( |
1704 | 259 | "", -1, ("object " + og.unparse('/') + ": error reading object: " + e.what()))); |
1705 | 259 | } |
1706 | 418k | } |
1707 | | |
1708 | 532k | if (isUnresolved(og)) { |
1709 | | // PDF spec says unknown objects resolve to the null object. |
1710 | 427k | updateCache(og, QPDFObject::create<QPDF_Null>(), -1, -1); |
1711 | 427k | } |
1712 | | |
1713 | 532k | auto& result(m->obj_cache[og].object); |
1714 | 532k | result->setDefaultDescription(&qpdf, og); |
1715 | 532k | return result; |
1716 | 547k | } |
1717 | | |
1718 | | void |
1719 | | Objects::resolveObjectsInStream(int obj_stream_number) |
1720 | 292k | { |
1721 | 292k | auto damaged = |
1722 | 292k | [this, obj_stream_number](int id, qpdf_offset_t offset, std::string const& msg) -> QPDFExc { |
1723 | 20.3k | return { |
1724 | 20.3k | qpdf_e_damaged_pdf, |
1725 | 20.3k | m->file->getName() + " object stream " + std::to_string(obj_stream_number), |
1726 | 20.3k | +"object " + std::to_string(id) + " 0", |
1727 | 20.3k | offset, |
1728 | 20.3k | msg, |
1729 | 20.3k | true}; |
1730 | 20.3k | }; |
1731 | | |
1732 | 292k | if (m->resolved_object_streams.contains(obj_stream_number)) { |
1733 | 249k | return; |
1734 | 249k | } |
1735 | 42.7k | m->resolved_object_streams.insert(obj_stream_number); |
1736 | | // Force resolution of object stream |
1737 | 42.7k | Stream obj_stream = qpdf.getObject(obj_stream_number, 0); |
1738 | 42.7k | if (!obj_stream) { |
1739 | 36.5k | throw damagedPDF( |
1740 | 36.5k | "object " + std::to_string(obj_stream_number) + " 0", |
1741 | 36.5k | "supposed object stream " + std::to_string(obj_stream_number) + " is not a stream"); |
1742 | 36.5k | } |
1743 | | |
1744 | | // For linearization data in the object, use the data from the object stream for the objects in |
1745 | | // the stream. |
1746 | 6.29k | QPDFObjGen stream_og(obj_stream_number, 0); |
1747 | 6.29k | qpdf_offset_t end_before_space = m->obj_cache[stream_og].end_before_space; |
1748 | 6.29k | qpdf_offset_t end_after_space = m->obj_cache[stream_og].end_after_space; |
1749 | | |
1750 | 6.29k | QPDFObjectHandle dict = obj_stream.getDict(); |
1751 | 6.29k | if (!dict.isDictionaryOfType("/ObjStm")) { |
1752 | 958 | warn(damagedPDF( |
1753 | 958 | "object " + std::to_string(obj_stream_number) + " 0", |
1754 | 958 | "supposed object stream " + std::to_string(obj_stream_number) + " has wrong type")); |
1755 | 958 | } |
1756 | | |
1757 | 6.29k | unsigned int n{0}; |
1758 | 6.29k | int first{0}; |
1759 | 6.29k | if (!(dict.getKey("/N").getValueAsUInt(n) && dict.getKey("/First").getValueAsInt(first))) { |
1760 | 440 | throw damagedPDF( |
1761 | 440 | "object " + std::to_string(obj_stream_number) + " 0", |
1762 | 440 | "object stream " + std::to_string(obj_stream_number) + " has incorrect keys"); |
1763 | 440 | } |
1764 | | |
1765 | | // id, offset, size |
1766 | 5.85k | std::vector<std::tuple<int, qpdf_offset_t, size_t>> offsets; |
1767 | | |
1768 | 5.85k | auto stream_data = obj_stream.getStreamData(qpdf_dl_specialized); |
1769 | | |
1770 | 5.85k | is::OffsetBuffer input("", stream_data); |
1771 | | |
1772 | 5.85k | const auto b_size = stream_data.size(); |
1773 | 5.85k | const auto end_offset = static_cast<qpdf_offset_t>(b_size); |
1774 | 5.85k | auto b_start = stream_data.data(); |
1775 | | |
1776 | 5.85k | if (first >= end_offset) { |
1777 | 74 | throw damagedPDF( |
1778 | 74 | "object " + std::to_string(obj_stream_number) + " 0", |
1779 | 74 | "object stream " + std::to_string(obj_stream_number) + " has invalid /First entry"); |
1780 | 74 | } |
1781 | | |
1782 | 5.78k | int id = 0; |
1783 | 5.78k | long long last_offset = -1; |
1784 | 5.78k | bool is_first = true; |
1785 | 110k | for (unsigned int i = 0; i < n; ++i) { |
1786 | 104k | auto tnum = readToken(input); |
1787 | 104k | auto id_offset = input.getLastOffset(); |
1788 | 104k | auto toffset = readToken(input); |
1789 | 104k | if (!(tnum.isInteger() && toffset.isInteger())) { |
1790 | 176 | throw damaged(0, input.getLastOffset(), "expected integer in object stream header"); |
1791 | 176 | } |
1792 | | |
1793 | 104k | int num = QUtil::string_to_int(tnum.getValue().c_str()); |
1794 | 104k | long long offset = QUtil::string_to_int(toffset.getValue().c_str()); |
1795 | | |
1796 | 104k | if (num == obj_stream_number) { |
1797 | 674 | warn(damaged(num, id_offset, "object stream claims to contain itself")); |
1798 | 674 | continue; |
1799 | 674 | } |
1800 | | |
1801 | 103k | if (num < 1) { |
1802 | 1.12k | warn(damaged(num, id_offset, "object id is invalid"s)); |
1803 | 1.12k | continue; |
1804 | 1.12k | } |
1805 | | |
1806 | 102k | if (offset <= last_offset) { |
1807 | 7.42k | warn(damaged( |
1808 | 7.42k | num, |
1809 | 7.42k | input.getLastOffset(), |
1810 | 7.42k | "offset " + std::to_string(offset) + |
1811 | 7.42k | " is invalid (must be larger than previous offset " + |
1812 | 7.42k | std::to_string(last_offset) + ")")); |
1813 | 7.42k | continue; |
1814 | 7.42k | } |
1815 | | |
1816 | 95.1k | if (num > m->xref_table_max_id) { |
1817 | 2.49k | continue; |
1818 | 2.49k | } |
1819 | | |
1820 | 92.6k | if (first + offset >= end_offset) { |
1821 | 10.9k | warn(damaged( |
1822 | 10.9k | num, input.getLastOffset(), "offset " + std::to_string(offset) + " is too large")); |
1823 | 10.9k | continue; |
1824 | 10.9k | } |
1825 | | |
1826 | 81.6k | if (is_first) { |
1827 | 1.58k | is_first = false; |
1828 | 80.0k | } else { |
1829 | 80.0k | offsets.emplace_back( |
1830 | 80.0k | id, last_offset + first, static_cast<size_t>(offset - last_offset)); |
1831 | 80.0k | } |
1832 | | |
1833 | 81.6k | last_offset = offset; |
1834 | 81.6k | id = num; |
1835 | 81.6k | } |
1836 | | |
1837 | 5.60k | if (!is_first) { |
1838 | | // We found at least one valid entry. |
1839 | 1.36k | offsets.emplace_back( |
1840 | 1.36k | id, last_offset + first, b_size - static_cast<size_t>(last_offset + first)); |
1841 | 1.36k | } |
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 | 72.1k | for (auto const& [obj_id, obj_offset, obj_size]: offsets) { |
1848 | 72.1k | QPDFObjGen og(obj_id, 0); |
1849 | 72.1k | auto entry = m->xref_table.find(og); |
1850 | 72.1k | if (entry != m->xref_table.end() && entry->second.getType() == 2 && |
1851 | 68.0k | entry->second.getObjStreamNumber() == obj_stream_number) { |
1852 | 67.6k | is::OffsetBuffer in("", {b_start + obj_offset, obj_size}, obj_offset); |
1853 | 67.6k | if (auto oh = Parser::parse(in, obj_stream_number, obj_id, m->tokenizer, qpdf)) { |
1854 | 62.4k | updateCache(og, oh.obj_sp(), end_before_space, end_after_space); |
1855 | 62.4k | } |
1856 | 67.6k | } else { |
1857 | 4.44k | QTC::TC("qpdf", "QPDF not caching overridden objstm object"); |
1858 | 4.44k | } |
1859 | 72.1k | } |
1860 | 5.60k | } |
1861 | | |
1862 | | QPDFObjectHandle |
1863 | | Objects::newIndirect(QPDFObjGen og, std::shared_ptr<QPDFObject> const& obj) |
1864 | 4.50k | { |
1865 | 4.50k | obj->setDefaultDescription(&qpdf, og); |
1866 | 4.50k | return {obj}; |
1867 | 4.50k | } |
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 | 595k | { |
1877 | 595k | object->setObjGen(&qpdf, og); |
1878 | 595k | if (isCached(og)) { |
1879 | 343k | auto& cache = m->obj_cache[og]; |
1880 | 343k | object->move_to(cache.object, destroy); |
1881 | 343k | cache.end_before_space = end_before_space; |
1882 | 343k | cache.end_after_space = end_after_space; |
1883 | 343k | } else { |
1884 | 252k | m->obj_cache[og] = ObjCache(object, end_before_space, end_after_space); |
1885 | 252k | } |
1886 | 595k | } |
1887 | | |
1888 | | bool |
1889 | | Objects::isCached(QPDFObjGen og) |
1890 | 2.09M | { |
1891 | 2.09M | return m->obj_cache.contains(og); |
1892 | 2.09M | } |
1893 | | |
1894 | | bool |
1895 | | Objects::isUnresolved(QPDFObjGen og) |
1896 | 1.50M | { |
1897 | 1.50M | return !isCached(og) || m->obj_cache[og].object->isUnresolved(); |
1898 | 1.50M | } |
1899 | | |
1900 | | QPDFObjGen |
1901 | | Objects::nextObjGen() |
1902 | 4.50k | { |
1903 | 4.50k | int max_objid = toI(qpdf.getObjectCount()); |
1904 | 4.50k | 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 | 4.50k | return {max_objid + 1, 0}; |
1908 | 4.50k | } |
1909 | | |
1910 | | QPDFObjectHandle |
1911 | | Objects::makeIndirectFromQPDFObject(std::shared_ptr<QPDFObject> const& obj) |
1912 | 4.50k | { |
1913 | 4.50k | QPDFObjGen next{nextObjGen()}; |
1914 | 4.50k | m->obj_cache[next] = ObjCache(obj, -1, -1); |
1915 | 4.50k | return newIndirect(next, m->obj_cache[next].object); |
1916 | 4.50k | } |
1917 | | |
1918 | | QPDFObjectHandle |
1919 | | QPDF::makeIndirectObject(QPDFObjectHandle oh) |
1920 | 4.50k | { |
1921 | 4.50k | if (!oh) { |
1922 | 0 | throw std::logic_error("attempted to make an uninitialized QPDFObjectHandle indirect"); |
1923 | 0 | } |
1924 | 4.50k | return m->objects.makeIndirectFromQPDFObject(oh.obj_sp()); |
1925 | 4.50k | } |
1926 | | |
1927 | | std::shared_ptr<QPDFObject> |
1928 | | Objects::getObjectForParser(int id, int gen, bool parse_pdf) |
1929 | 614k | { |
1930 | | // This method is called by the parser and therefore must not resolve any objects. |
1931 | 614k | auto og = QPDFObjGen(id, gen); |
1932 | 614k | if (auto iter = m->obj_cache.find(og); iter != m->obj_cache.end()) { |
1933 | 306k | return iter->second.object; |
1934 | 306k | } |
1935 | 308k | if (m->xref_table.contains(og) || (!m->parsed && og.getObj() < m->xref_table_max_id)) { |
1936 | 280k | return m->obj_cache.insert({og, QPDFObject::create<QPDF_Unresolved>(&qpdf, og)}) |
1937 | 280k | .first->second.object; |
1938 | 280k | } |
1939 | 27.8k | if (parse_pdf) { |
1940 | 27.8k | return QPDFObject::create<QPDF_Null>(); |
1941 | 27.8k | } |
1942 | 0 | return m->obj_cache.insert({og, QPDFObject::create<QPDF_Null>(&qpdf, og)}).first->second.object; |
1943 | 27.8k | } |
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 | 340k | { |
1962 | 340k | if (auto it = m->obj_cache.find(og); it != m->obj_cache.end()) { |
1963 | 255k | return {it->second.object}; |
1964 | 255k | } else if (m->parsed && !m->xref_table.contains(og)) { |
1965 | 11.1k | return QPDFObject::create<QPDF_Null>(); |
1966 | 74.7k | } else { |
1967 | 74.7k | auto result = |
1968 | 74.7k | m->obj_cache.try_emplace(og, QPDFObject::create<QPDF_Unresolved>(this, og), -1, -1); |
1969 | 74.7k | return {result.first->second.object}; |
1970 | 74.7k | } |
1971 | 340k | } |
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 | 4.53k | { |
1991 | 4.53k | m->xref_table.erase(og); |
1992 | 4.53k | 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 | 1.58k | cached->second.object->assign_null(); |
1995 | 1.58k | cached->second.object->setObjGen(nullptr, QPDFObjGen()); |
1996 | 1.58k | m->obj_cache.erase(cached); |
1997 | 1.58k | } |
1998 | 4.53k | } |
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 | 8.36k | { |
2029 | | // If obj_cache is dense, accommodate all object in tables,else accommodate only original |
2030 | | // objects. |
2031 | 8.36k | auto max_xref = !m->xref_table.empty() ? m->xref_table.crbegin()->first.getObj() : 0; |
2032 | 8.36k | auto max_obj = !m->obj_cache.empty() ? m->obj_cache.crbegin()->first.getObj() : 0; |
2033 | 8.36k | auto max_id = std::numeric_limits<int>::max() - 1; |
2034 | 8.36k | 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 | 8.36k | if (max_obj < 1.1 * std::max(toI(m->obj_cache.size()), max_xref)) { |
2041 | 6.67k | return toS(++max_obj); |
2042 | 6.67k | } |
2043 | 1.68k | return toS(++max_xref); |
2044 | 8.36k | } |
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 | 1.12k | { |
2055 | 1.12k | return compressible<bool>(); |
2056 | 1.12k | } |
2057 | | |
2058 | | template <typename T> |
2059 | | std::vector<T> |
2060 | | Objects::compressible() |
2061 | 1.12k | { |
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 | 1.12k | QPDFObjectHandle encryption_dict = m->trailer.getKey("/Encrypt"); |
2070 | 1.12k | QPDFObjGen encryption_dict_og = encryption_dict.getObjGen(); |
2071 | | |
2072 | 1.12k | const size_t max_obj = qpdf.getObjectCount(); |
2073 | 1.12k | std::vector<bool> visited(max_obj, false); |
2074 | 1.12k | std::vector<QPDFObjectHandle> queue; |
2075 | 1.12k | queue.reserve(512); |
2076 | 1.12k | queue.emplace_back(m->trailer); |
2077 | 1.12k | std::vector<T> result; |
2078 | 1.12k | if constexpr (std::is_same_v<T, QPDFObjGen>) { |
2079 | 0 | result.reserve(m->obj_cache.size()); |
2080 | 1.12k | } else { |
2081 | 1.12k | qpdf_static_expect(std::is_same_v<T, bool>); |
2082 | 1.12k | result.resize(max_obj + 1U, false); |
2083 | 1.12k | } |
2084 | 542k | while (!queue.empty()) { |
2085 | 541k | auto obj = queue.back(); |
2086 | 541k | queue.pop_back(); |
2087 | 541k | if (obj.getObjectID() > 0) { |
2088 | 154k | QPDFObjGen og = obj.getObjGen(); |
2089 | 154k | const size_t id = toS(og.getObj() - 1); |
2090 | 154k | if (id >= max_obj) { |
2091 | 0 | throw std::logic_error( |
2092 | 0 | "unexpected object id encountered in getCompressibleObjGens"); |
2093 | 0 | } |
2094 | 154k | if (visited[id]) { |
2095 | 60.7k | continue; |
2096 | 60.7k | } |
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 | 93.5k | auto upper = m->obj_cache.upper_bound(og); |
2102 | 93.5k | if (upper != m->obj_cache.end() && upper->first.getObj() == og.getObj()) { |
2103 | 1.12k | qpdf.removeObject(og); |
2104 | 1.12k | continue; |
2105 | 1.12k | } |
2106 | | |
2107 | 92.3k | visited[id] = true; |
2108 | | |
2109 | 92.3k | if (og == encryption_dict_og) { |
2110 | 114 | QTC::TC("qpdf", "QPDF exclude encryption dictionary"); |
2111 | 92.2k | } else if (!(obj.isStream() || |
2112 | 88.2k | (obj.isDictionaryOfType("/Sig") && obj.hasKey("/ByteRange") && |
2113 | 88.2k | obj.hasKey("/Contents")))) { |
2114 | 88.2k | if constexpr (std::is_same_v<T, QPDFObjGen>) { |
2115 | 0 | result.push_back(og); |
2116 | 88.2k | } else if constexpr (std::is_same_v<T, bool>) { |
2117 | 88.2k | result[id + 1U] = true; |
2118 | 88.2k | } |
2119 | 88.2k | } |
2120 | 92.3k | } |
2121 | 479k | if (obj.isStream()) { |
2122 | 3.98k | auto dict = obj.getDict().as_dictionary(); |
2123 | 3.98k | auto end = dict.crend(); |
2124 | 31.0k | for (auto iter = dict.crbegin(); iter != end; ++iter) { |
2125 | 27.0k | std::string const& key = iter->first; |
2126 | 27.0k | QPDFObjectHandle const& value = iter->second; |
2127 | 27.0k | if (!value.null()) { |
2128 | 23.5k | if (key == "/Length") { |
2129 | | // omit stream lengths |
2130 | 3.44k | if (value.isIndirect()) { |
2131 | 137 | QTC::TC("qpdf", "QPDF exclude indirect length"); |
2132 | 137 | } |
2133 | 20.0k | } else { |
2134 | 20.0k | queue.emplace_back(value); |
2135 | 20.0k | } |
2136 | 23.5k | } |
2137 | 27.0k | } |
2138 | 475k | } else if (obj.isDictionary()) { |
2139 | 53.8k | auto dict = obj.as_dictionary(); |
2140 | 53.8k | auto end = dict.crend(); |
2141 | 266k | for (auto iter = dict.crbegin(); iter != end; ++iter) { |
2142 | 213k | if (!iter->second.null()) { |
2143 | 178k | queue.emplace_back(iter->second); |
2144 | 178k | } |
2145 | 213k | } |
2146 | 421k | } else if (auto items = obj.as_array()) { |
2147 | 421k | queue.insert(queue.end(), items.crbegin(), items.crend()); |
2148 | 421k | } |
2149 | 479k | } |
2150 | | |
2151 | 1.12k | return result; |
2152 | 1.12k | } 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 | 1.12k | { | 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 | 1.12k | QPDFObjectHandle encryption_dict = m->trailer.getKey("/Encrypt"); | 2070 | 1.12k | QPDFObjGen encryption_dict_og = encryption_dict.getObjGen(); | 2071 | | | 2072 | 1.12k | const size_t max_obj = qpdf.getObjectCount(); | 2073 | 1.12k | std::vector<bool> visited(max_obj, false); | 2074 | 1.12k | std::vector<QPDFObjectHandle> queue; | 2075 | 1.12k | queue.reserve(512); | 2076 | 1.12k | queue.emplace_back(m->trailer); | 2077 | 1.12k | std::vector<T> result; | 2078 | | if constexpr (std::is_same_v<T, QPDFObjGen>) { | 2079 | | result.reserve(m->obj_cache.size()); | 2080 | 1.12k | } else { | 2081 | 1.12k | qpdf_static_expect(std::is_same_v<T, bool>); | 2082 | 1.12k | result.resize(max_obj + 1U, false); | 2083 | 1.12k | } | 2084 | 542k | while (!queue.empty()) { | 2085 | 541k | auto obj = queue.back(); | 2086 | 541k | queue.pop_back(); | 2087 | 541k | if (obj.getObjectID() > 0) { | 2088 | 154k | QPDFObjGen og = obj.getObjGen(); | 2089 | 154k | const size_t id = toS(og.getObj() - 1); | 2090 | 154k | if (id >= max_obj) { | 2091 | 0 | throw std::logic_error( | 2092 | 0 | "unexpected object id encountered in getCompressibleObjGens"); | 2093 | 0 | } | 2094 | 154k | if (visited[id]) { | 2095 | 60.7k | continue; | 2096 | 60.7k | } | 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 | 93.5k | auto upper = m->obj_cache.upper_bound(og); | 2102 | 93.5k | if (upper != m->obj_cache.end() && upper->first.getObj() == og.getObj()) { | 2103 | 1.12k | qpdf.removeObject(og); | 2104 | 1.12k | continue; | 2105 | 1.12k | } | 2106 | | | 2107 | 92.3k | visited[id] = true; | 2108 | | | 2109 | 92.3k | if (og == encryption_dict_og) { | 2110 | 114 | QTC::TC("qpdf", "QPDF exclude encryption dictionary"); | 2111 | 92.2k | } else if (!(obj.isStream() || | 2112 | 88.2k | (obj.isDictionaryOfType("/Sig") && obj.hasKey("/ByteRange") && | 2113 | 88.2k | obj.hasKey("/Contents")))) { | 2114 | | if constexpr (std::is_same_v<T, QPDFObjGen>) { | 2115 | | result.push_back(og); | 2116 | 88.2k | } else if constexpr (std::is_same_v<T, bool>) { | 2117 | 88.2k | result[id + 1U] = true; | 2118 | 88.2k | } | 2119 | 88.2k | } | 2120 | 92.3k | } | 2121 | 479k | if (obj.isStream()) { | 2122 | 3.98k | auto dict = obj.getDict().as_dictionary(); | 2123 | 3.98k | auto end = dict.crend(); | 2124 | 31.0k | for (auto iter = dict.crbegin(); iter != end; ++iter) { | 2125 | 27.0k | std::string const& key = iter->first; | 2126 | 27.0k | QPDFObjectHandle const& value = iter->second; | 2127 | 27.0k | if (!value.null()) { | 2128 | 23.5k | if (key == "/Length") { | 2129 | | // omit stream lengths | 2130 | 3.44k | if (value.isIndirect()) { | 2131 | 137 | QTC::TC("qpdf", "QPDF exclude indirect length"); | 2132 | 137 | } | 2133 | 20.0k | } else { | 2134 | 20.0k | queue.emplace_back(value); | 2135 | 20.0k | } | 2136 | 23.5k | } | 2137 | 27.0k | } | 2138 | 475k | } else if (obj.isDictionary()) { | 2139 | 53.8k | auto dict = obj.as_dictionary(); | 2140 | 53.8k | auto end = dict.crend(); | 2141 | 266k | for (auto iter = dict.crbegin(); iter != end; ++iter) { | 2142 | 213k | if (!iter->second.null()) { | 2143 | 178k | queue.emplace_back(iter->second); | 2144 | 178k | } | 2145 | 213k | } | 2146 | 421k | } else if (auto items = obj.as_array()) { | 2147 | 421k | queue.insert(queue.end(), items.crbegin(), items.crend()); | 2148 | 421k | } | 2149 | 479k | } | 2150 | | | 2151 | 1.12k | return result; | 2152 | 1.12k | } |
|