stdlib.cpp 36 KB

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