scanf.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626
  1. /*
  2. * Copyright (c) 2021, the SerenityOS developers.
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include <AK/Assertions.h>
  27. #include <AK/Format.h>
  28. #include <AK/GenericLexer.h>
  29. #include <AK/StdLibExtras.h>
  30. #include <ctype.h>
  31. #include <stdarg.h>
  32. #include <stdio.h>
  33. #include <stdlib.h>
  34. #include <string.h>
  35. enum LengthModifier {
  36. None,
  37. Default,
  38. Char,
  39. Short,
  40. Long,
  41. LongLong,
  42. IntMax,
  43. Size,
  44. PtrDiff,
  45. LongDouble,
  46. };
  47. enum ConversionSpecifier {
  48. Unspecified,
  49. Decimal,
  50. Integer,
  51. Octal,
  52. Unsigned,
  53. Hex,
  54. Floating,
  55. String,
  56. UseScanList,
  57. Character,
  58. Pointer,
  59. OutputNumberOfBytes,
  60. Invalid,
  61. };
  62. enum class ReadKind {
  63. Normal,
  64. Octal,
  65. Hex,
  66. Infer,
  67. };
  68. template<typename T, typename ApT, ReadKind kind = ReadKind::Normal>
  69. struct ReadElementConcrete {
  70. bool operator()(GenericLexer&, va_list)
  71. {
  72. return false;
  73. }
  74. };
  75. template<typename ApT, ReadKind kind>
  76. struct ReadElementConcrete<int, ApT, kind> {
  77. bool operator()(GenericLexer& lexer, va_list* ap)
  78. {
  79. lexer.ignore_while(isspace);
  80. auto* ptr = va_arg(*ap, ApT*);
  81. long value = 0;
  82. char* endptr = nullptr;
  83. auto nptr = lexer.remaining().characters_without_null_termination();
  84. if constexpr (kind == ReadKind::Normal)
  85. value = strtol(nptr, &endptr, 10);
  86. if constexpr (kind == ReadKind::Octal)
  87. value = strtol(nptr, &endptr, 8);
  88. if constexpr (kind == ReadKind::Hex)
  89. value = strtol(nptr, &endptr, 16);
  90. if constexpr (kind == ReadKind::Infer)
  91. value = strtol(nptr, &endptr, 0);
  92. if (!endptr)
  93. return false;
  94. if (endptr == nptr)
  95. return false;
  96. auto diff = endptr - nptr;
  97. VERIFY(diff > 0);
  98. lexer.ignore((size_t)diff);
  99. *ptr = value;
  100. return true;
  101. }
  102. };
  103. template<typename ApT, ReadKind kind>
  104. struct ReadElementConcrete<char, ApT, kind> {
  105. bool operator()(GenericLexer& lexer, va_list* ap)
  106. {
  107. static_assert(kind == ReadKind::Normal, "Can't read a non-normal character");
  108. auto* ptr = va_arg(*ap, ApT*);
  109. if (lexer.is_eof())
  110. return false;
  111. auto ch = lexer.consume();
  112. *ptr = ch;
  113. return true;
  114. }
  115. };
  116. template<typename ApT, ReadKind kind>
  117. struct ReadElementConcrete<unsigned, ApT, kind> {
  118. bool operator()(GenericLexer& lexer, va_list* ap)
  119. {
  120. lexer.ignore_while(isspace);
  121. auto* ptr = va_arg(*ap, ApT*);
  122. unsigned long value = 0;
  123. char* endptr = nullptr;
  124. auto nptr = lexer.remaining().characters_without_null_termination();
  125. if constexpr (kind == ReadKind::Normal)
  126. value = strtoul(nptr, &endptr, 10);
  127. if constexpr (kind == ReadKind::Octal)
  128. value = strtoul(nptr, &endptr, 8);
  129. if constexpr (kind == ReadKind::Hex)
  130. value = strtoul(nptr, &endptr, 16);
  131. if constexpr (kind == ReadKind::Infer)
  132. value = strtoul(nptr, &endptr, 0);
  133. if (!endptr)
  134. return false;
  135. if (endptr == nptr)
  136. return false;
  137. auto diff = endptr - nptr;
  138. VERIFY(diff > 0);
  139. lexer.ignore((size_t)diff);
  140. *ptr = value;
  141. return true;
  142. }
  143. };
  144. template<typename ApT, ReadKind kind>
  145. struct ReadElementConcrete<long long, ApT, kind> {
  146. bool operator()(GenericLexer& lexer, va_list* ap)
  147. {
  148. lexer.ignore_while(isspace);
  149. auto* ptr = va_arg(*ap, ApT*);
  150. long long value = 0;
  151. char* endptr = nullptr;
  152. auto nptr = lexer.remaining().characters_without_null_termination();
  153. if constexpr (kind == ReadKind::Normal)
  154. value = strtoll(nptr, &endptr, 10);
  155. if constexpr (kind == ReadKind::Octal)
  156. value = strtoll(nptr, &endptr, 8);
  157. if constexpr (kind == ReadKind::Hex)
  158. value = strtoll(nptr, &endptr, 16);
  159. if constexpr (kind == ReadKind::Infer)
  160. value = strtoll(nptr, &endptr, 0);
  161. if (!endptr)
  162. return false;
  163. if (endptr == nptr)
  164. return false;
  165. auto diff = endptr - nptr;
  166. VERIFY(diff > 0);
  167. lexer.ignore((size_t)diff);
  168. *ptr = value;
  169. return true;
  170. }
  171. };
  172. template<typename ApT, ReadKind kind>
  173. struct ReadElementConcrete<unsigned long long, ApT, kind> {
  174. bool operator()(GenericLexer& lexer, va_list* ap)
  175. {
  176. lexer.ignore_while(isspace);
  177. auto* ptr = va_arg(*ap, ApT*);
  178. unsigned long long value = 0;
  179. char* endptr = nullptr;
  180. auto nptr = lexer.remaining().characters_without_null_termination();
  181. if constexpr (kind == ReadKind::Normal)
  182. value = strtoull(nptr, &endptr, 10);
  183. if constexpr (kind == ReadKind::Octal)
  184. value = strtoull(nptr, &endptr, 8);
  185. if constexpr (kind == ReadKind::Hex)
  186. value = strtoull(nptr, &endptr, 16);
  187. if constexpr (kind == ReadKind::Infer)
  188. value = strtoull(nptr, &endptr, 0);
  189. if (!endptr)
  190. return false;
  191. if (endptr == nptr)
  192. return false;
  193. auto diff = endptr - nptr;
  194. VERIFY(diff > 0);
  195. lexer.ignore((size_t)diff);
  196. *ptr = value;
  197. return true;
  198. }
  199. };
  200. template<typename ApT, ReadKind kind>
  201. struct ReadElementConcrete<float, ApT, kind> {
  202. bool operator()(GenericLexer& lexer, va_list* ap)
  203. {
  204. lexer.ignore_while(isspace);
  205. auto* ptr = va_arg(*ap, ApT*);
  206. double value = 0;
  207. char* endptr = nullptr;
  208. auto nptr = lexer.remaining().characters_without_null_termination();
  209. if constexpr (kind == ReadKind::Normal)
  210. value = strtod(nptr, &endptr);
  211. else
  212. return false;
  213. if (!endptr)
  214. return false;
  215. if (endptr == nptr)
  216. return false;
  217. auto diff = endptr - nptr;
  218. VERIFY(diff > 0);
  219. lexer.ignore((size_t)diff);
  220. *ptr = value;
  221. return true;
  222. }
  223. };
  224. template<typename T, ReadKind kind>
  225. struct ReadElement {
  226. bool operator()(LengthModifier length_modifier, GenericLexer& input_lexer, va_list* ap)
  227. {
  228. switch (length_modifier) {
  229. default:
  230. case None:
  231. VERIFY_NOT_REACHED();
  232. case Default:
  233. return ReadElementConcrete<T, T, kind> {}(input_lexer, ap);
  234. case Char:
  235. return ReadElementConcrete<T, char, kind> {}(input_lexer, ap);
  236. case Short:
  237. return ReadElementConcrete<T, short, kind> {}(input_lexer, ap);
  238. case Long:
  239. if constexpr (IsSame<T, int>)
  240. return ReadElementConcrete<T, long, kind> {}(input_lexer, ap);
  241. if constexpr (IsSame<T, unsigned>)
  242. return ReadElementConcrete<T, unsigned, kind> {}(input_lexer, ap);
  243. if constexpr (IsSame<T, float>)
  244. return ReadElementConcrete<int, double, kind> {}(input_lexer, ap);
  245. return false;
  246. case LongLong:
  247. if constexpr (IsSame<T, int>)
  248. return ReadElementConcrete<long long, long long, kind> {}(input_lexer, ap);
  249. if constexpr (IsSame<T, unsigned>)
  250. return ReadElementConcrete<unsigned long long, unsigned long long, kind> {}(input_lexer, ap);
  251. if constexpr (IsSame<T, float>)
  252. return ReadElementConcrete<long long, double, kind> {}(input_lexer, ap);
  253. return false;
  254. case IntMax:
  255. return ReadElementConcrete<T, intmax_t, kind> {}(input_lexer, ap);
  256. case Size:
  257. return ReadElementConcrete<T, size_t, kind> {}(input_lexer, ap);
  258. case PtrDiff:
  259. return ReadElementConcrete<T, ptrdiff_t, kind> {}(input_lexer, ap);
  260. case LongDouble:
  261. return ReadElementConcrete<T, long double, kind> {}(input_lexer, ap);
  262. }
  263. }
  264. };
  265. template<>
  266. struct ReadElement<char*, ReadKind::Normal> {
  267. ReadElement(StringView scan_set = {}, bool invert = false)
  268. : scan_set(scan_set.is_null() ? " \t\n\f\r" : scan_set)
  269. , invert(scan_set.is_null() ? true : invert)
  270. , was_null(scan_set.is_null())
  271. {
  272. }
  273. bool operator()(LengthModifier length_modifier, GenericLexer& input_lexer, va_list* ap)
  274. {
  275. // FIXME: Implement wide strings and such.
  276. if (length_modifier != LengthModifier::Default)
  277. return false;
  278. if (was_null)
  279. input_lexer.ignore_while(isspace);
  280. auto* ptr = va_arg(*ap, char*);
  281. auto str = input_lexer.consume_while([this](auto c) { return this->matches(c); });
  282. if (str.is_empty())
  283. return false;
  284. memcpy(ptr, str.characters_without_null_termination(), str.length());
  285. ptr[str.length()] = 0;
  286. return true;
  287. }
  288. private:
  289. bool matches(char c) const
  290. {
  291. return invert ^ scan_set.contains(c);
  292. }
  293. const StringView scan_set;
  294. bool invert { false };
  295. bool was_null { false };
  296. };
  297. template<>
  298. struct ReadElement<void*, ReadKind::Normal> {
  299. bool operator()(LengthModifier length_modifier, GenericLexer& input_lexer, va_list* ap)
  300. {
  301. if (length_modifier != LengthModifier::Default)
  302. return false;
  303. input_lexer.ignore_while(isspace);
  304. auto* ptr = va_arg(*ap, void**);
  305. auto str = input_lexer.consume_while([this](auto c) { return this->should_consume(c); });
  306. if (count != 8) {
  307. fail:;
  308. for (size_t i = 0; i < count; ++i)
  309. input_lexer.retreat();
  310. return false;
  311. }
  312. char buf[9] { 0 };
  313. memcpy(buf, str.characters_without_null_termination(), 8);
  314. buf[8] = 0;
  315. char* endptr = nullptr;
  316. auto value = strtoull(buf, &endptr, 16);
  317. if (endptr != &buf[8])
  318. goto fail;
  319. memcpy(ptr, &value, sizeof(value));
  320. return true;
  321. }
  322. private:
  323. bool should_consume(char c)
  324. {
  325. if (count == 8)
  326. return false;
  327. if (!isxdigit(c))
  328. return false;
  329. ++count;
  330. return true;
  331. }
  332. size_t count { 0 };
  333. };
  334. extern "C" int vsscanf(const char* input, const char* format, va_list ap)
  335. {
  336. GenericLexer format_lexer { format };
  337. GenericLexer input_lexer { input };
  338. int elements_matched = 0;
  339. while (!format_lexer.is_eof()) {
  340. format_lexer.ignore_while(isspace);
  341. if (!format_lexer.next_is('%')) {
  342. read_one_literal:;
  343. input_lexer.ignore_while(isspace);
  344. if (format_lexer.is_eof())
  345. break;
  346. auto next_char = format_lexer.consume();
  347. if (!input_lexer.consume_specific(next_char))
  348. return elements_matched;
  349. continue;
  350. }
  351. if (format_lexer.next_is("%%")) {
  352. format_lexer.ignore();
  353. goto read_one_literal;
  354. }
  355. format_lexer.ignore(); // '%'
  356. // Parse width specification
  357. [[maybe_unused]] int width_specifier = 0;
  358. if (format_lexer.next_is(isdigit)) {
  359. auto width_digits = format_lexer.consume_while([](char c) { return isdigit(c); });
  360. width_specifier = width_digits.to_int().value();
  361. // FIXME: Actually use width specifier
  362. }
  363. bool invert_scanlist = false;
  364. StringView scanlist;
  365. LengthModifier length_modifier { None };
  366. ConversionSpecifier conversion_specifier { Unspecified };
  367. reread_lookahead:;
  368. auto format_lookahead = format_lexer.peek();
  369. if (length_modifier == None) {
  370. switch (format_lookahead) {
  371. case 'h':
  372. if (format_lexer.peek(1) == 'h') {
  373. format_lexer.consume(2);
  374. length_modifier = Char;
  375. } else {
  376. format_lexer.consume(1);
  377. length_modifier = Short;
  378. }
  379. break;
  380. case 'l':
  381. if (format_lexer.peek(1) == 'l') {
  382. format_lexer.consume(2);
  383. length_modifier = LongLong;
  384. } else {
  385. format_lexer.consume(1);
  386. length_modifier = Long;
  387. }
  388. break;
  389. case 'j':
  390. format_lexer.consume();
  391. length_modifier = IntMax;
  392. break;
  393. case 'z':
  394. format_lexer.consume();
  395. length_modifier = Size;
  396. break;
  397. case 't':
  398. format_lexer.consume();
  399. length_modifier = PtrDiff;
  400. break;
  401. case 'L':
  402. format_lexer.consume();
  403. length_modifier = LongDouble;
  404. break;
  405. default:
  406. length_modifier = Default;
  407. break;
  408. }
  409. goto reread_lookahead;
  410. }
  411. if (conversion_specifier == Unspecified) {
  412. switch (format_lookahead) {
  413. case 'd':
  414. format_lexer.consume();
  415. conversion_specifier = Decimal;
  416. break;
  417. case 'i':
  418. format_lexer.consume();
  419. conversion_specifier = Integer;
  420. break;
  421. case 'o':
  422. format_lexer.consume();
  423. conversion_specifier = Octal;
  424. break;
  425. case 'u':
  426. format_lexer.consume();
  427. conversion_specifier = Unsigned;
  428. break;
  429. case 'x':
  430. format_lexer.consume();
  431. conversion_specifier = Hex;
  432. break;
  433. case 'a':
  434. case 'e':
  435. case 'f':
  436. case 'g':
  437. format_lexer.consume();
  438. conversion_specifier = Floating;
  439. break;
  440. case 's':
  441. format_lexer.consume();
  442. conversion_specifier = String;
  443. break;
  444. case '[':
  445. format_lexer.consume();
  446. scanlist = format_lexer.consume_until(']');
  447. if (scanlist.starts_with('^')) {
  448. scanlist = scanlist.substring_view(1);
  449. invert_scanlist = true;
  450. }
  451. conversion_specifier = UseScanList;
  452. break;
  453. case 'c':
  454. format_lexer.consume();
  455. conversion_specifier = Character;
  456. break;
  457. case 'p':
  458. format_lexer.consume();
  459. conversion_specifier = Pointer;
  460. break;
  461. case 'n':
  462. format_lexer.consume();
  463. conversion_specifier = OutputNumberOfBytes;
  464. break;
  465. case 'C':
  466. format_lexer.consume();
  467. length_modifier = Long;
  468. conversion_specifier = Character;
  469. break;
  470. case 'S':
  471. format_lexer.consume();
  472. length_modifier = Long;
  473. conversion_specifier = String;
  474. break;
  475. default:
  476. format_lexer.consume();
  477. conversion_specifier = Invalid;
  478. break;
  479. }
  480. }
  481. // Now try to read.
  482. switch (conversion_specifier) {
  483. case Invalid:
  484. case Unspecified:
  485. default:
  486. // "undefined behaviour", let's be nice and crash.
  487. dbgln("Invalid conversion specifier {} in scanf!", (int)conversion_specifier);
  488. VERIFY_NOT_REACHED();
  489. case Decimal:
  490. if (!ReadElement<int, ReadKind::Normal> {}(length_modifier, input_lexer, (va_list*)&ap))
  491. format_lexer.consume_all();
  492. else
  493. ++elements_matched;
  494. break;
  495. case Integer:
  496. if (!ReadElement<int, ReadKind::Infer> {}(length_modifier, input_lexer, (va_list*)&ap))
  497. format_lexer.consume_all();
  498. else
  499. ++elements_matched;
  500. break;
  501. case Octal:
  502. if (!ReadElement<unsigned, ReadKind::Octal> {}(length_modifier, input_lexer, (va_list*)&ap))
  503. format_lexer.consume_all();
  504. else
  505. ++elements_matched;
  506. break;
  507. case Unsigned:
  508. if (!ReadElement<unsigned, ReadKind::Normal> {}(length_modifier, input_lexer, (va_list*)&ap))
  509. format_lexer.consume_all();
  510. else
  511. ++elements_matched;
  512. break;
  513. case Hex:
  514. if (!ReadElement<unsigned, ReadKind::Hex> {}(length_modifier, input_lexer, (va_list*)&ap))
  515. format_lexer.consume_all();
  516. else
  517. ++elements_matched;
  518. break;
  519. case Floating:
  520. if (!ReadElement<float, ReadKind::Normal> {}(length_modifier, input_lexer, (va_list*)&ap))
  521. format_lexer.consume_all();
  522. else
  523. ++elements_matched;
  524. break;
  525. case String:
  526. if (!ReadElement<char*, ReadKind::Normal> {}(length_modifier, input_lexer, (va_list*)&ap))
  527. format_lexer.consume_all();
  528. else
  529. ++elements_matched;
  530. break;
  531. case UseScanList:
  532. if (!ReadElement<char*, ReadKind::Normal> { scanlist, invert_scanlist }(length_modifier, input_lexer, (va_list*)&ap))
  533. format_lexer.consume_all();
  534. else
  535. ++elements_matched;
  536. break;
  537. case Character:
  538. if (!ReadElement<char, ReadKind::Normal> {}(length_modifier, input_lexer, (va_list*)&ap))
  539. format_lexer.consume_all();
  540. else
  541. ++elements_matched;
  542. break;
  543. case Pointer:
  544. if (!ReadElement<void*, ReadKind::Normal> {}(length_modifier, input_lexer, (va_list*)&ap))
  545. format_lexer.consume_all();
  546. else
  547. ++elements_matched;
  548. break;
  549. case OutputNumberOfBytes: {
  550. auto* ptr = va_arg(ap, int*);
  551. *ptr = input_lexer.tell();
  552. ++elements_matched;
  553. break;
  554. }
  555. }
  556. }
  557. return elements_matched;
  558. }