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>
50 /* Input-file-with-indexable-lines abstract type */
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' };
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 */
63 static bool rev_in_string(const char *);
64 static bool reallocate_lines(size_t *);
66 /* returns false if insufficient memory */
67 static bool plan_a(const char *);
69 static void plan_b(const char *);
71 /* New patch--prepare to edit another file. */
80 munmap(i_womp, i_size);
85 using_plan_a = true; /* maybe the next one is smaller */
90 tibuf[0] = tibuf[1] = NULL;
91 tiline[0] = tiline[1] = -1;
96 /* Construct the line index, somehow or other. */
99 scan_input(const char *filename)
101 if (!plan_a(filename))
104 say("Patching file %s using Plan %s...\n", filename,
105 (using_plan_a ? "A" : "B"));
110 reallocate_lines(size_t *lines_allocated)
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);
122 *lines_allocated = 0;
125 *lines_allocated = new_size;
130 /* Try keeping everything in memory. */
133 plan_a(const char *filename)
136 char *p, *s, lbuf[INITLINELEN];
137 struct stat filestat;
140 size_t iline, lines_allocated;
147 if (filename == NULL || *filename == '\0')
150 statfailed = stat(filename, &filestat);
151 if (statfailed && ok_to_create_file) {
153 say("(Creating file %s...)\n", filename);
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
162 makedirs(filename, true);
163 close(creat(filename, 0666));
164 statfailed = stat(filename, &filestat);
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. */
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;
176 char *tmp_filename1, *tmp_filename2;
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);
185 /* Leave room in lbuf for the diff command. */
188 #define try(f, a1, a2, a3) \
189 (snprintf(s, buf_size - 20, f, a1, a2, a3), stat(s, &cstat) == 0)
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);
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);
202 } else if (statfailed)
203 fatal("can't find %s\n", filename);
209 * else we can't write to it but it's not under a version
210 * control system, so just proceed.
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",
220 * It might be checked out unlocked. See if
221 * it's safe to check out the default version
225 say("Comparing file %s to default "
229 fatal("can't check out file %s: "
230 "differs from default %s version\n",
234 say("Checking out file %s from %s...\n",
236 if (system(buf) || stat(filename, &filestat))
237 fatal("can't check out file %s from %s\n",
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");
248 i_size = (size_t)filestat.st_size;
250 set_hunkmax(); /* make sure dynamic arrays are allocated */
252 return false; /* force plan b because plan a bombed */
254 if ((ifd = open(filename, O_RDONLY)) < 0)
255 pfatal("can't open file %s", filename);
258 i_womp = mmap(NULL, i_size, PROT_READ, MAP_PRIVATE, ifd, 0);
259 if (i_womp == MAP_FAILED) {
260 perror("mmap failed");
271 madvise(i_womp, i_size, MADV_SEQUENTIAL);
273 /* estimate the number of lines */
274 lines_allocated = i_size / 25;
275 if (lines_allocated < 100)
276 lines_allocated = 100;
278 if (!reallocate_lines(&lines_allocated))
281 /* now scan the buffer and build pointer array */
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++) {
287 if (iline == lines_allocated) {
288 if (!reallocate_lines(&lines_allocated))
291 /* these are NOT NUL terminated */
292 i_ptr[++iline] = s + 1;
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;
299 sz = s - i_ptr[iline];
304 munmap(i_womp, i_size);
309 memcpy(p, i_ptr[iline], sz);
312 /* count the extra line and make it point to some valid mem */
313 i_ptr[++iline] = empty_line;
315 last_line_missing_eol = false;
317 input_lines = iline - 1;
319 /* now check for revision, if any */
321 if (revision != NULL) {
322 if (!rev_in_string(i_womp)) {
325 say("Warning: this file doesn't appear "
326 "to be the %s version--patching anyway.\n",
329 fatal("this file doesn't appear to be the "
330 "%s version--aborting.\n",
333 ask("This file doesn't appear to be the "
334 "%s version--patch anyway? [n] ",
340 say("Good. This file appears to be the %s version.\n",
343 return true; /* plan a will work */
346 /* Keep (virtually) nothing in memory. */
349 plan_b(const char *filename)
352 size_t i = 0, j, maxlen = 1;
354 bool found_revision = (revision == NULL);
356 using_plan_a = false;
357 if ((ifp = fopen(filename, "r")) == NULL)
358 pfatal("can't open file %s", filename);
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 */
368 last_line_missing_eol = i > 0 && buf[i - 1] != '\n';
369 if (last_line_missing_eol && maxlen == i)
372 if (revision != NULL) {
373 if (!found_revision) {
376 say("Warning: this file doesn't appear "
377 "to be the %s version--patching anyway.\n",
380 fatal("this file doesn't appear to be the "
381 "%s version--aborting.\n",
384 ask("This file doesn't appear to be the %s "
385 "version--patch anyway? [n] ",
391 say("Good. This file appears to be the %s version.\n",
394 fseek(ifp, 0L, SEEK_SET); /* rewind file */
395 lines_per_buf = BUFFERSIZE / 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");
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) {
410 if (i % lines_per_buf != 0)
411 if (write(tifd, tibuf[0], BUFFERSIZE) < BUFFERSIZE)
412 pfatal("can't write temp file");
416 /* These are '\n' terminated strings, so no need to add a NUL */
417 if (j == 0 || p[j - 1] != '\n')
422 if ((tifd = open(TMPINNAME, O_RDONLY)) < 0)
423 pfatal("can't reopen file %s", TMPINNAME);
427 * Fetch a line from the input file, \n terminated, not necessarily \0.
430 ifetch(LINENUM line, int whichbuf)
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;
442 LINENUM offline = line % lines_per_buf;
443 LINENUM baseline = line - offline;
445 if (tiline[0] == baseline)
447 else if (tiline[1] == baseline)
450 tiline[whichbuf] = baseline;
452 if (lseek(tifd, (off_t) (baseline / lines_per_buf *
453 BUFFERSIZE), SEEK_SET) < 0)
454 pfatal("cannot seek in the temporary input file");
456 if (read(tifd, tibuf[whichbuf], BUFFERSIZE) < 0)
457 pfatal("error reading tmp file %s", TMPINNAME);
459 return tibuf[whichbuf] + (tireclen * offline);
464 * True if the string argument contains the revision number we want.
467 rev_in_string(const char *string)
472 if (revision == NULL)
474 patlen = strlen(revision);
475 if (strnEQ(string, revision, patlen) && isspace((unsigned char)string[patlen]))
477 for (s = string; *s; s++) {
478 if (isspace((unsigned char)*s) && strnEQ(s + 1, revision, patlen) &&
479 isspace((unsigned char)s[patlen + 1])) {