2017-11-30 21:16:13 +08:00
|
|
|
/*
|
2021-03-08 18:19:04 +08:00
|
|
|
* Copyright (c) 2006-2021, RT-Thread Development Team
|
2017-11-30 21:16:13 +08:00
|
|
|
*
|
2018-10-14 19:28:18 +08:00
|
|
|
* SPDX-License-Identifier: Apache-2.0
|
2017-11-30 21:16:13 +08:00
|
|
|
*
|
|
|
|
* Change Logs:
|
2024-04-02 11:18:15 +08:00
|
|
|
* Date Author Notes
|
|
|
|
* 2017/11/30 Bernard The first version.
|
|
|
|
* 2024/03/29 TroyMitchelle Add all function comments
|
2017-11-30 21:16:13 +08:00
|
|
|
*/
|
|
|
|
|
|
|
|
#include <stdint.h>
|
|
|
|
#include <stdio.h>
|
|
|
|
|
|
|
|
#include <rtthread.h>
|
2022-01-11 15:20:14 +08:00
|
|
|
#include <unistd.h>
|
2022-12-03 12:07:44 +08:00
|
|
|
#include <stdlib.h>
|
2022-01-11 15:20:14 +08:00
|
|
|
#include <sys/stat.h>
|
|
|
|
#include <sys/statfs.h>
|
2022-03-08 11:35:11 +08:00
|
|
|
#include <sys/errno.h>
|
2017-11-30 21:16:13 +08:00
|
|
|
|
2021-12-08 04:47:00 +08:00
|
|
|
#include "sys/mman.h"
|
2017-11-30 21:16:13 +08:00
|
|
|
|
2024-04-02 11:18:15 +08:00
|
|
|
/**
|
|
|
|
* @brief Maps a region of memory into the calling process's address space.
|
|
|
|
* @param addr Desired starting address of the mapping.
|
|
|
|
* @param length Length of the mapping.
|
|
|
|
* @param prot Protection of the mapped memory region.
|
|
|
|
* @param flags Type of the mapped memory region.
|
|
|
|
* @param fd File descriptor of the file to be mapped.
|
|
|
|
* @param offset Offset within the file to start the mapping.
|
|
|
|
* @return Upon success, returns a pointer to the mapped region; otherwise, MAP_FAILED is returned.
|
|
|
|
*/
|
2017-11-30 21:16:13 +08:00
|
|
|
void *mmap(void *addr, size_t length, int prot, int flags,
|
|
|
|
int fd, off_t offset)
|
|
|
|
{
|
|
|
|
uint8_t *mem;
|
|
|
|
|
|
|
|
if (addr)
|
|
|
|
{
|
|
|
|
mem = addr;
|
|
|
|
}
|
|
|
|
else mem = (uint8_t *)malloc(length);
|
|
|
|
|
|
|
|
if (mem)
|
|
|
|
{
|
|
|
|
off_t cur;
|
|
|
|
size_t read_bytes;
|
|
|
|
|
|
|
|
cur = lseek(fd, 0, SEEK_SET);
|
|
|
|
|
|
|
|
lseek(fd, offset, SEEK_SET);
|
2019-01-21 17:19:07 +08:00
|
|
|
read_bytes = read(fd, mem, length);
|
2017-11-30 21:16:13 +08:00
|
|
|
if (read_bytes != length)
|
|
|
|
{
|
|
|
|
if (addr == RT_NULL)
|
|
|
|
{
|
|
|
|
/* read failed */
|
|
|
|
free(mem);
|
|
|
|
mem = RT_NULL;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
lseek(fd, cur, SEEK_SET);
|
|
|
|
|
|
|
|
return mem;
|
|
|
|
}
|
|
|
|
|
|
|
|
errno = ENOMEM;
|
|
|
|
|
|
|
|
return MAP_FAILED;
|
|
|
|
}
|
|
|
|
|
2024-04-02 11:18:15 +08:00
|
|
|
/**
|
|
|
|
* @brief Unmaps a mapped region of memory.
|
|
|
|
* @param addr Starting address of the mapping to be unmapped.
|
|
|
|
* @param length Length of the mapping.
|
|
|
|
* @return Upon success, returns 0; otherwise, -1 is returned.
|
|
|
|
*/
|
2017-11-30 21:16:13 +08:00
|
|
|
int munmap(void *addr, size_t length)
|
|
|
|
{
|
|
|
|
if (addr)
|
|
|
|
{
|
|
|
|
free(addr);
|
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
|
|
|
|
return -1;
|
|
|
|
}
|