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"
22 const char defifsvar[] ALIGN1 = "IFS= \t\n";
23 const char defoptindvar[] ALIGN1 = "OPTIND=1";
26 int FAST_FUNC is_well_formed_var_name(const char *s, char terminator)
28 if (!s || !(isalpha(*s) || *s == '_'))
33 while (isalnum(*s) || *s == '_');
35 return *s == terminator;
40 /* Needs to be interruptible: shell must handle traps and shell-special signals
41 * while inside read. To implement this, be sure to not loop on EINTR
42 * and return errno == EINTR reliably.
44 //TODO: use more efficient setvar() which takes a pointer to malloced "VAR=VAL"
45 //string. hush naturally has it, and ash has setvareq().
46 //Here we can simply store "VAR=" at buffer start and store read data directly
47 //after "=", then pass buffer to setvar() to consume.
49 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 */
68 struct termios tty, old_tty;
70 int bufpos; /* need to be able to hold -1 */
78 if (!is_well_formed_var_name(*pp, '\0')) {
79 /* Mimic bash message */
80 bb_error_msg("read: '%s': not a valid identifier", *pp);
81 return (const char *)(uintptr_t)1;
86 nchars = 0; /* if != 0, -n is in effect */
88 nchars = bb_strtou(opt_n, NULL, 10);
89 if (nchars < 0 || errno)
90 return "invalid count";
91 /* note: "-n 0": off (bash 3.2 does this too) */
95 if (opt_t && !ENABLE_FEATURE_SH_READ_FRAC) {
96 end_ms = bb_strtou(opt_t, NULL, 10);
98 return "invalid timeout";
99 if (end_ms > UINT_MAX / 2048) /* be safely away from overflow */
100 end_ms = UINT_MAX / 2048;
103 if (opt_t && ENABLE_FEATURE_SH_READ_FRAC) {
104 /* bash 4.3 (maybe earlier) supports -t N.NNNNNN */
106 /* Eat up to three fractional digits */
107 int frac_digits = 3 + 1;
109 end_ms = bb_strtou(opt_t, &p, 10);
110 if (end_ms > UINT_MAX / 2048) /* be safely away from overflow */
111 end_ms = UINT_MAX / 2048;
114 /* EINVAL = number is ok, but not NUL terminated */
115 if (errno != EINVAL || *p != '.')
116 return "invalid timeout";
117 /* Do not check the rest: bash allows "0.123456xyz" */
118 while (*++p && --frac_digits) {
120 end_ms += (*p - '0');
121 if ((unsigned char)(*p - '0') > 9)
122 return "invalid timeout";
125 while (--frac_digits > 0) {
132 fd = bb_strtou(opt_u, NULL, 10);
134 return "invalid file descriptor";
137 if (opt_t && end_ms == 0) {
138 /* "If timeout is 0, read returns immediately, without trying
139 * to read any data. The exit status is 0 if input is available
140 * on the specified file descriptor, non-zero otherwise."
141 * bash seems to ignore -p PROMPT for this use case.
144 pfd[0].events = POLLIN;
145 r = poll(pfd, 1, /*timeout:*/ 0);
146 /* Return 0 only if poll returns 1 ("one fd ready"), else return 1: */
147 return (const char *)(uintptr_t)(r <= 0);
150 if (opt_p && isatty(fd)) {
151 fputs(opt_p, stderr);
158 if (nchars || (read_flags & BUILTIN_READ_SILENT)) {
162 tty.c_lflag &= ~ICANON;
163 // Setting it to more than 1 breaks poll():
164 // it blocks even if there's data. !??
165 //tty.c_cc[VMIN] = nchars < 256 ? nchars : 255;
166 /* reads will block only if < 1 char is available */
168 /* no timeout (reads block forever) */
171 if (read_flags & BUILTIN_READ_SILENT) {
172 tty.c_lflag &= ~(ECHO | ECHOK | ECHONL);
174 /* This forces execution of "restoring" tcgetattr later */
175 read_flags |= BUILTIN_READ_SILENT;
176 /* if tcgetattr failed, tcsetattr will fail too.
177 * Ignoring, it's harmless. */
178 tcsetattr(fd, TCSANOW, &tty);
181 retval = (const char *)(uintptr_t)0;
185 end_ms += (unsigned)monotonic_ms();
188 delim = opt_d ? *opt_d : '\n';
193 if ((bufpos & 0xff) == 0)
194 buffer = xrealloc(buffer, bufpos + 0x101);
198 timeout = end_ms - (unsigned)monotonic_ms();
199 /* ^^^^^^^^^^^^^ all values are unsigned,
200 * wrapping math is used here, good even if
201 * 32-bit unix time wrapped (year 2038+).
203 if (timeout <= 0) { /* already late? */
204 retval = (const char *)(uintptr_t)1;
209 /* We must poll even if timeout is -1:
210 * we want to be interrupted if signal arrives,
211 * regardless of SA_RESTART-ness of that signal!
214 pfd[0].events = POLLIN;
215 if (poll(pfd, 1, timeout) <= 0) {
216 /* timed out, or EINTR */
218 retval = (const char *)(uintptr_t)1;
221 if (read(fd, &buffer[bufpos], 1) != 1) {
223 retval = (const char *)(uintptr_t)1;
230 if (!(read_flags & BUILTIN_READ_RAW)) {
242 if (c == delim) /* '\n' or -d CHAR */
245 /* $IFS splitting. NOT done if we run "read"
246 * without variable names (bash compat).
247 * Thus, "read" and "read REPLY" are not the same.
249 if (!opt_d && argv[0]) {
250 /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05 */
251 const char *is_ifs = strchr(ifs, c);
252 if (startword && is_ifs) {
255 /* it is a non-space ifs char */
257 if (startword == 1) /* first one? */
258 continue; /* yes, it is not next word yet */
261 if (argv[1] != NULL && is_ifs) {
262 buffer[bufpos] = '\0';
264 setvar(*argv, buffer);
266 /* can we skip one non-space ifs char? (2: yes) */
267 startword = isspace(c) ? 2 : 1;
276 /* Remove trailing space $IFS chars */
278 && isspace(buffer[bufpos])
279 && strchr(ifs, buffer[bufpos]) != NULL
283 buffer[bufpos + 1] = '\0';
285 /* Last variable takes the entire remainder with delimiters
286 * (sans trailing whitespace $IFS),
287 * but ***only "if there are fewer vars than fields"(c)***!
288 * The "X:Y:" case below: there are two fields,
289 * and therefore last delimiter (:) is eaten:
291 * echo "X:Y:Z:" | (read x y; echo "|$x|$y|") # |X|Y:Z:|
292 * echo "X:Y:Z" | (read x y; echo "|$x|$y|") # |X|Y:Z|
293 * echo "X:Y:" | (read x y; echo "|$x|$y|") # |X|Y|, not |X|Y:|
294 * echo "X:Y : " | (read x y; echo "|$x|$y|") # |X|Y|
297 && strchr(ifs, buffer[bufpos]) != NULL
299 /* There _is_ a non-whitespace IFS char */
300 /* Skip whitespace IFS char before it */
302 && isspace(buffer[bufpos])
303 && strchr(ifs, buffer[bufpos]) != NULL
307 /* Are there $IFS chars? */
308 if (strcspn(buffer, ifs) >= ++bufpos) {
309 /* No: last var takes one field, not more */
310 /* So, drop trailing IFS delims */
311 buffer[bufpos] = '\0';
315 /* Use the remainder as a value for the next variable */
316 setvar(*argv, buffer);
317 /* Set the rest to "" */
321 /* Note: no $IFS removal */
322 buffer[bufpos] = '\0';
323 setvar("REPLY", buffer);
328 if (read_flags & BUILTIN_READ_SILENT)
329 tcsetattr(fd, TCSANOW, &old_tty);
339 uint8_t cmd; /* RLIMIT_xxx fit into it */
340 uint8_t factor_shift; /* shift by to get rlim_{cur,max} values */
345 static const struct limits limits_tbl[] = {
347 { RLIMIT_FSIZE, 9, 'f', "file size (blocks)" },
350 { RLIMIT_CPU, 0, 't', "cpu time (seconds)" },
353 { RLIMIT_DATA, 10, 'd', "data seg size (kb)" },
356 { RLIMIT_STACK, 10, 's', "stack size (kb)" },
359 { RLIMIT_CORE, 9, 'c', "core file size (blocks)" },
362 { RLIMIT_RSS, 10, 'm', "resident set size (kb)" },
364 #ifdef RLIMIT_MEMLOCK
365 { RLIMIT_MEMLOCK, 10, 'l', "locked memory (kb)" },
368 { RLIMIT_NPROC, 0, 'p', "processes" },
371 { RLIMIT_NOFILE, 0, 'n', "file descriptors" },
374 { RLIMIT_AS, 10, 'v', "address space (kb)" },
377 { RLIMIT_LOCKS, 0, 'w', "locks" },
380 { RLIMIT_NICE, 0, 'e', "scheduling priority" },
383 { RLIMIT_RTPRIO, 0, 'r', "real-time priority" },
392 /* "-": treat args as parameters of option with ASCII code 1 */
393 static const char ulimit_opt_string[] ALIGN1 = "-HSa"
412 #ifdef RLIMIT_MEMLOCK
435 static void printlim(unsigned opts, const struct rlimit *limit,
436 const struct limits *l)
440 val = limit->rlim_max;
441 if (!(opts & OPT_hard))
442 val = limit->rlim_cur;
444 if (val == RLIM_INFINITY)
447 val >>= l->factor_shift;
448 printf("%llu\n", (long long) val);
453 shell_builtin_ulimit(char **argv)
458 /* We can't use getopt32: need to handle commands like
459 * ulimit 123 -c2 -l 456
462 /* In case getopt() was already called:
463 * reset libc getopt() internal state.
467 argc = string_array_len(argv);
472 const struct limits *l;
473 int opt_char = getopt(argc, argv, ulimit_opt_string);
477 if (opt_char == 'H') {
481 if (opt_char == 'S') {
486 if (opt_char == 'a') {
487 for (l = limits_tbl; l != &limits_tbl[ARRAY_SIZE(limits_tbl)]; l++) {
488 getrlimit(l->cmd, &limit);
489 printf("-%c: %-30s ", l->option, l->name);
490 printlim(opts, &limit, l);
497 for (l = limits_tbl; l != &limits_tbl[ARRAY_SIZE(limits_tbl)]; l++) {
498 if (opt_char == l->option) {
501 getrlimit(l->cmd, &limit);
504 if (!val_str && argv[optind] && argv[optind][0] != '-')
505 val_str = argv[optind++]; /* ++ skips NN in "-c NN" case */
509 if (strcmp(val_str, "unlimited") == 0)
512 if (sizeof(val) == sizeof(int))
513 val = bb_strtou(val_str, NULL, 10);
514 else if (sizeof(val) == sizeof(long))
515 val = bb_strtoul(val_str, NULL, 10);
517 val = bb_strtoull(val_str, NULL, 10);
519 bb_error_msg("invalid number '%s'", val_str);
522 val <<= l->factor_shift;
524 //bb_error_msg("opt %c val_str:'%s' val:%lld", opt_char, val_str, (long long)val);
525 /* from man bash: "If neither -H nor -S
526 * is specified, both the soft and hard
529 opts = OPT_hard + OPT_soft;
531 limit.rlim_max = val;
533 limit.rlim_cur = val;
534 //bb_error_msg("setrlimit(%d, %lld, %lld)", l->cmd, (long long)limit.rlim_cur, (long long)limit.rlim_max);
535 if (setrlimit(l->cmd, &limit) < 0) {
536 bb_perror_msg("error setting limit");
540 printlim(opts, &limit, l);
544 } /* for (every possible opt) */
546 if (l == &limits_tbl[ARRAY_SIZE(limits_tbl)]) {
547 /* bad option. getopt already complained. */
550 } /* while (there are options) */