stdlib.cpp 29 KB

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