2 * $OpenBSD: inp.c,v 1.34 2006/03/11 19:41:30 otto Exp $
6 * patch - a program to apply diffs to original files
8 * Copyright 1986, Larry Wall
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following condition is met:
12 * 1. Redistributions of source code must retain the above copyright notice,
13 * this condition and the following disclaimer.
15 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND ANY
16 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
17 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
18 * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
19 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
21 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
22 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27 * -C option added in 1998, original code by Marc Espie, based on FreeBSD
31 #include <sys/types.h>
51 /* Input-file-with-indexable-lines abstract type */
53 static size_t i_size; /* size of the input file */
54 static char *i_womp; /* plan a buffer for entire file */
55 static char **i_ptr; /* pointers to lines in i_womp */
56 static char empty_line[] = { '\0' };
58 static int tifd = -1; /* plan b virtual string array */
59 static char *tibuf[2]; /* plan b buffers */
60 static LINENUM tiline[2] = {-1, -1}; /* 1st line in each buffer */
61 static LINENUM lines_per_buf; /* how many lines per buffer */
62 static int tireclen; /* length of records in tmp file */
64 static bool rev_in_string(const char *);
65 static bool reallocate_lines(size_t *);
67 /* returns false if insufficient memory */
68 static bool plan_a(const char *);
70 static void plan_b(const char *);
72 /* New patch--prepare to edit another file. */
81 munmap(i_womp, i_size);
86 using_plan_a = true; /* maybe the next one is smaller */
91 tibuf[0] = tibuf[1] = NULL;
92 tiline[0] = tiline[1] = -1;
97 /* Construct the line index, somehow or other. */
100 scan_input(const char *filename)
102 if (!plan_a(filename))
105 say("Patching file %s using Plan %s...\n", filename,
106 (using_plan_a ? "A" : "B"));
111 reallocate_lines(size_t *lines_allocated)
116 new_size = *lines_allocated * 3 / 2;
117 p = realloc(i_ptr, (new_size + 2) * sizeof(char *));
118 if (p == NULL) { /* shucks, it was a near thing */
119 munmap(i_womp, i_size);
123 *lines_allocated = 0;
126 *lines_allocated = new_size;
131 /* Try keeping everything in memory. */
134 plan_a(const char *filename)
137 char *p, *s, lbuf[MAXLINELEN];
138 struct stat filestat;
141 size_t iline, lines_allocated;
148 if (filename == NULL || *filename == '\0')
151 statfailed = stat(filename, &filestat);
152 if (statfailed && ok_to_create_file) {
154 say("(Creating file %s...)\n", filename);
157 * in check_patch case, we still display `Creating file' even
158 * though we're not. The rule is that -C should be as similar
159 * to normal patch behavior as possible
163 makedirs(filename, true);
164 close(creat(filename, 0666));
165 statfailed = stat(filename, &filestat);
167 if (statfailed && check_only)
168 fatal("%s not found, -C mode, can't probe further\n", filename);
169 /* For nonexistent or read-only files, look for RCS or SCCS versions. */
171 /* No one can write to it. */
172 (filestat.st_mode & 0222) == 0 ||
173 /* I can't write to it. */
174 ((filestat.st_mode & 0022) == 0 && filestat.st_uid != getuid())) {
175 const char *cs = NULL, *filebase, *filedir;
177 char *tmp_filename1, *tmp_filename2;
179 tmp_filename1 = strdup(filename);
180 tmp_filename2 = strdup(filename);
181 if (tmp_filename1 == NULL || tmp_filename2 == NULL)
182 fatal("strdupping filename");
183 filebase = basename(tmp_filename1);
184 filedir = dirname(tmp_filename2);
186 /* Leave room in lbuf for the diff command. */
189 #define try(f, a1, a2, a3) \
190 (snprintf(s, sizeof lbuf - 20, f, a1, a2, a3), stat(s, &cstat) == 0)
192 if (try("%s/RCS/%s%s", filedir, filebase, RCSSUFFIX) ||
193 try("%s/RCS/%s%s", filedir, filebase, "") ||
194 try("%s/%s%s", filedir, filebase, RCSSUFFIX)) {
195 snprintf(buf, buf_len, CHECKOUT, filename);
196 snprintf(lbuf, sizeof lbuf, RCSDIFF, filename);
198 } else if (try("%s/SCCS/%s%s", filedir, SCCSPREFIX, filebase) ||
199 try("%s/%s%s", filedir, SCCSPREFIX, filebase)) {
200 snprintf(buf, buf_len, GET, s);
201 snprintf(lbuf, sizeof lbuf, SCCSDIFF, s, filename);
203 } else if (statfailed)
204 fatal("can't find %s\n", filename);
210 * else we can't write to it but it's not under a version
211 * control system, so just proceed.
215 if ((filestat.st_mode & 0222) != 0)
216 /* The owner can write to it. */
217 fatal("file %s seems to be locked "
218 "by somebody else under %s\n",
221 * It might be checked out unlocked. See if
222 * it's safe to check out the default version
226 say("Comparing file %s to default "
230 fatal("can't check out file %s: "
231 "differs from default %s version\n",
235 say("Checking out file %s from %s...\n",
237 if (system(buf) || stat(filename, &filestat))
238 fatal("can't check out file %s from %s\n",
242 filemode = filestat.st_mode;
243 if (!S_ISREG(filemode))
244 fatal("%s is not a normal file--can't patch\n", filename);
245 if ((uint64_t)filestat.st_size > SIZE_MAX) {
246 say("block too large to mmap\n");
249 i_size = (size_t)filestat.st_size;
251 set_hunkmax(); /* make sure dynamic arrays are allocated */
253 return false; /* force plan b because plan a bombed */
255 if ((ifd = open(filename, O_RDONLY)) < 0)
256 pfatal("can't open file %s", filename);
259 i_womp = mmap(NULL, i_size, PROT_READ, MAP_PRIVATE, ifd, 0);
260 if (i_womp == MAP_FAILED) {
261 perror("mmap failed");
272 madvise(i_womp, i_size, MADV_SEQUENTIAL);
274 /* estimate the number of lines */
275 lines_allocated = i_size / 25;
276 if (lines_allocated < 100)
277 lines_allocated = 100;
279 if (!reallocate_lines(&lines_allocated))
282 /* now scan the buffer and build pointer array */
284 i_ptr[iline] = i_womp;
285 /* test for NUL too, to maintain the behavior of the original code */
286 for (s = i_womp, i = 0; i < i_size && *s != '\0'; s++, i++) {
288 if (iline == lines_allocated) {
289 if (!reallocate_lines(&lines_allocated))
292 /* these are NOT NUL terminated */
293 i_ptr[++iline] = s + 1;
296 /* if the last line contains no EOL, append one */
297 if (i_size > 0 && i_womp[i_size - 1] != '\n') {
298 last_line_missing_eol = true;
300 sz = s - i_ptr[iline];
305 munmap(i_womp, i_size);
310 memcpy(p, i_ptr[iline], sz);
313 /* count the extra line and make it point to some valid mem */
314 i_ptr[++iline] = empty_line;
316 last_line_missing_eol = false;
318 input_lines = iline - 1;
320 /* now check for revision, if any */
322 if (revision != NULL) {
323 if (!rev_in_string(i_womp)) {
326 say("Warning: this file doesn't appear "
327 "to be the %s version--patching anyway.\n",
330 fatal("this file doesn't appear to be the "
331 "%s version--aborting.\n",
334 ask("This file doesn't appear to be the "
335 "%s version--patch anyway? [n] ",
341 say("Good. This file appears to be the %s version.\n",
344 return true; /* plan a will work */
347 /* Keep (virtually) nothing in memory. */
350 plan_b(const char *filename)
353 size_t i = 0, j, maxlen = 1;
355 bool found_revision = (revision == NULL);
357 using_plan_a = false;
358 if ((ifp = fopen(filename, "r")) == NULL)
359 pfatal("can't open file %s", filename);
361 if ((tifd = open(TMPINNAME, O_EXCL | O_CREAT | O_WRONLY, 0666)) < 0)
362 pfatal("can't open file %s", TMPINNAME);
363 while (fgets(buf, buf_len, ifp) != NULL) {
364 if (revision != NULL && !found_revision && rev_in_string(buf))
365 found_revision = true;
366 if ((i = strlen(buf)) > maxlen)
367 maxlen = i; /* find longest line */
369 last_line_missing_eol = i > 0 && buf[i - 1] != '\n';
370 if (last_line_missing_eol && maxlen == i)
373 if (revision != NULL) {
374 if (!found_revision) {
377 say("Warning: this file doesn't appear "
378 "to be the %s version--patching anyway.\n",
381 fatal("this file doesn't appear to be the "
382 "%s version--aborting.\n",
385 ask("This file doesn't appear to be the %s "
386 "version--patch anyway? [n] ",
392 say("Good. This file appears to be the %s version.\n",
395 fseek(ifp, 0L, SEEK_SET); /* rewind file */
396 lines_per_buf = BUFFERSIZE / maxlen;
398 tibuf[0] = malloc(BUFFERSIZE + 1);
399 if (tibuf[0] == NULL)
400 fatal("out of memory\n");
401 tibuf[1] = malloc(BUFFERSIZE + 1);
402 if (tibuf[1] == NULL)
403 fatal("out of memory\n");
405 p = tibuf[0] + maxlen * (i % lines_per_buf);
406 if (i % lines_per_buf == 0) /* new block */
407 if (write(tifd, tibuf[0], BUFFERSIZE) < BUFFERSIZE)
408 pfatal("can't write temp file");
409 if (fgets(p, maxlen + 1, ifp) == NULL) {
411 if (i % lines_per_buf != 0)
412 if (write(tifd, tibuf[0], BUFFERSIZE) < BUFFERSIZE)
413 pfatal("can't write temp file");
417 /* These are '\n' terminated strings, so no need to add a NUL */
418 if (j == 0 || p[j - 1] != '\n')
423 if ((tifd = open(TMPINNAME, O_RDONLY)) < 0)
424 pfatal("can't reopen file %s", TMPINNAME);
428 * Fetch a line from the input file, \n terminated, not necessarily \0.
431 ifetch(LINENUM line, int whichbuf)
433 if (line < 1 || line > input_lines) {
434 if (warn_on_invalid_line) {
435 say("No such line %ld in input file, ignoring\n", line);
436 warn_on_invalid_line = false;
443 LINENUM offline = line % lines_per_buf;
444 LINENUM baseline = line - offline;
446 if (tiline[0] == baseline)
448 else if (tiline[1] == baseline)
451 tiline[whichbuf] = baseline;
453 if (lseek(tifd, (off_t) (baseline / lines_per_buf *
454 BUFFERSIZE), SEEK_SET) < 0)
455 pfatal("cannot seek in the temporary input file");
457 if (read(tifd, tibuf[whichbuf], BUFFERSIZE) < 0)
458 pfatal("error reading tmp file %s", TMPINNAME);
460 return tibuf[whichbuf] + (tireclen * offline);
465 * True if the string argument contains the revision number we want.
468 rev_in_string(const char *string)
473 if (revision == NULL)
475 patlen = strlen(revision);
476 if (strnEQ(string, revision, patlen) && isspace((unsigned char)string[patlen]))
478 for (s = string; *s; s++) {
479 if (isspace((unsigned char)*s) && strnEQ(s + 1, revision, patlen) &&
480 isspace((unsigned char)s[patlen + 1])) {