GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: usr.bin/sed/main.c Lines: 152 222 68.5 %
Date: 2016-12-06 Branches: 82 172 47.7 %

Line Branch Exec Source
1
/*	$OpenBSD: main.c,v 1.33 2016/07/14 08:31:18 semarie Exp $	*/
2
3
/*-
4
 * Copyright (c) 1992 Diomidis Spinellis.
5
 * Copyright (c) 1992, 1993
6
 *	The Regents of the University of California.  All rights reserved.
7
 *
8
 * This code is derived from software contributed to Berkeley by
9
 * Diomidis Spinellis of Imperial College, University of London.
10
 *
11
 * Redistribution and use in source and binary forms, with or without
12
 * modification, are permitted provided that the following conditions
13
 * are met:
14
 * 1. Redistributions of source code must retain the above copyright
15
 *    notice, this list of conditions and the following disclaimer.
16
 * 2. Redistributions in binary form must reproduce the above copyright
17
 *    notice, this list of conditions and the following disclaimer in the
18
 *    documentation and/or other materials provided with the distribution.
19
 * 3. Neither the name of the University nor the names of its contributors
20
 *    may be used to endorse or promote products derived from this software
21
 *    without specific prior written permission.
22
 *
23
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33
 * SUCH DAMAGE.
34
 */
35
36
#include <sys/types.h>
37
#include <sys/ioctl.h>
38
#include <sys/stat.h>
39
40
#include <ctype.h>
41
#include <errno.h>
42
#include <fcntl.h>
43
#include <limits.h>
44
#include <regex.h>
45
#include <stddef.h>
46
#include <stdio.h>
47
#include <stdlib.h>
48
#include <string.h>
49
#include <unistd.h>
50
#include <libgen.h>
51
52
#include "defs.h"
53
#include "extern.h"
54
55
/*
56
 * Linked list of units (strings and files) to be compiled
57
 */
58
struct s_compunit {
59
	struct s_compunit *next;
60
	enum e_cut {CU_FILE, CU_STRING} type;
61
	char *s;			/* Pointer to string or fname */
62
};
63
64
/*
65
 * Linked list pointer to compilation units and pointer to current
66
 * next pointer.
67
 */
68
static struct s_compunit *script, **cu_nextp = &script;
69
70
/*
71
 * Linked list of files to be processed
72
 */
73
struct s_flist {
74
	char *fname;
75
	struct s_flist *next;
76
};
77
78
/*
79
 * Linked list pointer to files and pointer to current
80
 * next pointer.
81
 */
82
static struct s_flist *files, **fl_nextp = &files;
83
84
FILE *infile;			/* Current input file */
85
FILE *outfile;			/* Current output file */
86
87
int Eflag, aflag, eflag, nflag;
88
static int rval;	/* Exit status */
89
90
/*
91
 * Current file and line number; line numbers restart across compilation
92
 * units, but span across input files.  The latter is optional if editing
93
 * in place.
94
 */
