stdlib.cpp 31 KB

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