stdlib.cpp 32 KB

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