Parser.cpp 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222
  1. /*
  2. * Copyright (c) 2021-2022, Matthew Olsson <mattco@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/BitStream.h>
  7. #include <AK/MemoryStream.h>
  8. #include <AK/ScopeGuard.h>
  9. #include <LibPDF/CommonNames.h>
  10. #include <LibPDF/Document.h>
  11. #include <LibPDF/Filter.h>
  12. #include <LibPDF/Parser.h>
  13. #include <LibTextCodec/Decoder.h>
  14. #include <ctype.h>
  15. namespace PDF {
  16. template<typename T, typename... Args>
  17. static NonnullRefPtr<T> make_object(Args... args) requires(IsBaseOf<Object, T>)
  18. {
  19. return adopt_ref(*new T(forward<Args>(args)...));
  20. }
  21. PDFErrorOr<Vector<Operator>> Parser::parse_operators(Document* document, ReadonlyBytes bytes)
  22. {
  23. auto parser = adopt_ref(*new Parser(document, bytes));
  24. parser->m_disable_encryption = true;
  25. return parser->parse_operators();
  26. }
  27. Parser::Parser(Document* document, ReadonlyBytes bytes)
  28. : m_reader(bytes)
  29. , m_document(document)
  30. {
  31. }
  32. Parser::Parser(ReadonlyBytes bytes)
  33. : m_reader(bytes)
  34. {
  35. }
  36. void Parser::set_document(WeakPtr<Document> const& document)
  37. {
  38. m_document = document;
  39. }
  40. PDFErrorOr<void> Parser::initialize()
  41. {
  42. TRY(parse_header());
  43. const auto linearization_result = TRY(initialize_linearization_dict());
  44. if (linearization_result == LinearizationResult::NotLinearized)
  45. return initialize_non_linearized_xref_table();
  46. bool is_linearized = m_linearization_dictionary.has_value();
  47. if (is_linearized) {
  48. // The file may have been linearized at one point, but could have been updated afterwards,
  49. // which means it is no longer a linearized PDF file.
  50. is_linearized = m_linearization_dictionary.value().length_of_file == m_reader.bytes().size();
  51. if (!is_linearized) {
  52. // FIXME: The file shouldn't be treated as linearized, yet the xref tables are still
  53. // split. This might take some tweaking to ensure correct behavior, which can be
  54. // implemented later.
  55. TODO();
  56. }
  57. }
  58. if (is_linearized)
  59. return initialize_linearized_xref_table();
  60. return initialize_non_linearized_xref_table();
  61. }
  62. PDFErrorOr<Value> Parser::parse_object_with_index(u32 index)
  63. {
  64. VERIFY(m_xref_table->has_object(index));
  65. auto byte_offset = m_xref_table->byte_offset_for_object(index);
  66. m_reader.move_to(byte_offset);
  67. auto indirect_value = TRY(parse_indirect_value());
  68. VERIFY(indirect_value->index() == index);
  69. return indirect_value->value();
  70. }
  71. PDFErrorOr<void> Parser::parse_header()
  72. {
  73. // FIXME: Do something with the version?
  74. m_reader.set_reading_forwards();
  75. if (m_reader.remaining() == 0)
  76. return error("Empty PDF document");
  77. m_reader.move_to(0);
  78. if (m_reader.remaining() < 8 || !m_reader.matches("%PDF-"))
  79. return error("Not a PDF document");
  80. m_reader.move_by(5);
  81. char major_ver = m_reader.read();
  82. if (major_ver != '1' && major_ver != '2')
  83. return error(String::formatted("Unknown major version \"{}\"", major_ver));
  84. if (m_reader.read() != '.')
  85. return error("Malformed PDF version");
  86. char minor_ver = m_reader.read();
  87. if (minor_ver < '0' || minor_ver > '7')
  88. return error(String::formatted("Unknown minor version \"{}\"", minor_ver));
  89. consume_eol();
  90. // Parse optional high-byte comment, which signifies a binary file
  91. // FIXME: Do something with this?
  92. auto comment = parse_comment();
  93. if (!comment.is_empty()) {
  94. auto binary = comment.length() >= 4;
  95. if (binary) {
  96. for (size_t i = 0; i < comment.length() && binary; i++)
  97. binary = static_cast<u8>(comment[i]) > 128;
  98. }
  99. }
  100. return {};
  101. }
  102. PDFErrorOr<Parser::LinearizationResult> Parser::initialize_linearization_dict()
  103. {
  104. // parse_header() is called immediately before this, so we are at the right location
  105. auto indirect_value = Value(*TRY(parse_indirect_value()));
  106. auto dict_value = TRY(m_document->resolve(indirect_value));
  107. if (!dict_value.has<NonnullRefPtr<Object>>())
  108. return error("Expected linearization object to be a dictionary");
  109. auto dict_object = dict_value.get<NonnullRefPtr<Object>>();
  110. if (!dict_object->is<DictObject>())
  111. return LinearizationResult::NotLinearized;
  112. auto dict = dict_object->cast<DictObject>();
  113. if (!dict->contains(CommonNames::Linearized))
  114. return LinearizationResult::NotLinearized;
  115. if (!dict->contains(CommonNames::L, CommonNames::H, CommonNames::O, CommonNames::E, CommonNames::N, CommonNames::T))
  116. return error("Malformed linearization dictionary");
  117. auto length_of_file = dict->get_value(CommonNames::L);
  118. auto hint_table = dict->get_value(CommonNames::H);
  119. auto first_page_object_number = dict->get_value(CommonNames::O);
  120. auto offset_of_first_page_end = dict->get_value(CommonNames::E);
  121. auto number_of_pages = dict->get_value(CommonNames::N);
  122. auto offset_of_main_xref_table = dict->get_value(CommonNames::T);
  123. auto first_page = dict->get(CommonNames::P).value_or({});
  124. // Validation
  125. if (!length_of_file.has_u32()
  126. || !hint_table.has<NonnullRefPtr<Object>>()
  127. || !first_page_object_number.has_u32()
  128. || !number_of_pages.has_u16()
  129. || !offset_of_main_xref_table.has_u32()
  130. || (!first_page.has<Empty>() && !first_page.has_u32())) {
  131. return error("Malformed linearization dictionary parameters");
  132. }
  133. auto hint_table_array = hint_table.get<NonnullRefPtr<Object>>()->cast<ArrayObject>();
  134. auto hint_table_size = hint_table_array->size();
  135. if (hint_table_size != 2 && hint_table_size != 4)
  136. return error("Expected hint table to be of length 2 or 4");
  137. auto primary_hint_stream_offset = hint_table_array->at(0);
  138. auto primary_hint_stream_length = hint_table_array->at(1);
  139. Value overflow_hint_stream_offset;
  140. Value overflow_hint_stream_length;
  141. if (hint_table_size == 4) {
  142. overflow_hint_stream_offset = hint_table_array->at(2);
  143. overflow_hint_stream_length = hint_table_array->at(3);
  144. }
  145. if (!primary_hint_stream_offset.has_u32()
  146. || !primary_hint_stream_length.has_u32()
  147. || (!overflow_hint_stream_offset.has<Empty>() && !overflow_hint_stream_offset.has_u32())
  148. || (!overflow_hint_stream_length.has<Empty>() && !overflow_hint_stream_length.has_u32())) {
  149. return error("Malformed hint stream");
  150. }
  151. m_linearization_dictionary = LinearizationDictionary {
  152. length_of_file.get_u32(),
  153. primary_hint_stream_offset.get_u32(),
  154. primary_hint_stream_length.get_u32(),
  155. overflow_hint_stream_offset.has<Empty>() ? NumericLimits<u32>::max() : overflow_hint_stream_offset.get_u32(),
  156. overflow_hint_stream_length.has<Empty>() ? NumericLimits<u32>::max() : overflow_hint_stream_length.get_u32(),
  157. first_page_object_number.get_u32(),
  158. offset_of_first_page_end.get_u32(),
  159. number_of_pages.get_u16(),
  160. offset_of_main_xref_table.get_u32(),
  161. first_page.has<Empty>() ? NumericLimits<u32>::max() : first_page.get_u32(),
  162. };
  163. return LinearizationResult::Linearized;
  164. }
  165. PDFErrorOr<void> Parser::initialize_linearized_xref_table()
  166. {
  167. // The linearization parameter dictionary has just been parsed, and the xref table
  168. // comes immediately after it. We are in the correct spot.
  169. m_xref_table = TRY(parse_xref_table());
  170. m_trailer = TRY(parse_file_trailer());
  171. // Also parse the main xref table and merge into the first-page xref table. Note
  172. // that we don't use the main xref table offset from the linearization dict because
  173. // for some reason, it specified the offset of the whitespace after the object
  174. // index start and length? So it's much easier to do it this way.
  175. auto main_xref_table_offset = m_trailer->get_value(CommonNames::Prev).to_int();
  176. m_reader.move_to(main_xref_table_offset);
  177. auto main_xref_table = TRY(parse_xref_table());
  178. TRY(m_xref_table->merge(move(*main_xref_table)));
  179. return {};
  180. }
  181. PDFErrorOr<void> Parser::initialize_hint_tables()
  182. {
  183. auto linearization_dict = m_linearization_dictionary.value();
  184. auto primary_offset = linearization_dict.primary_hint_stream_offset;
  185. auto overflow_offset = linearization_dict.overflow_hint_stream_offset;
  186. auto parse_hint_table = [&](size_t offset) -> RefPtr<StreamObject> {
  187. m_reader.move_to(offset);
  188. auto stream_indirect_value = parse_indirect_value();
  189. if (stream_indirect_value.is_error())
  190. return {};
  191. auto stream_value = stream_indirect_value.value()->value();
  192. if (!stream_value.has<NonnullRefPtr<Object>>())
  193. return {};
  194. auto stream_object = stream_value.get<NonnullRefPtr<Object>>();
  195. if (!stream_object->is<StreamObject>())
  196. return {};
  197. return stream_object->cast<StreamObject>();
  198. };
  199. auto primary_hint_stream = parse_hint_table(primary_offset);
  200. if (!primary_hint_stream)
  201. return error("Invalid primary hint stream");
  202. RefPtr<StreamObject> overflow_hint_stream;
  203. if (overflow_offset != NumericLimits<u32>::max())
  204. overflow_hint_stream = parse_hint_table(overflow_offset);
  205. ByteBuffer possible_merged_stream_buffer;
  206. ReadonlyBytes hint_stream_bytes;
  207. if (overflow_hint_stream) {
  208. auto primary_size = primary_hint_stream->bytes().size();
  209. auto overflow_size = overflow_hint_stream->bytes().size();
  210. auto total_size = primary_size + overflow_size;
  211. auto buffer_result = ByteBuffer::create_uninitialized(total_size);
  212. if (buffer_result.is_error())
  213. return Error { Error::Type::Internal, "Failed to allocate hint stream buffer" };
  214. possible_merged_stream_buffer = buffer_result.release_value();
  215. MUST(possible_merged_stream_buffer.try_append(primary_hint_stream->bytes()));
  216. MUST(possible_merged_stream_buffer.try_append(overflow_hint_stream->bytes()));
  217. hint_stream_bytes = possible_merged_stream_buffer.bytes();
  218. } else {
  219. hint_stream_bytes = primary_hint_stream->bytes();
  220. }
  221. auto hint_table = TRY(parse_page_offset_hint_table(hint_stream_bytes));
  222. auto hint_table_entries = parse_all_page_offset_hint_table_entries(hint_table, hint_stream_bytes);
  223. // FIXME: Do something with the hint tables
  224. return {};
  225. }
  226. PDFErrorOr<void> Parser::initialize_non_linearized_xref_table()
  227. {
  228. m_reader.move_to(m_reader.bytes().size() - 1);
  229. if (!navigate_to_before_eof_marker())
  230. return error("No EOF marker");
  231. if (!navigate_to_after_startxref())
  232. return error("No xref");
  233. m_reader.set_reading_forwards();
  234. auto xref_offset_value = parse_number();
  235. if (xref_offset_value.is_error() || !xref_offset_value.value().has<int>())
  236. return error("Invalid xref offset");
  237. auto xref_offset = xref_offset_value.value().get<int>();
  238. m_reader.move_to(xref_offset);
  239. m_xref_table = TRY(parse_xref_table());
  240. m_trailer = TRY(parse_file_trailer());
  241. return {};
  242. }
  243. PDFErrorOr<NonnullRefPtr<XRefTable>> Parser::parse_xref_table()
  244. {
  245. if (!m_reader.matches("xref"))
  246. return error("Expected \"xref\"");
  247. m_reader.move_by(4);
  248. if (!consume_eol())
  249. return error("Expected newline after \"xref\"");
  250. auto table = adopt_ref(*new XRefTable());
  251. do {
  252. if (m_reader.matches("trailer"))
  253. return table;
  254. Vector<XRefEntry> entries;
  255. auto starting_index_value = TRY(parse_number());
  256. auto starting_index = starting_index_value.get<int>();
  257. auto object_count_value = TRY(parse_number());
  258. auto object_count = object_count_value.get<int>();
  259. for (int i = 0; i < object_count; i++) {
  260. auto offset_string = String(m_reader.bytes().slice(m_reader.offset(), 10));
  261. m_reader.move_by(10);
  262. if (!consume(' '))
  263. return error("Malformed xref entry");
  264. auto generation_string = String(m_reader.bytes().slice(m_reader.offset(), 5));
  265. m_reader.move_by(5);
  266. if (!consume(' '))
  267. return error("Malformed xref entry");
  268. auto letter = m_reader.read();
  269. if (letter != 'n' && letter != 'f')
  270. return error("Malformed xref entry");
  271. // The line ending sequence can be one of the following:
  272. // SP CR, SP LF, or CR LF
  273. if (m_reader.matches(' ')) {
  274. consume();
  275. auto ch = consume();
  276. if (ch != '\r' && ch != '\n')
  277. return error("Malformed xref entry");
  278. } else {
  279. if (!m_reader.matches("\r\n"))
  280. return error("Malformed xref entry");
  281. m_reader.move_by(2);
  282. }
  283. auto offset = strtol(offset_string.characters(), nullptr, 10);
  284. auto generation = strtol(generation_string.characters(), nullptr, 10);
  285. entries.append({ offset, static_cast<u16>(generation), letter == 'n' });
  286. }
  287. table->add_section({ starting_index, object_count, entries });
  288. } while (matches_number());
  289. return table;
  290. }
  291. PDFErrorOr<NonnullRefPtr<DictObject>> Parser::parse_file_trailer()
  292. {
  293. while (matches_eol())
  294. consume_eol();
  295. if (!m_reader.matches("trailer"))
  296. return error("Expected \"trailer\" keyword");
  297. m_reader.move_by(7);
  298. consume_whitespace();
  299. auto dict = TRY(parse_dict());
  300. if (!m_reader.matches("startxref"))
  301. return error("Expected \"startxref\"");
  302. m_reader.move_by(9);
  303. consume_whitespace();
  304. m_reader.move_until([&](auto) { return matches_eol(); });
  305. VERIFY(consume_eol());
  306. if (!m_reader.matches("%%EOF"))
  307. return error("Expected \"%%EOF\"");
  308. m_reader.move_by(5);
  309. consume_whitespace();
  310. return dict;
  311. }
  312. PDFErrorOr<Parser::PageOffsetHintTable> Parser::parse_page_offset_hint_table(ReadonlyBytes hint_stream_bytes)
  313. {
  314. if (hint_stream_bytes.size() < sizeof(PageOffsetHintTable))
  315. return error("Hint stream is too small");
  316. size_t offset = 0;
  317. auto read_u32 = [&] {
  318. u32 data = reinterpret_cast<const u32*>(hint_stream_bytes.data() + offset)[0];
  319. offset += 4;
  320. return AK::convert_between_host_and_big_endian(data);
  321. };
  322. auto read_u16 = [&] {
  323. u16 data = reinterpret_cast<const u16*>(hint_stream_bytes.data() + offset)[0];
  324. offset += 2;
  325. return AK::convert_between_host_and_big_endian(data);
  326. };
  327. PageOffsetHintTable hint_table {
  328. read_u32(),
  329. read_u32(),
  330. read_u16(),
  331. read_u32(),
  332. read_u16(),
  333. read_u32(),
  334. read_u16(),
  335. read_u32(),
  336. read_u16(),
  337. read_u16(),
  338. read_u16(),
  339. read_u16(),
  340. read_u16(),
  341. };
  342. // Verify that all of the bits_required_for_xyz fields are <= 32, since all of the numeric
  343. // fields in PageOffsetHintTableEntry are u32
  344. VERIFY(hint_table.bits_required_for_object_number <= 32);
  345. VERIFY(hint_table.bits_required_for_page_length <= 32);
  346. VERIFY(hint_table.bits_required_for_content_stream_offsets <= 32);
  347. VERIFY(hint_table.bits_required_for_content_stream_length <= 32);
  348. VERIFY(hint_table.bits_required_for_number_of_shared_obj_refs <= 32);
  349. VERIFY(hint_table.bits_required_for_greatest_shared_obj_identifier <= 32);
  350. VERIFY(hint_table.bits_required_for_fraction_numerator <= 32);
  351. return hint_table;
  352. }
  353. Vector<Parser::PageOffsetHintTableEntry> Parser::parse_all_page_offset_hint_table_entries(PageOffsetHintTable const& hint_table, ReadonlyBytes hint_stream_bytes)
  354. {
  355. InputMemoryStream input_stream(hint_stream_bytes);
  356. input_stream.seek(sizeof(PageOffsetHintTable));
  357. InputBitStream bit_stream(input_stream);
  358. auto number_of_pages = m_linearization_dictionary.value().number_of_pages;
  359. Vector<PageOffsetHintTableEntry> entries;
  360. for (size_t i = 0; i < number_of_pages; i++)
  361. entries.append(PageOffsetHintTableEntry {});
  362. auto bits_required_for_object_number = hint_table.bits_required_for_object_number;
  363. auto bits_required_for_page_length = hint_table.bits_required_for_page_length;
  364. auto bits_required_for_content_stream_offsets = hint_table.bits_required_for_content_stream_offsets;
  365. auto bits_required_for_content_stream_length = hint_table.bits_required_for_content_stream_length;
  366. auto bits_required_for_number_of_shared_obj_refs = hint_table.bits_required_for_number_of_shared_obj_refs;
  367. auto bits_required_for_greatest_shared_obj_identifier = hint_table.bits_required_for_greatest_shared_obj_identifier;
  368. auto bits_required_for_fraction_numerator = hint_table.bits_required_for_fraction_numerator;
  369. auto parse_int_entry = [&](u32 PageOffsetHintTableEntry::*field, u32 bit_size) {
  370. if (bit_size <= 0)
  371. return;
  372. for (int i = 0; i < number_of_pages; i++) {
  373. auto& entry = entries[i];
  374. entry.*field = bit_stream.read_bits(bit_size);
  375. }
  376. };
  377. auto parse_vector_entry = [&](Vector<u32> PageOffsetHintTableEntry::*field, u32 bit_size) {
  378. if (bit_size <= 0)
  379. return;
  380. for (int page = 1; page < number_of_pages; page++) {
  381. auto number_of_shared_objects = entries[page].number_of_shared_objects;
  382. Vector<u32> items;
  383. items.ensure_capacity(number_of_shared_objects);
  384. for (size_t i = 0; i < number_of_shared_objects; i++)
  385. items.unchecked_append(bit_stream.read_bits(bit_size));
  386. entries[page].*field = move(items);
  387. }
  388. };
  389. parse_int_entry(&PageOffsetHintTableEntry::objects_in_page_number, bits_required_for_object_number);
  390. parse_int_entry(&PageOffsetHintTableEntry::page_length_number, bits_required_for_page_length);
  391. parse_int_entry(&PageOffsetHintTableEntry::number_of_shared_objects, bits_required_for_number_of_shared_obj_refs);
  392. parse_vector_entry(&PageOffsetHintTableEntry::shared_object_identifiers, bits_required_for_greatest_shared_obj_identifier);
  393. parse_vector_entry(&PageOffsetHintTableEntry::shared_object_location_numerators, bits_required_for_fraction_numerator);
  394. parse_int_entry(&PageOffsetHintTableEntry::page_content_stream_offset_number, bits_required_for_content_stream_offsets);
  395. parse_int_entry(&PageOffsetHintTableEntry::page_content_stream_length_number, bits_required_for_content_stream_length);
  396. return entries;
  397. }
  398. bool Parser::navigate_to_before_eof_marker()
  399. {
  400. m_reader.set_reading_backwards();
  401. while (!m_reader.done()) {
  402. m_reader.move_until([&](auto) { return matches_eol(); });
  403. if (m_reader.done())
  404. return false;
  405. consume_eol();
  406. if (!m_reader.matches("%%EOF"))
  407. continue;
  408. m_reader.move_by(5);
  409. if (!matches_eol())
  410. continue;
  411. consume_eol();
  412. return true;
  413. }
  414. return false;
  415. }
  416. bool Parser::navigate_to_after_startxref()
  417. {
  418. m_reader.set_reading_backwards();
  419. while (!m_reader.done()) {
  420. m_reader.move_until([&](auto) { return matches_eol(); });
  421. auto offset = m_reader.offset() + 1;
  422. consume_eol();
  423. if (!m_reader.matches("startxref"))
  424. continue;
  425. m_reader.move_by(9);
  426. if (!matches_eol())
  427. continue;
  428. m_reader.move_to(offset);
  429. return true;
  430. }
  431. return false;
  432. }
  433. String Parser::parse_comment()
  434. {
  435. if (!m_reader.matches('%'))
  436. return {};
  437. consume();
  438. auto comment_start_offset = m_reader.offset();
  439. m_reader.move_until([&](auto) {
  440. return matches_eol();
  441. });
  442. String str = StringView(m_reader.bytes().slice(comment_start_offset, m_reader.offset() - comment_start_offset));
  443. consume_eol();
  444. consume_whitespace();
  445. return str;
  446. }
  447. PDFErrorOr<Value> Parser::parse_value()
  448. {
  449. parse_comment();
  450. if (m_reader.matches("null")) {
  451. m_reader.move_by(4);
  452. consume_whitespace();
  453. return Value(nullptr);
  454. }
  455. if (m_reader.matches("true")) {
  456. m_reader.move_by(4);
  457. consume_whitespace();
  458. return Value(true);
  459. }
  460. if (m_reader.matches("false")) {
  461. m_reader.move_by(5);
  462. consume_whitespace();
  463. return Value(false);
  464. }
  465. if (matches_number())
  466. return parse_possible_indirect_value_or_ref();
  467. if (m_reader.matches('/'))
  468. return MUST(parse_name());
  469. if (m_reader.matches("<<")) {
  470. auto dict = TRY(parse_dict());
  471. if (m_reader.matches("stream"))
  472. return TRY(parse_stream(dict));
  473. return dict;
  474. }
  475. if (m_reader.matches_any('(', '<'))
  476. return parse_string();
  477. if (m_reader.matches('['))
  478. return TRY(parse_array());
  479. return error(String::formatted("Unexpected char \"{}\"", m_reader.peek()));
  480. }
  481. PDFErrorOr<Value> Parser::parse_possible_indirect_value_or_ref()
  482. {
  483. auto first_number = TRY(parse_number());
  484. if (!matches_number())
  485. return first_number;
  486. m_reader.save();
  487. auto second_number = parse_number();
  488. if (second_number.is_error()) {
  489. m_reader.load();
  490. return first_number;
  491. }
  492. if (m_reader.matches('R')) {
  493. m_reader.discard();
  494. consume();
  495. consume_whitespace();
  496. return Value(Reference(first_number.get<int>(), second_number.value().get<int>()));
  497. }
  498. if (m_reader.matches("obj")) {
  499. m_reader.discard();
  500. auto index = first_number.get<int>();
  501. auto generation = second_number.value().get<int>();
  502. VERIFY(index >= 0);
  503. VERIFY(generation >= 0);
  504. return TRY(parse_indirect_value(index, generation));
  505. }
  506. m_reader.load();
  507. return first_number;
  508. }
  509. PDFErrorOr<NonnullRefPtr<IndirectValue>> Parser::parse_indirect_value(u32 index, u32 generation)
  510. {
  511. if (!m_reader.matches("obj"))
  512. return error("Expected \"obj\" at beginning of indirect value");
  513. m_reader.move_by(3);
  514. if (matches_eol())
  515. consume_eol();
  516. push_reference({ index, generation });
  517. auto value = TRY(parse_value());
  518. if (!m_reader.matches("endobj"))
  519. return error("Expected \"endobj\" at end of indirect value");
  520. consume(6);
  521. consume_whitespace();
  522. pop_reference();
  523. return make_object<IndirectValue>(index, generation, value);
  524. }
  525. PDFErrorOr<NonnullRefPtr<IndirectValue>> Parser::parse_indirect_value()
  526. {
  527. auto first_number = TRY(parse_number());
  528. auto second_number = TRY(parse_number());
  529. auto index = first_number.get<int>();
  530. auto generation = second_number.get<int>();
  531. VERIFY(index >= 0);
  532. VERIFY(generation >= 0);
  533. return parse_indirect_value(index, generation);
  534. }
  535. PDFErrorOr<Value> Parser::parse_number()
  536. {
  537. size_t start_offset = m_reader.offset();
  538. bool is_float = false;
  539. bool consumed_digit = false;
  540. if (m_reader.matches('+') || m_reader.matches('-'))
  541. consume();
  542. while (!m_reader.done()) {
  543. if (m_reader.matches('.')) {
  544. if (is_float)
  545. break;
  546. is_float = true;
  547. consume();
  548. } else if (isdigit(m_reader.peek())) {
  549. consume();
  550. consumed_digit = true;
  551. } else {
  552. break;
  553. }
  554. }
  555. if (!consumed_digit)
  556. return error("Invalid number");
  557. consume_whitespace();
  558. auto string = String(m_reader.bytes().slice(start_offset, m_reader.offset() - start_offset));
  559. float f = strtof(string.characters(), nullptr);
  560. if (is_float)
  561. return Value(f);
  562. VERIFY(floorf(f) == f);
  563. return Value(static_cast<int>(f));
  564. }
  565. PDFErrorOr<NonnullRefPtr<NameObject>> Parser::parse_name()
  566. {
  567. if (!consume('/'))
  568. return error("Expected Name object to start with \"/\"");
  569. StringBuilder builder;
  570. while (true) {
  571. if (!matches_regular_character())
  572. break;
  573. if (m_reader.matches('#')) {
  574. int hex_value = 0;
  575. for (int i = 0; i < 2; i++) {
  576. auto ch = consume();
  577. VERIFY(isxdigit(ch));
  578. hex_value *= 16;
  579. if (ch <= '9') {
  580. hex_value += ch - '0';
  581. } else {
  582. hex_value += ch - 'A' + 10;
  583. }
  584. }
  585. builder.append(static_cast<char>(hex_value));
  586. continue;
  587. }
  588. builder.append(consume());
  589. }
  590. consume_whitespace();
  591. return make_object<NameObject>(builder.to_string());
  592. }
  593. NonnullRefPtr<StringObject> Parser::parse_string()
  594. {
  595. ScopeGuard guard([&] { consume_whitespace(); });
  596. String string;
  597. bool is_binary_string;
  598. if (m_reader.matches('(')) {
  599. string = parse_literal_string();
  600. is_binary_string = false;
  601. } else {
  602. string = parse_hex_string();
  603. is_binary_string = true;
  604. }
  605. VERIFY(!string.is_null());
  606. auto string_object = make_object<StringObject>(string, is_binary_string);
  607. if (m_document->security_handler() && !m_disable_encryption)
  608. m_document->security_handler()->decrypt(string_object, m_current_reference_stack.last());
  609. auto unencrypted_string = string_object->string();
  610. if (unencrypted_string.bytes().starts_with(Array<u8, 2> { 0xfe, 0xff })) {
  611. // The string is encoded in UTF16-BE
  612. string_object->set_string(TextCodec::decoder_for("utf-16be")->to_utf8(unencrypted_string));
  613. } else if (unencrypted_string.bytes().starts_with(Array<u8, 3> { 239, 187, 191 })) {
  614. // The string is encoded in UTF-8. This is the default anyways, but if these bytes
  615. // are explicitly included, we have to trim them
  616. string_object->set_string(unencrypted_string.substring(3));
  617. }
  618. return string_object;
  619. }
  620. String Parser::parse_literal_string()
  621. {
  622. VERIFY(consume('('));
  623. StringBuilder builder;
  624. auto opened_parens = 0;
  625. while (true) {
  626. if (m_reader.matches('(')) {
  627. opened_parens++;
  628. builder.append(consume());
  629. } else if (m_reader.matches(')')) {
  630. consume();
  631. if (opened_parens == 0)
  632. break;
  633. opened_parens--;
  634. builder.append(')');
  635. } else if (m_reader.matches('\\')) {
  636. consume();
  637. if (matches_eol()) {
  638. consume_eol();
  639. continue;
  640. }
  641. if (m_reader.done())
  642. return {};
  643. auto ch = consume();
  644. switch (ch) {
  645. case 'n':
  646. builder.append('\n');
  647. break;
  648. case 'r':
  649. builder.append('\r');
  650. break;
  651. case 't':
  652. builder.append('\t');
  653. break;
  654. case 'b':
  655. builder.append('\b');
  656. break;
  657. case 'f':
  658. builder.append('\f');
  659. break;
  660. case '(':
  661. builder.append('(');
  662. break;
  663. case ')':
  664. builder.append(')');
  665. break;
  666. case '\\':
  667. builder.append('\\');
  668. break;
  669. default: {
  670. if (ch >= '0' && ch <= '7') {
  671. int octal_value = ch - '0';
  672. for (int i = 0; i < 2; i++) {
  673. auto octal_ch = consume();
  674. if (octal_ch < '0' || octal_ch > '7')
  675. break;
  676. octal_value = octal_value * 8 + (octal_ch - '0');
  677. }
  678. builder.append(static_cast<char>(octal_value));
  679. } else {
  680. builder.append(ch);
  681. }
  682. }
  683. }
  684. } else if (matches_eol()) {
  685. consume_eol();
  686. builder.append('\n');
  687. } else {
  688. builder.append(consume());
  689. }
  690. }
  691. return builder.to_string();
  692. }
  693. String Parser::parse_hex_string()
  694. {
  695. VERIFY(consume('<'));
  696. StringBuilder builder;
  697. while (true) {
  698. if (m_reader.matches('>')) {
  699. consume();
  700. return builder.to_string();
  701. } else {
  702. int hex_value = 0;
  703. for (int i = 0; i < 2; i++) {
  704. auto ch = consume();
  705. if (ch == '>') {
  706. // The hex string contains an odd number of characters, and the last character
  707. // is assumed to be '0'
  708. consume();
  709. hex_value *= 16;
  710. builder.append(static_cast<char>(hex_value));
  711. return builder.to_string();
  712. }
  713. VERIFY(isxdigit(ch));
  714. hex_value *= 16;
  715. if (ch <= '9') {
  716. hex_value += ch - '0';
  717. } else if (ch >= 'A' && ch <= 'F') {
  718. hex_value += ch - 'A' + 10;
  719. } else {
  720. hex_value += ch - 'a' + 10;
  721. }
  722. }
  723. builder.append(static_cast<char>(hex_value));
  724. }
  725. }
  726. }
  727. PDFErrorOr<NonnullRefPtr<ArrayObject>> Parser::parse_array()
  728. {
  729. if (!consume('['))
  730. return error("Expected array to start with \"[\"");
  731. consume_whitespace();
  732. Vector<Value> values;
  733. while (!m_reader.matches(']'))
  734. values.append(TRY(parse_value()));
  735. VERIFY(consume(']'));
  736. consume_whitespace();
  737. return make_object<ArrayObject>(values);
  738. }
  739. PDFErrorOr<NonnullRefPtr<DictObject>> Parser::parse_dict()
  740. {
  741. if (!consume('<') || !consume('<'))
  742. return error("Expected dict to start with \"<<\"");
  743. consume_whitespace();
  744. HashMap<FlyString, Value> map;
  745. while (!m_reader.done()) {
  746. if (m_reader.matches(">>"))
  747. break;
  748. auto name = TRY(parse_name())->name();
  749. auto value = TRY(parse_value());
  750. map.set(name, value);
  751. }
  752. if (!consume('>') || !consume('>'))
  753. return error("Expected dict to end with \">>\"");
  754. consume_whitespace();
  755. return make_object<DictObject>(map);
  756. }
  757. PDFErrorOr<RefPtr<DictObject>> Parser::conditionally_parse_page_tree_node(u32 object_index)
  758. {
  759. VERIFY(m_xref_table->has_object(object_index));
  760. auto byte_offset = m_xref_table->byte_offset_for_object(object_index);
  761. m_reader.move_to(byte_offset);
  762. TRY(parse_number());
  763. TRY(parse_number());
  764. if (!m_reader.matches("obj"))
  765. return error(String::formatted("Invalid page tree offset {}", object_index));
  766. m_reader.move_by(3);
  767. consume_whitespace();
  768. VERIFY(consume('<') && consume('<'));
  769. consume_whitespace();
  770. HashMap<FlyString, Value> map;
  771. while (true) {
  772. if (m_reader.matches(">>"))
  773. break;
  774. auto name = TRY(parse_name());
  775. auto name_string = name->name();
  776. if (!name_string.is_one_of(CommonNames::Type, CommonNames::Parent, CommonNames::Kids, CommonNames::Count)) {
  777. // This is a page, not a page tree node
  778. return RefPtr<DictObject> {};
  779. }
  780. auto value = TRY(parse_value());
  781. if (name_string == CommonNames::Type) {
  782. if (!value.has<NonnullRefPtr<Object>>())
  783. return RefPtr<DictObject> {};
  784. auto type_object = value.get<NonnullRefPtr<Object>>();
  785. if (!type_object->is<NameObject>())
  786. return RefPtr<DictObject> {};
  787. auto type_name = type_object->cast<NameObject>();
  788. if (type_name->name() != CommonNames::Pages)
  789. return RefPtr<DictObject> {};
  790. }
  791. map.set(name->name(), value);
  792. }
  793. VERIFY(consume('>') && consume('>'));
  794. consume_whitespace();
  795. return make_object<DictObject>(map);
  796. }
  797. PDFErrorOr<NonnullRefPtr<StreamObject>> Parser::parse_stream(NonnullRefPtr<DictObject> dict)
  798. {
  799. if (!m_reader.matches("stream"))
  800. return error("Expected stream to start with \"stream\"");
  801. m_reader.move_by(6);
  802. if (!consume_eol())
  803. return error("Expected \"stream\" to be followed by a newline");
  804. ReadonlyBytes bytes;
  805. auto maybe_length = dict->get(CommonNames::Length);
  806. if (maybe_length.has_value() && (!maybe_length->has<Reference>() || m_xref_table)) {
  807. // The PDF writer has kindly provided us with the direct length of the stream
  808. m_reader.save();
  809. auto length = TRY(m_document->resolve_to<int>(maybe_length.value()));
  810. m_reader.load();
  811. bytes = m_reader.bytes().slice(m_reader.offset(), length);
  812. m_reader.move_by(length);
  813. consume_whitespace();
  814. } else {
  815. // We have to look for the endstream keyword
  816. auto stream_start = m_reader.offset();
  817. while (true) {
  818. m_reader.move_until([&](auto) { return matches_eol(); });
  819. auto potential_stream_end = m_reader.offset();
  820. consume_eol();
  821. if (!m_reader.matches("endstream"))
  822. continue;
  823. bytes = m_reader.bytes().slice(stream_start, potential_stream_end - stream_start);
  824. break;
  825. }
  826. }
  827. m_reader.move_by(9);
  828. consume_whitespace();
  829. auto stream_object = make_object<StreamObject>(dict, MUST(ByteBuffer::copy(bytes)));
  830. if (m_document->security_handler() && !m_disable_encryption)
  831. m_document->security_handler()->decrypt(stream_object, m_current_reference_stack.last());
  832. if (dict->contains(CommonNames::Filter)) {
  833. auto filter_type = MUST(dict->get_name(m_document, CommonNames::Filter))->name();
  834. auto maybe_bytes = Filter::decode(stream_object->bytes(), filter_type);
  835. if (maybe_bytes.is_error()) {
  836. warnln("Failed to decode filter: {}", maybe_bytes.error().string_literal());
  837. return error(String::formatted("Failed to decode filter {}", maybe_bytes.error().string_literal()));
  838. }
  839. stream_object->buffer() = maybe_bytes.release_value();
  840. }
  841. return stream_object;
  842. }
  843. PDFErrorOr<Vector<Operator>> Parser::parse_operators()
  844. {
  845. Vector<Operator> operators;
  846. Vector<Value> operator_args;
  847. constexpr static auto is_operator_char = [](char ch) {
  848. return isalpha(ch) || ch == '*' || ch == '\'';
  849. };
  850. while (!m_reader.done()) {
  851. auto ch = m_reader.peek();
  852. if (is_operator_char(ch)) {
  853. auto operator_start = m_reader.offset();
  854. while (is_operator_char(ch)) {
  855. consume();
  856. if (m_reader.done())
  857. break;
  858. ch = m_reader.peek();
  859. }
  860. auto operator_string = StringView(m_reader.bytes().slice(operator_start, m_reader.offset() - operator_start));
  861. auto operator_type = Operator::operator_type_from_symbol(operator_string);
  862. operators.append(Operator(operator_type, move(operator_args)));
  863. operator_args = Vector<Value>();
  864. consume_whitespace();
  865. continue;
  866. }
  867. operator_args.append(TRY(parse_value()));
  868. }
  869. return operators;
  870. }
  871. bool Parser::matches_eol() const
  872. {
  873. return m_reader.matches_any(0xa, 0xd);
  874. }
  875. bool Parser::matches_whitespace() const
  876. {
  877. return matches_eol() || m_reader.matches_any(0, 0x9, 0xc, ' ');
  878. }
  879. bool Parser::matches_number() const
  880. {
  881. if (m_reader.done())
  882. return false;
  883. auto ch = m_reader.peek();
  884. return isdigit(ch) || ch == '-' || ch == '+';
  885. }
  886. bool Parser::matches_delimiter() const
  887. {
  888. return m_reader.matches_any('(', ')', '<', '>', '[', ']', '{', '}', '/', '%');
  889. }
  890. bool Parser::matches_regular_character() const
  891. {
  892. return !matches_delimiter() && !matches_whitespace();
  893. }
  894. bool Parser::consume_eol()
  895. {
  896. if (m_reader.done()) {
  897. return false;
  898. }
  899. if (m_reader.matches("\r\n")) {
  900. consume(2);
  901. return true;
  902. }
  903. auto consumed = consume();
  904. return consumed == 0xd || consumed == 0xa;
  905. }
  906. bool Parser::consume_whitespace()
  907. {
  908. bool consumed = false;
  909. while (matches_whitespace()) {
  910. consumed = true;
  911. consume();
  912. }
  913. return consumed;
  914. }
  915. char Parser::consume()
  916. {
  917. return m_reader.read();
  918. }
  919. void Parser::consume(int amount)
  920. {
  921. for (size_t i = 0; i < static_cast<size_t>(amount); i++)
  922. consume();
  923. }
  924. bool Parser::consume(char ch)
  925. {
  926. return consume() == ch;
  927. }
  928. Error Parser::error(
  929. String const& message
  930. #ifdef PDF_DEBUG
  931. ,
  932. SourceLocation loc
  933. #endif
  934. ) const
  935. {
  936. #ifdef PDF_DEBUG
  937. dbgln("\033[31m{} Parser error at offset {}: {}\033[0m", loc, m_reader.offset(), message);
  938. #endif
  939. return Error { Error::Type::Parse, message };
  940. }
  941. }
  942. namespace AK {
  943. template<>
  944. struct Formatter<PDF::Parser::LinearizationDictionary> : Formatter<StringView> {
  945. ErrorOr<void> format(FormatBuilder& format_builder, PDF::Parser::LinearizationDictionary const& dict)
  946. {
  947. StringBuilder builder;
  948. builder.append("{\n");
  949. builder.appendff(" length_of_file={}\n", dict.length_of_file);
  950. builder.appendff(" primary_hint_stream_offset={}\n", dict.primary_hint_stream_offset);
  951. builder.appendff(" primary_hint_stream_length={}\n", dict.primary_hint_stream_length);
  952. builder.appendff(" overflow_hint_stream_offset={}\n", dict.overflow_hint_stream_offset);
  953. builder.appendff(" overflow_hint_stream_length={}\n", dict.overflow_hint_stream_length);
  954. builder.appendff(" first_page_object_number={}\n", dict.first_page_object_number);
  955. builder.appendff(" offset_of_first_page_end={}\n", dict.offset_of_first_page_end);
  956. builder.appendff(" number_of_pages={}\n", dict.number_of_pages);
  957. builder.appendff(" offset_of_main_xref_table={}\n", dict.offset_of_main_xref_table);
  958. builder.appendff(" first_page={}\n", dict.first_page);
  959. builder.append('}');
  960. return Formatter<StringView>::format(format_builder, builder.to_string());
  961. }
  962. };
  963. template<>
  964. struct Formatter<PDF::Parser::PageOffsetHintTable> : Formatter<StringView> {
  965. ErrorOr<void> format(FormatBuilder& format_builder, PDF::Parser::PageOffsetHintTable const& table)
  966. {
  967. StringBuilder builder;
  968. builder.append("{\n");
  969. builder.appendff(" least_number_of_objects_in_a_page={}\n", table.least_number_of_objects_in_a_page);
  970. builder.appendff(" location_of_first_page_object={}\n", table.location_of_first_page_object);
  971. builder.appendff(" bits_required_for_object_number={}\n", table.bits_required_for_object_number);
  972. builder.appendff(" least_length_of_a_page={}\n", table.least_length_of_a_page);
  973. builder.appendff(" bits_required_for_page_length={}\n", table.bits_required_for_page_length);
  974. builder.appendff(" least_offset_of_any_content_stream={}\n", table.least_offset_of_any_content_stream);
  975. builder.appendff(" bits_required_for_content_stream_offsets={}\n", table.bits_required_for_content_stream_offsets);
  976. builder.appendff(" least_content_stream_length={}\n", table.least_content_stream_length);
  977. builder.appendff(" bits_required_for_content_stream_length={}\n", table.bits_required_for_content_stream_length);
  978. builder.appendff(" bits_required_for_number_of_shared_obj_refs={}\n", table.bits_required_for_number_of_shared_obj_refs);
  979. builder.appendff(" bits_required_for_greatest_shared_obj_identifier={}\n", table.bits_required_for_greatest_shared_obj_identifier);
  980. builder.appendff(" bits_required_for_fraction_numerator={}\n", table.bits_required_for_fraction_numerator);
  981. builder.appendff(" shared_object_reference_fraction_denominator={}\n", table.shared_object_reference_fraction_denominator);
  982. builder.append('}');
  983. return Formatter<StringView>::format(format_builder, builder.to_string());
  984. }
  985. };
  986. template<>
  987. struct Formatter<PDF::Parser::PageOffsetHintTableEntry> : Formatter<StringView> {
  988. ErrorOr<void> format(FormatBuilder& format_builder, PDF::Parser::PageOffsetHintTableEntry const& entry)
  989. {
  990. StringBuilder builder;
  991. builder.append("{\n");
  992. builder.appendff(" objects_in_page_number={}\n", entry.objects_in_page_number);
  993. builder.appendff(" page_length_number={}\n", entry.page_length_number);
  994. builder.appendff(" number_of_shared_objects={}\n", entry.number_of_shared_objects);
  995. builder.append(" shared_object_identifiers=[");
  996. for (auto& identifier : entry.shared_object_identifiers)
  997. builder.appendff(" {}", identifier);
  998. builder.append(" ]\n");
  999. builder.append(" shared_object_location_numerators=[");
  1000. for (auto& numerator : entry.shared_object_location_numerators)
  1001. builder.appendff(" {}", numerator);
  1002. builder.append(" ]\n");
  1003. builder.appendff(" page_content_stream_offset_number={}\n", entry.page_content_stream_offset_number);
  1004. builder.appendff(" page_content_stream_length_number={}\n", entry.page_content_stream_length_number);
  1005. builder.append('}');
  1006. return Formatter<StringView>::format(format_builder, builder.to_string());
  1007. }
  1008. };
  1009. }