/*
 * DF-3879 fix sanity: the LEGITIMATE /dev/dsp mmap feature (offset 0,
 * size == bufsize) must still work after the overflow-safe bounds check.
 */
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/mman.h>
#include <sys/ioctl.h>
#include <sys/soundcard.h>

int main(void)
{
	setvbuf(stdout, NULL, _IONBF, 0);
	int fd = open("/dev/dsp", O_RDWR);
	if (fd < 0) { printf("[-] open: %s\n", strerror(errno)); return 2; }
	int fmt = AFMT_S16_LE, ch = 2, sp = 44100;
	audio_buf_info oi;
	if (ioctl(fd, SNDCTL_DSP_SETFMT, &fmt) < 0 ||
	    ioctl(fd, SNDCTL_DSP_CHANNELS, &ch) < 0 ||
	    ioctl(fd, SNDCTL_DSP_SPEED, &sp) < 0 ||
	    ioctl(fd, SNDCTL_DSP_GETOSPACE, &oi) < 0 || oi.bytes <= 0) {
		printf("[-] setup: %s\n", strerror(errno));
		return 2;
	}
	printf("[*] bufsize=%d\n", oi.bytes);
	void *p = mmap(NULL, (size_t)oi.bytes, PROT_READ | PROT_WRITE,
			MAP_SHARED, fd, 0);
	if (p == MAP_FAILED) {
		printf("[-] legit mmap(off=0, size=bufsize): %s (errno=%d)"
		       " — FIX BROKE THE FEATURE\n", strerror(errno), errno);
		return 3;
	}
	strcpy((char *)p, "LEGIT-OK");
	printf("[+] legit mmap ok, RW works (\"%s\") — feature preserved\n",
	       (char *)p);
	return 0;
}
