1 /* vi: set sw=4 ts=4: */
3 * Adapted from ash applet code
5 * This code is derived from software contributed to Berkeley by
8 * Copyright (c) 1989, 1991, 1993, 1994
9 * The Regents of the University of California. All rights reserved.
11 * Copyright (c) 1997-2005 Herbert Xu <herbert@gondor.apana.org.au>
12 * was re-ported from NetBSD and debianized.
14 * Copyright (c) 2010 Denys Vlasenko
17 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
20 #include "shell_common.h"
21 #include <sys/resource.h> /* getrlimit */
23 const char defifsvar[] ALIGN1 = "IFS= \t\n";
24 const char defoptindvar[] ALIGN1 = "OPTIND=1";
27 int FAST_FUNC is_well_formed_var_name(const char *s, char terminator)
29 if (!s || !(isalpha(*s) || *s == '_'))
34 while (isalnum(*s) || *s == '_');
36 return *s == terminator;
41 /* Needs to be interruptible: shell must handle traps and shell-special signals
42 * while inside read. To implement this, be sure to not loop on EINTR
43 * and return errno == EINTR reliably.
45 //TODO: use more efficient setvar() which takes a pointer to malloced "VAR=VAL"
46 //string. hush naturally has it, and ash has setvareq().
47 //Here we can simply store "VAR=" at buffer start and store read data directly
48 //after "=", then pass buffer to setvar() to consume.
50 shell_builtin_read(void FAST_FUNC (*setvar)(const char *name, const char *val),
61 #define fd (pfd[0].fd) /* -u FD */
63 unsigned end_ms; /* -t TIMEOUT */
64 int nchars; /* -n NUM */
67 struct termios tty, old_tty;
69 int bufpos; /* need to be able to hold -1 */
77 if (!is_well_formed_var_name(*pp, '\0')) {
78 /* Mimic bash message */
79 bb_error_msg("read: '%s': not a valid identifier", *pp);
80 return (const char *)(uintptr_t)1;
85 nchars = 0; /* if != 0, -n is in effect */
87 nchars = bb_strtou(opt_n, NULL, 10);
88 if (nchars < 0 || errno)
89 return "invalid count";
90 /* note: "-n 0": off (bash 3.2 does this too) */
94 if (opt_t && !ENABLE_FEATURE_SH_READ_FRAC) {
95 end_ms = bb_strtou(opt_t, NULL, 10);
97 return "invalid timeout";
98 if (end_ms > UINT_MAX / 2048) /* be safely away from overflow */
99 end_ms = UINT_MAX / 2048;
102 if (opt_t && ENABLE_FEATURE_SH_READ_FRAC) {
103 /* bash 4.3 (maybe earlier) supports -t N.NNNNNN */
105 /* Eat up to three fractional digits */
106 int frac_digits = 3 + 1;
108 end_ms = bb_strtou(opt_t, &p, 10);
109 if (end_ms > UINT_MAX / 2048) /* be safely away from overflow */
110 end_ms = UINT_MAX / 2048;
113 /* EINVAL = number is ok, but not NUL terminated */
114 if (errno != EINVAL || *p != '.')
115 return "invalid timeout";
116 /* Do not check the rest: bash allows "0.123456xyz" */
117 while (*++p && --frac_digits) {
119 end_ms += (*p - '0');
120 if ((unsigned char)(*p - '0') > 9)
121 return "invalid timeout";
124 while (--frac_digits > 0) {
131 fd = bb_strtou(opt_u, NULL, 10);
133 return "invalid file descriptor";
136 if (opt_t && end_ms == 0) {
137 /* "If timeout is 0, read returns immediately, without trying
138 * to read any data. The exit status is 0 if input is available
139 * on the specified file descriptor, non-zero otherwise."
140 * bash seems to ignore -p PROMPT for this use case.
143 pfd[0].events = POLLIN;
144 r = poll(pfd, 1, /*timeout:*/ 0);
145 /* Return 0 only if poll returns 1 ("one fd ready"), else return 1: */
146 return (const char *)(uintptr_t)(r <= 0);
149 if (opt_p && isatty(fd)) {
150 fputs(opt_p, stderr);
157 if (nchars || (read_flags & BUILTIN_READ_SILENT)) {
161 tty.c_lflag &= ~ICANON;
162 // Setting it to more than 1 breaks poll():
163 // it blocks even if there's data. !??
164 //tty.c_cc[VMIN] = nchars < 256 ? nchars : 255;
165 /* reads will block only if < 1 char is available */
167 /* no timeout (reads block forever) */
170 if (read_flags & BUILTIN_READ_SILENT) {
171 tty.c_lflag &= ~(ECHO | ECHOK | ECHONL);
173 /* This forces execution of "restoring" tcgetattr later */
174 read_flags |= BUILTIN_READ_SILENT;
175 /* if tcgetattr failed, tcsetattr will fail too.
176 * Ignoring, it's harmless. */
177 tcsetattr(fd, TCSANOW, &tty);
180 retval = (const char *)(uintptr_t)0;
184 end_ms += (unsigned)monotonic_ms();
191 if ((bufpos & 0xff) == 0)
192 buffer = xrealloc(buffer, bufpos + 0x101);
196 timeout = end_ms - (unsigned)monotonic_ms();
197 /* ^^^^^^^^^^^^^ all values are unsigned,
198 * wrapping math is used here, good even if
199 * 32-bit unix time wrapped (year 2038+).
201 if (timeout <= 0) { /* already late? */
202 retval = (const char *)(uintptr_t)1;
207 /* We must poll even if timeout is -1:
208 * we want to be interrupted if signal arrives,
209 * regardless of SA_RESTART-ness of that signal!
212 pfd[0].events = POLLIN;
213 if (poll(pfd, 1, timeout) <= 0) {
214 /* timed out, or EINTR */
216 retval = (const char *)(uintptr_t)1;
219 if (read(fd, &buffer[bufpos], 1) != 1) {
221 retval = (const char *)(uintptr_t)1;
228 if (!(read_flags & BUILTIN_READ_RAW)) {
243 /* $IFS splitting. NOT done if we run "read"
244 * without variable names (bash compat).
245 * Thus, "read" and "read REPLY" are not the same.
248 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05 */
249 const char *is_ifs = strchr(ifs, c);
250 if (startword && is_ifs) {
253 /* it is a non-space ifs char */
255 if (startword == 1) /* first one? */
256 continue; /* yes, it is not next word yet */
259 if (argv[1] != NULL && is_ifs) {
260 buffer[bufpos] = '\0';
262 setvar(*argv, buffer);
264 /* can we skip one non-space ifs char? (2: yes) */
265 startword = isspace(c) ? 2 : 1;
274 /* Remove trailing space $IFS chars */
275 while (--bufpos >= 0 && isspace(buffer[bufpos]) && strchr(ifs, buffer[bufpos]) != NULL)
277 buffer[bufpos + 1] = '\0';
278 /* Use the remainder as a value for the next variable */
279 setvar(*argv, buffer);
280 /* Set the rest to "" */
284 /* Note: no $IFS removal */
285 buffer[bufpos] = '\0';
286 setvar("REPLY", buffer);
291 if (read_flags & BUILTIN_READ_SILENT)
292 tcsetattr(fd, TCSANOW, &old_tty);
302 uint8_t cmd; /* RLIMIT_xxx fit into it */
303 uint8_t factor_shift; /* shift by to get rlim_{cur,max} values */
308 static const struct limits limits_tbl[] = {
310 { RLIMIT_FSIZE, 9, 'f', "file size (blocks)" },
313 { RLIMIT_CPU, 0, 't', "cpu time (seconds)" },
316 { RLIMIT_DATA, 10, 'd', "data seg size (kb)" },
319 { RLIMIT_STACK, 10, 's', "stack size (kb)" },
322 { RLIMIT_CORE, 9, 'c', "core file size (blocks)" },
325 { RLIMIT_RSS, 10, 'm', "resident set size (kb)" },
327 #ifdef RLIMIT_MEMLOCK
328 { RLIMIT_MEMLOCK, 10, 'l', "locked memory (kb)" },
331 { RLIMIT_NPROC, 0, 'p', "processes" },
334 { RLIMIT_NOFILE, 0, 'n', "file descriptors" },
337 { RLIMIT_AS, 10, 'v', "address space (kb)" },
340 { RLIMIT_LOCKS, 0, 'w', "locks" },
343 { RLIMIT_NICE, 0, 'e', "scheduling priority" },
346 { RLIMIT_RTPRIO, 0, 'r', "real-time priority" },
355 /* "-": treat args as parameters of option with ASCII code 1 */
356 static const char ulimit_opt_string[] ALIGN1 = "-HSa"
375 #ifdef RLIMIT_MEMLOCK
398 static void printlim(unsigned opts, const struct rlimit *limit,
399 const struct limits *l)
403 val = limit->rlim_max;
404 if (!(opts & OPT_hard))
405 val = limit->rlim_cur;
407 if (val == RLIM_INFINITY)
410 val >>= l->factor_shift;
411 printf("%llu\n", (long long) val);
416 shell_builtin_ulimit(char **argv)
421 /* We can't use getopt32: need to handle commands like
422 * ulimit 123 -c2 -l 456
425 /* In case getopt was already called:
426 * reset the libc getopt() function, which keeps internal state.
430 argc = string_array_len(argv);
435 const struct limits *l;
436 int opt_char = getopt(argc, argv, ulimit_opt_string);
440 if (opt_char == 'H') {
444 if (opt_char == 'S') {
449 if (opt_char == 'a') {
450 for (l = limits_tbl; l != &limits_tbl[ARRAY_SIZE(limits_tbl)]; l++) {
451 getrlimit(l->cmd, &limit);
452 printf("-%c: %-30s ", l->option, l->name);
453 printlim(opts, &limit, l);
460 for (l = limits_tbl; l != &limits_tbl[ARRAY_SIZE(limits_tbl)]; l++) {
461 if (opt_char == l->option) {
464 getrlimit(l->cmd, &limit);
467 if (!val_str && argv[optind] && argv[optind][0] != '-')
468 val_str = argv[optind++]; /* ++ skips NN in "-c NN" case */
472 if (strcmp(val_str, "unlimited") == 0)
475 if (sizeof(val) == sizeof(int))
476 val = bb_strtou(val_str, NULL, 10);
477 else if (sizeof(val) == sizeof(long))
478 val = bb_strtoul(val_str, NULL, 10);
480 val = bb_strtoull(val_str, NULL, 10);
482 bb_error_msg("invalid number '%s'", val_str);
485 val <<= l->factor_shift;
487 //bb_error_msg("opt %c val_str:'%s' val:%lld", opt_char, val_str, (long long)val);
488 /* from man bash: "If neither -H nor -S
489 * is specified, both the soft and hard
492 opts = OPT_hard + OPT_soft;
494 limit.rlim_max = val;
496 limit.rlim_cur = val;
497 //bb_error_msg("setrlimit(%d, %lld, %lld)", l->cmd, (long long)limit.rlim_cur, (long long)limit.rlim_max);
498 if (setrlimit(l->cmd, &limit) < 0) {
499 bb_perror_msg("error setting limit");
503 printlim(opts, &limit, l);
507 } /* for (every possible opt) */
509 if (l == &limits_tbl[ARRAY_SIZE(limits_tbl)]) {
510 /* bad option. getopt already complained. */
513 } /* while (there are options) */