~aleteoryx/muditaos

ref: 1a6ea1f4b3eb85b3c3018ecf51016cb35d5172cb muditaos/module-vfs/vfs.cpp -rw-r--r-- 9.3 KiB
1a6ea1f4 — Alek Rudnik [EGD-4205] mudita 1st audio assets (#940) 5 years ago
                                                                                
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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
// Copyright (c) 2017-2020, Mudita Sp. z.o.o. All rights reserved.
// For licensing, see https://github.com/mudita/MuditaOS/LICENSE.md

#include "vfs.hpp"

#include <memory>

#define eMMCHIDDEN_SECTOR_COUNT 8
#define eMMCPRIMARY_PARTITIONS  2
#define eMMCHUNDRED_64_BIT      100ULL
#define eMMCPARTITION_NUMBER    0
#define eMMCBYTES_PER_MB        (1024ull * 1024ull)
#define eMMCSECTORS_PER_MB      (eMMCBYTES_PER_MB / 512ull)

/* Used as a magic number to indicate that an FF_Disk_t structure is a RAM
disk. */
#define eMMCSIGNATURE             0x61606362
#define mainIO_MANAGER_CACHE_SIZE (15UL * FSL_SDMMC_DEFAULT_BLOCK_SIZE)

vfs::FILE *vfs::fopen(const char *filename, const char *mode)
{
    const auto handle = ff_fopen(relativeToRoot(filename).c_str(), mode);
    chnNotifier.onFileOpen(filename, mode, handle);
    return handle;
}

int vfs::fclose(FILE *stream)
{
    chnNotifier.onFileClose(stream);
    return ff_fclose(stream);
}

int vfs::remove(const char *name)
{
    const auto abs_name = relativeToRoot(name);
    const auto ret      = ff_remove(abs_name.c_str());
    if (!ret)
        chnNotifier.onFileRemove(abs_name);
    return ret;
}

size_t vfs::fread(void *ptr, size_t size, size_t count, FILE *stream)
{
    return ff_fread(ptr, size, count, stream);
}

size_t vfs::fwrite(const void *ptr, size_t size, size_t count, FILE *stream)
{
    return ff_fwrite(ptr, size, count, stream);
}

int vfs::fseek(FILE *stream, long int offset, int origin)
{
    return ff_fseek(stream, offset, origin);
}

long int vfs::ftell(FILE *stream)
{
    return ff_ftell(stream);
}

void vfs::rewind(FILE *stream)
{
    ff_rewind(stream);
}

size_t vfs::filelength(FILE *stream)
{
    return ff_filelength(stream);
}

char *vfs::fgets(char *buff, size_t count, FILE *stream)
{
    return ff_fgets(buff, count, stream);
}

std::string vfs::getcurrdir()
{
    char buff[64] = {};
    ff_getcwd(buff, sizeof buff);
    return std::string{buff};
}

static inline bool hasEnding(std::string const &fullString, std::string const &ending)
{
    if (fullString.length() >= ending.length()) {
        return (0 == fullString.compare(fullString.length() - ending.length(), ending.length(), ending));
    }
    else {
        return false;
    }
}

std::vector<vfs::DirectoryEntry> vfs::listdir(const char *path, const std::string &ext, const bool bypassRootCheck)
{
    std::vector<DirectoryEntry> dir_list;

    FileAttributes attribute;

    /* FF_FindData_t can be large, so it is best to allocate the structure
    dynamically, rather than declare it as a stack variable. */
    auto pxFindStruct = std::make_unique<FF_FindData_t>();

    /* FF_FindData_t must be cleared to 0. */
    memset(pxFindStruct.get(), 0x00, sizeof(FF_FindData_t));

    /* The first parameter to ff_findfist() is the directory being searched.  Do
    not add wildcards to the end of the directory name. */
    if (ff_findfirst(bypassRootCheck ? path : relativeToRoot(path).c_str(), pxFindStruct.get()) == 0 &&
        pxFindStruct != nullptr) {
        do {
            if ((pxFindStruct->ucAttributes & FF_FAT_ATTR_HIDDEN) ||
                (pxFindStruct->ucAttributes & FF_FAT_ATTR_SYSTEM) || (pxFindStruct->ucAttributes & FF_FAT_ATTR_VOLID) ||
                (pxFindStruct->ucAttributes & FF_FAT_ATTR_LFN)) {
                continue;
            }
            /* Point pcAttrib to a string that describes the file. */
            else if ((pxFindStruct->ucAttributes & FF_FAT_ATTR_DIR) != 0) {
                attribute = FileAttributes::Directory;
            }
            else if ((pxFindStruct->ucAttributes & FF_FAT_ATTR_ARCHIVE) || (pxFindStruct->ucAttributes == 0)) {
                attribute = FileAttributes::Writable;
            }
            else {
                attribute = FileAttributes::ReadOnly;
            }

            if (ext.empty()) {
                dir_list.push_back(DirectoryEntry{pxFindStruct->pcFileName, attribute, pxFindStruct->ulFileSize});
            }
            else {
                if (hasEnding(pxFindStruct->pcFileName, ext))
                    dir_list.push_back(DirectoryEntry{pxFindStruct->pcFileName, attribute, pxFindStruct->ulFileSize});
            }

        } while (ff_findnext(pxFindStruct.get()) == 0);
    }

    return dir_list;
}

bool vfs::eof(FILE *stream)
{
    return ff_feof(stream);
}

std::string vfs::getline(FILE *stream, uint32_t length)
{

    uint32_t currentPosition = ftell(stream);

    // allocate memory to read number of signs defined by length param. Size of buffer is increased by 1 to add string's
    // null terminator.
    std::unique_ptr<char[]> buffer(new char[length + 1]);
    memset(buffer.get(), 0, length + 1);

    uint32_t bytesRead = ff_fread(buffer.get(), 1, length, stream);

    // search buffer for /n sign
    for (uint32_t i = 0; i < bytesRead; ++i) {
        if (buffer[i] == 0x0A) {
            buffer[i] = 0;
            ff_fseek(stream, currentPosition + i + 1, SEEK_SET);
            break;
        }
    }

    std::string ret = std::string(buffer.get());

    return ret;
}

vfs::FilesystemStats vfs::getFilesystemStats()
{
    FF_Error_t xError;
    uint64_t ullFreeSectors;
    uint32_t ulTotalSizeMB, ulFreeSizeMB;
    int iPercentageFree;
    FF_IOManager_t *pxIOManager;
    vfs::FilesystemStats filesystemStats;

    if (emmcFFDisk != NULL) {
        pxIOManager = emmcFFDisk->pxIOManager;

        switch (pxIOManager->xPartition.ucType) {
        case FF_T_FAT12:
            filesystemStats.type = "FAT12";
            break;

        case FF_T_FAT16:
            filesystemStats.type = "FAT16";
            break;

        case FF_T_FAT32:
            filesystemStats.type = "FAT32";
            break;

        default:
            filesystemStats.type = "UNKOWN";
            break;
        }

        FF_GetFreeSize(pxIOManager, &xError);

        ullFreeSectors  = pxIOManager->xPartition.ulFreeClusterCount * pxIOManager->xPartition.ulSectorsPerCluster;
        iPercentageFree = (int)((eMMCHUNDRED_64_BIT * ullFreeSectors + pxIOManager->xPartition.ulDataSectors / 2) /
                                ((uint64_t)pxIOManager->xPartition.ulDataSectors));

        ulTotalSizeMB = pxIOManager->xPartition.ulDataSectors / eMMCSECTORS_PER_MB;
        ulFreeSizeMB  = (uint32_t)(ullFreeSectors / eMMCSECTORS_PER_MB);

        filesystemStats.freeMbytes  = ulFreeSizeMB;
        filesystemStats.totalMbytes = ulTotalSizeMB;
        filesystemStats.freePercent = iPercentageFree;
    }

    return filesystemStats;
}

std::string vfs::relativeToRoot(const std::string path)
{
    fs::path fsPath(path);

    if (fsPath.is_absolute()) {
        if (bootConfig.os_root_path.root_directory() == fsPath.root_directory())
            return fsPath;
        else
            return (purefs::dir::eMMC_disk / fsPath.relative_path()).c_str();
    }

    if (path.empty())
        return bootConfig.os_root_path;
    else
        return bootConfig.os_root_path / fsPath;
}

bool vfs::isDir(const char *path)
{
    if (path == nullptr)
        return false;

    FF_Stat_t fileStatus;

    const int ret = ff_stat(relativeToRoot(path).c_str(), &fileStatus);
    if (ret == 0) {
        return (fileStatus.st_mode == FF_IFDIR);
    }
    else {
        return false;
    }
}

bool vfs::fileExists(const char *path)
{
    if (path == nullptr)
        return false;

    FF_Stat_t fileStatus;
    const int ret = ff_stat(relativeToRoot(path).c_str(), &fileStatus);
    if (ret == 0) {
        return true;
    }
    return false;
}

int vfs::deltree(const char *path)
{
    if (path != nullptr)
        return ff_deltree(
            relativeToRoot(path).c_str(),
            [](void *ctx, const char *path) {
                auto _this = reinterpret_cast<vfs *>(ctx);
                _this->chnNotifier.onFileRemove(path);
            },
            this);
    else
        return -1;
}

int vfs::mkdir(const char *dir)
{
    if (dir != nullptr)
        return ff_mkdir(relativeToRoot(dir).c_str());
    else
        return -1;
}

int vfs::rename(const char *oldname, const char *newname)
{
    if (oldname != nullptr && newname != nullptr) {
        const auto ret = ff_rename(relativeToRoot(oldname).c_str(), relativeToRoot(newname).c_str(), true);
        if (!ret)
            chnNotifier.onFileRename(newname, oldname);
        return ret;
    }
    else
        return -1;
}

std::string vfs::lastErrnoToStr()
{
    return (strerror(stdioGET_ERRNO()));
}

size_t vfs::fprintf(FILE *stream, const char *format, ...)
{
    size_t count;
    size_t result;
    char *buffer = nullptr;
    va_list args;

    buffer = static_cast<char *>(ffconfigMALLOC(ffconfigFPRINTF_BUFFER_LENGTH));
    if (buffer == nullptr) {
        stdioSET_ERRNO(pdFREERTOS_ERRNO_ENOMEM);
        return -1;
    }

    va_start(args, format);
    count = vsnprintf(buffer, ffconfigFPRINTF_BUFFER_LENGTH, format, args);
    va_end(args);

    if (count > 0) {
        result = ff_fwrite(buffer, 1, count, stream);
        if (result < count) {
            count = -1;
        }
    }

    ffconfigFREE(buffer);
    return count;
}
auto vfs::getAbsolutePath(std::string_view path) const -> std::string
{
    namespace fs = std::filesystem;
    fs::path fs_path(path);
    if (fs_path.is_relative()) {
        char cwd_path[ffconfigMAX_FILENAME];
        ff_getcwd(cwd_path, sizeof cwd_path);
        fs::path fs_cwd(cwd_path);
        return fs_cwd / fs_path;
    }
    else {
        return std::string(path);
    }
}