stdlib.cpp 32 KB

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