svn commit: r204898 - user/delphij/patch

Xin LI delphij at FreeBSD.org
Mon Mar 8 23:06:10 UTC 2010


Author: delphij
Date: Mon Mar  8 23:06:09 2010
New Revision: 204898
URL: http://svn.freebsd.org/changeset/base/204898

Log:
  Initial work on the fully BSD licensed patch(1).  This is a port from
  OpenBSD's patch(1) as of today with local changes for WARNS=6.
  
  Obtained from:	OpenBSD

Added:
  user/delphij/patch/
  user/delphij/patch/Makefile   (contents, props changed)
  user/delphij/patch/README
  user/delphij/patch/backupfile.c   (contents, props changed)
  user/delphij/patch/backupfile.h   (contents, props changed)
  user/delphij/patch/common.h   (contents, props changed)
  user/delphij/patch/inp.c   (contents, props changed)
  user/delphij/patch/inp.h   (contents, props changed)
  user/delphij/patch/mkpath.c   (contents, props changed)
  user/delphij/patch/patch.1   (contents, props changed)
  user/delphij/patch/patch.c   (contents, props changed)
  user/delphij/patch/pathnames.h   (contents, props changed)
  user/delphij/patch/pch.c   (contents, props changed)
  user/delphij/patch/pch.h   (contents, props changed)
  user/delphij/patch/util.c   (contents, props changed)
  user/delphij/patch/util.h   (contents, props changed)

Added: user/delphij/patch/Makefile
==============================================================================
--- /dev/null	00:00:00 1970	(empty, because file is newly added)
+++ user/delphij/patch/Makefile	Mon Mar  8 23:06:09 2010	(r204898)
@@ -0,0 +1,7 @@
+#	$OpenBSD: Makefile,v 1.4 2005/05/16 15:22:46 espie Exp $
+# $FreeBSD$
+
+PROG=	patch
+SRCS=	patch.c pch.c inp.c util.c backupfile.c mkpath.c
+
+.include <bsd.prog.mk>

Added: user/delphij/patch/README
==============================================================================
--- /dev/null	00:00:00 1970	(empty, because file is newly added)
+++ user/delphij/patch/README	Mon Mar  8 23:06:09 2010	(r204898)
@@ -0,0 +1,125 @@
+$FreeBSD$
+
+this version modified to fit in with the 386bsd release.
+this isn't gnu software, so we're not obligated to give
+you the original sources -- if you want them, get them
+from prep.ai.mit.edu:pub/gnu/patch-2.0.12u8.tar.z
+
+					-- cgd
+
+#######################################################################
+
+
+This version of patch contains modifications made by the Free Software
+Foundation, summarized in the file ChangeLog.  Primarily they are to
+support the unified context diff format that GNU diff can produce, and
+to support making GNU Emacs-style backup files.  They also include
+fixes for some bugs.
+
+There are two GNU variants of patch: this one, which retains Larry
+Wall's interactive Configure script and has patchlevels starting with
+`12u'; and another one that has a GNU-style non-interactive configure
+script and accepts long-named options, and has patchlevels starting
+with `12g'.  Unlike the 12g variant, the 12u variant contains no
+copylefted code, for the paranoid.  The two variants are otherwise the
+same.  They should be available from the same places.
+
+The FSF is distributing this version of patch independently because as
+of this writing, Larry Wall has not released a new version of patch
+since mid-1988.  I have heard that he has been too busy working on
+other things, like Perl.
+
+Here is a wish list of some projects to improve patch:
+
+1.  Correctly handle files and patchfiles that contain NUL characters.
+This is hard to do straightforwardly; it would be less work to
+adopt a kind of escape encoding internally.
+Let ESC be a "control prefix".  ESC @ stands for NUL.  ESC [ stands for ESC.
+You need to crunch this when reading input (replace fgets),
+and when writing the output file (replace fputs),
+but otherwise everything can go along as it does now.
+Be careful to handle reject files correctly;
+I think they are currently created using `write', not `fputs'.
+
+2.  Correctly handle patches produced by GNU diff for files that do
+not end with a newline.
+
+Please send bug reports for this version of patch to
+bug-gnu-utils at prep.ai.mit.edu as well as to Larry Wall (lwall at netlabs.com).
+ --djm at gnu.ai.mit.edu (David MacKenzie)
+
+			Patch Kit, Version 2.0
+
+		    Copyright (c) 1988, Larry Wall
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following condition
+is met:
+ 1. Redistributions of source code must retain the above copyright
+    notice, this condition and the following disclaimer.
+
+THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
+FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGE.
+--------------------------------------------------------------------------
+
+Please read all the directions below before you proceed any further, and
+then follow them carefully.  Failure to do so may void your warranty. :-)
+
+After you have unpacked your kit, you should have all the files listed
+in MANIFEST.
+
+Installation
+
+1)  Run Configure.  This will figure out various things about your system.
+    Some things Configure will figure out for itself, other things it will
+    ask you about.  It will then proceed to make config.h, config.sh, and
+    Makefile.
+
+    You might possibly have to trim # comments from the front of Configure
+    if your sh doesn't handle them, but all other # comments will be taken
+    care of.
+
+    If you don't have sh, you'll have to rip the prototype of config.h out
+    of Configure and generate the defines by hand.
+
+2)  Glance through config.h to make sure system dependencies are correct.
+    Most of them should have been taken care of by running the
+    Configure script. 
+
+    If you have any additional changes to make to the C definitions, they
+    can be done in the Makefile, or in config.h.  Bear in mind that they may
+    get undone next time you run Configure.
+
+3)  make
+
+    This will attempt to make patch in the current directory.
+
+4)  make install
+
+    This will put patch into a public directory (normally /usr/local/bin).
+    It will also try to put the man pages in a reasonable place.  It will not
+    nroff the man page, however.
+
+5)  Read the manual entry before running patch.
+
+6)  IMPORTANT!  Help save the world!  Communicate any problems and
+    suggested patches to me, lwall at netlabs.com (Larry Wall),
+    so we can keep the world in sync.  If you have a problem, there's
+    someone else out there who either has had or will have the same problem.
+
+    If possible, send in patches such that the patch program will apply them.
+    Context diffs are the best, then normal diffs.  Don't send ed scripts--
+    I've probably changed my copy since the version you have.
+
+    Watch for patch patches in comp.sources.bugs.  Patches will generally be
+    in a form usable by the patch program.  Your current patch level
+    is shown in patchlevel.h.

