stdlib.cpp 29 KB

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