95
const char *fname;		/* File name. */
96
const char *outfname;		/* Output file name */
97
static char oldfname[PATH_MAX];	/* Old file name (for in-place editing) */
98
static char tmpfname[PATH_MAX];	/* Temporary file name (for in-place editing) */
99
char *inplace;			/* Inplace edit file extension */
100
u_long linenum;
101
102
static void add_compunit(enum e_cut, char *);
103
static void add_file(char *);
104
static int next_files_have_lines(void);
105
106
int termwidth;
107
108
int
109
main(int argc, char *argv[])
110
751
{
111
	struct winsize win;
112
	int c, fflag;
113
	char *p;
114
115
751
	fflag = 0;
116
751
	inplace = NULL;
117
1842
	while ((c = getopt(argc, argv, "Eae:f:i::nru")) != -1)
118


340
		switch (c) {
119
		case 'E':
120
		case 'r':
121
			Eflag = 1;
122
			break;
123
		case 'a':
124
			aflag = 1;
125
			break;
126
		case 'e':
127
118
			eflag = 1;
128
118
			add_compunit(CU_STRING, optarg);
129
118
			break;
130
		case 'f':
131
113
			fflag = 1;
132
113
			add_compunit(CU_FILE, optarg);
133
113
			break;
134
		case 'i':
135
			inplace = optarg ? optarg : "";
136
			break;
137
		case 'n':
138
109
			nflag = 1;
139
109
			break;
140
		case 'u':
141
			setvbuf(stdout, NULL, _IOLBF, 0);
142
			break;
143
		default:
144
		case '?':
145
			(void)fprintf(stderr,
146
			    "usage: sed [-aEnru] [-i[extension]] command [file ...]\n"
147
			    "       sed [-aEnru] [-e command] [-f command_file] [-i[extension]] [file ...]\n");
148
			exit(1);
149
		}
150
751
	argc -= optind;
151
751
	argv += optind;
152
153
751
	termwidth = 0;
154
751
	if ((p = getenv("COLUMNS")) != NULL)
155
		termwidth = strtonum(p, 0, INT_MAX, NULL);
156

751
	if (termwidth == 0 && ioctl(STDOUT_FILENO, TIOCGWINSZ, &win) == 0 &&
157
	    win.ws_col > 0)
158
		termwidth = win.ws_col;
159
751
	if (termwidth == 0)
160
751
		termwidth = 80;
161
162
751
	if (inplace != NULL) {
163
		if (pledge("stdio rpath wpath cpath fattr chown", NULL) == -1)
164
			error(FATAL, "pledge: %s", strerror(errno));
165
	} else {
166
751
		if (pledge("stdio rpath wpath cpath", NULL) == -1)
167
			error(FATAL, "pledge: %s", strerror(errno));
168
	}
169
170
	/* First usage case; script is the first arg */
171

751
	if (!eflag && !fflag && *argv) {
172
627
		add_compunit(CU_STRING, *argv);
173
627
		argv++;
174
	}
175
176
751
	compile();
177
178
	/* Continue with first and start second usage */
179
751
	if (*argv)
180
238
		for (; *argv; argv++)
181
238
			add_file(*argv);
182
	else
183
513
		add_file(NULL);
184
751
	process();
185
724
	cfclose(prog, NULL);
186
724
	if (fclose(stdout))
187
		error(FATAL, "stdout: %s", strerror(errno));
188
724
	exit (rval);
189
}
190
191
/*
192
 * Like fgets, but go through the chain of compilation units chaining them
193
 * together.  Empty strings and files are ignored.
194
 */
195
char *
196
cu_fgets(char **outbuf, size_t *outsize)
197
12556
{
198
	static enum {ST_EOF, ST_FILE, ST_STRING} state = ST_EOF;
199
	static FILE *f;		/* Current open file */
200
	static char *s;		/* Current pointer inside string */
201
	static char string_ident[30];
202
	size_t len;
203
	char *p;
204
205
12556
	if (*outbuf == NULL)
206
760
		*outsize = 0;
207
208
13527
again:
209

13527
	switch (state) {
210
	case ST_EOF:
211
1609
		if (script == NULL)
212
751
			return (NULL);
213
858
		linenum = 0;
214
858
		switch (script->type) {
215
		case CU_FILE:
216
113
			if ((f = fopen(script->s, "r")) == NULL)
217
				error(FATAL,
218
				    "%s: %s", script->s, strerror(errno));
219
113
			fname = script->s;
220
113
			state = ST_FILE;
221
113
			goto again;
222
		case CU_STRING:
223
745
			if ((snprintf(string_ident,
224
			    sizeof(string_ident), "\"%s\"", script->s)) >=
225
			    sizeof(string_ident))
226
365
				strlcpy(string_ident +
227
				    sizeof(string_ident) - 6, " ...\"", 5);
228
745
			fname = string_ident;
229
745
			s = script->s;
230
745
			state = ST_STRING;
231
745
			goto again;
232
		}
233
	case ST_FILE:
234
9723
		if ((p = fgetln(f, &len)) != NULL) {
235
9610
			linenum++;
236
9610
			if (len >= *outsize) {
237
113
				free(*outbuf);
238
113
				*outsize = ROUNDLEN(len + 1);
239
113
				*outbuf = xmalloc(*outsize);
240
			}
241
9610
			memcpy(*outbuf, p, len);
242
9610
			(*outbuf)[len] = '\0';
243

9610
			if (linenum == 1 && p[0] == '#' && p[1] == 'n')
244
				nflag = 1;
245
9610
			return (*outbuf);
246
		}
247
113
		script = script->next;
248
113
		(void)fclose(f);
249
113
		state = ST_EOF;
250
113
		goto again;
251
	case ST_STRING:
252

2195
		if (linenum == 0 && s[0] == '#' && s[1] == 'n')
253
			nflag = 1;
254
2195
		p = *outbuf;
255
2195
		len = *outsize;
256
		for (;;) {
257
61190
			if (len <= 1) {
258
647
				*outbuf = xrealloc(*outbuf,
259
				    *outsize + _POSIX2_LINE_MAX);
260
647
				p = *outbuf + *outsize - len;
261
647
				len += _POSIX2_LINE_MAX;
262
647
				*outsize += _POSIX2_LINE_MAX;
263
			}
264
61190
			switch (*s) {
265
			case '\0':
266
745
				state = ST_EOF;
267
745
				if (s == script->s) {
268
					script = script->next;
269
					goto again;
270
				} else {
271
745
					script = script->next;
272
745
					*p = '\0';
273
745
					linenum++;
274
745
					return (*outbuf);
275
				}
276
			case '\n':
277
1450
				*p++ = '\n';
278
1450
				*p = '\0';
279
1450
				s++;
280
1450
				linenum++;
281
1450
				return (*outbuf);
282
			default:
283
58995
				*p++ = *s++;
284
58995
				len--;
285
			}
286
58995
		}
287
	}
288
	/* NOTREACHED */
289
}
290
291
/*
292
 * Like fgets, but go through the list of files chaining them together.
293
 * Set len to the length of the line.
294
 */
