stdlib.cpp 29 KB

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