DocumentParser.cpp 32 KB

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