295
int
296
mf_fgets(SPACE *sp, enum e_spflag spflag)
297
101297
{
298
	struct stat sb;
299
	size_t len;
300
	char *p;
301
	int c, fd;
302
	static int firstfile;
303
304
101297
	if (infile == NULL) {
305
		/* stdin? */
306
751
		if (files->fname == NULL) {
307
513
			if (inplace != NULL)
308
				error(FATAL, "-i may not be used with stdin");
309
513
			infile = stdin;
310
513
			fname = "stdin";
311
513
			outfile = stdout;
312
513
			outfname = "stdout";
313
		}
314
315
751
		firstfile = 1;
316
	}
317
318
	for (;;) {
319


101535
		if (infile != NULL && (c = getc(infile)) != EOF) {
320
100573
			(void)ungetc(c, infile);
321
			break;
322
		}
323
		/* If we are here then either eof or no files are open yet */
324
962
		if (infile == stdin) {
325
507
			sp->len = 0;
326
507
			return (0);
327
		}
328
455
		if (infile != NULL) {
329
217
			fclose(infile);
330
217
			if (*oldfname != '\0') {
331
				if (rename(fname, oldfname) != 0) {
332
					error(WARNING, "rename()");
333
					unlink(tmpfname);
334
					exit(1);
335
				}
336
				*oldfname = '\0';
337
			}
338
217
			if (*tmpfname != '\0') {
339
				if (outfile != NULL && outfile != stdout)
340
					fclose(outfile);
341
				outfile = NULL;
342
				rename(tmpfname, fname);
343
				*tmpfname = '\0';
344
			}
345
217
			outfname = NULL;
346
		}
347
455
		if (firstfile == 0)
348
217
			files = files->next;
349
		else
350
238
			firstfile = 0;
351
455
		if (files == NULL) {
352
217
			sp->len = 0;
353
217
			return (0);
354
		}
355
238
		fname = files->fname;
356
238
		if (inplace != NULL) {
357
			if (lstat(fname, &sb) != 0)
358
				error(FATAL, "%s: %s", fname,
359
				    strerror(errno ? errno : EIO));
360
			if (!S_ISREG(sb.st_mode))
361
				error(FATAL, "%s: %s %s", fname,
362
				    "in-place editing only",
363
				    "works for regular files");
364
			if (*inplace != '\0') {
365
				strlcpy(oldfname, fname,
366
				    sizeof(oldfname));
367
				len = strlcat(oldfname, inplace,
368
				    sizeof(oldfname));
369
				if (len > sizeof(oldfname))
370
					error(FATAL, "%s: name too long", fname);
371
			}
372
			len = snprintf(tmpfname, sizeof(tmpfname), "%s/sedXXXXXXXXXX",
373
			    dirname(fname));
374
			if (len >= sizeof(tmpfname))
375
				error(FATAL, "%s: name too long", fname);
376
			if ((fd = mkstemp(tmpfname)) == -1)
377
				error(FATAL, "%s: %s", fname, strerror(errno));
378
			if ((outfile = fdopen(fd, "w")) == NULL) {
379
				unlink(tmpfname);
380
				error(FATAL, "%s", fname);
381
			}
382
			fchown(fileno(outfile), sb.st_uid, sb.st_gid);
383
			fchmod(fileno(outfile), sb.st_mode & ALLPERMS);
384
			outfname = tmpfname;
385
			linenum = 0;
386
			resetranges();
387
		} else {
388
238
			outfile = stdout;
389
238
			outfname = "stdout";
390
		}
391
238
		if ((infile = fopen(fname, "r")) == NULL) {
392
			error(WARNING, "%s", strerror(errno));
393
			rval = 1;
394
			continue;
395
		}
396
	}
397
398
	/*
399
	 * We are here only when infile is open and we still have something
400
	 * to read from it.
401
	 *
402
	 * Use fgetln so that we can handle essentially infinite input data.
403
	 * Can't use the pointer into the stdio buffer as the process space
404
	 * because the ungetc() can cause it to move.
405
	 */
406
100573
	p = fgetln(infile, &len);
407

201146
	if (ferror(infile))
408
		error(FATAL, "%s: %s", fname, strerror(errno ? errno : EIO));
409

201138
	if (len != 0 && p[len - 1] == '\n') {
410
100565
		sp->append_newline = 1;
411
100565
		len--;
412
8
	} else if (!lastline()) {
413
		sp->append_newline = 1;
414
	} else {
415
8
		sp->append_newline = 0;
416
	}
417
100573
	cspace(sp, p, len, spflag);
418
419
100573
	linenum++;
420
421
100573
	return (1);
422
}
423
424
/*
425
 * Add a compilation unit to the linked list
426
 */