Added: user/delphij/patch/backupfile.c
==============================================================================
--- /dev/null	00:00:00 1970	(empty, because file is newly added)
+++ user/delphij/patch/backupfile.c	Mon Mar  8 23:06:09 2010	(r204898)
@@ -0,0 +1,237 @@
+/*	$OpenBSD: backupfile.c,v 1.20 2009/10/27 23:59:41 deraadt Exp $	*/
+
+/*
+ * backupfile.c -- make Emacs style backup file names Copyright (C) 1990 Free
+ * Software Foundation, Inc.
+ * 
+ * This program is free software; you can redistribute it and/or modify it
+ * without restriction.
+ * 
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.
+ */
+
+/*
+ * David MacKenzie <djm at ai.mit.edu>. Some algorithms adapted from GNU Emacs.
+ */
+#include <sys/cdefs.h>
+__FBSDID("$FreeBSD$");
+
+#include <ctype.h>
+#include <dirent.h>
+#include <libgen.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+#include "backupfile.h"
+
+
+#define ISDIGIT(c) (isascii (c) && isdigit (c))
+
+/* Which type of backup file names are generated. */
+enum backup_type backup_type = none;
+
+/*
+ * The extension added to file names to produce a simple (as opposed to
+ * numbered) backup file name.
+ */
+const char	*simple_backup_suffix = "~";
+
+static char	*concat(const char *, const char *);
+static char	*make_version_name(const char *, int);
+static int	max_backup_version(const char *, const char *);
+static int	version_number(const char *, const char *, size_t);
+static int	argmatch(const char *, const char **);
+static void	invalid_arg(const char *, const char *, int);
+
+/*
+ * Return the name of the new backup file for file FILE, allocated with
+ * malloc.  Return 0 if out of memory. FILE must not end with a '/' unless it
+ * is the root directory. Do not call this function if backup_type == none.
+ */
+char *
+find_backup_file_name(const char *file)
+{
+	char	*dir, *base_versions;
+	int	highest_backup;
+
+	if (backup_type == simple)
+		return concat(file, simple_backup_suffix);
+	base_versions = concat(basename(file), ".~");
+	if (base_versions == NULL)
+		return NULL;
+	dir = dirname(file);
+	if (dir == NULL) {
+		free(base_versions);
+		return NULL;
+	}
+	highest_backup = max_backup_version(base_versions, dir);
+	free(base_versions);
+	if (backup_type == numbered_existing && highest_backup == 0)
+		return concat(file, simple_backup_suffix);
+	return make_version_name(file, highest_backup + 1);
+}
+
+/*
+ * Return the number of the highest-numbered backup file for file FILE in
+ * directory DIR.  If there are no numbered backups of FILE in DIR, or an
+ * error occurs reading DIR, return 0. FILE should already have ".~" appended
+ * to it.
+ */
+static int
+max_backup_version(const char *file, const char *dir)
+{
+	DIR	*dirp;
+	struct dirent	*dp;
+	int	highest_version, this_version;
+	size_t	file_name_length;
+
+	dirp = opendir(dir);
+	if (dirp == NULL)
+		return 0;
+
+	highest_version = 0;
+	file_name_length = strlen(file);
+
+	while ((dp = readdir(dirp)) != NULL) {
+		if (dp->d_namlen <= file_name_length)
+			continue;
+
+		this_version = version_number(file, dp->d_name, file_name_length);
+		if (this_version > highest_version)
+			highest_version = this_version;
+	}
+	closedir(dirp);
+	return highest_version;
+}
+
+/*
+ * Return a string, allocated with malloc, containing "FILE.~VERSION~".
+ * Return 0 if out of memory.
+ */
+static char *
+make_version_name(const char *file, int version)
+{
+	char	*backup_name;
+
+	if (asprintf(&backup_name, "%s.~%d~", file, version) == -1)
+		return NULL;
+	return backup_name;
+}
+
+/*
+ * If BACKUP is a numbered backup of BASE, return its version number;
+ * otherwise return 0.  BASE_LENGTH is the length of BASE. BASE should
+ * already have ".~" appended to it.
+ */
+static int
+version_number(const char *base, const char *backup, size_t base_length)
+{
+	int		version;
+	const char	*p;
+
+	version = 0;
+	if (!strncmp(base, backup, base_length) && ISDIGIT(backup[base_length])) {
+		for (p = &backup[base_length]; ISDIGIT(*p); ++p)
+			version = version * 10 + *p - '0';
+		if (p[0] != '~' || p[1])
+			version = 0;
+	}
+	return version;
+}
+
+/*
+ * Return the newly-allocated concatenation of STR1 and STR2. If out of
+ * memory, return 0.
+ */
+static char  *
+concat(const char *str1, const char *str2)
+{
+	char	*newstr;
+
+	if (asprintf(&newstr, "%s%s", str1, str2) == -1)
+		return NULL;
+	return newstr;
+}
+
+/*
+ * If ARG is an unambiguous match for an element of the null-terminated array
+ * OPTLIST, return the index in OPTLIST of the matched element, else -1 if it
+ * does not match any element or -2 if it is ambiguous (is a prefix of more
+ * than one element).
+ */
+static int
+argmatch(const char *arg, const char **optlist)
+{
+	int	i;	/* Temporary index in OPTLIST. */
+	size_t	arglen;	/* Length of ARG. */
+	int	matchind = -1;	/* Index of first nonexact match. */
+	int	ambiguous = 0;	/* If nonzero, multiple nonexact match(es). */
+
+	arglen = strlen(arg);
+
+	/* Test all elements for either exact match or abbreviated matches.  */
+	for (i = 0; optlist[i]; i++) {
+		if (!strncmp(optlist[i], arg, arglen)) {
+			if (strlen(optlist[i]) == arglen)
+				/* Exact match found.  */
+				return i;
+			else if (matchind == -1)
+				/* First nonexact match found.  */
+				matchind = i;
+			else
+				/* Second nonexact match found.  */
+				ambiguous = 1;
+		}
+	}
+	if (ambiguous)
+		return -2;
+	else
+		return matchind;
+}
+
+/*
+ * Error reporting for argmatch. KIND is a description of the type of entity
+ * that was being matched. VALUE is the invalid value that was given. PROBLEM
+ * is the return value from argmatch.
+ */
+static void
+invalid_arg(const char *kind, const char *value, int problem)
+{
+	fprintf(stderr, "patch: ");
+	if (problem == -1)
+		fprintf(stderr, "invalid");
+	else			/* Assume -2. */
+		fprintf(stderr, "ambiguous");
+	fprintf(stderr, " %s `%s'\n", kind, value);
+}
+
+static const char *backup_args[] = {
+	"never", "simple", "nil", "existing", "t", "numbered", 0
+};
+
+static enum backup_type backup_types[] = {
+	simple, simple, numbered_existing,
+	numbered_existing, numbered, numbered
+};
+
+/*
+ * Return the type of backup indicated by VERSION. Unique abbreviations are
+ * accepted.
+ */
+enum backup_type
+get_version(const char *version)
+{
+	int	i;
+
+	if (version == NULL || *version == '\0')
+		return numbered_existing;
+	i = argmatch(version, backup_args);
+	if (i >= 0)
+		return backup_types[i];
+	invalid_arg("version control type", version, i);
+	exit(2);
+}

