xref: /freebsd/usr.bin/tail/reverse.c (revision 154eb44539008299fc35db9302b2575d098e347f)
1 /*-
2  * Copyright (c) 1991, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * Edward Sze-Tyan Wang.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. All advertising materials mentioning features or use of this software
17  *    must display the following acknowledgement:
18  *	This product includes software developed by the University of
19  *	California, Berkeley and its contributors.
20  * 4. Neither the name of the University nor the names of its contributors
21  *    may be used to endorse or promote products derived from this software
22  *    without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  */
36 
37 #if 0
38 #ifndef lint
39 static char sccsid[] = "@(#)reverse.c	8.1 (Berkeley) 6/6/93";
40 #endif /* not lint */
41 #endif
42 
43 #include <sys/cdefs.h>
44 __FBSDID("$FreeBSD$");
45 
46 #include <sys/param.h>
47 #include <sys/stat.h>
48 #include <sys/mman.h>
49 
50 #include <err.h>
51 #include <errno.h>
52 #include <limits.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 *);
61 static void r_reg(FILE *, 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, 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, style, off, sbp);
89 	else
90 		switch(style) {
91 		case FBYTES:
92 		case RBYTES:
93 			bytes(fp, off);
94 			break;
95 		case FLINES:
96 		case RLINES:
97 			lines(fp, off);
98 			break;
99 		case REVERSE:
100 			r_buf(fp);
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, 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 
124 	/*
125 	 * Last char is special, ignore whether newline or not. Note that
126 	 * size == 0 is dealt with above, and size == 1 sets curoff to -1.
127 	 */
128 	curoff = size - 2;
129 	lineend = size;
130 	while (curoff >= 0) {
131 		if (curoff < map.mapoff || curoff >= map.mapoff + map.maplen) {
132 			if (maparound(&map, curoff) != 0) {
133 				ierr();
134 				return;
135 			}
136 		}
137 		for (i = curoff - map.mapoff; i >= 0; i--) {
138 			if (style == RBYTES && --off == 0)
139 				break;
140 			if (map.start[i] == '\n')
141 				break;
142 		}
143 		/* `i' is either the map offset of a '\n', or -1. */
144 		curoff = map.mapoff + i;
145 		if (i < 0)
146 			continue;
147 
148 		/* Print the line and update offsets. */
149 		if (mapprint(&map, curoff + 1, lineend - curoff - 1) != 0) {
150 			ierr();
151 			return;
152 		}
153 		lineend = curoff + 1;
154 		curoff--;
155 
156 		if (style == RLINES)
157 			off--;
158 
159 		if (off == 0 && style != REVERSE) {
160 			/* Avoid printing anything below. */
161 			curoff = 0;
162 			break;
163 		}
164 	}
165 	if (curoff < 0 && mapprint(&map, 0, lineend) != 0) {
166 		ierr();
167 		return;
168 	}
169 	if (map.start != NULL && munmap(map.start, map.maplen))
170 		ierr();
171 }
172 
173 typedef struct bf {
174 	struct bf *next;
175 	struct bf *prev;
176 	int len;
177 	char *l;
178 } BF;
179 
180 /*
181  * r_buf -- display a non-regular file in reverse order by line.
182  *
183  * This is the function that saves the entire input, storing the data in a
184  * doubly linked list of buffers and then displays them in reverse order.
185  * It has the usual nastiness of trying to find the newlines, as there's no
186  * guarantee that a newline occurs anywhere in the file, let alone in any
187  * particular buffer.  If we run out of memory, input is discarded (and the
188  * user warned).
189  */
190 static void
191 r_buf(FILE *fp)
192 {
193 	BF *mark, *tl, *tr;
194 	int ch, len, llen;
195 	char *p;
196 	off_t enomem;
197 
198 #define	BSZ	(128 * 1024)
199 	for (mark = NULL, enomem = 0;;) {
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 		if (enomem || (tl = malloc(sizeof(BF))) == NULL ||
206 		    (tl->l = malloc(BSZ)) == NULL) {
207 			if (!mark)
208 				err(1, "malloc");
209 			tl = enomem ? tl->next : mark;
210 			enomem += tl->len;
211 		} else if (mark) {
212 			tl->next = mark;
213 			tl->prev = mark->prev;
214 			mark->prev->next = tl;
215 			mark->prev = tl;
216 		} else {
217 			mark = tl;
218 			mark->next = mark->prev = mark;
219 		}
220 
221 		/* Fill the block with input data. */
222 		for (p = tl->l, len = 0;
223 		    len < BSZ && (ch = getc(fp)) != EOF; ++len)
224 			*p++ = ch;
225 
226 		if (ferror(fp)) {
227 			ierr();
228 			return;
229 		}
230 
231 		/*
232 		 * If no input data for this block and we tossed some data,
233 		 * recover it.
234 		 */
235 		if (!len) {
236 			if (enomem)
237 				enomem -= tl->len;
238 			tl = tl->prev;
239 			break;
240 		}
241 
242 		tl->len = len;
243 		if (ch == EOF)
244 			break;
245 	}
246 
247 	if (enomem) {
248 		warnx("warning: %qd bytes discarded", enomem);
249 		rval = 1;
250 	}
251 
252 	/*
253 	 * Step through the blocks in the reverse order read.  The last char
254 	 * is special, ignore whether newline or not.
255 	 */
256 	for (mark = tl;;) {
257 		for (p = tl->l + (len = tl->len) - 1, llen = 0; len--;
258 		    --p, ++llen)
259 			if (*p == '\n') {
260 				if (llen) {
261 					WR(p + 1, llen);
262 					llen = 0;
263 				}
264 				if (tl == mark)
265 					continue;
266 				for (tr = tl->next; tr->len; tr = tr->next) {
267 					WR(tr->l, tr->len);
268 					tr->len = 0;
269 					if (tr == mark)
270 						break;
271 				}
272 			}
273 		tl->len = llen;
274 		if ((tl = tl->prev) == mark)
275 			break;
276 	}
277 	tl = tl->next;
278 	if (tl->len) {
279 		WR(tl->l, tl->len);
280 		tl->len = 0;
281 	}
282 	while ((tl = tl->next)->len) {
283 		WR(tl->l, tl->len);
284 		tl->len = 0;
285 	}
286 }
287