stdlib.cpp 38 KB

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