DocumentParser.cpp 34 KB

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