Added: user/delphij/patch/backupfile.h
==============================================================================
--- /dev/null	00:00:00 1970	(empty, because file is newly added)
+++ user/delphij/patch/backupfile.h	Mon Mar  8 23:06:09 2010	(r204898)
@@ -0,0 +1,39 @@
+/*	$OpenBSD: backupfile.h,v 1.6 2003/07/28 18:35:36 otto Exp $	*/
+
+/*
+ * backupfile.h -- declarations for making Emacs style backup file names
+ * Copyright (C) 1990 Free Software Foundation, Inc.
+ * 
+ * This program is free software; you can redistribute it and/or modify it
+ * without restriction.
+ * 
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.
+ * 
+ * $FreeBSD$
+ */
+
+/* When to make backup files. */
+enum backup_type {
+	/* Never make backups. */
+	none,
+
+	/* Make simple backups of every file. */
+	simple,
+
+	/*
+	 * Make numbered backups of files that already have numbered backups,
+	 * and simple backups of the others.
+	 */
+	numbered_existing,
+
+	/* Make numbered backups of every file. */
+	numbered
+};
+
+extern enum backup_type backup_type;
+extern const char	*simple_backup_suffix;
+
+char		*find_backup_file_name(const char *file);
+enum backup_type get_version(const char *version);

