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 LINENUM lines_per_buf; /* how many lines per buffer */
65 static int tireclen; /* length of records in tmp file */
67 static bool rev_in_string(const char *);
68 static bool reallocate_lines(size_t *);
70 /* returns false if insufficient memory */
71 static bool plan_a(const char *);
73 static void plan_b(const char *);
75 /* New patch--prepare to edit another file. */
84 munmap(i_womp, i_size);
89 using_plan_a = true; /* maybe the next one is smaller */
94 tibuf[0] = tibuf[1] = NULL;
95 tiline[0] = tiline[1] = -1;
100 /* Construct the line index, somehow or other. */
103 scan_input(const char *filename)
105 if (!plan_a(filename))
108 say("Patching file %s using Plan %s...\n", filename,
109 (using_plan_a ? "A" : "B"));
114 reallocate_lines(size_t *lines_allocated)
119 new_size = *lines_allocated * 3 / 2;
120 p = realloc(i_ptr, (new_size + 2) * sizeof(char *));
121 if (p == NULL) { /* shucks, it was a near thing */
122 munmap(i_womp, i_size);
126 *lines_allocated = 0;
129 *lines_allocated = new_size;
134 /* Try keeping everything in memory. */
137 plan_a(const char *filename)
139 int ifd, statfailed, pstat;
140 char *p, *s, lbuf[INITLINELEN];
141 struct stat filestat;
144 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);
171 if (statfailed && check_only)
172 fatal("%s not found, -C mode, can't probe further\n", filename);
173 /* For nonexistent or read-only files, look for RCS versions. */
176 /* No one can write to it. */
177 (filestat.st_mode & 0222) == 0 ||
178 /* I can't write to it. */
179 ((filestat.st_mode & 0022) == 0 && filestat.st_uid != getuid())) {
180 char *filebase, *filedir;
182 char *tmp_filename1, *tmp_filename2;
183 char *argp[4] = { NULL };
184 posix_spawn_file_actions_t file_actions;
186 tmp_filename1 = strdup(filename);
187 tmp_filename2 = strdup(filename);
188 if (tmp_filename1 == NULL || tmp_filename2 == NULL)
189 fatal("strdupping filename");
191 filebase = basename(tmp_filename1);
192 filedir = dirname(tmp_filename2);
194 memset(argp, 0, sizeof(argp));
196 #define try(f, a1, a2, a3) \
197 (snprintf(lbuf, sizeof(lbuf), f, a1, a2, a3), stat(lbuf, &cstat) == 0)
200 * else we can't write to it but it's not under a version
201 * control system, so just proceed.
203 if (try("%s/RCS/%s%s", filedir, filebase, RCSSUFFIX) ||
204 try("%s/RCS/%s%s", filedir, filebase, "") ||
205 try("%s/%s%s", filedir, filebase, RCSSUFFIX)) {
207 if ((filestat.st_mode & 0222) != 0)
208 /* The owner can write to it. */
209 fatal("file %s seems to be locked "
210 "by somebody else under RCS\n",
213 * It might be checked out unlocked. See if
214 * it's safe to check out the default version
218 say("Comparing file %s to default "
219 "RCS version...\n", filename);
221 argp[0] = __DECONST(char *, RCSDIFF);
222 argp[1] = __DECONST(char *, filename);
223 posix_spawn_file_actions_init(&file_actions);
224 posix_spawn_file_actions_addopen(&file_actions,
225 STDOUT_FILENO, _PATH_DEVNULL, O_WRONLY, 0);
226 if (posix_spawn(&pid, RCSDIFF, &file_actions,
227 NULL, argp, NULL) == 0) {
228 pid = waitpid(pid, &pstat, 0);
229 if (pid == -1 || WEXITSTATUS(pstat) != 0)
230 fatal("can't check out file %s: "
231 "differs from default RCS version\n",
234 fatal("posix_spawn: %s\n", strerror(errno));
235 posix_spawn_file_actions_destroy(&file_actions);
239 say("Checking out file %s from RCS...\n",
242 argp[0] = __DECONST(char *, CHECKOUT);
243 argp[1] = __DECONST(char *, "-l");
244 argp[2] = __DECONST(char *, filename);
245 if (posix_spawn(&pid, CHECKOUT, NULL, NULL, argp,
247 pid = waitpid(pid, &pstat, 0);
248 if (pid == -1 || WEXITSTATUS(pstat) != 0 ||
249 stat(filename, &filestat))
250 fatal("can't check out file %s from RCS\n",
253 fatal("posix_spawn: %s\n", strerror(errno));
254 } else if (statfailed) {
255 fatal("can't find %s\n", filename);
261 filemode = filestat.st_mode;
262 if (!S_ISREG(filemode))
263 fatal("%s is not a normal file--can't patch\n", filename);
264 if ((uint64_t)filestat.st_size > SIZE_MAX) {
265 say("block too large to mmap\n");
268 i_size = (size_t)filestat.st_size;
270 set_hunkmax(); /* make sure dynamic arrays are allocated */
272 return false; /* force plan b because plan a bombed */
274 if ((ifd = open(filename, O_RDONLY)) < 0)
275 pfatal("can't open file %s", filename);
278 i_womp = mmap(NULL, i_size, PROT_READ, MAP_PRIVATE, ifd, 0);
279 if (i_womp == MAP_FAILED) {
280 perror("mmap failed");
291 madvise(i_womp, i_size, MADV_SEQUENTIAL);
293 /* estimate the number of lines */
294 lines_allocated = i_size / 25;
295 if (lines_allocated < 100)
296 lines_allocated = 100;
298 if (!reallocate_lines(&lines_allocated))
301 /* now scan the buffer and build pointer array */
303 i_ptr[iline] = i_womp;
304 /* test for NUL too, to maintain the behavior of the original code */
305 for (s = i_womp, i = 0; i < i_size && *s != '\0'; s++, i++) {
307 if (iline == lines_allocated) {
308 if (!reallocate_lines(&lines_allocated))
311 /* these are NOT NUL terminated */
312 i_ptr[++iline] = s + 1;
315 /* if the last line contains no EOL, append one */
316 if (i_size > 0 && i_womp[i_size - 1] != '\n') {
317 last_line_missing_eol = true;
319 sz = s - i_ptr[iline];
324 munmap(i_womp, i_size);
329 memcpy(p, i_ptr[iline], sz);
332 /* count the extra line and make it point to some valid mem */
333 i_ptr[++iline] = empty_line;
335 last_line_missing_eol = false;
337 input_lines = iline - 1;
339 /* now check for revision, if any */
341 if (revision != NULL) {
342 if (!rev_in_string(i_womp)) {
345 say("Warning: this file doesn't appear "
346 "to be the %s version--patching anyway.\n",
349 fatal("this file doesn't appear to be the "
350 "%s version--aborting.\n",
353 ask("This file doesn't appear to be the "
354 "%s version--patch anyway? [n] ",
360 say("Good. This file appears to be the %s version.\n",
363 return true; /* plan a will work */
366 /* Keep (virtually) nothing in memory. */
369 plan_b(const char *filename)
372 size_t i = 0, j, maxlen = 1;
374 bool found_revision = (revision == NULL);
376 using_plan_a = false;
377 if ((ifp = fopen(filename, "r")) == NULL)
378 pfatal("can't open file %s", filename);
380 if ((tifd = open(TMPINNAME, O_EXCL | O_CREAT | O_WRONLY, 0666)) < 0)
381 pfatal("can't open file %s", TMPINNAME);
382 while (fgets(buf, buf_size, ifp) != NULL) {
383 if (revision != NULL && !found_revision && rev_in_string(buf))
384 found_revision = true;
385 if ((i = strlen(buf)) > maxlen)
386 maxlen = i; /* find longest line */
388 last_line_missing_eol = i > 0 && buf[i - 1] != '\n';
389 if (last_line_missing_eol && maxlen == i)
392 if (revision != NULL) {
393 if (!found_revision) {
396 say("Warning: this file doesn't appear "
397 "to be the %s version--patching anyway.\n",
400 fatal("this file doesn't appear to be the "
401 "%s version--aborting.\n",
404 ask("This file doesn't appear to be the %s "
405 "version--patch anyway? [n] ",
411 say("Good. This file appears to be the %s version.\n",
414 fseek(ifp, 0L, SEEK_SET); /* rewind file */
415 lines_per_buf = BUFFERSIZE / maxlen;
417 tibuf[0] = malloc(BUFFERSIZE + 1);
418 if (tibuf[0] == NULL)
419 fatal("out of memory\n");
420 tibuf[1] = malloc(BUFFERSIZE + 1);
421 if (tibuf[1] == NULL)
422 fatal("out of memory\n");
424 p = tibuf[0] + maxlen * (i % lines_per_buf);
425 if (i % lines_per_buf == 0) /* new block */
426 if (write(tifd, tibuf[0], BUFFERSIZE) < BUFFERSIZE)
427 pfatal("can't write temp file");
428 if (fgets(p, maxlen + 1, ifp) == NULL) {
430 if (i % lines_per_buf != 0)
431 if (write(tifd, tibuf[0], BUFFERSIZE) < BUFFERSIZE)
432 pfatal("can't write temp file");
436 /* These are '\n' terminated strings, so no need to add a NUL */
437 if (j == 0 || p[j - 1] != '\n')
442 if ((tifd = open(TMPINNAME, O_RDONLY)) < 0)
443 pfatal("can't reopen file %s", TMPINNAME);
447 * Fetch a line from the input file, \n terminated, not necessarily \0.
450 ifetch(LINENUM line, int whichbuf)
452 if (line < 1 || line > input_lines) {
453 if (warn_on_invalid_line) {
454 say("No such line %ld in input file, ignoring\n", line);
455 warn_on_invalid_line = false;
462 LINENUM offline = line % lines_per_buf;
463 LINENUM baseline = line - offline;
465 if (tiline[0] == baseline)
467 else if (tiline[1] == baseline)
470 tiline[whichbuf] = baseline;
472 if (lseek(tifd, (off_t) (baseline / lines_per_buf *
473 BUFFERSIZE), SEEK_SET) < 0)
474 pfatal("cannot seek in the temporary input file");
476 if (read(tifd, tibuf[whichbuf], BUFFERSIZE) < 0)
477 pfatal("error reading tmp file %s", TMPINNAME);
479 return tibuf[whichbuf] + (tireclen * offline);
484 * True if the string argument contains the revision number we want.
487 rev_in_string(const char *string)
492 if (revision == NULL)
494 patlen = strlen(revision);
495 if (strnEQ(string, revision, patlen) && isspace((unsigned char)string[patlen]))
497 for (s = string; *s; s++) {
498 if (isspace((unsigned char)*s) && strnEQ(s + 1, revision, patlen) &&
499 isspace((unsigned char)s[patlen + 1])) {