DocumentParser.cpp 33 KB

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