Added: user/delphij/patch/common.h
==============================================================================
--- /dev/null	00:00:00 1970	(empty, because file is newly added)
+++ user/delphij/patch/common.h	Mon Mar  8 23:06:09 2010	(r204898)
@@ -0,0 +1,118 @@
+/*	$OpenBSD: common.h,v 1.26 2006/03/11 19:41:30 otto Exp $	*/
+
+/*
+ * patch - a program to apply diffs to original files
+ * 
+ * Copyright 1986, Larry Wall
+ * 
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following condition is met:
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this condition and the following disclaimer.
+ * 
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ * 
+ * -C option added in 1998, original code by Marc Espie, based on FreeBSD
+ * behaviour
+ *
+ * $FreeBSD$
+ */
+
+#include <sys/types.h>
+
+#include <stdbool.h>
+
+#define DEBUGGING
+
+/* constants */
+
+#define MAXHUNKSIZE 100000	/* is this enough lines? */
+#define INITHUNKMAX 125		/* initial dynamic allocation size */
+#define MAXLINELEN 8192
+#define BUFFERSIZE 1024
+
+#define SCCSPREFIX "s."
+#define GET "get -e %s"
+#define SCCSDIFF "get -p %s | diff - %s >/dev/null"
+
+#define RCSSUFFIX ",v"
+#define CHECKOUT "co -l %s"
+#define RCSDIFF "rcsdiff %s > /dev/null"
+
+#define ORIGEXT ".orig"
+#define REJEXT ".rej"
+
+/* handy definitions */
+
+#define strNE(s1,s2) (strcmp(s1, s2))
+#define strEQ(s1,s2) (!strcmp(s1, s2))
+#define strnNE(s1,s2,l) (strncmp(s1, s2, l))
+#define strnEQ(s1,s2,l) (!strncmp(s1, s2, l))
+
+/* typedefs */
+
+typedef long    LINENUM;	/* must be signed */
+
+/* globals */
+
+extern mode_t	filemode;
+
+extern char	buf[MAXLINELEN];/* general purpose buffer */
+
+extern bool	using_plan_a;	/* try to keep everything in memory */
+extern bool	out_of_mem;	/* ran out of memory in plan a */
+
+#define MAXFILEC 2
+
+extern char	*filearg[MAXFILEC];
+extern bool	ok_to_create_file;
+extern char	*outname;
+extern char	*origprae;
+
+extern char	*TMPOUTNAME;
+extern char	*TMPINNAME;
+extern char	*TMPREJNAME;
+extern char	*TMPPATNAME;
+extern bool	toutkeep;
+extern bool	trejkeep;
+
+#ifdef DEBUGGING
+extern int	debug;
+#endif
+
+extern bool	force;
+extern bool	batch;
+extern bool	verbose;
+extern bool	reverse;
+extern bool	noreverse;
+extern bool	skip_rest_of_patch;
+extern int	strippath;
+extern bool	canonicalize;
+/* TRUE if -C was specified on command line.  */
+extern bool	check_only;
+extern bool	warn_on_invalid_line;
+extern bool	last_line_missing_eol;
+
+
+#define CONTEXT_DIFF 1
+#define NORMAL_DIFF 2
+#define ED_DIFF 3
+#define NEW_CONTEXT_DIFF 4
+#define UNI_DIFF 5
+
+extern int	diff_type;
+extern char	*revision;	/* prerequisite revision, if any */
+extern LINENUM	input_lines;	/* how long is input file in lines */
+
+extern int	posix;
+

