stdlib.cpp 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240
  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/CharacterTypes.h>
  8. #include <AK/FloatingPointStringConversions.h>
  9. #include <AK/HashMap.h>
  10. #include <AK/Noncopyable.h>
  11. #include <AK/Random.h>
  12. #include <AK/StdLibExtras.h>
  13. #include <AK/Types.h>
  14. #include <AK/Utf8View.h>
  15. #include <alloca.h>
  16. #include <assert.h>
  17. #include <bits/pthread_cancel.h>
  18. #include <ctype.h>
  19. #include <errno.h>
  20. #include <fcntl.h>
  21. #include <pthread.h>
  22. #include <signal.h>
  23. #include <spawn.h>
  24. #include <stdio.h>
  25. #include <stdlib.h>
  26. #include <string.h>
  27. #include <sys/auxv.h>
  28. #include <sys/internals.h>
  29. #include <sys/ioctl.h>
  30. #include <sys/mman.h>
  31. #include <sys/stat.h>
  32. #include <sys/sysmacros.h>
  33. #include <sys/wait.h>
  34. #include <syscall.h>
  35. #include <unistd.h>
  36. #include <wchar.h>
  37. static void strtons(char const* str, char** endptr)
  38. {
  39. assert(endptr);
  40. char* ptr = const_cast<char*>(str);
  41. while (isspace(*ptr)) {
  42. ptr += 1;
  43. }
  44. *endptr = ptr;
  45. }
  46. enum Sign {
  47. Negative,
  48. Positive,
  49. };
  50. static Sign strtosign(char const* str, char** endptr)
  51. {
  52. assert(endptr);
  53. if (*str == '+') {
  54. *endptr = const_cast<char*>(str + 1);
  55. return Sign::Positive;
  56. } else if (*str == '-') {
  57. *endptr = const_cast<char*>(str + 1);
  58. return Sign::Negative;
  59. } else {
  60. *endptr = const_cast<char*>(str);
  61. return Sign::Positive;
  62. }
  63. }
  64. enum DigitConsumeDecision {
  65. Consumed,
  66. PosOverflow,
  67. NegOverflow,
  68. Invalid,
  69. };
  70. template<typename T, T min_value, T max_value>
  71. class NumParser {
  72. AK_MAKE_NONMOVABLE(NumParser);
  73. public:
  74. NumParser(Sign sign, int base)
  75. : m_base(base)
  76. , m_num(0)
  77. , m_sign(sign)
  78. {
  79. m_cutoff = positive() ? (max_value / base) : (min_value / base);
  80. m_max_digit_after_cutoff = positive() ? (max_value % base) : (min_value % base);
  81. }
  82. int parse_digit(char ch)
  83. {
  84. int digit;
  85. if (isdigit(ch))
  86. digit = ch - '0';
  87. else if (islower(ch))
  88. digit = ch - ('a' - 10);
  89. else if (isupper(ch))
  90. digit = ch - ('A' - 10);
  91. else
  92. return -1;
  93. if (static_cast<T>(digit) >= m_base)
  94. return -1;
  95. return digit;
  96. }
  97. DigitConsumeDecision consume(char ch)
  98. {
  99. int digit = parse_digit(ch);
  100. if (digit == -1)
  101. return DigitConsumeDecision::Invalid;
  102. if (!can_append_digit(digit)) {
  103. if (m_sign != Sign::Negative) {
  104. return DigitConsumeDecision::PosOverflow;
  105. } else {
  106. return DigitConsumeDecision::NegOverflow;
  107. }
  108. }
  109. m_num *= m_base;
  110. m_num += positive() ? digit : -digit;
  111. return DigitConsumeDecision::Consumed;
  112. }
  113. T number() const { return m_num; }
  114. private:
  115. bool can_append_digit(int digit)
  116. {
  117. bool const is_below_cutoff = positive() ? (m_num < m_cutoff) : (m_num > m_cutoff);
  118. if (is_below_cutoff) {
  119. return true;
  120. } else {
  121. return m_num == m_cutoff && digit <= m_max_digit_after_cutoff;
  122. }
  123. }
  124. bool positive() const
  125. {
  126. return m_sign != Sign::Negative;
  127. }
  128. const T m_base;
  129. T m_num;
  130. T m_cutoff;
  131. int m_max_digit_after_cutoff;
  132. Sign m_sign;
  133. };
  134. typedef NumParser<int, INT_MIN, INT_MAX> IntParser;
  135. typedef NumParser<long long, LONG_LONG_MIN, LONG_LONG_MAX> LongLongParser;
  136. typedef NumParser<unsigned long long, 0ULL, ULONG_LONG_MAX> ULongLongParser;
  137. static bool is_either(char* str, int offset, char lower, char upper)
  138. {
  139. char ch = *(str + offset);
  140. return ch == lower || ch == upper;
  141. }
  142. template<typename Callback>
  143. inline int generate_unique_filename(char* pattern, size_t suffix_length, Callback callback)
  144. {
  145. size_t length = strlen(pattern);
  146. if (length < 6 + suffix_length || memcmp(pattern + length - 6 - suffix_length, "XXXXXX", 6))
  147. return EINVAL;
  148. size_t start = length - 6 - suffix_length;
  149. constexpr char random_characters[] = "abcdefghijklmnopqrstuvwxyz0123456789";
  150. for (int attempt = 0; attempt < 100; ++attempt) {
  151. for (int i = 0; i < 6; ++i)
  152. pattern[start + i] = random_characters[(arc4random() % (sizeof(random_characters) - 1))];
  153. if (callback() == IterationDecision::Break)
  154. return 0;
  155. }
  156. return EEXIST;
  157. }
  158. static bool is_infinity_string(char* parse_ptr, char** endptr)
  159. {
  160. if (is_either(parse_ptr, 0, 'i', 'I')) {
  161. if (is_either(parse_ptr, 1, 'n', 'N')) {
  162. if (is_either(parse_ptr, 2, 'f', 'F')) {
  163. parse_ptr += 3;
  164. if (is_either(parse_ptr, 0, 'i', 'I')) {
  165. if (is_either(parse_ptr, 1, 'n', 'N')) {
  166. if (is_either(parse_ptr, 2, 'i', 'I')) {
  167. if (is_either(parse_ptr, 3, 't', 'T')) {
  168. if (is_either(parse_ptr, 4, 'y', 'Y')) {
  169. parse_ptr += 5;
  170. }
  171. }
  172. }
  173. }
  174. }
  175. if (endptr)
  176. *endptr = parse_ptr;
  177. return true;
  178. }
  179. }
  180. }
  181. return false;
  182. }
  183. static bool is_nan_string(char* parse_ptr, char** endptr)
  184. {
  185. // FIXME: Actually parse (or at least skip) the (n-char-sequenceopt) part
  186. if (is_either(parse_ptr, 0, 'n', 'N')) {
  187. if (is_either(parse_ptr, 1, 'a', 'A')) {
  188. if (is_either(parse_ptr, 2, 'n', 'N')) {
  189. if (endptr)
  190. *endptr = parse_ptr + 3;
  191. return true;
  192. }
  193. }
  194. }
  195. return false;
  196. }
  197. template<FloatingPoint T>
  198. static T c_str_to_floating_point(char const* str, char** endptr)
  199. {
  200. // First, they decompose the input string into three parts:
  201. char* parse_ptr = const_cast<char*>(str);
  202. // An initial, possibly empty, sequence of white-space characters (as specified by isspace())
  203. strtons(parse_ptr, &parse_ptr);
  204. // A subject sequence interpreted as a floating-point constant or representing infinity or NaN
  205. if (*parse_ptr == '\0') {
  206. if (endptr)
  207. *endptr = const_cast<char*>(str);
  208. return 0.;
  209. }
  210. bool is_hex = [&] {
  211. // A hexfloat must start with either 0x, 0X, -0x or -0X and have something after it
  212. char const* parse_head = parse_ptr;
  213. if (*parse_head == '-')
  214. ++parse_head;
  215. if (*parse_head != '0')
  216. return false;
  217. ++parse_head;
  218. if (*parse_head != 'x')
  219. return false;
  220. ++parse_head;
  221. // We must have at least one digit but it can come after the "decimal" point.
  222. if (is_ascii_hex_digit(*parse_head))
  223. return true;
  224. if (*parse_head != '.')
  225. return false;
  226. ++parse_head;
  227. return is_ascii_hex_digit(*parse_head);
  228. }();
  229. AK::FloatingPointParseResults<T> double_parse_result;
  230. if (is_hex) {
  231. // A 0x or 0X, then a non-empty sequence of hexadecimal digits optionally containing a radix character;
  232. // then an optional binary exponent part consisting of the character 'p' or the character 'P',
  233. // optionally followed by a '+' or '-' character, and then followed by one or more decimal digits
  234. double_parse_result = AK::parse_first_hexfloat_until_zero_character<T>(parse_ptr);
  235. } else {
  236. // A non-empty sequence of decimal digits optionally containing a radix character;
  237. // then an optional exponent part consisting of the character 'e' or the character 'E',
  238. // optionally followed by a '+' or '-' character, and then followed by one or more decimal digits
  239. double_parse_result = AK::parse_first_floating_point_until_zero_character<T>(parse_ptr);
  240. }
  241. if (double_parse_result.error == AK::FloatingPointError::None) {
  242. // The only way to get NaN (which we shouldn't) or infinities is rounding up to them so we
  243. // have to set ERANGE in that case.
  244. if (!__builtin_isfinite(double_parse_result.value))
  245. errno = ERANGE;
  246. if (endptr)
  247. *endptr = const_cast<char*>(double_parse_result.end_ptr);
  248. return double_parse_result.value;
  249. }
  250. if (double_parse_result.error == AK::FloatingPointError::RoundedDownToZero || double_parse_result.error == AK::FloatingPointError::OutOfRange) {
  251. // This is a special case for strtod, where we have a double so close to zero we had to round
  252. // it to zero, in which case we have to set ERANGE
  253. errno = ERANGE;
  254. if (endptr)
  255. *endptr = const_cast<char*>(double_parse_result.end_ptr);
  256. return double_parse_result.value;
  257. }
  258. // The only way we are here is if the input was not valid for parse_first_floating_point or not a valid hex float
  259. // So the only cases left are:
  260. // - One of INF or INFINITY, ignoring case
  261. // - One of NAN or NAN(n-char-sequenceopt), ignoring case in the NAN part
  262. const Sign sign = strtosign(parse_ptr, &parse_ptr);
  263. if (is_infinity_string(parse_ptr, endptr)) {
  264. // Don't set errno to ERANGE here:
  265. // The caller may want to distinguish between "input is
  266. // literal infinity" and "input is not literal infinity
  267. // but did not fit into double".
  268. if (sign != Sign::Negative)
  269. return static_cast<T>(__builtin_huge_val());
  270. else
  271. return static_cast<T>(-__builtin_huge_val());
  272. }
  273. if (is_nan_string(parse_ptr, endptr)) {
  274. errno = ERANGE;
  275. // FIXME: Do we actually want to return "different" NaN bit values?
  276. if (sign != Sign::Negative)
  277. return static_cast<T>(__builtin_nan(""));
  278. else
  279. return static_cast<T>(-__builtin_nan(""));
  280. }
  281. // If no conversion could be performed, 0 shall be returned, and errno may be set to [EINVAL].
  282. // FIXME: This is in the posix standard linked from strtod but not in implementations of strtod
  283. // and not in the man pages for linux strtod.
  284. if (endptr)
  285. *endptr = const_cast<char*>(str);
  286. return 0;
  287. }
  288. extern "C" {
  289. void exit(int status)
  290. {
  291. __cxa_finalize(nullptr);
  292. if (secure_getenv("LIBC_DUMP_MALLOC_STATS"))
  293. serenity_dump_malloc_stats();
  294. extern void _fini();
  295. _fini();
  296. fflush(nullptr);
  297. #ifndef _DYNAMIC_LOADER
  298. __pthread_key_destroy_for_current_thread();
  299. #endif
  300. _exit(status);
  301. }
  302. static void __atexit_to_cxa_atexit(void* handler)
  303. {
  304. reinterpret_cast<void (*)()>(handler)();
  305. }
  306. int atexit(void (*handler)())
  307. {
  308. return __cxa_atexit(__atexit_to_cxa_atexit, (void*)handler, nullptr);
  309. }
  310. void _abort()
  311. {
  312. // According to the GCC manual __builtin_trap() can call abort() so using it here might not seem safe at first. However,
  313. // on all the platforms we support GCC emits an undefined instruction instead of a call.
  314. __builtin_trap();
  315. }
  316. void abort()
  317. {
  318. // For starters, send ourselves a SIGABRT.
  319. raise(SIGABRT);
  320. // If that didn't kill us, try harder.
  321. sigset_t set;
  322. sigemptyset(&set);
  323. sigaddset(&set, SIGABRT);
  324. sigprocmask(SIG_UNBLOCK, &set, nullptr);
  325. raise(SIGABRT);
  326. _abort();
  327. }
  328. static HashTable<FlatPtr> s_malloced_environment_variables;
  329. static void free_environment_variable_if_needed(char const* var)
  330. {
  331. if (!s_malloced_environment_variables.contains((FlatPtr)var))
  332. return;
  333. s_malloced_environment_variables.remove((FlatPtr)var);
  334. free(const_cast<char*>(var));
  335. }
  336. char* getenv(char const* name)
  337. {
  338. size_t vl = strlen(name);
  339. for (size_t i = 0; environ[i]; ++i) {
  340. char const* decl = environ[i];
  341. char* eq = strchr(decl, '=');
  342. if (!eq)
  343. continue;
  344. size_t varLength = eq - decl;
  345. if (vl != varLength)
  346. continue;
  347. if (strncmp(decl, name, varLength) == 0)
  348. return eq + 1;
  349. }
  350. return nullptr;
  351. }
  352. char* secure_getenv(char const* name)
  353. {
  354. if (getauxval(AT_SECURE))
  355. return nullptr;
  356. return getenv(name);
  357. }
  358. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/unsetenv.html
  359. int unsetenv(char const* name)
  360. {
  361. auto new_var_len = strlen(name);
  362. if (new_var_len == 0 || strchr(name, '=')) {
  363. errno = EINVAL;
  364. return -1;
  365. }
  366. size_t environ_size = 0;
  367. int skip = -1;
  368. for (; environ[environ_size]; ++environ_size) {
  369. char* old_var = environ[environ_size];
  370. char* old_eq = strchr(old_var, '=');
  371. VERIFY(old_eq);
  372. size_t old_var_len = old_eq - old_var;
  373. if (new_var_len != old_var_len)
  374. continue; // can't match
  375. if (strncmp(name, old_var, new_var_len) == 0)
  376. skip = environ_size;
  377. }
  378. if (skip == -1)
  379. return 0; // not found: no failure.
  380. // Shuffle the existing array down by one.
  381. memmove(&environ[skip], &environ[skip + 1], ((environ_size - 1) - skip) * sizeof(environ[0]));
  382. environ[environ_size - 1] = nullptr;
  383. free_environment_variable_if_needed(name);
  384. return 0;
  385. }
  386. int clearenv()
  387. {
  388. size_t environ_size = 0;
  389. for (; environ[environ_size]; ++environ_size) {
  390. environ[environ_size] = NULL;
  391. }
  392. *environ = NULL;
  393. return 0;
  394. }
  395. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/setenv.html
  396. int setenv(char const* name, char const* value, int overwrite)
  397. {
  398. if (!overwrite && getenv(name))
  399. return 0;
  400. auto const total_length = strlen(name) + strlen(value) + 2;
  401. auto* var = (char*)malloc(total_length);
  402. snprintf(var, total_length, "%s=%s", name, value);
  403. s_malloced_environment_variables.set((FlatPtr)var);
  404. return putenv(var);
  405. }
  406. // A non-evil version of putenv that will strdup the env (and free it later)
  407. int serenity_putenv(char const* new_var, size_t length)
  408. {
  409. auto* var = strndup(new_var, length);
  410. s_malloced_environment_variables.set((FlatPtr)var);
  411. return putenv(var);
  412. }
  413. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/putenv.html
  414. int putenv(char* new_var)
  415. {
  416. char* new_eq = strchr(new_var, '=');
  417. if (!new_eq)
  418. return unsetenv(new_var);
  419. auto new_var_name_len = new_eq - new_var;
  420. int environ_size = 0;
  421. for (; environ[environ_size]; ++environ_size) {
  422. char* old_var = environ[environ_size];
  423. auto old_var_name_max_length = strnlen(old_var, new_var_name_len);
  424. char* old_eq = static_cast<char*>(memchr(old_var, '=', old_var_name_max_length + 1));
  425. if (!old_eq)
  426. continue; // name is longer, or possibly freed or overwritten value
  427. auto old_var_name_len = old_eq - old_var;
  428. if (new_var_name_len != old_var_name_len)
  429. continue; // can't match
  430. if (strncmp(new_var, old_var, new_var_name_len) == 0) {
  431. free_environment_variable_if_needed(old_var);
  432. environ[environ_size] = new_var;
  433. return 0;
  434. }
  435. }
  436. // At this point, we need to append the new var.
  437. // 2 here: one for the new var, one for the sentinel value.
  438. auto** new_environ = static_cast<char**>(kmalloc_array(environ_size + 2, sizeof(char*)));
  439. if (new_environ == nullptr) {
  440. errno = ENOMEM;
  441. return -1;
  442. }
  443. for (int i = 0; environ[i]; ++i)
  444. new_environ[i] = environ[i];
  445. new_environ[environ_size] = new_var;
  446. new_environ[environ_size + 1] = nullptr;
  447. // swap new and old
  448. // note that the initial environ is not heap allocated!
  449. extern bool __environ_is_malloced;
  450. if (__environ_is_malloced)
  451. free(environ);
  452. __environ_is_malloced = true;
  453. environ = new_environ;
  454. return 0;
  455. }
  456. static char const* __progname = NULL;
  457. char const* getprogname()
  458. {
  459. return __progname;
  460. }
  461. void setprogname(char const* progname)
  462. {
  463. for (int i = strlen(progname) - 1; i >= 0; i--) {
  464. if (progname[i] == '/') {
  465. __progname = progname + i + 1;
  466. return;
  467. }
  468. }
  469. __progname = progname;
  470. }
  471. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/strtod.html
  472. double strtod(char const* str, char** endptr)
  473. {
  474. return c_str_to_floating_point<double>(str, endptr);
  475. }
  476. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/strtold.html
  477. long double strtold(char const* str, char** endptr)
  478. {
  479. assert(sizeof(double) == sizeof(long double));
  480. return strtod(str, endptr);
  481. }
  482. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/strtof.html
  483. float strtof(char const* str, char** endptr)
  484. {
  485. return c_str_to_floating_point<float>(str, endptr);
  486. }
  487. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/atof.html
  488. double atof(char const* str)
  489. {
  490. return strtod(str, nullptr);
  491. }
  492. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/atoi.html
  493. int atoi(char const* str)
  494. {
  495. long value = strtol(str, nullptr, 10);
  496. if (value > INT_MAX) {
  497. return INT_MAX;
  498. }
  499. return value;
  500. }
  501. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/atol.html
  502. long atol(char const* str)
  503. {
  504. return strtol(str, nullptr, 10);
  505. }
  506. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/atoll.html
  507. long long atoll(char const* str)
  508. {
  509. return strtoll(str, nullptr, 10);
  510. }
  511. static char ptsname_buf[32];
  512. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/ptsname.html
  513. char* ptsname(int fd)
  514. {
  515. if (ptsname_r(fd, ptsname_buf, sizeof(ptsname_buf)) < 0)
  516. return nullptr;
  517. return ptsname_buf;
  518. }
  519. int ptsname_r(int fd, char* buffer, size_t size)
  520. {
  521. struct stat stat;
  522. if (fstat(fd, &stat) < 0)
  523. return -1;
  524. StringBuilder devpts_path_builder;
  525. devpts_path_builder.append("/dev/pts/"sv);
  526. int master_pty_index = 0;
  527. // Note: When the user opens a PTY from /dev/ptmx with posix_openpt(), the open file descriptor
  528. // points to /dev/ptmx, (major number is 5 and minor number is 2), but internally
  529. // in the kernel, it points to a new MasterPTY device. When we do ioctl with TIOCGPTN option
  530. // on the open file descriptor, it actually asks the MasterPTY what is the assigned index
  531. // of it when the PTYMultiplexer created it.
  532. if (ioctl(fd, TIOCGPTN, &master_pty_index) < 0)
  533. return -1;
  534. if (master_pty_index < 0) {
  535. errno = EINVAL;
  536. return -1;
  537. }
  538. devpts_path_builder.appendff("{:d}", master_pty_index);
  539. if (devpts_path_builder.length() > size) {
  540. errno = ERANGE;
  541. return -1;
  542. }
  543. memset(buffer, 0, devpts_path_builder.length() + 1);
  544. auto full_devpts_path_string = devpts_path_builder.to_deprecated_string();
  545. if (!full_devpts_path_string.copy_characters_to_buffer(buffer, size)) {
  546. errno = ERANGE;
  547. return -1;
  548. }
  549. return 0;
  550. }
  551. static unsigned long s_next_rand = 1;
  552. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/rand.html
  553. int rand()
  554. {
  555. s_next_rand = s_next_rand * 1103515245 + 12345;
  556. return ((unsigned)(s_next_rand / ((RAND_MAX + 1) * 2)) % (RAND_MAX + 1));
  557. }
  558. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/srand.html
  559. void srand(unsigned seed)
  560. {
  561. s_next_rand = seed;
  562. }
  563. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/abs.html
  564. int abs(int i)
  565. {
  566. return i < 0 ? -i : i;
  567. }
  568. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/labs.html
  569. long int labs(long int i)
  570. {
  571. return i < 0 ? -i : i;
  572. }
  573. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/llabs.html
  574. long long int llabs(long long int i)
  575. {
  576. return i < 0 ? -i : i;
  577. }
  578. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/random.html
  579. long int random()
  580. {
  581. return rand();
  582. }
  583. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/srandom.html
  584. void srandom(unsigned seed)
  585. {
  586. srand(seed);
  587. }
  588. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/system.html
  589. int system(char const* command)
  590. {
  591. __pthread_maybe_cancel();
  592. if (!command)
  593. return 1;
  594. pid_t child;
  595. char const* argv[] = { "sh", "-c", command, nullptr };
  596. if ((errno = posix_spawn(&child, "/bin/sh", nullptr, nullptr, const_cast<char**>(argv), environ)))
  597. return -1;
  598. int wstatus;
  599. waitpid(child, &wstatus, 0);
  600. return WEXITSTATUS(wstatus);
  601. }
  602. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/mktemp.html
  603. char* mktemp(char* pattern)
  604. {
  605. auto error = generate_unique_filename(pattern, 0, [&] {
  606. struct stat st;
  607. int rc = lstat(pattern, &st);
  608. if (rc < 0 && errno == ENOENT)
  609. return IterationDecision::Break;
  610. return IterationDecision::Continue;
  611. });
  612. if (error) {
  613. pattern[0] = '\0';
  614. errno = error;
  615. }
  616. return pattern;
  617. }
  618. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/mkstemp.html
  619. int mkstemp(char* pattern)
  620. {
  621. return mkstemps(pattern, 0);
  622. }
  623. // https://man7.org/linux/man-pages/man3/mkstemps.3.html
  624. int mkstemps(char* pattern, int suffix_length)
  625. {
  626. VERIFY(suffix_length >= 0);
  627. int fd = -1;
  628. auto error = generate_unique_filename(pattern, static_cast<size_t>(suffix_length), [&] {
  629. fd = open(pattern, O_RDWR | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR); // I'm using the flags I saw glibc using.
  630. if (fd >= 0)
  631. return IterationDecision::Break;
  632. return IterationDecision::Continue;
  633. });
  634. if (error) {
  635. errno = error;
  636. return -1;
  637. }
  638. return fd;
  639. }
  640. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/mkdtemp.html
  641. char* mkdtemp(char* pattern)
  642. {
  643. auto error = generate_unique_filename(pattern, 0, [&] {
  644. if (mkdir(pattern, 0700) == 0)
  645. return IterationDecision::Break;
  646. return IterationDecision::Continue;
  647. });
  648. if (error) {
  649. errno = error;
  650. return nullptr;
  651. }
  652. return pattern;
  653. }
  654. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/bsearch.html
  655. void* bsearch(void const* key, void const* base, size_t nmemb, size_t size, int (*compar)(void const*, void const*))
  656. {
  657. char* start = static_cast<char*>(const_cast<void*>(base));
  658. while (nmemb > 0) {
  659. char* middle_memb = start + (nmemb / 2) * size;
  660. int comparison = compar(key, middle_memb);
  661. if (comparison == 0)
  662. return middle_memb;
  663. else if (comparison > 0) {
  664. start = middle_memb + size;
  665. --nmemb;
  666. }
  667. nmemb /= 2;
  668. }
  669. return nullptr;
  670. }
  671. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/div.html
  672. div_t div(int numerator, int denominator)
  673. {
  674. div_t result;
  675. result.quot = numerator / denominator;
  676. result.rem = numerator % denominator;
  677. if (numerator >= 0 && result.rem < 0) {
  678. result.quot++;
  679. result.rem -= denominator;
  680. }
  681. return result;
  682. }
  683. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/ldiv.html
  684. ldiv_t ldiv(long numerator, long denominator)
  685. {
  686. ldiv_t result;
  687. result.quot = numerator / denominator;
  688. result.rem = numerator % denominator;
  689. if (numerator >= 0 && result.rem < 0) {
  690. result.quot++;
  691. result.rem -= denominator;
  692. }
  693. return result;
  694. }
  695. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/lldiv.html
  696. lldiv_t lldiv(long long numerator, long long denominator)
  697. {
  698. lldiv_t result;
  699. result.quot = numerator / denominator;
  700. result.rem = numerator % denominator;
  701. if (numerator >= 0 && result.rem < 0) {
  702. result.quot++;
  703. result.rem -= denominator;
  704. }
  705. return result;
  706. }
  707. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/mblen.html
  708. int mblen(char const* s, size_t n)
  709. {
  710. // POSIX: Equivalent to mbtowc(NULL, s, n), but we mustn't change the state of mbtowc.
  711. static mbstate_t internal_state = {};
  712. // Reset the internal state and ask whether we have shift states.
  713. if (s == nullptr) {
  714. internal_state = {};
  715. return 0;
  716. }
  717. size_t ret = mbrtowc(nullptr, s, n, &internal_state);
  718. // Incomplete characters get returned as illegal sequence.
  719. if (ret == -2ul) {
  720. errno = EILSEQ;
  721. return -1;
  722. }
  723. return ret;
  724. }
  725. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/mbstowcs.html
  726. size_t mbstowcs(wchar_t* pwcs, char const* s, size_t n)
  727. {
  728. static mbstate_t state = {};
  729. return mbsrtowcs(pwcs, &s, n, &state);
  730. }
  731. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/mbtowc.html
  732. int mbtowc(wchar_t* pwc, char const* s, size_t n)
  733. {
  734. static mbstate_t internal_state = {};
  735. // Reset the internal state and ask whether we have shift states.
  736. if (s == nullptr) {
  737. internal_state = {};
  738. return 0;
  739. }
  740. size_t ret = mbrtowc(pwc, s, n, &internal_state);
  741. // Incomplete characters get returned as illegal sequence.
  742. // Internal state is undefined, so don't bother with resetting.
  743. if (ret == -2ul) {
  744. errno = EILSEQ;
  745. return -1;
  746. }
  747. return ret;
  748. }
  749. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/wctomb.html
  750. int wctomb(char* s, wchar_t wc)
  751. {
  752. static mbstate_t _internal_state = {};
  753. // nullptr asks whether we have state-dependent encodings, but we don't have any.
  754. if (s == nullptr)
  755. return 0;
  756. return static_cast<int>(wcrtomb(s, wc, &_internal_state));
  757. }
  758. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/wcstombs.html
  759. size_t wcstombs(char* dest, wchar_t const* src, size_t max)
  760. {
  761. char* original_dest = dest;
  762. while ((size_t)(dest - original_dest) < max) {
  763. StringView v { (char const*)src, sizeof(wchar_t) };
  764. // FIXME: dependent on locale, for now utf-8 is supported.
  765. Utf8View utf8 { v };
  766. if (*utf8.begin() == '\0') {
  767. *dest = '\0';
  768. return (size_t)(dest - original_dest); // Exclude null character in returned size
  769. }
  770. for (auto byte : utf8) {
  771. if (byte != '\0')
  772. *dest++ = byte;
  773. }
  774. ++src;
  775. }
  776. return max;
  777. }
  778. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/strtol.html
  779. long strtol(char const* str, char** endptr, int base)
  780. {
  781. long long value = strtoll(str, endptr, base);
  782. if (value < LONG_MIN) {
  783. errno = ERANGE;
  784. return LONG_MIN;
  785. } else if (value > LONG_MAX) {
  786. errno = ERANGE;
  787. return LONG_MAX;
  788. }
  789. return value;
  790. }
  791. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/strtoul.html
  792. unsigned long strtoul(char const* str, char** endptr, int base)
  793. {
  794. unsigned long long value = strtoull(str, endptr, base);
  795. if (value > ULONG_MAX) {
  796. errno = ERANGE;
  797. return ULONG_MAX;
  798. }
  799. return value;
  800. }
  801. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/strtoll.html
  802. long long strtoll(char const* str, char** endptr, int base)
  803. {
  804. // Parse spaces and sign
  805. char* parse_ptr = const_cast<char*>(str);
  806. strtons(parse_ptr, &parse_ptr);
  807. const Sign sign = strtosign(parse_ptr, &parse_ptr);
  808. // Parse base
  809. if (base == 0) {
  810. if (*parse_ptr == '0') {
  811. if (tolower(*(parse_ptr + 1)) == 'x') {
  812. base = 16;
  813. parse_ptr += 2;
  814. } else {
  815. base = 8;
  816. }
  817. } else {
  818. base = 10;
  819. }
  820. }
  821. // Parse actual digits.
  822. LongLongParser digits { sign, base };
  823. bool digits_usable = false;
  824. bool should_continue = true;
  825. bool overflow = false;
  826. do {
  827. bool is_a_digit;
  828. if (overflow) {
  829. is_a_digit = digits.parse_digit(*parse_ptr) >= 0;
  830. } else {
  831. DigitConsumeDecision decision = digits.consume(*parse_ptr);
  832. switch (decision) {
  833. case DigitConsumeDecision::Consumed:
  834. is_a_digit = true;
  835. // The very first actual digit must pass here:
  836. digits_usable = true;
  837. break;
  838. case DigitConsumeDecision::PosOverflow:
  839. case DigitConsumeDecision::NegOverflow:
  840. is_a_digit = true;
  841. overflow = true;
  842. break;
  843. case DigitConsumeDecision::Invalid:
  844. is_a_digit = false;
  845. break;
  846. default:
  847. VERIFY_NOT_REACHED();
  848. }
  849. }
  850. should_continue = is_a_digit;
  851. parse_ptr += should_continue;
  852. } while (should_continue);
  853. if (!digits_usable) {
  854. // No actual number value available.
  855. if (endptr)
  856. *endptr = const_cast<char*>(str);
  857. return 0;
  858. }
  859. if (endptr)
  860. *endptr = parse_ptr;
  861. if (overflow) {
  862. errno = ERANGE;
  863. if (sign != Sign::Negative) {
  864. return LONG_LONG_MAX;
  865. } else {
  866. return LONG_LONG_MIN;
  867. }
  868. }
  869. return digits.number();
  870. }
  871. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/strtoull.html
  872. unsigned long long strtoull(char const* 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. uint32_t arc4random(void)
  945. {
  946. uint32_t buf;
  947. arc4random_buf(&buf, sizeof(buf));
  948. return buf;
  949. }
  950. static pthread_mutex_t s_randomness_mutex = PTHREAD_MUTEX_INITIALIZER;
  951. static u8* s_randomness_buffer;
  952. static size_t s_randomness_index;
  953. void arc4random_buf(void* buffer, size_t buffer_size)
  954. {
  955. pthread_mutex_lock(&s_randomness_mutex);
  956. size_t bytes_needed = buffer_size;
  957. auto* ptr = static_cast<u8*>(buffer);
  958. while (bytes_needed > 0) {
  959. if (!s_randomness_buffer || s_randomness_index >= PAGE_SIZE) {
  960. if (!s_randomness_buffer) {
  961. s_randomness_buffer = static_cast<u8*>(mmap(nullptr, PAGE_SIZE, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE | MAP_RANDOMIZED, 0, 0));
  962. VERIFY(s_randomness_buffer != MAP_FAILED);
  963. __pthread_fork_atfork_register_child(
  964. [] {
  965. munmap(s_randomness_buffer, PAGE_SIZE);
  966. s_randomness_buffer = nullptr;
  967. s_randomness_index = 0;
  968. });
  969. }
  970. syscall(SC_getrandom, s_randomness_buffer, PAGE_SIZE);
  971. s_randomness_index = 0;
  972. }
  973. size_t available_bytes = PAGE_SIZE - s_randomness_index;
  974. size_t bytes_to_copy = min(bytes_needed, available_bytes);
  975. memcpy(ptr, s_randomness_buffer + s_randomness_index, bytes_to_copy);
  976. s_randomness_index += bytes_to_copy;
  977. bytes_needed -= bytes_to_copy;
  978. ptr += bytes_to_copy;
  979. }
  980. pthread_mutex_unlock(&s_randomness_mutex);
  981. }
  982. uint32_t arc4random_uniform(uint32_t max_bounds)
  983. {
  984. return AK::get_random_uniform(max_bounds);
  985. }
  986. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/realpath.html
  987. char* realpath(char const* pathname, char* buffer)
  988. {
  989. if (!pathname) {
  990. errno = EFAULT;
  991. return nullptr;
  992. }
  993. size_t size = PATH_MAX;
  994. bool self_allocated = false;
  995. if (buffer == nullptr) {
  996. // Since we self-allocate, try to sneakily use a smaller buffer instead, in an attempt to use less memory.
  997. size = 64;
  998. buffer = (char*)malloc(size);
  999. self_allocated = true;
  1000. }
  1001. Syscall::SC_realpath_params params { { pathname, strlen(pathname) }, { buffer, size } };
  1002. int rc = syscall(SC_realpath, &params);
  1003. if (rc < 0) {
  1004. if (self_allocated)
  1005. free(buffer);
  1006. errno = -rc;
  1007. return nullptr;
  1008. }
  1009. if (self_allocated && static_cast<size_t>(rc) > size) {
  1010. // There was silent truncation, *and* we can simply retry without the caller noticing.
  1011. free(buffer);
  1012. size = static_cast<size_t>(rc);
  1013. buffer = (char*)malloc(size);
  1014. params.buffer = { buffer, size };
  1015. rc = syscall(SC_realpath, &params);
  1016. if (rc < 0) {
  1017. // Can only happen if we lose a race. Let's pretend we lost the race in the first place.
  1018. free(buffer);
  1019. errno = -rc;
  1020. return nullptr;
  1021. }
  1022. size_t new_size = static_cast<size_t>(rc);
  1023. if (new_size < size) {
  1024. // If we're here, the symlink has become longer while we were looking at it.
  1025. // There's not much we can do, unless we want to loop endlessly
  1026. // in this case. Let's leave it up to the caller whether to loop.
  1027. free(buffer);
  1028. errno = EAGAIN;
  1029. return nullptr;
  1030. }
  1031. }
  1032. errno = 0;
  1033. return buffer;
  1034. }
  1035. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/posix_openpt.html
  1036. int posix_openpt(int flags)
  1037. {
  1038. if (flags & ~(O_RDWR | O_NOCTTY | O_CLOEXEC)) {
  1039. errno = EINVAL;
  1040. return -1;
  1041. }
  1042. return open("/dev/ptmx", flags);
  1043. }
  1044. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/grantpt.html
  1045. int grantpt([[maybe_unused]] int fd)
  1046. {
  1047. return 0;
  1048. }
  1049. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/unlockpt.html
  1050. int unlockpt([[maybe_unused]] int fd)
  1051. {
  1052. return 0;
  1053. }
  1054. }
  1055. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/_Exit.html
  1056. void _Exit(int status)
  1057. {
  1058. _exit(status);
  1059. }