examples/loadables/rev.c
- include config.h to fix build (e.g., with unlocked-io)
- getlen: avoid reading one byte before start of line
- reverse_line: make sure BUF can fit the separator, if needed
- rev_internal: do not require an argument for the -0 option
- rev_internal: make sure to close any FD we opened, even if FD==0
---
examples/loadables/rev.c | 29 +++++++++++++++++------------
1 file changed, 17 insertions(+), 12 deletions(-)
diff --git a/examples/loadables/rev.c b/examples/loadables/rev.c
index b8d7d4d8..e15ca445 100644
--- a/examples/loadables/rev.c
+++ b/examples/loadables/rev.c
@@ -43,6 +43,8 @@
/* Headers */
+#include "config.h"
+
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
@@ -86,6 +88,7 @@ getlen(char *last_trlg_byte, int num_bytes_left)
if ((*p-- & mask[1]) != mask[0])
goto not_utf_8;
+ num_bytes_left--;
n = 2;
for (i = num_bytes_left >= 3 ? 3 : num_bytes_left; i > 0; i--, p--, n++)
{ /* 3 more bytes max */
@@ -119,9 +122,9 @@ reverse_line(SHELL_VAR *v, arrayind_t *ind, char *line,
size_t len,
* with NULL value and putting an allocated buffer in it.
*/
bind_array_element (v, (*ind)++, (char *)NULL, 0);
- buf = xmalloc(len + 1); /* +1 for NUL */
+ buf = xmalloc(len + outputsep + 1); /* +1 for NUL */
(((ARRAY *)v->value)->lastref)->value = buf;
- buf[len] = '\0';
+ buf[len + outputsep] = '\0';
} /* if (v) */
#endif
@@ -177,7 +180,7 @@ rev_internal(WORD_LIST *list)
ind = 0;
reset_internal_getopt();
- while ((opt = internal_getopt(list, "0:a:h")) != -1)
+ while ((opt = internal_getopt(list, "0a:h")) != -1)
switch (opt)
{
case '0':
@@ -221,15 +224,17 @@ rev_internal(WORD_LIST *list)
/* for each file */
if (l == 0)
- fd = 0;
+ fd = -1;
else
- SYSCALL(fd, open(l->word->word, O_RDONLY));
- if (fd == -1)
- {
- file_error(l->word->word);
- rval = EXECUTION_FAILURE;
- goto next_file;
- }
+ {
+ SYSCALL(fd, open(l->word->word, O_RDONLY));
+ if (fd == -1)
+ {
+ file_error(l->word->word);
+ rval = EXECUTION_FAILURE;
+ goto next_file;
+ }
+ }
#ifndef __CYGWIN__
unbuffered_read = (lseek(fd, 0L, SEEK_CUR) < 0) && (errno == ESPIPE);
@@ -250,7 +255,7 @@ rev_internal(WORD_LIST *list)
}
reverse_line(v, &ind, line, n, outputsep, sep);
} /* while ((n = zgetline(...) !=-1) */
- if (fd != 0)
+ if (fd != -1)
close(fd);
next_file:
--
2.54.0