DocumentParser.cpp 32 KB

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