Ported "cp" from NetBSD to toolbox.

Bug: 6798417
Change-Id: I716ab459b9edf4c7405bf042adbee0300b6f51c9
diff --git a/toolbox/Android.mk b/toolbox/Android.mk
index c1f165c..4fdb8f6 100644
--- a/toolbox/Android.mk
+++ b/toolbox/Android.mk
@@ -56,7 +56,7 @@
 	ionice \
 	touch \
 	lsof \
-        du \
+	du \
 	md5
 
 ifeq ($(HAVE_SELINUX),true)
@@ -78,10 +78,15 @@
 TOOLS += r
 endif
 
-LOCAL_SRC_FILES:= \
+ALL_TOOLS = $(TOOLS)
+ALL_TOOLS += \
+	cp
+
+LOCAL_SRC_FILES := \
 	dynarray.c \
 	toolbox.c \
-	$(patsubst %,%.c,$(TOOLS))
+	$(patsubst %,%.c,$(TOOLS)) \
+	cp/cp.c cp/utils.c
 
 LOCAL_SHARED_LIBRARIES := libcutils libc libusbhost
 
@@ -95,7 +100,7 @@
 
 endif
 
-LOCAL_MODULE:= toolbox
+LOCAL_MODULE := toolbox
 
 # Including this will define $(intermediates).
 #
@@ -104,7 +109,7 @@
 $(LOCAL_PATH)/toolbox.c: $(intermediates)/tools.h
 
 TOOLS_H := $(intermediates)/tools.h
-$(TOOLS_H): PRIVATE_TOOLS := $(TOOLS)
+$(TOOLS_H): PRIVATE_TOOLS := $(ALL_TOOLS)
 $(TOOLS_H): PRIVATE_CUSTOM_TOOL = echo "/* file generated automatically */" > $@ ; for t in $(PRIVATE_TOOLS) ; do echo "TOOL($$t)" >> $@ ; done
 $(TOOLS_H): $(LOCAL_PATH)/Android.mk
 $(TOOLS_H):
@@ -112,7 +117,7 @@
 
 # Make #!/system/bin/toolbox launchers for each tool.
 #
-SYMLINKS := $(addprefix $(TARGET_OUT)/bin/,$(TOOLS))
+SYMLINKS := $(addprefix $(TARGET_OUT)/bin/,$(ALL_TOOLS))
 $(SYMLINKS): TOOLBOX_BINARY := $(LOCAL_MODULE)
 $(SYMLINKS): $(LOCAL_INSTALLED_MODULE) $(LOCAL_PATH)/Android.mk
 	@echo "Symlink: $@ -> $(TOOLBOX_BINARY)"
