2 * Copyright 1986, Larry Wall
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.
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
21 * patch - a program to apply diffs to original files
23 * -C option added in 1998, original code by Marc Espie, based on FreeBSD
26 * $OpenBSD: inp.c,v 1.36 2012/04/10 14:46:34 ajacoutot Exp $
30 #include <sys/types.h>
54 /* Input-file-with-indexable-lines abstract type */
56 static size_t i_size; /* size of the input file */
57 static char *i_womp; /* plan a buffer for entire file */
58 static char **i_ptr; /* pointers to lines in i_womp */
59 static char empty_line[] = { '\0' };
61 static int tifd = -1; /* plan b virtual string array */
62 static char *tibuf[2]; /* plan b buffers */
63 static LINENUM tiline[2] = {-1, -1}; /* 1st line in each buffer */
64 static size_t lines_per_buf; /* how many lines per buffer */
65 static size_t tibuflen; /* plan b buffer length */
66 static size_t tireclen; /* length of records in tmp file */
68 static bool rev_in_string(const char *);
69 static bool reallocate_lines(size_t *);
71 /* returns false if insufficient memory */
72 static bool plan_a(const char *);
74 static void plan_b(const char *);
76 /* New patch--prepare to edit another file. */
85 munmap(i_womp, i_size);
90 using_plan_a = true; /* maybe the next one is smaller */
95 tibuf[0] = tibuf[1] = NULL;
96 tiline[0] = tiline[1] = -1;
101 /* Construct the line index, somehow or other. */
104 scan_input(const char *filename)
106 if (!plan_a(filename))
109 say("Patching file %s using Plan %s...\n", filename,
110 (using_plan_a ? "A" : "B"));
115 reallocate_lines(size_t *lines_allocated)
120 new_size = *lines_allocated * 3 / 2;
121 p = realloc(i_ptr, (new_size + 2) * sizeof(char *));
122 if (p == NULL) { /* shucks, it was a near thing */
123 munmap(i_womp, i_size);
127 *lines_allocated = 0;
130 *lines_allocated = new_size;
135 /* Try keeping everything in memory. */
138 plan_a(const char *filename)
142 struct stat filestat;
145 size_t iline, lines_allocated;
152 if (filename == NULL || *filename == '\0')
155 statfailed = stat(filename, &filestat);
156 if (statfailed && ok_to_create_file) {
158 say("(Creating file %s...)\n", filename);
161 * in check_patch case, we still display `Creating file' even
162 * though we're not. The rule is that -C should be as similar
163 * to normal patch behavior as possible
167 makedirs(filename, true);
168 close(creat(filename, 0666));
169 statfailed = stat(filename, &filestat);
172 fatal("can't find %s\n", filename);
173 filemode = filestat.st_mode;
174 if (!S_ISREG(filemode))
175 fatal("%s is not a normal file--can't patch\n", filename);
176 if ((uint64_t)filestat.st_size > SIZE_MAX) {
177 say("block too large to mmap\n");
180 i_size = (size_t)filestat.st_size;
182 set_hunkmax(); /* make sure dynamic arrays are allocated */
184 return false; /* force plan b because plan a bombed */
186 if ((ifd = open(filename, O_RDONLY)) < 0)
187 pfatal("can't open file %s", filename);
190 i_womp = mmap(NULL, i_size, PROT_READ, MAP_PRIVATE, ifd, 0);
191 if (i_womp == MAP_FAILED) {
192 perror("mmap failed");
203 madvise(i_womp, i_size, MADV_SEQUENTIAL);
205 /* estimate the number of lines */
206 lines_allocated = i_size / 25;
207 if (lines_allocated < 100)
208 lines_allocated = 100;
210 if (!reallocate_lines(&lines_allocated))
213 /* now scan the buffer and build pointer array */
215 i_ptr[iline] = i_womp;
217 * Testing for NUL here actively breaks files that innocently use NUL
218 * for other reasons. mmap(2) succeeded, just scan the whole buffer.
220 for (s = i_womp, i = 0; i < i_size; s++, i++) {
222 if (iline == lines_allocated) {
223 if (!reallocate_lines(&lines_allocated))
226 /* these are NOT NUL terminated */
227 i_ptr[++iline] = s + 1;
230 /* if the last line contains no EOL, append one */
231 if (i_size > 0 && i_womp[i_size - 1] != '\n') {
232 last_line_missing_eol = true;
234 sz = s - i_ptr[iline];
239 munmap(i_womp, i_size);
244 memcpy(p, i_ptr[iline], sz);
247 /* count the extra line and make it point to some valid mem */
248 i_ptr[++iline] = empty_line;
250 last_line_missing_eol = false;
252 input_lines = iline - 1;
254 /* now check for revision, if any */
256 if (revision != NULL) {
257 if (i_womp == NULL || !rev_in_string(i_womp)) {
260 say("Warning: this file doesn't appear "
261 "to be the %s version--patching anyway.\n",
264 fatal("this file doesn't appear to be the "
265 "%s version--aborting.\n",
268 ask("This file doesn't appear to be the "
269 "%s version--patch anyway? [n] ",
275 say("Good. This file appears to be the %s version.\n",
278 return true; /* plan a will work */
281 /* Keep (virtually) nothing in memory. */
284 plan_b(const char *filename)
287 size_t i = 0, j, len, maxlen = 1;
288 char *lbuf = NULL, *p;
289 bool found_revision = (revision == NULL);
291 using_plan_a = false;
292 if ((ifp = fopen(filename, "r")) == NULL)
293 pfatal("can't open file %s", filename);
295 if ((tifd = open(TMPINNAME, O_EXCL | O_CREAT | O_WRONLY, 0666)) < 0)
296 pfatal("can't open file %s", TMPINNAME);
297 while ((p = fgetln(ifp, &len)) != NULL) {
298 if (p[len - 1] == '\n')
301 /* EOF without EOL, copy and add the NUL */
302 if ((lbuf = malloc(len + 1)) == NULL)
303 fatal("out of memory\n");
304 memcpy(lbuf, p, len);
308 last_line_missing_eol = true;
311 if (revision != NULL && !found_revision && rev_in_string(p))
312 found_revision = true;
314 maxlen = len; /* find longest line */
318 pfatal("can't read file %s", filename);
320 if (revision != NULL) {
321 if (!found_revision) {
324 say("Warning: this file doesn't appear "
325 "to be the %s version--patching anyway.\n",
328 fatal("this file doesn't appear to be the "
329 "%s version--aborting.\n",
332 ask("This file doesn't appear to be the %s "
333 "version--patch anyway? [n] ",
339 say("Good. This file appears to be the %s version.\n",
342 fseek(ifp, 0L, SEEK_SET); /* rewind file */
344 tibuflen = maxlen > BUFFERSIZE ? maxlen : BUFFERSIZE;
345 lines_per_buf = tibuflen / maxlen;
346 tibuf[0] = malloc(tibuflen + 1);
347 if (tibuf[0] == NULL)
348 fatal("out of memory\n");
349 tibuf[1] = malloc(tibuflen + 1);
350 if (tibuf[1] == NULL)
351 fatal("out of memory\n");
353 p = tibuf[0] + maxlen * (i % lines_per_buf);
354 if (i % lines_per_buf == 0) /* new block */
355 if (write(tifd, tibuf[0], tibuflen) !=
357 pfatal("can't write temp file");
358 if (fgets(p, maxlen + 1, ifp) == NULL) {
360 if (i % lines_per_buf != 0)
361 if (write(tifd, tibuf[0], tibuflen) !=
363 pfatal("can't write temp file");
367 /* These are '\n' terminated strings, so no need to add a NUL */
368 if (j == 0 || p[j - 1] != '\n')
373 if ((tifd = open(TMPINNAME, O_RDONLY)) < 0)
374 pfatal("can't reopen file %s", TMPINNAME);
378 * Fetch a line from the input file, \n terminated, not necessarily \0.
381 ifetch(LINENUM line, int whichbuf)
383 if (line < 1 || line > input_lines) {
384 if (warn_on_invalid_line) {
385 say("No such line %ld in input file, ignoring\n", line);
386 warn_on_invalid_line = false;
393 LINENUM offline = line % lines_per_buf;
394 LINENUM baseline = line - offline;
396 if (tiline[0] == baseline)
398 else if (tiline[1] == baseline)
401 tiline[whichbuf] = baseline;
403 if (lseek(tifd, (off_t) (baseline / lines_per_buf *
404 tibuflen), SEEK_SET) < 0)
405 pfatal("cannot seek in the temporary input file");
407 if (read(tifd, tibuf[whichbuf], tibuflen) !=
409 pfatal("error reading tmp file %s", TMPINNAME);
411 return tibuf[whichbuf] + (tireclen * offline);
416 * True if the string argument contains the revision number we want.
419 rev_in_string(const char *string)
424 if (revision == NULL)
426 patlen = strlen(revision);
427 if (strnEQ(string, revision, patlen) && isspace((unsigned char)string[patlen]))
429 for (s = string; *s; s++) {
430 if (isspace((unsigned char)*s) && strnEQ(s + 1, revision, patlen) &&
431 isspace((unsigned char)s[patlen + 1])) {