stdlib.cpp 31 KB

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