File size: 2,348 Bytes
71e354e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 | /**************************************************************************************************
*
* Copyright (c) 2019-2026 Axera Semiconductor (Ningbo) Co., Ltd. All Rights Reserved.
*
* This source file is the property of Axera Semiconductor (Ningbo) Co., Ltd. and
* may not be copied or distributed in any isomorphic form without the prior
* written consent of Axera Semiconductor (Ningbo) Co., Ltd.
*
**************************************************************************************************/
#pragma once
#include <sys/mman.h>
#include <fcntl.h>
#include <stdio.h>
#include <fstream>
#include <vector>
#include <string.h>
#include <unistd.h>
namespace utils {
bool file_exist(const std::string &path);
bool read_file(const std::string &path, std::vector<char> &data);
bool read_file(const std::string &path, char **data, size_t *len);
}
class MMap
{
private:
void *_add = nullptr;
int _size;
public:
MMap() {}
MMap(const char *file)
{
open_file(file);
}
~MMap()
{
close_file();
}
bool open_file(const char *file)
{
_add = _mmap(file, &_size);
if (!_add)
{
return false;
}
return true;
}
void close_file()
{
if (_add)
{
munmap(_add, _size);
_add = nullptr;
_size = 0;
}
}
size_t size()
{
return _size;
}
void *data()
{
return _add;
}
static void *_mmap(const char *model_file, int *model_size)
{
auto *file_fp = fopen(model_file, "r");
if (!file_fp)
{
return nullptr;
}
fseek(file_fp, 0, SEEK_END);
*model_size = ftell(file_fp);
fclose(file_fp);
int fd = open(model_file, O_RDONLY);
if (fd < 0)
{
fprintf(stderr, "[MMap] open failed for file %s: %s\n", model_file, strerror(errno));
return nullptr;
}
void *mmap_addr = mmap(NULL, *model_size, PROT_READ, MAP_SHARED, fd, 0);
if (mmap_addr == MAP_FAILED)
{
fprintf(stderr, "[MMap] mmap failed for file %s: %s\n", model_file, strerror(errno));
close(fd);
return nullptr;
}
close(fd);
return mmap_addr;
}
}; |