xref: /freebsd/usr.bin/patch/inp.c (revision fcb560670601b2a4d87bb31d7531c8dcc37ee71b)
1 /*-
2  * Copyright 1986, Larry Wall
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following condition is met:
6  * 1. Redistributions of source code must retain the above copyright notice,
7  * this condition and the following disclaimer.
8  *
9  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND ANY
10  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
11  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
12  * DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
13  * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
14  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
15  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
16  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
17  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
18  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
19  * SUCH DAMAGE.
20  *
21  * patch - a program to apply diffs to original files
22  *
23  * -C option added in 1998, original code by Marc Espie, based on FreeBSD
24  * behaviour
25  *
26  * $OpenBSD: inp.c,v 1.36 2012/04/10 14:46:34 ajacoutot Exp $
27  * $FreeBSD$
28  */
29 
30 #include <sys/types.h>
31 #include <sys/file.h>
32 #include <sys/stat.h>
33 #include <sys/mman.h>
34 
35 #include <ctype.h>
36 #include <libgen.h>
37 #include <limits.h>
38 #include <stddef.h>
39 #include <stdio.h>
40 #include <stdlib.h>
41 #include <string.h>
42 #include <unistd.h>
43 
44 #include "common.h"
45 #include "util.h"
46 #include "pch.h"
47 #include "inp.h"
48 
49 
50 /* Input-file-with-indexable-lines abstract type */
51 
52 static size_t	i_size;		/* size of the input file */
53 static char	*i_womp;	/* plan a buffer for entire file */
54 static char	**i_ptr;	/* pointers to lines in i_womp */
55 static char	empty_line[] = { '\0' };
56 
57 static int	tifd = -1;	/* plan b virtual string array */
58 static char	*tibuf[2];	/* plan b buffers */
59 static LINENUM	tiline[2] = {-1, -1};	/* 1st line in each buffer */
60 static LINENUM	lines_per_buf;	/* how many lines per buffer */
61 static int	tireclen;	/* length of records in tmp file */
62 
63 static bool	rev_in_string(const char *);
64 static bool	reallocate_lines(size_t *);
65 
66 /* returns false if insufficient memory */
67 static bool	plan_a(const char *);
68 
69 static void	plan_b(const char *);
70 
71 /* New patch--prepare to edit another file. */
72 
73 void
74 re_input(void)
75 {
76 	if (using_plan_a) {
77 		free(i_ptr);
78 		i_ptr = NULL;
79 		if (i_womp != NULL) {
80 			munmap(i_womp, i_size);
81 			i_womp = NULL;
82 		}
83 		i_size = 0;
84 	} else {
85 		using_plan_a = true;	/* maybe the next one is smaller */
86 		close(tifd);
87 		tifd = -1;
88 		free(tibuf[0]);
89 		free(tibuf[1]);
90 		tibuf[0] = tibuf[1] = NULL;
91 		tiline[0] = tiline[1] = -1;
92 		tireclen = 0;
93 	}
94 }
95 
96 /* Construct the line index, somehow or other. */
97 
98 void
99 scan_input(const char *filename)
100 {
101 	if (!plan_a(filename))
102 		plan_b(filename);
103 	if (verbose) {
104 		say("Patching file %s using Plan %s...\n", filename,
105 		    (using_plan_a ? "A" : "B"));
106 	}
107 }
108 
109 static bool
110 reallocate_lines(size_t *lines_allocated)
111 {
112 	char	**p;
113 	size_t	new_size;
114 
115 	new_size = *lines_allocated * 3 / 2;
116 	p = realloc(i_ptr, (new_size + 2) * sizeof(char *));
117 	if (p == NULL) {	/* shucks, it was a near thing */
118 		munmap(i_womp, i_size);
119 		i_womp = NULL;
120 		free(i_ptr);
121 		i_ptr = NULL;
122 		*lines_allocated = 0;
123 		return false;
124 	}
125 	*lines_allocated = new_size;
126 	i_ptr = p;
127 	return true;
128 }
129 
130 /* Try keeping everything in memory. */
131 
132 static bool
133 plan_a(const char *filename)
134 {
135 	int		ifd, statfailed;
136 	char		*p, *s, lbuf[INITLINELEN];
137 	struct stat	filestat;
138 	ptrdiff_t	sz;
139 	size_t		i;
140 	size_t		iline, lines_allocated;
141 
142 #ifdef DEBUGGING
143 	if (debug & 8)
144 		return false;
145 #endif
146 
147 	if (filename == NULL || *filename == '\0')
148 		return false;
149 
150 	statfailed = stat(filename, &filestat);
151 	if (statfailed && ok_to_create_file) {
152 		if (verbose)
153 			say("(Creating file %s...)\n", filename);
154 
155 		/*
156 		 * in check_patch case, we still display `Creating file' even
157 		 * though we're not. The rule is that -C should be as similar
158 		 * to normal patch behavior as possible
159 		 */
160 		if (check_only)
161 			return true;
162 		makedirs(filename, true);
163 		close(creat(filename, 0666));
164 		statfailed = stat(filename, &filestat);
165 	}
166 	if (statfailed && check_only)
167 		fatal("%s not found, -C mode, can't probe further\n", filename);
168 	/* For nonexistent or read-only files, look for RCS or SCCS versions.  */
169 	if (statfailed ||
170 	    /* No one can write to it.  */
171 	    (filestat.st_mode & 0222) == 0 ||
172 	    /* I can't write to it.  */
173 	    ((filestat.st_mode & 0022) == 0 && filestat.st_uid != getuid())) {
174 		const char	*cs = NULL, *filebase, *filedir;
175 		struct stat	cstat;
176 		char *tmp_filename1, *tmp_filename2;
177 
178 		tmp_filename1 = strdup(filename);
179 		tmp_filename2 = strdup(filename);
180 		if (tmp_filename1 == NULL || tmp_filename2 == NULL)
181 			fatal("strdupping filename");
182 		filebase = basename(tmp_filename1);
183 		filedir = dirname(tmp_filename2);
184 
185 		/* Leave room in lbuf for the diff command.  */
186 		s = lbuf + 20;
187 
188 #define try(f, a1, a2, a3) \
189 	(snprintf(s, buf_size - 20, f, a1, a2, a3), stat(s, &cstat) == 0)
190 
191 		if (try("%s/RCS/%s%s", filedir, filebase, RCSSUFFIX) ||
192 		    try("%s/RCS/%s%s", filedir, filebase, "") ||
193 		    try("%s/%s%s", filedir, filebase, RCSSUFFIX)) {
194 			snprintf(buf, buf_size, CHECKOUT, filename);
195 			snprintf(lbuf, sizeof lbuf, RCSDIFF, filename);
196 			cs = "RCS";
197 		} else if (try("%s/SCCS/%s%s", filedir, SCCSPREFIX, filebase) ||
198 		    try("%s/%s%s", filedir, SCCSPREFIX, filebase)) {
199 			snprintf(buf, buf_size, GET, s);
200 			snprintf(lbuf, sizeof lbuf, SCCSDIFF, s, filename);
201 			cs = "SCCS";
202 		} else if (statfailed)
203 			fatal("can't find %s\n", filename);
204 
205 		free(tmp_filename1);
206 		free(tmp_filename2);
207 
208 		/*
209 		 * else we can't write to it but it's not under a version
210 		 * control system, so just proceed.
211 		 */
212 		if (cs) {
213 			if (!statfailed) {
214 				if ((filestat.st_mode & 0222) != 0)
215 					/* The owner can write to it.  */
216 					fatal("file %s seems to be locked "
217 					    "by somebody else under %s\n",
218 					    filename, cs);
219 				/*
220 				 * It might be checked out unlocked.  See if
221 				 * it's safe to check out the default version
222 				 * locked.
223 				 */
224 				if (verbose)
225 					say("Comparing file %s to default "
226 					    "%s version...\n",
227 					    filename, cs);
228 				if (system(lbuf))
229 					fatal("can't check out file %s: "
230 					    "differs from default %s version\n",
231 					    filename, cs);
232 			}
233 			if (verbose)
234 				say("Checking out file %s from %s...\n",
235 				    filename, cs);
236 			if (system(buf) || stat(filename, &filestat))
237 				fatal("can't check out file %s from %s\n",
238 				    filename, cs);
239 		}
240 	}
241 	filemode = filestat.st_mode;
242 	if (!S_ISREG(filemode))
243 		fatal("%s is not a normal file--can't patch\n", filename);
244 	if ((uint64_t)filestat.st_size > SIZE_MAX) {
245 		say("block too large to mmap\n");
246 		return false;
247 	}
248 	i_size = (size_t)filestat.st_size;
249 	if (out_of_mem) {
250 		set_hunkmax();	/* make sure dynamic arrays are allocated */
251 		out_of_mem = false;
252 		return false;	/* force plan b because plan a bombed */
253 	}
254 	if ((ifd = open(filename, O_RDONLY)) < 0)
255 		pfatal("can't open file %s", filename);
256 
257 	if (i_size) {
258 		i_womp = mmap(NULL, i_size, PROT_READ, MAP_PRIVATE, ifd, 0);
259 		if (i_womp == MAP_FAILED) {
260 			perror("mmap failed");
261 			i_womp = NULL;
262 			close(ifd);
263 			return false;
264 		}
265 	} else {
266 		i_womp = NULL;
267 	}
268 
269 	close(ifd);
270 	if (i_size)
271 		madvise(i_womp, i_size, MADV_SEQUENTIAL);
272 
273 	/* estimate the number of lines */
274 	lines_allocated = i_size / 25;
275 	if (lines_allocated < 100)
276 		lines_allocated = 100;
277 
278 	if (!reallocate_lines(&lines_allocated))
279 		return false;
280 
281 	/* now scan the buffer and build pointer array */
282 	iline = 1;
283 	i_ptr[iline] = i_womp;
284 	/* test for NUL too, to maintain the behavior of the original code */
285 	for (s = i_womp, i = 0; i < i_size && *s != '\0'; s++, i++) {
286 		if (*s == '\n') {
287 			if (iline == lines_allocated) {
288 				if (!reallocate_lines(&lines_allocated))
289 					return false;
290 			}
291 			/* these are NOT NUL terminated */
292 			i_ptr[++iline] = s + 1;
293 		}
294 	}
295 	/* if the last line contains no EOL, append one */
296 	if (i_size > 0 && i_womp[i_size - 1] != '\n') {
297 		last_line_missing_eol = true;
298 		/* fix last line */
299 		sz = s - i_ptr[iline];
300 		p = malloc(sz + 1);
301 		if (p == NULL) {
302 			free(i_ptr);
303 			i_ptr = NULL;
304 			munmap(i_womp, i_size);
305 			i_womp = NULL;
306 			return false;
307 		}
308 
309 		memcpy(p, i_ptr[iline], sz);
310 		p[sz] = '\n';
311 		i_ptr[iline] = p;
312 		/* count the extra line and make it point to some valid mem */
313 		i_ptr[++iline] = empty_line;
314 	} else
315 		last_line_missing_eol = false;
316 
317 	input_lines = iline - 1;
318 
319 	/* now check for revision, if any */
320 
321 	if (revision != NULL) {
322 		if (!rev_in_string(i_womp)) {
323 			if (force) {
324 				if (verbose)
325 					say("Warning: this file doesn't appear "
326 					    "to be the %s version--patching anyway.\n",
327 					    revision);
328 			} else if (batch) {
329 				fatal("this file doesn't appear to be the "
330 				    "%s version--aborting.\n",
331 				    revision);
332 			} else {
333 				ask("This file doesn't appear to be the "
334 				    "%s version--patch anyway? [n] ",
335 				    revision);
336 				if (*buf != 'y')
337 					fatal("aborted\n");
338 			}
339 		} else if (verbose)
340 			say("Good.  This file appears to be the %s version.\n",
341 			    revision);
342 	}
343 	return true;		/* plan a will work */
344 }
345 
346 /* Keep (virtually) nothing in memory. */
347 
348 static void
349 plan_b(const char *filename)
350 {
351 	FILE	*ifp;
352 	size_t	i = 0, j, maxlen = 1;
353 	char	*p;
354 	bool	found_revision = (revision == NULL);
355 
356 	using_plan_a = false;
357 	if ((ifp = fopen(filename, "r")) == NULL)
358 		pfatal("can't open file %s", filename);
359 	unlink(TMPINNAME);
360 	if ((tifd = open(TMPINNAME, O_EXCL | O_CREAT | O_WRONLY, 0666)) < 0)
361 		pfatal("can't open file %s", TMPINNAME);
362 	while (fgets(buf, buf_size, ifp) != NULL) {
363 		if (revision != NULL && !found_revision && rev_in_string(buf))
364 			found_revision = true;
365 		if ((i = strlen(buf)) > maxlen)
366 			maxlen = i;	/* find longest line */
367 	}
368 	last_line_missing_eol = i > 0 && buf[i - 1] != '\n';
369 	if (last_line_missing_eol && maxlen == i)
370 		maxlen++;
371 
372 	if (revision != NULL) {
373 		if (!found_revision) {
374 			if (force) {
375 				if (verbose)
376 					say("Warning: this file doesn't appear "
377 					    "to be the %s version--patching anyway.\n",
378 					    revision);
379 			} else if (batch) {
380 				fatal("this file doesn't appear to be the "
381 				    "%s version--aborting.\n",
382 				    revision);
383 			} else {
384 				ask("This file doesn't appear to be the %s "
385 				    "version--patch anyway? [n] ",
386 				    revision);
387 				if (*buf != 'y')
388 					fatal("aborted\n");
389 			}
390 		} else if (verbose)
391 			say("Good.  This file appears to be the %s version.\n",
392 			    revision);
393 	}
394 	fseek(ifp, 0L, SEEK_SET);	/* rewind file */
395 	lines_per_buf = BUFFERSIZE / maxlen;
396 	tireclen = maxlen;
397 	tibuf[0] = malloc(BUFFERSIZE + 1);
398 	if (tibuf[0] == NULL)
399 		fatal("out of memory\n");
400 	tibuf[1] = malloc(BUFFERSIZE + 1);
401 	if (tibuf[1] == NULL)
402 		fatal("out of memory\n");
403 	for (i = 1;; i++) {
404 		p = tibuf[0] + maxlen * (i % lines_per_buf);
405 		if (i % lines_per_buf == 0)	/* new block */
406 			if (write(tifd, tibuf[0], BUFFERSIZE) < BUFFERSIZE)
407 				pfatal("can't write temp file");
408 		if (fgets(p, maxlen + 1, ifp) == NULL) {
409 			input_lines = i - 1;
410 			if (i % lines_per_buf != 0)
411 				if (write(tifd, tibuf[0], BUFFERSIZE) < BUFFERSIZE)
412 					pfatal("can't write temp file");
413 			break;
414 		}
415 		j = strlen(p);
416 		/* These are '\n' terminated strings, so no need to add a NUL */
417 		if (j == 0 || p[j - 1] != '\n')
418 			p[j] = '\n';
419 	}
420 	fclose(ifp);
421 	close(tifd);
422 	if ((tifd = open(TMPINNAME, O_RDONLY)) < 0)
423 		pfatal("can't reopen file %s", TMPINNAME);
424 }
425 
426 /*
427  * Fetch a line from the input file, \n terminated, not necessarily \0.
428  */
429 char *
430 ifetch(LINENUM line, int whichbuf)
431 {
432 	if (line < 1 || line > input_lines) {
433 		if (warn_on_invalid_line) {
434 			say("No such line %ld in input file, ignoring\n", line);
435 			warn_on_invalid_line = false;
436 		}
437 		return NULL;
438 	}
439 	if (using_plan_a)
440 		return i_ptr[line];
441 	else {
442 		LINENUM	offline = line % lines_per_buf;
443 		LINENUM	baseline = line - offline;
444 
445 		if (tiline[0] == baseline)
446 			whichbuf = 0;
447 		else if (tiline[1] == baseline)
448 			whichbuf = 1;
449 		else {
450 			tiline[whichbuf] = baseline;
451 
452 			if (lseek(tifd, (off_t) (baseline / lines_per_buf *
453 			    BUFFERSIZE), SEEK_SET) < 0)
454 				pfatal("cannot seek in the temporary input file");
455 
456 			if (read(tifd, tibuf[whichbuf], BUFFERSIZE) < 0)
457 				pfatal("error reading tmp file %s", TMPINNAME);
458 		}
459 		return tibuf[whichbuf] + (tireclen * offline);
460 	}
461 }
462 
463 /*
464  * True if the string argument contains the revision number we want.
465  */
466 static bool
467 rev_in_string(const char *string)
468 {
469 	const char	*s;
470 	size_t		patlen;
471 
472 	if (revision == NULL)
473 		return true;
474 	patlen = strlen(revision);
475 	if (strnEQ(string, revision, patlen) && isspace((unsigned char)string[patlen]))
476 		return true;
477 	for (s = string; *s; s++) {
478 		if (isspace((unsigned char)*s) && strnEQ(s + 1, revision, patlen) &&
479 		    isspace((unsigned char)s[patlen + 1])) {
480 			return true;
481 		}
482 	}
483 	return false;
484 }
485