stdlib.cpp 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141
  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. template<typename Callback>
  153. inline int generate_unique_filename(char* pattern, Callback callback)
  154. {
  155. size_t length = strlen(pattern);
  156. if (length < 6 || memcmp(pattern + length - 6, "XXXXXX", 6))
  157. return EINVAL;
  158. size_t start = length - 6;
  159. static constexpr char random_characters[] = "abcdefghijklmnopqrstuvwxyz0123456789";
  160. for (int attempt = 0; attempt < 100; ++attempt) {
  161. for (int i = 0; i < 6; ++i)
  162. pattern[start + i] = random_characters[(arc4random() % (sizeof(random_characters) - 1))];
  163. if (callback() == IterationDecision::Break)
  164. return 0;
  165. }
  166. return EEXIST;
  167. }
  168. extern "C" {
  169. void exit(int status)
  170. {
  171. __cxa_finalize(nullptr);
  172. if (getenv("LIBC_DUMP_MALLOC_STATS"))
  173. serenity_dump_malloc_stats();
  174. extern void _fini();
  175. _fini();
  176. fflush(stdout);
  177. fflush(stderr);
  178. _exit(status);
  179. }
  180. static void __atexit_to_cxa_atexit(void* handler)
  181. {
  182. reinterpret_cast<void (*)()>(handler)();
  183. }
  184. int atexit(void (*handler)())
  185. {
  186. return __cxa_atexit(__atexit_to_cxa_atexit, (void*)handler, nullptr);
  187. }
  188. void abort()
  189. {
  190. // For starters, send ourselves a SIGABRT.
  191. raise(SIGABRT);
  192. // If that didn't kill us, try harder.
  193. raise(SIGKILL);
  194. _exit(127);
  195. }
  196. static HashTable<const char*> s_malloced_environment_variables;
  197. static void free_environment_variable_if_needed(const char* var)
  198. {
  199. if (!s_malloced_environment_variables.contains(var))
  200. return;
  201. free(const_cast<char*>(var));
  202. s_malloced_environment_variables.remove(var);
  203. }
  204. char* getenv(const char* name)
  205. {
  206. size_t vl = strlen(name);
  207. for (size_t i = 0; environ[i]; ++i) {
  208. const char* decl = environ[i];
  209. char* eq = strchr(decl, '=');
  210. if (!eq)
  211. continue;
  212. size_t varLength = eq - decl;
  213. if (vl != varLength)
  214. continue;
  215. if (strncmp(decl, name, varLength) == 0) {
  216. return eq + 1;
  217. }
  218. }
  219. return nullptr;
  220. }
  221. int unsetenv(const char* name)
  222. {
  223. auto new_var_len = strlen(name);
  224. size_t environ_size = 0;
  225. int skip = -1;
  226. for (; environ[environ_size]; ++environ_size) {
  227. char* old_var = environ[environ_size];
  228. char* old_eq = strchr(old_var, '=');
  229. ASSERT(old_eq);
  230. size_t old_var_len = old_eq - old_var;
  231. if (new_var_len != old_var_len)
  232. continue; // can't match
  233. if (strncmp(name, old_var, new_var_len) == 0)
  234. skip = environ_size;
  235. }
  236. if (skip == -1)
  237. return 0; // not found: no failure.
  238. // Shuffle the existing array down by one.
  239. memmove(&environ[skip], &environ[skip + 1], ((environ_size - 1) - skip) * sizeof(environ[0]));
  240. environ[environ_size - 1] = nullptr;
  241. free_environment_variable_if_needed(name);
  242. return 0;
  243. }
  244. int clearenv()
  245. {
  246. size_t environ_size = 0;
  247. for (; environ[environ_size]; ++environ_size) {
  248. environ[environ_size] = NULL;
  249. }
  250. *environ = NULL;
  251. return 0;
  252. }
  253. int setenv(const char* name, const char* value, int overwrite)
  254. {
  255. if (!overwrite && getenv(name))
  256. return 0;
  257. auto length = strlen(name) + strlen(value) + 2;
  258. auto* var = (char*)malloc(length);
  259. snprintf(var, length, "%s=%s", name, value);
  260. s_malloced_environment_variables.set(var);
  261. return putenv(var);
  262. }
  263. int putenv(char* new_var)
  264. {
  265. char* new_eq = strchr(new_var, '=');
  266. if (!new_eq)
  267. return unsetenv(new_var);
  268. auto new_var_len = new_eq - new_var;
  269. int environ_size = 0;
  270. for (; environ[environ_size]; ++environ_size) {
  271. char* old_var = environ[environ_size];
  272. char* old_eq = strchr(old_var, '=');
  273. ASSERT(old_eq);
  274. auto old_var_len = old_eq - old_var;
  275. if (new_var_len != old_var_len)
  276. continue; // can't match
  277. if (strncmp(new_var, old_var, new_var_len) == 0) {
  278. free_environment_variable_if_needed(old_var);
  279. environ[environ_size] = new_var;
  280. return 0;
  281. }
  282. }
  283. // At this point, we need to append the new var.
  284. // 2 here: one for the new var, one for the sentinel value.
  285. char** new_environ = (char**)malloc((environ_size + 2) * sizeof(char*));
  286. if (new_environ == nullptr) {
  287. errno = ENOMEM;
  288. return -1;
  289. }
  290. for (int i = 0; environ[i]; ++i) {
  291. new_environ[i] = environ[i];
  292. }
  293. new_environ[environ_size] = new_var;
  294. new_environ[environ_size + 1] = nullptr;
  295. // swap new and old
  296. // note that the initial environ is not heap allocated!
  297. extern bool __environ_is_malloced;
  298. if (__environ_is_malloced)
  299. free(environ);
  300. __environ_is_malloced = true;
  301. environ = new_environ;
  302. return 0;
  303. }
  304. double strtod(const char* str, char** endptr)
  305. {
  306. // Parse spaces, sign, and base
  307. char* parse_ptr = const_cast<char*>(str);
  308. strtons(parse_ptr, &parse_ptr);
  309. const Sign sign = strtosign(parse_ptr, &parse_ptr);
  310. // Parse inf/nan, if applicable.
  311. if (is_either(parse_ptr, 0, 'i', 'I')) {
  312. if (is_either(parse_ptr, 1, 'n', 'N')) {
  313. if (is_either(parse_ptr, 2, 'f', 'F')) {
  314. parse_ptr += 3;
  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, 'i', 'I')) {
  318. if (is_either(parse_ptr, 3, 't', 'T')) {
  319. if (is_either(parse_ptr, 4, 'y', 'Y')) {
  320. parse_ptr += 5;
  321. }
  322. }
  323. }
  324. }
  325. }
  326. if (endptr)
  327. *endptr = parse_ptr;
  328. // Don't set errno to ERANGE here:
  329. // The caller may want to distinguish between "input is
  330. // literal infinity" and "input is not literal infinity
  331. // but did not fit into double".
  332. if (sign != Sign::Negative) {
  333. return __builtin_huge_val();
  334. } else {
  335. return -__builtin_huge_val();
  336. }
  337. }
  338. }
  339. }
  340. if (is_either(parse_ptr, 0, 'n', 'N')) {
  341. if (is_either(parse_ptr, 1, 'a', 'A')) {
  342. if (is_either(parse_ptr, 2, 'n', 'N')) {
  343. if (endptr)
  344. *endptr = parse_ptr + 3;
  345. errno = ERANGE;
  346. if (sign != Sign::Negative) {
  347. return __builtin_nan("");
  348. } else {
  349. return -__builtin_nan("");
  350. }
  351. }
  352. }
  353. }
  354. // Parse base
  355. char exponent_lower;
  356. char exponent_upper;
  357. int base = 10;
  358. if (*parse_ptr == '0') {
  359. const char base_ch = *(parse_ptr + 1);
  360. if (base_ch == 'x' || base_ch == 'X') {
  361. base = 16;
  362. parse_ptr += 2;
  363. }
  364. }
  365. if (base == 10) {
  366. exponent_lower = 'e';
  367. exponent_upper = 'E';
  368. } else {
  369. exponent_lower = 'p';
  370. exponent_upper = 'P';
  371. }
  372. // Parse "digits", possibly keeping track of the exponent offset.
  373. // We parse the most significant digits and the position in the
  374. // base-`base` representation separately. This allows us to handle
  375. // numbers like `0.0000000000000000000000000000000000001234` or
  376. // `1234567890123456789012345678901234567890` with ease.
  377. LongLongParser digits { sign, base };
  378. bool digits_usable = false;
  379. bool should_continue = true;
  380. bool digits_overflow = false;
  381. bool after_decimal = false;
  382. int exponent = 0;
  383. do {
  384. if (!after_decimal && *parse_ptr == '.') {
  385. after_decimal = true;
  386. parse_ptr += 1;
  387. continue;
  388. }
  389. bool is_a_digit;
  390. if (digits_overflow) {
  391. is_a_digit = digits.parse_digit(*parse_ptr) != -1;
  392. } else {
  393. DigitConsumeDecision decision = digits.consume(*parse_ptr);
  394. switch (decision) {
  395. case DigitConsumeDecision::Consumed:
  396. is_a_digit = true;
  397. // The very first actual digit must pass here:
  398. digits_usable = true;
  399. break;
  400. case DigitConsumeDecision::PosOverflow:
  401. case DigitConsumeDecision::NegOverflow:
  402. is_a_digit = true;
  403. digits_overflow = true;
  404. break;
  405. case DigitConsumeDecision::Invalid:
  406. is_a_digit = false;
  407. break;
  408. default:
  409. ASSERT_NOT_REACHED();
  410. }
  411. }
  412. if (is_a_digit) {
  413. exponent -= after_decimal ? 1 : 0;
  414. exponent += digits_overflow ? 1 : 0;
  415. }
  416. should_continue = is_a_digit;
  417. parse_ptr += should_continue;
  418. } while (should_continue);
  419. if (!digits_usable) {
  420. // No actual number value available.
  421. if (endptr)
  422. *endptr = const_cast<char*>(str);
  423. return 0.0;
  424. }
  425. // Parse exponent.
  426. // We already know the next character is not a digit in the current base,
  427. // nor a valid decimal point. Check whether it's an exponent sign.
  428. if (*parse_ptr == exponent_lower || *parse_ptr == exponent_upper) {
  429. // Need to keep the old parse_ptr around, in case of rollback.
  430. char* old_parse_ptr = parse_ptr;
  431. parse_ptr += 1;
  432. // Can't use atol or strtol here: Must accept excessive exponents,
  433. // even exponents >64 bits.
  434. Sign exponent_sign = strtosign(parse_ptr, &parse_ptr);
  435. IntParser exponent_parser { exponent_sign, base };
  436. bool exponent_usable = false;
  437. bool exponent_overflow = false;
  438. should_continue = true;
  439. do {
  440. bool is_a_digit;
  441. if (exponent_overflow) {
  442. is_a_digit = exponent_parser.parse_digit(*parse_ptr) != -1;
  443. } else {
  444. DigitConsumeDecision decision = exponent_parser.consume(*parse_ptr);
  445. switch (decision) {
  446. case DigitConsumeDecision::Consumed:
  447. is_a_digit = true;
  448. // The very first actual digit must pass here:
  449. exponent_usable = true;
  450. break;
  451. case DigitConsumeDecision::PosOverflow:
  452. case DigitConsumeDecision::NegOverflow:
  453. is_a_digit = true;
  454. exponent_overflow = true;
  455. break;
  456. case DigitConsumeDecision::Invalid:
  457. is_a_digit = false;
  458. break;
  459. default:
  460. ASSERT_NOT_REACHED();
  461. }
  462. }
  463. should_continue = is_a_digit;
  464. parse_ptr += should_continue;
  465. } while (should_continue);
  466. if (!exponent_usable) {
  467. parse_ptr = old_parse_ptr;
  468. } else if (exponent_overflow) {
  469. // Technically this is wrong. If someone gives us 5GB of digits,
  470. // and then an exponent of -5_000_000_000, the resulting exponent
  471. // should be around 0.
  472. // However, I think it's safe to assume that we never have to deal
  473. // with that many digits anyway.
  474. if (sign != Sign::Negative) {
  475. exponent = INT_MIN;
  476. } else {
  477. exponent = INT_MAX;
  478. }
  479. } else {
  480. // Literal exponent is usable and fits in an int.
  481. // However, `exponent + exponent_parser.number()` might overflow an int.
  482. // This would result in the wrong sign of the exponent!
  483. long long new_exponent = static_cast<long long>(exponent) + static_cast<long long>(exponent_parser.number());
  484. if (new_exponent < INT_MIN) {
  485. exponent = INT_MIN;
  486. } else if (new_exponent > INT_MAX) {
  487. exponent = INT_MAX;
  488. } else {
  489. exponent = static_cast<int>(new_exponent);
  490. }
  491. }
  492. }
  493. // Parsing finished. now we only have to compute the result.
  494. if (endptr)
  495. *endptr = const_cast<char*>(parse_ptr);
  496. // If `digits` is zero, we don't even have to look at `exponent`.
  497. if (digits.number() == 0) {
  498. if (sign != Sign::Negative) {
  499. return 0.0;
  500. } else {
  501. return -0.0;
  502. }
  503. }
  504. // Deal with extreme exponents.
  505. // The smallest normal is 2^-1022.
  506. // The smallest denormal is 2^-1074.
  507. // The largest number in `digits` is 2^63 - 1.
  508. // Therefore, if "base^exponent" is smaller than 2^-(1074+63), the result is 0.0 anyway.
  509. // This threshold is roughly 5.3566 * 10^-343.
  510. // So if the resulting exponent is -344 or lower (closer to -inf),
  511. // the result is 0.0 anyway.
  512. // We only need to avoid false positives, so we can ignore base 16.
  513. if (exponent <= -344) {
  514. errno = ERANGE;
  515. // Definitely can't be represented more precisely.
  516. // I lied, sometimes the result is +0.0, and sometimes -0.0.
  517. if (sign != Sign::Negative) {
  518. return 0.0;
  519. } else {
  520. return -0.0;
  521. }
  522. }
  523. // The largest normal is 2^+1024-eps.
  524. // The smallest number in `digits` is 1.
  525. // Therefore, if "base^exponent" is 2^+1024, the result is INF anyway.
  526. // This threshold is roughly 1.7977 * 10^-308.
  527. // So if the resulting exponent is +309 or higher,
  528. // the result is INF anyway.
  529. // We only need to avoid false positives, so we can ignore base 16.
  530. if (exponent >= 309) {
  531. errno = ERANGE;
  532. // Definitely can't be represented more precisely.
  533. // I lied, sometimes the result is +INF, and sometimes -INF.
  534. if (sign != Sign::Negative) {
  535. return __builtin_huge_val();
  536. } else {
  537. return -__builtin_huge_val();
  538. }
  539. }
  540. // TODO: If `exponent` is large, this could be made faster.
  541. double value = digits.number();
  542. if (exponent < 0) {
  543. exponent = -exponent;
  544. for (int i = 0; i < exponent; ++i) {
  545. value /= base;
  546. }
  547. if (value == -0.0 || value == +0.0) {
  548. errno = ERANGE;
  549. }
  550. } else if (exponent > 0) {
  551. for (int i = 0; i < exponent; ++i) {
  552. value *= base;
  553. }
  554. if (value == -__builtin_huge_val() || value == +__builtin_huge_val()) {
  555. errno = ERANGE;
  556. }
  557. }
  558. return value;
  559. }
  560. long double strtold(const char* str, char** endptr)
  561. {
  562. assert(sizeof(double) == sizeof(long double));
  563. return strtod(str, endptr);
  564. }
  565. float strtof(const char* str, char** endptr)
  566. {
  567. return strtod(str, endptr);
  568. }
  569. double atof(const char* str)
  570. {
  571. return strtod(str, nullptr);
  572. }
  573. int atoi(const char* str)
  574. {
  575. long value = strtol(str, nullptr, 10);
  576. if (value > INT_MAX) {
  577. return INT_MAX;
  578. }
  579. return value;
  580. }
  581. long atol(const char* str)
  582. {
  583. return strtol(str, nullptr, 10);
  584. }
  585. long long atoll(const char* str)
  586. {
  587. return strtoll(str, nullptr, 10);
  588. }
  589. static char ptsname_buf[32];
  590. char* ptsname(int fd)
  591. {
  592. if (ptsname_r(fd, ptsname_buf, sizeof(ptsname_buf)) < 0)
  593. return nullptr;
  594. return ptsname_buf;
  595. }
  596. int ptsname_r(int fd, char* buffer, size_t size)
  597. {
  598. int rc = syscall(SC_ptsname, fd, buffer, size);
  599. __RETURN_WITH_ERRNO(rc, rc, -1);
  600. }
  601. static unsigned long s_next_rand = 1;
  602. int rand()
  603. {
  604. s_next_rand = s_next_rand * 1103515245 + 12345;
  605. return ((unsigned)(s_next_rand / ((RAND_MAX + 1) * 2)) % (RAND_MAX + 1));
  606. }
  607. void srand(unsigned seed)
  608. {
  609. s_next_rand = seed;
  610. }
  611. int abs(int i)
  612. {
  613. return i < 0 ? -i : i;
  614. }
  615. long int random()
  616. {
  617. return rand();
  618. }
  619. void srandom(unsigned seed)
  620. {
  621. srand(seed);
  622. }
  623. int system(const char* command)
  624. {
  625. if (!command)
  626. return 1;
  627. pid_t child;
  628. const char* argv[] = { "sh", "-c", command, nullptr };
  629. if ((errno = posix_spawn(&child, "/bin/sh", nullptr, nullptr, const_cast<char**>(argv), environ)))
  630. return -1;
  631. int wstatus;
  632. waitpid(child, &wstatus, 0);
  633. return WEXITSTATUS(wstatus);
  634. }
  635. char* mktemp(char* pattern)
  636. {
  637. auto error = generate_unique_filename(pattern, [&] {
  638. struct stat st;
  639. int rc = lstat(pattern, &st);
  640. if (rc < 0 && errno == ENOENT)
  641. return IterationDecision::Break;
  642. return IterationDecision::Continue;
  643. });
  644. if (error) {
  645. pattern[0] = '\0';
  646. errno = error;
  647. }
  648. return pattern;
  649. }
  650. int mkstemp(char* pattern)
  651. {
  652. int fd = -1;
  653. auto error = generate_unique_filename(pattern, [&] {
  654. fd = open(pattern, O_RDWR | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR); // I'm using the flags I saw glibc using.
  655. if (fd >= 0)
  656. return IterationDecision::Break;
  657. return IterationDecision::Continue;
  658. });
  659. if (error) {
  660. errno = error;
  661. return -1;
  662. }
  663. return fd;
  664. }
  665. char* mkdtemp(char* pattern)
  666. {
  667. auto error = generate_unique_filename(pattern, [&] {
  668. if (mkdir(pattern, 0700) == 0)
  669. return IterationDecision::Break;
  670. return IterationDecision::Continue;
  671. });
  672. if (error) {
  673. errno = error;
  674. return nullptr;
  675. }
  676. return pattern;
  677. }
  678. void* bsearch(const void* key, const void* base, size_t nmemb, size_t size, int (*compar)(const void*, const void*))
  679. {
  680. char* start = static_cast<char*>(const_cast<void*>(base));
  681. while (nmemb > 0) {
  682. char* middle_memb = start + (nmemb / 2) * size;
  683. int comparison = compar(key, middle_memb);
  684. if (comparison == 0)
  685. return middle_memb;
  686. else if (comparison > 0) {
  687. start = middle_memb + size;
  688. --nmemb;
  689. }
  690. nmemb /= 2;
  691. }
  692. return nullptr;
  693. }
  694. div_t div(int numerator, int denominator)
  695. {
  696. div_t result;
  697. result.quot = numerator / denominator;
  698. result.rem = numerator % denominator;
  699. if (numerator >= 0 && result.rem < 0) {
  700. result.quot++;
  701. result.rem -= denominator;
  702. }
  703. return result;
  704. }
  705. ldiv_t ldiv(long numerator, long denominator)
  706. {
  707. ldiv_t result;
  708. result.quot = numerator / denominator;
  709. result.rem = numerator % denominator;
  710. if (numerator >= 0 && result.rem < 0) {
  711. result.quot++;
  712. result.rem -= denominator;
  713. }
  714. return result;
  715. }
  716. size_t mbstowcs(wchar_t*, const char*, size_t)
  717. {
  718. dbgln("FIXME: Implement mbstowcs()");
  719. TODO();
  720. }
  721. int mbtowc(wchar_t* wch, const char* data, [[maybe_unused]] size_t data_size)
  722. {
  723. // FIXME: This needs a real implementation.
  724. if (wch && data) {
  725. *wch = *data;
  726. return 1;
  727. }
  728. if (!wch && data) {
  729. return 1;
  730. }
  731. return 0;
  732. }
  733. int wctomb(char*, wchar_t)
  734. {
  735. dbgln("FIXME: Implement wctomb()");
  736. TODO();
  737. }
  738. size_t wcstombs(char* dest, const wchar_t* src, size_t max)
  739. {
  740. char* originalDest = dest;
  741. while ((size_t)(dest - originalDest) < max) {
  742. StringView v { (const char*)src, sizeof(wchar_t) };
  743. // FIXME: dependent on locale, for now utf-8 is supported.
  744. Utf8View utf8 { v };
  745. if (*utf8.begin() == '\0') {
  746. *dest = '\0';
  747. return (size_t)(dest - originalDest); // Exclude null character in returned size
  748. }
  749. for (auto byte : utf8) {
  750. if (byte != '\0')
  751. *dest++ = byte;
  752. }
  753. ++src;
  754. }
  755. return max;
  756. }
  757. long strtol(const char* str, char** endptr, int base)
  758. {
  759. long long value = strtoll(str, endptr, base);
  760. if (value < LONG_MIN) {
  761. errno = ERANGE;
  762. return LONG_MIN;
  763. } else if (value > LONG_MAX) {
  764. errno = ERANGE;
  765. return LONG_MAX;
  766. }
  767. return value;
  768. }
  769. unsigned long strtoul(const char* str, char** endptr, int base)
  770. {
  771. unsigned long long value = strtoull(str, endptr, base);
  772. if (value > ULONG_MAX) {
  773. errno = ERANGE;
  774. return ULONG_MAX;
  775. }
  776. return value;
  777. }
  778. long long strtoll(const char* str, char** endptr, int base)
  779. {
  780. // Parse spaces and sign
  781. char* parse_ptr = const_cast<char*>(str);
  782. strtons(parse_ptr, &parse_ptr);
  783. const Sign sign = strtosign(parse_ptr, &parse_ptr);
  784. // Parse base
  785. if (base == 0) {
  786. if (*parse_ptr == '0') {
  787. if (tolower(*(parse_ptr + 1)) == 'x') {
  788. base = 16;
  789. parse_ptr += 2;
  790. } else {
  791. base = 8;
  792. }
  793. } else {
  794. base = 10;
  795. }
  796. }
  797. // Parse actual digits.
  798. LongLongParser digits { sign, base };
  799. bool digits_usable = false;
  800. bool should_continue = true;
  801. bool overflow = false;
  802. do {
  803. bool is_a_digit;
  804. if (overflow) {
  805. is_a_digit = digits.parse_digit(*parse_ptr) >= 0;
  806. } else {
  807. DigitConsumeDecision decision = digits.consume(*parse_ptr);
  808. switch (decision) {
  809. case DigitConsumeDecision::Consumed:
  810. is_a_digit = true;
  811. // The very first actual digit must pass here:
  812. digits_usable = true;
  813. break;
  814. case DigitConsumeDecision::PosOverflow:
  815. case DigitConsumeDecision::NegOverflow:
  816. is_a_digit = true;
  817. overflow = true;
  818. break;
  819. case DigitConsumeDecision::Invalid:
  820. is_a_digit = false;
  821. break;
  822. default:
  823. ASSERT_NOT_REACHED();
  824. }
  825. }
  826. should_continue = is_a_digit;
  827. parse_ptr += should_continue;
  828. } while (should_continue);
  829. if (!digits_usable) {
  830. // No actual number value available.
  831. if (endptr)
  832. *endptr = const_cast<char*>(str);
  833. return 0;
  834. }
  835. if (endptr)
  836. *endptr = parse_ptr;
  837. if (overflow) {
  838. errno = ERANGE;
  839. if (sign != Sign::Negative) {
  840. return LONG_LONG_MAX;
  841. } else {
  842. return LONG_LONG_MIN;
  843. }
  844. }
  845. return digits.number();
  846. }
  847. unsigned long long strtoull(const char* str, char** endptr, int base)
  848. {
  849. // Parse spaces and sign
  850. char* parse_ptr = const_cast<char*>(str);
  851. strtons(parse_ptr, &parse_ptr);
  852. // Parse base
  853. if (base == 0) {
  854. if (*parse_ptr == '0') {
  855. if (tolower(*(parse_ptr + 1)) == 'x') {
  856. base = 16;
  857. parse_ptr += 2;
  858. } else {
  859. base = 8;
  860. }
  861. } else {
  862. base = 10;
  863. }
  864. }
  865. // Parse actual digits.
  866. ULongLongParser digits { Sign::Positive, base };
  867. bool digits_usable = false;
  868. bool should_continue = true;
  869. bool overflow = false;
  870. do {
  871. bool is_a_digit;
  872. if (overflow) {
  873. is_a_digit = digits.parse_digit(*parse_ptr) >= 0;
  874. } else {
  875. DigitConsumeDecision decision = digits.consume(*parse_ptr);
  876. switch (decision) {
  877. case DigitConsumeDecision::Consumed:
  878. is_a_digit = true;
  879. // The very first actual digit must pass here:
  880. digits_usable = true;
  881. break;
  882. case DigitConsumeDecision::PosOverflow:
  883. case DigitConsumeDecision::NegOverflow:
  884. is_a_digit = true;
  885. overflow = true;
  886. break;
  887. case DigitConsumeDecision::Invalid:
  888. is_a_digit = false;
  889. break;
  890. default:
  891. ASSERT_NOT_REACHED();
  892. }
  893. }
  894. should_continue = is_a_digit;
  895. parse_ptr += should_continue;
  896. } while (should_continue);
  897. if (!digits_usable) {
  898. // No actual number value available.
  899. if (endptr)
  900. *endptr = const_cast<char*>(str);
  901. return 0;
  902. }
  903. if (endptr)
  904. *endptr = parse_ptr;
  905. if (overflow) {
  906. errno = ERANGE;
  907. return LONG_LONG_MAX;
  908. }
  909. return digits.number();
  910. }
  911. // Serenity's PRNG is not cryptographically secure. Do not rely on this for
  912. // any real crypto! These functions (for now) are for compatibility.
  913. // TODO: In the future, rand can be made deterministic and this not.
  914. uint32_t arc4random(void)
  915. {
  916. char buf[4];
  917. syscall(SC_getrandom, buf, 4, 0);
  918. return *(uint32_t*)buf;
  919. }
  920. void arc4random_buf(void* buffer, size_t buffer_size)
  921. {
  922. // arc4random_buf should never fail, but user supplied buffers could fail.
  923. // However, if the user passes a garbage buffer, that's on them.
  924. syscall(SC_getrandom, buffer, buffer_size, 0);
  925. }
  926. uint32_t arc4random_uniform(uint32_t max_bounds)
  927. {
  928. // If we try to divide all 2**32 numbers into groups of "max_bounds" numbers, we may end up
  929. // with a group around 2**32-1 that is a bit too small. For this reason, the implementation
  930. // `arc4random() % max_bounds` would be insufficient. Here we compute the last number of the
  931. // last "full group". Note that if max_bounds is a divisor of UINT32_MAX,
  932. // then we end up with UINT32_MAX:
  933. const uint32_t max_usable = UINT32_MAX - (static_cast<uint64_t>(UINT32_MAX) + 1) % max_bounds;
  934. uint32_t random_value = arc4random();
  935. for (int i = 0; i < 20 && random_value > max_usable; ++i) {
  936. // By chance we picked a value from the incomplete group. Note that this group has size at
  937. // most 2**31-1, so picking this group has a chance of less than 50%.
  938. // In practice, this means that for the worst possible input, there is still only a
  939. // once-in-a-million chance to get to iteration 20. In theory we should be able to loop
  940. // forever. Here we prefer marginally imperfect random numbers over weird runtime behavior.
  941. random_value = arc4random();
  942. }
  943. return random_value % max_bounds;
  944. }
  945. char* realpath(const char* pathname, char* buffer)
  946. {
  947. if (!pathname) {
  948. errno = EFAULT;
  949. return nullptr;
  950. }
  951. size_t size = PATH_MAX;
  952. bool self_allocated = false;
  953. if (buffer == nullptr) {
  954. // Since we self-allocate, try to sneakily use a smaller buffer instead, in an attempt to use less memory.
  955. size = 64;
  956. buffer = (char*)malloc(size);
  957. self_allocated = true;
  958. }
  959. Syscall::SC_realpath_params params { { pathname, strlen(pathname) }, { buffer, size } };
  960. int rc = syscall(SC_realpath, &params);
  961. if (rc < 0) {
  962. if (self_allocated)
  963. free(buffer);
  964. errno = -rc;
  965. return nullptr;
  966. }
  967. if (self_allocated && static_cast<size_t>(rc) > size) {
  968. // There was silent truncation, *and* we can simply retry without the caller noticing.
  969. free(buffer);
  970. size = static_cast<size_t>(rc);
  971. buffer = (char*)malloc(size);
  972. params.buffer = { buffer, size };
  973. rc = syscall(SC_realpath, &params);
  974. if (rc < 0) {
  975. // Can only happen if we lose a race. Let's pretend we lost the race in the first place.
  976. free(buffer);
  977. errno = -rc;
  978. return nullptr;
  979. }
  980. size_t new_size = static_cast<size_t>(rc);
  981. if (new_size < size) {
  982. // If we're here, the symlink has become longer while we were looking at it.
  983. // There's not much we can do, unless we want to loop endlessly
  984. // in this case. Let's leave it up to the caller whether to loop.
  985. free(buffer);
  986. errno = EAGAIN;
  987. return nullptr;
  988. }
  989. }
  990. errno = 0;
  991. return buffer;
  992. }
  993. int posix_openpt(int flags)
  994. {
  995. if (flags & ~(O_RDWR | O_NOCTTY | O_CLOEXEC)) {
  996. errno = EINVAL;
  997. return -1;
  998. }
  999. return open("/dev/ptmx", flags);
  1000. }
  1001. int grantpt([[maybe_unused]] int fd)
  1002. {
  1003. return 0;
  1004. }
  1005. int unlockpt([[maybe_unused]] int fd)
  1006. {
  1007. return 0;
  1008. }
  1009. }