stdlib.cpp 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192
  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. size_t mbstowcs(wchar_t*, const char*, size_t)
  758. {
  759. dbgln("FIXME: Implement mbstowcs()");
  760. TODO();
  761. }
  762. int mbtowc(wchar_t* wch, const char* data, [[maybe_unused]] size_t data_size)
  763. {
  764. // FIXME: This needs a real implementation.
  765. if (wch && data) {
  766. *wch = *data;
  767. return 1;
  768. }
  769. if (!wch && data) {
  770. return 1;
  771. }
  772. return 0;
  773. }
  774. int wctomb(char*, wchar_t)
  775. {
  776. dbgln("FIXME: Implement wctomb()");
  777. TODO();
  778. }
  779. size_t wcstombs(char* dest, const wchar_t* src, size_t max)
  780. {
  781. char* original_dest = dest;
  782. while ((size_t)(dest - original_dest) < max) {
  783. StringView v { (const char*)src, sizeof(wchar_t) };
  784. // FIXME: dependent on locale, for now utf-8 is supported.
  785. Utf8View utf8 { v };
  786. if (*utf8.begin() == '\0') {
  787. *dest = '\0';
  788. return (size_t)(dest - original_dest); // Exclude null character in returned size
  789. }
  790. for (auto byte : utf8) {
  791. if (byte != '\0')
  792. *dest++ = byte;
  793. }
  794. ++src;
  795. }
  796. return max;
  797. }
  798. long strtol(const char* str, char** endptr, int base)
  799. {
  800. long long value = strtoll(str, endptr, base);
  801. if (value < LONG_MIN) {
  802. errno = ERANGE;
  803. return LONG_MIN;
  804. } else if (value > LONG_MAX) {
  805. errno = ERANGE;
  806. return LONG_MAX;
  807. }
  808. return value;
  809. }
  810. unsigned long strtoul(const char* str, char** endptr, int base)
  811. {
  812. unsigned long long value = strtoull(str, endptr, base);
  813. if (value > ULONG_MAX) {
  814. errno = ERANGE;
  815. return ULONG_MAX;
  816. }
  817. return value;
  818. }
  819. long long strtoll(const char* str, char** endptr, int base)
  820. {
  821. // Parse spaces and sign
  822. char* parse_ptr = const_cast<char*>(str);
  823. strtons(parse_ptr, &parse_ptr);
  824. const Sign sign = strtosign(parse_ptr, &parse_ptr);
  825. // Parse base
  826. if (base == 0) {
  827. if (*parse_ptr == '0') {
  828. if (tolower(*(parse_ptr + 1)) == 'x') {
  829. base = 16;
  830. parse_ptr += 2;
  831. } else {
  832. base = 8;
  833. }
  834. } else {
  835. base = 10;
  836. }
  837. }
  838. // Parse actual digits.
  839. LongLongParser digits { sign, base };
  840. bool digits_usable = false;
  841. bool should_continue = true;
  842. bool overflow = false;
  843. do {
  844. bool is_a_digit;
  845. if (overflow) {
  846. is_a_digit = digits.parse_digit(*parse_ptr) >= 0;
  847. } else {
  848. DigitConsumeDecision decision = digits.consume(*parse_ptr);
  849. switch (decision) {
  850. case DigitConsumeDecision::Consumed:
  851. is_a_digit = true;
  852. // The very first actual digit must pass here:
  853. digits_usable = true;
  854. break;
  855. case DigitConsumeDecision::PosOverflow:
  856. case DigitConsumeDecision::NegOverflow:
  857. is_a_digit = true;
  858. overflow = true;
  859. break;
  860. case DigitConsumeDecision::Invalid:
  861. is_a_digit = false;
  862. break;
  863. default:
  864. VERIFY_NOT_REACHED();
  865. }
  866. }
  867. should_continue = is_a_digit;
  868. parse_ptr += should_continue;
  869. } while (should_continue);
  870. if (!digits_usable) {
  871. // No actual number value available.
  872. if (endptr)
  873. *endptr = const_cast<char*>(str);
  874. return 0;
  875. }
  876. if (endptr)
  877. *endptr = parse_ptr;
  878. if (overflow) {
  879. errno = ERANGE;
  880. if (sign != Sign::Negative) {
  881. return LONG_LONG_MAX;
  882. } else {
  883. return LONG_LONG_MIN;
  884. }
  885. }
  886. return digits.number();
  887. }
  888. unsigned long long strtoull(const char* str, char** endptr, int base)
  889. {
  890. // Parse spaces and sign
  891. char* parse_ptr = const_cast<char*>(str);
  892. strtons(parse_ptr, &parse_ptr);
  893. if (base == 16) {
  894. // Dr. POSIX: "If the value of base is 16, the characters 0x or 0X may optionally precede
  895. // the sequence of letters and digits, following the sign if present."
  896. if (*parse_ptr == '0') {
  897. if (tolower(*(parse_ptr + 1)) == 'x')
  898. parse_ptr += 2;
  899. }
  900. }
  901. // Parse base
  902. if (base == 0) {
  903. if (*parse_ptr == '0') {
  904. if (tolower(*(parse_ptr + 1)) == 'x') {
  905. base = 16;
  906. parse_ptr += 2;
  907. } else {
  908. base = 8;
  909. }
  910. } else {
  911. base = 10;
  912. }
  913. }
  914. // Parse actual digits.
  915. ULongLongParser digits { Sign::Positive, base };
  916. bool digits_usable = false;
  917. bool should_continue = true;
  918. bool overflow = false;
  919. do {
  920. bool is_a_digit;
  921. if (overflow) {
  922. is_a_digit = digits.parse_digit(*parse_ptr) >= 0;
  923. } else {
  924. DigitConsumeDecision decision = digits.consume(*parse_ptr);
  925. switch (decision) {
  926. case DigitConsumeDecision::Consumed:
  927. is_a_digit = true;
  928. // The very first actual digit must pass here:
  929. digits_usable = true;
  930. break;
  931. case DigitConsumeDecision::PosOverflow:
  932. case DigitConsumeDecision::NegOverflow:
  933. is_a_digit = true;
  934. overflow = true;
  935. break;
  936. case DigitConsumeDecision::Invalid:
  937. is_a_digit = false;
  938. break;
  939. default:
  940. VERIFY_NOT_REACHED();
  941. }
  942. }
  943. should_continue = is_a_digit;
  944. parse_ptr += should_continue;
  945. } while (should_continue);
  946. if (!digits_usable) {
  947. // No actual number value available.
  948. if (endptr)
  949. *endptr = const_cast<char*>(str);
  950. return 0;
  951. }
  952. if (endptr)
  953. *endptr = parse_ptr;
  954. if (overflow) {
  955. errno = ERANGE;
  956. return LONG_LONG_MAX;
  957. }
  958. return digits.number();
  959. }
  960. // Serenity's PRNG is not cryptographically secure. Do not rely on this for
  961. // any real crypto! These functions (for now) are for compatibility.
  962. // TODO: In the future, rand can be made deterministic and this not.
  963. uint32_t arc4random(void)
  964. {
  965. uint32_t buf;
  966. syscall(SC_getrandom, &buf, sizeof(buf), 0);
  967. return buf;
  968. }
  969. void arc4random_buf(void* buffer, size_t buffer_size)
  970. {
  971. // arc4random_buf should never fail, but user supplied buffers could fail.
  972. // However, if the user passes a garbage buffer, that's on them.
  973. syscall(SC_getrandom, buffer, buffer_size, 0);
  974. }
  975. uint32_t arc4random_uniform(uint32_t max_bounds)
  976. {
  977. return AK::get_random_uniform(max_bounds);
  978. }
  979. char* realpath(const char* pathname, char* buffer)
  980. {
  981. if (!pathname) {
  982. errno = EFAULT;
  983. return nullptr;
  984. }
  985. size_t size = PATH_MAX;
  986. bool self_allocated = false;
  987. if (buffer == nullptr) {
  988. // Since we self-allocate, try to sneakily use a smaller buffer instead, in an attempt to use less memory.
  989. size = 64;
  990. buffer = (char*)malloc(size);
  991. self_allocated = true;
  992. }
  993. Syscall::SC_realpath_params params { { pathname, strlen(pathname) }, { buffer, size } };
  994. int rc = syscall(SC_realpath, &params);
  995. if (rc < 0) {
  996. if (self_allocated)
  997. free(buffer);
  998. errno = -rc;
  999. return nullptr;
  1000. }
  1001. if (self_allocated && static_cast<size_t>(rc) > size) {
  1002. // There was silent truncation, *and* we can simply retry without the caller noticing.
  1003. free(buffer);
  1004. size = static_cast<size_t>(rc);
  1005. buffer = (char*)malloc(size);
  1006. params.buffer = { buffer, size };
  1007. rc = syscall(SC_realpath, &params);
  1008. if (rc < 0) {
  1009. // Can only happen if we lose a race. Let's pretend we lost the race in the first place.
  1010. free(buffer);
  1011. errno = -rc;
  1012. return nullptr;
  1013. }
  1014. size_t new_size = static_cast<size_t>(rc);
  1015. if (new_size < size) {
  1016. // If we're here, the symlink has become longer while we were looking at it.
  1017. // There's not much we can do, unless we want to loop endlessly
  1018. // in this case. Let's leave it up to the caller whether to loop.
  1019. free(buffer);
  1020. errno = EAGAIN;
  1021. return nullptr;
  1022. }
  1023. }
  1024. errno = 0;
  1025. return buffer;
  1026. }
  1027. int posix_openpt(int flags)
  1028. {
  1029. if (flags & ~(O_RDWR | O_NOCTTY | O_CLOEXEC)) {
  1030. errno = EINVAL;
  1031. return -1;
  1032. }
  1033. return open("/dev/ptmx", flags);
  1034. }
  1035. int grantpt([[maybe_unused]] int fd)
  1036. {
  1037. return 0;
  1038. }
  1039. int unlockpt([[maybe_unused]] int fd)
  1040. {
  1041. return 0;
  1042. }
  1043. }
  1044. void _Exit(int status)
  1045. {
  1046. _exit(status);
  1047. }