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.19 2008/09/19 18:33:34 joerg 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>
35 #include <sys/types.h>
56 /* Input-file-with-indexable-lines abstract type */
58 static off_t i_size
; /* size of the input file */
59 static char *i_womp
; /* plan a buffer for entire file */
60 static char **i_ptr
; /* pointers to lines in i_womp */
61 static char empty_line
[] = { '\0' };
63 static int tifd
= -1; /* plan b virtual string array */
64 static char *tibuf
[2]; /* plan b buffers */
65 static LINENUM tiline
[2] = {-1, -1}; /* 1st line in each buffer */
66 static LINENUM lines_per_buf
; /* how many lines per buffer */
67 static int tireclen
; /* length of records in tmp file */
69 static bool rev_in_string(const char *);
70 static bool reallocate_lines(size_t *);
72 /* returns false if insufficient memory */
73 static bool plan_a(const char *);
75 static void plan_b(const char *);
77 static int readfile(int fd
, char *buf
, size_t s
)
85 if((nread
= read(fd
, buf
, ntoread
)) < 0) {
95 /* New patch--prepare to edit another file. */
104 if (i_womp
!= NULL
) {
106 munmap(i_womp
, i_size
);
113 using_plan_a
= true; /* maybe the next one is smaller */
118 tibuf
[0] = tibuf
[1] = NULL
;
119 tiline
[0] = tiline
[1] = -1;
124 /* Construct the line index, somehow or other. */
127 scan_input(const char *filename
)
129 if (!plan_a(filename
))
132 say("Patching file %s using Plan %s...\n", filename
,
133 (using_plan_a
? "A" : "B"));
138 reallocate_lines(size_t *lines_allocated
)
143 new_size
= *lines_allocated
* 3 / 2;
144 p
= realloc(i_ptr
, (new_size
+ 2) * sizeof(char *));
145 if (p
== NULL
) { /* shucks, it was a near thing */
147 munmap(i_womp
, i_size
);
154 *lines_allocated
= 0;
157 *lines_allocated
= new_size
;
162 /* Try keeping everything in memory. */
165 plan_a(const char *filename
)
168 char *p
, *s
, lbuf
[MAXLINELEN
];
169 struct stat filestat
;
172 size_t iline
, lines_allocated
;
179 if (filename
== NULL
|| *filename
== '\0')
182 statfailed
= stat(filename
, &filestat
);
183 if (statfailed
&& ok_to_create_file
) {
185 say("(Creating file %s...)\n", filename
);
188 * in check_patch case, we still display `Creating file' even
189 * though we're not. The rule is that -C should be as similar
190 * to normal patch behavior as possible
194 makedirs(filename
, true);
195 close(creat(filename
, 0666));
196 statfailed
= stat(filename
, &filestat
);
198 if (statfailed
&& check_only
)
199 fatal("%s not found, -C mode, can't probe further\n", filename
);
200 /* For nonexistent or read-only files, look for RCS or SCCS versions. */
202 /* No one can write to it. */
203 (filestat
.st_mode
& 0222) == 0 ||
204 /* I can't write to it. */
205 ((filestat
.st_mode
& 0022) == 0 && filestat
.st_uid
!= getuid())) {
206 const char *cs
= NULL
, *filebase
, *filedir
;
208 char *tmp_filename1
, *tmp_filename2
;
210 tmp_filename1
= strdup(filename
);
211 tmp_filename2
= strdup(filename
);
212 if (tmp_filename1
== NULL
|| tmp_filename2
== NULL
)
213 fatal("strdupping filename");
214 filebase
= basename(tmp_filename1
);
215 filedir
= dirname(tmp_filename2
);
217 /* Leave room in lbuf for the diff command. */
220 #define try(f, a1, a2, a3) \
221 (snprintf(s, sizeof lbuf - 20, f, a1, a2, a3), stat(s, &cstat) == 0)
223 if (try("%s/RCS/%s%s", filedir
, filebase
, RCSSUFFIX
) ||
224 try("%s/RCS/%s%s", filedir
, filebase
, "") ||
225 try("%s/%s%s", filedir
, filebase
, RCSSUFFIX
)) {
226 snprintf(buf
, buf_len
, CHECKOUT
, filename
);
227 snprintf(lbuf
, sizeof lbuf
, RCSDIFF
, filename
);
229 } else if (try("%s/SCCS/%s%s", filedir
, SCCSPREFIX
, filebase
) ||
230 try("%s/%s%s", filedir
, SCCSPREFIX
, filebase
)) {
231 snprintf(buf
, buf_len
, GET
, s
);
232 snprintf(lbuf
, sizeof lbuf
, SCCSDIFF
, s
, filename
);
234 } else if (statfailed
)
235 fatal("can't find %s\n", filename
);
241 * else we can't write to it but it's not under a version
242 * control system, so just proceed.
246 if ((filestat
.st_mode
& 0222) != 0)
247 /* The owner can write to it. */
248 fatal("file %s seems to be locked "
249 "by somebody else under %s\n",
252 * It might be checked out unlocked. See if
253 * it's safe to check out the default version
257 say("Comparing file %s to default "
261 fatal("can't check out file %s: "
262 "differs from default %s version\n",
266 say("Checking out file %s from %s...\n",
268 if (system(buf
) || stat(filename
, &filestat
))
269 fatal("can't check out file %s from %s\n",
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 */
283 if (i_size
> SIZE_MAX
) {
284 say("block too large to mmap\n");
288 if ((ifd
= open(filename
, O_RDONLY
)) < 0)
289 pfatal("can't open file %s", filename
);
292 i_womp
= mmap(NULL
, i_size
, PROT_READ
, MAP_PRIVATE
, ifd
, 0);
293 if (i_womp
== MAP_FAILED
) {
294 perror("mmap failed");
300 i_womp
= malloc(i_size
);
301 if(i_size
&& i_womp
== NULL
) {
302 fprintf(stderr
, "Malloc failed.\n");
307 if(readfile(ifd
, i_womp
, i_size
) < 0) {
308 perror("Readfile failed.");
318 madvise(i_womp
, i_size
, MADV_SEQUENTIAL
);
321 /* estimate the number of lines */
322 lines_allocated
= i_size
/ 25;
323 if (lines_allocated
< 100)
324 lines_allocated
= 100;
326 if (!reallocate_lines(&lines_allocated
))
329 /* now scan the buffer and build pointer array */
331 i_ptr
[iline
] = i_womp
;
332 /* test for NUL too, to maintain the behavior of the original code */
333 for (s
= i_womp
, i
= 0; i
< i_size
&& *s
!= '\0'; s
++, i
++) {
335 if (iline
== lines_allocated
) {
336 if (!reallocate_lines(&lines_allocated
))
339 /* these are NOT NUL terminated */
340 i_ptr
[++iline
] = s
+ 1;
343 /* if the last line contains no EOL, append one */
344 if (i_size
> 0 && i_womp
[i_size
- 1] != '\n') {
345 last_line_missing_eol
= true;
347 sz
= s
- i_ptr
[iline
];
353 munmap(i_womp
, i_size
);
361 memcpy(p
, i_ptr
[iline
], sz
);
364 /* count the extra line and make it point to some valid mem */
365 i_ptr
[++iline
] = empty_line
;
367 last_line_missing_eol
= false;
369 input_lines
= iline
- 1;
371 /* now check for revision, if any */
373 if (revision
!= NULL
) {
374 if (!rev_in_string(i_womp
)) {
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 "
386 "%s version--patch anyway? [n] ",
392 say("Good. This file appears to be the %s version.\n",
395 return true; /* plan a will work */
398 /* Keep (virtually) nothing in memory. */
401 plan_b(const char *filename
)
404 size_t i
= 0, j
, maxlen
= 1;
406 bool found_revision
= (revision
== NULL
);
408 using_plan_a
= false;
409 if ((ifp
= fopen(filename
, "r")) == NULL
)
410 pfatal("can't open file %s", filename
);
412 if ((tifd
= open(TMPINNAME
, O_EXCL
| O_CREAT
| O_WRONLY
, 0666)) < 0)
413 pfatal("can't open file %s", TMPINNAME
);
414 while (fgets(buf
, buf_len
, ifp
) != NULL
) {
415 if (revision
!= NULL
&& !found_revision
&& rev_in_string(buf
))
416 found_revision
= true;
417 if ((i
= strlen(buf
)) > maxlen
)
418 maxlen
= i
; /* find longest line */
420 last_line_missing_eol
= i
> 0 && buf
[i
- 1] != '\n';
421 if (last_line_missing_eol
&& maxlen
== i
)
424 if (revision
!= NULL
) {
425 if (!found_revision
) {
428 say("Warning: this file doesn't appear "
429 "to be the %s version--patching anyway.\n",
432 fatal("this file doesn't appear to be the "
433 "%s version--aborting.\n",
436 ask("This file doesn't appear to be the %s "
437 "version--patch anyway? [n] ",
443 say("Good. This file appears to be the %s version.\n",
446 fseek(ifp
, 0L, SEEK_SET
); /* rewind file */
447 lines_per_buf
= BUFFERSIZE
/ maxlen
;
449 tibuf
[0] = malloc(BUFFERSIZE
+ 1);
450 if (tibuf
[0] == NULL
)
451 fatal("out of memory\n");
452 tibuf
[1] = malloc(BUFFERSIZE
+ 1);
453 if (tibuf
[1] == NULL
)
454 fatal("out of memory\n");
456 p
= tibuf
[0] + maxlen
* (i
% lines_per_buf
);
457 if (i
% lines_per_buf
== 0) /* new block */
458 if (write(tifd
, tibuf
[0], BUFFERSIZE
) < BUFFERSIZE
)
459 pfatal("can't write temp file");
460 if (fgets(p
, maxlen
+ 1, ifp
) == NULL
) {
462 if (i
% lines_per_buf
!= 0)
463 if (write(tifd
, tibuf
[0], BUFFERSIZE
) < BUFFERSIZE
)
464 pfatal("can't write temp file");
468 /* These are '\n' terminated strings, so no need to add a NUL */
469 if (j
== 0 || p
[j
- 1] != '\n')
474 if ((tifd
= open(TMPINNAME
, O_RDONLY
)) < 0)
475 pfatal("can't reopen file %s", TMPINNAME
);
479 * Fetch a line from the input file, \n terminated, not necessarily \0.
482 ifetch(LINENUM line
, int whichbuf
)
484 if (line
< 1 || line
> input_lines
) {
485 if (warn_on_invalid_line
) {
486 say("No such line %ld in input file, ignoring\n", line
);
487 warn_on_invalid_line
= false;
494 LINENUM offline
= line
% lines_per_buf
;
495 LINENUM baseline
= line
- offline
;
497 if (tiline
[0] == baseline
)
499 else if (tiline
[1] == baseline
)
502 tiline
[whichbuf
] = baseline
;
504 if (lseek(tifd
, (off_t
) (baseline
/ lines_per_buf
*
505 BUFFERSIZE
), SEEK_SET
) < 0)
506 pfatal("cannot seek in the temporary input file");
508 if (read(tifd
, tibuf
[whichbuf
], BUFFERSIZE
) < 0)
509 pfatal("error reading tmp file %s", TMPINNAME
);
511 return tibuf
[whichbuf
] + (tireclen
* offline
);
516 * True if the string argument contains the revision number we want.
519 rev_in_string(const char *string
)
524 if (revision
== NULL
)
526 patlen
= strlen(revision
);
527 if (strnEQ(string
, revision
, patlen
) && isspace((unsigned char)string
[patlen
]))
529 for (s
= string
; *s
; s
++) {
530 if (isspace((unsigned char)*s
) && strnEQ(s
+ 1, revision
, patlen
) &&
531 isspace((unsigned char)s
[patlen
+ 1])) {