xref: /freebsd/usr.bin/tail/reverse.c (revision 3494f7c0)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1991, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * This code is derived from software contributed to Berkeley by
8  * Edward Sze-Tyan Wang.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  */
34 
35 #include <sys/param.h>
36 #include <sys/queue.h>
37 #include <sys/stat.h>
38 #include <sys/mman.h>
39 
40 #include <err.h>
41 #include <errno.h>
42 #include <limits.h>
43 #include <stdint.h>
44 #include <stdio.h>
45 #include <stdlib.h>
46 #include <string.h>
47 #include <unistd.h>
48 
49 #include <libcasper.h>
50 #include <casper/cap_fileargs.h>
51 
52 #include "extern.h"
53 
54 static void r_buf(FILE *, const char *);
55 static void r_reg(FILE *, const char *, enum STYLE, off_t, struct stat *);
56 
57 /*
58  * reverse -- display input in reverse order by line.
59  *
60  * There are six separate cases for this -- regular and non-regular
61  * files by bytes, lines or the whole file.
62  *
63  * BYTES	display N bytes
64  *	REG	mmap the file and display the lines
65  *	NOREG	cyclically read characters into a wrap-around buffer
66  *
67  * LINES	display N lines
68  *	REG	mmap the file and display the lines
69  *	NOREG	cyclically read lines into a wrap-around array of buffers
70  *
71  * FILE		display the entire file
72  *	REG	mmap the file and display the lines
73  *	NOREG	cyclically read input into a linked list of buffers
74  */
75 void
76 reverse(FILE *fp, const char *fn, enum STYLE style, off_t off, struct stat *sbp)
77 {
78 	if (style != REVERSE && off == 0)
79 		return;
80 
81 	if (S_ISREG(sbp->st_mode))
82 		r_reg(fp, fn, style, off, sbp);
83 	else
84 		switch(style) {
85 		case FBYTES:
86 		case RBYTES:
87 			bytes(fp, fn, off);
88 			break;
89 		case FLINES:
90 		case RLINES:
91 			lines(fp, fn, off);
92 			break;
93 		case REVERSE:
94 			r_buf(fp, fn);
95 			break;
96 		default:
97 			break;
98 		}
99 }
100 
101 /*
102  * r_reg -- display a regular file in reverse order by line.
103  */
104 static void
105 r_reg(FILE *fp, const char *fn, enum STYLE style, off_t off, struct stat *sbp)
106 {
107 	struct mapinfo map;
108 	off_t curoff, size, lineend;
109 	int i;
110 
111 	if (!(size = sbp->st_size))
112 		return;
113 
114 	map.start = NULL;
115 	map.mapoff = map.maxoff = size;
116 	map.fd = fileno(fp);
117 	map.maplen = 0;
118 
119 	/*
120 	 * Last char is special, ignore whether newline or not. Note that
121 	 * size == 0 is dealt with above, and size == 1 sets curoff to -1.
122 	 */
123 	curoff = size - 2;
124 	lineend = size;
125 	while (curoff >= 0) {
126 		if (curoff < map.mapoff ||
127 		    curoff >= map.mapoff + (off_t)map.maplen) {
128 			if (maparound(&map, curoff) != 0) {
129 				ierr(fn);
130 				return;
131 			}
132 		}
133 		for (i = curoff - map.mapoff; i >= 0; i--) {
134 			if (style == RBYTES && --off == 0)
135 				break;
136 			if (map.start[i] == '\n')
137 				break;
138 		}
139 		/* `i' is either the map offset of a '\n', or -1. */
140 		curoff = map.mapoff + i;
141 		if (i < 0)
142 			continue;
143 
144 		/* Print the line and update offsets. */
145 		if (mapprint(&map, curoff + 1, lineend - curoff - 1) != 0) {
146 			ierr(fn);
147 			return;
148 		}
149 		lineend = curoff + 1;
150 		curoff--;
151 
152 		if (style == RLINES)
153 			off--;
154 
155 		if (off == 0 && style != REVERSE) {
156 			/* Avoid printing anything below. */
157 			curoff = 0;
158 			break;
159 		}
160 	}
161 	if (curoff < 0 && mapprint(&map, 0, lineend) != 0) {
162 		ierr(fn);
163 		return;
164 	}
165 	if (map.start != NULL && munmap(map.start, map.maplen))
166 		ierr(fn);
167 }
168 
169 #define BSZ	(128 * 1024)
170 typedef struct bfelem {
171 	TAILQ_ENTRY(bfelem) entries;
172 	size_t len;
173 	char l[BSZ];
174 } bfelem_t;
175 
176 /*
177  * r_buf -- display a non-regular file in reverse order by line.
178  *
179  * This is the function that saves the entire input, storing the data in a
180  * doubly linked list of buffers and then displays them in reverse order.
181  * It has the usual nastiness of trying to find the newlines, as there's no
182  * guarantee that a newline occurs anywhere in the file, let alone in any
183  * particular buffer.  If we run out of memory, input is discarded (and the
184  * user warned).
185  */
186 static void
187 r_buf(FILE *fp, const char *fn)
188 {
189 	struct bfelem *tl, *first = NULL;
190 	size_t llen;
191 	char *p;
192 	off_t enomem = 0;
193 	TAILQ_HEAD(bfhead, bfelem) head;
194 
195 	TAILQ_INIT(&head);
196 
197 	while (!feof(fp)) {
198 		size_t len;
199 
200 		/*
201 		 * Allocate a new block and link it into place in a doubly
202 		 * linked list.  If out of memory, toss the LRU block and
203 		 * keep going.
204 		 */
205 		while ((tl = malloc(sizeof(bfelem_t))) == NULL) {
206 			first = TAILQ_FIRST(&head);
207 			if (TAILQ_EMPTY(&head))
208 				err(1, "failed to allocate memory");
209 			enomem += first->len;
210 			TAILQ_REMOVE(&head, first, entries);
211 			free(first);
212 		}
213 		TAILQ_INSERT_TAIL(&head, tl, entries);
214 
215 		/* Fill the block with input data. */
216 		len = 0;
217 		while ((!feof(fp)) && len < BSZ) {
218 			p = tl->l + len;
219 			len += fread(p, 1, BSZ - len, fp);
220 			if (ferror(fp)) {
221 				ierr(fn);
222 				return;
223 			}
224 		}
225 
226 		tl->len = len;
227 	}
228 
229 	if (enomem) {
230 		warnx("warning: %jd bytes discarded", (intmax_t)enomem);
231 		rval = 1;
232 	}
233 
234 	/*
235 	 * Now print the lines in reverse order
236 	 * Outline:
237 	 *    Scan backward for "\n",
238 	 *    print forward to the end of the buffers
239 	 *    free any buffers that start after the "\n" just found
240 	 *    Loop
241 	 */
242 	tl = TAILQ_LAST(&head, bfhead);
243 	first = TAILQ_FIRST(&head);
244 	while (tl != NULL) {
245 		struct bfelem *temp;
246 
247 		for (p = tl->l + tl->len - 1, llen = 0; p >= tl->l;
248 		    --p, ++llen) {
249 			int start = (tl == first && p == tl->l);
250 
251 			if ((*p == '\n') || start) {
252 				struct bfelem *tr;
253 
254 				if (llen && start && *p != '\n')
255 					WR(p, llen + 1);
256 				else if (llen) {
257 					WR(p + 1, llen);
258 					if (start && *p == '\n')
259 						WR(p, 1);
260 				}
261 				tr = TAILQ_NEXT(tl, entries);
262 				llen = 0;
263 				if (tr != NULL) {
264 					TAILQ_FOREACH_FROM_SAFE(tr, &head,
265 					    entries, temp) {
266 						if (tr->len)
267 							WR(&tr->l, tr->len);
268 						TAILQ_REMOVE(&head, tr,
269 						    entries);
270 						free(tr);
271 					}
272 				}
273 			}
274 		}
275 		tl->len = llen;
276 		tl = TAILQ_PREV(tl, bfhead, entries);
277 	}
278 	TAILQ_REMOVE(&head, first, entries);
279 	free(first);
280 }
281