stdlib.cpp 36 KB

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