2 * $OpenBSD: inp.c,v 1.34 2006/03/11 19:41:30 otto Exp $
3 * $DragonFly: src/usr.bin/patch/inp.c,v 1.6 2007/09/29 23:11:10 swildner Exp $
4 * $NetBSD: inp.c,v 1.24 2015/07/24 18:56:00 christos Exp $
8 * patch - a program to apply diffs to original files
10 * Copyright 1986, Larry Wall
12 * Redistribution and use in source and binary forms, with or without
13 * modification, are permitted provided that the following condition is met:
14 * 1. Redistributions of source code must retain the above copyright notice,
15 * this condition and the following disclaimer.
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND ANY
18 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
19 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
20 * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
21 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
23 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
24 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 * -C option added in 1998, original code by Marc Espie, based on FreeBSD
33 #include <sys/cdefs.h>
34 __RCSID("$NetBSD: inp.c,v 1.24 2015/07/24 18:56:00 christos Exp $");
36 #include <sys/types.h>
59 /* Input-file-with-indexable-lines abstract type */
61 static off_t i_size
; /* size of the input file */
62 static char *i_womp
; /* plan a buffer for entire file */
63 static char **i_ptr
; /* pointers to lines in i_womp */
64 static char empty_line
[] = { '\0' };
66 static int tifd
= -1; /* plan b virtual string array */
67 static char *tibuf
[2]; /* plan b buffers */
68 static LINENUM tiline
[2] = {-1, -1}; /* 1st line in each buffer */
69 static LINENUM lines_per_buf
; /* how many lines per buffer */
70 static int tireclen
; /* length of records in tmp file */
72 static bool rev_in_string(const char *);
73 static bool reallocate_lines(size_t *);
75 /* returns false if insufficient memory */
76 static bool plan_a(const char *);
78 static void plan_b(const char *);
80 /* New patch--prepare to edit another file. */
90 munmap(i_womp
, i_size
);
94 using_plan_a
= true; /* maybe the next one is smaller */
99 tibuf
[0] = tibuf
[1] = NULL
;
100 tiline
[0] = tiline
[1] = -1;
105 /* Construct the line index, somehow or other. */
108 scan_input(const char *filename
)
110 if (!plan_a(filename
))
113 say("Patching file %s using Plan %s...\n", filename
,
114 (using_plan_a
? "A" : "B"));
119 reallocate_lines(size_t *lines_allocated
)
124 new_size
= *lines_allocated
* 3 / 2;
125 p
= realloc(i_ptr
, (new_size
+ 2) * sizeof(char *));
126 if (p
== NULL
) { /* shucks, it was a near thing */
127 munmap(i_womp
, i_size
);
131 *lines_allocated
= 0;
134 *lines_allocated
= new_size
;
139 /* Try keeping everything in memory. */
142 plan_a(const char *filename
)
144 int ifd
, statfailed
, devnull
, pstat
;
145 char *p
, *s
, lbuf
[MAXLINELEN
];
146 struct stat filestat
;
149 size_t iline
, lines_allocated
;
151 char *argp
[4] = {NULL
};
158 if (filename
== NULL
|| *filename
== '\0')
161 statfailed
= stat(filename
, &filestat
);
162 if (statfailed
&& ok_to_create_file
) {
164 say("(Creating file %s...)\n", filename
);
167 * in check_patch case, we still display `Creating file' even
168 * though we're not. The rule is that -C should be as similar
169 * to normal patch behavior as possible
173 makedirs(filename
, true);
174 close(creat(filename
, 0666));
175 statfailed
= stat(filename
, &filestat
);
177 if (statfailed
&& check_only
)
178 fatal("%s not found, -C mode, can't probe further\n", filename
);
179 /* For nonexistent or read-only files, look for RCS versions. */
181 /* No one can write to it. */
182 (filestat
.st_mode
& 0222) == 0 ||
183 /* I can't write to it. */
184 ((filestat
.st_mode
& 0022) == 0 && filestat
.st_uid
!= getuid())) {
185 char *filebase
, *filedir
;
187 char *tmp_filename1
, *tmp_filename2
;
189 tmp_filename1
= strdup(filename
);
190 tmp_filename2
= strdup(filename
);
191 if (tmp_filename1
== NULL
|| tmp_filename2
== NULL
)
192 fatal("strdupping filename");
194 filebase
= basename(tmp_filename1
);
195 filedir
= dirname(tmp_filename2
);
197 #define try(f, a1, a2, a3) \
198 (snprintf(lbuf, sizeof lbuf, f, a1, a2, a3), stat(lbuf, &cstat) == 0)
201 * else we can't write to it but it's not under a version
202 * control system, so just proceed.
204 if (try("%s/RCS/%s%s", filedir
, filebase
, RCSSUFFIX
) ||
205 try("%s/RCS/%s%s", filedir
, filebase
, "") ||
206 try("%s/%s%s", filedir
, filebase
, RCSSUFFIX
)) {
208 if ((filestat
.st_mode
& 0222) != 0)
209 /* The owner can write to it. */
210 fatal("file %s seems to be locked "
211 "by somebody else under RCS\n",
214 * It might be checked out unlocked. See if
215 * it's safe to check out the default version
219 say("Comparing file %s to default "
220 "RCS version...\n", filename
);
222 switch (pid
= fork()) {
224 fatal("can't fork: %s\n",
227 devnull
= open("/dev/null", O_RDONLY
);
229 fatal("can't open /dev/null: %s",
232 (void)dup2(devnull
, STDOUT_FILENO
);
233 argp
[0] = __UNCONST(RCSDIFF
);
234 argp
[1] = __UNCONST(filename
);
235 execv(RCSDIFF
, argp
);
238 pid
= waitpid(pid
, &pstat
, 0);
239 if (pid
== -1 || WEXITSTATUS(pstat
) != 0) {
240 fatal("can't check out file %s: "
241 "differs from default RCS version\n",
247 say("Checking out file %s from RCS...\n",
250 switch (pid
= fork()) {
252 fatal("can't fork: %s\n", strerror(errno
));
254 argp
[0] = __UNCONST(CHECKOUT
);
255 argp
[1] = __UNCONST("-l");
256 argp
[2] = __UNCONST(filename
);
257 execv(CHECKOUT
, argp
);
260 pid
= waitpid(pid
, &pstat
, 0);
261 if (pid
== -1 || WEXITSTATUS(pstat
) != 0 ||
262 stat(filename
, &filestat
)) {
263 fatal("can't check out file %s from RCS\n",
266 } else if (statfailed
) {
267 fatal("can't find %s\n", filename
);
273 filemode
= filestat
.st_mode
;
274 if (!S_ISREG(filemode
))
275 fatal("%s is not a normal file--can't patch\n", filename
);
276 i_size
= filestat
.st_size
;
278 set_hunkmax(); /* make sure dynamic arrays are allocated */
280 return false; /* force plan b because plan a bombed */
282 if ((uintmax_t)i_size
> (uintmax_t)SIZE_MAX
) {
283 say("block too large to mmap\n");
286 if ((ifd
= open(filename
, O_RDONLY
)) < 0)
287 pfatal("can't open file %s", filename
);
290 i_womp
= mmap(NULL
, i_size
, PROT_READ
, MAP_PRIVATE
, ifd
, 0);
291 if (i_womp
== MAP_FAILED
) {
292 perror("mmap failed");
302 #if !defined(__minix)
304 madvise(i_womp
, i_size
, MADV_SEQUENTIAL
);
305 #endif /* !defined(__minix) */
307 /* estimate the number of lines */
308 lines_allocated
= i_size
/ 25;
309 if (lines_allocated
< 100)
310 lines_allocated
= 100;
312 if (!reallocate_lines(&lines_allocated
))
315 /* now scan the buffer and build pointer array */
317 i_ptr
[iline
] = i_womp
;
318 /* test for NUL too, to maintain the behavior of the original code */
319 for (s
= i_womp
, i
= 0; i
< i_size
&& *s
!= '\0'; s
++, i
++) {
321 if (iline
== lines_allocated
) {
322 if (!reallocate_lines(&lines_allocated
))
325 /* these are NOT NUL terminated */
326 i_ptr
[++iline
] = s
+ 1;
329 /* if the last line contains no EOL, append one */
330 if (i_size
> 0 && i_womp
[i_size
- 1] != '\n') {
331 last_line_missing_eol
= true;
333 sz
= s
- i_ptr
[iline
];
338 munmap(i_womp
, i_size
);
343 memcpy(p
, i_ptr
[iline
], sz
);
346 /* count the extra line and make it point to some valid mem */
347 i_ptr
[++iline
] = empty_line
;
349 last_line_missing_eol
= false;
351 input_lines
= iline
- 1;
353 /* now check for revision, if any */
355 if (revision
!= NULL
) {
356 if (!rev_in_string(i_womp
)) {
359 say("Warning: this file doesn't appear "
360 "to be the %s version--patching anyway.\n",
363 fatal("this file doesn't appear to be the "
364 "%s version--aborting.\n",
367 ask("This file doesn't appear to be the "
368 "%s version--patch anyway? [n] ",
374 say("Good. This file appears to be the %s version.\n",
377 return true; /* plan a will work */
380 /* Keep (virtually) nothing in memory. */
383 plan_b(const char *filename
)
386 size_t i
= 0, j
, maxlen
= 1;
388 bool found_revision
= (revision
== NULL
);
390 using_plan_a
= false;
391 if ((ifp
= fopen(filename
, "r")) == NULL
)
392 pfatal("can't open file %s", filename
);
394 if ((tifd
= open(TMPINNAME
, O_EXCL
| O_CREAT
| O_WRONLY
, 0666)) < 0)
395 pfatal("can't open file %s", TMPINNAME
);
396 while (fgets(buf
, buf_len
, ifp
) != NULL
) {
397 if (revision
!= NULL
&& !found_revision
&& rev_in_string(buf
))
398 found_revision
= true;
399 if ((i
= strlen(buf
)) > maxlen
)
400 maxlen
= i
; /* find longest line */
402 last_line_missing_eol
= i
> 0 && buf
[i
- 1] != '\n';
403 if (last_line_missing_eol
&& maxlen
== i
)
406 if (revision
!= NULL
) {
407 if (!found_revision
) {
410 say("Warning: this file doesn't appear "
411 "to be the %s version--patching anyway.\n",
414 fatal("this file doesn't appear to be the "
415 "%s version--aborting.\n",
418 ask("This file doesn't appear to be the %s "
419 "version--patch anyway? [n] ",
425 say("Good. This file appears to be the %s version.\n",
428 fseek(ifp
, 0L, SEEK_SET
); /* rewind file */
429 lines_per_buf
= BUFFERSIZE
/ maxlen
;
431 tibuf
[0] = malloc(BUFFERSIZE
+ 1);
432 if (tibuf
[0] == NULL
)
433 fatal("out of memory\n");
434 tibuf
[1] = malloc(BUFFERSIZE
+ 1);
435 if (tibuf
[1] == NULL
)
436 fatal("out of memory\n");
438 p
= tibuf
[0] + maxlen
* (i
% lines_per_buf
);
439 if (i
% lines_per_buf
== 0) /* new block */
440 if (write(tifd
, tibuf
[0], BUFFERSIZE
) < BUFFERSIZE
)
441 pfatal("can't write temp file");
442 if (fgets(p
, maxlen
+ 1, ifp
) == NULL
) {
444 if (i
% lines_per_buf
!= 0)
445 if (write(tifd
, tibuf
[0], BUFFERSIZE
) < BUFFERSIZE
)
446 pfatal("can't write temp file");
450 /* These are '\n' terminated strings, so no need to add a NUL */
451 if (j
== 0 || p
[j
- 1] != '\n')
456 if ((tifd
= open(TMPINNAME
, O_RDONLY
)) < 0)
457 pfatal("can't reopen file %s", TMPINNAME
);
461 * Fetch a line from the input file, \n terminated, not necessarily \0.
464 ifetch(LINENUM line
, int whichbuf
)
466 if (line
< 1 || line
> input_lines
) {
467 if (warn_on_invalid_line
) {
468 say("No such line %ld in input file, ignoring\n", line
);
469 warn_on_invalid_line
= false;
476 LINENUM offline
= line
% lines_per_buf
;
477 LINENUM baseline
= line
- offline
;
479 if (tiline
[0] == baseline
)
481 else if (tiline
[1] == baseline
)
484 tiline
[whichbuf
] = baseline
;
486 if (lseek(tifd
, (off_t
) (baseline
/ lines_per_buf
*
487 BUFFERSIZE
), SEEK_SET
) < 0)
488 pfatal("cannot seek in the temporary input file");
490 if (read(tifd
, tibuf
[whichbuf
], BUFFERSIZE
) < 0)
491 pfatal("error reading tmp file %s", TMPINNAME
);
493 return tibuf
[whichbuf
] + (tireclen
* offline
);
498 * True if the string argument contains the revision number we want.
501 rev_in_string(const char *string
)
506 if (revision
== NULL
)
508 patlen
= strlen(revision
);
509 if (strnEQ(string
, revision
, patlen
) && isspace((unsigned char)string
[patlen
]))
511 for (s
= string
; *s
; s
++) {
512 if (isspace((unsigned char)*s
) && strnEQ(s
+ 1, revision
, patlen
) &&
513 isspace((unsigned char)s
[patlen
+ 1])) {