stdlib.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592
  1. #include <AK/Assertions.h>
  2. #include <AK/HashMap.h>
  3. #include <AK/StdLibExtras.h>
  4. #include <AK/String.h>
  5. #include <AK/Types.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. extern "C" {
  20. typedef void (*__atexit_handler)();
  21. static int __atexit_handler_count = 0;
  22. static __atexit_handler __atexit_handlers[32];
  23. void exit(int status)
  24. {
  25. for (int i = 0; i < __atexit_handler_count; ++i)
  26. __atexit_handlers[i]();
  27. extern void _fini();
  28. _fini();
  29. fflush(stdout);
  30. fflush(stderr);
  31. _exit(status);
  32. ASSERT_NOT_REACHED();
  33. }
  34. int atexit(void (*handler)())
  35. {
  36. ASSERT(__atexit_handler_count < 32);
  37. __atexit_handlers[__atexit_handler_count++] = handler;
  38. return 0;
  39. }
  40. void abort()
  41. {
  42. raise(SIGABRT);
  43. ASSERT_NOT_REACHED();
  44. }
  45. static HashTable<const char*> s_malloced_environment_variables;
  46. static void free_environment_variable_if_needed(const char* var)
  47. {
  48. if (!s_malloced_environment_variables.contains(var))
  49. return;
  50. free(const_cast<char*>(var));
  51. s_malloced_environment_variables.remove(var);
  52. }
  53. char* getenv(const char* name)
  54. {
  55. size_t vl = strlen(name);
  56. for (size_t i = 0; environ[i]; ++i) {
  57. const char* decl = environ[i];
  58. char* eq = strchr(decl, '=');
  59. if (!eq)
  60. continue;
  61. size_t varLength = eq - decl;
  62. if (vl != varLength)
  63. continue;
  64. if (strncmp(decl, name, varLength) == 0) {
  65. return eq + 1;
  66. }
  67. }
  68. return nullptr;
  69. }
  70. int unsetenv(const char* name)
  71. {
  72. auto new_var_len = strlen(name);
  73. size_t environ_size = 0;
  74. int skip = -1;
  75. for (; environ[environ_size]; ++environ_size) {
  76. char* old_var = environ[environ_size];
  77. char* old_eq = strchr(old_var, '=');
  78. ASSERT(old_eq);
  79. size_t old_var_len = old_eq - old_var;
  80. if (new_var_len != old_var_len)
  81. continue; // can't match
  82. if (strncmp(name, old_var, new_var_len) == 0)
  83. skip = environ_size;
  84. }
  85. if (skip == -1)
  86. return 0; // not found: no failure.
  87. // Shuffle the existing array down by one.
  88. memmove(&environ[skip], &environ[skip + 1], ((environ_size - 1) - skip) * sizeof(environ[0]));
  89. environ[environ_size - 1] = nullptr;
  90. free_environment_variable_if_needed(name);
  91. return 0;
  92. }
  93. int setenv(const char* name, const char* value, int overwrite)
  94. {
  95. if (!overwrite && !getenv(name))
  96. return 0;
  97. auto length = strlen(name) + strlen(value) + 2;
  98. auto* var = (char*)malloc(length);
  99. snprintf(var, length, "%s=%s", name, value);
  100. s_malloced_environment_variables.set(var);
  101. return putenv(var);
  102. }
  103. int putenv(char* new_var)
  104. {
  105. char* new_eq = strchr(new_var, '=');
  106. if (!new_eq)
  107. return unsetenv(new_var);
  108. auto new_var_len = new_eq - new_var;
  109. int environ_size = 0;
  110. for (; environ[environ_size]; ++environ_size) {
  111. char* old_var = environ[environ_size];
  112. char* old_eq = strchr(old_var, '=');
  113. ASSERT(old_eq);
  114. auto old_var_len = old_eq - old_var;
  115. if (new_var_len != old_var_len)
  116. continue; // can't match
  117. if (strncmp(new_var, old_var, new_var_len) == 0) {
  118. free_environment_variable_if_needed(old_var);
  119. environ[environ_size] = new_var;
  120. return 0;
  121. }
  122. }
  123. // At this point, we need to append the new var.
  124. // 2 here: one for the new var, one for the sentinel value.
  125. char** new_environ = (char**)malloc((environ_size + 2) * sizeof(char*));
  126. if (new_environ == nullptr) {
  127. errno = ENOMEM;
  128. return -1;
  129. }
  130. for (int i = 0; environ[i]; ++i) {
  131. new_environ[i] = environ[i];
  132. }
  133. new_environ[environ_size] = new_var;
  134. new_environ[environ_size + 1] = nullptr;
  135. // swap new and old
  136. // note that the initial environ is not heap allocated!
  137. extern bool __environ_is_malloced;
  138. if (__environ_is_malloced)
  139. free(environ);
  140. __environ_is_malloced = true;
  141. environ = new_environ;
  142. return 0;
  143. }
  144. }
  145. double strtod(const char* str, char** endptr)
  146. {
  147. (void)str;
  148. (void)endptr;
  149. dbgprintf("LibC: strtod: '%s'\n", str);
  150. ASSERT_NOT_REACHED();
  151. }
  152. long double strtold(const char* str, char** endptr)
  153. {
  154. (void)str;
  155. (void)endptr;
  156. dbgprintf("LibC: strtold: '%s'\n", str);
  157. ASSERT_NOT_REACHED();
  158. }
  159. float strtof(const char* str, char** endptr)
  160. {
  161. (void)str;
  162. (void)endptr;
  163. dbgprintf("LibC: strtof: '%s'\n", str);
  164. ASSERT_NOT_REACHED();
  165. }
  166. double atof(const char* str)
  167. {
  168. size_t len = strlen(str);
  169. size_t weight = 1;
  170. int exp_val = 0;
  171. double value = 0.0f;
  172. double fraction = 0.0f;
  173. bool has_sign = false;
  174. bool is_negative = false;
  175. bool is_fractional = false;
  176. bool is_scientific = false;
  177. if (str[0] == '-') {
  178. is_negative = true;
  179. has_sign = true;
  180. }
  181. if (str[0] == '+') {
  182. has_sign = true;
  183. }
  184. for (size_t i = has_sign; i < len; i++) {
  185. // Looks like we're about to start working on the fractional part
  186. if (str[i] == '.') {
  187. is_fractional = true;
  188. continue;
  189. }
  190. if (str[i] == 'e' || str[i] == 'E') {
  191. if (str[i + 1] == '-' || str[i + 1] == '+')
  192. exp_val = atoi(str + i + 2);
  193. else
  194. exp_val = atoi(str + i + 1);
  195. is_scientific = true;
  196. continue;
  197. }
  198. if (str[i] < '0' || str[i] > '9' || exp_val != 0)
  199. continue;
  200. if (is_fractional) {
  201. fraction *= 10;
  202. fraction += str[i] - '0';
  203. weight *= 10;
  204. } else {
  205. value = value * 10;
  206. value += str[i] - '0';
  207. }
  208. }
  209. fraction /= weight;
  210. value += fraction;
  211. if (is_scientific) {
  212. bool divide = exp_val < 0;
  213. if (divide)
  214. exp_val *= -1;
  215. for (int i = 0; i < exp_val; i++) {
  216. if (divide)
  217. value /= 10;
  218. else
  219. value *= 10;
  220. }
  221. }
  222. return is_negative ? -value : value;
  223. }
  224. int atoi(const char* str)
  225. {
  226. size_t len = strlen(str);
  227. int value = 0;
  228. bool isNegative = false;
  229. for (size_t i = 0; i < len; ++i) {
  230. if (i == 0 && str[0] == '-') {
  231. isNegative = true;
  232. continue;
  233. }
  234. if (str[i] < '0' || str[i] > '9')
  235. return value;
  236. value = value * 10;
  237. value += str[i] - '0';
  238. }
  239. return isNegative ? -value : value;
  240. }
  241. long atol(const char* str)
  242. {
  243. static_assert(sizeof(int) == sizeof(long));
  244. return atoi(str);
  245. }
  246. long long atoll(const char* str)
  247. {
  248. dbgprintf("FIXME(Libc): atoll('%s') passing through to atol()\n", str);
  249. return atol(str);
  250. }
  251. static char ptsname_buf[32];
  252. char* ptsname(int fd)
  253. {
  254. if (ptsname_r(fd, ptsname_buf, sizeof(ptsname_buf)) < 0)
  255. return nullptr;
  256. return ptsname_buf;
  257. }
  258. int ptsname_r(int fd, char* buffer, size_t size)
  259. {
  260. int rc = syscall(SC_ptsname_r, fd, buffer, size);
  261. __RETURN_WITH_ERRNO(rc, rc, -1);
  262. }
  263. static unsigned long s_next_rand = 1;
  264. int rand()
  265. {
  266. s_next_rand = s_next_rand * 1103515245 + 12345;
  267. return ((unsigned)(s_next_rand / ((RAND_MAX + 1) * 2)) % (RAND_MAX + 1));
  268. }
  269. void srand(unsigned seed)
  270. {
  271. s_next_rand = seed;
  272. }
  273. int abs(int i)
  274. {
  275. return i < 0 ? -i : i;
  276. }
  277. long int random()
  278. {
  279. return rand();
  280. }
  281. void srandom(unsigned seed)
  282. {
  283. srand(seed);
  284. }
  285. int system(const char* command)
  286. {
  287. if (!command)
  288. return 1;
  289. auto child = fork();
  290. if (child < 0)
  291. return -1;
  292. if (!child) {
  293. int rc = execl("/bin/sh", "sh", "-c", command, nullptr);
  294. ASSERT(rc < 0);
  295. perror("execl");
  296. exit(127);
  297. }
  298. int wstatus;
  299. waitpid(child, &wstatus, 0);
  300. return WEXITSTATUS(wstatus);
  301. }
  302. char* mktemp(char* pattern)
  303. {
  304. int length = strlen(pattern);
  305. if (length < 6 || !String(pattern).ends_with("XXXXXX")) {
  306. pattern[0] = '\0';
  307. errno = EINVAL;
  308. return pattern;
  309. }
  310. int start = length - 6;
  311. static constexpr char random_characters[] = "abcdefghijklmnopqrstuvwxyz0123456789";
  312. for (int attempt = 0; attempt < 100; ++attempt) {
  313. for (int i = 0; i < 6; ++i)
  314. pattern[start + i] = random_characters[(rand() % sizeof(random_characters))];
  315. struct stat st;
  316. int rc = lstat(pattern, &st);
  317. if (rc < 0 && errno == ENOENT)
  318. return pattern;
  319. }
  320. pattern[0] = '\0';
  321. errno = EEXIST;
  322. return pattern;
  323. }
  324. char* mkdtemp(char* pattern)
  325. {
  326. int length = strlen(pattern);
  327. if (length < 6 || !String(pattern).ends_with("XXXXXX")) {
  328. errno = EINVAL;
  329. return nullptr;
  330. }
  331. int start = length - 6;
  332. static constexpr char random_characters[] = "abcdefghijklmnopqrstuvwxyz0123456789";
  333. for (int attempt = 0; attempt < 100; ++attempt) {
  334. for (int i = 0; i < 6; ++i)
  335. pattern[start + i] = random_characters[(rand() % sizeof(random_characters))];
  336. struct stat st;
  337. int rc = lstat(pattern, &st);
  338. if (rc < 0 && errno == ENOENT) {
  339. if (mkdir(pattern, 0700) < 0)
  340. return nullptr;
  341. return pattern;
  342. }
  343. }
  344. errno = EEXIST;
  345. return nullptr;
  346. }
  347. void* bsearch(const void* key, const void* base, size_t nmemb, size_t size, int (*compar)(const void*, const void*))
  348. {
  349. dbgprintf("FIXME(LibC): bsearch(%p, %p, %u, %u, %p)\n", key, base, nmemb, size, compar);
  350. ASSERT_NOT_REACHED();
  351. }
  352. div_t div(int numerator, int denominator)
  353. {
  354. div_t result;
  355. result.quot = numerator / denominator;
  356. result.rem = numerator % denominator;
  357. if (numerator >= 0 && result.rem < 0) {
  358. result.quot++;
  359. result.rem -= denominator;
  360. }
  361. return result;
  362. }
  363. ldiv_t ldiv(long numerator, long denominator)
  364. {
  365. ldiv_t result;
  366. result.quot = numerator / denominator;
  367. result.rem = numerator % denominator;
  368. if (numerator >= 0 && result.rem < 0) {
  369. result.quot++;
  370. result.rem -= denominator;
  371. }
  372. return result;
  373. }
  374. size_t mbstowcs(wchar_t*, const char*, size_t)
  375. {
  376. ASSERT_NOT_REACHED();
  377. }
  378. size_t mbtowc(wchar_t*, const char*, size_t)
  379. {
  380. ASSERT_NOT_REACHED();
  381. }
  382. int wctomb(char*, wchar_t)
  383. {
  384. ASSERT_NOT_REACHED();
  385. }
  386. template<typename T, T min_value, T max_value>
  387. static T strtol_impl(const char* nptr, char** endptr, int base)
  388. {
  389. errno = 0;
  390. if (base < 0 || base == 1 || base > 36) {
  391. errno = EINVAL;
  392. if (endptr)
  393. *endptr = const_cast<char*>(nptr);
  394. return 0;
  395. }
  396. const char* p = nptr;
  397. while (isspace(*p))
  398. ++p;
  399. bool is_negative = false;
  400. if (*p == '-') {
  401. is_negative = true;
  402. ++p;
  403. } else {
  404. if (*p == '+')
  405. ++p;
  406. }
  407. if (base == 0 || base == 16) {
  408. if (base == 0)
  409. base = 10;
  410. if (*p == '0') {
  411. if (*(p + 1) == 'X' || *(p + 1) == 'x') {
  412. p += 2;
  413. base = 16;
  414. } else if (base != 16) {
  415. base = 8;
  416. }
  417. }
  418. }
  419. long cutoff_point = is_negative ? (min_value / base) : (max_value / base);
  420. int max_valid_digit_at_cutoff_point = is_negative ? (min_value % base) : (max_value % base);
  421. long num = 0;
  422. bool has_overflowed = false;
  423. unsigned digits_consumed = 0;
  424. for (;;) {
  425. char ch = *(p++);
  426. int digit;
  427. if (isdigit(ch))
  428. digit = ch - '0';
  429. else if (islower(ch))
  430. digit = ch - ('a' - 10);
  431. else if (isupper(ch))
  432. digit = ch - ('A' - 10);
  433. else
  434. break;
  435. if (digit >= base)
  436. break;
  437. if (has_overflowed)
  438. continue;
  439. bool is_past_cutoff = is_negative ? num < cutoff_point : num > cutoff_point;
  440. if (is_past_cutoff || (num == cutoff_point && digit > max_valid_digit_at_cutoff_point)) {
  441. has_overflowed = true;
  442. num = is_negative ? min_value : max_value;
  443. errno = ERANGE;
  444. } else {
  445. num *= base;
  446. num += is_negative ? -digit : digit;
  447. ++digits_consumed;
  448. }
  449. }
  450. if (endptr) {
  451. if (has_overflowed || digits_consumed > 0)
  452. *endptr = const_cast<char*>(p - 1);
  453. else
  454. *endptr = const_cast<char*>(nptr);
  455. }
  456. return num;
  457. }
  458. long strtol(const char* str, char** endptr, int base)
  459. {
  460. return strtol_impl<long, LONG_MIN, LONG_MAX>(str, endptr, base);
  461. }
  462. unsigned long strtoul(const char* str, char** endptr, int base)
  463. {
  464. auto value = strtol(str, endptr, base);
  465. ASSERT(value >= 0);
  466. return value;
  467. }
  468. long long strtoll(const char* str, char** endptr, int base)
  469. {
  470. return strtol_impl<long long, LONG_LONG_MIN, LONG_LONG_MAX>(str, endptr, base);
  471. }
  472. unsigned long long strtoull(const char* str, char** endptr, int base)
  473. {
  474. auto value = strtoll(str, endptr, base);
  475. ASSERT(value >= 0);
  476. return value;
  477. }
  478. // Serenity's PRNG is not cryptographically secure. Do not rely on this for
  479. // any real crypto! These functions (for now) are for compatibility.
  480. // TODO: In the future, rand can be made determinstic and this not.
  481. uint32_t arc4random(void)
  482. {
  483. char buf[4];
  484. syscall(SC_getrandom, buf, 4, 0);
  485. return *(uint32_t*)buf;
  486. }
  487. void arc4random_buf(void* buffer, size_t buffer_size)
  488. {
  489. // arc4random_buf should never fail, but user supplied buffers could fail.
  490. // However, if the user passes a garbage buffer, that's on them.
  491. syscall(SC_getrandom, buffer, buffer_size, 0);
  492. }
  493. uint32_t arc4random_uniform(uint32_t max_bounds)
  494. {
  495. // XXX: Should actually apply special rules for uniformity; avoid what is
  496. // called "modulo bias".
  497. return arc4random() % max_bounds;
  498. }