DocumentParser.cpp 31 KB

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