stdlib.cpp 32 KB

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