stdlib.cpp 38 KB

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