stdlib.cpp 34 KB

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