DocumentParser.cpp 35 KB

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