stdlib.cpp 29 KB

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