scanf.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618
  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 read_element_concrete {
  70. bool operator()(GenericLexer&, va_list)
  71. {
  72. return false;
  73. }
  74. };
  75. template<typename ApT, ReadKind kind>
  76. struct read_element_concrete<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 read_element_concrete<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 read_element_concrete<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 read_element_concrete<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 read_element_concrete<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 read_element_concrete<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 read_element {
  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 read_element_concrete<T, T, kind> {}(input_lexer, ap);
  234. case Char:
  235. return read_element_concrete<T, char, kind> {}(input_lexer, ap);
  236. case Short:
  237. return read_element_concrete<T, short, kind> {}(input_lexer, ap);
  238. case Long:
  239. if constexpr (IsSame<T, int>::value)
  240. return read_element_concrete<T, long, kind> {}(input_lexer, ap);
  241. if constexpr (IsSame<T, unsigned>::value)
  242. return read_element_concrete<T, unsigned, kind> {}(input_lexer, ap);
  243. if constexpr (IsSame<T, float>::value)
  244. return read_element_concrete<int, double, kind> {}(input_lexer, ap);
  245. return false;
  246. case LongLong:
  247. if constexpr (IsSame<T, int>::value)
  248. return read_element_concrete<long long, long long, kind> {}(input_lexer, ap);
  249. if constexpr (IsSame<T, unsigned>::value)
  250. return read_element_concrete<unsigned long long, unsigned long long, kind> {}(input_lexer, ap);
  251. if constexpr (IsSame<T, float>::value)
  252. return read_element_concrete<long long, double, kind> {}(input_lexer, ap);
  253. return false;
  254. case IntMax:
  255. return read_element_concrete<T, intmax_t, kind> {}(input_lexer, ap);
  256. case Size:
  257. return read_element_concrete<T, size_t, kind> {}(input_lexer, ap);
  258. case PtrDiff:
  259. return read_element_concrete<T, ptrdiff_t, kind> {}(input_lexer, ap);
  260. case LongDouble:
  261. return read_element_concrete<T, long double, kind> {}(input_lexer, ap);
  262. }
  263. }
  264. };
  265. template<>
  266. struct read_element<char*, ReadKind::Normal> {
  267. read_element(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 read_element<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. bool invert_scanlist = false;
  357. StringView scanlist;
  358. LengthModifier length_modifier { None };
  359. ConversionSpecifier conversion_specifier { Unspecified };
  360. reread_lookahead:;
  361. auto format_lookahead = format_lexer.peek();
  362. if (length_modifier == None) {
  363. switch (format_lookahead) {
  364. case 'h':
  365. if (format_lexer.peek(1) == 'h') {
  366. format_lexer.consume(2);
  367. length_modifier = Char;
  368. } else {
  369. format_lexer.consume(1);
  370. length_modifier = Short;
  371. }
  372. break;
  373. case 'l':
  374. if (format_lexer.peek(1) == 'l') {
  375. format_lexer.consume(2);
  376. length_modifier = LongLong;
  377. } else {
  378. format_lexer.consume(1);
  379. length_modifier = Long;
  380. }
  381. break;
  382. case 'j':
  383. format_lexer.consume();
  384. length_modifier = IntMax;
  385. break;
  386. case 'z':
  387. format_lexer.consume();
  388. length_modifier = Size;
  389. break;
  390. case 't':
  391. format_lexer.consume();
  392. length_modifier = PtrDiff;
  393. break;
  394. case 'L':
  395. format_lexer.consume();
  396. length_modifier = LongDouble;
  397. break;
  398. default:
  399. length_modifier = Default;
  400. break;
  401. }
  402. goto reread_lookahead;
  403. }
  404. if (conversion_specifier == Unspecified) {
  405. switch (format_lookahead) {
  406. case 'd':
  407. format_lexer.consume();
  408. conversion_specifier = Decimal;
  409. break;
  410. case 'i':
  411. format_lexer.consume();
  412. conversion_specifier = Integer;
  413. break;
  414. case 'o':
  415. format_lexer.consume();
  416. conversion_specifier = Octal;
  417. break;
  418. case 'u':
  419. format_lexer.consume();
  420. conversion_specifier = Unsigned;
  421. break;
  422. case 'x':
  423. format_lexer.consume();
  424. conversion_specifier = Hex;
  425. break;
  426. case 'a':
  427. case 'e':
  428. case 'f':
  429. case 'g':
  430. format_lexer.consume();
  431. conversion_specifier = Floating;
  432. break;
  433. case 's':
  434. format_lexer.consume();
  435. conversion_specifier = String;
  436. break;
  437. case '[':
  438. format_lexer.consume();
  439. scanlist = format_lexer.consume_until(']');
  440. if (scanlist.starts_with('^')) {
  441. scanlist = scanlist.substring_view(1);
  442. invert_scanlist = true;
  443. }
  444. conversion_specifier = UseScanList;
  445. break;
  446. case 'c':
  447. format_lexer.consume();
  448. conversion_specifier = Character;
  449. break;
  450. case 'p':
  451. format_lexer.consume();
  452. conversion_specifier = Pointer;
  453. break;
  454. case 'n':
  455. format_lexer.consume();
  456. conversion_specifier = OutputNumberOfBytes;
  457. break;
  458. case 'C':
  459. format_lexer.consume();
  460. length_modifier = Long;
  461. conversion_specifier = Character;
  462. break;
  463. case 'S':
  464. format_lexer.consume();
  465. length_modifier = Long;
  466. conversion_specifier = String;
  467. break;
  468. default:
  469. format_lexer.consume();
  470. conversion_specifier = Invalid;
  471. break;
  472. }
  473. }
  474. // Now try to read.
  475. switch (conversion_specifier) {
  476. case Invalid:
  477. case Unspecified:
  478. default:
  479. // "undefined behaviour", let's be nice and crash.
  480. dbgln("Invalid conversion specifier {} in scanf!", (int)conversion_specifier);
  481. VERIFY_NOT_REACHED();
  482. case Decimal:
  483. if (!read_element<int, ReadKind::Normal> {}(length_modifier, input_lexer, (va_list*)&ap))
  484. format_lexer.consume_all();
  485. else
  486. ++elements_matched;
  487. break;
  488. case Integer:
  489. if (!read_element<int, ReadKind::Infer> {}(length_modifier, input_lexer, (va_list*)&ap))
  490. format_lexer.consume_all();
  491. else
  492. ++elements_matched;
  493. break;
  494. case Octal:
  495. if (!read_element<unsigned, ReadKind::Octal> {}(length_modifier, input_lexer, (va_list*)&ap))
  496. format_lexer.consume_all();
  497. else
  498. ++elements_matched;
  499. break;
  500. case Unsigned:
  501. if (!read_element<unsigned, ReadKind::Normal> {}(length_modifier, input_lexer, (va_list*)&ap))
  502. format_lexer.consume_all();
  503. else
  504. ++elements_matched;
  505. break;
  506. case Hex:
  507. if (!read_element<unsigned, ReadKind::Hex> {}(length_modifier, input_lexer, (va_list*)&ap))
  508. format_lexer.consume_all();
  509. else
  510. ++elements_matched;
  511. break;
  512. case Floating:
  513. if (!read_element<float, ReadKind::Normal> {}(length_modifier, input_lexer, (va_list*)&ap))
  514. format_lexer.consume_all();
  515. else
  516. ++elements_matched;
  517. break;
  518. case String:
  519. if (!read_element<char*, ReadKind::Normal> {}(length_modifier, input_lexer, (va_list*)&ap))
  520. format_lexer.consume_all();
  521. else
  522. ++elements_matched;
  523. break;
  524. case UseScanList:
  525. if (!read_element<char*, ReadKind::Normal> { scanlist, invert_scanlist }(length_modifier, input_lexer, (va_list*)&ap))
  526. format_lexer.consume_all();
  527. else
  528. ++elements_matched;
  529. break;
  530. case Character:
  531. if (!read_element<char, ReadKind::Normal> {}(length_modifier, input_lexer, (va_list*)&ap))
  532. format_lexer.consume_all();
  533. else
  534. ++elements_matched;
  535. break;
  536. case Pointer:
  537. if (!read_element<void*, ReadKind::Normal> {}(length_modifier, input_lexer, (va_list*)&ap))
  538. format_lexer.consume_all();
  539. else
  540. ++elements_matched;
  541. break;
  542. case OutputNumberOfBytes: {
  543. auto* ptr = va_arg(ap, int*);
  544. *ptr = input_lexer.tell();
  545. ++elements_matched;
  546. break;
  547. }
  548. }
  549. }
  550. return elements_matched;
  551. }