[PATCH 09/11] sandbox: Add a way to map a file into memory

Marek Behún marek.behun at nic.cz
Thu Aug 19 12:28:20 CEST 2021


On Wed, 18 Aug 2021 21:40:31 -0600
Simon Glass <sjg at chromium.org> wrote:

> It is useful to map a file into memory so that it can be accessed using
> simple pointers. Add a function to support this.
> 
> Signed-off-by: Simon Glass <sjg at chromium.org>

> +int os_map_file(const char *pathname, int os_flags, void **bufp, int *sizep)
> +{
> +	void *ptr;
> +	int size;
> +	int ifd;
> +
> +	ifd = os_open(pathname, os_flags);
> +	if (ifd < 0) {
> +		printf("Cannot open file '%s'\n", pathname);
> +		return -EIO;
> +	}
> +	size = os_filesize(ifd);
> +	if (size < 0) {
> +		printf("Cannot get file size of '%s'\n", pathname);
> +		return -EIO;
> +	}
> +
> +	ptr = mmap(0, size, PROT_READ | PROT_WRITE, MAP_SHARED, ifd, 0);
> +	if (ptr == MAP_FAILED) {
> +		printf("Can't map file '%s': %s\n", pathname, strerror(errno));
> +		return -EPERM;
> +	}
> +
> +	*bufp = ptr;
> +	*sizep = size;
> +
> +	return 0;
> +}

You need to close the file descriptor after mmapping.

Marek


More information about the U-Boot mailing list