/*
 * Load-instrumented copy of the FIXED bcmp (fix.diff applied) — same
 * LDB/LDC accounting as bcmp_instr.c to show out-of-region loads == 0.
 */
#include <string.h>
#include <machine/endian.h>

typedef	const unsigned char	*ustring;
typedef unsigned long		ul;
typedef const unsigned long	*culp;

unsigned long g_below_start[2], g_past_end[2], g_in[2], g_max_below[2], g_max_past[2];
const unsigned char *g_lo[2], *g_hi[2];
long g_last_outside_case[4];
int g_case[3];

#define NOTE(idx, p, sz) do {                                   \
    const unsigned char *_p = (const unsigned char *)(p);       \
    if (_p < g_lo[idx]) {                                       \
        g_below_start[idx]++;                                   \
        unsigned long d = (unsigned long)(g_lo[idx] - _p);      \
        if (d > g_max_below[idx]) g_max_below[idx] = d;         \
    } else if (_p + (sz) > g_hi[idx]) {                         \
        g_past_end[idx]++;                                      \
        unsigned long d = (unsigned long)(_p + (sz) - g_hi[idx]); \
        if (d > g_max_past[idx]) {                              \
            g_max_past[idx] = d;                                \
            g_last_outside_case[0]=g_case[0];                   \
            g_last_outside_case[1]=g_case[1];                   \
            g_last_outside_case[2]=g_case[2];                   \
            g_last_outside_case[3]=idx;                         \
        }                                                       \
    } else g_in[idx]++;                                         \
} while (0)

#define LDC(idx, e) ({ culp _q = (e); NOTE(idx, _q, sizeof(ul)); *_q; })
#define LDB(idx, e) ({ const unsigned char *_q = (e); NOTE(idx, _q, 1); *_q; })

int
bcmp_fixed(const void *b1, const void *b2, size_t length)
{
	size_t	len = length;
	ustring	p1 = b1, p2 = b2;

	if (len == 0)
		return (0);

	while (((long)p1 | (long)p2) & (sizeof(long) - 1)) {
		if (LDB(0, p1) != LDB(1, p2)) { p1++; p2++; return (1); }
		p1++; p2++;
		if (--len <= 0)
			return (0);
	}

	while (len >= sizeof(long)) {
		if (LDC(0, (culp)p1) != LDC(1, (culp)p2))
			return (1);
		p1 += sizeof(long);
		p2 += sizeof(long);
		len -= sizeof(long);
	}

	while (len--) {
		if (LDB(0, p1++) != LDB(1, p2++))
			return (1);
	}
	return (0);
}
