stdlib.cpp 29 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include <AK/Assertions.h>
  27. #include <AK/HashMap.h>
  28. #include <AK/Noncopyable.h>
  29. #include <AK/StdLibExtras.h>
  30. #include <AK/Types.h>
  31. #include <AK/Utf8View.h>
  32. #include <Kernel/API/Syscall.h>
  33. #include <alloca.h>
  34. #include <assert.h>
  35. #include <ctype.h>
  36. #include <errno.h>
  37. #include <signal.h>
  38. #include <spawn.h>
  39. #include <stdio.h>
  40. #include <stdlib.h>
  41. #include <string.h>
  42. #include <sys/internals.h>
  43. #include <sys/mman.h>
  44. #include <sys/stat.h>
  45. #include <sys/wait.h>
  46. #include <unistd.h>
  47. static void strtons(const char* str, char** endptr)
  48. {
  49. assert(endptr);
  50. char* ptr = const_cast<char*>(str);
  51. while (isspace(*ptr)) {
  52. ptr += 1;
  53. }
  54. *endptr = ptr;
  55. }
  56. enum Sign {
  57. Negative,
  58. Positive,
  59. };
  60. static Sign strtosign(const char* str, char** endptr)
  61. {
  62. assert(endptr);
  63. if (*str == '+') {
  64. *endptr = const_cast<char*>(str + 1);
  65. return Sign::Positive;
  66. } else if (*str == '-') {
  67. *endptr = const_cast<char*>(str + 1);
  68. return Sign::Negative;
  69. } else {
  70. *endptr = const_cast<char*>(str);
  71. return Sign::Positive;
  72. }
  73. }
  74. enum DigitConsumeDecision {
  75. Consumed,
  76. PosOverflow,
  77. NegOverflow,
  78. Invalid,
  79. };
  80. template<typename T, T min_value, T max_value>
  81. class NumParser {
  82. AK_MAKE_NONMOVABLE(NumParser);
  83. public:
  84. NumParser(Sign sign, int base)
  85. : m_base(base)
  86. , m_num(0)
  87. , m_sign(sign)
  88. {
  89. m_cutoff = positive() ? (max_value / base) : (min_value / base);
  90. m_max_digit_after_cutoff = positive() ? (max_value % base) : (min_value % base);
  91. }
  92. int parse_digit(char ch)
  93. {
  94. int digit;
  95. if (isdigit(ch))
  96. digit = ch - '0';
  97. else if (islower(ch))
  98. digit = ch - ('a' - 10);
  99. else if (isupper(ch))
  100. digit = ch - ('A' - 10);
  101. else
  102. return -1;
  103. if (static_cast<T>(digit) >= m_base)
  104. return -1;
  105. return digit;
  106. }
  107. DigitConsumeDecision consume(char ch)
  108. {
  109. int digit = parse_digit(ch);
  110. if (digit == -1)
  111. return DigitConsumeDecision::Invalid;
  112. if (!can_append_digit(digit)) {
  113. if (m_sign != Sign::Negative) {
  114. return DigitConsumeDecision::PosOverflow;
  115. } else {
  116. return DigitConsumeDecision::NegOverflow;
  117. }
  118. }
  119. m_num *= m_base;
  120. m_num += positive() ? digit : -digit;
  121. return DigitConsumeDecision::Consumed;
  122. }
  123. T number() const { return m_num; };
  124. private:
  125. bool can_append_digit(int digit)
  126. {
  127. const bool is_below_cutoff = positive() ? (m_num < m_cutoff) : (m_num > m_cutoff);
  128. if (is_below_cutoff) {
  129. return true;
  130. } else {
  131. return m_num == m_cutoff && digit < m_max_digit_after_cutoff;
  132. }
  133. }
  134. bool positive() const
  135. {
  136. return m_sign != Sign::Negative;
  137. }
  138. const T m_base;
  139. T m_num;
  140. T m_cutoff;
  141. int m_max_digit_after_cutoff;
  142. Sign m_sign;
  143. };
  144. typedef NumParser<int, INT_MIN, INT_MAX> IntParser;
  145. typedef NumParser<long long, LONG_LONG_MIN, LONG_LONG_MAX> LongLongParser;
  146. typedef NumParser<unsigned long long, 0ULL, ULONG_LONG_MAX> ULongLongParser;
  147. static bool is_either(char* str, int offset, char lower, char upper)
  148. {
  149. char ch = *(str + offset);
  150. return ch == lower || ch == upper;
  151. }
  152. __attribute__((warn_unused_result)) int __generate_unique_filename(char* pattern)
  153. {
  154. size_t length = strlen(pattern);
  155. if (length < 6 || memcmp(pattern + length - 6, "XXXXXX", 6)) {
  156. errno = EINVAL;
  157. return -1;
  158. }
  159. size_t start = length - 6;
  160. static constexpr char random_characters[] = "abcdefghijklmnopqrstuvwxyz0123456789";
  161. for (int attempt = 0; attempt < 100; ++attempt) {
  162. for (int i = 0; i < 6; ++i)
  163. pattern[start + i] = random_characters[(rand() % sizeof(random_characters))];
  164. struct stat st;
  165. int rc = lstat(pattern, &st);
  166. if (rc < 0 && errno == ENOENT)
  167. return 0;
  168. }
  169. errno = EEXIST;
  170. return -1;
  171. }
  172. extern "C" {
  173. void exit(int status)
  174. {
  175. __cxa_finalize(nullptr);
  176. if (getenv("LIBC_DUMP_MALLOC_STATS"))
  177. serenity_dump_malloc_stats();
  178. extern void _fini();
  179. _fini();
  180. fflush(stdout);
  181. fflush(stderr);
  182. _exit(status);
  183. }
  184. static void __atexit_to_cxa_atexit(void* handler)
  185. {
  186. reinterpret_cast<void (*)()>(handler)();
  187. }
  188. int atexit(void (*handler)())
  189. {
  190. return __cxa_atexit(__atexit_to_cxa_atexit, (void*)handler, nullptr);
  191. }
  192. void abort()
  193. {
  194. // For starters, send ourselves a SIGABRT.
  195. raise(SIGABRT);
  196. // If that didn't kill us, try harder.
  197. raise(SIGKILL);
  198. _exit(127);
  199. }
  200. static HashTable<const char*> s_malloced_environment_variables;
  201. static void free_environment_variable_if_needed(const char* var)
  202. {
  203. if (!s_malloced_environment_variables.contains(var))
  204. return;
  205. free(const_cast<char*>(var));
  206. s_malloced_environment_variables.remove(var);
  207. }
  208. char* getenv(const char* name)
  209. {
  210. size_t vl = strlen(name);
  211. for (size_t i = 0; environ[i]; ++i) {
  212. const char* decl = environ[i];
  213. char* eq = strchr(decl, '=');
  214. if (!eq)
  215. continue;
  216. size_t varLength = eq - decl;
  217. if (vl != varLength)
  218. continue;
  219. if (strncmp(decl, name, varLength) == 0) {
  220. return eq + 1;
  221. }
  222. }
  223. return nullptr;
  224. }
  225. int unsetenv(const char* name)
  226. {
  227. auto new_var_len = strlen(name);
  228. size_t environ_size = 0;
  229. int skip = -1;
  230. for (; environ[environ_size]; ++environ_size) {
  231. char* old_var = environ[environ_size];
  232. char* old_eq = strchr(old_var, '=');
  233. ASSERT(old_eq);
  234. size_t old_var_len = old_eq - old_var;
  235. if (new_var_len != old_var_len)
  236. continue; // can't match
  237. if (strncmp(name, old_var, new_var_len) == 0)
  238. skip = environ_size;
  239. }
  240. if (skip == -1)
  241. return 0; // not found: no failure.
  242. // Shuffle the existing array down by one.
  243. memmove(&environ[skip], &environ[skip + 1], ((environ_size - 1) - skip) * sizeof(environ[0]));
  244. environ[environ_size - 1] = nullptr;
  245. free_environment_variable_if_needed(name);
  246. return 0;
  247. }
  248. int setenv(const char* name, const char* value, int overwrite)
  249. {
  250. if (!overwrite && getenv(name))
  251. return 0;
  252. auto length = strlen(name) + strlen(value) + 2;
  253. auto* var = (char*)malloc(length);
  254. snprintf(var, length, "%s=%s", name, value);
  255. s_malloced_environment_variables.set(var);
  256. return putenv(var);
  257. }
  258. int putenv(char* new_var)
  259. {
  260. char* new_eq = strchr(new_var, '=');
  261. if (!new_eq)
  262. return unsetenv(new_var);
  263. auto new_var_len = new_eq - new_var;
  264. int environ_size = 0;
  265. for (; environ[environ_size]; ++environ_size) {
  266. char* old_var = environ[environ_size];
  267. char* old_eq = strchr(old_var, '=');
  268. ASSERT(old_eq);
  269. auto old_var_len = old_eq - old_var;
  270. if (new_var_len != old_var_len)
  271. continue; // can't match
  272. if (strncmp(new_var, old_var, new_var_len) == 0) {
  273. free_environment_variable_if_needed(old_var);
  274. environ[environ_size] = new_var;
  275. return 0;
  276. }
  277. }
  278. // At this point, we need to append the new var.
  279. // 2 here: one for the new var, one for the sentinel value.
  280. char** new_environ = (char**)malloc((environ_size + 2) * sizeof(char*));
  281. if (new_environ == nullptr) {
  282. errno = ENOMEM;
  283. return -1;
  284. }
  285. for (int i = 0; environ[i]; ++i) {
  286. new_environ[i] = environ[i];
  287. }
  288. new_environ[environ_size] = new_var;
  289. new_environ[environ_size + 1] = nullptr;
  290. // swap new and old
  291. // note that the initial environ is not heap allocated!
  292. extern bool __environ_is_malloced;
  293. if (__environ_is_malloced)
  294. free(environ);
  295. __environ_is_malloced = true;
  296. environ = new_environ;
  297. return 0;
  298. }
  299. double strtod(const char* str, char** endptr)
  300. {
  301. // Parse spaces, sign, and base
  302. char* parse_ptr = const_cast<char*>(str);
  303. strtons(parse_ptr, &parse_ptr);
  304. const Sign sign = strtosign(parse_ptr, &parse_ptr);
  305. // Parse inf/nan, if applicable.
  306. if (is_either(parse_ptr, 0, 'i', 'I')) {
  307. if (is_either(parse_ptr, 1, 'n', 'N')) {
  308. if (is_either(parse_ptr, 2, 'f', 'F')) {
  309. parse_ptr += 3;
  310. if (is_either(parse_ptr, 0, 'i', 'I')) {
  311. if (is_either(parse_ptr, 1, 'n', 'N')) {
  312. if (is_either(parse_ptr, 2, 'i', 'I')) {
  313. if (is_either(parse_ptr, 3, 't', 'T')) {
  314. if (is_either(parse_ptr, 4, 'y', 'Y')) {
  315. parse_ptr += 5;
  316. }
  317. }
  318. }
  319. }
  320. }
  321. if (endptr)
  322. *endptr = parse_ptr;
  323. // Don't set errno to ERANGE here:
  324. // The caller may want to distinguish between "input is
  325. // literal infinity" and "input is not literal infinity
  326. // but did not fit into double".
  327. if (sign != Sign::Negative) {
  328. return __builtin_huge_val();
  329. } else {
  330. return -__builtin_huge_val();
  331. }
  332. }
  333. }
  334. }
  335. if (is_either(parse_ptr, 0, 'n', 'N')) {
  336. if (is_either(parse_ptr, 1, 'a', 'A')) {
  337. if (is_either(parse_ptr, 2, 'n', 'N')) {
  338. if (endptr)
  339. *endptr = parse_ptr + 3;
  340. errno = ERANGE;
  341. if (sign != Sign::Negative) {
  342. return __builtin_nan("");
  343. } else {
  344. return -__builtin_nan("");
  345. }
  346. }
  347. }
  348. }
  349. // Parse base
  350. char exponent_lower;
  351. char exponent_upper;
  352. int base = 10;
  353. if (*parse_ptr == '0') {
  354. const char base_ch = *(parse_ptr + 1);
  355. if (base_ch == 'x' || base_ch == 'X') {
  356. base = 16;
  357. parse_ptr += 2;
  358. }
  359. }
  360. if (base == 10) {
  361. exponent_lower = 'e';
  362. exponent_upper = 'E';
  363. } else {
  364. exponent_lower = 'p';
  365. exponent_upper = 'P';
  366. }
  367. // Parse "digits", possibly keeping track of the exponent offset.
  368. // We parse the most significant digits and the position in the
  369. // base-`base` representation separately. This allows us to handle
  370. // numbers like `0.0000000000000000000000000000000000001234` or
  371. // `1234567890123456789012345678901234567890` with ease.
  372. LongLongParser digits { sign, base };
  373. bool digits_usable = false;
  374. bool should_continue = true;
  375. bool digits_overflow = false;
  376. bool after_decimal = false;
  377. int exponent = 0;
  378. do {
  379. if (!after_decimal && *parse_ptr == '.') {
  380. after_decimal = true;
  381. parse_ptr += 1;
  382. continue;
  383. }
  384. bool is_a_digit;
  385. if (digits_overflow) {
  386. is_a_digit = digits.parse_digit(*parse_ptr) != -1;
  387. } else {
  388. DigitConsumeDecision decision = digits.consume(*parse_ptr);
  389. switch (decision) {
  390. case DigitConsumeDecision::Consumed:
  391. is_a_digit = true;
  392. // The very first actual digit must pass here:
  393. digits_usable = true;
  394. break;
  395. case DigitConsumeDecision::PosOverflow:
  396. // fallthrough
  397. case DigitConsumeDecision::NegOverflow:
  398. is_a_digit = true;
  399. digits_overflow = true;
  400. break;
  401. case DigitConsumeDecision::Invalid:
  402. is_a_digit = false;
  403. break;
  404. default:
  405. ASSERT_NOT_REACHED();
  406. }
  407. }
  408. if (is_a_digit) {
  409. exponent -= after_decimal ? 1 : 0;
  410. exponent += digits_overflow ? 1 : 0;
  411. }
  412. should_continue = is_a_digit;
  413. parse_ptr += should_continue;
  414. } while (should_continue);
  415. if (!digits_usable) {
  416. // No actual number value available.
  417. if (endptr)
  418. *endptr = const_cast<char*>(str);
  419. return 0.0;
  420. }
  421. // Parse exponent.
  422. // We already know the next character is not a digit in the current base,
  423. // nor a valid decimal point. Check whether it's an exponent sign.
  424. if (*parse_ptr == exponent_lower || *parse_ptr == exponent_upper) {
  425. // Need to keep the old parse_ptr around, in case of rollback.
  426. char* old_parse_ptr = parse_ptr;
  427. parse_ptr += 1;
  428. // Can't use atol or strtol here: Must accept excessive exponents,
  429. // even exponents >64 bits.
  430. Sign exponent_sign = strtosign(parse_ptr, &parse_ptr);
  431. IntParser exponent_parser { exponent_sign, base };
  432. bool exponent_usable = false;
  433. bool exponent_overflow = false;
  434. should_continue = true;
  435. do {
  436. bool is_a_digit;
  437. if (exponent_overflow) {
  438. is_a_digit = exponent_parser.parse_digit(*parse_ptr) != -1;
  439. } else {
  440. DigitConsumeDecision decision = exponent_parser.consume(*parse_ptr);
  441. switch (decision) {
  442. case DigitConsumeDecision::Consumed:
  443. is_a_digit = true;
  444. // The very first actual digit must pass here:
  445. exponent_usable = true;
  446. break;
  447. case DigitConsumeDecision::PosOverflow:
  448. // fallthrough
  449. case DigitConsumeDecision::NegOverflow:
  450. is_a_digit = true;
  451. exponent_overflow = true;
  452. break;
  453. case DigitConsumeDecision::Invalid:
  454. is_a_digit = false;
  455. break;
  456. default:
  457. ASSERT_NOT_REACHED();
  458. }
  459. }
  460. should_continue = is_a_digit;
  461. parse_ptr += should_continue;
  462. } while (should_continue);
  463. if (!exponent_usable) {
  464. parse_ptr = old_parse_ptr;
  465. } else if (exponent_overflow) {
  466. // Technically this is wrong. If someone gives us 5GB of digits,
  467. // and then an exponent of -5_000_000_000, the resulting exponent
  468. // should be around 0.
  469. // However, I think it's safe to assume that we never have to deal
  470. // with that many digits anyway.
  471. if (sign != Sign::Negative) {
  472. exponent = INT_MIN;
  473. } else {
  474. exponent = INT_MAX;
  475. }
  476. } else {
  477. // Literal exponent is usable and fits in an int.
  478. // However, `exponent + exponent_parser.number()` might overflow an int.
  479. // This would result in the wrong sign of the exponent!
  480. long long new_exponent = static_cast<long long>(exponent) + static_cast<long long>(exponent_parser.number());
  481. if (new_exponent < INT_MIN) {
  482. exponent = INT_MIN;
  483. } else if (new_exponent > INT_MAX) {
  484. exponent = INT_MAX;
  485. } else {
  486. exponent = static_cast<int>(new_exponent);
  487. }
  488. }
  489. }
  490. // Parsing finished. now we only have to compute the result.
  491. if (endptr)
  492. *endptr = const_cast<char*>(parse_ptr);
  493. // If `digits` is zero, we don't even have to look at `exponent`.
  494. if (digits.number() == 0) {
  495. if (sign != Sign::Negative) {
  496. return 0.0;
  497. } else {
  498. return -0.0;
  499. }
  500. }
  501. // Deal with extreme exponents.
  502. // The smallest normal is 2^-1022.
  503. // The smallest denormal is 2^-1074.
  504. // The largest number in `digits` is 2^63 - 1.
  505. // Therefore, if "base^exponent" is smaller than 2^-(1074+63), the result is 0.0 anyway.
  506. // This threshold is roughly 5.3566 * 10^-343.
  507. // So if the resulting exponent is -344 or lower (closer to -inf),
  508. // the result is 0.0 anyway.
  509. // We only need to avoid false positives, so we can ignore base 16.
  510. if (exponent <= -344) {
  511. errno = ERANGE;
  512. // Definitely can't be represented more precisely.
  513. // I lied, sometimes the result is +0.0, and sometimes -0.0.
  514. if (sign != Sign::Negative) {
  515. return 0.0;
  516. } else {
  517. return -0.0;
  518. }
  519. }
  520. // The largest normal is 2^+1024-eps.
  521. // The smallest number in `digits` is 1.
  522. // Therefore, if "base^exponent" is 2^+1024, the result is INF anyway.
  523. // This threshold is roughly 1.7977 * 10^-308.
  524. // So if the resulting exponent is +309 or higher,
  525. // the result is INF anyway.
  526. // We only need to avoid false positives, so we can ignore base 16.
  527. if (exponent >= 309) {
  528. errno = ERANGE;
  529. // Definitely can't be represented more precisely.
  530. // I lied, sometimes the result is +INF, and sometimes -INF.
  531. if (sign != Sign::Negative) {
  532. return __builtin_huge_val();
  533. } else {
  534. return -__builtin_huge_val();
  535. }
  536. }
  537. // TODO: If `exponent` is large, this could be made faster.
  538. double value = digits.number();
  539. if (exponent < 0) {
  540. exponent = -exponent;
  541. for (int i = 0; i < exponent; ++i) {
  542. value /= base;
  543. }
  544. if (value == -0.0 || value == +0.0) {
  545. errno = ERANGE;
  546. }
  547. } else if (exponent > 0) {
  548. for (int i = 0; i < exponent; ++i) {
  549. value *= base;
  550. }
  551. if (value == -__builtin_huge_val() || value == +__builtin_huge_val()) {
  552. errno = ERANGE;
  553. }
  554. }
  555. return value;
  556. }
  557. long double strtold(const char* str, char** endptr)
  558. {
  559. assert(sizeof(double) == sizeof(long double));
  560. return strtod(str, endptr);
  561. }
  562. float strtof(const char* str, char** endptr)
  563. {
  564. return strtod(str, endptr);
  565. }
  566. double atof(const char* str)
  567. {
  568. return strtod(str, nullptr);
  569. }
  570. int atoi(const char* str)
  571. {
  572. long value = strtol(str, nullptr, 10);
  573. if (value > INT_MAX) {
  574. return INT_MAX;
  575. }
  576. return value;
  577. }
  578. long atol(const char* str)
  579. {
  580. return strtol(str, nullptr, 10);
  581. }
  582. long long atoll(const char* str)
  583. {
  584. return strtoll(str, nullptr, 10);
  585. }
  586. static char ptsname_buf[32];
  587. char* ptsname(int fd)
  588. {
  589. if (ptsname_r(fd, ptsname_buf, sizeof(ptsname_buf)) < 0)
  590. return nullptr;
  591. return ptsname_buf;
  592. }
  593. int ptsname_r(int fd, char* buffer, size_t size)
  594. {
  595. int rc = syscall(SC_ptsname, fd, buffer, size);
  596. __RETURN_WITH_ERRNO(rc, rc, -1);
  597. }
  598. static unsigned long s_next_rand = 1;
  599. int rand()
  600. {
  601. s_next_rand = s_next_rand * 1103515245 + 12345;
  602. return ((unsigned)(s_next_rand / ((RAND_MAX + 1) * 2)) % (RAND_MAX + 1));
  603. }
  604. void srand(unsigned seed)
  605. {
  606. s_next_rand = seed;
  607. }
  608. int abs(int i)
  609. {
  610. return i < 0 ? -i : i;
  611. }
  612. long int random()
  613. {
  614. return rand();
  615. }
  616. void srandom(unsigned seed)
  617. {
  618. srand(seed);
  619. }
  620. int system(const char* command)
  621. {
  622. if (!command)
  623. return 1;
  624. pid_t child;
  625. const char* argv[] = { "sh", "-c", command, nullptr };
  626. if ((errno = posix_spawn(&child, "/bin/sh", nullptr, nullptr, const_cast<char**>(argv), environ)))
  627. return -1;
  628. int wstatus;
  629. waitpid(child, &wstatus, 0);
  630. return WEXITSTATUS(wstatus);
  631. }
  632. char* mktemp(char* pattern)
  633. {
  634. if (__generate_unique_filename(pattern) < 0)
  635. pattern[0] = '\0';
  636. return pattern;
  637. }
  638. int mkstemp(char* pattern)
  639. {
  640. char* path = mktemp(pattern);
  641. int fd = open(path, O_RDWR | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR); // I'm using the flags I saw glibc using.
  642. if (fd >= 0)
  643. return fd;
  644. return -1;
  645. }
  646. char* mkdtemp(char* pattern)
  647. {
  648. if (__generate_unique_filename(pattern) < 0)
  649. return nullptr;
  650. if (mkdir(pattern, 0700) < 0)
  651. return nullptr;
  652. return pattern;
  653. }
  654. void* bsearch(const void* key, const void* base, size_t nmemb, size_t size, int (*compar)(const void*, const void*))
  655. {
  656. char* start = static_cast<char*>(const_cast<void*>(base));
  657. while (nmemb > 0) {
  658. char* middle_memb = start + (nmemb / 2) * size;
  659. int comparison = compar(key, middle_memb);
  660. if (comparison == 0)
  661. return middle_memb;
  662. else if (comparison > 0) {
  663. start = middle_memb + size;
  664. --nmemb;
  665. }
  666. nmemb /= 2;
  667. }
  668. return NULL;
  669. }
  670. div_t div(int numerator, int denominator)
  671. {
  672. div_t result;
  673. result.quot = numerator / denominator;
  674. result.rem = numerator % denominator;
  675. if (numerator >= 0 && result.rem < 0) {
  676. result.quot++;
  677. result.rem -= denominator;
  678. }
  679. return result;
  680. }
  681. ldiv_t ldiv(long numerator, long denominator)
  682. {
  683. ldiv_t result;
  684. result.quot = numerator / denominator;
  685. result.rem = numerator % denominator;
  686. if (numerator >= 0 && result.rem < 0) {
  687. result.quot++;
  688. result.rem -= denominator;
  689. }
  690. return result;
  691. }
  692. size_t mbstowcs(wchar_t*, const char*, size_t)
  693. {
  694. ASSERT_NOT_REACHED();
  695. }
  696. int mbtowc(wchar_t* wch, const char* data, size_t data_size)
  697. {
  698. // FIXME: This needs a real implementation.
  699. UNUSED_PARAM(data_size);
  700. if (wch && data) {
  701. *wch = *data;
  702. return 1;
  703. }
  704. if (!wch && data) {
  705. return 1;
  706. }
  707. return 0;
  708. }
  709. int wctomb(char*, wchar_t)
  710. {
  711. ASSERT_NOT_REACHED();
  712. }
  713. size_t wcstombs(char* dest, const wchar_t* src, size_t max)
  714. {
  715. char* originalDest = dest;
  716. while ((size_t)(dest - originalDest) < max) {
  717. StringView v { (const char*)src, sizeof(wchar_t) };
  718. // FIXME: dependent on locale, for now utf-8 is supported.
  719. Utf8View utf8 { v };
  720. if (*utf8.begin() == '\0') {
  721. *dest = '\0';
  722. return (size_t)(dest - originalDest); // Exclude null character in returned size
  723. }
  724. for (auto byte : utf8) {
  725. if (byte != '\0')
  726. *dest++ = byte;
  727. }
  728. ++src;
  729. }
  730. return max;
  731. }
  732. long strtol(const char* str, char** endptr, int base)
  733. {
  734. long long value = strtoll(str, endptr, base);
  735. if (value < LONG_MIN) {
  736. errno = ERANGE;
  737. return LONG_MIN;
  738. } else if (value > LONG_MAX) {
  739. errno = ERANGE;
  740. return LONG_MAX;
  741. }
  742. return value;
  743. }
  744. unsigned long strtoul(const char* str, char** endptr, int base)
  745. {
  746. unsigned long long value = strtoull(str, endptr, base);
  747. if (value > ULONG_MAX) {
  748. errno = ERANGE;
  749. return ULONG_MAX;
  750. }
  751. return value;
  752. }
  753. long long strtoll(const char* str, char** endptr, int base)
  754. {
  755. // Parse spaces and sign
  756. char* parse_ptr = const_cast<char*>(str);
  757. strtons(parse_ptr, &parse_ptr);
  758. const Sign sign = strtosign(parse_ptr, &parse_ptr);
  759. // Parse base
  760. if (base == 0) {
  761. if (*parse_ptr == '0') {
  762. if (tolower(*(parse_ptr + 1)) == 'x') {
  763. base = 16;
  764. parse_ptr += 2;
  765. } else {
  766. base = 8;
  767. }
  768. } else {
  769. base = 10;
  770. }
  771. }
  772. // Parse actual digits.
  773. LongLongParser digits { sign, base };
  774. bool digits_usable = false;
  775. bool should_continue = true;
  776. bool overflow = false;
  777. do {
  778. bool is_a_digit;
  779. if (overflow) {
  780. is_a_digit = digits.parse_digit(*parse_ptr) >= 0;
  781. } else {
  782. DigitConsumeDecision decision = digits.consume(*parse_ptr);
  783. switch (decision) {
  784. case DigitConsumeDecision::Consumed:
  785. is_a_digit = true;
  786. // The very first actual digit must pass here:
  787. digits_usable = true;
  788. break;
  789. case DigitConsumeDecision::PosOverflow: // fall-through
  790. case DigitConsumeDecision::NegOverflow:
  791. is_a_digit = true;
  792. overflow = true;
  793. break;
  794. case DigitConsumeDecision::Invalid:
  795. is_a_digit = false;
  796. break;
  797. default:
  798. ASSERT_NOT_REACHED();
  799. }
  800. }
  801. should_continue = is_a_digit;
  802. parse_ptr += should_continue;
  803. } while (should_continue);
  804. if (!digits_usable) {
  805. // No actual number value available.
  806. if (endptr)
  807. *endptr = const_cast<char*>(str);
  808. return 0;
  809. }
  810. if (endptr)
  811. *endptr = parse_ptr;
  812. if (overflow) {
  813. errno = ERANGE;
  814. if (sign != Sign::Negative) {
  815. return LONG_LONG_MAX;
  816. } else {
  817. return LONG_LONG_MIN;
  818. }
  819. }
  820. return digits.number();
  821. }
  822. unsigned long long strtoull(const char* str, char** endptr, int base)
  823. {
  824. // Parse spaces and sign
  825. char* parse_ptr = const_cast<char*>(str);
  826. strtons(parse_ptr, &parse_ptr);
  827. // Parse base
  828. if (base == 0) {
  829. if (*parse_ptr == '0') {
  830. if (tolower(*(parse_ptr + 1)) == 'x') {
  831. base = 16;
  832. parse_ptr += 2;
  833. } else {
  834. base = 8;
  835. }
  836. } else {
  837. base = 10;
  838. }
  839. }
  840. // Parse actual digits.
  841. ULongLongParser digits { Sign::Positive, base };
  842. bool digits_usable = false;
  843. bool should_continue = true;
  844. bool overflow = false;
  845. do {
  846. bool is_a_digit;
  847. if (overflow) {
  848. is_a_digit = digits.parse_digit(*parse_ptr) >= 0;
  849. } else {
  850. DigitConsumeDecision decision = digits.consume(*parse_ptr);
  851. switch (decision) {
  852. case DigitConsumeDecision::Consumed:
  853. is_a_digit = true;
  854. // The very first actual digit must pass here:
  855. digits_usable = true;
  856. break;
  857. case DigitConsumeDecision::PosOverflow: // fall-through
  858. case DigitConsumeDecision::NegOverflow:
  859. is_a_digit = true;
  860. overflow = true;
  861. break;
  862. case DigitConsumeDecision::Invalid:
  863. is_a_digit = false;
  864. break;
  865. default:
  866. ASSERT_NOT_REACHED();
  867. }
  868. }
  869. should_continue = is_a_digit;
  870. parse_ptr += should_continue;
  871. } while (should_continue);
  872. if (!digits_usable) {
  873. // No actual number value available.
  874. if (endptr)
  875. *endptr = const_cast<char*>(str);
  876. return 0;
  877. }
  878. if (endptr)
  879. *endptr = parse_ptr;
  880. if (overflow) {
  881. errno = ERANGE;
  882. return LONG_LONG_MAX;
  883. }
  884. return digits.number();
  885. }
  886. // Serenity's PRNG is not cryptographically secure. Do not rely on this for
  887. // any real crypto! These functions (for now) are for compatibility.
  888. // TODO: In the future, rand can be made determinstic and this not.
  889. uint32_t arc4random(void)
  890. {
  891. char buf[4];
  892. syscall(SC_getrandom, buf, 4, 0);
  893. return *(uint32_t*)buf;
  894. }
  895. void arc4random_buf(void* buffer, size_t buffer_size)
  896. {
  897. // arc4random_buf should never fail, but user supplied buffers could fail.
  898. // However, if the user passes a garbage buffer, that's on them.
  899. syscall(SC_getrandom, buffer, buffer_size, 0);
  900. }
  901. uint32_t arc4random_uniform(uint32_t max_bounds)
  902. {
  903. // XXX: Should actually apply special rules for uniformity; avoid what is
  904. // called "modulo bias".
  905. return arc4random() % max_bounds;
  906. }
  907. char* realpath(const char* pathname, char* buffer)
  908. {
  909. if (!pathname) {
  910. errno = EFAULT;
  911. return nullptr;
  912. }
  913. size_t size = PATH_MAX;
  914. if (buffer == nullptr)
  915. buffer = (char*)malloc(size);
  916. Syscall::SC_realpath_params params { { pathname, strlen(pathname) }, { buffer, size } };
  917. int rc = syscall(SC_realpath, &params);
  918. if (rc < 0) {
  919. errno = -rc;
  920. return nullptr;
  921. }
  922. errno = 0;
  923. return buffer;
  924. }
  925. int posix_openpt(int flags)
  926. {
  927. if (flags & ~(O_RDWR | O_NOCTTY | O_CLOEXEC)) {
  928. errno = EINVAL;
  929. return -1;
  930. }
  931. return open("/dev/ptmx", flags);
  932. }
  933. int grantpt(int fd)
  934. {
  935. (void)fd;
  936. return 0;
  937. }
  938. int unlockpt(int fd)
  939. {
  940. (void)fd;
  941. return 0;
  942. }
  943. }