xref: /freebsd/usr.bin/tail/reverse.c (revision 5bf5ca772c6de2d53344a78cf461447cc322ccea)
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 #if 0
36 #ifndef lint
37 static char sccsid[] = "@(#)reverse.c	8.1 (Berkeley) 6/6/93";
38 #endif /* not lint */
39 #endif
40 
41 #include <sys/cdefs.h>
42 __FBSDID("$FreeBSD$");
43 
44 #include <sys/param.h>
45 #include <sys/queue.h>
46 #include <sys/stat.h>
47 #include <sys/mman.h>
48 
49 #include <err.h>
50 #include <errno.h>
51 #include <limits.h>
52 #include <stdint.h>
53 #include <stdio.h>
54 #include <stdlib.h>
55 #include <string.h>
56 #include <unistd.h>
57 
58 #include "extern.h"
59 
60 static void r_buf(FILE *, const char *);
61 static void r_reg(FILE *, const char *, enum STYLE, off_t, struct stat *);
62 
63 /*
64  * reverse -- display input in reverse order by line.
65  *
66  * There are six separate cases for this -- regular and non-regular
67  * files by bytes, lines or the whole file.
68  *
69  * BYTES	display N bytes
70  *	REG	mmap the file and display the lines
71  *	NOREG	cyclically read characters into a wrap-around buffer
72  *
73  * LINES	display N lines
74  *	REG	mmap the file and display the lines
75  *	NOREG	cyclically read lines into a wrap-around array of buffers
76  *
77  * FILE		display the entire file
78  *	REG	mmap the file and display the lines
79  *	NOREG	cyclically read input into a linked list of buffers
80  */
81 void
82 reverse(FILE *fp, const char *fn, enum STYLE style, off_t off, struct stat *sbp)
83 {
84 	if (style != REVERSE && off == 0)
85 		return;
86 
87 	if (S_ISREG(sbp->st_mode))
88 		r_reg(fp, fn, style, off, sbp);
89 	else
90 		switch(style) {
91 		case FBYTES:
92 		case RBYTES:
93 			bytes(fp, fn, off);
94 			break;
95 		case FLINES:
96 		case RLINES:
97 			lines(fp, fn, off);
98 			break;
99 		case REVERSE:
100 			r_buf(fp, fn);
101 			break;
102 		default:
103 			break;
104 		}
105 }
106 
107 /*
108  * r_reg -- display a regular file in reverse order by line.
109  */
110 static void
111 r_reg(FILE *fp, const char *fn, enum STYLE style, off_t off, struct stat *sbp)
112 {
113 	struct mapinfo map;
114 	off_t curoff, size, lineend;
115 	int i;
116 
117 	if (!(size = sbp->st_size))
118 		return;
119 
120 	map.start = NULL;
121 	map.mapoff = map.maxoff = size;
122 	map.fd = fileno(fp);
123 	map.maplen = 0;
124 
125 	/*
126 	 * Last char is special, ignore whether newline or not. Note that
127 	 * size == 0 is dealt with above, and size == 1 sets curoff to -1.
128 	 */
129 	curoff = size - 2;
130 	lineend = size;
131 	while (curoff >= 0) {
132 		if (curoff < map.mapoff ||
133 		    curoff >= map.mapoff + (off_t)map.maplen) {
134 			if (maparound(&map, curoff) != 0) {
135 				ierr(fn);
136 				return;
137 			}
138 		}
139 		for (i = curoff - map.mapoff; i >= 0; i--) {
140 			if (style == RBYTES && --off == 0)
141 				break;
142 			if (map.start[i] == '\n')
143 				break;
144 		}
145 		/* `i' is either the map offset of a '\n', or -1. */
146 		curoff = map.mapoff + i;
147 		if (i < 0)
148 			continue;
149 
150 		/* Print the line and update offsets. */
151 		if (mapprint(&map, curoff + 1, lineend - curoff - 1) != 0) {
152 			ierr(fn);
153 			return;
154 		}
155 		lineend = curoff + 1;
156 		curoff--;
157 
158 		if (style == RLINES)
159 			off--;
160 
161 		if (off == 0 && style != REVERSE) {
162 			/* Avoid printing anything below. */
163 			curoff = 0;
164 			break;
165 		}
166 	}
167 	if (curoff < 0 && mapprint(&map, 0, lineend) != 0) {
168 		ierr(fn);
169 		return;
170 	}
171 	if (map.start != NULL && munmap(map.start, map.maplen))
172 		ierr(fn);
173 }
174 
175 #define BSZ	(128 * 1024)
176 typedef struct bfelem {
177 	TAILQ_ENTRY(bfelem) entries;
178 	size_t len;
179 	char l[BSZ];
180 } bfelem_t;
181 
182 /*
183  * r_buf -- display a non-regular file in reverse order by line.
184  *
185  * This is the function that saves the entire input, storing the data in a
186  * doubly linked list of buffers and then displays them in reverse order.
187  * It has the usual nastiness of trying to find the newlines, as there's no
188  * guarantee that a newline occurs anywhere in the file, let alone in any
189  * particular buffer.  If we run out of memory, input is discarded (and the
190  * user warned).
191  */
192 static void
193 r_buf(FILE *fp, const char *fn)
194 {
195 	struct bfelem *tl, *first = NULL;
196 	size_t llen;
197 	char *p;
198 	off_t enomem = 0;
199 	TAILQ_HEAD(bfhead, bfelem) head;
200 
201 	TAILQ_INIT(&head);
202 
203 	while (!feof(fp)) {
204 		size_t len;
205 
206 		/*
207 		 * Allocate a new block and link it into place in a doubly
208 		 * linked list.  If out of memory, toss the LRU block and
209 		 * keep going.
210 		 */
211 		while ((tl = malloc(sizeof(bfelem_t))) == NULL) {
212 			first = TAILQ_FIRST(&head);
213 			if (TAILQ_EMPTY(&head))
214 				err(1, "malloc");
215 			enomem += first->len;
216 			TAILQ_REMOVE(&head, first, entries);
217 			free(first);
218 		}
219 		TAILQ_INSERT_TAIL(&head, tl, entries);
220 
221 		/* Fill the block with input data. */
222 		len = 0;
223 		while ((!feof(fp)) && len < BSZ) {
224 			p = tl->l + len;
225 			len += fread(p, 1, BSZ - len, fp);
226 			if (ferror(fp)) {
227 				ierr(fn);
228 				return;
229 			}
230 		}
231 
232 		tl->len = len;
233 	}
234 
235 	if (enomem) {
236 		warnx("warning: %jd bytes discarded", (intmax_t)enomem);
237 		rval = 1;
238 	}
239 
240 	/*
241 	 * Now print the lines in reverse order
242 	 * Outline:
243 	 *    Scan backward for "\n",
244 	 *    print forward to the end of the buffers
245 	 *    free any buffers that start after the "\n" just found
246 	 *    Loop
247 	 */
248 	tl = TAILQ_LAST(&head, bfhead);
249 	first = TAILQ_FIRST(&head);
250 	while (tl != NULL) {
251 		struct bfelem *temp;
252 
253 		for (p = tl->l + tl->len - 1, llen = 0; p >= tl->l;
254 		    --p, ++llen) {
255 			int start = (tl == first && p == tl->l);
256 
257 			if ((*p == '\n') || start) {
258 				struct bfelem *tr;
259 
260 				if (llen && start && *p != '\n')
261 					WR(p, llen + 1);
262 				else if (llen) {
263 					WR(p + 1, llen);
264 					if (start && *p == '\n')
265 						WR(p, 1);
266 				}
267 				tr = TAILQ_NEXT(tl, entries);
268 				llen = 0;
269 				if (tr != NULL) {
270 					TAILQ_FOREACH_FROM_SAFE(tr, &head,
271 					    entries, temp) {
272 						if (tr->len)
273 							WR(&tr->l, tr->len);
274 						TAILQ_REMOVE(&head, tr,
275 						    entries);
276 						free(tr);
277 					}
278 				}
279 			}
280 		}
281 		tl->len = llen;
282 		tl = TAILQ_PREV(tl, bfhead, entries);
283 	}
284 	TAILQ_REMOVE(&head, first, entries);
285 	free(first);
286 }
287