stdlib.cpp 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259
  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. T const 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. Sign const 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. [[gnu::weak]] void (*__call_fini_functions)();
  290. void exit(int status)
  291. {
  292. __cxa_finalize(nullptr);
  293. if (secure_getenv("LIBC_DUMP_MALLOC_STATS"))
  294. serenity_dump_malloc_stats();
  295. __call_fini_functions();
  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_byte_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. static long s_next_rand48 = 0;
  553. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/rand.html
  554. int rand()
  555. {
  556. s_next_rand = s_next_rand * 1103515245 + 12345;
  557. return ((unsigned)(s_next_rand / ((RAND_MAX + 1) * 2)) % (RAND_MAX + 1));
  558. }
  559. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/srand.html
  560. void srand(unsigned seed)
  561. {
  562. s_next_rand = seed;
  563. }
  564. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/drand48.html
  565. double drand48()
  566. {
  567. constexpr u64 a = 0x5DEECE66DULL;
  568. constexpr u64 c = 0xBULL;
  569. constexpr u64 m = 1ULL << 48;
  570. s_next_rand48 = (a * s_next_rand48 + c) & (m - 1);
  571. return static_cast<double>(s_next_rand48) / m;
  572. }
  573. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/srand48.html
  574. void srand48(long seed)
  575. {
  576. s_next_rand48 = (seed & 0xFFFFFFFF) << 16 | 0x330E;
  577. }
  578. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/abs.html
  579. int abs(int i)
  580. {
  581. return i < 0 ? -i : i;
  582. }
  583. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/labs.html
  584. long int labs(long int i)
  585. {
  586. return i < 0 ? -i : i;
  587. }
  588. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/llabs.html
  589. long long int llabs(long long int i)
  590. {
  591. return i < 0 ? -i : i;
  592. }
  593. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/random.html
  594. long int random()
  595. {
  596. return rand();
  597. }
  598. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/srandom.html
  599. void srandom(unsigned seed)
  600. {
  601. srand(seed);
  602. }
  603. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/system.html
  604. int system(char const* command)
  605. {
  606. __pthread_maybe_cancel();
  607. if (!command)
  608. return 1;
  609. pid_t child;
  610. char const* argv[] = { "sh", "-c", command, nullptr };
  611. if ((errno = posix_spawn(&child, "/bin/sh", nullptr, nullptr, const_cast<char**>(argv), environ)))
  612. return -1;
  613. int wstatus;
  614. waitpid(child, &wstatus, 0);
  615. return WEXITSTATUS(wstatus);
  616. }
  617. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/mktemp.html
  618. char* mktemp(char* pattern)
  619. {
  620. auto error = generate_unique_filename(pattern, 0, [&] {
  621. struct stat st;
  622. int rc = lstat(pattern, &st);
  623. if (rc < 0 && errno == ENOENT)
  624. return IterationDecision::Break;
  625. return IterationDecision::Continue;
  626. });
  627. if (error) {
  628. pattern[0] = '\0';
  629. errno = error;
  630. }
  631. return pattern;
  632. }
  633. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/mkstemp.html
  634. int mkstemp(char* pattern)
  635. {
  636. return mkstemps(pattern, 0);
  637. }
  638. // https://man7.org/linux/man-pages/man3/mkstemps.3.html
  639. int mkstemps(char* pattern, int suffix_length)
  640. {
  641. VERIFY(suffix_length >= 0);
  642. int fd = -1;
  643. auto error = generate_unique_filename(pattern, static_cast<size_t>(suffix_length), [&] {
  644. fd = open(pattern, O_RDWR | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR); // I'm using the flags I saw glibc using.
  645. if (fd >= 0)
  646. return IterationDecision::Break;
  647. return IterationDecision::Continue;
  648. });
  649. if (error) {
  650. errno = error;
  651. return -1;
  652. }
  653. return fd;
  654. }
  655. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/mkdtemp.html
  656. char* mkdtemp(char* pattern)
  657. {
  658. auto error = generate_unique_filename(pattern, 0, [&] {
  659. if (mkdir(pattern, 0700) == 0)
  660. return IterationDecision::Break;
  661. return IterationDecision::Continue;
  662. });
  663. if (error) {
  664. errno = error;
  665. return nullptr;
  666. }
  667. return pattern;
  668. }
  669. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/bsearch.html
  670. void* bsearch(void const* key, void const* base, size_t nmemb, size_t size, int (*compar)(void const*, void const*))
  671. {
  672. char* start = static_cast<char*>(const_cast<void*>(base));
  673. while (nmemb > 0) {
  674. char* middle_memb = start + (nmemb / 2) * size;
  675. int comparison = compar(key, middle_memb);
  676. if (comparison == 0)
  677. return middle_memb;
  678. else if (comparison > 0) {
  679. start = middle_memb + size;
  680. --nmemb;
  681. }
  682. nmemb /= 2;
  683. }
  684. return nullptr;
  685. }
  686. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/div.html
  687. div_t div(int numerator, int denominator)
  688. {
  689. div_t result;
  690. result.quot = numerator / denominator;
  691. result.rem = numerator % denominator;
  692. if (numerator >= 0 && result.rem < 0) {
  693. result.quot++;
  694. result.rem -= denominator;
  695. }
  696. return result;
  697. }
  698. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/ldiv.html
  699. ldiv_t ldiv(long numerator, long denominator)
  700. {
  701. ldiv_t result;
  702. result.quot = numerator / denominator;
  703. result.rem = numerator % denominator;
  704. if (numerator >= 0 && result.rem < 0) {
  705. result.quot++;
  706. result.rem -= denominator;
  707. }
  708. return result;
  709. }
  710. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/lldiv.html
  711. lldiv_t lldiv(long long numerator, long long denominator)
  712. {
  713. lldiv_t result;
  714. result.quot = numerator / denominator;
  715. result.rem = numerator % denominator;
  716. if (numerator >= 0 && result.rem < 0) {
  717. result.quot++;
  718. result.rem -= denominator;
  719. }
  720. return result;
  721. }
  722. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/mblen.html
  723. int mblen(char const* s, size_t n)
  724. {
  725. // POSIX: Equivalent to mbtowc(NULL, s, n), but we mustn't change the state of mbtowc.
  726. static mbstate_t internal_state = {};
  727. // Reset the internal state and ask whether we have shift states.
  728. if (s == nullptr) {
  729. internal_state = {};
  730. return 0;
  731. }
  732. size_t ret = mbrtowc(nullptr, s, n, &internal_state);
  733. // Incomplete characters get returned as illegal sequence.
  734. if (ret == -2ul) {
  735. errno = EILSEQ;
  736. return -1;
  737. }
  738. return ret;
  739. }
  740. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/mbstowcs.html
  741. size_t mbstowcs(wchar_t* pwcs, char const* s, size_t n)
  742. {
  743. static mbstate_t state = {};
  744. return mbsrtowcs(pwcs, &s, n, &state);
  745. }
  746. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/mbtowc.html
  747. int mbtowc(wchar_t* pwc, char const* s, size_t n)
  748. {
  749. static mbstate_t internal_state = {};
  750. // Reset the internal state and ask whether we have shift states.
  751. if (s == nullptr) {
  752. internal_state = {};
  753. return 0;
  754. }
  755. size_t ret = mbrtowc(pwc, s, n, &internal_state);
  756. // Incomplete characters get returned as illegal sequence.
  757. // Internal state is undefined, so don't bother with resetting.
  758. if (ret == -2ul) {
  759. errno = EILSEQ;
  760. return -1;
  761. }
  762. return ret;
  763. }
  764. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/wctomb.html
  765. int wctomb(char* s, wchar_t wc)
  766. {
  767. static mbstate_t _internal_state = {};
  768. // nullptr asks whether we have state-dependent encodings, but we don't have any.
  769. if (s == nullptr)
  770. return 0;
  771. return static_cast<int>(wcrtomb(s, wc, &_internal_state));
  772. }
  773. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/wcstombs.html
  774. size_t wcstombs(char* dest, wchar_t const* src, size_t max)
  775. {
  776. char* original_dest = dest;
  777. while ((size_t)(dest - original_dest) < max) {
  778. StringView v { (char const*)src, sizeof(wchar_t) };
  779. // FIXME: dependent on locale, for now utf-8 is supported.
  780. Utf8View utf8 { v };
  781. if (*utf8.begin() == '\0') {
  782. *dest = '\0';
  783. return (size_t)(dest - original_dest); // Exclude null character in returned size
  784. }
  785. for (auto byte : utf8) {
  786. if (byte != '\0')
  787. *dest++ = byte;
  788. }
  789. ++src;
  790. }
  791. return max;
  792. }
  793. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/strtol.html
  794. long strtol(char const* str, char** endptr, int base)
  795. {
  796. long long value = strtoll(str, endptr, base);
  797. if (value < LONG_MIN) {
  798. errno = ERANGE;
  799. return LONG_MIN;
  800. } else if (value > LONG_MAX) {
  801. errno = ERANGE;
  802. return LONG_MAX;
  803. }
  804. return value;
  805. }
  806. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/strtoul.html
  807. unsigned long strtoul(char const* str, char** endptr, int base)
  808. {
  809. unsigned long long value = strtoull(str, endptr, base);
  810. if (value > ULONG_MAX) {
  811. errno = ERANGE;
  812. return ULONG_MAX;
  813. }
  814. return value;
  815. }
  816. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/strtoll.html
  817. long long strtoll(char const* str, char** endptr, int base)
  818. {
  819. // Parse spaces and sign
  820. char* parse_ptr = const_cast<char*>(str);
  821. strtons(parse_ptr, &parse_ptr);
  822. Sign const sign = strtosign(parse_ptr, &parse_ptr);
  823. // Parse base
  824. if (base == 0) {
  825. if (*parse_ptr == '0') {
  826. if (tolower(*(parse_ptr + 1)) == 'x') {
  827. base = 16;
  828. parse_ptr += 2;
  829. } else {
  830. base = 8;
  831. }
  832. } else {
  833. base = 10;
  834. }
  835. }
  836. // Parse actual digits.
  837. LongLongParser digits { sign, base };
  838. bool digits_usable = false;
  839. bool should_continue = true;
  840. bool overflow = false;
  841. do {
  842. bool is_a_digit;
  843. if (overflow) {
  844. is_a_digit = digits.parse_digit(*parse_ptr) >= 0;
  845. } else {
  846. DigitConsumeDecision decision = digits.consume(*parse_ptr);
  847. switch (decision) {
  848. case DigitConsumeDecision::Consumed:
  849. is_a_digit = true;
  850. // The very first actual digit must pass here:
  851. digits_usable = true;
  852. break;
  853. case DigitConsumeDecision::PosOverflow:
  854. case DigitConsumeDecision::NegOverflow:
  855. is_a_digit = true;
  856. overflow = true;
  857. break;
  858. case DigitConsumeDecision::Invalid:
  859. is_a_digit = false;
  860. break;
  861. default:
  862. VERIFY_NOT_REACHED();
  863. }
  864. }
  865. should_continue = is_a_digit;
  866. parse_ptr += should_continue;
  867. } while (should_continue);
  868. if (!digits_usable) {
  869. // No actual number value available.
  870. if (endptr)
  871. *endptr = const_cast<char*>(str);
  872. return 0;
  873. }
  874. if (endptr)
  875. *endptr = parse_ptr;
  876. if (overflow) {
  877. errno = ERANGE;
  878. if (sign != Sign::Negative) {
  879. return LONG_LONG_MAX;
  880. } else {
  881. return LONG_LONG_MIN;
  882. }
  883. }
  884. return digits.number();
  885. }
  886. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/strtoull.html
  887. unsigned long long strtoull(char const* str, char** endptr, int base)
  888. {
  889. // Parse spaces and sign
  890. char* parse_ptr = const_cast<char*>(str);
  891. strtons(parse_ptr, &parse_ptr);
  892. if (base == 16) {
  893. // Dr. POSIX: "If the value of base is 16, the characters 0x or 0X may optionally precede
  894. // the sequence of letters and digits, following the sign if present."
  895. if (*parse_ptr == '0') {
  896. if (tolower(*(parse_ptr + 1)) == 'x')
  897. parse_ptr += 2;
  898. }
  899. }
  900. // Parse base
  901. if (base == 0) {
  902. if (*parse_ptr == '0') {
  903. if (tolower(*(parse_ptr + 1)) == 'x') {
  904. base = 16;
  905. parse_ptr += 2;
  906. } else {
  907. base = 8;
  908. }
  909. } else {
  910. base = 10;
  911. }
  912. }
  913. // Parse actual digits.
  914. ULongLongParser digits { Sign::Positive, base };
  915. bool digits_usable = false;
  916. bool should_continue = true;
  917. bool overflow = false;
  918. do {
  919. bool is_a_digit;
  920. if (overflow) {
  921. is_a_digit = digits.parse_digit(*parse_ptr) >= 0;
  922. } else {
  923. DigitConsumeDecision decision = digits.consume(*parse_ptr);
  924. switch (decision) {
  925. case DigitConsumeDecision::Consumed:
  926. is_a_digit = true;
  927. // The very first actual digit must pass here:
  928. digits_usable = true;
  929. break;
  930. case DigitConsumeDecision::PosOverflow:
  931. case DigitConsumeDecision::NegOverflow:
  932. is_a_digit = true;
  933. overflow = true;
  934. break;
  935. case DigitConsumeDecision::Invalid:
  936. is_a_digit = false;
  937. break;
  938. default:
  939. VERIFY_NOT_REACHED();
  940. }
  941. }
  942. should_continue = is_a_digit;
  943. parse_ptr += should_continue;
  944. } while (should_continue);
  945. if (!digits_usable) {
  946. // No actual number value available.
  947. if (endptr)
  948. *endptr = const_cast<char*>(str);
  949. return 0;
  950. }
  951. if (endptr)
  952. *endptr = parse_ptr;
  953. if (overflow) {
  954. errno = ERANGE;
  955. return LONG_LONG_MAX;
  956. }
  957. return digits.number();
  958. }
  959. uint32_t arc4random(void)
  960. {
  961. uint32_t buf;
  962. arc4random_buf(&buf, sizeof(buf));
  963. return buf;
  964. }
  965. static pthread_mutex_t s_randomness_mutex = PTHREAD_MUTEX_INITIALIZER;
  966. static u8* s_randomness_buffer;
  967. static size_t s_randomness_index;
  968. void arc4random_buf(void* buffer, size_t buffer_size)
  969. {
  970. pthread_mutex_lock(&s_randomness_mutex);
  971. size_t bytes_needed = buffer_size;
  972. auto* ptr = static_cast<u8*>(buffer);
  973. while (bytes_needed > 0) {
  974. if (!s_randomness_buffer || s_randomness_index >= PAGE_SIZE) {
  975. if (!s_randomness_buffer) {
  976. s_randomness_buffer = static_cast<u8*>(mmap(nullptr, PAGE_SIZE, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE | MAP_RANDOMIZED, 0, 0));
  977. VERIFY(s_randomness_buffer != MAP_FAILED);
  978. __pthread_fork_atfork_register_child(
  979. [] {
  980. munmap(s_randomness_buffer, PAGE_SIZE);
  981. s_randomness_buffer = nullptr;
  982. s_randomness_index = 0;
  983. });
  984. }
  985. syscall(SC_getrandom, s_randomness_buffer, PAGE_SIZE);
  986. s_randomness_index = 0;
  987. }
  988. size_t available_bytes = PAGE_SIZE - s_randomness_index;
  989. size_t bytes_to_copy = min(bytes_needed, available_bytes);
  990. memcpy(ptr, s_randomness_buffer + s_randomness_index, bytes_to_copy);
  991. s_randomness_index += bytes_to_copy;
  992. bytes_needed -= bytes_to_copy;
  993. ptr += bytes_to_copy;
  994. }
  995. pthread_mutex_unlock(&s_randomness_mutex);
  996. }
  997. uint32_t arc4random_uniform(uint32_t max_bounds)
  998. {
  999. return AK::get_random_uniform(max_bounds);
  1000. }
  1001. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/realpath.html
  1002. char* realpath(char const* pathname, char* buffer)
  1003. {
  1004. if (!pathname) {
  1005. errno = EFAULT;
  1006. return nullptr;
  1007. }
  1008. size_t size = PATH_MAX;
  1009. bool self_allocated = false;
  1010. if (buffer == nullptr) {
  1011. // Since we self-allocate, try to sneakily use a smaller buffer instead, in an attempt to use less memory.
  1012. size = 64;
  1013. buffer = (char*)malloc(size);
  1014. self_allocated = true;
  1015. }
  1016. Syscall::SC_realpath_params params { { pathname, strlen(pathname) }, { buffer, size } };
  1017. int rc = syscall(SC_realpath, &params);
  1018. if (rc < 0) {
  1019. if (self_allocated)
  1020. free(buffer);
  1021. errno = -rc;
  1022. return nullptr;
  1023. }
  1024. if (self_allocated && static_cast<size_t>(rc) > size) {
  1025. // There was silent truncation, *and* we can simply retry without the caller noticing.
  1026. free(buffer);
  1027. size = static_cast<size_t>(rc);
  1028. buffer = (char*)malloc(size);
  1029. params.buffer = { buffer, size };
  1030. rc = syscall(SC_realpath, &params);
  1031. if (rc < 0) {
  1032. // Can only happen if we lose a race. Let's pretend we lost the race in the first place.
  1033. free(buffer);
  1034. errno = -rc;
  1035. return nullptr;
  1036. }
  1037. size_t new_size = static_cast<size_t>(rc);
  1038. if (new_size < size) {
  1039. // If we're here, the symlink has become longer while we were looking at it.
  1040. // There's not much we can do, unless we want to loop endlessly
  1041. // in this case. Let's leave it up to the caller whether to loop.
  1042. free(buffer);
  1043. errno = EAGAIN;
  1044. return nullptr;
  1045. }
  1046. }
  1047. errno = 0;
  1048. return buffer;
  1049. }
  1050. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/posix_openpt.html
  1051. int posix_openpt(int flags)
  1052. {
  1053. if (flags & ~(O_RDWR | O_NOCTTY | O_CLOEXEC)) {
  1054. errno = EINVAL;
  1055. return -1;
  1056. }
  1057. return open("/dev/ptmx", flags);
  1058. }
  1059. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/grantpt.html
  1060. int grantpt([[maybe_unused]] int fd)
  1061. {
  1062. return 0;
  1063. }
  1064. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/unlockpt.html
  1065. int unlockpt([[maybe_unused]] int fd)
  1066. {
  1067. return 0;
  1068. }
  1069. }
  1070. // https://pubs.opengroup.org/onlinepubs/9699919799/functions/_Exit.html
  1071. void _Exit(int status)
  1072. {
  1073. _exit(status);
  1074. }