stdlib.cpp 32 KB

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