stdlib.cpp 27 KB

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