diff --git a/toolbox/cp/cp.c b/toolbox/cp/cp.c
new file mode 100644
index 0000000..bd3c70e
--- /dev/null
+++ b/toolbox/cp/cp.c
@@ -0,0 +1,552 @@
+/* $NetBSD: cp.c,v 1.58 2012/01/04 15:58:37 christos Exp $ */
+
+/*
+ * 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#ifndef lint
+__COPYRIGHT(
+"@(#) Copyright (c) 1988, 1993, 1994\
+ The Regents of the University of California.  All rights reserved.");
+#endif /* not lint */
+
+#ifndef lint
+#if 0
+static char sccsid[] = "@(#)cp.c	8.5 (Berkeley) 4/29/95";
+#else
+__RCSID("$NetBSD: cp.c,v 1.58 2012/01/04 15:58:37 christos Exp $");
+#endif
+#endif /* not lint */
+
+/*
+ * 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/param.h>
+#include <sys/stat.h>
+
+#include <assert.h>
+#include <err.h>
+#include <errno.h>
+#include <fts.h>
+#include <locale.h>
+#include <signal.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <unistd.h>
+
+#include "extern.h"
+
+#define	STRIP_TRAILING_SLASH(p) {					\
+        while ((p).p_end > (p).p_path + 1 && (p).p_end[-1] == '/')	\
+                *--(p).p_end = '\0';					\
+}
+
+static char empty[] = "";
+PATH_T to = { .p_end = to.p_path, .target_end = empty  };
+
+uid_t myuid;
+int Hflag, Lflag, Rflag, Pflag, fflag, iflag, lflag, pflag, rflag, vflag, Nflag;
+mode_t myumask;
+sig_atomic_t pinfo;
+
+enum op { FILE_TO_FILE, FILE_TO_DIR, DIR_TO_DNE };
+
+static int copy(char *[], enum op, int);
+
+static void
+progress(int sig __unused)
+{
+
+	pinfo++;
+}
+
+int
+cp_main(int argc, char *argv[])
+{
+	struct stat to_stat, tmp_stat;
+	enum op type;
+	int ch, fts_options, r, have_trailing_slash;
+	char *target, **src;
+
+#ifndef ANDROID
+	setprogname(argv[0]);
+#endif
+	(void)setlocale(LC_ALL, "");
+
+	Hflag = Lflag = Pflag = Rflag = 0;
+	while ((ch = getopt(argc, argv, "HLNPRfailprv")) != -1)
+		switch (ch) {
+		case 'H':
+			Hflag = 1;
+			Lflag = Pflag = 0;
+			break;
+		case 'L':
+			Lflag = 1;
+			Hflag = Pflag = 0;
+			break;
+		case 'N':
+			Nflag = 1;
+			break;
+		case 'P':
+			Pflag = 1;
+			Hflag = Lflag = 0;
+			break;
+		case 'R':
+			Rflag = 1;
+			break;
+		case 'a':
+			Pflag = 1;
+			pflag = 1;
+			Rflag = 1;
+			Hflag = Lflag = 0;
+			break;
+		case 'f':
+			fflag = 1;
+			iflag = 0;
+			break;
+		case 'i':
+			iflag = isatty(fileno(stdin));
+			fflag = 0;
+			break;
+		case 'l':
+			lflag = 1;
+			break;
+		case 'p':
+			pflag = 1;
+			break;
+		case 'r':
+			rflag = 1;
+			break;
+		case 'v':
+			vflag = 1;
+			break;
+		case '?':
+		default:
+			cp_usage();
+			/* NOTREACHED */
+		}
+	argc -= optind;
+	argv += optind;
+
+	if (argc < 2)
+		cp_usage();
+
+	fts_options = FTS_NOCHDIR | FTS_PHYSICAL;
+	if (rflag) {
+		if (Rflag) {
+			errx(EXIT_FAILURE,
+		    "the -R and -r options may not be specified together.");
+			/* NOTREACHED */
+		}
+		if (Hflag || Lflag || Pflag) {
+			errx(EXIT_FAILURE,
+	"the -H, -L, and -P options may not be specified with the -r option.");
+			/* NOTREACHED */
+		}
+		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 if (!Pflag) {
+		fts_options &= ~FTS_PHYSICAL;
+		fts_options |= FTS_LOGICAL | FTS_COMFOLLOW;
+	}
+
+	myuid = getuid();
+
+	/* Copy the umask for explicit mode setting. */
+	myumask = umask(0);
+	(void)umask(myumask);
+
+	/* Save the target base in "to". */
+	target = argv[--argc];
+	if (strlcpy(to.p_path, target, sizeof(to.p_path)) >= sizeof(to.p_path))
+		errx(EXIT_FAILURE, "%s: name too long", target);
+	to.p_end = to.p_path + strlen(to.p_path);
+	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;
+
+#ifndef ANDROID
+	(void)signal(SIGINFO, progress);
+#endif
+
+	/*
+	 * 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".
+	 */
+	if (Pflag)
+		r = lstat(to.p_path, &to_stat);
+	else
+		r = stat(to.p_path, &to_stat);
+	if (r == -1 && errno != ENOENT) {
+		err(EXIT_FAILURE, "%s", to.p_path);
+		/* NOTREACHED */
+	}
+	if (r == -1 || !S_ISDIR(to_stat.st_mode)) {
+		/*
+		 * Case (1).  Target is not a directory.
+		 */
+		if (argc > 1)
+			cp_usage();
+		/*
+		 * 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)))
+				r = stat(*argv, &tmp_stat);
+			else
+				r = lstat(*argv, &tmp_stat);
+			if (r == -1) {
+				err(EXIT_FAILURE, "%s", *argv);
+				/* NOTREACHED */
+			}
+
+			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)
+				errx(1, "directory %s does not exist",
+				     to.p_path);
+			else
+				errx(1, "%s is not a directory", to.p_path);
+		}
+	} else {
+		/*
+		 * Case (2).  Target is a directory.
+		 */
+		type = FILE_TO_DIR;
+	}
+
+	/*
+	 * make "cp -rp src/ dst" behave like "cp -rp src dst" not
+	 * like "cp -rp src/. dst"
+	 */
+	for (src = argv; *src; src++) {
+		size_t len = strlen(*src);
+		while (len-- > 1 && (*src)[len] == '/')
+			(*src)[len] = '\0';
+	}
+
+	exit(copy(argv, type, fts_options));
+	/* NOTREACHED */
+}
+
+static int dnestack[MAXPATHLEN]; /* unlikely we'll have more nested dirs */
+static ssize_t dnesp;
+static void
+pushdne(int dne)
+{
+
+	dnestack[dnesp++] = dne;
+	assert(dnesp < MAXPATHLEN);
+}
+
+static int
+popdne(void)
+{
+	int rv;
+
+	rv = dnestack[--dnesp];
+	assert(dnesp >= 0);
+	return rv;
+}
+
+static int
+copy(char *argv[], enum op type, int fts_options)
+{
+	struct stat to_stat;
+	FTS *ftsp;
+	FTSENT *curr;
+	int base, dne, sval;
+	int this_failed, any_failed;
+	size_t nlen;
+	char *p, *target_mid;
+
+	base = 0;	/* XXX gcc -Wuninitialized (see comment below) */
+
+	if ((ftsp = fts_open(argv, fts_options, NULL)) == NULL)
+		err(EXIT_FAILURE, "%s", argv[0]);
+		/* NOTREACHED */
+	for (any_failed = 0; (curr = fts_read(ftsp)) != NULL;) {
+		this_failed = 0;
+		switch (curr->fts_info) {
+		case FTS_NS:
+		case FTS_DNR:
+		case FTS_ERR:
+			warnx("%s: %s", curr->fts_path,
+					strerror(curr->fts_errno));
+			this_failed = any_failed = 1;
+			continue;
+		case FTS_DC:			/* Warn, continue. */
+			warnx("%s: directory causes a cycle", curr->fts_path);
+			this_failed = any_failed = 1;
+			continue;
+		}
+
+		/*
+		 * 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) {
+			if ((curr->fts_namelen +
+			    to.target_end - to.p_path + 1) > MAXPATHLEN) {
+				warnx("%s/%s: name too long (not copied)",
+						to.p_path, curr->fts_name);
+				this_failed = any_failed = 1;
+				continue;
+			}
+
+			/*
+			 * 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
+			 * concatentation 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) {
+				warnx("%s%s: name too long (not copied)",
+				    to.p_path, p);
+				this_failed = any_failed = 1;
+				continue;
+			}
+			(void)strncat(target_mid, p, nlen);
+			to.p_end = target_mid + nlen;
+			*to.p_end = 0;
+			STRIP_TRAILING_SLASH(to);
+		}
+
+		sval = Pflag ? lstat(to.p_path, &to_stat) : stat(to.p_path, &to_stat);
+		/* Not an error but need to remember it happened */
+		if (sval == -1)
+			dne = 1;
+		else {
+			if (to_stat.st_dev == curr->fts_statp->st_dev &&
+			    to_stat.st_ino == curr->fts_statp->st_ino) {
+				warnx("%s and %s are identical (not copied).",
+				    to.p_path, curr->fts_path);
+				this_failed = any_failed = 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)) {
+		warnx("cannot overwrite directory %s with non-directory %s",
+				    to.p_path, curr->fts_path);
+				this_failed = any_failed = 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))
+					this_failed = any_failed = 1;
+			} else {
+				if (copy_link(curr, !dne))
+					this_failed = any_failed = 1;
+			}
+			break;
+		case S_IFDIR:
+			if (!Rflag && !rflag) {
+				if (curr->fts_info == FTS_D)
+					warnx("%s is a directory (not copied).",
+					    curr->fts_path);
+				(void)fts_set(ftsp, curr, FTS_SKIP);
+				this_failed = any_failed = 1;
+				break;
+			}
+
+                        /*
+                         * Directories get noticed twice:
+                         *  In the first pass, create it if needed.
+                         *  In the second pass, after the children have been copied, set the permissions.
+                         */
+			if (curr->fts_info == FTS_D) /* First pass */
+			{
+				/*
+				 * 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..
+				 */
+				pushdne(dne);
+				if (dne) {
+					if (mkdir(to.p_path,
+					    curr->fts_statp->st_mode | S_IRWXU) < 0)
+						err(EXIT_FAILURE, "%s",
+						    to.p_path);
+						/* NOTREACHED */
+				} else if (!S_ISDIR(to_stat.st_mode)) {
+					errno = ENOTDIR;
+					err(EXIT_FAILURE, "%s",
+						to.p_path);
+					/* NOTREACHED */
+				}
+			}
+			else if (curr->fts_info == FTS_DP) /* Second pass */
+			{
+	                        /*
+				 * If not -p and directory didn't exist, set it to be
+				 * the same as the from directory, umodified by the
+				 * umask; arguably wrong, but it's been that way
+				 * forever.
+				 */
+				if (pflag && setfile(curr->fts_statp, 0))
+					this_failed = any_failed = 1;
+				else if ((dne = popdne()))
+					(void)chmod(to.p_path,
+					    curr->fts_statp->st_mode);
+			}
+			else
+			{
+				warnx("directory %s encountered when not expected.",
+				    curr->fts_path);
+				this_failed = any_failed = 1;
+				break;
+			}
+
+			break;
+		case S_IFBLK:
+		case S_IFCHR:
+			if (Rflag) {
+				if (copy_special(curr->fts_statp, !dne))
+					this_failed = any_failed = 1;
+			} else
+				if (copy_file(curr, dne))
+					this_failed = any_failed = 1;
+			break;
+		case S_IFIFO:
+			if (Rflag) {
+				if (copy_fifo(curr->fts_statp, !dne))
+					this_failed = any_failed = 1;
+			} else
+				if (copy_file(curr, dne))
+					this_failed = any_failed = 1;
+			break;
+		default:
+			if (copy_file(curr, dne))
+				this_failed = any_failed = 1;
+			break;
+		}
+		if (vflag && !this_failed)
+			(void)printf("%s -> %s\n", curr->fts_path, to.p_path);
+	}
+	if (errno) {
+		err(EXIT_FAILURE, "fts_read");
+		/* NOTREACHED */
+	}
+	(void)fts_close(ftsp);
+	return (any_failed);
+}
diff --git a/toolbox/cp/extern.h b/toolbox/cp/extern.h
new file mode 100644
index 0000000..ffbadf7
--- /dev/null
+++ b/toolbox/cp/extern.h
@@ -0,0 +1,61 @@
+/* $NetBSD: extern.h,v 1.17 2012/01/04 15:58:37 christos Exp $ */
+
+/*-
+ * 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.
+ * 3. 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
+ */
+
+#ifndef _EXTERN_H_
+#define _EXTERN_H_
+
+typedef struct {
+	char *p_end;			/* pointer to NULL at end of path */
+	char *target_end;		/* pointer to end of target base */
+	char p_path[MAXPATHLEN + 1];	/* pointer to the start of a path */
+} PATH_T;
+
+extern PATH_T to;
+extern uid_t myuid;
+extern int Rflag, rflag, Hflag, Lflag, Pflag, fflag, iflag, lflag, pflag, Nflag;
+extern mode_t myumask;
+extern sig_atomic_t pinfo;
+
+#include <sys/cdefs.h>
+
+__BEGIN_DECLS
+int	copy_fifo(struct stat *, int);
+int	copy_file(FTSENT *, int);
+int	copy_link(FTSENT *, int);
+int	copy_special(struct stat *, int);
+int	set_utimes(const char *, struct stat *);
+int	setfile(struct stat *, int);
+void cp_usage(void) __attribute__((__noreturn__));
+__END_DECLS
+
+#endif /* !_EXTERN_H_ */
diff --git a/toolbox/cp/utils.c b/toolbox/cp/utils.c
new file mode 100644
index 0000000..b682bbe
--- /dev/null
+++ b/toolbox/cp/utils.c
@@ -0,0 +1,446 @@
+/* $NetBSD: utils.c,v 1.41 2012/01/04 15:58:37 christos Exp $ */
+
+/*-
+ * 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.
+ * 3. 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.
+ */
+
+#include <sys/cdefs.h>
+#ifndef lint
+#if 0
+static char sccsid[] = "@(#)utils.c	8.3 (Berkeley) 4/1/94";
+#else
+__RCSID("$NetBSD: utils.c,v 1.41 2012/01/04 15:58:37 christos Exp $");
+#endif
+#endif /* not lint */
+
+#include <sys/mman.h>
+#include <sys/param.h>
+#include <sys/stat.h>
+#include <sys/time.h>
+#ifndef ANDROID
+#include <sys/extattr.h>
+#endif
+
+#include <err.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <fts.h>
+#include <stdbool.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+#include "extern.h"
+
+#ifdef ANDROID
+#define MAXBSIZE 65536
+#endif
+
+#define	MMAP_MAX_SIZE	(8 * 1048576)
+#define	MMAP_MAX_WRITE	(64 * 1024)
+
+int
+set_utimes(const char *file, struct stat *fs)
+{
+    static struct timeval tv[2];
+
+#ifdef ANDROID
+    tv[0].tv_sec = fs->st_atime;
+    tv[0].tv_usec = 0;
+    tv[1].tv_sec = fs->st_mtime;
+    tv[1].tv_usec = 0;
+
+    if (utimes(file, tv)) {
+        warn("utimes: %s", file);
+        return 1;
+    }
+#else
+    TIMESPEC_TO_TIMEVAL(&tv[0], &fs->st_atimespec);
+    TIMESPEC_TO_TIMEVAL(&tv[1], &fs->st_mtimespec);
+
+    if (lutimes(file, tv)) {
+    warn("lutimes: %s", file);
+    return (1);
+    }
+#endif
+    return (0);
+}
+
+struct finfo {
+	const char *from;
+	const char *to;
+	size_t size;
+};
+
+static void
+progress(const struct finfo *fi, size_t written)
+{
+	int pcent = (int)((100.0 * written) / fi->size);
+
+	pinfo = 0;
+	(void)fprintf(stderr, "%s => %s %zu/%zu bytes %d%% written\n",
+	    fi->from, fi->to, written, fi->size, pcent);
+}
+
+int
+copy_file(FTSENT *entp, int dne)
+{
+	static char buf[MAXBSIZE];
+	struct stat to_stat, *fs;
+	int ch, checkch, from_fd, rcount, rval, to_fd, tolnk, wcount;
+	char *p;
+	size_t ptotal = 0;
+
+	if ((from_fd = open(entp->fts_path, O_RDONLY, 0)) == -1) {
+		warn("%s", entp->fts_path);
+		return (1);
+	}
+
+	to_fd = -1;
+	fs = entp->fts_statp;
+	tolnk = ((Rflag && !(Lflag || Hflag)) || Pflag);
+
+	/*
+	 * 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) {
+		struct stat sb;
+		int sval;
+
+		if (iflag) {
+			(void)fprintf(stderr, "overwrite %s? ", to.p_path);
+			checkch = ch = getchar();
+			while (ch != '\n' && ch != EOF)
+				ch = getchar();
+			if (checkch != 'y' && checkch != 'Y') {
+				(void)close(from_fd);
+				return (0);
+			}
+		}
+
+		sval = tolnk ?
+			lstat(to.p_path, &sb) : stat(to.p_path, &sb);
+		if (sval == -1) {
+			warn("stat: %s", to.p_path);
+			(void)close(from_fd);
+			return (1);
+		}
+
+		if (!(tolnk && S_ISLNK(sb.st_mode)))
+			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 && (fflag || tolnk)) {
+		/*
+		 * attempt to remove existing destination file name and
+		 * 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));
+	}
+
+	if (to_fd == -1) {
+		warn("%s", to.p_path);
+		(void)close(from_fd);
+		return (1);
+	}
+
+	rval = 0;
+
+	/* if hard linking then simply close the open fds, link and return */
+	if (lflag) {
+		(void)close(from_fd);
+		(void)close(to_fd);
+		(void)unlink(to.p_path);
+		if (link(entp->fts_path, to.p_path)) {
+			warn("%s", to.p_path);
+			return (1);
+		}
+		return (0);
+	}
+	/* NOTREACHED */
+
+	/*
+	 * There's no reason to do anything other than close the file
+	 * now if it's empty, so let's not bother.
+	 */
+	if (fs->st_size > 0) {
+		struct finfo fi;
+
+		fi.from = entp->fts_path;
+		fi.to = to.p_path;
+		fi.size = (size_t)fs->st_size;
+
+		/*
+		 * 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.
+		 */
+		bool use_read;
+
+		use_read = true;
+		if (fs->st_size <= MMAP_MAX_SIZE) {
+			size_t fsize = (size_t)fs->st_size;
+			p = mmap(NULL, fsize, PROT_READ, MAP_FILE|MAP_SHARED,
+			    from_fd, (off_t)0);
+			if (p != MAP_FAILED) {
+				size_t remainder;
+
+				use_read = false;
+
+				(void) madvise(p, (size_t)fs->st_size,
+				     MADV_SEQUENTIAL);
+
+				/*
+				 * Write out the data in small chunks to
+				 * avoid locking the output file for a
+				 * long time if the reading the data from
+				 * the source is slow.
+				 */
+				remainder = fsize;
+				do {
+					ssize_t chunk;
+
+					chunk = (remainder > MMAP_MAX_WRITE) ?
+					    MMAP_MAX_WRITE : remainder;
+					if (write(to_fd, &p[fsize - remainder],
+					    chunk) != chunk) {
+						warn("%s", to.p_path);
+						rval = 1;
+						break;
+					}
+					remainder -= chunk;
+					ptotal += chunk;
+					if (pinfo)
+						progress(&fi, ptotal);
+				} while (remainder > 0);
+
+				if (munmap(p, fsize) < 0) {
+					warn("%s", entp->fts_path);
+					rval = 1;
+				}
+			}
+		}
+
+		if (use_read) {
+			while ((rcount = read(from_fd, buf, MAXBSIZE)) > 0) {
+				wcount = write(to_fd, buf, (size_t)rcount);
+				if (rcount != wcount || wcount == -1) {
+					warn("%s", to.p_path);
+					rval = 1;
+					break;
+				}
+				ptotal += wcount;
+				if (pinfo)
+					progress(&fi, ptotal);
+			}
+			if (rcount < 0) {
+				warn("%s", entp->fts_path);
+				rval = 1;
+			}
+		}
+	}
+
+#ifndef ANDROID
+	if (pflag && (fcpxattr(from_fd, to_fd) != 0))
+		warn("%s: error copying extended attributes", to.p_path);
+#endif
+
+	(void)close(from_fd);
+
+	if (rval == 1) {
+		(void)close(to_fd);
+		return (1);
+	}
+
+	if (pflag && setfile(fs, to_fd))
+		rval = 1;
+	/*
+	 * If the source was setuid or setgid, lose the bits unless the
+	 * copy is owned by the same user and group.
+	 */
+#define	RETAINBITS \
+	(S_ISUID | S_ISGID | S_ISVTX | S_IRWXU | S_IRWXG | S_IRWXO)
+	if (!pflag && dne
+	    && fs->st_mode & (S_ISUID | S_ISGID) && fs->st_uid == myuid) {
+		if (fstat(to_fd, &to_stat)) {
+			warn("%s", to.p_path);
+			rval = 1;
+		} else if (fs->st_gid == to_stat.st_gid &&
+		    fchmod(to_fd, fs->st_mode & RETAINBITS & ~myumask)) {
+			warn("%s", to.p_path);
+			rval = 1;
+		}
+	}
+	if (close(to_fd)) {
+		warn("%s", to.p_path);
+		rval = 1;
+	}
+	/* set the mod/access times now after close of the fd */
+	if (pflag && set_utimes(to.p_path, fs)) {
+	    rval = 1;
+	}
+	return (rval);
+}
+
+int
+copy_link(FTSENT *p, int exists)
+{
+	int len;
+	char target[MAXPATHLEN];
+
+	if ((len = readlink(p->fts_path, target, sizeof(target)-1)) == -1) {
+		warn("readlink: %s", p->fts_path);
+		return (1);
+	}
+	target[len] = '\0';
+	if (exists && unlink(to.p_path)) {
+		warn("unlink: %s", to.p_path);
+		return (1);
+	}
+	if (symlink(target, to.p_path)) {
+		warn("symlink: %s", target);
+		return (1);
+	}
+	return (pflag ? setfile(p->fts_statp, 0) : 0);
+}
+
+int
+copy_fifo(struct stat *from_stat, int exists)
+{
+	if (exists && unlink(to.p_path)) {
+		warn("unlink: %s", to.p_path);
+		return (1);
+	}
+	if (mkfifo(to.p_path, from_stat->st_mode)) {
+		warn("mkfifo: %s", to.p_path);
+		return (1);
+	}
+	return (pflag ? setfile(from_stat, 0) : 0);
+}
+
+int
+copy_special(struct stat *from_stat, int exists)
+{
+	if (exists && unlink(to.p_path)) {
+		warn("unlink: %s", to.p_path);
+		return (1);
+	}
+	if (mknod(to.p_path, from_stat->st_mode, from_stat->st_rdev)) {
+		warn("mknod: %s", to.p_path);
+		return (1);
+	}
+	return (pflag ? setfile(from_stat, 0) : 0);
+}
+
+
+/*
+ * Function: setfile
+ *
+ * Purpose:
+ *   Set the owner/group/permissions for the "to" file to the information
+ *   in the stat structure.  If fd is zero, also call set_utimes() to set
+ *   the mod/access times.  If fd is non-zero, the caller must do a utimes
+ *   itself after close(fd).
+ */
+int
+setfile(struct stat *fs, int fd)
+{
+	int rval, islink;
+
+	rval = 0;
+	islink = S_ISLNK(fs->st_mode);
+	fs->st_mode &= S_ISUID | S_ISGID | 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 (fd ? fchown(fd, fs->st_uid, fs->st_gid) :
+	    lchown(to.p_path, fs->st_uid, fs->st_gid)) {
+		if (errno != EPERM) {
+			warn("chown: %s", to.p_path);
+			rval = 1;
+		}
+		fs->st_mode &= ~(S_ISUID | S_ISGID);
+	}
+#ifdef ANDROID
+    if (fd ? fchmod(fd, fs->st_mode) : chmod(to.p_path, fs->st_mode)) {
+#else
+    if (fd ? fchmod(fd, fs->st_mode) : lchmod(to.p_path, fs->st_mode)) {
+#endif
+        warn("chmod: %s", to.p_path);
+        rval = 1;
+    }
+
+#ifndef ANDROID
+	if (!islink && !Nflag) {
+		unsigned long fflags = fs->st_flags;
+		/*
+		 * XXX
+		 * NFS doesn't support chflags; ignore errors unless
+		 * there's reason to believe we're losing bits.
+		 * (Note, this still won't be right if the server
+		 * supports flags and we were trying to *remove* flags
+		 * on a file that we copied, i.e., that we didn't create.)
+		 */
+		errno = 0;
+		if ((fd ? fchflags(fd, fflags) :
+		    chflags(to.p_path, fflags)) == -1)
+			if (errno != EOPNOTSUPP || fs->st_flags != 0) {
+				warn("chflags: %s", to.p_path);
+				rval = 1;
+			}
+	}
+#endif
+	/* if fd is non-zero, caller must call set_utimes() after close() */
+	if (fd == 0 && set_utimes(to.p_path, fs))
+	    rval = 1;
+	return (rval);
+}
+
+void
+cp_usage(void)
+{
+	(void)fprintf(stderr,
+	    "usage: cp [-R [-H | -L | -P]] [-f | -i] [-alNpv] src target\n"
+	    "       cp [-R [-H | -L | -P]] [-f | -i] [-alNpv] src1 ... srcN directory\n");
+	exit(1);
+	/* NOTREACHED */
+}