DocumentParser.cpp 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886
  1. /*
  2. * Copyright (c) 2021-2022, Matthew Olsson <mattco@serenityos.org>
  3. * Copyright (c) 2022, Julian Offenhäuser <offenhaeuser@protonmail.com>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <AK/BitStream.h>
  8. #include <AK/Endian.h>
  9. #include <AK/MemoryStream.h>
  10. #include <LibPDF/CommonNames.h>
  11. #include <LibPDF/Document.h>
  12. #include <LibPDF/DocumentParser.h>
  13. #include <LibPDF/ObjectDerivatives.h>
  14. namespace PDF {
  15. DocumentParser::DocumentParser(Document* document, ReadonlyBytes bytes)
  16. : Parser(document, bytes)
  17. {
  18. }
  19. PDFErrorOr<Version> DocumentParser::initialize()
  20. {
  21. m_reader.set_reading_forwards();
  22. if (m_reader.remaining() == 0)
  23. return error("Empty PDF document");
  24. auto maybe_version = parse_header();
  25. if (maybe_version.is_error()) {
  26. warnln("{}", maybe_version.error().message());
  27. warnln("No valid PDF header detected, continuing anyway.");
  28. maybe_version = Version { 1, 6 }; // ¯\_(ツ)_/¯
  29. }
  30. auto const linearization_result = TRY(initialize_linearization_dict());
  31. if (linearization_result == LinearizationResult::NotLinearized) {
  32. TRY(initialize_non_linearized_xref_table());
  33. return maybe_version.value();
  34. }
  35. bool is_linearized = m_linearization_dictionary.has_value();
  36. if (is_linearized) {
  37. // If the length given in the linearization dictionary is not equal to the length
  38. // of the document, then this file has most likely been incrementally updated, and
  39. // should no longer be treated as linearized.
  40. // FIXME: This check requires knowing the full size of the file, while linearization
  41. // is all about being able to render some of it without having to download all of it.
  42. // PDF 2.0 Annex G.7 "Accessing an updated file" talks about this some,
  43. // but mostly just throws its hand in the air.
  44. is_linearized = m_linearization_dictionary.value().length_of_file == m_reader.bytes().size();
  45. }
  46. if (is_linearized)
  47. TRY(initialize_linearized_xref_table());
  48. else
  49. TRY(initialize_non_linearized_xref_table());
  50. return maybe_version.value();
  51. }
  52. PDFErrorOr<Value> DocumentParser::parse_object_with_index(u32 index)
  53. {
  54. VERIFY(m_xref_table->has_object(index));
  55. // PDF spec 1.7, Indirect Objects:
  56. // "An indirect reference to an undefined object is not an error; it is simply treated as a reference to the null object."
  57. // FIXME: Should this apply to the !has_object() case right above too?
  58. if (!m_xref_table->is_object_in_use(index))
  59. return nullptr;
  60. // If this is called to resolve an indirect object reference while parsing another object,
  61. // make sure to restore the current position after parsing the indirect object, so that the
  62. // parser can keep parsing the original object stream afterwards.
  63. // parse_compressed_object_with_index() also moves the reader's position, so this needs
  64. // to be before the potential call to parse_compressed_object_with_index().
  65. class SavePoint {
  66. public:
  67. SavePoint(Reader& reader)
  68. : m_reader(reader)
  69. {
  70. m_reader.save();
  71. }
  72. ~SavePoint() { m_reader.load(); }
  73. private:
  74. Reader& m_reader;
  75. };
  76. SavePoint restore_current_position { m_reader };
  77. if (m_xref_table->is_object_compressed(index))
  78. // The object can be found in a object stream
  79. return parse_compressed_object_with_index(index);
  80. auto byte_offset = m_xref_table->byte_offset_for_object(index);
  81. m_reader.move_to(byte_offset);
  82. auto indirect_value = TRY(parse_indirect_value());
  83. VERIFY(indirect_value->index() == index);
  84. return indirect_value->value();
  85. }
  86. PDFErrorOr<size_t> DocumentParser::scan_for_header_start(ReadonlyBytes bytes)
  87. {
  88. // PDF 1.7 spec, APPENDIX H, 3.4.1 "File Header":
  89. // "13. Acrobat viewers require only that the header appear somewhere within the first 1024 bytes of the file."
  90. // ...which of course means files depend on it.
  91. // All offsets in the file are relative to the header start, not to the start of the file.
  92. StringView first_bytes { bytes.data(), min(bytes.size(), 1024 - "1.4"sv.length()) };
  93. Optional<size_t> start_offset = first_bytes.find("%PDF-"sv);
  94. if (!start_offset.has_value())
  95. return Error { Error::Type::Parse, "Failed to find PDF start" };
  96. return start_offset.value();
  97. }
  98. PDFErrorOr<Version> DocumentParser::parse_header()
  99. {
  100. m_reader.move_to(0);
  101. if (m_reader.remaining() < 8 || !m_reader.matches("%PDF-"))
  102. return error("Not a PDF document");
  103. m_reader.move_by(5);
  104. char major_ver = m_reader.read();
  105. if (major_ver != '1' && major_ver != '2') {
  106. dbgln_if(PDF_DEBUG, "Unknown major version \"{}\"", major_ver);
  107. return error("Unknown major version");
  108. }
  109. if (m_reader.read() != '.')
  110. return error("Malformed PDF version");
  111. char minor_ver = m_reader.read();
  112. if (minor_ver < '0' || minor_ver > '7') {
  113. dbgln_if(PDF_DEBUG, "Unknown minor version \"{}\"", minor_ver);
  114. return error("Unknown minor version");
  115. }
  116. m_reader.consume_eol();
  117. m_reader.consume_whitespace();
  118. // Parse optional high-byte comment, which signifies a binary file
  119. // FIXME: Do something with this?
  120. auto comment = parse_comment();
  121. if (!comment.is_empty()) {
  122. auto binary = comment.length() >= 4;
  123. if (binary) {
  124. for (size_t i = 0; i < comment.length() && binary; i++)
  125. binary = static_cast<u8>(comment[i]) > 128;
  126. }
  127. }
  128. return Version { major_ver - '0', minor_ver - '0' };
  129. }
  130. PDFErrorOr<DocumentParser::LinearizationResult> DocumentParser::initialize_linearization_dict()
  131. {
  132. // parse_header() is called immediately before this, so we are at the right location.
  133. // There may not actually be a linearization dict, or even a valid PDF object here.
  134. // If that is the case, this file may be completely valid but not linearized.
  135. // If there is indeed a linearization dict, there should be an object number here.
  136. if (!m_reader.matches_number())
  137. return LinearizationResult::NotLinearized;
  138. // At this point, we still don't know for sure if we are dealing with a valid object.
  139. // The linearization dict is read before decryption state is initialized.
  140. // A linearization dict only contains numbers, so the decryption dictionary is not been needed (only strings and streams get decrypted, and only streams get unfiltered).
  141. // But we don't know if the first object is a linearization dictionary until after parsing it, so the object might be a stream.
  142. // If that stream is encrypted and filtered, we'd try to unfilter it while it's still encrypted, handing encrypted data to the unfiltering algorithms.
  143. // This makes them assert, since they can't make sense of the encrypted data.
  144. // So read the first object without unfiltering.
  145. // If it is a linearization dict, there's no stream data and this has no effect.
  146. // If it is a stream, this isn't a linearized file and the object will be read on demand (and unfiltered) later, when the object is lazily read via an xref entry.
  147. set_filters_enabled(false);
  148. auto indirect_value_or_error = parse_indirect_value();
  149. set_filters_enabled(true);
  150. if (indirect_value_or_error.is_error())
  151. return LinearizationResult::NotLinearized;
  152. auto dict_value = indirect_value_or_error.value()->value();
  153. if (!dict_value.has<NonnullRefPtr<Object>>())
  154. return error("Expected linearization object to be a dictionary");
  155. auto dict_object = dict_value.get<NonnullRefPtr<Object>>();
  156. if (!dict_object->is<DictObject>())
  157. return LinearizationResult::NotLinearized;
  158. auto dict = dict_object->cast<DictObject>();
  159. if (!dict->contains(CommonNames::Linearized))
  160. return LinearizationResult::NotLinearized;
  161. if (!dict->contains(CommonNames::L, CommonNames::H, CommonNames::O, CommonNames::E, CommonNames::N, CommonNames::T))
  162. return error("Malformed linearization dictionary");
  163. auto length_of_file = dict->get_value(CommonNames::L);
  164. auto hint_table = dict->get_value(CommonNames::H);
  165. auto first_page_object_number = dict->get_value(CommonNames::O);
  166. auto offset_of_first_page_end = dict->get_value(CommonNames::E);
  167. auto number_of_pages = dict->get_value(CommonNames::N);
  168. auto offset_of_main_xref_table = dict->get_value(CommonNames::T);
  169. auto first_page = dict->get(CommonNames::P).value_or({});
  170. // Validation
  171. if (!length_of_file.has_u32()
  172. || !hint_table.has<NonnullRefPtr<Object>>()
  173. || !first_page_object_number.has_u32()
  174. || !number_of_pages.has_u16()
  175. || !offset_of_main_xref_table.has_u32()
  176. || (!first_page.has<Empty>() && !first_page.has_u32())) {
  177. return error("Malformed linearization dictionary parameters");
  178. }
  179. auto hint_table_array = hint_table.get<NonnullRefPtr<Object>>()->cast<ArrayObject>();
  180. auto hint_table_size = hint_table_array->size();
  181. if (hint_table_size != 2 && hint_table_size != 4)
  182. return error("Expected hint table to be of length 2 or 4");
  183. auto primary_hint_stream_offset = hint_table_array->at(0);
  184. auto primary_hint_stream_length = hint_table_array->at(1);
  185. Value overflow_hint_stream_offset;
  186. Value overflow_hint_stream_length;
  187. if (hint_table_size == 4) {
  188. overflow_hint_stream_offset = hint_table_array->at(2);
  189. overflow_hint_stream_length = hint_table_array->at(3);
  190. }
  191. if (!primary_hint_stream_offset.has_u32()
  192. || !primary_hint_stream_length.has_u32()
  193. || (!overflow_hint_stream_offset.has<Empty>() && !overflow_hint_stream_offset.has_u32())
  194. || (!overflow_hint_stream_length.has<Empty>() && !overflow_hint_stream_length.has_u32())) {
  195. return error("Malformed hint stream");
  196. }
  197. m_linearization_dictionary = LinearizationDictionary {
  198. length_of_file.get_u32(),
  199. primary_hint_stream_offset.get_u32(),
  200. primary_hint_stream_length.get_u32(),
  201. overflow_hint_stream_offset.has<Empty>() ? NumericLimits<u32>::max() : overflow_hint_stream_offset.get_u32(),
  202. overflow_hint_stream_length.has<Empty>() ? NumericLimits<u32>::max() : overflow_hint_stream_length.get_u32(),
  203. first_page_object_number.get_u32(),
  204. offset_of_first_page_end.get_u32(),
  205. number_of_pages.get_u16(),
  206. offset_of_main_xref_table.get_u32(),
  207. first_page.has<Empty>() ? NumericLimits<u32>::max() : first_page.get_u32(),
  208. };
  209. return LinearizationResult::Linearized;
  210. }
  211. PDFErrorOr<void> DocumentParser::initialize_linearized_xref_table()
  212. {
  213. // The linearization parameter dictionary has just been parsed, and the xref table
  214. // comes immediately after it. We are in the correct spot.
  215. m_xref_table = TRY(parse_xref_table());
  216. // Also parse the main xref table and merge into the first-page xref table. Note
  217. // that we don't use the main xref table offset from the linearization dict because
  218. // for some reason, it specified the offset of the whitespace after the object
  219. // index start and length? So it's much easier to do it this way.
  220. auto main_xref_table_offset = m_xref_table->trailer()->get_value(CommonNames::Prev).to_int();
  221. m_reader.move_to(main_xref_table_offset);
  222. auto main_xref_table = TRY(parse_xref_table());
  223. TRY(m_xref_table->merge(move(*main_xref_table)));
  224. return validate_xref_table_and_fix_if_necessary();
  225. }
  226. PDFErrorOr<void> DocumentParser::initialize_hint_tables()
  227. {
  228. auto linearization_dict = m_linearization_dictionary.value();
  229. auto primary_offset = linearization_dict.primary_hint_stream_offset;
  230. auto overflow_offset = linearization_dict.overflow_hint_stream_offset;
  231. auto parse_hint_table = [&](size_t offset) -> RefPtr<StreamObject> {
  232. m_reader.move_to(offset);
  233. auto stream_indirect_value = parse_indirect_value();
  234. if (stream_indirect_value.is_error())
  235. return {};
  236. auto stream_value = stream_indirect_value.value()->value();
  237. if (!stream_value.has<NonnullRefPtr<Object>>())
  238. return {};
  239. auto stream_object = stream_value.get<NonnullRefPtr<Object>>();
  240. if (!stream_object->is<StreamObject>())
  241. return {};
  242. return stream_object->cast<StreamObject>();
  243. };
  244. auto primary_hint_stream = parse_hint_table(primary_offset);
  245. if (!primary_hint_stream)
  246. return error("Invalid primary hint stream");
  247. RefPtr<StreamObject> overflow_hint_stream;
  248. if (overflow_offset != NumericLimits<u32>::max())
  249. overflow_hint_stream = parse_hint_table(overflow_offset);
  250. ByteBuffer possible_merged_stream_buffer;
  251. ReadonlyBytes hint_stream_bytes;
  252. if (overflow_hint_stream) {
  253. auto primary_size = primary_hint_stream->bytes().size();
  254. auto overflow_size = overflow_hint_stream->bytes().size();
  255. auto total_size = primary_size + overflow_size;
  256. auto buffer_result = ByteBuffer::create_uninitialized(total_size);
  257. if (buffer_result.is_error())
  258. return Error { Error::Type::Internal, "Failed to allocate hint stream buffer" };
  259. possible_merged_stream_buffer = buffer_result.release_value();
  260. MUST(possible_merged_stream_buffer.try_append(primary_hint_stream->bytes()));
  261. MUST(possible_merged_stream_buffer.try_append(overflow_hint_stream->bytes()));
  262. hint_stream_bytes = possible_merged_stream_buffer.bytes();
  263. } else {
  264. hint_stream_bytes = primary_hint_stream->bytes();
  265. }
  266. auto hint_table = TRY(parse_page_offset_hint_table(hint_stream_bytes));
  267. auto hint_table_entries = TRY(parse_all_page_offset_hint_table_entries(hint_table, hint_stream_bytes));
  268. // FIXME: Do something with the hint tables
  269. return {};
  270. }
  271. PDFErrorOr<void> DocumentParser::initialize_non_linearized_xref_table()
  272. {
  273. m_reader.move_to(m_reader.bytes().size() - 1);
  274. if (!navigate_to_before_eof_marker())
  275. return error("No EOF marker");
  276. if (!navigate_to_after_startxref())
  277. return error("No xref");
  278. m_reader.set_reading_forwards();
  279. auto xref_offset_value = TRY(parse_number());
  280. auto xref_offset = TRY(m_document->resolve_to<int>(xref_offset_value));
  281. m_reader.move_to(xref_offset);
  282. // As per 7.5.6 Incremental Updates:
  283. // When a conforming reader reads the file, it shall build its cross-reference
  284. // information in such a way that the most recent copy of each object shall be
  285. // the one accessed from the file.
  286. // NOTE: This means that we have to follow back the chain of XRef table sections
  287. // and only add objects that were not already specified in a previous
  288. // (and thus newer) XRef section.
  289. while (1) {
  290. auto xref_table = TRY(parse_xref_table());
  291. if (!m_xref_table)
  292. m_xref_table = xref_table;
  293. else
  294. TRY(m_xref_table->merge(move(*xref_table)));
  295. if (!xref_table->trailer() || !xref_table->trailer()->contains(CommonNames::Prev))
  296. break;
  297. auto offset = TRY(m_document->resolve_to<int>(xref_table->trailer()->get_value(CommonNames::Prev)));
  298. m_reader.move_to(offset);
  299. }
  300. return validate_xref_table_and_fix_if_necessary();
  301. }
  302. PDFErrorOr<void> DocumentParser::validate_xref_table_and_fix_if_necessary()
  303. {
  304. /* While an xref table may start with an object number other than zero, this is
  305. very uncommon and likely a sign of a document with broken indices.
  306. Like most other PDF parsers seem to do, we still try to salvage the situation.
  307. NOTE: This is probably not spec-compliant behavior.*/
  308. size_t first_valid_index = 0;
  309. while (m_xref_table->byte_offset_for_object(first_valid_index) == invalid_byte_offset)
  310. first_valid_index++;
  311. if (first_valid_index) {
  312. auto& entries = m_xref_table->entries();
  313. bool need_to_rebuild_table = true;
  314. for (size_t i = first_valid_index; i < entries.size(); ++i) {
  315. if (!entries[i].in_use)
  316. continue;
  317. size_t actual_object_number = 0;
  318. if (entries[i].compressed) {
  319. auto object_stream_index = m_xref_table->object_stream_for_object(i);
  320. auto stream_offset = m_xref_table->byte_offset_for_object(object_stream_index);
  321. m_reader.move_to(stream_offset);
  322. auto first_number = TRY(parse_number());
  323. actual_object_number = first_number.get_u32();
  324. } else {
  325. auto byte_offset = m_xref_table->byte_offset_for_object(i);
  326. m_reader.move_to(byte_offset);
  327. auto indirect_value = TRY(parse_indirect_value());
  328. actual_object_number = indirect_value->index();
  329. }
  330. if (actual_object_number != i - first_valid_index) {
  331. /* Our suspicion was wrong, not all object numbers are shifted equally.
  332. This could mean that the document is hopelessly broken, or it just
  333. starts at a non-zero object index for some reason. */
  334. need_to_rebuild_table = false;
  335. break;
  336. }
  337. }
  338. if (need_to_rebuild_table) {
  339. warnln("Broken xref table detected, trying to fix it.");
  340. entries.remove(0, first_valid_index);
  341. }
  342. }
  343. return {};
  344. }
  345. static PDFErrorOr<NonnullRefPtr<StreamObject>> indirect_value_as_stream(NonnullRefPtr<IndirectValue> indirect_value)
  346. {
  347. auto value = indirect_value->value();
  348. if (!value.has<NonnullRefPtr<Object>>())
  349. return Error { Error::Type::Parse, "Expected indirect value to be a stream" };
  350. auto value_object = value.get<NonnullRefPtr<Object>>();
  351. if (!value_object->is<StreamObject>())
  352. return Error { Error::Type::Parse, "Expected indirect value to be a stream" };
  353. return value_object->cast<StreamObject>();
  354. }
  355. PDFErrorOr<NonnullRefPtr<XRefTable>> DocumentParser::parse_xref_stream()
  356. {
  357. auto xref_stream = TRY(parse_indirect_value());
  358. auto stream = TRY(indirect_value_as_stream(xref_stream));
  359. auto dict = stream->dict();
  360. auto type = TRY(dict->get_name(m_document, CommonNames::Type))->name();
  361. if (type != "XRef")
  362. return error("Malformed xref dictionary");
  363. auto field_sizes = TRY(dict->get_array(m_document, "W"));
  364. if (field_sizes->size() != 3)
  365. return error("Malformed xref dictionary");
  366. if (field_sizes->at(1).get_u32() == 0)
  367. return error("Malformed xref dictionary");
  368. auto number_of_object_entries = dict->get_value("Size").get<int>();
  369. struct Subsection {
  370. int start;
  371. int count;
  372. };
  373. Vector<Subsection> subsections;
  374. if (dict->contains(CommonNames::Index)) {
  375. auto index_array = TRY(dict->get_array(m_document, CommonNames::Index));
  376. if (index_array->size() % 2 != 0)
  377. return error("Malformed xref dictionary");
  378. for (size_t i = 0; i < index_array->size(); i += 2)
  379. subsections.append({ index_array->at(i).get<int>(), index_array->at(i + 1).get<int>() });
  380. } else {
  381. subsections.append({ 0, number_of_object_entries });
  382. }
  383. auto table = adopt_ref(*new XRefTable());
  384. auto field_to_long = [](ReadonlyBytes field) -> long {
  385. long value = 0;
  386. const u8 max = (field.size() - 1) * 8;
  387. for (size_t i = 0; i < field.size(); ++i) {
  388. value |= static_cast<long>(field[i]) << (max - (i * 8));
  389. }
  390. return value;
  391. };
  392. size_t byte_index = 0;
  393. for (auto [start, count] : subsections) {
  394. Vector<XRefEntry> entries;
  395. for (int i = 0; i < count; i++) {
  396. Array<long, 3> fields;
  397. for (size_t field_index = 0; field_index < 3; ++field_index) {
  398. if (!field_sizes->at(field_index).has_u32())
  399. return error("Malformed xref stream");
  400. auto field_size = field_sizes->at(field_index).get_u32();
  401. if (field_size > 8)
  402. return error("Malformed xref stream");
  403. if (byte_index + field_size > stream->bytes().size())
  404. return error("The xref stream data cut off early");
  405. auto field = stream->bytes().slice(byte_index, field_size);
  406. fields[field_index] = field_to_long(field);
  407. byte_index += field_size;
  408. }
  409. u8 type = fields[0];
  410. if (field_sizes->at(0).get_u32() == 0)
  411. type = 1;
  412. entries.append({ fields[1], static_cast<u16>(fields[2]), type != 0, type == 2 });
  413. }
  414. table->add_section({ start, count, move(entries) });
  415. }
  416. table->set_trailer(dict);
  417. return table;
  418. }
  419. PDFErrorOr<NonnullRefPtr<XRefTable>> DocumentParser::parse_xref_table()
  420. {
  421. if (!m_reader.matches("xref")) {
  422. // Since version 1.5, there may be a cross-reference stream instead
  423. return parse_xref_stream();
  424. }
  425. m_reader.move_by(4);
  426. m_reader.consume_non_eol_whitespace();
  427. if (!m_reader.consume_eol())
  428. return error("Expected newline after \"xref\"");
  429. auto table = adopt_ref(*new XRefTable());
  430. while (m_reader.matches_number()) {
  431. Vector<XRefEntry> entries;
  432. auto starting_index_value = TRY(parse_number());
  433. auto object_count_value = TRY(parse_number());
  434. if (!(starting_index_value.has_u32() && object_count_value.has_u32()))
  435. return error("Malformed xref entry");
  436. auto object_count = object_count_value.get<int>();
  437. auto starting_index = starting_index_value.get<int>();
  438. for (int i = 0; i < object_count; i++) {
  439. auto offset_string = ByteString(m_reader.bytes().slice(m_reader.offset(), 10));
  440. m_reader.move_by(10);
  441. if (!m_reader.consume(' '))
  442. return error("Malformed xref entry");
  443. auto generation_string = ByteString(m_reader.bytes().slice(m_reader.offset(), 5));
  444. m_reader.move_by(5);
  445. if (!m_reader.consume(' '))
  446. return error("Malformed xref entry");
  447. auto letter = m_reader.read();
  448. if (letter != 'n' && letter != 'f')
  449. return error("Malformed xref entry");
  450. // The line ending sequence can be one of the following:
  451. // SP CR, SP LF, or CR LF
  452. if (m_reader.matches(' ')) {
  453. m_reader.consume();
  454. auto ch = m_reader.consume();
  455. if (ch != '\r' && ch != '\n')
  456. return error("Malformed xref entry");
  457. } else {
  458. if (!m_reader.matches("\r\n"))
  459. return error("Malformed xref entry");
  460. m_reader.move_by(2);
  461. }
  462. auto offset = strtol(offset_string.characters(), nullptr, 10);
  463. auto generation = strtol(generation_string.characters(), nullptr, 10);
  464. entries.append({ offset, static_cast<u16>(generation), letter == 'n' });
  465. }
  466. table->add_section({ starting_index, object_count, entries });
  467. }
  468. m_reader.consume_whitespace();
  469. if (m_reader.matches("trailer"))
  470. table->set_trailer(TRY(parse_file_trailer()));
  471. return table;
  472. }
  473. PDFErrorOr<NonnullRefPtr<DictObject>> DocumentParser::parse_file_trailer()
  474. {
  475. while (m_reader.matches_eol())
  476. m_reader.consume_eol();
  477. if (!m_reader.matches("trailer"))
  478. return error("Expected \"trailer\" keyword");
  479. m_reader.move_by(7);
  480. m_reader.consume_whitespace();
  481. return parse_dict();
  482. }
  483. PDFErrorOr<Value> DocumentParser::parse_compressed_object_with_index(u32 index)
  484. {
  485. auto object_stream_index = m_xref_table->object_stream_for_object(index);
  486. auto stream_offset = m_xref_table->byte_offset_for_object(object_stream_index);
  487. m_reader.move_to(stream_offset);
  488. auto obj_stream = TRY(parse_indirect_value());
  489. auto stream = TRY(indirect_value_as_stream(obj_stream));
  490. if (obj_stream->index() != object_stream_index)
  491. return error("Mismatching object stream index");
  492. auto dict = stream->dict();
  493. auto type = TRY(dict->get_name(m_document, CommonNames::Type))->name();
  494. if (type != "ObjStm")
  495. return error("Invalid object stream type");
  496. auto object_count = dict->get_value("N").get_u32();
  497. auto first_object_offset = dict->get_value("First").get_u32();
  498. Parser stream_parser(m_document, stream->bytes());
  499. // The data was already decrypted when reading the outer compressed ObjStm.
  500. stream_parser.set_encryption_enabled(false);
  501. for (u32 i = 0; i < object_count; ++i) {
  502. auto object_number = TRY(stream_parser.parse_number());
  503. auto object_offset = TRY(stream_parser.parse_number());
  504. if (object_number.get_u32() == index) {
  505. stream_parser.move_to(first_object_offset + object_offset.get_u32());
  506. break;
  507. }
  508. }
  509. stream_parser.push_reference({ index, 0 });
  510. auto value = TRY(stream_parser.parse_value());
  511. stream_parser.pop_reference();
  512. return value;
  513. }
  514. PDFErrorOr<DocumentParser::PageOffsetHintTable> DocumentParser::parse_page_offset_hint_table(ReadonlyBytes hint_stream_bytes)
  515. {
  516. if (hint_stream_bytes.size() < sizeof(PageOffsetHintTable))
  517. return error("Hint stream is too small");
  518. size_t offset = 0;
  519. auto read_u32 = [&] {
  520. u32 data = reinterpret_cast<const u32*>(hint_stream_bytes.data() + offset)[0];
  521. offset += 4;
  522. return AK::convert_between_host_and_big_endian(data);
  523. };
  524. auto read_u16 = [&] {
  525. u16 data = reinterpret_cast<const u16*>(hint_stream_bytes.data() + offset)[0];
  526. offset += 2;
  527. return AK::convert_between_host_and_big_endian(data);
  528. };
  529. PageOffsetHintTable hint_table {
  530. read_u32(),
  531. read_u32(),
  532. read_u16(),
  533. read_u32(),
  534. read_u16(),
  535. read_u32(),
  536. read_u16(),
  537. read_u32(),
  538. read_u16(),
  539. read_u16(),
  540. read_u16(),
  541. read_u16(),
  542. read_u16(),
  543. };
  544. // Verify that all of the bits_required_for_xyz fields are <= 32, since all of the numeric
  545. // fields in PageOffsetHintTableEntry are u32
  546. VERIFY(hint_table.bits_required_for_object_number <= 32);
  547. VERIFY(hint_table.bits_required_for_page_length <= 32);
  548. VERIFY(hint_table.bits_required_for_content_stream_offsets <= 32);
  549. VERIFY(hint_table.bits_required_for_content_stream_length <= 32);
  550. VERIFY(hint_table.bits_required_for_number_of_shared_obj_refs <= 32);
  551. VERIFY(hint_table.bits_required_for_greatest_shared_obj_identifier <= 32);
  552. VERIFY(hint_table.bits_required_for_fraction_numerator <= 32);
  553. return hint_table;
  554. }
  555. PDFErrorOr<Vector<DocumentParser::PageOffsetHintTableEntry>> DocumentParser::parse_all_page_offset_hint_table_entries(PageOffsetHintTable const& hint_table, ReadonlyBytes hint_stream_bytes)
  556. {
  557. auto input_stream = TRY(try_make<FixedMemoryStream>(hint_stream_bytes));
  558. TRY(input_stream->seek(sizeof(PageOffsetHintTable)));
  559. LittleEndianInputBitStream bit_stream { move(input_stream) };
  560. auto number_of_pages = m_linearization_dictionary.value().number_of_pages;
  561. Vector<PageOffsetHintTableEntry> entries;
  562. for (size_t i = 0; i < number_of_pages; i++)
  563. entries.append(PageOffsetHintTableEntry {});
  564. auto bits_required_for_object_number = hint_table.bits_required_for_object_number;
  565. auto bits_required_for_page_length = hint_table.bits_required_for_page_length;
  566. auto bits_required_for_content_stream_offsets = hint_table.bits_required_for_content_stream_offsets;
  567. auto bits_required_for_content_stream_length = hint_table.bits_required_for_content_stream_length;
  568. auto bits_required_for_number_of_shared_obj_refs = hint_table.bits_required_for_number_of_shared_obj_refs;
  569. auto bits_required_for_greatest_shared_obj_identifier = hint_table.bits_required_for_greatest_shared_obj_identifier;
  570. auto bits_required_for_fraction_numerator = hint_table.bits_required_for_fraction_numerator;
  571. auto parse_int_entry = [&](u32 PageOffsetHintTableEntry::*field, u32 bit_size) -> ErrorOr<void> {
  572. if (bit_size <= 0)
  573. return {};
  574. for (int i = 0; i < number_of_pages; i++) {
  575. auto& entry = entries[i];
  576. entry.*field = TRY(bit_stream.read_bits(bit_size));
  577. }
  578. return {};
  579. };
  580. auto parse_vector_entry = [&](Vector<u32> PageOffsetHintTableEntry::*field, u32 bit_size) -> ErrorOr<void> {
  581. if (bit_size <= 0)
  582. return {};
  583. for (int page = 1; page < number_of_pages; page++) {
  584. auto number_of_shared_objects = entries[page].number_of_shared_objects;
  585. Vector<u32> items;
  586. items.ensure_capacity(number_of_shared_objects);
  587. for (size_t i = 0; i < number_of_shared_objects; i++)
  588. items.unchecked_append(TRY(bit_stream.read_bits(bit_size)));
  589. entries[page].*field = move(items);
  590. }
  591. return {};
  592. };
  593. TRY(parse_int_entry(&PageOffsetHintTableEntry::objects_in_page_number, bits_required_for_object_number));
  594. TRY(parse_int_entry(&PageOffsetHintTableEntry::page_length_number, bits_required_for_page_length));
  595. TRY(parse_int_entry(&PageOffsetHintTableEntry::number_of_shared_objects, bits_required_for_number_of_shared_obj_refs));
  596. TRY(parse_vector_entry(&PageOffsetHintTableEntry::shared_object_identifiers, bits_required_for_greatest_shared_obj_identifier));
  597. TRY(parse_vector_entry(&PageOffsetHintTableEntry::shared_object_location_numerators, bits_required_for_fraction_numerator));
  598. TRY(parse_int_entry(&PageOffsetHintTableEntry::page_content_stream_offset_number, bits_required_for_content_stream_offsets));
  599. TRY(parse_int_entry(&PageOffsetHintTableEntry::page_content_stream_length_number, bits_required_for_content_stream_length));
  600. return entries;
  601. }
  602. bool DocumentParser::navigate_to_before_eof_marker()
  603. {
  604. m_reader.set_reading_backwards();
  605. while (!m_reader.done()) {
  606. m_reader.consume_eol();
  607. m_reader.consume_whitespace();
  608. if (m_reader.matches("%%EOF")) {
  609. m_reader.move_by(5);
  610. return true;
  611. }
  612. m_reader.move_until([&](auto) { return m_reader.matches_eol(); });
  613. }
  614. return false;
  615. }
  616. bool DocumentParser::navigate_to_after_startxref()
  617. {
  618. m_reader.set_reading_backwards();
  619. while (!m_reader.done()) {
  620. m_reader.move_until([&](auto) { return m_reader.matches_eol(); });
  621. auto offset = m_reader.offset() + 1;
  622. m_reader.consume_eol();
  623. m_reader.consume_whitespace();
  624. if (!m_reader.matches("startxref"))
  625. continue;
  626. m_reader.move_by(9);
  627. if (!m_reader.matches_eol())
  628. continue;
  629. m_reader.move_to(offset);
  630. return true;
  631. }
  632. return false;
  633. }
  634. PDFErrorOr<RefPtr<DictObject>> DocumentParser::conditionally_parse_page_tree_node(u32 object_index)
  635. {
  636. auto dict_value = TRY(parse_object_with_index(object_index));
  637. auto dict_object = dict_value.get<NonnullRefPtr<Object>>();
  638. if (!dict_object->is<DictObject>())
  639. return error(ByteString::formatted("Invalid page tree with xref index {}", object_index));
  640. auto dict = dict_object->cast<DictObject>();
  641. if (!dict->contains_any_of(CommonNames::Type, CommonNames::Parent, CommonNames::Kids, CommonNames::Count))
  642. // This is a page, not a page tree node
  643. return RefPtr<DictObject> {};
  644. if (!dict->contains(CommonNames::Type))
  645. return RefPtr<DictObject> {};
  646. auto type_object = TRY(dict->get_object(m_document, CommonNames::Type));
  647. if (!type_object->is<NameObject>())
  648. return RefPtr<DictObject> {};
  649. auto type_name = type_object->cast<NameObject>();
  650. if (type_name->name() != CommonNames::Pages)
  651. return RefPtr<DictObject> {};
  652. return dict;
  653. }
  654. }
  655. namespace AK {
  656. template<>
  657. struct Formatter<PDF::DocumentParser::LinearizationDictionary> : Formatter<StringView> {
  658. ErrorOr<void> format(FormatBuilder& format_builder, PDF::DocumentParser::LinearizationDictionary const& dict)
  659. {
  660. StringBuilder builder;
  661. builder.append("{\n"sv);
  662. builder.appendff(" length_of_file={}\n", dict.length_of_file);
  663. builder.appendff(" primary_hint_stream_offset={}\n", dict.primary_hint_stream_offset);
  664. builder.appendff(" primary_hint_stream_length={}\n", dict.primary_hint_stream_length);
  665. builder.appendff(" overflow_hint_stream_offset={}\n", dict.overflow_hint_stream_offset);
  666. builder.appendff(" overflow_hint_stream_length={}\n", dict.overflow_hint_stream_length);
  667. builder.appendff(" first_page_object_number={}\n", dict.first_page_object_number);
  668. builder.appendff(" offset_of_first_page_end={}\n", dict.offset_of_first_page_end);
  669. builder.appendff(" number_of_pages={}\n", dict.number_of_pages);
  670. builder.appendff(" offset_of_main_xref_table={}\n", dict.offset_of_main_xref_table);
  671. builder.appendff(" first_page={}\n", dict.first_page);
  672. builder.append('}');
  673. return Formatter<StringView>::format(format_builder, builder.to_byte_string());
  674. }
  675. };
  676. template<>
  677. struct Formatter<PDF::DocumentParser::PageOffsetHintTable> : Formatter<StringView> {
  678. ErrorOr<void> format(FormatBuilder& format_builder, PDF::DocumentParser::PageOffsetHintTable const& table)
  679. {
  680. StringBuilder builder;
  681. builder.append("{\n"sv);
  682. builder.appendff(" least_number_of_objects_in_a_page={}\n", table.least_number_of_objects_in_a_page);
  683. builder.appendff(" location_of_first_page_object={}\n", table.location_of_first_page_object);
  684. builder.appendff(" bits_required_for_object_number={}\n", table.bits_required_for_object_number);
  685. builder.appendff(" least_length_of_a_page={}\n", table.least_length_of_a_page);
  686. builder.appendff(" bits_required_for_page_length={}\n", table.bits_required_for_page_length);
  687. builder.appendff(" least_offset_of_any_content_stream={}\n", table.least_offset_of_any_content_stream);
  688. builder.appendff(" bits_required_for_content_stream_offsets={}\n", table.bits_required_for_content_stream_offsets);
  689. builder.appendff(" least_content_stream_length={}\n", table.least_content_stream_length);
  690. builder.appendff(" bits_required_for_content_stream_length={}\n", table.bits_required_for_content_stream_length);
  691. builder.appendff(" bits_required_for_number_of_shared_obj_refs={}\n", table.bits_required_for_number_of_shared_obj_refs);
  692. builder.appendff(" bits_required_for_greatest_shared_obj_identifier={}\n", table.bits_required_for_greatest_shared_obj_identifier);
  693. builder.appendff(" bits_required_for_fraction_numerator={}\n", table.bits_required_for_fraction_numerator);
  694. builder.appendff(" shared_object_reference_fraction_denominator={}\n", table.shared_object_reference_fraction_denominator);
  695. builder.append('}');
  696. return Formatter<StringView>::format(format_builder, builder.to_byte_string());
  697. }
  698. };
  699. template<>
  700. struct Formatter<PDF::DocumentParser::PageOffsetHintTableEntry> : Formatter<StringView> {
  701. ErrorOr<void> format(FormatBuilder& format_builder, PDF::DocumentParser::PageOffsetHintTableEntry const& entry)
  702. {
  703. StringBuilder builder;
  704. builder.append("{\n"sv);
  705. builder.appendff(" objects_in_page_number={}\n", entry.objects_in_page_number);
  706. builder.appendff(" page_length_number={}\n", entry.page_length_number);
  707. builder.appendff(" number_of_shared_objects={}\n", entry.number_of_shared_objects);
  708. builder.append(" shared_object_identifiers=["sv);
  709. for (auto& identifier : entry.shared_object_identifiers)
  710. builder.appendff(" {}", identifier);
  711. builder.append(" ]\n"sv);
  712. builder.append(" shared_object_location_numerators=["sv);
  713. for (auto& numerator : entry.shared_object_location_numerators)
  714. builder.appendff(" {}", numerator);
  715. builder.append(" ]\n"sv);
  716. builder.appendff(" page_content_stream_offset_number={}\n", entry.page_content_stream_offset_number);
  717. builder.appendff(" page_content_stream_length_number={}\n", entry.page_content_stream_length_number);
  718. builder.append('}');
  719. return Formatter<StringView>::format(format_builder, builder.to_byte_string());
  720. }
  721. };
  722. }