stdlib.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723
  1. #include <AK/Assertions.h>
  2. #include <AK/HashMap.h>
  3. #include <AK/StdLibExtras.h>
  4. #include <AK/Types.h>
  5. #include <AK/Utf8View.h>
  6. #include <Kernel/Syscall.h>
  7. #include <alloca.h>
  8. #include <assert.h>
  9. #include <ctype.h>
  10. #include <errno.h>
  11. #include <signal.h>
  12. #include <stdio.h>
  13. #include <stdlib.h>
  14. #include <string.h>
  15. #include <sys/mman.h>
  16. #include <sys/stat.h>
  17. #include <sys/wait.h>
  18. #include <unistd.h>
  19. template<typename T, T min_value, T max_value>
  20. static inline T strtol_impl(const char* nptr, char** endptr, int base)
  21. {
  22. errno = 0;
  23. if (base < 0 || base == 1 || base > 36) {
  24. errno = EINVAL;
  25. if (endptr)
  26. *endptr = const_cast<char*>(nptr);
  27. return 0;
  28. }
  29. const char* p = nptr;
  30. while (isspace(*p))
  31. ++p;
  32. bool is_negative = false;
  33. if (*p == '-') {
  34. is_negative = true;
  35. ++p;
  36. } else {
  37. if (*p == '+')
  38. ++p;
  39. }
  40. if (base == 0 || base == 16) {
  41. if (base == 0)
  42. base = 10;
  43. if (*p == '0') {
  44. if (*(p + 1) == 'X' || *(p + 1) == 'x') {
  45. p += 2;
  46. base = 16;
  47. } else if (base != 16) {
  48. base = 8;
  49. }
  50. }
  51. }
  52. long cutoff_point = is_negative ? (min_value / base) : (max_value / base);
  53. int max_valid_digit_at_cutoff_point = is_negative ? (min_value % base) : (max_value % base);
  54. long num = 0;
  55. bool has_overflowed = false;
  56. unsigned digits_consumed = 0;
  57. for (;;) {
  58. char ch = *(p++);
  59. int digit;
  60. if (isdigit(ch))
  61. digit = ch - '0';
  62. else if (islower(ch))
  63. digit = ch - ('a' - 10);
  64. else if (isupper(ch))
  65. digit = ch - ('A' - 10);
  66. else
  67. break;
  68. if (digit >= base)
  69. break;
  70. if (has_overflowed)
  71. continue;
  72. bool is_past_cutoff = is_negative ? num < cutoff_point : num > cutoff_point;
  73. if (is_past_cutoff || (num == cutoff_point && digit > max_valid_digit_at_cutoff_point)) {
  74. has_overflowed = true;
  75. num = is_negative ? min_value : max_value;
  76. errno = ERANGE;
  77. } else {
  78. num *= base;
  79. num += is_negative ? -digit : digit;
  80. ++digits_consumed;
  81. }
  82. }
  83. if (endptr) {
  84. if (has_overflowed || digits_consumed > 0)
  85. *endptr = const_cast<char*>(p - 1);
  86. else
  87. *endptr = const_cast<char*>(nptr);
  88. }
  89. return num;
  90. }
  91. __attribute__((warn_unused_result)) int __generate_unique_filename(char* pattern)
  92. {
  93. size_t length = strlen(pattern);
  94. if (length < 6 || memcmp(pattern + length - 6, "XXXXXX", 6)) {
  95. errno = EINVAL;
  96. return -1;
  97. }
  98. size_t start = length - 6;
  99. static constexpr char random_characters[] = "abcdefghijklmnopqrstuvwxyz0123456789";
  100. for (int attempt = 0; attempt < 100; ++attempt) {
  101. for (int i = 0; i < 6; ++i)
  102. pattern[start + i] = random_characters[(rand() % sizeof(random_characters))];
  103. struct stat st;
  104. int rc = lstat(pattern, &st);
  105. if (rc < 0 && errno == ENOENT)
  106. return 0;
  107. }
  108. errno = EEXIST;
  109. return -1;
  110. }
  111. extern "C" {
  112. // Itanium C++ ABI methods defined in crt0.cpp
  113. extern int __cxa_atexit(void (*function)(void*), void* paramter, void* dso_handle);
  114. extern void __cxa_finalize(void* dso_handle);
  115. void exit(int status)
  116. {
  117. __cxa_finalize(nullptr);
  118. extern void _fini();
  119. _fini();
  120. fflush(stdout);
  121. fflush(stderr);
  122. _exit(status);
  123. ASSERT_NOT_REACHED();
  124. }
  125. static void __atexit_to_cxa_atexit(void* handler)
  126. {
  127. reinterpret_cast<void (*)()>(handler)();
  128. }
  129. int atexit(void (*handler)())
  130. {
  131. return __cxa_atexit(__atexit_to_cxa_atexit, (void*)handler, nullptr);
  132. }
  133. void abort()
  134. {
  135. raise(SIGABRT);
  136. ASSERT_NOT_REACHED();
  137. }
  138. static HashTable<const char*> s_malloced_environment_variables;
  139. static void free_environment_variable_if_needed(const char* var)
  140. {
  141. if (!s_malloced_environment_variables.contains(var))
  142. return;
  143. free(const_cast<char*>(var));
  144. s_malloced_environment_variables.remove(var);
  145. }
  146. char* getenv(const char* name)
  147. {
  148. size_t vl = strlen(name);
  149. for (size_t i = 0; environ[i]; ++i) {
  150. const char* decl = environ[i];
  151. char* eq = strchr(decl, '=');
  152. if (!eq)
  153. continue;
  154. size_t varLength = eq - decl;
  155. if (vl != varLength)
  156. continue;
  157. if (strncmp(decl, name, varLength) == 0) {
  158. return eq + 1;
  159. }
  160. }
  161. return nullptr;
  162. }
  163. int unsetenv(const char* name)
  164. {
  165. auto new_var_len = strlen(name);
  166. size_t environ_size = 0;
  167. int skip = -1;
  168. for (; environ[environ_size]; ++environ_size) {
  169. char* old_var = environ[environ_size];
  170. char* old_eq = strchr(old_var, '=');
  171. ASSERT(old_eq);
  172. size_t old_var_len = old_eq - old_var;
  173. if (new_var_len != old_var_len)
  174. continue; // can't match
  175. if (strncmp(name, old_var, new_var_len) == 0)
  176. skip = environ_size;
  177. }
  178. if (skip == -1)
  179. return 0; // not found: no failure.
  180. // Shuffle the existing array down by one.
  181. memmove(&environ[skip], &environ[skip + 1], ((environ_size - 1) - skip) * sizeof(environ[0]));
  182. environ[environ_size - 1] = nullptr;
  183. free_environment_variable_if_needed(name);
  184. return 0;
  185. }
  186. int setenv(const char* name, const char* value, int overwrite)
  187. {
  188. if (!overwrite && !getenv(name))
  189. return 0;
  190. auto length = strlen(name) + strlen(value) + 2;
  191. auto* var = (char*)malloc(length);
  192. snprintf(var, length, "%s=%s", name, value);
  193. s_malloced_environment_variables.set(var);
  194. return putenv(var);
  195. }
  196. int putenv(char* new_var)
  197. {
  198. char* new_eq = strchr(new_var, '=');
  199. if (!new_eq)
  200. return unsetenv(new_var);
  201. auto new_var_len = new_eq - new_var;
  202. int environ_size = 0;
  203. for (; environ[environ_size]; ++environ_size) {
  204. char* old_var = environ[environ_size];
  205. char* old_eq = strchr(old_var, '=');
  206. ASSERT(old_eq);
  207. auto old_var_len = old_eq - old_var;
  208. if (new_var_len != old_var_len)
  209. continue; // can't match
  210. if (strncmp(new_var, old_var, new_var_len) == 0) {
  211. free_environment_variable_if_needed(old_var);
  212. environ[environ_size] = new_var;
  213. return 0;
  214. }
  215. }
  216. // At this point, we need to append the new var.
  217. // 2 here: one for the new var, one for the sentinel value.
  218. char** new_environ = (char**)malloc((environ_size + 2) * sizeof(char*));
  219. if (new_environ == nullptr) {
  220. errno = ENOMEM;
  221. return -1;
  222. }
  223. for (int i = 0; environ[i]; ++i) {
  224. new_environ[i] = environ[i];
  225. }
  226. new_environ[environ_size] = new_var;
  227. new_environ[environ_size + 1] = nullptr;
  228. // swap new and old
  229. // note that the initial environ is not heap allocated!
  230. extern bool __environ_is_malloced;
  231. if (__environ_is_malloced)
  232. free(environ);
  233. __environ_is_malloced = true;
  234. environ = new_environ;
  235. return 0;
  236. }
  237. double strtod(const char* str, char** endptr)
  238. {
  239. size_t len = strlen(str);
  240. size_t weight = 1;
  241. int exp_val = 0;
  242. double value = 0.0f;
  243. double fraction = 0.0f;
  244. bool has_sign = false;
  245. bool is_negative = false;
  246. bool is_fractional = false;
  247. bool is_scientific = false;
  248. if (str[0] == '-') {
  249. is_negative = true;
  250. has_sign = true;
  251. }
  252. if (str[0] == '+') {
  253. has_sign = true;
  254. }
  255. size_t i;
  256. for (i = has_sign; i < len; i++) {
  257. // Looks like we're about to start working on the fractional part
  258. if (str[i] == '.') {
  259. is_fractional = true;
  260. continue;
  261. }
  262. if (str[i] == 'e' || str[i] == 'E') {
  263. if (str[i + 1] == '-' || str[i + 1] == '+')
  264. exp_val = atoi(str + i + 2);
  265. else
  266. exp_val = atoi(str + i + 1);
  267. is_scientific = true;
  268. continue;
  269. }
  270. if (str[i] < '0' || str[i] > '9' || exp_val != 0)
  271. continue;
  272. if (is_fractional) {
  273. fraction *= 10;
  274. fraction += str[i] - '0';
  275. weight *= 10;
  276. } else {
  277. value = value * 10;
  278. value += str[i] - '0';
  279. }
  280. }
  281. fraction /= weight;
  282. value += fraction;
  283. if (is_scientific) {
  284. bool divide = exp_val < 0;
  285. if (divide)
  286. exp_val *= -1;
  287. for (int i = 0; i < exp_val; i++) {
  288. if (divide)
  289. value /= 10;
  290. else
  291. value *= 10;
  292. }
  293. }
  294. //FIXME: Not entirely sure if this is correct, but seems to work.
  295. if (endptr)
  296. *endptr = const_cast<char*>(str + i);
  297. return is_negative ? -value : value;
  298. }
  299. long double strtold(const char* str, char** endptr)
  300. {
  301. (void)str;
  302. (void)endptr;
  303. dbgprintf("LibC: strtold: '%s'\n", str);
  304. ASSERT_NOT_REACHED();
  305. }
  306. float strtof(const char* str, char** endptr)
  307. {
  308. (void)str;
  309. (void)endptr;
  310. dbgprintf("LibC: strtof: '%s'\n", str);
  311. ASSERT_NOT_REACHED();
  312. }
  313. double atof(const char* str)
  314. {
  315. size_t len = strlen(str);
  316. size_t weight = 1;
  317. int exp_val = 0;
  318. double value = 0.0f;
  319. double fraction = 0.0f;
  320. bool has_sign = false;
  321. bool is_negative = false;
  322. bool is_fractional = false;
  323. bool is_scientific = false;
  324. if (str[0] == '-') {
  325. is_negative = true;
  326. has_sign = true;
  327. }
  328. if (str[0] == '+') {
  329. has_sign = true;
  330. }
  331. for (size_t i = has_sign; i < len; i++) {
  332. // Looks like we're about to start working on the fractional part
  333. if (str[i] == '.') {
  334. is_fractional = true;
  335. continue;
  336. }
  337. if (str[i] == 'e' || str[i] == 'E') {
  338. if (str[i + 1] == '-' || str[i + 1] == '+')
  339. exp_val = atoi(str + i + 2);
  340. else
  341. exp_val = atoi(str + i + 1);
  342. is_scientific = true;
  343. continue;
  344. }
  345. if (str[i] < '0' || str[i] > '9' || exp_val != 0)
  346. continue;
  347. if (is_fractional) {
  348. fraction *= 10;
  349. fraction += str[i] - '0';
  350. weight *= 10;
  351. } else {
  352. value = value * 10;
  353. value += str[i] - '0';
  354. }
  355. }
  356. fraction /= weight;
  357. value += fraction;
  358. if (is_scientific) {
  359. bool divide = exp_val < 0;
  360. if (divide)
  361. exp_val *= -1;
  362. for (int i = 0; i < exp_val; i++) {
  363. if (divide)
  364. value /= 10;
  365. else
  366. value *= 10;
  367. }
  368. }
  369. return is_negative ? -value : value;
  370. }
  371. int atoi(const char* str)
  372. {
  373. size_t len = strlen(str);
  374. int value = 0;
  375. bool isNegative = false;
  376. for (size_t i = 0; i < len; ++i) {
  377. if (i == 0 && str[0] == '-') {
  378. isNegative = true;
  379. continue;
  380. }
  381. if (str[i] < '0' || str[i] > '9')
  382. return value;
  383. value = value * 10;
  384. value += str[i] - '0';
  385. }
  386. return isNegative ? -value : value;
  387. }
  388. long atol(const char* str)
  389. {
  390. static_assert(sizeof(int) == sizeof(long));
  391. return atoi(str);
  392. }
  393. long long atoll(const char* str)
  394. {
  395. dbgprintf("FIXME(Libc): atoll('%s') passing through to atol()\n", str);
  396. return atol(str);
  397. }
  398. static char ptsname_buf[32];
  399. char* ptsname(int fd)
  400. {
  401. if (ptsname_r(fd, ptsname_buf, sizeof(ptsname_buf)) < 0)
  402. return nullptr;
  403. return ptsname_buf;
  404. }
  405. int ptsname_r(int fd, char* buffer, size_t size)
  406. {
  407. int rc = syscall(SC_ptsname_r, fd, buffer, size);
  408. __RETURN_WITH_ERRNO(rc, rc, -1);
  409. }
  410. static unsigned long s_next_rand = 1;
  411. int rand()
  412. {
  413. s_next_rand = s_next_rand * 1103515245 + 12345;
  414. return ((unsigned)(s_next_rand / ((RAND_MAX + 1) * 2)) % (RAND_MAX + 1));
  415. }
  416. void srand(unsigned seed)
  417. {
  418. s_next_rand = seed;
  419. }
  420. int abs(int i)
  421. {
  422. return i < 0 ? -i : i;
  423. }
  424. long int random()
  425. {
  426. return rand();
  427. }
  428. void srandom(unsigned seed)
  429. {
  430. srand(seed);
  431. }
  432. int system(const char* command)
  433. {
  434. if (!command)
  435. return 1;
  436. auto child = fork();
  437. if (child < 0)
  438. return -1;
  439. if (!child) {
  440. int rc = execl("/bin/sh", "sh", "-c", command, nullptr);
  441. ASSERT(rc < 0);
  442. perror("execl");
  443. exit(127);
  444. }
  445. int wstatus;
  446. waitpid(child, &wstatus, 0);
  447. return WEXITSTATUS(wstatus);
  448. }
  449. char* mktemp(char* pattern)
  450. {
  451. if (__generate_unique_filename(pattern) < 0)
  452. pattern[0] = '\0';
  453. return pattern;
  454. }
  455. int mkstemp(char* pattern)
  456. {
  457. char* path = mktemp(pattern);
  458. int fd = open(path, O_RDWR | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR); // I'm using the flags I saw glibc using.
  459. if (fd >= 0)
  460. return fd;
  461. return -1;
  462. }
  463. char* mkdtemp(char* pattern)
  464. {
  465. if (__generate_unique_filename(pattern) < 0)
  466. return nullptr;
  467. if (mkdir(pattern, 0700) < 0)
  468. return nullptr;
  469. return pattern;
  470. }
  471. void* bsearch(const void* key, const void* base, size_t nmemb, size_t size, int (*compar)(const void*, const void*))
  472. {
  473. int low = 0;
  474. int high = nmemb - 1;
  475. while (low <= high) {
  476. int middle = (low + high) / 2;
  477. void* middle_memb = const_cast<char*>((const char*)base + middle * size);
  478. int comparison = compar(key, middle_memb);
  479. if (comparison < 0)
  480. high = middle - 1;
  481. else if (comparison > 0)
  482. low = middle + 1;
  483. else
  484. return middle_memb;
  485. }
  486. return NULL;
  487. }
  488. div_t div(int numerator, int denominator)
  489. {
  490. div_t result;
  491. result.quot = numerator / denominator;
  492. result.rem = numerator % denominator;
  493. if (numerator >= 0 && result.rem < 0) {
  494. result.quot++;
  495. result.rem -= denominator;
  496. }
  497. return result;
  498. }
  499. ldiv_t ldiv(long numerator, long denominator)
  500. {
  501. ldiv_t result;
  502. result.quot = numerator / denominator;
  503. result.rem = numerator % denominator;
  504. if (numerator >= 0 && result.rem < 0) {
  505. result.quot++;
  506. result.rem -= denominator;
  507. }
  508. return result;
  509. }
  510. size_t mbstowcs(wchar_t*, const char*, size_t)
  511. {
  512. ASSERT_NOT_REACHED();
  513. }
  514. size_t mbtowc(wchar_t* wch, const char* data, size_t data_size)
  515. {
  516. // FIXME: This needs a real implementation.
  517. UNUSED_PARAM(data_size);
  518. if (wch && data) {
  519. *wch = *data;
  520. return 1;
  521. }
  522. if (!wch && data) {
  523. return 1;
  524. }
  525. return 0;
  526. }
  527. int wctomb(char*, wchar_t)
  528. {
  529. ASSERT_NOT_REACHED();
  530. }
  531. size_t wcstombs(char* dest, const wchar_t* src, size_t max)
  532. {
  533. char* originalDest = dest;
  534. while ((size_t)(dest - originalDest) < max) {
  535. StringView v { (const char*)src, sizeof(wchar_t) };
  536. // FIXME: dependent on locale, for now utf-8 is supported.
  537. Utf8View utf8 { v };
  538. if (*utf8.begin() == '\0') {
  539. *dest = '\0';
  540. return (size_t)(dest - originalDest); // Exclude null character in returned size
  541. }
  542. for (auto byte : utf8) {
  543. if (byte != '\0')
  544. *dest++ = byte;
  545. }
  546. ++src;
  547. }
  548. return max;
  549. }
  550. long strtol(const char* str, char** endptr, int base)
  551. {
  552. return strtol_impl<long, LONG_MIN, LONG_MAX>(str, endptr, base);
  553. }
  554. unsigned long strtoul(const char* str, char** endptr, int base)
  555. {
  556. auto value = strtol(str, endptr, base);
  557. ASSERT(value >= 0);
  558. return value;
  559. }
  560. long long strtoll(const char* str, char** endptr, int base)
  561. {
  562. return strtol_impl<long long, LONG_LONG_MIN, LONG_LONG_MAX>(str, endptr, base);
  563. }
  564. unsigned long long strtoull(const char* str, char** endptr, int base)
  565. {
  566. auto value = strtoll(str, endptr, base);
  567. ASSERT(value >= 0);
  568. return value;
  569. }
  570. // Serenity's PRNG is not cryptographically secure. Do not rely on this for
  571. // any real crypto! These functions (for now) are for compatibility.
  572. // TODO: In the future, rand can be made determinstic and this not.
  573. uint32_t arc4random(void)
  574. {
  575. char buf[4];
  576. syscall(SC_getrandom, buf, 4, 0);
  577. return *(uint32_t*)buf;
  578. }
  579. void arc4random_buf(void* buffer, size_t buffer_size)
  580. {
  581. // arc4random_buf should never fail, but user supplied buffers could fail.
  582. // However, if the user passes a garbage buffer, that's on them.
  583. syscall(SC_getrandom, buffer, buffer_size, 0);
  584. }
  585. uint32_t arc4random_uniform(uint32_t max_bounds)
  586. {
  587. // XXX: Should actually apply special rules for uniformity; avoid what is
  588. // called "modulo bias".
  589. return arc4random() % max_bounds;
  590. }
  591. char* realpath(const char* pathname, char* buffer)
  592. {
  593. if (!pathname) {
  594. errno = EFAULT;
  595. return nullptr;
  596. }
  597. size_t size = PATH_MAX;
  598. if (buffer == nullptr)
  599. buffer = (char*)malloc(size);
  600. Syscall::SC_realpath_params params { { pathname, strlen(pathname) }, { buffer, size } };
  601. int rc = syscall(SC_realpath, &params);
  602. if (rc < 0) {
  603. errno = -rc;
  604. return nullptr;
  605. }
  606. errno = 0;
  607. return buffer;
  608. }
  609. }