stdlib.cpp 31 KB

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