DocumentParser.cpp 35 KB

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