Parser.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711
  1. /*
  2. * Copyright (c) 2021, Matthew Olsson <mattco@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/ScopeGuard.h>
  7. #include <AK/TypeCasts.h>
  8. #include <LibPDF/Document.h>
  9. #include <LibPDF/Parser.h>
  10. #include <ctype.h>
  11. #include <math.h>
  12. namespace PDF {
  13. template<typename T, typename... Args>
  14. static NonnullRefPtr<T> make_object(Args... args) requires(IsBaseOf<Object, T>)
  15. {
  16. return adopt_ref(*new T(forward<Args>(args)...));
  17. }
  18. Parser::Parser(Badge<Document>, const ReadonlyBytes& bytes)
  19. : m_reader(bytes)
  20. {
  21. }
  22. bool Parser::perform_validation()
  23. {
  24. return !sloppy_is_linearized() && parse_header();
  25. }
  26. Parser::XRefTableAndTrailer Parser::parse_last_xref_table_and_trailer()
  27. {
  28. m_reader.move_to(m_reader.bytes().size() - 1);
  29. VERIFY(navigate_to_before_eof_marker());
  30. navigate_to_after_startxref();
  31. VERIFY(!m_reader.done());
  32. m_reader.set_reading_forwards();
  33. auto xref_offset_value = parse_number();
  34. VERIFY(xref_offset_value.is_int());
  35. auto xref_offset = xref_offset_value.as_int();
  36. m_reader.move_to(xref_offset);
  37. auto xref_table = parse_xref_table();
  38. auto trailer = parse_file_trailer();
  39. return { xref_table, trailer };
  40. }
  41. NonnullRefPtr<IndirectValue> Parser::parse_indirect_value_at_offset(size_t offset)
  42. {
  43. m_reader.set_reading_forwards();
  44. m_reader.move_to(offset);
  45. return parse_indirect_value();
  46. }
  47. bool Parser::parse_header()
  48. {
  49. // FIXME: Do something with the version?
  50. m_reader.set_reading_forwards();
  51. m_reader.move_to(0);
  52. if (m_reader.remaining() < 8 || !m_reader.matches("%PDF-"))
  53. return false;
  54. m_reader.move_by(5);
  55. char major_ver = m_reader.read();
  56. if (major_ver != '1' && major_ver != '2')
  57. return false;
  58. if (m_reader.read() != '.')
  59. return false;
  60. char minor_ver = m_reader.read();
  61. if (minor_ver < '0' || major_ver > '7')
  62. return false;
  63. consume_eol();
  64. // Parse optional high-byte comment, which signifies a binary file
  65. // FIXME: Do something with this?
  66. auto comment = parse_comment();
  67. if (!comment.is_empty()) {
  68. auto binary = comment.length() >= 4;
  69. if (binary) {
  70. for (size_t i = 0; i < comment.length() && binary; i++)
  71. binary = static_cast<u8>(comment[i]) > 128;
  72. }
  73. }
  74. return true;
  75. }
  76. XRefTable Parser::parse_xref_table()
  77. {
  78. VERIFY(m_reader.matches("xref"));
  79. m_reader.move_by(4);
  80. consume_eol();
  81. XRefTable table;
  82. while (true) {
  83. if (m_reader.matches("trailer"))
  84. break;
  85. Vector<XRefEntry> entries;
  86. auto starting_index_value = parse_number();
  87. auto starting_index = starting_index_value.as_int();
  88. auto object_count_value = parse_number();
  89. auto object_count = object_count_value.as_int();
  90. for (int i = 0; i < object_count; i++) {
  91. auto offset_string = String(m_reader.bytes().slice(m_reader.offset(), 10));
  92. m_reader.move_by(10);
  93. consume(' ');
  94. auto generation_string = String(m_reader.bytes().slice(m_reader.offset(), 5));
  95. m_reader.move_by(5);
  96. consume(' ');
  97. auto letter = m_reader.read();
  98. VERIFY(letter == 'n' || letter == 'f');
  99. // The line ending sequence can be one of the following:
  100. // SP CR, SP LF, or CR LF
  101. if (m_reader.matches(' ')) {
  102. consume();
  103. auto ch = consume();
  104. VERIFY(ch == '\r' || ch == '\n');
  105. } else {
  106. VERIFY(m_reader.matches("\r\n"));
  107. m_reader.move_by(2);
  108. }
  109. auto offset = strtol(offset_string.characters(), nullptr, 10);
  110. auto generation = strtol(generation_string.characters(), nullptr, 10);
  111. entries.append({ offset, static_cast<u16>(generation), letter == 'n' });
  112. }
  113. table.add_section({ starting_index, object_count, entries });
  114. }
  115. return table;
  116. }
  117. NonnullRefPtr<DictObject> Parser::parse_file_trailer()
  118. {
  119. VERIFY(m_reader.matches("trailer"));
  120. m_reader.move_by(7);
  121. consume_whitespace();
  122. auto dict = parse_dict();
  123. VERIFY(m_reader.matches("startxref"));
  124. m_reader.move_by(9);
  125. consume_whitespace();
  126. m_reader.move_until([&](auto) { return matches_eol(); });
  127. consume_eol();
  128. VERIFY(m_reader.matches("%%EOF"));
  129. m_reader.move_by(5);
  130. consume_whitespace();
  131. VERIFY(m_reader.done());
  132. return dict;
  133. }
  134. bool Parser::navigate_to_before_eof_marker()
  135. {
  136. m_reader.set_reading_backwards();
  137. while (!m_reader.done()) {
  138. m_reader.move_until([&](auto) { return matches_eol(); });
  139. if (m_reader.done())
  140. return false;
  141. consume_eol();
  142. if (!m_reader.matches("%%EOF"))
  143. continue;
  144. m_reader.move_by(5);
  145. if (!matches_eol())
  146. continue;
  147. consume_eol();
  148. return true;
  149. }
  150. return false;
  151. }
  152. bool Parser::navigate_to_after_startxref()
  153. {
  154. m_reader.set_reading_backwards();
  155. while (!m_reader.done()) {
  156. m_reader.move_until([&](auto) { return matches_eol(); });
  157. auto offset = m_reader.offset() + 1;
  158. consume_eol();
  159. if (!m_reader.matches("startxref"))
  160. continue;
  161. m_reader.move_by(9);
  162. if (!matches_eol())
  163. continue;
  164. m_reader.move_to(offset);
  165. return true;
  166. }
  167. return false;
  168. }
  169. bool Parser::sloppy_is_linearized()
  170. {
  171. ScopeGuard guard([&] {
  172. m_reader.move_to(0);
  173. m_reader.set_reading_forwards();
  174. });
  175. auto limit = min(1024ul, m_reader.bytes().size() - 1);
  176. m_reader.move_to(limit);
  177. m_reader.set_reading_backwards();
  178. while (!m_reader.done()) {
  179. m_reader.move_until('/');
  180. if (m_reader.matches("/Linearized"))
  181. return true;
  182. m_reader.move_by(1);
  183. }
  184. return false;
  185. }
  186. String Parser::parse_comment()
  187. {
  188. if (!m_reader.matches('%'))
  189. return {};
  190. consume();
  191. auto comment_start_offset = m_reader.offset();
  192. m_reader.move_until([&] {
  193. return matches_eol();
  194. });
  195. String str = StringView(m_reader.bytes().slice(comment_start_offset, m_reader.offset() - comment_start_offset));
  196. consume_eol();
  197. consume_whitespace();
  198. return str;
  199. }
  200. Value Parser::parse_value()
  201. {
  202. parse_comment();
  203. if (m_reader.matches("null")) {
  204. m_reader.move_by(4);
  205. consume_whitespace();
  206. return Value();
  207. }
  208. if (m_reader.matches("true")) {
  209. m_reader.move_by(4);
  210. consume_whitespace();
  211. return Value(true);
  212. }
  213. if (m_reader.matches("false")) {
  214. m_reader.move_by(5);
  215. consume_whitespace();
  216. return Value(false);
  217. }
  218. if (matches_number())
  219. return parse_possible_indirect_value_or_ref();
  220. if (m_reader.matches('/'))
  221. return parse_name();
  222. if (m_reader.matches("<<")) {
  223. auto dict = parse_dict();
  224. if (m_reader.matches("stream\n"))
  225. return parse_stream(dict);
  226. return dict;
  227. }
  228. if (m_reader.matches_any('(', '<'))
  229. return parse_string();
  230. if (m_reader.matches('['))
  231. return parse_array();
  232. dbgln("tried to parse value, but found char {} ({}) at offset {}", m_reader.peek(), static_cast<u8>(m_reader.peek()), m_reader.offset());
  233. VERIFY_NOT_REACHED();
  234. }
  235. Value Parser::parse_possible_indirect_value_or_ref()
  236. {
  237. auto first_number = parse_number();
  238. if (!first_number.is_int() || !matches_number())
  239. return first_number;
  240. m_reader.save();
  241. auto second_number = parse_number();
  242. if (!second_number.is_int()) {
  243. m_reader.load();
  244. return first_number;
  245. }
  246. if (m_reader.matches('R')) {
  247. m_reader.discard();
  248. consume();
  249. consume_whitespace();
  250. return make_object<IndirectValueRef>(first_number.as_int(), second_number.as_int());
  251. }
  252. if (m_reader.matches("obj")) {
  253. m_reader.discard();
  254. return parse_indirect_value(first_number.as_int(), second_number.as_int());
  255. }
  256. m_reader.load();
  257. return first_number;
  258. }
  259. NonnullRefPtr<IndirectValue> Parser::parse_indirect_value(int index, int generation)
  260. {
  261. VERIFY(m_reader.matches("obj"));
  262. m_reader.move_by(3);
  263. if (matches_eol())
  264. consume_eol();
  265. auto value = parse_value();
  266. VERIFY(value.is_object());
  267. VERIFY(m_reader.matches("endobj"));
  268. return make_object<IndirectValue>(index, generation, value.as_object());
  269. }
  270. NonnullRefPtr<IndirectValue> Parser::parse_indirect_value()
  271. {
  272. auto first_number = parse_number();
  273. auto second_number = parse_number();
  274. VERIFY(first_number.is_int() && second_number.is_int());
  275. return parse_indirect_value(first_number.as_int(), second_number.as_int());
  276. }
  277. Value Parser::parse_number()
  278. {
  279. size_t start_offset = m_reader.offset();
  280. bool is_float = false;
  281. if (m_reader.matches('+') || m_reader.matches('-'))
  282. consume();
  283. while (!m_reader.done()) {
  284. if (m_reader.matches('.')) {
  285. if (is_float)
  286. break;
  287. is_float = true;
  288. consume();
  289. } else if (isdigit(m_reader.peek())) {
  290. consume();
  291. } else {
  292. break;
  293. }
  294. }
  295. consume_whitespace();
  296. auto string = String(m_reader.bytes().slice(start_offset, m_reader.offset() - start_offset));
  297. float f = strtof(string.characters(), nullptr);
  298. if (is_float)
  299. return Value(f);
  300. VERIFY(floorf(f) == f);
  301. return Value(static_cast<int>(f));
  302. }
  303. NonnullRefPtr<NameObject> Parser::parse_name()
  304. {
  305. consume('/');
  306. StringBuilder builder;
  307. while (true) {
  308. if (!matches_regular_character())
  309. break;
  310. if (m_reader.matches('#')) {
  311. int hex_value = 0;
  312. for (int i = 0; i < 2; i++) {
  313. auto ch = consume();
  314. VERIFY(isxdigit(ch));
  315. hex_value *= 16;
  316. if (ch <= '9') {
  317. hex_value += ch - '0';
  318. } else {
  319. hex_value += ch - 'A' + 10;
  320. }
  321. }
  322. builder.append(static_cast<char>(hex_value));
  323. continue;
  324. }
  325. builder.append(consume());
  326. }
  327. consume_whitespace();
  328. return make_object<NameObject>(builder.to_string());
  329. }
  330. NonnullRefPtr<StringObject> Parser::parse_string()
  331. {
  332. ScopeGuard guard([&] { consume_whitespace(); });
  333. if (m_reader.matches('('))
  334. return make_object<StringObject>(parse_literal_string(), false);
  335. return make_object<StringObject>(parse_hex_string(), true);
  336. }
  337. String Parser::parse_literal_string()
  338. {
  339. consume('(');
  340. StringBuilder builder;
  341. auto opened_parens = 0;
  342. while (true) {
  343. if (m_reader.matches('(')) {
  344. opened_parens++;
  345. builder.append(consume());
  346. } else if (m_reader.matches(')')) {
  347. consume();
  348. if (opened_parens == 0)
  349. break;
  350. opened_parens--;
  351. builder.append(')');
  352. } else if (m_reader.matches('\\')) {
  353. consume();
  354. if (matches_eol()) {
  355. consume_eol();
  356. continue;
  357. }
  358. VERIFY(!m_reader.done());
  359. auto ch = consume();
  360. switch (ch) {
  361. case 'n':
  362. builder.append('\n');
  363. break;
  364. case 'r':
  365. builder.append('\r');
  366. break;
  367. case 't':
  368. builder.append('\t');
  369. break;
  370. case 'b':
  371. builder.append('\b');
  372. break;
  373. case 'f':
  374. builder.append('\f');
  375. break;
  376. case '(':
  377. builder.append('(');
  378. break;
  379. case ')':
  380. builder.append(')');
  381. break;
  382. case '\\':
  383. builder.append('\\');
  384. break;
  385. default: {
  386. if (ch >= '0' && ch <= '7') {
  387. int octal_value = ch - '0';
  388. for (int i = 0; i < 2; i++) {
  389. auto octal_ch = consume();
  390. if (octal_ch < '0' || octal_ch > '7')
  391. break;
  392. octal_value = octal_value * 8 + (octal_ch - '0');
  393. }
  394. builder.append(static_cast<char>(octal_value));
  395. } else {
  396. builder.append(ch);
  397. }
  398. }
  399. }
  400. } else if (matches_eol()) {
  401. consume_eol();
  402. builder.append('\n');
  403. } else {
  404. builder.append(consume());
  405. }
  406. }
  407. VERIFY(opened_parens == 0);
  408. return builder.to_string();
  409. }
  410. String Parser::parse_hex_string()
  411. {
  412. consume('<');
  413. StringBuilder builder;
  414. while (true) {
  415. if (m_reader.matches('>')) {
  416. consume();
  417. return builder.to_string();
  418. } else {
  419. int hex_value = 0;
  420. for (int i = 0; i < 2; i++) {
  421. auto ch = consume();
  422. if (ch == '>') {
  423. // The hex string contains an odd number of characters, and the last character
  424. // is assumed to be '0'
  425. consume();
  426. hex_value *= 16;
  427. builder.append(static_cast<char>(hex_value));
  428. return builder.to_string();
  429. }
  430. VERIFY(isxdigit(ch));
  431. hex_value *= 16;
  432. if (ch <= '9') {
  433. hex_value += ch - '0';
  434. } else {
  435. hex_value += ch - 'A' + 10;
  436. }
  437. }
  438. builder.append(static_cast<char>(hex_value));
  439. }
  440. }
  441. }
  442. NonnullRefPtr<ArrayObject> Parser::parse_array()
  443. {
  444. consume('[');
  445. consume_whitespace();
  446. Vector<Value> values;
  447. while (!m_reader.matches(']'))
  448. values.append(parse_value());
  449. consume(']');
  450. consume_whitespace();
  451. return make_object<ArrayObject>(values);
  452. }
  453. NonnullRefPtr<DictObject> Parser::parse_dict()
  454. {
  455. consume('<');
  456. consume('<');
  457. consume_whitespace();
  458. HashMap<FlyString, Value> map;
  459. while (true) {
  460. if (m_reader.matches(">>"))
  461. break;
  462. auto name = parse_name();
  463. auto value = parse_value();
  464. map.set(name->name(), value);
  465. }
  466. consume('>');
  467. consume('>');
  468. consume_whitespace();
  469. return make_object<DictObject>(map);
  470. }
  471. RefPtr<DictObject> Parser::conditionally_parse_page_tree_node_at_offset(size_t offset)
  472. {
  473. m_reader.move_to(offset);
  474. parse_number();
  475. parse_number();
  476. VERIFY(m_reader.matches("obj"));
  477. m_reader.move_by(3);
  478. consume_whitespace();
  479. consume('<');
  480. consume('<');
  481. consume_whitespace();
  482. HashMap<FlyString, Value> map;
  483. while (true) {
  484. if (m_reader.matches(">>"))
  485. break;
  486. auto name = parse_name();
  487. auto name_string = name->name();
  488. if (!name_string.is_one_of("Type", "Parent", "Kids", "Count")) {
  489. // This is a page, not a page tree node
  490. return {};
  491. }
  492. auto value = parse_value();
  493. if (name_string == "Type") {
  494. if (!value.is_object())
  495. return {};
  496. auto type_object = value.as_object();
  497. if (!type_object->is_name())
  498. return {};
  499. auto type_name = object_cast<NameObject>(type_object);
  500. if (type_name->name() != "Pages")
  501. return {};
  502. }
  503. map.set(name->name(), value);
  504. }
  505. consume('>');
  506. consume('>');
  507. consume_whitespace();
  508. return make_object<DictObject>(map);
  509. }
  510. NonnullRefPtr<StreamObject> Parser::parse_stream(NonnullRefPtr<DictObject> dict)
  511. {
  512. VERIFY(m_reader.matches("stream"));
  513. m_reader.move_by(6);
  514. consume_eol();
  515. ReadonlyBytes bytes;
  516. auto maybe_length = dict->get("Length");
  517. if (maybe_length.has_value()) {
  518. // The PDF writer has kindly provided us with the direct length of the stream
  519. m_reader.save();
  520. auto length = m_document->resolve_to<int>(maybe_length.value());
  521. m_reader.load();
  522. bytes = m_reader.bytes().slice(m_reader.offset(), length);
  523. m_reader.move_by(length);
  524. consume_whitespace();
  525. } else {
  526. // We have to look for the endstream keyword
  527. auto stream_start = m_reader.offset();
  528. while (true) {
  529. m_reader.move_until([&] { return matches_eol(); });
  530. auto potential_stream_end = m_reader.offset();
  531. consume_eol();
  532. if (!m_reader.matches("endstream"))
  533. continue;
  534. bytes = m_reader.bytes().slice(stream_start, potential_stream_end - stream_start);
  535. break;
  536. }
  537. }
  538. m_reader.move_by(9);
  539. consume_whitespace();
  540. return make_object<StreamObject>(dict, bytes);
  541. }
  542. bool Parser::matches_eol() const
  543. {
  544. return m_reader.matches_any(0xa, 0xd);
  545. }
  546. bool Parser::matches_whitespace() const
  547. {
  548. return matches_eol() || m_reader.matches_any(0, 0x9, 0xc, ' ');
  549. }
  550. bool Parser::matches_number() const
  551. {
  552. if (m_reader.done())
  553. return false;
  554. auto ch = m_reader.peek();
  555. return isdigit(ch) || ch == '-' || ch == '+';
  556. }
  557. bool Parser::matches_delimiter() const
  558. {
  559. return m_reader.matches_any('(', ')', '<', '>', '[', ']', '{', '}', '/', '%');
  560. }
  561. bool Parser::matches_regular_character() const
  562. {
  563. return !matches_delimiter() && !matches_whitespace();
  564. }
  565. void Parser::consume_eol()
  566. {
  567. if (m_reader.matches("\r\n")) {
  568. consume(2);
  569. } else {
  570. auto consumed = consume();
  571. VERIFY(consumed == 0xd || consumed == 0xa);
  572. }
  573. }
  574. bool Parser::consume_whitespace()
  575. {
  576. bool consumed = false;
  577. while (matches_whitespace()) {
  578. consumed = true;
  579. consume();
  580. }
  581. return consumed;
  582. }
  583. char Parser::consume()
  584. {
  585. return m_reader.read();
  586. }
  587. void Parser::consume(char ch)
  588. {
  589. VERIFY(consume() == ch);
  590. }
  591. }