DocumentParser.cpp 31 KB

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