Index: trunk/src/gmake/kmkbuiltin/cp.c
===================================================================
--- trunk/src/gmake/kmkbuiltin/cp.c	(revision 229)
+++ trunk/src/gmake/kmkbuiltin/cp.c	(revision 229)
@@ -0,0 +1,558 @@
+/*
+ * Copyright (c) 1988, 1993, 1994
+ *	The Regents of the University of California.  All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * David Hitz of Auspex Systems Inc.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 4. Neither the name of the University nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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.
+ */
+
+#if 0
+#ifndef lint
+static char const copyright[] =
+"@(#) Copyright (c) 1988, 1993, 1994\n\
+	The Regents of the University of California.  All rights reserved.\n";
+#endif /* not lint */
+
+#ifndef lint
+static char sccsid[] = "@(#)cp.c	8.2 (Berkeley) 4/1/94";
+#endif /* not lint */
+#endif
+#include <sys/cdefs.h>
+//__FBSDID("$FreeBSD: src/bin/cp/cp.c,v 1.50 2004/04/06 20:06:44 markm Exp $");
+
+/*
+ * Cp copies source files to target files.
+ *
+ * The global PATH_T structure "to" always contains the path to the
+ * current target file.  Since fts(3) does not change directories,
+ * this path can be either absolute or dot-relative.
+ *
+ * The basic algorithm is to initialize "to" and use fts(3) to traverse
+ * the file hierarchy rooted in the argument list.  A trivial case is the
+ * case of 'cp file1 file2'.  The more interesting case is the case of
+ * 'cp file1 file2 ... fileN dir' where the hierarchy is traversed and the
+ * path (relative to the root of the traversal) is appended to dir (stored
+ * in "to") to form the final target path.
+ */
+
+#include <sys/types.h>
+#include <sys/stat.h>
+
+#include <err.h>
+#include <errno.h>
+#include <fts.h>
+#include <limits.h>
+#include <signal.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+#include "cp_extern.h"
+
+#ifndef S_IFWHT
+#define S_IFWHT 0
+#define S_ISWHT(s) 0
+#define undelete(s) (-1)
+#endif
+
+#ifndef S_ISTXT
+#ifdef S_ISVTX
+#define S_ISTXT S_ISVTX
+#else
+#define S_ISTXT 0
+#endif
+#endif /* !S_ISTXT */
+
+
+#define	STRIP_TRAILING_SLASH(p) {					\
+        while ((p).p_end > (p).p_path + 1 && (p).p_end[-1] == '/')	\
+                *--(p).p_end = 0;					\
+}
+
+/* have wrappers for globals in cp_extern! */
+
+const char *cp_argv0;
+static char emptystring[] = "";
+
+PATH_T to = { to.p_path, emptystring, "" };
+
+int fflag, iflag, nflag, pflag, vflag;
+int Rflag, rflag;
+volatile sig_atomic_t info;
+
+enum op { FILE_TO_FILE, FILE_TO_DIR, DIR_TO_DNE };
+
+static int copy(char *[], enum op, int);
+static int mastercmp(const FTSENT * const *, const FTSENT * const *);
+#ifdef SIGINFO
+static void siginfo(int __unused);
+#endif
+
+int
+kmk_builtin_cp(int argc, char *argv[])
+{
+	struct stat to_stat, tmp_stat;
+	enum op type;
+	int Hflag, Lflag, Pflag, ch, fts_options, r, have_trailing_slash;
+	char *target;
+
+        argv0 = argv[0];
+        to.p_end = to.p_path;
+        to.target_end = emptystring;
+        memset(to.p_path, 0, sizeof(to.p_path));
+        fflag = iflag = nflag = pflag = vflag = Rflag = rflag = 0;
+        info = 0;
+        opterr = 1;
+        optarg = NULL;
+        optopt = 0;
+        optind = 0; /* init */
+
+	Hflag = Lflag = Pflag = 0;
+	while ((ch = getopt(argc, argv, "HLPRfinprv")) != -1)
+		switch (ch) {
+		case 'H':
+			Hflag = 1;
+			Lflag = Pflag = 0;
+			break;
+		case 'L':
+			Lflag = 1;
+			Hflag = Pflag = 0;
+			break;
+		case 'P':
+			Pflag = 1;
+			Hflag = Lflag = 0;
+			break;
+		case 'R':
+			Rflag = 1;
+			break;
+		case 'f':
+			fflag = 1;
+			iflag = nflag = 0;
+			break;
+		case 'i':
+			iflag = 1;
+			fflag = nflag = 0;
+			break;
+		case 'n':
+			nflag = 1;
+			fflag = iflag = 0;
+			break;
+		case 'p':
+			pflag = 1;
+			break;
+		case 'r':
+			rflag = 1;
+			break;
+		case 'v':
+			vflag = 1;
+			break;
+		default:
+			usage();
+			break;
+		}
+	argc -= optind;
+	argv += optind;
+
+	if (argc < 2)
+		usage();
+
+	fts_options = FTS_NOCHDIR | FTS_PHYSICAL;
+	if (rflag) {
+		if (Rflag) {
+			fprintf(stderr,
+                            "%s: the -R and -r options may not be specified together.\n", argv0);
+                        return 1;
+                }
+		if (Hflag || Lflag || Pflag) {
+			fprintf(stderr, "%s: the -H, -L, and -P options may not be specified with the -r option.\n", argv0);
+                        return 1;
+                }
+		fts_options &= ~FTS_PHYSICAL;
+		fts_options |= FTS_LOGICAL;
+	}
+	if (Rflag) {
+		if (Hflag)
+			fts_options |= FTS_COMFOLLOW;
+		if (Lflag) {
+			fts_options &= ~FTS_PHYSICAL;
+			fts_options |= FTS_LOGICAL;
+		}
+	} else {
+		fts_options &= ~FTS_PHYSICAL;
+		fts_options |= FTS_LOGICAL | FTS_COMFOLLOW;
+	}
+#ifdef SIGINFO
+	(void)signal(SIGINFO, siginfo);
+#endif
+
+	/* Save the target base in "to". */
+	target = argv[--argc];
+	if (strlcpy(to.p_path, target, sizeof(to.p_path)) >= sizeof(to.p_path)) {
+		fprintf(stderr, "%s: %s: name too long\n", argv0, target);
+                return 1;
+        }
+	to.p_end = to.p_path + strlen(to.p_path);
+        if (to.p_path == to.p_end) {
+		*to.p_end++ = '.';
+		*to.p_end = 0;
+	}
+	have_trailing_slash = (to.p_end[-1] == '/');
+	if (have_trailing_slash)
+		STRIP_TRAILING_SLASH(to);
+	to.target_end = to.p_end;
+
+	/* Set end of argument list for fts(3). */
+	argv[argc] = NULL;
+
+	/*
+	 * Cp has two distinct cases:
+	 *
+	 * cp [-R] source target
+	 * cp [-R] source1 ... sourceN directory
+	 *
+	 * In both cases, source can be either a file or a directory.
+	 *
+	 * In (1), the target becomes a copy of the source. That is, if the
+	 * source is a file, the target will be a file, and likewise for
+	 * directories.
+	 *
+	 * In (2), the real target is not directory, but "directory/source".
+	 */
+	r = stat(to.p_path, &to_stat);
+	if (r == -1 && errno != ENOENT) {
+		fprintf(stderr, "%s: %s: %s\n", argv0, to.p_path, strerror(errno));
+        }
+	if (r == -1 || !S_ISDIR(to_stat.st_mode)) {
+		/*
+		 * Case (1).  Target is not a directory.
+		 */
+		if (argc > 1) {
+			usage();
+			return 1;
+		}
+		/*
+		 * Need to detect the case:
+		 *	cp -R dir foo
+		 * Where dir is a directory and foo does not exist, where
+		 * we want pathname concatenations turned on but not for
+		 * the initial mkdir().
+		 */
+		if (r == -1) {
+			if (rflag || (Rflag && (Lflag || Hflag)))
+				stat(*argv, &tmp_stat);
+			else
+				lstat(*argv, &tmp_stat);
+
+			if (S_ISDIR(tmp_stat.st_mode) && (Rflag || rflag))
+				type = DIR_TO_DNE;
+			else
+				type = FILE_TO_FILE;
+		} else
+			type = FILE_TO_FILE;
+
+		if (have_trailing_slash && type == FILE_TO_FILE) {
+			if (r == -1)
+				fprintf(stderr, "%s: directory %s does not exist\n", argv0,
+				     to.p_path);
+			else
+				fprintf(stderr, "%s: %s is not a directory\n", argv0, to.p_path);
+                        return 1;
+		}
+	} else
+		/*
+		 * Case (2).  Target is a directory.
+		 */
+		type = FILE_TO_DIR;
+
+	return copy(argv, type, fts_options);
+}
+
+static int
+copy(char *argv[], enum op type, int fts_options)
+{
+	struct stat to_stat;
+	FTS *ftsp;
+	FTSENT *curr;
+	int base = 0, dne, badcp, rval;
+	size_t nlen;
+	char *p, *target_mid;
+	mode_t mask, mode;
+
+	/*
+	 * Keep an inverted copy of the umask, for use in correcting
+	 * permissions on created directories when not using -p.
+	 */
+	mask = ~umask(0777);
+	umask(~mask);
+
+	if ((ftsp = fts_open(argv, fts_options, mastercmp)) == NULL) {
+		fprintf(stderr, "%s: fts_open: %s\n", argv0, strerror(errno));
+                return 1;
+        }
+	for (badcp = rval = 0; (curr = fts_read(ftsp)) != NULL; badcp = 0) {
+		switch (curr->fts_info) {
+		case FTS_NS:
+		case FTS_DNR:
+		case FTS_ERR:
+			fprintf(stderr, "%s: %s: %s\n",
+			    argv0, curr->fts_path, strerror(curr->fts_errno));
+			badcp = rval = 1;
+			continue;
+		case FTS_DC:			/* Warn, continue. */
+			fprintf(stderr, "%s: %s: directory causes a cycle\n", argv0, curr->fts_path);
+			badcp = rval = 1;
+			continue;
+		default:
+			;
+		}
+
+		/*
+		 * If we are in case (2) or (3) above, we need to append the
+                 * source name to the target name.
+                 */
+		if (type != FILE_TO_FILE) {
+			/*
+			 * Need to remember the roots of traversals to create
+			 * correct pathnames.  If there's a directory being
+			 * copied to a non-existent directory, e.g.
+			 *	cp -R a/dir noexist
+			 * the resulting path name should be noexist/foo, not
+			 * noexist/dir/foo (where foo is a file in dir), which
+			 * is the case where the target exists.
+			 *
+			 * Also, check for "..".  This is for correct path
+			 * concatenation for paths ending in "..", e.g.
+			 *	cp -R .. /tmp
+			 * Paths ending in ".." are changed to ".".  This is
+			 * tricky, but seems the easiest way to fix the problem.
+			 *
+			 * XXX
+			 * Since the first level MUST be FTS_ROOTLEVEL, base
+			 * is always initialized.
+			 */
+			if (curr->fts_level == FTS_ROOTLEVEL) {
+				if (type != DIR_TO_DNE) {
+					p = strrchr(curr->fts_path, '/');
+					base = (p == NULL) ? 0 :
+					    (int)(p - curr->fts_path + 1);
+
+					if (!strcmp(&curr->fts_path[base],
+					    ".."))
+						base += 1;
+				} else
+					base = curr->fts_pathlen;
+			}
+
+			p = &curr->fts_path[base];
+			nlen = curr->fts_pathlen - base;
+			target_mid = to.target_end;
+			if (*p != '/' && target_mid[-1] != '/')
+				*target_mid++ = '/';
+			*target_mid = 0;
+			if (target_mid - to.p_path + nlen >= PATH_MAX) {
+				fprintf(stderr, "%s: %s%s: name too long (not copied)\n", argv0,
+				    to.p_path, p);
+				badcp = rval = 1;
+				continue;
+			}
+			(void)strncat(target_mid, p, nlen);
+			to.p_end = target_mid + nlen;
+			*to.p_end = 0;
+			STRIP_TRAILING_SLASH(to);
+		}
+
+		if (curr->fts_info == FTS_DP) {
+			/*
+			 * We are nearly finished with this directory.  If we
+			 * didn't actually copy it, or otherwise don't need to
+			 * change its attributes, then we are done.
+			 */
+			if (!curr->fts_number)
+				continue;
+			/*
+			 * If -p is in effect, set all the attributes.
+			 * Otherwise, set the correct permissions, limited
+			 * by the umask.  Optimise by avoiding a chmod()
+			 * if possible (which is usually the case if we
+			 * made the directory).  Note that mkdir() does not
+			 * honour setuid, setgid and sticky bits, but we
+			 * normally want to preserve them on directories.
+			 */
+			if (pflag) {
+				if (setfile(curr->fts_statp, -1))
+				    rval = 1;
+			} else {
+				mode = curr->fts_statp->st_mode;
+				if ((mode & (S_ISUID | S_ISGID | S_ISTXT)) ||
+				    ((mode | S_IRWXU) & mask) != (mode & mask))
+					if (chmod(to.p_path, mode & mask) != 0){
+						fprintf(stderr, "%s: chmod: %s: %s\n", argv0, to.p_path, strerror(errno));
+						rval = 1;
+					}
+			}
+			continue;
+		}
+
+		/* Not an error but need to remember it happened */
+		if (stat(to.p_path, &to_stat) == -1)
+			dne = 1;
+		else {
+			if (to_stat.st_dev == curr->fts_statp->st_dev &&
+			    to_stat.st_ino == curr->fts_statp->st_ino) {
+				fprintf(stderr, "%s: %s and %s are identical (not copied).\n",
+				    argv0, to.p_path, curr->fts_path);
+				badcp = rval = 1;
+				if (S_ISDIR(curr->fts_statp->st_mode))
+					(void)fts_set(ftsp, curr, FTS_SKIP);
+				continue;
+			}
+			if (!S_ISDIR(curr->fts_statp->st_mode) &&
+			    S_ISDIR(to_stat.st_mode)) {
+				fprintf(stderr,
+                                    "%s: cannot overwrite directory %s with "
+				    "non-directory %s\n",
+				    argv0, to.p_path, curr->fts_path);
+				badcp = rval = 1;
+				continue;
+			}
+			dne = 0;
+		}
+
+		switch (curr->fts_statp->st_mode & S_IFMT) {
+		case S_IFLNK:
+			/* Catch special case of a non-dangling symlink */
+			if ((fts_options & FTS_LOGICAL) ||
+			    ((fts_options & FTS_COMFOLLOW) &&
+			    curr->fts_level == 0)) {
+				if (copy_file(curr, dne))
+					badcp = rval = 1;
+			} else {	
+				if (copy_link(curr, !dne))
+					badcp = rval = 1;
+			}
+			break;
+		case S_IFDIR:
+			if (!Rflag && !rflag) {
+				fprintf(stderr, "%s: %s is a directory (not copied).\n",
+				    argv0, curr->fts_path);
+				(void)fts_set(ftsp, curr, FTS_SKIP);
+				badcp = rval = 1;
+				break;
+			}
+			/*
+			 * If the directory doesn't exist, create the new
+			 * one with the from file mode plus owner RWX bits,
+			 * modified by the umask.  Trade-off between being
+			 * able to write the directory (if from directory is
+			 * 555) and not causing a permissions race.  If the
+			 * umask blocks owner writes, we fail..
+			 */
+			if (dne) {
+				if (mkdir(to.p_path,
+				    curr->fts_statp->st_mode | S_IRWXU) < 0) {
+					fprintf(stderr, "%s: %s: %s\n", argv0, to.p_path, strerror(errno));
+                                        return 1;
+                                }
+			} else if (!S_ISDIR(to_stat.st_mode)) {
+				errno = ENOTDIR;
+				fprintf(stderr, "%s: %s: %s\n", argv0, to.p_path, strerror(errno));
+			}
+			/*
+			 * Arrange to correct directory attributes later
+			 * (in the post-order phase) if this is a new
+			 * directory, or if the -p flag is in effect.
+			 */
+			curr->fts_number = pflag || dne;
+			break;
+		case S_IFBLK:
+		case S_IFCHR:
+			if (Rflag) {
+				if (copy_special(curr->fts_statp, !dne))
+					badcp = rval = 1;
+			} else {
+				if (copy_file(curr, dne))
+					badcp = rval = 1;
+			}
+			break;
+		case S_IFIFO:
+			if (Rflag) {
+				if (copy_fifo(curr->fts_statp, !dne))
+					badcp = rval = 1;
+			} else {
+				if (copy_file(curr, dne))
+					badcp = rval = 1;
+			}
+			break;
+		default:
+			if (copy_file(curr, dne))
+				badcp = rval = 1;
+			break;
+		}
+		if (vflag && !badcp)
+			(void)printf("%s -> %s\n", curr->fts_path, to.p_path);
+	}
+	if (errno) {
+		fprintf(stderr, "%s: fts_read: %s\n", argv0, strerror(errno));
+        }
+	return (rval);
+}
+
+/*
+ * mastercmp --
+ *	The comparison function for the copy order.  The order is to copy
+ *	non-directory files before directory files.  The reason for this
+ *	is because files tend to be in the same cylinder group as their
+ *	parent directory, whereas directories tend not to be.  Copying the
+ *	files first reduces seeking.
+ */
+static int
+mastercmp(const FTSENT * const *a, const FTSENT * const *b)
+{
+	int a_info, b_info;
+
+	a_info = (*a)->fts_info;
+	if (a_info == FTS_ERR || a_info == FTS_NS || a_info == FTS_DNR)
+		return (0);
+	b_info = (*b)->fts_info;
+	if (b_info == FTS_ERR || b_info == FTS_NS || b_info == FTS_DNR)
+		return (0);
+	if (a_info == FTS_D)
+		return (-1);
+	if (b_info == FTS_D)
+		return (1);
+	return (0);
+}
+
+#ifdef SIGINFO
+static void
+siginfo(int sig __unused)
+{
+
+	info = 1;
+}
+#endif
Index: trunk/src/gmake/kmkbuiltin/cp_extern.h
===================================================================
--- trunk/src/gmake/kmkbuiltin/cp_extern.h	(revision 229)
+++ trunk/src/gmake/kmkbuiltin/cp_extern.h	(revision 229)
@@ -0,0 +1,62 @@
+/*-
+ * Copyright (c) 1991, 1993, 1994
+ *	The Regents of the University of California.  All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 4. Neither the name of the University nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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.
+ *
+ *	@(#)extern.h	8.2 (Berkeley) 4/1/94
+ * $FreeBSD: src/bin/cp/extern.h,v 1.19 2004/04/06 20:06:44 markm Exp $
+ */
+
+typedef struct {
+	char	*p_end;			/* pointer to NULL at end of path */
+	char	*target_end;		/* pointer to end of target base */
+	char	p_path[PATH_MAX];	/* pointer to the start of a path */
+} PATH_T;
+
+#define argv0   cp_argv0
+#define to      cp_to
+#define fflag   cp_fflag
+#define iflag   cp_iflag
+#define nflag   cp_nflag
+#define pflag   cp_pflag
+#define vflag   cp_vflag
+#define info    cp_info
+#define usage   cp_usage
+#define setfile cp_setfile
+
+extern const char *argv0;
+extern PATH_T to;
+extern int fflag, iflag, nflag, pflag, vflag;
+extern volatile sig_atomic_t info;
+
+__BEGIN_DECLS
+int	copy_fifo(struct stat *, int);
+int	copy_file(const FTSENT *, int);
+int	copy_link(const FTSENT *, int);
+int	copy_special(struct stat *, int);
+int	setfile(struct stat *, int);
+void	usage(void);
+__END_DECLS
Index: trunk/src/gmake/kmkbuiltin/cp_utils.c
===================================================================
--- trunk/src/gmake/kmkbuiltin/cp_utils.c	(revision 229)
+++ trunk/src/gmake/kmkbuiltin/cp_utils.c	(revision 229)
@@ -0,0 +1,349 @@
+/*-
+ * Copyright (c) 1991, 1993, 1994
+ *	The Regents of the University of California.  All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 4. Neither the name of the University nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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.
+ */
+
+#ifndef lint
+#if 0
+static char sccsid[] = "@(#)utils.c	8.3 (Berkeley) 4/1/94";
+#endif
+#endif /* not lint */
+#include <sys/cdefs.h>
+//__FBSDID("$FreeBSD: src/bin/cp/utils.c,v 1.43 2004/04/06 20:06:44 markm Exp $");
+
+#include <sys/param.h>
+#include <sys/stat.h>
+#ifdef VM_AND_BUFFER_CACHE_SYNCHRONIZED
+#include <sys/mman.h>
+#endif
+
+#include <err.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <fts.h>
+#include <limits.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <sysexits.h>
+#include <unistd.h>
+#include <signal.h>
+
+#include "cp_extern.h"
+#define	cp_pct(x,y)	(int)(100.0 * (double)(x) / (double)(y))
+
+#ifndef MAXBSIZE
+#define MAXBSIZE (128*1024)
+#endif
+
+int
+copy_file(const FTSENT *entp, int dne)
+{
+	static char buf[MAXBSIZE];
+	struct stat *fs;
+	int ch, checkch, from_fd, rcount, rval, to_fd;
+	ssize_t wcount;
+	size_t wresid;
+	size_t wtotal;
+	char *bufp;
+#ifdef VM_AND_BUFFER_CACHE_SYNCHRONIZED
+	char *p;
+#endif
+
+	if ((from_fd = open(entp->fts_path, O_RDONLY, 0)) == -1) {
+		fprintf(stderr, "%s: %s: %s\n", argv0, entp->fts_path, strerror(errno));
+		return (1);
+	}
+
+	fs = entp->fts_statp;
+
+	/*
+	 * If the file exists and we're interactive, verify with the user.
+	 * If the file DNE, set the mode to be the from file, minus setuid
+	 * bits, modified by the umask; arguably wrong, but it makes copying
+	 * executables work right and it's been that way forever.  (The
+	 * other choice is 666 or'ed with the execute bits on the from file
+	 * modified by the umask.)
+	 */
+	if (!dne) {
+#define YESNO "(y/n [n]) "
+		if (nflag) {
+			if (vflag)
+				printf("%s not overwritten\n", to.p_path);
+			return (0);
+		} else if (iflag) {
+			(void)fprintf(stderr, "overwrite %s? %s",
+					to.p_path, YESNO);
+			checkch = ch = getchar();
+			while (ch != '\n' && ch != EOF)
+				ch = getchar();
+			if (checkch != 'y' && checkch != 'Y') {
+				(void)close(from_fd);
+				(void)fprintf(stderr, "not overwritten\n");
+				return (1);
+			}
+		}
+		
+		if (fflag) {
+		    /* remove existing destination file name,
+		     * create a new file  */
+		    (void)unlink(to.p_path);
+		    to_fd = open(to.p_path, O_WRONLY | O_TRUNC | O_CREAT,
+				 fs->st_mode & ~(S_ISUID | S_ISGID));
+		} else
+		    /* overwrite existing destination file name */
+		    to_fd = open(to.p_path, O_WRONLY | O_TRUNC, 0);
+	} else
+		to_fd = open(to.p_path, O_WRONLY | O_TRUNC | O_CREAT,
+		    fs->st_mode & ~(S_ISUID | S_ISGID));
+
+	if (to_fd == -1) {
+		fprintf(stderr, "%s: %s: %s\n", argv0, to.p_path, strerror(errno));
+		(void)close(from_fd);
+		return (1);
+	}
+
+	rval = 0;
+
+	/*
+	 * Mmap and write if less than 8M (the limit is so we don't totally
+	 * trash memory on big files.  This is really a minor hack, but it
+	 * wins some CPU back.
+	 */
+#ifdef VM_AND_BUFFER_CACHE_SYNCHRONIZED
+	if (S_ISREG(fs->st_mode) && fs->st_size > 0 &&
+	    fs->st_size <= 8 * 1048576) {
+		if ((p = mmap(NULL, (size_t)fs->st_size, PROT_READ,
+		    MAP_SHARED, from_fd, (off_t)0)) == MAP_FAILED) {
+			fprintf(stderr, "%s: %s: %s\n", argv0, entp->fts_path, strerror(errno));
+			rval = 1;
+		} else {
+			wtotal = 0;
+			for (bufp = p, wresid = fs->st_size; ;
+			    bufp += wcount, wresid -= (size_t)wcount) {
+				wcount = write(to_fd, bufp, wresid);
+				wtotal += wcount;
+				if (info) {
+					info = 0;
+					(void)fprintf(stderr,
+						"%s -> %s %3d%%\n",
+						entp->fts_path, to.p_path,
+						cp_pct(wtotal, fs->st_size));
+						
+				}
+				if (wcount >= (ssize_t)wresid || wcount <= 0)
+					break;
+			}
+			if (wcount != (ssize_t)wresid) {
+				fprintf(stderr, "%s: %s: %s\n", argv0, to.p_path, strerror(errno));
+				rval = 1;
+			}
+			/* Some systems don't unmap on close(2). */
+			if (munmap(p, fs->st_size) < 0) {
+				fprintf(stderr, "%s: %s: %s\n", entp->fts_path, strerror(errno));
+				rval = 1;
+			}
+		}
+	} else
+#endif
+	{
+		wtotal = 0;
+		while ((rcount = read(from_fd, buf, MAXBSIZE)) > 0) {
+			for (bufp = buf, wresid = rcount; ;
+			    bufp += wcount, wresid -= wcount) {
+				wcount = write(to_fd, bufp, wresid);
+				wtotal += wcount;
+				if (info) {
+					info = 0;
+					(void)fprintf(stderr,
+						"%s -> %s %3d%%\n",
+						entp->fts_path, to.p_path,
+						cp_pct(wtotal, fs->st_size));
+						
+				}
+				if (wcount >= (ssize_t)wresid || wcount <= 0)
+					break;
+			}
+			if (wcount != (ssize_t)wresid) {
+				fprintf(stderr, "%s: %s: %s\n", argv0, to.p_path, strerror(errno));
+				rval = 1;
+				break;
+			}
+		}
+		if (rcount < 0) {
+			fprintf(stderr, "%s: %s: %s\n", argv0, entp->fts_path, strerror(errno));
+			rval = 1;
+		}
+	}
+
+	/*
+	 * Don't remove the target even after an error.  The target might
+	 * not be a regular file, or its attributes might be important,
+	 * or its contents might be irreplaceable.  It would only be safe
+	 * to remove it if we created it and its length is 0.
+	 */
+
+	if (pflag && setfile(fs, to_fd))
+		rval = 1;
+	(void)close(from_fd);
+	if (close(to_fd)) {
+		fprintf(stderr, "%s: %s: %s\n", argv0, to.p_path, strerror(errno));
+		rval = 1;
+	}
+	return (rval);
+}
+
+int
+copy_link(const FTSENT *p, int exists)
+{
+	int len;
+	char llink[PATH_MAX];
+
+	if ((len = readlink(p->fts_path, llink, sizeof(llink) - 1)) == -1) {
+		fprintf(stderr, "%s: readlink: %s: %s\n", argv0, p->fts_path, strerror(errno));
+		return (1);
+	}
+	llink[len] = '\0';
+	if (exists && unlink(to.p_path)) {
+		fprintf(stderr, "%s: unlink: %s: %s\n", argv0, to.p_path, strerror(errno));
+		return (1);
+	}
+	if (symlink(llink, to.p_path)) {
+		fprintf(stderr, "%s: symlink: %s: %s\n", argv0, llink, strerror(errno));
+		return (1);
+	}
+	return (pflag ? setfile(p->fts_statp, -1) : 0);
+}
+
+int
+copy_fifo(struct stat *from_stat, int exists)
+{
+	if (exists && unlink(to.p_path)) {
+		fprintf(stderr, "%s: unlink: %s: %s\n", argv0, to.p_path, strerror(errno));
+		return (1);
+	}
+	if (mkfifo(to.p_path, from_stat->st_mode)) {
+		fprintf(stderr, "%s: mkfifo: %s\n", argv0, to.p_path, strerror(errno));
+		return (1);
+	}
+	return (pflag ? setfile(from_stat, -1) : 0);
+}
+
+int
+copy_special(struct stat *from_stat, int exists)
+{
+	if (exists && unlink(to.p_path)) {
+		fprintf(stderr, "%s: unlink: %s: %s\n", argv0, to.p_path, strerror(errno));
+		return (1);
+	}
+	if (mknod(to.p_path, from_stat->st_mode, from_stat->st_rdev)) {
+		fprintf(stderr, "%s: mknod: %s: %s\n", argv0, to.p_path, strerror(errno));
+		return (1);
+	}
+	return (pflag ? setfile(from_stat, -1) : 0);
+}
+
+int
+setfile(struct stat *fs, int fd)
+{
+	static struct timeval tv[2];
+	struct stat ts;
+	int rval, gotstat, islink, fdval;
+
+	rval = 0;
+	fdval = fd != -1;
+	islink = !fdval && S_ISLNK(fs->st_mode);
+	fs->st_mode &= S_ISUID | S_ISGID | S_ISVTX |
+		       S_IRWXU | S_IRWXG | S_IRWXO;
+
+#ifdef HAVE_ST_TIMESPEC
+	TIMESPEC_TO_TIMEVAL(&tv[0], &fs->st_atimespec);
+	TIMESPEC_TO_TIMEVAL(&tv[1], &fs->st_mtimespec);
+#else
+        tv[0].tv_sec = fs->st_atime;
+        tv[1].tv_sec = fs->st_mtime;
+        tv[0].tv_usec = tv[1].tv_usec = 0;
+#endif
+	if (islink ? lutimes(to.p_path, tv) : utimes(to.p_path, tv)) {
+		fprintf(stderr, "%s: %sutimes: %s: %s\n", argv0, islink ? "l" : "", to.p_path, strerror(errno));
+		rval = 1;
+	}
+	if (fdval ? fstat(fd, &ts) :
+	    (islink ? lstat(to.p_path, &ts) : stat(to.p_path, &ts)))
+		gotstat = 0;
+	else {
+		gotstat = 1;
+		ts.st_mode &= S_ISUID | S_ISGID | S_ISVTX |
+			      S_IRWXU | S_IRWXG | S_IRWXO;
+	}
+	/*
+	 * Changing the ownership probably won't succeed, unless we're root
+	 * or POSIX_CHOWN_RESTRICTED is not set.  Set uid/gid before setting
+	 * the mode; current BSD behavior is to remove all setuid bits on
+	 * chown.  If chown fails, lose setuid/setgid bits.
+	 */
+	if (!gotstat || fs->st_uid != ts.st_uid || fs->st_gid != ts.st_gid)
+		if (fdval ? fchown(fd, fs->st_uid, fs->st_gid) :
+		    (islink ? lchown(to.p_path, fs->st_uid, fs->st_gid) :
+		    chown(to.p_path, fs->st_uid, fs->st_gid))) {
+			if (errno != EPERM) {
+				fprintf(stderr, "%s: chown: %s: %s\n", argv0, to.p_path, strerror(errno));
+				rval = 1;
+			}
+			fs->st_mode &= ~(S_ISUID | S_ISGID);
+		}
+
+	if (!gotstat || fs->st_mode != ts.st_mode)
+		if (fdval ? fchmod(fd, fs->st_mode) :
+		    (islink ? lchmod(to.p_path, fs->st_mode) :
+		    chmod(to.p_path, fs->st_mode))) {
+			fprintf(stderr, "%s: chmod: %s: %s\n", to.p_path, strerror(errno));
+			rval = 1;
+		}
+
+#ifdef HAVE_ST_FLAGS
+	if (!gotstat || fs->st_flags != ts.st_flags)
+		if (fdval ?
+		    fchflags(fd, fs->st_flags) :
+		    (islink ? (errno = ENOSYS) :
+		    chflags(to.p_path, fs->st_flags))) {
+			fprintf(stderr, "%s: chflags: %s: %s", argv0, to.p_path, strerror(errno));
+			rval = 1;
+		}
+#endif
+
+	return (rval);
+}
+
+void
+usage(void)
+{
+
+	(void)fprintf(stderr, "%s\n%s\n",
+"usage: cp [-R [-H | -L | -P]] [-f | -i | -n] [-pv] src target",
+"       cp [-R [-H | -L | -P]] [-f | -i | -n] [-pv] src1 ... srcN directory");
+	exit(EX_USAGE);
+}
Index: trunk/src/gmake/kmkbuiltin/strlcpy.c
===================================================================
--- trunk/src/gmake/kmkbuiltin/strlcpy.c	(revision 229)
+++ trunk/src/gmake/kmkbuiltin/strlcpy.c	(revision 229)
@@ -0,0 +1,70 @@
+/*	$OpenBSD: strlcpy.c,v 1.4 1999/05/01 18:56:41 millert Exp $	*/
+
+/*
+ * Copyright (c) 1998 Todd C. Miller <Todd.Miller@courtesan.com>
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ *    derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED ``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 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.
+ */
+
+#if defined(LIBC_SCCS) && !defined(lint)
+static char *rcsid = "$OpenBSD: strlcpy.c,v 1.4 1999/05/01 18:56:41 millert Exp $");
+#endif /* LIBC_SCCS and not lint */
+#include <sys/cdefs.h>
+//__FBSDID("$FreeBSD: src/lib/libc/string/strlcpy.c,v 1.7 2003/05/01 19:03:14 nectar Exp $");
+
+#include <sys/types.h>
+#include <string.h>
+
+/*
+ * Copy src to string dst of size siz.  At most siz-1 characters
+ * will be copied.  Always NUL terminates (unless siz == 0).
+ * Returns strlen(src); if retval >= siz, truncation occurred.
+ */
+size_t strlcpy(dst, src, siz)
+	char *dst;
+	const char *src;
+	size_t siz;
+{
+	char *d = dst;
+	const char *s = src;
+	size_t n = siz;
+
+	/* Copy as many bytes as will fit */
+	if (n != 0 && --n != 0) {
+		do {
+			if ((*d++ = *s++) == 0)
+				break;
+		} while (--n != 0);
+	}
+
+	/* Not enough room in dst, add NUL and traverse rest of src */
+	if (n == 0) {
+		if (siz != 0)
+			*d = '\0';		/* NUL-terminate dst */
+		while (*s++)
+			;
+	}
+
+	return(s - src - 1);	/* count does not include NUL */
+}
