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