commit fd3a93f5d70d0950c13e24b7d74faacca2674812
parent b2a077bd6f9ba5066e0bfbe7755694dc637d3d4b
Author: xplshn <anto@xplshn.com.ar>
Date: Tue, 30 Jun 2026 16:56:41 -0300
portable diskutils: blkid, lsblk, fdisk | general cleanup
Diffstat:
33 files changed, 7529 insertions(+), 9837 deletions(-)
diff --git a/Makefile b/Makefile
@@ -123,8 +123,9 @@ POSIX_BIN_ALL =\
cmd/posix/date\
cmd/posix/dd\
cmd/posix/df\
- cmd/posix/diff/diff\
- cmd/posix/patch/patch\
+ cmd/posix/diff\
+ cmd/posix/patch\
+ cmd/posix/diff3\
cmd/posix/dirname\
cmd/posix/du\
cmd/posix/echo\
@@ -277,7 +278,6 @@ PSEUDO_BIN_ALL =\
cmd/extra/lsblk\
cmd/extra/fdisk\
cmd/extra/sync\
- cmd/extra/diff3/diff3\
cmd/dev/ar/ar\
cmd/dev/as/as\
cmd/dev/ld/ld\
@@ -296,20 +296,7 @@ MAKEOBJ =\
cmd/posix/make/posix.o\
cmd/posix/make/rules.o
-DIFFOBJ =\
- cmd/posix/diff/diff.o\
- cmd/posix/diff/diffdir.o\
- cmd/posix/diff/diffreg.o\
- cmd/posix/diff/pr.o\
- cmd/posix/diff/xmalloc.o
-
-PATCHOBJ =\
- cmd/posix/patch/patch.o\
- cmd/posix/patch/pch.o\
- cmd/posix/patch/inp.o\
- cmd/posix/patch/util.o\
- cmd/posix/patch/backupfile.o\
- cmd/posix/patch/mkpath.o
+
BIN_basename_1 = cmd/posix/basename
BIN_cal_1 = cmd/posix/cal
@@ -325,8 +312,8 @@ BIN_cut_1 = cmd/posix/cut
BIN_date_1 = cmd/posix/date
BIN_dd_1 = cmd/posix/dd
BIN_df_1 = cmd/posix/df
-BIN_diff_1 = cmd/posix/diff/diff
-BIN_patch_1 = cmd/posix/patch/patch
+BIN_diff_1 = cmd/posix/diff
+BIN_patch_1 = cmd/posix/patch
BIN_dirname_1 = cmd/posix/dirname
BIN_du_1 = cmd/posix/du
BIN_echo_1 = cmd/posix/echo
@@ -475,7 +462,7 @@ BIN_blkid_1 = cmd/extra/blkid
BIN_lsblk_1 = cmd/extra/lsblk
BIN_fdisk_1 = cmd/extra/fdisk
BIN_sync_1 = cmd/extra/sync
-BIN_diff3_1 = cmd/extra/diff3/diff3
+BIN_diff3_1 = cmd/posix/diff3
BIN_ar_1 = cmd/dev/ar/ar
BIN_as_1 = cmd/dev/as/as
BIN_ld_1 = cmd/dev/ld/ld
@@ -698,20 +685,8 @@ $(MAKEOBJ): cmd/posix/make/make.h
cmd/posix/make/make: $(MAKEOBJ) $(LIB)
$(CC) $(LDFLAGS) -o $@ $(MAKEOBJ) $(LIB) $(LDLIBS)
-$(DIFFOBJ): cmd/posix/diff/diff.h cmd/posix/diff/pr.h cmd/posix/diff/xmalloc.h
-
-cmd/posix/diff/diff: $(DIFFOBJ) $(LIB)
- $(CC) $(LDFLAGS) -o $@ $(DIFFOBJ) $(LIB) $(LDLIBS) -lm
-
-$(PATCHOBJ): cmd/posix/patch/common.h cmd/posix/patch/util.h \
- cmd/posix/patch/pch.h cmd/posix/patch/inp.h \
- cmd/posix/patch/backupfile.h cmd/posix/patch/pathnames.h
-
-cmd/posix/patch/%.o: cmd/posix/patch/%.c
- $(CC) $(CPPFLAGS) -Icmd/posix/patch $(CFLAGS) -o $@ -c $<
-
-cmd/posix/patch/patch: $(PATCHOBJ) $(LIB)
- $(CC) $(LDFLAGS) -o $@ $(PATCHOBJ) $(LIB) $(LDLIBS)
+cmd/posix/diff: cmd/posix/diff.c $(LIB)
+ $(CC) $(CPPFLAGS) $(CFLAGS) $(LDFLAGS) -o $@ cmd/posix/diff.c $(LIB) $(LDLIBS) -lm
shared/libutf/libutf.a: $(LIBUTFOBJ)
$(AR) $(ARFLAGS) $@ $?
@@ -760,12 +735,12 @@ man: scripts/mkman/mkman
clean:
rm -f shared/libutf/*.o shared/libutil/*.o shared/libredline/*.o
- rm -f cmd/posix/*.o cmd/posix/diff/*.o cmd/posix/patch/*.o cmd/posix/make/*.o cmd/posix/awk/*.o cmd/posix/sh/*.o
+ rm -f cmd/posix/*.o cmd/posix/make/*.o cmd/posix/awk/*.o cmd/posix/sh/*.o
rm -f cmd/linux/*.o cmd/net/*.o cmd/xsi/*.o cmd/pseudo/*.o
- rm -f cmd/extra/*.o cmd/extra/diff3/*.o cmd/dev/ar/*.o cmd/dev/ld/*.o cmd/dev/cc/*.o cmd/dev/as/*.o cmd/dev/xcutil/*.o
+ rm -f cmd/extra/*.o cmd/dev/ar/*.o cmd/dev/ld/*.o cmd/dev/cc/*.o cmd/dev/as/*.o cmd/dev/xcutil/*.o
rm -f $(POSIX_BIN_ALL) $(LINUX_BIN_ALL) $(NET_BIN_ALL) $(XSI_BIN_ALL) $(PSEUDO_BIN_ALL) $(LIB)
rm -f cmd/posix/make/make cmd/posix/getconf.h cmd/posix/bc.c
- rm -f cmd/posix/patch/patch
+ rm -f
rm -f cmd/posix/awk/awk cmd/posix/awk/maketab cmd/posix/awk/awkgram.tab.c cmd/posix/awk/awkgram.tab.h cmd/posix/awk/proctab.c
rm -f cmd/posix/sh/sh cmd/posix/sh/mknodes cmd/posix/sh/mksyntax
rm -f cmd/posix/sh/syntax.c cmd/posix/sh/syntax.h cmd/posix/sh/nodes.c cmd/posix/sh/nodes.h cmd/posix/sh/builtins.c cmd/posix/sh/builtins.h cmd/posix/sh/token.h
diff --git a/Makefile.sh b/Makefile.sh
@@ -271,9 +271,6 @@ build_simple_tools() {
for src in cmd/"$cat"/*.c; do
[ -f "$src" ] || continue
base=${src##*/}; base=${base%.c}
- if [ "$cat" = posix ] && [ "$base" = diff ]; then
- continue
- fi
var=$(cfgvar "$cat" "$base")
cfg_enabled "$var" || continue
compile_c "$src" "${src%.c}.o"
@@ -282,45 +279,14 @@ build_simple_tools() {
drain
local bin
for bin in $staged; do
- link_bin "$bin" "${bin}.o" -- $LIB
+ if [ "${bin##*/}" = "diff" ]; then
+ link_bin "$bin" "${bin}.o" -- $LIB -lm
+ else
+ link_bin "$bin" "${bin}.o" -- $LIB
+ fi
done
}
-# generated multi-file tools under cmd/posix
-#
-build_diff() {
- cfg_enabled BUILD_POSIX_DIFF || return 0
- local dir=cmd/posix/diff
- local objs=""
- EXTRA_HDR="$dir/diff.h $dir/pr.h $dir/xmalloc.h"
- compile_c "$dir/diff.c" "$dir/diff.o"
- compile_c "$dir/diffdir.c" "$dir/diffdir.o"
- compile_c "$dir/diffreg.c" "$dir/diffreg.o"
- compile_c "$dir/pr.c" "$dir/pr.o"
- compile_c "$dir/xmalloc.c" "$dir/xmalloc.o"
- EXTRA_HDR=
- objs="$dir/diff.o $dir/diffdir.o $dir/diffreg.o $dir/pr.o $dir/xmalloc.o"
- link_bin "$dir/diff" $objs -- $LIB -lm
-}
-
-build_patch() {
- cfg_enabled BUILD_POSIX_PATCH || return 0
- local dir=cmd/posix/patch
- EXTRA_HDR="$dir/common.h $dir/util.h $dir/pch.h $dir/inp.h $dir/backupfile.h $dir/pathnames.h"
- objs_for "$dir" "" "-I$dir"
- EXTRA_HDR=
- link_bin "$dir/patch" $_objs -- $LIB
-}
-
-build_diff3() {
- cfg_enabled BUILD_PSEUDO_DIFF3 || return 0
- local dir=cmd/extra/diff3
- EXTRA_HDR="cmd/posix/diff/xmalloc.h"
- compile_c "$dir/diff3.c" "$dir/diff3.o"
- EXTRA_HDR=
- link_bin "$dir/diff3" "$dir/diff3.o" cmd/posix/diff/xmalloc.o -- $LIB
-}
-
build_awk() {
cfg_enabled BUILD_POSIX_AWK || return 0
local dir=cmd/posix/awk
@@ -415,8 +381,6 @@ build_posix() {
scripts/getconf.sh > cmd/posix/getconf.h || { rm -f cmd/posix/getconf.h; exit 1; }
}
build_simple_tools posix
- build_diff
- build_patch
build_awk
build_sh
build_make
@@ -533,9 +497,6 @@ build_man() {
build_man_for "$(cfgvar "$cat" "$base")" "$src"
done
done
- build_man_for BUILD_POSIX_DIFF cmd/posix/diff/diff.c
- build_man_for BUILD_POSIX_PATCH cmd/posix/patch/patch.c
- build_man_for BUILD_PSEUDO_DIFF3 cmd/extra/diff3/diff3.c
}
# install and clean
@@ -560,7 +521,6 @@ do_clean() {
find cmd -type f ! -name '*.*' -perm -100 -exec rm -f {} +
rm -f shared/libaruuelf.so
rm -f cmd/posix/bc.c cmd/posix/getconf.h
- rm -f cmd/posix/patch/patch
rm -f cmd/posix/awk/maketab cmd/posix/awk/proctab.c
rm -f cmd/posix/awk/awkgram.tab.c cmd/posix/awk/awkgram.tab.h
rm -f cmd/posix/sh/mknodes cmd/posix/sh/mksyntax
@@ -582,14 +542,13 @@ case "$TARGET" in
build_simple_tools xsi
build_simple_tools pseudo
build_simple_tools extra
- build_diff3
;;
lib) build_lib ;;
posix) build_lib; build_posix ;;
dev) build_lib; build_dev ;;
make) build_lib; build_make ;;
linux|net|xsi|pseudo|extra)
- build_lib; build_simple_tools "$TARGET"; [ "$TARGET" = extra ] && build_diff3 ;;
+ build_lib; build_simple_tools "$TARGET" ;;
man) build_man ;;
install) do_install ;;
clean) do_clean ;;
diff --git a/cmd/extra/blkid.c b/cmd/extra/blkid.c
@@ -8,43 +8,6 @@
#include <unistd.h>
#include <fcntl.h>
-struct FsType {
- const char *name;
- size_t magic_offset;
- size_t magic_len;
- uint64_t magic1;
- uint64_t magic2;
- size_t uuid_offset;
- size_t uuid_len;
- size_t label_offset;
- size_t label_len;
-};
-
-static const struct FsType fstypes[] = {
- /* ext2/3/4 */
- { "ext", 1080, 2, 0xEF53, 0x53EF, 1128, 16, 1144, 16 },
- /* vfat / fat32 */
- { "vfat", 82, 5, 0x3233544146ULL, 0, 67, 4, 71, 11 },
- /* vfat / fat12/16 */
- { "vfat", 54, 4, 0x31544146, 0, 39, 4, 43, 11 },
- /* ntfs */
- { "ntfs", 3, 4, 0x5346544e, 0, 72, 8, 0, 0 },
- /* xfs */
- { "xfs", 0, 4, 0x42534658, 0x58465342, 32, 16, 108, 12 },
- /* btrfs */
- { "btrfs", 65600, 8, 0x4D5F53665248425FULL, 0, 65803, 16, 65819, 256 },
- /* f2fs */
- { "f2fs", 1024, 4, 0xF2F52010, 0x1020F5F2, 1132, 16, 1148, 512 },
- /* ufs1 */
- { "ufs1", 9564, 4, 0x011954, 0x54190100, 0, 0, 0, 0 },
- /* ufs2 */
- { "ufs2", 66908, 4, 0x19540119, 0x19015419, 67056, 16, 67072, 32 },
- /* fossil */
- { "fossil", 131200, 4, 0x2340A3B1, 0xB1A34023, 0, 0, 131072, 127 },
- /* cwfs */
- { "cwfs", 0, 4, 0xc1a551f5, 0xf551a5c1, 0, 0, 0, 0 },
-};
-
static char *oflag = "full";
static char *sflag = NULL;
static int Uflag = 0;
@@ -57,35 +20,6 @@ usage(void)
}
static void
-format_uuid(const unsigned char *buf, size_t len, const char *type, char *out, size_t out_len)
-{
- size_t i;
- char *p = out;
-
- if (strcmp(type, "vfat") == 0) {
- snprintf(out, out_len, "%02X%02X-%02X%02X", buf[3], buf[2], buf[1], buf[0]);
- return;
- }
-
- if (strcmp(type, "ntfs") == 0) {
- for (i = 8; i > 0; i--) {
- snprintf(p, out_len - (p - out), "%02X", buf[i - 1]);
- p += 2;
- }
- return;
- }
-
- for (i = 0; i < len; i++) {
- if (i == 4 || i == 6 || i == 8 || i == 10) {
- *p++ = '-';
- }
- snprintf(p, out_len - (p - out), "%02x", buf[i]);
- p += 2;
- }
- *p = '\0';
-}
-
-static void
print_tag(const char *devname, const char *tag, const char *value)
{
if (sflag && strcasecmp(sflag, tag) != 0)
@@ -101,191 +35,45 @@ print_tag(const char *devname, const char *tag, const char *value)
}
static int
-detect_zfs(const unsigned char *buf, size_t len)
-{
- size_t offset;
- uint64_t magic;
-
- for (offset = 131072; offset + 8 <= len; offset += 1024) {
- magic = ((uint64_t)buf[offset + 7] << 56) |
- ((uint64_t)buf[offset + 6] << 48) |
- ((uint64_t)buf[offset + 5] << 40) |
- ((uint64_t)buf[offset + 4] << 32) |
- ((uint64_t)buf[offset + 3] << 24) |
- ((uint64_t)buf[offset + 2] << 16) |
- ((uint64_t)buf[offset + 1] << 8) |
- (uint64_t)buf[offset];
-
- if (magic == 0x00bab10caULL || magic == 0x0cb1ba0000000000ULL ||
- magic == 0x00bab10cULL || magic == 0x0cb1ba00ULL)
- return 1;
- }
- return 0;
-}
-
-static int
-detect_plan9_other(const unsigned char *buf, size_t len, const char **name)
-{
- if (len >= 4) {
- uint32_t magic = ((uint32_t)buf[3] << 24) | ((uint32_t)buf[2] << 16) | ((uint32_t)buf[1] << 8) | (uint32_t)buf[0];
- if (magic == 0x686a6673 || magic == 0x73666a68) {
- *name = "hjfs";
- return 1;
- }
- if (magic == 0x67656673 || magic == 0x73666567) {
- *name = "gefs";
- return 1;
- }
- }
- if (len >= 516) {
- uint32_t magic = ((uint32_t)buf[515] << 24) | ((uint32_t)buf[514] << 16) | ((uint32_t)buf[513] << 8) | (uint32_t)buf[512];
- if (magic == 0x686a6673 || magic == 0x73666a68) {
- *name = "hjfs";
- return 1;
- }
- if (magic == 0x67656673 || magic == 0x73666567) {
- *name = "gefs";
- return 1;
- }
- }
- return 0;
-}
-
-static int
do_blkid(const char *path)
{
struct BlockDev dev;
- unsigned char *buf;
- size_t read_size = 262144; /* 256kb */
- size_t i, j;
- int found = 0;
+ char type[64] = {0};
+ char label[256] = {0};
+ char uuid[256] = {0};
+ int res;
if (blockdev_open(&dev, path, 0) < 0)
return -1;
- if (dev.size < read_size)
- read_size = dev.size;
-
- buf = emalloc(read_size);
- /* read sectors */
- size_t sectors_to_read = (read_size + dev.sec_size - 1) / dev.sec_size;
- if (blockdev_read(&dev, 0, buf, sectors_to_read) < 0) {
- free(buf);
- blockdev_close(&dev);
- return -1;
- }
-
- for (i = 0; i < LEN(fstypes); i++) {
- const struct FsType *fs = &fstypes[i];
- if (fs->magic_offset + fs->magic_len > read_size)
- continue;
-
- uint64_t val = 0;
- for (j = 0; j < fs->magic_len; j++) {
- val |= ((uint64_t)buf[fs->magic_offset + j]) << (8 * j);
- }
-
- if (val == fs->magic1 || (fs->magic2 && val == fs->magic2)) {
- const char *type_name = fs->name;
- if (strcmp(fs->name, "ext") == 0) {
- if (buf[1116] & 4)
- type_name = "ext3";
- else if (buf[1120] & 64)
- type_name = "ext4";
- else
- type_name = "ext2";
- }
-
- if (Uflag || Lflag) {
- char label[256] = {0};
- char uuid[256] = {0};
- if (fs->label_len && fs->label_offset + fs->label_len <= read_size) {
- snprintf(label, sizeof(label), "%.*s", (int)fs->label_len, buf + fs->label_offset);
- }
- if (fs->uuid_len && fs->uuid_offset + fs->uuid_len <= read_size) {
- format_uuid(buf + fs->uuid_offset, fs->uuid_len, fs->name, uuid, sizeof(uuid));
- }
- if (Uflag) {
- printf("%s\n", uuid);
- } else {
- printf("%s\n", label);
- }
- found = 1;
- break;
+ res = blockdev_detect_fs(&dev, type, sizeof(type), label, sizeof(label), uuid, sizeof(uuid));
+ if (res == 0) {
+ if (Uflag || Lflag) {
+ if (Uflag) {
+ printf("%s\n", uuid);
+ } else {
+ printf("%s\n", label);
}
-
+ } else {
if (strcmp(oflag, "export") == 0) {
printf("DEVNAME=%s\n", path);
} else if (strcmp(oflag, "value") != 0) {
printf("%s:", path);
}
- if (fs->label_len && fs->label_offset + fs->label_len <= read_size) {
- char label[256];
- snprintf(label, sizeof(label), "%.*s", (int)fs->label_len, buf + fs->label_offset);
- /* strip trailing spaces */
- char *end = label + strlen(label) - 1;
- while (end >= label && *end == ' ') {
- *end = '\0';
- end--;
- }
- if (label[0])
- print_tag(path, "LABEL", label);
- }
-
- if (fs->uuid_len && fs->uuid_offset + fs->uuid_len <= read_size) {
- char uuid[256];
- format_uuid(buf + fs->uuid_offset, fs->uuid_len, fs->name, uuid, sizeof(uuid));
+ if (label[0])
+ print_tag(path, "LABEL", label);
+ if (uuid[0])
print_tag(path, "UUID", uuid);
- }
+ print_tag(path, "TYPE", type);
- print_tag(path, "TYPE", type_name);
if (strcmp(oflag, "full") == 0)
printf("\n");
-
- found = 1;
- break;
}
}
- if (!found && detect_zfs(buf, read_size)) {
- if (Uflag || Lflag) {
- printf("\n");
- } else {
- if (strcmp(oflag, "export") == 0) {
- printf("DEVNAME=%s\n", path);
- } else if (strcmp(oflag, "value") != 0) {
- printf("%s:", path);
- }
- print_tag(path, "TYPE", "zfs_member");
- if (strcmp(oflag, "full") == 0)
- printf("\n");
- }
- found = 1;
- }
-
- if (!found) {
- const char *p9_name = NULL;
- if (detect_plan9_other(buf, read_size, &p9_name)) {
- if (Uflag || Lflag) {
- printf("\n");
- } else {
- if (strcmp(oflag, "export") == 0) {
- printf("DEVNAME=%s\n", path);
- } else if (strcmp(oflag, "value") != 0) {
- printf("%s:", path);
- }
- print_tag(path, "TYPE", p9_name);
- if (strcmp(oflag, "full") == 0)
- printf("\n");
- }
- found = 1;
- }
- }
-
- free(buf);
blockdev_close(&dev);
- return found ? 0 : -2;
+ return res == 0 ? 0 : -2;
}
// ?man blkid: print block device attributes
@@ -330,17 +118,17 @@ main(int argc, char *argv[])
return 1;
}
for (curr = list; curr; curr = curr->next) {
- char devpath[128];
- snprintf(devpath, sizeof(devpath), "/dev/%s", curr->name);
- do_blkid(devpath);
+ do_blkid(curr->path);
struct BlockDevInfo *part;
for (part = curr->parts; part; part = part->next) {
- snprintf(devpath, sizeof(devpath), "/dev/%s", part->name);
- do_blkid(devpath);
+ do_blkid(part->path);
}
}
blockdev_free_list(list);
}
+ if (fshut(stdin, "<stdin>") | fshut(stdout, "<stdout>"))
+ ret = 2;
+
return ret;
}
diff --git a/cmd/extra/diff3/diff3.c b/cmd/extra/diff3/diff3.c
@@ -1,1250 +0,0 @@
-/* $OpenBSD: diff3prog.c,v 1.11 2009/10/27 23:59:37 deraadt Exp $ */
-
-/*
- * Copyright (C) Caldera International Inc. 2001-2002.
- * 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 and documentation 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. All advertising materials mentioning features or use of this software
- * must display the following acknowledgement:
- * This product includes software developed or owned by Caldera
- * International, Inc.
- * 4. Neither the name of Caldera International, Inc. nor the names of other
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * USE OF THE SOFTWARE PROVIDED FOR UNDER THIS LICENSE BY CALDERA
- * INTERNATIONAL, INC. 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 CALDERA INTERNATIONAL, INC. 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.
- */
-/*-
- * Copyright (c) 1991, 1993
- * 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>
-#include <sys/types.h>
-#include <sys/wait.h>
-
-#include <ctype.h>
-#include <err.h>
-#include <fcntl.h>
-#include <getopt.h>
-#include <stdbool.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <limits.h>
-#include <inttypes.h>
-#include <string.h>
-#include <unistd.h>
-#include <errno.h>
-#include <poll.h>
-
-#include "util.h"
-#include "../../posix/diff/xmalloc.h"
-
-// ?man diff3: 3-way differential file comparison
-// ?man arguments: file1 file2 file3
-// ?man synopsis: [-3AaEeimTXx] [--diff-program program] [--strip-trailing-cr] [-L label1] [-L label2] [-L label3] file1 file2 file3
-// ?man synopsis: [--help]
-// ?man synopsis: [--version]
-// ?man ## OPTIONS
-// ?man ### -3, --easy-only
-// ?man Produces an output script suitable for ed(1) with changes specific only to file3.
-// ?man ### -A, --show-all
-// ?man Output all changes, bracketing conflicts.
-// ?man ### -a, --text
-// ?man Treat all files as ASCII.
-// ?man ### -E, --show-overlap
-// ?man Similar to e and x, respectively, but treat overlapping changes (i.e., changes that would be noted with ==== in the normal listing) differently. The overlapping lines from both files will be inserted by the edit script, bracketed by "<<<<<<" and ">>>>>>" lines.
-// ?man ### -X
-// ?man Similar to e and x, respectively, but treat overlapping changes (i.e., changes that would be noted with ==== in the normal listing) differently. The overlapping lines from both files will be inserted by the edit script, bracketed by "<<<<<<" and ">>>>>>" lines.
-// ?man ### -e, --ed
-// ?man Produces output in a form suitable as an input script for the ed(1) utility. The script may then be used to merge differences common between all three files and differences specific to file1 and file3. In other words, the e option ignores differences specific to file1 and file2, and those specific to file2 and file3. It is useful for backing out changes specific to file2 only.
-// ?man ### --help
-// ?man Prints usage information and exits.
-// ?man ### -i
-// ?man Appends 'w' and 'q' ed(1) commands.
-// ?man ### -L, --label
-// ?man Defines labels to print instead of file names file1, file2 and file3.
-// ?man ### -m, --merge
-// ?man Merge output instead of generating ed script.
-// ?man ### -T, --initial-tab
-// ?man In the normal listing, use a tab instead of two spaces at the beginning of each line. In modes that produce an ed(1) script, this option changes nothing.
-// ?man ### -x, --overlap-only
-// ?man Produces an output script suitable for ed(1) with changes specific only to all three versions.
-// ?man ### --diff-program program
-// ?man Use program instead of the default diff(1) to compare files.
-// ?man ### --strip-trailing-cr
-// ?man Strip trailing carriage return on input files.
-// ?man ### --version
-// ?man Prints version information and exits.
-// ?man ## DESCRIPTION
-// ?man The diff3 utility compares the contents of three different versions of a file, file1, file2 and file3, writing the result to the standard output. The options describe different methods of merging and purging the separate versions into a new file. diff3 is used by rcs(1) to merge specific versions or create new versions.
-// ?man
-// ?man The E option is used by RCS merge(1) to ensure that overlapping changes in the merged files are preserved and brought to someone's attention.
-// ?man
-// ?man For example, suppose lines 7-8 are changed in both file1 and file2. Applying the edit script generated by the command
-// ?man
-// ?man $ diff3 -E file1 file2 file3
-// ?man
-// ?man to file1 results in the file:
-// ?man
-// ?man lines 1-6
-// ?man of file1
-// ?man <<<<<<< file1
-// ?man lines 7-8
-// ?man of file1
-// ?man =======
-// ?man lines 7-8
-// ?man of file3
-// ?man >>>>>>> file3
-// ?man rest of file1
-// ?man
-// ?man The default output of diff3 makes notation of the differences between all files, and those differences specific to each pair of files. The changes are described by the commands necessary for ed(1) to create the desired target from the different versions. See diff(1) for a description of the commands.
-// ?man ### ====
-// ?man The lines beneath this notation are ranges of lines which are different between all files.
-// ?man ### ====n
-// ?man The lines beneath this notation are ranges of lines which are exclusively different in file n.
-// ?man ## SEE ALSO
-// ?man diff(1), ed(1), merge(1), rcs(1), sdiff(1)
-// ?man ## HISTORY
-// ?man A diff3 command appeared in AT&T Version 7 UNIX.
-// ?man ## BUGS
-// ?man The e option cannot catch and change lines which have "." as the first and only character on the line. The resulting script will fail on that line as "." is an ed(1) command.
-
-#ifndef __dead2
-#define __dead2 __attribute__((__noreturn__))
-#endif
-
-#ifndef __DECONST
-#define __DECONST(type, var) ((type)(uintptr_t)(const void *)(var))
-#endif
-
-/*
- * "from" is first in range of changed lines; "to" is last+1
- * from=to=line after point of insertion for added lines.
- */
-struct range {
- int from;
- int to;
-};
-
-struct diff {
-#define DIFF_TYPE1 1
-#define DIFF_TYPE2 2
-#define DIFF_TYPE3 3
- int type;
-#if DEBUG
- char *line;
-#endif /* DEBUG */
-
- /* Ranges as lines */
- struct range old;
- struct range new;
-};
-
-#define EFLAG_NONE 0
-#define EFLAG_OVERLAP 1
-#define EFLAG_NOOVERLAP 2
-#define EFLAG_UNMERGED 3
-
-static size_t szchanges;
-
-static struct diff *d13;
-static struct diff *d23;
-/*
- * "de" is used to gather editing scripts. These are later spewed out in
- * reverse order. Its first element must be all zero, the "old" and "new"
- * components of "de" contain line positions. Array overlap indicates which
- * sections in "de" correspond to lines that are different in all three files.
- */
-static struct diff *de;
-static char *overlap;
-static int overlapcnt;
-static FILE *fp[3];
-static int cline[3]; /* # of the last-read line in each file (0-2) */
-static int sigpipe[2];
-/*
- * The latest known correspondence between line numbers of the 3 files
- * is stored in last[1-3];
- */
-static int last[4];
-static int Aflag, eflag, iflag, mflag, Tflag;
-static int oflag; /* indicates whether to mark overlaps (-E or -X) */
-static int strip_cr;
-static char *f1mark, *f2mark, *f3mark;
-static const char *oldmark = "<<<<<<<";
-static const char *orgmark = "|||||||";
-static const char *newmark = ">>>>>>>";
-static const char *divider = "=======";
-
-static bool duplicate(struct range *, struct range *);
-static int edit(struct diff *, bool, int, int);
-static char *getchange(FILE *);
-static char *get_line(FILE *, size_t *);
-static int readin(int fd, struct diff **);
-static int skip(int, int, const char *);
-static void change(int, struct range *, bool);
-static void keep(int, struct range *);
-static void merge(int, int);
-static void prange(struct range *, bool);
-static void repos(int);
-static void separate(const char *);
-static void edscript(int) __dead2;
-static void Ascript(int) __dead2;
-static void mergescript(int) __dead2;
-static void increase(void);
-static void usage(void);
-static void printrange(FILE *, struct range *);
-
-static const char diff3_version[] = "FreeBSD diff3 20240925";
-
-enum {
- DIFFPROG_OPT,
- STRIPCR_OPT,
- HELP_OPT,
- VERSION_OPT
-};
-
-#define DIFF_PATH "/usr/bin/diff"
-
-#define OPTIONS "3aAeEiL:mTxX"
-static struct option longopts[] = {
- { "ed", no_argument, NULL, 'e' },
- { "show-overlap", no_argument, NULL, 'E' },
- { "overlap-only", no_argument, NULL, 'x' },
- { "initial-tab", no_argument, NULL, 'T' },
- { "text", no_argument, NULL, 'a' },
- { "strip-trailing-cr", no_argument, NULL, STRIPCR_OPT },
- { "show-all", no_argument, NULL, 'A' },
- { "easy-only", no_argument, NULL, '3' },
- { "merge", no_argument, NULL, 'm' },
- { "label", required_argument, NULL, 'L' },
- { "diff-program", required_argument, NULL, DIFFPROG_OPT },
- { "help", no_argument, NULL, HELP_OPT},
- { "version", no_argument, NULL, VERSION_OPT}
-};
-
-static void
-usage(void)
-{
- fprintf(stderr, "usage: diff3 [-3aAeEimTxX] [-L label1] [-L label2] "
- "[-L label3] file1 file2 file3\n");
-}
-
-// ?man diff3: 3-way differential file comparison
-// ?man arguments: file1 file2 file3
-// ?man synopsis: [-3AaEeimTXx] [--diff-program program] [--strip-trailing-cr] [-L label1] [-L label2] [-L label3] file1 file2 file3
-// ?man synopsis: [--help]
-// ?man synopsis: [--version]
-// ?man The diff3 utility compares the contents of three different versions of a file, file1, file2 and file3, writing the result to the standard output. The options describe different methods of merging and purging the separate versions into a new file. diff3 is used by rcs(1) to merge specific versions or create new versions.
-// ?man ## OPTIONS
-// ?man ### -3, --easy-only
-// ?man Produces an output script suitable for ed(1) with changes specific only to file3.
-// ?man ### -A, --show-all
-// ?man Output all changes, bracketing conflicts.
-// ?man ### -a, --text
-// ?man Treat all files as ASCII.
-// ?man ### -E, --show-overlap
-// ?man Similar to e and x, respectively, but treat overlapping changes (i.e., changes that would be noted with ==== in the normal listing) differently. The overlapping lines from both files will be inserted by the edit script, bracketed by "<<<<<<" and ">>>>>>" lines.
-// ?man ### -X
-// ?man Similar to e and x, respectively, but treat overlapping changes (i.e., changes that would be noted with ==== in the normal listing) differently. The overlapping lines from both files will be inserted by the edit script, bracketed by "<<<<<<" and ">>>>>>" lines.
-// ?man ### -e, --ed
-// ?man Produces output in a form suitable as an input script for the ed(1) utility. The script may then be used to merge differences common between all three files and differences specific to file1 and file3. In other words, the e option ignores differences specific to file1 and file2, and those specific to file2 and file3. It is useful for backing out changes specific to file2 only.
-// ?man ### --help
-// ?man Prints usage information and exits.
-// ?man ### -i
-// ?man Appends 'w' and 'q' ed(1) commands.
-// ?man ### -L, --label
-// ?man Defines labels to print instead of file names file1, file2 and file3.
-// ?man ### -m, --merge
-// ?man Merge output instead of generating ed script.
-// ?man ### -T, --initial-tab
-// ?man In the normal listing, use a tab instead of two spaces at the beginning of each line. In modes that produce an ed(1) script, this option changes nothing.
-// ?man ### -x, --overlap-only
-// ?man Produces an output script suitable for ed(1) with changes specific only to all three versions.
-// ?man ### --diff-program program
-// ?man Use program instead of the default diff(1) to compare files.
-// ?man ### --strip-trailing-cr
-// ?man Strip trailing carriage return on input files.
-// ?man ### --version
-// ?man Prints version information and exits.
-// ?man ## DESCRIPTION
-// ?man The E option is used by RCS merge(1) to ensure that overlapping changes in the merged files are preserved and brought to someone's attention.
-// ?man
-// ?man For example, suppose lines 7-8 are changed in both file1 and file2. Applying the edit script generated by the command
-// ?man
-// ?man $ diff3 -E file1 file2 file3
-// ?man
-// ?man to file1 results in the file:
-// ?man
-// ?man lines 1-6
-// ?man of file1
-// ?man <<<<<<< file1
-// ?man lines 7-8
-// ?man of file1
-// ?man =======
-// ?man lines 7-8
-// ?man of file3
-// ?man >>>>>>> file3
-// ?man rest of file1
-// ?man
-// ?man The default output of diff3 makes notation of the differences between all files, and those differences specific to each pair of files. The changes are described by the commands necessary for ed(1) to create the desired target from the different versions. See diff(1) for a description of the commands.
-// ?man ### ====
-// ?man The lines beneath this notation are ranges of lines which are different between all files.
-// ?man ### ====n
-// ?man The lines beneath this notation are ranges of lines which are exclusively different in file n.
-// ?man ## SEE ALSO
-// ?man diff(1), ed(1), merge(1), rcs(1), sdiff(1)
-// ?man ## HISTORY
-// ?man A diff3 command appeared in AT&T Version 7 UNIX.
-// ?man ## BUGS
-// ?man The e option cannot catch and change lines which have "." as the first and only character on the line. The resulting script will fail on that line as "." is an ed(1) command.
-
-static int
-strtoi(char *str, char **end)
-{
- intmax_t num;
-
- errno = 0;
- num = strtoimax(str, end, 10);
- if ((end != NULL && *end == str) ||
- num < 0 || num > INT_MAX ||
- errno == EINVAL || errno == ERANGE)
- err(1, "error in diff output");
- return (int)num;
-}
-
-/*
- * Read diff hunks into the array pointed to by *dd.
- *
- * The output from `diff foo bar` consists of a series of hunks describing
- * an addition (lines in bar not present in foo), change (lines in bar
- * different from lines in foo), or deletion (lines in foo not present in
- * bar). Each record starts with a line of the form:
- *
- * a[,b]xc[,d]
- *
- * where a, b, c, and d are nonnegative integers (b and d are printed only
- * if they differ from a and c, respectively), and x is either 'a' for an
- * addition, 'c' for a change, or 'd' for a deletion. This is then
- * followed by a series of lines (which we ignore) giving the added,
- * changed, or deleted text.
- *
- * For an addition, a == b is the last line in 'foo' before the addition,
- * while c through d is the range of lines in 'bar' to be added to 'foo'.
- *
- * For a change, a through b is the range of lines in 'foo' to be replaced
- * and c through d is the range of lines in 'bar' to replace them with.
- *
- * For a deletion, a through b is the range of lines in 'foo' to remove
- * and c == d is the line in 'bar' which corresponds to the last line
- * before the deletion.
- *
- * The observant reader will have noticed that x is not really needed and
- * that we can fully describe any hunk using only a, b, c, and d:
- *
- * - an addition replaces a zero-length range in one file with a
- * non-zero-length range from the other
- *
- * - a change replaces a non-zero-length range in one file with a
- * non-zero-length range from the other
- *
- * - a deletion replaces a non-zero-length range in one file with a
- * zero-length range from the other
- */
-static int
-readin(int fd, struct diff **dd)
-{
- int a, b, c, d;
- int i;
- char kind, *p;
- FILE *f;
-
- f = fdopen(fd, "r");
- if (f == NULL)
- err(2, "fdopen");
- for (i = 0; (p = getchange(f)) != NULL; i++) {
- if ((size_t)i >= szchanges - 1)
- increase();
-#if DEBUG
- (*dd)[i].line = strdup(p);
-#endif /* DEBUG */
-
- a = b = strtoi(p, &p);
- if (*p == ',')
- b = strtoi(p + 1, &p);
- kind = *p++;
- c = d = strtoi(p, &p);
- if (*p == ',')
- d = strtoi(p + 1, &p);
- if (*p != '\n')
- errx(1, "error in diff output");
- if (kind == 'a')
- a++;
- else if (kind == 'c')
- /* nothing */ ;
- else if (kind == 'd')
- c++;
- else
- errx(1, "error in diff output");
- b++;
- d++;
- if (b < a || d < c)
- errx(1, "error in diff output");
- (*dd)[i].old.from = a;
- (*dd)[i].old.to = b;
- (*dd)[i].new.from = c;
- (*dd)[i].new.to = d;
- if (i > 0) {
- if ((*dd)[i].old.from < (*dd)[i - 1].old.to ||
- (*dd)[i].new.from < (*dd)[i - 1].new.to)
- errx(1, "diff output out of order");
- }
- }
- if (i > 0) {
- (*dd)[i].old.from = (*dd)[i].old.to = (*dd)[i - 1].old.to;
- (*dd)[i].new.from = (*dd)[i].new.to = (*dd)[i - 1].new.to;
- }
- fclose(f);
- return (i);
-}
-
-static void
-diffexec(const char *diffprog, char **diffargv, int fd[])
-{
- switch (fork()) {
- case 0:
- close(fd[0]);
- if (dup2(fd[1], STDOUT_FILENO) == -1)
- err(2, "child could not duplicate descriptor");
- close(fd[1]);
- execvp(diffprog, diffargv);
- err(2, "could not execute diff: %s", diffprog);
- break;
- case -1:
- err(2, "could not fork");
- break;
- }
- close(fd[1]);
-}
-
-static char *
-getchange(FILE *b)
-{
- char *line;
-
- while ((line = get_line(b, NULL)) != NULL) {
- if (isdigit((unsigned char)line[0]))
- return (line);
- }
- return (NULL);
-}
-
-
-static char *
-get_line(FILE *b, size_t *n)
-{
- ssize_t len;
- static char *buf = NULL;
- static size_t bufsize = 0;
-
- if ((len = getline(&buf, &bufsize, b)) < 0)
- return (NULL);
-
- if (strip_cr && len >= 2 && strcmp("\r\n", &(buf[len - 2])) == 0) {
- buf[len - 2] = '\n';
- buf[len - 1] = '\0';
- len--;
- }
-
- if (n != NULL)
- *n = len;
-
- return (buf);
-}
-
-static void
-merge(int m1, int m2)
-{
- struct diff *d1, *d2, *d3;
- int j, t1, t2;
- bool dup = false;
-
- d1 = d13;
- d2 = d23;
- j = 0;
-
- for (;;) {
- t1 = (d1 < d13 + m1);
- t2 = (d2 < d23 + m2);
- if (!t1 && !t2)
- break;
-
- /* first file is different from the others */
- if (!t2 || (t1 && d1->new.to < d2->new.from)) {
- /* stuff peculiar to 1st file */
- if (eflag == EFLAG_NONE) {
- separate("1");
- change(1, &d1->old, false);
- keep(2, &d1->new);
- change(3, &d1->new, false);
- } else if (eflag == EFLAG_OVERLAP) {
- j = edit(d2, dup, j, DIFF_TYPE1);
- }
- d1++;
- continue;
- }
- /* second file is different from others */
- if (!t1 || (t2 && d2->new.to < d1->new.from)) {
- if (eflag == EFLAG_NONE) {
- separate("2");
- keep(1, &d2->new);
- change(3, &d2->new, false);
- change(2, &d2->old, false);
- } else if (Aflag || mflag) {
- // XXX-THJ: What does it mean for the second file to differ?
- if (eflag == EFLAG_UNMERGED)
- j = edit(d2, dup, j, DIFF_TYPE2);
- }
- d2++;
- continue;
- }
- /*
- * Merge overlapping changes in first file
- * this happens after extension (see below).
- */
- if (d1 + 1 < d13 + m1 && d1->new.to >= d1[1].new.from) {
- d1[1].old.from = d1->old.from;
- d1[1].new.from = d1->new.from;
- d1++;
- continue;
- }
-
- /* merge overlapping changes in second */
- if (d2 + 1 < d23 + m2 && d2->new.to >= d2[1].new.from) {
- d2[1].old.from = d2->old.from;
- d2[1].new.from = d2->new.from;
- d2++;
- continue;
- }
- /* stuff peculiar to third file or different in all */
- if (d1->new.from == d2->new.from && d1->new.to == d2->new.to) {
- dup = duplicate(&d1->old, &d2->old);
- /*
- * dup = 0 means all files differ
- * dup = 1 means files 1 and 2 identical
- */
- if (eflag == EFLAG_NONE) {
- separate(dup ? "3" : "");
- change(1, &d1->old, dup);
- change(2, &d2->old, false);
- d3 = d1->old.to > d1->old.from ? d1 : d2;
- change(3, &d3->new, false);
- } else {
- j = edit(d1, dup, j, DIFF_TYPE3);
- }
- dup = false;
- d1++;
- d2++;
- continue;
- }
- /*
- * Overlapping changes from file 1 and 2; extend changes
- * appropriately to make them coincide.
- */
- if (d1->new.from < d2->new.from) {
- d2->old.from -= d2->new.from - d1->new.from;
- d2->new.from = d1->new.from;
- } else if (d2->new.from < d1->new.from) {
- d1->old.from -= d1->new.from - d2->new.from;
- d1->new.from = d2->new.from;
- }
- if (d1->new.to > d2->new.to) {
- d2->old.to += d1->new.to - d2->new.to;
- d2->new.to = d1->new.to;
- } else if (d2->new.to > d1->new.to) {
- d1->old.to += d2->new.to - d1->new.to;
- d1->new.to = d2->new.to;
- }
- }
-
- if (mflag)
- mergescript(j);
- else if (Aflag)
- Ascript(j);
- else if (eflag)
- edscript(j);
-}
-
-static void
-separate(const char *s)
-{
- printf("====%s\n", s);
-}
-
-/*
- * The range of lines rold.from thru rold.to in file i is to be changed.
- * It is to be printed only if it does not duplicate something to be
- * printed later.
- */
-static void
-change(int i, struct range *rold, bool dup)
-{
-
- printf("%d:", i);
- last[i] = rold->to;
- prange(rold, false);
- if (dup)
- return;
- i--;
- skip(i, rold->from, NULL);
- skip(i, rold->to, " ");
-}
-
-/*
- * Print the range of line numbers, rold.from thru rold.to, as n1,n2 or
- * n1.
- */
-static void
-prange(struct range *rold, bool delete)
-{
-
- if (rold->to <= rold->from)
- printf("%da\n", rold->from - 1);
- else {
- printf("%d", rold->from);
- if (rold->to > rold->from + 1)
- printf(",%d", rold->to - 1);
- if (delete)
- printf("d\n");
- else
- printf("c\n");
- }
-}
-
-/*
- * No difference was reported by diff between file 1 (or 2) and file 3,
- * and an artificial dummy difference (trange) must be ginned up to
- * correspond to the change reported in the other file.
- */
-static void
-keep(int i, struct range *rnew)
-{
- int delta;
- struct range trange;
-
- delta = last[3] - last[i];
- trange.from = rnew->from - delta;
- trange.to = rnew->to - delta;
- change(i, &trange, true);
-}
-
-/*
- * skip to just before line number from in file "i". If "pr" is non-NULL,
- * print all skipped stuff with string pr as a prefix.
- */
-static int
-skip(int i, int from, const char *pr)
-{
- size_t j, n;
- char *line;
-
- for (n = 0; cline[i] < from - 1; n += j) {
- if ((line = get_line(fp[i], &j)) == NULL)
- errx(EXIT_FAILURE, "logic error");
- if (pr != NULL)
- printf("%s%s", Tflag == 1 ? "\t" : pr, line);
- cline[i]++;
- }
- return ((int) n);
-}
-
-/*
- * Return 1 or 0 according as the old range (in file 1) contains exactly
- * the same data as the new range (in file 2).
- */
-static bool
-duplicate(struct range *r1, struct range *r2)
-{
- int c, d;
- int nchar;
- int nline;
-
- if (r1->to-r1->from != r2->to-r2->from)
- return (0);
- skip(0, r1->from, NULL);
- skip(1, r2->from, NULL);
- nchar = 0;
- for (nline = 0; nline < r1->to - r1->from; nline++) {
- do {
- c = getc(fp[0]);
- d = getc(fp[1]);
- if (c == -1 && d == -1)
- break;
- if (c == -1 || d == -1)
- errx(EXIT_FAILURE, "logic error");
- nchar++;
- if (c != d) {
- repos(nchar);
- return (0);
- }
- } while (c != '\n');
- }
- repos(nchar);
- return (1);
-}
-
-static void
-repos(int nchar)
-{
- int i;
-
- for (i = 0; i < 2; i++)
- (void)fseek(fp[i], (long)-nchar, SEEK_CUR);
-}
-
-/*
- * collect an editing script for later regurgitation
- */
-static int
-edit(struct diff *diff, bool dup, int j, int difftype)
-{
- if (!(eflag == EFLAG_UNMERGED ||
- (!dup && eflag == EFLAG_OVERLAP ) ||
- (dup && eflag == EFLAG_NOOVERLAP))) {
- return (j);
- }
- j++;
- overlap[j] = !dup;
- if (!dup)
- overlapcnt++;
-
- de[j].type = difftype;
-#if DEBUG
- de[j].line = strdup(diff->line);
-#endif /* DEBUG */
-
- de[j].old.from = diff->old.from;
- de[j].old.to = diff->old.to;
- de[j].new.from = diff->new.from;
- de[j].new.to = diff->new.to;
- return (j);
-}
-
-static void
-printrange(FILE *p, struct range *r)
-{
- char *line = NULL;
- size_t len = 0;
- int i = 1;
-
- /* We haven't been asked to print anything */
- if (r->from == r->to)
- return;
-
- if (r->from > r->to)
- errx(EXIT_FAILURE, "invalid print range");
-
- /*
- * XXX-THJ: We read through all of the file for each range printed.
- * This duplicates work and will probably impact performance on large
- * files with lots of ranges.
- */
- fseek(p, 0L, SEEK_SET);
- while (getline(&line, &len, p) > 0) {
- if (i >= r->from)
- printf("%s", line);
- if (++i > r->to - 1)
- break;
- }
- free(line);
-}
-
-/* regurgitate */
-static void
-edscript(int n)
-{
- bool delete;
- struct range *new, *old;
-
- for (; n > 0; n--) {
- new = &de[n].new;
- old = &de[n].old;
-
- delete = (new->from == new->to);
- if (de[n].type == DIFF_TYPE1) {
- if (delete)
- printf("%dd\n", new->from - 1);
- else if (old->from == new->from && old->to == new->to) {
- printf("%dc\n", old->from);
- printrange(fp[2], old);
- printf(".\n");
- }
- continue;
- } else {
- if (!oflag || !overlap[n]) {
- prange(old, delete);
- } else {
- printf("%da\n", old->to - 1);
- printf("%s\n", divider);
- }
- printrange(fp[2], new);
- if (!oflag || !overlap[n]) {
- if (!delete)
- printf(".\n");
- } else {
- printf("%s %s\n.\n", newmark, f3mark);
- printf("%da\n%s %s\n.\n", old->from - 1,
- oldmark, f1mark);
- }
- }
- }
- if (iflag)
- printf("w\nq\n");
-
- exit(eflag == EFLAG_NONE ? overlapcnt : 0);
-}
-
-/*
- * Output an edit script to turn mine into yours, when there is a conflict
- * between the 3 files bracket the changes. Regurgitate the diffs in reverse
- * order to allow the ed script to track down where the lines are as changes
- * are made.
- */
-static void
-Ascript(int n)
-{
- int startmark;
- bool deletenew;
- bool deleteold;
-
- struct range *new, *old;
-
- for (; n > 0; n--) {
- new = &de[n].new;
- old = &de[n].old;
- deletenew = (new->from == new->to);
- deleteold = (old->from == old->to);
-
- if (de[n].type == DIFF_TYPE2) {
- if (!oflag || !overlap[n]) {
- prange(old, deletenew);
- printrange(fp[2], new);
- } else {
- startmark = new->to - 1;
-
- printf("%da\n", startmark);
- printf("%s %s\n", newmark, f3mark);
-
- printf(".\n");
-
- printf("%da\n", startmark -
- (new->to - new->from));
- printf("%s %s\n", oldmark, f2mark);
- if (!deleteold)
- printrange(fp[1], old);
- printf("%s\n.\n", divider);
- }
-
- } else if (de[n].type == DIFF_TYPE3) {
- startmark = old->to - 1;
-
- if (!oflag || !overlap[n]) {
- prange(old, deletenew);
- printrange(fp[2], new);
- } else {
- printf("%da\n", startmark);
- printf("%s %s\n", orgmark, f2mark);
-
- if (deleteold) {
- struct range r;
- r.from = old->from-1;
- r.to = new->to;
- printrange(fp[1], &r);
- } else
- printrange(fp[1], old);
-
- printf("%s\n", divider);
- printrange(fp[2], new);
- }
-
- if (!oflag || !overlap[n]) {
- if (!deletenew)
- printf(".\n");
- } else {
- printf("%s %s\n.\n", newmark, f3mark);
-
- /*
- * Go to the start of the conflict in original
- * file and append lines
- */
- printf("%da\n%s %s\n.\n",
- startmark - (old->to - old->from),
- oldmark, f1mark);
- }
- }
- }
- if (iflag)
- printf("w\nq\n");
-
- exit(overlapcnt > 0);
-}
-
-/*
- * Output the merged file directly (don't generate an ed script). When
- * regurgitating diffs we need to walk forward through the file and print any
- * inbetween lines.
- */
-static void
-mergescript(int i)
-{
- struct range r, *new, *old;
- int n;
- bool delete = false;
-
- r.from = 1;
- r.to = 1;
-
- for (n = 1; n <= i; n++) {
- new = &de[n].new;
- old = &de[n].old;
-
- /*
- * Print any lines leading up to here. If we are merging don't
- * print deleted ranges.
- */
- delete = (new->from == new->to);
- if (de[n].type == DIFF_TYPE1 && delete)
- r.to = new->from - 1;
- else if (de[n].type == DIFF_TYPE3 && (old->from == old->to)) {
- r.from = old->from - 1;
- r.to = new->from;
- } else
- r.to = old->from;
-
- printrange(fp[0], &r);
- switch (de[n].type) {
- case DIFF_TYPE1:
- /* If this isn't a delete print it */
- if (!delete)
- printrange(fp[2], new);
- break;
- case DIFF_TYPE2:
- printf("%s %s\n", oldmark, f2mark);
- printrange(fp[1], old);
- printf("%s\n", divider);
- printrange(fp[2], new);
- printf("%s %s\n", newmark, f3mark);
- break;
- case DIFF_TYPE3:
- if (!oflag || !overlap[n]) {
- printrange(fp[2], new);
- } else {
-
- printf("%s %s\n", oldmark, f1mark);
- printrange(fp[0], old);
-
- if (eflag != EFLAG_OVERLAP) {
- printf("%s %s\n", orgmark, f2mark);
- if (old->from == old->to) {
- struct range or;
- or.from = old->from - 1;
- or.to = new->to;
- printrange(fp[1], &or);
- } else {
- printrange(fp[1], old);
- }
- }
-
- printf("%s\n", divider);
-
- printrange(fp[2], new);
- printf("%s %s\n", newmark, f3mark);
- }
- break;
- default:
- printf("Error: Unhandled diff type - exiting\n");
- exit(EXIT_FAILURE);
- }
-
- if (old->from == old->to)
- r.from = new->to;
- else
- r.from = old->to;
- }
-
- /*
- * Print from the final range to the end of 'myfile'. Any deletions or
- * additions to this file should have been handled by now.
- *
- * If the ranges are the same we need to rewind a line.
- * If the new range is 0 length (from == to), we need to use the old
- * range.
- */
- new = &de[n-1].new;
- old = &de[n-1].old;
-
- if (old->from == new->from && old->to == new->to)
- r.from--;
- else if (new->from == new->to)
- r.from = old->from;
-
- r.to = INT_MAX;
- printrange(fp[2], &r);
- exit(overlapcnt > 0);
-}
-
-static void
-increase(void)
-{
- struct diff *p;
- char *q;
- size_t newsz, incr;
-
- /* are the memset(3) calls needed? */
- newsz = szchanges == 0 ? 64 : 2 * szchanges;
- incr = newsz - szchanges;
-
- p = reallocarray(d13, newsz, sizeof(*p));
- if (p == NULL)
- err(1, NULL);
- memset(p + szchanges, 0, incr * sizeof(*p));
- d13 = p;
- p = reallocarray(d23, newsz, sizeof(*p));
- if (p == NULL)
- err(1, NULL);
- memset(p + szchanges, 0, incr * sizeof(*p));
- d23 = p;
- p = reallocarray(de, newsz, sizeof(*p));
- if (p == NULL)
- err(1, NULL);
- memset(p + szchanges, 0, incr * sizeof(*p));
- de = p;
- q = reallocarray(overlap, newsz, 1);
- if (q == NULL)
- err(1, NULL);
- memset(q + szchanges, 0, incr * 1);
- overlap = q;
- szchanges = newsz;
-}
-
-static void
-handle_sig(int signo)
-{
- write(sigpipe[1], &signo, sizeof(signo));
-}
-
-int
-main(int argc, char **argv)
-{
- int ch, nblabels, status, m, n, npe, nleft;
- char *labels[] = { NULL, NULL, NULL };
- const char *diffprog = DIFF_PATH;
- char *file1, *file2, *file3;
- char *diffargv[7];
- int diffargc = 0;
- int fd13[2], fd23[2], signo;
- pid_t wpid;
- struct pollfd pfd;
-
- nblabels = 0;
- eflag = EFLAG_NONE;
- oflag = 0;
- diffargv[diffargc++] = __DECONST(char *, diffprog);
- while ((ch = getopt_long(argc, argv, OPTIONS, longopts, NULL)) != -1) {
- switch (ch) {
- case '3':
- eflag = EFLAG_NOOVERLAP;
- break;
- case 'a':
- diffargv[diffargc++] = __DECONST(char *, "-a");
- break;
- case 'A':
- Aflag = 1;
- break;
- case 'e':
- eflag = EFLAG_UNMERGED;
- break;
- case 'E':
- eflag = EFLAG_OVERLAP;
- oflag = 1;
- break;
- case 'i':
- iflag = 1;
- break;
- case 'L':
- oflag = 1;
- if (nblabels >= 3)
- errx(2, "too many file label options");
- labels[nblabels++] = optarg;
- break;
- case 'm':
- Aflag = 1;
- oflag = 1;
- mflag = 1;
- break;
- case 'T':
- Tflag = 1;
- break;
- case 'x':
- eflag = EFLAG_OVERLAP;
- break;
- case 'X':
- oflag = 1;
- eflag = EFLAG_OVERLAP;
- break;
- case DIFFPROG_OPT:
- diffprog = optarg;
- break;
- case STRIPCR_OPT:
- strip_cr = 1;
- diffargv[diffargc++] = __DECONST(char *, "--strip-trailing-cr");
- break;
- case HELP_OPT:
- usage();
- exit(0);
- case VERSION_OPT:
- printf("%s\n", diff3_version);
- exit(0);
- }
- }
- argc -= optind;
- argv += optind;
-
- if (Aflag) {
- if (eflag == EFLAG_NONE)
- eflag = EFLAG_UNMERGED;
- oflag = 1;
- }
-
- if (argc != 3) {
- usage();
- exit(2);
- }
-
- /* TODO stdio */
- file1 = argv[0];
- file2 = argv[1];
- file3 = argv[2];
-
- if (oflag) {
- xasprintf(&f1mark, "%s",
- labels[0] != NULL ? labels[0] : file1);
- xasprintf(&f2mark, "%s",
- labels[1] != NULL ? labels[1] : file2);
- xasprintf(&f3mark, "%s",
- labels[2] != NULL ? labels[2] : file3);
- }
- fp[0] = fopen(file1, "r");
- if (fp[0] == NULL)
- err(2, "Can't open %s", file1);
-
- fp[1] = fopen(file2, "r");
- if (fp[1] == NULL)
- err(2, "Can't open %s", file2);
-
- fp[2] = fopen(file3, "r");
- if (fp[2] == NULL)
- err(2, "Can't open %s", file3);
-
- if (pipe(fd13))
- err(2, "pipe");
- if (pipe(fd23))
- err(2, "pipe");
- if (pipe(sigpipe))
- err(2, "pipe");
- if (fcntl(sigpipe[0], F_SETFD, FD_CLOEXEC))
- err(2, "fcntl");
- if (fcntl(sigpipe[1], F_SETFD, FD_CLOEXEC))
- err(2, "fcntl");
-
- pfd.fd = sigpipe[0];
- pfd.events = POLLIN;
- pfd.revents = 0;
-
- if (signal(SIGCHLD, handle_sig) == SIG_ERR)
- err(2, "signal");
-
- diffargv[diffargc] = file1;
- diffargv[diffargc + 1] = file3;
- diffargv[diffargc + 2] = NULL;
-
- nleft = 0;
- diffexec(diffprog, diffargv, fd13);
- nleft++;
-
- diffargv[diffargc] = file2;
- diffexec(diffprog, diffargv, fd23);
- nleft++;
-
- /* parse diffs */
- increase();
- m = readin(fd13[0], &d13);
- n = readin(fd23[0], &d23);
-
- /* waitpid */
- while (nleft > 0) {
- npe = poll(&pfd, 1, -1);
- if (npe == -1) {
- if (errno == EINTR) continue;
- err(2, "poll");
- }
- if (pfd.revents != POLLIN)
- continue;
- if (read(pfd.fd, &signo, sizeof(signo)) < 0)
- err(2, "read");
- while ((wpid = waitpid(-1, &status, WNOHANG)) > 0) {
- if (WIFEXITED(status) && WEXITSTATUS(status) >= 2)
- errx(2, "diff exited abnormally");
- else if (WIFSIGNALED(status))
- errx(2, "diff killed by signal %d",
- WTERMSIG(status));
- nleft--;
- }
- }
- merge(m, n);
-
- return (EXIT_SUCCESS);
-}
diff --git a/cmd/extra/fdisk.c b/cmd/extra/fdisk.c
@@ -2,11 +2,11 @@
#include "util.h"
#include "diskutil.h"
+#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
-#include <fcntl.h>
struct MbrPartition {
uint8_t boot;
@@ -49,6 +49,47 @@ struct GptPartition {
uint16_t name[36];
} __attribute__((packed));
+struct BsdPartition {
+ uint32_t size;
+ uint32_t offset;
+ uint16_t offset_h;
+ uint16_t size_h;
+ uint8_t fstype;
+ uint8_t fragblock;
+ uint16_t cpg;
+} __attribute__((packed));
+
+struct BsdDisklabel {
+ uint32_t d_magic;
+ uint16_t d_type;
+ uint16_t d_subtype;
+ char d_typename[16];
+ char d_packname[16];
+ uint32_t d_secsize;
+ uint32_t d_nsectors;
+ uint32_t d_ntracks;
+ uint32_t d_ncylinders;
+ uint32_t d_secpercyl;
+ uint32_t d_secperunit;
+ uint8_t d_uid[8];
+ uint32_t d_acylinders;
+ uint16_t d_bstarth;
+ uint16_t d_bendh;
+ uint32_t d_bstart;
+ uint32_t d_bend;
+ uint32_t d_flags;
+ uint32_t d_spare4[5];
+ uint16_t d_secperunith;
+ uint16_t d_version;
+ uint32_t d_spare[4];
+ uint32_t d_magic2;
+ uint16_t d_checksum;
+ uint16_t d_npartitions;
+ uint32_t d_spare2;
+ uint32_t d_spare3;
+ struct BsdPartition d_partitions[16];
+} __attribute__((packed));
+
static uint32_t crc32_table[256];
static int crc32_table_initialized = 0;
@@ -84,9 +125,11 @@ static int opt_list = 0;
static int opt_print = 0;
static int opt_init_gpt = 0;
static int opt_init_mbr = 0;
+static int opt_init_bsd = 0;
static int opt_add = 0;
static int opt_del = 0;
static int opt_part_idx = -1;
+static int opt_part_is_letter = 0;
static uint64_t opt_start = 0;
static uint64_t opt_end = 0;
static const char *opt_type = NULL;
@@ -94,11 +137,11 @@ static const char *opt_type = NULL;
static void
usage(void)
{
- eprintf("usage: %s [-l] [-p] [-g] [-m] [-a] [-d] [-n index] [-b start] [-e end] [-t type] [device]\n", argv0);
+ eprintf("usage: %s [-l] [-p] [-g] [-m] [-s] [-a] [-d] [-n index] [-b start] [-e end] [-t type] [device]\n", argv0);
}
static void
-print_mbr(struct MbrHeader *mbr, const char *path)
+mbr_print(struct MbrHeader *mbr, const char *path)
{
int i;
printf("Disk: %s\n", path);
@@ -118,7 +161,7 @@ print_mbr(struct MbrHeader *mbr, const char *path)
}
static void
-print_gpt(struct GptHeader *hdr, struct GptPartition *parts, const char *path)
+gpt_print(struct GptHeader *hdr, struct GptPartition *parts, const char *path)
{
uint32_t i;
char guid[37];
@@ -147,7 +190,7 @@ print_gpt(struct GptHeader *hdr, struct GptPartition *parts, const char *path)
}
static int
-read_gpt(struct BlockDev *dev, struct GptHeader *hdr, struct GptPartition *parts)
+gpt_read(struct BlockDev *dev, struct GptHeader *hdr, struct GptPartition *parts)
{
unsigned char sector[512];
size_t part_sectors;
@@ -168,31 +211,31 @@ read_gpt(struct BlockDev *dev, struct GptHeader *hdr, struct GptPartition *parts
}
static int
-write_gpt(struct BlockDev *dev, struct GptHeader *hdr, struct GptPartition *parts)
+gpt_write(struct BlockDev *dev, struct GptHeader *hdr, struct GptPartition *parts)
{
unsigned char sector[512];
- size_t part_sectors = (hdr->num_parts * hdr->part_size + dev->sec_size - 1) / dev->sec_size;
+ struct MbrHeader pmbr;
+ struct GptHeader backup_hdr;
+ uint64_t limit;
+ size_t part_sectors;
+
+ part_sectors = (hdr->num_parts * hdr->part_size + dev->sec_size - 1) / dev->sec_size;
- /* update partition entries crc */
hdr->parts_crc = crc32(~0U, parts, hdr->num_parts * hdr->part_size) ^ ~0U;
- /* calculate header crc (zeroing the crc field first) */
hdr->crc = 0;
hdr->crc = crc32(~0U, hdr, hdr->size) ^ ~0U;
- /* write protective mbr to sector 0 */
- struct MbrHeader pmbr;
memset(&pmbr, 0, sizeof(pmbr));
pmbr.parts[0].type = 0xEE;
pmbr.parts[0].start_lba = 1;
- uint64_t limit = dev->size / dev->sec_size - 1;
+ limit = dev->size / dev->sec_size - 1;
pmbr.parts[0].size = limit > 0xFFFFFFFFU ? 0xFFFFFFFFU : (uint32_t)limit;
pmbr.sig[0] = 0x55;
pmbr.sig[1] = 0xAA;
if (blockdev_write(dev, 0, &pmbr, 1) < 0)
return -1;
- /* write primary header and partition entries */
memset(sector, 0, sizeof(sector));
memcpy(sector, hdr, sizeof(*hdr));
if (blockdev_write(dev, 1, sector, 1) < 0)
@@ -200,8 +243,7 @@ write_gpt(struct BlockDev *dev, struct GptHeader *hdr, struct GptPartition *part
if (blockdev_write(dev, hdr->partition_lba, parts, part_sectors) < 0)
return -1;
- /* write backup partition entries and backup header */
- struct GptHeader backup_hdr = *hdr;
+ backup_hdr = *hdr;
backup_hdr.current_lba = hdr->backup_lba;
backup_hdr.backup_lba = hdr->current_lba;
backup_hdr.partition_lba = backup_hdr.current_lba - part_sectors;
@@ -220,6 +262,99 @@ write_gpt(struct BlockDev *dev, struct GptHeader *hdr, struct GptPartition *part
return 0;
}
+static uint16_t
+bsd_dkcksum(void *lp, size_t nparts)
+{
+ uint16_t *start;
+ uint16_t *end;
+ uint16_t sum = 0;
+
+ start = (uint16_t *)lp;
+ end = (uint16_t *)((char *)lp + 148 + nparts * 16);
+ while (start < end)
+ sum ^= *start++;
+ return sum;
+}
+
+static int
+bsd_is_partition_type(uint8_t type)
+{
+ return type == 0xa5 || type == 0xa6 || type == 0xa9;
+}
+
+static int
+bsd_read(struct BlockDev *dev, uint64_t base_sec, struct BsdDisklabel *lp)
+{
+ unsigned char sector[512];
+ if (blockdev_read(dev, base_sec + 1, sector, 1) < 0)
+ return -1;
+ memcpy(lp, sector, sizeof(*lp));
+ if (lp->d_magic != 0x82564557U || lp->d_magic2 != 0x82564557U)
+ return -1;
+ return 0;
+}
+
+static int
+bsd_write(struct BlockDev *dev, uint64_t base_sec, struct BsdDisklabel *lp)
+{
+ unsigned char sector[512];
+ memset(sector, 0, sizeof(sector));
+ lp->d_checksum = 0;
+ lp->d_checksum = bsd_dkcksum(lp, lp->d_npartitions);
+ memcpy(sector, lp, sizeof(*lp));
+ if (blockdev_write(dev, base_sec + 1, sector, 1) < 0)
+ return -1;
+ return 0;
+}
+
+static void
+bsd_print(struct BsdDisklabel *lp, const char *path, uint64_t base_sec)
+{
+ uint64_t start, size;
+ int i;
+
+ printf("Disk: %s (at sector %llu)\n", path, (unsigned long long)base_sec);
+ printf("Partition table (BSD disklabel):\n");
+ printf("%-5s %-12s %-12s %-10s\n", "Index", "Start", "Size", "Type");
+ for (i = 0; i < lp->d_npartitions; i++) {
+ struct BsdPartition *p = &lp->d_partitions[i];
+ start = ((uint64_t)p->offset_h << 32) | p->offset;
+ size = ((uint64_t)p->size_h << 32) | p->size;
+ if (size == 0)
+ continue;
+ printf("%-5c %-12llu %-12llu 0x%02x\n",
+ 'a' + i,
+ (unsigned long long)start,
+ (unsigned long long)size,
+ p->fstype);
+ }
+}
+
+static int
+bsd_find_label(struct BlockDev *dev, uint64_t *base_sec, struct BsdDisklabel *lp)
+{
+ struct MbrHeader mbr;
+ int i;
+
+ if (bsd_read(dev, 0, lp) == 0) {
+ *base_sec = 0;
+ return 0;
+ }
+
+ if (blockdev_read(dev, 0, &mbr, 1) == 0 && mbr.sig[0] == 0x55 && mbr.sig[1] == 0xAA) {
+ for (i = 0; i < 4; i++) {
+ if (mbr.parts[i].size > 0 && bsd_is_partition_type(mbr.parts[i].type)) {
+ if (bsd_read(dev, mbr.parts[i].start_lba, lp) == 0) {
+ *base_sec = mbr.parts[i].start_lba;
+ return 0;
+ }
+ }
+ }
+ }
+
+ return -1;
+}
+
static int
do_print(const char *path)
{
@@ -227,17 +362,36 @@ do_print(const char *path)
struct MbrHeader mbr;
struct GptHeader gpt_hdr;
struct GptPartition gpt_parts[128];
+ struct BsdDisklabel bsd_lp;
+ int i;
+ int found_bsd = 0;
if (blockdev_open(&dev, path, 0) < 0) {
weprintf("cannot open %s:", path);
return -1;
}
- if (read_gpt(&dev, &gpt_hdr, gpt_parts) == 0) {
- print_gpt(&gpt_hdr, gpt_parts, path);
+ if (gpt_read(&dev, &gpt_hdr, gpt_parts) == 0) {
+ gpt_print(&gpt_hdr, gpt_parts, path);
+ } else if (blockdev_read(&dev, 0, &mbr, 1) == 0 && mbr.sig[0] == 0x55 && mbr.sig[1] == 0xAA) {
+ for (i = 0; i < 4; i++) {
+ if (mbr.parts[i].size > 0 && bsd_is_partition_type(mbr.parts[i].type)) {
+ if (bsd_read(&dev, mbr.parts[i].start_lba, &bsd_lp) == 0) {
+ bsd_print(&bsd_lp, path, mbr.parts[i].start_lba);
+ found_bsd = 1;
+ }
+ }
+ }
+ if (!found_bsd) {
+ if (bsd_read(&dev, 0, &bsd_lp) == 0) {
+ bsd_print(&bsd_lp, path, 0);
+ } else {
+ mbr_print(&mbr, path);
+ }
+ }
} else {
- if (blockdev_read(&dev, 0, &mbr, 1) == 0 && mbr.sig[0] == 0x55 && mbr.sig[1] == 0xAA) {
- print_mbr(&mbr, path);
+ if (bsd_read(&dev, 0, &bsd_lp) == 0) {
+ bsd_print(&bsd_lp, path, 0);
} else {
printf("Disk %s: unpartitioned or unknown format\n", path);
}
@@ -254,14 +408,25 @@ do_fdisk(const char *path)
struct MbrHeader mbr;
struct GptHeader gpt_hdr;
struct GptPartition gpt_parts[128];
+ struct BsdDisklabel lp;
+ struct BsdDisklabel bsd_lp;
+ struct GptPartition *gp;
+ struct BsdPartition *bp;
+ struct MbrPartition *mp;
+ uint64_t base_sec;
+ uint64_t limit;
+ uint64_t bsd_base;
+ uint64_t size;
+ int idx;
int has_gpt = 0;
+ int has_bsd = 0;
if (blockdev_open(&dev, path, 1) < 0) {
weprintf("cannot open %s:", path);
return -1;
}
- has_gpt = (read_gpt(&dev, &gpt_hdr, gpt_parts) == 0);
+ has_gpt = (gpt_read(&dev, &gpt_hdr, gpt_parts) == 0);
if (opt_init_mbr) {
memset(&mbr, 0, sizeof(mbr));
@@ -291,7 +456,7 @@ do_fdisk(const char *path)
gpt_hdr.part_size = 128;
memset(gpt_parts, 0, sizeof(gpt_parts));
- if (write_gpt(&dev, &gpt_hdr, gpt_parts) < 0) {
+ if (gpt_write(&dev, &gpt_hdr, gpt_parts) < 0) {
weprintf("cannot write GPT to %s:", path);
blockdev_close(&dev);
return -1;
@@ -301,6 +466,42 @@ do_fdisk(const char *path)
return 0;
}
+ if (opt_init_bsd) {
+ base_sec = 0;
+ limit = dev.size / dev.sec_size;
+
+ if (blockdev_read(&dev, 0, &mbr, 1) == 0 && mbr.sig[0] == 0x55 && mbr.sig[1] == 0xAA) {
+ if (!opt_part_is_letter && opt_part_idx >= 1 && opt_part_idx <= 4) {
+ mp = &mbr.parts[opt_part_idx - 1];
+ if (mp->size > 0) {
+ base_sec = mp->start_lba;
+ limit = base_sec + mp->size;
+ }
+ }
+ }
+
+ memset(&lp, 0, sizeof(lp));
+ lp.d_magic = 0x82564557U;
+ lp.d_magic2 = 0x82564557U;
+ lp.d_secsize = dev.sec_size;
+ lp.d_npartitions = 8;
+ lp.d_partitions[2].offset = (uint32_t)base_sec;
+ lp.d_partitions[2].offset_h = (uint16_t)(base_sec >> 32);
+ size = limit - base_sec;
+ lp.d_partitions[2].size = (uint32_t)size;
+ lp.d_partitions[2].size_h = (uint16_t)(size >> 32);
+ lp.d_partitions[2].fstype = 0;
+
+ if (bsd_write(&dev, base_sec, &lp) < 0) {
+ weprintf("cannot write BSD disklabel to %s:", path);
+ blockdev_close(&dev);
+ return -1;
+ }
+ printf("Initialized BSD disklabel on %s (at sector %llu)\n", path, (unsigned long long)base_sec);
+ blockdev_close(&dev);
+ return 0;
+ }
+
if (opt_add) {
if (opt_part_idx < 1) {
weprintf("add requires partition index (-n)\n");
@@ -314,46 +515,76 @@ do_fdisk(const char *path)
blockdev_close(&dev);
return -1;
}
- struct GptPartition *p = &gpt_parts[opt_part_idx - 1];
- p->start_lba = opt_start;
- p->end_lba = opt_end;
- /* default type guid: linux filesystem data */
- p->type_guid[0] = 0xAF; p->type_guid[1] = 0x3D; p->type_guid[2] = 0xC6; p->type_guid[3] = 0x0F;
- p->type_guid[4] = 0x83; p->type_guid[5] = 0x84;
- p->type_guid[6] = 0x72; p->type_guid[7] = 0x47;
- p->type_guid[8] = 0x8E; p->type_guid[9] = 0x79;
- p->type_guid[10] = 0x3D; p->type_guid[11] = 0x69; p->type_guid[12] = 0xD8; p->type_guid[13] = 0x47; p->type_guid[14] = 0x7D; p->type_guid[15] = 0xE4;
-
- if (write_gpt(&dev, &gpt_hdr, gpt_parts) < 0) {
+ gp = &gpt_parts[opt_part_idx - 1];
+ gp->start_lba = opt_start;
+ gp->end_lba = opt_end;
+ gp->type_guid[0] = 0xAF; gp->type_guid[1] = 0x3D; gp->type_guid[2] = 0xC6; gp->type_guid[3] = 0x0F;
+ gp->type_guid[4] = 0x83; gp->type_guid[5] = 0x84;
+ gp->type_guid[6] = 0x72; gp->type_guid[7] = 0x47;
+ gp->type_guid[8] = 0x8E; gp->type_guid[9] = 0x79;
+ gp->type_guid[10] = 0x3D; gp->type_guid[11] = 0x69; gp->type_guid[12] = 0xD8; gp->type_guid[13] = 0x47; gp->type_guid[14] = 0x7D; gp->type_guid[15] = 0xE4;
+
+ if (gpt_write(&dev, &gpt_hdr, gpt_parts) < 0) {
weprintf("cannot update GPT on %s:", path);
blockdev_close(&dev);
return -1;
}
printf("Added GPT partition %d to %s\n", opt_part_idx, path);
} else {
- if (blockdev_read(&dev, 0, &mbr, 1) < 0) {
- weprintf("cannot read MBR from %s:", path);
- blockdev_close(&dev);
- return -1;
- }
- if (opt_part_idx > 4) {
- weprintf("MBR partition index must be 1-4\n");
- blockdev_close(&dev);
- return -1;
+ has_bsd = (bsd_find_label(&dev, &bsd_base, &bsd_lp) == 0);
+ if (opt_part_is_letter || has_bsd) {
+ if (!has_bsd) {
+ weprintf("BSD disklabel not found on %s\n", path);
+ blockdev_close(&dev);
+ return -1;
+ }
+ idx = opt_part_idx - 1;
+ if (idx >= 16) {
+ weprintf("BSD partition index must be a-p\n");
+ blockdev_close(&dev);
+ return -1;
+ }
+ bp = &bsd_lp.d_partitions[idx];
+ bp->offset = (uint32_t)opt_start;
+ bp->offset_h = (uint16_t)(opt_start >> 32);
+ size = opt_end - opt_start + 1;
+ bp->size = (uint32_t)size;
+ bp->size_h = (uint16_t)(size >> 32);
+ bp->fstype = opt_type ? (uint8_t)strtoul(opt_type, NULL, 0) : 7;
+ if (idx >= bsd_lp.d_npartitions)
+ bsd_lp.d_npartitions = idx + 1;
+
+ if (bsd_write(&dev, bsd_base, &bsd_lp) < 0) {
+ weprintf("cannot update BSD disklabel on %s:", path);
+ blockdev_close(&dev);
+ return -1;
+ }
+ printf("Added BSD partition %c to %s\n", 'a' + idx, path);
+ } else {
+ if (blockdev_read(&dev, 0, &mbr, 1) < 0) {
+ weprintf("cannot read MBR from %s:", path);
+ blockdev_close(&dev);
+ return -1;
+ }
+ if (opt_part_idx > 4) {
+ weprintf("MBR partition index must be 1-4\n");
+ blockdev_close(&dev);
+ return -1;
+ }
+ mp = &mbr.parts[opt_part_idx - 1];
+ mp->start_lba = (uint32_t)opt_start;
+ mp->size = (uint32_t)(opt_end - opt_start + 1);
+ mp->type = opt_type ? (uint8_t)strtoul(opt_type, NULL, 0) : 0x83;
+ mbr.sig[0] = 0x55;
+ mbr.sig[1] = 0xAA;
+
+ if (blockdev_write(&dev, 0, &mbr, 1) < 0) {
+ weprintf("cannot update MBR on %s:", path);
+ blockdev_close(&dev);
+ return -1;
+ }
+ printf("Added MBR partition %d to %s\n", opt_part_idx, path);
}
- struct MbrPartition *p = &mbr.parts[opt_part_idx - 1];
- p->start_lba = (uint32_t)opt_start;
- p->size = (uint32_t)(opt_end - opt_start + 1);
- p->type = opt_type ? (uint8_t)strtoul(opt_type, NULL, 0) : 0x83;
- mbr.sig[0] = 0x55;
- mbr.sig[1] = 0xAA;
-
- if (blockdev_write(&dev, 0, &mbr, 1) < 0) {
- weprintf("cannot update MBR on %s:", path);
- blockdev_close(&dev);
- return -1;
- }
- printf("Added MBR partition %d to %s\n", opt_part_idx, path);
}
}
@@ -371,30 +602,53 @@ do_fdisk(const char *path)
return -1;
}
memset(&gpt_parts[opt_part_idx - 1], 0, sizeof(struct GptPartition));
- if (write_gpt(&dev, &gpt_hdr, gpt_parts) < 0) {
+ if (gpt_write(&dev, &gpt_hdr, gpt_parts) < 0) {
weprintf("cannot update GPT on %s:", path);
blockdev_close(&dev);
return -1;
}
printf("Deleted GPT partition %d from %s\n", opt_part_idx, path);
} else {
- if (blockdev_read(&dev, 0, &mbr, 1) < 0) {
- weprintf("cannot read MBR from %s:", path);
- blockdev_close(&dev);
- return -1;
- }
- if (opt_part_idx > 4) {
- weprintf("MBR partition index must be 1-4\n");
- blockdev_close(&dev);
- return -1;
- }
- memset(&mbr.parts[opt_part_idx - 1], 0, sizeof(struct MbrPartition));
- if (blockdev_write(&dev, 0, &mbr, 1) < 0) {
- weprintf("cannot update MBR on %s:", path);
- blockdev_close(&dev);
- return -1;
+ has_bsd = (bsd_find_label(&dev, &bsd_base, &bsd_lp) == 0);
+ if (opt_part_is_letter || has_bsd) {
+ if (!has_bsd) {
+ weprintf("BSD disklabel not found on %s\n", path);
+ blockdev_close(&dev);
+ return -1;
+ }
+ idx = opt_part_idx - 1;
+ if (idx >= 16) {
+ weprintf("BSD partition index must be a-p\n");
+ blockdev_close(&dev);
+ return -1;
+ }
+ memset(&bsd_lp.d_partitions[idx], 0, sizeof(struct BsdPartition));
+ if (bsd_write(&dev, bsd_base, &bsd_lp) < 0) {
+ weprintf("cannot update BSD disklabel on %s:", path);
+ blockdev_close(&dev);
+ return -1;
+ }
+ printf("Deleted BSD partition %c from %s\n", 'a' + idx, path);
+ } else {
+ if (blockdev_read(&dev, 0, &mbr, 1) < 0) {
+ weprintf("cannot read MBR from %s:", path);
+ blockdev_close(&dev);
+ return -1;
+ }
+ if (opt_part_idx > 4) {
+ weprintf("MBR partition index must be 1-4\n");
+ blockdev_close(&dev);
+ return -1;
+ }
+ mp = &mbr.parts[opt_part_idx - 1];
+ memset(mp, 0, sizeof(struct MbrPartition));
+ if (blockdev_write(&dev, 0, &mbr, 1) < 0) {
+ weprintf("cannot update MBR on %s:", path);
+ blockdev_close(&dev);
+ return -1;
+ }
+ printf("Deleted MBR partition %d from %s\n", opt_part_idx, path);
}
- printf("Deleted MBR partition %d from %s\n", opt_part_idx, path);
}
}
@@ -403,11 +657,13 @@ do_fdisk(const char *path)
}
// ?man fdisk: partition table manipulator
-// ?man arguments: [-l] [-p] [-g] [-m] [-a] [-d] [-n index] [-b start] [-e end] [-t type] [device]
-// ?man fdisk performs partition table operations for MBR and GPT disks
+// ?man arguments: [-l] [-p] [-g] [-m] [-s] [-a] [-d] [-n index] [-b start] [-e end] [-t type] [device]
+// ?man fdisk performs partition table operations for MBR, GPT and BSD disklabels
int
main(int argc, char *argv[])
{
+ int ret = 0;
+
ARGBEGIN {
// ?man -l:list partitions of all devices
case 'l':
@@ -425,6 +681,10 @@ main(int argc, char *argv[])
case 'm':
opt_init_mbr = 1;
break;
+ // ?man -s:initialize disk with BSD disklabel
+ case 's':
+ opt_init_bsd = 1;
+ break;
// ?man -a:add partition
case 'a':
opt_add = 1;
@@ -433,10 +693,18 @@ main(int argc, char *argv[])
case 'd':
opt_del = 1;
break;
- // ?man -n:partition index
- case 'n':
- opt_part_idx = (int)estrtol(EARGF(usage()), 10);
+ // ?man -n:partition index or letter
+ case 'n': {
+ char *arg = EARGF(usage());
+ if (arg[0] >= 'a' && arg[0] <= 'p' && arg[1] == '\0') {
+ opt_part_idx = arg[0] - 'a' + 1;
+ opt_part_is_letter = 1;
+ } else {
+ opt_part_idx = (int)estrtol(arg, 10);
+ opt_part_is_letter = 0;
+ }
break;
+ }
// ?man -b:starting sector LBA
case 'b':
opt_start = (uint64_t)estrtoul(EARGF(usage()), 10);
@@ -445,7 +713,7 @@ main(int argc, char *argv[])
case 'e':
opt_end = (uint64_t)estrtoul(EARGF(usage()), 10);
break;
- // ?man -t:partition type (MBR hex or GPT string)
+ // ?man -t:partition type (MBR/BSD hex or GPT string)
case 't':
opt_type = EARGF(usage());
break;
@@ -459,20 +727,24 @@ main(int argc, char *argv[])
if (!list)
return 1;
for (curr = list; curr; curr = curr->next) {
- char devpath[128];
- snprintf(devpath, sizeof(devpath), "/dev/%s", curr->name);
- do_print(devpath);
+ do_print(curr->path);
}
blockdev_free_list(list);
- return 0;
+ if (fshut(stdin, "<stdin>") | fshut(stdout, "<stdout>"))
+ ret = 2;
+ return ret;
}
if (argc != 1)
usage();
if (opt_print) {
- return do_print(argv[0]) < 0 ? 1 : 0;
+ ret = do_print(argv[0]) < 0 ? 1 : 0;
+ } else {
+ ret = do_fdisk(argv[0]) < 0 ? 1 : 0;
}
- return do_fdisk(argv[0]) < 0 ? 1 : 0;
+ if (fshut(stdin, "<stdin>") | fshut(stdout, "<stdout>"))
+ ret = 2;
+ return ret;
}
diff --git a/cmd/extra/lsblk.c b/cmd/extra/lsblk.c
@@ -78,6 +78,9 @@ main(int argc, char *argv[])
printf("%s\n", hdrbuf);
for (curr = list; curr; curr = curr->next) {
+ if (strncmp(curr->name, "ram", 3) == 0)
+ continue;
+
print_line(max_len,
curr->name,
curr->major, curr->minor,
diff --git a/cmd/posix/diff.c b/cmd/posix/diff.c
@@ -0,0 +1,2489 @@
+/* See LICENSE file for copyright and license details. */
+#include "util.h"
+
+#include <sys/stat.h>
+#include <sys/wait.h>
+
+#include <ctype.h>
+#include <dirent.h>
+#include <err.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <fnmatch.h>
+#include <getopt.h>
+#include <limits.h>
+#include <math.h>
+#include <paths.h>
+#include <poll.h>
+#include <regex.h>
+#include <signal.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <stdint.h>
+#include <time.h>
+#include <unistd.h>
+
+#ifndef __dead
+#define __dead __attribute__((__noreturn__))
+#endif
+
+#define d_status d_type
+
+/* output format options */
+#define D_NORMAL 0
+#define D_EDIT -1
+#define D_REVERSE 1
+#define D_CONTEXT 2
+#define D_UNIFIED 3
+#define D_IFDEF 4
+#define D_NREVERSE 5
+#define D_BRIEF 6
+#define D_GFORMAT 7
+#define D_SIDEBYSIDE 8
+
+#define D_UNSET -2
+
+/* algorithms */
+#define D_DIFFNONE 0
+#define D_DIFFSTONE 1
+#define D_DIFFMYERS 2
+#define D_DIFFPATIENCE 3
+
+/* output flags */
+#define D_HEADER 0x001
+#define D_EMPTY1 0x002
+#define D_EMPTY2 0x004
+
+/* command line flags */
+#define D_FORCEASCII 0x008
+#define D_FOLDBLANKS 0x010
+#define D_MINIMAL 0x020
+#define D_IGNORECASE 0x040
+#define D_PROTOTYPE 0x080
+#define D_EXPANDTABS 0x100
+#define D_IGNOREBLANKS 0x200
+#define D_STRIPCR 0x400
+#define D_SKIPBLANKLINES 0x800
+#define D_MATCHLAST 0x1000
+
+/* features supported by new algorithms */
+#define D_NEWALGO_FLAGS (D_FORCEASCII | D_PROTOTYPE | D_IGNOREBLANKS)
+
+/* status values for print_status and diffreg return values */
+#define D_SAME 0
+#define D_DIFFER 1
+#define D_BINARY 2
+#define D_MISMATCH1 3
+#define D_MISMATCH2 4
+#define D_SKIPPED1 5
+#define D_SKIPPED2 6
+#define D_ERROR 7
+
+/* color options */
+#define COLORFLAG_NEVER 0
+#define COLORFLAG_AUTO 1
+#define COLORFLAG_ALWAYS 2
+
+#define FUNCTION_CONTEXT_SIZE 55
+#define _PATH_PR "/usr/bin/pr"
+
+#ifndef roundup
+#define roundup(x, y) ((((x) + ((y) - 1)) / (y)) * (y))
+#endif
+
+struct Excludes {
+ char *pattern;
+ struct Excludes *next;
+};
+
+struct Cand {
+ int x;
+ int y;
+ int pred;
+};
+
+struct Line {
+ int serial;
+ int value;
+};
+
+struct ContextVec {
+ int a;
+ int b;
+ int c;
+ int d;
+};
+
+struct Pr {
+ int ostdout;
+ pid_t cpid;
+};
+
+struct Algorithm {
+ const char *name;
+ int id;
+};
+
+static struct Algorithm algorithms[] = {
+ {"stone", D_DIFFSTONE},
+ {"myers", D_DIFFMYERS},
+ {"patience", D_DIFFPATIENCE},
+ {NULL, D_DIFFNONE}
+};
+
+/* options */
+#define OPTIONS "0123456789A:aBbC:cdD:efF:HhI:iL:lnNPpqrS:sTtU:uwW:X:x:y"
+enum {
+ OPT_TSIZE = CHAR_MAX + 1,
+ OPT_STRIPCR,
+ OPT_IGN_FN_CASE,
+ OPT_NO_IGN_FN_CASE,
+ OPT_NORMAL,
+ OPT_HELP,
+ OPT_HORIZON_LINES,
+ OPT_CHANGED_GROUP_FORMAT,
+ OPT_SUPPRESS_COMMON,
+ OPT_COLOR,
+ OPT_NO_DEREFERENCE,
+ OPT_VERSION,
+};
+
+static struct option longopts[] = {
+ { "algorithm", required_argument, 0, 'A' },
+ { "text", no_argument, 0, 'a' },
+ { "ignore-space-change", no_argument, 0, 'b' },
+ { "context", optional_argument, 0, 'C' },
+ { "ifdef", required_argument, 0, 'D' },
+ { "minimal", no_argument, 0, 'd' },
+ { "ed", no_argument, 0, 'e' },
+ { "forward-ed", no_argument, 0, 'f' },
+ { "show-function-line", required_argument, 0, 'F' },
+ { "speed-large-files", no_argument, NULL, 'H' },
+ { "ignore-blank-lines", no_argument, 0, 'B' },
+ { "ignore-matching-lines", required_argument, 0, 'I' },
+ { "ignore-case", no_argument, 0, 'i' },
+ { "paginate", no_argument, NULL, 'l' },
+ { "label", required_argument, 0, 'L' },
+ { "new-file", no_argument, 0, 'N' },
+ { "rcs", no_argument, 0, 'n' },
+ { "unidirectional-new-file", no_argument, 0, 'P' },
+ { "show-c-function", no_argument, 0, 'p' },
+ { "brief", no_argument, 0, 'q' },
+ { "recursive", no_argument, 0, 'r' },
+ { "report-identical-files", no_argument, 0, 's' },
+ { "starting-file", required_argument, 0, 'S' },
+ { "expand-tabs", no_argument, 0, 't' },
+ { "initial-tab", no_argument, 0, 'T' },
+ { "unified", optional_argument, 0, 'U' },
+ { "ignore-all-space", no_argument, 0, 'w' },
+ { "width", required_argument, 0, 'W' },
+ { "exclude", required_argument, 0, 'x' },
+ { "exclude-from", required_argument, 0, 'X' },
+ { "side-by-side", no_argument, NULL, 'y' },
+ { "ignore-file-name-case", no_argument, NULL, OPT_IGN_FN_CASE },
+ { "help", no_argument, NULL, OPT_HELP},
+ { "horizon-lines", required_argument, NULL, OPT_HORIZON_LINES },
+ { "no-dereference", no_argument, NULL, OPT_NO_DEREFERENCE},
+ { "no-ignore-file-name-case", no_argument, NULL, OPT_NO_IGN_FN_CASE },
+ { "normal", no_argument, NULL, OPT_NORMAL },
+ { "strip-trailing-cr", no_argument, NULL, OPT_STRIPCR },
+ { "tabsize", required_argument, NULL, OPT_TSIZE },
+ { "changed-group-format", required_argument, NULL, OPT_CHANGED_GROUP_FORMAT},
+ { "suppress-common-lines", no_argument, NULL, OPT_SUPPRESS_COMMON },
+ { "color", optional_argument, NULL, OPT_COLOR },
+ { "version", no_argument, NULL, OPT_VERSION},
+ { NULL, 0, 0, '\0'}
+};
+
+static const char diff_version[] = "FreeBSD diff 20240307";
+int lflag, Nflag, Pflag, rflag, sflag, Tflag, cflag;
+int ignore_file_case, suppress_common, color, noderef;
+static int help = 0;
+int diff_format, diff_context, diff_algorithm, status;
+int diff_algorithm_set;
+int tabsize = 8, width = 130;
+static int colorflag = COLORFLAG_NEVER;
+char *start, *ifdefname, *diffargs, *label[2];
+char *ignore_pats, *most_recent_pat;
+char *group_format = NULL;
+const char *add_code, *del_code;
+struct stat stb1, stb2;
+struct Excludes *excludes_list;
+regex_t ignore_re, most_recent_re;
+
+enum Readhash {
+ RH_BINARY,
+ RH_OK,
+ RH_EOF
+};
+
+static struct Line *file[2];
+
+static int *J;
+static int *class;
+static int *klist;
+static int *member;
+static int clen;
+static int inifdef;
+static size_t len[2];
+static size_t pref, suff;
+static size_t slen[2];
+static int anychange;
+static int hw, lpad, rpad;
+static int edoffset;
+static long *ixnew;
+static long *ixold;
+static struct Cand *clist;
+static int clistlen;
+static struct Line *sfile[2];
+static int (*chrtran)(int);
+static struct ContextVec *context_vec_start;
+static struct ContextVec *context_vec_end;
+static struct ContextVec *context_vec_ptr;
+static char lastbuf[FUNCTION_CONTEXT_SIZE];
+static int lastline;
+static int lastmatchline;
+
+static int sigpipe[2] = {-1, -1};
+static struct pollfd poll_fd;
+
+static void checked_regcomp(char const *, regex_t *);
+static void usage(void);
+static void conflicting_format(void);
+static void push_excludes(char *);
+static void push_ignore_pats(char *);
+static void read_excludes_file(char *);
+static void set_argstr(char **, char **);
+static char *diff_splice(char *, char *);
+static int do_color(void);
+static int cup2low(int);
+static int clow2low(int);
+static void xasprintf(char **, const char *, ...);
+
+int diffreg(char *, char *, int, int);
+void diffdir(char *, char *, int);
+void print_status(int, char *, char *, const char *);
+
+static int selectfile(const struct dirent *);
+static void diffit(struct dirent *, char *, size_t, struct dirent *, char *, size_t, int);
+static void print_only(const char *, size_t, const char *);
+
+static FILE *opentemp(const char *);
+static void output(char *, FILE *, char *, FILE *, int);
+static void check(FILE *, FILE *, int);
+static void range(int, int, const char *);
+static void uni_range(int, int);
+static void dump_context_vec(FILE *, FILE *, int);
+static void dump_unified_vec(FILE *, FILE *, int);
+static int prepare(int, FILE *, size_t, int);
+static void prune(void);
+static void equiv(struct Line *, int, struct Line *, int, int *);
+static void unravel(int);
+static void unsort(struct Line *, int, int *);
+static void change(char *, FILE *, char *, FILE *, int, int, int, int, int *);
+static void sort(struct Line *, int);
+static void print_header(const char *, const char *);
+static void print_space(int, int, int);
+static int ignoreline_pattern(char *);
+static int ignoreline(char *, int);
+static int asciifile(FILE *);
+static int fetch(long *, int, int, FILE *, int, int, int);
+static int newcand(int, int, int);
+static int search(int *, int, int);
+static int skipline(FILE *);
+static int stone(int *, int, int *, int *, int);
+static enum Readhash readhash(FILE *, int, unsigned *);
+static int files_differ(FILE *, FILE *, int);
+static char *match_function(const long *, int, FILE *);
+static char *preadline(int, size_t, off_t);
+
+static void handle_sig(int);
+struct Pr *start_pr(char *, char *);
+void stop_pr(struct Pr *);
+
+static void
+handle_sig(int signo)
+{
+ write(sigpipe[1], &signo, sizeof(signo));
+}
+
+struct Pr *
+start_pr(char *file1, char *file2)
+{
+ int pfd[2];
+ pid_t pid;
+ char *header;
+ struct Pr *pr;
+
+ pr = ecalloc(1, sizeof(*pr));
+ xasprintf(&header, "%s %s %s", diffargs, file1, file2);
+ signal(SIGPIPE, SIG_IGN);
+ fflush(stdout);
+ if (pipe(pfd) == -1)
+ err(2, "pipe");
+ if (sigpipe[0] < 0) {
+ if (pipe(sigpipe) == -1)
+ err(2, "pipe");
+ if (fcntl(sigpipe[0], F_SETFD, FD_CLOEXEC) == -1)
+ err(2, "fcntl");
+ if (fcntl(sigpipe[1], F_SETFD, FD_CLOEXEC) == -1)
+ err(2, "fcntl");
+ if (signal(SIGCHLD, handle_sig) == SIG_ERR)
+ err(2, "signal");
+ poll_fd.fd = sigpipe[0];
+ poll_fd.events = POLLIN;
+ }
+ poll_fd.revents = 0;
+ switch ((pid = fork())) {
+ case -1:
+ status |= 2;
+ free(header);
+ err(2, "no more processes");
+ case 0:
+ if (pfd[0] != STDIN_FILENO) {
+ dup2(pfd[0], STDIN_FILENO);
+ close(pfd[0]);
+ }
+ close(pfd[1]);
+ execl(_PATH_PR, _PATH_PR, "-h", header, (char *)0);
+ _exit(127);
+ default:
+ if (pfd[1] != STDOUT_FILENO) {
+ pr->ostdout = dup(STDOUT_FILENO);
+ dup2(pfd[1], STDOUT_FILENO);
+ close(pfd[1]);
+ }
+ close(pfd[0]);
+ free(header);
+ pr->cpid = pid;
+ }
+ return pr;
+}
+
+void
+stop_pr(struct Pr *pr)
+{
+ int wstatus;
+ int done = 0;
+
+ if (!pr)
+ return;
+
+ fflush(stdout);
+ if (pr->ostdout != STDOUT_FILENO) {
+ close(STDOUT_FILENO);
+ dup2(pr->ostdout, STDOUT_FILENO);
+ close(pr->ostdout);
+ }
+ while (!done) {
+ pid_t wpid;
+ int npe = poll(&poll_fd, 1, -1);
+ if (npe == -1) {
+ if (errno == EINTR)
+ continue;
+ err(2, "poll");
+ }
+ if (poll_fd.revents != POLLIN)
+ continue;
+ if (read(poll_fd.fd, &npe, sizeof(npe)) < 0)
+ err(2, "read");
+ while ((wpid = waitpid(-1, &wstatus, WNOHANG)) > 0) {
+ if (wpid != pr->cpid)
+ continue;
+ if (WIFEXITED(wstatus) && WEXITSTATUS(wstatus) != 0)
+ errx(2, "pr exited abnormally");
+ else if (WIFSIGNALED(wstatus))
+ errx(2, "pr killed by signal %d", WTERMSIG(wstatus));
+ done = 1;
+ break;
+ }
+ }
+ free(pr);
+}
+
+// ?man diff: differential file and directory comparator
+// ?man arguments: file1 file2
+// ?man synopsis: [-aBbdipTtw] [-c|-e|-f|-n|-q|-u|-y] [-A algo] [--brief] [--color=when] [--changed-group-format GFMT] [--ed] [--expand-tabs] [--forward-ed] [--ignore-all-space] [--ignore-case] [--ignore-space-change] [--initial-tab] [--minimal] [--no-dereference] [--no-ignore-file-name-case] [--normal] [--rcs] [--show-c-function] [--starting-file] [--speed-large-files] [--strip-trailing-cr] [--tabsize number] [--text] [-I pattern] [-F pattern] [-L label] file1 file2
+int
+main(int argc, char **argv)
+{
+ const char *errstr = NULL;
+ char *ep, **oargv;
+ long l;
+ int ch, dflags, lastch, gotstdin, prevoptind, newarg;
+
+ oargv = argv;
+ gotstdin = 0;
+ dflags = 0;
+ lastch = '\0';
+ prevoptind = 1;
+ newarg = 1;
+ diff_context = 3;
+ diff_format = D_UNSET;
+ diff_algorithm = D_DIFFMYERS;
+ diff_algorithm_set = 0;
+#define FORMAT_MISMATCHED(type) \
+ (diff_format != D_UNSET && diff_format != (type))
+ while ((ch = getopt_long(argc, argv, OPTIONS, longopts, NULL)) != -1) {
+ // ?man -0: context length
+ // ?man -1: context length
+ // ?man -2: context length
+ // ?man -3: context length
+ // ?man -4: context length
+ // ?man -5: context length
+ // ?man -6: context length
+ // ?man -7: context length
+ // ?man -8: context length
+ // ?man -9: context length
+ switch (ch) {
+ case '0': case '1': case '2': case '3': case '4':
+ case '5': case '6': case '7': case '8': case '9':
+ if (newarg)
+ usage();
+ else if (lastch == 'c' || lastch == 'u')
+ diff_context = 0;
+ else if (!isdigit(lastch) || diff_context > INT_MAX / 10)
+ usage();
+ diff_context = (diff_context * 10) + (ch - '0');
+ break;
+ // ?man -A:algo: algorithm (stone, myers, patience)
+ case 'A':
+ diff_algorithm = D_DIFFNONE;
+ for (struct Algorithm *a = algorithms; a->name; a++) {
+ if (strcasecmp(optarg, a->name) == 0) {
+ diff_algorithm = a->id;
+ diff_algorithm_set = 1;
+ break;
+ }
+ }
+ if (diff_algorithm == D_DIFFNONE) {
+ printf("unknown algorithm: %s\n", optarg);
+ usage();
+ }
+ break;
+ // ?man -a: force text mode
+ case 'a':
+ dflags |= D_FORCEASCII;
+ break;
+ // ?man -b: ignore space changes
+ case 'b':
+ dflags |= D_FOLDBLANKS;
+ break;
+ // ?man -C:lines: context format
+ case 'C':
+ // ?man -c: context format
+ case 'c':
+ if (FORMAT_MISMATCHED(D_CONTEXT))
+ conflicting_format();
+ cflag = 1;
+ diff_format = D_CONTEXT;
+ if (optarg != NULL) {
+ l = strtol(optarg, &ep, 10);
+ if (*ep != '\0' || l < 0 || l >= INT_MAX)
+ usage();
+ diff_context = (int)l;
+ }
+ break;
+ // ?man -d: minimal diff search
+ case 'd':
+ dflags |= D_MINIMAL;
+ break;
+ // ?man -D:name: ifdef format
+ case 'D':
+ if (FORMAT_MISMATCHED(D_IFDEF))
+ conflicting_format();
+ diff_format = D_IFDEF;
+ ifdefname = optarg;
+ break;
+ // ?man -e: ed script format
+ case 'e':
+ if (FORMAT_MISMATCHED(D_EDIT))
+ conflicting_format();
+ diff_format = D_EDIT;
+ break;
+ // ?man -f: forward ed script format
+ case 'f':
+ if (FORMAT_MISMATCHED(D_REVERSE))
+ conflicting_format();
+ diff_format = D_REVERSE;
+ break;
+ // ?man -H: speed up large files (stub)
+ case 'H':
+ break;
+ // ?man -h: backward compatibility (stub)
+ case 'h':
+ break;
+ // ?man -B: ignore blank lines
+ case 'B':
+ dflags |= D_SKIPBLANKLINES;
+ break;
+ // ?man -F:pat: show function matching pattern
+ case 'F':
+ if (dflags & D_PROTOTYPE)
+ conflicting_format();
+ dflags |= D_MATCHLAST;
+ most_recent_pat = estrdup(optarg);
+ break;
+ // ?man -I:pat: ignore pattern matching lines
+ case 'I':
+ push_ignore_pats(optarg);
+ break;
+ // ?man -i: ignore case
+ case 'i':
+ dflags |= D_IGNORECASE;
+ break;
+ // ?man -L:label: custom label
+ case 'L':
+ if (label[0] == NULL)
+ label[0] = optarg;
+ else if (label[1] == NULL)
+ label[1] = optarg;
+ else
+ usage();
+ break;
+ // ?man -l: paginate output using pr
+ case 'l':
+ lflag = 1;
+ break;
+ // ?man -N: treat missing files as empty
+ case 'N':
+ Nflag = 1;
+ break;
+ // ?man -n: rcs format
+ case 'n':
+ if (FORMAT_MISMATCHED(D_NREVERSE))
+ conflicting_format();
+ diff_format = D_NREVERSE;
+ break;
+ // ?man -p: show C prototype context
+ case 'p':
+ if (dflags & D_MATCHLAST)
+ conflicting_format();
+ dflags |= D_PROTOTYPE;
+ break;
+ // ?man -P: treat missing destination files as empty
+ case 'P':
+ Pflag = 1;
+ break;
+ // ?man -r: recursive directory comparison
+ case 'r':
+ rflag = 1;
+ break;
+ // ?man -q: brief output (differ / same only)
+ case 'q':
+ if (FORMAT_MISMATCHED(D_BRIEF))
+ conflicting_format();
+ diff_format = D_BRIEF;
+ break;
+ // ?man -S:name: starting file in directory comparison
+ case 'S':
+ start = optarg;
+ break;
+ // ?man -s: report identical files
+ case 's':
+ sflag = 1;
+ break;
+ // ?man -T: initial tab alignment
+ case 'T':
+ Tflag = 1;
+ break;
+ // ?man -t: expand tabs in output
+ case 't':
+ dflags |= D_EXPANDTABS;
+ break;
+ // ?man -U:lines: unified context format
+ case 'U':
+ // ?man -u: unified context format
+ case 'u':
+ if (FORMAT_MISMATCHED(D_UNIFIED))
+ conflicting_format();
+ diff_format = D_UNIFIED;
+ if (optarg != NULL) {
+ l = strtol(optarg, &ep, 10);
+ if (*ep != '\0' || l < 0 || l >= INT_MAX)
+ usage();
+ diff_context = (int)l;
+ }
+ break;
+ // ?man -w: ignore all whitespace
+ case 'w':
+ dflags |= D_IGNOREBLANKS;
+ break;
+ // ?man -W:cols: column width for side-by-side
+ case 'W':
+ width = (int)strtonum(optarg, 1, INT_MAX, &errstr);
+ if (errstr) {
+ warnx("invalid width argument");
+ usage();
+ }
+ break;
+ // ?man -X:file: exclude patterns file
+ case 'X':
+ read_excludes_file(optarg);
+ break;
+ // ?man -x:pat: exclude pattern
+ case 'x':
+ push_excludes(optarg);
+ break;
+ // ?man -y: side by side format
+ case 'y':
+ if (FORMAT_MISMATCHED(D_SIDEBYSIDE))
+ conflicting_format();
+ diff_format = D_SIDEBYSIDE;
+ break;
+ case OPT_CHANGED_GROUP_FORMAT:
+ if (FORMAT_MISMATCHED(D_GFORMAT))
+ conflicting_format();
+ diff_format = D_GFORMAT;
+ group_format = optarg;
+ break;
+ case OPT_HELP:
+ help = 1;
+ usage();
+ break;
+ case OPT_HORIZON_LINES:
+ break;
+ case OPT_IGN_FN_CASE:
+ ignore_file_case = 1;
+ break;
+ case OPT_NO_IGN_FN_CASE:
+ ignore_file_case = 0;
+ break;
+ case OPT_NORMAL:
+ if (FORMAT_MISMATCHED(D_NORMAL))
+ conflicting_format();
+ diff_format = D_NORMAL;
+ break;
+ case OPT_TSIZE:
+ tabsize = (int)strtonum(optarg, 1, INT_MAX, &errstr);
+ if (errstr) {
+ warnx("invalid tabsize argument");
+ usage();
+ }
+ break;
+ case OPT_STRIPCR:
+ dflags |= D_STRIPCR;
+ break;
+ case OPT_SUPPRESS_COMMON:
+ suppress_common = 1;
+ break;
+ case OPT_COLOR:
+ if (optarg == NULL || strncmp(optarg, "auto", 4) == 0)
+ colorflag = COLORFLAG_AUTO;
+ else if (strncmp(optarg, "always", 6) == 0)
+ colorflag = COLORFLAG_ALWAYS;
+ else if (strncmp(optarg, "never", 5) == 0)
+ colorflag = COLORFLAG_NEVER;
+ else
+ errx(2, "unsupported color option %s", optarg);
+ break;
+ case OPT_NO_DEREFERENCE:
+ noderef = 1;
+ break;
+ case OPT_VERSION:
+ printf("%s\n", diff_version);
+ exit(0);
+ default:
+ usage();
+ break;
+ }
+ lastch = ch;
+ newarg = optind != prevoptind;
+ prevoptind = optind;
+ }
+ if (diff_format == D_UNSET && (dflags & D_PROTOTYPE) != 0)
+ diff_format = D_CONTEXT;
+ if (diff_format == D_UNSET)
+ diff_format = D_NORMAL;
+ argc -= optind;
+ argv += optind;
+
+ if (do_color()) {
+ char *p;
+ const char *env;
+
+ color = 1;
+ add_code = "32";
+ del_code = "31";
+ env = getenv("DIFFCOLORS");
+ if (env != NULL && *env != '\0' && (p = estrdup(env))) {
+ add_code = p;
+ strsep(&p, ":");
+ if (p != NULL)
+ del_code = p;
+ }
+ }
+
+ if (argc != 2)
+ usage();
+ checked_regcomp(ignore_pats, &ignore_re);
+ checked_regcomp(most_recent_pat, &most_recent_re);
+ if (strcmp(argv[0], "-") == 0) {
+ fstat(STDIN_FILENO, &stb1);
+ gotstdin = 1;
+ } else if (stat(argv[0], &stb1) != 0) {
+ if (!Nflag || errno != ENOENT)
+ err(2, "%s", argv[0]);
+ dflags |= D_EMPTY1;
+ memset(&stb1, 0, sizeof(struct stat));
+ }
+
+ if (strcmp(argv[1], "-") == 0) {
+ fstat(STDIN_FILENO, &stb2);
+ gotstdin = 1;
+ } else if (stat(argv[1], &stb2) != 0) {
+ if (!Nflag || errno != ENOENT)
+ err(2, "%s", argv[1]);
+ dflags |= D_EMPTY2;
+ memset(&stb2, 0, sizeof(stb2));
+ stb2.st_mode = stb1.st_mode;
+ }
+
+ if (dflags & D_EMPTY1 && dflags & D_EMPTY2){
+ warn("%s", argv[0]);
+ warn("%s", argv[1]);
+ exit(2);
+ }
+
+ if (stb1.st_mode == 0)
+ stb1.st_mode = stb2.st_mode;
+
+ if (gotstdin && (S_ISDIR(stb1.st_mode) || S_ISDIR(stb2.st_mode)))
+ errx(2, "cant compare - to directory");
+ set_argstr(oargv, argv);
+ if (S_ISDIR(stb1.st_mode) && S_ISDIR(stb2.st_mode)) {
+ if (diff_format == D_IFDEF)
+ errx(2, "-D option not supported with directories");
+ diffdir(argv[0], argv[1], dflags);
+ } else {
+ if (S_ISDIR(stb1.st_mode)) {
+ argv[0] = diff_splice(argv[0], argv[1]);
+ if (stat(argv[0], &stb1) == -1)
+ err(2, "%s", argv[0]);
+ }
+ if (S_ISDIR(stb2.st_mode)) {
+ argv[1] = diff_splice(argv[1], argv[0]);
+ if (stat(argv[1], &stb2) == -1)
+ err(2, "%s", argv[1]);
+ }
+ print_status(diffreg(argv[0], argv[1], dflags, 1), argv[0], argv[1], "");
+ }
+ if (fflush(stdout) != 0)
+ err(2, "stdout");
+ exit(status);
+}
+
+static void
+checked_regcomp(char const *pattern, regex_t *comp)
+{
+ char buf[BUFSIZ];
+ int error;
+
+ if (pattern == NULL)
+ return;
+
+ error = regcomp(comp, pattern, REG_NEWLINE | REG_EXTENDED);
+ if (error != 0) {
+ regerror(error, comp, buf, sizeof(buf));
+ if (*pattern != '\0')
+ errx(2, "%s: %s", pattern, buf);
+ else
+ errx(2, "%s", buf);
+ }
+}
+
+static void
+set_argstr(char **av, char **ave)
+{
+ size_t argsize;
+ char **ap;
+
+ argsize = strlen("diff") + 1;
+ for (ap = av + 1; ap < ave; ap++) {
+ if (strcmp(*ap, "--") != 0)
+ argsize += 1 + strlen(*ap);
+ }
+ diffargs = emalloc(argsize);
+ strlcpy(diffargs, "diff", argsize);
+ for (ap = av + 1; ap < ave; ap++) {
+ if (strcmp(*ap, "--") != 0) {
+ strlcat(diffargs, " ", argsize);
+ strlcat(diffargs, *ap, argsize);
+ }
+ }
+}
+
+static void
+read_excludes_file(char *file)
+{
+ FILE *fp;
+ char *pattern = NULL;
+ size_t blen = 0;
+ ssize_t len;
+
+ if (strcmp(file, "-") == 0)
+ fp = stdin;
+ else if ((fp = fopen(file, "r")) == NULL)
+ err(2, "%s", file);
+ while ((len = getline(&pattern, &blen, fp)) >= 0) {
+ if ((len > 0) && (pattern[len - 1] == '\n'))
+ pattern[len - 1] = '\0';
+ push_excludes(pattern);
+ pattern = NULL;
+ blen = 0;
+ }
+ free(pattern);
+ if (strcmp(file, "-") != 0)
+ fclose(fp);
+}
+
+static void
+push_excludes(char *pattern)
+{
+ struct Excludes *entry;
+
+ entry = emalloc(sizeof(*entry));
+ entry->pattern = pattern;
+ entry->next = excludes_list;
+ excludes_list = entry;
+}
+
+static void
+push_ignore_pats(char *pattern)
+{
+ size_t len;
+
+ if (ignore_pats == NULL)
+ ignore_pats = estrdup(pattern);
+ else {
+ len = strlen(ignore_pats) + strlen(pattern) + 2;
+ ignore_pats = ereallocarray(ignore_pats, 1, len);
+ strlcat(ignore_pats, "|", len);
+ strlcat(ignore_pats, pattern, len);
+ }
+}
+
+void
+print_status(int val, char *path1, char *path2, const char *entry)
+{
+ if (label[0] != NULL)
+ path1 = label[0];
+ if (label[1] != NULL)
+ path2 = label[1];
+
+ switch (val) {
+ case D_BINARY:
+ printf("Binary files %s%s and %s%s differ\n", path1, entry, path2, entry);
+ break;
+ case D_DIFFER:
+ if (diff_format == D_BRIEF)
+ printf("Files %s%s and %s%s differ\n", path1, entry, path2, entry);
+ break;
+ case D_SAME:
+ if (sflag)
+ printf("Files %s%s and %s%s are identical\n", path1, entry, path2, entry);
+ break;
+ case D_MISMATCH1:
+ printf("File %s%s is directory, %s%s is file\n", path1, entry, path2, entry);
+ break;
+ case D_MISMATCH2:
+ printf("File %s%s is file, %s%s is directory\n", path1, entry, path2, entry);
+ break;
+ case D_SKIPPED1:
+ printf("File %s%s is not regular file or directory\n", path1, entry);
+ break;
+ case D_SKIPPED2:
+ printf("File %s%s is not regular file or directory\n", path2, entry);
+ break;
+ }
+}
+
+static void
+usage(void)
+{
+ fprintf(stderr, "usage: diff [-aBbdipTtw] [-c|-e|-f|-n|-q|-u|-y] [-A algo] "
+ "[-I pattern] [-F pattern] [-L label] file1 file2\n");
+ exit(2);
+}
+
+static void
+conflicting_format(void)
+{
+ errx(2, "conflicting output format options");
+}
+
+static char *
+diff_splice(char *dir, char *file)
+{
+ char *p, *res;
+
+ p = strrchr(file, '/');
+ p = p ? p + 1 : file;
+ xasprintf(&res, "%s/%s", dir, p);
+ return res;
+}
+
+static void
+xasprintf(char **strp, const char *fmt, ...)
+{
+ va_list ap;
+ int r;
+
+ va_start(ap, fmt);
+ r = vasprintf(strp, fmt, ap);
+ va_end(ap);
+ if (r == -1)
+ err(2, "asprintf");
+}
+
+static int
+cup2low(int c)
+{
+ return tolower(c);
+}
+
+static int
+clow2low(int c)
+{
+ return c;
+}
+
+static int
+do_color(void)
+{
+ if (colorflag == COLORFLAG_ALWAYS)
+ return 1;
+ if (colorflag == COLORFLAG_NEVER)
+ return 0;
+ if (isatty(STDOUT_FILENO)) {
+ char *term = getenv("COLORTERM");
+ if (term && *term != '\0')
+ return 1;
+ }
+ return 0;
+}
+
+void
+diffdir(char *p1, char *p2, int flags)
+{
+ struct dirent *dent1, **dp1, **edp1, **dirp1 = NULL;
+ struct dirent *dent2, **dp2, **edp2, **dirp2 = NULL;
+ size_t dirlen1, dirlen2;
+ char path1[PATH_MAX], path2[PATH_MAX];
+ int pos;
+
+ edp1 = edp2 = NULL;
+ dirlen1 = strlcpy(path1, *p1 ? p1 : ".", sizeof(path1));
+ if (dirlen1 >= sizeof(path1) - 1) {
+ errno = ENAMETOOLONG;
+ warn("%s", p1);
+ status |= 2;
+ return;
+ }
+ if (path1[dirlen1 - 1] != '/') {
+ path1[dirlen1++] = '/';
+ path1[dirlen1] = '\0';
+ }
+ dirlen2 = strlcpy(path2, *p2 ? p2 : ".", sizeof(path2));
+ if (dirlen2 >= sizeof(path2) - 1) {
+ errno = ENAMETOOLONG;
+ warn("%s", p2);
+ status |= 2;
+ return;
+ }
+ if (path2[dirlen2 - 1] != '/') {
+ path2[dirlen2++] = '/';
+ path2[dirlen2] = '\0';
+ }
+
+ pos = scandir(path1, &dirp1, selectfile, alphasort);
+ if (pos == -1) {
+ if (errno == ENOENT && (Nflag || Pflag))
+ pos = 0;
+ else {
+ warn("%s", path1);
+ goto closem;
+ }
+ }
+ dp1 = dirp1;
+ edp1 = dirp1 + pos;
+
+ pos = scandir(path2, &dirp2, selectfile, alphasort);
+ if (pos == -1) {
+ if (errno == ENOENT && Nflag)
+ pos = 0;
+ else {
+ warn("%s", path2);
+ goto closem;
+ }
+ }
+ dp2 = dirp2;
+ edp2 = dirp2 + pos;
+
+ if (start != NULL) {
+ while (dp1 != edp1 && strcmp((*dp1)->d_name, start) < 0)
+ dp1++;
+ while (dp2 != edp2 && strcmp((*dp2)->d_name, start) < 0)
+ dp2++;
+ }
+
+ while (dp1 != edp1 || dp2 != edp2) {
+ dent1 = dp1 != edp1 ? *dp1 : NULL;
+ dent2 = dp2 != edp2 ? *dp2 : NULL;
+
+ pos = dent1 == NULL ? 1 : dent2 == NULL ? -1 :
+ ignore_file_case ? strcasecmp(dent1->d_name, dent2->d_name) :
+ strcmp(dent1->d_name, dent2->d_name);
+ if (pos == 0) {
+ diffit(dent1, path1, dirlen1, dent2, path2, dirlen2, flags);
+ dp1++;
+ dp2++;
+ } else if (pos < 0) {
+ if (Nflag)
+ diffit(dent1, path1, dirlen1, dent2, path2, dirlen2, flags);
+ else {
+ print_only(path1, dirlen1, dent1->d_name);
+ status |= 1;
+ }
+ dp1++;
+ } else {
+ if (Nflag || Pflag)
+ diffit(dent2, path1, dirlen1, dent1, path2, dirlen2, flags);
+ else {
+ print_only(path2, dirlen2, dent2->d_name);
+ status |= 1;
+ }
+ dp2++;
+ }
+ }
+
+closem:
+ if (dirp1 != NULL) {
+ for (dp1 = dirp1; dp1 < edp1; dp1++)
+ free(*dp1);
+ free(dirp1);
+ }
+ if (dirp2 != NULL) {
+ for (dp2 = dirp2; dp2 < edp2; dp2++)
+ free(*dp2);
+ free(dirp2);
+ }
+}
+
+static void
+diffit(struct dirent *dp, char *path1, size_t plen1, struct dirent *dp2,
+ char *path2, size_t plen2, int flags)
+{
+ flags |= D_HEADER;
+ strlcpy(path1 + plen1, dp->d_name, PATH_MAX - plen1);
+
+ if (ignore_file_case && strcasecmp(dp->d_name, dp2->d_name) == 0)
+ strlcpy(path2 + plen2, dp2->d_name, PATH_MAX - plen2);
+ else
+ strlcpy(path2 + plen2, dp->d_name, PATH_MAX - plen2);
+
+ if (noderef) {
+ if (lstat(path1, &stb1) != 0) {
+ if (!(Nflag || Pflag) || errno != ENOENT) {
+ warn("%s", path1);
+ return;
+ }
+ flags |= D_EMPTY1;
+ memset(&stb1, 0, sizeof(stb1));
+ }
+
+ if (lstat(path2, &stb2) != 0) {
+ if (!Nflag || errno != ENOENT) {
+ warn("%s", path2);
+ return;
+ }
+ flags |= D_EMPTY2;
+ memset(&stb2, 0, sizeof(stb2));
+ stb2.st_mode = stb1.st_mode;
+ }
+ if (stb1.st_mode == 0)
+ stb1.st_mode = stb2.st_mode;
+ if (S_ISLNK(stb1.st_mode) || S_ISLNK(stb2.st_mode)) {
+ if (S_ISLNK(stb1.st_mode) && S_ISLNK(stb2.st_mode)) {
+ char buf1[PATH_MAX];
+ char buf2[PATH_MAX];
+ ssize_t len1;
+ ssize_t len2;
+
+ len1 = readlink(path1, buf1, sizeof(buf1));
+ len2 = readlink(path2, buf2, sizeof(buf2));
+ if (len1 < 0 || len2 < 0) {
+ perror("reading links");
+ return;
+ }
+ buf1[len1] = '\0';
+ buf2[len2] = '\0';
+ if (len1 != len2 || strncmp(buf1, buf2, len1) != 0) {
+ printf("Symbolic links %s and %s differ\n", path1, path2);
+ status |= 1;
+ }
+ return;
+ }
+ printf("File %s is a %s while file %s is a %s\n",
+ path1, S_ISLNK(stb1.st_mode) ? "symbolic link" :
+ S_ISDIR(stb1.st_mode) ? "directory" : "file",
+ path2, S_ISLNK(stb2.st_mode) ? "symbolic link" :
+ S_ISDIR(stb2.st_mode) ? "directory" : "file");
+ status |= 1;
+ return;
+ }
+ } else {
+ if (stat(path1, &stb1) != 0) {
+ if (!(Nflag || Pflag) || errno != ENOENT) {
+ warn("%s", path1);
+ return;
+ }
+ flags |= D_EMPTY1;
+ memset(&stb1, 0, sizeof(stb1));
+ }
+
+ if (stat(path2, &stb2) != 0) {
+ if (!Nflag || errno != ENOENT) {
+ warn("%s", path2);
+ return;
+ }
+ flags |= D_EMPTY2;
+ memset(&stb2, 0, sizeof(stb2));
+ stb2.st_mode = stb1.st_mode;
+ }
+ if (stb1.st_mode == 0)
+ stb1.st_mode = stb2.st_mode;
+ }
+ if (S_ISDIR(stb1.st_mode) && S_ISDIR(stb2.st_mode)) {
+ if (rflag)
+ diffdir(path1, path2, flags);
+ else
+ printf("Common subdirectories: %s and %s\n", path1, path2);
+ return;
+ }
+ if (!S_ISREG(stb1.st_mode) && !S_ISDIR(stb1.st_mode))
+ dp->d_status = D_SKIPPED1;
+ else if (!S_ISREG(stb2.st_mode) && !S_ISDIR(stb2.st_mode))
+ dp->d_status = D_SKIPPED2;
+ else
+ dp->d_status = diffreg(path1, path2, flags, 0);
+ print_status(dp->d_status, path1, path2, "");
+}
+
+static int
+selectfile(const struct dirent *dp)
+{
+ struct Excludes *excl;
+
+ if (dp->d_fileno == 0)
+ return 0;
+
+ if (dp->d_name[0] == '.' && (dp->d_name[1] == '\0' ||
+ (dp->d_name[1] == '.' && dp->d_name[2] == '\0')))
+ return 0;
+
+ for (excl = excludes_list; excl != NULL; excl = excl->next)
+ if (fnmatch(excl->pattern, dp->d_name, FNM_PATHNAME) == 0)
+ return 0;
+
+ return 1;
+}
+
+void
+print_only(const char *path, size_t dirlen, const char *entry)
+{
+ if (dirlen > 1)
+ dirlen--;
+ printf("Only in %.*s: %s\n", (int)dirlen, path, entry);
+}
+
+int
+diffreg(char *file1, char *file2, int flags, int capsicum)
+{
+ FILE *f1, *f2;
+ int i, rval;
+ struct Pr *pr = NULL;
+
+ f1 = f2 = NULL;
+ rval = D_SAME;
+ anychange = 0;
+ lastline = 0;
+ lastmatchline = 0;
+
+ if (diff_format == D_SIDEBYSIDE) {
+ if (flags & D_EXPANDTABS) {
+ if (width > 3)
+ hw = (width - 3) / 2;
+ else
+ hw = 0;
+ } else if (width <= 3 || width <= tabsize) {
+ hw = 0;
+ } else {
+ hw = (width - 3) / 2;
+ while (hw > 0 && roundup(hw + 3, tabsize) + hw > width)
+ hw--;
+ if (width - (roundup(hw + 3, tabsize) + hw) < tabsize)
+ width = roundup(hw + 3, tabsize) + hw;
+ }
+ lpad = (width - hw * 2 - 1) / 2;
+ rpad = (width - hw * 2 - 1) - lpad;
+ }
+
+ if (flags & D_IGNORECASE)
+ chrtran = cup2low;
+ else
+ chrtran = clow2low;
+ if (S_ISDIR(stb1.st_mode) != S_ISDIR(stb2.st_mode))
+ return S_ISDIR(stb1.st_mode) ? D_MISMATCH1 : D_MISMATCH2;
+ if (strcmp(file1, "-") == 0 && strcmp(file2, "-") == 0)
+ goto closem;
+
+ if (flags & D_EMPTY1)
+ f1 = fopen(_PATH_DEVNULL, "r");
+ else {
+ if (!S_ISREG(stb1.st_mode)) {
+ if ((f1 = opentemp(file1)) == NULL || fstat(fileno(f1), &stb1) == -1) {
+ warn("%s", file1);
+ rval = D_ERROR;
+ status |= 2;
+ goto closem;
+ }
+ } else if (strcmp(file1, "-") == 0)
+ f1 = stdin;
+ else
+ f1 = fopen(file1, "r");
+ }
+ if (f1 == NULL) {
+ warn("%s", file1);
+ rval = D_ERROR;
+ status |= 2;
+ goto closem;
+ }
+
+ if (flags & D_EMPTY2)
+ f2 = fopen(_PATH_DEVNULL, "r");
+ else {
+ if (!S_ISREG(stb2.st_mode)) {
+ if ((f2 = opentemp(file2)) == NULL || fstat(fileno(f2), &stb2) == -1) {
+ warn("%s", file2);
+ rval = D_ERROR;
+ status |= 2;
+ goto closem;
+ }
+ } else if (strcmp(file2, "-") == 0)
+ f2 = stdin;
+ else
+ f2 = fopen(file2, "r");
+ }
+ if (f2 == NULL) {
+ warn("%s", file2);
+ rval = D_ERROR;
+ status |= 2;
+ goto closem;
+ }
+
+ if (lflag)
+ pr = start_pr(file1, file2);
+
+ (void)capsicum;
+
+ switch (files_differ(f1, f2, flags)) {
+ case 0:
+ goto closem;
+ case 1:
+ break;
+ default:
+ rval = D_ERROR;
+ status |= 2;
+ goto closem;
+ }
+
+ if (diff_format == D_BRIEF && ignore_pats == NULL &&
+ (flags & (D_FOLDBLANKS|D_IGNOREBLANKS|D_IGNORECASE|D_SKIPBLANKLINES|D_STRIPCR)) == 0)
+ {
+ rval = D_DIFFER;
+ status |= 1;
+ goto closem;
+ }
+ if ((flags & D_FORCEASCII) != 0) {
+ prepare(0, f1, stb1.st_size, flags);
+ prepare(1, f2, stb2.st_size, flags);
+ } else if (!asciifile(f1) || !asciifile(f2) ||
+ !prepare(0, f1, stb1.st_size, flags) ||
+ !prepare(1, f2, stb2.st_size, flags)) {
+ rval = D_BINARY;
+ status |= 1;
+ goto closem;
+ }
+ if (len[0] > INT_MAX - 2)
+ errno = EFBIG, err(1, "%s", file1);
+ if (len[1] > INT_MAX - 2)
+ errno = EFBIG, err(1, "%s", file2);
+
+ prune();
+ sort(sfile[0], slen[0]);
+ sort(sfile[1], slen[1]);
+
+ member = (int *)file[1];
+ equiv(sfile[0], slen[0], sfile[1], slen[1], member);
+ member = ereallocarray(member, slen[1] + 2, sizeof(*member));
+
+ class = (int *)file[0];
+ unsort(sfile[0], slen[0], class);
+ class = ereallocarray(class, slen[0] + 2, sizeof(*class));
+
+ klist = ecalloc(slen[0] + 2, sizeof(*klist));
+ clen = 0;
+ clistlen = 100;
+ clist = ecalloc(clistlen, sizeof(*clist));
+ i = stone(class, slen[0], member, klist, flags);
+ free(member);
+ free(class);
+
+ J = ereallocarray(J, len[0] + 2, sizeof(*J));
+ unravel(klist[i]);
+ free(clist);
+ free(klist);
+
+ ixold = ereallocarray(ixold, len[0] + 2, sizeof(*ixold));
+ ixnew = ereallocarray(ixnew, len[1] + 2, sizeof(*ixnew));
+ check(f1, f2, flags);
+ output(file1, f1, file2, f2, flags);
+
+closem:
+ if (pr != NULL)
+ stop_pr(pr);
+ if (anychange) {
+ status |= 1;
+ if (rval == D_SAME)
+ rval = D_DIFFER;
+ }
+ if (f1 != NULL && f1 != stdin)
+ fclose(f1);
+ if (f2 != NULL && f2 != stdin)
+ fclose(f2);
+
+ return rval;
+}
+
+static int
+files_differ(FILE *f1, FILE *f2, int flags)
+{
+ char buf1[BUFSIZ], buf2[BUFSIZ];
+ size_t i, j;
+
+ if ((flags & (D_EMPTY1|D_EMPTY2)) || stb1.st_size != stb2.st_size ||
+ (stb1.st_mode & S_IFMT) != (stb2.st_mode & S_IFMT))
+ return 1;
+
+ if (stb1.st_dev == stb2.st_dev && stb1.st_ino == stb2.st_ino)
+ return 0;
+
+ for (;;) {
+ i = fread(buf1, 1, sizeof(buf1), f1);
+ j = fread(buf2, 1, sizeof(buf2), f2);
+ if ((!i && ferror(f1)) || (!j && ferror(f2)))
+ return -1;
+ if (i != j)
+ return 1;
+ if (i == 0)
+ return 0;
+ if (memcmp(buf1, buf2, i) != 0)
+ return 1;
+ }
+}
+
+static FILE *
+opentemp(const char *f)
+{
+ char buf[BUFSIZ], tempfile[PATH_MAX];
+ ssize_t nread;
+ int ifd, ofd;
+
+ if (strcmp(f, "-") == 0)
+ ifd = STDIN_FILENO;
+ else if ((ifd = open(f, O_RDONLY, 0644)) == -1)
+ return NULL;
+
+ strlcpy(tempfile, _PATH_TMP "/diff.XXXXXXXX", sizeof(tempfile));
+ if ((ofd = mkstemp(tempfile)) == -1) {
+ close(ifd);
+ return NULL;
+ }
+ unlink(tempfile);
+ while ((nread = read(ifd, buf, BUFSIZ)) > 0) {
+ if (write(ofd, buf, nread) != nread) {
+ close(ifd);
+ close(ofd);
+ return NULL;
+ }
+ }
+ close(ifd);
+ lseek(ofd, (off_t)0, SEEK_SET);
+ return fdopen(ofd, "r");
+}
+
+static int
+prepare(int i, FILE *fd, size_t filesize, int flags)
+{
+ struct Line *p;
+ unsigned h;
+ size_t sz, j = 0;
+ enum Readhash r;
+
+ rewind(fd);
+ sz = filesize / 25;
+ if (sz < 100)
+ sz = 100;
+
+ p = ecalloc(sz + 3, sizeof(*p));
+ while ((r = readhash(fd, flags, &h)) != RH_EOF) {
+ if (r == RH_BINARY)
+ return 0;
+ if (j == SIZE_MAX)
+ break;
+ if (j == sz) {
+ sz = sz * 3 / 2;
+ p = ereallocarray(p, sz + 3, sizeof(*p));
+ }
+ p[++j].value = h;
+ }
+ len[i] = j;
+ file[i] = p;
+ return 1;
+}
+
+static void
+prune(void)
+{
+ size_t i, j;
+
+ for (pref = 0; pref < len[0] && pref < len[1] &&
+ file[0][pref + 1].value == file[1][pref + 1].value;
+ pref++)
+ ;
+ for (suff = 0; suff < len[0] - pref && suff < len[1] - pref &&
+ file[0][len[0] - suff].value == file[1][len[1] - suff].value;
+ suff++)
+ ;
+ for (j = 0; j < 2; j++) {
+ sfile[j] = file[j] + pref;
+ slen[j] = len[j] - pref - suff;
+ for (i = 0; i <= slen[j]; i++)
+ sfile[j][i].serial = i;
+ }
+}
+
+static void
+equiv(struct Line *a, int n, struct Line *b, int m, int *c)
+{
+ int i, j;
+
+ i = j = 1;
+ while (i <= n && j <= m) {
+ if (a[i].value < b[j].value)
+ a[i++].value = 0;
+ else if (a[i].value == b[j].value)
+ a[i++].value = j;
+ else
+ j++;
+ }
+ while (i <= n)
+ a[i++].value = 0;
+ b[m + 1].value = 0;
+ j = 0;
+ while (++j <= m) {
+ c[j] = -b[j].serial;
+ while (b[j + 1].value == b[j].value) {
+ j++;
+ c[j] = b[j].serial;
+ }
+ }
+ c[j] = -1;
+}
+
+static int
+stone(int *a, int n, int *b, int *c, int flags)
+{
+ int i, k, y, j, l;
+ int oldc, tc, oldl, sq;
+ unsigned numtries, bound;
+
+ if (flags & D_MINIMAL)
+ bound = UINT_MAX;
+ else {
+ sq = sqrt(n);
+ bound = MAX(256, sq);
+ }
+
+ k = 0;
+ c[0] = newcand(0, 0, 0);
+ for (i = 1; i <= n; i++) {
+ j = a[i];
+ if (j == 0)
+ continue;
+ y = -b[j];
+ oldl = 0;
+ oldc = c[0];
+ numtries = 0;
+ do {
+ if (y <= clist[oldc].y)
+ continue;
+ l = search(c, k, y);
+ if (l != oldl + 1)
+ oldc = c[l - 1];
+ if (l <= k) {
+ if (clist[c[l]].y <= y)
+ continue;
+ tc = c[l];
+ c[l] = newcand(i, y, oldc);
+ oldc = tc;
+ oldl = l;
+ numtries++;
+ } else {
+ c[l] = newcand(i, y, oldc);
+ k++;
+ break;
+ }
+ } while ((y = b[++j]) > 0 && numtries < bound);
+ }
+ return k;
+}
+
+static int
+newcand(int x, int y, int pred)
+{
+ struct Cand *q;
+
+ if (clen == clistlen) {
+ clistlen = clistlen * 11 / 10;
+ clist = ereallocarray(clist, clistlen, sizeof(*clist));
+ }
+ q = clist + clen;
+ q->x = x;
+ q->y = y;
+ q->pred = pred;
+ return clen++;
+}
+
+static int
+search(int *c, int k, int y)
+{
+ int i, j, l, t;
+
+ if (clist[c[k]].y < y)
+ return k + 1;
+ i = 0;
+ j = k + 1;
+ for (;;) {
+ l = (i + j) / 2;
+ if (l <= i)
+ break;
+ t = clist[c[l]].y;
+ if (t > y)
+ j = l;
+ else if (t < y)
+ i = l;
+ else
+ return l;
+ }
+ return l + 1;
+}
+
+static void
+unravel(int p)
+{
+ struct Cand *q;
+ size_t i;
+
+ for (i = 0; i <= len[0]; i++)
+ J[i] = i <= pref ? i :
+ i > len[0] - suff ? i + len[1] - len[0] : 0;
+ for (q = clist + p; q->y != 0; q = clist + q->pred)
+ J[q->x + pref] = q->y + pref;
+}
+
+static void
+check(FILE *f1, FILE *f2, int flags)
+{
+ int i, j, c, d;
+ long ctold, ctnew;
+
+ rewind(f1);
+ rewind(f2);
+ j = 1;
+ ixold[0] = ixnew[0] = 0;
+ ctold = ctnew = 0;
+ for (i = 1; i <= (int)len[0]; i++) {
+ if (J[i] == 0) {
+ ixold[i] = ctold += skipline(f1);
+ continue;
+ }
+ while (j < J[i]) {
+ ixnew[j] = ctnew += skipline(f2);
+ j++;
+ }
+ if (flags & (D_FOLDBLANKS | D_IGNOREBLANKS | D_IGNORECASE | D_STRIPCR)) {
+ for (;;) {
+ c = getc(f1);
+ d = getc(f2);
+ if (flags & (D_FOLDBLANKS | D_IGNOREBLANKS)) {
+ if (c == EOF && isspace(d)) {
+ ctnew++;
+ break;
+ } else if (isspace(c) && d == EOF) {
+ ctold++;
+ break;
+ }
+ }
+ ctold++;
+ ctnew++;
+ if (flags & D_STRIPCR && (c == '\r' || d == '\r')) {
+ if (c == '\r') {
+ if ((c = getc(f1)) == '\n')
+ ctold++;
+ else
+ ungetc(c, f1);
+ }
+ if (d == '\r') {
+ if ((d = getc(f2)) == '\n')
+ ctnew++;
+ else
+ ungetc(d, f2);
+ }
+ break;
+ }
+ if ((flags & D_FOLDBLANKS) && isspace(c) && isspace(d)) {
+ do {
+ if (c == '\n')
+ break;
+ ctold++;
+ } while (isspace(c = getc(f1)));
+ do {
+ if (d == '\n')
+ break;
+ ctnew++;
+ } while (isspace(d = getc(f2)));
+ } else if (flags & D_IGNOREBLANKS) {
+ while (isspace(c) && c != '\n') {
+ c = getc(f1);
+ ctold++;
+ }
+ while (isspace(d) && d != '\n') {
+ d = getc(f2);
+ ctnew++;
+ }
+ }
+ if (chrtran(c) != chrtran(d)) {
+ J[i] = 0;
+ if (c != '\n' && c != EOF)
+ ctold += skipline(f1);
+ if (d != '\n' && c != EOF)
+ ctnew += skipline(f2);
+ break;
+ }
+ if (c == '\n' || c == EOF)
+ break;
+ }
+ } else {
+ for (;;) {
+ ctold++;
+ ctnew++;
+ if ((c = getc(f1)) != (d = getc(f2))) {
+ J[i] = 0;
+ if (c != '\n' && c != EOF)
+ ctold += skipline(f1);
+ if (d != '\n' && c != EOF)
+ ctnew += skipline(f2);
+ break;
+ }
+ if (c == '\n' || c == EOF)
+ break;
+ }
+ }
+ ixold[i] = ctold;
+ ixnew[j] = ctnew;
+ j++;
+ }
+ for (; j <= (int)len[1]; j++) {
+ ixnew[j] = ctnew += skipline(f2);
+ }
+}
+
+static void
+sort(struct Line *a, int n)
+{
+ struct Line *ai, *aim, w;
+ int j, m = 0, k;
+
+ if (n == 0)
+ return;
+ for (j = 1; j <= n; j *= 2)
+ m = 2 * j - 1;
+ for (m /= 2; m != 0; m /= 2) {
+ k = n - m;
+ for (j = 1; j <= k; j++) {
+ for (ai = &a[j]; ai > a; ai -= m) {
+ aim = &ai[m];
+ if (aim < ai)
+ break;
+ if (aim->value > ai[0].value ||
+ (aim->value == ai[0].value && aim->serial > ai[0].serial))
+ break;
+ w.value = ai[0].value;
+ ai[0].value = aim->value;
+ aim->value = w.value;
+ w.serial = ai[0].serial;
+ ai[0].serial = aim->serial;
+ aim->serial = w.serial;
+ }
+ }
+ }
+}
+
+static void
+unsort(struct Line *f, int l, int *b)
+{
+ int *a, i;
+
+ a = ecalloc(l + 1, sizeof(*a));
+ for (i = 1; i <= l; i++)
+ a[f[i].serial] = f[i].value;
+ for (i = 1; i <= l; i++)
+ b[i] = a[i];
+ free(a);
+}
+
+static int
+skipline(FILE *f)
+{
+ int i, c;
+
+ for (i = 1; (c = getc(f)) != '\n' && c != EOF; i++)
+ continue;
+ return i;
+}
+
+static void
+output(char *file1, FILE *f1, char *file2, FILE *f2, int flags)
+{
+ int i, j, m, i0, i1, j0, j1, nc;
+
+ rewind(f1);
+ rewind(f2);
+ m = len[0];
+ J[0] = 0;
+ J[m + 1] = len[1] + 1;
+ if (diff_format != D_EDIT) {
+ for (i0 = 1; i0 <= m; i0 = i1 + 1) {
+ while (i0 <= m && J[i0] == J[i0 - 1] + 1) {
+ if (diff_format == D_SIDEBYSIDE && suppress_common != 1) {
+ nc = fetch(ixold, i0, i0, f1, '\0', 1, flags);
+ print_space(nc, hw - nc + lpad + 1 + rpad, flags);
+ fetch(ixnew, J[i0], J[i0], f2, '\0', 0, flags);
+ printf("\n");
+ }
+ i0++;
+ }
+ j0 = J[i0 - 1] + 1;
+ i1 = i0 - 1;
+ while (i1 < m && J[i1 + 1] == 0)
+ i1++;
+ j1 = J[i1 + 1] - 1;
+ J[i1] = j1;
+
+ if (diff_format == D_SIDEBYSIDE) {
+ for (i = i0, j = j0; i <= i1 && j <= j1; i++, j++)
+ change(file1, f1, file2, f2, i, i, j, j, &flags);
+ while (i <= i1) {
+ change(file1, f1, file2, f2, i, i, j + 1, j, &flags);
+ i++;
+ }
+ while (j <= j1) {
+ change(file1, f1, file2, f2, i + 1, i, j, j, &flags);
+ j++;
+ }
+ } else
+ change(file1, f1, file2, f2, i0, i1, j0, j1, &flags);
+ }
+ } else {
+ for (i0 = m; i0 >= 1; i0 = i1 - 1) {
+ while (i0 >= 1 && J[i0] == J[i0 + 1] - 1 && J[i0] != 0)
+ i0--;
+ j0 = J[i0 + 1] - 1;
+ i1 = i0 + 1;
+ while (i1 > 1 && J[i1 - 1] == 0)
+ i1--;
+ j1 = J[i1 - 1] + 1;
+ J[i1] = j1;
+ change(file1, f1, file2, f2, i1, i0, j1, j0, &flags);
+ }
+ }
+ if (m == 0)
+ change(file1, f1, file2, f2, 1, 0, 1, len[1], &flags);
+ if (diff_format == D_IFDEF || diff_format == D_GFORMAT) {
+ for (;;) {
+#define c i0
+ if ((c = getc(f1)) == EOF)
+ return;
+ printf("%c", c);
+ }
+#undef c
+ }
+ if (anychange != 0) {
+ if (diff_format == D_CONTEXT)
+ dump_context_vec(f1, f2, flags);
+ else if (diff_format == D_UNIFIED)
+ dump_unified_vec(f1, f2, flags);
+ }
+}
+
+static void
+range(int a, int b, const char *separator)
+{
+ printf("%d", a > b ? b : a);
+ if (a < b)
+ printf("%s%d", separator, b);
+}
+
+static void
+uni_range(int a, int b)
+{
+ if (a < b)
+ printf("%d,%d", a, b - a + 1);
+ else if (a == b)
+ printf("%d", b);
+ else
+ printf("%d,0", b);
+}
+
+static char *
+preadline(int fd, size_t rlen, off_t off)
+{
+ char *line;
+ ssize_t nr;
+
+ line = emalloc(rlen + 1);
+ if ((nr = pread(fd, line, rlen, off)) == -1)
+ err(2, "preadline");
+ if (nr > 0 && line[nr-1] == '\n')
+ nr--;
+ line[nr] = '\0';
+ return line;
+}
+
+static int
+ignoreline_pattern(char *line)
+{
+ int ret;
+
+ ret = regexec(&ignore_re, line, 0, NULL, 0);
+ return ret == 0;
+}
+
+static int
+ignoreline(char *line, int skip_blanks)
+{
+ if (skip_blanks && *line == '\0')
+ return 1;
+ if (ignore_pats != NULL && ignoreline_pattern(line))
+ return 1;
+ return 0;
+}
+
+static void
+change(char *file1, FILE *f1, char *file2, FILE *f2, int a, int b, int c, int d,
+ int *pflags)
+{
+ static size_t max_context = 64;
+ long curpos;
+ int i, nc;
+ const char *walk;
+ int skip_blanks, ignore;
+
+ skip_blanks = (*pflags & D_SKIPBLANKLINES);
+restart:
+ if ((diff_format != D_IFDEF || diff_format == D_GFORMAT) && a > b && c > d)
+ return;
+ if (ignore_pats != NULL || skip_blanks) {
+ char *line;
+ if (a <= b) {
+ for (i = a; i <= b; i++) {
+ line = preadline(fileno(f1), ixold[i] - ixold[i - 1], ixold[i - 1]);
+ ignore = ignoreline(line, skip_blanks);
+ free(line);
+ if (!ignore)
+ goto proceed;
+ }
+ }
+ if (a > b || c <= d) {
+ for (i = c; i <= d; i++) {
+ line = preadline(fileno(f2), ixnew[i] - ixnew[i - 1], ixnew[i - 1]);
+ ignore = ignoreline(line, skip_blanks);
+ free(line);
+ if (!ignore)
+ goto proceed;
+ }
+ }
+ return;
+ }
+proceed:
+ if (*pflags & D_HEADER && diff_format != D_BRIEF) {
+ printf("%s %s %s\n", diffargs, file1, file2);
+ *pflags &= ~D_HEADER;
+ }
+ if (diff_format == D_CONTEXT || diff_format == D_UNIFIED) {
+ if (context_vec_start == NULL || context_vec_ptr == context_vec_end - 1) {
+ ptrdiff_t offset = -1;
+
+ if (context_vec_start != NULL)
+ offset = context_vec_ptr - context_vec_start;
+ max_context <<= 1;
+ context_vec_start = ereallocarray(context_vec_start, max_context, sizeof(*context_vec_start));
+ context_vec_end = context_vec_start + max_context;
+ context_vec_ptr = context_vec_start + offset;
+ }
+ if (anychange == 0) {
+ print_header(file1, file2);
+ anychange = 1;
+ } else if (a > context_vec_ptr->b + (2 * diff_context) + 1 &&
+ c > context_vec_ptr->d + (2 * diff_context) + 1) {
+ if (diff_format == D_CONTEXT)
+ dump_context_vec(f1, f2, *pflags);
+ else
+ dump_unified_vec(f1, f2, *pflags);
+ }
+ context_vec_ptr++;
+ context_vec_ptr->a = a;
+ context_vec_ptr->b = b;
+ context_vec_ptr->c = c;
+ context_vec_ptr->d = d;
+ return;
+ }
+ if (anychange == 0)
+ anychange = 1;
+ switch (diff_format) {
+ case D_BRIEF:
+ return;
+ case D_NORMAL:
+ case D_EDIT:
+ range(a, b, ",");
+ printf("%c", a > b ? 'a' : c > d ? 'd' : 'c');
+ if (diff_format == D_NORMAL)
+ range(c, d, ",");
+ printf("\n");
+ break;
+ case D_REVERSE:
+ printf("%c", a > b ? 'a' : c > d ? 'd' : 'c');
+ range(a, b, " ");
+ printf("\n");
+ break;
+ case D_NREVERSE:
+ if (a > b)
+ printf("a%d %d\n", b, d - c + 1);
+ else {
+ printf("d%d %d\n", a, b - a + 1);
+ if (!(c > d))
+ printf("a%d %d\n", b, d - c + 1);
+ }
+ break;
+ }
+ if (diff_format == D_GFORMAT) {
+ curpos = ftell(f1);
+ nc = ixold[a > b ? b : a - 1] - curpos;
+ for (i = 0; i < nc; i++)
+ printf("%c", getc(f1));
+ for (walk = group_format; *walk != '\0'; walk++) {
+ if (*walk == '%') {
+ walk++;
+ switch (*walk) {
+ case '<':
+ fetch(ixold, a, b, f1, '<', 1, *pflags);
+ break;
+ case '>':
+ fetch(ixnew, c, d, f2, '>', 0, *pflags);
+ break;
+ default:
+ printf("%%%c", *walk);
+ break;
+ }
+ continue;
+ }
+ printf("%c", *walk);
+ }
+ }
+ if (diff_format == D_SIDEBYSIDE) {
+ if (color && a > b)
+ printf("\033[%sm", add_code);
+ else if (color && c > d)
+ printf("\033[%sm", del_code);
+ if (a > b) {
+ print_space(0, hw + lpad, *pflags);
+ } else {
+ nc = fetch(ixold, a, b, f1, '\0', 1, *pflags);
+ print_space(nc, hw - nc + lpad, *pflags);
+ }
+ if (color && a > b)
+ printf("\033[%sm", add_code);
+ else if (color && c > d)
+ printf("\033[%sm", del_code);
+ printf("%c", (a > b) ? '>' : ((c > d) ? '<' : '|'));
+ if (color && c > d)
+ printf("\033[m");
+ print_space(hw + lpad + 1, rpad, *pflags);
+ fetch(ixnew, c, d, f2, '\0', 0, *pflags);
+ printf("\n");
+ }
+ if (diff_format == D_NORMAL || diff_format == D_IFDEF) {
+ fetch(ixold, a, b, f1, '<', 1, *pflags);
+ if (a <= b && c <= d && diff_format == D_NORMAL)
+ printf("---\n");
+ }
+ if (diff_format != D_GFORMAT && diff_format != D_SIDEBYSIDE)
+ fetch(ixnew, c, d, f2, diff_format == D_NORMAL ? '>' : '\0', 0, *pflags);
+ if (edoffset != 0 && diff_format == D_EDIT) {
+ printf(".\n");
+ printf("%ds/.//\n", a + edoffset - 1);
+ b = a + edoffset - 1;
+ a = b + 1;
+ c += edoffset;
+ goto restart;
+ }
+ if ((diff_format == D_EDIT || diff_format == D_REVERSE) && c <= d)
+ printf(".\n");
+ if (inifdef) {
+ printf("#endif /* %s */\n", ifdefname);
+ inifdef = 0;
+ }
+}
+
+static int
+fetch(long *f, int a, int b, FILE *lb, int ch, int oldfile, int flags)
+{
+ int i, j, c, lastc, col, nc, newcol;
+
+ edoffset = 0;
+ nc = 0;
+ col = 0;
+ if ((diff_format == D_IFDEF) && oldfile) {
+ long curpos = ftell(lb);
+ nc = f[a > b ? b : a - 1] - curpos;
+ for (i = 0; i < nc; i++)
+ printf("%c", getc(lb));
+ }
+ if (a > b)
+ return 0;
+ if (diff_format == D_IFDEF) {
+ if (inifdef) {
+ printf("#else /* %s%s */\n",
+ oldfile == 1 ? "!" : "", ifdefname);
+ } else {
+ if (oldfile)
+ printf("#ifndef %s\n", ifdefname);
+ else
+ printf("#ifdef %s\n", ifdefname);
+ }
+ inifdef = 1 + oldfile;
+ }
+ for (i = a; i <= b; i++) {
+ fseek(lb, f[i - 1], SEEK_SET);
+ nc = f[i] - f[i - 1];
+ if (diff_format == D_SIDEBYSIDE && hw < nc)
+ nc = hw;
+ if (diff_format != D_IFDEF && diff_format != D_GFORMAT && ch != '\0') {
+ if (color && (ch == '>' || ch == '+'))
+ printf("\033[%sm", add_code);
+ else if (color && (ch == '<' || ch == '-'))
+ printf("\033[%sm", del_code);
+ printf("%c", ch);
+ if (Tflag && (diff_format == D_NORMAL ||
+ diff_format == D_CONTEXT ||
+ diff_format == D_UNIFIED))
+ printf("\t");
+ else if (diff_format != D_UNIFIED)
+ printf(" ");
+ }
+ col = j = 0;
+ lastc = '\0';
+ while (j < nc && (hw == 0 || col < hw)) {
+ c = getc(lb);
+ if (flags & D_STRIPCR && c == '\r') {
+ if ((c = getc(lb)) == '\n')
+ j++;
+ else {
+ ungetc(c, lb);
+ c = '\r';
+ }
+ }
+ if (c == EOF) {
+ if (diff_format == D_EDIT ||
+ diff_format == D_REVERSE ||
+ diff_format == D_NREVERSE)
+ warnx("No newline at end of file");
+ else
+ printf("\n\\ No newline at end of file\n");
+ return col;
+ }
+ if (c == '\t') {
+ newcol = roundup(col + 1, tabsize);
+ if ((flags & D_EXPANDTABS) == 0) {
+ if (hw > 0 && newcol >= hw)
+ return col;
+ printf("\t");
+ } else {
+ if (hw > 0 && newcol > hw)
+ newcol = hw;
+ printf("%*s", newcol - col, "");
+ }
+ col = newcol;
+ } else {
+ if (diff_format == D_EDIT && j == 1 && c == '\n' && lastc == '.') {
+ printf(".\n");
+ edoffset = i - a + 1;
+ return edoffset;
+ }
+ if (diff_format != D_SIDEBYSIDE || c != '\n') {
+ if (color && c == '\n')
+ printf("\033[m%c", c);
+ else
+ printf("%c", c);
+ col++;
+ }
+ }
+ j++;
+ lastc = c;
+ }
+ }
+ if (color && diff_format == D_SIDEBYSIDE)
+ printf("\033[m");
+ return col;
+}
+
+static enum Readhash
+readhash(FILE *f, int flags, unsigned *hash)
+{
+ int i, t, space;
+ unsigned sum;
+
+ sum = 1;
+ space = 0;
+ for (i = 0;;) {
+ switch (t = getc(f)) {
+ case '\0':
+ if ((flags & D_FORCEASCII) == 0)
+ return RH_BINARY;
+ goto hashchar;
+ case '\r':
+ if (flags & D_STRIPCR) {
+ t = getc(f);
+ if (t == '\n')
+ break;
+ ungetc(t, f);
+ }
+ /* FALLTHROUGH */
+ case '\t':
+ case '\v':
+ case '\f':
+ case ' ':
+ if ((flags & (D_FOLDBLANKS|D_IGNOREBLANKS)) != 0) {
+ space++;
+ continue;
+ }
+ /* FALLTHROUGH */
+ default:
+ hashchar:
+ if (space && (flags & D_IGNOREBLANKS) == 0) {
+ i++;
+ space = 0;
+ }
+ sum = sum * 127 + chrtran(t);
+ i++;
+ continue;
+ case EOF:
+ if (i == 0)
+ return RH_EOF;
+ /* FALLTHROUGH */
+ case '\n':
+ break;
+ }
+ break;
+ }
+ *hash = sum;
+ return RH_OK;
+}
+
+static int
+asciifile(FILE *f)
+{
+ unsigned char buf[BUFSIZ];
+ size_t cnt;
+
+ if (f == NULL)
+ return 1;
+
+ rewind(f);
+ cnt = fread(buf, 1, sizeof(buf), f);
+ return memchr(buf, '\0', cnt) == NULL;
+}
+
+#define begins_with(s, pre) (strncmp(s, pre, sizeof(pre) - 1) == 0)
+
+static char *
+match_function(const long *f, int pos, FILE *fp)
+{
+ char buf[FUNCTION_CONTEXT_SIZE];
+ size_t nc;
+ int last = lastline;
+ const char *state = NULL;
+
+ lastline = pos;
+ for (; pos > last; pos--) {
+ fseek(fp, f[pos - 1], SEEK_SET);
+ nc = f[pos] - f[pos - 1];
+ if (nc >= sizeof(buf))
+ nc = sizeof(buf) - 1;
+ nc = fread(buf, 1, nc, fp);
+ if (nc == 0)
+ continue;
+ buf[nc] = '\0';
+ buf[strcspn(buf, "\n")] = '\0';
+ if (most_recent_pat != NULL) {
+ int ret = regexec(&most_recent_re, buf, 0, NULL, 0);
+ if (ret != 0)
+ continue;
+ strlcpy(lastbuf, buf, sizeof(lastbuf));
+ lastmatchline = pos;
+ return lastbuf;
+ } else if (isalpha(buf[0]) || buf[0] == '_' || buf[0] == '$' || buf[0] == '-' || buf[0] == '+') {
+ if (begins_with(buf, "private:")) {
+ if (!state)
+ state = " (private)";
+ } else if (begins_with(buf, "protected:")) {
+ if (!state)
+ state = " (protected)";
+ } else if (begins_with(buf, "public:")) {
+ if (!state)
+ state = " (public)";
+ } else {
+ strlcpy(lastbuf, buf, sizeof(lastbuf));
+ if (state)
+ strlcat(lastbuf, state, sizeof(lastbuf));
+ lastmatchline = pos;
+ return lastbuf;
+ }
+ }
+ }
+ return lastmatchline > 0 ? lastbuf : NULL;
+}
+
+static void
+dump_context_vec(FILE *f1, FILE *f2, int flags)
+{
+ struct ContextVec *cvp = context_vec_start;
+ int lowa, upb, lowc, upd, do_output;
+ int a, b, c, d;
+ char ch, *f;
+
+ if (context_vec_start > context_vec_ptr)
+ return;
+
+ b = d = 0;
+ lowa = MAX(1, cvp->a - diff_context);
+ upb = MIN((int)len[0], context_vec_ptr->b + diff_context);
+ lowc = MAX(1, cvp->c - diff_context);
+ upd = MIN((int)len[1], context_vec_ptr->d + diff_context);
+
+ printf("***************");
+ if (flags & (D_PROTOTYPE | D_MATCHLAST)) {
+ f = match_function(ixold, cvp->a - 1, f1);
+ if (f != NULL)
+ printf(" %s", f);
+ }
+ printf("\n*** ");
+ range(lowa, upb, ",");
+ printf(" ****\n");
+
+ do_output = 0;
+ for (; cvp <= context_vec_ptr; cvp++)
+ if (cvp->a <= cvp->b) {
+ cvp = context_vec_start;
+ do_output++;
+ break;
+ }
+ if (do_output) {
+ while (cvp <= context_vec_ptr) {
+ a = cvp->a;
+ b = cvp->b;
+ c = cvp->c;
+ d = cvp->d;
+
+ if (a <= b && c <= d)
+ ch = 'c';
+ else
+ ch = (a <= b) ? 'd' : 'a';
+
+ if (ch == 'a')
+ fetch(ixold, lowa, b, f1, ' ', 0, flags);
+ else {
+ fetch(ixold, lowa, a - 1, f1, ' ', 0, flags);
+ fetch(ixold, a, b, f1, ch == 'c' ? '!' : '-', 0, flags);
+ }
+ lowa = b + 1;
+ cvp++;
+ }
+ fetch(ixold, b + 1, upb, f1, ' ', 0, flags);
+ }
+
+ printf("--- ");
+ range(lowc, upd, ",");
+ printf(" ----\n");
+
+ do_output = 0;
+ for (cvp = context_vec_start; cvp <= context_vec_ptr; cvp++)
+ if (cvp->c <= cvp->d) {
+ cvp = context_vec_start;
+ do_output++;
+ break;
+ }
+ if (do_output) {
+ while (cvp <= context_vec_ptr) {
+ a = cvp->a;
+ b = cvp->b;
+ c = cvp->c;
+ d = cvp->d;
+
+ if (a <= b && c <= d)
+ ch = 'c';
+ else
+ ch = (a <= b) ? 'd' : 'a';
+
+ if (ch == 'd')
+ fetch(ixnew, lowc, d, f2, ' ', 0, flags);
+ else {
+ fetch(ixnew, lowc, c - 1, f2, ' ', 0, flags);
+ fetch(ixnew, c, d, f2, ch == 'c' ? '!' : '+', 0, flags);
+ }
+ lowc = d + 1;
+ cvp++;
+ }
+ fetch(ixnew, d + 1, upd, f2, ' ', 0, flags);
+ }
+ context_vec_ptr = context_vec_start - 1;
+}
+
+static void
+dump_unified_vec(FILE *f1, FILE *f2, int flags)
+{
+ struct ContextVec *cvp = context_vec_start;
+ int lowa, upb, lowc, upd;
+ int a, b, c, d;
+ char ch, *f;
+
+ if (context_vec_start > context_vec_ptr)
+ return;
+
+ b = d = 0;
+ lowa = MAX(1, cvp->a - diff_context);
+ upb = MIN((int)len[0], context_vec_ptr->b + diff_context);
+ lowc = MAX(1, cvp->c - diff_context);
+ upd = MIN((int)len[1], context_vec_ptr->d + diff_context);
+
+ printf("@@ -");
+ uni_range(lowa, upb);
+ printf(" +");
+ uni_range(lowc, upd);
+ printf(" @@");
+ if (flags & (D_PROTOTYPE | D_MATCHLAST)) {
+ f = match_function(ixold, cvp->a - 1, f1);
+ if (f != NULL)
+ printf(" %s", f);
+ }
+ printf("\n");
+
+ for (; cvp <= context_vec_ptr; cvp++) {
+ a = cvp->a;
+ b = cvp->b;
+ c = cvp->c;
+ d = cvp->d;
+
+ if (a <= b && c <= d)
+ ch = 'c';
+ else
+ ch = (a <= b) ? 'd' : 'a';
+
+ switch (ch) {
+ case 'c':
+ fetch(ixold, lowa, a - 1, f1, ' ', 0, flags);
+ fetch(ixold, a, b, f1, '-', 0, flags);
+ fetch(ixnew, c, d, f2, '+', 0, flags);
+ break;
+ case 'd':
+ fetch(ixold, lowa, a - 1, f1, ' ', 0, flags);
+ fetch(ixold, a, b, f1, '-', 0, flags);
+ break;
+ case 'a':
+ fetch(ixnew, lowc, c - 1, f2, ' ', 0, flags);
+ fetch(ixnew, c, d, f2, '+', 0, flags);
+ break;
+ }
+ lowa = b + 1;
+ lowc = d + 1;
+ }
+ fetch(ixnew, d + 1, upd, f2, ' ', 0, flags);
+ context_vec_ptr = context_vec_start - 1;
+}
+
+static void
+print_header(const char *file1, const char *file2)
+{
+ const char *time_format;
+ char buf[256];
+ struct tm tm1, tm2, *tm_ptr1, *tm_ptr2;
+ int nsec1 = stb1.st_mtim.tv_nsec;
+ int nsec2 = stb2.st_mtim.tv_nsec;
+
+ time_format = "%Y-%m-%d %H:%M:%S";
+ if (cflag)
+ time_format = "%c";
+ tm_ptr1 = localtime_r(&stb1.st_mtime, &tm1);
+ tm_ptr2 = localtime_r(&stb2.st_mtime, &tm2);
+ if (label[0] != NULL)
+ printf("%s %s\n", diff_format == D_CONTEXT ? "***" : "---", label[0]);
+ else {
+ strftime(buf, sizeof(buf), time_format, tm_ptr1);
+ printf("%s %s\t%s", diff_format == D_CONTEXT ? "***" : "---", file1, buf);
+ if (!cflag) {
+ strftime(buf, sizeof(buf), "%z", tm_ptr1);
+ printf(".%.9d %s", nsec1, buf);
+ }
+ printf("\n");
+ }
+ if (label[1] != NULL)
+ printf("%s %s\n", diff_format == D_CONTEXT ? "---" : "+++", label[1]);
+ else {
+ strftime(buf, sizeof(buf), time_format, tm_ptr2);
+ printf("%s %s\t%s", diff_format == D_CONTEXT ? "---" : "+++", file2, buf);
+ if (!cflag) {
+ strftime(buf, sizeof(buf), "%z", tm_ptr2);
+ printf(".%.9d %s", nsec2, buf);
+ }
+ printf("\n");
+ }
+}
+
+static void
+print_space(int nc, int n, int flags)
+{
+ int col, newcol, tabstop;
+
+ col = nc;
+ newcol = nc + n;
+ if ((flags & D_EXPANDTABS) == 0) {
+ while ((tabstop = roundup(col + 1, tabsize)) <= newcol) {
+ printf("\t");
+ col = tabstop;
+ }
+ }
+ printf("%*s", newcol - col, "");
+}
diff --git a/cmd/posix/diff/diff.c b/cmd/posix/diff/diff.c
@@ -1,908 +0,0 @@
-/* $OpenBSD: diff.c,v 1.67 2019/06/28 13:35:00 deraadt Exp $ */
-
-/*
- * Copyright (c) 2003 Todd C. Miller <Todd.Miller@courtesan.com>
- *
- * Permission to use, copy, modify, and distribute this software for any
- * purpose with or without fee is hereby granted, provided that the above
- * copyright notice and this permission notice appear in all copies.
- *
- * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
- * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
- * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
- * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
- * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
- * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
- *
- * Sponsored in part by the Defense Advanced Research Projects
- * Agency (DARPA) and Air Force Research Laboratory, Air Force
- * Materiel Command, USAF, under agreement number F39502-99-1-0512.
- */
-
-#include <sys/cdefs.h>
-#include <sys/stat.h>
-
-#include <ctype.h>
-#include <err.h>
-#include <errno.h>
-#include <getopt.h>
-#include <limits.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <unistd.h>
-
-#include "util.h"
-
-#include "diff.h"
-#include "xmalloc.h"
-
-#ifndef __dead2
-#define __dead2 __attribute__((__noreturn__))
-#endif
-
-static const char diff_version[] = "FreeBSD diff 20240307";
-bool lflag, Nflag, Pflag, rflag, sflag, Tflag, cflag;
-bool ignore_file_case, suppress_common, color, noderef;
-static bool help = false;
-int diff_format, diff_context, diff_algorithm, status;
-bool diff_algorithm_set;
-int tabsize = 8, width = 130;
-static int colorflag = COLORFLAG_NEVER;
-char *start, *ifdefname, *diffargs, *label[2];
-char *ignore_pats, *most_recent_pat;
-char *group_format = NULL;
-const char *add_code, *del_code;
-struct stat stb1, stb2;
-struct excludes *excludes_list;
-regex_t ignore_re, most_recent_re;
-
-static struct algorithm {
- const char *name;
- int id;
-} algorithms[] = {
- {"stone", D_DIFFSTONE},
- {"myers", D_DIFFMYERS},
- {"patience", D_DIFFPATIENCE},
- {NULL, D_DIFFNONE}
-};
-
-#define OPTIONS "0123456789A:aBbC:cdD:efF:HhI:iL:lnNPpqrS:sTtU:uwW:X:x:y"
-enum {
- OPT_TSIZE = CHAR_MAX + 1,
- OPT_STRIPCR,
- OPT_IGN_FN_CASE,
- OPT_NO_IGN_FN_CASE,
- OPT_NORMAL,
- OPT_HELP,
- OPT_HORIZON_LINES,
- OPT_CHANGED_GROUP_FORMAT,
- OPT_SUPPRESS_COMMON,
- OPT_COLOR,
- OPT_NO_DEREFERENCE,
- OPT_VERSION,
-};
-
-static struct option longopts[] = {
- { "algorithm", required_argument, 0, 'A' },
- { "text", no_argument, 0, 'a' },
- { "ignore-space-change", no_argument, 0, 'b' },
- { "context", optional_argument, 0, 'C' },
- { "ifdef", required_argument, 0, 'D' },
- { "minimal", no_argument, 0, 'd' },
- { "ed", no_argument, 0, 'e' },
- { "forward-ed", no_argument, 0, 'f' },
- { "show-function-line", required_argument, 0, 'F' },
- { "speed-large-files", no_argument, NULL, 'H' },
- { "ignore-blank-lines", no_argument, 0, 'B' },
- { "ignore-matching-lines", required_argument, 0, 'I' },
- { "ignore-case", no_argument, 0, 'i' },
- { "paginate", no_argument, NULL, 'l' },
- { "label", required_argument, 0, 'L' },
- { "new-file", no_argument, 0, 'N' },
- { "rcs", no_argument, 0, 'n' },
- { "unidirectional-new-file", no_argument, 0, 'P' },
- { "show-c-function", no_argument, 0, 'p' },
- { "brief", no_argument, 0, 'q' },
- { "recursive", no_argument, 0, 'r' },
- { "report-identical-files", no_argument, 0, 's' },
- { "starting-file", required_argument, 0, 'S' },
- { "expand-tabs", no_argument, 0, 't' },
- { "initial-tab", no_argument, 0, 'T' },
- { "unified", optional_argument, 0, 'U' },
- { "ignore-all-space", no_argument, 0, 'w' },
- { "width", required_argument, 0, 'W' },
- { "exclude", required_argument, 0, 'x' },
- { "exclude-from", required_argument, 0, 'X' },
- { "side-by-side", no_argument, NULL, 'y' },
- { "ignore-file-name-case", no_argument, NULL, OPT_IGN_FN_CASE },
- { "help", no_argument, NULL, OPT_HELP},
- { "horizon-lines", required_argument, NULL, OPT_HORIZON_LINES },
- { "no-dereference", no_argument, NULL, OPT_NO_DEREFERENCE},
- { "no-ignore-file-name-case", no_argument, NULL, OPT_NO_IGN_FN_CASE },
- { "normal", no_argument, NULL, OPT_NORMAL },
- { "strip-trailing-cr", no_argument, NULL, OPT_STRIPCR },
- { "tabsize", required_argument, NULL, OPT_TSIZE },
- { "changed-group-format", required_argument, NULL, OPT_CHANGED_GROUP_FORMAT},
- { "suppress-common-lines", no_argument, NULL, OPT_SUPPRESS_COMMON },
- { "color", optional_argument, NULL, OPT_COLOR },
- { "version", no_argument, NULL, OPT_VERSION},
- { NULL, 0, 0, '\0'}
-};
-
-static void checked_regcomp(char const *, regex_t *);
-static void usage(void) __dead2;
-static void conflicting_format(void) __dead2;
-static void push_excludes(char *);
-static void push_ignore_pats(char *);
-static void read_excludes_file(char *file);
-static void set_argstr(char **, char **);
-static char *splice(char *, char *);
-static bool do_color(void);
-
-/* ?man diff: differential file and directory comparator
-arguments: file1 file2
-synopsis: [-aBbdipTtw] [-c|-e|-f|-n|-q|-u|-y] [-A algo] [--brief] [--color=when] [--changed-group-format GFMT] [--ed] [--expand-tabs] [--forward-ed] [--ignore-all-space] [--ignore-case] [--ignore-space-change] [--initial-tab] [--minimal] [--no-dereference] [--no-ignore-file-name-case] [--normal] [--rcs] [--show-c-function] [--starting-file] [--speed-large-files] [--strip-trailing-cr] [--tabsize number] [--text] [-I pattern] [-F pattern] [-L label] file1 file2
-synopsis: [-aBbdilpTtw] [-A algo] [-I pattern] [-F pattern] [-L label] [--brief] [--color=when] [--changed-group-format GFMT] [--ed] [--expand-tabs] [--forward-ed] [--ignore-all-space] [--ignore-case] [--ignore-space-change] [--initial-tab] [--minimal] [--no-dereference] [--no-ignore-file-name-case] [--normal] [--paginate] [--rcs] [--show-c-function] [--speed-large-files] [--starting-file] [--strip-trailing-cr] [--tabsize number] [--text] -C number file1 file2
-synopsis: [-aBbdiltw] [-A algo] [-I pattern] [--brief] [--color=when] [--changed-group-format GFMT] [--ed] [--expand-tabs] [--forward-ed] [--ignore-all-space] [--ignore-case] [--ignore-space-change] [--initial-tab] [--minimal] [--no-dereference] [--no-ignore-file-name-case] [--normal] [--paginate] [--rcs] [--show-c-function] [--speed-large-files] [--starting-file] [--strip-trailing-cr] [--tabsize number] [--text] -D string file1 file2
-synopsis: [-aBbdilpTtw] [-A algo] [-I pattern] [-F pattern] [-L label] [--brief] [--color=when] [--changed-group-format GFMT] [--ed] [--expand-tabs] [--forward-ed] [--ignore-all-space] [--ignore-case] [--ignore-space-change] [--initial-tab] [--minimal] [--no-dereference] [--no-ignore-file-name-case] [--normal] [--paginate] [--rcs] [--show-c-function] [--speed-large-files] [--starting-file] [--strip-trailing-cr] [--tabsize number] [--text] -U number file1 file2
-synopsis: [-aBbdilNPprsTtw] [-c|-e|-f|-n|-q|-u] [-A algo] [--brief] [--color=when] [--changed-group-format GFMT] [--context] [--ed] [--expand-tabs] [--forward-ed] [--ignore-all-space] [--ignore-case] [--ignore-space-change] [--initial-tab] [--minimal] [--new-file] [--no-dereference] [--no-ignore-file-name-case] [--normal] [--paginate] [--rcs] [--recursive] [--report-identical-files] [--show-c-function] [--speed-large-files] [--strip-trailing-cr] [--tabsize number] [--text] [--unidirectional-new-file] [--unified] [-I pattern] [-F pattern] [-L label] [-S name] [-X file] [-x pattern] dir1 dir2
-synopsis: [-aBbditwW] [--color=when] [--expand-tabs] [--ignore-all-space] [--ignore-blank-lines] [--ignore-case] [--minimal] [--no-dereference] [--no-ignore-file-name-case] [--strip-trailing-cr] [--suppress-common-lines] [--tabsize number] [--text] -y file1 file2
-synopsis: diff [--help]
-synopsis: diff [--version]
-The diff utility compares the contents of file1 and file2 and writes to the standard output the list of changes necessary to convert one file into the other. No output is produced if the files are identical.
-## OUTPUT OPTIONS
-### -C number, --context number
-Like c but produces a diff with number lines of context.
-### -c
-Produces a diff with 3 lines of context.
-
-With c the output format is modified slightly: the output begins with identification of the files involved and their creation dates and then each change is separated by a line with fifteen *'s. The lines removed from file1 are marked with '- '; those added to file2 are marked '+ '. Lines which are changed from one file to the other are marked in both files with '! '. Changes which lie within 3 lines of each other are grouped together on output.
-### -D string, --ifdef string
-Creates a merged version of file1 and file2 on the standard output, with C preprocessor controls included so that a compilation of the result without defining string is equivalent to compiling file1, while defining string will yield file2.
-### -e, --ed
-Produces output in a form suitable as input for the editor utility, ed(1), which can then be used to convert file1 into file2.
-
-Extra commands are added to the output when comparing directories with e, so that the result is a sh(1) script for converting text files which are common to the two directories from their state in dir1 to their state in dir2. Note that when comparing directories with e, the resulting file may no longer be interpreted as an ed(1) script. Output is added to indicate which file each set of ed(1) commands applies to. These hunks can be manually extracted to produce an ed(1) script, which can also be applied with patch(1).
-### -f, --forward-ed
-Identical output to that of the e flag, but in reverse order. It cannot be digested by ed(1).
-### --help
-This option prints a summary to stdout and exits with status 0.
-### -n
-Produces a script similar to that of e, but in the opposite order and with a count of changed lines on each insert or delete command. This is the form used by rcsdiff.
-### -q, --brief
-Just print a line when the files differ. Does not output a list of changes.
-### -U number, --unified number
-Like u but produces a diff with number lines of context.
-### -u
-Produces a unified diff with 3 lines of context.
-
-A unified diff is similar to the context diff produced by the c option. However, unlike with c, all lines to be changed (added and/or removed) are present in a single section.
-### --version
-This option prints a version string to stdout and exits with status 0.
-### -y, --side-by-side
-Output in two columns with a marker between them.
-
-The marker can be one of the following:
-
-### space
-Corresponding lines are identical.
-### '|'
-Corresponding lines are different.
-### '<'
-Files differ and only the first file contains the line.
-### '>'
-Files differ and only the second file contains the line.
-## COMPARISON OPTIONS
-### -A algo, --algorithm algo
-Configure the algorithm used when comparing files. diff supports 3 algorithms:
-
-### myers
-The Myers diff algorithm finds the shortest edit which transforms one input into the other. It generally runs in O(N+D²) time, requiring O(N) space, where N is the sum of the lengths of the inputs and D is the length of the difference between them, with a theoretical O(N·D) worst case. If it encounters worst-case input, the implementation used by diff falls back to a less optimal but faster algorithm.
-### patience
-The Patience variant of the Myers algorithm attempts to create more aesthetically pleasing diff output by logically grouping lines.
-### stone
-The Stone algorithm (commonly known as Hunt-McIlroy or Hunt-Szymanski) looks for the longest common subsequence between compared files. Stone encounters worst case performance when there are long common subsequences. In large files this can lead to a significant performance impact. The Stone algorithm is maintained for compatibility.
-
-The diff utility defaults to the Myers algorithm, but will fall back to the Stone algorithm if the input or output options are not supported by the Myers implementation.
-### -a, --text
-Treat all files as ASCII text.
-
-Normally diff will simply print "Binary files ... differ" if files contain binary characters. Use of this option forces diff to produce a diff.
-### -B, --ignore-blank-lines
-Causes chunks that include only blank lines to be ignored.
-### -b, --ignore-space-change
-Causes trailing blanks (spaces and tabs) to be ignored, and other strings of blanks to compare equal.
-### --color when
-Color the additions green, and removals red, or the value in the DIFFCOLORS environment variable.
-
-The possible values of when are "never", "always" and "auto". auto will use color if the output is a tty and the COLORTERM environment variable is set to a non-empty string.
-### -d, --minimal
-Try very hard to produce a diff as small as possible. This may consume a lot of processing power and memory when processing large files with many changes.
-### -F pattern, --show-function-line pattern
-Like p, but display the last line that matches provided pattern.
-### -I pattern, --ignore-matching-lines pattern
-Ignores changes, insertions, and deletions whose lines match the extended regular expression pattern. Multiple I patterns may be specified. All lines in the change must match some pattern for the change to be ignored. See re_format(7) for more information on regular expression patterns.
-### -i, --ignore-case
-Ignores the case of letters. E.g., "A" will compare equal to "a".
-### -l, --paginate
-Pass the output through pr(1) to paginate it.
-### -L label, --label label
-Print label instead of the first (and second, if this option is specified twice) file name and time in the context or unified diff header.
-### -p, --show-c-function
-With unified and context diffs, show with each change the first 40 characters of the last line before the context beginning with a letter, an underscore or a dollar sign. For C and Objective-C source code following standard layout conventions, this will show the prototype of the function the change applies to.
-### -T, --initial-tab
-Print a tab rather than a space before the rest of the line for the normal, context or unified output formats. This makes the alignment of tabs in the line consistent.
-### -t, --expand-tabs
-Will expand tabs in output lines.
-
-Normal or c output adds character(s) to the front of each line which may screw up the indentation of the original source lines and make the output listing difficult to interpret. This option will preserve the original source's indentation.
-### -w, --ignore-all-space
-Is similar to b --ignore-space-change but causes whitespace (blanks and tabs) to be totally ignored. E.g., "if ( a == b )" will compare equal to "if(a==b)".
-### -W number, --width number
-Output at most number columns when using side by side format. The default value is 130. Note that unless t was specified, diff will always align the second column to a tab stop, so values of --width smaller than approximately five times the value of --tabsize may yield surprising results.
-### --changed-group-format GFMT
-Format input groups in the provided.
-
-the format is a string with special keywords:
-
-### %<
-lines from FILE1
-### %>
-lines from FILE2
-### --ignore-file-name-case
-ignore case when comparing file names
-### --no-dereference
-do not follow symbolic links
-### --no-ignore-file-name-case
-do not ignore case when comparing file names (default)
-### --normal
-default diff output
-### --speed-large-files
-stub option for compatibility with GNU diff
-### --strip-trailing-cr
-strip carriage return on input files
-### --suppress-common-lines
-Do not output common lines when using the side by side format
-### --tabsize number
-Number of spaces representing a tab (default 8)
-## DIRECTORY COMPARISON OPTIONS
-### -N, --new-file
-If a file is found in only one directory, act as if it was found in the other directory too but was of zero size.
-### -P, --unidirectional-new-file
-If a file is found only in dir2, act as if it was found in dir1 too but was of zero size.
-### -r, --recursive
-Causes application of diff recursively to common subdirectories encountered.
-### -S name, --starting-file name
-Re-starts a directory diff in the middle, beginning with file name.
-### -s, --report-identical-files
-Causes diff to report files which are the same, which are otherwise not mentioned.
-### -X file, --exclude-from file
-Exclude files and subdirectories from comparison whose basenames match lines in file. Multiple X options may be specified.
-### -x pattern, --exclude pattern
-Exclude files and subdirectories from comparison whose basenames match pattern. Patterns are matched using shell-style globbing via fnmatch(3). Multiple x options may be specified.
-
-If both arguments are directories, diff sorts the contents of the directories by name, and then runs the regular file diff algorithm, producing a change list, on text files which are different. Binary files which differ, common subdirectories, and files which appear in only one directory are described as such. In directory mode only regular files and directories are compared. If a non-regular file such as a device special file or FIFO is encountered, a diagnostic message is printed.
-
-If only one of file1 and file2 is a directory, diff is applied to the non-directory file and the file contained in the directory file with a filename that is the same as the last component of the non-directory file.
-
-If either file1 or file2 is -, the standard input is used in its place.
-## OUTPUT STYLE
-The default (without e, c, or n -rcs options) output contains lines of these forms, where XX, YY, ZZ, QQ are line numbers respective of file order.
-
-### XXaYY
-At (the end of) line XX of file1, append the contents of line YY of file2 to make them equal.
-### XXaYY,ZZ
-Same as above, but append the range of lines, YY through ZZ of file2 to line XX of file1.
-### XXdYY
-At line XX delete the line. The value YY tells to which line the change would bring file1 in line with file2.
-### XX,YYdZZ
-Delete the range of lines XX through YY in file1.
-### XXcYY
-Change the line XX in file1 to the line YY in file2.
-### XX,YYcZZ
-Replace the range of specified lines with the line ZZ.
-### XX,YYcZZ,QQ
-Replace the range XX,YY from file1 with the range ZZ,QQ from file2.
-
-These lines resemble ed(1) subcommands to convert file1 into file2. The line numbers before the action letters pertain to file1; those after pertain to file2. Thus, by exchanging a for d and reading the line in reverse order, one can also determine how to convert file2 into file1. As in ed(1), identical pairs (where num1 = num2) are abbreviated as a single number.
-## ENVIRONMENT
-### DIFFCOLORS
-The value of this variable is the form add:rm, where add is the ASCII escape sequence for additions and rm is the ASCII escape sequence for deletions. If this is unset, diff uses green for additions and red for removals.
-## FILES
-### /tmp/diff.XXXXXXXX
-Temporary file used when comparing a device or the standard input. Note that the temporary file is unlinked as soon as it is created so it will not show up in a directory listing.
-## EXIT STATUS
-### 0
-No differences were found.
-### 1
-Differences were found.
-### >1
-An error occurred.
-
-The --help and --version options exit with a status of 0.
-## EXAMPLES
-### Compare old_dir and new_dir recursively generating an unified diff and treating files found only in one of those directories as new files
-$ diff -ruN /path/to/old_dir /path/to/new_dir
-### Same as above but excluding files matching the expressions "*.h" and "*.c"
-$ diff -ruN -x '*.h' -x '*.c' /path/to/old_dir /path/to/new_dir
-### Show a single line indicating if the files differ
-$ diff -q /boot/loader.conf /boot/defaults/loader.conf
-Files /boot/loader.conf and /boot/defaults/loader.conf differ
-### Assuming a file named example.txt with the following contents
-FreeBSD is an operating system
-Linux is a kernel
-OpenBSD is an operating system
-### Compare stdin with example.txt excluding from the comparison those lines containing either "Linux" or "Open"
-$ echo "FreeBSD is an operating system" | diff -q -I 'Linux|Open' example.txt -
-## SEE ALSO
-cmp(1), comm(1), diff3(1), ed(1), patch(1), pr(1), sdiff(1)
-## STANDARDS
-The diff utility is compliant with the POSIX.1-2008 specification.
-
-The flags A a D d I i L l N n P p q S s T t w X x y are extensions to that specification.
-## HISTORY
-A diff command appeared in AT&T Version 6 UNIX.
-
-The diff implementation used in FreeBSD was GNU diff until FreeBSD 11.4. This was replaced in FreeBSD 12.0 by a BSD-licensed implementation written by Todd Miller. Some GNUisms were lost in the process.
-
-libdiff was imported from the Game of Trees version control system and default algorithm was changed to Myers for FreeBSD 15 .
-*/
-int
-main(int argc, char **argv)
-{
- const char *errstr = NULL;
- char *ep, **oargv;
- long l;
- int ch, dflags, lastch, gotstdin, prevoptind, newarg;
-
- oargv = argv;
- gotstdin = 0;
- dflags = 0;
- lastch = '\0';
- prevoptind = 1;
- newarg = 1;
- diff_context = 3;
- diff_format = D_UNSET;
- diff_algorithm = D_DIFFMYERS;
- diff_algorithm_set = false;
-#define FORMAT_MISMATCHED(type) \
- (diff_format != D_UNSET && diff_format != (type))
- while ((ch = getopt_long(argc, argv, OPTIONS, longopts, NULL)) != -1) {
- switch (ch) {
- case '0': case '1': case '2': case '3': case '4':
- case '5': case '6': case '7': case '8': case '9':
- if (newarg)
- usage(); /* disallow -[0-9]+ */
- else if (lastch == 'c' || lastch == 'u')
- diff_context = 0;
- else if (!isdigit(lastch) || diff_context > INT_MAX / 10)
- usage();
- diff_context = (diff_context * 10) + (ch - '0');
- break;
- case 'A':
- diff_algorithm = D_DIFFNONE;
- for (struct algorithm *a = algorithms; a->name;a++) {
- if(strcasecmp(optarg, a->name) == 0) {
- diff_algorithm = a->id;
- diff_algorithm_set = true;
- break;
- }
- }
-
- if (diff_algorithm == D_DIFFNONE) {
- printf("unknown algorithm: %s\n", optarg);
- usage();
- }
- break;
- case 'a':
- dflags |= D_FORCEASCII;
- break;
- case 'b':
- dflags |= D_FOLDBLANKS;
- break;
- case 'C':
- case 'c':
- if (FORMAT_MISMATCHED(D_CONTEXT))
- conflicting_format();
- cflag = true;
- diff_format = D_CONTEXT;
- if (optarg != NULL) {
- l = strtol(optarg, &ep, 10);
- if (*ep != '\0' || l < 0 || l >= INT_MAX)
- usage();
- diff_context = (int)l;
- }
- break;
- case 'd':
- dflags |= D_MINIMAL;
- break;
- case 'D':
- if (FORMAT_MISMATCHED(D_IFDEF))
- conflicting_format();
- diff_format = D_IFDEF;
- ifdefname = optarg;
- break;
- case 'e':
- if (FORMAT_MISMATCHED(D_EDIT))
- conflicting_format();
- diff_format = D_EDIT;
- break;
- case 'f':
- if (FORMAT_MISMATCHED(D_REVERSE))
- conflicting_format();
- diff_format = D_REVERSE;
- break;
- case 'H':
- /* ignore but needed for compatibility with GNU diff */
- break;
- case 'h':
- /* silently ignore for backwards compatibility */
- break;
- case 'B':
- dflags |= D_SKIPBLANKLINES;
- break;
- case 'F':
- if (dflags & D_PROTOTYPE)
- conflicting_format();
- dflags |= D_MATCHLAST;
- most_recent_pat = xstrdup(optarg);
- break;
- case 'I':
- push_ignore_pats(optarg);
- break;
- case 'i':
- dflags |= D_IGNORECASE;
- break;
- case 'L':
- if (label[0] == NULL)
- label[0] = optarg;
- else if (label[1] == NULL)
- label[1] = optarg;
- else
- usage();
- break;
- case 'l':
- lflag = true;
- break;
- case 'N':
- Nflag = true;
- break;
- case 'n':
- if (FORMAT_MISMATCHED(D_NREVERSE))
- conflicting_format();
- diff_format = D_NREVERSE;
- break;
- case 'p':
- if (dflags & D_MATCHLAST)
- conflicting_format();
- dflags |= D_PROTOTYPE;
- break;
- case 'P':
- Pflag = true;
- break;
- case 'r':
- rflag = true;
- break;
- case 'q':
- if (FORMAT_MISMATCHED(D_BRIEF))
- conflicting_format();
- diff_format = D_BRIEF;
- break;
- case 'S':
- start = optarg;
- break;
- case 's':
- sflag = true;
- break;
- case 'T':
- Tflag = true;
- break;
- case 't':
- dflags |= D_EXPANDTABS;
- break;
- case 'U':
- case 'u':
- if (FORMAT_MISMATCHED(D_UNIFIED))
- conflicting_format();
- diff_format = D_UNIFIED;
- if (optarg != NULL) {
- l = strtol(optarg, &ep, 10);
- if (*ep != '\0' || l < 0 || l >= INT_MAX)
- usage();
- diff_context = (int)l;
- }
- break;
- case 'w':
- dflags |= D_IGNOREBLANKS;
- break;
- case 'W':
- width = (int) strtonum(optarg, 1, INT_MAX, &errstr);
- if (errstr) {
- warnx("Invalid argument for width");
- usage();
- }
- break;
- case 'X':
- read_excludes_file(optarg);
- break;
- case 'x':
- push_excludes(optarg);
- break;
- case 'y':
- if (FORMAT_MISMATCHED(D_SIDEBYSIDE))
- conflicting_format();
- diff_format = D_SIDEBYSIDE;
- break;
- case OPT_CHANGED_GROUP_FORMAT:
- if (FORMAT_MISMATCHED(D_GFORMAT))
- conflicting_format();
- diff_format = D_GFORMAT;
- group_format = optarg;
- break;
- case OPT_HELP:
- help = true;
- usage();
- break;
- case OPT_HORIZON_LINES:
- break; /* XXX TODO for compatibility with GNU diff3 */
- case OPT_IGN_FN_CASE:
- ignore_file_case = true;
- break;
- case OPT_NO_IGN_FN_CASE:
- ignore_file_case = false;
- break;
- case OPT_NORMAL:
- if (FORMAT_MISMATCHED(D_NORMAL))
- conflicting_format();
- diff_format = D_NORMAL;
- break;
- case OPT_TSIZE:
- tabsize = (int) strtonum(optarg, 1, INT_MAX, &errstr);
- if (errstr) {
- warnx("Invalid argument for tabsize");
- usage();
- }
- break;
- case OPT_STRIPCR:
- dflags |= D_STRIPCR;
- break;
- case OPT_SUPPRESS_COMMON:
- suppress_common = 1;
- break;
- case OPT_COLOR:
- if (optarg == NULL || strncmp(optarg, "auto", 4) == 0)
- colorflag = COLORFLAG_AUTO;
- else if (strncmp(optarg, "always", 6) == 0)
- colorflag = COLORFLAG_ALWAYS;
- else if (strncmp(optarg, "never", 5) == 0)
- colorflag = COLORFLAG_NEVER;
- else
- errx(2, "unsupported --color value '%s' (must be always, auto, or never)",
- optarg);
- break;
- case OPT_NO_DEREFERENCE:
- noderef = true;
- break;
- case OPT_VERSION:
- printf("%s\n", diff_version);
- exit(0);
- default:
- usage();
- break;
- }
- lastch = ch;
- newarg = optind != prevoptind;
- prevoptind = optind;
- }
- if (diff_format == D_UNSET && (dflags & D_PROTOTYPE) != 0)
- diff_format = D_CONTEXT;
- if (diff_format == D_UNSET)
- diff_format = D_NORMAL;
- argc -= optind;
- argv += optind;
-
- if (do_color()) {
- char *p;
- const char *env;
-
- color = true;
- add_code = "32";
- del_code = "31";
- env = getenv("DIFFCOLORS");
- if (env != NULL && *env != '\0' && (p = strdup(env))) {
- add_code = p;
- strsep(&p, ":");
- if (p != NULL)
- del_code = p;
- }
- }
-
-#ifdef __OpenBSD__
- if (pledge("stdio rpath tmppath", NULL) == -1)
- err(2, "pledge");
-#endif
-
- /*
- * Do sanity checks, fill in stb1 and stb2 and call the appropriate
- * driver routine. Both drivers use the contents of stb1 and stb2.
- */
- if (argc != 2)
- usage();
- checked_regcomp(ignore_pats, &ignore_re);
- checked_regcomp(most_recent_pat, &most_recent_re);
- if (strcmp(argv[0], "-") == 0) {
- fstat(STDIN_FILENO, &stb1);
- gotstdin = 1;
- } else if (stat(argv[0], &stb1) != 0) {
- if (!Nflag || errno != ENOENT)
- err(2, "%s", argv[0]);
- dflags |= D_EMPTY1;
- memset(&stb1, 0, sizeof(struct stat));
- }
-
- if (strcmp(argv[1], "-") == 0) {
- fstat(STDIN_FILENO, &stb2);
- gotstdin = 1;
- } else if (stat(argv[1], &stb2) != 0) {
- if (!Nflag || errno != ENOENT)
- err(2, "%s", argv[1]);
- dflags |= D_EMPTY2;
- memset(&stb2, 0, sizeof(stb2));
- stb2.st_mode = stb1.st_mode;
- }
-
- if (dflags & D_EMPTY1 && dflags & D_EMPTY2){
- warn("%s", argv[0]);
- warn("%s", argv[1]);
- exit(2);
- }
-
- if (stb1.st_mode == 0)
- stb1.st_mode = stb2.st_mode;
-
- if (gotstdin && (S_ISDIR(stb1.st_mode) || S_ISDIR(stb2.st_mode)))
- errx(2, "can't compare - to a directory");
- set_argstr(oargv, argv);
- if (S_ISDIR(stb1.st_mode) && S_ISDIR(stb2.st_mode)) {
- if (diff_format == D_IFDEF)
- errx(2, "-D option not supported with directories");
- diffdir(argv[0], argv[1], dflags);
- } else {
- if (S_ISDIR(stb1.st_mode)) {
- argv[0] = splice(argv[0], argv[1]);
- if (stat(argv[0], &stb1) == -1)
- err(2, "%s", argv[0]);
- }
- if (S_ISDIR(stb2.st_mode)) {
- argv[1] = splice(argv[1], argv[0]);
- if (stat(argv[1], &stb2) == -1)
- err(2, "%s", argv[1]);
- }
- print_status(diffreg(argv[0], argv[1], dflags, 1), argv[0],
- argv[1], "");
- }
- if (fflush(stdout) != 0)
- err(2, "stdout");
- exit(status);
-}
-
-static void
-checked_regcomp(char const *pattern, regex_t *comp)
-{
- char buf[BUFSIZ];
- int error;
-
- if (pattern == NULL)
- return;
-
- error = regcomp(comp, pattern, REG_NEWLINE | REG_EXTENDED);
- if (error != 0) {
- regerror(error, comp, buf, sizeof(buf));
- if (*pattern != '\0')
- errx(2, "%s: %s", pattern, buf);
- else
- errx(2, "%s", buf);
- }
-}
-
-static void
-set_argstr(char **av, char **ave)
-{
- size_t argsize;
- char **ap;
-
- argsize = strlen("diff") + 1;
- for (ap = av + 1; ap < ave; ap++) {
- if (strcmp(*ap, "--") != 0)
- argsize += 1 + strlen(*ap);
- }
- diffargs = xmalloc(argsize);
- strlcpy(diffargs, "diff", argsize);
- for (ap = av + 1; ap < ave; ap++) {
- if (strcmp(*ap, "--") != 0) {
- strlcat(diffargs, " ", argsize);
- strlcat(diffargs, *ap, argsize);
- }
- }
-}
-
-/*
- * Read in an excludes file and push each line.
- */
-static void
-read_excludes_file(char *file)
-{
- FILE *fp;
- char *pattern = NULL;
- size_t blen = 0;
- ssize_t len;
-
- if (strcmp(file, "-") == 0)
- fp = stdin;
- else if ((fp = fopen(file, "r")) == NULL)
- err(2, "%s", file);
- while ((len = getline(&pattern, &blen, fp)) >= 0) {
- if ((len > 0) && (pattern[len - 1] == '\n'))
- pattern[len - 1] = '\0';
- push_excludes(pattern);
- /* we allocate a new string per line */
- pattern = NULL;
- blen = 0;
- }
- free(pattern);
- if (strcmp(file, "-") != 0)
- fclose(fp);
-}
-
-/*
- * Push a pattern onto the excludes list.
- */
-static void
-push_excludes(char *pattern)
-{
- struct excludes *entry;
-
- entry = xmalloc(sizeof(*entry));
- entry->pattern = pattern;
- entry->next = excludes_list;
- excludes_list = entry;
-}
-
-static void
-push_ignore_pats(char *pattern)
-{
- size_t len;
-
- if (ignore_pats == NULL)
- ignore_pats = xstrdup(pattern);
- else {
- /* old + "|" + new + NUL */
- len = strlen(ignore_pats) + strlen(pattern) + 2;
- ignore_pats = xreallocarray(ignore_pats, 1, len);
- strlcat(ignore_pats, "|", len);
- strlcat(ignore_pats, pattern, len);
- }
-}
-
-void
-print_status(int val, char *path1, char *path2, const char *entry)
-{
- if (label[0] != NULL)
- path1 = label[0];
- if (label[1] != NULL)
- path2 = label[1];
-
- switch (val) {
- case D_BINARY:
- printf("Binary files %s%s and %s%s differ\n",
- path1, entry, path2, entry);
- break;
- case D_DIFFER:
- if (diff_format == D_BRIEF)
- printf("Files %s%s and %s%s differ\n",
- path1, entry, path2, entry);
- break;
- case D_SAME:
- if (sflag)
- printf("Files %s%s and %s%s are identical\n",
- path1, entry, path2, entry);
- break;
- case D_MISMATCH1:
- printf("File %s%s is a directory while file %s%s is a regular file\n",
- path1, entry, path2, entry);
- break;
- case D_MISMATCH2:
- printf("File %s%s is a regular file while file %s%s is a directory\n",
- path1, entry, path2, entry);
- break;
- case D_SKIPPED1:
- printf("File %s%s is not a regular file or directory and was skipped\n",
- path1, entry);
- break;
- case D_SKIPPED2:
- printf("File %s%s is not a regular file or directory and was skipped\n",
- path2, entry);
- break;
- case D_ERROR:
- break;
- }
-}
-
-static void
-usage(void)
-{
- (void)fprintf(help ? stdout : stderr,
- "usage: diff [-aBbdilpTtw] [-c | -e | -f | -n | -q | -u] [--ignore-case]\n"
- " [--no-ignore-case] [--normal] [--strip-trailing-cr] [--tabsize]\n"
- " [-I pattern] [-F pattern] [-L label] file1 file2\n"
- " diff [-aBbdilpTtw] [-I pattern] [-L label] [--ignore-case]\n"
- " [--no-ignore-case] [--normal] [--strip-trailing-cr] [--tabsize]\n"
- " [-F pattern] -C number file1 file2\n"
- " diff [-aBbdiltw] [-I pattern] [--ignore-case] [--no-ignore-case]\n"
- " [--normal] [--strip-trailing-cr] [--tabsize] -D string file1 file2\n"
- " diff [-aBbdilpTtw] [-I pattern] [-L label] [--ignore-case]\n"
- " [--no-ignore-case] [--normal] [--tabsize] [--strip-trailing-cr]\n"
- " [-F pattern] -U number file1 file2\n"
- " diff [-aBbdilNPprsTtw] [-c | -e | -f | -n | -q | -u] [--ignore-case]\n"
- " [--no-ignore-case] [--normal] [--tabsize] [-I pattern] [-L label]\n"
- " [-F pattern] [-S name] [-X file] [-x pattern] dir1 dir2\n"
- " diff [-aBbditwW] [--expand-tabs] [--ignore-all-space]\n"
- " [--ignore-blank-lines] [--ignore-case] [--minimal]\n"
- " [--no-ignore-file-name-case] [--strip-trailing-cr]\n"
- " [--suppress-common-lines] [--tabsize] [--text] [--width]\n"
- " -y | --side-by-side file1 file2\n"
- " diff [--help] [--version]\n");
-
- if (help)
- exit(0);
- else
- exit(2);
-}
-
-static void
-conflicting_format(void)
-{
-
- fprintf(stderr, "error: conflicting output format options.\n");
- usage();
-}
-
-static bool
-do_color(void)
-{
- const char *p, *p2;
-
- switch (colorflag) {
- case COLORFLAG_AUTO:
- p = getenv("CLICOLOR");
- p2 = getenv("COLORTERM");
- if ((p != NULL && *p != '\0') || (p2 != NULL && *p2 != '\0'))
- return isatty(STDOUT_FILENO);
- break;
- case COLORFLAG_ALWAYS:
- return (true);
- case COLORFLAG_NEVER:
- return (false);
- }
-
- return (false);
-}
-
-static char *
-splice(char *dir, char *path)
-{
- char *tail, *buf;
- size_t dirlen;
-
- dirlen = strlen(dir);
- while (dirlen != 0 && dir[dirlen - 1] == '/')
- dirlen--;
- if ((tail = strrchr(path, '/')) == NULL)
- tail = path;
- else
- tail++;
- xasprintf(&buf, "%.*s/%s", (int)dirlen, dir, tail);
- return (buf);
-}
diff --git a/cmd/posix/diff/diff.h b/cmd/posix/diff/diff.h
@@ -1,137 +0,0 @@
-/* $OpenBSD: diff.h,v 1.34 2020/11/01 18:16:08 jcs Exp $ */
-
-/*-
- * Copyright (c) 1991, 1993
- * 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/types.h>
-#include <sys/stat.h>
-
-#include <stdbool.h>
-#include <regex.h>
-
-/*
- * Output format options
- */
-#define D_NORMAL 0 /* Normal output */
-#define D_EDIT -1 /* Editor script out */
-#define D_REVERSE 1 /* Reverse editor script */
-#define D_CONTEXT 2 /* Diff with context */
-#define D_UNIFIED 3 /* Unified context diff */
-#define D_IFDEF 4 /* Diff with merged #ifdef's */
-#define D_NREVERSE 5 /* Reverse ed script with numbered
- lines and no trailing . */
-#define D_BRIEF 6 /* Say if the files differ */
-#define D_GFORMAT 7 /* Diff with defined changed group format */
-#define D_SIDEBYSIDE 8 /* Side by side */
-
-#define D_UNSET -2
-
-/*
- * Algorithms
- */
-
-#define D_DIFFNONE 0
-#define D_DIFFSTONE 1 /* Stone or 'old diff' algorithm */
-#define D_DIFFMYERS 2 /* Myers diff algorithm */
-#define D_DIFFPATIENCE 3 /* Patience diff algorithm */
-
-/*
- * Output flags
- */
-#define D_HEADER 0x001 /* Print a header/footer between files */
-#define D_EMPTY1 0x002 /* Treat first file as empty (/dev/null) */
-#define D_EMPTY2 0x004 /* Treat second file as empty (/dev/null) */
-
-/*
- * Command line flags
- */
-#define D_FORCEASCII 0x008 /* Treat file as ascii regardless of content */
-#define D_FOLDBLANKS 0x010 /* Treat all white space as equal */
-#define D_MINIMAL 0x020 /* Make diff as small as possible */
-#define D_IGNORECASE 0x040 /* Case-insensitive matching */
-#define D_PROTOTYPE 0x080 /* Display C function prototype */
-#define D_EXPANDTABS 0x100 /* Expand tabs to spaces */
-#define D_IGNOREBLANKS 0x200 /* Ignore white space changes */
-#define D_STRIPCR 0x400 /* Strip trailing cr */
-#define D_SKIPBLANKLINES 0x800 /* Skip blank lines */
-#define D_MATCHLAST 0x1000 /* Display last line matching provided regex */
-
-/* Features supported by new algorithms */
-#define D_NEWALGO_FLAGS (D_FORCEASCII | D_PROTOTYPE | D_IGNOREBLANKS)
-
-/*
- * Status values for print_status() and diffreg() return values
- */
-#define D_SAME 0 /* Files are the same */
-#define D_DIFFER 1 /* Files are different */
-#define D_BINARY 2 /* Binary files are different */
-#define D_MISMATCH1 3 /* path1 was a dir, path2 a file */
-#define D_MISMATCH2 4 /* path1 was a file, path2 a dir */
-#define D_SKIPPED1 5 /* path1 was a special file */
-#define D_SKIPPED2 6 /* path2 was a special file */
-#define D_ERROR 7 /* A file access error occurred */
-
-/*
- * Color options
- */
-#define COLORFLAG_NEVER 0
-#define COLORFLAG_AUTO 1
-#define COLORFLAG_ALWAYS 2
-
-struct excludes {
- char *pattern;
- struct excludes *next;
-};
-
-extern bool lflag, Nflag, Pflag, rflag, sflag, Tflag, cflag;
-extern bool ignore_file_case, suppress_common, color, noderef, algorithm_set;
-extern int diff_format, diff_context, diff_algorithm, status;
-extern bool diff_algorithm_set;
-extern int tabsize, width;
-extern char *start, *ifdefname, *diffargs, *label[2];
-extern char *ignore_pats, *most_recent_pat;
-extern char *group_format;
-extern const char *add_code, *del_code;
-extern struct stat stb1, stb2;
-extern struct excludes *excludes_list;
-extern regex_t ignore_re, most_recent_re;
-
-int diffreg(char *, char *, int, int);
-int diffreg_new(char *, char *, int, int);
-bool can_libdiff(int);
-void diffdir(char *, char *, int);
-void print_status(int, char *, char *, const char *);
-
-#ifndef MIN
-#define MIN(X, Y) (((X) < (Y)) ? (X) : (Y))
-#endif
-
-#ifndef MAX
-#define MAX(X, Y) (((X) > (Y)) ? (X) : (Y))
-#endif
diff --git a/cmd/posix/diff/diffdir.c b/cmd/posix/diff/diffdir.c
@@ -1,377 +0,0 @@
-/* $OpenBSD: diffdir.c,v 1.45 2015/10/05 20:15:00 millert Exp $ */
-
-/*
- * Copyright (c) 2003, 2010 Todd C. Miller <Todd.Miller@courtesan.com>
- *
- * Permission to use, copy, modify, and distribute this software for any
- * purpose with or without fee is hereby granted, provided that the above
- * copyright notice and this permission notice appear in all copies.
- *
- * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
- * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
- * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
- * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
- * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
- * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
- *
- * Sponsored in part by the Defense Advanced Research Projects
- * Agency (DARPA) and Air Force Research Laboratory, Air Force
- * Materiel Command, USAF, under agreement number F39502-99-1-0512.
- */
-
-#include <sys/cdefs.h>
-#include <sys/stat.h>
-
-#include <dirent.h>
-#include <err.h>
-#include <errno.h>
-#include <fcntl.h>
-#include <fnmatch.h>
-#include <limits.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <unistd.h>
-
-#include "util.h"
-
-#include "diff.h"
-
-static int selectfile(const struct dirent *);
-static void diffit(struct dirent *, char *, size_t, struct dirent *,
- char *, size_t, int);
-static void print_only(const char *, size_t, const char *);
-
-#define d_status d_type /* we need to store status for -l */
-
-#if 0
-struct inode {
- dev_t dev;
- ino_t ino;
- RB_ENTRY(inode) entry;
-};
-
-static int
-inodecmp(struct inode *a, struct inode *b)
-{
- return (a->dev < b->dev ? -1 : a->dev > b->dev ? 1 :
- a->ino < b->ino ? -1 : a->ino > b->ino ? 1 : 0);
-}
-
-RB_HEAD(inodetree, inode);
-static struct inodetree v1 = RB_INITIALIZER(&v1);
-static struct inodetree v2 = RB_INITIALIZER(&v2);
-RB_GENERATE_STATIC(inodetree, inode, entry, inodecmp);
-
-static int
-vscandir(struct inodetree *tree, const char *path, struct dirent ***dirp,
- int (*selectf)(const struct dirent *),
- int (*comparf)(const struct dirent **, const struct dirent **))
-{
- struct stat sb;
- struct inode *ino = NULL;
- int fd = -1, ret, serrno;
-
- if ((fd = open(path, O_DIRECTORY | O_RDONLY)) < 0 ||
- (ino = calloc(1, sizeof(*ino))) == NULL ||
- fstat(fd, &sb) != 0)
- goto fail;
- ino->dev = sb.st_dev;
- ino->ino = sb.st_ino;
- if (RB_FIND(inodetree, tree, ino)) {
- free(ino);
- close(fd);
- warnx("%s: Directory loop detected", path);
- *dirp = NULL;
- return (0);
- }
- if ((ret = fdscandir(fd, dirp, selectf, comparf)) < 0)
- goto fail;
- RB_INSERT(inodetree, tree, ino);
- close(fd);
- return (ret);
-fail:
- serrno = errno;
- if (ino != NULL)
- free(ino);
- if (fd >= 0)
- close(fd);
- errno = serrno;
- return (-1);
-}
-#endif
-
-/*
- * Diff directory traversal. Will be called recursively if -r was specified.
- */
-void
-diffdir(char *p1, char *p2, int flags)
-{
- struct dirent *dent1, **dp1, **edp1, **dirp1 = NULL;
- struct dirent *dent2, **dp2, **edp2, **dirp2 = NULL;
- size_t dirlen1, dirlen2;
- char path1[PATH_MAX], path2[PATH_MAX];
- int pos;
-
- edp1 = edp2 = NULL;
-
- dirlen1 = strlcpy(path1, *p1 ? p1 : ".", sizeof(path1));
- if (dirlen1 >= sizeof(path1) - 1) {
- errno = ENAMETOOLONG;
- warn("%s", p1);
- status |= 2;
- return;
- }
- if (path1[dirlen1 - 1] != '/') {
- path1[dirlen1++] = '/';
- path1[dirlen1] = '\0';
- }
- dirlen2 = strlcpy(path2, *p2 ? p2 : ".", sizeof(path2));
- if (dirlen2 >= sizeof(path2) - 1) {
- errno = ENAMETOOLONG;
- warn("%s", p2);
- status |= 2;
- return;
- }
- if (path2[dirlen2 - 1] != '/') {
- path2[dirlen2++] = '/';
- path2[dirlen2] = '\0';
- }
-
- /*
- * Get a list of entries in each directory, skipping "excluded" files
- * and sorting alphabetically.
- */
- pos = scandir(path1, &dirp1, selectfile, alphasort);
- if (pos == -1) {
- if (errno == ENOENT && (Nflag || Pflag)) {
- pos = 0;
- } else {
- warn("%s", path1);
- goto closem;
- }
- }
- dp1 = dirp1;
- edp1 = dirp1 + pos;
-
- pos = scandir(path2, &dirp2, selectfile, alphasort);
- if (pos == -1) {
- if (errno == ENOENT && Nflag) {
- pos = 0;
- } else {
- warn("%s", path2);
- goto closem;
- }
- }
- dp2 = dirp2;
- edp2 = dirp2 + pos;
-
- /*
- * If we were given a starting point, find it.
- */
- if (start != NULL) {
- while (dp1 != edp1 && strcmp((*dp1)->d_name, start) < 0)
- dp1++;
- while (dp2 != edp2 && strcmp((*dp2)->d_name, start) < 0)
- dp2++;
- }
-
- /*
- * Iterate through the two directory lists, diffing as we go.
- */
- while (dp1 != edp1 || dp2 != edp2) {
- dent1 = dp1 != edp1 ? *dp1 : NULL;
- dent2 = dp2 != edp2 ? *dp2 : NULL;
-
- pos = dent1 == NULL ? 1 : dent2 == NULL ? -1 :
- ignore_file_case ? strcasecmp(dent1->d_name, dent2->d_name) :
- strcmp(dent1->d_name, dent2->d_name) ;
- if (pos == 0) {
- /* file exists in both dirs, diff it */
- diffit(dent1, path1, dirlen1, dent2, path2, dirlen2, flags);
- dp1++;
- dp2++;
- } else if (pos < 0) {
- /* file only in first dir, only diff if -N */
- if (Nflag) {
- diffit(dent1, path1, dirlen1, dent2, path2,
- dirlen2, flags);
- } else {
- print_only(path1, dirlen1, dent1->d_name);
- status |= 1;
- }
- dp1++;
- } else {
- /* file only in second dir, only diff if -N or -P */
- if (Nflag || Pflag)
- diffit(dent2, path1, dirlen1, dent1, path2,
- dirlen2, flags);
- else {
- print_only(path2, dirlen2, dent2->d_name);
- status |= 1;
- }
- dp2++;
- }
- }
-
-closem:
- if (dirp1 != NULL) {
- for (dp1 = dirp1; dp1 < edp1; dp1++)
- free(*dp1);
- free(dirp1);
- }
- if (dirp2 != NULL) {
- for (dp2 = dirp2; dp2 < edp2; dp2++)
- free(*dp2);
- free(dirp2);
- }
-}
-
-/*
- * Do the actual diff by calling either diffreg() or diffdir().
- */
-static void
-diffit(struct dirent *dp, char *path1, size_t plen1, struct dirent *dp2,
- char *path2, size_t plen2, int flags)
-{
- flags |= D_HEADER;
- strlcpy(path1 + plen1, dp->d_name, PATH_MAX - plen1);
-
- /*
- * If we are ignoring file case, use dent2s name here if both names are
- * the same apart from case.
- */
- if (ignore_file_case && strcasecmp(dp->d_name, dp2->d_name) == 0)
- strlcpy(path2 + plen2, dp2->d_name, PATH_MAX - plen2);
- else
- strlcpy(path2 + plen2, dp->d_name, PATH_MAX - plen2);
-
- if (noderef) {
- if (lstat(path1, &stb1) != 0) {
- if (!(Nflag || Pflag) || errno != ENOENT) {
- warn("%s", path1);
- return;
- }
- flags |= D_EMPTY1;
- memset(&stb1, 0, sizeof(stb1));
- }
-
- if (lstat(path2, &stb2) != 0) {
- if (!Nflag || errno != ENOENT) {
- warn("%s", path2);
- return;
- }
- flags |= D_EMPTY2;
- memset(&stb2, 0, sizeof(stb2));
- stb2.st_mode = stb1.st_mode;
- }
- if (stb1.st_mode == 0)
- stb1.st_mode = stb2.st_mode;
- if (S_ISLNK(stb1.st_mode) || S_ISLNK(stb2.st_mode)) {
- if (S_ISLNK(stb1.st_mode) && S_ISLNK(stb2.st_mode)) {
- char buf1[PATH_MAX];
- char buf2[PATH_MAX];
- ssize_t len1 = 0;
- ssize_t len2 = 0;
-
- len1 = readlink(path1, buf1, sizeof(buf1));
- len2 = readlink(path2, buf2, sizeof(buf2));
-
- if (len1 < 0 || len2 < 0) {
- perror("reading links");
- return;
- }
- buf1[len1] = '\0';
- buf2[len2] = '\0';
-
- if (len1 != len2 || strncmp(buf1, buf2, len1) != 0) {
- printf("Symbolic links %s and %s differ\n",
- path1, path2);
- status |= 1;
- }
-
- return;
- }
-
- printf("File %s is a %s while file %s is a %s\n",
- path1, S_ISLNK(stb1.st_mode) ? "symbolic link" :
- (S_ISDIR(stb1.st_mode) ? "directory" :
- (S_ISREG(stb1.st_mode) ? "file" : "error")),
- path2, S_ISLNK(stb2.st_mode) ? "symbolic link" :
- (S_ISDIR(stb2.st_mode) ? "directory" :
- (S_ISREG(stb2.st_mode) ? "file" : "error")));
- status |= 1;
- return;
- }
- } else {
- if (stat(path1, &stb1) != 0) {
- if (!(Nflag || Pflag) || errno != ENOENT) {
- warn("%s", path1);
- return;
- }
- flags |= D_EMPTY1;
- memset(&stb1, 0, sizeof(stb1));
- }
-
- if (stat(path2, &stb2) != 0) {
- if (!Nflag || errno != ENOENT) {
- warn("%s", path2);
- return;
- }
- flags |= D_EMPTY2;
- memset(&stb2, 0, sizeof(stb2));
- stb2.st_mode = stb1.st_mode;
- }
- if (stb1.st_mode == 0)
- stb1.st_mode = stb2.st_mode;
- }
- if (S_ISDIR(stb1.st_mode) && S_ISDIR(stb2.st_mode)) {
- if (rflag)
- diffdir(path1, path2, flags);
- else
- printf("Common subdirectories: %s and %s\n",
- path1, path2);
- return;
- }
- if (!S_ISREG(stb1.st_mode) && !S_ISDIR(stb1.st_mode))
- dp->d_status = D_SKIPPED1;
- else if (!S_ISREG(stb2.st_mode) && !S_ISDIR(stb2.st_mode))
- dp->d_status = D_SKIPPED2;
- else
- dp->d_status = diffreg(path1, path2, flags, 0);
- print_status(dp->d_status, path1, path2, "");
-}
-
-/*
- * Returns 1 if the directory entry should be included in the
- * diff, else 0. Checks the excludes list.
- */
-static int
-selectfile(const struct dirent *dp)
-{
- struct excludes *excl;
-
- if (dp->d_fileno == 0)
- return (0);
-
- /* always skip "." and ".." */
- if (dp->d_name[0] == '.' && (dp->d_name[1] == '\0' ||
- (dp->d_name[1] == '.' && dp->d_name[2] == '\0')))
- return (0);
-
- /* check excludes list */
- for (excl = excludes_list; excl != NULL; excl = excl->next)
- if (fnmatch(excl->pattern, dp->d_name, FNM_PATHNAME) == 0)
- return (0);
-
- return (1);
-}
-
-void
-print_only(const char *path, size_t dirlen, const char *entry)
-{
- if (dirlen > 1)
- dirlen--;
- printf("Only in %.*s: %s\n", (int)dirlen, path, entry);
-}
diff --git a/cmd/posix/diff/diffreg.c b/cmd/posix/diff/diffreg.c
@@ -1,1697 +0,0 @@
-/* $OpenBSD: diffreg.c,v 1.93 2019/06/28 13:35:00 deraadt Exp $ */
-
-/*-
- * SPDX-License-Identifier: BSD-4-Clause
- *
- * Copyright (C) Caldera International Inc. 2001-2002.
- * 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 and documentation 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. All advertising materials mentioning features or use of this software
- * must display the following acknowledgement:
- * This product includes software developed or owned by Caldera
- * International, Inc.
- * 4. Neither the name of Caldera International, Inc. nor the names of other
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * USE OF THE SOFTWARE PROVIDED FOR UNDER THIS LICENSE BY CALDERA
- * INTERNATIONAL, INC. 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 CALDERA INTERNATIONAL, INC. 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.
- */
-/*-
- * Copyright (c) 1991, 1993
- * 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/stat.h>
-#include <sys/param.h>
-
-#include <ctype.h>
-#include <err.h>
-#include <errno.h>
-#include <fcntl.h>
-#include <limits.h>
-#include <math.h>
-#include <paths.h>
-#include <regex.h>
-#include <stdbool.h>
-#include <stddef.h>
-#include <stdint.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <time.h>
-#include <unistd.h>
-#include <limits.h>
-
-#include "util.h"
-
-#include "pr.h"
-#include "diff.h"
-#include "xmalloc.h"
-
-#ifndef roundup
-#define roundup(x, y) ((((x) + ((y) - 1)) / (y)) * (y))
-#endif
-
-/*
- * diff - compare two files.
- */
-
-/*
- * Uses an algorithm due to Harold Stone, which finds a pair of longest
- * identical subsequences in the two files.
- *
- * The major goal is to generate the match vector J. J[i] is the index of
- * the line in file1 corresponding to line i file0. J[i] = 0 if there is no
- * such line in file1.
- *
- * Lines are hashed so as to work in core. All potential matches are
- * located by sorting the lines of each file on the hash (called
- * ``value''). In particular, this collects the equivalence classes in
- * file1 together. Subroutine equiv replaces the value of each line in
- * file0 by the index of the first element of its matching equivalence in
- * (the reordered) file1. To save space equiv squeezes file1 into a single
- * array member in which the equivalence classes are simply concatenated,
- * except that their first members are flagged by changing sign.
- *
- * Next the indices that point into member are unsorted into array class
- * according to the original order of file0.
- *
- * The cleverness lies in routine stone. This marches through the lines of
- * file0, developing a vector klist of "k-candidates". At step i
- * a k-candidate is a matched pair of lines x,y (x in file0 y in file1)
- * such that there is a common subsequence of length k between the first
- * i lines of file0 and the first y lines of file1, but there is no such
- * subsequence for any smaller y. x is the earliest possible mate to y that
- * occurs in such a subsequence.
- *
- * Whenever any of the members of the equivalence class of lines in file1
- * matable to a line in file0 has serial number less than the y of some
- * k-candidate, that k-candidate with the smallest such y is replaced. The
- * new k-candidate is chained (via pred) to the current k-1 candidate so
- * that the actual subsequence can be recovered. When a member has serial
- * number greater that the y of all k-candidates, the klist is extended. At
- * the end, the longest subsequence is pulled out and placed in the array J
- * by unravel.
- *
- * With J in hand, the matches there recorded are check'ed against reality
- * to assure that no spurious matches have crept in due to hashing. If they
- * have, they are broken, and "jackpot" is recorded -- a harmless matter
- * except that a true match for a spuriously mated line may now be
- * unnecessarily reported as a change.
- *
- * Much of the complexity of the program comes simply from trying to
- * minimize core utilization and maximize the range of doable problems by
- * dynamically allocating what is needed and reusing what is not. The core
- * requirements for problems larger than somewhat are (in words)
- * 2*length(file0) + length(file1) + 3*(number of k-candidates installed),
- * typically about 6n words for files of length n.
- */
-
-struct cand {
- int x;
- int y;
- int pred;
-};
-
-static struct line {
- int serial;
- int value;
-} *file[2];
-
-/*
- * The following struct is used to record change information when
- * doing a "context" or "unified" diff. (see routine "change" to
- * understand the highly mnemonic field names)
- */
-struct context_vec {
- int a; /* start line in old file */
- int b; /* end line in old file */
- int c; /* start line in new file */
- int d; /* end line in new file */
-};
-
-enum readhash { RH_BINARY, RH_OK, RH_EOF };
-
-static FILE *opentemp(const char *);
-static void output(char *, FILE *, char *, FILE *, int);
-static void check(FILE *, FILE *, int);
-static void range(int, int, const char *);
-static void uni_range(int, int);
-static void dump_context_vec(FILE *, FILE *, int);
-static void dump_unified_vec(FILE *, FILE *, int);
-static bool prepare(int, FILE *, size_t, int);
-static void prune(void);
-static void equiv(struct line *, int, struct line *, int, int *);
-static void unravel(int);
-static void unsort(struct line *, int, int *);
-static void change(char *, FILE *, char *, FILE *, int, int, int, int, int *);
-static void sort(struct line *, int);
-static void print_header(const char *, const char *);
-static void print_space(int, int, int);
-static bool ignoreline_pattern(char *);
-static bool ignoreline(char *, bool);
-static int asciifile(FILE *);
-static int fetch(long *, int, int, FILE *, int, int, int);
-static int newcand(int, int, int);
-static int search(int *, int, int);
-static int skipline(FILE *);
-static int stone(int *, int, int *, int *, int);
-static enum readhash readhash(FILE *, int, unsigned *);
-static int files_differ(FILE *, FILE *, int);
-static char *match_function(const long *, int, FILE *);
-static char *preadline(int, size_t, off_t);
-
-static int *J; /* will be overlaid on class */
-static int *class; /* will be overlaid on file[0] */
-static int *klist; /* will be overlaid on file[0] after class */
-static int *member; /* will be overlaid on file[1] */
-static int clen;
-static int inifdef; /* whether or not we are in a #ifdef block */
-static size_t len[2]; /* lengths of files in lines */
-static size_t pref, suff; /* lengths of prefix and suffix */
-static size_t slen[2]; /* lengths of files minus pref / suff */
-static int anychange;
-static int hw, lpad,rpad; /* half width and padding */
-static int edoffset;
-static long *ixnew; /* will be overlaid on file[1] */
-static long *ixold; /* will be overlaid on klist */
-static struct cand *clist; /* merely a free storage pot for candidates */
-static int clistlen; /* the length of clist */
-static struct line *sfile[2]; /* shortened by pruning common prefix/suffix */
-static int (*chrtran)(int); /* translation table for case-folding */
-static struct context_vec *context_vec_start;
-static struct context_vec *context_vec_end;
-static struct context_vec *context_vec_ptr;
-
-#define FUNCTION_CONTEXT_SIZE 55
-static char lastbuf[FUNCTION_CONTEXT_SIZE];
-static int lastline;
-static int lastmatchline;
-
-static int
-clow2low(int c)
-{
-
- return (c);
-}
-
-static int
-cup2low(int c)
-{
-
- return (tolower(c));
-}
-
-int
-diffreg(char *file1, char *file2, int flags, int capsicum)
-{
- FILE *f1, *f2;
- int i, rval;
- struct pr *pr = NULL;
-
- f1 = f2 = NULL;
- rval = D_SAME;
- anychange = 0;
- lastline = 0;
- lastmatchline = 0;
-
- /*
- * In side-by-side mode, we need to print the left column, a
- * change marker surrounded by padding, and the right column.
- *
- * If expanding tabs, we don't care about alignment, so we simply
- * subtract 3 from the width and divide by two.
- *
- * If not expanding tabs, we need to ensure that the right column
- * is aligned to a tab stop. We start with the same formula, then
- * decrement until we reach a size that lets us tab-align the
- * right column. We then adjust the width down if necessary for
- * the padding calculation to work.
- *
- * Left padding is half the space left over, rounded down; right
- * padding is whatever is needed to match the width.
- */
- if (diff_format == D_SIDEBYSIDE) {
- if (flags & D_EXPANDTABS) {
- if (width > 3) {
- hw = (width - 3) / 2;
- } else {
- /* not enough space */
- hw = 0;
- }
- } else if (width <= 3 || width <= tabsize) {
- /* not enough space */
- hw = 0;
- } else {
- hw = (width - 3) / 2;
- while (hw > 0 && roundup(hw + 3, tabsize) + hw > width)
- hw--;
- if (width - (roundup(hw + 3, tabsize) + hw) < tabsize)
- width = roundup(hw + 3, tabsize) + hw;
- }
- lpad = (width - hw * 2 - 1) / 2;
- rpad = (width - hw * 2 - 1) - lpad;
- }
-
- if (flags & D_IGNORECASE)
- chrtran = cup2low;
- else
- chrtran = clow2low;
- if (S_ISDIR(stb1.st_mode) != S_ISDIR(stb2.st_mode))
- return (S_ISDIR(stb1.st_mode) ? D_MISMATCH1 : D_MISMATCH2);
- if (strcmp(file1, "-") == 0 && strcmp(file2, "-") == 0)
- goto closem;
-
- if (flags & D_EMPTY1)
- f1 = fopen(_PATH_DEVNULL, "r");
- else {
- if (!S_ISREG(stb1.st_mode)) {
- if ((f1 = opentemp(file1)) == NULL ||
- fstat(fileno(f1), &stb1) == -1) {
- warn("%s", file1);
- rval = D_ERROR;
- status |= 2;
- goto closem;
- }
- } else if (strcmp(file1, "-") == 0)
- f1 = stdin;
- else
- f1 = fopen(file1, "r");
- }
- if (f1 == NULL) {
- warn("%s", file1);
- rval = D_ERROR;
- status |= 2;
- goto closem;
- }
-
- if (flags & D_EMPTY2)
- f2 = fopen(_PATH_DEVNULL, "r");
- else {
- if (!S_ISREG(stb2.st_mode)) {
- if ((f2 = opentemp(file2)) == NULL ||
- fstat(fileno(f2), &stb2) == -1) {
- warn("%s", file2);
- rval = D_ERROR;
- status |= 2;
- goto closem;
- }
- } else if (strcmp(file2, "-") == 0)
- f2 = stdin;
- else
- f2 = fopen(file2, "r");
- }
- if (f2 == NULL) {
- warn("%s", file2);
- rval = D_ERROR;
- status |= 2;
- goto closem;
- }
-
- if (lflag)
- pr = start_pr(file1, file2);
-
- (void)capsicum;
-
- switch (files_differ(f1, f2, flags)) {
- case 0:
- goto closem;
- case 1:
- break;
- default:
- /* error */
- rval = D_ERROR;
- status |= 2;
- goto closem;
- }
-
- if (diff_format == D_BRIEF && ignore_pats == NULL &&
- (flags & (D_FOLDBLANKS|D_IGNOREBLANKS|D_IGNORECASE|
- D_SKIPBLANKLINES|D_STRIPCR)) == 0)
- {
- rval = D_DIFFER;
- status |= 1;
- goto closem;
- }
- if ((flags & D_FORCEASCII) != 0) {
- (void)prepare(0, f1, stb1.st_size, flags);
- (void)prepare(1, f2, stb2.st_size, flags);
- } else if (!asciifile(f1) || !asciifile(f2) ||
- !prepare(0, f1, stb1.st_size, flags) ||
- !prepare(1, f2, stb2.st_size, flags)) {
- rval = D_BINARY;
- status |= 1;
- goto closem;
- }
- if (len[0] > INT_MAX - 2)
- errno = EFBIG, err(1, "%s", file1);
- if (len[1] > INT_MAX - 2)
- errno = EFBIG, err(1, "%s", file2);
-
- prune();
- sort(sfile[0], slen[0]);
- sort(sfile[1], slen[1]);
-
- member = (int *)file[1];
- equiv(sfile[0], slen[0], sfile[1], slen[1], member);
- member = xreallocarray(member, slen[1] + 2, sizeof(*member));
-
- class = (int *)file[0];
- unsort(sfile[0], slen[0], class);
- class = xreallocarray(class, slen[0] + 2, sizeof(*class));
-
- klist = xcalloc(slen[0] + 2, sizeof(*klist));
- clen = 0;
- clistlen = 100;
- clist = xcalloc(clistlen, sizeof(*clist));
- i = stone(class, slen[0], member, klist, flags);
- free(member);
- free(class);
-
- J = xreallocarray(J, len[0] + 2, sizeof(*J));
- unravel(klist[i]);
- free(clist);
- free(klist);
-
- ixold = xreallocarray(ixold, len[0] + 2, sizeof(*ixold));
- ixnew = xreallocarray(ixnew, len[1] + 2, sizeof(*ixnew));
- check(f1, f2, flags);
- output(file1, f1, file2, f2, flags);
-
-closem:
- if (pr != NULL)
- stop_pr(pr);
- if (anychange) {
- status |= 1;
- if (rval == D_SAME)
- rval = D_DIFFER;
- }
- if (f1 != NULL)
- fclose(f1);
- if (f2 != NULL)
- fclose(f2);
-
- return (rval);
-}
-
-/*
- * Check to see if the given files differ.
- * Returns 0 if they are the same, 1 if different, and -1 on error.
- * XXX - could use code from cmp(1) [faster]
- */
-static int
-files_differ(FILE *f1, FILE *f2, int flags)
-{
- char buf1[BUFSIZ], buf2[BUFSIZ];
- size_t i, j;
-
- if ((flags & (D_EMPTY1|D_EMPTY2)) || stb1.st_size != stb2.st_size ||
- (stb1.st_mode & S_IFMT) != (stb2.st_mode & S_IFMT))
- return (1);
-
- if (stb1.st_dev == stb2.st_dev && stb1.st_ino == stb2.st_ino)
- return (0);
-
- for (;;) {
- i = fread(buf1, 1, sizeof(buf1), f1);
- j = fread(buf2, 1, sizeof(buf2), f2);
- if ((!i && ferror(f1)) || (!j && ferror(f2)))
- return (-1);
- if (i != j)
- return (1);
- if (i == 0)
- return (0);
- if (memcmp(buf1, buf2, i) != 0)
- return (1);
- }
-}
-
-static FILE *
-opentemp(const char *f)
-{
- char buf[BUFSIZ], tempfile[PATH_MAX];
- ssize_t nread;
- int ifd, ofd;
-
- if (strcmp(f, "-") == 0)
- ifd = STDIN_FILENO;
- else if ((ifd = open(f, O_RDONLY, 0644)) == -1)
- return (NULL);
-
- (void)strlcpy(tempfile, _PATH_TMP "/diff.XXXXXXXX", sizeof(tempfile));
-
- if ((ofd = mkstemp(tempfile)) == -1) {
- close(ifd);
- return (NULL);
- }
- unlink(tempfile);
- while ((nread = read(ifd, buf, BUFSIZ)) > 0) {
- if (write(ofd, buf, nread) != nread) {
- close(ifd);
- close(ofd);
- return (NULL);
- }
- }
- close(ifd);
- lseek(ofd, (off_t)0, SEEK_SET);
- return (fdopen(ofd, "r"));
-}
-
-static bool
-prepare(int i, FILE *fd, size_t filesize, int flags)
-{
- struct line *p;
- unsigned h;
- size_t sz, j = 0;
- enum readhash r;
-
- rewind(fd);
-
- sz = MIN(filesize, SIZE_MAX) / 25;
- if (sz < 100)
- sz = 100;
-
- p = xcalloc(sz + 3, sizeof(*p));
- while ((r = readhash(fd, flags, &h)) != RH_EOF) {
- if (r == RH_BINARY)
- return (false);
- if (j == SIZE_MAX)
- break;
- if (j == sz) {
- sz = sz * 3 / 2;
- p = xreallocarray(p, sz + 3, sizeof(*p));
- }
- p[++j].value = h;
- }
-
- len[i] = j;
- file[i] = p;
-
- return (true);
-}
-
-static void
-prune(void)
-{
- size_t i, j;
-
- for (pref = 0; pref < len[0] && pref < len[1] &&
- file[0][pref + 1].value == file[1][pref + 1].value;
- pref++)
- ;
- for (suff = 0; suff < len[0] - pref && suff < len[1] - pref &&
- file[0][len[0] - suff].value == file[1][len[1] - suff].value;
- suff++)
- ;
- for (j = 0; j < 2; j++) {
- sfile[j] = file[j] + pref;
- slen[j] = len[j] - pref - suff;
- for (i = 0; i <= slen[j]; i++)
- sfile[j][i].serial = i;
- }
-}
-
-static void
-equiv(struct line *a, int n, struct line *b, int m, int *c)
-{
- int i, j;
-
- i = j = 1;
- while (i <= n && j <= m) {
- if (a[i].value < b[j].value)
- a[i++].value = 0;
- else if (a[i].value == b[j].value)
- a[i++].value = j;
- else
- j++;
- }
- while (i <= n)
- a[i++].value = 0;
- b[m + 1].value = 0;
- j = 0;
- while (++j <= m) {
- c[j] = -b[j].serial;
- while (b[j + 1].value == b[j].value) {
- j++;
- c[j] = b[j].serial;
- }
- }
- c[j] = -1;
-}
-
-static int
-stone(int *a, int n, int *b, int *c, int flags)
-{
- int i, k, y, j, l;
- int oldc, tc, oldl, sq;
- unsigned numtries, bound;
-
- if (flags & D_MINIMAL)
- bound = UINT_MAX;
- else {
- sq = sqrt(n);
- bound = MAX(256, sq);
- }
-
- k = 0;
- c[0] = newcand(0, 0, 0);
- for (i = 1; i <= n; i++) {
- j = a[i];
- if (j == 0)
- continue;
- y = -b[j];
- oldl = 0;
- oldc = c[0];
- numtries = 0;
- do {
- if (y <= clist[oldc].y)
- continue;
- l = search(c, k, y);
- if (l != oldl + 1)
- oldc = c[l - 1];
- if (l <= k) {
- if (clist[c[l]].y <= y)
- continue;
- tc = c[l];
- c[l] = newcand(i, y, oldc);
- oldc = tc;
- oldl = l;
- numtries++;
- } else {
- c[l] = newcand(i, y, oldc);
- k++;
- break;
- }
- } while ((y = b[++j]) > 0 && numtries < bound);
- }
- return (k);
-}
-
-static int
-newcand(int x, int y, int pred)
-{
- struct cand *q;
-
- if (clen == clistlen) {
- clistlen = clistlen * 11 / 10;
- clist = xreallocarray(clist, clistlen, sizeof(*clist));
- }
- q = clist + clen;
- q->x = x;
- q->y = y;
- q->pred = pred;
- return (clen++);
-}
-
-static int
-search(int *c, int k, int y)
-{
- int i, j, l, t;
-
- if (clist[c[k]].y < y) /* quick look for typical case */
- return (k + 1);
- i = 0;
- j = k + 1;
- for (;;) {
- l = (i + j) / 2;
- if (l <= i)
- break;
- t = clist[c[l]].y;
- if (t > y)
- j = l;
- else if (t < y)
- i = l;
- else
- return (l);
- }
- return (l + 1);
-}
-
-static void
-unravel(int p)
-{
- struct cand *q;
- size_t i;
-
- for (i = 0; i <= len[0]; i++)
- J[i] = i <= pref ? i :
- i > len[0] - suff ? i + len[1] - len[0] : 0;
- for (q = clist + p; q->y != 0; q = clist + q->pred)
- J[q->x + pref] = q->y + pref;
-}
-
-/*
- * Check does double duty:
- * 1. ferret out any fortuitous correspondences due to confounding by
- * hashing (which result in "jackpot")
- * 2. collect random access indexes to the two files
- */
-static void
-check(FILE *f1, FILE *f2, int flags)
-{
- int i, j, /* jackpot, */ c, d;
- long ctold, ctnew;
-
- rewind(f1);
- rewind(f2);
- j = 1;
- ixold[0] = ixnew[0] = 0;
- /* jackpot = 0; */
- ctold = ctnew = 0;
- for (i = 1; i <= (int)len[0]; i++) {
- if (J[i] == 0) {
- ixold[i] = ctold += skipline(f1);
- continue;
- }
- while (j < J[i]) {
- ixnew[j] = ctnew += skipline(f2);
- j++;
- }
- if (flags & (D_FOLDBLANKS | D_IGNOREBLANKS | D_IGNORECASE | D_STRIPCR)) {
- for (;;) {
- c = getc(f1);
- d = getc(f2);
- /*
- * GNU diff ignores a missing newline
- * in one file for -b or -w.
- */
- if (flags & (D_FOLDBLANKS | D_IGNOREBLANKS)) {
- if (c == EOF && isspace(d)) {
- ctnew++;
- break;
- } else if (isspace(c) && d == EOF) {
- ctold++;
- break;
- }
- }
- ctold++;
- ctnew++;
- if (flags & D_STRIPCR && (c == '\r' || d == '\r')) {
- if (c == '\r') {
- if ((c = getc(f1)) == '\n') {
- ctold++;
- } else {
- ungetc(c, f1);
- }
- }
- if (d == '\r') {
- if ((d = getc(f2)) == '\n') {
- ctnew++;
- } else {
- ungetc(d, f2);
- }
- }
- break;
- }
- if ((flags & D_FOLDBLANKS) && isspace(c) &&
- isspace(d)) {
- do {
- if (c == '\n')
- break;
- ctold++;
- } while (isspace(c = getc(f1)));
- do {
- if (d == '\n')
- break;
- ctnew++;
- } while (isspace(d = getc(f2)));
- } else if (flags & D_IGNOREBLANKS) {
- while (isspace(c) && c != '\n') {
- c = getc(f1);
- ctold++;
- }
- while (isspace(d) && d != '\n') {
- d = getc(f2);
- ctnew++;
- }
- }
- if (chrtran(c) != chrtran(d)) {
- /* jackpot++; */
- J[i] = 0;
- if (c != '\n' && c != EOF)
- ctold += skipline(f1);
- if (d != '\n' && c != EOF)
- ctnew += skipline(f2);
- break;
- }
- if (c == '\n' || c == EOF)
- break;
- }
- } else {
- for (;;) {
- ctold++;
- ctnew++;
- if ((c = getc(f1)) != (d = getc(f2))) {
- /* jackpot++; */
- J[i] = 0;
- if (c != '\n' && c != EOF)
- ctold += skipline(f1);
- if (d != '\n' && c != EOF)
- ctnew += skipline(f2);
- break;
- }
- if (c == '\n' || c == EOF)
- break;
- }
- }
- ixold[i] = ctold;
- ixnew[j] = ctnew;
- j++;
- }
- for (; j <= (int)len[1]; j++) {
- ixnew[j] = ctnew += skipline(f2);
- }
- /*
- * if (jackpot)
- * fprintf(stderr, "jackpot\n");
- */
-}
-
-/* shellsort CACM #201 */
-static void
-sort(struct line *a, int n)
-{
- struct line *ai, *aim, w;
- int j, m = 0, k;
-
- if (n == 0)
- return;
- for (j = 1; j <= n; j *= 2)
- m = 2 * j - 1;
- for (m /= 2; m != 0; m /= 2) {
- k = n - m;
- for (j = 1; j <= k; j++) {
- for (ai = &a[j]; ai > a; ai -= m) {
- aim = &ai[m];
- if (aim < ai)
- break; /* wraparound */
- if (aim->value > ai[0].value ||
- (aim->value == ai[0].value &&
- aim->serial > ai[0].serial))
- break;
- w.value = ai[0].value;
- ai[0].value = aim->value;
- aim->value = w.value;
- w.serial = ai[0].serial;
- ai[0].serial = aim->serial;
- aim->serial = w.serial;
- }
- }
- }
-}
-
-static void
-unsort(struct line *f, int l, int *b)
-{
- int *a, i;
-
- a = xcalloc(l + 1, sizeof(*a));
- for (i = 1; i <= l; i++)
- a[f[i].serial] = f[i].value;
- for (i = 1; i <= l; i++)
- b[i] = a[i];
- free(a);
-}
-
-static int
-skipline(FILE *f)
-{
- int i, c;
-
- for (i = 1; (c = getc(f)) != '\n' && c != EOF; i++)
- continue;
- return (i);
-}
-
-static void
-output(char *file1, FILE *f1, char *file2, FILE *f2, int flags)
-{
- int i, j, m, i0, i1, j0, j1, nc;
-
- rewind(f1);
- rewind(f2);
- m = len[0];
- J[0] = 0;
- J[m + 1] = len[1] + 1;
- if (diff_format != D_EDIT) {
- for (i0 = 1; i0 <= m; i0 = i1 + 1) {
- while (i0 <= m && J[i0] == J[i0 - 1] + 1) {
- if (diff_format == D_SIDEBYSIDE && suppress_common != 1) {
- nc = fetch(ixold, i0, i0, f1, '\0', 1, flags);
- print_space(nc, hw - nc + lpad + 1 + rpad, flags);
- fetch(ixnew, J[i0], J[i0], f2, '\0', 0, flags);
- printf("\n");
- }
- i0++;
- }
- j0 = J[i0 - 1] + 1;
- i1 = i0 - 1;
- while (i1 < m && J[i1 + 1] == 0)
- i1++;
- j1 = J[i1 + 1] - 1;
- J[i1] = j1;
-
- /*
- * When using side-by-side, lines from both of the files are
- * printed. The algorithm used by diff(1) identifies the ranges
- * in which two files differ.
- * See the change() function below.
- * The for loop below consumes the shorter range, whereas one of
- * the while loops deals with the longer one.
- */
- if (diff_format == D_SIDEBYSIDE) {
- for (i = i0, j = j0; i <= i1 && j <= j1; i++, j++)
- change(file1, f1, file2, f2, i, i, j, j, &flags);
-
- while (i <= i1) {
- change(file1, f1, file2, f2, i, i, j + 1, j, &flags);
- i++;
- }
-
- while (j <= j1) {
- change(file1, f1, file2, f2, i + 1, i, j, j, &flags);
- j++;
- }
- } else
- change(file1, f1, file2, f2, i0, i1, j0, j1, &flags);
- }
- } else {
- for (i0 = m; i0 >= 1; i0 = i1 - 1) {
- while (i0 >= 1 && J[i0] == J[i0 + 1] - 1 && J[i0] != 0)
- i0--;
- j0 = J[i0 + 1] - 1;
- i1 = i0 + 1;
- while (i1 > 1 && J[i1 - 1] == 0)
- i1--;
- j1 = J[i1 - 1] + 1;
- J[i1] = j1;
- change(file1, f1, file2, f2, i1, i0, j1, j0, &flags);
- }
- }
- if (m == 0)
- change(file1, f1, file2, f2, 1, 0, 1, len[1], &flags);
- if (diff_format == D_IFDEF || diff_format == D_GFORMAT) {
- for (;;) {
-#define c i0
- if ((c = getc(f1)) == EOF)
- return;
- printf("%c", c);
- }
-#undef c
- }
- if (anychange != 0) {
- if (diff_format == D_CONTEXT)
- dump_context_vec(f1, f2, flags);
- else if (diff_format == D_UNIFIED)
- dump_unified_vec(f1, f2, flags);
- }
-}
-
-static void
-range(int a, int b, const char *separator)
-{
- printf("%d", a > b ? b : a);
- if (a < b)
- printf("%s%d", separator, b);
-}
-
-static void
-uni_range(int a, int b)
-{
- if (a < b)
- printf("%d,%d", a, b - a + 1);
- else if (a == b)
- printf("%d", b);
- else
- printf("%d,0", b);
-}
-
-static char *
-preadline(int fd, size_t rlen, off_t off)
-{
- char *line;
- ssize_t nr;
-
- line = xmalloc(rlen + 1);
- if ((nr = pread(fd, line, rlen, off)) == -1)
- err(2, "preadline");
- if (nr > 0 && line[nr-1] == '\n')
- nr--;
- line[nr] = '\0';
- return (line);
-}
-
-static bool
-ignoreline_pattern(char *line)
-{
- int ret;
-
- ret = regexec(&ignore_re, line, 0, NULL, 0);
- return (ret == 0); /* if it matched, it should be ignored. */
-}
-
-static bool
-ignoreline(char *line, bool skip_blanks)
-{
-
- if (skip_blanks && *line == '\0')
- return (true);
- if (ignore_pats != NULL && ignoreline_pattern(line))
- return (true);
- return (false);
-}
-
-/*
- * Indicate that there is a difference between lines a and b of the from file
- * to get to lines c to d of the to file. If a is greater then b then there
- * are no lines in the from file involved and this means that there were
- * lines appended (beginning at b). If c is greater than d then there are
- * lines missing from the to file.
- */
-static void
-change(char *file1, FILE *f1, char *file2, FILE *f2, int a, int b, int c, int d,
- int *pflags)
-{
- static size_t max_context = 64;
- long curpos;
- int i, nc;
- const char *walk;
- bool skip_blanks, ignore;
-
- skip_blanks = (*pflags & D_SKIPBLANKLINES);
-restart:
- if ((diff_format != D_IFDEF || diff_format == D_GFORMAT) &&
- a > b && c > d)
- return;
- if (ignore_pats != NULL || skip_blanks) {
- char *line;
- /*
- * All lines in the change, insert, or delete must match an ignore
- * pattern for the change to be ignored.
- */
- if (a <= b) { /* Changes and deletes. */
- for (i = a; i <= b; i++) {
- line = preadline(fileno(f1),
- ixold[i] - ixold[i - 1], ixold[i - 1]);
- ignore = ignoreline(line, skip_blanks);
- free(line);
- if (!ignore)
- goto proceed;
- }
- }
- if (a > b || c <= d) { /* Changes and inserts. */
- for (i = c; i <= d; i++) {
- line = preadline(fileno(f2),
- ixnew[i] - ixnew[i - 1], ixnew[i - 1]);
- ignore = ignoreline(line, skip_blanks);
- free(line);
- if (!ignore)
- goto proceed;
- }
- }
- return;
- }
-proceed:
- if (*pflags & D_HEADER && diff_format != D_BRIEF) {
- printf("%s %s %s\n", diffargs, file1, file2);
- *pflags &= ~D_HEADER;
- }
- if (diff_format == D_CONTEXT || diff_format == D_UNIFIED) {
- /*
- * Allocate change records as needed.
- */
- if (context_vec_start == NULL ||
- context_vec_ptr == context_vec_end - 1) {
- ptrdiff_t offset = -1;
-
- if (context_vec_start != NULL)
- offset = context_vec_ptr - context_vec_start;
- max_context <<= 1;
- context_vec_start = xreallocarray(context_vec_start,
- max_context, sizeof(*context_vec_start));
- context_vec_end = context_vec_start + max_context;
- context_vec_ptr = context_vec_start + offset;
- }
- if (anychange == 0) {
- /*
- * Print the context/unidiff header first time through.
- */
- print_header(file1, file2);
- anychange = 1;
- } else if (a > context_vec_ptr->b + (2 * diff_context) + 1 &&
- c > context_vec_ptr->d + (2 * diff_context) + 1) {
- /*
- * If this change is more than 'diff_context' lines from the
- * previous change, dump the record and reset it.
- */
- if (diff_format == D_CONTEXT)
- dump_context_vec(f1, f2, *pflags);
- else
- dump_unified_vec(f1, f2, *pflags);
- }
- context_vec_ptr++;
- context_vec_ptr->a = a;
- context_vec_ptr->b = b;
- context_vec_ptr->c = c;
- context_vec_ptr->d = d;
- return;
- }
- if (anychange == 0)
- anychange = 1;
- switch (diff_format) {
- case D_BRIEF:
- return;
- case D_NORMAL:
- case D_EDIT:
- range(a, b, ",");
- printf("%c", a > b ? 'a' : c > d ? 'd' : 'c');
- if (diff_format == D_NORMAL)
- range(c, d, ",");
- printf("\n");
- break;
- case D_REVERSE:
- printf("%c", a > b ? 'a' : c > d ? 'd' : 'c');
- range(a, b, " ");
- printf("\n");
- break;
- case D_NREVERSE:
- if (a > b)
- printf("a%d %d\n", b, d - c + 1);
- else {
- printf("d%d %d\n", a, b - a + 1);
- if (!(c > d))
- /* add changed lines */
- printf("a%d %d\n", b, d - c + 1);
- }
- break;
- }
- if (diff_format == D_GFORMAT) {
- curpos = ftell(f1);
- /* print through if append (a>b), else to (nb: 0 vs 1 orig) */
- nc = ixold[a > b ? b : a - 1] - curpos;
- for (i = 0; i < nc; i++)
- printf("%c", getc(f1));
- for (walk = group_format; *walk != '\0'; walk++) {
- if (*walk == '%') {
- walk++;
- switch (*walk) {
- case '<':
- fetch(ixold, a, b, f1, '<', 1, *pflags);
- break;
- case '>':
- fetch(ixnew, c, d, f2, '>', 0, *pflags);
- break;
- default:
- printf("%%%c", *walk);
- break;
- }
- continue;
- }
- printf("%c", *walk);
- }
- }
- if (diff_format == D_SIDEBYSIDE) {
- if (color && a > b)
- printf("\033[%sm", add_code);
- else if (color && c > d)
- printf("\033[%sm", del_code);
- if (a > b) {
- print_space(0, hw + lpad, *pflags);
- } else {
- nc = fetch(ixold, a, b, f1, '\0', 1, *pflags);
- print_space(nc, hw - nc + lpad, *pflags);
- }
- if (color && a > b)
- printf("\033[%sm", add_code);
- else if (color && c > d)
- printf("\033[%sm", del_code);
- printf("%c", (a > b) ? '>' : ((c > d) ? '<' : '|'));
- if (color && c > d)
- printf("\033[m");
- print_space(hw + lpad + 1, rpad, *pflags);
- fetch(ixnew, c, d, f2, '\0', 0, *pflags);
- printf("\n");
- }
- if (diff_format == D_NORMAL || diff_format == D_IFDEF) {
- fetch(ixold, a, b, f1, '<', 1, *pflags);
- if (a <= b && c <= d && diff_format == D_NORMAL)
- printf("---\n");
- }
- if (diff_format != D_GFORMAT && diff_format != D_SIDEBYSIDE)
- fetch(ixnew, c, d, f2, diff_format == D_NORMAL ? '>' : '\0', 0, *pflags);
- if (edoffset != 0 && diff_format == D_EDIT) {
- /*
- * A non-zero edoffset value for D_EDIT indicates that the last line
- * printed was a bare dot (".") that has been escaped as ".." to
- * prevent ed(1) from misinterpreting it. We have to add a
- * substitute command to change this back and restart where we left
- * off.
- */
- printf(".\n");
- printf("%ds/.//\n", a + edoffset - 1);
- b = a + edoffset - 1;
- a = b + 1;
- c += edoffset;
- goto restart;
- }
- if ((diff_format == D_EDIT || diff_format == D_REVERSE) && c <= d)
- printf(".\n");
- if (inifdef) {
- printf("#endif /* %s */\n", ifdefname);
- inifdef = 0;
- }
-}
-
-static int
-fetch(long *f, int a, int b, FILE *lb, int ch, int oldfile, int flags)
-{
- int i, j, c, lastc, col, nc, newcol;
-
- edoffset = 0;
- nc = 0;
- col = 0;
- /*
- * When doing #ifdef's, copy down to current line
- * if this is the first file, so that stuff makes it to output.
- */
- if ((diff_format == D_IFDEF) && oldfile) {
- long curpos = ftell(lb);
- /* print through if append (a>b), else to (nb: 0 vs 1 orig) */
- nc = f[a > b ? b : a - 1] - curpos;
- for (i = 0; i < nc; i++)
- printf("%c", getc(lb));
- }
- if (a > b)
- return (0);
- if (diff_format == D_IFDEF) {
- if (inifdef) {
- printf("#else /* %s%s */\n",
- oldfile == 1 ? "!" : "", ifdefname);
- } else {
- if (oldfile)
- printf("#ifndef %s\n", ifdefname);
- else
- printf("#ifdef %s\n", ifdefname);
- }
- inifdef = 1 + oldfile;
- }
- for (i = a; i <= b; i++) {
- fseek(lb, f[i - 1], SEEK_SET);
- nc = f[i] - f[i - 1];
- if (diff_format == D_SIDEBYSIDE && hw < nc)
- nc = hw;
- if (diff_format != D_IFDEF && diff_format != D_GFORMAT &&
- ch != '\0') {
- if (color && (ch == '>' || ch == '+'))
- printf("\033[%sm", add_code);
- else if (color && (ch == '<' || ch == '-'))
- printf("\033[%sm", del_code);
- printf("%c", ch);
- if (Tflag && (diff_format == D_NORMAL ||
- diff_format == D_CONTEXT ||
- diff_format == D_UNIFIED))
- printf("\t");
- else if (diff_format != D_UNIFIED)
- printf(" ");
- }
- col = j = 0;
- lastc = '\0';
- while (j < nc && (hw == 0 || col < hw)) {
- c = getc(lb);
- if (flags & D_STRIPCR && c == '\r') {
- if ((c = getc(lb)) == '\n')
- j++;
- else {
- ungetc(c, lb);
- c = '\r';
- }
- }
- if (c == EOF) {
- if (diff_format == D_EDIT ||
- diff_format == D_REVERSE ||
- diff_format == D_NREVERSE)
- warnx("No newline at end of file");
- else
- printf("\n\\ No newline at end of file\n");
- return (col);
- }
- /*
- * when using --side-by-side, col needs to be increased
- * in any case to keep the columns aligned
- */
- if (c == '\t') {
- /*
- * Calculate where the tab would bring us.
- * If it would take us to the end of the
- * column, either clip it (if expanding
- * tabs) or return right away (if not).
- */
- newcol = roundup(col + 1, tabsize);
- if ((flags & D_EXPANDTABS) == 0) {
- if (hw > 0 && newcol >= hw)
- return (col);
- printf("\t");
- } else {
- if (hw > 0 && newcol > hw)
- newcol = hw;
- printf("%*s", newcol - col, "");
- }
- col = newcol;
- } else {
- if (diff_format == D_EDIT && j == 1 && c == '\n' &&
- lastc == '.') {
- /*
- * Don't print a bare "." line since that will confuse
- * ed(1). Print ".." instead and set the, global variable
- * edoffset to an offset from which to restart. The
- * caller must check the value of edoffset
- */
- printf(".\n");
- edoffset = i - a + 1;
- return (edoffset);
- }
- /* when side-by-side, do not print a newline */
- if (diff_format != D_SIDEBYSIDE || c != '\n') {
- if (color && c == '\n')
- printf("\033[m%c", c);
- else
- printf("%c", c);
- col++;
- }
- }
-
- j++;
- lastc = c;
- }
- }
- if (color && diff_format == D_SIDEBYSIDE)
- printf("\033[m");
- return (col);
-}
-
-/*
- * Hash function taken from Robert Sedgewick, Algorithms in C, 3d ed., p 578.
- */
-static enum readhash
-readhash(FILE *f, int flags, unsigned *hash)
-{
- int i, t, space;
- unsigned sum;
-
- sum = 1;
- space = 0;
- for (i = 0;;) {
- switch (t = getc(f)) {
- case '\0':
- if ((flags & D_FORCEASCII) == 0)
- return (RH_BINARY);
- goto hashchar;
- case '\r':
- if (flags & D_STRIPCR) {
- t = getc(f);
- if (t == '\n')
- break;
- ungetc(t, f);
- }
- /* FALLTHROUGH */
- case '\t':
- case '\v':
- case '\f':
- case ' ':
- if ((flags & (D_FOLDBLANKS|D_IGNOREBLANKS)) != 0) {
- space++;
- continue;
- }
- /* FALLTHROUGH */
- default:
- hashchar:
- if (space && (flags & D_IGNOREBLANKS) == 0) {
- i++;
- space = 0;
- }
- sum = sum * 127 + chrtran(t);
- i++;
- continue;
- case EOF:
- if (i == 0)
- return (RH_EOF);
- /* FALLTHROUGH */
- case '\n':
- break;
- }
- break;
- }
- *hash = sum;
- return (RH_OK);
-}
-
-static int
-asciifile(FILE *f)
-{
- unsigned char buf[BUFSIZ];
- size_t cnt;
-
- if (f == NULL)
- return (1);
-
- rewind(f);
- cnt = fread(buf, 1, sizeof(buf), f);
- return (memchr(buf, '\0', cnt) == NULL);
-}
-
-#define begins_with(s, pre) (strncmp(s, pre, sizeof(pre) - 1) == 0)
-
-static char *
-match_function(const long *f, int pos, FILE *fp)
-{
- char buf[FUNCTION_CONTEXT_SIZE];
- size_t nc;
- int last = lastline;
- const char *state = NULL;
-
- lastline = pos;
- for (; pos > last; pos--) {
- fseek(fp, f[pos - 1], SEEK_SET);
- nc = f[pos] - f[pos - 1];
- if (nc >= sizeof(buf))
- nc = sizeof(buf) - 1;
- nc = fread(buf, 1, nc, fp);
- if (nc == 0)
- continue;
- buf[nc] = '\0';
- buf[strcspn(buf, "\n")] = '\0';
- if (most_recent_pat != NULL) {
- int ret = regexec(&most_recent_re, buf, 0, NULL, 0);
-
- if (ret != 0)
- continue;
- strlcpy(lastbuf, buf, sizeof(lastbuf));
- lastmatchline = pos;
- return (lastbuf);
- } else if (isalpha(buf[0]) || buf[0] == '_' || buf[0] == '$'
- || buf[0] == '-' || buf[0] == '+') {
- if (begins_with(buf, "private:")) {
- if (!state)
- state = " (private)";
- } else if (begins_with(buf, "protected:")) {
- if (!state)
- state = " (protected)";
- } else if (begins_with(buf, "public:")) {
- if (!state)
- state = " (public)";
- } else {
- strlcpy(lastbuf, buf, sizeof(lastbuf));
- if (state)
- strlcat(lastbuf, state, sizeof(lastbuf));
- lastmatchline = pos;
- return (lastbuf);
- }
- }
- }
- return (lastmatchline > 0 ? lastbuf : NULL);
-}
-
-/* dump accumulated "context" diff changes */
-static void
-dump_context_vec(FILE *f1, FILE *f2, int flags)
-{
- struct context_vec *cvp = context_vec_start;
- int lowa, upb, lowc, upd, do_output;
- int a, b, c, d;
- char ch, *f;
-
- if (context_vec_start > context_vec_ptr)
- return;
-
- b = d = 0; /* gcc */
- lowa = MAX(1, cvp->a - diff_context);
- upb = MIN((int)len[0], context_vec_ptr->b + diff_context);
- lowc = MAX(1, cvp->c - diff_context);
- upd = MIN((int)len[1], context_vec_ptr->d + diff_context);
-
- printf("***************");
- if (flags & (D_PROTOTYPE | D_MATCHLAST)) {
- f = match_function(ixold, cvp->a - 1, f1);
- if (f != NULL)
- printf(" %s", f);
- }
- printf("\n*** ");
- range(lowa, upb, ",");
- printf(" ****\n");
-
- /*
- * Output changes to the "old" file. The first loop suppresses
- * output if there were no changes to the "old" file (we'll see
- * the "old" lines as context in the "new" list).
- */
- do_output = 0;
- for (; cvp <= context_vec_ptr; cvp++)
- if (cvp->a <= cvp->b) {
- cvp = context_vec_start;
- do_output++;
- break;
- }
- if (do_output) {
- while (cvp <= context_vec_ptr) {
- a = cvp->a;
- b = cvp->b;
- c = cvp->c;
- d = cvp->d;
-
- if (a <= b && c <= d)
- ch = 'c';
- else
- ch = (a <= b) ? 'd' : 'a';
-
- if (ch == 'a')
- fetch(ixold, lowa, b, f1, ' ', 0, flags);
- else {
- fetch(ixold, lowa, a - 1, f1, ' ', 0, flags);
- fetch(ixold, a, b, f1,
- ch == 'c' ? '!' : '-', 0, flags);
- }
- lowa = b + 1;
- cvp++;
- }
- fetch(ixold, b + 1, upb, f1, ' ', 0, flags);
- }
- /* output changes to the "new" file */
- printf("--- ");
- range(lowc, upd, ",");
- printf(" ----\n");
-
- do_output = 0;
- for (cvp = context_vec_start; cvp <= context_vec_ptr; cvp++)
- if (cvp->c <= cvp->d) {
- cvp = context_vec_start;
- do_output++;
- break;
- }
- if (do_output) {
- while (cvp <= context_vec_ptr) {
- a = cvp->a;
- b = cvp->b;
- c = cvp->c;
- d = cvp->d;
-
- if (a <= b && c <= d)
- ch = 'c';
- else
- ch = (a <= b) ? 'd' : 'a';
-
- if (ch == 'd')
- fetch(ixnew, lowc, d, f2, ' ', 0, flags);
- else {
- fetch(ixnew, lowc, c - 1, f2, ' ', 0, flags);
- fetch(ixnew, c, d, f2,
- ch == 'c' ? '!' : '+', 0, flags);
- }
- lowc = d + 1;
- cvp++;
- }
- fetch(ixnew, d + 1, upd, f2, ' ', 0, flags);
- }
- context_vec_ptr = context_vec_start - 1;
-}
-
-/* dump accumulated "unified" diff changes */
-static void
-dump_unified_vec(FILE *f1, FILE *f2, int flags)
-{
- struct context_vec *cvp = context_vec_start;
- int lowa, upb, lowc, upd;
- int a, b, c, d;
- char ch, *f;
-
- if (context_vec_start > context_vec_ptr)
- return;
-
- b = d = 0; /* gcc */
- lowa = MAX(1, cvp->a - diff_context);
- upb = MIN((int)len[0], context_vec_ptr->b + diff_context);
- lowc = MAX(1, cvp->c - diff_context);
- upd = MIN((int)len[1], context_vec_ptr->d + diff_context);
-
- printf("@@ -");
- uni_range(lowa, upb);
- printf(" +");
- uni_range(lowc, upd);
- printf(" @@");
- if (flags & (D_PROTOTYPE | D_MATCHLAST)) {
- f = match_function(ixold, cvp->a - 1, f1);
- if (f != NULL)
- printf(" %s", f);
- }
- printf("\n");
-
- /*
- * Output changes in "unified" diff format--the old and new lines
- * are printed together.
- */
- for (; cvp <= context_vec_ptr; cvp++) {
- a = cvp->a;
- b = cvp->b;
- c = cvp->c;
- d = cvp->d;
-
- /*
- * c: both new and old changes
- * d: only changes in the old file
- * a: only changes in the new file
- */
- if (a <= b && c <= d)
- ch = 'c';
- else
- ch = (a <= b) ? 'd' : 'a';
-
- switch (ch) {
- case 'c':
- fetch(ixold, lowa, a - 1, f1, ' ', 0, flags);
- fetch(ixold, a, b, f1, '-', 0, flags);
- fetch(ixnew, c, d, f2, '+', 0, flags);
- break;
- case 'd':
- fetch(ixold, lowa, a - 1, f1, ' ', 0, flags);
- fetch(ixold, a, b, f1, '-', 0, flags);
- break;
- case 'a':
- fetch(ixnew, lowc, c - 1, f2, ' ', 0, flags);
- fetch(ixnew, c, d, f2, '+', 0, flags);
- break;
- }
- lowa = b + 1;
- lowc = d + 1;
- }
- fetch(ixnew, d + 1, upd, f2, ' ', 0, flags);
-
- context_vec_ptr = context_vec_start - 1;
-}
-
-static void
-print_header(const char *file1, const char *file2)
-{
- const char *time_format;
- char buf[256];
- struct tm tm1, tm2, *tm_ptr1, *tm_ptr2;
- int nsec1 = stb1.st_mtim.tv_nsec;
- int nsec2 = stb2.st_mtim.tv_nsec;
-
- time_format = "%Y-%m-%d %H:%M:%S";
-
- if (cflag)
- time_format = "%c";
- tm_ptr1 = localtime_r(&stb1.st_mtime, &tm1);
- tm_ptr2 = localtime_r(&stb2.st_mtime, &tm2);
- if (label[0] != NULL)
- printf("%s %s\n", diff_format == D_CONTEXT ? "***" : "---",
- label[0]);
- else {
- strftime(buf, sizeof(buf), time_format, tm_ptr1);
- printf("%s %s\t%s", diff_format == D_CONTEXT ? "***" : "---",
- file1, buf);
- if (!cflag) {
- strftime(buf, sizeof(buf), "%z", tm_ptr1);
- printf(".%.9d %s", nsec1, buf);
- }
- printf("\n");
- }
- if (label[1] != NULL)
- printf("%s %s\n", diff_format == D_CONTEXT ? "---" : "+++",
- label[1]);
- else {
- strftime(buf, sizeof(buf), time_format, tm_ptr2);
- printf("%s %s\t%s", diff_format == D_CONTEXT ? "---" : "+++",
- file2, buf);
- if (!cflag) {
- strftime(buf, sizeof(buf), "%z", tm_ptr2);
- printf(".%.9d %s", nsec2, buf);
- }
- printf("\n");
- }
-}
-
-/*
- * Prints n number of space characters either by using tab
- * or single space characters.
- * nc is the preceding number of characters
- */
-static void
-print_space(int nc, int n, int flags)
-{
- int col, newcol, tabstop;
-
- col = nc;
- newcol = nc + n;
- /* first, use tabs if allowed */
- if ((flags & D_EXPANDTABS) == 0) {
- while ((tabstop = roundup(col + 1, tabsize)) <= newcol) {
- printf("\t");
- col = tabstop;
- }
- }
- /* finish with spaces */
- printf("%*s", newcol - col, "");
-}
diff --git a/cmd/posix/diff/pr.c b/cmd/posix/diff/pr.c
@@ -1,155 +0,0 @@
-/*-
- * Copyright (c) 2017 Baptiste Daroussin <bapt@FreeBSD.org>
- * 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
- * in this position and unchanged.
- * 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.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``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(S) 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>
-#include <sys/wait.h>
-
-#include <err.h>
-#include <paths.h>
-#include <signal.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <unistd.h>
-#include <fcntl.h>
-#include <errno.h>
-#include <poll.h>
-
-#include "util.h"
-
-#include "pr.h"
-#include "diff.h"
-#include "xmalloc.h"
-
-#define _PATH_PR "/usr/bin/pr"
-
-static int sigpipe[2] = {-1, -1};
-static struct pollfd poll_fd;
-
-static void
-handle_sig(int signo)
-{
- write(sigpipe[1], &signo, sizeof(signo));
-}
-
-struct pr *
-start_pr(char *file1, char *file2)
-{
- int pfd[2];
- pid_t pid;
- char *header;
- struct pr *pr;
-
- pr = xcalloc(1, sizeof(*pr));
-
- xasprintf(&header, "%s %s %s", diffargs, file1, file2);
- signal(SIGPIPE, SIG_IGN);
- fflush(stdout);
- rewind(stdout);
- if (pipe(pfd) == -1)
- err(2, "pipe");
- if (sigpipe[0] < 0) {
- if (pipe(sigpipe) == -1)
- err(2, "pipe");
- if (fcntl(sigpipe[0], F_SETFD, FD_CLOEXEC) == -1)
- err(2, "fcntl");
- if (fcntl(sigpipe[1], F_SETFD, FD_CLOEXEC) == -1)
- err(2, "fcntl");
- if (signal(SIGCHLD, handle_sig) == SIG_ERR)
- err(2, "signal");
- poll_fd.fd = sigpipe[0];
- poll_fd.events = POLLIN;
- }
- poll_fd.revents = 0;
- switch ((pid = fork())) {
- case -1:
- status |= 2;
- free(header);
- err(2, "No more processes");
- case 0:
- /* child */
- if (pfd[0] != STDIN_FILENO) {
- dup2(pfd[0], STDIN_FILENO);
- close(pfd[0]);
- }
- close(pfd[1]);
- execl(_PATH_PR, _PATH_PR, "-h", header, (char *)0);
- _exit(127);
- default:
-
- /* parent */
- if (pfd[1] != STDOUT_FILENO) {
- pr->ostdout = dup(STDOUT_FILENO);
- dup2(pfd[1], STDOUT_FILENO);
- close(pfd[1]);
- }
- close(pfd[0]);
- rewind(stdout);
- free(header);
- pr->cpid = pid;
- }
- return (pr);
-}
-
-/* close the pipe to pr and restore stdout */
-void
-stop_pr(struct pr *pr)
-{
- int wstatus;
- int done = 0;
-
- if (pr == NULL)
- return;
-
- fflush(stdout);
- if (pr->ostdout != STDOUT_FILENO) {
- close(STDOUT_FILENO);
- dup2(pr->ostdout, STDOUT_FILENO);
- close(pr->ostdout);
- }
- while (!done) {
- pid_t wpid;
- int npe = poll(&poll_fd, 1, -1);
- if (npe == -1) {
- if (errno == EINTR) continue;
- err(2, "poll");
- }
- if (poll_fd.revents != POLLIN)
- continue;
- if (read(poll_fd.fd, &npe, sizeof(npe)) < 0)
- err(2, "read");
- while ((wpid = waitpid(-1, &wstatus, WNOHANG)) > 0) {
- if (wpid != pr->cpid) continue;
- if (WIFEXITED(wstatus) && WEXITSTATUS(wstatus) != 0)
- errx(2, "pr exited abnormally");
- else if (WIFSIGNALED(wstatus))
- errx(2, "pr killed by signal %d",
- WTERMSIG(wstatus));
- done = 1;
- break;
- }
- }
- free(pr);
-}
diff --git a/cmd/posix/diff/pr.h b/cmd/posix/diff/pr.h
@@ -1,33 +0,0 @@
-/*-
- * Copyright (c) 2017 Baptiste Daroussin <bapt@FreeBSD.org>
- * 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
- * in this position and unchanged.
- * 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.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``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(S) 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.
- */
-
-struct pr {
- int ostdout;
- pid_t cpid;
-};
-
-struct pr *start_pr(char *file1, char *file2);
-void stop_pr(struct pr *);
diff --git a/cmd/posix/diff/xmalloc.c b/cmd/posix/diff/xmalloc.c
@@ -1,96 +0,0 @@
-/* $OpenBSD: xmalloc.c,v 1.10 2019/06/28 05:44:09 deraadt Exp $ */
-/*
- * Author: Tatu Ylonen <ylo@cs.hut.fi>
- * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
- * All rights reserved
- * Versions of malloc and friends that check their results, and never return
- * failure (they call fatal if they encounter an error).
- *
- * As far as I am concerned, the code I have written for this software
- * can be used freely for any purpose. Any derived versions of this
- * software must be clearly marked as such, and if the derived work is
- * incompatible with the protocol description in the RFC file, it must be
- * called by a name other than "ssh" or "Secure Shell".
- */
-
-#include <err.h>
-#include <stdarg.h>
-#include <stdint.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-
-#include "util.h"
-
-#include "xmalloc.h"
-
-void *
-xmalloc(size_t size)
-{
- void *ptr;
-
- if (size == 0)
- errx(2, "xmalloc: zero size");
- ptr = malloc(size);
- if (ptr == NULL)
- err(2, "xmalloc: allocating %zu bytes", size);
- return ptr;
-}
-
-void *
-xcalloc(size_t nmemb, size_t size)
-{
- void *ptr;
-
- ptr = calloc(nmemb, size);
- if (ptr == NULL)
- err(2, "xcalloc: allocating %zu * %zu bytes", nmemb, size);
- return ptr;
-}
-
-void *
-xreallocarray(void *ptr, size_t nmemb, size_t size)
-{
- void *new_ptr;
-
- new_ptr = reallocarray(ptr, nmemb, size);
- if (new_ptr == NULL)
- err(2, "xreallocarray: allocating %zu * %zu bytes",
- nmemb, size);
- return new_ptr;
-}
-
-char *
-xstrdup(const char *str)
-{
- char *cp;
-
- if ((cp = strdup(str)) == NULL)
- err(2, "xstrdup");
- return cp;
-}
-
-int
-xasprintf(char **ret, const char *fmt, ...)
-{
- va_list ap;
- va_list ap2;
- int i;
- size_t n;
-
- va_start(ap, fmt);
- va_copy(ap2, ap);
- i = vsnprintf(NULL, 0, fmt, ap);
- if (i < 0)
- err(2, "xasprintf");
- n = (size_t)i + 1;
- *ret = xmalloc(n);
- i = vsnprintf(*ret, n, fmt, ap2);
- va_end(ap2);
- va_end(ap);
-
- if (i == -1)
- err(2, "xasprintf");
-
- return i;
-}
diff --git a/cmd/posix/diff/xmalloc.h b/cmd/posix/diff/xmalloc.h
@@ -1,32 +0,0 @@
-/* $OpenBSD: xmalloc.h,v 1.4 2015/11/12 16:30:30 mmcc Exp $ */
-
-/*
- * Author: Tatu Ylonen <ylo@cs.hut.fi>
- * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
- * All rights reserved
- * Created: Mon Mar 20 22:09:17 1995 ylo
- *
- * Versions of malloc and friends that check their results, and never return
- * failure (they call fatal if they encounter an error).
- *
- * As far as I am concerned, the code I have written for this software
- * can be used freely for any purpose. Any derived versions of this
- * software must be clearly marked as such, and if the derived work is
- * incompatible with the protocol description in the RFC file, it must be
- * called by a name other than "ssh" or "Secure Shell".
- */
-
-#ifndef XMALLOC_H
-#define XMALLOC_H
-
-#include <stddef.h>
-
-void *xmalloc(size_t);
-void *xcalloc(size_t, size_t);
-void *xreallocarray(void *, size_t, size_t);
-char *xstrdup(const char *);
-int xasprintf(char **, const char *, ...)
- __attribute__((__format__ (printf, 2, 3)))
- __attribute__((__nonnull__ (2)));
-
-#endif /* XMALLOC_H */
diff --git a/cmd/posix/diff3.c b/cmd/posix/diff3.c
@@ -0,0 +1,894 @@
+/* See LICENSE file for copyright and license details. */
+#include "util.h"
+
+#include <sys/types.h>
+#include <sys/wait.h>
+
+#include <ctype.h>
+#include <err.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <stdarg.h>
+#include <getopt.h>
+#include <inttypes.h>
+#include <limits.h>
+#include <poll.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+struct Range {
+ int from;
+ int to;
+};
+
+struct Diff {
+#define DIFF_TYPE1 1
+#define DIFF_TYPE2 2
+#define DIFF_TYPE3 3
+ int type;
+
+ struct Range old;
+ struct Range new;
+};
+
+#define EFLAG_NONE 0
+#define EFLAG_OVERLAP 1
+#define EFLAG_NOOVERLAP 2
+#define EFLAG_UNMERGED 3
+
+static size_t szchanges;
+
+static struct Diff *d13;
+static struct Diff *d23;
+static struct Diff *de;
+static char *overlap;
+static int overlapcnt;
+static FILE *fp[3];
+static int cline[3];
+static int sigpipe[2];
+static int last[4];
+static int Aflag, eflag, iflag, mflag, Tflag;
+static int oflag;
+static int strip_cr;
+static char *f1mark, *f2mark, *f3mark;
+static const char *oldmark = "<<<<<<<";
+static const char *orgmark = "|||||||";
+static const char *newmark = ">>>>>>>";
+static const char *divider = "=======";
+
+static int duplicate(struct Range *, struct Range *);
+static int edit(struct Diff *, int, int, int);
+static char *getchange(FILE *);
+static char *get_line(FILE *, size_t *);
+static int readin(int, struct Diff **);
+static int skip(int, int, const char *);
+static void change(int, struct Range *, int);
+static void keep(int, struct Range *);
+static void merge(int, int);
+static void prange(struct Range *, int);
+static void repos(int);
+static void separate(const char *);
+static void edscript(int);
+static void Ascript(int);
+static void mergescript(int);
+static void increase(void);
+static void usage(void);
+static void printrange(FILE *, struct Range *);
+static void diffexec(const char *, char **, int *);
+static int strtoi(char *, char **);
+static void handle_sig(int);
+static void xasprintf(char **, const char *, ...);
+
+static const char diff3_version[] = "FreeBSD diff3 20240925";
+
+enum {
+ DIFFPROG_OPT,
+ STRIPCR_OPT,
+ HELP_OPT,
+ VERSION_OPT
+};
+
+#define DIFF_PATH "/usr/bin/diff"
+
+#define OPTIONS "3aAeEiL:mTxX"
+static struct option longopts[] = {
+ { "ed", no_argument, NULL, 'e' },
+ { "show-overlap", no_argument, NULL, 'E' },
+ { "overlap-only", no_argument, NULL, 'x' },
+ { "initial-tab", no_argument, NULL, 'T' },
+ { "text", no_argument, NULL, 'a' },
+ { "strip-trailing-cr", no_argument, NULL, STRIPCR_OPT },
+ { "show-all", no_argument, NULL, 'A' },
+ { "easy-only", no_argument, NULL, '3' },
+ { "merge", no_argument, NULL, 'm' },
+ { "label", required_argument, NULL, 'L' },
+ { "diff-program", required_argument, NULL, DIFFPROG_OPT },
+ { "help", no_argument, NULL, HELP_OPT},
+ { "version", no_argument, NULL, VERSION_OPT}
+};
+
+static void
+usage(void)
+{
+ fprintf(stderr, "usage: diff3 [-3aAeEimTxX] [-L label1] [-L label2] "
+ "[-L label3] file1 file2 file3\n");
+}
+
+static int
+strtoi(char *str, char **end)
+{
+ intmax_t num;
+
+ errno = 0;
+ num = strtoimax(str, end, 10);
+ if ((end != NULL && *end == str) ||
+ num < 0 || num > INT_MAX ||
+ errno == EINVAL || errno == ERANGE)
+ err(1, "error in diff output");
+ return (int)num;
+}
+
+static int
+readin(int fd, struct Diff **dd)
+{
+ int a, b, c, d;
+ int i;
+ char kind, *p;
+ FILE *f;
+
+ f = fdopen(fd, "r");
+ if (f == NULL)
+ err(2, "fdopen");
+ for (i = 0; (p = getchange(f)) != NULL; i++) {
+ if ((size_t)i >= szchanges - 1)
+ increase();
+
+ a = b = strtoi(p, &p);
+ if (*p == ',')
+ b = strtoi(p + 1, &p);
+ kind = *p++;
+ c = d = strtoi(p, &p);
+ if (*p == ',')
+ d = strtoi(p + 1, &p);
+ if (*p != '\n')
+ errx(1, "error in diff output");
+ if (kind == 'a')
+ a++;
+ else if (kind == 'c')
+ /* nothing */ ;
+ else if (kind == 'd')
+ c++;
+ else
+ errx(1, "error in diff output");
+ b++;
+ d++;
+ if (b < a || d < c)
+ errx(1, "error in diff output");
+ (*dd)[i].old.from = a;
+ (*dd)[i].old.to = b;
+ (*dd)[i].new.from = c;
+ (*dd)[i].new.to = d;
+ if (i > 0) {
+ if ((*dd)[i].old.from < (*dd)[i - 1].old.to ||
+ (*dd)[i].new.from < (*dd)[i - 1].new.to)
+ errx(1, "diff output out of order");
+ }
+ }
+ if (i > 0) {
+ (*dd)[i].old.from = (*dd)[i].old.to = (*dd)[i - 1].old.to;
+ (*dd)[i].new.from = (*dd)[i].new.to = (*dd)[i - 1].new.to;
+ }
+ fclose(f);
+ return i;
+}
+
+static void
+diffexec(const char *diffprog, char **diffargv, int fd[])
+{
+ switch (fork()) {
+ case 0:
+ close(fd[0]);
+ if (dup2(fd[1], STDOUT_FILENO) == -1)
+ err(2, "child could not duplicate descriptor");
+ close(fd[1]);
+ execvp(diffprog, diffargv);
+ err(2, "could not execute diff: %s", diffprog);
+ break;
+ case -1:
+ err(2, "could not fork");
+ break;
+ }
+ close(fd[1]);
+}
+
+static char *
+getchange(FILE *b)
+{
+ char *line;
+
+ while ((line = get_line(b, NULL)) != NULL) {
+ if (isdigit((unsigned char)line[0]))
+ return line;
+ }
+ return NULL;
+}
+
+static char *
+get_line(FILE *b, size_t *n)
+{
+ ssize_t len;
+ static char *buf = NULL;
+ static size_t bufsize = 0;
+
+ if ((len = getline(&buf, &bufsize, b)) < 0)
+ return NULL;
+
+ if (strip_cr && len >= 2 && strcmp("\r\n", &(buf[len - 2])) == 0) {
+ buf[len - 2] = '\n';
+ buf[len - 1] = '\0';
+ len--;
+ }
+
+ if (n != NULL)
+ *n = len;
+
+ return buf;
+}
+
+static void
+merge(int m1, int m2)
+{
+ struct Diff *d1, *d2, *d3;
+ int j, t1, t2;
+ int dup = 0;
+
+ d1 = d13;
+ d2 = d23;
+ j = 0;
+
+ for (;;) {
+ t1 = (d1 < d13 + m1);
+ t2 = (d2 < d23 + m2);
+ if (!t1 && !t2)
+ break;
+
+ if (!t2 || (t1 && d1->new.to < d2->new.from)) {
+ if (eflag == EFLAG_NONE) {
+ separate("1");
+ change(1, &d1->old, 0);
+ keep(2, &d1->new);
+ change(3, &d1->new, 0);
+ } else if (eflag == EFLAG_OVERLAP) {
+ j = edit(d2, dup, j, DIFF_TYPE1);
+ }
+ d1++;
+ continue;
+ }
+ if (!t1 || (t2 && d2->new.to < d1->new.from)) {
+ if (eflag == EFLAG_NONE) {
+ separate("2");
+ keep(1, &d2->new);
+ change(3, &d2->new, 0);
+ change(2, &d2->old, 0);
+ } else if (Aflag || mflag) {
+ if (eflag == EFLAG_UNMERGED)
+ j = edit(d2, dup, j, DIFF_TYPE2);
+ }
+ d2++;
+ continue;
+ }
+ if (d1 + 1 < d13 + m1 && d1->new.to >= d1[1].new.from) {
+ d1[1].old.from = d1->old.from;
+ d1[1].new.from = d1->new.from;
+ d1++;
+ continue;
+ }
+ if (d2 + 1 < d23 + m2 && d2->new.to >= d2[1].new.from) {
+ d2[1].old.from = d2->old.from;
+ d2[1].new.from = d2->new.from;
+ d2++;
+ continue;
+ }
+ if (d1->new.from == d2->new.from && d1->new.to == d2->new.to) {
+ dup = duplicate(&d1->old, &d2->old);
+ if (eflag == EFLAG_NONE) {
+ separate(dup ? "3" : "");
+ change(1, &d1->old, dup);
+ change(2, &d2->old, 0);
+ d3 = d1->old.to > d1->old.from ? d1 : d2;
+ change(3, &d3->new, 0);
+ } else {
+ j = edit(d1, dup, j, DIFF_TYPE3);
+ }
+ dup = 0;
+ d1++;
+ d2++;
+ continue;
+ }
+ if (d1->new.from < d2->new.from) {
+ d2->old.from -= d2->new.from - d1->new.from;
+ d2->new.from = d1->new.from;
+ } else if (d2->new.from < d1->new.from) {
+ d1->old.from -= d1->new.from - d2->new.from;
+ d1->new.from = d2->new.from;
+ }
+ if (d1->new.to > d2->new.to) {
+ d2->old.to += d1->new.to - d2->new.to;
+ d2->new.to = d1->new.to;
+ } else if (d2->new.to > d1->new.to) {
+ d1->old.to += d2->new.to - d1->new.to;
+ d1->new.to = d2->new.to;
+ }
+ }
+
+ if (mflag)
+ mergescript(j);
+ else if (Aflag)
+ Ascript(j);
+ else if (eflag)
+ edscript(j);
+}
+
+static void
+separate(const char *s)
+{
+ printf("====%s\n", s);
+}
+
+static void
+change(int i, struct Range *rold, int dup)
+{
+ printf("%d:", i);
+ last[i] = rold->to;
+ prange(rold, 0);
+ if (dup)
+ return;
+ i--;
+ skip(i, rold->from, NULL);
+ skip(i, rold->to, " ");
+}
+
+static void
+prange(struct Range *rold, int delete)
+{
+ if (rold->to <= rold->from)
+ printf("%da\n", rold->from - 1);
+ else {
+ printf("%d", rold->from);
+ if (rold->to > rold->from + 1)
+ printf(",%d", rold->to - 1);
+ if (delete)
+ printf("d\n");
+ else
+ printf("c\n");
+ }
+}
+
+static void
+keep(int i, struct Range *rnew)
+{
+ int delta;
+ struct Range trange;
+
+ delta = last[3] - last[i];
+ trange.from = rnew->from - delta;
+ trange.to = rnew->to - delta;
+ change(i, &trange, 1);
+}
+
+static int
+skip(int i, int from, const char *pr)
+{
+ size_t j, n;
+ char *line;
+
+ for (n = 0; cline[i] < from - 1; n += j) {
+ if ((line = get_line(fp[i], &j)) == NULL)
+ errx(EXIT_FAILURE, "logic error");
+ if (pr != NULL)
+ printf("%s%s", Tflag == 1 ? "\t" : pr, line);
+ cline[i]++;
+ }
+ return (int)n;
+}
+
+static int
+duplicate(struct Range *r1, struct Range *r2)
+{
+ int c, d;
+ int nchar;
+ int nline;
+
+ if (r1->to-r1->from != r2->to-r2->from)
+ return 0;
+ skip(0, r1->from, NULL);
+ skip(1, r2->from, NULL);
+ nchar = 0;
+ for (nline = 0; nline < r1->to - r1->from; nline++) {
+ do {
+ c = getc(fp[0]);
+ d = getc(fp[1]);
+ if (c == -1 && d == -1)
+ break;
+ if (c == -1 || d == -1)
+ errx(EXIT_FAILURE, "logic error");
+ nchar++;
+ if (c != d) {
+ repos(nchar);
+ return 0;
+ }
+ } while (c != '\n');
+ }
+ repos(nchar);
+ return 1;
+}
+
+static void
+repos(int nchar)
+{
+ int i;
+
+ for (i = 0; i < 2; i++)
+ (void)fseek(fp[i], (long)-nchar, SEEK_CUR);
+}
+
+static int
+edit(struct Diff *diff, int dup, int j, int difftype)
+{
+ if (!(eflag == EFLAG_UNMERGED ||
+ (!dup && eflag == EFLAG_OVERLAP) ||
+ (dup && eflag == EFLAG_NOOVERLAP))) {
+ return j;
+ }
+ j++;
+ overlap[j] = !dup;
+ if (!dup)
+ overlapcnt++;
+
+ de[j].type = difftype;
+ de[j].old.from = diff->old.from;
+ de[j].old.to = diff->old.to;
+ de[j].new.from = diff->new.from;
+ de[j].new.to = diff->new.to;
+ return j;
+}
+
+static void
+printrange(FILE *p, struct Range *r)
+{
+ char *line = NULL;
+ size_t len = 0;
+ int i = 1;
+
+ if (r->from == r->to)
+ return;
+
+ if (r->from > r->to)
+ errx(EXIT_FAILURE, "invalid print range");
+
+ fseek(p, 0L, SEEK_SET);
+ while (getline(&line, &len, p) > 0) {
+ if (i >= r->from)
+ printf("%s", line);
+ if (++i > r->to - 1)
+ break;
+ }
+ free(line);
+}
+
+static void
+edscript(int n)
+{
+ int delete;
+ struct Range *new, *old;
+
+ for (; n > 0; n--) {
+ new = &de[n].new;
+ old = &de[n].old;
+
+ delete = (new->from == new->to);
+ if (de[n].type == DIFF_TYPE1) {
+ if (delete)
+ printf("%dd\n", new->from - 1);
+ else if (old->from == new->from && old->to == new->to) {
+ printf("%dc\n", old->from);
+ printrange(fp[2], old);
+ printf(".\n");
+ }
+ continue;
+ } else {
+ if (!oflag || !overlap[n]) {
+ prange(old, delete);
+ } else {
+ printf("%da\n", old->to - 1);
+ printf("%s\n", divider);
+ }
+ printrange(fp[2], new);
+ if (!oflag || !overlap[n]) {
+ if (!delete)
+ printf(".\n");
+ } else {
+ printf("%s %s\n.\n", newmark, f3mark);
+ printf("%da\n%s %s\n.\n", old->from - 1, oldmark, f1mark);
+ }
+ }
+ }
+ if (iflag)
+ printf("w\nq\n");
+
+ exit(eflag == EFLAG_NONE ? overlapcnt : 0);
+}
+
+static void
+Ascript(int n)
+{
+ int startmark;
+ int deletenew;
+ int deleteold;
+ struct Range *new, *old;
+
+ for (; n > 0; n--) {
+ new = &de[n].new;
+ old = &de[n].old;
+ deletenew = (new->from == new->to);
+ deleteold = (old->from == old->to);
+
+ if (de[n].type == DIFF_TYPE2) {
+ if (!oflag || !overlap[n]) {
+ prange(old, deletenew);
+ printrange(fp[2], new);
+ } else {
+ startmark = new->to - 1;
+ printf("%da\n", startmark);
+ printf("%s %s\n", newmark, f3mark);
+ printf(".\n");
+ printf("%da\n", startmark - (new->to - new->from));
+ printf("%s %s\n", oldmark, f2mark);
+ if (!deleteold)
+ printrange(fp[1], old);
+ printf("%s\n.\n", divider);
+ }
+ } else if (de[n].type == DIFF_TYPE3) {
+ startmark = old->to - 1;
+ if (!oflag || !overlap[n]) {
+ prange(old, deletenew);
+ printrange(fp[2], new);
+ } else {
+ printf("%da\n", startmark);
+ printf("%s %s\n", orgmark, f2mark);
+ if (deleteold) {
+ struct Range r;
+ r.from = old->from-1;
+ r.to = new->to;
+ printrange(fp[1], &r);
+ } else
+ printrange(fp[1], old);
+ printf("%s\n", divider);
+ printrange(fp[2], new);
+ }
+ if (!oflag || !overlap[n]) {
+ if (!deletenew)
+ printf(".\n");
+ } else {
+ printf("%s %s\n.\n", newmark, f3mark);
+ printf("%da\n%s %s\n.\n", startmark - (old->to - old->from), oldmark, f1mark);
+ }
+ }
+ }
+ if (iflag)
+ printf("w\nq\n");
+
+ exit(overlapcnt > 0);
+}
+
+static void
+mergescript(int i)
+{
+ struct Range r, *new, *old;
+ int n;
+ int delete = 0;
+
+ r.from = 1;
+ r.to = 1;
+
+ for (n = 1; n <= i; n++) {
+ new = &de[n].new;
+ old = &de[n].old;
+
+ delete = (new->from == new->to);
+ if (de[n].type == DIFF_TYPE1 && delete)
+ r.to = new->from - 1;
+ else if (de[n].type == DIFF_TYPE3 && (old->from == old->to)) {
+ r.from = old->from - 1;
+ r.to = new->from;
+ } else
+ r.to = old->from;
+
+ printrange(fp[0], &r);
+ switch (de[n].type) {
+ case DIFF_TYPE1:
+ if (!delete)
+ printrange(fp[2], new);
+ break;
+ case DIFF_TYPE2:
+ printf("%s %s\n", oldmark, f2mark);
+ printrange(fp[1], old);
+ printf("%s\n", divider);
+ printrange(fp[2], new);
+ printf("%s %s\n", newmark, f3mark);
+ break;
+ case DIFF_TYPE3:
+ if (!oflag || !overlap[n]) {
+ printrange(fp[2], new);
+ } else {
+ printf("%s %s\n", oldmark, f1mark);
+ printrange(fp[0], old);
+ if (eflag != EFLAG_OVERLAP) {
+ printf("%s %s\n", orgmark, f2mark);
+ if (old->from == old->to) {
+ struct Range or;
+ or.from = old->from - 1;
+ or.to = new->to;
+ printrange(fp[1], &or);
+ } else {
+ printrange(fp[1], old);
+ }
+ }
+ printf("%s\n", divider);
+ printrange(fp[2], new);
+ printf("%s %s\n", newmark, f3mark);
+ }
+ break;
+ default:
+ printf("Error: Unhandled diff type - exiting\n");
+ exit(EXIT_FAILURE);
+ }
+
+ if (old->from == old->to)
+ r.from = new->to;
+ else
+ r.from = old->to;
+ }
+
+ new = &de[n-1].new;
+ old = &de[n-1].old;
+
+ if (old->from == new->from && old->to == new->to)
+ r.from--;
+ else if (new->from == new->to)
+ r.from = old->from;
+
+ r.to = INT_MAX;
+ printrange(fp[2], &r);
+ exit(overlapcnt > 0);
+}
+
+static void
+increase(void)
+{
+ struct Diff *p;
+ char *q;
+ size_t newsz, incr;
+
+ newsz = szchanges == 0 ? 64 : 2 * szchanges;
+ incr = newsz - szchanges;
+
+ p = ereallocarray(d13, newsz, sizeof(*p));
+ memset(p + szchanges, 0, incr * sizeof(*p));
+ d13 = p;
+
+ p = ereallocarray(d23, newsz, sizeof(*p));
+ memset(p + szchanges, 0, incr * sizeof(*p));
+ d23 = p;
+
+ p = ereallocarray(de, newsz, sizeof(*p));
+ memset(p + szchanges, 0, incr * sizeof(*p));
+ de = p;
+
+ q = ereallocarray(overlap, newsz, 1);
+ memset(q + szchanges, 0, incr * 1);
+ overlap = q;
+ szchanges = newsz;
+}
+
+static void
+handle_sig(int signo)
+{
+ write(sigpipe[1], &signo, sizeof(signo));
+}
+
+static void
+xasprintf(char **strp, const char *fmt, ...)
+{
+ va_list ap;
+ int r;
+
+ va_start(ap, fmt);
+ r = vasprintf(strp, fmt, ap);
+ va_end(ap);
+ if (r == -1)
+ err(2, "asprintf");
+}
+
+// ?man diff3: 3-way differential file comparison
+// ?man arguments: file1 file2 file3
+// ?man synopsis: [-3aAeEiL:mTxX] [--diff-program program] [--strip-trailing-cr] [-L label1] [-L label2] [-L label3] file1 file2 file3
+int
+main(int argc, char **argv)
+{
+ int ch, nblabels, status, m, n, npe, nleft;
+ char *labels[] = { NULL, NULL, NULL };
+ const char *diffprog = DIFF_PATH;
+ char *file1, *file2, *file3;
+ char *diffargv[7];
+ int diffargc = 0;
+ int fd13[2], fd23[2], signo;
+ pid_t wpid;
+ struct pollfd pfd;
+
+ nblabels = 0;
+ eflag = EFLAG_NONE;
+ oflag = 0;
+ diffargv[diffargc++] = (char *)diffprog;
+ while ((ch = getopt_long(argc, argv, OPTIONS, longopts, NULL)) != -1) {
+ // ?man -3: output changes specific only to file3
+ switch (ch) {
+ case '3':
+ eflag = EFLAG_NOOVERLAP;
+ break;
+ // ?man -a: treat files as text
+ case 'a':
+ diffargv[diffargc++] = "-a";
+ break;
+ // ?man -A: output all changes bracketing conflicts
+ case 'A':
+ Aflag = 1;
+ break;
+ // ?man -e: output ed script
+ case 'e':
+ eflag = EFLAG_UNMERGED;
+ break;
+ // ?man -E: show overlapping changes
+ case 'E':
+ eflag = EFLAG_OVERLAP;
+ oflag = 1;
+ break;
+ // ?man -i: append w and q ed commands
+ case 'i':
+ iflag = 1;
+ break;
+ // ?man -L:label: define label
+ case 'L':
+ oflag = 1;
+ if (nblabels >= 3)
+ errx(2, "too many file label options");
+ labels[nblabels++] = optarg;
+ break;
+ // ?man -m: merge output
+ case 'm':
+ Aflag = 1;
+ oflag = 1;
+ mflag = 1;
+ break;
+ // ?man -T: use tab prefix in normal listing
+ case 'T':
+ Tflag = 1;
+ break;
+ // ?man -x: output script with changes specific to all three
+ case 'x':
+ eflag = EFLAG_OVERLAP;
+ break;
+ // ?man -X: show overlapping changes
+ case 'X':
+ oflag = 1;
+ eflag = EFLAG_OVERLAP;
+ break;
+ case DIFFPROG_OPT:
+ diffprog = optarg;
+ break;
+ case STRIPCR_OPT:
+ strip_cr = 1;
+ diffargv[diffargc++] = "--strip-trailing-cr";
+ break;
+ case HELP_OPT:
+ usage();
+ exit(0);
+ case VERSION_OPT:
+ printf("%s\n", diff3_version);
+ exit(0);
+ }
+ }
+ argc -= optind;
+ argv += optind;
+
+ if (Aflag) {
+ if (eflag == EFLAG_NONE)
+ eflag = EFLAG_UNMERGED;
+ oflag = 1;
+ }
+
+ if (argc != 3) {
+ usage();
+ exit(2);
+ }
+
+ file1 = argv[0];
+ file2 = argv[1];
+ file3 = argv[2];
+
+ if (oflag) {
+ xasprintf(&f1mark, "%s", labels[0] != NULL ? labels[0] : file1);
+ xasprintf(&f2mark, "%s", labels[1] != NULL ? labels[1] : file2);
+ xasprintf(&f3mark, "%s", labels[2] != NULL ? labels[2] : file3);
+ }
+ fp[0] = fopen(file1, "r");
+ if (fp[0] == NULL)
+ err(2, "Can't open %s", file1);
+
+ fp[1] = fopen(file2, "r");
+ if (fp[1] == NULL)
+ err(2, "Can't open %s", file2);
+
+ fp[2] = fopen(file3, "r");
+ if (fp[2] == NULL)
+ err(2, "Can't open %s", file3);
+
+ if (pipe(fd13))
+ err(2, "pipe");
+ if (pipe(fd23))
+ err(2, "pipe");
+ if (pipe(sigpipe))
+ err(2, "pipe");
+ if (fcntl(sigpipe[0], F_SETFD, FD_CLOEXEC))
+ err(2, "fcntl");
+ if (fcntl(sigpipe[1], F_SETFD, FD_CLOEXEC))
+ err(2, "fcntl");
+
+ pfd.fd = sigpipe[0];
+ pfd.events = POLLIN;
+ pfd.revents = 0;
+
+ if (signal(SIGCHLD, handle_sig) == SIG_ERR)
+ err(2, "signal");
+
+ diffargv[diffargc] = file1;
+ diffargv[diffargc + 1] = file3;
+ diffargv[diffargc + 2] = NULL;
+
+ nleft = 0;
+ diffexec(diffprog, diffargv, fd13);
+ nleft++;
+
+ diffargv[diffargc] = file2;
+ diffexec(diffprog, diffargv, fd23);
+ nleft++;
+
+ increase();
+ m = readin(fd13[0], &d13);
+ n = readin(fd23[0], &d23);
+
+ while (nleft > 0) {
+ npe = poll(&pfd, 1, -1);
+ if (npe == -1) {
+ if (errno == EINTR)
+ continue;
+ err(2, "poll");
+ }
+ if (pfd.revents != POLLIN)
+ continue;
+ if (read(pfd.fd, &signo, sizeof(signo)) < 0)
+ err(2, "read");
+ while ((wpid = waitpid(-1, &status, WNOHANG)) > 0) {
+ if (WIFEXITED(status) && WEXITSTATUS(status) >= 2)
+ errx(2, "diff exited abnormally");
+ else if (WIFSIGNALED(status))
+ errx(2, "diff killed by signal %d", WTERMSIG(status));
+ nleft--;
+ }
+ }
+ merge(m, n);
+
+ return EXIT_SUCCESS;
+}
diff --git a/cmd/posix/patch.c b/cmd/posix/patch.c
@@ -0,0 +1,3150 @@
+/* See LICENSE file for copyright and license details. */
+#include "util.h"
+
+#include <sys/file.h>
+#include <sys/mman.h>
+#include <sys/param.h>
+#include <sys/stat.h>
+#include <sys/wait.h>
+
+#include <ctype.h>
+#include <dirent.h>
+#include <err.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <getopt.h>
+#include <libgen.h>
+#include <limits.h>
+#include <paths.h>
+#include <stdarg.h>
+#include <stddef.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+#define DEBUGGING
+
+#define MAXHUNKSIZE 100000
+#define INITHUNKMAX 125
+#define INITLINELEN 8192
+#define BUFFERSIZE 1024
+#define LINENUM_MAX LONG_MAX
+
+#define SCCSPREFIX "s."
+#define GET "get -e %s"
+#define SCCSDIFF "get -p %s | diff - %s >/dev/null"
+
+#define RCSSUFFIX ",v"
+#define CHECKOUT "/usr/bin/co"
+#define RCSDIFF "/usr/bin/rcsdiff"
+
+#define ORIGEXT ".orig"
+#define REJEXT ".rej"
+
+#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))
+
+#define OLD_FILE 0
+#define NEW_FILE 1
+#define INDEX_FILE 2
+#define MAX_FILE 3
+
+#define CONTEXT_DIFF 1
+#define NORMAL_DIFF 2
+#define ED_DIFF 3
+#define NEW_CONTEXT_DIFF 4
+#define UNI_DIFF 5
+
+#define _PATH_ED "/bin/ed"
+
+#define ISDIGIT(c) (isascii((unsigned char)c) && isdigit((unsigned char)c))
+
+#ifndef __UNCONST
+#define __UNCONST(a) ((void *)(unsigned long)(const void *)(a))
+#endif
+
+#ifndef __dead
+#define __dead __attribute__((__noreturn__))
+#endif
+
+typedef long LINENUM;
+
+enum BackupType {
+ BACKUP_UNDEFINED,
+ BACKUP_NONE,
+ BACKUP_SIMPLE,
+ BACKUP_NUMBERED_EXISTING,
+ BACKUP_NUMBERED
+};
+
+struct FileName {
+ char *path;
+ int exists;
+};
+
+mode_t filemode = 0644;
+char *buf;
+size_t bufsz;
+int using_plan_a = 1;
+int out_of_mem = 0;
+
+#define MAXFILEC 2
+char *filearg[MAXFILEC];
+int ok_to_create_file = 0;
+char *outname = NULL;
+char *origprae = NULL;
+char *TMPOUTNAME;
+char *TMPINNAME;
+char *TMPREJNAME;
+char *TMPPATNAME;
+int toutkeep = 0;
+int trejkeep = 0;
+int warn_on_invalid_line;
+int last_line_missing_eol;
+
+#ifdef DEBUGGING
+int debug = 0;
+#endif
+
+int force = 0;
+int batch = 0;
+int verbose = 1;
+int reverse = 0;
+int noreverse = 0;
+int skip_rest_of_patch = 0;
+int strippath = 957;
+int canonicalize = 0;
+int check_only = 0;
+int diff_type = 0;
+char *revision = NULL;
+LINENUM input_lines = 0;
+int posix = 0;
+int backup_if_mismatch = -1;
+
+enum BackupType backup_type = BACKUP_UNDEFINED;
+const char *simple_backup_suffix = "~";
+
+static int remove_empty_files = 0;
+static int reverse_flag_specified = 0;
+static char rejname[PATH_MAX];
+static char serrbuf[BUFSIZ];
+static LINENUM last_frozen_line = 0;
+static int Argc;
+static char **Argv;
+static int Argc_last;
+static char **Argv_last;
+static FILE *ofp = NULL;
+static FILE *rejfp = NULL;
+static int filec = 0;
+static LINENUM last_offset = 0;
+static LINENUM maxfuzz = 2;
+
+static int do_defines = 0;
+static char if_defined[128];
+static char not_defined[128];
+static const char else_defined[] = "#else\n";
+static char end_defined[128];
+
+/* function declarations */
+static void reinitialize_almost_everything(void);
+static void get_some_switches(void);
+static void reset_getopt_state(void);
+static LINENUM locate_hunk(LINENUM);
+static void abort_context_hunk(void);
+static void rej_line(int, LINENUM);
+static void abort_hunk(void);
+static void apply_hunk(LINENUM);
+static void init_output(const char *);
+static void init_reject(const char *);
+static void copy_till(LINENUM, int);
+static int spew_output(void);
+static void dump_patch_line(LINENUM, int);
+static void dump_input_line(LINENUM, int);
+static int patch_match(LINENUM, LINENUM, LINENUM);
+static int similar(const char *, const char *, ssize_t);
+static void usage(void);
+
+void re_patch(void);
+void open_patch_file(const char *);
+void set_hunkmax(void);
+int there_is_another_patch(void);
+int another_hunk(void);
+int pch_swap(void);
+char *pfetch(LINENUM);
+ssize_t pch_line_len(LINENUM);
+LINENUM pch_first(void);
+LINENUM pch_ptrn_lines(void);
+LINENUM pch_newfirst(void);
+LINENUM pch_repl_lines(void);
+LINENUM pch_end(void);
+LINENUM pch_context(void);
+LINENUM pch_hunk_beg(void);
+char pch_char(LINENUM);
+void do_ed_script(void);
+
+void re_input(void);
+void scan_input(const char *);
+char *ifetch(LINENUM, int);
+
+char *fetchname(const char *, int *, int);
+char *checked_in(char *);
+LINENUM strtolinenum(char *, char **);
+int backup_file(const char *);
+int move_file(const char *, const char *);
+int copy_file(const char *, const char *);
+void say(const char *, ...);
+__dead void fatal(const char *, ...);
+__dead void pfatal(const char *, ...);
+void ask(const char *, ...);
+char *savestr(const char *);
+void set_signals(int);
+void ignore_signals(void);
+void makedirs(const char *, int);
+__dead void version(void);
+__dead void my_exit(int);
+static void *pch_realloc(void *, size_t, size_t);
+int mkpath(char *);
+char *find_backup_file_name(const char *);
+enum BackupType get_version(const char *);
+
+static off_t i_size;
+static char *i_womp;
+static char **i_ptr;
+static char empty_line[] = { '\0' };
+
+static int tifd = -1;
+static char *tibuf[2];
+static LINENUM tiline[2] = {-1, -1};
+static LINENUM lines_per_buf;
+static int tireclen;
+
+static int rev_in_string(const char *);
+static int reallocate_lines(size_t *);
+static int plan_a(const char *);
+static void plan_b(const char *);
+
+static long p_filesize;
+static LINENUM p_first;
+static LINENUM p_newfirst;
+static LINENUM p_ptrn_lines;
+static LINENUM p_repl_lines;
+static LINENUM p_end = -1;
+static LINENUM p_max;
+static LINENUM p_context = 3;
+static LINENUM p_input_line = 0;
+static char **p_line = NULL;
+static ssize_t *p_len = NULL;
+static char *p_char = NULL;
+static int hunkmax = INITHUNKMAX;
+static int p_indent;
+static LINENUM p_base;
+static LINENUM p_bline;
+static LINENUM p_start;
+static LINENUM p_sline;
+static LINENUM p_hunk_beg;
+static LINENUM p_efake = -1;
+static LINENUM p_bfake = -1;
+static FILE *pfp = NULL;
+static char *bestguess = NULL;
+
+static void grow_hunkmax(void);
+static int intuit_diff_type(void);
+static void next_intuit_at(LINENUM, LINENUM);
+static void skip_to(LINENUM, LINENUM);
+static int pgetline(char **, size_t *, FILE *);
+static char *best_name(const struct FileName *, int);
+static char *posix_name(const struct FileName *, int);
+static size_t num_components(const char *);
+
+static char *patch_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);
+
+static const char *backup_args[] = {
+ "none", "never", "simple", "nil", "existing", "t", "numbered", 0
+};
+static enum BackupType backup_types[] = {
+ BACKUP_NONE, BACKUP_SIMPLE, BACKUP_SIMPLE, BACKUP_NUMBERED_EXISTING,
+ BACKUP_NUMBERED_EXISTING, BACKUP_NUMBERED, BACKUP_NUMBERED
+};
+
+/* implementation */
+
+// ?man patch: apply a diff file to an original
+int
+main(int argc, char *argv[])
+{
+ int error, hunk, failed, i, fd;
+ LINENUM where, newwhere, fuzz, mymaxfuzz;
+ const char *tmpdir;
+ char *v;
+
+ error = 0;
+ where = 0;
+ bufsz = INITLINELEN;
+ if ((buf = malloc(bufsz)) == NULL)
+ pfatal("allocating input buffer");
+ buf[0] = '\0';
+
+ setbuf(stderr, serrbuf);
+ for (i = 0; i < MAXFILEC; i++)
+ filearg[i] = NULL;
+
+ if ((tmpdir = getenv("TMPDIR")) == NULL || *tmpdir == '\0')
+ tmpdir = _PATH_TMP;
+ for (i = strlen(tmpdir) - 1; i > 0 && tmpdir[i] == '/'; i--)
+ ;
+ i++;
+ if (asprintf(&TMPOUTNAME, "%.*s/patchoXXXXXXXXXX", i, tmpdir) == -1)
+ fatal("cannot allocate memory");
+ if ((fd = mkstemp(TMPOUTNAME)) < 0)
+ pfatal("cant create %s", TMPOUTNAME);
+ close(fd);
+
+ if (asprintf(&TMPINNAME, "%.*s/patchiXXXXXXXXXX", i, tmpdir) == -1)
+ fatal("cannot allocate memory");
+ if ((fd = mkstemp(TMPINNAME)) < 0)
+ pfatal("cant create %s", TMPINNAME);
+ close(fd);
+
+ if (asprintf(&TMPREJNAME, "%.*s/patchrXXXXXXXXXX", i, tmpdir) == -1)
+ fatal("cannot allocate memory");
+ if ((fd = mkstemp(TMPREJNAME)) < 0)
+ pfatal("cant create %s", TMPREJNAME);
+ close(fd);
+
+ if (asprintf(&TMPPATNAME, "%.*s/patchpXXXXXXXXXX", i, tmpdir) == -1)
+ fatal("cannot allocate memory");
+ if ((fd = mkstemp(TMPPATNAME)) < 0)
+ pfatal("cant create %s", TMPPATNAME);
+ close(fd);
+
+ v = getenv("SIMPLE_BACKUP_SUFFIX");
+ if (v)
+ simple_backup_suffix = v;
+ else
+ simple_backup_suffix = ORIGEXT;
+
+ if ((v = getenv("PATCH_VERSION_CONTROL")) == NULL)
+ v = getenv("VERSION_CONTROL");
+ if (v != NULL)
+ backup_type = get_version(v);
+
+ Argc = argc;
+ Argv = argv;
+ get_some_switches();
+
+ if (backup_type == BACKUP_UNDEFINED)
+ backup_type = posix ? BACKUP_NONE : BACKUP_NUMBERED_EXISTING;
+
+ set_signals(0);
+
+ for (open_patch_file(filearg[1]); there_is_another_patch(); reinitialize_almost_everything()) {
+ warn_on_invalid_line = 1;
+ if (outname == NULL)
+ outname = savestr(filearg[0]);
+
+ if (diff_type == ED_DIFF) {
+ do_ed_script();
+ continue;
+ }
+ if (!skip_rest_of_patch)
+ init_output(TMPOUTNAME);
+
+ init_reject(TMPREJNAME);
+
+ if (!skip_rest_of_patch)
+ scan_input(filearg[0]);
+
+ hunk = 0;
+ failed = 0;
+ out_of_mem = 0;
+ while (another_hunk()) {
+ hunk++;
+ fuzz = 0;
+ mymaxfuzz = pch_context();
+ if (maxfuzz < mymaxfuzz)
+ mymaxfuzz = maxfuzz;
+ if (!skip_rest_of_patch) {
+ do {
+ where = locate_hunk(fuzz);
+ if (hunk == 1 && where == 0 && !force) {
+ if (!pch_swap()) {
+ if (fuzz == 0)
+ say("Not enough memory to try swapped hunk! Assuming unswapped.\n");
+ continue;
+ }
+ reverse = !reverse;
+ where = locate_hunk(fuzz);
+ if (where == 0) {
+ if (!pch_swap())
+ fatal("lost hunk on alloc error!\n");
+ reverse = !reverse;
+ } else if (noreverse) {
+ if (!pch_swap())
+ fatal("lost hunk on alloc error!\n");
+ reverse = !reverse;
+ say("Ignoring previously applied (or reversed) patch.\n");
+ skip_rest_of_patch = 1;
+ } else if (batch) {
+ if (verbose)
+ say("%seversed (or %spreviously applied) patch detected! %s -R.",
+ reverse ? "R" : "Unr",
+ reverse ? "" : "not ",
+ reverse ? "Assuming" : "Ignoring");
+ } else {
+ ask("%seversed (or %spreviously applied) patch detected! %s -R? [y] ",
+ reverse ? "R" : "Unr",
+ reverse ? "" : "not ",
+ reverse ? "Assume" : "Ignore");
+ if (*buf == 'n') {
+ ask("Apply anyway? [n] ");
+ if (*buf != 'y')
+ skip_rest_of_patch = 1;
+ where = 0;
+ reverse = !reverse;
+ if (!pch_swap())
+ fatal("lost hunk on alloc error!\n");
+ }
+ }
+ }
+ } while (!skip_rest_of_patch && where == 0 && ++fuzz <= mymaxfuzz);
+
+ if (skip_rest_of_patch) {
+ if (ferror(ofp) || fclose(ofp)) {
+ say("Error writing %s\n", TMPOUTNAME);
+ error = 1;
+ }
+ ofp = NULL;
+ }
+ }
+ newwhere = pch_newfirst() + last_offset;
+ if (skip_rest_of_patch) {
+ abort_hunk();
+ failed++;
+ if (verbose)
+ say("Hunk #%d ignored at %ld.\n", hunk, newwhere);
+ } else if (where == 0) {
+ abort_hunk();
+ failed++;
+ if (verbose)
+ say("Hunk #%d failed at %ld.\n", hunk, newwhere);
+ } else {
+ apply_hunk(where);
+ if (verbose) {
+ say("Hunk #%d succeeded at %ld", hunk, newwhere);
+ if (fuzz != 0)
+ say(" with fuzz %ld", fuzz);
+ if (last_offset)
+ say(" (offset %ld line%s)", last_offset, last_offset == 1L ? "" : "s");
+ say(".\n");
+ }
+ }
+ }
+
+ if (out_of_mem && using_plan_a) {
+ Argc = Argc_last;
+ Argv = Argv_last;
+ say("\n\nRan out of memory using Plan A--trying again...\n\n");
+ if (ofp)
+ fclose(ofp);
+ ofp = NULL;
+ if (rejfp)
+ fclose(rejfp);
+ rejfp = NULL;
+ continue;
+ }
+ if (hunk == 0)
+ fatal("internal error: hunk should not be 0\n");
+
+ if (!skip_rest_of_patch && !spew_output()) {
+ say("cant write %s\n", TMPOUTNAME);
+ error = 1;
+ }
+
+ ignore_signals();
+ if (!skip_rest_of_patch) {
+ struct stat statbuf;
+ char *realout = outname;
+
+ if (!check_only) {
+ enum BackupType saved = backup_type;
+ if (failed > 0 && backup_if_mismatch > 0 && backup_type == BACKUP_NONE)
+ backup_type = BACKUP_SIMPLE;
+ if (move_file(TMPOUTNAME, outname) < 0) {
+ toutkeep = 1;
+ realout = TMPOUTNAME;
+ chmod(TMPOUTNAME, filemode);
+ } else
+ chmod(outname, filemode);
+ backup_type = saved;
+
+ if (remove_empty_files && stat(realout, &statbuf) == 0 && statbuf.st_size == 0) {
+ if (verbose)
+ say("Removing %s (empty after patching).\n", realout);
+ unlink(realout);
+ }
+ }
+ }
+ if (ferror(rejfp) || fclose(rejfp)) {
+ say("Error writing %s\n", rejname);
+ error = 1;
+ }
+ rejfp = NULL;
+ if (failed) {
+ error = 1;
+ if (*rejname == '\0') {
+ if (strlcpy(rejname, outname, sizeof(rejname)) >= sizeof(rejname))
+ fatal("filename %s is too long\n", outname);
+ if (strlcat(rejname, REJEXT, sizeof(rejname)) >= sizeof(rejname))
+ fatal("filename %s is too long\n", outname);
+ }
+ if (skip_rest_of_patch) {
+ say("%d out of %d hunks ignored--saving rejects to %s\n", failed, hunk, rejname);
+ } else {
+ say("%d out of %d hunks FAILED -- saving rejects to %s\n", failed, hunk, rejname);
+ }
+ if (!check_only && move_file(TMPREJNAME, rejname) < 0)
+ trejkeep = 1;
+ }
+ set_signals(1);
+ }
+ my_exit(error);
+}
+
+static void
+reset_getopt_state(void)
+{
+#if defined(__GLIBC__) || defined(__linux__)
+ optind = 0;
+#else
+ optreset = 1;
+ optind = 1;
+#endif
+}
+
+static void
+reinitialize_almost_everything(void)
+{
+ re_patch();
+ re_input();
+
+ input_lines = 0;
+ last_frozen_line = 0;
+ filec = 0;
+ if (!out_of_mem) {
+ free(filearg[0]);
+ filearg[0] = NULL;
+ }
+ free(outname);
+ outname = NULL;
+ last_offset = 0;
+ diff_type = 0;
+ free(revision);
+ revision = NULL;
+ reverse = reverse_flag_specified;
+ skip_rest_of_patch = 0;
+ get_some_switches();
+}
+
+static void
+get_some_switches(void)
+{
+ const char *options = "b::B:cCd:D:eEfF:i:lnNo:p:r:RstuvV:x:z:";
+ static struct option longopts[] = {
+ {"backup", no_argument, 0, 'b'},
+ {"backup-if-mismatch", no_argument, &backup_if_mismatch, 1},
+ {"batch", no_argument, 0, 't'},
+ {"check", no_argument, 0, 'C'},
+ {"context", no_argument, 0, 'c'},
+ {"debug", required_argument, 0, 'x'},
+ {"directory", required_argument, 0, 'd'},
+ {"ed", no_argument, 0, 'e'},
+ {"force", no_argument, 0, 'f'},
+ {"forward", no_argument, 0, 'N'},
+ {"fuzz", required_argument, 0, 'F'},
+ {"ifdef", required_argument, 0, 'D'},
+ {"input", required_argument, 0, 'i'},
+ {"ignore-whitespace", no_argument, 0, 'l'},
+ {"no-backup-if-mismatch", no_argument, &backup_if_mismatch, 0},
+ {"normal", no_argument, 0, 'n'},
+ {"output", required_argument, 0, 'o'},
+ {"prefix", required_argument, 0, 'B'},
+ {"quiet", no_argument, 0, 's'},
+ {"reject-file", required_argument, 0, 'r'},
+ {"remove-empty-files", no_argument, 0, 'E'},
+ {"reverse", no_argument, 0, 'R'},
+ {"silent", no_argument, 0, 's'},
+ {"strip", required_argument, 0, 'p'},
+ {"suffix", required_argument, 0, 'z'},
+ {"unified", no_argument, 0, 'u'},
+ {"version", no_argument, 0, 'v'},
+ {"version-control", required_argument, 0, 'V'},
+ {"posix", no_argument, &posix, 1},
+ {NULL, 0, 0, 0}
+ };
+ int ch;
+
+ rejname[0] = '\0';
+ Argc_last = Argc;
+ Argv_last = Argv;
+ if (!Argc)
+ return;
+ reset_getopt_state();
+ while ((ch = getopt_long(Argc, Argv, options, longopts, NULL)) != -1) {
+ switch (ch) {
+ case 'b':
+ if (backup_type == BACKUP_UNDEFINED)
+ backup_type = BACKUP_NUMBERED_EXISTING;
+ if (optarg == NULL)
+ break;
+ if (verbose)
+ say("Warning, the -b suffix option has been obsoleted by the -z option\n");
+ /* FALLTHROUGH */
+ case 'z':
+ simple_backup_suffix = savestr(optarg);
+ break;
+ case 'B':
+ origprae = savestr(optarg);
+ break;
+ case 'c':
+ diff_type = CONTEXT_DIFF;
+ break;
+ case 'C':
+ check_only = 1;
+ break;
+ case 'd':
+ if (chdir(optarg) < 0)
+ pfatal("cant cd to %s", optarg);
+ break;
+ case 'D':
+ do_defines = 1;
+ if (!isalpha((unsigned char)*optarg) && *optarg != '_')
+ fatal("argument to -D is not an identifier\n");
+ snprintf(if_defined, sizeof if_defined, "#ifdef %s\n", optarg);
+ snprintf(not_defined, sizeof not_defined, "#ifndef %s\n", optarg);
+ snprintf(end_defined, sizeof end_defined, "#endif /* %s */\n", optarg);
+ break;
+ case 'e':
+ diff_type = ED_DIFF;
+ break;
+ case 'E':
+ remove_empty_files = 1;
+ break;
+ case 'f':
+ force = 1;
+ break;
+ case 'F':
+ maxfuzz = strtolinenum(optarg, NULL);
+ break;
+ case 'i':
+ free(filearg[1]);
+ filearg[1] = fetchname(optarg, &warn_on_invalid_line, 0);
+ break;
+ case 'l':
+ canonicalize = 1;
+ break;
+ case 'n':
+ diff_type = NORMAL_DIFF;
+ break;
+ case 'N':
+ noreverse = 1;
+ break;
+ case 'o':
+ outname = savestr(optarg);
+ break;
+ case 'p':
+ strippath = (int)strtolinenum(optarg, NULL);
+ break;
+ case 'r':
+ if (strlcpy(rejname, optarg, sizeof(rejname)) >= sizeof(rejname))
+ fatal("reject filename %s too long\n", optarg);
+ break;
+ case 'R':
+ reverse = 1;
+ reverse_flag_specified = 1;
+ break;
+ case 's':
+ verbose = 0;
+ break;
+ case 't':
+ batch = 1;
+ break;
+ case 'u':
+ diff_type = UNI_DIFF;
+ break;
+ case 'v':
+ version();
+ break;
+ case 'V':
+ backup_type = get_version(optarg);
+ break;
+ case 'x':
+#ifdef DEBUGGING
+ debug = (int)strtolinenum(optarg, NULL);
+#endif
+ break;
+ default:
+ if (ch == 0)
+ break;
+ usage();
+ }
+ }
+ Argc -= optind;
+ Argv += optind;
+
+ for (ch = 0; ch < Argc; ch++) {
+ if (filec >= MAXFILEC)
+ usage();
+ filearg[filec++] = savestr(Argv[ch]);
+ }
+}
+
+static void
+usage(void)
+{
+ fprintf(stderr, "usage: patch [-bCcEeflNnRstuv] [-B backup-prefix] [-D symbol] "
+ "[-d directory] [-F max-fuzz] [-i patchfile] [-o out-file] "
+ "[-p strip-count] [-r rej-name] [-V method] [-x number] "
+ "[-z backup-ext] [origfile [patchfile]]\n");
+ my_exit(2);
+}
+
+static LINENUM
+locate_hunk(LINENUM fuzz)
+{
+ LINENUM first_hunk_line = pch_first();
+ LINENUM count = pch_ptrn_lines();
+ LINENUM max_line = input_lines - count + 1;
+ LINENUM line;
+ LINENUM offset;
+
+ if (!count)
+ return first_hunk_line + last_offset;
+
+ if (first_hunk_line + last_offset <= 0)
+ offset = 1 - first_hunk_line;
+ else if (first_hunk_line + last_offset > max_line)
+ offset = max_line - first_hunk_line;
+ else
+ offset = last_offset;
+
+ for (line = first_hunk_line + offset; line <= max_line; line++) {
+ if (patch_match(line, count, fuzz)) {
+ last_offset = line - first_hunk_line;
+ return line;
+ }
+ }
+ for (line = first_hunk_line + offset - 1; line >= 1; line--) {
+ if (patch_match(line, count, fuzz)) {
+ last_offset = line - first_hunk_line;
+ return line;
+ }
+ }
+ return 0;
+}
+
+static int
+patch_match(LINENUM line, LINENUM count, LINENUM fuzz)
+{
+ LINENUM i;
+ LINENUM pat_line;
+ char *str;
+ char *pat;
+ ssize_t len;
+
+ for (i = 1; i <= count; i++) {
+ pat_line = i;
+ if (i <= fuzz)
+ continue;
+ if (i > count - fuzz)
+ continue;
+ str = ifetch(line + i - 1 - fuzz, 0);
+ if (str == NULL)
+ return 0;
+ pat = pfetch(pat_line);
+ len = pch_line_len(pat_line);
+ if (canonicalize) {
+ if (!similar(str, pat, len))
+ return 0;
+ } else if (strncmp(str, pat, len) != 0)
+ return 0;
+ }
+ return 1;
+}
+
+static int
+similar(const char *a, const char *b, ssize_t len)
+{
+ while (len > 0) {
+ if (isspace((unsigned char)*b)) {
+ if (!isspace((unsigned char)*a))
+ return 0;
+ while (len > 0 && isspace((unsigned char)*b)) {
+ b++;
+ len--;
+ }
+ while (isspace((unsigned char)*a) && *a != '\n')
+ a++;
+ } else {
+ if (*a != *b)
+ return 0;
+ a++;
+ b++;
+ len--;
+ }
+ }
+ if (*a == '\n' || *a == '\r') {
+ while (*a == '\n' || *a == '\r')
+ a++;
+ return *a == '\0';
+ }
+ return *a == '\0' || isspace((unsigned char)*a);
+}
+
+static void
+abort_hunk(void)
+{
+ LINENUM i;
+ LINENUM pat_line;
+ char *str;
+ ssize_t len;
+
+ for (i = 1; i <= pch_end(); i++) {
+ pat_line = i;
+ str = pfetch(pat_line);
+ len = pch_line_len(pat_line);
+ rej_line(pat_line, i);
+ }
+}
+
+static void
+rej_line(int pat_line, LINENUM i)
+{
+ char *str = pfetch(pat_line);
+ char ch = pch_char(pat_line);
+ if (rejfp != NULL) {
+ if (ch == ' ')
+ fprintf(rejfp, " %s", str);
+ else
+ fprintf(rejfp, "%c%s", ch, str);
+ }
+}
+
+static void
+abort_context_hunk(void)
+{
+ LINENUM i;
+ for (i = 0; i <= pch_end(); i++) {
+ rej_line(i, i);
+ }
+}
+
+static void
+apply_hunk(LINENUM where)
+{
+ LINENUM old = 1;
+ const LINENUM lastline = pch_ptrn_lines();
+ LINENUM new = lastline + 1;
+#define OUTSIDE 0
+#define IN_IFNDEF 1
+#define IN_IFDEF 2
+#define IN_ELSE 3
+ int def_state = OUTSIDE;
+ const LINENUM pat_end = pch_end();
+
+ where--;
+ while (pch_char(new) == '=' || pch_char(new) == '\n')
+ new++;
+
+ while (old <= lastline) {
+ if (pch_char(old) == '-') {
+ copy_till(where + old - 1, 0);
+ if (do_defines) {
+ if (def_state == OUTSIDE) {
+ fputs(not_defined, ofp);
+ def_state = IN_IFNDEF;
+ } else if (def_state == IN_IFDEF) {
+ fputs(else_defined, ofp);
+ def_state = IN_ELSE;
+ }
+ fputs(pfetch(old), ofp);
+ }
+ last_frozen_line++;
+ old++;
+ } else if (new > pat_end) {
+ break;
+ } else if (pch_char(new) == '+') {
+ copy_till(where + old - 1, 0);
+ if (do_defines) {
+ if (def_state == IN_IFNDEF) {
+ fputs(else_defined, ofp);
+ def_state = IN_ELSE;
+ } else if (def_state == OUTSIDE) {
+ fputs(if_defined, ofp);
+ def_state = IN_IFDEF;
+ }
+ }
+ fputs(pfetch(new), ofp);
+ new++;
+ } else if (pch_char(new) != pch_char(old)) {
+ say("Out-of-sync patch, lines %ld,%ld--mangled text or line numbers, maybe?\n",
+ pch_hunk_beg() + old,
+ pch_hunk_beg() + new);
+ my_exit(2);
+ } else if (pch_char(new) == '!') {
+ copy_till(where + old - 1, 0);
+ if (do_defines) {
+ fputs(not_defined, ofp);
+ def_state = IN_IFNDEF;
+ }
+ while (pch_char(old) == '!') {
+ if (do_defines) {
+ fputs(pfetch(old), ofp);
+ }
+ last_frozen_line++;
+ old++;
+ }
+ if (do_defines) {
+ fputs(else_defined, ofp);
+ def_state = IN_ELSE;
+ }
+ while (pch_char(new) == '!') {
+ fputs(pfetch(new), ofp);
+ new++;
+ }
+ } else {
+ if (pch_char(new) != ' ')
+ fatal("Internal error: expected ' '\n");
+ old++;
+ new++;
+ if (do_defines && def_state != OUTSIDE) {
+ fputs(end_defined, ofp);
+ def_state = OUTSIDE;
+ }
+ }
+ }
+ if (new <= pat_end && pch_char(new) == '+') {
+ copy_till(where + old - 1, 0);
+ if (do_defines) {
+ if (def_state == OUTSIDE) {
+ fputs(if_defined, ofp);
+ def_state = IN_IFDEF;
+ } else if (def_state == IN_IFNDEF) {
+ fputs(else_defined, ofp);
+ def_state = IN_ELSE;
+ }
+ }
+ while (new <= pat_end && pch_char(new) == '+') {
+ fputs(pfetch(new), ofp);
+ new++;
+ }
+ }
+ if (do_defines && def_state != OUTSIDE) {
+ fputs(end_defined, ofp);
+ }
+#undef OUTSIDE
+#undef IN_IFNDEF
+#undef IN_IFDEF
+#undef IN_ELSE
+}
+
+static void
+dump_input_line(LINENUM line, int write_newline)
+{
+ char *s = ifetch(line, 0);
+ if (s == NULL)
+ return;
+ for (; *s != '\n' && *s != '\0'; s++)
+ putc(*s, ofp);
+ if (write_newline)
+ putc('\n', ofp);
+}
+
+static void
+copy_till(LINENUM line, int end)
+{
+ if (last_frozen_line > line)
+ fatal("misordered hunks! output would be garbled\n");
+ while (last_frozen_line < line) {
+ if (++last_frozen_line == line && end)
+ dump_input_line(last_frozen_line, !last_line_missing_eol);
+ else
+ dump_input_line(last_frozen_line, 1);
+ }
+}
+
+static int
+spew_output(void)
+{
+ if (input_lines)
+ copy_till(input_lines, 1);
+ if (ferror(ofp) || fclose(ofp))
+ return 0;
+ ofp = NULL;
+ return 1;
+}
+
+static void
+init_output(const char *name)
+{
+ ofp = fopen(name, "w");
+ if (ofp == NULL)
+ pfatal("cant create %s", name);
+}
+
+static void
+init_reject(const char *name)
+{
+ rejfp = fopen(name, "w");
+ if (rejfp == NULL)
+ pfatal("cant create %s", name);
+}
+
+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 = 1;
+ close(tifd);
+ tifd = -1;
+ free(tibuf[0]);
+ free(tibuf[1]);
+ tibuf[0] = tibuf[1] = NULL;
+ tiline[0] = tiline[1] = -1;
+ tireclen = 0;
+ }
+}
+
+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 int
+reallocate_lines(size_t *lines_allocated)
+{
+ char **p;
+ size_t new_size;
+
+ new_size = *lines_allocated * 3 / 2;
+ p = pch_realloc(i_ptr, new_size + 2, sizeof(char *));
+ if (p == NULL) {
+ munmap(i_womp, i_size);
+ i_womp = NULL;
+ free(i_ptr);
+ i_ptr = NULL;
+ *lines_allocated = 0;
+ return 0;
+ }
+ *lines_allocated = new_size;
+ i_ptr = p;
+ return 1;
+}
+
+static int
+plan_a(const char *filename)
+{
+ int ifd, statfailed, devnull, pstat;
+ char *p, *s, *lbuf;
+ struct stat filestat;
+ off_t i;
+ ptrdiff_t sz;
+ size_t iline, lines_allocated, lbufsz;
+ pid_t pid;
+ char *argp[4] = {NULL};
+
+#ifdef DEBUGGING
+ if (debug & 8)
+ return 0;
+#endif
+
+ if (filename == NULL || *filename == '\0')
+ return 0;
+
+ statfailed = stat(filename, &filestat);
+ if (statfailed && ok_to_create_file) {
+ if (verbose)
+ say("(Creating file %s...)\n", filename);
+ if (check_only)
+ return 1;
+ makedirs(filename, 1);
+ close(creat(filename, 0666));
+ statfailed = stat(filename, &filestat);
+ }
+ if (statfailed && check_only)
+ fatal("%s not found, -C mode, cant probe further\n", filename);
+
+ if (statfailed || (filestat.st_mode & 0222) == 0 ||
+ ((filestat.st_mode & 0022) == 0 && filestat.st_uid != getuid())) {
+ char *filebase, *filedir;
+ struct stat cstat;
+ char *tmp_filename1, *tmp_filename2;
+
+ tmp_filename1 = strdup(filename);
+ tmp_filename2 = strdup(filename);
+ if (tmp_filename1 == NULL || tmp_filename2 == NULL)
+ fatal("strdupping filename");
+ filebase = basename(tmp_filename1);
+ filedir = dirname(tmp_filename2);
+
+ lbufsz = INITLINELEN;
+ if ((lbuf = malloc(bufsz)) == NULL)
+ pfatal("allocating line buffer");
+ lbuf[0] = '\0';
+
+#define try(f, a1, a2, a3) \
+ (snprintf(lbuf, lbufsz, f, a1, a2, a3), stat(lbuf, &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)) {
+ if (!statfailed) {
+ if ((filestat.st_mode & 0222) != 0)
+ fatal("file %s seems to be locked by somebody else under RCS\n", filename);
+ if (verbose)
+ say("Comparing file %s to default RCS version...\n", filename);
+ switch (pid = fork()) {
+ case -1:
+ fatal("cant fork: %s\n", strerror(errno));
+ case 0:
+ devnull = open("/dev/null", O_RDONLY);
+ if (devnull == -1)
+ fatal("cant open /dev/null: %s", strerror(errno));
+ dup2(devnull, STDOUT_FILENO);
+ argp[0] = __UNCONST(RCSDIFF);
+ argp[1] = __UNCONST(filename);
+ execv(RCSDIFF, argp);
+ exit(127);
+ }
+ pid = waitpid(pid, &pstat, 0);
+ if (pid == -1 || WEXITSTATUS(pstat) != 0)
+ fatal("cant check out file %s: differs from default RCS version\n", filename);
+ }
+ if (verbose)
+ say("Checking out file %s from RCS...\n", filename);
+ switch (pid = fork()) {
+ case -1:
+ fatal("cant fork: %s\n", strerror(errno));
+ case 0:
+ argp[0] = __UNCONST(CHECKOUT);
+ argp[1] = __UNCONST("-l");
+ argp[2] = __UNCONST(filename);
+ execv(CHECKOUT, argp);
+ exit(127);
+ }
+ pid = waitpid(pid, &pstat, 0);
+ if (pid == -1 || WEXITSTATUS(pstat) != 0 || stat(filename, &filestat))
+ fatal("cant check out file %s from RCS\n", filename);
+ } else if (statfailed) {
+ fatal("cant find %s\n", filename);
+ }
+#undef try
+ free(lbuf);
+ free(tmp_filename1);
+ free(tmp_filename2);
+ }
+
+ filemode = filestat.st_mode;
+ if (!S_ISREG(filemode))
+ fatal("%s is not a normal file--cant patch\n", filename);
+ i_size = filestat.st_size;
+ if (out_of_mem) {
+ set_hunkmax();
+ out_of_mem = 0;
+ return 0;
+ }
+ if ((uintmax_t)i_size > (uintmax_t)SIZE_MAX) {
+ say("block too large to mmap\n");
+ return 0;
+ }
+ if ((ifd = open(filename, O_RDONLY)) < 0)
+ pfatal("cant open file %s", filename);
+
+ if (i_size) {
+ 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 0;
+ }
+ } else
+ i_womp = NULL;
+
+ close(ifd);
+ if (i_size)
+ madvise(i_womp, i_size, MADV_SEQUENTIAL);
+
+ lines_allocated = i_size / 25;
+ if (lines_allocated < 100)
+ lines_allocated = 100;
+
+ if (!reallocate_lines(&lines_allocated))
+ return 0;
+
+ iline = 1;
+ i_ptr[iline] = i_womp;
+ 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 0;
+ }
+ i_ptr[++iline] = s + 1;
+ }
+ }
+ if (i_size > 0 && i_womp[i_size - 1] != '\n') {
+ last_line_missing_eol = 1;
+ 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 0;
+ }
+ memcpy(p, i_ptr[iline], sz);
+ p[sz] = '\n';
+ i_ptr[iline] = p;
+ i_ptr[++iline] = empty_line;
+ } else
+ last_line_missing_eol = 0;
+
+ input_lines = iline - 1;
+
+ if (revision != NULL) {
+ if (!rev_in_string(i_womp)) {
+ if (force) {
+ if (verbose)
+ say("Warning: this file doesnt appear to be the %s version--patching anyway\n", revision);
+ } else if (batch) {
+ fatal("this file doesnt appear to be the %s version--aborting\n", revision);
+ } else {
+ ask("This file doesnt 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 1;
+}
+
+static void
+plan_b(const char *filename)
+{
+ FILE *ifp;
+ size_t i = 0, j, maxlen = 1;
+ char *p;
+ int found_revision = (revision == NULL);
+
+ using_plan_a = 0;
+ if ((ifp = fopen(filename, "r")) == NULL)
+ pfatal("cant open file %s", filename);
+ unlink(TMPINNAME);
+ if ((tifd = open(TMPINNAME, O_EXCL | O_CREAT | O_WRONLY, 0666)) < 0)
+ pfatal("cant open file %s", TMPINNAME);
+ while (getline(&buf, &bufsz, ifp) != -1) {
+ if (revision != NULL && !found_revision && rev_in_string(buf))
+ found_revision = 1;
+ if ((i = strlen(buf)) > maxlen)
+ maxlen = i;
+ }
+ 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 doesnt appear to be the %s version--patching anyway\n", revision);
+ } else if (batch) {
+ fatal("this file doesnt appear to be the %s version--aborting\n", revision);
+ } else {
+ ask("This file doesnt 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);
+ 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) {
+ if (write(tifd, tibuf[0], BUFFERSIZE) < BUFFERSIZE)
+ pfatal("cant 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("cant write temp file");
+ }
+ break;
+ }
+ j = strlen(p);
+ if (j == 0 || p[j - 1] != '\n')
+ p[j] = '\n';
+ }
+ fclose(ifp);
+ close(tifd);
+ if ((tifd = open(TMPINNAME, O_RDONLY)) < 0)
+ pfatal("cant reopen file %s", TMPINNAME);
+}
+
+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 = 0;
+ }
+ 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);
+ }
+}
+
+static int
+rev_in_string(const char *string)
+{
+ const char *s;
+ size_t patlen;
+
+ if (revision == NULL)
+ return 1;
+ patlen = strlen(revision);
+ if (strnEQ(string, revision, patlen) && isspace((unsigned char)string[patlen]))
+ return 1;
+ for (s = string; *s; s++) {
+ if (isspace((unsigned char)*s) && strnEQ(s + 1, revision, patlen) &&
+ isspace((unsigned char)s[patlen + 1]))
+ return 1;
+ }
+ return 0;
+}
+
+void
+re_patch(void)
+{
+ p_first = 0;
+ p_newfirst = 0;
+ p_ptrn_lines = 0;
+ p_repl_lines = 0;
+ p_end = (LINENUM)-1;
+ p_max = 0;
+ p_indent = 0;
+}
+
+void
+open_patch_file(const char *filename)
+{
+ struct stat filestat;
+
+ if (filename == NULL || *filename == '\0' || strEQ(filename, "-")) {
+ pfp = fopen(TMPPATNAME, "w");
+ if (pfp == NULL)
+ pfatal("cant create %s", TMPPATNAME);
+ while (getline(&buf, &bufsz, stdin) != -1)
+ fprintf(pfp, "%s", buf);
+ if (ferror(pfp) || fclose(pfp))
+ pfatal("cant write %s", TMPPATNAME);
+ filename = TMPPATNAME;
+ }
+ pfp = fopen(filename, "r");
+ if (pfp == NULL)
+ pfatal("patch file %s not found", filename);
+ fstat(fileno(pfp), &filestat);
+ p_filesize = filestat.st_size;
+ next_intuit_at(0L, 1L);
+ set_hunkmax();
+}
+
+void
+set_hunkmax(void)
+{
+ if (p_line == NULL)
+ p_line = calloc((size_t)hunkmax, sizeof(char *));
+ if (p_len == NULL)
+ p_len = calloc((size_t)hunkmax, sizeof(ssize_t));
+ if (p_char == NULL)
+ p_char = calloc((size_t)hunkmax, sizeof(char));
+}
+
+static void
+grow_hunkmax(void)
+{
+ int new_hunkmax;
+ char **new_p_line;
+ ssize_t *new_p_len;
+ char *new_p_char;
+
+ new_hunkmax = hunkmax * 2;
+ if (p_line == NULL || p_len == NULL || p_char == NULL)
+ fatal("Internal memory allocation error\n");
+
+ new_p_line = pch_realloc(p_line, new_hunkmax, sizeof(char *));
+ if (new_p_line == NULL)
+ free(p_line);
+ new_p_len = pch_realloc(p_len, new_hunkmax, sizeof(ssize_t));
+ if (new_p_len == NULL)
+ free(p_len);
+ new_p_char = pch_realloc(p_char, new_hunkmax, sizeof(char));
+ if (new_p_char == NULL)
+ free(p_char);
+
+ p_char = new_p_char;
+ p_len = new_p_len;
+ p_line = new_p_line;
+
+ if (p_line != NULL && p_len != NULL && p_char != NULL) {
+ hunkmax = new_hunkmax;
+ return;
+ }
+
+ if (!using_plan_a)
+ fatal("out of memory\n");
+ out_of_mem = 1;
+}
+
+int
+there_is_another_patch(void)
+{
+ int exists = 0;
+
+ if (p_base != 0L && p_base >= p_filesize) {
+ if (verbose)
+ say("done\n");
+ return 0;
+ }
+ if (verbose)
+ say("Hmm...");
+ diff_type = intuit_diff_type();
+ if (!diff_type) {
+ if (p_base != 0L) {
+ if (verbose)
+ say(" Ignoring the trailing garbage.\ndone\n");
+ } else
+ say(" I cant seem to find a patch in there anywhere\n");
+ return 0;
+ }
+ if (verbose) {
+ say(" %sooks like %s to me...\n",
+ (p_base == 0L ? "L" : "The next patch l"),
+ diff_type == UNI_DIFF ? "a unified diff" :
+ diff_type == CONTEXT_DIFF ? "a context diff" :
+ diff_type == NEW_CONTEXT_DIFF ? "a new-style context diff" :
+ diff_type == NORMAL_DIFF ? "a normal diff" : "an ed script");
+ }
+ if (p_indent && verbose)
+ say("(Patch is indented %d space%s.)\n", p_indent, p_indent == 1 ? "" : "s");
+ skip_to(p_start, p_sline);
+ while (filearg[0] == NULL) {
+ if (force || batch) {
+ say("No file to patch. Skipping...\n");
+ filearg[0] = savestr(bestguess);
+ skip_rest_of_patch = 1;
+ return 1;
+ }
+ ask("File to patch: ");
+ if (*buf != '\n') {
+ free(bestguess);
+ bestguess = savestr(buf);
+ filearg[0] = fetchname(buf, &exists, 0);
+ }
+ if (!exists) {
+ ask("No file found--skip this patch? [n] ");
+ if (*buf != 'y')
+ continue;
+ if (verbose)
+ say("Skipping patch...\n");
+ free(filearg[0]);
+ filearg[0] = fetchname(bestguess, &exists, 0);
+ skip_rest_of_patch = 1;
+ return 1;
+ }
+ }
+ return 1;
+}
+
+static int
+intuit_diff_type(void)
+{
+ long this_line = 0, previous_line;
+ long first_command_line = -1;
+ LINENUM fcl_line = -1;
+ int last_line_was_command = 0, this_is_a_command = 0;
+ int stars_last_line = 0, stars_this_line = 0;
+ char *s, *t;
+ int indent, retval;
+ struct FileName names[MAX_FILE];
+
+ memset(names, 0, sizeof(names));
+ ok_to_create_file = 0;
+ fseek(pfp, p_base, SEEK_SET);
+ p_input_line = p_bline - 1;
+ for (;;) {
+ previous_line = this_line;
+ last_line_was_command = this_is_a_command;
+ stars_last_line = stars_this_line;
+ this_line = ftell(pfp);
+ indent = 0;
+ p_input_line++;
+ if (getline(&buf, &bufsz, pfp) == -1) {
+ if (first_command_line >= 0L) {
+ p_start = first_command_line;
+ p_sline = fcl_line;
+ retval = ED_DIFF;
+ goto scan_exit;
+ } else {
+ p_start = this_line;
+ p_sline = p_input_line;
+ retval = 0;
+ goto scan_exit;
+ }
+ }
+ for (s = buf; *s == ' ' || *s == '\t' || *s == 'X'; s++) {
+ if (*s == '\t')
+ indent += 8 - (indent % 8);
+ else
+ indent++;
+ }
+ for (t = s; isdigit((unsigned char)*t) || *t == ','; t++)
+ ;
+ this_is_a_command = (isdigit((unsigned char)*s) && (*t == 'd' || *t == 'c' || *t == 'a'));
+ if (first_command_line < 0L && this_is_a_command) {
+ first_command_line = this_line;
+ fcl_line = p_input_line;
+ p_indent = indent;
+ }
+ if (!stars_last_line && strnEQ(s, "*** ", 4)) {
+ names[OLD_FILE].path = fetchname(s + 4, &names[OLD_FILE].exists, strippath);
+ } else if (strnEQ(s, "--- ", 4)) {
+ names[NEW_FILE].path = fetchname(s + 4, &names[NEW_FILE].exists, strippath);
+ } else if (strnEQ(s, "+++ ", 4)) {
+ names[OLD_FILE].path = fetchname(s + 4, &names[OLD_FILE].exists, strippath);
+ } else if (strnEQ(s, "Index:", 6)) {
+ names[INDEX_FILE].path = fetchname(s + 6, &names[INDEX_FILE].exists, strippath);
+ } else if (strnEQ(s, "Prereq:", 7)) {
+ for (t = s + 7; isspace((unsigned char)*t); t++)
+ ;
+ revision = savestr(t);
+ for (t = revision; *t && !isspace((unsigned char)*t); t++)
+ ;
+ *t = '\0';
+ if (*revision == '\0') {
+ free(revision);
+ revision = NULL;
+ }
+ }
+ if ((!diff_type || diff_type == ED_DIFF) && first_command_line >= 0L && strEQ(s, ".\n")) {
+ p_indent = indent;
+ p_start = first_command_line;
+ p_sline = fcl_line;
+ retval = ED_DIFF;
+ goto scan_exit;
+ }
+ if ((!diff_type || diff_type == UNI_DIFF) && strnEQ(s, "@@ -", 4)) {
+ if (strnEQ(s + 4, "0,0", 3))
+ ok_to_create_file = 1;
+ p_indent = indent;
+ p_start = this_line;
+ p_sline = p_input_line;
+ retval = UNI_DIFF;
+ goto scan_exit;
+ }
+ stars_this_line = strnEQ(s, "********", 8);
+ if ((!diff_type || diff_type == CONTEXT_DIFF) && stars_last_line && strnEQ(s, "*** ", 4)) {
+ if (atol(s + 4) == 0)
+ ok_to_create_file = 1;
+ while (*s != '\n')
+ s++;
+ p_indent = indent;
+ p_start = previous_line;
+ p_sline = p_input_line - 1;
+ retval = (*(s - 1) == '*' ? NEW_CONTEXT_DIFF : CONTEXT_DIFF);
+ goto scan_exit;
+ }
+ if ((!diff_type || diff_type == NORMAL_DIFF) && last_line_was_command &&
+ (strnEQ(s, "< ", 2) || strnEQ(s, "> ", 2))) {
+ p_start = previous_line;
+ p_sline = p_input_line - 1;
+ p_indent = indent;
+ retval = NORMAL_DIFF;
+ goto scan_exit;
+ }
+ }
+scan_exit:
+ if (retval == UNI_DIFF) {
+ struct FileName tmp = names[OLD_FILE];
+ names[OLD_FILE] = names[NEW_FILE];
+ names[NEW_FILE] = tmp;
+ }
+ if (filearg[0] == NULL) {
+ if (posix)
+ filearg[0] = posix_name(names, ok_to_create_file);
+ else {
+ if (names[OLD_FILE].path != NULL || names[NEW_FILE].path != NULL) {
+ free(names[INDEX_FILE].path);
+ names[INDEX_FILE].path = NULL;
+ }
+ filearg[0] = best_name(names, ok_to_create_file);
+ }
+ }
+ free(bestguess);
+ bestguess = NULL;
+ if (filearg[0] != NULL)
+ bestguess = savestr(filearg[0]);
+ else if (!ok_to_create_file) {
+ if (posix)
+ bestguess = posix_name(names, 1);
+ else
+ bestguess = best_name(names, 1);
+ }
+ free(names[OLD_FILE].path);
+ free(names[NEW_FILE].path);
+ free(names[INDEX_FILE].path);
+ return retval;
+}
+
+static void
+next_intuit_at(LINENUM file_pos, LINENUM file_line)
+{
+ p_base = file_pos;
+ p_bline = file_line;
+}
+
+static void
+skip_to(LINENUM file_pos, LINENUM file_line)
+{
+ int ret;
+
+ if (p_base > file_pos)
+ fatal("Internal error: seek %ld>%ld\n", p_base, file_pos);
+ if (verbose && p_base < file_pos) {
+ fseek(pfp, p_base, SEEK_SET);
+ say("The text leading up to this was:\n--------------------------\n");
+ while (ftell(pfp) < file_pos) {
+ ret = getline(&buf, &bufsz, pfp);
+ if (ret == -1)
+ fatal("Unexpected end of file\n");
+ say("|%s", buf);
+ }
+ say("--------------------------\n");
+ } else
+ fseek(pfp, file_pos, SEEK_SET);
+ p_input_line = file_line - 1;
+}
+
+__dead static void
+malformed(void)
+{
+ fatal("malformed patch at line %ld: %s", p_input_line, buf);
+}
+
+static LINENUM
+getlinenum(const char *s)
+{
+ LINENUM l = (LINENUM)atol(s);
+ if (l < 0) {
+ l = 0;
+ malformed();
+ }
+ return l;
+}
+
+static LINENUM
+getskiplinenum(char **p)
+{
+ char *s = *p;
+ LINENUM l = getlinenum(s);
+ while (isdigit((unsigned char)*s))
+ s++;
+ *p = s;
+ return l;
+}
+
+static int
+remove_special_line(void)
+{
+ int c;
+
+ c = fgetc(pfp);
+ if (c == '\\') {
+ do {
+ c = fgetc(pfp);
+ } while (c != EOF && c != '\n');
+ return 1;
+ }
+ if (c != EOF)
+ fseek(pfp, -1L, SEEK_CUR);
+ return 0;
+}
+
+int
+another_hunk(void)
+{
+ long line_beginning;
+ LINENUM repl_beginning;
+ LINENUM fillcnt;
+ LINENUM fillsrc;
+ LINENUM filldst;
+ int ptrn_spaces_eaten;
+ int repl_could_be_missing;
+ int repl_missing;
+ long repl_backtrack_position;
+ LINENUM repl_patch_line;
+ LINENUM ptrn_copiable;
+ char *s;
+ int context = 0;
+ int ret;
+
+ while (p_end >= 0) {
+ if (p_end == p_efake)
+ p_end = p_bfake;
+ else
+ free(p_line[p_end]);
+ p_end--;
+ }
+ p_efake = -1;
+ p_max = hunkmax;
+
+ if (diff_type == CONTEXT_DIFF || diff_type == NEW_CONTEXT_DIFF) {
+ line_beginning = ftell(pfp);
+ repl_beginning = 0;
+ fillcnt = 0;
+ fillsrc = 0;
+ filldst = 0;
+ ptrn_spaces_eaten = 0;
+ repl_could_be_missing = 1;
+ repl_missing = 0;
+ repl_backtrack_position = 0;
+ repl_patch_line = 0;
+ ptrn_copiable = 0;
+
+ ret = pgetline(&buf, &bufsz, pfp);
+ p_input_line++;
+ if (ret == -1 || strnNE(buf, "********", 8)) {
+ next_intuit_at(line_beginning, p_input_line);
+ return 0;
+ }
+ p_context = 100;
+ p_hunk_beg = p_input_line + 1;
+ while (p_end < p_max) {
+ ret = pgetline(&buf, &bufsz, pfp);
+ p_input_line++;
+ if (ret == -1) {
+ if (repl_beginning && repl_could_be_missing) {
+ repl_missing = 1;
+ goto hunk_done;
+ }
+ fatal("unexpected end of file in patch\n");
+ }
+ p_end++;
+ if (p_end >= hunkmax)
+ fatal("Internal error: hunk larger than hunk buffer size");
+ p_char[p_end] = *buf;
+ p_line[p_end] = NULL;
+ switch (*buf) {
+ case '*':
+ if (strnEQ(buf, "********", 8)) {
+ if (repl_beginning && repl_could_be_missing) {
+ repl_missing = 1;
+ goto hunk_done;
+ } else
+ fatal("unexpected end of hunk at line %ld\n", p_input_line);
+ }
+ if (p_end != 0) {
+ if (repl_beginning && repl_could_be_missing) {
+ repl_missing = 1;
+ goto hunk_done;
+ }
+ fatal("unexpected *** at line %ld: %s", p_input_line, buf);
+ }
+ context = 0;
+ p_line[p_end] = savestr(buf);
+ if (out_of_mem) {
+ p_end--;
+ return 0;
+ }
+ for (s = buf; *s && !isdigit((unsigned char)*s); s++)
+ ;
+ if (!*s)
+ malformed();
+ if (strnEQ(s, "0,0", 3))
+ memmove(s, s + 2, strlen(s + 2) + 1);
+ p_first = getskiplinenum(&s);
+ if (*s == ',') {
+ for (; *s && !isdigit((unsigned char)*s); s++)
+ ;
+ if (!*s)
+ malformed();
+ p_ptrn_lines = (getlinenum(s)) - p_first + 1;
+ if (p_ptrn_lines < 0)
+ malformed();
+ } else if (p_first)
+ p_ptrn_lines = 1;
+ else {
+ p_ptrn_lines = 0;
+ p_first = 1;
+ }
+ if (p_first >= LINENUM_MAX - p_ptrn_lines || p_ptrn_lines >= LINENUM_MAX - 6)
+ malformed();
+ p_max = p_ptrn_lines + 6;
+ while (p_max >= hunkmax)
+ grow_hunkmax();
+ p_max = hunkmax;
+ break;
+ case '-':
+ if (buf[1] == '-') {
+ if (repl_beginning || (p_end != p_ptrn_lines + 1 + (p_char[p_end - 1] == '\n'))) {
+ if (p_end == 1) {
+ p_end = p_ptrn_lines + 1;
+ fillsrc = p_end + 1;
+ filldst = 1;
+ fillcnt = p_ptrn_lines;
+ } else {
+ if (repl_beginning) {
+ if (repl_could_be_missing) {
+ repl_missing = 1;
+ goto hunk_done;
+ }
+ fatal("duplicate \"---\" at line %ld\n", p_input_line);
+ } else {
+ fatal("premature/overdue \"---\" at line %ld\n", p_input_line);
+ }
+ }
+ }
+ repl_beginning = p_end;
+ repl_backtrack_position = ftell(pfp);
+ repl_patch_line = p_input_line;
+ p_line[p_end] = savestr(buf);
+ if (out_of_mem) {
+ p_end--;
+ return 0;
+ }
+ p_char[p_end] = '=';
+ for (s = buf; *s && !isdigit((unsigned char)*s); s++)
+ ;
+ if (!*s)
+ malformed();
+ p_newfirst = getskiplinenum(&s);
+ if (*s == ',') {
+ for (; *s && !isdigit((unsigned char)*s); s++)
+ ;
+ if (!*s)
+ malformed();
+ p_repl_lines = (getlinenum(s)) - p_newfirst + 1;
+ if (p_repl_lines < 0)
+ malformed();
+ } else if (p_newfirst)
+ p_repl_lines = 1;
+ else {
+ p_repl_lines = 0;
+ p_newfirst = 1;
+ }
+ if (p_newfirst >= LINENUM_MAX - p_repl_lines || p_repl_lines >= LINENUM_MAX - p_end)
+ malformed();
+ p_max = p_repl_lines + p_end;
+ if (p_max > MAXHUNKSIZE)
+ fatal("hunk too large at line %ld\n", p_input_line);
+ while (p_max >= hunkmax)
+ grow_hunkmax();
+ if (p_repl_lines != ptrn_copiable && (p_context != 0 || p_repl_lines != 1))
+ repl_could_be_missing = 0;
+ break;
+ }
+ goto change_line;
+ case '+':
+ case '!':
+ repl_could_be_missing = 0;
+ change_line:
+ if (buf[1] == '\n' && canonicalize)
+ strlcpy(buf + 1, " \n", bufsz - 1);
+ if (!isspace((unsigned char)buf[1]) && buf[1] != '>' && buf[1] != '<' &&
+ repl_beginning && repl_could_be_missing) {
+ repl_missing = 1;
+ goto hunk_done;
+ }
+ if (context >= 0) {
+ if (context < p_context)
+ p_context = context;
+ context = -1000;
+ }
+ p_line[p_end] = savestr(buf + 2);
+ if (out_of_mem) {
+ p_end--;
+ return 0;
+ }
+ if (p_end == p_ptrn_lines) {
+ if (remove_special_line()) {
+ int length = strlen(p_line[p_end]) - 1;
+ (p_line[p_end])[length] = 0;
+ }
+ }
+ break;
+ case '\t':
+ case '\n':
+ if (repl_beginning && repl_could_be_missing &&
+ (!ptrn_spaces_eaten || diff_type == NEW_CONTEXT_DIFF)) {
+ repl_missing = 1;
+ goto hunk_done;
+ }
+ p_line[p_end] = savestr(buf);
+ if (out_of_mem) {
+ p_end--;
+ return 0;
+ }
+ if (p_end != p_ptrn_lines + 1) {
+ ptrn_spaces_eaten |= (repl_beginning != 0);
+ context++;
+ if (!repl_beginning)
+ ptrn_copiable++;
+ p_char[p_end] = ' ';
+ }
+ break;
+ case ' ':
+ if (!isspace((unsigned char)buf[1]) && repl_beginning && repl_could_be_missing) {
+ repl_missing = 1;
+ goto hunk_done;
+ }
+ context++;
+ if (!repl_beginning)
+ ptrn_copiable++;
+ p_line[p_end] = savestr(buf + 2);
+ if (out_of_mem) {
+ p_end--;
+ return 0;
+ }
+ break;
+ default:
+ if (repl_beginning && repl_could_be_missing) {
+ repl_missing = 1;
+ goto hunk_done;
+ }
+ malformed();
+ }
+ if (p_line[p_end])
+ p_len[p_end] = strlen(p_line[p_end]);
+ else
+ p_len[p_end] = 0;
+ }
+
+hunk_done:
+ if (p_end >= 0 && !repl_beginning)
+ fatal("no --- found in patch at line %ld\n", pch_hunk_beg());
+
+ if (repl_missing) {
+ p_input_line = repl_patch_line;
+ for (p_end--; p_end > repl_beginning; p_end--)
+ free(p_line[p_end]);
+ fseek(pfp, repl_backtrack_position, SEEK_SET);
+
+ if (!p_context && p_repl_lines == 1) {
+ p_repl_lines = 0;
+ p_max--;
+ }
+ fillsrc = 1;
+ filldst = repl_beginning + 1;
+ fillcnt = p_repl_lines;
+ p_end = p_max;
+ } else if (!p_context && fillcnt == 1) {
+ while (filldst < p_end) {
+ p_line[filldst] = p_line[filldst + 1];
+ p_char[filldst] = p_char[filldst + 1];
+ p_len[filldst] = p_len[filldst + 1];
+ filldst++;
+ }
+ p_end--;
+ p_first++;
+ fillcnt = 0;
+ p_ptrn_lines = 0;
+ }
+ if (diff_type == CONTEXT_DIFF && (fillcnt || (p_first > 1 && ptrn_copiable > 2 * p_context))) {
+ diff_type = NEW_CONTEXT_DIFF;
+ }
+ if (fillcnt) {
+ p_bfake = filldst;
+ p_efake = filldst + fillcnt - 1;
+ while (fillcnt-- > 0) {
+ while (fillsrc <= p_end && p_char[fillsrc] != ' ')
+ fillsrc++;
+ if (fillsrc > p_end)
+ fatal("replacement text mangled in hunk at line %ld\n", p_hunk_beg);
+ p_line[filldst] = p_line[fillsrc];
+ p_char[filldst] = p_char[fillsrc];
+ p_len[filldst] = p_len[fillsrc];
+ fillsrc++;
+ filldst++;
+ }
+ while (fillsrc <= p_end && fillsrc != repl_beginning && p_char[fillsrc] != ' ')
+ fillsrc++;
+ if (fillsrc != p_end + 1 && fillsrc != repl_beginning)
+ malformed();
+ if (filldst != p_end + 1 && filldst != repl_beginning)
+ malformed();
+ }
+ if (p_line[p_end] != NULL) {
+ if (remove_special_line()) {
+ p_len[p_end] -= 1;
+ (p_line[p_end])[p_len[p_end]] = 0;
+ }
+ }
+ } else if (diff_type == UNI_DIFF) {
+ LINENUM fillold;
+ LINENUM fillnew;
+ char ch;
+
+ line_beginning = ftell(pfp);
+ ret = pgetline(&buf, &bufsz, pfp);
+ p_input_line++;
+ if (ret == -1 || strnNE(buf, "@@ -", 4)) {
+ next_intuit_at(line_beginning, p_input_line);
+ return 0;
+ }
+ s = buf + 4;
+ if (!*s)
+ malformed();
+ p_first = getskiplinenum(&s);
+ if (*s == ',') {
+ s++;
+ p_ptrn_lines = getskiplinenum(&s);
+ } else
+ p_ptrn_lines = 1;
+ if (p_first >= LINENUM_MAX - p_ptrn_lines)
+ malformed();
+ if (*s == ' ')
+ s++;
+ if (*s != '+' || !*++s)
+ malformed();
+ p_newfirst = getskiplinenum(&s);
+ if (*s == ',') {
+ s++;
+ p_repl_lines = getskiplinenum(&s);
+ } else
+ p_repl_lines = 1;
+ if (*s == ' ')
+ s++;
+ if (*s != '@')
+ malformed();
+ if (p_first >= LINENUM_MAX - p_ptrn_lines ||
+ p_newfirst > LINENUM_MAX - p_repl_lines ||
+ p_ptrn_lines >= LINENUM_MAX - p_repl_lines - 1)
+ malformed();
+ if (!p_ptrn_lines)
+ p_first++;
+ p_max = p_ptrn_lines + p_repl_lines + 1;
+ while (p_max >= hunkmax)
+ grow_hunkmax();
+ fillold = 1;
+ fillnew = fillold + p_ptrn_lines;
+ p_end = fillnew + p_repl_lines;
+ snprintf(buf, bufsz, "*** %ld,%ld ****\n", p_first, p_first + p_ptrn_lines - 1);
+ p_line[0] = savestr(buf);
+ if (out_of_mem) {
+ p_end = -1;
+ return 0;
+ }
+ p_char[0] = '*';
+ snprintf(buf, bufsz, "--- %ld,%ld ----\n", p_newfirst, p_newfirst + p_repl_lines - 1);
+ p_line[fillnew] = savestr(buf);
+ if (out_of_mem) {
+ p_end = 0;
+ return 0;
+ }
+ p_char[fillnew++] = '=';
+ p_context = 100;
+ context = 0;
+ p_hunk_beg = p_input_line + 1;
+ while (fillold <= p_ptrn_lines || fillnew <= p_end) {
+ ret = pgetline(&buf, &bufsz, pfp);
+ p_input_line++;
+ if (ret == -1) {
+ if (p_max - fillnew < 3)
+ strlcpy(buf, " \n", bufsz);
+ else
+ fatal("unexpected end of file in patch\n");
+ }
+ if (*buf == '\t' || *buf == '\n') {
+ ch = ' ';
+ s = savestr(buf);
+ } else {
+ ch = *buf;
+ s = savestr(buf + 1);
+ }
+ if (out_of_mem) {
+ while (--fillnew > p_ptrn_lines)
+ free(p_line[fillnew]);
+ p_end = fillold - 1;
+ return 0;
+ }
+ switch (ch) {
+ case '-':
+ if (fillold > p_ptrn_lines) {
+ free(s);
+ p_end = fillnew - 1;
+ malformed();
+ }
+ p_char[fillold] = ch;
+ p_line[fillold] = s;
+ p_len[fillold++] = strlen(s);
+ if (fillold > p_ptrn_lines) {
+ if (remove_special_line()) {
+ p_len[fillold - 1] -= 1;
+ s[p_len[fillold - 1]] = 0;
+ }
+ }
+ break;
+ case '=':
+ ch = ' ';
+ /* FALL THROUGH */
+ case ' ':
+ if (fillold > p_ptrn_lines) {
+ free(s);
+ while (--fillnew > p_ptrn_lines)
+ free(p_line[fillnew]);
+ p_end = fillold - 1;
+ malformed();
+ }
+ context++;
+ p_char[fillold] = ch;
+ p_line[fillold] = s;
+ p_len[fillold++] = strlen(s);
+ s = savestr(s);
+ if (out_of_mem) {
+ while (--fillnew > p_ptrn_lines)
+ free(p_line[fillnew]);
+ p_end = fillold - 1;
+ return 0;
+ }
+ if (fillold > p_ptrn_lines) {
+ if (remove_special_line()) {
+ p_len[fillold - 1] -= 1;
+ s[p_len[fillold - 1]] = 0;
+ }
+ }
+ /* FALL THROUGH */
+ case '+':
+ if (fillnew > p_end) {
+ free(s);
+ while (--fillnew > p_ptrn_lines)
+ free(p_line[fillnew]);
+ p_end = fillold - 1;
+ malformed();
+ }
+ p_char[fillnew] = ch;
+ p_line[fillnew] = s;
+ p_len[fillnew++] = strlen(s);
+ if (fillold > p_ptrn_lines) {
+ if (remove_special_line()) {
+ p_len[fillnew - 1] -= 1;
+ s[p_len[fillnew - 1]] = 0;
+ }
+ }
+ break;
+ default:
+ p_end = fillnew;
+ malformed();
+ }
+ if (ch != ' ' && context > 0) {
+ if (context < p_context)
+ p_context = context;
+ context = -1000;
+ }
+ }
+ } else {
+ char hunk_type;
+ int i;
+ LINENUM min, max;
+
+ line_beginning = ftell(pfp);
+ p_context = 0;
+ ret = pgetline(&buf, &bufsz, pfp);
+ p_input_line++;
+ if (ret == -1 || !isdigit((unsigned char)*buf)) {
+ next_intuit_at(line_beginning, p_input_line);
+ return 0;
+ }
+ s = buf;
+ p_first = getskiplinenum(&s);
+ if (*s == ',') {
+ s++;
+ p_ptrn_lines = getskiplinenum(&s) - p_first + 1;
+ } else
+ p_ptrn_lines = (*s != 'a');
+ if (p_first >= LINENUM_MAX - p_ptrn_lines)
+ malformed();
+ hunk_type = *s++;
+ if (hunk_type == 'a')
+ p_first++;
+ min = getskiplinenum(&s);
+ if (*s == ',')
+ max = getlinenum(++s);
+ else
+ max = min;
+ if (min < 0 || min > max || max - min == LINENUM_MAX)
+ malformed();
+ if (hunk_type == 'd')
+ min++;
+ p_end = p_ptrn_lines + p_repl_lines + 1;
+ p_newfirst = min;
+ p_repl_lines = max - min + 1;
+ if (p_newfirst > LINENUM_MAX - p_repl_lines || p_ptrn_lines >= LINENUM_MAX - p_repl_lines - 1)
+ malformed();
+ p_end = p_ptrn_lines + p_repl_lines + 1;
+ if (p_end > MAXHUNKSIZE)
+ fatal("hunk too large at line %ld\n", p_input_line);
+ while (p_end >= hunkmax)
+ grow_hunkmax();
+ snprintf(buf, bufsz, "*** %ld,%ld\n", p_first, p_first + p_ptrn_lines - 1);
+ p_line[0] = savestr(buf);
+ if (out_of_mem) {
+ p_end = -1;
+ return 0;
+ }
+ p_char[0] = '*';
+ for (i = 1; i <= p_ptrn_lines; i++) {
+ ret = pgetline(&buf, &bufsz, pfp);
+ p_input_line++;
+ if (ret == -1)
+ fatal("unexpected end of file in patch at line %ld\n", p_input_line);
+ if (*buf != '<')
+ fatal("< expected at line %ld of patch\n", p_input_line);
+ p_line[i] = savestr(buf + 2);
+ if (out_of_mem) {
+ p_end = i - 1;
+ return 0;
+ }
+ p_len[i] = strlen(p_line[i]);
+ p_char[i] = '-';
+ }
+ if (remove_special_line()) {
+ p_len[i - 1] -= 1;
+ (p_line[i - 1])[p_len[i - 1]] = 0;
+ }
+ if (hunk_type == 'c') {
+ ret = pgetline(&buf, &bufsz, pfp);
+ p_input_line++;
+ if (ret == -1)
+ fatal("unexpected end of file in patch at line %ld\n", p_input_line);
+ if (*buf != '-')
+ fatal("--- expected at line %ld of patch\n", p_input_line);
+ }
+ snprintf(buf, bufsz, "--- %ld,%ld\n", min, max);
+ p_line[i] = savestr(buf);
+ if (out_of_mem) {
+ p_end = i - 1;
+ return 0;
+ }
+ p_char[i] = '=';
+ for (i++; i <= p_end; i++) {
+ ret = pgetline(&buf, &bufsz, pfp);
+ p_input_line++;
+ if (ret == -1)
+ fatal("unexpected end of file in patch at line %ld\n", p_input_line);
+ if (*buf != '>')
+ fatal("> expected at line %ld of patch\n", p_input_line);
+ p_line[i] = savestr(buf + 2);
+ if (out_of_mem) {
+ p_end = i - 1;
+ return 0;
+ }
+ p_len[i] = strlen(p_line[i]);
+ p_char[i] = '+';
+ }
+ if (remove_special_line()) {
+ p_len[i - 1] -= 1;
+ (p_line[i - 1])[p_len[i - 1]] = 0;
+ }
+ }
+ if (reverse) {
+ if (!pch_swap())
+ say("Not enough memory to swap next hunk!\n");
+ }
+ if (p_end + 1 < hunkmax)
+ p_char[p_end + 1] = '^';
+ return 1;
+}
+
+int
+pgetline(char **bf, size_t *sz, FILE *fp)
+{
+ char *s;
+ int indent = 0;
+ int ret;
+
+ ret = getline(bf, sz, fp);
+ if (p_indent && ret != -1) {
+ for (s = buf; indent < p_indent && (*s == ' ' || *s == '\t' || *s == 'X'); s++) {
+ if (*s == '\t')
+ indent += 8 - (indent % 7);
+ else
+ indent++;
+ }
+ if (buf != s && strlcpy(buf, s, bufsz) >= bufsz)
+ fatal("buffer too small in pgetline()\n");
+ }
+ return ret;
+}
+
+int
+pch_swap(void)
+{
+ char **tp_line;
+ ssize_t *tp_len;
+ char *tp_char;
+ LINENUM i;
+ LINENUM n;
+ int blankline = 0;
+ char *s;
+
+ i = p_first;
+ p_first = p_newfirst;
+ p_newfirst = i;
+
+ tp_line = p_line;
+ tp_len = p_len;
+ tp_char = p_char;
+ p_line = NULL;
+ p_len = NULL;
+ p_char = NULL;
+ set_hunkmax();
+ if (p_line == NULL || p_len == NULL || p_char == NULL) {
+ free(p_line);
+ p_line = tp_line;
+ free(p_len);
+ p_len = tp_len;
+ free(p_char);
+ p_char = tp_char;
+ return 0;
+ }
+
+ i = p_ptrn_lines + 1;
+ if (tp_char[i] == '\n') {
+ blankline = 1;
+ i++;
+ }
+ if (p_efake >= 0) {
+ if (p_efake <= i)
+ n = p_end - i + 1;
+ else
+ n = -i;
+ p_efake += n;
+ p_bfake += n;
+ }
+ for (n = 0; i <= p_end; i++, n++) {
+ p_line[n] = tp_line[i];
+ p_char[n] = tp_char[i];
+ if (p_char[n] == '+')
+ p_char[n] = '-';
+ p_len[n] = tp_len[i];
+ }
+ if (blankline) {
+ i = p_ptrn_lines + 1;
+ p_line[n] = tp_line[i];
+ p_char[n] = tp_char[i];
+ p_len[n] = tp_len[i];
+ n++;
+ }
+ if (p_char[0] != '=')
+ fatal("expected '=' found '%c'\n", p_char[0]);
+ p_char[0] = '*';
+ for (s = p_line[0]; *s; s++)
+ if (*s == '-')
+ *s = '*';
+
+ if (p_char[0] != '*')
+ fatal("expected '*' found '%c'\n", p_char[0]);
+ tp_char[0] = '=';
+ for (s = tp_line[0]; *s; s++)
+ if (*s == '*')
+ *s = '-';
+ for (i = 0; n <= p_end; i++, n++) {
+ p_line[n] = tp_line[i];
+ p_char[n] = tp_char[i];
+ if (p_char[n] == '-')
+ p_char[n] = '+';
+ p_len[n] = tp_len[i];
+ }
+ if (i != p_ptrn_lines + 1)
+ fatal("expected %ld lines, got %ld\n", p_ptrn_lines + 1, i);
+
+ i = p_ptrn_lines;
+ p_ptrn_lines = p_repl_lines;
+ p_repl_lines = i;
+
+ free(tp_line);
+ free(tp_len);
+ free(tp_char);
+ return 1;
+}
+
+LINENUM
+pch_first(void)
+{
+ return p_first;
+}
+
+LINENUM
+pch_ptrn_lines(void)
+{
+ return p_ptrn_lines;
+}
+
+LINENUM
+pch_newfirst(void)
+{
+ return p_newfirst;
+}
+
+LINENUM
+pch_repl_lines(void)
+{
+ return p_repl_lines;
+}
+
+LINENUM
+pch_end(void)
+{
+ return p_end;
+}
+
+LINENUM
+pch_context(void)
+{
+ return p_context;
+}
+
+ssize_t
+pch_line_len(LINENUM line)
+{
+ return p_len[line];
+}
+
+char
+pch_char(LINENUM line)
+{
+ return p_char[line];
+}
+
+char *
+pfetch(LINENUM line)
+{
+ return p_line[line];
+}
+
+LINENUM
+pch_hunk_beg(void)
+{
+ return p_hunk_beg;
+}
+
+void
+do_ed_script(void)
+{
+ char *t;
+ long beginning_of_this_line;
+ FILE *pipefp = NULL;
+ int continuation;
+
+ if (!skip_rest_of_patch) {
+ if (copy_file(filearg[0], TMPOUTNAME) < 0) {
+ unlink(TMPOUTNAME);
+ fatal("cant create temp file %s", TMPOUTNAME);
+ }
+ snprintf(buf, bufsz, "%s -S%s %s", _PATH_ED, verbose ? "" : "s", TMPOUTNAME);
+ pipefp = popen(buf, "w");
+ }
+ for (;;) {
+ beginning_of_this_line = ftell(pfp);
+ if (pgetline(&buf, &bufsz, pfp) == -1) {
+ next_intuit_at(beginning_of_this_line, p_input_line);
+ break;
+ }
+ p_input_line++;
+ for (t = buf; isdigit((unsigned char)*t) || *t == ','; t++)
+ ;
+ if (isdigit((unsigned char)*buf) && (*t == 'a' || *t == 'c' || *t == 'd' || *t == 'i' || *t == 's')) {
+ if (pipefp != NULL)
+ fprintf(pipefp, "%s", buf);
+ if (*t == 's') {
+ for (;;) {
+ continuation = 0;
+ t = strchr(buf, '\0') - 1;
+ while (--t >= buf && *t == '\\')
+ continuation = !continuation;
+ if (!continuation || pgetline(&buf, &bufsz, pfp) == -1)
+ break;
+ if (pipefp != NULL)
+ fprintf(pipefp, "%s", buf);
+ }
+ } else if (*t != 'd') {
+ while (pgetline(&buf, &bufsz, pfp) != -1) {
+ p_input_line++;
+ if (pipefp != NULL)
+ fprintf(pipefp, "%s", buf);
+ if (strEQ(buf, ".\n"))
+ break;
+ }
+ }
+ } else {
+ next_intuit_at(beginning_of_this_line, p_input_line);
+ break;
+ }
+ }
+ if (pipefp == NULL)
+ return;
+ fprintf(pipefp, "w\n");
+ fprintf(pipefp, "q\n");
+ fflush(pipefp);
+ pclose(pipefp);
+ ignore_signals();
+ if (!check_only) {
+ if (move_file(TMPOUTNAME, outname) < 0) {
+ toutkeep = 1;
+ chmod(TMPOUTNAME, filemode);
+ } else
+ chmod(outname, filemode);
+ }
+ set_signals(1);
+}
+
+static char *
+posix_name(const struct FileName *names, int assume_exists)
+{
+ char *path = NULL;
+ int i;
+
+ for (i = 0; i < MAX_FILE; i++) {
+ if (names[i].path != NULL && names[i].exists) {
+ path = names[i].path;
+ break;
+ }
+ }
+ if (path == NULL && !assume_exists) {
+ for (i = 0; i < MAX_FILE; i++) {
+ if (names[i].path != NULL && (path = checked_in(names[i].path)) != NULL)
+ break;
+ }
+ if (path == NULL && ok_to_create_file && names[NEW_FILE].path != NULL)
+ path = names[NEW_FILE].path;
+ }
+ return path ? savestr(path) : NULL;
+}
+
+static char *
+best_name(const struct FileName *names, int assume_exists)
+{
+ size_t min_components, min_baselen, min_len, tmp;
+ char *best = NULL;
+ int i;
+
+ min_components = min_baselen = min_len = SIZE_MAX;
+ for (i = INDEX_FILE; i >= OLD_FILE; i--) {
+ if (names[i].path == NULL || (!names[i].exists && !assume_exists))
+ continue;
+ if ((tmp = num_components(names[i].path)) > min_components)
+ continue;
+ min_components = tmp;
+ if ((tmp = strlen(basename(names[i].path))) > min_baselen)
+ continue;
+ min_baselen = tmp;
+ if ((tmp = strlen(names[i].path)) > min_len)
+ continue;
+ min_len = tmp;
+ best = names[i].path;
+ }
+ if (best == NULL) {
+ min_components = min_baselen = min_len = SIZE_MAX;
+ for (i = INDEX_FILE; i >= OLD_FILE; i--) {
+ if (names[i].path == NULL || checked_in(names[i].path) == NULL)
+ continue;
+ if ((tmp = num_components(names[i].path)) > min_components)
+ continue;
+ min_components = tmp;
+ if ((tmp = strlen(basename(names[i].path))) > min_baselen)
+ continue;
+ min_baselen = tmp;
+ if ((tmp = strlen(names[i].path)) > min_len)
+ continue;
+ min_len = tmp;
+ best = names[i].path;
+ }
+ if (best == NULL && ok_to_create_file && names[NEW_FILE].path != NULL)
+ best = names[NEW_FILE].path;
+ }
+ return best ? savestr(best) : NULL;
+}
+
+static size_t
+num_components(const char *path)
+{
+ size_t n;
+ const char *cp;
+
+ for (n = 0, cp = path; (cp = strchr(cp, '/')) != NULL; n++, cp++) {
+ while (*cp == '/')
+ cp++;
+ }
+ return n;
+}
+
+LINENUM
+strtolinenum(char *nptr, char **endptr)
+{
+ LINENUM rv;
+ char c;
+ char *p;
+ const char *errstr;
+
+ for (p = nptr; isdigit((unsigned char)*p); p++)
+ ;
+
+ if (p == nptr)
+ malformed();
+
+ c = *p;
+ *p = '\0';
+
+ rv = strtonum(nptr, 0, LINENUM_MAX, &errstr);
+ if (errstr != NULL)
+ fatal("invalid line number at line %ld: `%s' is %s\n",
+ p_input_line, nptr, errstr);
+
+ *p = c;
+ *endptr = p;
+
+ return rv;
+}
+
+int
+move_file(const char *from, const char *to)
+{
+ int fromfd;
+ ssize_t i;
+
+ if (strEQ(to, "-")) {
+ fromfd = open(from, O_RDONLY);
+ if (fromfd < 0)
+ pfatal("internal error, cant reopen %s", from);
+ while ((i = read(fromfd, buf, bufsz)) > 0) {
+ if (write(STDOUT_FILENO, buf, i) != i)
+ pfatal("write failed");
+ }
+ close(fromfd);
+ return 0;
+ }
+ if (backup_file(to) < 0) {
+ say("Cant backup %s, output is in %s: %s\n", to, from, strerror(errno));
+ return -1;
+ }
+ if (rename(from, to) < 0) {
+ if (errno != EXDEV || copy_file(from, to) < 0) {
+ say("Cant create %s, output is in %s: %s\n", to, from, strerror(errno));
+ return -1;
+ }
+ }
+ return 0;
+}
+
+int
+backup_file(const char *orig)
+{
+ struct stat filestat;
+ char bakname[PATH_MAX], *s, *simplename;
+ dev_t orig_device;
+ ino_t orig_inode;
+
+ if (backup_type == BACKUP_NONE || stat(orig, &filestat) != 0)
+ return 0;
+ if ((origprae && *origprae == 0) || *simple_backup_suffix == 0) {
+ unlink(orig);
+ return 0;
+ }
+ orig_device = filestat.st_dev;
+ orig_inode = filestat.st_ino;
+
+ if (origprae) {
+ if (strlcpy(bakname, origprae, sizeof(bakname)) >= sizeof(bakname) ||
+ strlcat(bakname, orig, sizeof(bakname)) >= sizeof(bakname))
+ fatal("filename too long\n");
+ } else {
+ if ((s = find_backup_file_name(orig)) == NULL)
+ fatal("out of memory\n");
+ if (strlcpy(bakname, s, sizeof(bakname)) >= sizeof(bakname))
+ fatal("filename too long\n");
+ free(s);
+ }
+
+ if ((simplename = strrchr(bakname, '/')) != NULL)
+ simplename = simplename + 1;
+ else
+ simplename = bakname;
+
+ while (stat(bakname, &filestat) == 0 && orig_device == filestat.st_dev && orig_inode == filestat.st_ino) {
+ for (s = simplename; *s && !islower((unsigned char)*s); s++)
+ ;
+ if (*s)
+ *s = toupper((unsigned char)*s);
+ else
+ memmove(simplename, simplename + 1, strlen(simplename + 1) + 1);
+ }
+ if (rename(orig, bakname) < 0) {
+ if (errno != EXDEV || copy_file(orig, bakname) < 0)
+ return -1;
+ }
+ return 0;
+}
+
+int
+copy_file(const char *from, const char *to)
+{
+ int tofd, fromfd;
+ ssize_t i;
+
+ tofd = open(to, O_CREAT|O_TRUNC|O_WRONLY, 0666);
+ if (tofd < 0)
+ return -1;
+ fromfd = open(from, O_RDONLY, 0);
+ if (fromfd < 0)
+ pfatal("internal error, cant reopen %s", from);
+ while ((i = read(fromfd, buf, bufsz)) > 0) {
+ if (write(tofd, buf, i) != i)
+ pfatal("write to %s failed", to);
+ }
+ close(fromfd);
+ close(tofd);
+ return 0;
+}
+
+char *
+savestr(const char *s)
+{
+ char *rv;
+
+ if (!s)
+ s = "Oops";
+ rv = strdup(s);
+ if (rv == NULL) {
+ if (using_plan_a)
+ out_of_mem = 1;
+ else
+ fatal("out of memory\n");
+ }
+ return rv;
+}
+
+void
+say(const char *fmt, ...)
+{
+ va_list ap;
+
+ va_start(ap, fmt);
+ vfprintf(stderr, fmt, ap);
+ va_end(ap);
+ fflush(stderr);
+}
+
+__dead void
+fatal(const char *fmt, ...)
+{
+ va_list ap;
+
+ va_start(ap, fmt);
+ fprintf(stderr, "patch: **** ");
+ vfprintf(stderr, fmt, ap);
+ va_end(ap);
+ my_exit(2);
+}
+
+__dead void
+pfatal(const char *fmt, ...)
+{
+ va_list ap;
+ int errnum = errno;
+
+ fprintf(stderr, "patch: **** ");
+ va_start(ap, fmt);
+ vfprintf(stderr, fmt, ap);
+ va_end(ap);
+ fprintf(stderr, ": %s\n", strerror(errnum));
+ my_exit(2);
+}
+
+void
+ask(const char *fmt, ...)
+{
+ va_list ap;
+ ssize_t nr = 0;
+ static int ttyfd = -1;
+
+ va_start(ap, fmt);
+ vfprintf(stdout, fmt, ap);
+ va_end(ap);
+ fflush(stdout);
+ if (ttyfd < 0)
+ ttyfd = open(_PATH_TTY, O_RDONLY);
+ if (ttyfd >= 0) {
+ if ((nr = read(ttyfd, buf, bufsz)) > 0 && buf[nr - 1] == '\n')
+ buf[nr - 1] = '\0';
+ }
+ if (ttyfd < 0 || nr <= 0) {
+ putchar('\n');
+ buf[0] = '\0';
+ }
+}
+
+void
+set_signals(int reset)
+{
+ static sig_t hupval, intval;
+
+ if (!reset) {
+ hupval = signal(SIGHUP, SIG_IGN);
+ if (hupval != SIG_IGN)
+ hupval = (sig_t)my_exit;
+ intval = signal(SIGINT, SIG_IGN);
+ if (intval != SIG_IGN)
+ intval = (sig_t)my_exit;
+ }
+ signal(SIGHUP, hupval);
+ signal(SIGINT, intval);
+}
+
+void
+ignore_signals(void)
+{
+ signal(SIGHUP, SIG_IGN);
+ signal(SIGINT, SIG_IGN);
+}
+
+void
+makedirs(const char *filename, int striplast)
+{
+ char *tmpbuf;
+
+ if ((tmpbuf = strdup(filename)) == NULL)
+ fatal("out of memory\n");
+
+ if (striplast) {
+ char *s = strrchr(tmpbuf, '/');
+ if (s == NULL) {
+ free(tmpbuf);
+ return;
+ }
+ *s = '\0';
+ }
+ if (mkpath(tmpbuf) != 0)
+ pfatal("creation of %s failed", tmpbuf);
+ free(tmpbuf);
+}
+
+char *
+fetchname(const char *at, int *exists, int strip_leading)
+{
+ char *fullname, *name, *t;
+ int sleading, tab;
+ struct stat filestat;
+
+ if (at == NULL || *at == '\0')
+ return NULL;
+ while (isspace((unsigned char)*at))
+ at++;
+ if (strnEQ(at, _PATH_DEVNULL, sizeof(_PATH_DEVNULL) - 1))
+ return NULL;
+ name = fullname = t = savestr(at);
+ tab = strchr(t, '\t') != NULL;
+ for (sleading = strip_leading; *t != '\0' && ((tab && *t != '\t') || !isspace((unsigned char)*t)); t++) {
+ if (t[0] == '/' && t[1] != '/' && t[1] != '\0') {
+ if (--sleading >= 0)
+ name = t + 1;
+ }
+ }
+ *t = '\0';
+
+ if (strip_leading == 957 && name != fullname && *fullname != '/') {
+ name[-1] = '\0';
+ if (stat(fullname, &filestat) == 0 && S_ISDIR(filestat.st_mode)) {
+ name[-1] = '/';
+ name = fullname;
+ }
+ }
+ name = savestr(name);
+ free(fullname);
+
+ *exists = stat(name, &filestat) == 0;
+ return name;
+}
+
+char *
+checked_in(char *file)
+{
+ char *filebase, *filedir, tmpbuf[PATH_MAX];
+ struct stat filestat;
+
+ filebase = basename(file);
+ filedir = dirname(file);
+
+#define try(f, a1, a2, a3) \
+(snprintf(tmpbuf, sizeof tmpbuf, f, a1, a2, a3), stat(tmpbuf, &filestat) == 0)
+
+ if (try("%s/RCS/%s%s", filedir, filebase, RCSSUFFIX) ||
+ try("%s/RCS/%s%s", filedir, filebase, "") ||
+ try("%s/%s%s", filedir, filebase, RCSSUFFIX) ||
+ try("%s/SCCS/%s%s", filedir, SCCSPREFIX, filebase) ||
+ try("%s/%s%s", filedir, SCCSPREFIX, filebase))
+ return file;
+
+ return NULL;
+}
+
+__dead void
+version(void)
+{
+ printf("Patch version 2.0-12u9-NetBSD\n");
+ my_exit(EXIT_SUCCESS);
+}
+
+__dead void
+my_exit(int status)
+{
+ unlink(TMPINNAME);
+ if (!toutkeep)
+ unlink(TMPOUTNAME);
+ if (!trejkeep)
+ unlink(TMPREJNAME);
+ unlink(TMPPATNAME);
+ exit(status);
+}
+
+static void *
+pch_realloc(void *ptr, size_t number, size_t size)
+{
+ if (number > SIZE_MAX / size) {
+ errno = EOVERFLOW;
+ return NULL;
+ }
+ return realloc(ptr, number * size);
+}
+
+int
+mkpath(char *path)
+{
+ struct stat sb;
+ char *slash;
+ int done = 0;
+
+ slash = path;
+ while (!done) {
+ slash += strspn(slash, "/");
+ slash += strcspn(slash, "/");
+ done = (*slash == '\0');
+ *slash = '\0';
+ if (stat(path, &sb)) {
+ if (errno != ENOENT || (mkdir(path, 0777) && errno != EEXIST)) {
+ warn("%s", path);
+ return -1;
+ }
+ } else if (!S_ISDIR(sb.st_mode)) {
+ warnx("%s: %s", path, strerror(ENOTDIR));
+ return -1;
+ }
+ *slash = '/';
+ }
+ return 0;
+}
+
+char *
+find_backup_file_name(const char *file)
+{
+ char *dir, *base_versions, *tmp_file;
+ int highest_backup;
+
+ if (backup_type == BACKUP_SIMPLE)
+ return patch_concat(file, simple_backup_suffix);
+ tmp_file = strdup(file);
+ if (tmp_file == NULL)
+ return NULL;
+ base_versions = patch_concat(basename(tmp_file), ".~");
+ free(tmp_file);
+ if (base_versions == NULL)
+ return NULL;
+ tmp_file = strdup(file);
+ if (tmp_file == NULL) {
+ free(base_versions);
+ return NULL;
+ }
+ dir = dirname(tmp_file);
+ if (dir == NULL) {
+ free(base_versions);
+ free(tmp_file);
+ return NULL;
+ }
+ highest_backup = max_backup_version(base_versions, dir);
+ free(base_versions);
+ free(tmp_file);
+ if (backup_type == BACKUP_NUMBERED_EXISTING && highest_backup == 0)
+ return patch_concat(file, simple_backup_suffix);
+ return make_version_name(file, highest_backup + 1);
+}
+
+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 (strlen(dp->d_name) <= 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;
+}
+
+static char *
+make_version_name(const char *file, int version_num)
+{
+ char *backup_name;
+
+ if (asprintf(&backup_name, "%s.~%d~", file, version_num) == -1)
+ return NULL;
+ return backup_name;
+}
+
+static int
+version_number(const char *base, const char *backup, size_t base_length)
+{
+ int version_num;
+ const char *p;
+
+ version_num = 0;
+ if (!strncmp(base, backup, base_length) && ISDIGIT(backup[base_length])) {
+ for (p = &backup[base_length]; ISDIGIT(*p); ++p)
+ version_num = version_num * 10 + *p - '0';
+ if (p[0] != '~' || p[1])
+ version_num = 0;
+ }
+ return version_num;
+}
+
+static char *
+patch_concat(const char *str1, const char *str2)
+{
+ char *newstr;
+
+ if (asprintf(&newstr, "%s%s", str1, str2) == -1)
+ return NULL;
+ return newstr;
+}
+
+static int
+argmatch(const char *arg, const char **optlist)
+{
+ int i;
+ size_t arglen;
+ int matchind = -1;
+ int ambiguous = 0;
+
+ arglen = strlen(arg);
+ for (i = 0; optlist[i]; i++) {
+ if (!strncmp(optlist[i], arg, arglen)) {
+ if (strlen(optlist[i]) == arglen)
+ return i;
+ else if (matchind == -1)
+ matchind = i;
+ else
+ ambiguous = 1;
+ }
+ }
+ if (ambiguous)
+ return -2;
+ else
+ return matchind;
+}
+
+static void
+invalid_arg(const char *kind, const char *value, int problem)
+{
+ fprintf(stderr, "patch: ");
+ if (problem == -1)
+ fprintf(stderr, "invalid");
+ else
+ fprintf(stderr, "ambiguous");
+ fprintf(stderr, " %s `%s'\n", kind, value);
+}
+
+enum BackupType
+get_version(const char *version_str)
+{
+ int i;
+
+ if (version_str == NULL || *version_str == '\0')
+ return BACKUP_NUMBERED_EXISTING;
+ i = argmatch(version_str, backup_args);
+ if (i >= 0)
+ return backup_types[i];
+ invalid_arg("version control type", version_str, i);
+ exit(2);
+}
diff --git a/cmd/posix/patch/backupfile.c b/cmd/posix/patch/backupfile.c
@@ -1,251 +0,0 @@
-/*
- * $OpenBSD: backupfile.c,v 1.19 2006/03/11 19:41:30 otto Exp $
- * $DragonFly: src/usr.bin/patch/backupfile.c,v 1.5 2008/08/11 00:05:06 joerg Exp $
- * $NetBSD: backupfile.c,v 1.16 2021/02/19 17:46:53 nia 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@ai.mit.edu>. Some algorithms adapted from GNU Emacs.
- */
-
-#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 ((unsigned char)c) && isdigit ((unsigned char)c))
-
-/* Which type of backup file names are generated. */
-enum backup_type backup_type = undefined;
-
-/*
- * 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, *tmp_file;
- int highest_backup;
-
- if (backup_type == simple)
- return concat(file, simple_backup_suffix);
- tmp_file = strdup(file);
- if (tmp_file == NULL)
- return NULL;
- base_versions = concat(basename(tmp_file), ".~");
- free(tmp_file);
- if (base_versions == NULL)
- return NULL;
- tmp_file = strdup(file);
- if (tmp_file == NULL) {
- free(base_versions);
- return NULL;
- }
- dir = dirname(tmp_file);
- if (dir == NULL) {
- free(base_versions);
- free(tmp_file);
- return NULL;
- }
- highest_backup = max_backup_version(base_versions, dir);
- free(base_versions);
- free(tmp_file);
- 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 (strlen(dp->d_name) <= 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[] = {
- "none", "never", "simple", "nil", "existing", "t", "numbered", 0
-};
-
-static enum backup_type backup_types[] = {
- none, 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);
-}
diff --git a/cmd/posix/patch/backupfile.h b/cmd/posix/patch/backupfile.h
@@ -1,44 +0,0 @@
-/*
- * $OpenBSD: backupfile.h,v 1.6 2003/07/28 18:35:36 otto Exp $
- * $DragonFly: src/usr.bin/patch/backupfile.h,v 1.3 2007/09/29 23:11:10 swildner Exp $
- * $NetBSD: backupfile.h,v 1.7 2021/02/19 17:46:53 nia 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.
- *
- */
-
-/* When to make backup files. */
-enum backup_type {
- undefined,
-
- /* 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);
diff --git a/cmd/posix/patch/common.h b/cmd/posix/patch/common.h
@@ -1,136 +0,0 @@
-/*
- * $OpenBSD: common.h,v 1.26 2006/03/11 19:41:30 otto Exp $
- * $DragonFly: src/usr.bin/patch/common.h,v 1.5 2008/08/10 23:50:12 joerg Exp $
- * $NetBSD: common.h,v 1.22 2021/05/25 11:25:59 cjep 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/types.h>
-
-#include <limits.h>
-#include <stdbool.h>
-#include <stdint.h>
-
-#include <util.h>
-
-#ifndef __dead
-#define __dead __attribute__((__noreturn__))
-#endif
-#ifndef __printflike
-#define __printflike(a, b) __attribute__((__format__(printf, a, b)))
-#endif
-#ifndef __UNCONST
-#define __UNCONST(a) ((void *)(uintptr_t)(const void *)(a))
-#endif
-
-#define DEBUGGING
-
-/* constants */
-
-#define MAXHUNKSIZE 100000 /* is this enough lines? */
-#define INITHUNKMAX 125 /* initial dynamic allocation size */
-#define INITLINELEN 8192
-#define BUFFERSIZE 1024
-#define LINENUM_MAX LONG_MAX
-
-#define SCCSPREFIX "s."
-#define GET "get -e %s"
-#define SCCSDIFF "get -p %s | diff - %s >/dev/null"
-
-#define RCSSUFFIX ",v"
-#define CHECKOUT "/usr/bin/co"
-#define RCSDIFF "/usr/bin/rcsdiff"
-
-#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; /* general purpose buffer */
-extern size_t bufsz; /* general purpose buffer size */
-
-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;
-
diff --git a/cmd/posix/patch/inp.c b/cmd/posix/patch/inp.c
@@ -1,519 +0,0 @@
-/*
- * $OpenBSD: inp.c,v 1.34 2006/03/11 19:41:30 otto Exp $
- * $DragonFly: src/usr.bin/patch/inp.c,v 1.6 2007/09/29 23:11:10 swildner Exp $
- * $NetBSD: inp.c,v 1.30 2023/06/16 23:36:26 wiz 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/types.h>
-#include <sys/file.h>
-#include <sys/stat.h>
-#include <sys/mman.h>
-#include <sys/wait.h>
-
-#include <ctype.h>
-#include <errno.h>
-#include <fcntl.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 char empty_line[] = { '\0' };
-
-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 = pch_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, devnull, pstat;
- char *p, *s, *lbuf;
- struct stat filestat;
- off_t i;
- ptrdiff_t sz;
- size_t iline, lines_allocated, lbufsz;
- pid_t pid;
- char *argp[4] = {NULL};
-
-#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 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())) {
- char *filebase, *filedir;
- struct stat cstat;
- char *tmp_filename1, *tmp_filename2;
-
- tmp_filename1 = strdup(filename);
- tmp_filename2 = strdup(filename);
- if (tmp_filename1 == NULL || tmp_filename2 == NULL)
- fatal("strdupping filename");
-
- filebase = basename(tmp_filename1);
- filedir = dirname(tmp_filename2);
-
- lbufsz = INITLINELEN;
- if ((lbuf = malloc(bufsz)) == NULL)
- pfatal("allocating line buffer");
- lbuf[0] = '\0';
-
-#define try(f, a1, a2, a3) \
- (snprintf(lbuf, lbufsz, f, a1, a2, a3), stat(lbuf, &cstat) == 0)
-
- /*
- * else we can't write to it but it's not under a version
- * control system, so just proceed.
- */
- if (try("%s/RCS/%s%s", filedir, filebase, RCSSUFFIX) ||
- try("%s/RCS/%s%s", filedir, filebase, "") ||
- try("%s/%s%s", filedir, filebase, RCSSUFFIX)) {
- 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 RCS\n",
- filename);
- /*
- * 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 "
- "RCS version...\n", filename);
-
- switch (pid = fork()) {
- case -1:
- fatal("can't fork: %s\n",
- strerror(errno));
- case 0:
- devnull = open("/dev/null", O_RDONLY);
- if (devnull == -1) {
- fatal("can't open /dev/null: %s",
- strerror(errno));
- }
- (void)dup2(devnull, STDOUT_FILENO);
- argp[0] = __UNCONST(RCSDIFF);
- argp[1] = __UNCONST(filename);
- execv(RCSDIFF, argp);
- exit(127);
- }
- pid = waitpid(pid, &pstat, 0);
- if (pid == -1 || WEXITSTATUS(pstat) != 0) {
- fatal("can't check out file %s: "
- "differs from default RCS version\n",
- filename);
- }
- }
-
- if (verbose)
- say("Checking out file %s from RCS...\n",
- filename);
-
- switch (pid = fork()) {
- case -1:
- fatal("can't fork: %s\n", strerror(errno));
- case 0:
- argp[0] = __UNCONST(CHECKOUT);
- argp[1] = __UNCONST("-l");
- argp[2] = __UNCONST(filename);
- execv(CHECKOUT, argp);
- exit(127);
- }
- pid = waitpid(pid, &pstat, 0);
- if (pid == -1 || WEXITSTATUS(pstat) != 0 ||
- stat(filename, &filestat)) {
- fatal("can't check out file %s from RCS\n",
- filename);
- }
- } else if (statfailed) {
- fatal("can't find %s\n", filename);
- }
- free(lbuf);
- free(tmp_filename1);
- free(tmp_filename2);
- }
-
- 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 ((uintmax_t)i_size > (uintmax_t)SIZE_MAX) {
- say("block too large to mmap\n");
- return false;
- }
- if ((ifd = open(filename, O_RDONLY)) < 0)
- pfatal("can't open file %s", filename);
-
- if (i_size) {
- 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;
- }
- } else {
- i_womp = NULL;
- }
-
- 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] = empty_line;
- } 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);
- unlink(TMPINNAME);
- if ((tifd = open(TMPINNAME, O_EXCL | O_CREAT | O_WRONLY, 0666)) < 0)
- pfatal("can't open file %s", TMPINNAME);
- while (getline(&buf, &bufsz, ifp) != -1) {
- 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)
- return true;
- patlen = strlen(revision);
- if (strnEQ(string, revision, patlen) && isspace((unsigned char)string[patlen]))
- return true;
- for (s = string; *s; s++) {
- if (isspace((unsigned char)*s) && strnEQ(s + 1, revision, patlen) &&
- isspace((unsigned char)s[patlen + 1])) {
- return true;
- }
- }
- return false;
-}
diff --git a/cmd/posix/patch/inp.h b/cmd/posix/patch/inp.h
@@ -1,35 +0,0 @@
-/*
- * $OpenBSD: inp.h,v 1.8 2003/08/15 08:00:51 otto Exp $
- * $DragonFly: src/usr.bin/patch/inp.h,v 1.1 2004/09/24 18:44:28 joerg Exp $
- * $NetBSD: inp.h,v 1.10 2008/09/19 18:33:34 joerg 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
- */
-
-void re_input(void);
-void scan_input(const char *);
-char *ifetch(LINENUM, int);
diff --git a/cmd/posix/patch/mkpath.c b/cmd/posix/patch/mkpath.c
@@ -1,81 +0,0 @@
-/*
- * $OpenBSD: mkpath.c,v 1.2 2005/06/20 07:14:06 otto Exp $
- * $DragonFly: src/usr.bin/patch/mkpath.c,v 1.1 2007/09/29 23:11:10 swildner Exp $
- * $NetBSD: mkpath.c,v 1.1 2008/09/19 18:33:34 joerg Exp $
- */
-
-/*
- * Copyright (c) 1983, 1992, 1993
- * 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/types.h>
-#include <sys/stat.h>
-#include <err.h>
-#include <errno.h>
-#include <string.h>
-
-int mkpath(char *);
-
-/* Code taken directly from mkdir(1).
-
- * mkpath -- create directories.
- * path - path
- */
-int
-mkpath(char *path)
-{
- struct stat sb;
- char *slash;
- int done = 0;
-
- slash = path;
-
- while (!done) {
- slash += strspn(slash, "/");
- slash += strcspn(slash, "/");
-
- done = (*slash == '\0');
- *slash = '\0';
-
- if (stat(path, &sb)) {
- if (errno != ENOENT || (mkdir(path, 0777) &&
- errno != EEXIST)) {
- warn("%s", path);
- return (-1);
- }
- } else if (!S_ISDIR(sb.st_mode)) {
- warnx("%s: %s", path, strerror(ENOTDIR));
- return (-1);
- }
-
- *slash = '/';
- }
-
- return (0);
-}
-
diff --git a/cmd/posix/patch/patch.c b/cmd/posix/patch/patch.c
@@ -1,1338 +0,0 @@
-/*
- * $OpenBSD: patch.c,v 1.45 2007/04/18 21:52:24 sobrado Exp $
- * $DragonFly: src/usr.bin/patch/patch.c,v 1.10 2008/08/10 23:39:56 joerg Exp $
- * $NetBSD: patch.c,v 1.35 2024/07/12 15:48:39 manu 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
- */
-
-/* ?man patch: apply a diff file to an original
-synopsis: [-bCcEeflNnRstuv] [-B backup-prefix] [-D symbol] [-d directory] [-F max-fuzz] [-i patchfile] [-o out-file] [-p strip-count] [-r rej-name] [-V t | nil | never | none] [-x number] [-z backup-ext] [--backup-if-mismatch] [--no-backup-if-mismatch] [--posix] [origfile [patchfile]]
-patch will take a patch file containing any of the four forms of difference listing produced by the `diff(1)` program and apply those differences to an original file, producing a patched version. If `patchfile` is omitted, or is a hyphen, the patch will be read from the standard input.
-
-patch will attempt to determine the type of the diff listing, unless over-ruled by a `-c`, `-e`, `-n`, or `-u` option. Context diffs (old-style, new-style, and unified) and normal diffs are applied directly by the patch program itself, whereas ed diffs are simply fed to the `ed(1)` editor via a pipe.
-
-If the `patchfile` contains more than one patch, patch will try to apply each of them as if they came from separate patch files. This means, among other things, that it is assumed that the name of the file to patch must be determined for each diff listing, and that the garbage before each diff listing will be examined for interesting things such as file names and revision level (see the section on Filename Determination below).
-
-## OPTIONS
-### -B backup-prefix, --prefix backup-prefix
-Causes the next argument to be interpreted as a prefix to the backup file name. If this argument is specified, any argument to `-z` will be ignored.
-
-### -b, --backup
-Save a backup copy of the file before it is modified. By default the original file is saved with a backup extension of `.orig` unless the file already has a numbered backup, in which case a numbered backup is made. This is equivalent to specifying `-V existing`. This option is currently the default, unless `--posix` is specified.
-
-### --backup-if-mismatch
-Create a backup file if the patch doesn't apply cleanly. This option only makes sense when `--backup` is disabled, i.e. when in `--posix` mode.
-
-### -C, --check
-Checks that the patch would apply cleanly, but does not modify anything.
-
-### -c, --context
-Forces patch to interpret the patch file as a context diff.
-
-### -D symbol, --ifdef symbol
-Causes patch to use the `#ifdef...#endif` construct to mark changes. The argument following will be used as the differentiating symbol. Note that, unlike the C compiler, there must be a space between the `-D` and the argument.
-
-### -d directory, --directory directory
-Causes patch to interpret the next argument as a directory, and change the working directory to it before doing anything else.
-
-### -E, --remove-empty-files
-Causes patch to remove output files that are empty after the patches have been applied. This option is useful when applying patches that create or remove files.
-
-### -e, --ed
-Forces patch to interpret the patch file as an `ed(1)` script.
-
-### -F max-fuzz, --fuzz max-fuzz
-Sets the maximum fuzz factor. This option only applies to context diffs, and causes patch to ignore up to that many lines in looking for places to install a hunk. Note that a larger fuzz factor increases the odds of a faulty patch. The default fuzz factor is 2, and it may not be set to more than the number of lines of context in the context diff, ordinarily 3.
-
-### -f, --force
-Forces patch to assume that the user knows exactly what he or she is doing, and to not ask any questions. It assumes the following: skip patches for which a file to patch can't be found; patch files even though they have the wrong version for the `Prereq:` line in the patch; and assume that patches are not reversed even if they look like they are. This option does not suppress commentary; use `-s` for that.
-
-### -i patchfile, --input patchfile
-Causes the next argument to be interpreted as the input file name (i.e., a patchfile). This option may be specified multiple times.
-
-### -l, --ignore-whitespace
-Causes the pattern matching to be done loosely, in case the tabs and spaces have been munged in your input file. Any sequence of whitespace in the pattern line will match any sequence in the input file. Normal characters must still match exactly. Each line of the context must still match a line in the input file.
-
-### -N, --forward
-Causes patch to ignore patches that it thinks are reversed or already applied. See also `-R`.
-
-### -n, --normal
-Forces patch to interpret the patch file as a normal diff.
-
-### --no-backup-if-mismatch
-Turn off `--backup-if-mismatch`. This option exists mostly for compatibility with GNU patch.
-
-### -o out-file, --output out-file
-Causes the next argument to be interpreted as the output file name.
-
-### -p strip-count, --strip strip-count
-Sets the pathname strip count, which controls how pathnames found in the patch file are treated, in case you keep your files in a different directory than the person who sent out the patch. The strip count specifies how many slashes are to be stripped from the front of the pathname. (Any intervening directory names also go away.) For example, supposing the file name in the patch file was `/u/howard/src/blurfl/blurfl.c`:
-
-Setting `-p0` gives the entire pathname unmodified.
-
-`-p1` gives
-
-`u/howard/src/blurfl/blurfl.c`
-
-without the leading slash.
-
-`-p4` gives
-
-`blurfl/blurfl.c`
-
-Not specifying `-p` at all just gives you `blurfl.c`, unless all of the directories in the leading path (`u/howard/src/blurfl`) exist and that path is relative, in which case you get the entire pathname unmodified. Whatever you end up with is looked for either in the current directory, or the directory specified by the `-d` option.
-
-### -R, --reverse
-Tells patch that this patch was created with the old and new files swapped. (Yes, I'm afraid that does happen occasionally, human nature being what it is.) patch will attempt to swap each hunk around before applying it. Rejects will come out in the swapped format. The `-R` option will not work with ed diff scripts because there is too little information to reconstruct the reverse operation.
-
-If the first hunk of a patch fails, patch will reverse the hunk to see if it can be applied that way. If it can, you will be asked if you want to have the `-R` option set. If it can't, the patch will continue to be applied normally. (Note: this method cannot detect a reversed patch if it is a normal diff and if the first command is an append (i.e., it should have been a delete) since appends always succeed, due to the fact that a null context will match anywhere. Luckily, most patches add or change lines rather than delete them, so most reversed normal diffs will begin with a delete, which will fail, triggering the heuristic.)
-
-### -r rej-name, --reject-file rej-name
-Causes the next argument to be interpreted as the reject file name.
-
-### -s, --quiet, --silent
-Makes patch do its work silently, unless an error occurs.
-
-### -t, --batch
-Similar to `-f`, in that it suppresses questions, but makes some different assumptions: skip patches for which a file to patch can't be found (the same as `-f`); skip patches for which the file has the wrong version for the `Prereq:` line in the patch; and assume that patches are reversed if they look like they are.
-
-### -u, --unified
-Forces patch to interpret the patch file as a unified context diff (a unidiff).
-
-### -V t | nil | never | none, --version-control t | nil | never | none
-Causes the next argument to be interpreted as a method for creating backup file names. The type of backups made can also be given in the `PATCH_VERSION_CONTROL` or `VERSION_CONTROL` environment variables, which are overridden by this option. The `-B` option overrides this option, causing the prefix to always be used for making backup file names. The values of the `PATCH_VERSION_CONTROL` and `VERSION_CONTROL` environment variables and the argument to the `-V` option are like the GNU Emacs "version-control" variable; they also recognize synonyms that are more descriptive. The valid values are (unique abbreviations are accepted):
-
-`t`, numbered
-: Always make numbered backups.
-
-`nil`, existing
-: Make numbered backups of files that already have them, simple backups of the others.
-
-`never`, simple
-: Always make simple backups.
-
-`none`
-: No backups are created.
-
-### -v, --version
-Causes patch to print out its revision header and patch level.
-
-### -x number, --debug number
-Sets internal debugging flags, and is of interest only to patchers.
-
-### -z backup-ext, --suffix backup-ext
-Causes the next argument to be interpreted as the backup extension, to be used in place of `.orig`.
-
-### --posix
-Enables strict POSIX.1-2004 conformance, specifically:
-
-Backup files are not created unless the `-b` option is specified.
-
-If unspecified, the file name used is the first of the old, new and index files that exists.
-
-## Patch Application
-patch will try to skip any leading garbage, apply the diff, and then skip any trailing garbage. Thus you could feed an article or message containing a diff listing to patch, and it should work. If the entire diff is indented by a consistent amount, this will be taken into account.
-
-With context diffs, and to a lesser extent with normal diffs, patch can detect when the line numbers mentioned in the patch are incorrect, and will attempt to find the correct place to apply each hunk of the patch. As a first guess, it takes the line number mentioned for the hunk, plus or minus any offset used in applying the previous hunk. If that is not the correct place, patch will scan both forwards and backwards for a set of lines matching the context given in the hunk. First patch looks for a place where all lines of the context match. If no such place is found, and it's a context diff, and the maximum fuzz factor is set to 1 or more, then another scan takes place ignoring the first and last line of context. If that fails, and the maximum fuzz factor is set to 2 or more, the first two and last two lines of context are ignored, and another scan is made. (The default maximum fuzz factor is 2.)
-
-If patch cannot find a place to install that hunk of the patch, it will put the hunk out to a reject file, which normally is the name of the output file plus `.rej`. (Note that the rejected hunk will come out in context diff form whether the input patch was a context diff or a normal diff. If the input was a normal diff, many of the contexts will simply be null.) The line numbers on the hunks in the reject file may be different than in the patch file: they reflect the approximate location patch thinks the failed hunks belong in the new file rather than the old one.
-
-As each hunk is completed, you will be told whether the hunk succeeded or failed, and which line (in the new file) patch thought the hunk should go on. If this is different from the line number specified in the diff, you will be told the offset. A single large offset MAY be an indication that a hunk was installed in the wrong place. You will also be told if a fuzz factor was used to make the match, in which case you should also be slightly suspicious.
-
-## Filename Determination
-If no original file is specified on the command line, patch will try to figure out from the leading garbage what the name of the file to edit is. When checking a prospective file name, pathname components are stripped as specified by the `-p` option and the file's existence and writability are checked relative to the current working directory (or the directory specified by the `-d` option).
-
-If the diff is a context or unified diff, patch is able to determine the old and new file names from the diff header. For context diffs, the "old" file is specified in the line beginning with "***" and the "new" file is specified in the line beginning with "---". For a unified diff, the "old" file is specified in the line beginning with "---" and the "new" file is specified in the line beginning with "+++". If there is an `Index:` line in the leading garbage (regardless of the diff type), patch will use the file name from that line as the "index" file.
-
-patch will choose the file name by performing the following steps, with the first match used:
-
-If patch is operating in strict POSIX.1-2004 mode, the first of the "old", "new" and "index" file names that exist is used. Otherwise, patch will examine either the "old" and "new" file names or, for a non-context diff, the "index" file name, and choose the file name with the fewest path components, the shortest basename, and the shortest total file name length (in that order).
-
-If no file exists, patch checks for the existence of the files in an RCS directory using the criteria specified above. If found, patch will attempt to get or check out the file.
-
-If no suitable file was found to patch, the patch file is a context or unified diff, and the old file was zero length, the new file name is created and used.
-
-If the file name still cannot be determined, patch will prompt the user for the file name to use.
-
-Additionally, if the leading garbage contains a `Prereq:` line, patch will take the first word from the prerequisites line (normally a version number) and check the input file to see if that word can be found. If not, patch will ask for confirmation before proceeding.
-
-The upshot of all this is that you should be able to say, while in a news interface, the following:
-
-`| patch -d /usr/src/local/blurfl`
-
-and patch a file in the blurfl directory directly from the article containing the patch.
-
-## Backup Files
-By default, the patched version is put in place of the original, with the original file backed up to the same name with the extension `.orig`, or as specified by the `-B`, `-V`, or `-z` options. The extension used for making backup files may also be specified in the `SIMPLE_BACKUP_SUFFIX` environment variable, which is overridden by the options above.
-
-If the backup file is a symbolic or hard link to the original file, patch creates a new backup file name by changing the first lowercase letter in the last component of the file's name into uppercase. If there are no more lowercase letters in the name, it removes the first character from the name. It repeats this process until it comes up with a backup file that does not already exist or is not linked to the original file.
-
-You may also specify where you want the output to go with the `-o` option; if that file already exists, it is backed up first.
-
-## Notes For Patch Senders
-There are several things you should bear in mind if you are going to be sending out patches:
-
-First, you can save people a lot of grief by keeping a `patchlevel.h` file which is patched to increment the patch level as the first diff in the patch file you send out. If you put a `Prereq:` line in with the patch, it won't let them apply patches out of order without some warning.
-
-Second, make sure you've specified the file names right, either in a context diff header, or with an `Index:` line. If you are patching something in a subdirectory, be sure to tell the patch user to specify a `-p` option as needed.
-
-Third, you can create a file by sending out a diff that compares a null file to the file you want to create. This will only work if the file you want to create doesn't exist already in the target directory.
-
-Fourth, take care not to send out reversed patches, since it makes people wonder whether they already applied the patch.
-
-Fifth, while you may be able to get away with putting 582 diff listings into one file, it is probably wiser to group related patches into separate files in case something goes haywire.
-
-## ENVIRONMENT
-`POSIXLY_CORRECT`
-: When set, patch behaves as if the `--posix` option has been specified.
-
-`SIMPLE_BACKUP_SUFFIX`
-: Extension to use for backup file names instead of `.orig`.
-
-`TMPDIR`
-: Directory to put temporary files in; default is `/tmp`.
-
-`PATCH_VERSION_CONTROL`
-: Selects when numbered backup files are made.
-
-`VERSION_CONTROL`
-: Same as `PATCH_VERSION_CONTROL`.
-
-## FILES
-`$TMPDIR/patch*`
-: patch temporary files
-
-`/dev/tty`
-: used to read input when patch prompts the user
-
-## DIAGNOSTICS
-Too many to list here, but generally indicative that patch couldn't parse your patch file.
-
-The message "Hmm..." indicates that there is unprocessed text in the patch file and that patch is attempting to intuit whether there is a patch in that text and, if so, what kind of patch it is.
-
-The patch utility exits with one of the following values:
-
-`0`
-: Successful completion.
-
-`1`
-: One or more lines were written to a reject file.
-
-`>1`
-: An error occurred.
-
-When applying a set of patches in a loop it behooves you to check this exit status so you don't apply a later patch to a partially patched file.
-
-## SEE ALSO
-`diff(1)`
-
-## STANDARDS
-The patch utility is compliant with the POSIX.1-2004 specification (except as detailed above for the `--posix` option), though the presence of patch itself is optional.
-
-The flags `-C`, `-E`, `-f`, `-s`, `-t`, `-u`, `-v`, `-B`, `-F`, `-V`, `-x`, and `-z` and `--posix` are extensions to that specification.
-
-## AUTHORS
-Larry Wall with many other contributors.
-
-## CAVEATS
-patch cannot tell if the line numbers are off in an ed script, and can only detect bad line numbers in a normal diff when it finds a "change" or a "delete" command. A context diff using fuzz factor 3 may have the same problem. Until a suitable interactive interface is added, you should probably do a context diff in these cases to see if the changes made sense. Of course, compiling without errors is a pretty good indication that the patch worked, but not always.
-
-patch usually produces the correct results, even when it has to do a lot of guessing. However, the results are guaranteed to be correct only when the patch is applied to exactly the same version of the file that the patch was generated from.
-
-## BUGS
-Could be smarter about partial matches, excessively deviant offsets and swapped code, but that would take an extra pass.
-
-Check patch mode (`-C`) will fail if you try to check several patches in succession that build on each other. The entire patch code would have to be restructured to keep temporary files around so that it can handle this situation.
-
-If code has been duplicated (for instance with `#ifdef OLDCODE ... #else ... #endif`), patch is incapable of patching both versions, and, if it works at all, will likely patch the wrong one, and tell you that it succeeded to boot.
-
-If you apply a patch you've already applied, patch will think it is a reversed patch, and offer to un-apply the patch. This could be construed as a feature.
-*/
-
-#include <sys/types.h>
-#include <sys/stat.h>
-
-#include <ctype.h>
-#include <getopt.h>
-#include <limits.h>
-#include <stdio.h>
-#include <string.h>
-#include <stdlib.h>
-#include <unistd.h>
-
-#include "common.h"
-#include "util.h"
-#include "pch.h"
-#include "inp.h"
-#include "backupfile.h"
-#include "pathnames.h"
-
-mode_t filemode = 0644;
-
-char *buf; /* general purpose buffer */
-size_t bufsz; /* general purpose buffer size */
-
-bool using_plan_a = true; /* try to keep everything in memory */
-bool out_of_mem = false; /* ran out of memory in plan a */
-
-#define MAXFILEC 2
-
-char *filearg[MAXFILEC];
-bool ok_to_create_file = false;
-char *outname = NULL;
-char *origprae = NULL;
-char *TMPOUTNAME;
-char *TMPINNAME;
-char *TMPREJNAME;
-char *TMPPATNAME;
-bool toutkeep = false;
-bool trejkeep = false;
-bool warn_on_invalid_line;
-bool last_line_missing_eol;
-
-#ifdef DEBUGGING
-int debug = 0;
-#endif
-
-bool force = false;
-bool batch = false;
-bool verbose = true;
-bool reverse = false;
-bool noreverse = false;
-bool skip_rest_of_patch = false;
-int strippath = 957;
-bool canonicalize = false;
-bool check_only = false;
-int diff_type = 0;
-char *revision = NULL; /* prerequisite revision, if any */
-LINENUM input_lines = 0; /* how long is input file in lines */
-int posix = 0; /* strict POSIX mode? */
-int backup_if_mismatch = -1;/* create backup file when patch doesn't apply cleanly */
-
-static void reinitialize_almost_everything(void);
-static void get_some_switches(void);
-static void reset_getopt_state(void);
-static LINENUM locate_hunk(LINENUM);
-static void abort_context_hunk(void);
-static void rej_line(int, LINENUM);
-static void abort_hunk(void);
-static void apply_hunk(LINENUM);
-static void init_output(const char *);
-static void init_reject(const char *);
-static void copy_till(LINENUM, bool);
-static bool spew_output(void);
-static void dump_line(LINENUM, bool);
-static bool patch_match(LINENUM, LINENUM, LINENUM);
-static bool similar(const char *, const char *, ssize_t);
-__dead static void usage(void);
-
-/* true if -E was specified on command line. */
-static bool remove_empty_files = false;
-
-/* true if -R was specified on command line. */
-static bool reverse_flag_specified = false;
-
-/* buffer holding the name of the rejected patch file. */
-static char rejname[PATH_MAX];
-
-/* buffer for stderr */
-static char serrbuf[BUFSIZ];
-
-/* how many input lines have been irretractibly output */
-static LINENUM last_frozen_line = 0;
-
-static int Argc; /* guess */
-static char **Argv;
-static int Argc_last; /* for restarting plan_b */
-static char **Argv_last;
-
-static FILE *ofp = NULL; /* output file pointer */
-static FILE *rejfp = NULL; /* reject file pointer */
-
-static int filec = 0; /* how many file arguments? */
-static LINENUM last_offset = 0;
-static LINENUM maxfuzz = 2;
-
-/* patch using ifdef, ifndef, etc. */
-static bool do_defines = false;
-/* #ifdef xyzzy */
-static char if_defined[128];
-/* #ifndef xyzzy */
-static char not_defined[128];
-/* #else */
-static const char else_defined[] = "#else\n";
-/* #endif xyzzy */
-static char end_defined[128];
-
-
-/* Apply a set of diffs as appropriate. */
-
-int
-main(int argc, char *argv[])
-{
- int error = 0, hunk, failed, i, fd;
- LINENUM where = 0, newwhere, fuzz, mymaxfuzz;
- const char *tmpdir;
- char *v;
-
- bufsz = INITLINELEN;
- if ((buf = malloc(bufsz)) == NULL)
- pfatal("allocating input buffer");
- buf[0] = '\0';
-
- setbuf(stderr, serrbuf);
- for (i = 0; i < MAXFILEC; i++)
- filearg[i] = NULL;
-
- /* Cons up the names of the temporary files. */
- if ((tmpdir = getenv("TMPDIR")) == NULL || *tmpdir == '\0')
- tmpdir = _PATH_TMP;
- for (i = strlen(tmpdir) - 1; i > 0 && tmpdir[i] == '/'; i--)
- ;
- i++;
- if (asprintf(&TMPOUTNAME, "%.*s/patchoXXXXXXXXXX", i, tmpdir) == -1)
- fatal("cannot allocate memory");
- if ((fd = mkstemp(TMPOUTNAME)) < 0)
- pfatal("can't create %s", TMPOUTNAME);
- close(fd);
-
- if (asprintf(&TMPINNAME, "%.*s/patchiXXXXXXXXXX", i, tmpdir) == -1)
- fatal("cannot allocate memory");
- if ((fd = mkstemp(TMPINNAME)) < 0)
- pfatal("can't create %s", TMPINNAME);
- close(fd);
-
- if (asprintf(&TMPREJNAME, "%.*s/patchrXXXXXXXXXX", i, tmpdir) == -1)
- fatal("cannot allocate memory");
- if ((fd = mkstemp(TMPREJNAME)) < 0)
- pfatal("can't create %s", TMPREJNAME);
- close(fd);
-
- if (asprintf(&TMPPATNAME, "%.*s/patchpXXXXXXXXXX", i, tmpdir) == -1)
- fatal("cannot allocate memory");
- if ((fd = mkstemp(TMPPATNAME)) < 0)
- pfatal("can't create %s", TMPPATNAME);
- close(fd);
-
- v = getenv("SIMPLE_BACKUP_SUFFIX");
- if (v)
- simple_backup_suffix = v;
- else
- simple_backup_suffix = ORIGEXT;
-
- if ((v = getenv("PATCH_VERSION_CONTROL")) == NULL)
- v = getenv("VERSION_CONTROL");
- if (v != NULL)
- backup_type = get_version(v);
-
- /* parse switches */
- Argc = argc;
- Argv = argv;
- get_some_switches();
-
- if (backup_type == undefined)
- backup_type = posix ? none : numbered_existing;
-
- /* make sure we clean up /tmp in case of disaster */
- set_signals(0);
-
- for (open_patch_file(filearg[1]); there_is_another_patch();
- reinitialize_almost_everything()) {
- /* for each patch in patch file */
-
- warn_on_invalid_line = true;
-
- if (outname == NULL)
- outname = savestr(filearg[0]);
-
- /* for ed script just up and do it and exit */
- if (diff_type == ED_DIFF) {
- do_ed_script();
- continue;
- }
- /* initialize the patched file */
- if (!skip_rest_of_patch)
- init_output(TMPOUTNAME);
-
- /* initialize reject file */
- init_reject(TMPREJNAME);
-
- /* find out where all the lines are */
- if (!skip_rest_of_patch)
- scan_input(filearg[0]);
-
- /* from here on, open no standard i/o files, because malloc */
- /* might misfire and we can't catch it easily */
-
- /* apply each hunk of patch */
- hunk = 0;
- failed = 0;
- out_of_mem = false;
- while (another_hunk()) {
- hunk++;
- fuzz = 0;
- mymaxfuzz = pch_context();
- if (maxfuzz < mymaxfuzz)
- mymaxfuzz = maxfuzz;
- if (!skip_rest_of_patch) {
- do {
- where = locate_hunk(fuzz);
- if (hunk == 1 && where == 0 && !force) {
- /* dwim for reversed patch? */
- if (!pch_swap()) {
- if (fuzz == 0)
- say("Not enough memory to try swapped hunk! Assuming unswapped.\n");
- continue;
- }
- reverse = !reverse;
- /* try again */
- where = locate_hunk(fuzz);
- if (where == 0) {
- /* didn't find it swapped */
- if (!pch_swap())
- /* put it back to normal */
- fatal("lost hunk on alloc error!\n");
- reverse = !reverse;
- } else if (noreverse) {
- if (!pch_swap())
- /* put it back to normal */
- fatal("lost hunk on alloc error!\n");
- reverse = !reverse;
- say("Ignoring previously applied (or reversed) patch.\n");
- skip_rest_of_patch = true;
- } else if (batch) {
- if (verbose)
- say("%seversed (or %spreviously applied) patch detected! %s -R.",
- reverse ? "R" : "Unr",
- reverse ? "" : "not ",
- reverse ? "Assuming" : "Ignoring");
- } else {
- ask("%seversed (or %spreviously applied) patch detected! %s -R? [y] ",
- reverse ? "R" : "Unr",
- reverse ? "" : "not ",
- reverse ? "Assume" : "Ignore");
- if (*buf == 'n') {
- ask("Apply anyway? [n] ");
- if (*buf != 'y')
- skip_rest_of_patch = true;
- where = 0;
- reverse = !reverse;
- if (!pch_swap())
- /* put it back to normal */
- fatal("lost hunk on alloc error!\n");
- }
- }
- }
- } while (!skip_rest_of_patch && where == 0 &&
- ++fuzz <= mymaxfuzz);
-
- if (skip_rest_of_patch) { /* just got decided */
- if (ferror(ofp) || fclose(ofp)) {
- say("Error writing %s\n",
- TMPOUTNAME);
- error = 1;
- }
- ofp = NULL;
- }
- }
- newwhere = pch_newfirst() + last_offset;
- if (skip_rest_of_patch) {
- abort_hunk();
- failed++;
- if (verbose)
- say("Hunk #%d ignored at %ld.\n",
- hunk, newwhere);
- } else if (where == 0) {
- abort_hunk();
- failed++;
- if (verbose)
- say("Hunk #%d failed at %ld.\n",
- hunk, newwhere);
- } else {
- apply_hunk(where);
- if (verbose) {
- say("Hunk #%d succeeded at %ld",
- hunk, newwhere);
- if (fuzz != 0)
- say(" with fuzz %ld", fuzz);
- if (last_offset)
- say(" (offset %ld line%s)",
- last_offset,
- last_offset == 1L ? "" : "s");
- say(".\n");
- }
- }
- }
-
- if (out_of_mem && using_plan_a) {
- Argc = Argc_last;
- Argv = Argv_last;
- say("\n\nRan out of memory using Plan A--trying again...\n\n");
- if (ofp)
- fclose(ofp);
- ofp = NULL;
- if (rejfp)
- fclose(rejfp);
- rejfp = NULL;
- continue;
- }
- if (hunk == 0)
- fatal("Internal error: hunk should not be 0\n");
-
- /* finish spewing out the new file */
- if (!skip_rest_of_patch && !spew_output()) {
- say("Can't write %s\n", TMPOUTNAME);
- error = 1;
- }
-
- /* and put the output where desired */
- ignore_signals();
- if (!skip_rest_of_patch) {
- struct stat statbuf;
- char *realout = outname;
-
- if (!check_only) {
- /* handle --backup-if-mismatch */
- enum backup_type saved = backup_type;
- if (failed > 0 && backup_if_mismatch > 0 && backup_type == none)
- backup_type = simple;
- if (move_file(TMPOUTNAME, outname) < 0) {
- toutkeep = true;
- realout = TMPOUTNAME;
- chmod(TMPOUTNAME, filemode);
- } else
- chmod(outname, filemode);
- backup_type = saved;
-
- if (remove_empty_files &&
- stat(realout, &statbuf) == 0 &&
- statbuf.st_size == 0) {
- if (verbose)
- say("Removing %s (empty after patching).\n",
- realout);
- unlink(realout);
- }
- }
- }
- if (ferror(rejfp) || fclose(rejfp)) {
- say("Error writing %s\n", rejname);
- error = 1;
- }
- rejfp = NULL;
- if (failed) {
- error = 1;
- if (*rejname == '\0') {
- if (strlcpy(rejname, outname,
- sizeof(rejname)) >= sizeof(rejname))
- fatal("filename %s is too long\n", outname);
- if (strlcat(rejname, REJEXT,
- sizeof(rejname)) >= sizeof(rejname))
- fatal("filename %s is too long\n", outname);
- }
- if (skip_rest_of_patch) {
- say("%d out of %d hunks ignored--saving rejects to %s\n",
- failed, hunk, rejname);
- } else {
- say("%d out of %d hunks FAILED -- saving rejects to %s\n",
- failed, hunk, rejname);
- }
- if (!check_only && move_file(TMPREJNAME, rejname) < 0)
- trejkeep = true;
- }
- set_signals(1);
- }
- my_exit(error);
- /* NOTREACHED */
-}
-
-static void
-reset_getopt_state(void)
-{
-#if defined(__GLIBC__) || defined(__linux__)
- optind = 0;
-#else
- optreset = 1;
- optind = 1;
-#endif
-}
-
-/* Prepare to find the next patch to do in the patch file. */
-
-static void
-reinitialize_almost_everything(void)
-{
- re_patch();
- re_input();
-
- input_lines = 0;
- last_frozen_line = 0;
-
- filec = 0;
- if (!out_of_mem) {
- free(filearg[0]);
- filearg[0] = NULL;
- }
-
- free(outname);
- outname = NULL;
-
- last_offset = 0;
- diff_type = 0;
-
- free(revision);
- revision = NULL;
-
- reverse = reverse_flag_specified;
- skip_rest_of_patch = false;
-
- get_some_switches();
-}
-
-/* Process switches and filenames. */
-
-static void
-get_some_switches(void)
-{
- const char *options = "b::B:cCd:D:eEfF:i:lnNo:p:r:RstuvV:x:z:";
- static struct option longopts[] = {
- {"backup", no_argument, 0, 'b'},
- {"backup-if-mismatch", no_argument, &backup_if_mismatch, 1},
- {"batch", no_argument, 0, 't'},
- {"check", no_argument, 0, 'C'},
- {"context", no_argument, 0, 'c'},
- {"debug", required_argument, 0, 'x'},
- {"directory", required_argument, 0, 'd'},
- {"ed", no_argument, 0, 'e'},
- {"force", no_argument, 0, 'f'},
- {"forward", no_argument, 0, 'N'},
- {"fuzz", required_argument, 0, 'F'},
- {"ifdef", required_argument, 0, 'D'},
- {"input", required_argument, 0, 'i'},
- {"ignore-whitespace", no_argument, 0, 'l'},
- {"no-backup-if-mismatch", no_argument, &backup_if_mismatch, 0},
- {"normal", no_argument, 0, 'n'},
- {"output", required_argument, 0, 'o'},
- {"prefix", required_argument, 0, 'B'},
- {"quiet", no_argument, 0, 's'},
- {"reject-file", required_argument, 0, 'r'},
- {"remove-empty-files", no_argument, 0, 'E'},
- {"reverse", no_argument, 0, 'R'},
- {"silent", no_argument, 0, 's'},
- {"strip", required_argument, 0, 'p'},
- {"suffix", required_argument, 0, 'z'},
- {"unified", no_argument, 0, 'u'},
- {"version", no_argument, 0, 'v'},
- {"version-control", required_argument, 0, 'V'},
- {"posix", no_argument, &posix, 1},
- {NULL, 0, 0, 0}
- };
- int ch;
-
- rejname[0] = '\0';
- Argc_last = Argc;
- Argv_last = Argv;
- if (!Argc)
- return;
- reset_getopt_state();
- while ((ch = getopt_long(Argc, Argv, options, longopts, NULL)) != -1) {
- switch (ch) {
- case 'b':
- if (backup_type == undefined)
- backup_type = numbered_existing;
- if (optarg == NULL)
- break;
- if (verbose)
- say("Warning, the ``-b suffix'' option has been"
- " obsoleted by the -z option.\n");
- /* FALLTHROUGH */
- case 'z':
- /* must directly follow 'b' case for backwards compat */
- simple_backup_suffix = savestr(optarg);
- break;
- case 'B':
- origprae = savestr(optarg);
- break;
- case 'c':
- diff_type = CONTEXT_DIFF;
- break;
- case 'C':
- check_only = true;
- break;
- case 'd':
- if (chdir(optarg) < 0)
- pfatal("can't cd to %s", optarg);
- break;
- case 'D':
- do_defines = true;
- if (!isalpha((unsigned char)*optarg) && *optarg != '_')
- fatal("argument to -D is not an identifier\n");
- snprintf(if_defined, sizeof if_defined,
- "#ifdef %s\n", optarg);
- snprintf(not_defined, sizeof not_defined,
- "#ifndef %s\n", optarg);
- snprintf(end_defined, sizeof end_defined,
- "#endif /* %s */\n", optarg);
- break;
- case 'e':
- diff_type = ED_DIFF;
- break;
- case 'E':
- remove_empty_files = true;
- break;
- case 'f':
- force = true;
- break;
- case 'F':
- maxfuzz = atoi(optarg);
- break;
- case 'i':
- if (++filec == MAXFILEC)
- fatal("too many file arguments\n");
- filearg[filec] = savestr(optarg);
- break;
- case 'l':
- canonicalize = true;
- break;
- case 'n':
- diff_type = NORMAL_DIFF;
- break;
- case 'N':
- noreverse = true;
- break;
- case 'o':
- outname = savestr(optarg);
- break;
- case 'p':
- strippath = atoi(optarg);
- break;
- case 'r':
- if (strlcpy(rejname, optarg,
- sizeof(rejname)) >= sizeof(rejname))
- fatal("argument for -r is too long\n");
- break;
- case 'R':
- reverse = true;
- reverse_flag_specified = true;
- break;
- case 's':
- verbose = false;
- break;
- case 't':
- batch = true;
- break;
- case 'u':
- diff_type = UNI_DIFF;
- break;
- case 'v':
- version();
- break;
- case 'V':
- backup_type = get_version(optarg);
- break;
-#ifdef DEBUGGING
- case 'x':
- debug = atoi(optarg);
- break;
-#endif
- default:
- if (ch != '\0')
- usage();
- break;
- }
- }
- Argc -= optind;
- Argv += optind;
-
- if (Argc > 0) {
- filearg[0] = savestr(*Argv++);
- Argc--;
- while (Argc > 0) {
- if (++filec == MAXFILEC)
- fatal("too many file arguments\n");
- filearg[filec] = savestr(*Argv++);
- Argc--;
- }
- }
-
- if (getenv("POSIXLY_CORRECT") != NULL)
- posix = 1;
-
- if (backup_if_mismatch == -1) {
- backup_if_mismatch = posix ? 0 : 1;
- }
-}
-
-static void
-usage(void)
-{
- fprintf(stderr,
-"usage: patch [-bCcEeflNnRstuv] [-B backup-prefix] [-D symbol] [-d directory]\n"
-" [-F max-fuzz] [-i patchfile] [-o out-file] [-p strip-count]\n"
-" [-r rej-name] [-V t | nil | never] [-x number] [-z backup-ext]\n"
-" [--backup-if-mismatch] [--no-backup-if-mismatch] [--posix]\n"
-" [origfile [patchfile]]\n"
-" patch <patchfile\n");
- my_exit(EXIT_FAILURE);
-}
-
-/*
- * Attempt to find the right place to apply this hunk of patch.
- */
-static LINENUM
-locate_hunk(LINENUM fuzz)
-{
- LINENUM first_guess = pch_first() + last_offset;
- LINENUM offset;
- LINENUM pat_lines = pch_ptrn_lines();
- LINENUM max_pos_offset = input_lines - first_guess - pat_lines + 1;
- LINENUM max_neg_offset = first_guess - last_frozen_line - 1 + pch_context();
-
- if (pat_lines == 0) { /* null range matches always */
- if (verbose && fuzz == 0 && (diff_type == CONTEXT_DIFF
- || diff_type == NEW_CONTEXT_DIFF
- || diff_type == UNI_DIFF)) {
- say("Empty context always matches.\n");
- }
- return (first_guess);
- }
- if (max_neg_offset >= first_guess) /* do not try lines < 0 */
- max_neg_offset = first_guess - 1;
- if (first_guess <= input_lines && patch_match(first_guess, 0, fuzz))
- return first_guess;
- for (offset = 1; ; offset++) {
- bool check_after = (offset <= max_pos_offset);
- bool check_before = (offset <= max_neg_offset);
-
- if (check_after && patch_match(first_guess, offset, fuzz)) {
-#ifdef DEBUGGING
- if (debug & 1)
- say("Offset changing from %ld to %ld\n",
- last_offset, offset);
-#endif
- last_offset = offset;
- return first_guess + offset;
- } else if (check_before && patch_match(first_guess, -offset, fuzz)) {
-#ifdef DEBUGGING
- if (debug & 1)
- say("Offset changing from %ld to %ld\n",
- last_offset, -offset);
-#endif
- last_offset = -offset;
- return first_guess - offset;
- } else if (!check_before && !check_after)
- return 0;
- }
-}
-
-/* We did not find the pattern, dump out the hunk so they can handle it. */
-
-static void
-abort_context_hunk(void)
-{
- LINENUM i;
- const LINENUM pat_end = pch_end();
- /*
- * add in last_offset to guess the same as the previous successful
- * hunk
- */
- const LINENUM oldfirst = pch_first() + last_offset;
- const LINENUM newfirst = pch_newfirst() + last_offset;
- const LINENUM oldlast = oldfirst + pch_ptrn_lines() - 1;
- const LINENUM newlast = newfirst + pch_repl_lines() - 1;
- const char *stars = (diff_type >= NEW_CONTEXT_DIFF ? " ****" : "");
- const char *minuses = (diff_type >= NEW_CONTEXT_DIFF ? " ----" : " -----");
-
- fprintf(rejfp, "***************\n");
- for (i = 0; i <= pat_end; i++) {
- switch (pch_char(i)) {
- case '*':
- if (oldlast < oldfirst)
- fprintf(rejfp, "*** 0%s\n", stars);
- else if (oldlast == oldfirst)
- fprintf(rejfp, "*** %ld%s\n", oldfirst, stars);
- else
- fprintf(rejfp, "*** %ld,%ld%s\n", oldfirst,
- oldlast, stars);
- break;
- case '=':
- if (newlast < newfirst)
- fprintf(rejfp, "--- 0%s\n", minuses);
- else if (newlast == newfirst)
- fprintf(rejfp, "--- %ld%s\n", newfirst, minuses);
- else
- fprintf(rejfp, "--- %ld,%ld%s\n", newfirst,
- newlast, minuses);
- break;
- case '\n':
- fprintf(rejfp, "%s", pfetch(i));
- break;
- case ' ':
- case '-':
- case '+':
- case '!':
- fprintf(rejfp, "%c %s", pch_char(i), pfetch(i));
- break;
- default:
- fatal("fatal internal error in abort_context_hunk\n");
- }
- }
-}
-
-static void
-rej_line(int ch, LINENUM i)
-{
- size_t len;
- const char *line = pfetch(i);
-
- len = strlen(line);
-
- fprintf(rejfp, "%c%s", ch, line);
- if (len == 0 || line[len-1] != '\n')
- fprintf(rejfp, "\n\\ No newline at end of file\n");
-}
-
-static void
-abort_hunk(void)
-{
- LINENUM i, j, split;
- int ch1, ch2;
- const LINENUM pat_end = pch_end();
- const LINENUM oldfirst = pch_first() + last_offset;
- const LINENUM newfirst = pch_newfirst() + last_offset;
-
- if (diff_type != UNI_DIFF) {
- abort_context_hunk();
- return;
- }
- split = -1;
- for (i = 0; i <= pat_end; i++) {
- if (pch_char(i) == '=') {
- split = i;
- break;
- }
- }
- if (split == -1) {
- fprintf(rejfp, "malformed hunk: no split found\n");
- return;
- }
- i = 0;
- j = split + 1;
- fprintf(rejfp, "@@ -%ld,%ld +%ld,%ld @@\n",
- pch_ptrn_lines() ? oldfirst : 0,
- pch_ptrn_lines(), newfirst, pch_repl_lines());
- while (i < split || j <= pat_end) {
- ch1 = i < split ? pch_char(i) : -1;
- ch2 = j <= pat_end ? pch_char(j) : -1;
- if (ch1 == '-') {
- rej_line('-', i);
- i++;
- } else if (ch1 == ' ' && ch2 == ' ') {
- rej_line(' ', i);
- i++;
- j++;
- } else if (ch1 == '!' && ch2 == '!') {
- while (i < split && ch1 == '!') {
- rej_line('-', i);
- i++;
- ch1 = i < split ? pch_char(i) : -1;
- }
- while (j <= pat_end && ch2 == '!') {
- rej_line('+', j);
- j++;
- ch2 = j <= pat_end ? pch_char(j) : -1;
- }
- } else if (ch1 == '*') {
- i++;
- } else if (ch2 == '+' || ch2 == ' ') {
- rej_line(ch2, j);
- j++;
- } else {
- fprintf(rejfp, "internal error on (%ld %ld %ld)\n",
- i, split, j);
- rej_line(ch1, i);
- rej_line(ch2, j);
- return;
- }
- }
-}
-
-/* We found where to apply it (we hope), so do it. */
-
-static void
-apply_hunk(LINENUM where)
-{
- LINENUM old = 1;
- const LINENUM lastline = pch_ptrn_lines();
- LINENUM new = lastline + 1;
-#define OUTSIDE 0
-#define IN_IFNDEF 1
-#define IN_IFDEF 2
-#define IN_ELSE 3
- int def_state = OUTSIDE;
- const LINENUM pat_end = pch_end();
-
- where--;
- while (pch_char(new) == '=' || pch_char(new) == '\n')
- new++;
-
- while (old <= lastline) {
- if (pch_char(old) == '-') {
- copy_till(where + old - 1, false);
- if (do_defines) {
- if (def_state == OUTSIDE) {
- fputs(not_defined, ofp);
- def_state = IN_IFNDEF;
- } else if (def_state == IN_IFDEF) {
- fputs(else_defined, ofp);
- def_state = IN_ELSE;
- }
- fputs(pfetch(old), ofp);
- }
- last_frozen_line++;
- old++;
- } else if (new > pat_end) {
- break;
- } else if (pch_char(new) == '+') {
- copy_till(where + old - 1, false);
- if (do_defines) {
- if (def_state == IN_IFNDEF) {
- fputs(else_defined, ofp);
- def_state = IN_ELSE;
- } else if (def_state == OUTSIDE) {
- fputs(if_defined, ofp);
- def_state = IN_IFDEF;
- }
- }
- fputs(pfetch(new), ofp);
- new++;
- } else if (pch_char(new) != pch_char(old)) {
- say("Out-of-sync patch, lines %ld,%ld--mangled text or line numbers, maybe?\n",
- pch_hunk_beg() + old,
- pch_hunk_beg() + new);
-#ifdef DEBUGGING
- say("oldchar = '%c', newchar = '%c'\n",
- pch_char(old), pch_char(new));
-#endif
- my_exit(2);
- } else if (pch_char(new) == '!') {
- copy_till(where + old - 1, false);
- if (do_defines) {
- fputs(not_defined, ofp);
- def_state = IN_IFNDEF;
- }
- while (pch_char(old) == '!') {
- if (do_defines) {
- fputs(pfetch(old), ofp);
- }
- last_frozen_line++;
- old++;
- }
- if (do_defines) {
- fputs(else_defined, ofp);
- def_state = IN_ELSE;
- }
- while (pch_char(new) == '!') {
- fputs(pfetch(new), ofp);
- new++;
- }
- } else {
- if (pch_char(new) != ' ')
- fatal("Internal error: expected ' '\n");
- old++;
- new++;
- if (do_defines && def_state != OUTSIDE) {
- fputs(end_defined, ofp);
- def_state = OUTSIDE;
- }
- }
- }
- if (new <= pat_end && pch_char(new) == '+') {
- copy_till(where + old - 1, false);
- if (do_defines) {
- if (def_state == OUTSIDE) {
- fputs(if_defined, ofp);
- def_state = IN_IFDEF;
- } else if (def_state == IN_IFNDEF) {
- fputs(else_defined, ofp);
- def_state = IN_ELSE;
- }
- }
- while (new <= pat_end && pch_char(new) == '+') {
- fputs(pfetch(new), ofp);
- new++;
- }
- }
- if (do_defines && def_state != OUTSIDE) {
- fputs(end_defined, ofp);
- }
-}
-
-/*
- * Open the new file.
- */
-static void
-init_output(const char *name)
-{
- ofp = fopen(name, "w");
- if (ofp == NULL)
- pfatal("can't create %s", name);
-}
-
-/*
- * Open a file to put hunks we can't locate.
- */
-static void
-init_reject(const char *name)
-{
- rejfp = fopen(name, "w");
- if (rejfp == NULL)
- pfatal("can't create %s", name);
-}
-
-/*
- * Copy input file to output, up to wherever hunk is to be applied.
- * If endoffile is true, treat the last line specially since it may
- * lack a newline.
- */
-static void
-copy_till(LINENUM lastline, bool endoffile)
-{
- if (last_frozen_line > lastline)
- fatal("misordered hunks! output would be garbled\n");
- while (last_frozen_line < lastline) {
- if (++last_frozen_line == lastline && endoffile)
- dump_line(last_frozen_line, !last_line_missing_eol);
- else
- dump_line(last_frozen_line, true);
- }
-}
-
-/*
- * Finish copying the input file to the output file.
- */
-static bool
-spew_output(void)
-{
- int rv;
-
-#ifdef DEBUGGING
- if (debug & 256)
- say("il=%ld lfl=%ld\n", input_lines, last_frozen_line);
-#endif
- if (input_lines)
- copy_till(input_lines, true); /* dump remainder of file */
- rv = ferror(ofp) == 0 && fclose(ofp) == 0;
- ofp = NULL;
- return rv;
-}
-
-/*
- * Copy one line from input to output.
- */
-static void
-dump_line(LINENUM line, bool write_newline)
-{
- char *s;
-
- s = ifetch(line, 0);
- if (s == NULL)
- return;
- /* Note: string is not NUL terminated. */
- for (; *s != '\n'; s++)
- putc(*s, ofp);
- if (write_newline)
- putc('\n', ofp);
-}
-
-/*
- * Does the patch pattern match at line base+offset?
- */
-static bool
-patch_match(LINENUM base, LINENUM offset, LINENUM fuzz)
-{
- LINENUM pline = 1 + fuzz;
- LINENUM iline;
- LINENUM pat_lines = pch_ptrn_lines() - fuzz;
- const char *ilineptr;
- const char *plineptr;
- ssize_t plinelen;
-
- for (iline = base + offset + fuzz; pline <= pat_lines; pline++, iline++) {
- ilineptr = ifetch(iline, offset >= 0);
- if (ilineptr == NULL)
- return false;
- plineptr = pfetch(pline);
- plinelen = pch_line_len(pline);
- if (canonicalize) {
- if (!similar(ilineptr, plineptr, plinelen))
- return false;
- } else if (strnNE(ilineptr, plineptr, plinelen))
- return false;
- if (iline == input_lines) {
- /*
- * We are looking at the last line of the file.
- * If the file has no eol, the patch line should
- * not have one either and vice-versa. Note that
- * plinelen > 0.
- */
- if (last_line_missing_eol) {
- if (plineptr[plinelen - 1] == '\n')
- return false;
- } else {
- if (plineptr[plinelen - 1] != '\n')
- return false;
- }
- }
- }
- return true;
-}
-
-/*
- * Do two lines match with canonicalized white space?
- */
-static bool
-similar(const char *a, const char *b, ssize_t len)
-{
- while (len) {
- if (isspace((unsigned char)*b)) { /* whitespace (or \n) to match? */
- if (!isspace((unsigned char)*a)) /* no corresponding whitespace? */
- return false;
- while (len && isspace((unsigned char)*b) && *b != '\n')
- b++, len--; /* skip pattern whitespace */
- while (isspace((unsigned char)*a) && *a != '\n')
- a++; /* skip target whitespace */
- if (*a == '\n' || *b == '\n')
- return (*a == *b); /* should end in sync */
- } else if (*a++ != *b++) /* match non-whitespace chars */
- return false;
- else
- len--; /* probably not necessary */
- }
- return true; /* actually, this is not reached */
- /* since there is always a \n */
-}
diff --git a/cmd/posix/patch/pathnames.h b/cmd/posix/patch/pathnames.h
@@ -1,14 +0,0 @@
-/*
- * $OpenBSD: pathnames.h,v 1.1 2003/07/29 20:10:17 millert Exp $
- * $DragonFly: src/usr.bin/patch/pathnames.h,v 1.2 2008/08/11 00:04:12 joerg Exp $
- * $NetBSD: pathnames.h,v 1.1 2008/09/19 18:33:34 joerg Exp $
- */
-
-/*
- * Placed in the public domain by Todd C. Miller <Todd.Miller@courtesan.com>
- * on July 29, 2003.
- */
-
-#include <paths.h>
-
-#define _PATH_ED "/bin/ed"
diff --git a/cmd/posix/patch/pch.c b/cmd/posix/patch/pch.c
@@ -1,1596 +0,0 @@
-/*
- * $OpenBSD: pch.c,v 1.37 2007/09/02 15:19:33 deraadt Exp $
- * $DragonFly: src/usr.bin/patch/pch.c,v 1.6 2008/08/10 23:35:40 joerg Exp $
- * $NetBSD: pch.c,v 1.34 2024/07/12 15:48:39 manu 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/types.h>
-#include <sys/stat.h>
-
-#include <ctype.h>
-#include <libgen.h>
-#include <limits.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <unistd.h>
-
-#include "common.h"
-#include "util.h"
-#include "pch.h"
-#include "pathnames.h"
-
-/* Patch (diff listing) abstract type. */
-
-static long p_filesize; /* size of the patch file */
-static LINENUM p_first; /* 1st line number */
-static LINENUM p_newfirst; /* 1st line number of replacement */
-static LINENUM p_ptrn_lines; /* # lines in pattern */
-static LINENUM p_repl_lines; /* # lines in replacement text */
-static LINENUM p_end = -1; /* last line in hunk */
-static LINENUM p_max; /* max allowed value of p_end */
-static LINENUM p_context = 3; /* # of context lines */
-static LINENUM p_input_line = 0; /* current line # from patch file */
-static char **p_line = NULL;/* the text of the hunk */
-static ssize_t *p_len = NULL; /* length of each line */
-static char *p_char = NULL; /* +, -, and ! */
-static int hunkmax = INITHUNKMAX; /* size of above arrays to begin with */
-static int p_indent; /* indent to patch */
-static LINENUM p_base; /* where to intuit this time */
-static LINENUM p_bline; /* line # of p_base */
-static LINENUM p_start; /* where intuit found a patch */
-static LINENUM p_sline; /* and the line number for it */
-static LINENUM p_hunk_beg; /* line number of current hunk */
-static LINENUM p_efake = -1; /* end of faked up lines--don't free */
-static LINENUM p_bfake = -1; /* beg of faked up lines */
-static FILE *pfp = NULL; /* patch file pointer */
-static char *bestguess = NULL; /* guess at correct filename */
-
-static void grow_hunkmax(void);
-static int intuit_diff_type(void);
-static void next_intuit_at(LINENUM, LINENUM);
-static void skip_to(LINENUM, LINENUM);
-static int pgetline(char **, size_t *, FILE *);
-static char *best_name(const struct file_name *, bool);
-static char *posix_name(const struct file_name *, bool);
-static size_t num_components(const char *);
-
-/*
- * Prepare to look for the next patch in the patch file.
- */
-void
-re_patch(void)
-{
- p_first = 0;
- p_newfirst = 0;
- p_ptrn_lines = 0;
- p_repl_lines = 0;
- p_end = (LINENUM) - 1;
- p_max = 0;
- p_indent = 0;
-}
-
-/*
- * Open the patch file at the beginning of time.
- */
-void
-open_patch_file(const char *filename)
-{
- struct stat filestat;
-
- if (filename == NULL || *filename == '\0' || strEQ(filename, "-")) {
- pfp = fopen(TMPPATNAME, "w");
- if (pfp == NULL)
- pfatal("can't create %s", TMPPATNAME);
- while (getline(&buf, &bufsz, stdin) != -1)
- fprintf(pfp, "%s", buf);
- if (ferror(pfp) || fclose(pfp))
- pfatal("can't write %s", TMPPATNAME);
- filename = TMPPATNAME;
- }
- pfp = fopen(filename, "r");
- if (pfp == NULL)
- pfatal("patch file %s not found", filename);
- fstat(fileno(pfp), &filestat);
- p_filesize = filestat.st_size;
- next_intuit_at(0L, 1L); /* start at the beginning */
- set_hunkmax();
-}
-
-/*
- * Make sure our dynamically realloced tables are malloced to begin with.
- */
-void
-set_hunkmax(void)
-{
- if (p_line == NULL)
- p_line = calloc((size_t) hunkmax, sizeof(char *));
- if (p_len == NULL)
- p_len = calloc((size_t) hunkmax, sizeof(ssize_t));
- if (p_char == NULL)
- p_char = calloc((size_t) hunkmax, sizeof(char));
-}
-
-/*
- * Enlarge the arrays containing the current hunk of patch.
- */
-static void
-grow_hunkmax(void)
-{
- int new_hunkmax;
- char **new_p_line;
- ssize_t *new_p_len;
- char *new_p_char;
-
- new_hunkmax = hunkmax * 2;
-
- if (p_line == NULL || p_len == NULL || p_char == NULL)
- fatal("Internal memory allocation error\n");
-
- new_p_line = pch_realloc(p_line, new_hunkmax, sizeof(char *));
- if (new_p_line == NULL)
- free(p_line);
-
- new_p_len = pch_realloc(p_len, new_hunkmax, sizeof(ssize_t));
- if (new_p_len == NULL)
- free(p_len);
-
- new_p_char = pch_realloc(p_char, new_hunkmax, sizeof(char));
- if (new_p_char == NULL)
- free(p_char);
-
- p_char = new_p_char;
- p_len = new_p_len;
- p_line = new_p_line;
-
- if (p_line != NULL && p_len != NULL && p_char != NULL) {
- hunkmax = new_hunkmax;
- return;
- }
-
- if (!using_plan_a)
- fatal("out of memory\n");
- out_of_mem = true; /* whatever is null will be allocated again */
- /* from within plan_a(), of all places */
-}
-
-/* True if the remainder of the patch file contains a diff of some sort. */
-
-bool
-there_is_another_patch(void)
-{
- bool exists = false;
-
- if (p_base != 0L && p_base >= p_filesize) {
- if (verbose)
- say("done\n");
- return false;
- }
- if (verbose)
- say("Hmm...");
- diff_type = intuit_diff_type();
- if (!diff_type) {
- if (p_base != 0L) {
- if (verbose)
- say(" Ignoring the trailing garbage.\ndone\n");
- } else
- say(" I can't seem to find a patch in there anywhere.\n");
- return false;
- }
- if (verbose)
- say(" %sooks like %s to me...\n",
- (p_base == 0L ? "L" : "The next patch l"),
- diff_type == UNI_DIFF ? "a unified diff" :
- diff_type == CONTEXT_DIFF ? "a context diff" :
- diff_type == NEW_CONTEXT_DIFF ? "a new-style context diff" :
- diff_type == NORMAL_DIFF ? "a normal diff" :
- "an ed script");
- if (p_indent && verbose)
- say("(Patch is indented %d space%s.)\n", p_indent,
- p_indent == 1 ? "" : "s");
- skip_to(p_start, p_sline);
- while (filearg[0] == NULL) {
- if (force || batch) {
- say("No file to patch. Skipping...\n");
- filearg[0] = savestr(bestguess);
- skip_rest_of_patch = true;
- return true;
- }
- ask("File to patch: ");
- if (*buf != '\n') {
- free(bestguess);
- bestguess = savestr(buf);
- filearg[0] = fetchname(buf, &exists, 0);
- }
- if (!exists) {
- ask("No file found--skip this patch? [n] ");
- if (*buf != 'y')
- continue;
- if (verbose)
- say("Skipping patch...\n");
- free(filearg[0]);
- filearg[0] = fetchname(bestguess, &exists, 0);
- skip_rest_of_patch = true;
- return true;
- }
- }
- return true;
-}
-
-/* Determine what kind of diff is in the remaining part of the patch file. */
-
-static int
-intuit_diff_type(void)
-{
- long this_line = 0, previous_line;
- long first_command_line = -1;
- LINENUM fcl_line = -1;
- bool last_line_was_command = false, this_is_a_command = false;
- bool stars_last_line = false, stars_this_line = false;
- char *s, *t;
- int indent, retval;
- struct file_name names[MAX_FILE];
-
- memset(names, 0, sizeof(names));
- ok_to_create_file = false;
- fseek(pfp, p_base, SEEK_SET);
- p_input_line = p_bline - 1;
- for (;;) {
- previous_line = this_line;
- last_line_was_command = this_is_a_command;
- stars_last_line = stars_this_line;
- this_line = ftell(pfp);
- indent = 0;
- p_input_line++;
- if (getline(&buf, &bufsz, pfp) == -1) {
- if (first_command_line >= 0L) {
- /* nothing but deletes!? */
- p_start = first_command_line;
- p_sline = fcl_line;
- retval = ED_DIFF;
- goto scan_exit;
- } else {
- p_start = this_line;
- p_sline = p_input_line;
- retval = 0;
- goto scan_exit;
- }
- }
- for (s = buf; *s == ' ' || *s == '\t' || *s == 'X'; s++) {
- if (*s == '\t')
- indent += 8 - (indent % 8);
- else
- indent++;
- }
- for (t = s; isdigit((unsigned char)*t) || *t == ','; t++)
- ;
- this_is_a_command = (isdigit((unsigned char)*s) &&
- (*t == 'd' || *t == 'c' || *t == 'a'));
- if (first_command_line < 0L && this_is_a_command) {
- first_command_line = this_line;
- fcl_line = p_input_line;
- p_indent = indent; /* assume this for now */
- }
- if (!stars_last_line && strnEQ(s, "*** ", 4))
- names[OLD_FILE].path = fetchname(s + 4,
- &names[OLD_FILE].exists, strippath);
- else if (strnEQ(s, "--- ", 4))
- names[NEW_FILE].path = fetchname(s + 4,
- &names[NEW_FILE].exists, strippath);
- else if (strnEQ(s, "+++ ", 4))
- /* pretend it is the old name */
- names[OLD_FILE].path = fetchname(s + 4,
- &names[OLD_FILE].exists, strippath);
- else if (strnEQ(s, "Index:", 6))
- names[INDEX_FILE].path = fetchname(s + 6,
- &names[INDEX_FILE].exists, strippath);
- else if (strnEQ(s, "Prereq:", 7)) {
- for (t = s + 7; isspace((unsigned char)*t); t++)
- ;
- revision = savestr(t);
- for (t = revision; *t && !isspace((unsigned char)*t); t++)
- ;
- *t = '\0';
- if (*revision == '\0') {
- free(revision);
- revision = NULL;
- }
- }
- if ((!diff_type || diff_type == ED_DIFF) &&
- first_command_line >= 0L &&
- strEQ(s, ".\n")) {
- p_indent = indent;
- p_start = first_command_line;
- p_sline = fcl_line;
- retval = ED_DIFF;
- goto scan_exit;
- }
- if ((!diff_type || diff_type == UNI_DIFF) && strnEQ(s, "@@ -", 4)) {
- if (strnEQ(s + 4, "0,0", 3))
- ok_to_create_file = true;
- p_indent = indent;
- p_start = this_line;
- p_sline = p_input_line;
- retval = UNI_DIFF;
- goto scan_exit;
- }
- stars_this_line = strnEQ(s, "********", 8);
- if ((!diff_type || diff_type == CONTEXT_DIFF) && stars_last_line &&
- strnEQ(s, "*** ", 4)) {
- if (atol(s + 4) == 0)
- ok_to_create_file = true;
- /*
- * If this is a new context diff the character just
- * before the newline is a '*'.
- */
- while (*s != '\n')
- s++;
- p_indent = indent;
- p_start = previous_line;
- p_sline = p_input_line - 1;
- retval = (*(s - 1) == '*' ? NEW_CONTEXT_DIFF : CONTEXT_DIFF);
- goto scan_exit;
- }
- if ((!diff_type || diff_type == NORMAL_DIFF) &&
- last_line_was_command &&
- (strnEQ(s, "< ", 2) || strnEQ(s, "> ", 2))) {
- p_start = previous_line;
- p_sline = p_input_line - 1;
- p_indent = indent;
- retval = NORMAL_DIFF;
- goto scan_exit;
- }
- }
-scan_exit:
- if (retval == UNI_DIFF) {
- /* unswap old and new */
- struct file_name tmp = names[OLD_FILE];
- names[OLD_FILE] = names[NEW_FILE];
- names[NEW_FILE] = tmp;
- }
- if (filearg[0] == NULL) {
- if (posix)
- filearg[0] = posix_name(names, ok_to_create_file);
- else {
- /* Ignore the Index: name for context diffs, like GNU */
- if (names[OLD_FILE].path != NULL ||
- names[NEW_FILE].path != NULL) {
- free(names[INDEX_FILE].path);
- names[INDEX_FILE].path = NULL;
- }
- filearg[0] = best_name(names, ok_to_create_file);
- }
- }
-
- free(bestguess);
- bestguess = NULL;
- if (filearg[0] != NULL)
- bestguess = savestr(filearg[0]);
- else if (!ok_to_create_file) {
- /*
- * We don't want to create a new file but we need a
- * filename to set bestguess. Avoid setting filearg[0]
- * so the file is not created automatically.
- */
- if (posix)
- bestguess = posix_name(names, true);
- else
- bestguess = best_name(names, true);
- }
- free(names[OLD_FILE].path);
- free(names[NEW_FILE].path);
- free(names[INDEX_FILE].path);
- return retval;
-}
-
-/*
- * Remember where this patch ends so we know where to start up again.
- */
-static void
-next_intuit_at(LINENUM file_pos, LINENUM file_line)
-{
- p_base = file_pos;
- p_bline = file_line;
-}
-
-/*
- * Basically a verbose fseek() to the actual diff listing.
- */
-static void
-skip_to(LINENUM file_pos, LINENUM file_line)
-{
- int ret;
-
- if (p_base > file_pos)
- fatal("Internal error: seek %ld>%ld\n", p_base, file_pos);
- if (verbose && p_base < file_pos) {
- fseek(pfp, p_base, SEEK_SET);
- say("The text leading up to this was:\n--------------------------\n");
- while (ftell(pfp) < file_pos) {
- ret = getline(&buf, &bufsz, pfp);
- if (ret == -1)
- fatal("Unexpected end of file\n");
- say("|%s", buf);
- }
- say("--------------------------\n");
- } else
- fseek(pfp, file_pos, SEEK_SET);
- p_input_line = file_line - 1;
-}
-
-/* Make this a function for better debugging. */
-__dead static void
-malformed(void)
-{
- fatal("malformed patch at line %ld: %s", p_input_line, buf);
- /* about as informative as "Syntax error" in C */
-}
-
-static LINENUM
-getlinenum(const char *s)
-{
- LINENUM l = (LINENUM)atol(s);
- if (l < 0) {
- l = 0;
- malformed();
- }
- return l;
-}
-
-static LINENUM
-getskiplinenum(char **p)
-{
- char *s = *p;
- LINENUM l = getlinenum(s);
- while (isdigit((unsigned char)*s))
- s++;
- *p = s;
- return l;
-}
-
-/*
- * True if the line has been discarded (i.e., it is a line saying
- * "\ No newline at end of file".)
- */
-static bool
-remove_special_line(void)
-{
- int c;
-
- c = fgetc(pfp);
- if (c == '\\') {
- do {
- c = fgetc(pfp);
- } while (c != EOF && c != '\n');
-
- return true;
- }
- if (c != EOF)
- fseek(pfp, -1L, SEEK_CUR);
-
- return false;
-}
-
-/*
- * True if there is more of the current diff listing to process.
- */
-bool
-another_hunk(void)
-{
- long line_beginning; /* file pos of the current line */
- LINENUM repl_beginning; /* index of --- line */
- LINENUM fillcnt; /* #lines of missing ptrn or repl */
- LINENUM fillsrc; /* index of first line to copy */
- LINENUM filldst; /* index of first missing line */
- bool ptrn_spaces_eaten; /* ptrn was slightly misformed */
- bool repl_could_be_missing; /* no + or ! lines in this hunk */
- bool repl_missing; /* we are now backtracking */
- long repl_backtrack_position; /* file pos of first repl line */
- LINENUM repl_patch_line; /* input line number for same */
- LINENUM ptrn_copiable; /* # of copiable lines in ptrn */
- char *s;
- int context = 0;
- int ret;
-
- while (p_end >= 0) {
- if (p_end == p_efake)
- p_end = p_bfake; /* don't free twice */
- else
- free(p_line[p_end]);
- p_end--;
- }
- p_efake = -1;
-
- p_max = hunkmax; /* gets reduced when --- found */
- if (diff_type == CONTEXT_DIFF || diff_type == NEW_CONTEXT_DIFF) {
- line_beginning = ftell(pfp);
- repl_beginning = 0;
- fillcnt = 0;
- fillsrc = 0;
- filldst = 0;
- ptrn_spaces_eaten = false;
- repl_could_be_missing = true;
- repl_missing = false;
- repl_backtrack_position = 0;
- repl_patch_line = 0;
- ptrn_copiable = 0;
-
- ret = pgetline(&buf, &bufsz, pfp);
- p_input_line++;
- if (ret == -1 || strnNE(buf, "********", 8)) {
- next_intuit_at(line_beginning, p_input_line);
- return false;
- }
- p_context = 100;
- p_hunk_beg = p_input_line + 1;
- while (p_end < p_max) {
- // line_beginning = ftell(pfp);
- ret = pgetline(&buf, &bufsz, pfp);
- p_input_line++;
- if (ret == -1) {
- if (repl_beginning && repl_could_be_missing) {
- repl_missing = true;
- goto hunk_done;
- }
- fatal("unexpected end of file in patch\n");
- }
- p_end++;
- if (p_end >= hunkmax)
- fatal("Internal error: hunk larger than hunk "
- "buffer size");
- p_char[p_end] = *buf;
- p_line[p_end] = NULL;
- switch (*buf) {
- case '*':
- if (strnEQ(buf, "********", 8)) {
- if (repl_beginning && repl_could_be_missing) {
- repl_missing = true;
- goto hunk_done;
- } else
- fatal("unexpected end of hunk "
- "at line %ld\n",
- p_input_line);
- }
- if (p_end != 0) {
- if (repl_beginning && repl_could_be_missing) {
- repl_missing = true;
- goto hunk_done;
- }
- fatal("unexpected *** at line %ld: %s",
- p_input_line, buf);
- }
- context = 0;
- p_line[p_end] = savestr(buf);
- if (out_of_mem) {
- p_end--;
- return false;
- }
- for (s = buf; *s && !isdigit((unsigned char)*s); s++)
- ;
- if (!*s)
- malformed();
- if (strnEQ(s, "0,0", 3))
- memmove(s, s + 2, strlen(s + 2) + 1);
- p_first = getskiplinenum(&s);
- if (*s == ',') {
- for (; *s && !isdigit((unsigned char)*s); s++)
- ;
- if (!*s)
- malformed();
- p_ptrn_lines = (getlinenum(s)) - p_first + 1;
- if (p_ptrn_lines < 0)
- malformed();
- } else if (p_first)
- p_ptrn_lines = 1;
- else {
- p_ptrn_lines = 0;
- p_first = 1;
- }
- if (p_first >= LINENUM_MAX - p_ptrn_lines ||
- p_ptrn_lines >= LINENUM_MAX - 6)
- malformed();
-
- /* we need this much at least */
- p_max = p_ptrn_lines + 6;
- while (p_max >= hunkmax)
- grow_hunkmax();
- p_max = hunkmax;
- break;
- case '-':
- if (buf[1] == '-') {
- if (repl_beginning ||
- (p_end != p_ptrn_lines + 1 +
- (p_char[p_end - 1] == '\n'))) {
- if (p_end == 1) {
- /*
- * `old' lines were omitted;
- * set up to fill them in
- * from 'new' context lines.
- */
- p_end = p_ptrn_lines + 1;
- fillsrc = p_end + 1;
- filldst = 1;
- fillcnt = p_ptrn_lines;
- } else {
- if (repl_beginning) {
- if (repl_could_be_missing) {
- repl_missing = true;
- goto hunk_done;
- }
- fatal("duplicate \"---\" at line %ld--check line numbers at line %ld\n",
- p_input_line, p_hunk_beg + repl_beginning);
- } else {
- fatal("%s \"---\" at line %ld--check line numbers at line %ld\n",
- (p_end <= p_ptrn_lines
- ? "Premature"
- : "Overdue"),
- p_input_line, p_hunk_beg);
- }
- }
- }
- repl_beginning = p_end;
- repl_backtrack_position = ftell(pfp);
- repl_patch_line = p_input_line;
- p_line[p_end] = savestr(buf);
- if (out_of_mem) {
- p_end--;
- return false;
- }
- p_char[p_end] = '=';
- for (s = buf; *s && !isdigit((unsigned char)*s); s++)
- ;
- if (!*s)
- malformed();
- p_newfirst = getskiplinenum(&s);
- if (*s == ',') {
- for (; *s && !isdigit((unsigned char)*s); s++)
- ;
- if (!*s)
- malformed();
- p_repl_lines = (getlinenum(s)) -
- p_newfirst + 1;
- if (p_repl_lines < 0)
- malformed();
- } else if (p_newfirst)
- p_repl_lines = 1;
- else {
- p_repl_lines = 0;
- p_newfirst = 1;
- }
- if (p_newfirst >= LINENUM_MAX - p_repl_lines ||
- p_repl_lines >= LINENUM_MAX - p_end)
- malformed();
- p_max = p_repl_lines + p_end;
- if (p_max > MAXHUNKSIZE)
- fatal("hunk too large (%ld lines) at line %ld: %s",
- p_max, p_input_line, buf);
- while (p_max >= hunkmax)
- grow_hunkmax();
- if (p_repl_lines != ptrn_copiable &&
- (p_context != 0 || p_repl_lines != 1))
- repl_could_be_missing = false;
- break;
- }
- goto change_line;
- case '+':
- case '!':
- repl_could_be_missing = false;
- change_line:
- if (buf[1] == '\n' && canonicalize)
- strlcpy(buf + 1, " \n", bufsz - 1);
- if (!isspace((unsigned char)buf[1]) && buf[1] != '>' &&
- buf[1] != '<' &&
- repl_beginning && repl_could_be_missing) {
- repl_missing = true;
- goto hunk_done;
- }
- if (context >= 0) {
- if (context < p_context)
- p_context = context;
- context = -1000;
- }
- p_line[p_end] = savestr(buf + 2);
- if (out_of_mem) {
- p_end--;
- return false;
- }
- if (p_end == p_ptrn_lines) {
- if (remove_special_line()) {
- int len;
-
- len = strlen(p_line[p_end]) - 1;
- (p_line[p_end])[len] = 0;
- }
- }
- break;
- case '\t':
- case '\n': /* assume the 2 spaces got eaten */
- if (repl_beginning && repl_could_be_missing &&
- (!ptrn_spaces_eaten ||
- diff_type == NEW_CONTEXT_DIFF)) {
- repl_missing = true;
- goto hunk_done;
- }
- p_line[p_end] = savestr(buf);
- if (out_of_mem) {
- p_end--;
- return false;
- }
- if (p_end != p_ptrn_lines + 1) {
- ptrn_spaces_eaten |= (repl_beginning != 0);
- context++;
- if (!repl_beginning)
- ptrn_copiable++;
- p_char[p_end] = ' ';
- }
- break;
- case ' ':
- if (!isspace((unsigned char)buf[1]) &&
- repl_beginning && repl_could_be_missing) {
- repl_missing = true;
- goto hunk_done;
- }
- context++;
- if (!repl_beginning)
- ptrn_copiable++;
- p_line[p_end] = savestr(buf + 2);
- if (out_of_mem) {
- p_end--;
- return false;
- }
- break;
- default:
- if (repl_beginning && repl_could_be_missing) {
- repl_missing = true;
- goto hunk_done;
- }
- malformed();
- }
- /* set up p_len for strncmp() so we don't have to */
- /* assume null termination */
- if (p_line[p_end])
- p_len[p_end] = strlen(p_line[p_end]);
- else
- p_len[p_end] = 0;
- }
-
-hunk_done:
- if (p_end >= 0 && !repl_beginning)
- fatal("no --- found in patch at line %ld\n", pch_hunk_beg());
-
- if (repl_missing) {
-
- /* reset state back to just after --- */
- p_input_line = repl_patch_line;
- for (p_end--; p_end > repl_beginning; p_end--)
- free(p_line[p_end]);
- fseek(pfp, repl_backtrack_position, SEEK_SET);
-
- /* redundant 'new' context lines were omitted - set */
- /* up to fill them in from the old file context */
- if (!p_context && p_repl_lines == 1) {
- p_repl_lines = 0;
- p_max--;
- }
- fillsrc = 1;
- filldst = repl_beginning + 1;
- fillcnt = p_repl_lines;
- p_end = p_max;
- } else if (!p_context && fillcnt == 1) {
- /* the first hunk was a null hunk with no context */
- /* and we were expecting one line -- fix it up. */
- while (filldst < p_end) {
- p_line[filldst] = p_line[filldst + 1];
- p_char[filldst] = p_char[filldst + 1];
- p_len[filldst] = p_len[filldst + 1];
- filldst++;
- }
-#if 0
- repl_beginning--; /* this doesn't need to be fixed */
-#endif
- p_end--;
- p_first++; /* do append rather than insert */
- fillcnt = 0;
- p_ptrn_lines = 0;
- }
- if (diff_type == CONTEXT_DIFF &&
- (fillcnt || (p_first > 1 && ptrn_copiable > 2 * p_context))) {
- if (verbose)
- say("%s\n%s\n%s\n",
- "(Fascinating--this is really a new-style context diff but without",
- "the telltale extra asterisks on the *** line that usually indicate",
- "the new style...)");
- diff_type = NEW_CONTEXT_DIFF;
- }
- /* if there were omitted context lines, fill them in now */
- if (fillcnt) {
- p_bfake = filldst; /* remember where not to free() */
- p_efake = filldst + fillcnt - 1;
- while (fillcnt-- > 0) {
- while (fillsrc <= p_end && p_char[fillsrc] != ' ')
- fillsrc++;
- if (fillsrc > p_end)
- fatal("replacement text or line numbers mangled in hunk at line %ld\n",
- p_hunk_beg);
- p_line[filldst] = p_line[fillsrc];
- p_char[filldst] = p_char[fillsrc];
- p_len[filldst] = p_len[fillsrc];
- fillsrc++;
- filldst++;
- }
- while (fillsrc <= p_end && fillsrc != repl_beginning &&
- p_char[fillsrc] != ' ')
- fillsrc++;
-#ifdef DEBUGGING
- if (debug & 64)
- printf("fillsrc %ld, filldst %ld, rb %ld, e+1 %ld\n",
- fillsrc, filldst, repl_beginning, p_end + 1);
-#endif
- if (fillsrc != p_end + 1 && fillsrc != repl_beginning)
- malformed();
- if (filldst != p_end + 1 && filldst != repl_beginning)
- malformed();
- }
- if (p_line[p_end] != NULL) {
- if (remove_special_line()) {
- p_len[p_end] -= 1;
- (p_line[p_end])[p_len[p_end]] = 0;
- }
- }
- } else if (diff_type == UNI_DIFF) {
- LINENUM fillold; /* index of old lines */
- LINENUM fillnew; /* index of new lines */
- char ch;
-
- line_beginning = ftell(pfp); /* file pos of the current line */
- ret = pgetline(&buf, &bufsz, pfp);
- p_input_line++;
- if (ret == -1 || strnNE(buf, "@@ -", 4)) {
- next_intuit_at(line_beginning, p_input_line);
- return false;
- }
- s = buf + 4;
- if (!*s)
- malformed();
- p_first = getskiplinenum(&s);
- if (*s == ',') {
- s++;
- p_ptrn_lines = getskiplinenum(&s);
- } else
- p_ptrn_lines = 1;
- if (p_first >= LINENUM_MAX - p_ptrn_lines)
- malformed();
- if (*s == ' ')
- s++;
- if (*s != '+' || !*++s)
- malformed();
- p_newfirst = getskiplinenum(&s);
- if (*s == ',') {
- s++;
- p_repl_lines = getskiplinenum(&s);
- } else
- p_repl_lines = 1;
- if (*s == ' ')
- s++;
- if (*s != '@')
- malformed();
- if (p_first >= LINENUM_MAX - p_ptrn_lines ||
- p_newfirst > LINENUM_MAX - p_repl_lines ||
- p_ptrn_lines >= LINENUM_MAX - p_repl_lines - 1)
- malformed();
- if (!p_ptrn_lines)
- p_first++; /* do append rather than insert */
- p_max = p_ptrn_lines + p_repl_lines + 1;
- while (p_max >= hunkmax)
- grow_hunkmax();
- fillold = 1;
- fillnew = fillold + p_ptrn_lines;
- p_end = fillnew + p_repl_lines;
- snprintf(buf, bufsz, "*** %ld,%ld ****\n", p_first,
- p_first + p_ptrn_lines - 1);
- p_line[0] = savestr(buf);
- if (out_of_mem) {
- p_end = -1;
- return false;
- }
- p_char[0] = '*';
- snprintf(buf, bufsz, "--- %ld,%ld ----\n", p_newfirst,
- p_newfirst + p_repl_lines - 1);
- p_line[fillnew] = savestr(buf);
- if (out_of_mem) {
- p_end = 0;
- return false;
- }
- p_char[fillnew++] = '=';
- p_context = 100;
- context = 0;
- p_hunk_beg = p_input_line + 1;
- while (fillold <= p_ptrn_lines || fillnew <= p_end) {
- // line_beginning = ftell(pfp);
- ret = pgetline(&buf, &bufsz, pfp);
- p_input_line++;
- if (ret == -1) {
- if (p_max - fillnew < 3) {
- /* assume blank lines got chopped */
- strlcpy(buf, " \n", bufsz);
- } else {
- fatal("unexpected end of file in patch\n");
- }
- }
- if (*buf == '\t' || *buf == '\n') {
- ch = ' '; /* assume the space got eaten */
- s = savestr(buf);
- } else {
- ch = *buf;
- s = savestr(buf + 1);
- }
- if (out_of_mem) {
- while (--fillnew > p_ptrn_lines)
- free(p_line[fillnew]);
- p_end = fillold - 1;
- return false;
- }
- switch (ch) {
- case '-':
- if (fillold > p_ptrn_lines) {
- free(s);
- p_end = fillnew - 1;
- malformed();
- }
- p_char[fillold] = ch;
- p_line[fillold] = s;
- p_len[fillold++] = strlen(s);
- if (fillold > p_ptrn_lines) {
- if (remove_special_line()) {
- p_len[fillold - 1] -= 1;
- s[p_len[fillold - 1]] = 0;
- }
- }
- break;
- case '=':
- ch = ' ';
- /* FALL THROUGH */
- case ' ':
- if (fillold > p_ptrn_lines) {
- free(s);
- while (--fillnew > p_ptrn_lines)
- free(p_line[fillnew]);
- p_end = fillold - 1;
- malformed();
- }
- context++;
- p_char[fillold] = ch;
- p_line[fillold] = s;
- p_len[fillold++] = strlen(s);
- s = savestr(s);
- if (out_of_mem) {
- while (--fillnew > p_ptrn_lines)
- free(p_line[fillnew]);
- p_end = fillold - 1;
- return false;
- }
- if (fillold > p_ptrn_lines) {
- if (remove_special_line()) {
- p_len[fillold - 1] -= 1;
- s[p_len[fillold - 1]] = 0;
- }
- }
- /* FALL THROUGH */
- case '+':
- if (fillnew > p_end) {
- free(s);
- while (--fillnew > p_ptrn_lines)
- free(p_line[fillnew]);
- p_end = fillold - 1;
- malformed();
- }
- p_char[fillnew] = ch;
- p_line[fillnew] = s;
- p_len[fillnew++] = strlen(s);
- if (fillold > p_ptrn_lines) {
- if (remove_special_line()) {
- p_len[fillnew - 1] -= 1;
- s[p_len[fillnew - 1]] = 0;
- }
- }
- break;
- default:
- p_end = fillnew;
- malformed();
- }
- if (ch != ' ' && context > 0) {
- if (context < p_context)
- p_context = context;
- context = -1000;
- }
- } /* while */
- } else { /* normal diff--fake it up */
- char hunk_type;
- int i;
- LINENUM min, max;
-
- line_beginning = ftell(pfp);
- p_context = 0;
- ret = pgetline(&buf, &bufsz, pfp);
- p_input_line++;
- if (ret == -1 || !isdigit((unsigned char)*buf)) {
- next_intuit_at(line_beginning, p_input_line);
- return false;
- }
- s = buf;
- p_first = getskiplinenum(&s);
- if (*s == ',') {
- s++;
- p_ptrn_lines = getskiplinenum(&s) - p_first + 1;
- } else
- p_ptrn_lines = (*s != 'a');
- if (p_first >= LINENUM_MAX - p_ptrn_lines)
- malformed();
- hunk_type = *s++;
- if (hunk_type == 'a')
- p_first++; /* do append rather than insert */
- min = getskiplinenum(&s);
- if (*s == ',')
- max = getlinenum(++s);
- else
- max = min;
- if (min < 0 || min > max || max - min == LINENUM_MAX)
- malformed();
- if (hunk_type == 'd')
- min++;
- p_end = p_ptrn_lines + 1 + max - min + 1;
- p_newfirst = min;
- p_repl_lines = max - min + 1;
- if (p_newfirst > LINENUM_MAX - p_repl_lines ||
- p_ptrn_lines >= LINENUM_MAX - p_repl_lines - 1)
- malformed();
- p_end = p_ptrn_lines + p_repl_lines + 1;
- if (p_end > MAXHUNKSIZE)
- fatal("hunk too large (%ld lines) at line %ld: %s",
- p_end, p_input_line, buf);
- while (p_end >= hunkmax)
- grow_hunkmax();
- snprintf(buf, bufsz, "*** %ld,%ld\n", p_first,
- p_first + p_ptrn_lines - 1);
- p_line[0] = savestr(buf);
- if (out_of_mem) {
- p_end = -1;
- return false;
- }
- p_char[0] = '*';
- for (i = 1; i <= p_ptrn_lines; i++) {
- ret = pgetline(&buf, &bufsz, pfp);
- p_input_line++;
- if (ret == -1)
- fatal("unexpected end of file in patch at line %ld\n",
- p_input_line);
- if (*buf != '<')
- fatal("< expected at line %ld of patch\n",
- p_input_line);
- p_line[i] = savestr(buf + 2);
- if (out_of_mem) {
- p_end = i - 1;
- return false;
- }
- p_len[i] = strlen(p_line[i]);
- p_char[i] = '-';
- }
-
- if (remove_special_line()) {
- p_len[i - 1] -= 1;
- (p_line[i - 1])[p_len[i - 1]] = 0;
- }
- if (hunk_type == 'c') {
- ret = pgetline(&buf, &bufsz, pfp);
- p_input_line++;
- if (ret == -1)
- fatal("unexpected end of file in patch at line %ld\n",
- p_input_line);
- if (*buf != '-')
- fatal("--- expected at line %ld of patch\n",
- p_input_line);
- }
- snprintf(buf, bufsz, "--- %ld,%ld\n", min, max);
- p_line[i] = savestr(buf);
- if (out_of_mem) {
- p_end = i - 1;
- return false;
- }
- p_char[i] = '=';
- for (i++; i <= p_end; i++) {
- ret = pgetline(&buf, &bufsz, pfp);
- p_input_line++;
- if (ret == -1)
- fatal("unexpected end of file in patch at line %ld\n",
- p_input_line);
- if (*buf != '>')
- fatal("> expected at line %ld of patch\n",
- p_input_line);
- p_line[i] = savestr(buf + 2);
- if (out_of_mem) {
- p_end = i - 1;
- return false;
- }
- p_len[i] = strlen(p_line[i]);
- p_char[i] = '+';
- }
-
- if (remove_special_line()) {
- p_len[i - 1] -= 1;
- (p_line[i - 1])[p_len[i - 1]] = 0;
- }
- }
- if (reverse) /* backwards patch? */
- if (!pch_swap())
- say("Not enough memory to swap next hunk!\n");
-#ifdef DEBUGGING
- if (debug & 2) {
- int i;
- char special;
-
- for (i = 0; i <= p_end; i++) {
- if (i == p_ptrn_lines)
- special = '^';
- else
- special = ' ';
- fprintf(stderr, "%3d %c %c %s", i, p_char[i],
- special, p_line[i]);
- fflush(stderr);
- }
- }
-#endif
- if (p_end + 1 < hunkmax)/* paranoia reigns supreme... */
- p_char[p_end + 1] = '^'; /* add a stopper for apply_hunk */
- return true;
-}
-
-/*
- * Input a line from the patch file, worrying about indentation.
- */
-int
-pgetline(char **bf, size_t *sz, FILE *fp)
-{
- char *s;
- int indent = 0;
- int ret;
-
- ret = getline(bf, sz, fp);
-
- if (p_indent && ret != -1) {
- for (s = buf;
- indent < p_indent && (*s == ' ' || *s == '\t' || *s == 'X');
- s++) {
- if (*s == '\t')
- indent += 8 - (indent % 7);
- else
- indent++;
- }
- if (buf != s && strlcpy(buf, s, bufsz) >= bufsz)
- fatal("buffer too small in pgetline()\n");
- }
- return ret;
-}
-
-/*
- * Reverse the old and new portions of the current hunk.
- */
-bool
-pch_swap(void)
-{
- char **tp_line; /* the text of the hunk */
- ssize_t *tp_len; /* length of each line */
- char *tp_char; /* +, -, and ! */
- LINENUM i;
- LINENUM n;
- bool blankline = false;
- char *s;
-
- i = p_first;
- p_first = p_newfirst;
- p_newfirst = i;
-
- /* make a scratch copy */
-
- tp_line = p_line;
- tp_len = p_len;
- tp_char = p_char;
- p_line = NULL; /* force set_hunkmax to allocate again */
- p_len = NULL;
- p_char = NULL;
- set_hunkmax();
- if (p_line == NULL || p_len == NULL || p_char == NULL) {
-
- free(p_line);
- p_line = tp_line;
- free(p_len);
- p_len = tp_len;
- free(p_char);
- p_char = tp_char;
- return false; /* not enough memory to swap hunk! */
- }
- /* now turn the new into the old */
-
- i = p_ptrn_lines + 1;
- if (tp_char[i] == '\n') { /* account for possible blank line */
- blankline = true;
- i++;
- }
- if (p_efake >= 0) { /* fix non-freeable ptr range */
- if (p_efake <= i)
- n = p_end - i + 1;
- else
- n = -i;
- p_efake += n;
- p_bfake += n;
- }
- for (n = 0; i <= p_end; i++, n++) {
- p_line[n] = tp_line[i];
- p_char[n] = tp_char[i];
- if (p_char[n] == '+')
- p_char[n] = '-';
- p_len[n] = tp_len[i];
- }
- if (blankline) {
- i = p_ptrn_lines + 1;
- p_line[n] = tp_line[i];
- p_char[n] = tp_char[i];
- p_len[n] = tp_len[i];
- n++;
- }
- if (p_char[0] != '=')
- fatal("Malformed patch at line %ld: expected '=' found '%c'\n",
- p_input_line, p_char[0]);
- p_char[0] = '*';
- for (s = p_line[0]; *s; s++)
- if (*s == '-')
- *s = '*';
-
- /* now turn the old into the new */
-
- if (p_char[0] != '*')
- fatal("Malformed patch at line %ld: expected '*' found '%c'\n",
- p_input_line, p_char[0]);
- tp_char[0] = '=';
- for (s = tp_line[0]; *s; s++)
- if (*s == '*')
- *s = '-';
- for (i = 0; n <= p_end; i++, n++) {
- p_line[n] = tp_line[i];
- p_char[n] = tp_char[i];
- if (p_char[n] == '-')
- p_char[n] = '+';
- p_len[n] = tp_len[i];
- }
-
- if (i != p_ptrn_lines + 1)
- fatal("Malformed patch at line %ld: expected %ld lines, "
- "got %ld\n",
- p_input_line, p_ptrn_lines + 1, i);
-
- i = p_ptrn_lines;
- p_ptrn_lines = p_repl_lines;
- p_repl_lines = i;
-
- free(tp_line);
- free(tp_len);
- free(tp_char);
-
- return true;
-}
-
-/*
- * Return the specified line position in the old file of the old context.
- */
-LINENUM
-pch_first(void)
-{
- return p_first;
-}
-
-/*
- * Return the number of lines of old context.
- */
-LINENUM
-pch_ptrn_lines(void)
-{
- return p_ptrn_lines;
-}
-
-/*
- * Return the probable line position in the new file of the first line.
- */
-LINENUM
-pch_newfirst(void)
-{
- return p_newfirst;
-}
-
-/*
- * Return the number of lines in the replacement text including context.
- */
-LINENUM
-pch_repl_lines(void)
-{
- return p_repl_lines;
-}
-
-/*
- * Return the number of lines in the whole hunk.
- */
-LINENUM
-pch_end(void)
-{
- return p_end;
-}
-
-/*
- * Return the number of context lines before the first changed line.
- */
-LINENUM
-pch_context(void)
-{
- return p_context;
-}
-
-/*
- * Return the length of a particular patch line.
- */
-ssize_t
-pch_line_len(LINENUM line)
-{
- return p_len[line];
-}
-
-/*
- * Return the control character (+, -, *, !, etc) for a patch line.
- */
-char
-pch_char(LINENUM line)
-{
- return p_char[line];
-}
-
-/*
- * Return a pointer to a particular patch line.
- */
-char *
-pfetch(LINENUM line)
-{
- return p_line[line];
-}
-
-/*
- * Return where in the patch file this hunk began, for error messages.
- */
-LINENUM
-pch_hunk_beg(void)
-{
- return p_hunk_beg;
-}
-
-/*
- * Apply an ed script by feeding ed itself.
- */
-void
-do_ed_script(void)
-{
- char *t;
- long beginning_of_this_line;
- FILE *pipefp = NULL;
- int continuation;
-
- if (!skip_rest_of_patch) {
- if (copy_file(filearg[0], TMPOUTNAME) < 0) {
- unlink(TMPOUTNAME);
- fatal("can't create temp file %s", TMPOUTNAME);
- }
- snprintf(buf, bufsz, "%s -S%s %s", _PATH_ED,
- verbose ? "" : "s", TMPOUTNAME);
- pipefp = popen(buf, "w");
- }
- for (;;) {
- beginning_of_this_line = ftell(pfp);
- if (pgetline(&buf, &bufsz, pfp) == -1) {
- next_intuit_at(beginning_of_this_line, p_input_line);
- break;
- }
- p_input_line++;
- for (t = buf; isdigit((unsigned char)*t) || *t == ','; t++)
- ;
- /* POSIX defines allowed commands as {a,c,d,i,s} */
- if (isdigit((unsigned char)*buf) && (*t == 'a' || *t == 'c' ||
- *t == 'd' || *t == 'i' || *t == 's')) {
- if (pipefp != NULL)
- fprintf(pipefp, "%s", buf);
- if (*t == 's') {
- for (;;) {
- continuation = 0;
- t = strchr(buf, '\0') - 1;
- while (--t >= buf && *t == '\\')
- continuation = !continuation;
- if (!continuation ||
- pgetline(&buf, &bufsz, pfp) == -1)
- break;
- if (pipefp != NULL)
- fprintf(pipefp, "%s", buf);
- }
- } else if (*t != 'd') {
- while (pgetline(&buf, &bufsz, pfp) != -1) {
- p_input_line++;
- if (pipefp != NULL)
- fprintf(pipefp, "%s", buf);
- if (strEQ(buf, ".\n"))
- break;
- }
- }
- } else {
- next_intuit_at(beginning_of_this_line, p_input_line);
- break;
- }
- }
- if (pipefp == NULL)
- return;
- fprintf(pipefp, "w\n");
- fprintf(pipefp, "q\n");
- fflush(pipefp);
- pclose(pipefp);
- ignore_signals();
- if (!check_only) {
- if (move_file(TMPOUTNAME, outname) < 0) {
- toutkeep = true;
- chmod(TMPOUTNAME, filemode);
- } else
- chmod(outname, filemode);
- }
- set_signals(1);
-}
-
-/*
- * Choose the name of the file to be patched based on POSIX rules.
- * NOTE: the POSIX rules are amazingly stupid and we only follow them
- * if the user specified --posix or set POSIXLY_CORRECT.
- */
-static char *
-posix_name(const struct file_name *names, bool assume_exists)
-{
- char *path = NULL;
- int i;
-
- /*
- * POSIX states that the filename will be chosen from one
- * of the old, new and index names (in that order) if
- * the file exists relative to CWD after -p stripping.
- */
- for (i = 0; i < MAX_FILE; i++) {
- if (names[i].path != NULL && names[i].exists) {
- path = names[i].path;
- break;
- }
- }
- if (path == NULL && !assume_exists) {
- /*
- * No files found, look for something we can checkout from
- * RCS/SCCS dirs. Same order as above.
- */
- for (i = 0; i < MAX_FILE; i++) {
- if (names[i].path != NULL &&
- (path = checked_in(names[i].path)) != NULL)
- break;
- }
- /*
- * Still no match? Check to see if the diff could be creating
- * a new file.
- */
- if (path == NULL && ok_to_create_file &&
- names[NEW_FILE].path != NULL)
- path = names[NEW_FILE].path;
- }
-
- return path ? savestr(path) : NULL;
-}
-
-/*
- * Choose the name of the file to be patched based the "best" one
- * available.
- */
-static char *
-best_name(const struct file_name *names, bool assume_exists)
-{
- size_t min_components, min_baselen, min_len, tmp;
- char *best = NULL;
- int i;
-
- /*
- * The "best" name is the one with the fewest number of path
- * components, the shortest basename length, and the shortest
- * overall length (in that order). We only use the Index: file
- * if neither of the old or new files could be intuited from
- * the diff header.
- */
- min_components = min_baselen = min_len = SIZE_MAX;
- for (i = INDEX_FILE; i >= OLD_FILE; i--) {
- if (names[i].path == NULL ||
- (!names[i].exists && !assume_exists))
- continue;
- if ((tmp = num_components(names[i].path)) > min_components)
- continue;
- min_components = tmp;
- if ((tmp = strlen(basename(names[i].path))) > min_baselen)
- continue;
- min_baselen = tmp;
- if ((tmp = strlen(names[i].path)) > min_len)
- continue;
- min_len = tmp;
- best = names[i].path;
- }
- if (best == NULL) {
- /*
- * No files found, look for something we can checkout from
- * RCS/SCCS dirs. Logic is identical to that above...
- */
- min_components = min_baselen = min_len = SIZE_MAX;
- for (i = INDEX_FILE; i >= OLD_FILE; i--) {
- if (names[i].path == NULL ||
- checked_in(names[i].path) == NULL)
- continue;
- if ((tmp = num_components(names[i].path)) > min_components)
- continue;
- min_components = tmp;
- if ((tmp = strlen(basename(names[i].path))) > min_baselen)
- continue;
- min_baselen = tmp;
- if ((tmp = strlen(names[i].path)) > min_len)
- continue;
- min_len = tmp;
- best = names[i].path;
- }
- /*
- * Still no match? Check to see if the diff could be creating
- * a new file.
- */
- if (best == NULL && ok_to_create_file &&
- names[NEW_FILE].path != NULL)
- best = names[NEW_FILE].path;
- }
-
- return best ? savestr(best) : NULL;
-}
-
-static size_t
-num_components(const char *path)
-{
- size_t n;
- const char *cp;
-
- for (n = 0, cp = path; (cp = strchr(cp, '/')) != NULL; n++, cp++) {
- while (*cp == '/')
- cp++; /* skip consecutive slashes */
- }
- return n;
-}
diff --git a/cmd/posix/patch/pch.h b/cmd/posix/patch/pch.h
@@ -1,59 +0,0 @@
-/*
- * $OpenBSD: pch.h,v 1.9 2003/10/31 20:20:45 millert Exp $
- * $DragonFly: src/usr.bin/patch/pch.h,v 1.1 2004/09/24 18:44:28 joerg Exp $
- * $NetBSD: pch.h,v 1.11 2024/07/12 15:48:39 manu 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
- */
-
-#define OLD_FILE 0
-#define NEW_FILE 1
-#define INDEX_FILE 2
-#define MAX_FILE 3
-
-struct file_name {
- char *path;
- bool exists;
-};
-
-void re_patch(void);
-void open_patch_file(const char *);
-void set_hunkmax(void);
-bool there_is_another_patch(void);
-bool another_hunk(void);
-bool pch_swap(void);
-char *pfetch(LINENUM);
-ssize_t pch_line_len(LINENUM);
-LINENUM pch_first(void);
-LINENUM pch_ptrn_lines(void);
-LINENUM pch_newfirst(void);
-LINENUM pch_repl_lines(void);
-LINENUM pch_end(void);
-LINENUM pch_context(void);
-LINENUM pch_hunk_beg(void);
-char pch_char(LINENUM);
-void do_ed_script(void);
diff --git a/cmd/posix/patch/util.c b/cmd/posix/patch/util.c
@@ -1,444 +0,0 @@
-/*
- * $OpenBSD: util.c,v 1.32 2006/03/11 19:41:30 otto Exp $
- * $DragonFly: src/usr.bin/patch/util.c,v 1.9 2007/09/29 23:11:10 swildner Exp $
- * $NetBSD: util.c,v 1.30 2021/05/25 11:25:59 cjep 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/param.h>
-#include <sys/stat.h>
-
-#include <ctype.h>
-#include <errno.h>
-#include <fcntl.h>
-#include <libgen.h>
-#include <signal.h>
-#include <stdarg.h>
-#include <stdlib.h>
-#include <stdio.h>
-#include <string.h>
-#include <unistd.h>
-
-#include "common.h"
-#include "util.h"
-#include "backupfile.h"
-#include "pathnames.h"
-
-/* Rename a file, copying it if necessary. */
-
-int
-move_file(const char *from, const char *to)
-{
- int fromfd;
- ssize_t i;
-
- /* to stdout? */
-
- if (strEQ(to, "-")) {
-#ifdef DEBUGGING
- if (debug & 4)
- say("Moving %s to stdout.\n", from);
-#endif
- fromfd = open(from, O_RDONLY);
- if (fromfd < 0)
- pfatal("internal error, can't reopen %s", from);
- while ((i = read(fromfd, buf, bufsz)) > 0)
- if (write(STDOUT_FILENO, buf, i) != i)
- pfatal("write failed");
- close(fromfd);
- return 0;
- }
- if (backup_file(to) < 0) {
- say("Can't backup %s, output is in %s: %s\n", to, from,
- strerror(errno));
- return -1;
- }
-#ifdef DEBUGGING
- if (debug & 4)
- say("Moving %s to %s.\n", from, to);
-#endif
- if (rename(from, to) < 0) {
- if (errno != EXDEV || copy_file(from, to) < 0) {
- say("Can't create %s, output is in %s: %s\n",
- to, from, strerror(errno));
- return -1;
- }
- }
- return 0;
-}
-
-/* Backup the original file. */
-
-int
-backup_file(const char *orig)
-{
- struct stat filestat;
- char bakname[PATH_MAX], *s, *simplename;
- dev_t orig_device;
- ino_t orig_inode;
-
- if (backup_type == none || stat(orig, &filestat) != 0)
- return 0; /* nothing to do */
- /*
- * If the user used zero prefixes or suffixes, then
- * he doesn't want backups. Yet we have to remove
- * orig to break possible hardlinks.
- */
- if ((origprae && *origprae == 0) || *simple_backup_suffix == 0) {
- unlink(orig);
- return 0;
- }
- orig_device = filestat.st_dev;
- orig_inode = filestat.st_ino;
-
- if (origprae) {
- if (strlcpy(bakname, origprae, sizeof(bakname)) >= sizeof(bakname) ||
- strlcat(bakname, orig, sizeof(bakname)) >= sizeof(bakname))
- fatal("filename %s too long for buffer\n", origprae);
- } else {
- if ((s = find_backup_file_name(orig)) == NULL)
- fatal("out of memory\n");
- if (strlcpy(bakname, s, sizeof(bakname)) >= sizeof(bakname))
- fatal("filename %s too long for buffer\n", s);
- free(s);
- }
-
- if ((simplename = strrchr(bakname, '/')) != NULL)
- simplename = simplename + 1;
- else
- simplename = bakname;
-
- /*
- * Find a backup name that is not the same file. Change the
- * first lowercase char into uppercase; if that isn't
- * sufficient, chop off the first char and try again.
- */
- while (stat(bakname, &filestat) == 0 &&
- orig_device == filestat.st_dev && orig_inode == filestat.st_ino) {
- /* Skip initial non-lowercase chars. */
- for (s = simplename; *s && !islower((unsigned char)*s); s++)
- ;
- if (*s)
- *s = toupper((unsigned char)*s);
- else
- memmove(simplename, simplename + 1,
- strlen(simplename + 1) + 1);
- }
-#ifdef DEBUGGING
- if (debug & 4)
- say("Moving %s to %s.\n", orig, bakname);
-#endif
- if (rename(orig, bakname) < 0) {
- if (errno != EXDEV || copy_file(orig, bakname) < 0)
- return -1;
- }
- return 0;
-}
-
-/*
- * Copy a file.
- */
-int
-copy_file(const char *from, const char *to)
-{
- int tofd, fromfd;
- ssize_t i;
-
- tofd = open(to, O_CREAT|O_TRUNC|O_WRONLY, 0666);
- if (tofd < 0)
- return -1;
- fromfd = open(from, O_RDONLY, 0);
- if (fromfd < 0)
- pfatal("internal error, can't reopen %s", from);
- while ((i = read(fromfd, buf, bufsz)) > 0)
- if (write(tofd, buf, i) != i)
- pfatal("write to %s failed", to);
- close(fromfd);
- close(tofd);
- return 0;
-}
-
-/*
- * Allocate a unique area for a string.
- */
-char *
-savestr(const char *s)
-{
- char *rv;
-
- if (!s)
- s = "Oops";
- rv = strdup(s);
- if (rv == NULL) {
- if (using_plan_a)
- out_of_mem = true;
- else
- fatal("out of memory\n");
- }
- return rv;
-}
-
-/*
- * Vanilla terminal output (buffered).
- */
-void
-say(const char *fmt, ...)
-{
- va_list ap;
-
- va_start(ap, fmt);
- vfprintf(stderr, fmt, ap);
- va_end(ap);
- fflush(stderr);
-}
-
-/*
- * Terminal output, pun intended.
- */
-void
-fatal(const char *fmt, ...)
-{
- va_list ap;
-
- va_start(ap, fmt);
- fprintf(stderr, "patch: **** ");
- vfprintf(stderr, fmt, ap);
- va_end(ap);
- my_exit(2);
-}
-
-/*
- * Say something from patch, something from the system, then silence . . .
- */
-void
-pfatal(const char *fmt, ...)
-{
- va_list ap;
- int errnum = errno;
-
- fprintf(stderr, "patch: **** ");
- va_start(ap, fmt);
- vfprintf(stderr, fmt, ap);
- va_end(ap);
- fprintf(stderr, ": %s\n", strerror(errnum));
- my_exit(2);
-}
-
-/*
- * Get a response from the user via /dev/tty
- */
-void
-ask(const char *fmt, ...)
-{
- va_list ap;
- ssize_t nr = 0;
- static int ttyfd = -1;
-
- va_start(ap, fmt);
- vfprintf(stdout, fmt, ap);
- va_end(ap);
- fflush(stdout);
- if (ttyfd < 0)
- ttyfd = open(_PATH_TTY, O_RDONLY);
- if (ttyfd >= 0) {
- if ((nr = read(ttyfd, buf, bufsz)) > 0 &&
- buf[nr - 1] == '\n')
- buf[nr - 1] = '\0';
- }
- if (ttyfd < 0 || nr <= 0) {
- /* no tty or error reading, pretend user entered 'return' */
- putchar('\n');
- buf[0] = '\0';
- }
-}
-
-/*
- * How to handle certain events when not in a critical region.
- */
-void
-set_signals(int reset)
-{
- static sig_t hupval, intval;
-
- if (!reset) {
- hupval = signal(SIGHUP, SIG_IGN);
- if (hupval != SIG_IGN)
- hupval = my_exit;
- intval = signal(SIGINT, SIG_IGN);
- if (intval != SIG_IGN)
- intval = my_exit;
- }
- signal(SIGHUP, hupval);
- signal(SIGINT, intval);
-}
-
-/*
- * How to handle certain events when in a critical region.
- */
-void
-ignore_signals(void)
-{
- signal(SIGHUP, SIG_IGN);
- signal(SIGINT, SIG_IGN);
-}
-
-/*
- * Make sure we'll have the directories to create a file. If `striplast' is
- * true, ignore the last element of `filename'.
- */
-
-void
-makedirs(const char *filename, bool striplast)
-{
- char *tmpbuf;
-
- if ((tmpbuf = strdup(filename)) == NULL)
- fatal("out of memory\n");
-
- if (striplast) {
- char *s = strrchr(tmpbuf, '/');
- if (s == NULL) {
- free(tmpbuf);
- return; /* nothing to be done */
- }
- *s = '\0';
- }
- if (mkpath(tmpbuf) != 0)
- pfatal("creation of %s failed", tmpbuf);
- free(tmpbuf);
-}
-
-/*
- * Make filenames more reasonable.
- */
-char *
-fetchname(const char *at, bool *exists, int strip_leading)
-{
- char *fullname, *name, *t;
- int sleading, tab;
- struct stat filestat;
-
- if (at == NULL || *at == '\0')
- return NULL;
- while (isspace((unsigned char)*at))
- at++;
-#ifdef DEBUGGING
- if (debug & 128)
- say("fetchname %s %d\n", at, strip_leading);
-#endif
- /* So files can be created by diffing against /dev/null. */
- if (strnEQ(at, _PATH_DEVNULL, sizeof(_PATH_DEVNULL) - 1))
- return NULL;
- name = fullname = t = savestr(at);
-
- tab = strchr(t, '\t') != NULL;
- /* Strip off up to `strip_leading' path components and NUL terminate. */
- for (sleading = strip_leading; *t != '\0' && ((tab && *t != '\t') ||
- !isspace((unsigned char)*t)); t++) {
- if (t[0] == '/' && t[1] != '/' && t[1] != '\0')
- if (--sleading >= 0)
- name = t + 1;
- }
- *t = '\0';
-
- /*
- * If no -p option was given (957 is the default value!), we were
- * given a relative pathname, and the leading directories that we
- * just stripped off all exist, put them back on.
- */
- if (strip_leading == 957 && name != fullname && *fullname != '/') {
- name[-1] = '\0';
- if (stat(fullname, &filestat) == 0 && S_ISDIR(filestat.st_mode)) {
- name[-1] = '/';
- name = fullname;
- }
- }
- name = savestr(name);
- free(fullname);
-
- *exists = stat(name, &filestat) == 0;
- return name;
-}
-
-/*
- * Takes the name returned by fetchname and looks in RCS/SCCS directories
- * for a checked in version.
- */
-char *
-checked_in(char *file)
-{
- char *filebase, *filedir, tmpbuf[PATH_MAX];
- struct stat filestat;
-
- filebase = basename(file);
- filedir = dirname(file);
-
-#define try(f, a1, a2, a3) \
-(snprintf(tmpbuf, sizeof tmpbuf, f, a1, a2, a3), stat(tmpbuf, &filestat) == 0)
-
- if (try("%s/RCS/%s%s", filedir, filebase, RCSSUFFIX) ||
- try("%s/RCS/%s%s", filedir, filebase, "") ||
- try("%s/%s%s", filedir, filebase, RCSSUFFIX) ||
- try("%s/SCCS/%s%s", filedir, SCCSPREFIX, filebase) ||
- try("%s/%s%s", filedir, SCCSPREFIX, filebase))
- return file;
-
- return NULL;
-}
-
-void
-version(void)
-{
- printf("Patch version 2.0-12u9-NetBSD\n");
- my_exit(EXIT_SUCCESS);
-}
-
-/*
- * Exit with cleanup.
- */
-void
-my_exit(int status)
-{
- unlink(TMPINNAME);
- if (!toutkeep)
- unlink(TMPOUTNAME);
- if (!trejkeep)
- unlink(TMPREJNAME);
- unlink(TMPPATNAME);
- exit(status);
-}
-
-void *
-pch_realloc(void *ptr, size_t number, size_t size)
-{
- if (number > SIZE_MAX / size) {
- errno = EOVERFLOW;
- return NULL;
- }
- return realloc(ptr, number * size);
-}
diff --git a/cmd/posix/patch/util.h b/cmd/posix/patch/util.h
@@ -1,52 +0,0 @@
-/*
- * $OpenBSD: util.h,v 1.15 2005/06/20 07:14:06 otto Exp $
- * $DragonFly: src/usr.bin/patch/util.h,v 1.2 2007/09/29 23:11:10 swildner Exp $
- * $NetBSD: util.h,v 1.13 2018/06/18 18:33:31 christos 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
- */
-
-char *fetchname(const char *, bool *, int);
-char *checked_in(char *);
-LINENUM strtolinenum(char *, char **);
-int backup_file(const char *);
-int move_file(const char *, const char *);
-int copy_file(const char *, const char *);
-void say(const char *, ...) __printflike(1, 2);
-void fatal(const char *, ...) __printflike(1, 2) __dead;
-void pfatal(const char *, ...) __printflike(1, 2) __dead;
-void ask(const char *, ...) __printflike(1, 2);
-char *savestr(const char *);
-void set_signals(int);
-void ignore_signals(void);
-void makedirs(const char *, bool);
-void version(void) __dead;
-void my_exit(int) __dead;
-void *pch_realloc(void *, size_t, size_t);
-
-/* in mkpath.c */
-extern int mkpath(char *);
diff --git a/cmd/pseudo/mkpasswd.c b/cmd/pseudo/mkpasswd.c
@@ -0,0 +1,164 @@
+/* See LICENSE file for copyright and license details. */
+#include "util.h"
+
+#include <ctype.h>
+#include <fcntl.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+static void
+usage(void)
+{
+ eprintf("usage: %s [-P fd] [-m type] [-S salt] [password] [salt]\n", argv0);
+}
+
+// ?man mkpasswd: encrypt the given password using salt
+// ?man arguments: [password] [salt]
+// ?man encrypt password using crypt(3) with random or provided salt
+int
+main(int argc, char *argv[])
+{
+ char *mflag;
+ char *sflag;
+ char *parg;
+ char *password;
+ char *cryptpass;
+ int pfd;
+ int fd;
+ int r;
+ int i;
+ int len;
+ int id;
+ char salt[128];
+ char rand_bytes[32];
+ char passbuf[1024];
+ static const char saltchars[] = "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
+
+ mflag = NULL;
+ sflag = NULL;
+ parg = NULL;
+ password = NULL;
+ cryptpass = NULL;
+ pfd = -1;
+
+ ARGBEGIN {
+ // ?man -P:fd: read password from file descriptor
+ case 'P':
+ parg = EARGF(usage());
+ pfd = estrtonum(parg, 0, INT_MAX);
+ break;
+ // ?man -m:type: encryption method (des, md5, sha256, sha512)
+ case 'm':
+ mflag = EARGF(usage());
+ break;
+ // ?man -S:salt: salt to use
+ case 'S':
+ sflag = EARGF(usage());
+ break;
+ default:
+ usage();
+ } ARGEND
+
+ if (argc > 2)
+ usage();
+
+ if (argc == 2) {
+ if (sflag)
+ eprintf("duplicate salt\n");
+ sflag = argv[1];
+ }
+
+ if (argc >= 1)
+ password = argv[0];
+
+ /* default type is des */
+ if (!mflag)
+ mflag = "des";
+
+ if (strcasecmp(mflag, "des") == 0) {
+ id = 0;
+ len = 2;
+ } else if (strcasecmp(mflag, "md5") == 0) {
+ id = 1;
+ len = 8;
+ } else if (strcasecmp(mflag, "sha256") == 0) {
+ id = 5;
+ len = 16;
+ } else if (strcasecmp(mflag, "sha512") == 0) {
+ id = 6;
+ len = 16;
+ } else {
+ eprintf("bad method: %s\n", mflag);
+ }
+
+ if (sflag) {
+ /* validate provided salt */
+ char *s = sflag;
+ while (*s) {
+ if (!isalnum((unsigned char)*s) && *s != '.' && *s != '/')
+ eprintf("bad SALT (need [a-zA-Z0-9./])\n");
+ s++;
+ }
+ if (id > 0)
+ snprintf(salt, sizeof(salt), "$%d$%s", id, sflag);
+ else
+ estrlcpy(salt, sflag, sizeof(salt));
+ } else {
+ /* generate random salt */
+ fd = open("/dev/urandom", O_RDONLY);
+ if (fd < 0)
+ eprintf("open /dev/urandom:");
+ r = read(fd, rand_bytes, len);
+ if (r < len)
+ eprintf("read /dev/urandom:");
+ close(fd);
+
+ if (id > 0) {
+ snprintf(salt, sizeof(salt), "$%d$", id);
+ for (i = 0; i < len; i++)
+ salt[3 + i] = saltchars[(unsigned char)rand_bytes[i] % 64];
+ salt[3 + len] = '\0';
+ } else {
+ for (i = 0; i < len; i++)
+ salt[i] = saltchars[(unsigned char)rand_bytes[i] % 64];
+ salt[len] = '\0';
+ }
+ }
+
+ if (pfd >= 0) {
+ if (dup2(pfd, 0) == -1)
+ eprintf("dup2:");
+ close(pfd);
+ }
+
+ if (!password) {
+ if (isatty(0)) {
+ char *p = getpass("Password: ");
+ if (!p)
+ eprintf("getpass failed\n");
+ estrlcpy(passbuf, p, sizeof(passbuf));
+ password = passbuf;
+ } else {
+ /* read from stdin */
+ int bytes = read(0, passbuf, sizeof(passbuf) - 1);
+ if (bytes < 0)
+ eprintf("read stdin:");
+ /* strip trailing newline or cr */
+ while (bytes > 0 && (passbuf[bytes - 1] == '\n' || passbuf[bytes - 1] == '\r'))
+ bytes--;
+ passbuf[bytes] = '\0';
+ password = passbuf;
+ }
+ }
+
+ cryptpass = crypt(password, salt);
+ if (!cryptpass)
+ eprintf("crypt:");
+ printf("%s\n", cryptpass);
+
+ if (fshut(stdout, "<stdout>"))
+ return 2;
+ return 0;
+}
diff --git a/deps.mk b/deps.mk
@@ -20,11 +20,6 @@ cmd/extra/lsblk.o: shared/util.h
cmd/extra/lsblk.o: shared/arg.h
cmd/extra/lsblk.o: shared/compat.h
cmd/extra/lsblk.o: shared/diskutil.h
-cmd/extra/diff3/diff3.o: cmd/extra/diff3/diff3.c
-cmd/extra/diff3/diff3.o: shared/util.h
-cmd/extra/diff3/diff3.o: shared/arg.h
-cmd/extra/diff3/diff3.o: shared/compat.h
-cmd/extra/diff3/diff3.o: cmd/extra/diff3/../../posix/diff/xmalloc.h
cmd/extra/sync.o: cmd/extra/sync.c
cmd/extra/sync.o: shared/arg.h
cmd/extra/sync.o: shared/util.h
@@ -858,36 +853,7 @@ cmd/posix/date.o: cmd/posix/date.c
cmd/posix/date.o: shared/util.h
cmd/posix/date.o: shared/arg.h
cmd/posix/date.o: shared/compat.h
-cmd/posix/diff/diff.o: cmd/posix/diff/diff.c
-cmd/posix/diff/diff.o: shared/util.h
-cmd/posix/diff/diff.o: shared/arg.h
-cmd/posix/diff/diff.o: shared/compat.h
-cmd/posix/diff/diff.o: cmd/posix/diff/diff.h
-cmd/posix/diff/diff.o: cmd/posix/diff/xmalloc.h
-cmd/posix/diff/diffdir.o: cmd/posix/diff/diffdir.c
-cmd/posix/diff/diffdir.o: shared/util.h
-cmd/posix/diff/diffdir.o: shared/arg.h
-cmd/posix/diff/diffdir.o: shared/compat.h
-cmd/posix/diff/diffdir.o: cmd/posix/diff/diff.h
-cmd/posix/diff/diffreg.o: cmd/posix/diff/diffreg.c
-cmd/posix/diff/diffreg.o: shared/util.h
-cmd/posix/diff/diffreg.o: shared/arg.h
-cmd/posix/diff/diffreg.o: shared/compat.h
-cmd/posix/diff/diffreg.o: cmd/posix/diff/pr.h
-cmd/posix/diff/diffreg.o: cmd/posix/diff/diff.h
-cmd/posix/diff/diffreg.o: cmd/posix/diff/xmalloc.h
-cmd/posix/diff/pr.o: cmd/posix/diff/pr.c
-cmd/posix/diff/pr.o: shared/util.h
-cmd/posix/diff/pr.o: shared/arg.h
-cmd/posix/diff/pr.o: shared/compat.h
-cmd/posix/diff/pr.o: cmd/posix/diff/pr.h
-cmd/posix/diff/pr.o: cmd/posix/diff/diff.h
-cmd/posix/diff/pr.o: cmd/posix/diff/xmalloc.h
-cmd/posix/diff/xmalloc.o: cmd/posix/diff/xmalloc.c
-cmd/posix/diff/xmalloc.o: shared/util.h
-cmd/posix/diff/xmalloc.o: shared/arg.h
-cmd/posix/diff/xmalloc.o: shared/compat.h
-cmd/posix/diff/xmalloc.o: cmd/posix/diff/xmalloc.h
+cmd/posix/diff.o: cmd/posix/diff.c shared/util.h shared/arg.h shared/compat.h
cmd/posix/env.o: cmd/posix/env.c
cmd/posix/env.o: shared/util.h
cmd/posix/env.o: shared/arg.h
@@ -949,43 +915,9 @@ cmd/posix/uuencode.o: cmd/posix/uuencode.c
cmd/posix/uuencode.o: shared/util.h
cmd/posix/uuencode.o: shared/arg.h
cmd/posix/uuencode.o: shared/compat.h
-cmd/posix/patch/backupfile.o: cmd/posix/patch/backupfile.c
-cmd/posix/patch/backupfile.o: cmd/posix/patch/backupfile.h
-cmd/posix/patch/inp.o: cmd/posix/patch/inp.c
-cmd/posix/patch/inp.o: cmd/posix/patch/common.h
-cmd/posix/patch/inp.o: shared/util.h
-cmd/posix/patch/inp.o: shared/arg.h
-cmd/posix/patch/inp.o: shared/compat.h
-cmd/posix/patch/inp.o: cmd/posix/patch/util.h
-cmd/posix/patch/inp.o: cmd/posix/patch/pch.h
-cmd/posix/patch/inp.o: cmd/posix/patch/inp.h
-cmd/posix/patch/mkpath.o: cmd/posix/patch/mkpath.c
-cmd/posix/patch/patch.o: cmd/posix/patch/patch.c
-cmd/posix/patch/patch.o: cmd/posix/patch/common.h
-cmd/posix/patch/patch.o: shared/util.h
-cmd/posix/patch/patch.o: shared/arg.h
-cmd/posix/patch/patch.o: shared/compat.h
-cmd/posix/patch/patch.o: cmd/posix/patch/util.h
-cmd/posix/patch/patch.o: cmd/posix/patch/pch.h
-cmd/posix/patch/patch.o: cmd/posix/patch/inp.h
-cmd/posix/patch/patch.o: cmd/posix/patch/backupfile.h
-cmd/posix/patch/patch.o: cmd/posix/patch/pathnames.h
-cmd/posix/patch/pch.o: cmd/posix/patch/pch.c
-cmd/posix/patch/pch.o: cmd/posix/patch/common.h
-cmd/posix/patch/pch.o: shared/util.h
-cmd/posix/patch/pch.o: shared/arg.h
-cmd/posix/patch/pch.o: shared/compat.h
-cmd/posix/patch/pch.o: cmd/posix/patch/util.h
-cmd/posix/patch/pch.o: cmd/posix/patch/pch.h
-cmd/posix/patch/pch.o: cmd/posix/patch/pathnames.h
-cmd/posix/patch/util.o: cmd/posix/patch/util.c
-cmd/posix/patch/util.o: cmd/posix/patch/common.h
-cmd/posix/patch/util.o: shared/util.h
-cmd/posix/patch/util.o: shared/arg.h
-cmd/posix/patch/util.o: shared/compat.h
-cmd/posix/patch/util.o: cmd/posix/patch/util.h
-cmd/posix/patch/util.o: cmd/posix/patch/backupfile.h
-cmd/posix/patch/util.o: cmd/posix/patch/pathnames.h
+cmd/posix/patch.o: cmd/posix/patch.c shared/util.h shared/arg.h shared/compat.h
+cmd/posix/diff3.o: cmd/posix/diff3.c shared/util.h shared/arg.h shared/compat.h
+cmd/pseudo/mkpasswd.o: cmd/pseudo/mkpasswd.c shared/util.h shared/arg.h shared/compat.h
cmd/pseudo/base64.o: cmd/pseudo/base64.c
cmd/pseudo/base64.o: shared/util.h
cmd/pseudo/base64.o: shared/arg.h
diff --git a/shared/diskutil.h b/shared/diskutil.h
@@ -2,18 +2,30 @@
#ifndef ARUU_DISKUTIL_H
#define ARUU_DISKUTIL_H
-#include <stdint.h>
#include <stddef.h>
+#include <stdint.h>
+
+#ifndef PATH_DEV
+#define PATH_DEV "/dev"
+#endif
+
+#ifndef PATH_PROC
+#define PATH_PROC "/proc"
+#endif
+
+#define PATH_PARTITIONS PATH_PROC "/partitions"
+#define PATH_MOUNTS PATH_PROC "/mounts"
struct BlockDev {
int fd;
- uint64_t size; /* size in bytes */
+ uint64_t size; /* size in bytes */
size_t sec_size; /* sector size */
};
struct BlockDevInfo {
char name[32];
- char type[16]; /* disk, part, loop */
+ char path[128]; /* absolute path to device node */
+ char type[16]; /* disk, part, loop */
uint64_t size;
int major;
int minor;
@@ -24,10 +36,16 @@ struct BlockDevInfo {
};
int blockdev_open(struct BlockDev *dev, const char *path, int writable);
-int blockdev_read(struct BlockDev *dev, uint64_t sector, void *buf, size_t sector_count);
-int blockdev_write(struct BlockDev *dev, uint64_t sector, const void *buf, size_t sector_count);
+int blockdev_read(struct BlockDev *dev, uint64_t sector, void *buf,
+ size_t sector_count);
+int blockdev_write(struct BlockDev *dev, uint64_t sector, const void *buf,
+ size_t sector_count);
void blockdev_close(struct BlockDev *dev);
+int blockdev_detect_fs(struct BlockDev *dev, char *type, size_t type_sz,
+ char *label, size_t label_sz, char *uuid,
+ size_t uuid_sz);
+
struct BlockDevInfo *blockdev_get_list(void);
void blockdev_free_list(struct BlockDevInfo *list);
diff --git a/shared/libutil/diskutil.c b/shared/libutil/diskutil.c
@@ -2,14 +2,14 @@
#include "../diskutil.h"
#include "../util.h"
-#include <sys/types.h>
-#include <sys/stat.h>
+#include <errno.h>
#include <fcntl.h>
-#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
-#include <errno.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <unistd.h>
#if defined(__linux__)
#include <sys/ioctl.h>
@@ -123,13 +123,22 @@ blockdev_get_list(void)
{
#if defined(__linux__)
FILE *fp;
+ FILE *mfile;
char line[256];
- struct BlockDevInfo *head = NULL, *tail = NULL;
+ char mline[512];
+ char devpath[128];
+ char mnt[256];
+ char fs[64];
+ struct BlockDevInfo *head = NULL;
+ struct BlockDevInfo *tail = NULL;
+ struct BlockDevInfo *info;
+ struct BlockDevInfo *curr;
unsigned int major, minor;
unsigned long long blocks;
char name[64];
+ int is_part;
- fp = fopen("/proc/partitions", "r");
+ fp = fopen(PATH_PARTITIONS, "r");
if (!fp)
return NULL;
@@ -137,24 +146,28 @@ blockdev_get_list(void)
if (sscanf(line, " %u %u %llu %63s", &major, &minor, &blocks, name) != 4)
continue;
- struct BlockDevInfo *info = calloc(1, sizeof(*info));
- if (!info)
- break;
+ info = ecalloc(1, sizeof(*info));
strlcpy(info->name, name, sizeof(info->name));
+ snprintf(info->path, sizeof(info->path), "%s/%s", PATH_DEV, name);
info->size = blocks * 1024;
info->major = major;
info->minor = minor;
- /* check if this is a partition of an existing disk */
- struct BlockDevInfo *curr;
- int is_part = 0;
+ /* search tree topology to link partition node under proper target parent disk */
+ is_part = 0;
for (curr = head; curr; curr = curr->next) {
size_t len = strlen(curr->name);
if (strncmp(name, curr->name, len) == 0) {
char c = name[len];
- if ((c >= '0' && c <= '9') || (c == 'p' && name[len+1] >= '0' && name[len+1] <= '9')) {
- is_part = 1;
+ if (curr->name[len - 1] >= '0' && curr->name[len - 1] <= '9') {
+ if (c == 'p' && name[len + 1] >= '0' && name[len + 1] <= '9')
+ is_part = 1;
+ } else {
+ if (c >= '0' && c <= '9')
+ is_part = 1;
+ }
+ if (is_part) {
strlcpy(info->type, "part", sizeof(info->type));
struct BlockDevInfo *p = curr->parts;
if (!p) {
@@ -181,16 +194,14 @@ blockdev_get_list(void)
}
fclose(fp);
- /* parse mounts to populate mountpoint and fstype */
- FILE *mfile = fopen("/proc/mounts", "r");
+ mfile = fopen(PATH_MOUNTS, "r");
if (mfile) {
- char mline[512];
- char devpath[128], mnt[256], fs[64];
while (fgets(mline, sizeof(mline), mfile)) {
if (sscanf(mline, "%127s %255s %63s", devpath, mnt, fs) == 3) {
char *devname = devpath;
- if (strncmp(devpath, "/dev/", 5) == 0)
- devname = devpath + 5;
+ size_t dev_len = strlen(PATH_DEV);
+ if (strncmp(devpath, PATH_DEV, dev_len) == 0 && devpath[dev_len] == '/')
+ devname = devpath + dev_len + 1;
struct BlockDevInfo *curr;
for (curr = head; curr; curr = curr->next) {
if (strcmp(curr->name, devname) == 0) {
@@ -214,57 +225,67 @@ blockdev_get_list(void)
#elif defined(__FreeBSD__)
char disks[1024];
- size_t len = sizeof(disks);
- struct BlockDevInfo *head = NULL, *tail = NULL;
+ char devpath[128];
+ char *tok;
+ char *ptr;
+ struct BlockDevInfo *head = NULL;
+ struct BlockDevInfo *tail = NULL;
+ struct BlockDevInfo *info;
+ struct BlockDevInfo *part;
+ struct BlockDevInfo *p;
+ struct BlockDev dev;
+ DIR *dir;
+ struct dirent *de;
+ size_t disk_len;
+ size_t len;
+ struct statfs *mntbuf;
+ int mntsize;
+ int i;
+ len = sizeof(disks);
if (sysctlbyname("kern.disks", disks, &len, NULL, 0) < 0)
return NULL;
- char *tok, *ptr = disks;
+ ptr = disks;
while ((tok = strsep(&ptr, " \t")) != NULL) {
if (!*tok)
continue;
- struct BlockDevInfo *info = calloc(1, sizeof(*info));
- if (!info)
- break;
+ info = ecalloc(1, sizeof(*info));
strlcpy(info->name, tok, sizeof(info->name));
+ snprintf(info->path, sizeof(info->path), "%s/%s", PATH_DEV, tok);
strlcpy(info->type, "disk", sizeof(info->type));
- char devpath[64];
- snprintf(devpath, sizeof(devpath), "/dev/%s", tok);
- struct BlockDev dev;
+ snprintf(devpath, sizeof(devpath), "%s/%s", PATH_DEV, tok);
if (blockdev_open(&dev, devpath, 0) == 0) {
info->size = dev.size;
blockdev_close(&dev);
}
- DIR *dir = opendir("/dev");
+ dir = opendir(PATH_DEV);
if (dir) {
- struct dirent *de;
- size_t disk_len = strlen(tok);
+ disk_len = strlen(tok);
while ((de = readdir(dir)) != NULL) {
if (strncmp(de->d_name, tok, disk_len) == 0) {
char c = de->d_name[disk_len];
if (c == 's' || c == 'p') {
- struct BlockDevInfo *part = calloc(1, sizeof(*part));
- if (part) {
- strlcpy(part->name, de->d_name, sizeof(part->name));
- strlcpy(part->type, "part", sizeof(part->type));
- snprintf(devpath, sizeof(devpath), "/dev/%s", de->d_name);
- if (blockdev_open(&dev, devpath, 0) == 0) {
- part->size = dev.size;
- blockdev_close(&dev);
- }
- struct BlockDevInfo *p = info->parts;
- if (!p) {
- info->parts = part;
- } else {
- while (p->next)
- p = p->next;
- p->next = part;
- }
+ part = ecalloc(1, sizeof(*part));
+ strlcpy(part->name, de->d_name, sizeof(part->name));
+ snprintf(part->path, sizeof(part->path), "%s/%s", PATH_DEV, de->d_name);
+ strlcpy(part->type, "part", sizeof(part->type));
+ snprintf(devpath, sizeof(devpath), "%s/%s", PATH_DEV, de->d_name);
+ if (blockdev_open(&dev, devpath, 0) == 0) {
+ part->size = dev.size;
+ blockdev_close(&dev);
+ }
+ p = info->parts;
+ if (!p) {
+ info->parts = part;
+ } else {
+ while (p->next)
+ p = p->next;
+ p->next = part;
}
}
}
@@ -280,13 +301,13 @@ blockdev_get_list(void)
tail = info;
}
- struct statfs *mntbuf;
- int mntsize = getmntinfo(&mntbuf, MNT_NOWAIT);
- for (int i = 0; i < mntsize; i++) {
- char *devpath = mntbuf[i].f_mntfromname;
- char *devname = devpath;
- if (strncmp(devpath, "/dev/", 5) == 0)
- devname = devpath + 5;
+ mntsize = getmntinfo(&mntbuf, MNT_NOWAIT);
+ for (i = 0; i < mntsize; i++) {
+ char *frompath = mntbuf[i].f_mntfromname;
+ char *devname = frompath;
+ size_t dev_len = strlen(PATH_DEV);
+ if (strncmp(frompath, PATH_DEV, dev_len) == 0 && frompath[dev_len] == '/')
+ devname = frompath + dev_len + 1;
struct BlockDevInfo *curr;
for (curr = head; curr; curr = curr->next) {
if (strcmp(curr->name, devname) == 0) {
@@ -307,54 +328,66 @@ blockdev_get_list(void)
#elif defined(__OpenBSD__)
char disknames[1024];
- size_t len = sizeof(disknames);
- int mib[2] = { CTL_HW, HW_DISKNAMES };
- struct BlockDevInfo *head = NULL, *tail = NULL;
+ char devpath[128];
+ char *tok;
+ char *ptr;
+ char *colon;
+ struct BlockDevInfo *head = NULL;
+ struct BlockDevInfo *tail = NULL;
+ struct BlockDevInfo *info;
+ struct BlockDevInfo *part;
+ struct BlockDevInfo *p;
+ struct BlockDev dev;
+ size_t len;
+ int mib[2];
+ char c;
+ struct statfs *mntbuf;
+ int mntsize;
+ int i;
+ mib[0] = CTL_HW;
+ mib[1] = HW_DISKNAMES;
+ len = sizeof(disknames);
if (sysctl(mib, 2, disknames, &len, NULL, 0) < 0)
return NULL;
- char *tok, *ptr = disknames;
+ ptr = disknames;
while ((tok = strsep(&ptr, ",")) != NULL) {
- char *colon = strchr(tok, ':');
+ colon = strchr(tok, ':');
if (colon)
*colon = '\0';
if (!*tok)
continue;
- struct BlockDevInfo *info = calloc(1, sizeof(*info));
- if (!info)
- break;
+ info = ecalloc(1, sizeof(*info));
strlcpy(info->name, tok, sizeof(info->name));
+ snprintf(info->path, sizeof(info->path), "%s/r%sc", PATH_DEV, tok);
strlcpy(info->type, "disk", sizeof(info->type));
- char devpath[64];
- snprintf(devpath, sizeof(devpath), "/dev/r%sc", tok);
- struct BlockDev dev;
+ snprintf(devpath, sizeof(devpath), "%s/r%sc", PATH_DEV, tok);
if (blockdev_open(&dev, devpath, 0) == 0) {
info->size = dev.size;
blockdev_close(&dev);
}
- for (char c = 'a'; c <= 'p'; c++) {
+ for (c = 'a'; c <= 'p'; c++) {
if (c == 'c')
continue;
- snprintf(devpath, sizeof(devpath), "/dev/r%s%c", tok, c);
+ snprintf(devpath, sizeof(devpath), "%s/r%s%c", PATH_DEV, tok, c);
if (blockdev_open(&dev, devpath, 0) == 0) {
- struct BlockDevInfo *part = calloc(1, sizeof(*part));
- if (part) {
- snprintf(part->name, sizeof(part->name), "%s%c", tok, c);
- strlcpy(part->type, "part", sizeof(part->type));
- part->size = dev.size;
- struct BlockDevInfo *p = info->parts;
- if (!p) {
- info->parts = part;
- } else {
- while (p->next)
- p = p->next;
- p->next = part;
- }
+ part = ecalloc(1, sizeof(*part));
+ snprintf(part->name, sizeof(part->name), "%s%c", tok, c);
+ snprintf(part->path, sizeof(part->path), "%s/r%s%c", PATH_DEV, tok, c);
+ strlcpy(part->type, "part", sizeof(part->type));
+ part->size = dev.size;
+ p = info->parts;
+ if (!p) {
+ info->parts = part;
+ } else {
+ while (p->next)
+ p = p->next;
+ p->next = part;
}
blockdev_close(&dev);
}
@@ -368,13 +401,13 @@ blockdev_get_list(void)
tail = info;
}
- struct statfs *mntbuf;
- int mntsize = getmntinfo(&mntbuf, MNT_NOWAIT);
- for (int i = 0; i < mntsize; i++) {
- char *devpath = mntbuf[i].f_mntfromname;
- char *devname = devpath;
- if (strncmp(devpath, "/dev/", 5) == 0)
- devname = devpath + 5;
+ mntsize = getmntinfo(&mntbuf, MNT_NOWAIT);
+ for (i = 0; i < mntsize; i++) {
+ char *frompath = mntbuf[i].f_mntfromname;
+ char *devname = frompath;
+ size_t dev_len = strlen(PATH_DEV);
+ if (strncmp(frompath, PATH_DEV, dev_len) == 0 && frompath[dev_len] == '/')
+ devname = frompath + dev_len + 1;
struct BlockDevInfo *curr;
for (curr = head; curr; curr = curr->next) {
if (strcmp(curr->name, devname) == 0) {
@@ -394,26 +427,29 @@ blockdev_get_list(void)
return head;
#else
- struct BlockDevInfo *head = NULL, *tail = NULL;
+ struct BlockDevInfo *head = NULL;
+ struct BlockDevInfo *tail = NULL;
+ struct BlockDevInfo *info;
+ struct BlockDev dev;
char devname[16];
- for (char c = 'a'; c <= 'z'; c++) {
+ char devpath[128];
+ char c;
+
+ for (c = 'a'; c <= 'z'; c++) {
snprintf(devname, sizeof(devname), "sd%c", c);
- char devpath[32];
- snprintf(devpath, sizeof(devpath), "/dev/%s", devname);
- struct BlockDev dev;
+ snprintf(devpath, sizeof(devpath), "%s/%s", PATH_DEV, devname);
if (blockdev_open(&dev, devpath, 0) == 0) {
- struct BlockDevInfo *info = calloc(1, sizeof(*info));
- if (info) {
- strlcpy(info->name, devname, sizeof(info->name));
- strlcpy(info->type, "disk", sizeof(info->type));
- info->size = dev.size;
- if (!head) {
- head = info;
- } else {
- tail->next = info;
- }
- tail = info;
+ info = ecalloc(1, sizeof(*info));
+ strlcpy(info->name, devname, sizeof(info->name));
+ snprintf(info->path, sizeof(info->path), "%s/%s", PATH_DEV, devname);
+ strlcpy(info->type, "disk", sizeof(info->type));
+ info->size = dev.size;
+ if (!head) {
+ head = info;
+ } else {
+ tail->next = info;
}
+ tail = info;
blockdev_close(&dev);
}
}
@@ -437,3 +473,269 @@ blockdev_free_list(struct BlockDevInfo *list)
curr = next;
}
}
+
+struct FsType {
+ const char *name;
+ size_t magic_offset;
+ size_t magic_len;
+ uint64_t magic1;
+ uint64_t magic2;
+ size_t uuid_offset;
+ size_t uuid_len;
+ size_t label_offset;
+ size_t label_len;
+};
+
+static const struct FsType fstypes[] = {
+ /* ext2/3/4 */
+ { "ext", 1080, 2, 0xEF53, 0x53EF, 1128, 16, 1144, 16 },
+ /* vfat / fat32 */
+ { "vfat", 82, 5, 0x3233544146ULL, 0, 67, 4, 71, 11 },
+ /* vfat / fat12/16 */
+ { "vfat", 54, 4, 0x31544146, 0, 39, 4, 43, 11 },
+ /* ntfs */
+ { "ntfs", 3, 4, 0x5346544e, 0, 72, 8, 0, 0 },
+ /* xfs */
+ { "xfs", 0, 4, 0x42534658, 0x58465342, 32, 16, 108, 12 },
+ /* btrfs */
+ { "btrfs", 65600, 8, 0x4D5F53665248425FULL, 0, 65803, 16, 65819, 256 },
+ /* f2fs */
+ { "f2fs", 1024, 4, 0xF2F52010, 0x1020F5F2, 1132, 16, 1148, 512 },
+ /* ufs1 */
+ { "ufs1", 9564, 4, 0x011954, 0x54190100, 8428, 8, 0, 0 },
+ /* ufs2 */
+ { "ufs2", 66908, 4, 0x19540119, 0x19015419, 65772, 8, 66216, 32 },
+ /* fossil */
+ { "fossil", 131200, 4, 0x2340A3B1, 0xB1A34023, 0, 0, 131072, 127 },
+};
+
+static void
+format_uuid(const unsigned char *buf, size_t len, const char *type, char *out, size_t out_len)
+{
+ size_t i;
+ char *p;
+
+ p = out;
+ if (strcmp(type, "vfat") == 0) {
+ snprintf(out, out_len, "%02X%02X-%02X%02X", buf[3], buf[2], buf[1], buf[0]);
+ return;
+ }
+
+ if (strcmp(type, "ntfs") == 0) {
+ for (i = 8; i > 0; i--) {
+ snprintf(p, out_len - (p - out), "%02X", buf[i - 1]);
+ p += 2;
+ }
+ return;
+ }
+
+ for (i = 0; i < len; i++) {
+ if (i == 4 || i == 6 || i == 8 || i == 10) {
+ *p++ = '-';
+ }
+ snprintf(p, out_len - (p - out), "%02x", buf[i]);
+ p += 2;
+ }
+ *p = '\0';
+}
+
+static int
+zfs_detect(const unsigned char *buf, size_t len)
+{
+ size_t offset;
+ uint64_t magic;
+
+ for (offset = 131072; offset + 8 <= len; offset += 1024) {
+ magic = ((uint64_t)buf[offset + 7] << 56) |
+ ((uint64_t)buf[offset + 6] << 48) |
+ ((uint64_t)buf[offset + 5] << 40) |
+ ((uint64_t)buf[offset + 4] << 32) |
+ ((uint64_t)buf[offset + 3] << 24) |
+ ((uint64_t)buf[offset + 2] << 16) |
+ ((uint64_t)buf[offset + 1] << 8) |
+ (uint64_t)buf[offset];
+
+ if (magic == 0x00bab10c00000000ULL || magic == 0x0cb1ba0000000000ULL ||
+ magic == 0x00bab10cULL || magic == 0x0cb1ba00ULL)
+ return 1;
+ }
+ return 0;
+}
+
+struct Plan9FsDef {
+ const char *name;
+ int blocksize;
+ int namelen;
+ int dirblks;
+ int indirblks;
+ int daddrbits;
+};
+
+static const struct Plan9FsDef p9_fs_defs[] = {
+ { "cwfs64x", 16384, 144, 6, 4, 64 },
+ { "cwfs64", 16384, 56, 6, 4, 64 },
+ { "cwfs", 16384, 28, 6, 2, 32 },
+ { "fs64", 8192, 56, 6, 4, 64 },
+ { "fs", 4096, 28, 6, 2, 32 },
+};
+
+static int
+plan9_magic_check(const unsigned char *p, const char **name)
+{
+ if (memcmp(p, "\x01\x1c\xe5\x0d", 4) == 0 || memcmp(p, "\x0d\xe5\x1c\x01", 4) == 0) {
+ *name = "hjfs";
+ return 1;
+ }
+ if (memcmp(p, "gefs", 4) == 0 || memcmp(p, "sfeg", 4) == 0) {
+ *name = "gefs";
+ return 1;
+ }
+ return 0;
+}
+
+static int
+plan9_detect_other(const unsigned char *buf, size_t len, const char **name)
+{
+ if (len >= 4 && plan9_magic_check(buf, name))
+ return 1;
+ if (len >= 516 && plan9_magic_check(buf + 512, name))
+ return 1;
+ return 0;
+}
+
+static int
+plan9_detect_text(const unsigned char *buf, size_t len, const char **name)
+{
+ int blocksize = 0, namelen = 0, dirblks = 0, indirblks = 0, daddrbits = 0;
+ char line[128];
+ char key[64];
+ int val;
+ size_t i = 0, j;
+
+ if (len >= 256 + 15) {
+ if (memcmp(buf + 256, "kfs wren device", 15) == 0) {
+ *name = "kfs";
+ return 1;
+ }
+ }
+
+ if (len < 512)
+ return 0;
+ i = 512;
+ if (len > 1536)
+ len = 1536;
+
+ while (i < len) {
+ size_t k = 0;
+ while (i < len && buf[i] != '\n' && k < sizeof(line) - 1) {
+ line[k++] = buf[i++];
+ }
+ if (i < len && buf[i] == '\n')
+ i++;
+ line[k] = '\0';
+
+ if (sscanf(line, "%63s %d", key, &val) == 2) {
+ if (strcmp(key, "blocksize") == 0) blocksize = val;
+ else if (strcmp(key, "namelen") == 0) namelen = val;
+ else if (strcmp(key, "dirblks") == 0) dirblks = val;
+ else if (strcmp(key, "indirblks") == 0) indirblks = val;
+ else if (strcmp(key, "daddrbits") == 0) daddrbits = val;
+ }
+ }
+
+ for (j = 0; j < LEN(p9_fs_defs); j++) {
+ if (blocksize == p9_fs_defs[j].blocksize &&
+ namelen == p9_fs_defs[j].namelen &&
+ dirblks == p9_fs_defs[j].dirblks &&
+ indirblks == p9_fs_defs[j].indirblks &&
+ daddrbits == p9_fs_defs[j].daddrbits) {
+ *name = p9_fs_defs[j].name;
+ return 1;
+ }
+ }
+
+ return 0;
+}
+
+int
+blockdev_detect_fs(struct BlockDev *dev, char *type, size_t type_sz,
+ char *label, size_t label_sz, char *uuid, size_t uuid_sz)
+{
+ unsigned char *buf;
+ size_t read_size = 262144; /* 256kb */
+ size_t sectors_to_read;
+ size_t i, j;
+ int found = 0;
+
+ if (dev->size < read_size)
+ read_size = dev->size;
+
+ buf = emalloc(read_size);
+ sectors_to_read = (read_size + dev->sec_size - 1) / dev->sec_size;
+ if (blockdev_read(dev, 0, buf, sectors_to_read) < 0) {
+ free(buf);
+ return -2;
+ }
+
+ for (i = 0; i < LEN(fstypes); i++) {
+ const struct FsType *fs = &fstypes[i];
+ if (fs->magic_offset + fs->magic_len > read_size)
+ continue;
+
+ uint64_t val = 0;
+ for (j = 0; j < fs->magic_len; j++) {
+ val |= ((uint64_t)buf[fs->magic_offset + j]) << (8 * j);
+ }
+
+ if (val == fs->magic1 || (fs->magic2 && val == fs->magic2)) {
+ const char *type_name = fs->name;
+ if (strcmp(fs->name, "ext") == 0) {
+ if (buf[1116] & 4)
+ type_name = "ext3";
+ else if (buf[1120] & 64)
+ type_name = "ext4";
+ else
+ type_name = "ext2";
+ }
+
+ if (type && type_sz)
+ strlcpy(type, type_name, type_sz);
+
+ if (label && label_sz && fs->label_len && fs->label_offset + fs->label_len <= read_size) {
+ snprintf(label, label_sz, "%.*s", (int)fs->label_len, buf + fs->label_offset);
+ /* strip trailing spaces */
+ char *end = label + strlen(label) - 1;
+ while (end >= label && *end == ' ') {
+ *end = '\0';
+ end--;
+ }
+ }
+
+ if (uuid && uuid_sz && fs->uuid_len && fs->uuid_offset + fs->uuid_len <= read_size) {
+ format_uuid(buf + fs->uuid_offset, fs->uuid_len, fs->name, uuid, uuid_sz);
+ }
+
+ found = 1;
+ break;
+ }
+ }
+
+ if (!found && zfs_detect(buf, read_size)) {
+ if (type && type_sz)
+ strlcpy(type, "zfs_member", type_sz);
+ found = 1;
+ }
+
+ if (!found) {
+ const char *p9_name = NULL;
+ if (plan9_detect_other(buf, read_size, &p9_name) ||
+ plan9_detect_text(buf, read_size, &p9_name)) {
+ if (type && type_sz)
+ strlcpy(type, p9_name, type_sz);
+ found = 1;
+ }
+ }
+
+ free(buf);
+ return found ? 0 : -1;
+}