DocumentParser.cpp 32 KB

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