stdlib.cpp 33 KB

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