- Take back the commit from Oct. 1, 2004 since FreeBSD has changed their
[dragonfly.git] / usr.bin / patch / inp.c
CommitLineData
48d201a5
JS
1/*
2 * $OpenBSD: inp.c,v 1.32 2004/08/05 21:47:24 deraadt Exp $
f7e25d55 3 * $DragonFly: src/usr.bin/patch/inp.c,v 1.3 2004/12/26 15:55:23 swildner Exp $
48d201a5
JS
4 */
5
6/*
7 * patch - a program to apply diffs to original files
8 *
9 * Copyright 1986, Larry Wall
10 *
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following condition is met:
13 * 1. Redistributions of source code must retain the above copyright notice,
14 * this condition and the following disclaimer.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
20 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
22 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
23 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26 * SUCH DAMAGE.
27 *
28 * -C option added in 1998, original code by Marc Espie, based on FreeBSD
29 * behaviour
30 */
31
32#include <sys/types.h>
33#include <sys/file.h>
34#include <sys/stat.h>
35#include <sys/mman.h>
36
37#include <ctype.h>
38#include <libgen.h>
39#include <limits.h>
40#include <stddef.h>
41#include <stdio.h>
42#include <stdlib.h>
43#include <string.h>
44#include <unistd.h>
45
46#include "common.h"
47#include "util.h"
48#include "pch.h"
49#include "inp.h"
50
51
52/* Input-file-with-indexable-lines abstract type */
53
54static off_t i_size; /* size of the input file */
55static char *i_womp; /* plan a buffer for entire file */
56static char **i_ptr; /* pointers to lines in i_womp */
f9ea5d32 57static char empty_line[] = { '\0' };
48d201a5
JS
58
59static int tifd = -1; /* plan b virtual string array */
60static char *tibuf[2]; /* plan b buffers */
61static LINENUM tiline[2] = {-1, -1}; /* 1st line in each buffer */
62static LINENUM lines_per_buf; /* how many lines per buffer */
63static int tireclen; /* length of records in tmp file */
64
65static bool rev_in_string(const char *);
66static bool reallocate_lines(size_t *);
67
68/* returns false if insufficient memory */
69static bool plan_a(const char *);
70
71static void plan_b(const char *);
72
73/* New patch--prepare to edit another file. */
74
75void
76re_input(void)
77{
78 if (using_plan_a) {
79 i_size = 0;
80 free(i_ptr);
81 i_ptr = NULL;
82 if (i_womp != NULL) {
83 munmap(i_womp, i_size);
84 i_womp = NULL;
85 }
86 } else {
87 using_plan_a = true; /* maybe the next one is smaller */
88 close(tifd);
89 tifd = -1;
90 free(tibuf[0]);
91 free(tibuf[1]);
92 tibuf[0] = tibuf[1] = NULL;
93 tiline[0] = tiline[1] = -1;
94 tireclen = 0;
95 }
96}
97
98/* Constuct the line index, somehow or other. */
99
100void
101scan_input(const char *filename)
102{
103 if (!plan_a(filename))
104 plan_b(filename);
105 if (verbose) {
106 say("Patching file %s using Plan %s...\n", filename,
107 (using_plan_a ? "A" : "B"));
108 }
109}
110
111static bool
112reallocate_lines(size_t *lines_allocated)
113{
114 char **p;
115 size_t new_size;
116
117 new_size = *lines_allocated * 3 / 2;
118 p = realloc(i_ptr, (new_size + 2) * sizeof(char *));
119 if (p == NULL) { /* shucks, it was a near thing */
120 munmap(i_womp, i_size);
121 i_womp = NULL;
122 free(i_ptr);
123 i_ptr = NULL;
124 *lines_allocated = 0;
125 return false;
126 }
127 *lines_allocated = new_size;
128 i_ptr = p;
129 return true;
130}
131
132/* Try keeping everything in memory. */
133
134static bool
135plan_a(const char *filename)
136{
137 int ifd, statfailed;
138 char *p, *s, lbuf[MAXLINELEN];
139 LINENUM iline;
140 struct stat filestat;
141 off_t i;
142 ptrdiff_t sz;
143 size_t lines_allocated;
144
145#ifdef DEBUGGING
146 if (debug & 8)
147 return false;
148#endif
149
150 if (filename == NULL || *filename == '\0')
151 return false;
152
153 statfailed = stat(filename, &filestat);
154 if (statfailed && ok_to_create_file) {
155 if (verbose)
156 say("(Creating file %s...)\n", filename);
157
158 /*
159 * in check_patch case, we still display `Creating file' even
160 * though we're not. The rule is that -C should be as similar
161 * to normal patch behavior as possible
162 */
163 if (check_only)
164 return true;
165 makedirs(filename, true);
166 close(creat(filename, 0666));
167 statfailed = stat(filename, &filestat);
168 }
169 if (statfailed && check_only)
170 fatal("%s not found, -C mode, can't probe further\n", filename);
171 /* For nonexistent or read-only files, look for RCS or SCCS versions. */
172 if (statfailed ||
173 /* No one can write to it. */
174 (filestat.st_mode & 0222) == 0 ||
175 /* I can't write to it. */
176 ((filestat.st_mode & 0022) == 0 && filestat.st_uid != getuid())) {
f9ea5d32 177 const char *cs = NULL, *filebase, *filedir;
48d201a5
JS
178 struct stat cstat;
179
180 filebase = basename(filename);
181 filedir = dirname(filename);
182
183 /* Leave room in lbuf for the diff command. */
184 s = lbuf + 20;
185
186#define try(f, a1, a2, a3) \
187 (snprintf(s, sizeof lbuf - 20, f, a1, a2, a3), stat(s, &cstat) == 0)
188
189 if (try("%s/RCS/%s%s", filedir, filebase, RCSSUFFIX) ||
190 try("%s/RCS/%s%s", filedir, filebase, "") ||
191 try("%s/%s%s", filedir, filebase, RCSSUFFIX)) {
192 snprintf(buf, sizeof buf, CHECKOUT, filename);
193 snprintf(lbuf, sizeof lbuf, RCSDIFF, filename);
194 cs = "RCS";
195 } else if (try("%s/SCCS/%s%s", filedir, SCCSPREFIX, filebase) ||
196 try("%s/%s%s", filedir, SCCSPREFIX, filebase)) {
197 snprintf(buf, sizeof buf, GET, s);
198 snprintf(lbuf, sizeof lbuf, SCCSDIFF, s, filename);
199 cs = "SCCS";
200 } else if (statfailed)
201 fatal("can't find %s\n", filename);
202 /*
203 * else we can't write to it but it's not under a version
204 * control system, so just proceed.
205 */
206 if (cs) {
207 if (!statfailed) {
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 %s\n",
212 filename, cs);
213 /*
214 * It might be checked out unlocked. See if
215 * it's safe to check out the default version
216 * locked.
217 */
218 if (verbose)
219 say("Comparing file %s to default "
220 "%s version...\n",
221 filename, cs);
222 if (system(lbuf))
223 fatal("can't check out file %s: "
224 "differs from default %s version\n",
225 filename, cs);
226 }
227 if (verbose)
228 say("Checking out file %s from %s...\n",
229 filename, cs);
230 if (system(buf) || stat(filename, &filestat))
231 fatal("can't check out file %s from %s\n",
232 filename, cs);
233 }
234 }
235 filemode = filestat.st_mode;
236 if (!S_ISREG(filemode))
237 fatal("%s is not a normal file--can't patch\n", filename);
238 i_size = filestat.st_size;
239 if (out_of_mem) {
240 set_hunkmax(); /* make sure dynamic arrays are allocated */
241 out_of_mem = false;
242 return false; /* force plan b because plan a bombed */
243 }
244 if (i_size > SIZE_MAX) {
245 say("block too large to mmap\n");
246 return false;
247 }
248 if ((ifd = open(filename, O_RDONLY)) < 0)
249 pfatal("can't open file %s", filename);
250
251 i_womp = mmap(NULL, i_size, PROT_READ, MAP_PRIVATE, ifd, 0);
252 if (i_womp == MAP_FAILED) {
253 perror("mmap failed");
254 i_womp = NULL;
255 close(ifd);
256 return false;
257 }
258
259 close(ifd);
260 if (i_size)
261 madvise(i_womp, i_size, MADV_SEQUENTIAL);
262
263 /* estimate the number of lines */
264 lines_allocated = i_size / 25;
265 if (lines_allocated < 100)
266 lines_allocated = 100;
267
268 if (!reallocate_lines(&lines_allocated))
269 return false;
270
271 /* now scan the buffer and build pointer array */
272 iline = 1;
273 i_ptr[iline] = i_womp;
274 /* test for NUL too, to maintain the behavior of the original code */
275 for (s = i_womp, i = 0; i < i_size && *s != '\0'; s++, i++) {
276 if (*s == '\n') {
277 if (iline == (LINENUM)lines_allocated) {
278 if (!reallocate_lines(&lines_allocated))
279 return false;
280 }
281 /* these are NOT NUL terminated */
282 i_ptr[++iline] = s + 1;
283 }
284 }
285 /* if the last line contains no EOL, append one */
286 if (i_size > 0 && i_womp[i_size - 1] != '\n') {
287 last_line_missing_eol = true;
288 /* fix last line */
289 sz = s - i_ptr[iline];
290 p = malloc(sz + 1);
291 if (p == NULL) {
292 free(i_ptr);
293 i_ptr = NULL;
294 munmap(i_womp, i_size);
295 i_womp = NULL;
296 return false;
297 }
298
299 memcpy(p, i_ptr[iline], sz);
300 p[sz] = '\n';
301 i_ptr[iline] = p;
302 /* count the extra line and make it point to some valid mem */
f9ea5d32 303 i_ptr[++iline] = empty_line;
48d201a5
JS
304 } else
305 last_line_missing_eol = false;
306
307 input_lines = iline - 1;
308
309 /* now check for revision, if any */
310
311 if (revision != NULL) {
312 if (!rev_in_string(i_womp)) {
313 if (force) {
314 if (verbose)
315 say("Warning: this file doesn't appear "
316 "to be the %s version--patching anyway.\n",
317 revision);
318 } else if (batch) {
319 fatal("this file doesn't appear to be the "
320 "%s version--aborting.\n",
321 revision);
322 } else {
323 ask("This file doesn't appear to be the "
324 "%s version--patch anyway? [n] ",
325 revision);
326 if (*buf != 'y')
327 fatal("aborted\n");
328 }
329 } else if (verbose)
330 say("Good. This file appears to be the %s version.\n",
331 revision);
332 }
333 return true; /* plan a will work */
334}
335
336/* Keep (virtually) nothing in memory. */
337
338static void
339plan_b(const char *filename)
340{
341 FILE *ifp;
342 int i = 0, j, maxlen = 1;
343 char *p;
344 bool found_revision = (revision == NULL);
345
346 using_plan_a = false;
347 if ((ifp = fopen(filename, "r")) == NULL)
348 pfatal("can't open file %s", filename);
f7e25d55 349 unlink(TMPINNAME);
48d201a5
JS
350 if ((tifd = open(TMPINNAME, O_EXCL | O_CREAT | O_WRONLY, 0666)) < 0)
351 pfatal("can't open file %s", TMPINNAME);
352 while (fgets(buf, sizeof buf, ifp) != NULL) {
353 if (revision != NULL && !found_revision && rev_in_string(buf))
354 found_revision = true;
355 if ((i = strlen(buf)) > maxlen)
356 maxlen = i; /* find longest line */
357 }
358 last_line_missing_eol = i > 0 && buf[i - 1] != '\n';
359 if (last_line_missing_eol && maxlen == i)
360 maxlen++;
361
362 if (revision != NULL) {
363 if (!found_revision) {
364 if (force) {
365 if (verbose)
366 say("Warning: this file doesn't appear "
367 "to be the %s version--patching anyway.\n",
368 revision);
369 } else if (batch) {
370 fatal("this file doesn't appear to be the "
371 "%s version--aborting.\n",
372 revision);
373 } else {
374 ask("This file doesn't appear to be the %s "
375 "version--patch anyway? [n] ",
376 revision);
377 if (*buf != 'y')
378 fatal("aborted\n");
379 }
380 } else if (verbose)
381 say("Good. This file appears to be the %s version.\n",
382 revision);
383 }
384 fseek(ifp, 0L, SEEK_SET); /* rewind file */
385 lines_per_buf = BUFFERSIZE / maxlen;
386 tireclen = maxlen;
387 tibuf[0] = malloc(BUFFERSIZE + 1);
388 if (tibuf[0] == NULL)
389 fatal("out of memory\n");
390 tibuf[1] = malloc(BUFFERSIZE + 1);
391 if (tibuf[1] == NULL)
392 fatal("out of memory\n");
393 for (i = 1;; i++) {
394 p = tibuf[0] + maxlen * (i % lines_per_buf);
395 if (i % lines_per_buf == 0) /* new block */
396 if (write(tifd, tibuf[0], BUFFERSIZE) < BUFFERSIZE)
397 pfatal("can't write temp file");
398 if (fgets(p, maxlen + 1, ifp) == NULL) {
399 input_lines = i - 1;
400 if (i % lines_per_buf != 0)
401 if (write(tifd, tibuf[0], BUFFERSIZE) < BUFFERSIZE)
402 pfatal("can't write temp file");
403 break;
404 }
405 j = strlen(p);
406 /* These are '\n' terminated strings, so no need to add a NUL */
407 if (j == 0 || p[j - 1] != '\n')
408 p[j] = '\n';
409 }
410 fclose(ifp);
411 close(tifd);
412 if ((tifd = open(TMPINNAME, O_RDONLY)) < 0)
413 pfatal("can't reopen file %s", TMPINNAME);
414}
415
416/*
417 * Fetch a line from the input file, \n terminated, not necessarily \0.
418 */
419char *
420ifetch(LINENUM line, int whichbuf)
421{
422 if (line < 1 || line > input_lines) {
423 if (warn_on_invalid_line) {
424 say("No such line %ld in input file, ignoring\n", line);
425 warn_on_invalid_line = false;
426 }
427 return NULL;
428 }
429 if (using_plan_a)
430 return i_ptr[line];
431 else {
432 LINENUM offline = line % lines_per_buf;
433 LINENUM baseline = line - offline;
434
435 if (tiline[0] == baseline)
436 whichbuf = 0;
437 else if (tiline[1] == baseline)
438 whichbuf = 1;
439 else {
440 tiline[whichbuf] = baseline;
441
442 lseek(tifd, (off_t) (baseline / lines_per_buf *
443 BUFFERSIZE), SEEK_SET);
444
445 if (read(tifd, tibuf[whichbuf], BUFFERSIZE) < 0)
446 pfatal("error reading tmp file %s", TMPINNAME);
447 }
448 return tibuf[whichbuf] + (tireclen * offline);
449 }
450}
451
452/*
453 * True if the string argument contains the revision number we want.
454 */
455static bool
456rev_in_string(const char *string)
457{
458 const char *s;
459 int patlen;
460
461 if (revision == NULL)
462 return true;
463 patlen = strlen(revision);
464 if (strnEQ(string, revision, patlen) && isspace(string[patlen]))
465 return true;
466 for (s = string; *s; s++) {
467 if (isspace(*s) && strnEQ(s + 1, revision, patlen) &&
468 isspace(s[patlen + 1])) {
469 return true;
470 }
471 }
472 return false;
473}