coverity appeasement
[minix.git] / commands / patch / inp.c
blobe104cb12242dfd39c251330f1077d4278de9b672
1 /*
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 $
5 */
7 /*
8 * patch - a program to apply diffs to original files
9 *
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
27 * SUCH DAMAGE.
29 * -C option added in 1998, original code by Marc Espie, based on FreeBSD
30 * behaviour
33 #include <sys/cdefs.h>
35 #include <sys/types.h>
36 #include <sys/file.h>
37 #include <sys/stat.h>
38 #include <sys/mman.h>
40 #include <ctype.h>
41 #include <libgen.h>
42 #include <limits.h>
43 #include <stddef.h>
44 #include <stdio.h>
45 #include <stdlib.h>
46 #include <string.h>
47 #include <unistd.h>
48 #include <fcntl.h>
50 #include "common.h"
51 #include "util.h"
52 #include "pch.h"
53 #include "inp.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)
79 int ntoread, nread;
81 ntoread = s;
82 nread = 0;
84 while(ntoread > 0) {
85 if((nread = read(fd, buf, ntoread)) < 0) {
86 return nread;
88 buf += nread;
89 ntoread -= nread;
92 return 0;
95 /* New patch--prepare to edit another file. */
97 void
98 re_input(void)
100 if (using_plan_a) {
101 i_size = 0;
102 free(i_ptr);
103 i_ptr = NULL;
104 if (i_womp != NULL) {
105 #ifndef __minix
106 munmap(i_womp, i_size);
107 #else
108 free(i_womp);
109 #endif
110 i_womp = NULL;
112 } else {
113 using_plan_a = true; /* maybe the next one is smaller */
114 close(tifd);
115 tifd = -1;
116 free(tibuf[0]);
117 free(tibuf[1]);
118 tibuf[0] = tibuf[1] = NULL;
119 tiline[0] = tiline[1] = -1;
120 tireclen = 0;
124 /* Construct the line index, somehow or other. */
126 void
127 scan_input(const char *filename)
129 if (!plan_a(filename))
130 plan_b(filename);
131 if (verbose) {
132 say("Patching file %s using Plan %s...\n", filename,
133 (using_plan_a ? "A" : "B"));
137 static bool
138 reallocate_lines(size_t *lines_allocated)
140 char **p;
141 size_t new_size;
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 */
146 #ifndef __minix
147 munmap(i_womp, i_size);
148 #else
149 free(i_womp);
150 #endif
151 i_womp = NULL;
152 free(i_ptr);
153 i_ptr = NULL;
154 *lines_allocated = 0;
155 return false;
157 *lines_allocated = new_size;
158 i_ptr = p;
159 return true;
162 /* Try keeping everything in memory. */
164 static bool
165 plan_a(const char *filename)
167 int ifd, statfailed;
168 char *p, *s, lbuf[MAXLINELEN];
169 struct stat filestat;
170 off_t i;
171 ptrdiff_t sz;
172 size_t iline, lines_allocated;
174 #ifdef DEBUGGING
175 if (debug & 8)
176 return false;
177 #endif
179 if (filename == NULL || *filename == '\0')
180 return false;
182 statfailed = stat(filename, &filestat);
183 if (statfailed && ok_to_create_file) {
184 if (verbose)
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
192 if (check_only)
193 return true;
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. */
201 if (statfailed ||
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;
207 struct stat cstat;
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. */
218 s = lbuf + 20;
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);
228 cs = "RCS";
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);
233 cs = "SCCS";
234 } else if (statfailed)
235 fatal("can't find %s\n", filename);
237 free(tmp_filename1);
238 free(tmp_filename2);
241 * else we can't write to it but it's not under a version
242 * control system, so just proceed.
244 if (cs) {
245 if (!statfailed) {
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",
250 filename, cs);
252 * It might be checked out unlocked. See if
253 * it's safe to check out the default version
254 * locked.
256 if (verbose)
257 say("Comparing file %s to default "
258 "%s version...\n",
259 filename, cs);
260 if (system(lbuf))
261 fatal("can't check out file %s: "
262 "differs from default %s version\n",
263 filename, cs);
265 if (verbose)
266 say("Checking out file %s from %s...\n",
267 filename, cs);
268 if (system(buf) || stat(filename, &filestat))
269 fatal("can't check out file %s from %s\n",
270 filename, cs);
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;
277 if (out_of_mem) {
278 set_hunkmax(); /* make sure dynamic arrays are allocated */
279 out_of_mem = false;
280 return false; /* force plan b because plan a bombed */
282 #ifndef __minix
283 if (i_size > SIZE_MAX) {
284 say("block too large to mmap\n");
285 return false;
287 #endif
288 if ((ifd = open(filename, O_RDONLY)) < 0)
289 pfatal("can't open file %s", filename);
291 #ifndef __minix
292 i_womp = mmap(NULL, i_size, PROT_READ, MAP_PRIVATE, ifd, 0);
293 if (i_womp == MAP_FAILED) {
294 perror("mmap failed");
295 i_womp = NULL;
296 close(ifd);
297 return false;
299 #else
300 i_womp = malloc(i_size);
301 if(i_size && i_womp == NULL) {
302 fprintf(stderr, "Malloc failed.\n");
303 i_womp = NULL;
304 close(ifd);
305 return false;
307 if(readfile(ifd, i_womp, i_size) < 0) {
308 perror("Readfile failed.");
309 i_womp = NULL;
310 close(ifd);
311 return false;
313 #endif
315 close(ifd);
316 #ifndef __minix
317 if (i_size)
318 madvise(i_womp, i_size, MADV_SEQUENTIAL);
319 #endif
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))
327 return false;
329 /* now scan the buffer and build pointer array */
330 iline = 1;
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++) {
334 if (*s == '\n') {
335 if (iline == lines_allocated) {
336 if (!reallocate_lines(&lines_allocated))
337 return false;
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;
346 /* fix last line */
347 sz = s - i_ptr[iline];
348 p = malloc(sz + 1);
349 if (p == NULL) {
350 free(i_ptr);
351 i_ptr = NULL;
352 #ifndef __minix
353 munmap(i_womp, i_size);
354 #else
355 free(i_womp);
356 #endif
357 i_womp = NULL;
358 return false;
361 memcpy(p, i_ptr[iline], sz);
362 p[sz] = '\n';
363 i_ptr[iline] = p;
364 /* count the extra line and make it point to some valid mem */
365 i_ptr[++iline] = empty_line;
366 } else
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)) {
375 if (force) {
376 if (verbose)
377 say("Warning: this file doesn't appear "
378 "to be the %s version--patching anyway.\n",
379 revision);
380 } else if (batch) {
381 fatal("this file doesn't appear to be the "
382 "%s version--aborting.\n",
383 revision);
384 } else {
385 ask("This file doesn't appear to be the "
386 "%s version--patch anyway? [n] ",
387 revision);
388 if (*buf != 'y')
389 fatal("aborted\n");
391 } else if (verbose)
392 say("Good. This file appears to be the %s version.\n",
393 revision);
395 return true; /* plan a will work */
398 /* Keep (virtually) nothing in memory. */
400 static void
401 plan_b(const char *filename)
403 FILE *ifp;
404 size_t i = 0, j, maxlen = 1;
405 char *p;
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);
411 unlink(TMPINNAME);
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)
422 maxlen++;
424 if (revision != NULL) {
425 if (!found_revision) {
426 if (force) {
427 if (verbose)
428 say("Warning: this file doesn't appear "
429 "to be the %s version--patching anyway.\n",
430 revision);
431 } else if (batch) {
432 fatal("this file doesn't appear to be the "
433 "%s version--aborting.\n",
434 revision);
435 } else {
436 ask("This file doesn't appear to be the %s "
437 "version--patch anyway? [n] ",
438 revision);
439 if (*buf != 'y')
440 fatal("aborted\n");
442 } else if (verbose)
443 say("Good. This file appears to be the %s version.\n",
444 revision);
446 fseek(ifp, 0L, SEEK_SET); /* rewind file */
447 lines_per_buf = BUFFERSIZE / maxlen;
448 tireclen = 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");
455 for (i = 1;; i++) {
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) {
461 input_lines = i - 1;
462 if (i % lines_per_buf != 0)
463 if (write(tifd, tibuf[0], BUFFERSIZE) < BUFFERSIZE)
464 pfatal("can't write temp file");
465 break;
467 j = strlen(p);
468 /* These are '\n' terminated strings, so no need to add a NUL */
469 if (j == 0 || p[j - 1] != '\n')
470 p[j] = '\n';
472 fclose(ifp);
473 close(tifd);
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.
481 char *
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;
489 return NULL;
491 if (using_plan_a)
492 return i_ptr[line];
493 else {
494 LINENUM offline = line % lines_per_buf;
495 LINENUM baseline = line - offline;
497 if (tiline[0] == baseline)
498 whichbuf = 0;
499 else if (tiline[1] == baseline)
500 whichbuf = 1;
501 else {
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.
518 static bool
519 rev_in_string(const char *string)
521 const char *s;
522 size_t patlen;
524 if (revision == NULL)
525 return true;
526 patlen = strlen(revision);
527 if (strnEQ(string, revision, patlen) && isspace((unsigned char)string[patlen]))
528 return true;
529 for (s = string; *s; s++) {
530 if (isspace((unsigned char)*s) && strnEQ(s + 1, revision, patlen) &&
531 isspace((unsigned char)s[patlen + 1])) {
532 return true;
535 return false;