stdlib.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  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/HashMap.h>
  28. #include <AK/Noncopyable.h>
  29. #include <AK/StdLibExtras.h>
  30. #include <AK/Types.h>
  31. #include <AK/Utf8View.h>
  32. #include <Kernel/API/Syscall.h>
  33. #include <alloca.h>
  34. #include <assert.h>
  35. #include <ctype.h>
  36. #include <errno.h>
  37. #include <signal.h>
  38. #include <spawn.h>
  39. #include <stdio.h>
  40. #include <stdlib.h>
  41. #include <string.h>
  42. #include <sys/internals.h>
  43. #include <sys/mman.h>
  44. #include <sys/stat.h>
  45. #include <sys/wait.h>
  46. #include <unistd.h>
  47. static void strtons(const char* str, char** endptr)
  48. {
  49. assert(endptr);
  50. char* ptr = const_cast<char*>(str);
  51. while (isspace(*ptr)) {
  52. ptr += 1;
  53. }
  54. *endptr = ptr;
  55. }
  56. enum Sign {
  57. Negative,
  58. Positive,
  59. };
  60. static Sign strtosign(const char* str, char** endptr)
  61. {
  62. assert(endptr);
  63. if (*str == '+') {
  64. *endptr = const_cast<char*>(str + 1);
  65. return Sign::Positive;
  66. } else if (*str == '-') {
  67. *endptr = const_cast<char*>(str + 1);
  68. return Sign::Negative;
  69. } else {
  70. *endptr = const_cast<char*>(str);
  71. return Sign::Positive;
  72. }
  73. }
  74. enum DigitConsumeDecision {
  75. Consumed,
  76. PosOverflow,
  77. NegOverflow,
  78. Invalid,
  79. };
  80. template<typename T, T min_value, T max_value>
  81. class NumParser {
  82. AK_MAKE_NONMOVABLE(NumParser);
  83. public:
  84. NumParser(Sign sign, int base)
  85. : m_base(base)
  86. , m_num(0)
  87. , m_sign(sign)
  88. {
  89. m_cutoff = positive() ? (max_value / base) : (min_value / base);
  90. m_max_digit_after_cutoff = positive() ? (max_value % base) : (min_value % base);
  91. }
  92. int parse_digit(char ch)
  93. {
  94. int digit;
  95. if (isdigit(ch))
  96. digit = ch - '0';
  97. else if (islower(ch))
  98. digit = ch - ('a' - 10);
  99. else if (isupper(ch))
  100. digit = ch - ('A' - 10);
  101. else
  102. return -1;
  103. if (static_cast<T>(digit) >= m_base)
  104. return -1;
  105. return digit;
  106. }
  107. DigitConsumeDecision consume(char ch)
  108. {
  109. int digit = parse_digit(ch);
  110. if (digit == -1)
  111. return DigitConsumeDecision::Invalid;
  112. if (!can_append_digit(digit)) {
  113. if (m_sign != Sign::Negative) {
  114. return DigitConsumeDecision::PosOverflow;
  115. } else {
  116. return DigitConsumeDecision::NegOverflow;
  117. }
  118. }
  119. m_num *= m_base;
  120. m_num += positive() ? digit : -digit;
  121. return DigitConsumeDecision::Consumed;
  122. }
  123. T number() const { return m_num; };
  124. private:
  125. bool can_append_digit(int digit)
  126. {
  127. const bool is_below_cutoff = positive() ? (m_num < m_cutoff) : (m_num > m_cutoff);
  128. if (is_below_cutoff) {
  129. return true;
  130. } else {
  131. return m_num == m_cutoff && digit < m_max_digit_after_cutoff;
  132. }
  133. }
  134. bool positive() const
  135. {
  136. return m_sign != Sign::Negative;
  137. }
  138. const T m_base;
  139. T m_num;
  140. T m_cutoff;
  141. int m_max_digit_after_cutoff;
  142. Sign m_sign;
  143. };
  144. typedef NumParser<int, INT_MIN, INT_MAX> IntParser;
  145. typedef NumParser<long long, LONG_LONG_MIN, LONG_LONG_MAX> LongLongParser;
  146. typedef NumParser<unsigned long long, 0ULL, ULONG_LONG_MAX> ULongLongParser;
  147. static bool is_either(char* str, int offset, char lower, char upper)
  148. {
  149. char ch = *(str + offset);
  150. return ch == lower || ch == upper;
  151. }
  152. __attribute__((warn_unused_result)) int __generate_unique_filename(char* pattern)
  153. {
  154. size_t length = strlen(pattern);
  155. if (length < 6 || memcmp(pattern + length - 6, "XXXXXX", 6)) {
  156. errno = EINVAL;
  157. return -1;
  158. }
  159. size_t start = length - 6;
  160. static constexpr char random_characters[] = "abcdefghijklmnopqrstuvwxyz0123456789";
  161. for (int attempt = 0; attempt < 100; ++attempt) {
  162. for (int i = 0; i < 6; ++i)
  163. pattern[start + i] = random_characters[(arc4random() % (sizeof(random_characters) - 1))];
  164. struct stat st;
  165. int rc = lstat(pattern, &st);
  166. if (rc < 0 && errno == ENOENT)
  167. return 0;
  168. }
  169. errno = EEXIST;
  170. return -1;
  171. }
  172. extern "C" {
  173. void exit(int status)
  174. {
  175. __cxa_finalize(nullptr);
  176. if (getenv("LIBC_DUMP_MALLOC_STATS"))
  177. serenity_dump_malloc_stats();
  178. extern void _fini();
  179. _fini();
  180. fflush(stdout);
  181. fflush(stderr);
  182. _exit(status);
  183. }
  184. static void __atexit_to_cxa_atexit(void* handler)
  185. {
  186. reinterpret_cast<void (*)()>(handler)();
  187. }
  188. int atexit(void (*handler)())
  189. {
  190. return __cxa_atexit(__atexit_to_cxa_atexit, (void*)handler, nullptr);
  191. }
  192. void abort()
  193. {
  194. // For starters, send ourselves a SIGABRT.
  195. raise(SIGABRT);
  196. // If that didn't kill us, try harder.
  197. raise(SIGKILL);
  198. _exit(127);
  199. }
  200. static HashTable<const char*> s_malloced_environment_variables;
  201. static void free_environment_variable_if_needed(const char* var)
  202. {
  203. if (!s_malloced_environment_variables.contains(var))
  204. return;
  205. free(const_cast<char*>(var));
  206. s_malloced_environment_variables.remove(var);
  207. }
  208. char* getenv(const char* name)
  209. {
  210. size_t vl = strlen(name);
  211. for (size_t i = 0; environ[i]; ++i) {
  212. const char* decl = environ[i];
  213. char* eq = strchr(decl, '=');
  214. if (!eq)
  215. continue;
  216. size_t varLength = eq - decl;
  217. if (vl != varLength)
  218. continue;
  219. if (strncmp(decl, name, varLength) == 0) {
  220. return eq + 1;
  221. }
  222. }
  223. return nullptr;
  224. }
  225. int unsetenv(const char* name)
  226. {
  227. auto new_var_len = strlen(name);
  228. size_t environ_size = 0;
  229. int skip = -1;
  230. for (; environ[environ_size]; ++environ_size) {
  231. char* old_var = environ[environ_size];
  232. char* old_eq = strchr(old_var, '=');
  233. ASSERT(old_eq);
  234. size_t old_var_len = old_eq - old_var;
  235. if (new_var_len != old_var_len)
  236. continue; // can't match
  237. if (strncmp(name, old_var, new_var_len) == 0)
  238. skip = environ_size;
  239. }
  240. if (skip == -1)
  241. return 0; // not found: no failure.
  242. // Shuffle the existing array down by one.
  243. memmove(&environ[skip], &environ[skip + 1], ((environ_size - 1) - skip) * sizeof(environ[0]));
  244. environ[environ_size - 1] = nullptr;
  245. free_environment_variable_if_needed(name);
  246. return 0;
  247. }
  248. int clearenv()
  249. {
  250. size_t environ_size = 0;
  251. for (; environ[environ_size]; ++environ_size) {
  252. environ[environ_size] = NULL;
  253. }
  254. *environ = NULL;
  255. return 0;
  256. }
  257. int setenv(const char* name, const char* value, int overwrite)
  258. {
  259. if (!overwrite && getenv(name))
  260. return 0;
  261. auto length = strlen(name) + strlen(value) + 2;
  262. auto* var = (char*)malloc(length);
  263. snprintf(var, length, "%s=%s", name, value);
  264. s_malloced_environment_variables.set(var);
  265. return putenv(var);
  266. }
  267. int putenv(char* new_var)
  268. {
  269. char* new_eq = strchr(new_var, '=');
  270. if (!new_eq)
  271. return unsetenv(new_var);
  272. auto new_var_len = new_eq - new_var;
  273. int environ_size = 0;
  274. for (; environ[environ_size]; ++environ_size) {
  275. char* old_var = environ[environ_size];
  276. char* old_eq = strchr(old_var, '=');
  277. ASSERT(old_eq);
  278. auto old_var_len = old_eq - old_var;
  279. if (new_var_len != old_var_len)
  280. continue; // can't match
  281. if (strncmp(new_var, old_var, new_var_len) == 0) {
  282. free_environment_variable_if_needed(old_var);
  283. environ[environ_size] = new_var;
  284. return 0;
  285. }
  286. }
  287. // At this point, we need to append the new var.
  288. // 2 here: one for the new var, one for the sentinel value.
  289. char** new_environ = (char**)malloc((environ_size + 2) * sizeof(char*));
  290. if (new_environ == nullptr) {
  291. errno = ENOMEM;
  292. return -1;
  293. }
  294. for (int i = 0; environ[i]; ++i) {
  295. new_environ[i] = environ[i];
  296. }
  297. new_environ[environ_size] = new_var;
  298. new_environ[environ_size + 1] = nullptr;
  299. // swap new and old
  300. // note that the initial environ is not heap allocated!
  301. extern bool __environ_is_malloced;
  302. if (__environ_is_malloced)
  303. free(environ);
  304. __environ_is_malloced = true;
  305. environ = new_environ;
  306. return 0;
  307. }
  308. double strtod(const char* str, char** endptr)
  309. {
  310. // Parse spaces, sign, and base
  311. char* parse_ptr = const_cast<char*>(str);
  312. strtons(parse_ptr, &parse_ptr);
  313. const Sign sign = strtosign(parse_ptr, &parse_ptr);
  314. // Parse inf/nan, if applicable.
  315. if (is_either(parse_ptr, 0, 'i', 'I')) {
  316. if (is_either(parse_ptr, 1, 'n', 'N')) {
  317. if (is_either(parse_ptr, 2, 'f', 'F')) {
  318. parse_ptr += 3;
  319. if (is_either(parse_ptr, 0, 'i', 'I')) {
  320. if (is_either(parse_ptr, 1, 'n', 'N')) {
  321. if (is_either(parse_ptr, 2, 'i', 'I')) {
  322. if (is_either(parse_ptr, 3, 't', 'T')) {
  323. if (is_either(parse_ptr, 4, 'y', 'Y')) {
  324. parse_ptr += 5;
  325. }
  326. }
  327. }
  328. }
  329. }
  330. if (endptr)
  331. *endptr = parse_ptr;
  332. // Don't set errno to ERANGE here:
  333. // The caller may want to distinguish between "input is
  334. // literal infinity" and "input is not literal infinity
  335. // but did not fit into double".
  336. if (sign != Sign::Negative) {
  337. return __builtin_huge_val();
  338. } else {
  339. return -__builtin_huge_val();
  340. }
  341. }
  342. }
  343. }
  344. if (is_either(parse_ptr, 0, 'n', 'N')) {
  345. if (is_either(parse_ptr, 1, 'a', 'A')) {
  346. if (is_either(parse_ptr, 2, 'n', 'N')) {
  347. if (endptr)
  348. *endptr = parse_ptr + 3;
  349. errno = ERANGE;
  350. if (sign != Sign::Negative) {
  351. return __builtin_nan("");
  352. } else {
  353. return -__builtin_nan("");
  354. }
  355. }
  356. }
  357. }
  358. // Parse base
  359. char exponent_lower;
  360. char exponent_upper;
  361. int base = 10;
  362. if (*parse_ptr == '0') {
  363. const char base_ch = *(parse_ptr + 1);
  364. if (base_ch == 'x' || base_ch == 'X') {
  365. base = 16;
  366. parse_ptr += 2;
  367. }
  368. }
  369. if (base == 10) {
  370. exponent_lower = 'e';
  371. exponent_upper = 'E';
  372. } else {
  373. exponent_lower = 'p';
  374. exponent_upper = 'P';
  375. }
  376. // Parse "digits", possibly keeping track of the exponent offset.
  377. // We parse the most significant digits and the position in the
  378. // base-`base` representation separately. This allows us to handle
  379. // numbers like `0.0000000000000000000000000000000000001234` or
  380. // `1234567890123456789012345678901234567890` with ease.
  381. LongLongParser digits { sign, base };
  382. bool digits_usable = false;
  383. bool should_continue = true;
  384. bool digits_overflow = false;
  385. bool after_decimal = false;
  386. int exponent = 0;
  387. do {
  388. if (!after_decimal && *parse_ptr == '.') {
  389. after_decimal = true;
  390. parse_ptr += 1;
  391. continue;
  392. }
  393. bool is_a_digit;
  394. if (digits_overflow) {
  395. is_a_digit = digits.parse_digit(*parse_ptr) != -1;
  396. } else {
  397. DigitConsumeDecision decision = digits.consume(*parse_ptr);
  398. switch (decision) {
  399. case DigitConsumeDecision::Consumed:
  400. is_a_digit = true;
  401. // The very first actual digit must pass here:
  402. digits_usable = true;
  403. break;
  404. case DigitConsumeDecision::PosOverflow:
  405. case DigitConsumeDecision::NegOverflow:
  406. is_a_digit = true;
  407. digits_overflow = true;
  408. break;
  409. case DigitConsumeDecision::Invalid:
  410. is_a_digit = false;
  411. break;
  412. default:
  413. ASSERT_NOT_REACHED();
  414. }
  415. }
  416. if (is_a_digit) {
  417. exponent -= after_decimal ? 1 : 0;
  418. exponent += digits_overflow ? 1 : 0;
  419. }
  420. should_continue = is_a_digit;
  421. parse_ptr += should_continue;
  422. } while (should_continue);
  423. if (!digits_usable) {
  424. // No actual number value available.
  425. if (endptr)
  426. *endptr = const_cast<char*>(str);
  427. return 0.0;
  428. }
  429. // Parse exponent.
  430. // We already know the next character is not a digit in the current base,
  431. // nor a valid decimal point. Check whether it's an exponent sign.
  432. if (*parse_ptr == exponent_lower || *parse_ptr == exponent_upper) {
  433. // Need to keep the old parse_ptr around, in case of rollback.
  434. char* old_parse_ptr = parse_ptr;
  435. parse_ptr += 1;
  436. // Can't use atol or strtol here: Must accept excessive exponents,
  437. // even exponents >64 bits.
  438. Sign exponent_sign = strtosign(parse_ptr, &parse_ptr);
  439. IntParser exponent_parser { exponent_sign, base };
  440. bool exponent_usable = false;
  441. bool exponent_overflow = false;
  442. should_continue = true;
  443. do {
  444. bool is_a_digit;
  445. if (exponent_overflow) {
  446. is_a_digit = exponent_parser.parse_digit(*parse_ptr) != -1;
  447. } else {
  448. DigitConsumeDecision decision = exponent_parser.consume(*parse_ptr);
  449. switch (decision) {
  450. case DigitConsumeDecision::Consumed:
  451. is_a_digit = true;
  452. // The very first actual digit must pass here:
  453. exponent_usable = true;
  454. break;
  455. case DigitConsumeDecision::PosOverflow:
  456. case DigitConsumeDecision::NegOverflow:
  457. is_a_digit = true;
  458. exponent_overflow = true;
  459. break;
  460. case DigitConsumeDecision::Invalid:
  461. is_a_digit = false;
  462. break;
  463. default:
  464. ASSERT_NOT_REACHED();
  465. }
  466. }
  467. should_continue = is_a_digit;
  468. parse_ptr += should_continue;
  469. } while (should_continue);
  470. if (!exponent_usable) {
  471. parse_ptr = old_parse_ptr;
  472. } else if (exponent_overflow) {
  473. // Technically this is wrong. If someone gives us 5GB of digits,
  474. // and then an exponent of -5_000_000_000, the resulting exponent
  475. // should be around 0.
  476. // However, I think it's safe to assume that we never have to deal
  477. // with that many digits anyway.
  478. if (sign != Sign::Negative) {
  479. exponent = INT_MIN;
  480. } else {
  481. exponent = INT_MAX;
  482. }
  483. } else {
  484. // Literal exponent is usable and fits in an int.
  485. // However, `exponent + exponent_parser.number()` might overflow an int.
  486. // This would result in the wrong sign of the exponent!
  487. long long new_exponent = static_cast<long long>(exponent) + static_cast<long long>(exponent_parser.number());
  488. if (new_exponent < INT_MIN) {
  489. exponent = INT_MIN;
  490. } else if (new_exponent > INT_MAX) {
  491. exponent = INT_MAX;
  492. } else {
  493. exponent = static_cast<int>(new_exponent);
  494. }
  495. }
  496. }
  497. // Parsing finished. now we only have to compute the result.
  498. if (endptr)
  499. *endptr = const_cast<char*>(parse_ptr);
  500. // If `digits` is zero, we don't even have to look at `exponent`.
  501. if (digits.number() == 0) {
  502. if (sign != Sign::Negative) {
  503. return 0.0;
  504. } else {
  505. return -0.0;
  506. }
  507. }
  508. // Deal with extreme exponents.
  509. // The smallest normal is 2^-1022.
  510. // The smallest denormal is 2^-1074.
  511. // The largest number in `digits` is 2^63 - 1.
  512. // Therefore, if "base^exponent" is smaller than 2^-(1074+63), the result is 0.0 anyway.
  513. // This threshold is roughly 5.3566 * 10^-343.
  514. // So if the resulting exponent is -344 or lower (closer to -inf),
  515. // the result is 0.0 anyway.
  516. // We only need to avoid false positives, so we can ignore base 16.
  517. if (exponent <= -344) {
  518. errno = ERANGE;
  519. // Definitely can't be represented more precisely.
  520. // I lied, sometimes the result is +0.0, and sometimes -0.0.
  521. if (sign != Sign::Negative) {
  522. return 0.0;
  523. } else {
  524. return -0.0;
  525. }
  526. }
  527. // The largest normal is 2^+1024-eps.
  528. // The smallest number in `digits` is 1.
  529. // Therefore, if "base^exponent" is 2^+1024, the result is INF anyway.
  530. // This threshold is roughly 1.7977 * 10^-308.
  531. // So if the resulting exponent is +309 or higher,
  532. // the result is INF anyway.
  533. // We only need to avoid false positives, so we can ignore base 16.
  534. if (exponent >= 309) {
  535. errno = ERANGE;
  536. // Definitely can't be represented more precisely.
  537. // I lied, sometimes the result is +INF, and sometimes -INF.
  538. if (sign != Sign::Negative) {
  539. return __builtin_huge_val();
  540. } else {
  541. return -__builtin_huge_val();
  542. }
  543. }
  544. // TODO: If `exponent` is large, this could be made faster.
  545. double value = digits.number();
  546. if (exponent < 0) {
  547. exponent = -exponent;
  548. for (int i = 0; i < exponent; ++i) {
  549. value /= base;
  550. }
  551. if (value == -0.0 || value == +0.0) {
  552. errno = ERANGE;
  553. }
  554. } else if (exponent > 0) {
  555. for (int i = 0; i < exponent; ++i) {
  556. value *= base;
  557. }
  558. if (value == -__builtin_huge_val() || value == +__builtin_huge_val()) {
  559. errno = ERANGE;
  560. }
  561. }
  562. return value;
  563. }
  564. long double strtold(const char* str, char** endptr)
  565. {
  566. assert(sizeof(double) == sizeof(long double));
  567. return strtod(str, endptr);
  568. }
  569. float strtof(const char* str, char** endptr)
  570. {
  571. return strtod(str, endptr);
  572. }
  573. double atof(const char* str)
  574. {
  575. return strtod(str, nullptr);
  576. }
  577. int atoi(const char* str)
  578. {
  579. long value = strtol(str, nullptr, 10);
  580. if (value > INT_MAX) {
  581. return INT_MAX;
  582. }
  583. return value;
  584. }
  585. long atol(const char* str)
  586. {
  587. return strtol(str, nullptr, 10);
  588. }
  589. long long atoll(const char* str)
  590. {
  591. return strtoll(str, nullptr, 10);
  592. }
  593. static char ptsname_buf[32];
  594. char* ptsname(int fd)
  595. {
  596. if (ptsname_r(fd, ptsname_buf, sizeof(ptsname_buf)) < 0)
  597. return nullptr;
  598. return ptsname_buf;
  599. }
  600. int ptsname_r(int fd, char* buffer, size_t size)
  601. {
  602. int rc = syscall(SC_ptsname, fd, buffer, size);
  603. __RETURN_WITH_ERRNO(rc, rc, -1);
  604. }
  605. static unsigned long s_next_rand = 1;
  606. int rand()
  607. {
  608. s_next_rand = s_next_rand * 1103515245 + 12345;
  609. return ((unsigned)(s_next_rand / ((RAND_MAX + 1) * 2)) % (RAND_MAX + 1));
  610. }
  611. void srand(unsigned seed)
  612. {
  613. s_next_rand = seed;
  614. }
  615. int abs(int i)
  616. {
  617. return i < 0 ? -i : i;
  618. }
  619. long int random()
  620. {
  621. return rand();
  622. }
  623. void srandom(unsigned seed)
  624. {
  625. srand(seed);
  626. }
  627. int system(const char* command)
  628. {
  629. if (!command)
  630. return 1;
  631. pid_t child;
  632. const char* argv[] = { "sh", "-c", command, nullptr };
  633. if ((errno = posix_spawn(&child, "/bin/sh", nullptr, nullptr, const_cast<char**>(argv), environ)))
  634. return -1;
  635. int wstatus;
  636. waitpid(child, &wstatus, 0);
  637. return WEXITSTATUS(wstatus);
  638. }
  639. char* mktemp(char* pattern)
  640. {
  641. if (__generate_unique_filename(pattern) < 0)
  642. pattern[0] = '\0';
  643. return pattern;
  644. }
  645. int mkstemp(char* pattern)
  646. {
  647. char* path = mktemp(pattern);
  648. int fd = open(path, O_RDWR | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR); // I'm using the flags I saw glibc using.
  649. if (fd >= 0)
  650. return fd;
  651. return -1;
  652. }
  653. char* mkdtemp(char* pattern)
  654. {
  655. if (__generate_unique_filename(pattern) < 0)
  656. return nullptr;
  657. if (mkdir(pattern, 0700) < 0)
  658. return nullptr;
  659. return pattern;
  660. }
  661. void* bsearch(const void* key, const void* base, size_t nmemb, size_t size, int (*compar)(const void*, const void*))
  662. {
  663. char* start = static_cast<char*>(const_cast<void*>(base));
  664. while (nmemb > 0) {
  665. char* middle_memb = start + (nmemb / 2) * size;
  666. int comparison = compar(key, middle_memb);
  667. if (comparison == 0)
  668. return middle_memb;
  669. else if (comparison > 0) {
  670. start = middle_memb + size;
  671. --nmemb;
  672. }
  673. nmemb /= 2;
  674. }
  675. return nullptr;
  676. }
  677. div_t div(int numerator, int denominator)
  678. {
  679. div_t result;
  680. result.quot = numerator / denominator;
  681. result.rem = numerator % denominator;
  682. if (numerator >= 0 && result.rem < 0) {
  683. result.quot++;
  684. result.rem -= denominator;
  685. }
  686. return result;
  687. }
  688. ldiv_t ldiv(long numerator, long denominator)
  689. {
  690. ldiv_t result;
  691. result.quot = numerator / denominator;
  692. result.rem = numerator % denominator;
  693. if (numerator >= 0 && result.rem < 0) {
  694. result.quot++;
  695. result.rem -= denominator;
  696. }
  697. return result;
  698. }
  699. size_t mbstowcs(wchar_t*, const char*, size_t)
  700. {
  701. ASSERT_NOT_REACHED();
  702. }
  703. int mbtowc(wchar_t* wch, const char* data, [[maybe_unused]] size_t data_size)
  704. {
  705. // FIXME: This needs a real implementation.
  706. if (wch && data) {
  707. *wch = *data;
  708. return 1;
  709. }
  710. if (!wch && data) {
  711. return 1;
  712. }
  713. return 0;
  714. }
  715. int wctomb(char*, wchar_t)
  716. {
  717. ASSERT_NOT_REACHED();
  718. }
  719. size_t wcstombs(char* dest, const wchar_t* src, size_t max)
  720. {
  721. char* originalDest = dest;
  722. while ((size_t)(dest - originalDest) < max) {
  723. StringView v { (const char*)src, sizeof(wchar_t) };
  724. // FIXME: dependent on locale, for now utf-8 is supported.
  725. Utf8View utf8 { v };
  726. if (*utf8.begin() == '\0') {
  727. *dest = '\0';
  728. return (size_t)(dest - originalDest); // Exclude null character in returned size
  729. }
  730. for (auto byte : utf8) {
  731. if (byte != '\0')
  732. *dest++ = byte;
  733. }
  734. ++src;
  735. }
  736. return max;
  737. }
  738. long strtol(const char* str, char** endptr, int base)
  739. {
  740. long long value = strtoll(str, endptr, base);
  741. if (value < LONG_MIN) {
  742. errno = ERANGE;
  743. return LONG_MIN;
  744. } else if (value > LONG_MAX) {
  745. errno = ERANGE;
  746. return LONG_MAX;
  747. }
  748. return value;
  749. }
  750. unsigned long strtoul(const char* str, char** endptr, int base)
  751. {
  752. unsigned long long value = strtoull(str, endptr, base);
  753. if (value > ULONG_MAX) {
  754. errno = ERANGE;
  755. return ULONG_MAX;
  756. }
  757. return value;
  758. }
  759. long long strtoll(const char* str, char** endptr, int base)
  760. {
  761. // Parse spaces and sign
  762. char* parse_ptr = const_cast<char*>(str);
  763. strtons(parse_ptr, &parse_ptr);
  764. const Sign sign = strtosign(parse_ptr, &parse_ptr);
  765. // Parse base
  766. if (base == 0) {
  767. if (*parse_ptr == '0') {
  768. if (tolower(*(parse_ptr + 1)) == 'x') {
  769. base = 16;
  770. parse_ptr += 2;
  771. } else {
  772. base = 8;
  773. }
  774. } else {
  775. base = 10;
  776. }
  777. }
  778. // Parse actual digits.
  779. LongLongParser digits { sign, base };
  780. bool digits_usable = false;
  781. bool should_continue = true;
  782. bool overflow = false;
  783. do {
  784. bool is_a_digit;
  785. if (overflow) {
  786. is_a_digit = digits.parse_digit(*parse_ptr) >= 0;
  787. } else {
  788. DigitConsumeDecision decision = digits.consume(*parse_ptr);
  789. switch (decision) {
  790. case DigitConsumeDecision::Consumed:
  791. is_a_digit = true;
  792. // The very first actual digit must pass here:
  793. digits_usable = true;
  794. break;
  795. case DigitConsumeDecision::PosOverflow:
  796. case DigitConsumeDecision::NegOverflow:
  797. is_a_digit = true;
  798. overflow = true;
  799. break;
  800. case DigitConsumeDecision::Invalid:
  801. is_a_digit = false;
  802. break;
  803. default:
  804. ASSERT_NOT_REACHED();
  805. }
  806. }
  807. should_continue = is_a_digit;
  808. parse_ptr += should_continue;
  809. } while (should_continue);
  810. if (!digits_usable) {
  811. // No actual number value available.
  812. if (endptr)
  813. *endptr = const_cast<char*>(str);
  814. return 0;
  815. }
  816. if (endptr)
  817. *endptr = parse_ptr;
  818. if (overflow) {
  819. errno = ERANGE;
  820. if (sign != Sign::Negative) {
  821. return LONG_LONG_MAX;
  822. } else {
  823. return LONG_LONG_MIN;
  824. }
  825. }
  826. return digits.number();
  827. }
  828. unsigned long long strtoull(const char* str, char** endptr, int base)
  829. {
  830. // Parse spaces and sign
  831. char* parse_ptr = const_cast<char*>(str);
  832. strtons(parse_ptr, &parse_ptr);
  833. // Parse base
  834. if (base == 0) {
  835. if (*parse_ptr == '0') {
  836. if (tolower(*(parse_ptr + 1)) == 'x') {
  837. base = 16;
  838. parse_ptr += 2;
  839. } else {
  840. base = 8;
  841. }
  842. } else {
  843. base = 10;
  844. }
  845. }
  846. // Parse actual digits.
  847. ULongLongParser digits { Sign::Positive, base };
  848. bool digits_usable = false;
  849. bool should_continue = true;
  850. bool overflow = false;
  851. do {
  852. bool is_a_digit;
  853. if (overflow) {
  854. is_a_digit = digits.parse_digit(*parse_ptr) >= 0;
  855. } else {
  856. DigitConsumeDecision decision = digits.consume(*parse_ptr);
  857. switch (decision) {
  858. case DigitConsumeDecision::Consumed:
  859. is_a_digit = true;
  860. // The very first actual digit must pass here:
  861. digits_usable = true;
  862. break;
  863. case DigitConsumeDecision::PosOverflow:
  864. case DigitConsumeDecision::NegOverflow:
  865. is_a_digit = true;
  866. overflow = true;
  867. break;
  868. case DigitConsumeDecision::Invalid:
  869. is_a_digit = false;
  870. break;
  871. default:
  872. ASSERT_NOT_REACHED();
  873. }
  874. }
  875. should_continue = is_a_digit;
  876. parse_ptr += should_continue;
  877. } while (should_continue);
  878. if (!digits_usable) {
  879. // No actual number value available.
  880. if (endptr)
  881. *endptr = const_cast<char*>(str);
  882. return 0;
  883. }
  884. if (endptr)
  885. *endptr = parse_ptr;
  886. if (overflow) {
  887. errno = ERANGE;
  888. return LONG_LONG_MAX;
  889. }
  890. return digits.number();
  891. }
  892. // Serenity's PRNG is not cryptographically secure. Do not rely on this for
  893. // any real crypto! These functions (for now) are for compatibility.
  894. // TODO: In the future, rand can be made deterministic and this not.
  895. uint32_t arc4random(void)
  896. {
  897. char buf[4];
  898. syscall(SC_getrandom, buf, 4, 0);
  899. return *(uint32_t*)buf;
  900. }
  901. void arc4random_buf(void* buffer, size_t buffer_size)
  902. {
  903. // arc4random_buf should never fail, but user supplied buffers could fail.
  904. // However, if the user passes a garbage buffer, that's on them.
  905. syscall(SC_getrandom, buffer, buffer_size, 0);
  906. }
  907. uint32_t arc4random_uniform(uint32_t max_bounds)
  908. {
  909. // XXX: Should actually apply special rules for uniformity; avoid what is
  910. // called "modulo bias".
  911. return arc4random() % max_bounds;
  912. }
  913. char* realpath(const char* pathname, char* buffer)
  914. {
  915. if (!pathname) {
  916. errno = EFAULT;
  917. return nullptr;
  918. }
  919. size_t size = PATH_MAX;
  920. if (buffer == nullptr)
  921. buffer = (char*)malloc(size);
  922. Syscall::SC_realpath_params params { { pathname, strlen(pathname) }, { buffer, size } };
  923. int rc = syscall(SC_realpath, &params);
  924. if (rc < 0) {
  925. errno = -rc;
  926. return nullptr;
  927. }
  928. errno = 0;
  929. return buffer;
  930. }
  931. int posix_openpt(int flags)
  932. {
  933. if (flags & ~(O_RDWR | O_NOCTTY | O_CLOEXEC)) {
  934. errno = EINVAL;
  935. return -1;
  936. }
  937. return open("/dev/ptmx", flags);
  938. }
  939. int grantpt([[maybe_unused]] int fd)
  940. {
  941. return 0;
  942. }
  943. int unlockpt([[maybe_unused]] int fd)
  944. {
  945. return 0;
  946. }
  947. }