stdlib.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233
  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. free(const_cast<char*>(var));
  334. s_malloced_environment_variables.remove((FlatPtr)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. }
  351. return nullptr;
  352. }
  353. char* secure_getenv(char const* name)
  354. {
  355. if (getauxval(AT_SECURE))
  356. return nullptr;
  357. return getenv(name);
  358. }
  359. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/unsetenv.html
  360. int unsetenv(char const* name)
  361. {
  362. auto new_var_len = strlen(name);
  363. size_t environ_size = 0;
  364. int skip = -1;
  365. for (; environ[environ_size]; ++environ_size) {
  366. char* old_var = environ[environ_size];
  367. char* old_eq = strchr(old_var, '=');
  368. VERIFY(old_eq);
  369. size_t old_var_len = old_eq - old_var;
  370. if (new_var_len != old_var_len)
  371. continue; // can't match
  372. if (strncmp(name, old_var, new_var_len) == 0)
  373. skip = environ_size;
  374. }
  375. if (skip == -1)
  376. return 0; // not found: no failure.
  377. // Shuffle the existing array down by one.
  378. memmove(&environ[skip], &environ[skip + 1], ((environ_size - 1) - skip) * sizeof(environ[0]));
  379. environ[environ_size - 1] = nullptr;
  380. free_environment_variable_if_needed(name);
  381. return 0;
  382. }
  383. int clearenv()
  384. {
  385. size_t environ_size = 0;
  386. for (; environ[environ_size]; ++environ_size) {
  387. environ[environ_size] = NULL;
  388. }
  389. *environ = NULL;
  390. return 0;
  391. }
  392. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/setenv.html
  393. int setenv(char const* name, char const* value, int overwrite)
  394. {
  395. return serenity_setenv(name, strlen(name), value, strlen(value), overwrite);
  396. }
  397. int serenity_setenv(char const* name, ssize_t name_length, char const* value, ssize_t value_length, int overwrite)
  398. {
  399. if (!overwrite && getenv(name))
  400. return 0;
  401. auto const total_length = name_length + value_length + 2;
  402. auto* var = (char*)malloc(total_length);
  403. snprintf(var, total_length, "%s=%s", name, value);
  404. s_malloced_environment_variables.set((FlatPtr)var);
  405. return putenv(var);
  406. }
  407. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/putenv.html
  408. int putenv(char* new_var)
  409. {
  410. char* new_eq = strchr(new_var, '=');
  411. if (!new_eq)
  412. return unsetenv(new_var);
  413. auto new_var_len = new_eq - new_var;
  414. int environ_size = 0;
  415. for (; environ[environ_size]; ++environ_size) {
  416. char* old_var = environ[environ_size];
  417. char* old_eq = strchr(old_var, '=');
  418. VERIFY(old_eq);
  419. auto old_var_len = old_eq - old_var;
  420. if (new_var_len != old_var_len)
  421. continue; // can't match
  422. if (strncmp(new_var, old_var, new_var_len) == 0) {
  423. free_environment_variable_if_needed(old_var);
  424. environ[environ_size] = new_var;
  425. return 0;
  426. }
  427. }
  428. // At this point, we need to append the new var.
  429. // 2 here: one for the new var, one for the sentinel value.
  430. auto** new_environ = static_cast<char**>(kmalloc_array(environ_size + 2, sizeof(char*)));
  431. if (new_environ == nullptr) {
  432. errno = ENOMEM;
  433. return -1;
  434. }
  435. for (int i = 0; environ[i]; ++i) {
  436. new_environ[i] = environ[i];
  437. }
  438. new_environ[environ_size] = new_var;
  439. new_environ[environ_size + 1] = nullptr;
  440. // swap new and old
  441. // note that the initial environ is not heap allocated!
  442. extern bool __environ_is_malloced;
  443. if (__environ_is_malloced)
  444. free(environ);
  445. __environ_is_malloced = true;
  446. environ = new_environ;
  447. return 0;
  448. }
  449. static char const* __progname = NULL;
  450. char const* getprogname()
  451. {
  452. return __progname;
  453. }
  454. void setprogname(char const* progname)
  455. {
  456. for (int i = strlen(progname) - 1; i >= 0; i--) {
  457. if (progname[i] == '/') {
  458. __progname = progname + i + 1;
  459. return;
  460. }
  461. }
  462. __progname = progname;
  463. }
  464. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/strtod.html
  465. double strtod(char const* str, char** endptr)
  466. {
  467. return c_str_to_floating_point<double>(str, endptr);
  468. }
  469. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/strtold.html
  470. long double strtold(char const* str, char** endptr)
  471. {
  472. assert(sizeof(double) == sizeof(long double));
  473. return strtod(str, endptr);
  474. }
  475. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/strtof.html
  476. float strtof(char const* str, char** endptr)
  477. {
  478. return c_str_to_floating_point<float>(str, endptr);
  479. }
  480. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/atof.html
  481. double atof(char const* str)
  482. {
  483. return strtod(str, nullptr);
  484. }
  485. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/atoi.html
  486. int atoi(char const* str)
  487. {
  488. long value = strtol(str, nullptr, 10);
  489. if (value > INT_MAX) {
  490. return INT_MAX;
  491. }
  492. return value;
  493. }
  494. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/atol.html
  495. long atol(char const* str)
  496. {
  497. return strtol(str, nullptr, 10);
  498. }
  499. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/atoll.html
  500. long long atoll(char const* str)
  501. {
  502. return strtoll(str, nullptr, 10);
  503. }
  504. static char ptsname_buf[32];
  505. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/ptsname.html
  506. char* ptsname(int fd)
  507. {
  508. if (ptsname_r(fd, ptsname_buf, sizeof(ptsname_buf)) < 0)
  509. return nullptr;
  510. return ptsname_buf;
  511. }
  512. int ptsname_r(int fd, char* buffer, size_t size)
  513. {
  514. struct stat stat;
  515. if (fstat(fd, &stat) < 0)
  516. return -1;
  517. StringBuilder devpts_path_builder;
  518. devpts_path_builder.append("/dev/pts/"sv);
  519. int master_pty_index = 0;
  520. // Note: When the user opens a PTY from /dev/ptmx with posix_openpt(), the open file descriptor
  521. // points to /dev/ptmx, (major number is 5 and minor number is 2), but internally
  522. // in the kernel, it points to a new MasterPTY device. When we do ioctl with TIOCGPTN option
  523. // on the open file descriptor, it actually asks the MasterPTY what is the assigned index
  524. // of it when the PTYMultiplexer created it.
  525. if (ioctl(fd, TIOCGPTN, &master_pty_index) < 0)
  526. return -1;
  527. if (master_pty_index < 0) {
  528. errno = EINVAL;
  529. return -1;
  530. }
  531. devpts_path_builder.appendff("{:d}", master_pty_index);
  532. if (devpts_path_builder.length() > size) {
  533. errno = ERANGE;
  534. return -1;
  535. }
  536. memset(buffer, 0, devpts_path_builder.length() + 1);
  537. auto full_devpts_path_string = devpts_path_builder.build();
  538. if (!full_devpts_path_string.copy_characters_to_buffer(buffer, size)) {
  539. errno = ERANGE;
  540. return -1;
  541. }
  542. return 0;
  543. }
  544. static unsigned long s_next_rand = 1;
  545. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/rand.html
  546. int rand()
  547. {
  548. s_next_rand = s_next_rand * 1103515245 + 12345;
  549. return ((unsigned)(s_next_rand / ((RAND_MAX + 1) * 2)) % (RAND_MAX + 1));
  550. }
  551. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/srand.html
  552. void srand(unsigned seed)
  553. {
  554. s_next_rand = seed;
  555. }
  556. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/abs.html
  557. int abs(int i)
  558. {
  559. return i < 0 ? -i : i;
  560. }
  561. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/labs.html
  562. long int labs(long int i)
  563. {
  564. return i < 0 ? -i : i;
  565. }
  566. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/llabs.html
  567. long long int llabs(long long int i)
  568. {
  569. return i < 0 ? -i : i;
  570. }
  571. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/random.html
  572. long int random()
  573. {
  574. return rand();
  575. }
  576. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/srandom.html
  577. void srandom(unsigned seed)
  578. {
  579. srand(seed);
  580. }
  581. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/system.html
  582. int system(char const* command)
  583. {
  584. __pthread_maybe_cancel();
  585. if (!command)
  586. return 1;
  587. pid_t child;
  588. char const* argv[] = { "sh", "-c", command, nullptr };
  589. if ((errno = posix_spawn(&child, "/bin/sh", nullptr, nullptr, const_cast<char**>(argv), environ)))
  590. return -1;
  591. int wstatus;
  592. waitpid(child, &wstatus, 0);
  593. return WEXITSTATUS(wstatus);
  594. }
  595. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/mktemp.html
  596. char* mktemp(char* pattern)
  597. {
  598. auto error = generate_unique_filename(pattern, 0, [&] {
  599. struct stat st;
  600. int rc = lstat(pattern, &st);
  601. if (rc < 0 && errno == ENOENT)
  602. return IterationDecision::Break;
  603. return IterationDecision::Continue;
  604. });
  605. if (error) {
  606. pattern[0] = '\0';
  607. errno = error;
  608. }
  609. return pattern;
  610. }
  611. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/mkstemp.html
  612. int mkstemp(char* pattern)
  613. {
  614. return mkstemps(pattern, 0);
  615. }
  616. // https://man7.org/linux/man-pages/man3/mkstemps.3.html
  617. int mkstemps(char* pattern, int suffix_length)
  618. {
  619. VERIFY(suffix_length >= 0);
  620. int fd = -1;
  621. auto error = generate_unique_filename(pattern, static_cast<size_t>(suffix_length), [&] {
  622. fd = open(pattern, O_RDWR | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR); // I'm using the flags I saw glibc using.
  623. if (fd >= 0)
  624. return IterationDecision::Break;
  625. return IterationDecision::Continue;
  626. });
  627. if (error) {
  628. errno = error;
  629. return -1;
  630. }
  631. return fd;
  632. }
  633. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/mkdtemp.html
  634. char* mkdtemp(char* pattern)
  635. {
  636. auto error = generate_unique_filename(pattern, 0, [&] {
  637. if (mkdir(pattern, 0700) == 0)
  638. return IterationDecision::Break;
  639. return IterationDecision::Continue;
  640. });
  641. if (error) {
  642. errno = error;
  643. return nullptr;
  644. }
  645. return pattern;
  646. }
  647. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/bsearch.html
  648. void* bsearch(void const* key, void const* base, size_t nmemb, size_t size, int (*compar)(void const*, void const*))
  649. {
  650. char* start = static_cast<char*>(const_cast<void*>(base));
  651. while (nmemb > 0) {
  652. char* middle_memb = start + (nmemb / 2) * size;
  653. int comparison = compar(key, middle_memb);
  654. if (comparison == 0)
  655. return middle_memb;
  656. else if (comparison > 0) {
  657. start = middle_memb + size;
  658. --nmemb;
  659. }
  660. nmemb /= 2;
  661. }
  662. return nullptr;
  663. }
  664. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/div.html
  665. div_t div(int numerator, int denominator)
  666. {
  667. div_t result;
  668. result.quot = numerator / denominator;
  669. result.rem = numerator % denominator;
  670. if (numerator >= 0 && result.rem < 0) {
  671. result.quot++;
  672. result.rem -= denominator;
  673. }
  674. return result;
  675. }
  676. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/ldiv.html
  677. ldiv_t ldiv(long numerator, long denominator)
  678. {
  679. ldiv_t result;
  680. result.quot = numerator / denominator;
  681. result.rem = numerator % denominator;
  682. if (numerator >= 0 && result.rem < 0) {
  683. result.quot++;
  684. result.rem -= denominator;
  685. }
  686. return result;
  687. }
  688. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/lldiv.html
  689. lldiv_t lldiv(long long numerator, long long denominator)
  690. {
  691. lldiv_t result;
  692. result.quot = numerator / denominator;
  693. result.rem = numerator % denominator;
  694. if (numerator >= 0 && result.rem < 0) {
  695. result.quot++;
  696. result.rem -= denominator;
  697. }
  698. return result;
  699. }
  700. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/mblen.html
  701. int mblen(char const* s, size_t n)
  702. {
  703. // POSIX: Equivalent to mbtowc(NULL, s, n), but we mustn't change the state of mbtowc.
  704. static mbstate_t internal_state = {};
  705. // Reset the internal state and ask whether we have shift states.
  706. if (s == nullptr) {
  707. internal_state = {};
  708. return 0;
  709. }
  710. size_t ret = mbrtowc(nullptr, s, n, &internal_state);
  711. // Incomplete characters get returned as illegal sequence.
  712. if (ret == -2ul) {
  713. errno = EILSEQ;
  714. return -1;
  715. }
  716. return ret;
  717. }
  718. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/mbstowcs.html
  719. size_t mbstowcs(wchar_t* pwcs, char const* s, size_t n)
  720. {
  721. static mbstate_t state = {};
  722. return mbsrtowcs(pwcs, &s, n, &state);
  723. }
  724. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/mbtowc.html
  725. int mbtowc(wchar_t* pwc, char const* s, size_t n)
  726. {
  727. static mbstate_t internal_state = {};
  728. // Reset the internal state and ask whether we have shift states.
  729. if (s == nullptr) {
  730. internal_state = {};
  731. return 0;
  732. }
  733. size_t ret = mbrtowc(pwc, s, n, &internal_state);
  734. // Incomplete characters get returned as illegal sequence.
  735. // Internal state is undefined, so don't bother with resetting.
  736. if (ret == -2ul) {
  737. errno = EILSEQ;
  738. return -1;
  739. }
  740. return ret;
  741. }
  742. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/wctomb.html
  743. int wctomb(char* s, wchar_t wc)
  744. {
  745. static mbstate_t _internal_state = {};
  746. // nullptr asks whether we have state-dependent encodings, but we don't have any.
  747. if (s == nullptr)
  748. return 0;
  749. return static_cast<int>(wcrtomb(s, wc, &_internal_state));
  750. }
  751. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/wcstombs.html
  752. size_t wcstombs(char* dest, wchar_t const* src, size_t max)
  753. {
  754. char* original_dest = dest;
  755. while ((size_t)(dest - original_dest) < max) {
  756. StringView v { (char const*)src, sizeof(wchar_t) };
  757. // FIXME: dependent on locale, for now utf-8 is supported.
  758. Utf8View utf8 { v };
  759. if (*utf8.begin() == '\0') {
  760. *dest = '\0';
  761. return (size_t)(dest - original_dest); // Exclude null character in returned size
  762. }
  763. for (auto byte : utf8) {
  764. if (byte != '\0')
  765. *dest++ = byte;
  766. }
  767. ++src;
  768. }
  769. return max;
  770. }
  771. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/strtol.html
  772. long strtol(char const* str, char** endptr, int base)
  773. {
  774. long long value = strtoll(str, endptr, base);
  775. if (value < LONG_MIN) {
  776. errno = ERANGE;
  777. return LONG_MIN;
  778. } else if (value > LONG_MAX) {
  779. errno = ERANGE;
  780. return LONG_MAX;
  781. }
  782. return value;
  783. }
  784. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/strtoul.html
  785. unsigned long strtoul(char const* str, char** endptr, int base)
  786. {
  787. unsigned long long value = strtoull(str, endptr, base);
  788. if (value > ULONG_MAX) {
  789. errno = ERANGE;
  790. return ULONG_MAX;
  791. }
  792. return value;
  793. }
  794. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/strtoll.html
  795. long long strtoll(char const* str, char** endptr, int base)
  796. {
  797. // Parse spaces and sign
  798. char* parse_ptr = const_cast<char*>(str);
  799. strtons(parse_ptr, &parse_ptr);
  800. const Sign sign = strtosign(parse_ptr, &parse_ptr);
  801. // Parse base
  802. if (base == 0) {
  803. if (*parse_ptr == '0') {
  804. if (tolower(*(parse_ptr + 1)) == 'x') {
  805. base = 16;
  806. parse_ptr += 2;
  807. } else {
  808. base = 8;
  809. }
  810. } else {
  811. base = 10;
  812. }
  813. }
  814. // Parse actual digits.
  815. LongLongParser digits { sign, base };
  816. bool digits_usable = false;
  817. bool should_continue = true;
  818. bool overflow = false;
  819. do {
  820. bool is_a_digit;
  821. if (overflow) {
  822. is_a_digit = digits.parse_digit(*parse_ptr) >= 0;
  823. } else {
  824. DigitConsumeDecision decision = digits.consume(*parse_ptr);
  825. switch (decision) {
  826. case DigitConsumeDecision::Consumed:
  827. is_a_digit = true;
  828. // The very first actual digit must pass here:
  829. digits_usable = true;
  830. break;
  831. case DigitConsumeDecision::PosOverflow:
  832. case DigitConsumeDecision::NegOverflow:
  833. is_a_digit = true;
  834. overflow = true;
  835. break;
  836. case DigitConsumeDecision::Invalid:
  837. is_a_digit = false;
  838. break;
  839. default:
  840. VERIFY_NOT_REACHED();
  841. }
  842. }
  843. should_continue = is_a_digit;
  844. parse_ptr += should_continue;
  845. } while (should_continue);
  846. if (!digits_usable) {
  847. // No actual number value available.
  848. if (endptr)
  849. *endptr = const_cast<char*>(str);
  850. return 0;
  851. }
  852. if (endptr)
  853. *endptr = parse_ptr;
  854. if (overflow) {
  855. errno = ERANGE;
  856. if (sign != Sign::Negative) {
  857. return LONG_LONG_MAX;
  858. } else {
  859. return LONG_LONG_MIN;
  860. }
  861. }
  862. return digits.number();
  863. }
  864. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/strtoull.html
  865. unsigned long long strtoull(char const* str, char** endptr, int base)
  866. {
  867. // Parse spaces and sign
  868. char* parse_ptr = const_cast<char*>(str);
  869. strtons(parse_ptr, &parse_ptr);
  870. if (base == 16) {
  871. // Dr. POSIX: "If the value of base is 16, the characters 0x or 0X may optionally precede
  872. // the sequence of letters and digits, following the sign if present."
  873. if (*parse_ptr == '0') {
  874. if (tolower(*(parse_ptr + 1)) == 'x')
  875. parse_ptr += 2;
  876. }
  877. }
  878. // Parse base
  879. if (base == 0) {
  880. if (*parse_ptr == '0') {
  881. if (tolower(*(parse_ptr + 1)) == 'x') {
  882. base = 16;
  883. parse_ptr += 2;
  884. } else {
  885. base = 8;
  886. }
  887. } else {
  888. base = 10;
  889. }
  890. }
  891. // Parse actual digits.
  892. ULongLongParser digits { Sign::Positive, base };
  893. bool digits_usable = false;
  894. bool should_continue = true;
  895. bool overflow = false;
  896. do {
  897. bool is_a_digit;
  898. if (overflow) {
  899. is_a_digit = digits.parse_digit(*parse_ptr) >= 0;
  900. } else {
  901. DigitConsumeDecision decision = digits.consume(*parse_ptr);
  902. switch (decision) {
  903. case DigitConsumeDecision::Consumed:
  904. is_a_digit = true;
  905. // The very first actual digit must pass here:
  906. digits_usable = true;
  907. break;
  908. case DigitConsumeDecision::PosOverflow:
  909. case DigitConsumeDecision::NegOverflow:
  910. is_a_digit = true;
  911. overflow = true;
  912. break;
  913. case DigitConsumeDecision::Invalid:
  914. is_a_digit = false;
  915. break;
  916. default:
  917. VERIFY_NOT_REACHED();
  918. }
  919. }
  920. should_continue = is_a_digit;
  921. parse_ptr += should_continue;
  922. } while (should_continue);
  923. if (!digits_usable) {
  924. // No actual number value available.
  925. if (endptr)
  926. *endptr = const_cast<char*>(str);
  927. return 0;
  928. }
  929. if (endptr)
  930. *endptr = parse_ptr;
  931. if (overflow) {
  932. errno = ERANGE;
  933. return LONG_LONG_MAX;
  934. }
  935. return digits.number();
  936. }
  937. uint32_t arc4random(void)
  938. {
  939. uint32_t buf;
  940. arc4random_buf(&buf, sizeof(buf));
  941. return buf;
  942. }
  943. static pthread_mutex_t s_randomness_mutex = PTHREAD_MUTEX_INITIALIZER;
  944. static u8* s_randomness_buffer;
  945. static size_t s_randomness_index;
  946. void arc4random_buf(void* buffer, size_t buffer_size)
  947. {
  948. pthread_mutex_lock(&s_randomness_mutex);
  949. size_t bytes_needed = buffer_size;
  950. auto* ptr = static_cast<u8*>(buffer);
  951. while (bytes_needed > 0) {
  952. if (!s_randomness_buffer || s_randomness_index >= PAGE_SIZE) {
  953. if (!s_randomness_buffer) {
  954. s_randomness_buffer = static_cast<u8*>(mmap(nullptr, PAGE_SIZE, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE | MAP_RANDOMIZED, 0, 0));
  955. VERIFY(s_randomness_buffer != MAP_FAILED);
  956. __pthread_fork_atfork_register_child(
  957. [] {
  958. munmap(s_randomness_buffer, PAGE_SIZE);
  959. s_randomness_buffer = nullptr;
  960. s_randomness_index = 0;
  961. });
  962. }
  963. syscall(SC_getrandom, s_randomness_buffer, PAGE_SIZE);
  964. s_randomness_index = 0;
  965. }
  966. size_t available_bytes = PAGE_SIZE - s_randomness_index;
  967. size_t bytes_to_copy = min(bytes_needed, available_bytes);
  968. memcpy(ptr, s_randomness_buffer + s_randomness_index, bytes_to_copy);
  969. s_randomness_index += bytes_to_copy;
  970. bytes_needed -= bytes_to_copy;
  971. ptr += bytes_to_copy;
  972. }
  973. pthread_mutex_unlock(&s_randomness_mutex);
  974. }
  975. uint32_t arc4random_uniform(uint32_t max_bounds)
  976. {
  977. return AK::get_random_uniform(max_bounds);
  978. }
  979. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/realpath.html
  980. char* realpath(char const* pathname, char* buffer)
  981. {
  982. if (!pathname) {
  983. errno = EFAULT;
  984. return nullptr;
  985. }
  986. size_t size = PATH_MAX;
  987. bool self_allocated = false;
  988. if (buffer == nullptr) {
  989. // Since we self-allocate, try to sneakily use a smaller buffer instead, in an attempt to use less memory.
  990. size = 64;
  991. buffer = (char*)malloc(size);
  992. self_allocated = true;
  993. }
  994. Syscall::SC_realpath_params params { { pathname, strlen(pathname) }, { buffer, size } };
  995. int rc = syscall(SC_realpath, &params);
  996. if (rc < 0) {
  997. if (self_allocated)
  998. free(buffer);
  999. errno = -rc;
  1000. return nullptr;
  1001. }
  1002. if (self_allocated && static_cast<size_t>(rc) > size) {
  1003. // There was silent truncation, *and* we can simply retry without the caller noticing.
  1004. free(buffer);
  1005. size = static_cast<size_t>(rc);
  1006. buffer = (char*)malloc(size);
  1007. params.buffer = { buffer, size };
  1008. rc = syscall(SC_realpath, &params);
  1009. if (rc < 0) {
  1010. // Can only happen if we lose a race. Let's pretend we lost the race in the first place.
  1011. free(buffer);
  1012. errno = -rc;
  1013. return nullptr;
  1014. }
  1015. size_t new_size = static_cast<size_t>(rc);
  1016. if (new_size < size) {
  1017. // If we're here, the symlink has become longer while we were looking at it.
  1018. // There's not much we can do, unless we want to loop endlessly
  1019. // in this case. Let's leave it up to the caller whether to loop.
  1020. free(buffer);
  1021. errno = EAGAIN;
  1022. return nullptr;
  1023. }
  1024. }
  1025. errno = 0;
  1026. return buffer;
  1027. }
  1028. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/posix_openpt.html
  1029. int posix_openpt(int flags)
  1030. {
  1031. if (flags & ~(O_RDWR | O_NOCTTY | O_CLOEXEC)) {
  1032. errno = EINVAL;
  1033. return -1;
  1034. }
  1035. return open("/dev/ptmx", flags);
  1036. }
  1037. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/grantpt.html
  1038. int grantpt([[maybe_unused]] int fd)
  1039. {
  1040. return 0;
  1041. }
  1042. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/unlockpt.html
  1043. int unlockpt([[maybe_unused]] int fd)
  1044. {
  1045. return 0;
  1046. }
  1047. }
  1048. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/_Exit.html
  1049. void _Exit(int status)
  1050. {
  1051. _exit(status);
  1052. }