Added: user/delphij/patch/inp.c
==============================================================================
--- /dev/null	00:00:00 1970	(empty, because file is newly added)
+++ user/delphij/patch/inp.c	Mon Mar  8 23:06:09 2010	(r204898)
@@ -0,0 +1,468 @@
+/*	$OpenBSD: inp.c,v 1.35 2009/10/27 23:59:41 deraadt Exp $	*/
+
+/*
+ * patch - a program to apply diffs to original files
+ * 
+ * Copyright 1986, Larry Wall
+ * 
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following condition is met:
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this condition and the following disclaimer.
+ * 
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ * 
+ * -C option added in 1998, original code by Marc Espie, based on FreeBSD
+ * behaviour
+ */
+
+#include <sys/cdefs.h>
+__FBSDID("$FreeBSD$");
+
+#include <sys/types.h>
+#include <sys/file.h>
+#include <sys/stat.h>
+#include <sys/mman.h>
+
+#include <ctype.h>
+#include <libgen.h>
+#include <limits.h>
+#include <stddef.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+#include "common.h"
+#include "util.h"
+#include "pch.h"
+#include "inp.h"
+
+
+/* Input-file-with-indexable-lines abstract type */
+
+static off_t	i_size;		/* size of the input file */
+static char	*i_womp;	/* plan a buffer for entire file */
+static char	**i_ptr;	/* pointers to lines in i_womp */
+
+static int	tifd = -1;	/* plan b virtual string array */
+static char	*tibuf[2];	/* plan b buffers */
+static LINENUM	tiline[2] = {-1, -1};	/* 1st line in each buffer */
+static LINENUM	lines_per_buf;	/* how many lines per buffer */
+static int	tireclen;	/* length of records in tmp file */
+
+static bool	rev_in_string(const char *);
+static bool	reallocate_lines(size_t *);
+
+/* returns false if insufficient memory */
+static bool	plan_a(const char *);
+
+static void	plan_b(const char *);
+
+/* New patch--prepare to edit another file. */
+
+void
+re_input(void)
+{
+	if (using_plan_a) {
+		i_size = 0;
+		free(i_ptr);
+		i_ptr = NULL;
+		if (i_womp != NULL) {
+			munmap(i_womp, i_size);
+			i_womp = NULL;
+		}
+	} else {
+		using_plan_a = true;	/* maybe the next one is smaller */
+		close(tifd);
+		tifd = -1;
+		free(tibuf[0]);
+		free(tibuf[1]);
+		tibuf[0] = tibuf[1] = NULL;
+		tiline[0] = tiline[1] = -1;
+		tireclen = 0;
+	}
+}
+
+/* Construct the line index, somehow or other. */
+
+void
+scan_input(const char *filename)
+{
+	if (!plan_a(filename))
+		plan_b(filename);
+	if (verbose) {
+		say("Patching file %s using Plan %s...\n", filename,
+		    (using_plan_a ? "A" : "B"));
+	}
+}
+
+static bool
+reallocate_lines(size_t *lines_allocated)
+{
+	char	**p;
+	size_t	new_size;
+
+	new_size = *lines_allocated * 3 / 2;
+	p = realloc(i_ptr, (new_size + 2) * sizeof(char *));
+	if (p == NULL) {	/* shucks, it was a near thing */
+		munmap(i_womp, i_size);
+		i_womp = NULL;
+		free(i_ptr);
+		i_ptr = NULL;
+		*lines_allocated = 0;
+		return false;
+	}
+	*lines_allocated = new_size;
+	i_ptr = p;
+	return true;
+}
+
+/* Try keeping everything in memory. */
+
+static bool
+plan_a(const char *filename)
+{
+	int		ifd, statfailed;
+	char		*p, *s, lbuf[MAXLINELEN];
+	struct stat	filestat;
+	off_t		i;
+	ptrdiff_t	sz;
+	size_t		iline, lines_allocated;
+
+#ifdef DEBUGGING
+	if (debug & 8)
+		return false;
+#endif
+
+	if (filename == NULL || *filename == '\0')
+		return false;
+
+	statfailed = stat(filename, &filestat);
+	if (statfailed && ok_to_create_file) {
+		if (verbose)
+			say("(Creating file %s...)\n", filename);
+
+		/*
+		 * in check_patch case, we still display `Creating file' even
+		 * though we're not. The rule is that -C should be as similar
+		 * to normal patch behavior as possible
+		 */
+		if (check_only)
+			return true;
+		makedirs(filename, true);
+		close(creat(filename, 0666));
+		statfailed = stat(filename, &filestat);
+	}
+	if (statfailed && check_only)
+		fatal("%s not found, -C mode, can't probe further\n", filename);
+	/* For nonexistent or read-only files, look for RCS or SCCS versions.  */
+	if (statfailed ||
+	    /* No one can write to it.  */
+	    (filestat.st_mode & 0222) == 0 ||
+	    /* I can't write to it.  */
+	    ((filestat.st_mode & 0022) == 0 && filestat.st_uid != getuid())) {
+		const char	*cs = NULL, *filebase, *filedir;
+		struct stat	cstat;
+
+		filebase = basename(filename);
+		filedir = dirname(filename);
+
+		/* Leave room in lbuf for the diff command.  */
+		s = lbuf + 20;
+
+#define try(f, a1, a2, a3) \
+	(snprintf(s, sizeof lbuf - 20, f, a1, a2, a3), stat(s, &cstat) == 0)
+
+		if (try("%s/RCS/%s%s", filedir, filebase, RCSSUFFIX) ||
+		    try("%s/RCS/%s%s", filedir, filebase, "") ||
+		    try("%s/%s%s", filedir, filebase, RCSSUFFIX)) {
+			snprintf(buf, sizeof buf, CHECKOUT, filename);
+			snprintf(lbuf, sizeof lbuf, RCSDIFF, filename);
+			cs = "RCS";
+		} else if (try("%s/SCCS/%s%s", filedir, SCCSPREFIX, filebase) ||
+		    try("%s/%s%s", filedir, SCCSPREFIX, filebase)) {
+			snprintf(buf, sizeof buf, GET, s);
+			snprintf(lbuf, sizeof lbuf, SCCSDIFF, s, filename);
+			cs = "SCCS";
+		} else if (statfailed)
+			fatal("can't find %s\n", filename);
+		/*
+		 * else we can't write to it but it's not under a version
+		 * control system, so just proceed.
+		 */
+		if (cs) {
+			if (!statfailed) {
+				if ((filestat.st_mode & 0222) != 0)
+					/* The owner can write to it.  */
+					fatal("file %s seems to be locked "
+					    "by somebody else under %s\n",
+					    filename, cs);
+				/*
+				 * It might be checked out unlocked.  See if
+				 * it's safe to check out the default version
+				 * locked.
+				 */
+				if (verbose)
+					say("Comparing file %s to default "
+					    "%s version...\n",
+					    filename, cs);
+				if (system(lbuf))
+					fatal("can't check out file %s: "
+					    "differs from default %s version\n",
+					    filename, cs);
+			}
+			if (verbose)
+				say("Checking out file %s from %s...\n",
+				    filename, cs);
+			if (system(buf) || stat(filename, &filestat))
+				fatal("can't check out file %s from %s\n",
+				    filename, cs);
+		}
+	}
+	filemode = filestat.st_mode;
+	if (!S_ISREG(filemode))
+		fatal("%s is not a normal file--can't patch\n", filename);
+	i_size = filestat.st_size;
+	if (out_of_mem) {
+		set_hunkmax();	/* make sure dynamic arrays are allocated */
+		out_of_mem = false;
+		return false;	/* force plan b because plan a bombed */
+	}
+	if ((ifd = open(filename, O_RDONLY)) < 0)
+		pfatal("can't open file %s", filename);
+
+	i_womp = mmap(NULL, i_size, PROT_READ, MAP_PRIVATE, ifd, 0);
+	if (i_womp == MAP_FAILED) {
+		perror("mmap failed");
+		i_womp = NULL;
+		close(ifd);
+		return false;
+	}
+
+	close(ifd);
+	if (i_size)
+		madvise(i_womp, i_size, MADV_SEQUENTIAL);
+
+	/* estimate the number of lines */
+	lines_allocated = i_size / 25;
+	if (lines_allocated < 100)
+		lines_allocated = 100;
+
+	if (!reallocate_lines(&lines_allocated))
+		return false;
+
+	/* now scan the buffer and build pointer array */
+	iline = 1;
+	i_ptr[iline] = i_womp;
+	/* test for NUL too, to maintain the behavior of the original code */
+	for (s = i_womp, i = 0; i < i_size && *s != '\0'; s++, i++) {
+		if (*s == '\n') {
+			if (iline == lines_allocated) {
+				if (!reallocate_lines(&lines_allocated))
+					return false;
+			}
+			/* these are NOT NUL terminated */
+			i_ptr[++iline] = s + 1;
+		}
+	}
+	/* if the last line contains no EOL, append one */
+	if (i_size > 0 && i_womp[i_size - 1] != '\n') {
+		last_line_missing_eol = true;
+		/* fix last line */
+		sz = s - i_ptr[iline];
+		p = malloc(sz + 1);
+		if (p == NULL) {
+			free(i_ptr);
+			i_ptr = NULL;
+			munmap(i_womp, i_size);
+			i_womp = NULL;
+			return false;
+		}
+
+		memcpy(p, i_ptr[iline], sz);
+		p[sz] = '\n';
+		i_ptr[iline] = p;
+		/* count the extra line and make it point to some valid mem */
+		i_ptr[++iline] = strdup("");
+	} else
+		last_line_missing_eol = false;
+
+	input_lines = iline - 1;
+
+	/* now check for revision, if any */
+
+	if (revision != NULL) {
+		if (!rev_in_string(i_womp)) {
+			if (force) {
+				if (verbose)
+					say("Warning: this file doesn't appear "
+					    "to be the %s version--patching anyway.\n",
+					    revision);
+			} else if (batch) {
+				fatal("this file doesn't appear to be the "
+				    "%s version--aborting.\n",
+				    revision);
+			} else {
+				ask("This file doesn't appear to be the "
+				    "%s version--patch anyway? [n] ",
+				    revision);
+				if (*buf != 'y')
+					fatal("aborted\n");
+			}
+		} else if (verbose)
+			say("Good.  This file appears to be the %s version.\n",
+			    revision);
+	}
+	return true;		/* plan a will work */
+}
+
+/* Keep (virtually) nothing in memory. */
+
+static void
+plan_b(const char *filename)
+{
+	FILE	*ifp;
+	size_t	i = 0, j, maxlen = 1;
+	char	*p;
+	bool	found_revision = (revision == NULL);
+
+	using_plan_a = false;
+	if ((ifp = fopen(filename, "r")) == NULL)
+		pfatal("can't open file %s", filename);
+	(void) unlink(TMPINNAME);
+	if ((tifd = open(TMPINNAME, O_EXCL | O_CREAT | O_WRONLY, 0666)) < 0)
+		pfatal("can't open file %s", TMPINNAME);
+	while (fgets(buf, sizeof buf, ifp) != NULL) {
+		if (revision != NULL && !found_revision && rev_in_string(buf))
+			found_revision = true;
+		if ((i = strlen(buf)) > maxlen)
+			maxlen = i;	/* find longest line */
+	}
+	last_line_missing_eol = i > 0 && buf[i - 1] != '\n';
+	if (last_line_missing_eol && maxlen == i)
+		maxlen++;
+
+	if (revision != NULL) {
+		if (!found_revision) {
+			if (force) {
+				if (verbose)
+					say("Warning: this file doesn't appear "
+					    "to be the %s version--patching anyway.\n",
+					    revision);
+			} else if (batch) {
+				fatal("this file doesn't appear to be the "
+				    "%s version--aborting.\n",
+				    revision);
+			} else {
+				ask("This file doesn't appear to be the %s "
+				    "version--patch anyway? [n] ",
+				    revision);
+				if (*buf != 'y')
+					fatal("aborted\n");
+			}
+		} else if (verbose)
+			say("Good.  This file appears to be the %s version.\n",
+			    revision);
+	}
+	fseek(ifp, 0L, SEEK_SET);	/* rewind file */
+	lines_per_buf = BUFFERSIZE / maxlen;
+	tireclen = maxlen;
+	tibuf[0] = malloc(BUFFERSIZE + 1);
+	if (tibuf[0] == NULL)
+		fatal("out of memory\n");
+	tibuf[1] = malloc(BUFFERSIZE + 1);
+	if (tibuf[1] == NULL)
+		fatal("out of memory\n");
+	for (i = 1;; i++) {
+		p = tibuf[0] + maxlen * (i % lines_per_buf);
+		if (i % lines_per_buf == 0)	/* new block */
+			if (write(tifd, tibuf[0], BUFFERSIZE) < BUFFERSIZE)
+				pfatal("can't write temp file");
+		if (fgets(p, maxlen + 1, ifp) == NULL) {
+			input_lines = i - 1;
+			if (i % lines_per_buf != 0)
+				if (write(tifd, tibuf[0], BUFFERSIZE) < BUFFERSIZE)
+					pfatal("can't write temp file");
+			break;
+		}
+		j = strlen(p);
+		/* These are '\n' terminated strings, so no need to add a NUL */
+		if (j == 0 || p[j - 1] != '\n')
+			p[j] = '\n';
+	}
+	fclose(ifp);
+	close(tifd);
+	if ((tifd = open(TMPINNAME, O_RDONLY)) < 0)
+		pfatal("can't reopen file %s", TMPINNAME);
+}
+
+/*
+ * Fetch a line from the input file, \n terminated, not necessarily \0.
+ */
+char *
+ifetch(LINENUM line, int whichbuf)
+{
+	if (line < 1 || line > input_lines) {
+		if (warn_on_invalid_line) {
+			say("No such line %ld in input file, ignoring\n", line);
+			warn_on_invalid_line = false;
+		}
+		return NULL;
+	}
+	if (using_plan_a)
+		return i_ptr[line];
+	else {
+		LINENUM	offline = line % lines_per_buf;
+		LINENUM	baseline = line - offline;
+
+		if (tiline[0] == baseline)
+			whichbuf = 0;
+		else if (tiline[1] == baseline)
+			whichbuf = 1;
+		else {
+			tiline[whichbuf] = baseline;
+
+			if (lseek(tifd, (off_t) (baseline / lines_per_buf *
+			    BUFFERSIZE), SEEK_SET) < 0)
+				pfatal("cannot seek in the temporary input file");
+
+			if (read(tifd, tibuf[whichbuf], BUFFERSIZE) < 0)
+				pfatal("error reading tmp file %s", TMPINNAME);
+		}
+		return tibuf[whichbuf] + (tireclen * offline);
+	}
+}
+
+/*
+ * True if the string argument contains the revision number we want.
+ */
+static bool
+rev_in_string(const char *string)
+{
+	const char	*s;
+	size_t		patlen;
+
+	if (revision == NULL)

*** DIFF OUTPUT TRUNCATED AT 1000 LINES ***


More information about the svn-src-user mailing list