// Memory-map and dump the content of a file.
// Useful for Sysfs resources that can not be read(2),
// e.g. the BAR resources of PCI devices.
// Usage: mmap_dump /sys/bus/pci/.../resource0 | hd

#include <err.h>
#include <fcntl.h>
#include <stdio.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>

int main(int argc, char *argv[])
{
	char *fn, *fm, *p;
	int fd;

	if (argc != 2)
		errx(1, "wrong argument count");

	fn = argv[1];

	fd = open(fn, O_RDONLY);
	if (fd == -1)
		err(2, "can't open file");

	off_t length = lseek(fd, 0, SEEK_END);
	if (length == -1)
			err(3, "lseek failed");

	fm = mmap(0, length, PROT_READ, MAP_PRIVATE, fd, 0);
	if (fm == MAP_FAILED)
		err(4, "mmap failed");

	for (p = fm; p < fm + length; ++p)
		fputc(*p, stdout);

	if (munmap(fm, length) == -1)
		warn("munmap failed");

	if (close(fd) == -1)
		warn("close failed");

	return 0;
}