~aleteoryx/muditaos

ref: 879213397dbbd3377c34c9be1d8c906e611a4979 muditaos/module-vfs/src/deprecated/vfs.cpp -rw-r--r-- 11.6 KiB
87921339 — Jakub Pyszczak [EGD-4757] Add unit test for new filesystem 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
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
// 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 <purefs/filesystem_paths.hpp>
#include <memory>
#include <cstring>

#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)

#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"

std::atomic<bool> vfs::initDone{false};

vfs::FILE *vfs::fopen(const char *filename, const char *mode)
{
    if (!initDone) {
        stdioSET_ERRNO(pdFREERTOS_ERRNO_EIO);
        return nullptr;
    }
    const auto filename_rel = relativeToRoot(filename);
    const auto handle       = ff_fopen(filename_rel.c_str(), mode);
    chnNotifier.onFileOpen(filename_rel, mode, handle);
    return handle;
}

int vfs::fclose(FILE *stream)
{
    if (!initDone) {
        stdioSET_ERRNO(pdFREERTOS_ERRNO_EIO);
        return -1;
    }
    const auto ret = ff_fclose(stream);
    chnNotifier.onFileClose(stream);
    return ret;
}

int vfs::remove(const char *name)
{
    if (!initDone) {
        stdioSET_ERRNO(pdFREERTOS_ERRNO_EIO);
        return -1;
    }
    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)
{
    if (!initDone) {
        stdioSET_ERRNO(pdFREERTOS_ERRNO_EIO);
        return ssize_t(-1);
    }
    return ff_fread(ptr, size, count, stream);
}

size_t vfs::fwrite(const void *ptr, size_t size, size_t count, FILE *stream)
{
    if (!initDone) {
        stdioSET_ERRNO(pdFREERTOS_ERRNO_EIO);
        return size_t(0);
    }
    return ff_fwrite(ptr, size, count, stream);
}

int vfs::fseek(FILE *stream, long int offset, int origin)
{
    if (!initDone) {
        stdioSET_ERRNO(pdFREERTOS_ERRNO_EIO);
        return -1;
    }
    return ff_fseek(stream, offset, origin);
}

long int vfs::ftell(FILE *stream)
{
    if (!initDone) {
        stdioSET_ERRNO(pdFREERTOS_ERRNO_EIO);
        return -1;
    }
    return ff_ftell(stream);
}

void vfs::rewind(FILE *stream)
{
    if (!initDone) {
        stdioSET_ERRNO(pdFREERTOS_ERRNO_EIO);
    }
    ff_rewind(stream);
}

size_t vfs::filelength(FILE *stream)
{
    if (!initDone) {
        stdioSET_ERRNO(pdFREERTOS_ERRNO_EIO);
        return 0;
    }
    return ff_filelength(stream);
}

char *vfs::fgets(char *buff, size_t count, FILE *stream)
{
    if (!initDone) {
        stdioSET_ERRNO(pdFREERTOS_ERRNO_EIO);
        return nullptr;
    }
    return ff_fgets(buff, count, stream);
}

std::string vfs::getcurrdir()
{
    if (!initDone) {
        stdioSET_ERRNO(pdFREERTOS_ERRNO_EIO);
        return {};
    }
    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)
{
    if (!initDone) {
        stdioSET_ERRNO(pdFREERTOS_ERRNO_EIO);
        return {};
    }
    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)
{
    if (!initDone) {
        stdioSET_ERRNO(pdFREERTOS_ERRNO_EIO);
        return true;
    }
    return ff_feof(stream);
}

std::string vfs::getline(FILE *stream, uint32_t length)
{
    if (!initDone) {
        stdioSET_ERRNO(pdFREERTOS_ERRNO_EIO);
        return {};
    }
    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()
{

    if (!initDone) {
        stdioSET_ERRNO(pdFREERTOS_ERRNO_EIO);
        return {};
    }
    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::createPath(purefs::dir::getRootDiskPath(), 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 (!initDone) {
        stdioSET_ERRNO(pdFREERTOS_ERRNO_EIO);
        return false;
    }
    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 (!initDone) {
        stdioSET_ERRNO(pdFREERTOS_ERRNO_EIO);
        return false;
    }
    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 (!initDone) {
        stdioSET_ERRNO(pdFREERTOS_ERRNO_EIO);
        return -1;
    }
    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 (!initDone) {
        stdioSET_ERRNO(pdFREERTOS_ERRNO_EIO);
        return -1;
    }
    if (dir != nullptr)
        return ff_mkdir(relativeToRoot(dir).c_str());
    else
        return -1;
}

int vfs::rename(const char *oldname, const char *newname)
{

    if (!initDone) {
        stdioSET_ERRNO(pdFREERTOS_ERRNO_EIO);
        return -1;
    }
    if (oldname != nullptr && newname != nullptr) {
        const auto old_rel = relativeToRoot(oldname);
        const auto new_rel = relativeToRoot(newname);
        const auto ret     = ff_rename(old_rel.c_str(), new_rel.c_str(), true);
        if (!ret)
            chnNotifier.onFileRename(new_rel, old_rel);
        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;

    if (!initDone) {
        stdioSET_ERRNO(pdFREERTOS_ERRNO_EIO);
        return 0;
    }
    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;
    if (!initDone) {
        stdioSET_ERRNO(pdFREERTOS_ERRNO_EIO);
        return {};
    }
    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);
    }
}

#pragma GCC diagnostic pop