427
static void
428
add_compunit(enum e_cut type, char *s)
429
858
{
430
	struct s_compunit *cu;
431
432
858
	cu = xmalloc(sizeof(struct s_compunit));
433
858
	cu->type = type;
434
858
	cu->s = s;
435
858
	cu->next = NULL;
436
858
	*cu_nextp = cu;
437
858
	cu_nextp = &cu->next;
438
858
}
439
440
/*
441
 * Add a file to the linked list
442
 */
443
static void
444
add_file(char *s)
445
751
{
446
	struct s_flist *fp;
447
448
751
	fp = xmalloc(sizeof(struct s_flist));
449
751
	fp->next = NULL;
450
751
	*fl_nextp = fp;
451
751
	fp->fname = s;
452
751
	fl_nextp = &fp->next;
453
751
}
454
455
456
static int
457
next_files_have_lines()
458
8
{
459
	struct s_flist *file;
460
	FILE *file_fd;
461
	int ch;
462
463
8
	file = files;
464
16
	while ((file = file->next) != NULL) {
465
		if ((file_fd = fopen(file->fname, "r")) == NULL)
466
			continue;
467
468
		if ((ch = getc(file_fd)) != EOF) {
469
			/*
470
			 * This next file has content, therefore current
471
			 * file doesn't contains the last line.
472
			 */
473
			ungetc(ch, file_fd);
474
			fclose(file_fd);
475
			return (1);
476
		}
477
		fclose(file_fd);
478
	}
479
8
	return (0);
480
}
481
482
int
483
lastline(void)
484
8
{
485
	int ch;
486
487

8
	if (feof(infile)) {
488

8
		return !(
489
		    (inplace == NULL) &&
490
		    next_files_have_lines());
491
	}
492
	if ((ch = getc(infile)) == EOF) {
493
		return !(
494
		    (inplace == NULL) &&
495
		    next_files_have_lines());
496
	}
497
	ungetc(ch, infile);
498
	return (0);
499
}