stdlib.cpp 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340
  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, Callback callback)
  143. {
  144. size_t length = strlen(pattern);
  145. if (length < 6 || memcmp(pattern + length - 6, "XXXXXX", 6))
  146. return EINVAL;
  147. size_t start = length - 6;
  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, [&] {
  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. int fd = -1;
  741. auto error = generate_unique_filename(pattern, [&] {
  742. fd = open(pattern, O_RDWR | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR); // I'm using the flags I saw glibc using.
  743. if (fd >= 0)
  744. return IterationDecision::Break;
  745. return IterationDecision::Continue;
  746. });
  747. if (error) {
  748. errno = error;
  749. return -1;
  750. }
  751. return fd;
  752. }
  753. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/mkdtemp.html
  754. char* mkdtemp(char* pattern)
  755. {
  756. auto error = generate_unique_filename(pattern, [&] {
  757. if (mkdir(pattern, 0700) == 0)
  758. return IterationDecision::Break;
  759. return IterationDecision::Continue;
  760. });
  761. if (error) {
  762. errno = error;
  763. return nullptr;
  764. }
  765. return pattern;
  766. }
  767. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/bsearch.html
  768. void* bsearch(void const* key, void const* base, size_t nmemb, size_t size, int (*compar)(void const*, void const*))
  769. {
  770. char* start = static_cast<char*>(const_cast<void*>(base));
  771. while (nmemb > 0) {
  772. char* middle_memb = start + (nmemb / 2) * size;
  773. int comparison = compar(key, middle_memb);
  774. if (comparison == 0)
  775. return middle_memb;
  776. else if (comparison > 0) {
  777. start = middle_memb + size;
  778. --nmemb;
  779. }
  780. nmemb /= 2;
  781. }
  782. return nullptr;
  783. }
  784. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/div.html
  785. div_t div(int numerator, int denominator)
  786. {
  787. div_t result;
  788. result.quot = numerator / denominator;
  789. result.rem = numerator % denominator;
  790. if (numerator >= 0 && result.rem < 0) {
  791. result.quot++;
  792. result.rem -= denominator;
  793. }
  794. return result;
  795. }
  796. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/ldiv.html
  797. ldiv_t ldiv(long numerator, long denominator)
  798. {
  799. ldiv_t result;
  800. result.quot = numerator / denominator;
  801. result.rem = numerator % denominator;
  802. if (numerator >= 0 && result.rem < 0) {
  803. result.quot++;
  804. result.rem -= denominator;
  805. }
  806. return result;
  807. }
  808. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/lldiv.html
  809. lldiv_t lldiv(long long numerator, long long denominator)
  810. {
  811. lldiv_t result;
  812. result.quot = numerator / denominator;
  813. result.rem = numerator % denominator;
  814. if (numerator >= 0 && result.rem < 0) {
  815. result.quot++;
  816. result.rem -= denominator;
  817. }
  818. return result;
  819. }
  820. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/mblen.html
  821. int mblen(char const* s, size_t n)
  822. {
  823. // POSIX: Equivalent to mbtowc(NULL, s, n), but we mustn't change the state of mbtowc.
  824. static mbstate_t internal_state = {};
  825. // Reset the internal state and ask whether we have shift states.
  826. if (s == nullptr) {
  827. internal_state = {};
  828. return 0;
  829. }
  830. size_t ret = mbrtowc(nullptr, s, n, &internal_state);
  831. // Incomplete characters get returned as illegal sequence.
  832. if (ret == -2ul) {
  833. errno = EILSEQ;
  834. return -1;
  835. }
  836. return ret;
  837. }
  838. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/mbstowcs.html
  839. size_t mbstowcs(wchar_t* pwcs, char const* s, size_t n)
  840. {
  841. static mbstate_t state = {};
  842. return mbsrtowcs(pwcs, &s, n, &state);
  843. }
  844. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/mbtowc.html
  845. int mbtowc(wchar_t* pwc, char const* s, size_t n)
  846. {
  847. static mbstate_t internal_state = {};
  848. // Reset the internal state and ask whether we have shift states.
  849. if (s == nullptr) {
  850. internal_state = {};
  851. return 0;
  852. }
  853. size_t ret = mbrtowc(pwc, s, n, &internal_state);
  854. // Incomplete characters get returned as illegal sequence.
  855. // Internal state is undefined, so don't bother with resetting.
  856. if (ret == -2ul) {
  857. errno = EILSEQ;
  858. return -1;
  859. }
  860. return ret;
  861. }
  862. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/wctomb.html
  863. int wctomb(char* s, wchar_t wc)
  864. {
  865. static mbstate_t _internal_state = {};
  866. // nullptr asks whether we have state-dependent encodings, but we don't have any.
  867. if (s == nullptr)
  868. return 0;
  869. return static_cast<int>(wcrtomb(s, wc, &_internal_state));
  870. }
  871. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/wcstombs.html
  872. size_t wcstombs(char* dest, wchar_t const* src, size_t max)
  873. {
  874. char* original_dest = dest;
  875. while ((size_t)(dest - original_dest) < max) {
  876. StringView v { (char const*)src, sizeof(wchar_t) };
  877. // FIXME: dependent on locale, for now utf-8 is supported.
  878. Utf8View utf8 { v };
  879. if (*utf8.begin() == '\0') {
  880. *dest = '\0';
  881. return (size_t)(dest - original_dest); // Exclude null character in returned size
  882. }
  883. for (auto byte : utf8) {
  884. if (byte != '\0')
  885. *dest++ = byte;
  886. }
  887. ++src;
  888. }
  889. return max;
  890. }
  891. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/strtol.html
  892. long strtol(char const* str, char** endptr, int base)
  893. {
  894. long long value = strtoll(str, endptr, base);
  895. if (value < LONG_MIN) {
  896. errno = ERANGE;
  897. return LONG_MIN;
  898. } else if (value > LONG_MAX) {
  899. errno = ERANGE;
  900. return LONG_MAX;
  901. }
  902. return value;
  903. }
  904. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/strtoul.html
  905. unsigned long strtoul(char const* str, char** endptr, int base)
  906. {
  907. unsigned long long value = strtoull(str, endptr, base);
  908. if (value > ULONG_MAX) {
  909. errno = ERANGE;
  910. return ULONG_MAX;
  911. }
  912. return value;
  913. }
  914. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/strtoll.html
  915. long long strtoll(char const* str, char** endptr, int base)
  916. {
  917. // Parse spaces and sign
  918. char* parse_ptr = const_cast<char*>(str);
  919. strtons(parse_ptr, &parse_ptr);
  920. const Sign sign = strtosign(parse_ptr, &parse_ptr);
  921. // Parse base
  922. if (base == 0) {
  923. if (*parse_ptr == '0') {
  924. if (tolower(*(parse_ptr + 1)) == 'x') {
  925. base = 16;
  926. parse_ptr += 2;
  927. } else {
  928. base = 8;
  929. }
  930. } else {
  931. base = 10;
  932. }
  933. }
  934. // Parse actual digits.
  935. LongLongParser digits { sign, base };
  936. bool digits_usable = false;
  937. bool should_continue = true;
  938. bool overflow = false;
  939. do {
  940. bool is_a_digit;
  941. if (overflow) {
  942. is_a_digit = digits.parse_digit(*parse_ptr) >= 0;
  943. } else {
  944. DigitConsumeDecision decision = digits.consume(*parse_ptr);
  945. switch (decision) {
  946. case DigitConsumeDecision::Consumed:
  947. is_a_digit = true;
  948. // The very first actual digit must pass here:
  949. digits_usable = true;
  950. break;
  951. case DigitConsumeDecision::PosOverflow:
  952. case DigitConsumeDecision::NegOverflow:
  953. is_a_digit = true;
  954. overflow = true;
  955. break;
  956. case DigitConsumeDecision::Invalid:
  957. is_a_digit = false;
  958. break;
  959. default:
  960. VERIFY_NOT_REACHED();
  961. }
  962. }
  963. should_continue = is_a_digit;
  964. parse_ptr += should_continue;
  965. } while (should_continue);
  966. if (!digits_usable) {
  967. // No actual number value available.
  968. if (endptr)
  969. *endptr = const_cast<char*>(str);
  970. return 0;
  971. }
  972. if (endptr)
  973. *endptr = parse_ptr;
  974. if (overflow) {
  975. errno = ERANGE;
  976. if (sign != Sign::Negative) {
  977. return LONG_LONG_MAX;
  978. } else {
  979. return LONG_LONG_MIN;
  980. }
  981. }
  982. return digits.number();
  983. }
  984. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/strtoull.html
  985. unsigned long long strtoull(char const* str, char** endptr, int base)
  986. {
  987. // Parse spaces and sign
  988. char* parse_ptr = const_cast<char*>(str);
  989. strtons(parse_ptr, &parse_ptr);
  990. if (base == 16) {
  991. // Dr. POSIX: "If the value of base is 16, the characters 0x or 0X may optionally precede
  992. // the sequence of letters and digits, following the sign if present."
  993. if (*parse_ptr == '0') {
  994. if (tolower(*(parse_ptr + 1)) == 'x')
  995. parse_ptr += 2;
  996. }
  997. }
  998. // Parse base
  999. if (base == 0) {
  1000. if (*parse_ptr == '0') {
  1001. if (tolower(*(parse_ptr + 1)) == 'x') {
  1002. base = 16;
  1003. parse_ptr += 2;
  1004. } else {
  1005. base = 8;
  1006. }
  1007. } else {
  1008. base = 10;
  1009. }
  1010. }
  1011. // Parse actual digits.
  1012. ULongLongParser digits { Sign::Positive, base };
  1013. bool digits_usable = false;
  1014. bool should_continue = true;
  1015. bool overflow = false;
  1016. do {
  1017. bool is_a_digit;
  1018. if (overflow) {
  1019. is_a_digit = digits.parse_digit(*parse_ptr) >= 0;
  1020. } else {
  1021. DigitConsumeDecision decision = digits.consume(*parse_ptr);
  1022. switch (decision) {
  1023. case DigitConsumeDecision::Consumed:
  1024. is_a_digit = true;
  1025. // The very first actual digit must pass here:
  1026. digits_usable = true;
  1027. break;
  1028. case DigitConsumeDecision::PosOverflow:
  1029. case DigitConsumeDecision::NegOverflow:
  1030. is_a_digit = true;
  1031. overflow = true;
  1032. break;
  1033. case DigitConsumeDecision::Invalid:
  1034. is_a_digit = false;
  1035. break;
  1036. default:
  1037. VERIFY_NOT_REACHED();
  1038. }
  1039. }
  1040. should_continue = is_a_digit;
  1041. parse_ptr += should_continue;
  1042. } while (should_continue);
  1043. if (!digits_usable) {
  1044. // No actual number value available.
  1045. if (endptr)
  1046. *endptr = const_cast<char*>(str);
  1047. return 0;
  1048. }
  1049. if (endptr)
  1050. *endptr = parse_ptr;
  1051. if (overflow) {
  1052. errno = ERANGE;
  1053. return LONG_LONG_MAX;
  1054. }
  1055. return digits.number();
  1056. }
  1057. uint32_t arc4random(void)
  1058. {
  1059. uint32_t buf;
  1060. arc4random_buf(&buf, sizeof(buf));
  1061. return buf;
  1062. }
  1063. static pthread_mutex_t s_randomness_mutex = PTHREAD_MUTEX_INITIALIZER;
  1064. static u8* s_randomness_buffer;
  1065. static size_t s_randomness_index;
  1066. void arc4random_buf(void* buffer, size_t buffer_size)
  1067. {
  1068. pthread_mutex_lock(&s_randomness_mutex);
  1069. size_t bytes_needed = buffer_size;
  1070. auto* ptr = static_cast<u8*>(buffer);
  1071. while (bytes_needed > 0) {
  1072. if (!s_randomness_buffer || s_randomness_index >= PAGE_SIZE) {
  1073. if (!s_randomness_buffer) {
  1074. s_randomness_buffer = static_cast<u8*>(mmap(nullptr, PAGE_SIZE, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE | MAP_RANDOMIZED, 0, 0));
  1075. VERIFY(s_randomness_buffer != MAP_FAILED);
  1076. __pthread_fork_atfork_register_child(
  1077. [] {
  1078. munmap(s_randomness_buffer, PAGE_SIZE);
  1079. s_randomness_buffer = nullptr;
  1080. s_randomness_index = 0;
  1081. });
  1082. }
  1083. syscall(SC_getrandom, s_randomness_buffer, PAGE_SIZE);
  1084. s_randomness_index = 0;
  1085. }
  1086. size_t available_bytes = PAGE_SIZE - s_randomness_index;
  1087. size_t bytes_to_copy = min(bytes_needed, available_bytes);
  1088. memcpy(ptr, s_randomness_buffer + s_randomness_index, bytes_to_copy);
  1089. s_randomness_index += bytes_to_copy;
  1090. bytes_needed -= bytes_to_copy;
  1091. ptr += bytes_to_copy;
  1092. }
  1093. pthread_mutex_unlock(&s_randomness_mutex);
  1094. }
  1095. uint32_t arc4random_uniform(uint32_t max_bounds)
  1096. {
  1097. return AK::get_random_uniform(max_bounds);
  1098. }
  1099. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/realpath.html
  1100. char* realpath(char const* pathname, char* buffer)
  1101. {
  1102. if (!pathname) {
  1103. errno = EFAULT;
  1104. return nullptr;
  1105. }
  1106. size_t size = PATH_MAX;
  1107. bool self_allocated = false;
  1108. if (buffer == nullptr) {
  1109. // Since we self-allocate, try to sneakily use a smaller buffer instead, in an attempt to use less memory.
  1110. size = 64;
  1111. buffer = (char*)malloc(size);
  1112. self_allocated = true;
  1113. }
  1114. Syscall::SC_realpath_params params { { pathname, strlen(pathname) }, { buffer, size } };
  1115. int rc = syscall(SC_realpath, &params);
  1116. if (rc < 0) {
  1117. if (self_allocated)
  1118. free(buffer);
  1119. errno = -rc;
  1120. return nullptr;
  1121. }
  1122. if (self_allocated && static_cast<size_t>(rc) > size) {
  1123. // There was silent truncation, *and* we can simply retry without the caller noticing.
  1124. free(buffer);
  1125. size = static_cast<size_t>(rc);
  1126. buffer = (char*)malloc(size);
  1127. params.buffer = { buffer, size };
  1128. rc = syscall(SC_realpath, &params);
  1129. if (rc < 0) {
  1130. // Can only happen if we lose a race. Let's pretend we lost the race in the first place.
  1131. free(buffer);
  1132. errno = -rc;
  1133. return nullptr;
  1134. }
  1135. size_t new_size = static_cast<size_t>(rc);
  1136. if (new_size < size) {
  1137. // If we're here, the symlink has become longer while we were looking at it.
  1138. // There's not much we can do, unless we want to loop endlessly
  1139. // in this case. Let's leave it up to the caller whether to loop.
  1140. free(buffer);
  1141. errno = EAGAIN;
  1142. return nullptr;
  1143. }
  1144. }
  1145. errno = 0;
  1146. return buffer;
  1147. }
  1148. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/posix_openpt.html
  1149. int posix_openpt(int flags)
  1150. {
  1151. if (flags & ~(O_RDWR | O_NOCTTY | O_CLOEXEC)) {
  1152. errno = EINVAL;
  1153. return -1;
  1154. }
  1155. return open("/dev/ptmx", flags);
  1156. }
  1157. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/grantpt.html
  1158. int grantpt([[maybe_unused]] int fd)
  1159. {
  1160. return 0;
  1161. }
  1162. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/unlockpt.html
  1163. int unlockpt([[maybe_unused]] int fd)
  1164. {
  1165. return 0;
  1166. }
  1167. }
  1168. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/_Exit.html
  1169. void _Exit(int status)
  1170. {
  1171. _exit(status);
  1172. }