xref: /freebsd/usr.bin/sed/main.c (revision cccdaf507eee8fb34494b4624eb85bb951e323c8)
19b50d902SRodney W. Grimes /*-
28a16b7a1SPedro F. Giffuni  * SPDX-License-Identifier: BSD-3-Clause
38a16b7a1SPedro F. Giffuni  *
41a2a4fc8SPedro F. Giffuni  * Copyright (c) 2013 Johann 'Myrkraverk' Oskarsson.
59b50d902SRodney W. Grimes  * Copyright (c) 1992 Diomidis Spinellis.
69b50d902SRodney W. Grimes  * Copyright (c) 1992, 1993
79b50d902SRodney W. Grimes  *	The Regents of the University of California.  All rights reserved.
89b50d902SRodney W. Grimes  *
99b50d902SRodney W. Grimes  * This code is derived from software contributed to Berkeley by
109b50d902SRodney W. Grimes  * Diomidis Spinellis of Imperial College, University of London.
119b50d902SRodney W. Grimes  *
129b50d902SRodney W. Grimes  * Redistribution and use in source and binary forms, with or without
139b50d902SRodney W. Grimes  * modification, are permitted provided that the following conditions
149b50d902SRodney W. Grimes  * are met:
159b50d902SRodney W. Grimes  * 1. Redistributions of source code must retain the above copyright
169b50d902SRodney W. Grimes  *    notice, this list of conditions and the following disclaimer.
179b50d902SRodney W. Grimes  * 2. Redistributions in binary form must reproduce the above copyright
189b50d902SRodney W. Grimes  *    notice, this list of conditions and the following disclaimer in the
199b50d902SRodney W. Grimes  *    documentation and/or other materials provided with the distribution.
20fbbd9655SWarner Losh  * 3. Neither the name of the University nor the names of its contributors
219b50d902SRodney W. Grimes  *    may be used to endorse or promote products derived from this software
229b50d902SRodney W. Grimes  *    without specific prior written permission.
239b50d902SRodney W. Grimes  *
249b50d902SRodney W. Grimes  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
259b50d902SRodney W. Grimes  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
269b50d902SRodney W. Grimes  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
279b50d902SRodney W. Grimes  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
289b50d902SRodney W. Grimes  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
299b50d902SRodney W. Grimes  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
309b50d902SRodney W. Grimes  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
319b50d902SRodney W. Grimes  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
329b50d902SRodney W. Grimes  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
339b50d902SRodney W. Grimes  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
349b50d902SRodney W. Grimes  * SUCH DAMAGE.
359b50d902SRodney W. Grimes  */
369b50d902SRodney W. Grimes 
37e74bf75fSMark Murray #include <sys/cdefs.h>
38e74bf75fSMark Murray __FBSDID("$FreeBSD$");
39e74bf75fSMark Murray 
409b50d902SRodney W. Grimes #ifndef lint
4173a08bb2SPhilippe Charnier static const char copyright[] =
429b50d902SRodney W. Grimes "@(#) Copyright (c) 1992, 1993\n\
439b50d902SRodney W. Grimes 	The Regents of the University of California.  All rights reserved.\n";
44e74bf75fSMark Murray #endif
459b50d902SRodney W. Grimes 
469b50d902SRodney W. Grimes #ifndef lint
47e74bf75fSMark Murray static const char sccsid[] = "@(#)main.c	8.2 (Berkeley) 1/3/94";
4873a08bb2SPhilippe Charnier #endif
499b50d902SRodney W. Grimes 
508701af62SMaxim Sobolev #include <sys/types.h>
518701af62SMaxim Sobolev #include <sys/mman.h>
52839af0c1SJuli Mallett #include <sys/param.h>
53839af0c1SJuli Mallett #include <sys/stat.h>
549b50d902SRodney W. Grimes 
5573a08bb2SPhilippe Charnier #include <err.h>
569b50d902SRodney W. Grimes #include <errno.h>
57821df508SXin LI #include <fcntl.h>
58a3eb24c6SStefan Farfeleder #include <libgen.h>
5981a8648aSTim J. Robbins #include <limits.h>
60726aebe5SAndrey A. Chernov #include <locale.h>
619b50d902SRodney W. Grimes #include <regex.h>
62821df508SXin LI #include <stddef.h>
639b50d902SRodney W. Grimes #include <stdio.h>
649b50d902SRodney W. Grimes #include <stdlib.h>
659b50d902SRodney W. Grimes #include <string.h>
669b50d902SRodney W. Grimes #include <unistd.h>
679b50d902SRodney W. Grimes 
689b50d902SRodney W. Grimes #include "defs.h"
699b50d902SRodney W. Grimes #include "extern.h"
709b50d902SRodney W. Grimes 
719b50d902SRodney W. Grimes /*
729b50d902SRodney W. Grimes  * Linked list of units (strings and files) to be compiled
739b50d902SRodney W. Grimes  */
749b50d902SRodney W. Grimes struct s_compunit {
759b50d902SRodney W. Grimes 	struct s_compunit *next;
769b50d902SRodney W. Grimes 	enum e_cut {CU_FILE, CU_STRING} type;
77249a8a80SPedro F. Giffuni 	char *s;			/* Pointer to string or fname */
789b50d902SRodney W. Grimes };
799b50d902SRodney W. Grimes 
809b50d902SRodney W. Grimes /*
819b50d902SRodney W. Grimes  * Linked list pointer to compilation units and pointer to current
829b50d902SRodney W. Grimes  * next pointer.
839b50d902SRodney W. Grimes  */
849b50d902SRodney W. Grimes static struct s_compunit *script, **cu_nextp = &script;
859b50d902SRodney W. Grimes 
869b50d902SRodney W. Grimes /*
879b50d902SRodney W. Grimes  * Linked list of files to be processed
889b50d902SRodney W. Grimes  */
899b50d902SRodney W. Grimes struct s_flist {
90249a8a80SPedro F. Giffuni 	char *fname;
919b50d902SRodney W. Grimes 	struct s_flist *next;
929b50d902SRodney W. Grimes };
939b50d902SRodney W. Grimes 
949b50d902SRodney W. Grimes /*
959b50d902SRodney W. Grimes  * Linked list pointer to files and pointer to current
969b50d902SRodney W. Grimes  * next pointer.
979b50d902SRodney W. Grimes  */
989b50d902SRodney W. Grimes static struct s_flist *files, **fl_nextp = &files;
999b50d902SRodney W. Grimes 
100f54cda14SDag-Erling Smørgrav FILE *infile;			/* Current input file */
101f54cda14SDag-Erling Smørgrav FILE *outfile;			/* Current output file */
1028523e9a6STim J. Robbins 
1039b50d902SRodney W. Grimes int aflag, eflag, nflag;
104175de1e6SBrian Feldman int rflags = 0;
105b4805026SMark Johnston int quit = 0;
1063af4dcb2STim J. Robbins static int rval;		/* Exit status */
1079b50d902SRodney W. Grimes 
108f6703c9cSYaroslav Tykhiy static int ispan;		/* Whether inplace editing spans across files */
109f6703c9cSYaroslav Tykhiy 
1109b50d902SRodney W. Grimes /*
1119b50d902SRodney W. Grimes  * Current file and line number; line numbers restart across compilation
112f6703c9cSYaroslav Tykhiy  * units, but span across input files.  The latter is optional if editing
113f6703c9cSYaroslav Tykhiy  * in place.
1149b50d902SRodney W. Grimes  */
115e74bf75fSMark Murray const char *fname;		/* File name. */
116f54cda14SDag-Erling Smørgrav const char *outfname;		/* Output file name */
117f54cda14SDag-Erling Smørgrav static char oldfname[PATH_MAX];	/* Old file name (for in-place editing) */
118f54cda14SDag-Erling Smørgrav static char tmpfname[PATH_MAX];	/* Temporary file name (for in-place editing) */
119b4805026SMark Johnston const char *inplace;		/* Inplace edit file extension. */
1209b50d902SRodney W. Grimes u_long linenum;
1219b50d902SRodney W. Grimes 
122249a8a80SPedro F. Giffuni static void add_compunit(enum e_cut, char *);
123249a8a80SPedro F. Giffuni static void add_file(char *);
124*cccdaf50SAlfonso Gregory static void usage(void) __dead2;
1259b50d902SRodney W. Grimes 
1269b50d902SRodney W. Grimes int
127e6478125SDag-Erling Smørgrav main(int argc, char *argv[])
1289b50d902SRodney W. Grimes {
129f9ab72bbSMateusz Piotrowski 	int c, fflag, fflagstdin;
130249a8a80SPedro F. Giffuni 	char *temp_arg;
1319b50d902SRodney W. Grimes 
132726aebe5SAndrey A. Chernov 	(void) setlocale(LC_ALL, "");
133726aebe5SAndrey A. Chernov 
1349b50d902SRodney W. Grimes 	fflag = 0;
135f9ab72bbSMateusz Piotrowski 	fflagstdin = 0;
136839af0c1SJuli Mallett 	inplace = NULL;
137839af0c1SJuli Mallett 
138fc39ce9eSPedro F. Giffuni 	while ((c = getopt(argc, argv, "EI:ae:f:i:lnru")) != -1)
1399b50d902SRodney W. Grimes 		switch (c) {
140701d73b6SWarner Losh 		case 'r':		/* Gnu sed compat */
141175de1e6SBrian Feldman 		case 'E':
142175de1e6SBrian Feldman 			rflags = REG_EXTENDED;
143175de1e6SBrian Feldman 			break;
144f6703c9cSYaroslav Tykhiy 		case 'I':
145f6703c9cSYaroslav Tykhiy 			inplace = optarg;
146f6703c9cSYaroslav Tykhiy 			ispan = 1;	/* span across input files */
147f6703c9cSYaroslav Tykhiy 			break;
1489b50d902SRodney W. Grimes 		case 'a':
1499b50d902SRodney W. Grimes 			aflag = 1;
1509b50d902SRodney W. Grimes 			break;
1519b50d902SRodney W. Grimes 		case 'e':
1529b50d902SRodney W. Grimes 			eflag = 1;
153249a8a80SPedro F. Giffuni 			if ((temp_arg = malloc(strlen(optarg) + 2)) == NULL)
154249a8a80SPedro F. Giffuni 				err(1, "malloc");
155249a8a80SPedro F. Giffuni 			strcpy(temp_arg, optarg);
156249a8a80SPedro F. Giffuni 			strcat(temp_arg, "\n");
157637a1a74SEnji Cooper 			add_compunit(CU_STRING, temp_arg);
1589b50d902SRodney W. Grimes 			break;
1599b50d902SRodney W. Grimes 		case 'f':
1609b50d902SRodney W. Grimes 			fflag = 1;
161f9ab72bbSMateusz Piotrowski 			if (strcmp(optarg, "-") == 0)
162f9ab72bbSMateusz Piotrowski 				fflagstdin = 1;
1639b50d902SRodney W. Grimes 			add_compunit(CU_FILE, optarg);
1649b50d902SRodney W. Grimes 			break;
165839af0c1SJuli Mallett 		case 'i':
166839af0c1SJuli Mallett 			inplace = optarg;
167f6703c9cSYaroslav Tykhiy 			ispan = 0;	/* don't span across input files */
168839af0c1SJuli Mallett 			break;
1691ed86f6cSGleb Smirnoff 		case 'l':
17090d81f30SPedro F. Giffuni 			if(setvbuf(stdout, NULL, _IOLBF, 0) != 0)
17190d81f30SPedro F. Giffuni 				warnx("setting line buffered output failed");
1721ed86f6cSGleb Smirnoff 			break;
1739b50d902SRodney W. Grimes 		case 'n':
1749b50d902SRodney W. Grimes 			nflag = 1;
1759b50d902SRodney W. Grimes 			break;
176fc39ce9eSPedro F. Giffuni 		case 'u':
17790d81f30SPedro F. Giffuni 			if(setvbuf(stdout, NULL, _IONBF, 0) != 0)
178fc39ce9eSPedro F. Giffuni 				warnx("setting unbuffered output failed");
179fc39ce9eSPedro F. Giffuni 			break;
1809b50d902SRodney W. Grimes 		default:
1819b50d902SRodney W. Grimes 		case '?':
18273a08bb2SPhilippe Charnier 			usage();
1839b50d902SRodney W. Grimes 		}
1849b50d902SRodney W. Grimes 	argc -= optind;
1859b50d902SRodney W. Grimes 	argv += optind;
1869b50d902SRodney W. Grimes 
1879b50d902SRodney W. Grimes 	/* First usage case; script is the first arg */
1889b50d902SRodney W. Grimes 	if (!eflag && !fflag && *argv) {
1899b50d902SRodney W. Grimes 		add_compunit(CU_STRING, *argv);
1909b50d902SRodney W. Grimes 		argv++;
1919b50d902SRodney W. Grimes 	}
1929b50d902SRodney W. Grimes 
1939b50d902SRodney W. Grimes 	compile();
1949b50d902SRodney W. Grimes 
1959b50d902SRodney W. Grimes 	/* Continue with first and start second usage */
1969b50d902SRodney W. Grimes 	if (*argv)
1979b50d902SRodney W. Grimes 		for (; *argv; argv++)
1989b50d902SRodney W. Grimes 			add_file(*argv);
199f9ab72bbSMateusz Piotrowski 	else if (fflagstdin)
200f9ab72bbSMateusz Piotrowski 		exit(rval);
2019b50d902SRodney W. Grimes 	else
2029b50d902SRodney W. Grimes 		add_file(NULL);
2039b50d902SRodney W. Grimes 	process();
2049b50d902SRodney W. Grimes 	cfclose(prog, NULL);
2059b50d902SRodney W. Grimes 	if (fclose(stdout))
20673a08bb2SPhilippe Charnier 		err(1, "stdout");
2073af4dcb2STim J. Robbins 	exit(rval);
2089b50d902SRodney W. Grimes }
2099b50d902SRodney W. Grimes 
21073a08bb2SPhilippe Charnier static void
211e6478125SDag-Erling Smørgrav usage(void)
21273a08bb2SPhilippe Charnier {
213fc39ce9eSPedro F. Giffuni 	(void)fprintf(stderr,
214f2431000SPedro F. Giffuni 	    "usage: %s script [-Ealnru] [-i extension] [file ...]\n"
2159b788a2eSPedro F. Giffuni 	    "\t%s [-Ealnu] [-i extension] [-e script] ... [-f script_file]"
216fc39ce9eSPedro F. Giffuni 	    " ... [file ...]\n", getprogname(), getprogname());
21773a08bb2SPhilippe Charnier 	exit(1);
21873a08bb2SPhilippe Charnier }
21973a08bb2SPhilippe Charnier 
2209b50d902SRodney W. Grimes /*
2219b50d902SRodney W. Grimes  * Like fgets, but go through the chain of compilation units chaining them
2229b50d902SRodney W. Grimes  * together.  Empty strings and files are ignored.
2239b50d902SRodney W. Grimes  */
224249a8a80SPedro F. Giffuni char *
225249a8a80SPedro F. Giffuni cu_fgets(char *buf, int n, int *more)
2269b50d902SRodney W. Grimes {
2279b50d902SRodney W. Grimes 	static enum {ST_EOF, ST_FILE, ST_STRING} state = ST_EOF;
2289b50d902SRodney W. Grimes 	static FILE *f;		/* Current open file */
229249a8a80SPedro F. Giffuni 	static char *s;		/* Current pointer inside string */
230249a8a80SPedro F. Giffuni 	static char string_ident[30];
2319b50d902SRodney W. Grimes 	char *p;
2329b50d902SRodney W. Grimes 
2339b50d902SRodney W. Grimes again:
2349b50d902SRodney W. Grimes 	switch (state) {
2359b50d902SRodney W. Grimes 	case ST_EOF:
236c56690efSArchie Cobbs 		if (script == NULL) {
237c56690efSArchie Cobbs 			if (more != NULL)
238c56690efSArchie Cobbs 				*more = 0;
2399b50d902SRodney W. Grimes 			return (NULL);
240c56690efSArchie Cobbs 		}
2419b50d902SRodney W. Grimes 		linenum = 0;
2429b50d902SRodney W. Grimes 		switch (script->type) {
2439b50d902SRodney W. Grimes 		case CU_FILE:
244f9ab72bbSMateusz Piotrowski 			if (strcmp(script->s, "-") == 0) {
245f9ab72bbSMateusz Piotrowski 				f = stdin;
246f9ab72bbSMateusz Piotrowski 				fname = "stdin";
247f9ab72bbSMateusz Piotrowski 			} else {
2489b50d902SRodney W. Grimes 				if ((f = fopen(script->s, "r")) == NULL)
24973a08bb2SPhilippe Charnier 				        err(1, "%s", script->s);
2509b50d902SRodney W. Grimes 				fname = script->s;
251f9ab72bbSMateusz Piotrowski 			}
2529b50d902SRodney W. Grimes 			state = ST_FILE;
2539b50d902SRodney W. Grimes 			goto again;
2549b50d902SRodney W. Grimes 		case CU_STRING:
255d3e5e11cSDavid Malone 			if (((size_t)snprintf(string_ident,
2569b50d902SRodney W. Grimes 			    sizeof(string_ident), "\"%s\"", script->s)) >=
2579b50d902SRodney W. Grimes 			    sizeof(string_ident) - 1)
2589b50d902SRodney W. Grimes 				(void)strcpy(string_ident +
2599b50d902SRodney W. Grimes 				    sizeof(string_ident) - 6, " ...\"");
2609b50d902SRodney W. Grimes 			fname = string_ident;
2619b50d902SRodney W. Grimes 			s = script->s;
2629b50d902SRodney W. Grimes 			state = ST_STRING;
2639b50d902SRodney W. Grimes 			goto again;
26451a8f735SPedro F. Giffuni 		default:
26551a8f735SPedro F. Giffuni 			__unreachable();
2669b50d902SRodney W. Grimes 		}
2679b50d902SRodney W. Grimes 	case ST_FILE:
268249a8a80SPedro F. Giffuni 		if ((p = fgets(buf, n, f)) != NULL) {
2699b50d902SRodney W. Grimes 			linenum++;
270249a8a80SPedro F. Giffuni 			if (linenum == 1 && buf[0] == '#' && buf[1] == 'n')
2719b50d902SRodney W. Grimes 				nflag = 1;
272c56690efSArchie Cobbs 			if (more != NULL)
273c56690efSArchie Cobbs 				*more = !feof(f);
274249a8a80SPedro F. Giffuni 			return (p);
275249a8a80SPedro F. Giffuni 		}
2769b50d902SRodney W. Grimes 		script = script->next;
2779b50d902SRodney W. Grimes 		(void)fclose(f);
2789b50d902SRodney W. Grimes 		state = ST_EOF;
2799b50d902SRodney W. Grimes 		goto again;
2809b50d902SRodney W. Grimes 	case ST_STRING:
2819b50d902SRodney W. Grimes 		if (linenum == 0 && s[0] == '#' && s[1] == 'n')
2829b50d902SRodney W. Grimes 			nflag = 1;
283249a8a80SPedro F. Giffuni 		p = buf;
284b4932d18SPedro F. Giffuni 		for (;;) {
285249a8a80SPedro F. Giffuni 			if (n-- <= 1) {
286249a8a80SPedro F. Giffuni 				*p = '\0';
287249a8a80SPedro F. Giffuni 				linenum++;
288249a8a80SPedro F. Giffuni 				if (more != NULL)
289249a8a80SPedro F. Giffuni 					*more = 1;
290249a8a80SPedro F. Giffuni 				return (buf);
291249a8a80SPedro F. Giffuni 			}
2929b50d902SRodney W. Grimes 			switch (*s) {
2939b50d902SRodney W. Grimes 			case '\0':
2949b50d902SRodney W. Grimes 				state = ST_EOF;
295249a8a80SPedro F. Giffuni 				if (s == script->s) {
2969b50d902SRodney W. Grimes 					script = script->next;
297249a8a80SPedro F. Giffuni 					goto again;
298249a8a80SPedro F. Giffuni 				} else {
299249a8a80SPedro F. Giffuni 					script = script->next;
300249a8a80SPedro F. Giffuni 					*p = '\0';
301249a8a80SPedro F. Giffuni 					linenum++;
302249a8a80SPedro F. Giffuni 					if (more != NULL)
303249a8a80SPedro F. Giffuni 						*more = 0;
304249a8a80SPedro F. Giffuni 					return (buf);
305249a8a80SPedro F. Giffuni 				}
3069b50d902SRodney W. Grimes 			case '\n':
307249a8a80SPedro F. Giffuni 				*p++ = '\n';
308249a8a80SPedro F. Giffuni 				*p = '\0';
3099b50d902SRodney W. Grimes 				s++;
3109b50d902SRodney W. Grimes 				linenum++;
311c56690efSArchie Cobbs 				if (more != NULL)
312c56690efSArchie Cobbs 					*more = 0;
313249a8a80SPedro F. Giffuni 				return (buf);
3149b50d902SRodney W. Grimes 			default:
315249a8a80SPedro F. Giffuni 				*p++ = *s++;
3169b50d902SRodney W. Grimes 			}
3179b50d902SRodney W. Grimes 		}
3189b50d902SRodney W. Grimes 	}
3199b50d902SRodney W. Grimes 	/* NOTREACHED */
32073a08bb2SPhilippe Charnier 	return (NULL);
3219b50d902SRodney W. Grimes }
3229b50d902SRodney W. Grimes 
3239b50d902SRodney W. Grimes /*
3249b50d902SRodney W. Grimes  * Like fgets, but go through the list of files chaining them together.
3259b50d902SRodney W. Grimes  * Set len to the length of the line.
3269b50d902SRodney W. Grimes  */
3279b50d902SRodney W. Grimes int
328e6478125SDag-Erling Smørgrav mf_fgets(SPACE *sp, enum e_spflag spflag)
3299b50d902SRodney W. Grimes {
330f54cda14SDag-Erling Smørgrav 	struct stat sb;
3311a2a4fc8SPedro F. Giffuni 	ssize_t len;
3326718ba18SEd Schouten 	char *dirbuf, *basebuf;
3331a2a4fc8SPedro F. Giffuni 	static char *p = NULL;
3341a2a4fc8SPedro F. Giffuni 	static size_t plen = 0;
3355f4cf81eSWolfram Schneider 	int c;
3368701af62SMaxim Sobolev 	static int firstfile;
3379b50d902SRodney W. Grimes 
338f54cda14SDag-Erling Smørgrav 	if (infile == NULL) {
3398701af62SMaxim Sobolev 		/* stdin? */
3409b50d902SRodney W. Grimes 		if (files->fname == NULL) {
341839af0c1SJuli Mallett 			if (inplace != NULL)
342f6703c9cSYaroslav Tykhiy 				errx(1, "-I or -i may not be used with stdin");
343f54cda14SDag-Erling Smørgrav 			infile = stdin;
3449b50d902SRodney W. Grimes 			fname = "stdin";
345f54cda14SDag-Erling Smørgrav 			outfile = stdout;
346f54cda14SDag-Erling Smørgrav 			outfname = "stdout";
3478701af62SMaxim Sobolev 		}
3488701af62SMaxim Sobolev 		firstfile = 1;
3498701af62SMaxim Sobolev 	}
3508701af62SMaxim Sobolev 
3518701af62SMaxim Sobolev 	for (;;) {
352b4805026SMark Johnston 		if (infile != NULL && (c = getc(infile)) != EOF && !quit) {
353f54cda14SDag-Erling Smørgrav 			(void)ungetc(c, infile);
3548701af62SMaxim Sobolev 			break;
3558701af62SMaxim Sobolev 		}
3568701af62SMaxim Sobolev 		/* If we are here then either eof or no files are open yet */
357f54cda14SDag-Erling Smørgrav 		if (infile == stdin) {
358254fac85STim J. Robbins 			sp->len = 0;
3598701af62SMaxim Sobolev 			return (0);
3608701af62SMaxim Sobolev 		}
361f54cda14SDag-Erling Smørgrav 		if (infile != NULL) {
362f54cda14SDag-Erling Smørgrav 			fclose(infile);
3637bbdbe14SBrian Somers 			if (*oldfname != '\0') {
364919e14f0SJilles Tjoelker 				/* if there was a backup file, remove it */
365919e14f0SJilles Tjoelker 				unlink(oldfname);
366919e14f0SJilles Tjoelker 				/*
367919e14f0SJilles Tjoelker 				 * Backup the original.  Note that hard links
368919e14f0SJilles Tjoelker 				 * are not supported on all filesystems.
369919e14f0SJilles Tjoelker 				 */
370919e14f0SJilles Tjoelker 				if ((link(fname, oldfname) != 0) &&
371919e14f0SJilles Tjoelker 				   (rename(fname, oldfname) != 0)) {
372f54cda14SDag-Erling Smørgrav 					warn("rename()");
373919e14f0SJilles Tjoelker 					if (*tmpfname)
374f54cda14SDag-Erling Smørgrav 						unlink(tmpfname);
375f54cda14SDag-Erling Smørgrav 					exit(1);
3768701af62SMaxim Sobolev 				}
3777bbdbe14SBrian Somers 				*oldfname = '\0';
3787bbdbe14SBrian Somers 			}
3797bbdbe14SBrian Somers 			if (*tmpfname != '\0') {
3807bbdbe14SBrian Somers 				if (outfile != NULL && outfile != stdout)
381919e14f0SJilles Tjoelker 					if (fclose(outfile) != 0) {
382919e14f0SJilles Tjoelker 						warn("fclose()");
383919e14f0SJilles Tjoelker 						unlink(tmpfname);
384919e14f0SJilles Tjoelker 						exit(1);
385919e14f0SJilles Tjoelker 					}
3867bbdbe14SBrian Somers 				outfile = NULL;
387919e14f0SJilles Tjoelker 				if (rename(tmpfname, fname) != 0) {
388919e14f0SJilles Tjoelker 					/* this should not happen really! */
389919e14f0SJilles Tjoelker 					warn("rename()");
390919e14f0SJilles Tjoelker 					unlink(tmpfname);
391919e14f0SJilles Tjoelker 					exit(1);
392919e14f0SJilles Tjoelker 				}
3937bbdbe14SBrian Somers 				*tmpfname = '\0';
3947bbdbe14SBrian Somers 			}
395f54cda14SDag-Erling Smørgrav 			outfname = NULL;
396f54cda14SDag-Erling Smørgrav 		}
397f54cda14SDag-Erling Smørgrav 		if (firstfile == 0)
3988701af62SMaxim Sobolev 			files = files->next;
399f54cda14SDag-Erling Smørgrav 		else
4008701af62SMaxim Sobolev 			firstfile = 0;
4018701af62SMaxim Sobolev 		if (files == NULL) {
402254fac85STim J. Robbins 			sp->len = 0;
4038701af62SMaxim Sobolev 			return (0);
4048701af62SMaxim Sobolev 		}
4059b50d902SRodney W. Grimes 		fname = files->fname;
406f54cda14SDag-Erling Smørgrav 		if (inplace != NULL) {
407f54cda14SDag-Erling Smørgrav 			if (lstat(fname, &sb) != 0)
408f54cda14SDag-Erling Smørgrav 				err(1, "%s", fname);
4098e2106f0SXin LI 			if (!S_ISREG(sb.st_mode))
410f54cda14SDag-Erling Smørgrav 				errx(1, "%s: %s %s", fname,
411f54cda14SDag-Erling Smørgrav 				    "in-place editing only",
412f54cda14SDag-Erling Smørgrav 				    "works for regular files");
413f54cda14SDag-Erling Smørgrav 			if (*inplace != '\0') {
414f54cda14SDag-Erling Smørgrav 				strlcpy(oldfname, fname,
415f54cda14SDag-Erling Smørgrav 				    sizeof(oldfname));
416f54cda14SDag-Erling Smørgrav 				len = strlcat(oldfname, inplace,
417f54cda14SDag-Erling Smørgrav 				    sizeof(oldfname));
418249a8a80SPedro F. Giffuni 				if (len > (ssize_t)sizeof(oldfname))
419f54cda14SDag-Erling Smørgrav 					errx(1, "%s: name too long", fname);
420f54cda14SDag-Erling Smørgrav 			}
4216718ba18SEd Schouten 			if ((dirbuf = strdup(fname)) == NULL ||
4226718ba18SEd Schouten 			    (basebuf = strdup(fname)) == NULL)
4236718ba18SEd Schouten 				err(1, "strdup");
424f54cda14SDag-Erling Smørgrav 			len = snprintf(tmpfname, sizeof(tmpfname),
4256718ba18SEd Schouten 			    "%s/.!%ld!%s", dirname(dirbuf), (long)getpid(),
4266718ba18SEd Schouten 			    basename(basebuf));
4276718ba18SEd Schouten 			free(dirbuf);
4286718ba18SEd Schouten 			free(basebuf);
429249a8a80SPedro F. Giffuni 			if (len >= (ssize_t)sizeof(tmpfname))
430f54cda14SDag-Erling Smørgrav 				errx(1, "%s: name too long", fname);
431f54cda14SDag-Erling Smørgrav 			unlink(tmpfname);
432fc04dce0SPedro F. Giffuni 			if (outfile != NULL && outfile != stdout)
433fc04dce0SPedro F. Giffuni 				fclose(outfile);
43476c76d54SPedro F. Giffuni 			if ((outfile = fopen(tmpfname, "w")) == NULL)
43576c76d54SPedro F. Giffuni 				err(1, "%s", fname);
436f54cda14SDag-Erling Smørgrav 			fchown(fileno(outfile), sb.st_uid, sb.st_gid);
437f54cda14SDag-Erling Smørgrav 			fchmod(fileno(outfile), sb.st_mode & ALLPERMS);
438f54cda14SDag-Erling Smørgrav 			outfname = tmpfname;
439f6703c9cSYaroslav Tykhiy 			if (!ispan) {
440f6703c9cSYaroslav Tykhiy 				linenum = 0;
44126a5710cSYaroslav Tykhiy 				resetstate();
442f6703c9cSYaroslav Tykhiy 			}
443f54cda14SDag-Erling Smørgrav 		} else {
444f54cda14SDag-Erling Smørgrav 			outfile = stdout;
445f54cda14SDag-Erling Smørgrav 			outfname = "stdout";
446f54cda14SDag-Erling Smørgrav 		}
447f54cda14SDag-Erling Smørgrav 		if ((infile = fopen(fname, "r")) == NULL) {
4483af4dcb2STim J. Robbins 			warn("%s", fname);
4496689fb2bSTim J. Robbins 			rval = 1;
4503af4dcb2STim J. Robbins 			continue;
4513af4dcb2STim J. Robbins 		}
4529b50d902SRodney W. Grimes 	}
4539b50d902SRodney W. Grimes 	/*
454f54cda14SDag-Erling Smørgrav 	 * We are here only when infile is open and we still have something
4558523e9a6STim J. Robbins 	 * to read from it.
4568701af62SMaxim Sobolev 	 *
4571a2a4fc8SPedro F. Giffuni 	 * Use getline() so that we can handle essentially infinite input
4581a2a4fc8SPedro F. Giffuni 	 * data.  The p and plen are static so each invocation gives
4591a2a4fc8SPedro F. Giffuni 	 * getline() the same buffer which is expanded as needed.
4609b50d902SRodney W. Grimes 	 */
4611a2a4fc8SPedro F. Giffuni 	len = getline(&p, &plen, infile);
4621a2a4fc8SPedro F. Giffuni 	if (len == -1)
4631a2a4fc8SPedro F. Giffuni 		err(1, "%s", fname);
46496d68291SJean-Sébastien Pédron 	if (len != 0 && p[len - 1] == '\n') {
46596d68291SJean-Sébastien Pédron 		sp->append_newline = 1;
466ed92199dSTim J. Robbins 		len--;
46796d68291SJean-Sébastien Pédron 	} else if (!lastline()) {
46896d68291SJean-Sébastien Pédron 		sp->append_newline = 1;
46996d68291SJean-Sébastien Pédron 	} else {
47096d68291SJean-Sébastien Pédron 		sp->append_newline = 0;
47196d68291SJean-Sébastien Pédron 	}
4729b50d902SRodney W. Grimes 	cspace(sp, p, len, spflag);
4739b50d902SRodney W. Grimes 
4749b50d902SRodney W. Grimes 	linenum++;
4758701af62SMaxim Sobolev 
4769b50d902SRodney W. Grimes 	return (1);
4779b50d902SRodney W. Grimes }
4789b50d902SRodney W. Grimes 
4799b50d902SRodney W. Grimes /*
4809b50d902SRodney W. Grimes  * Add a compilation unit to the linked list
4819b50d902SRodney W. Grimes  */
4829b50d902SRodney W. Grimes static void
483249a8a80SPedro F. Giffuni add_compunit(enum e_cut type, char *s)
4849b50d902SRodney W. Grimes {
4859b50d902SRodney W. Grimes 	struct s_compunit *cu;
4869b50d902SRodney W. Grimes 
4878e33c0a0SDavid E. O'Brien 	if ((cu = malloc(sizeof(struct s_compunit))) == NULL)
4888e33c0a0SDavid E. O'Brien 		err(1, "malloc");
4899b50d902SRodney W. Grimes 	cu->type = type;
4909b50d902SRodney W. Grimes 	cu->s = s;
4919b50d902SRodney W. Grimes 	cu->next = NULL;
4929b50d902SRodney W. Grimes 	*cu_nextp = cu;
4939b50d902SRodney W. Grimes 	cu_nextp = &cu->next;
4949b50d902SRodney W. Grimes }
4959b50d902SRodney W. Grimes 
4969b50d902SRodney W. Grimes /*
4979b50d902SRodney W. Grimes  * Add a file to the linked list
4989b50d902SRodney W. Grimes  */
4999b50d902SRodney W. Grimes static void
500249a8a80SPedro F. Giffuni add_file(char *s)
5019b50d902SRodney W. Grimes {
5029b50d902SRodney W. Grimes 	struct s_flist *fp;
5039b50d902SRodney W. Grimes 
5048e33c0a0SDavid E. O'Brien 	if ((fp = malloc(sizeof(struct s_flist))) == NULL)
5058e33c0a0SDavid E. O'Brien 		err(1, "malloc");
5069b50d902SRodney W. Grimes 	fp->next = NULL;
5079b50d902SRodney W. Grimes 	*fl_nextp = fp;
5089b50d902SRodney W. Grimes 	fp->fname = s;
5099b50d902SRodney W. Grimes 	fl_nextp = &fp->next;
5109b50d902SRodney W. Grimes }
511839af0c1SJuli Mallett 
51296d68291SJean-Sébastien Pédron static int
513707c9cc5SPedro F. Giffuni next_files_have_lines(void)
51496d68291SJean-Sébastien Pédron {
51596d68291SJean-Sébastien Pédron 	struct s_flist *file;
51696d68291SJean-Sébastien Pédron 	FILE *file_fd;
51796d68291SJean-Sébastien Pédron 	int ch;
51896d68291SJean-Sébastien Pédron 
51996d68291SJean-Sébastien Pédron 	file = files;
52096d68291SJean-Sébastien Pédron 	while ((file = file->next) != NULL) {
52196d68291SJean-Sébastien Pédron 		if ((file_fd = fopen(file->fname, "r")) == NULL)
52296d68291SJean-Sébastien Pédron 			continue;
52396d68291SJean-Sébastien Pédron 
52496d68291SJean-Sébastien Pédron 		if ((ch = getc(file_fd)) != EOF) {
52596d68291SJean-Sébastien Pédron 			/*
52696d68291SJean-Sébastien Pédron 			 * This next file has content, therefore current
52796d68291SJean-Sébastien Pédron 			 * file doesn't contains the last line.
52896d68291SJean-Sébastien Pédron 			 */
52996d68291SJean-Sébastien Pédron 			ungetc(ch, file_fd);
53096d68291SJean-Sébastien Pédron 			fclose(file_fd);
53196d68291SJean-Sébastien Pédron 			return (1);
53296d68291SJean-Sébastien Pédron 		}
53396d68291SJean-Sébastien Pédron 
53496d68291SJean-Sébastien Pédron 		fclose(file_fd);
53596d68291SJean-Sébastien Pédron 	}
53696d68291SJean-Sébastien Pédron 
53796d68291SJean-Sébastien Pédron 	return (0);
53896d68291SJean-Sébastien Pédron }
53996d68291SJean-Sébastien Pédron 
5408523e9a6STim J. Robbins int
5418523e9a6STim J. Robbins lastline(void)
5428523e9a6STim J. Robbins {
5438523e9a6STim J. Robbins 	int ch;
5448523e9a6STim J. Robbins 
54596d68291SJean-Sébastien Pédron 	if (feof(infile)) {
54696d68291SJean-Sébastien Pédron 		return !(
54796d68291SJean-Sébastien Pédron 		    (inplace == NULL || ispan) &&
54896d68291SJean-Sébastien Pédron 		    next_files_have_lines());
54996d68291SJean-Sébastien Pédron 	}
55096d68291SJean-Sébastien Pédron 	if ((ch = getc(infile)) == EOF) {
55196d68291SJean-Sébastien Pédron 		return !(
55296d68291SJean-Sébastien Pédron 		    (inplace == NULL || ispan) &&
55396d68291SJean-Sébastien Pédron 		    next_files_have_lines());
55496d68291SJean-Sébastien Pédron 	}
555f54cda14SDag-Erling Smørgrav 	ungetc(ch, infile);
5568523e9a6STim J. Robbins 	return (0);
5578523e9a6STim J. Robbins }
558