Project

General

Profile

memrw.c » memrw.c

Frédéric Blanc, 2023-12-14 15:54

 
/* memrw.c

Copyright (c) 2023- GAUCHARD David (LAAS-CNRS)
Copyright (c) 2023- BLANC Frédéric (LAAS-CNRS)

memrw is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

memrw is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with memrw. If not, see <http://www.gnu.org/licenses/>.
*/

// gcc -Wall -Wextra memrw.c -o memrw && ./memrw 0x40000000 1 0xfe

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <unistd.h>
#include <stdint.h>

int main(int argc, char *argv[]) {
if (argc < 3) {
printf("Usage: %s <phys_addr> <read-len> [ value8bits value8bits ... ]\n", argv[0]);
return 0;
}

off_t offset = strtoul(argv[1], NULL, 0);
size_t len = strtoul(argv[2], NULL, 0);

// Truncate offset to a multiple of the page size, or mmap will fail.
size_t page_size = sysconf(_SC_PAGE_SIZE);
off_t page_base = (offset / page_size) * page_size;
off_t page_offset = offset - page_base;

printf("page_size = 0x%zx (%zd)\n", page_size, page_size);
printf("page_base = 0x%lx\n", page_base);
printf("page_offset = %lx\n", page_offset);
printf("page_offset + len = %lx\n", page_offset + len);

int fd = open("/dev/mem", O_SYNC | O_RDWR);
if (fd == -1)
{
perror("open(O_SYNC, O_RDWR)");
exit(EXIT_FAILURE);
}
unsigned char *mem = mmap(NULL, page_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, page_base);
if (mem == MAP_FAILED) {
perror("Can't map memory");
return -1;
}

size_t i;
printf("avant:\n");
for (i = 0; i < len; ++i)
printf("%02x ", (int)mem[page_offset + i]);
printf("\n");

i = 0;
while (argv[i + 3] != NULL)
{
uint8_t v = strtoul(argv[i + 3], NULL, 0);
printf("writing 0x%02x @ %p (virtual %p)\n", v, (void*)(offset + i), &mem[page_offset + i]);
mem[page_offset + i] = v;
i++;
}

printf("apres:\n");
for (i = 0; i < len; ++i)
printf("%02x ", (int)mem[page_offset + i]);
printf("\n");

if (munmap(mem, page_size) == -1)
{
perror("munmap");
exit(EXIT_FAILURE);
}

return 0;
}
    (1-1/1)