DocumentParser.cpp 35 KB

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