repo_name string | dataset string | owner string | lang string | func_name string | code string | docstring string | url string | sha string |
|---|---|---|---|---|---|---|---|---|
teddycloud | github_2023 | toniebox-reverse-engineering | c | test_gpt_header | static int test_gpt_header ( /* 0:Invalid, 1:Valid */
const BYTE* gpth /* Pointer to the GPT header */
)
{
UINT i;
DWORD bcc, hlen;
if (memcmp(gpth + GPTH_Sign, "EFI PART" "\0\0\1", 12)) return 0; /* Check signature and version (1.0) */
hlen = ld_dword(gpth + GPTH_Size); /* Check header size */
if (hlen < 92 || hlen > FF_MIN_SS) return 0;
for (i = 0, bcc = 0xFFFFFFFF; i < hlen; i++) { /* Check header BCC */
bcc = crc32(bcc, i - GPTH_Bcc < 4 ? 0 : gpth[i]);
}
if (~bcc != ld_dword(gpth + GPTH_Bcc)) return 0;
if (ld_dword(gpth + GPTH_PteSize) != SZ_GPTE) return 0; /* Table entry size (must be SZ_GPTE bytes) */
if (ld_dword(gpth + GPTH_PtNum) > 128) return 0; /* Table size (must be 128 entries or less) */
return 1;
} | /* Check validity of GPT header */ | https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/fat/source/ff.c#L3239-L3258 | 83d3b29cbfc74e8f76f48f8782646c8e464055b2 |
teddycloud | github_2023 | toniebox-reverse-engineering | c | make_rand | static DWORD make_rand (
DWORD seed, /* Seed value */
BYTE *buff, /* Output buffer */
UINT n /* Data length */
)
{
UINT r;
if (seed == 0) seed = 1;
do {
for (r = 0; r < 8; r++) seed = seed & 1 ? seed >> 1 ^ 0xA3000000 : seed >> 1; /* Shift 8 bits the 32-bit LFSR */
*buff++ = (BYTE)seed;
} while (--n);
return seed;
} | /* Generate random value */ | https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/fat/source/ff.c#L3263-L3278 | 83d3b29cbfc74e8f76f48f8782646c8e464055b2 |
teddycloud | github_2023 | toniebox-reverse-engineering | c | check_fs | static UINT check_fs ( /* 0:FAT/FAT32 VBR, 1:exFAT VBR, 2:Not FAT and valid BS, 3:Not FAT and invalid BS, 4:Disk error */
FATFS* fs, /* Filesystem object */
LBA_t sect /* Sector to load and check if it is an FAT-VBR or not */
)
{
WORD w, sign;
BYTE b;
fs->wflag = 0; fs->winsect = (LBA_t)0 - 1; /* Invaidate window */
if (move_window(fs, sect) != FR_OK) return 4; /* Load the boot sector */
sign = ld_word(fs->win + BS_55AA);
#if FF_FS_EXFAT
if (sign == 0xAA55 && !memcmp(fs->win + BS_JmpBoot, "\xEB\x76\x90" "EXFAT ", 11)) return 1; /* It is an exFAT VBR */
#endif
b = fs->win[BS_JmpBoot];
if (b == 0xEB || b == 0xE9 || b == 0xE8) { /* Valid JumpBoot code? (short jump, near jump or near call) */
if (sign == 0xAA55 && !memcmp(fs->win + BS_FilSysType32, "FAT32 ", 8)) {
return 0; /* It is an FAT32 VBR */
}
/* FAT volumes formatted with early MS-DOS lack BS_55AA and BS_FilSysType, so FAT VBR needs to be identified without them. */
w = ld_word(fs->win + BPB_BytsPerSec);
b = fs->win[BPB_SecPerClus];
if ((w & (w - 1)) == 0 && w >= FF_MIN_SS && w <= FF_MAX_SS /* Properness of sector size (512-4096 and 2^n) */
&& b != 0 && (b & (b - 1)) == 0 /* Properness of cluster size (2^n) */
&& ld_word(fs->win + BPB_RsvdSecCnt) != 0 /* Properness of reserved sectors (MNBZ) */
&& (UINT)fs->win[BPB_NumFATs] - 1 <= 1 /* Properness of FATs (1 or 2) */
&& ld_word(fs->win + BPB_RootEntCnt) != 0 /* Properness of root dir entries (MNBZ) */
&& (ld_word(fs->win + BPB_TotSec16) >= 128 || ld_dword(fs->win + BPB_TotSec32) >= 0x10000) /* Properness of volume sectors (>=128) */
&& ld_word(fs->win + BPB_FATSz16) != 0) { /* Properness of FAT size (MNBZ) */
return 0; /* It can be presumed an FAT VBR */
}
}
return sign == 0xAA55 ? 2 : 3; /* Not an FAT VBR (valid or invalid BS) */
} | /*-----------------------------------------------------------------------*/
/* Load a sector and check if it is an FAT VBR */
/*-----------------------------------------------------------------------*/
/* Check what the sector is */ | https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/fat/source/ff.c#L3291-L3325 | 83d3b29cbfc74e8f76f48f8782646c8e464055b2 |
teddycloud | github_2023 | toniebox-reverse-engineering | c | find_volume | static UINT find_volume ( /* Returns BS status found in the hosting drive */
FATFS* fs, /* Filesystem object */
UINT part /* Partition to fined = 0:find as SFD and partitions, >0:forced partition number */
)
{
UINT fmt, i;
DWORD mbr_pt[4];
fmt = check_fs(fs, 0); /* Load sector 0 and check if it is an FAT VBR as SFD format */
if (fmt != 2 && (fmt >= 3 || part == 0)) return fmt; /* Returns if it is an FAT VBR as auto scan, not a BS or disk error */
/* Sector 0 is not an FAT VBR or forced partition number wants a partition */
#if FF_LBA64
if (fs->win[MBR_Table + PTE_System] == 0xEE) { /* GPT protective MBR? */
DWORD n_ent, v_ent, ofs;
QWORD pt_lba;
if (move_window(fs, 1) != FR_OK) return 4; /* Load GPT header sector (next to MBR) */
if (!test_gpt_header(fs->win)) return 3; /* Check if GPT header is valid */
n_ent = ld_dword(fs->win + GPTH_PtNum); /* Number of entries */
pt_lba = ld_qword(fs->win + GPTH_PtOfs); /* Table location */
for (v_ent = i = 0; i < n_ent; i++) { /* Find FAT partition */
if (move_window(fs, pt_lba + i * SZ_GPTE / SS(fs)) != FR_OK) return 4; /* PT sector */
ofs = i * SZ_GPTE % SS(fs); /* Offset in the sector */
if (!memcmp(fs->win + ofs + GPTE_PtGuid, GUID_MS_Basic, 16)) { /* MS basic data partition? */
v_ent++;
fmt = check_fs(fs, ld_qword(fs->win + ofs + GPTE_FstLba)); /* Load VBR and check status */
if (part == 0 && fmt <= 1) return fmt; /* Auto search (valid FAT volume found first) */
if (part != 0 && v_ent == part) return fmt; /* Forced partition order (regardless of it is valid or not) */
}
}
return 3; /* Not found */
}
#endif
if (FF_MULTI_PARTITION && part > 4) return 3; /* MBR has 4 partitions max */
for (i = 0; i < 4; i++) { /* Load partition offset in the MBR */
mbr_pt[i] = ld_dword(fs->win + MBR_Table + i * SZ_PTE + PTE_StLba);
}
i = part ? part - 1 : 0; /* Table index to find first */
do { /* Find an FAT volume */
fmt = mbr_pt[i] ? check_fs(fs, mbr_pt[i]) : 3; /* Check if the partition is FAT */
} while (part == 0 && fmt >= 2 && ++i < 4);
return fmt;
} | /* Find an FAT volume */
/* (It supports only generic partitioning rules, MBR, GPT and SFD) */ | https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/fat/source/ff.c#L3331-L3376 | 83d3b29cbfc74e8f76f48f8782646c8e464055b2 |
teddycloud | github_2023 | toniebox-reverse-engineering | c | mount_volume | static FRESULT mount_volume ( /* FR_OK(0): successful, !=0: an error occurred */
const TCHAR** path, /* Pointer to pointer to the path name (drive number) */
FATFS** rfs, /* Pointer to pointer to the found filesystem object */
BYTE mode /* Desiered access mode to check write protection */
)
{
int vol;
FATFS *fs;
DSTATUS stat;
LBA_t bsect;
DWORD tsect, sysect, fasize, nclst, szbfat;
WORD nrsv;
UINT fmt;
/* Get logical drive number */
*rfs = 0;
vol = get_ldnumber(path);
if (vol < 0) return FR_INVALID_DRIVE;
/* Check if the filesystem object is valid or not */
fs = FatFs[vol]; /* Get pointer to the filesystem object */
if (!fs) return FR_NOT_ENABLED; /* Is the filesystem object available? */
#if FF_FS_REENTRANT
if (!lock_volume(fs, 1)) return FR_TIMEOUT; /* Lock the volume, and system if needed */
#endif
*rfs = fs; /* Return pointer to the filesystem object */
mode &= (BYTE)~FA_READ; /* Desired access mode, write access or not */
if (fs->fs_type != 0) { /* If the volume has been mounted */
stat = disk_status(fs->pdrv);
if (!(stat & STA_NOINIT)) { /* and the physical drive is kept initialized */
if (!FF_FS_READONLY && mode && (stat & STA_PROTECT)) { /* Check write protection if needed */
return FR_WRITE_PROTECTED;
}
return FR_OK; /* The filesystem object is already valid */
}
}
/* The filesystem object is not valid. */
/* Following code attempts to mount the volume. (find an FAT volume, analyze the BPB and initialize the filesystem object) */
fs->fs_type = 0; /* Invalidate the filesystem object */
stat = disk_initialize(fs->pdrv); /* Initialize the volume hosting physical drive */
if (stat & STA_NOINIT) { /* Check if the initialization succeeded */
return FR_NOT_READY; /* Failed to initialize due to no medium or hard error */
}
if (!FF_FS_READONLY && mode && (stat & STA_PROTECT)) { /* Check disk write protection if needed */
return FR_WRITE_PROTECTED;
}
#if FF_MAX_SS != FF_MIN_SS /* Get sector size (multiple sector size cfg only) */
if (disk_ioctl(fs->pdrv, GET_SECTOR_SIZE, &SS(fs)) != RES_OK) return FR_DISK_ERR;
if (SS(fs) > FF_MAX_SS || SS(fs) < FF_MIN_SS || (SS(fs) & (SS(fs) - 1))) return FR_DISK_ERR;
#endif
/* Find an FAT volume on the hosting drive */
fmt = find_volume(fs, LD2PT(vol));
if (fmt == 4) return FR_DISK_ERR; /* An error occurred in the disk I/O layer */
if (fmt >= 2) return FR_NO_FILESYSTEM; /* No FAT volume is found */
bsect = fs->winsect; /* Volume offset in the hosting physical drive */
/* An FAT volume is found (bsect). Following code initializes the filesystem object */
#if FF_FS_EXFAT
if (fmt == 1) {
QWORD maxlba;
DWORD so, cv, bcl, i;
for (i = BPB_ZeroedEx; i < BPB_ZeroedEx + 53 && fs->win[i] == 0; i++) ; /* Check zero filler */
if (i < BPB_ZeroedEx + 53) return FR_NO_FILESYSTEM;
if (ld_word(fs->win + BPB_FSVerEx) != 0x100) return FR_NO_FILESYSTEM; /* Check exFAT version (must be version 1.0) */
if (1 << fs->win[BPB_BytsPerSecEx] != SS(fs)) { /* (BPB_BytsPerSecEx must be equal to the physical sector size) */
return FR_NO_FILESYSTEM;
}
maxlba = ld_qword(fs->win + BPB_TotSecEx) + bsect; /* Last LBA of the volume + 1 */
if (!FF_LBA64 && maxlba >= 0x100000000) return FR_NO_FILESYSTEM; /* (It cannot be accessed in 32-bit LBA) */
fs->fsize = ld_dword(fs->win + BPB_FatSzEx); /* Number of sectors per FAT */
fs->n_fats = fs->win[BPB_NumFATsEx]; /* Number of FATs */
if (fs->n_fats != 1) return FR_NO_FILESYSTEM; /* (Supports only 1 FAT) */
fs->csize = 1 << fs->win[BPB_SecPerClusEx]; /* Cluster size */
if (fs->csize == 0) return FR_NO_FILESYSTEM; /* (Must be 1..32768 sectors) */
nclst = ld_dword(fs->win + BPB_NumClusEx); /* Number of clusters */
if (nclst > MAX_EXFAT) return FR_NO_FILESYSTEM; /* (Too many clusters) */
fs->n_fatent = nclst + 2;
/* Boundaries and Limits */
fs->volbase = bsect;
fs->database = bsect + ld_dword(fs->win + BPB_DataOfsEx);
fs->fatbase = bsect + ld_dword(fs->win + BPB_FatOfsEx);
if (maxlba < (QWORD)fs->database + nclst * fs->csize) return FR_NO_FILESYSTEM; /* (Volume size must not be smaller than the size required) */
fs->dirbase = ld_dword(fs->win + BPB_RootClusEx);
/* Get bitmap location and check if it is contiguous (implementation assumption) */
so = i = 0;
for (;;) { /* Find the bitmap entry in the root directory (in only first cluster) */
if (i == 0) {
if (so >= fs->csize) return FR_NO_FILESYSTEM; /* Not found? */
if (move_window(fs, clst2sect(fs, (DWORD)fs->dirbase) + so) != FR_OK) return FR_DISK_ERR;
so++;
}
if (fs->win[i] == ET_BITMAP) break; /* Is it a bitmap entry? */
i = (i + SZDIRE) % SS(fs); /* Next entry */
}
bcl = ld_dword(fs->win + i + 20); /* Bitmap cluster */
if (bcl < 2 || bcl >= fs->n_fatent) return FR_NO_FILESYSTEM; /* (Wrong cluster#) */
fs->bitbase = fs->database + fs->csize * (bcl - 2); /* Bitmap sector */
for (;;) { /* Check if bitmap is contiguous */
if (move_window(fs, fs->fatbase + bcl / (SS(fs) / 4)) != FR_OK) return FR_DISK_ERR;
cv = ld_dword(fs->win + bcl % (SS(fs) / 4) * 4);
if (cv == 0xFFFFFFFF) break; /* Last link? */
if (cv != ++bcl) return FR_NO_FILESYSTEM; /* Fragmented bitmap? */
}
#if !FF_FS_READONLY
fs->last_clst = fs->free_clst = 0xFFFFFFFF; /* Initialize cluster allocation information */
#endif
fmt = FS_EXFAT; /* FAT sub-type */
} else
#endif /* FF_FS_EXFAT */
{
if (ld_word(fs->win + BPB_BytsPerSec) != SS(fs)) return FR_NO_FILESYSTEM; /* (BPB_BytsPerSec must be equal to the physical sector size) */
fasize = ld_word(fs->win + BPB_FATSz16); /* Number of sectors per FAT */
if (fasize == 0) fasize = ld_dword(fs->win + BPB_FATSz32);
fs->fsize = fasize;
fs->n_fats = fs->win[BPB_NumFATs]; /* Number of FATs */
if (fs->n_fats != 1 && fs->n_fats != 2) return FR_NO_FILESYSTEM; /* (Must be 1 or 2) */
fasize *= fs->n_fats; /* Number of sectors for FAT area */
fs->csize = fs->win[BPB_SecPerClus]; /* Cluster size */
if (fs->csize == 0 || (fs->csize & (fs->csize - 1))) return FR_NO_FILESYSTEM; /* (Must be power of 2) */
fs->n_rootdir = ld_word(fs->win + BPB_RootEntCnt); /* Number of root directory entries */
if (fs->n_rootdir % (SS(fs) / SZDIRE)) return FR_NO_FILESYSTEM; /* (Must be sector aligned) */
tsect = ld_word(fs->win + BPB_TotSec16); /* Number of sectors on the volume */
if (tsect == 0) tsect = ld_dword(fs->win + BPB_TotSec32);
nrsv = ld_word(fs->win + BPB_RsvdSecCnt); /* Number of reserved sectors */
if (nrsv == 0) return FR_NO_FILESYSTEM; /* (Must not be 0) */
/* Determine the FAT sub type */
sysect = nrsv + fasize + fs->n_rootdir / (SS(fs) / SZDIRE); /* RSV + FAT + DIR */
if (tsect < sysect) return FR_NO_FILESYSTEM; /* (Invalid volume size) */
nclst = (tsect - sysect) / fs->csize; /* Number of clusters */
if (nclst == 0) return FR_NO_FILESYSTEM; /* (Invalid volume size) */
fmt = 0;
if (nclst <= MAX_FAT32) fmt = FS_FAT32;
if (nclst <= MAX_FAT16) fmt = FS_FAT16;
if (nclst <= MAX_FAT12) fmt = FS_FAT12;
if (fmt == 0) return FR_NO_FILESYSTEM;
/* Boundaries and Limits */
fs->n_fatent = nclst + 2; /* Number of FAT entries */
fs->volbase = bsect; /* Volume start sector */
fs->fatbase = bsect + nrsv; /* FAT start sector */
fs->database = bsect + sysect; /* Data start sector */
if (fmt == FS_FAT32) {
if (ld_word(fs->win + BPB_FSVer32) != 0) return FR_NO_FILESYSTEM; /* (Must be FAT32 revision 0.0) */
if (fs->n_rootdir != 0) return FR_NO_FILESYSTEM; /* (BPB_RootEntCnt must be 0) */
fs->dirbase = ld_dword(fs->win + BPB_RootClus32); /* Root directory start cluster */
szbfat = fs->n_fatent * 4; /* (Needed FAT size) */
} else {
if (fs->n_rootdir == 0) return FR_NO_FILESYSTEM; /* (BPB_RootEntCnt must not be 0) */
fs->dirbase = fs->fatbase + fasize; /* Root directory start sector */
szbfat = (fmt == FS_FAT16) ? /* (Needed FAT size) */
fs->n_fatent * 2 : fs->n_fatent * 3 / 2 + (fs->n_fatent & 1);
}
if (fs->fsize < (szbfat + (SS(fs) - 1)) / SS(fs)) return FR_NO_FILESYSTEM; /* (BPB_FATSz must not be less than the size needed) */
#if !FF_FS_READONLY
/* Get FSInfo if available */
fs->last_clst = fs->free_clst = 0xFFFFFFFF; /* Initialize cluster allocation information */
fs->fsi_flag = 0x80;
#if (FF_FS_NOFSINFO & 3) != 3
if (fmt == FS_FAT32 /* Allow to update FSInfo only if BPB_FSInfo32 == 1 */
&& ld_word(fs->win + BPB_FSInfo32) == 1
&& move_window(fs, bsect + 1) == FR_OK)
{
fs->fsi_flag = 0;
if (ld_word(fs->win + BS_55AA) == 0xAA55 /* Load FSInfo data if available */
&& ld_dword(fs->win + FSI_LeadSig) == 0x41615252
&& ld_dword(fs->win + FSI_StrucSig) == 0x61417272)
{
#if (FF_FS_NOFSINFO & 1) == 0
fs->free_clst = ld_dword(fs->win + FSI_Free_Count);
#endif
#if (FF_FS_NOFSINFO & 2) == 0
fs->last_clst = ld_dword(fs->win + FSI_Nxt_Free);
#endif
}
}
#endif /* (FF_FS_NOFSINFO & 3) != 3 */
#endif /* !FF_FS_READONLY */
}
fs->fs_type = (BYTE)fmt;/* FAT sub-type (the filesystem object gets valid) */
fs->id = ++Fsid; /* Volume mount ID */
#if FF_USE_LFN == 1
fs->lfnbuf = LfnBuf; /* Static LFN working buffer */
#if FF_FS_EXFAT
fs->dirbuf = DirBuf; /* Static directory block scratchpad buuffer */
#endif
#endif
#if FF_FS_RPATH != 0
fs->cdir = 0; /* Initialize current directory */
#endif
#if FF_FS_LOCK /* Clear file lock semaphores */
clear_share(fs);
#endif
return FR_OK;
} | /*-----------------------------------------------------------------------*/
/* Determine logical drive number and mount the volume if needed */
/*-----------------------------------------------------------------------*/ | https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/fat/source/ff.c#L3385-L3604 | 83d3b29cbfc74e8f76f48f8782646c8e464055b2 |
teddycloud | github_2023 | toniebox-reverse-engineering | c | validate | static FRESULT validate ( /* Returns FR_OK or FR_INVALID_OBJECT */
FFOBJID* obj, /* Pointer to the FFOBJID, the 1st member in the FIL/DIR structure, to check validity */
FATFS** rfs /* Pointer to pointer to the owner filesystem object to return */
)
{
FRESULT res = FR_INVALID_OBJECT;
if (obj && obj->fs && obj->fs->fs_type && obj->id == obj->fs->id) { /* Test if the object is valid */
#if FF_FS_REENTRANT
if (lock_volume(obj->fs, 0)) { /* Take a grant to access the volume */
if (!(disk_status(obj->fs->pdrv) & STA_NOINIT)) { /* Test if the hosting phsical drive is kept initialized */
res = FR_OK;
} else {
unlock_volume(obj->fs, FR_OK); /* Invalidated volume, abort to access */
}
} else { /* Could not take */
res = FR_TIMEOUT;
}
#else
if (!(disk_status(obj->fs->pdrv) & STA_NOINIT)) { /* Test if the hosting phsical drive is kept initialized */
res = FR_OK;
}
#endif
}
*rfs = (res == FR_OK) ? obj->fs : 0; /* Return corresponding filesystem object if it is valid */
return res;
} | /*-----------------------------------------------------------------------*/
/* Check if the file/directory object is valid or not */
/*-----------------------------------------------------------------------*/ | https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/fat/source/ff.c#L3613-L3640 | 83d3b29cbfc74e8f76f48f8782646c8e464055b2 |
teddycloud | github_2023 | toniebox-reverse-engineering | c | f_mount | FRESULT f_mount (
FATFS* fs, /* Pointer to the filesystem object to be registered (NULL:unmount)*/
const TCHAR* path, /* Logical drive number to be mounted/unmounted */
BYTE opt /* Mount option: 0=Do not mount (delayed mount), 1=Mount immediately */
)
{
FATFS *cfs;
int vol;
FRESULT res;
const TCHAR *rp = path;
/* Get volume ID (logical drive number) */
vol = get_ldnumber(&rp);
if (vol < 0) return FR_INVALID_DRIVE;
cfs = FatFs[vol]; /* Pointer to the filesystem object of the volume */
if (cfs) { /* Unregister current filesystem object if regsitered */
FatFs[vol] = 0;
#if FF_FS_LOCK
clear_share(cfs);
#endif
#if FF_FS_REENTRANT /* Discard mutex of the current volume */
ff_mutex_delete(vol);
#endif
cfs->fs_type = 0; /* Invalidate the filesystem object to be unregistered */
}
if (fs) { /* Register new filesystem object */
fs->pdrv = LD2PD(vol); /* Volume hosting physical drive */
#if FF_FS_REENTRANT /* Create a volume mutex */
fs->ldrv = (BYTE)vol; /* Owner volume ID */
if (!ff_mutex_create(vol)) return FR_INT_ERR;
#if FF_FS_LOCK
if (SysLock == 0) { /* Create a system mutex if needed */
if (!ff_mutex_create(FF_VOLUMES)) {
ff_mutex_delete(vol);
return FR_INT_ERR;
}
SysLock = 1; /* System mutex is ready */
}
#endif
#endif
fs->fs_type = 0; /* Invalidate the new filesystem object */
FatFs[vol] = fs; /* Register new fs object */
}
if (opt == 0) return FR_OK; /* Do not mount now, it will be mounted in subsequent file functions */
res = mount_volume(&path, &fs, 0); /* Force mounted the volume */
LEAVE_FF(fs, res);
} | /*---------------------------------------------------------------------------
Public Functions (FatFs API)
----------------------------------------------------------------------------*/
/*-----------------------------------------------------------------------*/
/* Mount/Unmount a Logical Drive */
/*-----------------------------------------------------------------------*/ | https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/fat/source/ff.c#L3657-L3708 | 83d3b29cbfc74e8f76f48f8782646c8e464055b2 |
teddycloud | github_2023 | toniebox-reverse-engineering | c | f_open | FRESULT f_open (
FIL* fp, /* Pointer to the blank file object */
const TCHAR* path, /* Pointer to the file name */
BYTE mode /* Access mode and open mode flags */
)
{
FRESULT res;
DIR dj;
FATFS *fs;
#if !FF_FS_READONLY
DWORD cl, bcs, clst, tm;
LBA_t sc;
FSIZE_t ofs;
#endif
DEF_NAMBUF
if (!fp) return FR_INVALID_OBJECT;
/* Get logical drive number */
mode &= FF_FS_READONLY ? FA_READ : FA_READ | FA_WRITE | FA_CREATE_ALWAYS | FA_CREATE_NEW | FA_OPEN_ALWAYS | FA_OPEN_APPEND;
res = mount_volume(&path, &fs, mode);
if (res == FR_OK) {
dj.obj.fs = fs;
INIT_NAMBUF(fs);
res = follow_path(&dj, path); /* Follow the file path */
#if !FF_FS_READONLY /* Read/Write configuration */
if (res == FR_OK) {
if (dj.fn[NSFLAG] & NS_NONAME) { /* Origin directory itself? */
res = FR_INVALID_NAME;
}
#if FF_FS_LOCK
else {
res = chk_share(&dj, (mode & ~FA_READ) ? 1 : 0); /* Check if the file can be used */
}
#endif
}
/* Create or Open a file */
if (mode & (FA_CREATE_ALWAYS | FA_OPEN_ALWAYS | FA_CREATE_NEW)) {
if (res != FR_OK) { /* No file, create new */
if (res == FR_NO_FILE) { /* There is no file to open, create a new entry */
#if FF_FS_LOCK
res = enq_share() ? dir_register(&dj) : FR_TOO_MANY_OPEN_FILES;
#else
res = dir_register(&dj);
#endif
}
mode |= FA_CREATE_ALWAYS; /* File is created */
}
else { /* Any object with the same name is already existing */
if (dj.obj.attr & (AM_RDO | AM_DIR)) { /* Cannot overwrite it (R/O or DIR) */
res = FR_DENIED;
} else {
if (mode & FA_CREATE_NEW) res = FR_EXIST; /* Cannot create as new file */
}
}
if (res == FR_OK && (mode & FA_CREATE_ALWAYS)) { /* Truncate the file if overwrite mode */
#if FF_FS_EXFAT
if (fs->fs_type == FS_EXFAT) {
/* Get current allocation info */
fp->obj.fs = fs;
init_alloc_info(fs, &fp->obj);
/* Set directory entry block initial state */
memset(fs->dirbuf + 2, 0, 30); /* Clear 85 entry except for NumSec */
memset(fs->dirbuf + 38, 0, 26); /* Clear C0 entry except for NumName and NameHash */
fs->dirbuf[XDIR_Attr] = AM_ARC;
st_dword(fs->dirbuf + XDIR_CrtTime, GET_FATTIME());
fs->dirbuf[XDIR_GenFlags] = 1;
res = store_xdir(&dj);
if (res == FR_OK && fp->obj.sclust != 0) { /* Remove the cluster chain if exist */
res = remove_chain(&fp->obj, fp->obj.sclust, 0);
fs->last_clst = fp->obj.sclust - 1; /* Reuse the cluster hole */
}
} else
#endif
{
/* Set directory entry initial state */
tm = GET_FATTIME(); /* Set created time */
st_dword(dj.dir + DIR_CrtTime, tm);
st_dword(dj.dir + DIR_ModTime, tm);
cl = ld_clust(fs, dj.dir); /* Get current cluster chain */
dj.dir[DIR_Attr] = AM_ARC; /* Reset attribute */
st_clust(fs, dj.dir, 0); /* Reset file allocation info */
st_dword(dj.dir + DIR_FileSize, 0);
fs->wflag = 1;
if (cl != 0) { /* Remove the cluster chain if exist */
sc = fs->winsect;
res = remove_chain(&dj.obj, cl, 0);
if (res == FR_OK) {
res = move_window(fs, sc);
fs->last_clst = cl - 1; /* Reuse the cluster hole */
}
}
}
}
}
else { /* Open an existing file */
if (res == FR_OK) { /* Is the object exsiting? */
if (dj.obj.attr & AM_DIR) { /* File open against a directory */
res = FR_NO_FILE;
} else {
if ((mode & FA_WRITE) && (dj.obj.attr & AM_RDO)) { /* Write mode open against R/O file */
res = FR_DENIED;
}
}
}
}
if (res == FR_OK) {
if (mode & FA_CREATE_ALWAYS) mode |= FA_MODIFIED; /* Set file change flag if created or overwritten */
fp->dir_sect = fs->winsect; /* Pointer to the directory entry */
fp->dir_ptr = dj.dir;
#if FF_FS_LOCK
fp->obj.lockid = inc_share(&dj, (mode & ~FA_READ) ? 1 : 0); /* Lock the file for this session */
if (fp->obj.lockid == 0) res = FR_INT_ERR;
#endif
}
#else /* R/O configuration */
if (res == FR_OK) {
if (dj.fn[NSFLAG] & NS_NONAME) { /* Is it origin directory itself? */
res = FR_INVALID_NAME;
} else {
if (dj.obj.attr & AM_DIR) { /* Is it a directory? */
res = FR_NO_FILE;
}
}
}
#endif
if (res == FR_OK) {
#if FF_FS_EXFAT
if (fs->fs_type == FS_EXFAT) {
fp->obj.c_scl = dj.obj.sclust; /* Get containing directory info */
fp->obj.c_size = ((DWORD)dj.obj.objsize & 0xFFFFFF00) | dj.obj.stat;
fp->obj.c_ofs = dj.blk_ofs;
init_alloc_info(fs, &fp->obj);
} else
#endif
{
fp->obj.sclust = ld_clust(fs, dj.dir); /* Get object allocation info */
fp->obj.objsize = ld_dword(dj.dir + DIR_FileSize);
}
#if FF_USE_FASTSEEK
fp->cltbl = 0; /* Disable fast seek mode */
#endif
fp->obj.fs = fs; /* Validate the file object */
fp->obj.id = fs->id;
fp->flag = mode; /* Set file access mode */
fp->err = 0; /* Clear error flag */
fp->sect = 0; /* Invalidate current data sector */
fp->fptr = 0; /* Set file pointer top of the file */
#if !FF_FS_READONLY
#if !FF_FS_TINY
memset(fp->buf, 0, sizeof fp->buf); /* Clear sector buffer */
#endif
if ((mode & FA_SEEKEND) && fp->obj.objsize > 0) { /* Seek to end of file if FA_OPEN_APPEND is specified */
fp->fptr = fp->obj.objsize; /* Offset to seek */
bcs = (DWORD)fs->csize * SS(fs); /* Cluster size in byte */
clst = fp->obj.sclust; /* Follow the cluster chain */
for (ofs = fp->obj.objsize; res == FR_OK && ofs > bcs; ofs -= bcs) {
clst = get_fat(&fp->obj, clst);
if (clst <= 1) res = FR_INT_ERR;
if (clst == 0xFFFFFFFF) res = FR_DISK_ERR;
}
fp->clust = clst;
if (res == FR_OK && ofs % SS(fs)) { /* Fill sector buffer if not on the sector boundary */
sc = clst2sect(fs, clst);
if (sc == 0) {
res = FR_INT_ERR;
} else {
fp->sect = sc + (DWORD)(ofs / SS(fs));
#if !FF_FS_TINY
if (disk_read(fs->pdrv, fp->buf, fp->sect, 1) != RES_OK) res = FR_DISK_ERR;
#endif
}
}
#if FF_FS_LOCK
if (res != FR_OK) dec_share(fp->obj.lockid); /* Decrement file open counter if seek failed */
#endif
}
#endif
}
FREE_NAMBUF();
}
if (res != FR_OK) fp->obj.fs = 0; /* Invalidate file object on error */
LEAVE_FF(fs, res);
} | /*-----------------------------------------------------------------------*/
/* Open or Create a File */
/*-----------------------------------------------------------------------*/ | https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/fat/source/ff.c#L3717-L3905 | 83d3b29cbfc74e8f76f48f8782646c8e464055b2 |
teddycloud | github_2023 | toniebox-reverse-engineering | c | f_read | FRESULT f_read (
FIL* fp, /* Open file to be read */
void* buff, /* Data buffer to store the read data */
UINT btr, /* Number of bytes to read */
UINT* br /* Number of bytes read */
)
{
FRESULT res;
FATFS *fs;
DWORD clst;
LBA_t sect;
FSIZE_t remain;
UINT rcnt, cc, csect;
BYTE *rbuff = (BYTE*)buff;
*br = 0; /* Clear read byte counter */
res = validate(&fp->obj, &fs); /* Check validity of the file object */
if (res != FR_OK || (res = (FRESULT)fp->err) != FR_OK) LEAVE_FF(fs, res); /* Check validity */
if (!(fp->flag & FA_READ)) LEAVE_FF(fs, FR_DENIED); /* Check access mode */
remain = fp->obj.objsize - fp->fptr;
if (btr > remain) btr = (UINT)remain; /* Truncate btr by remaining bytes */
for ( ; btr > 0; btr -= rcnt, *br += rcnt, rbuff += rcnt, fp->fptr += rcnt) { /* Repeat until btr bytes read */
if (fp->fptr % SS(fs) == 0) { /* On the sector boundary? */
csect = (UINT)(fp->fptr / SS(fs) & (fs->csize - 1)); /* Sector offset in the cluster */
if (csect == 0) { /* On the cluster boundary? */
if (fp->fptr == 0) { /* On the top of the file? */
clst = fp->obj.sclust; /* Follow cluster chain from the origin */
} else { /* Middle or end of the file */
#if FF_USE_FASTSEEK
if (fp->cltbl) {
clst = clmt_clust(fp, fp->fptr); /* Get cluster# from the CLMT */
} else
#endif
{
clst = get_fat(&fp->obj, fp->clust); /* Follow cluster chain on the FAT */
}
}
if (clst < 2) ABORT(fs, FR_INT_ERR);
if (clst == 0xFFFFFFFF) ABORT(fs, FR_DISK_ERR);
fp->clust = clst; /* Update current cluster */
}
sect = clst2sect(fs, fp->clust); /* Get current sector */
if (sect == 0) ABORT(fs, FR_INT_ERR);
sect += csect;
cc = btr / SS(fs); /* When remaining bytes >= sector size, */
if (cc > 0) { /* Read maximum contiguous sectors directly */
if (csect + cc > fs->csize) { /* Clip at cluster boundary */
cc = fs->csize - csect;
}
if (disk_read(fs->pdrv, rbuff, sect, cc) != RES_OK) ABORT(fs, FR_DISK_ERR);
#if !FF_FS_READONLY && FF_FS_MINIMIZE <= 2 /* Replace one of the read sectors with cached data if it contains a dirty sector */
#if FF_FS_TINY
if (fs->wflag && fs->winsect - sect < cc) {
memcpy(rbuff + ((fs->winsect - sect) * SS(fs)), fs->win, SS(fs));
}
#else
if ((fp->flag & FA_DIRTY) && fp->sect - sect < cc) {
memcpy(rbuff + ((fp->sect - sect) * SS(fs)), fp->buf, SS(fs));
}
#endif
#endif
rcnt = SS(fs) * cc; /* Number of bytes transferred */
continue;
}
#if !FF_FS_TINY
if (fp->sect != sect) { /* Load data sector if not in cache */
#if !FF_FS_READONLY
if (fp->flag & FA_DIRTY) { /* Write-back dirty sector cache */
if (disk_write(fs->pdrv, fp->buf, fp->sect, 1) != RES_OK) ABORT(fs, FR_DISK_ERR);
fp->flag &= (BYTE)~FA_DIRTY;
}
#endif
if (disk_read(fs->pdrv, fp->buf, sect, 1) != RES_OK) ABORT(fs, FR_DISK_ERR); /* Fill sector cache */
}
#endif
fp->sect = sect;
}
rcnt = SS(fs) - (UINT)fp->fptr % SS(fs); /* Number of bytes remains in the sector */
if (rcnt > btr) rcnt = btr; /* Clip it by btr if needed */
#if FF_FS_TINY
if (move_window(fs, fp->sect) != FR_OK) ABORT(fs, FR_DISK_ERR); /* Move sector window */
memcpy(rbuff, fs->win + fp->fptr % SS(fs), rcnt); /* Extract partial sector */
#else
memcpy(rbuff, fp->buf + fp->fptr % SS(fs), rcnt); /* Extract partial sector */
#endif
}
LEAVE_FF(fs, FR_OK);
} | /*-----------------------------------------------------------------------*/
/* Read File */
/*-----------------------------------------------------------------------*/ | https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/fat/source/ff.c#L3914-L4004 | 83d3b29cbfc74e8f76f48f8782646c8e464055b2 |
teddycloud | github_2023 | toniebox-reverse-engineering | c | f_write | FRESULT f_write (
FIL* fp, /* Open file to be written */
const void* buff, /* Data to be written */
UINT btw, /* Number of bytes to write */
UINT* bw /* Number of bytes written */
)
{
FRESULT res;
FATFS *fs;
DWORD clst;
LBA_t sect;
UINT wcnt, cc, csect;
const BYTE *wbuff = (const BYTE*)buff;
*bw = 0; /* Clear write byte counter */
res = validate(&fp->obj, &fs); /* Check validity of the file object */
if (res != FR_OK || (res = (FRESULT)fp->err) != FR_OK) LEAVE_FF(fs, res); /* Check validity */
if (!(fp->flag & FA_WRITE)) LEAVE_FF(fs, FR_DENIED); /* Check access mode */
/* Check fptr wrap-around (file size cannot reach 4 GiB at FAT volume) */
if ((!FF_FS_EXFAT || fs->fs_type != FS_EXFAT) && (DWORD)(fp->fptr + btw) < (DWORD)fp->fptr) {
btw = (UINT)(0xFFFFFFFF - (DWORD)fp->fptr);
}
for ( ; btw > 0; btw -= wcnt, *bw += wcnt, wbuff += wcnt, fp->fptr += wcnt, fp->obj.objsize = (fp->fptr > fp->obj.objsize) ? fp->fptr : fp->obj.objsize) { /* Repeat until all data written */
if (fp->fptr % SS(fs) == 0) { /* On the sector boundary? */
csect = (UINT)(fp->fptr / SS(fs)) & (fs->csize - 1); /* Sector offset in the cluster */
if (csect == 0) { /* On the cluster boundary? */
if (fp->fptr == 0) { /* On the top of the file? */
clst = fp->obj.sclust; /* Follow from the origin */
if (clst == 0) { /* If no cluster is allocated, */
clst = create_chain(&fp->obj, 0); /* create a new cluster chain */
}
} else { /* On the middle or end of the file */
#if FF_USE_FASTSEEK
if (fp->cltbl) {
clst = clmt_clust(fp, fp->fptr); /* Get cluster# from the CLMT */
} else
#endif
{
clst = create_chain(&fp->obj, fp->clust); /* Follow or stretch cluster chain on the FAT */
}
}
if (clst == 0) break; /* Could not allocate a new cluster (disk full) */
if (clst == 1) ABORT(fs, FR_INT_ERR);
if (clst == 0xFFFFFFFF) ABORT(fs, FR_DISK_ERR);
fp->clust = clst; /* Update current cluster */
if (fp->obj.sclust == 0) fp->obj.sclust = clst; /* Set start cluster if the first write */
}
#if FF_FS_TINY
if (fs->winsect == fp->sect && sync_window(fs) != FR_OK) ABORT(fs, FR_DISK_ERR); /* Write-back sector cache */
#else
if (fp->flag & FA_DIRTY) { /* Write-back sector cache */
if (disk_write(fs->pdrv, fp->buf, fp->sect, 1) != RES_OK) ABORT(fs, FR_DISK_ERR);
fp->flag &= (BYTE)~FA_DIRTY;
}
#endif
sect = clst2sect(fs, fp->clust); /* Get current sector */
if (sect == 0) ABORT(fs, FR_INT_ERR);
sect += csect;
cc = btw / SS(fs); /* When remaining bytes >= sector size, */
if (cc > 0) { /* Write maximum contiguous sectors directly */
if (csect + cc > fs->csize) { /* Clip at cluster boundary */
cc = fs->csize - csect;
}
if (disk_write(fs->pdrv, wbuff, sect, cc) != RES_OK) ABORT(fs, FR_DISK_ERR);
#if FF_FS_MINIMIZE <= 2
#if FF_FS_TINY
if (fs->winsect - sect < cc) { /* Refill sector cache if it gets invalidated by the direct write */
memcpy(fs->win, wbuff + ((fs->winsect - sect) * SS(fs)), SS(fs));
fs->wflag = 0;
}
#else
if (fp->sect - sect < cc) { /* Refill sector cache if it gets invalidated by the direct write */
memcpy(fp->buf, wbuff + ((fp->sect - sect) * SS(fs)), SS(fs));
fp->flag &= (BYTE)~FA_DIRTY;
}
#endif
#endif
wcnt = SS(fs) * cc; /* Number of bytes transferred */
continue;
}
#if FF_FS_TINY
if (fp->fptr >= fp->obj.objsize) { /* Avoid silly cache filling on the growing edge */
if (sync_window(fs) != FR_OK) ABORT(fs, FR_DISK_ERR);
fs->winsect = sect;
}
#else
if (fp->sect != sect && /* Fill sector cache with file data */
fp->fptr < fp->obj.objsize &&
disk_read(fs->pdrv, fp->buf, sect, 1) != RES_OK) {
ABORT(fs, FR_DISK_ERR);
}
#endif
fp->sect = sect;
}
wcnt = SS(fs) - (UINT)fp->fptr % SS(fs); /* Number of bytes remains in the sector */
if (wcnt > btw) wcnt = btw; /* Clip it by btw if needed */
#if FF_FS_TINY
if (move_window(fs, fp->sect) != FR_OK) ABORT(fs, FR_DISK_ERR); /* Move sector window */
memcpy(fs->win + fp->fptr % SS(fs), wbuff, wcnt); /* Fit data to the sector */
fs->wflag = 1;
#else
memcpy(fp->buf + fp->fptr % SS(fs), wbuff, wcnt); /* Fit data to the sector */
fp->flag |= FA_DIRTY;
#endif
}
fp->flag |= FA_MODIFIED; /* Set file change flag */
LEAVE_FF(fs, FR_OK);
} | /*-----------------------------------------------------------------------*/
/* Write File */
/*-----------------------------------------------------------------------*/ | https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/fat/source/ff.c#L4014-L4126 | 83d3b29cbfc74e8f76f48f8782646c8e464055b2 |
teddycloud | github_2023 | toniebox-reverse-engineering | c | f_sync | FRESULT f_sync (
FIL* fp /* Open file to be synced */
)
{
FRESULT res;
FATFS *fs;
DWORD tm;
BYTE *dir;
res = validate(&fp->obj, &fs); /* Check validity of the file object */
if (res == FR_OK) {
if (fp->flag & FA_MODIFIED) { /* Is there any change to the file? */
#if !FF_FS_TINY
if (fp->flag & FA_DIRTY) { /* Write-back cached data if needed */
if (disk_write(fs->pdrv, fp->buf, fp->sect, 1) != RES_OK) LEAVE_FF(fs, FR_DISK_ERR);
fp->flag &= (BYTE)~FA_DIRTY;
}
#endif
/* Update the directory entry */
tm = GET_FATTIME(); /* Modified time */
#if FF_FS_EXFAT
if (fs->fs_type == FS_EXFAT) {
res = fill_first_frag(&fp->obj); /* Fill first fragment on the FAT if needed */
if (res == FR_OK) {
res = fill_last_frag(&fp->obj, fp->clust, 0xFFFFFFFF); /* Fill last fragment on the FAT if needed */
}
if (res == FR_OK) {
DIR dj;
DEF_NAMBUF
INIT_NAMBUF(fs);
res = load_obj_xdir(&dj, &fp->obj); /* Load directory entry block */
if (res == FR_OK) {
fs->dirbuf[XDIR_Attr] |= AM_ARC; /* Set archive attribute to indicate that the file has been changed */
fs->dirbuf[XDIR_GenFlags] = fp->obj.stat | 1; /* Update file allocation information */
st_dword(fs->dirbuf + XDIR_FstClus, fp->obj.sclust); /* Update start cluster */
st_qword(fs->dirbuf + XDIR_FileSize, fp->obj.objsize); /* Update file size */
st_qword(fs->dirbuf + XDIR_ValidFileSize, fp->obj.objsize); /* (FatFs does not support Valid File Size feature) */
st_dword(fs->dirbuf + XDIR_ModTime, tm); /* Update modified time */
fs->dirbuf[XDIR_ModTime10] = 0;
st_dword(fs->dirbuf + XDIR_AccTime, 0);
res = store_xdir(&dj); /* Restore it to the directory */
if (res == FR_OK) {
res = sync_fs(fs);
fp->flag &= (BYTE)~FA_MODIFIED;
}
}
FREE_NAMBUF();
}
} else
#endif
{
res = move_window(fs, fp->dir_sect);
if (res == FR_OK) {
dir = fp->dir_ptr;
dir[DIR_Attr] |= AM_ARC; /* Set archive attribute to indicate that the file has been changed */
st_clust(fp->obj.fs, dir, fp->obj.sclust); /* Update file allocation information */
st_dword(dir + DIR_FileSize, (DWORD)fp->obj.objsize); /* Update file size */
st_dword(dir + DIR_ModTime, tm); /* Update modified time */
st_word(dir + DIR_LstAccDate, 0);
fs->wflag = 1;
res = sync_fs(fs); /* Restore it to the directory */
fp->flag &= (BYTE)~FA_MODIFIED;
}
}
}
}
LEAVE_FF(fs, res);
} | /*-----------------------------------------------------------------------*/
/* Synchronize the File */
/*-----------------------------------------------------------------------*/ | https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/fat/source/ff.c#L4135-L4205 | 83d3b29cbfc74e8f76f48f8782646c8e464055b2 |
teddycloud | github_2023 | toniebox-reverse-engineering | c | f_close | FRESULT f_close (
FIL* fp /* Open file to be closed */
)
{
FRESULT res;
FATFS *fs;
#if !FF_FS_READONLY
res = f_sync(fp); /* Flush cached data */
if (res == FR_OK)
#endif
{
res = validate(&fp->obj, &fs); /* Lock volume */
if (res == FR_OK) {
#if FF_FS_LOCK
res = dec_share(fp->obj.lockid); /* Decrement file open counter */
if (res == FR_OK) fp->obj.fs = 0; /* Invalidate file object */
#else
fp->obj.fs = 0; /* Invalidate file object */
#endif
#if FF_FS_REENTRANT
unlock_volume(fs, FR_OK); /* Unlock volume */
#endif
}
}
return res;
} | /* !FF_FS_READONLY */
/*-----------------------------------------------------------------------*/
/* Close File */
/*-----------------------------------------------------------------------*/ | https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/fat/source/ff.c#L4216-L4242 | 83d3b29cbfc74e8f76f48f8782646c8e464055b2 |
teddycloud | github_2023 | toniebox-reverse-engineering | c | f_chdrive | FRESULT f_chdrive (
const TCHAR* path /* Drive number to set */
)
{
int vol;
/* Get logical drive number */
vol = get_ldnumber(&path);
if (vol < 0) return FR_INVALID_DRIVE;
CurrVol = (BYTE)vol; /* Set it as current volume */
return FR_OK;
} | /*-----------------------------------------------------------------------*/
/* Change Current Directory or Current Drive, Get Current Directory */
/*-----------------------------------------------------------------------*/ | https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/fat/source/ff.c#L4252-L4265 | 83d3b29cbfc74e8f76f48f8782646c8e464055b2 |
teddycloud | github_2023 | toniebox-reverse-engineering | c | f_lseek | FRESULT f_lseek (
FIL* fp, /* Pointer to the file object */
FSIZE_t ofs /* File pointer from top of file */
)
{
FRESULT res;
FATFS *fs;
DWORD clst, bcs;
LBA_t nsect;
FSIZE_t ifptr;
#if FF_USE_FASTSEEK
DWORD cl, pcl, ncl, tcl, tlen, ulen;
DWORD *tbl;
LBA_t dsc;
#endif
res = validate(&fp->obj, &fs); /* Check validity of the file object */
if (res == FR_OK) res = (FRESULT)fp->err;
#if FF_FS_EXFAT && !FF_FS_READONLY
if (res == FR_OK && fs->fs_type == FS_EXFAT) {
res = fill_last_frag(&fp->obj, fp->clust, 0xFFFFFFFF); /* Fill last fragment on the FAT if needed */
}
#endif
if (res != FR_OK) LEAVE_FF(fs, res);
#if FF_USE_FASTSEEK
if (fp->cltbl) { /* Fast seek */
if (ofs == CREATE_LINKMAP) { /* Create CLMT */
tbl = fp->cltbl;
tlen = *tbl++; ulen = 2; /* Given table size and required table size */
cl = fp->obj.sclust; /* Origin of the chain */
if (cl != 0) {
do {
/* Get a fragment */
tcl = cl; ncl = 0; ulen += 2; /* Top, length and used items */
do {
pcl = cl; ncl++;
cl = get_fat(&fp->obj, cl);
if (cl <= 1) ABORT(fs, FR_INT_ERR);
if (cl == 0xFFFFFFFF) ABORT(fs, FR_DISK_ERR);
} while (cl == pcl + 1);
if (ulen <= tlen) { /* Store the length and top of the fragment */
*tbl++ = ncl; *tbl++ = tcl;
}
} while (cl < fs->n_fatent); /* Repeat until end of chain */
}
*fp->cltbl = ulen; /* Number of items used */
if (ulen <= tlen) {
*tbl = 0; /* Terminate table */
} else {
res = FR_NOT_ENOUGH_CORE; /* Given table size is smaller than required */
}
} else { /* Fast seek */
if (ofs > fp->obj.objsize) ofs = fp->obj.objsize; /* Clip offset at the file size */
fp->fptr = ofs; /* Set file pointer */
if (ofs > 0) {
fp->clust = clmt_clust(fp, ofs - 1);
dsc = clst2sect(fs, fp->clust);
if (dsc == 0) ABORT(fs, FR_INT_ERR);
dsc += (DWORD)((ofs - 1) / SS(fs)) & (fs->csize - 1);
if (fp->fptr % SS(fs) && dsc != fp->sect) { /* Refill sector cache if needed */
#if !FF_FS_TINY
#if !FF_FS_READONLY
if (fp->flag & FA_DIRTY) { /* Write-back dirty sector cache */
if (disk_write(fs->pdrv, fp->buf, fp->sect, 1) != RES_OK) ABORT(fs, FR_DISK_ERR);
fp->flag &= (BYTE)~FA_DIRTY;
}
#endif
if (disk_read(fs->pdrv, fp->buf, dsc, 1) != RES_OK) ABORT(fs, FR_DISK_ERR); /* Load current sector */
#endif
fp->sect = dsc;
}
}
}
} else
#endif
/* Normal Seek */
{
#if FF_FS_EXFAT
if (fs->fs_type != FS_EXFAT && ofs >= 0x100000000) ofs = 0xFFFFFFFF; /* Clip at 4 GiB - 1 if at FATxx */
#endif
if (ofs > fp->obj.objsize && (FF_FS_READONLY || !(fp->flag & FA_WRITE))) { /* In read-only mode, clip offset with the file size */
ofs = fp->obj.objsize;
}
ifptr = fp->fptr;
fp->fptr = nsect = 0;
if (ofs > 0) {
bcs = (DWORD)fs->csize * SS(fs); /* Cluster size (byte) */
if (ifptr > 0 &&
(ofs - 1) / bcs >= (ifptr - 1) / bcs) { /* When seek to same or following cluster, */
fp->fptr = (ifptr - 1) & ~(FSIZE_t)(bcs - 1); /* start from the current cluster */
ofs -= fp->fptr;
clst = fp->clust;
} else { /* When seek to back cluster, */
clst = fp->obj.sclust; /* start from the first cluster */
#if !FF_FS_READONLY
if (clst == 0) { /* If no cluster chain, create a new chain */
clst = create_chain(&fp->obj, 0);
if (clst == 1) ABORT(fs, FR_INT_ERR);
if (clst == 0xFFFFFFFF) ABORT(fs, FR_DISK_ERR);
fp->obj.sclust = clst;
}
#endif
fp->clust = clst;
}
if (clst != 0) {
while (ofs > bcs) { /* Cluster following loop */
ofs -= bcs; fp->fptr += bcs;
#if !FF_FS_READONLY
if (fp->flag & FA_WRITE) { /* Check if in write mode or not */
if (FF_FS_EXFAT && fp->fptr > fp->obj.objsize) { /* No FAT chain object needs correct objsize to generate FAT value */
fp->obj.objsize = fp->fptr;
fp->flag |= FA_MODIFIED;
}
clst = create_chain(&fp->obj, clst); /* Follow chain with forceed stretch */
if (clst == 0) { /* Clip file size in case of disk full */
ofs = 0; break;
}
} else
#endif
{
clst = get_fat(&fp->obj, clst); /* Follow cluster chain if not in write mode */
}
if (clst == 0xFFFFFFFF) ABORT(fs, FR_DISK_ERR);
if (clst <= 1 || clst >= fs->n_fatent) ABORT(fs, FR_INT_ERR);
fp->clust = clst;
}
fp->fptr += ofs;
if (ofs % SS(fs)) {
nsect = clst2sect(fs, clst); /* Current sector */
if (nsect == 0) ABORT(fs, FR_INT_ERR);
nsect += (DWORD)(ofs / SS(fs));
}
}
}
if (!FF_FS_READONLY && fp->fptr > fp->obj.objsize) { /* Set file change flag if the file size is extended */
fp->obj.objsize = fp->fptr;
fp->flag |= FA_MODIFIED;
}
if (fp->fptr % SS(fs) && nsect != fp->sect) { /* Fill sector cache if needed */
#if !FF_FS_TINY
#if !FF_FS_READONLY
if (fp->flag & FA_DIRTY) { /* Write-back dirty sector cache */
if (disk_write(fs->pdrv, fp->buf, fp->sect, 1) != RES_OK) ABORT(fs, FR_DISK_ERR);
fp->flag &= (BYTE)~FA_DIRTY;
}
#endif
if (disk_read(fs->pdrv, fp->buf, nsect, 1) != RES_OK) ABORT(fs, FR_DISK_ERR); /* Fill sector cache */
#endif
fp->sect = nsect;
}
}
LEAVE_FF(fs, res);
} | /*-----------------------------------------------------------------------*/
/* Seek File Read/Write Pointer */
/*-----------------------------------------------------------------------*/ | https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/fat/source/ff.c#L4433-L4588 | 83d3b29cbfc74e8f76f48f8782646c8e464055b2 |
teddycloud | github_2023 | toniebox-reverse-engineering | c | f_opendir | FRESULT f_opendir (
DIR* dp, /* Pointer to directory object to create */
const TCHAR* path /* Pointer to the directory path */
)
{
FRESULT res;
FATFS *fs;
DEF_NAMBUF
if (!dp) return FR_INVALID_OBJECT;
/* Get logical drive */
res = mount_volume(&path, &fs, 0);
if (res == FR_OK) {
dp->obj.fs = fs;
INIT_NAMBUF(fs);
res = follow_path(dp, path); /* Follow the path to the directory */
if (res == FR_OK) { /* Follow completed */
if (!(dp->fn[NSFLAG] & NS_NONAME)) { /* It is not the origin directory itself */
if (dp->obj.attr & AM_DIR) { /* This object is a sub-directory */
#if FF_FS_EXFAT
if (fs->fs_type == FS_EXFAT) {
dp->obj.c_scl = dp->obj.sclust; /* Get containing directory inforamation */
dp->obj.c_size = ((DWORD)dp->obj.objsize & 0xFFFFFF00) | dp->obj.stat;
dp->obj.c_ofs = dp->blk_ofs;
init_alloc_info(fs, &dp->obj); /* Get object allocation info */
} else
#endif
{
dp->obj.sclust = ld_clust(fs, dp->dir); /* Get object allocation info */
}
} else { /* This object is a file */
res = FR_NO_PATH;
}
}
if (res == FR_OK) {
dp->obj.id = fs->id;
res = dir_sdi(dp, 0); /* Rewind directory */
#if FF_FS_LOCK
if (res == FR_OK) {
if (dp->obj.sclust != 0) {
dp->obj.lockid = inc_share(dp, 0); /* Lock the sub directory */
if (!dp->obj.lockid) res = FR_TOO_MANY_OPEN_FILES;
} else {
dp->obj.lockid = 0; /* Root directory need not to be locked */
}
}
#endif
}
}
FREE_NAMBUF();
if (res == FR_NO_FILE) res = FR_NO_PATH;
}
if (res != FR_OK) dp->obj.fs = 0; /* Invalidate the directory object if function failed */
LEAVE_FF(fs, res);
} | /*-----------------------------------------------------------------------*/
/* Create a Directory Object */
/*-----------------------------------------------------------------------*/ | https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/fat/source/ff.c#L4597-L4654 | 83d3b29cbfc74e8f76f48f8782646c8e464055b2 |
teddycloud | github_2023 | toniebox-reverse-engineering | c | f_closedir | FRESULT f_closedir (
DIR *dp /* Pointer to the directory object to be closed */
)
{
FRESULT res;
FATFS *fs;
res = validate(&dp->obj, &fs); /* Check validity of the file object */
if (res == FR_OK) {
#if FF_FS_LOCK
if (dp->obj.lockid) res = dec_share(dp->obj.lockid); /* Decrement sub-directory open counter */
if (res == FR_OK) dp->obj.fs = 0; /* Invalidate directory object */
#else
dp->obj.fs = 0; /* Invalidate directory object */
#endif
#if FF_FS_REENTRANT
unlock_volume(fs, FR_OK); /* Unlock volume */
#endif
}
return res;
} | /*-----------------------------------------------------------------------*/
/* Close Directory */
/*-----------------------------------------------------------------------*/ | https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/fat/source/ff.c#L4663-L4684 | 83d3b29cbfc74e8f76f48f8782646c8e464055b2 |
teddycloud | github_2023 | toniebox-reverse-engineering | c | f_readdir | FRESULT f_readdir (
DIR* dp, /* Pointer to the open directory object */
FILINFO* fno /* Pointer to file information to return */
)
{
FRESULT res;
FATFS *fs;
DEF_NAMBUF
res = validate(&dp->obj, &fs); /* Check validity of the directory object */
if (res == FR_OK) {
if (!fno) {
res = dir_sdi(dp, 0); /* Rewind the directory object */
} else {
INIT_NAMBUF(fs);
res = DIR_READ_FILE(dp); /* Read an item */
if (res == FR_NO_FILE) res = FR_OK; /* Ignore end of directory */
if (res == FR_OK) { /* A valid entry is found */
get_fileinfo(dp, fno); /* Get the object information */
res = dir_next(dp, 0); /* Increment index for next */
if (res == FR_NO_FILE) res = FR_OK; /* Ignore end of directory now */
}
FREE_NAMBUF();
}
}
LEAVE_FF(fs, res);
} | /*-----------------------------------------------------------------------*/
/* Read Directory Entries in Sequence */
/*-----------------------------------------------------------------------*/ | https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/fat/source/ff.c#L4693-L4720 | 83d3b29cbfc74e8f76f48f8782646c8e464055b2 |
teddycloud | github_2023 | toniebox-reverse-engineering | c | f_findnext | FRESULT f_findnext (
DIR* dp, /* Pointer to the open directory object */
FILINFO* fno /* Pointer to the file information structure */
)
{
FRESULT res;
for (;;) {
res = f_readdir(dp, fno); /* Get a directory item */
if (res != FR_OK || !fno || !fno->fname[0]) break; /* Terminate if any error or end of directory */
if (pattern_match(dp->pat, fno->fname, 0, FIND_RECURS)) break; /* Test for the file name */
#if FF_USE_LFN && FF_USE_FIND == 2
if (pattern_match(dp->pat, fno->altname, 0, FIND_RECURS)) break; /* Test for alternative name if exist */
#endif
}
return res;
} | /*-----------------------------------------------------------------------*/
/* Find Next File */
/*-----------------------------------------------------------------------*/ | https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/fat/source/ff.c#L4729-L4746 | 83d3b29cbfc74e8f76f48f8782646c8e464055b2 |
teddycloud | github_2023 | toniebox-reverse-engineering | c | f_findfirst | FRESULT f_findfirst (
DIR* dp, /* Pointer to the blank directory object */
FILINFO* fno, /* Pointer to the file information structure */
const TCHAR* path, /* Pointer to the directory to open */
const TCHAR* pattern /* Pointer to the matching pattern */
)
{
FRESULT res;
dp->pat = pattern; /* Save pointer to pattern string */
res = f_opendir(dp, path); /* Open the target directory */
if (res == FR_OK) {
res = f_findnext(dp, fno); /* Find the first item */
}
return res;
} | /*-----------------------------------------------------------------------*/
/* Find First File */
/*-----------------------------------------------------------------------*/ | https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/fat/source/ff.c#L4754-L4770 | 83d3b29cbfc74e8f76f48f8782646c8e464055b2 |
teddycloud | github_2023 | toniebox-reverse-engineering | c | f_stat | FRESULT f_stat (
const TCHAR* path, /* Pointer to the file path */
FILINFO* fno /* Pointer to file information to return */
)
{
FRESULT res;
DIR dj;
DEF_NAMBUF
/* Get logical drive */
res = mount_volume(&path, &dj.obj.fs, 0);
if (res == FR_OK) {
INIT_NAMBUF(dj.obj.fs);
res = follow_path(&dj, path); /* Follow the file path */
if (res == FR_OK) { /* Follow completed */
if (dj.fn[NSFLAG] & NS_NONAME) { /* It is origin directory */
res = FR_INVALID_NAME;
} else { /* Found an object */
if (fno) get_fileinfo(&dj, fno);
}
}
FREE_NAMBUF();
}
LEAVE_FF(dj.obj.fs, res);
} | /*-----------------------------------------------------------------------*/
/* Get File Status */
/*-----------------------------------------------------------------------*/ | https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/fat/source/ff.c#L4781-L4807 | 83d3b29cbfc74e8f76f48f8782646c8e464055b2 |
teddycloud | github_2023 | toniebox-reverse-engineering | c | f_getfree | FRESULT f_getfree (
const TCHAR* path, /* Logical drive number */
DWORD* nclst, /* Pointer to a variable to return number of free clusters */
FATFS** fatfs /* Pointer to return pointer to corresponding filesystem object */
)
{
FRESULT res;
FATFS *fs;
DWORD nfree, clst, stat;
LBA_t sect;
UINT i;
FFOBJID obj;
/* Get logical drive */
res = mount_volume(&path, &fs, 0);
if (res == FR_OK) {
*fatfs = fs; /* Return ptr to the fs object */
/* If free_clst is valid, return it without full FAT scan */
if (fs->free_clst <= fs->n_fatent - 2) {
*nclst = fs->free_clst;
} else {
/* Scan FAT to obtain number of free clusters */
nfree = 0;
if (fs->fs_type == FS_FAT12) { /* FAT12: Scan bit field FAT entries */
clst = 2; obj.fs = fs;
do {
stat = get_fat(&obj, clst);
if (stat == 0xFFFFFFFF) {
res = FR_DISK_ERR; break;
}
if (stat == 1) {
res = FR_INT_ERR; break;
}
if (stat == 0) nfree++;
} while (++clst < fs->n_fatent);
} else {
#if FF_FS_EXFAT
if (fs->fs_type == FS_EXFAT) { /* exFAT: Scan allocation bitmap */
BYTE bm;
UINT b;
clst = fs->n_fatent - 2; /* Number of clusters */
sect = fs->bitbase; /* Bitmap sector */
i = 0; /* Offset in the sector */
do { /* Counts numbuer of bits with zero in the bitmap */
if (i == 0) { /* New sector? */
res = move_window(fs, sect++);
if (res != FR_OK) break;
}
for (b = 8, bm = ~fs->win[i]; b && clst; b--, clst--) {
nfree += bm & 1;
bm >>= 1;
}
i = (i + 1) % SS(fs);
} while (clst);
} else
#endif
{ /* FAT16/32: Scan WORD/DWORD FAT entries */
clst = fs->n_fatent; /* Number of entries */
sect = fs->fatbase; /* Top of the FAT */
i = 0; /* Offset in the sector */
do { /* Counts numbuer of entries with zero in the FAT */
if (i == 0) { /* New sector? */
res = move_window(fs, sect++);
if (res != FR_OK) break;
}
if (fs->fs_type == FS_FAT16) {
if (ld_word(fs->win + i) == 0) nfree++;
i += 2;
} else {
if ((ld_dword(fs->win + i) & 0x0FFFFFFF) == 0) nfree++;
i += 4;
}
i %= SS(fs);
} while (--clst);
}
}
if (res == FR_OK) { /* Update parameters if succeeded */
*nclst = nfree; /* Return the free clusters */
fs->free_clst = nfree; /* Now free_clst is valid */
fs->fsi_flag |= 1; /* FAT32: FSInfo is to be updated */
}
}
}
LEAVE_FF(fs, res);
} | /*-----------------------------------------------------------------------*/
/* Get Number of Free Clusters */
/*-----------------------------------------------------------------------*/ | https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/fat/source/ff.c#L4816-L4903 | 83d3b29cbfc74e8f76f48f8782646c8e464055b2 |
teddycloud | github_2023 | toniebox-reverse-engineering | c | f_truncate | FRESULT f_truncate (
FIL* fp /* Pointer to the file object */
)
{
FRESULT res;
FATFS *fs;
DWORD ncl;
res = validate(&fp->obj, &fs); /* Check validity of the file object */
if (res != FR_OK || (res = (FRESULT)fp->err) != FR_OK) LEAVE_FF(fs, res);
if (!(fp->flag & FA_WRITE)) LEAVE_FF(fs, FR_DENIED); /* Check access mode */
if (fp->fptr < fp->obj.objsize) { /* Process when fptr is not on the eof */
if (fp->fptr == 0) { /* When set file size to zero, remove entire cluster chain */
res = remove_chain(&fp->obj, fp->obj.sclust, 0);
fp->obj.sclust = 0;
} else { /* When truncate a part of the file, remove remaining clusters */
ncl = get_fat(&fp->obj, fp->clust);
res = FR_OK;
if (ncl == 0xFFFFFFFF) res = FR_DISK_ERR;
if (ncl == 1) res = FR_INT_ERR;
if (res == FR_OK && ncl < fs->n_fatent) {
res = remove_chain(&fp->obj, ncl, fp->clust);
}
}
fp->obj.objsize = fp->fptr; /* Set file size to current read/write point */
fp->flag |= FA_MODIFIED;
#if !FF_FS_TINY
if (res == FR_OK && (fp->flag & FA_DIRTY)) {
if (disk_write(fs->pdrv, fp->buf, fp->sect, 1) != RES_OK) {
res = FR_DISK_ERR;
} else {
fp->flag &= (BYTE)~FA_DIRTY;
}
}
#endif
if (res != FR_OK) ABORT(fs, res);
}
LEAVE_FF(fs, res);
} | /*-----------------------------------------------------------------------*/
/* Truncate File */
/*-----------------------------------------------------------------------*/ | https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/fat/source/ff.c#L4912-L4953 | 83d3b29cbfc74e8f76f48f8782646c8e464055b2 |
teddycloud | github_2023 | toniebox-reverse-engineering | c | f_unlink | FRESULT f_unlink (
const TCHAR* path /* Pointer to the file or directory path */
)
{
FRESULT res;
FATFS *fs;
DIR dj, sdj;
DWORD dclst = 0;
#if FF_FS_EXFAT
FFOBJID obj;
#endif
DEF_NAMBUF
/* Get logical drive */
res = mount_volume(&path, &fs, FA_WRITE);
if (res == FR_OK) {
dj.obj.fs = fs;
INIT_NAMBUF(fs);
res = follow_path(&dj, path); /* Follow the file path */
if (FF_FS_RPATH && res == FR_OK && (dj.fn[NSFLAG] & NS_DOT)) {
res = FR_INVALID_NAME; /* Cannot remove dot entry */
}
#if FF_FS_LOCK
if (res == FR_OK) res = chk_share(&dj, 2); /* Check if it is an open object */
#endif
if (res == FR_OK) { /* The object is accessible */
if (dj.fn[NSFLAG] & NS_NONAME) {
res = FR_INVALID_NAME; /* Cannot remove the origin directory */
} else {
if (dj.obj.attr & AM_RDO) {
res = FR_DENIED; /* Cannot remove R/O object */
}
}
if (res == FR_OK) {
#if FF_FS_EXFAT
obj.fs = fs;
if (fs->fs_type == FS_EXFAT) {
init_alloc_info(fs, &obj);
dclst = obj.sclust;
} else
#endif
{
dclst = ld_clust(fs, dj.dir);
}
if (dj.obj.attr & AM_DIR) { /* Is it a sub-directory? */
#if FF_FS_RPATH != 0
if (dclst == fs->cdir) { /* Is it the current directory? */
res = FR_DENIED;
} else
#endif
{
sdj.obj.fs = fs; /* Open the sub-directory */
sdj.obj.sclust = dclst;
#if FF_FS_EXFAT
if (fs->fs_type == FS_EXFAT) {
sdj.obj.objsize = obj.objsize;
sdj.obj.stat = obj.stat;
}
#endif
res = dir_sdi(&sdj, 0);
if (res == FR_OK) {
res = DIR_READ_FILE(&sdj); /* Test if the directory is empty */
if (res == FR_OK) res = FR_DENIED; /* Not empty? */
if (res == FR_NO_FILE) res = FR_OK; /* Empty? */
}
}
}
}
if (res == FR_OK) {
res = dir_remove(&dj); /* Remove the directory entry */
if (res == FR_OK && dclst != 0) { /* Remove the cluster chain if exist */
#if FF_FS_EXFAT
res = remove_chain(&obj, dclst, 0);
#else
res = remove_chain(&dj.obj, dclst, 0);
#endif
}
if (res == FR_OK) res = sync_fs(fs);
}
}
FREE_NAMBUF();
}
LEAVE_FF(fs, res);
} | /*-----------------------------------------------------------------------*/
/* Delete a File/Directory */
/*-----------------------------------------------------------------------*/ | https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/fat/source/ff.c#L4962-L5047 | 83d3b29cbfc74e8f76f48f8782646c8e464055b2 |
teddycloud | github_2023 | toniebox-reverse-engineering | c | f_mkdir | FRESULT f_mkdir (
const TCHAR* path /* Pointer to the directory path */
)
{
FRESULT res;
FATFS *fs;
DIR dj;
FFOBJID sobj;
DWORD dcl, pcl, tm;
DEF_NAMBUF
res = mount_volume(&path, &fs, FA_WRITE); /* Get logical drive */
if (res == FR_OK) {
dj.obj.fs = fs;
INIT_NAMBUF(fs);
res = follow_path(&dj, path); /* Follow the file path */
if (res == FR_OK) res = FR_EXIST; /* Name collision? */
if (FF_FS_RPATH && res == FR_NO_FILE && (dj.fn[NSFLAG] & NS_DOT)) { /* Invalid name? */
res = FR_INVALID_NAME;
}
if (res == FR_NO_FILE) { /* It is clear to create a new directory */
sobj.fs = fs; /* New object id to create a new chain */
dcl = create_chain(&sobj, 0); /* Allocate a cluster for the new directory */
res = FR_OK;
if (dcl == 0) res = FR_DENIED; /* No space to allocate a new cluster? */
if (dcl == 1) res = FR_INT_ERR; /* Any insanity? */
if (dcl == 0xFFFFFFFF) res = FR_DISK_ERR; /* Disk error? */
tm = GET_FATTIME();
if (res == FR_OK) {
res = dir_clear(fs, dcl); /* Clean up the new table */
if (res == FR_OK) {
if (!FF_FS_EXFAT || fs->fs_type != FS_EXFAT) { /* Create dot entries (FAT only) */
memset(fs->win + DIR_Name, ' ', 11); /* Create "." entry */
fs->win[DIR_Name] = '.';
fs->win[DIR_Attr] = AM_DIR;
st_dword(fs->win + DIR_ModTime, tm);
st_clust(fs, fs->win, dcl);
memcpy(fs->win + SZDIRE, fs->win, SZDIRE); /* Create ".." entry */
fs->win[SZDIRE + 1] = '.'; pcl = dj.obj.sclust;
st_clust(fs, fs->win + SZDIRE, pcl);
fs->wflag = 1;
}
res = dir_register(&dj); /* Register the object to the parent directoy */
}
}
if (res == FR_OK) {
#if FF_FS_EXFAT
if (fs->fs_type == FS_EXFAT) { /* Initialize directory entry block */
st_dword(fs->dirbuf + XDIR_ModTime, tm); /* Created time */
st_dword(fs->dirbuf + XDIR_FstClus, dcl); /* Table start cluster */
st_dword(fs->dirbuf + XDIR_FileSize, (DWORD)fs->csize * SS(fs)); /* Directory size needs to be valid */
st_dword(fs->dirbuf + XDIR_ValidFileSize, (DWORD)fs->csize * SS(fs));
fs->dirbuf[XDIR_GenFlags] = 3; /* Initialize the object flag */
fs->dirbuf[XDIR_Attr] = AM_DIR; /* Attribute */
res = store_xdir(&dj);
} else
#endif
{
st_dword(dj.dir + DIR_ModTime, tm); /* Created time */
st_clust(fs, dj.dir, dcl); /* Table start cluster */
dj.dir[DIR_Attr] = AM_DIR; /* Attribute */
fs->wflag = 1;
}
if (res == FR_OK) {
res = sync_fs(fs);
}
} else {
remove_chain(&sobj, dcl, 0); /* Could not register, remove the allocated cluster */
}
}
FREE_NAMBUF();
}
LEAVE_FF(fs, res);
} | /*-----------------------------------------------------------------------*/
/* Create a Directory */
/*-----------------------------------------------------------------------*/ | https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/fat/source/ff.c#L5056-L5131 | 83d3b29cbfc74e8f76f48f8782646c8e464055b2 |
teddycloud | github_2023 | toniebox-reverse-engineering | c | f_rename | FRESULT f_rename (
const TCHAR* path_old, /* Pointer to the object name to be renamed */
const TCHAR* path_new /* Pointer to the new name */
)
{
FRESULT res;
FATFS *fs;
DIR djo, djn;
BYTE buf[FF_FS_EXFAT ? SZDIRE * 2 : SZDIRE], *dir;
LBA_t sect;
DEF_NAMBUF
get_ldnumber(&path_new); /* Snip the drive number of new name off */
res = mount_volume(&path_old, &fs, FA_WRITE); /* Get logical drive of the old object */
if (res == FR_OK) {
djo.obj.fs = fs;
INIT_NAMBUF(fs);
res = follow_path(&djo, path_old); /* Check old object */
if (res == FR_OK && (djo.fn[NSFLAG] & (NS_DOT | NS_NONAME))) res = FR_INVALID_NAME; /* Check validity of name */
#if FF_FS_LOCK
if (res == FR_OK) {
res = chk_share(&djo, 2);
}
#endif
if (res == FR_OK) { /* Object to be renamed is found */
#if FF_FS_EXFAT
if (fs->fs_type == FS_EXFAT) { /* At exFAT volume */
BYTE nf, nn;
WORD nh;
memcpy(buf, fs->dirbuf, SZDIRE * 2); /* Save 85+C0 entry of old object */
memcpy(&djn, &djo, sizeof djo);
res = follow_path(&djn, path_new); /* Make sure if new object name is not in use */
if (res == FR_OK) { /* Is new name already in use by any other object? */
res = (djn.obj.sclust == djo.obj.sclust && djn.dptr == djo.dptr) ? FR_NO_FILE : FR_EXIST;
}
if (res == FR_NO_FILE) { /* It is a valid path and no name collision */
res = dir_register(&djn); /* Register the new entry */
if (res == FR_OK) {
nf = fs->dirbuf[XDIR_NumSec]; nn = fs->dirbuf[XDIR_NumName];
nh = ld_word(fs->dirbuf + XDIR_NameHash);
memcpy(fs->dirbuf, buf, SZDIRE * 2); /* Restore 85+C0 entry */
fs->dirbuf[XDIR_NumSec] = nf; fs->dirbuf[XDIR_NumName] = nn;
st_word(fs->dirbuf + XDIR_NameHash, nh);
if (!(fs->dirbuf[XDIR_Attr] & AM_DIR)) fs->dirbuf[XDIR_Attr] |= AM_ARC; /* Set archive attribute if it is a file */
/* Start of critical section where an interruption can cause a cross-link */
res = store_xdir(&djn);
}
}
} else
#endif
{ /* At FAT/FAT32 volume */
memcpy(buf, djo.dir, SZDIRE); /* Save directory entry of the object */
memcpy(&djn, &djo, sizeof (DIR)); /* Duplicate the directory object */
res = follow_path(&djn, path_new); /* Make sure if new object name is not in use */
if (res == FR_OK) { /* Is new name already in use by any other object? */
res = (djn.obj.sclust == djo.obj.sclust && djn.dptr == djo.dptr) ? FR_NO_FILE : FR_EXIST;
}
if (res == FR_NO_FILE) { /* It is a valid path and no name collision */
res = dir_register(&djn); /* Register the new entry */
if (res == FR_OK) {
dir = djn.dir; /* Copy directory entry of the object except name */
memcpy(dir + 13, buf + 13, SZDIRE - 13);
dir[DIR_Attr] = buf[DIR_Attr];
if (!(dir[DIR_Attr] & AM_DIR)) dir[DIR_Attr] |= AM_ARC; /* Set archive attribute if it is a file */
fs->wflag = 1;
if ((dir[DIR_Attr] & AM_DIR) && djo.obj.sclust != djn.obj.sclust) { /* Update .. entry in the sub-directory if needed */
sect = clst2sect(fs, ld_clust(fs, dir));
if (sect == 0) {
res = FR_INT_ERR;
} else {
/* Start of critical section where an interruption can cause a cross-link */
res = move_window(fs, sect);
dir = fs->win + SZDIRE * 1; /* Ptr to .. entry */
if (res == FR_OK && dir[1] == '.') {
st_clust(fs, dir, djn.obj.sclust);
fs->wflag = 1;
}
}
}
}
}
}
if (res == FR_OK) {
res = dir_remove(&djo); /* Remove old entry */
if (res == FR_OK) {
res = sync_fs(fs);
}
}
/* End of the critical section */
}
FREE_NAMBUF();
}
LEAVE_FF(fs, res);
} | /*-----------------------------------------------------------------------*/
/* Rename a File/Directory */
/*-----------------------------------------------------------------------*/ | https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/fat/source/ff.c#L5140-L5236 | 83d3b29cbfc74e8f76f48f8782646c8e464055b2 |
teddycloud | github_2023 | toniebox-reverse-engineering | c | f_chmod | FRESULT f_chmod (
const TCHAR* path, /* Pointer to the file path */
BYTE attr, /* Attribute bits */
BYTE mask /* Attribute mask to change */
)
{
FRESULT res;
FATFS *fs;
DIR dj;
DEF_NAMBUF
res = mount_volume(&path, &fs, FA_WRITE); /* Get logical drive */
if (res == FR_OK) {
dj.obj.fs = fs;
INIT_NAMBUF(fs);
res = follow_path(&dj, path); /* Follow the file path */
if (res == FR_OK && (dj.fn[NSFLAG] & (NS_DOT | NS_NONAME))) res = FR_INVALID_NAME; /* Check object validity */
if (res == FR_OK) {
mask &= AM_RDO|AM_HID|AM_SYS|AM_ARC; /* Valid attribute mask */
#if FF_FS_EXFAT
if (fs->fs_type == FS_EXFAT) {
fs->dirbuf[XDIR_Attr] = (attr & mask) | (fs->dirbuf[XDIR_Attr] & (BYTE)~mask); /* Apply attribute change */
res = store_xdir(&dj);
} else
#endif
{
dj.dir[DIR_Attr] = (attr & mask) | (dj.dir[DIR_Attr] & (BYTE)~mask); /* Apply attribute change */
fs->wflag = 1;
}
if (res == FR_OK) {
res = sync_fs(fs);
}
}
FREE_NAMBUF();
}
LEAVE_FF(fs, res);
} | /*-----------------------------------------------------------------------*/
/* Change Attribute */
/*-----------------------------------------------------------------------*/ | https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/fat/source/ff.c#L5250-L5288 | 83d3b29cbfc74e8f76f48f8782646c8e464055b2 |
teddycloud | github_2023 | toniebox-reverse-engineering | c | f_utime | FRESULT f_utime (
const TCHAR* path, /* Pointer to the file/directory name */
const FILINFO* fno /* Pointer to the timestamp to be set */
)
{
FRESULT res;
FATFS *fs;
DIR dj;
DEF_NAMBUF
res = mount_volume(&path, &fs, FA_WRITE); /* Get logical drive */
if (res == FR_OK) {
dj.obj.fs = fs;
INIT_NAMBUF(fs);
res = follow_path(&dj, path); /* Follow the file path */
if (res == FR_OK && (dj.fn[NSFLAG] & (NS_DOT | NS_NONAME))) res = FR_INVALID_NAME; /* Check object validity */
if (res == FR_OK) {
#if FF_FS_EXFAT
if (fs->fs_type == FS_EXFAT) {
st_dword(fs->dirbuf + XDIR_ModTime, (DWORD)fno->fdate << 16 | fno->ftime);
res = store_xdir(&dj);
} else
#endif
{
st_dword(dj.dir + DIR_ModTime, (DWORD)fno->fdate << 16 | fno->ftime);
fs->wflag = 1;
}
if (res == FR_OK) {
res = sync_fs(fs);
}
}
FREE_NAMBUF();
}
LEAVE_FF(fs, res);
} | /*-----------------------------------------------------------------------*/
/* Change Timestamp */
/*-----------------------------------------------------------------------*/ | https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/fat/source/ff.c#L5297-L5333 | 83d3b29cbfc74e8f76f48f8782646c8e464055b2 |
teddycloud | github_2023 | toniebox-reverse-engineering | c | f_getlabel | FRESULT f_getlabel (
const TCHAR* path, /* Logical drive number */
TCHAR* label, /* Buffer to store the volume label */
DWORD* vsn /* Variable to store the volume serial number */
)
{
FRESULT res;
FATFS *fs;
DIR dj;
UINT si, di;
WCHAR wc;
/* Get logical drive */
res = mount_volume(&path, &fs, 0);
/* Get volume label */
if (res == FR_OK && label) {
dj.obj.fs = fs; dj.obj.sclust = 0; /* Open root directory */
res = dir_sdi(&dj, 0);
if (res == FR_OK) {
res = DIR_READ_LABEL(&dj); /* Find a volume label entry */
if (res == FR_OK) {
#if FF_FS_EXFAT
if (fs->fs_type == FS_EXFAT) {
WCHAR hs;
UINT nw;
for (si = di = hs = 0; si < dj.dir[XDIR_NumLabel]; si++) { /* Extract volume label from 83 entry */
wc = ld_word(dj.dir + XDIR_Label + si * 2);
if (hs == 0 && IsSurrogate(wc)) { /* Is the code a surrogate? */
hs = wc; continue;
}
nw = put_utf((DWORD)hs << 16 | wc, &label[di], 4); /* Store it in API encoding */
if (nw == 0) { /* Encode error? */
di = 0; break;
}
di += nw;
hs = 0;
}
if (hs != 0) di = 0; /* Broken surrogate pair? */
label[di] = 0;
} else
#endif
{
si = di = 0; /* Extract volume label from AM_VOL entry */
while (si < 11) {
wc = dj.dir[si++];
#if FF_USE_LFN && FF_LFN_UNICODE >= 1 /* Unicode output */
if (dbc_1st((BYTE)wc) && si < 11) wc = wc << 8 | dj.dir[si++]; /* Is it a DBC? */
wc = ff_oem2uni(wc, CODEPAGE); /* Convert it into Unicode */
if (wc == 0) { /* Invalid char in current code page? */
di = 0; break;
}
di += put_utf(wc, &label[di], 4); /* Store it in Unicode */
#else /* ANSI/OEM output */
label[di++] = (TCHAR)wc;
#endif
}
do { /* Truncate trailing spaces */
label[di] = 0;
if (di == 0) break;
} while (label[--di] == ' ');
}
}
}
if (res == FR_NO_FILE) { /* No label entry and return nul string */
label[0] = 0;
res = FR_OK;
}
}
/* Get volume serial number */
if (res == FR_OK && vsn) {
res = move_window(fs, fs->volbase);
if (res == FR_OK) {
switch (fs->fs_type) {
case FS_EXFAT:
di = BPB_VolIDEx;
break;
case FS_FAT32:
di = BS_VolID32;
break;
default:
di = BS_VolID;
}
*vsn = ld_dword(fs->win + di);
}
}
LEAVE_FF(fs, res);
} | /*-----------------------------------------------------------------------*/
/* Get Volume Label */
/*-----------------------------------------------------------------------*/ | https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/fat/source/ff.c#L5344-L5436 | 83d3b29cbfc74e8f76f48f8782646c8e464055b2 |
teddycloud | github_2023 | toniebox-reverse-engineering | c | f_setlabel | FRESULT f_setlabel (
const TCHAR* label /* Volume label to set with heading logical drive number */
)
{
FRESULT res;
FATFS *fs;
DIR dj;
BYTE dirvn[22];
UINT di;
WCHAR wc;
static const char badchr[18] = "+.,;=[]" "/*:<>|\\\"\?\x7F"; /* [0..16] for FAT, [7..16] for exFAT */
#if FF_USE_LFN
DWORD dc;
#endif
/* Get logical drive */
res = mount_volume(&label, &fs, FA_WRITE);
if (res != FR_OK) LEAVE_FF(fs, res);
#if FF_FS_EXFAT
if (fs->fs_type == FS_EXFAT) { /* On the exFAT volume */
memset(dirvn, 0, 22);
di = 0;
while ((UINT)*label >= ' ') { /* Create volume label */
dc = tchar2uni(&label); /* Get a Unicode character */
if (dc >= 0x10000) {
if (dc == 0xFFFFFFFF || di >= 10) { /* Wrong surrogate or buffer overflow */
dc = 0;
} else {
st_word(dirvn + di * 2, (WCHAR)(dc >> 16)); di++;
}
}
if (dc == 0 || strchr(&badchr[7], (int)dc) || di >= 11) { /* Check validity of the volume label */
LEAVE_FF(fs, FR_INVALID_NAME);
}
st_word(dirvn + di * 2, (WCHAR)dc); di++;
}
} else
#endif
{ /* On the FAT/FAT32 volume */
memset(dirvn, ' ', 11);
di = 0;
while ((UINT)*label >= ' ') { /* Create volume label */
#if FF_USE_LFN
dc = tchar2uni(&label);
wc = (dc < 0x10000) ? ff_uni2oem(ff_wtoupper(dc), CODEPAGE) : 0;
#else /* ANSI/OEM input */
wc = (BYTE)*label++;
if (dbc_1st((BYTE)wc)) wc = dbc_2nd((BYTE)*label) ? wc << 8 | (BYTE)*label++ : 0;
if (IsLower(wc)) wc -= 0x20; /* To upper ASCII characters */
#if FF_CODE_PAGE == 0
if (ExCvt && wc >= 0x80) wc = ExCvt[wc - 0x80]; /* To upper extended characters (SBCS cfg) */
#elif FF_CODE_PAGE < 900
if (wc >= 0x80) wc = ExCvt[wc - 0x80]; /* To upper extended characters (SBCS cfg) */
#endif
#endif
if (wc == 0 || strchr(&badchr[0], (int)wc) || di >= (UINT)((wc >= 0x100) ? 10 : 11)) { /* Reject invalid characters for volume label */
LEAVE_FF(fs, FR_INVALID_NAME);
}
if (wc >= 0x100) dirvn[di++] = (BYTE)(wc >> 8);
dirvn[di++] = (BYTE)wc;
}
if (dirvn[0] == DDEM) LEAVE_FF(fs, FR_INVALID_NAME); /* Reject illegal name (heading DDEM) */
while (di && dirvn[di - 1] == ' ') di--; /* Snip trailing spaces */
}
/* Set volume label */
dj.obj.fs = fs; dj.obj.sclust = 0; /* Open root directory */
res = dir_sdi(&dj, 0);
if (res == FR_OK) {
res = DIR_READ_LABEL(&dj); /* Get volume label entry */
if (res == FR_OK) {
if (FF_FS_EXFAT && fs->fs_type == FS_EXFAT) {
dj.dir[XDIR_NumLabel] = (BYTE)di; /* Change the volume label */
memcpy(dj.dir + XDIR_Label, dirvn, 22);
} else {
if (di != 0) {
memcpy(dj.dir, dirvn, 11); /* Change the volume label */
} else {
dj.dir[DIR_Name] = DDEM; /* Remove the volume label */
}
}
fs->wflag = 1;
res = sync_fs(fs);
} else { /* No volume label entry or an error */
if (res == FR_NO_FILE) {
res = FR_OK;
if (di != 0) { /* Create a volume label entry */
res = dir_alloc(&dj, 1); /* Allocate an entry */
if (res == FR_OK) {
memset(dj.dir, 0, SZDIRE); /* Clean the entry */
if (FF_FS_EXFAT && fs->fs_type == FS_EXFAT) {
dj.dir[XDIR_Type] = ET_VLABEL; /* Create volume label entry */
dj.dir[XDIR_NumLabel] = (BYTE)di;
memcpy(dj.dir + XDIR_Label, dirvn, 22);
} else {
dj.dir[DIR_Attr] = AM_VOL; /* Create volume label entry */
memcpy(dj.dir, dirvn, 11);
}
fs->wflag = 1;
res = sync_fs(fs);
}
}
}
}
}
LEAVE_FF(fs, res);
} | /*-----------------------------------------------------------------------*/
/* Set Volume Label */
/*-----------------------------------------------------------------------*/ | https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/fat/source/ff.c#L5445-L5553 | 83d3b29cbfc74e8f76f48f8782646c8e464055b2 |
teddycloud | github_2023 | toniebox-reverse-engineering | c | f_expand | FRESULT f_expand (
FIL* fp, /* Pointer to the file object */
FSIZE_t fsz, /* File size to be expanded to */
BYTE opt /* Operation mode 0:Find and prepare or 1:Find and allocate */
)
{
FRESULT res;
FATFS *fs;
DWORD n, clst, stcl, scl, ncl, tcl, lclst;
res = validate(&fp->obj, &fs); /* Check validity of the file object */
if (res != FR_OK || (res = (FRESULT)fp->err) != FR_OK) LEAVE_FF(fs, res);
if (fsz == 0 || fp->obj.objsize != 0 || !(fp->flag & FA_WRITE)) LEAVE_FF(fs, FR_DENIED);
#if FF_FS_EXFAT
if (fs->fs_type != FS_EXFAT && fsz >= 0x100000000) LEAVE_FF(fs, FR_DENIED); /* Check if in size limit */
#endif
n = (DWORD)fs->csize * SS(fs); /* Cluster size */
tcl = (DWORD)(fsz / n) + ((fsz & (n - 1)) ? 1 : 0); /* Number of clusters required */
stcl = fs->last_clst; lclst = 0;
if (stcl < 2 || stcl >= fs->n_fatent) stcl = 2;
#if FF_FS_EXFAT
if (fs->fs_type == FS_EXFAT) {
scl = find_bitmap(fs, stcl, tcl); /* Find a contiguous cluster block */
if (scl == 0) res = FR_DENIED; /* No contiguous cluster block was found */
if (scl == 0xFFFFFFFF) res = FR_DISK_ERR;
if (res == FR_OK) { /* A contiguous free area is found */
if (opt) { /* Allocate it now */
res = change_bitmap(fs, scl, tcl, 1); /* Mark the cluster block 'in use' */
lclst = scl + tcl - 1;
} else { /* Set it as suggested point for next allocation */
lclst = scl - 1;
}
}
} else
#endif
{
scl = clst = stcl; ncl = 0;
for (;;) { /* Find a contiguous cluster block */
n = get_fat(&fp->obj, clst);
if (++clst >= fs->n_fatent) clst = 2;
if (n == 1) {
res = FR_INT_ERR; break;
}
if (n == 0xFFFFFFFF) {
res = FR_DISK_ERR; break;
}
if (n == 0) { /* Is it a free cluster? */
if (++ncl == tcl) break; /* Break if a contiguous cluster block is found */
} else {
scl = clst; ncl = 0; /* Not a free cluster */
}
if (clst == stcl) { /* No contiguous cluster? */
res = FR_DENIED; break;
}
}
if (res == FR_OK) { /* A contiguous free area is found */
if (opt) { /* Allocate it now */
for (clst = scl, n = tcl; n; clst++, n--) { /* Create a cluster chain on the FAT */
res = put_fat(fs, clst, (n == 1) ? 0xFFFFFFFF : clst + 1);
if (res != FR_OK) break;
lclst = clst;
}
} else { /* Set it as suggested point for next allocation */
lclst = scl - 1;
}
}
}
if (res == FR_OK) {
fs->last_clst = lclst; /* Set suggested start cluster to start next */
if (opt) { /* Is it allocated now? */
fp->obj.sclust = scl; /* Update object allocation information */
fp->obj.objsize = fsz;
if (FF_FS_EXFAT) fp->obj.stat = 2; /* Set status 'contiguous chain' */
fp->flag |= FA_MODIFIED;
if (fs->free_clst <= fs->n_fatent - 2) { /* Update FSINFO */
fs->free_clst -= tcl;
fs->fsi_flag |= 1;
}
}
}
LEAVE_FF(fs, res);
} | /*-----------------------------------------------------------------------*/
/* Allocate a Contiguous Blocks to the File */
/*-----------------------------------------------------------------------*/ | https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/fat/source/ff.c#L5565-L5650 | 83d3b29cbfc74e8f76f48f8782646c8e464055b2 |
teddycloud | github_2023 | toniebox-reverse-engineering | c | f_forward | FRESULT f_forward (
FIL* fp, /* Pointer to the file object */
UINT (*func)(const BYTE*,UINT), /* Pointer to the streaming function */
UINT btf, /* Number of bytes to forward */
UINT* bf /* Pointer to number of bytes forwarded */
)
{
FRESULT res;
FATFS *fs;
DWORD clst;
LBA_t sect;
FSIZE_t remain;
UINT rcnt, csect;
BYTE *dbuf;
*bf = 0; /* Clear transfer byte counter */
res = validate(&fp->obj, &fs); /* Check validity of the file object */
if (res != FR_OK || (res = (FRESULT)fp->err) != FR_OK) LEAVE_FF(fs, res);
if (!(fp->flag & FA_READ)) LEAVE_FF(fs, FR_DENIED); /* Check access mode */
remain = fp->obj.objsize - fp->fptr;
if (btf > remain) btf = (UINT)remain; /* Truncate btf by remaining bytes */
for ( ; btf > 0 && (*func)(0, 0); fp->fptr += rcnt, *bf += rcnt, btf -= rcnt) { /* Repeat until all data transferred or stream goes busy */
csect = (UINT)(fp->fptr / SS(fs) & (fs->csize - 1)); /* Sector offset in the cluster */
if (fp->fptr % SS(fs) == 0) { /* On the sector boundary? */
if (csect == 0) { /* On the cluster boundary? */
clst = (fp->fptr == 0) ? /* On the top of the file? */
fp->obj.sclust : get_fat(&fp->obj, fp->clust);
if (clst <= 1) ABORT(fs, FR_INT_ERR);
if (clst == 0xFFFFFFFF) ABORT(fs, FR_DISK_ERR);
fp->clust = clst; /* Update current cluster */
}
}
sect = clst2sect(fs, fp->clust); /* Get current data sector */
if (sect == 0) ABORT(fs, FR_INT_ERR);
sect += csect;
#if FF_FS_TINY
if (move_window(fs, sect) != FR_OK) ABORT(fs, FR_DISK_ERR); /* Move sector window to the file data */
dbuf = fs->win;
#else
if (fp->sect != sect) { /* Fill sector cache with file data */
#if !FF_FS_READONLY
if (fp->flag & FA_DIRTY) { /* Write-back dirty sector cache */
if (disk_write(fs->pdrv, fp->buf, fp->sect, 1) != RES_OK) ABORT(fs, FR_DISK_ERR);
fp->flag &= (BYTE)~FA_DIRTY;
}
#endif
if (disk_read(fs->pdrv, fp->buf, sect, 1) != RES_OK) ABORT(fs, FR_DISK_ERR);
}
dbuf = fp->buf;
#endif
fp->sect = sect;
rcnt = SS(fs) - (UINT)fp->fptr % SS(fs); /* Number of bytes remains in the sector */
if (rcnt > btf) rcnt = btf; /* Clip it by btr if needed */
rcnt = (*func)(dbuf + ((UINT)fp->fptr % SS(fs)), rcnt); /* Forward the file data */
if (rcnt == 0) ABORT(fs, FR_INT_ERR);
}
LEAVE_FF(fs, FR_OK);
} | /*-----------------------------------------------------------------------*/
/* Forward Data to the Stream Directly */
/*-----------------------------------------------------------------------*/ | https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/fat/source/ff.c#L5661-L5722 | 83d3b29cbfc74e8f76f48f8782646c8e464055b2 |
teddycloud | github_2023 | toniebox-reverse-engineering | c | create_partition | static FRESULT create_partition (
BYTE drv, /* Physical drive number */
const LBA_t plst[], /* Partition list */
BYTE sys, /* System ID for each partition (for only MBR) */
BYTE *buf /* Working buffer for a sector */
)
{
UINT i, cy;
LBA_t sz_drv;
DWORD sz_drv32, nxt_alloc32, sz_part32;
BYTE *pte;
BYTE hd, n_hd, sc, n_sc;
/* Get physical drive size */
if (disk_ioctl(drv, GET_SECTOR_COUNT, &sz_drv) != RES_OK) return FR_DISK_ERR;
#if FF_LBA64
if (sz_drv >= FF_MIN_GPT) { /* Create partitions in GPT format */
WORD ss;
UINT sz_ptbl, pi, si, ofs;
DWORD bcc, rnd, align;
QWORD nxt_alloc, sz_part, sz_pool, top_bpt;
static const BYTE gpt_mbr[16] = {0x00, 0x00, 0x02, 0x00, 0xEE, 0xFE, 0xFF, 0x00, 0x01, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF};
#if FF_MAX_SS != FF_MIN_SS
if (disk_ioctl(drv, GET_SECTOR_SIZE, &ss) != RES_OK) return FR_DISK_ERR; /* Get sector size */
if (ss > FF_MAX_SS || ss < FF_MIN_SS || (ss & (ss - 1))) return FR_DISK_ERR;
#else
ss = FF_MAX_SS;
#endif
rnd = (DWORD)sz_drv + GET_FATTIME(); /* Random seed */
align = GPT_ALIGN / ss; /* Partition alignment for GPT [sector] */
sz_ptbl = GPT_ITEMS * SZ_GPTE / ss; /* Size of partition table [sector] */
top_bpt = sz_drv - sz_ptbl - 1; /* Backup partition table start sector */
nxt_alloc = 2 + sz_ptbl; /* First allocatable sector */
sz_pool = top_bpt - nxt_alloc; /* Size of allocatable area */
bcc = 0xFFFFFFFF; sz_part = 1;
pi = si = 0; /* partition table index, size table index */
do {
if (pi * SZ_GPTE % ss == 0) memset(buf, 0, ss); /* Clean the buffer if needed */
if (sz_part != 0) { /* Is the size table not termintated? */
nxt_alloc = (nxt_alloc + align - 1) & ((QWORD)0 - align); /* Align partition start */
sz_part = plst[si++]; /* Get a partition size */
if (sz_part <= 100) { /* Is the size in percentage? */
sz_part = sz_pool * sz_part / 100;
sz_part = (sz_part + align - 1) & ((QWORD)0 - align); /* Align partition end (only if in percentage) */
}
if (nxt_alloc + sz_part > top_bpt) { /* Clip the size at end of the pool */
sz_part = (nxt_alloc < top_bpt) ? top_bpt - nxt_alloc : 0;
}
}
if (sz_part != 0) { /* Add a partition? */
ofs = pi * SZ_GPTE % ss;
memcpy(buf + ofs + GPTE_PtGuid, GUID_MS_Basic, 16); /* Set partition GUID (Microsoft Basic Data) */
rnd = make_rand(rnd, buf + ofs + GPTE_UpGuid, 16); /* Set unique partition GUID */
st_qword(buf + ofs + GPTE_FstLba, nxt_alloc); /* Set partition start sector */
st_qword(buf + ofs + GPTE_LstLba, nxt_alloc + sz_part - 1); /* Set partition end sector */
nxt_alloc += sz_part; /* Next allocatable sector */
}
if ((pi + 1) * SZ_GPTE % ss == 0) { /* Write the buffer if it is filled up */
for (i = 0; i < ss; bcc = crc32(bcc, buf[i++])) ; /* Calculate table check sum */
if (disk_write(drv, buf, 2 + pi * SZ_GPTE / ss, 1) != RES_OK) return FR_DISK_ERR; /* Write to primary table */
if (disk_write(drv, buf, top_bpt + pi * SZ_GPTE / ss, 1) != RES_OK) return FR_DISK_ERR; /* Write to secondary table */
}
} while (++pi < GPT_ITEMS);
/* Create primary GPT header */
memset(buf, 0, ss);
memcpy(buf + GPTH_Sign, "EFI PART" "\0\0\1\0" "\x5C\0\0", 16); /* Signature, version (1.0) and size (92) */
st_dword(buf + GPTH_PtBcc, ~bcc); /* Table check sum */
st_qword(buf + GPTH_CurLba, 1); /* LBA of this header */
st_qword(buf + GPTH_BakLba, sz_drv - 1); /* LBA of secondary header */
st_qword(buf + GPTH_FstLba, 2 + sz_ptbl); /* LBA of first allocatable sector */
st_qword(buf + GPTH_LstLba, top_bpt - 1); /* LBA of last allocatable sector */
st_dword(buf + GPTH_PteSize, SZ_GPTE); /* Size of a table entry */
st_dword(buf + GPTH_PtNum, GPT_ITEMS); /* Number of table entries */
st_dword(buf + GPTH_PtOfs, 2); /* LBA of this table */
rnd = make_rand(rnd, buf + GPTH_DskGuid, 16); /* Disk GUID */
for (i = 0, bcc= 0xFFFFFFFF; i < 92; bcc = crc32(bcc, buf[i++])) ; /* Calculate header check sum */
st_dword(buf + GPTH_Bcc, ~bcc); /* Header check sum */
if (disk_write(drv, buf, 1, 1) != RES_OK) return FR_DISK_ERR;
/* Create secondary GPT header */
st_qword(buf + GPTH_CurLba, sz_drv - 1); /* LBA of this header */
st_qword(buf + GPTH_BakLba, 1); /* LBA of primary header */
st_qword(buf + GPTH_PtOfs, top_bpt); /* LBA of this table */
st_dword(buf + GPTH_Bcc, 0);
for (i = 0, bcc= 0xFFFFFFFF; i < 92; bcc = crc32(bcc, buf[i++])) ; /* Calculate header check sum */
st_dword(buf + GPTH_Bcc, ~bcc); /* Header check sum */
if (disk_write(drv, buf, sz_drv - 1, 1) != RES_OK) return FR_DISK_ERR;
/* Create protective MBR */
memset(buf, 0, ss);
memcpy(buf + MBR_Table, gpt_mbr, 16); /* Create a GPT partition */
st_word(buf + BS_55AA, 0xAA55);
if (disk_write(drv, buf, 0, 1) != RES_OK) return FR_DISK_ERR;
} else
#endif
{ /* Create partitions in MBR format */
sz_drv32 = (DWORD)sz_drv;
n_sc = N_SEC_TRACK; /* Determine drive CHS without any consideration of the drive geometry */
for (n_hd = 8; n_hd != 0 && sz_drv32 / n_hd / n_sc > 1024; n_hd *= 2) ;
if (n_hd == 0) n_hd = 255; /* Number of heads needs to be <256 */
memset(buf, 0, FF_MAX_SS); /* Clear MBR */
pte = buf + MBR_Table; /* Partition table in the MBR */
for (i = 0, nxt_alloc32 = n_sc; i < 4 && nxt_alloc32 != 0 && nxt_alloc32 < sz_drv32; i++, nxt_alloc32 += sz_part32) {
sz_part32 = (DWORD)plst[i]; /* Get partition size */
if (sz_part32 <= 100) sz_part32 = (sz_part32 == 100) ? sz_drv32 : sz_drv32 / 100 * sz_part32; /* Size in percentage? */
if (nxt_alloc32 + sz_part32 > sz_drv32 || nxt_alloc32 + sz_part32 < nxt_alloc32) sz_part32 = sz_drv32 - nxt_alloc32; /* Clip at drive size */
if (sz_part32 == 0) break; /* End of table or no sector to allocate? */
st_dword(pte + PTE_StLba, nxt_alloc32); /* Start LBA */
st_dword(pte + PTE_SizLba, sz_part32); /* Number of sectors */
pte[PTE_System] = sys; /* System type */
cy = (UINT)(nxt_alloc32 / n_sc / n_hd); /* Start cylinder */
hd = (BYTE)(nxt_alloc32 / n_sc % n_hd); /* Start head */
sc = (BYTE)(nxt_alloc32 % n_sc + 1); /* Start sector */
pte[PTE_StHead] = hd;
pte[PTE_StSec] = (BYTE)((cy >> 2 & 0xC0) | sc);
pte[PTE_StCyl] = (BYTE)cy;
cy = (UINT)((nxt_alloc32 + sz_part32 - 1) / n_sc / n_hd); /* End cylinder */
hd = (BYTE)((nxt_alloc32 + sz_part32 - 1) / n_sc % n_hd); /* End head */
sc = (BYTE)((nxt_alloc32 + sz_part32 - 1) % n_sc + 1); /* End sector */
pte[PTE_EdHead] = hd;
pte[PTE_EdSec] = (BYTE)((cy >> 2 & 0xC0) | sc);
pte[PTE_EdCyl] = (BYTE)cy;
pte += SZ_PTE; /* Next entry */
}
st_word(buf + BS_55AA, 0xAA55); /* MBR signature */
if (disk_write(drv, buf, 0, 1) != RES_OK) return FR_DISK_ERR; /* Write it to the MBR */
}
return FR_OK;
} | /* Create partitions on the physical drive in format of MBR or GPT */ | https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/fat/source/ff.c#L5739-L5878 | 83d3b29cbfc74e8f76f48f8782646c8e464055b2 |
teddycloud | github_2023 | toniebox-reverse-engineering | c | f_fdisk | FRESULT f_fdisk (
BYTE pdrv, /* Physical drive number */
const LBA_t ptbl[], /* Pointer to the size table for each partitions */
void* work /* Pointer to the working buffer (null: use heap memory) */
)
{
BYTE *buf = (BYTE*)work;
DSTATUS stat;
FRESULT res;
/* Initialize the physical drive */
stat = disk_initialize(pdrv);
if (stat & STA_NOINIT) return FR_NOT_READY;
if (stat & STA_PROTECT) return FR_WRITE_PROTECTED;
#if FF_USE_LFN == 3
if (!buf) buf = ff_memalloc(FF_MAX_SS); /* Use heap memory for working buffer */
#endif
if (!buf) return FR_NOT_ENOUGH_CORE;
res = create_partition(pdrv, ptbl, 0x07, buf); /* Create partitions (system ID is temporary setting and determined by f_mkfs) */
LEAVE_MKFS(res);
} | /*-----------------------------------------------------------------------*/
/* Create Partition Table on the Physical Drive */
/*-----------------------------------------------------------------------*/ | https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/fat/source/ff.c#L6386-L6410 | 83d3b29cbfc74e8f76f48f8782646c8e464055b2 |
teddycloud | github_2023 | toniebox-reverse-engineering | c | putc_bfd | static void putc_bfd (putbuff* pb, TCHAR c)
{
UINT n;
int i, nc;
#if FF_USE_LFN && FF_LFN_UNICODE
WCHAR hs, wc;
#if FF_LFN_UNICODE == 2
DWORD dc;
const TCHAR* tp;
#endif
#endif
if (FF_USE_STRFUNC == 2 && c == '\n') { /* LF -> CRLF conversion */
putc_bfd(pb, '\r');
}
i = pb->idx; /* Write index of pb->buf[] */
if (i < 0) return; /* In write error? */
nc = pb->nchr; /* Write unit counter */
#if FF_USE_LFN && FF_LFN_UNICODE
#if FF_LFN_UNICODE == 1 /* UTF-16 input */
if (IsSurrogateH(c)) { /* Is this a high-surrogate? */
pb->hs = c; return; /* Save it for next */
}
hs = pb->hs; pb->hs = 0;
if (hs != 0) { /* Is there a leading high-surrogate? */
if (!IsSurrogateL(c)) hs = 0; /* Discard high-surrogate if not a surrogate pair */
} else {
if (IsSurrogateL(c)) return; /* Discard stray low-surrogate */
}
wc = c;
#elif FF_LFN_UNICODE == 2 /* UTF-8 input */
for (;;) {
if (pb->ct == 0) { /* Out of multi-byte sequence? */
pb->bs[pb->wi = 0] = (BYTE)c; /* Save 1st byte */
if ((BYTE)c < 0x80) break; /* Single byte code? */
if (((BYTE)c & 0xE0) == 0xC0) pb->ct = 1; /* 2-byte sequence? */
if (((BYTE)c & 0xF0) == 0xE0) pb->ct = 2; /* 3-byte sequence? */
if (((BYTE)c & 0xF8) == 0xF0) pb->ct = 3; /* 4-byte sequence? */
return; /* Wrong leading byte (discard it) */
} else { /* In the multi-byte sequence */
if (((BYTE)c & 0xC0) != 0x80) { /* Broken sequence? */
pb->ct = 0; continue; /* Discard the sequense */
}
pb->bs[++pb->wi] = (BYTE)c; /* Save the trailing byte */
if (--pb->ct == 0) break; /* End of the sequence? */
return;
}
}
tp = (const TCHAR*)pb->bs;
dc = tchar2uni(&tp); /* UTF-8 ==> UTF-16 */
if (dc == 0xFFFFFFFF) return; /* Wrong code? */
hs = (WCHAR)(dc >> 16);
wc = (WCHAR)dc;
#elif FF_LFN_UNICODE == 3 /* UTF-32 input */
if (IsSurrogate(c) || c >= 0x110000) return; /* Discard invalid code */
if (c >= 0x10000) { /* Out of BMP? */
hs = (WCHAR)(0xD800 | ((c >> 10) - 0x40)); /* Make high surrogate */
wc = 0xDC00 | (c & 0x3FF); /* Make low surrogate */
} else {
hs = 0;
wc = (WCHAR)c;
}
#endif
/* A code point in UTF-16 is available in hs and wc */
#if FF_STRF_ENCODE == 1 /* Write a code point in UTF-16LE */
if (hs != 0) { /* Surrogate pair? */
st_word(&pb->buf[i], hs);
i += 2;
nc++;
}
st_word(&pb->buf[i], wc);
i += 2;
#elif FF_STRF_ENCODE == 2 /* Write a code point in UTF-16BE */
if (hs != 0) { /* Surrogate pair? */
pb->buf[i++] = (BYTE)(hs >> 8);
pb->buf[i++] = (BYTE)hs;
nc++;
}
pb->buf[i++] = (BYTE)(wc >> 8);
pb->buf[i++] = (BYTE)wc;
#elif FF_STRF_ENCODE == 3 /* Write a code point in UTF-8 */
if (hs != 0) { /* 4-byte sequence? */
nc += 3;
hs = (hs & 0x3FF) + 0x40;
pb->buf[i++] = (BYTE)(0xF0 | hs >> 8);
pb->buf[i++] = (BYTE)(0x80 | (hs >> 2 & 0x3F));
pb->buf[i++] = (BYTE)(0x80 | (hs & 3) << 4 | (wc >> 6 & 0x0F));
pb->buf[i++] = (BYTE)(0x80 | (wc & 0x3F));
} else {
if (wc < 0x80) { /* Single byte? */
pb->buf[i++] = (BYTE)wc;
} else {
if (wc < 0x800) { /* 2-byte sequence? */
nc += 1;
pb->buf[i++] = (BYTE)(0xC0 | wc >> 6);
} else { /* 3-byte sequence */
nc += 2;
pb->buf[i++] = (BYTE)(0xE0 | wc >> 12);
pb->buf[i++] = (BYTE)(0x80 | (wc >> 6 & 0x3F));
}
pb->buf[i++] = (BYTE)(0x80 | (wc & 0x3F));
}
}
#else /* Write a code point in ANSI/OEM */
if (hs != 0) return;
wc = ff_uni2oem(wc, CODEPAGE); /* UTF-16 ==> ANSI/OEM */
if (wc == 0) return;
if (wc >= 0x100) {
pb->buf[i++] = (BYTE)(wc >> 8); nc++;
}
pb->buf[i++] = (BYTE)wc;
#endif
#else /* ANSI/OEM input (without re-encoding) */
pb->buf[i++] = (BYTE)c;
#endif
if (i >= (int)(sizeof pb->buf) - 4) { /* Write buffered characters to the file */
f_write(pb->fp, pb->buf, (UINT)i, &n);
i = (n == (UINT)i) ? 0 : -1;
}
pb->idx = i;
pb->nchr = nc + 1;
} | /* Buffered file write with code conversion */ | https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/fat/source/ff.c#L6578-L6704 | 83d3b29cbfc74e8f76f48f8782646c8e464055b2 |
teddycloud | github_2023 | toniebox-reverse-engineering | c | putc_flush | static int putc_flush (putbuff* pb)
{
UINT nw;
if ( pb->idx >= 0 /* Flush buffered characters to the file */
&& f_write(pb->fp, pb->buf, (UINT)pb->idx, &nw) == FR_OK
&& (UINT)pb->idx == nw) return pb->nchr;
return -1;
} | /* Flush remaining characters in the buffer */ | https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/fat/source/ff.c#L6709-L6717 | 83d3b29cbfc74e8f76f48f8782646c8e464055b2 |
teddycloud | github_2023 | toniebox-reverse-engineering | c | putc_init | static void putc_init (putbuff* pb, FIL* fp)
{
memset(pb, 0, sizeof (putbuff));
pb->fp = fp;
} | /* Initialize write buffer */ | https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/fat/source/ff.c#L6722-L6726 | 83d3b29cbfc74e8f76f48f8782646c8e464055b2 |
teddycloud | github_2023 | toniebox-reverse-engineering | c | f_puts | int f_puts (
const TCHAR* str, /* Pointer to the string to be output */
FIL* fp /* Pointer to the file object */
)
{
putbuff pb;
putc_init(&pb, fp);
while (*str) putc_bfd(&pb, *str++); /* Put the string */
return putc_flush(&pb);
} | /*-----------------------------------------------------------------------*/
/* Put a String to the File */
/*-----------------------------------------------------------------------*/ | https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/fat/source/ff.c#L6750-L6761 | 83d3b29cbfc74e8f76f48f8782646c8e464055b2 |
teddycloud | github_2023 | toniebox-reverse-engineering | c | f_printf | int f_printf (
FIL* fp, /* Pointer to the file object */
const TCHAR* fmt, /* Pointer to the format string */
... /* Optional arguments... */
)
{
va_list arp;
putbuff pb;
UINT i, j, w, f, r;
int prec;
#if FF_PRINT_LLI && FF_INTDEF == 2
QWORD v;
#else
DWORD v;
#endif
TCHAR *tp;
TCHAR tc, pad;
TCHAR nul = 0;
char d, str[SZ_NUM_BUF];
putc_init(&pb, fp);
va_start(arp, fmt);
for (;;) {
tc = *fmt++;
if (tc == 0) break; /* End of format string */
if (tc != '%') { /* Not an escape character (pass-through) */
putc_bfd(&pb, tc);
continue;
}
f = w = 0; pad = ' '; prec = -1; /* Initialize parms */
tc = *fmt++;
if (tc == '0') { /* Flag: '0' padded */
pad = '0'; tc = *fmt++;
} else if (tc == '-') { /* Flag: Left aligned */
f = 2; tc = *fmt++;
}
if (tc == '*') { /* Minimum width from an argument */
w = va_arg(arp, int);
tc = *fmt++;
} else {
while (IsDigit(tc)) { /* Minimum width */
w = w * 10 + tc - '0';
tc = *fmt++;
}
}
if (tc == '.') { /* Precision */
tc = *fmt++;
if (tc == '*') { /* Precision from an argument */
prec = va_arg(arp, int);
tc = *fmt++;
} else {
prec = 0;
while (IsDigit(tc)) { /* Precision */
prec = prec * 10 + tc - '0';
tc = *fmt++;
}
}
}
if (tc == 'l') { /* Size: long int */
f |= 4; tc = *fmt++;
#if FF_PRINT_LLI && FF_INTDEF == 2
if (tc == 'l') { /* Size: long long int */
f |= 8; tc = *fmt++;
}
#endif
}
if (tc == 0) break; /* End of format string */
switch (tc) { /* Atgument type is... */
case 'b': /* Unsigned binary */
r = 2; break;
case 'o': /* Unsigned octal */
r = 8; break;
case 'd': /* Signed decimal */
case 'u': /* Unsigned decimal */
r = 10; break;
case 'x': /* Unsigned hexadecimal (lower case) */
case 'X': /* Unsigned hexadecimal (upper case) */
r = 16; break;
case 'c': /* Character */
putc_bfd(&pb, (TCHAR)va_arg(arp, int));
continue;
case 's': /* String */
tp = va_arg(arp, TCHAR*); /* Get a pointer argument */
if (!tp) tp = &nul; /* Null ptr generates a null string */
for (j = 0; tp[j]; j++) ; /* j = tcslen(tp) */
if (prec >= 0 && j > (UINT)prec) j = prec; /* Limited length of string body */
for ( ; !(f & 2) && j < w; j++) putc_bfd(&pb, pad); /* Left pads */
while (*tp && prec--) putc_bfd(&pb, *tp++); /* Body */
while (j++ < w) putc_bfd(&pb, ' '); /* Right pads */
continue;
#if FF_PRINT_FLOAT && FF_INTDEF == 2
case 'f': /* Floating point (decimal) */
case 'e': /* Floating point (e) */
case 'E': /* Floating point (E) */
ftoa(str, va_arg(arp, double), prec, tc); /* Make a floating point string */
for (j = strlen(str); !(f & 2) && j < w; j++) putc_bfd(&pb, pad); /* Left pads */
for (i = 0; str[i]; putc_bfd(&pb, str[i++])) ; /* Body */
while (j++ < w) putc_bfd(&pb, ' '); /* Right pads */
continue;
#endif
default: /* Unknown type (pass-through) */
putc_bfd(&pb, tc); continue;
}
/* Get an integer argument and put it in numeral */
#if FF_PRINT_LLI && FF_INTDEF == 2
if (f & 8) { /* long long argument? */
v = (QWORD)va_arg(arp, long long);
} else if (f & 4) { /* long argument? */
v = (tc == 'd') ? (QWORD)(long long)va_arg(arp, long) : (QWORD)va_arg(arp, unsigned long);
} else { /* int/short/char argument */
v = (tc == 'd') ? (QWORD)(long long)va_arg(arp, int) : (QWORD)va_arg(arp, unsigned int);
}
if (tc == 'd' && (v & 0x8000000000000000)) { /* Negative value? */
v = 0 - v; f |= 1;
}
#else
if (f & 4) { /* long argument? */
v = (DWORD)va_arg(arp, long);
} else { /* int/short/char argument */
v = (tc == 'd') ? (DWORD)(long)va_arg(arp, int) : (DWORD)va_arg(arp, unsigned int);
}
if (tc == 'd' && (v & 0x80000000)) { /* Negative value? */
v = 0 - v; f |= 1;
}
#endif
i = 0;
do { /* Make an integer number string */
d = (char)(v % r); v /= r;
if (d > 9) d += (tc == 'x') ? 0x27 : 0x07;
str[i++] = d + '0';
} while (v && i < SZ_NUM_BUF);
if (f & 1) str[i++] = '-'; /* Sign */
/* Write it */
for (j = i; !(f & 2) && j < w; j++) { /* Left pads */
putc_bfd(&pb, pad);
}
do { /* Body */
putc_bfd(&pb, (TCHAR)str[--i]);
} while (i);
while (j++ < w) { /* Right pads */
putc_bfd(&pb, ' ');
}
}
va_end(arp);
return putc_flush(&pb);
} | /* FF_PRINT_FLOAT && FF_INTDEF == 2 */ | https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/fat/source/ff.c#L6893-L7049 | 83d3b29cbfc74e8f76f48f8782646c8e464055b2 |
teddycloud | github_2023 | toniebox-reverse-engineering | c | f_setcp | FRESULT f_setcp (
WORD cp /* Value to be set as active code page */
)
{
static const WORD validcp[22] = { 437, 720, 737, 771, 775, 850, 852, 855, 857, 860, 861, 862, 863, 864, 865, 866, 869, 932, 936, 949, 950, 0};
static const BYTE *const tables[22] = {Ct437, Ct720, Ct737, Ct771, Ct775, Ct850, Ct852, Ct855, Ct857, Ct860, Ct861, Ct862, Ct863, Ct864, Ct865, Ct866, Ct869, Dc932, Dc936, Dc949, Dc950, 0};
UINT i;
for (i = 0; validcp[i] != 0 && validcp[i] != cp; i++) ; /* Find the code page */
if (validcp[i] != cp) return FR_INVALID_PARAMETER; /* Not found? */
CodePage = cp;
if (cp >= 900) { /* DBCS */
ExCvt = 0;
DbcTbl = tables[i];
} else { /* SBCS */
ExCvt = tables[i];
DbcTbl = 0;
}
return FR_OK;
} | /*-----------------------------------------------------------------------*/
/* Set Active Codepage for the Path Name */
/*-----------------------------------------------------------------------*/ | https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/fat/source/ff.c#L7061-L7082 | 83d3b29cbfc74e8f76f48f8782646c8e464055b2 |
teddycloud | github_2023 | toniebox-reverse-engineering | c | ff_mutex_create | int ff_mutex_create ( /* Returns 1:Function succeeded or 0:Could not create the mutex */
int vol /* Mutex ID: Volume mutex (0 to FF_VOLUMES - 1) or system mutex (FF_VOLUMES) */
)
{
#if OS_TYPE == 0 /* Win32 */
Mutex[vol] = CreateMutex(NULL, FALSE, NULL);
return (int)(Mutex[vol] != INVALID_HANDLE_VALUE);
#elif OS_TYPE == 1 /* uITRON */
T_CMTX cmtx = {TA_TPRI,1};
Mutex[vol] = acre_mtx(&cmtx);
return (int)(Mutex[vol] > 0);
#elif OS_TYPE == 2 /* uC/OS-II */
OS_ERR err;
Mutex[vol] = OSMutexCreate(0, &err);
return (int)(err == OS_NO_ERR);
#elif OS_TYPE == 3 /* FreeRTOS */
Mutex[vol] = xSemaphoreCreateMutex();
return (int)(Mutex[vol] != NULL);
#elif OS_TYPE == 4 /* CMSIS-RTOS */
osMutexDef(cmsis_os_mutex);
Mutex[vol] = osMutexCreate(osMutex(cmsis_os_mutex));
return (int)(Mutex[vol] != NULL);
#endif
} | /*------------------------------------------------------------------------*/
/* Create a Mutex */
/*------------------------------------------------------------------------*/
/* This function is called in f_mount function to create a new mutex
/ or semaphore for the volume. When a 0 is returned, the f_mount function
/ fails with FR_INT_ERR.
*/ | https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/fat/source/ffsystem.c#L79-L110 | 83d3b29cbfc74e8f76f48f8782646c8e464055b2 |
teddycloud | github_2023 | toniebox-reverse-engineering | c | ff_mutex_delete | void ff_mutex_delete ( /* Returns 1:Function succeeded or 0:Could not delete due to an error */
int vol /* Mutex ID: Volume mutex (0 to FF_VOLUMES - 1) or system mutex (FF_VOLUMES) */
)
{
#if OS_TYPE == 0 /* Win32 */
CloseHandle(Mutex[vol]);
#elif OS_TYPE == 1 /* uITRON */
del_mtx(Mutex[vol]);
#elif OS_TYPE == 2 /* uC/OS-II */
OS_ERR err;
OSMutexDel(Mutex[vol], OS_DEL_ALWAYS, &err);
#elif OS_TYPE == 3 /* FreeRTOS */
vSemaphoreDelete(Mutex[vol]);
#elif OS_TYPE == 4 /* CMSIS-RTOS */
osMutexDelete(Mutex[vol]);
#endif
} | /*------------------------------------------------------------------------*/
/* Delete a Mutex */
/*------------------------------------------------------------------------*/
/* This function is called in f_mount function to delete a mutex or
/ semaphore of the volume created with ff_mutex_create function.
*/ | https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/fat/source/ffsystem.c#L120-L142 | 83d3b29cbfc74e8f76f48f8782646c8e464055b2 |
teddycloud | github_2023 | toniebox-reverse-engineering | c | ff_mutex_take | int ff_mutex_take ( /* Returns 1:Succeeded or 0:Timeout */
int vol /* Mutex ID: Volume mutex (0 to FF_VOLUMES - 1) or system mutex (FF_VOLUMES) */
)
{
#if OS_TYPE == 0 /* Win32 */
return (int)(WaitForSingleObject(Mutex[vol], FF_FS_TIMEOUT) == WAIT_OBJECT_0);
#elif OS_TYPE == 1 /* uITRON */
return (int)(tloc_mtx(Mutex[vol], FF_FS_TIMEOUT) == E_OK);
#elif OS_TYPE == 2 /* uC/OS-II */
OS_ERR err;
OSMutexPend(Mutex[vol], FF_FS_TIMEOUT, &err));
return (int)(err == OS_NO_ERR);
#elif OS_TYPE == 3 /* FreeRTOS */
return (int)(xSemaphoreTake(Mutex[vol], FF_FS_TIMEOUT) == pdTRUE);
#elif OS_TYPE == 4 /* CMSIS-RTOS */
return (int)(osMutexWait(Mutex[vol], FF_FS_TIMEOUT) == osOK);
#endif
} | /*------------------------------------------------------------------------*/
/* Request a Grant to Access the Volume */
/*------------------------------------------------------------------------*/
/* This function is called on enter file functions to lock the volume.
/ When a 0 is returned, the file function fails with FR_TIMEOUT.
*/ | https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/fat/source/ffsystem.c#L152-L175 | 83d3b29cbfc74e8f76f48f8782646c8e464055b2 |
teddycloud | github_2023 | toniebox-reverse-engineering | c | ff_mutex_give | void ff_mutex_give (
int vol /* Mutex ID: Volume mutex (0 to FF_VOLUMES - 1) or system mutex (FF_VOLUMES) */
)
{
#if OS_TYPE == 0 /* Win32 */
ReleaseMutex(Mutex[vol]);
#elif OS_TYPE == 1 /* uITRON */
unl_mtx(Mutex[vol]);
#elif OS_TYPE == 2 /* uC/OS-II */
OSMutexPost(Mutex[vol]);
#elif OS_TYPE == 3 /* FreeRTOS */
xSemaphoreGive(Mutex[vol]);
#elif OS_TYPE == 4 /* CMSIS-RTOS */
osMutexRelease(Mutex[vol]);
#endif
} | /*------------------------------------------------------------------------*/
/* Release a Grant to Access the Volume */
/*------------------------------------------------------------------------*/
/* This function is called on leave file functions to unlock the volume.
*/ | https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/fat/source/ffsystem.c#L185-L205 | 83d3b29cbfc74e8f76f48f8782646c8e464055b2 |
teddycloud | github_2023 | toniebox-reverse-engineering | c | ff_wtoupper | DWORD ff_wtoupper ( /* Returns up-converted code point */
DWORD uni /* Unicode code point to be up-converted */
)
{
const WORD* p;
WORD uc, bc, nc, cmd;
static const WORD cvt1[] = { /* Compressed up conversion table for U+0000 - U+0FFF */
/* Basic Latin */
0x0061,0x031A,
/* Latin-1 Supplement */
0x00E0,0x0317,
0x00F8,0x0307,
0x00FF,0x0001,0x0178,
/* Latin Extended-A */
0x0100,0x0130,
0x0132,0x0106,
0x0139,0x0110,
0x014A,0x012E,
0x0179,0x0106,
/* Latin Extended-B */
0x0180,0x004D,0x0243,0x0181,0x0182,0x0182,0x0184,0x0184,0x0186,0x0187,0x0187,0x0189,0x018A,0x018B,0x018B,0x018D,0x018E,0x018F,0x0190,0x0191,0x0191,0x0193,0x0194,0x01F6,0x0196,0x0197,0x0198,0x0198,0x023D,0x019B,0x019C,0x019D,0x0220,0x019F,0x01A0,0x01A0,0x01A2,0x01A2,0x01A4,0x01A4,0x01A6,0x01A7,0x01A7,0x01A9,0x01AA,0x01AB,0x01AC,0x01AC,0x01AE,0x01AF,0x01AF,0x01B1,0x01B2,0x01B3,0x01B3,0x01B5,0x01B5,0x01B7,0x01B8,0x01B8,0x01BA,0x01BB,0x01BC,0x01BC,0x01BE,0x01F7,0x01C0,0x01C1,0x01C2,0x01C3,0x01C4,0x01C5,0x01C4,0x01C7,0x01C8,0x01C7,0x01CA,0x01CB,0x01CA,
0x01CD,0x0110,
0x01DD,0x0001,0x018E,
0x01DE,0x0112,
0x01F3,0x0003,0x01F1,0x01F4,0x01F4,
0x01F8,0x0128,
0x0222,0x0112,
0x023A,0x0009,0x2C65,0x023B,0x023B,0x023D,0x2C66,0x023F,0x0240,0x0241,0x0241,
0x0246,0x010A,
/* IPA Extensions */
0x0253,0x0040,0x0181,0x0186,0x0255,0x0189,0x018A,0x0258,0x018F,0x025A,0x0190,0x025C,0x025D,0x025E,0x025F,0x0193,0x0261,0x0262,0x0194,0x0264,0x0265,0x0266,0x0267,0x0197,0x0196,0x026A,0x2C62,0x026C,0x026D,0x026E,0x019C,0x0270,0x0271,0x019D,0x0273,0x0274,0x019F,0x0276,0x0277,0x0278,0x0279,0x027A,0x027B,0x027C,0x2C64,0x027E,0x027F,0x01A6,0x0281,0x0282,0x01A9,0x0284,0x0285,0x0286,0x0287,0x01AE,0x0244,0x01B1,0x01B2,0x0245,0x028D,0x028E,0x028F,0x0290,0x0291,0x01B7,
/* Greek, Coptic */
0x037B,0x0003,0x03FD,0x03FE,0x03FF,
0x03AC,0x0004,0x0386,0x0388,0x0389,0x038A,
0x03B1,0x0311,
0x03C2,0x0002,0x03A3,0x03A3,
0x03C4,0x0308,
0x03CC,0x0003,0x038C,0x038E,0x038F,
0x03D8,0x0118,
0x03F2,0x000A,0x03F9,0x03F3,0x03F4,0x03F5,0x03F6,0x03F7,0x03F7,0x03F9,0x03FA,0x03FA,
/* Cyrillic */
0x0430,0x0320,
0x0450,0x0710,
0x0460,0x0122,
0x048A,0x0136,
0x04C1,0x010E,
0x04CF,0x0001,0x04C0,
0x04D0,0x0144,
/* Armenian */
0x0561,0x0426,
0x0000 /* EOT */
};
static const WORD cvt2[] = { /* Compressed up conversion table for U+1000 - U+FFFF */
/* Phonetic Extensions */
0x1D7D,0x0001,0x2C63,
/* Latin Extended Additional */
0x1E00,0x0196,
0x1EA0,0x015A,
/* Greek Extended */
0x1F00,0x0608,
0x1F10,0x0606,
0x1F20,0x0608,
0x1F30,0x0608,
0x1F40,0x0606,
0x1F51,0x0007,0x1F59,0x1F52,0x1F5B,0x1F54,0x1F5D,0x1F56,0x1F5F,
0x1F60,0x0608,
0x1F70,0x000E,0x1FBA,0x1FBB,0x1FC8,0x1FC9,0x1FCA,0x1FCB,0x1FDA,0x1FDB,0x1FF8,0x1FF9,0x1FEA,0x1FEB,0x1FFA,0x1FFB,
0x1F80,0x0608,
0x1F90,0x0608,
0x1FA0,0x0608,
0x1FB0,0x0004,0x1FB8,0x1FB9,0x1FB2,0x1FBC,
0x1FCC,0x0001,0x1FC3,
0x1FD0,0x0602,
0x1FE0,0x0602,
0x1FE5,0x0001,0x1FEC,
0x1FF3,0x0001,0x1FFC,
/* Letterlike Symbols */
0x214E,0x0001,0x2132,
/* Number forms */
0x2170,0x0210,
0x2184,0x0001,0x2183,
/* Enclosed Alphanumerics */
0x24D0,0x051A,
0x2C30,0x042F,
/* Latin Extended-C */
0x2C60,0x0102,
0x2C67,0x0106, 0x2C75,0x0102,
/* Coptic */
0x2C80,0x0164,
/* Georgian Supplement */
0x2D00,0x0826,
/* Full-width */
0xFF41,0x031A,
0x0000 /* EOT */
};
if (uni < 0x10000) { /* Is it in BMP? */
uc = (WORD)uni;
p = uc < 0x1000 ? cvt1 : cvt2;
for (;;) {
bc = *p++; /* Get the block base */
if (bc == 0 || uc < bc) break; /* Not matched? */
nc = *p++; cmd = nc >> 8; nc &= 0xFF; /* Get processing command and block size */
if (uc < bc + nc) { /* In the block? */
switch (cmd) {
case 0: uc = p[uc - bc]; break; /* Table conversion */
case 1: uc -= (uc - bc) & 1; break; /* Case pairs */
case 2: uc -= 16; break; /* Shift -16 */
case 3: uc -= 32; break; /* Shift -32 */
case 4: uc -= 48; break; /* Shift -48 */
case 5: uc -= 26; break; /* Shift -26 */
case 6: uc += 8; break; /* Shift +8 */
case 7: uc -= 80; break; /* Shift -80 */
case 8: uc -= 0x1C60; break; /* Shift -0x1C60 */
}
break;
}
if (cmd == 0) p += nc; /* Skip table if needed */
}
uni = uc;
}
return uni;
} | /*------------------------------------------------------------------------*/
/* Unicode Up-case Conversion */
/*------------------------------------------------------------------------*/ | https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/fat/source/ffunicode.c#L15464-L15590 | 83d3b29cbfc74e8f76f48f8782646c8e464055b2 |
teddycloud | github_2023 | toniebox-reverse-engineering | c | cache_stats | void cache_stats(cache_stats_t *stats)
{
if (stats == NULL)
{
return;
}
cache_entry_t *pos = &cache_table;
memset(stats, 0, sizeof(cache_stats_t)); // Initialize all stats to zero
while (pos != NULL)
{
stats->total_entries++;
stats->memory_used += sizeof(*pos); // Add size of the cache entry structure
if (pos->original_url)
{
stats->memory_used += strlen(pos->original_url) + 1; // Add length of original_url string
}
if (pos->cached_url)
{
stats->memory_used += strlen(pos->cached_url) + 1; // Add length of cached_url string
}
if (pos->file_path)
{
stats->memory_used += strlen(pos->file_path) + 1; // Add length of file_path string
}
if (pos->exists)
{
stats->exists_entries++;
}
if (fsFileExists(pos->file_path))
{
stats->total_files++;
uint32_t size = 0;
fsGetFileSize(pos->file_path, &size);
stats->total_size += size;
}
pos = pos->next;
}
} | /**
* @brief Gathers statistics about the current cache.
*
* @param stats Pointer to a structure where the statistics will be stored.
*/ | https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cache.c#L48-L88 | 83d3b29cbfc74e8f76f48f8782646c8e464055b2 |
teddycloud | github_2023 | toniebox-reverse-engineering | c | process_nvs_item | static error_t process_nvs_item(FsFile *file, size_t offset, size_t part_offset, struct ESP32_nvs_item *item, char (*namespaces)[MAX_NAMESPACE_COUNT][MAX_KEY_SIZE])
{
error_t error = NO_ERROR;
if (item->nsIndex == 0)
{
TRACE_INFO(" Namespace %s\r\n", item->key);
if (item->uint8 > MAX_NAMESPACE_COUNT)
{
TRACE_ERROR("namespace index is %" PRIu32 ", which seems invalid", item->uint8);
return ERROR_FAILURE;
}
osStrcpy((*namespaces)[item->uint8], item->key);
uint32_t crc_header_calc = crc32_header(item);
TRACE_INFO(" Header CRC %08" PRIX32 " (calc %08" PRIX32 ")\r\n", item->crc32, crc_header_calc);
if (item->crc32 != crc_header_calc)
{
TRACE_INFO(" * Updating CRC\r\n");
item->crc32 = crc_header_calc;
error = ERROR_BAD_CRC;
}
}
else
{
if (item->nsIndex > MAX_NAMESPACE_COUNT)
{
TRACE_ERROR(" Namespace index is %" PRIu32 ", which seems invalid", item->nsIndex);
}
else
{
TRACE_INFO(" Namespace %s\r\n", (*namespaces)[item->nsIndex]);
}
TRACE_INFO(" Key %s\r\n", item->key);
switch (item->datatype & 0xF0)
{
case 0x00:
case 0x10:
{
char type_string[32] = {0};
osSprintf(type_string, "%sint%i_t", (item->datatype & 0xF0) ? "" : "u", (item->datatype & 0x0F) * 8);
TRACE_INFO(" Type %s (0x%08" PRIX32 ")\r\n", type_string, item->datatype);
TRACE_INFO(" Chunk Index 0x%02" PRIX8 "\r\n", item->chunkIndex);
switch (item->datatype)
{
case NVS_TYPE_U8:
TRACE_INFO(" Value %" PRIu8 " (0x%02" PRIX8 ")\r\n", item->uint8, item->uint8);
break;
case NVS_TYPE_U16:
TRACE_INFO(" Value %" PRIu16 " (0x%04" PRIX16 ")\r\n", item->uint16, item->uint16);
break;
case NVS_TYPE_U32:
TRACE_INFO(" Value %" PRIu32 " (0x%08" PRIX32 ")\r\n", item->uint32, item->uint32);
break;
case NVS_TYPE_U64:
TRACE_INFO(" Value %" PRIu64 " (0x%016" PRIX64 ")\r\n", item->uint64, item->uint64);
break;
case NVS_TYPE_I8:
TRACE_INFO(" Value %" PRId8 " (0x%02" PRIX8 ")\r\n", item->int8, item->int8);
break;
case NVS_TYPE_I16:
TRACE_INFO(" Value %" PRId16 " (0x%04" PRIX16 ")\r\n", item->int16, item->int16);
break;
case NVS_TYPE_I32:
TRACE_INFO(" Value %" PRId32 " (0x%08" PRIX32 ")\r\n", item->int32, item->int32);
break;
case NVS_TYPE_I64:
TRACE_INFO(" Value %" PRId64 " (0x%016" PRIX64 ")\r\n", item->int64, item->int64);
break;
}
break;
}
}
switch (item->datatype)
{
case NVS_TYPE_STR:
{
TRACE_INFO(" Type string (0x%02" PRIX8 ")\r\n", item->datatype);
TRACE_INFO(" Chunk Index 0x%02" PRIX8 "\r\n", item->chunkIndex);
uint16_t length = item->uint16;
if (length > MAX_STRING_LENGTH)
{
TRACE_ERROR("length is %" PRIu32 ", which seems invalid", length);
return ERROR_FAILURE;
}
char *buffer = osAllocMem(length);
if (!buffer)
{
TRACE_ERROR("Failed to allocate memory\r\n");
return ERROR_FAILURE;
}
error = file_read_block(file, offset + part_offset + sizeof(struct ESP32_nvs_item), buffer, length);
if (error != NO_ERROR)
{
osFreeMem(buffer);
return ERROR_FAILURE;
}
uint32_t crc_data_calc = crc32(buffer, length);
TRACE_INFO(" Size %" PRIu32 "\r\n", item->var_length.size);
TRACE_INFO(" Data %s\r\n", buffer);
TRACE_INFO(" Data CRC %08" PRIX32 " (calc %08" PRIX32 ")\r\n", item->var_length.data_crc32, crc_data_calc);
if (item->var_length.data_crc32 != crc_data_calc)
{
TRACE_INFO(" * Updating CRC\r\n");
item->var_length.data_crc32 = crc_data_calc;
error = ERROR_BAD_CRC;
}
osFreeMem(buffer);
break;
}
case NVS_TYPE_BLOB_IDX:
TRACE_INFO(" Type blob index (0x%02" PRIX8 ")\r\n", item->datatype);
TRACE_INFO(" Chunk Index 0x%02" PRIX8 "\r\n", item->chunkIndex);
TRACE_INFO(" Total size %" PRIu32 "\r\n", item->blob_index.size);
TRACE_INFO(" Chunk count %" PRIu32 "\r\n", item->blob_index.chunk_count);
TRACE_INFO(" Chunk start %" PRIu32 "\r\n", item->blob_index.chunk_start);
break;
case NVS_TYPE_BLOB:
{
TRACE_INFO(" Type blob (0x%" PRIX8 ")\r\n", item->datatype);
TRACE_INFO(" Chunk Index 0x%02" PRIX8 "\r\n", item->chunkIndex);
uint16_t length = item->uint16;
if (length > MAX_STRING_LENGTH)
{
TRACE_ERROR("length is %" PRIu32 ", which seems invalid", length);
return ERROR_FAILURE;
}
uint8_t *buffer = osAllocMem(length);
char *buffer_hex = osAllocMem(BUFFER_HEX_SIZE(length));
if (!buffer || !buffer_hex)
{
TRACE_ERROR("Failed to allocate memory\r\n");
osFreeMem(buffer);
osFreeMem(buffer_hex);
return ERROR_FAILURE;
}
error = file_read_block(file, offset + part_offset + sizeof(struct ESP32_nvs_item), buffer, length);
if (error != NO_ERROR)
{
osFreeMem(buffer);
osFreeMem(buffer_hex);
return ERROR_FAILURE;
}
for (int hex_pos = 0; hex_pos < length; hex_pos++)
{
osSprintf(&buffer_hex[3 * hex_pos], "%02" PRIX8 " ", buffer[hex_pos]);
}
uint32_t crc_data_calc = crc32(buffer, length);
TRACE_INFO(" Size %" PRIu32 "\r\n", item->var_length.size);
TRACE_INFO(" Data %s\r\n", buffer_hex);
TRACE_INFO(" Data CRC %08" PRIX32 " (calc %08" PRIX32 ")\r\n", item->var_length.data_crc32, crc_data_calc);
if (item->var_length.data_crc32 != crc_data_calc)
{
TRACE_INFO(" * Updating CRC\r\n");
item->var_length.data_crc32 = crc_data_calc;
error = ERROR_BAD_CRC;
}
osFreeMem(buffer);
osFreeMem(buffer_hex);
break;
}
}
uint32_t crc_header_calc = crc32_header(item);
TRACE_INFO(" Header CRC %08" PRIX32 " (calc %08" PRIX32 ")\r\n", item->crc32, crc_header_calc);
if (item->crc32 != crc_header_calc)
{
TRACE_INFO(" * Updating CRC\r\n");
item->crc32 = crc_header_calc;
error = ERROR_BAD_CRC;
}
}
return error;
} | /**
* @brief Processes a single NVS item.
*
* This function processes a single NVS item, updates its CRC if necessary, and
* logs relevant information about the item. If the CRC check fails, the function
* updates the CRC and returns an error code indicating the CRC mismatch.
*
* @param file Pointer to the file to read/write.
* @param offset Offset within the file.
* @param part_offset Offset of the specific NVS item within the file.
* @param item Pointer to the NVS item structure.
* @param namespaces Array of namespace strings, passed by reference.
* @return
* - NO_ERROR if successful.
* - ERROR_BAD_CRC if the CRC check fails and the CRC is updated.
* - ERROR_FAILURE for other errors.
*/ | https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/esp32.c#L473-L656 | 83d3b29cbfc74e8f76f48f8782646c8e464055b2 |
teddycloud | github_2023 | toniebox-reverse-engineering | c | esp32_fixup_nvs | error_t esp32_fixup_nvs(FsFile *file, size_t offset, size_t length, bool modify)
{
char namespaces[MAX_NAMESPACE_COUNT][MAX_KEY_SIZE] = {0};
for (size_t sector_offset = 0; sector_offset < length; sector_offset += NVS_SECTOR_SIZE)
{
error_t error;
struct ESP32_nvs_page_header page_header;
size_t block_offset = offset + sector_offset;
error = file_read_block(file, block_offset, &page_header, sizeof(page_header));
if (error != NO_ERROR)
{
TRACE_ERROR("Failed to read input file\r\n");
return ERROR_FAILURE;
}
switch (page_header.state)
{
case NVS_PAGE_STATE_UNINIT:
TRACE_INFO("NVS Block --, offset 0x%08" PRIX32 "\r\n", (uint32_t)block_offset);
TRACE_INFO(" State: %s\r\n", "Uninitialized");
continue;
case NVS_PAGE_STATE_CORRUPT:
TRACE_INFO("NVS Block --, offset 0x%08" PRIX32 "\r\n", (uint32_t)block_offset);
TRACE_INFO(" State: %s\r\n", "Corrupt");
continue;
case NVS_PAGE_STATE_ACTIVE:
TRACE_INFO("NVS Block #%" PRIu32 ", offset 0x%08" PRIX32 "\r\n", page_header.seq, (uint32_t)block_offset);
TRACE_INFO(" State: %s\r\n", "Active");
break;
case NVS_PAGE_STATE_FULL:
TRACE_INFO("NVS Block #%" PRIu32 ", offset 0x%08" PRIX32 "\r\n", page_header.seq, (uint32_t)block_offset);
TRACE_INFO(" State: %s\r\n", "Full");
break;
case NVS_PAGE_STATE_FREEING:
TRACE_INFO("NVS Block #%" PRIu32 ", offset 0x%08" PRIX32 "\r\n", page_header.seq, (uint32_t)block_offset);
TRACE_INFO(" State: %s\r\n", "Freeing");
break;
}
TRACE_INFO(" Header CRC %08" PRIX32 "\r\n", page_header.crc32);
for (int entry = 0; entry < MAX_ENTRY_COUNT; entry++)
{
uint8_t bmp = esp32_nvs_state_get(&page_header, entry);
size_t entry_offset = sizeof(struct ESP32_nvs_page_header) + entry * sizeof(struct ESP32_nvs_item);
if (bmp == NVS_STATE_WRITTEN)
{
TRACE_INFO(" Entry #%" PRIu32 ", offset 0x%08" PRIX32 "\r\n", entry, (uint32_t)entry_offset);
struct ESP32_nvs_item nvs_item;
error = file_read_block(file, block_offset + entry_offset, &nvs_item, sizeof(nvs_item));
if (error != NO_ERROR)
{
TRACE_ERROR("Failed to read input file\r\n");
return ERROR_FAILURE;
}
error = process_nvs_item(file, offset, sector_offset + entry_offset, &nvs_item, &namespaces);
if (error == ERROR_BAD_CRC)
{
TRACE_INFO(" CRC updated -> Writing entry\r\n");
file_write_block(file, block_offset + entry_offset, &nvs_item, sizeof(nvs_item));
}
else if (error != NO_ERROR)
{
return error;
}
entry += nvs_item.span - 1;
}
}
}
return NO_ERROR;
} | /**
* @brief Fixes up the NVS data.
*
* This function scans through the NVS data in the specified file, updates CRCs,
* and logs relevant information about the NVS pages and items.
*
* @param file Pointer to the file to read/write.
* @param offset Offset within the file.
* @param length Length of the data to process.
* @param modify Flag indicating whether to modify the file.
* @return Error code indicating success or failure.
*/ | https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/esp32.c#L670-L748 | 83d3b29cbfc74e8f76f48f8782646c8e464055b2 |
teddycloud | github_2023 | toniebox-reverse-engineering | c | mem_replace | uint32_t mem_replace(uint8_t *buffer, size_t buffer_len, const char *pattern, const char *replace)
{
int replaced = 0;
size_t pattern_len = osStrlen(pattern) + 1;
size_t replace_len = osStrlen(replace) + 1;
if (pattern_len == 0 || buffer_len == 0)
{
return 0;
}
for (size_t i = 0; i <= buffer_len - pattern_len; ++i)
{
if (memcmp(&buffer[i], pattern, pattern_len) == 0)
{
// Make sure we don't write beyond buffer end
size_t end_index = i + replace_len;
if (end_index > buffer_len)
{
break;
}
osMemcpy(&buffer[i], replace, replace_len);
i += (pattern_len - 1); // Skip ahead
replaced++;
}
}
return replaced;
} | /**
* @brief Replaces all occurrences of a pattern string with a replacement string in a given buffer.
*
* This function searches the buffer for the C-string 'pattern' and replaces all its occurrences with the
* C-string 'replace'. It doesn't check if the sizes of the two strings differ and overwrites the original
* string beyond its end if needed. It makes sure not to read or write beyond the buffer end.
*
* @param buffer The buffer in which to replace occurrences of 'pattern'.
* @param buffer_len The length of the buffer.
* @param pattern The pattern string to search for.
* @param replace The replacement string.
* @return The number of replacements made.
*/ | https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/esp32.c#L1661-L1690 | 83d3b29cbfc74e8f76f48f8782646c8e464055b2 |
teddycloud | github_2023 | toniebox-reverse-engineering | c | sanitizePath | void sanitizePath(char *path, bool isDir)
{
size_t i, j;
bool slash = false;
pathCanonicalize(path);
/* Merge all double (or more) slashes // */
for (i = 0, j = 0; path[i]; ++i)
{
if (path[i] == PATH_SEPARATOR)
{
if (slash)
continue;
slash = true;
}
else
{
slash = false;
}
path[j++] = path[i];
}
/* Make sure the path doesn't end with a '/' unless it's the root directory. */
if (j > 1 && path[j - 1] == PATH_SEPARATOR)
j--;
/* Null terminate the sanitized path */
path[j] = '\0';
#ifndef WIN32
/* If path doesn't start with '/', shift right and add '/' */
if (path[0] != PATH_SEPARATOR)
{
memmove(&path[1], &path[0], j + 1); // Shift right
path[0] = PATH_SEPARATOR; // Add '/' at the beginning
j++;
}
#endif
/* If path doesn't end with '/', add '/' at the end */
if (isDir)
{
if (path[j - 1] != PATH_SEPARATOR)
{
path[j] = PATH_SEPARATOR; // Add '/' at the end
path[j + 1] = '\0'; // Null terminate
}
}
} | /* sanitizes the path - needs two additional characters in worst case, so make sure 'path' has enough space */ | https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/handler_api.c#L48-L97 | 83d3b29cbfc74e8f76f48f8782646c8e464055b2 |
teddycloud | github_2023 | toniebox-reverse-engineering | c | mqtt_publish | bool mqtt_publish(const char *item_topic, const char *content)
{
int entries = 0;
bool success = false;
mutex_lock(MUTEX_MQTT_TX_BUFFER);
for (int pos = 0; pos < MQTT_TX_BUFFERS; pos++)
{
if (!mqtt_tx_buffers[pos].used)
{
/* found the first empty slot */
if (success)
{
/* was the content already queued before? */
break;
}
/* new content to send */
mqtt_tx_buffers[pos].topic = strdup(item_topic);
mqtt_tx_buffers[pos].payload = strdup(content);
mqtt_tx_buffers[pos].used = true;
success = true;
break;
}
else if (!osStrcmp(mqtt_tx_buffers[pos].topic, item_topic))
{
/* topic matches, assume content differs */
success = false;
if (!osStrcmp(mqtt_tx_buffers[pos].payload, content))
{
/* content matched */
success = true;
}
else if (++entries > 2)
{
/* when seen more than twice, replace the last one to reduce traffic */
osFreeMem(mqtt_tx_buffers[pos].payload);
mqtt_tx_buffers[pos].payload = strdup(content);
mqtt_tx_buffers[pos].used = true;
success = true;
break;
}
}
}
mutex_unlock(MUTEX_MQTT_TX_BUFFER);
return success;
} | /**
* @brief Publishes an MQTT message by placing it into a transmission buffer.
*
* This function attempts to queue an MQTT message for transmission based on the topic and content provided.
* The function looks for an available slot in the transmission buffer or tries to find an existing message
* with the same topic. If a message with the same topic is found:
* - If the content matches and it is the last message in queue, the message is considered already queued.
* - If the content does not match and the topic has been seen more than twice, the existing message's content
* is replaced to reduce traffic.
*
* Note: The function ensures thread-safety by acquiring and releasing a mutex during the buffer operations.
*
* @param item_topic The topic of the MQTT message.
* @param content The content (payload) of the MQTT message.
* @return Returns true if the message was successfully queued or is already in the queue, otherwise false.
*/ | https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/mqtt.c#L237-L284 | 83d3b29cbfc74e8f76f48f8782646c8e464055b2 |
teddycloud | github_2023 | toniebox-reverse-engineering | c | ipv4StringToAddr | error_t ipv4StringToAddr(const char_t *str, Ipv4Addr *ipAddr)
{
error_t error;
int_t i = 0;
int_t value = -1;
// Parse input string
while (1)
{
// Decimal digit found?
if (osIsdigit(*str))
{
// First digit to be decoded?
if (value < 0)
value = 0;
// Update the value of the current byte
value = (value * 10) + (*str - '0');
// The resulting value shall be in range 0 to 255
if (value > 255)
{
// The conversion failed
error = ERROR_INVALID_SYNTAX;
break;
}
}
// Dot separator found?
else if (*str == '.' && i < 4)
{
// Each dot must be preceded by a valid number
if (value < 0)
{
// The conversion failed
error = ERROR_INVALID_SYNTAX;
break;
}
// Save the current byte
((uint8_t *)ipAddr)[i++] = value;
// Prepare to decode the next byte
value = -1;
}
// End of string detected?
else if (*str == '\0' && i == 3)
{
// The NULL character must be preceded by a valid number
if (value < 0)
{
// The conversion failed
error = ERROR_INVALID_SYNTAX;
}
else
{
// Save the last byte of the IPv4 address
((uint8_t *)ipAddr)[i] = value;
// The conversion succeeded
error = NO_ERROR;
}
// We are done
break;
}
// Invalid character...
else
{
// The conversion failed
error = ERROR_INVALID_SYNTAX;
break;
}
// Point to the next character
str++;
}
// Return status code
return error;
} | /**
* @brief Convert a dot-decimal string to a binary IPv4 address
* @param[in] str NULL-terminated string representing the IPv4 address
* @param[out] ipAddr Binary representation of the IPv4 address
* @return Error code
**/ | https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/server_helpers.c#L533-L610 | 83d3b29cbfc74e8f76f48f8782646c8e464055b2 |
teddycloud | github_2023 | toniebox-reverse-engineering | c | ipv6StringToAddr | error_t ipv6StringToAddr(const char_t *str, Ipv6Addr *ipAddr)
{
error_t error;
int_t i = 0;
int_t j = -1;
int32_t value = -1;
// Parse input string
while (1)
{
// Hexadecimal digit found?
if (isxdigit((uint8_t)*str))
{
// First digit to be decoded?
if (value < 0)
value = 0;
// Update the value of the current 16-bit word
if (osIsdigit(*str))
{
value = (value * 16) + (*str - '0');
}
else if (osIsupper(*str))
{
value = (value * 16) + (*str - 'A' + 10);
}
else
{
value = (value * 16) + (*str - 'a' + 10);
}
// Check resulting value
if (value > 0xFFFF)
{
// The conversion failed
error = ERROR_INVALID_SYNTAX;
break;
}
}
//"::" symbol found?
else if (!osStrncmp(str, "::", 2))
{
// The "::" can only appear once in an IPv6 address
if (j >= 0)
{
// The conversion failed
error = ERROR_INVALID_SYNTAX;
break;
}
// The "::" symbol is preceded by a number?
if (value >= 0)
{
// Save the current 16-bit word
ipAddr->w[i++] = htons(value);
// Prepare to decode the next 16-bit word
value = -1;
}
// Save the position of the "::" symbol
j = i;
// Point to the next character
str++;
}
//":" symbol found?
else if (*str == ':' && i < 8)
{
// Each ":" must be preceded by a valid number
if (value < 0)
{
// The conversion failed
error = ERROR_INVALID_SYNTAX;
break;
}
// Save the current 16-bit word
ipAddr->w[i++] = htons(value);
// Prepare to decode the next 16-bit word
value = -1;
}
// End of string detected?
else if (*str == '\0' && i == 7 && j < 0)
{
// The NULL character must be preceded by a valid number
if (value < 0)
{
// The conversion failed
error = ERROR_INVALID_SYNTAX;
}
else
{
// Save the last 16-bit word of the IPv6 address
ipAddr->w[i] = htons(value);
// The conversion succeeded
error = NO_ERROR;
}
// We are done
break;
}
else if (*str == '\0' && i < 7 && j >= 0)
{
// Save the last 16-bit word of the IPv6 address
if (value >= 0)
ipAddr->w[i++] = htons(value);
// Move the part of the address that follows the "::" symbol
for (int k = 0; k < (i - j); k++)
{
ipAddr->w[7 - k] = ipAddr->w[i - 1 - k];
}
// A sequence of zeroes can now be written in place of "::"
for (int k = 0; k < (8 - i); k++)
{
ipAddr->w[j + k] = 0;
}
// The conversion succeeded
error = NO_ERROR;
break;
}
// Invalid character...
else
{
// The conversion failed
error = ERROR_INVALID_SYNTAX;
break;
}
// Point to the next character
str++;
}
// Return status code
return error;
} | /**
* @brief Convert a string representation of an IPv6 address to a binary IPv6 address
* @param[in] str NULL-terminated string representing the IPv6 address
* @param[out] ipAddr Binary representation of the IPv6 address
* @return Error code
**/ | https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/server_helpers.c#L619-L755 | 83d3b29cbfc74e8f76f48f8782646c8e464055b2 |
teddycloud | github_2023 | toniebox-reverse-engineering | c | ipStringToAddr | error_t ipStringToAddr(const char_t *str, IpAddr *ipAddr)
{
error_t error;
#if (IPV6_SUPPORT == ENABLED)
// IPv6 address?
if (osStrchr(str, ':') != NULL)
{
// IPv6 addresses are 16-byte long
ipAddr->length = sizeof(Ipv6Addr);
// Convert the string to IPv6 address
error = ipv6StringToAddr(str, &ipAddr->ipv6Addr);
}
else
#endif
#if (IPV4_SUPPORT == ENABLED)
// IPv4 address?
if (osStrchr(str, '.') != NULL)
{
// IPv4 addresses are 4-byte long
ipAddr->length = sizeof(Ipv4Addr);
// Convert the string to IPv4 address
error = ipv4StringToAddr(str, &ipAddr->ipv4Addr);
}
else
#endif
// Invalid IP address?
{
// Report an error
error = ERROR_FAILURE;
}
// Return status code
return error;
} | /**
* @brief Convert a string representation of an IP address to a binary IP address
* @param[in] str NULL-terminated string representing the IP address
* @param[out] ipAddr Binary representation of the IP address
* @return Error code
**/ | https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/server_helpers.c#L764-L798 | 83d3b29cbfc74e8f76f48f8782646c8e464055b2 |
teddycloud | github_2023 | toniebox-reverse-engineering | c | settings_load_all_certs | void settings_load_all_certs()
{
for (size_t id = 0; id < MAX_OVERLAYS; id++)
{
settings_load_certs_id(id);
}
} | /* unused? */ | https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/settings.c#L1622-L1628 | 83d3b29cbfc74e8f76f48f8782646c8e464055b2 |
teddycloud | github_2023 | toniebox-reverse-engineering | c | der_get_length | error_t der_get_length(FsFile *fp, size_t *outLength)
{
uint8_t derLen;
size_t len;
error_t err = fsReadFile(fp, &derLen, 1, &len);
if (err != NO_ERROR || len != 1)
{
*outLength = 0;
return err;
}
if ((derLen & 0x80) == 0)
{
*outLength = derLen; // Short form
}
else
{
uint8_t num_bytes = derLen & 0x7f; // Long form
uint32_t length = 0;
for (uint8_t i = 0; i < num_bytes; i++)
{
err = fsReadFile(fp, &derLen, 1, &len);
if (err != NO_ERROR || len != 1)
{
*outLength = 0;
return err;
}
length = (length << 8) | derLen;
}
*outLength = length;
}
return NO_ERROR;
} | /**
* @brief Reads a length field from ASN.1 DER data
*
* This function reads a length field from ASN.1 DER data from the given file.
* The length is encoded either in short form (single byte) or long form
* (multiple bytes with the high bit set in the first byte).
*
* @param[in] fp The file to read from
* @return The length read from the file
*/ | https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/tls_adapter.c#L52-L86 | 83d3b29cbfc74e8f76f48f8782646c8e464055b2 |
teddycloud | github_2023 | toniebox-reverse-engineering | c | der_detect | error_t der_detect(const char *filename, eDerType *type)
{
error_t ret = NO_ERROR;
*type = eDerTypeUnknown;
FsFile *fp = fsOpenFile(filename, FS_FILE_MODE_READ);
if (!fp)
{
return ERROR_FAILURE;
}
/* while loop to break out and clean up commonly */
do
{
uint8_t tag;
size_t len;
/* read first byte */
error_t err = fsReadFile(fp, &tag, 1, &len);
if (err != NO_ERROR || len != 1)
{
ret = ERROR_FAILURE;
break;
}
/* check for DER SEQUENCE format */
if (tag != 0x30)
{
break;
}
/* read length of SEQUENCE */
size_t length;
err = der_get_length(fp, &length);
if (err != NO_ERROR)
{
ret = ERROR_FAILURE;
break;
}
/* now get type of content */
err = fsReadFile(fp, &tag, 1, &len);
if (err != NO_ERROR || len != 1)
{
ret = ERROR_FAILURE;
break;
}
if (tag == 0x30)
{
/* when it's an SEQUENCE, its probably a certificate */
*type = eDerTypeCertificate;
}
else if (tag == 0x02)
{
/* when it's an INTEGER, its probably the RSA key */
*type = eDerTypeKey;
}
} while (0);
fsCloseFile(fp);
return ret;
} | /**
* @brief Determines the type of DER data in a file
*
* This function attempts to determine whether the given file contains
* an X.509 certificate or an RSA private key encoded in ASN.1 DER format.
* The type is determined based on the first few bytes of the data.
*
* @param[in] filename The name of the file to check
* @return The type of the DER data in the file, or eDerTypeUnknown if the type could not be determined
*/ | https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/tls_adapter.c#L98-L161 | 83d3b29cbfc74e8f76f48f8782646c8e464055b2 |
teddycloud | github_2023 | toniebox-reverse-engineering | c | read_certificate | error_t read_certificate(const char_t *filename, char_t **buffer, size_t *length)
{
error_t error;
// Initialize output parameters
*buffer = NULL;
*length = 0;
if (!filename)
{
TRACE_ERROR("Filename NULL\r\n");
return ERROR_READ_FAILED;
}
const char_t *type = NULL;
eDerType derType;
error = der_detect(filename, &derType);
if (error != NO_ERROR)
{
TRACE_ERROR("Failed to open '%s' for cert type detection\r\n", filename);
return ERROR_READ_FAILED;
}
switch (derType)
{
case eDerTypeCertificate:
type = "CERTIFICATE";
TRACE_INFO("File '%s' detected as DER style %s\r\n", filename, type);
break;
case eDerTypeKey:
type = "RSA PRIVATE KEY";
TRACE_INFO("File '%s' detected as DER style %s\r\n", filename, type);
break;
default:
TRACE_INFO("File '%s' assumed PEM style\r\n", filename);
type = NULL;
break;
}
FsFile *fp = NULL;
do
{
uint32_t fileLength = 0;
error = fsGetFileSize(filename, &fileLength);
if (error != NO_ERROR)
{
break;
}
/* allocate file content buffer */
*length = fileLength;
*buffer = osAllocMem(fileLength + 1);
if (*buffer == NULL)
{
error = ERROR_OUT_OF_MEMORY;
break;
}
osMemset(*buffer, 0x00, fileLength + 1);
// Open the specified file
fp = fsOpenFile(filename, FS_FILE_MODE_READ);
// Failed to open the file?
if (fp == NULL)
{
error = ERROR_OPEN_FAILED;
break;
}
// Read file contents
size_t read = 0;
error = fsReadFile(fp, *buffer, *length, &read);
// Failed to read data?
if (error != NO_ERROR)
{
break;
}
// Failed to read data?
if (read != *length)
{
error = ERROR_READ_FAILED;
break;
}
// Successful processing
error = NO_ERROR;
} while (0);
// Close file
if (fp != NULL)
fsCloseFile(fp);
// Any error to report?
if (error)
{
TRACE_ERROR("Error: Cannot load file %s\r\n", filename);
// Clean up side effects
osFreeMem(*buffer);
*buffer = NULL;
*length = 0;
}
/* convert .der to .pem by encoding it into ascii format */
if (type && *buffer)
{
char *inBuf = *buffer;
size_t inBufLen = *length;
char *outBuf = NULL;
size_t outBufLen = 0;
/* get size of output string */
error = pemEncodeFile(inBuf, inBufLen, type, NULL, &outBufLen);
if (error != NO_ERROR)
{
TRACE_ERROR("Error: pemEncodeFile failed for %s with error %s\r\n", filename, error2text(error));
return error;
}
outBuf = osAllocMem(outBufLen + 1);
osMemset(outBuf, 0x00, outBufLen + 1);
error = pemEncodeFile(inBuf, inBufLen, type, outBuf, &outBufLen);
osFreeMem(inBuf);
/* replace output data with generated ascii string */
*buffer = outBuf;
*length = outBufLen;
}
// Return status code
return error;
} | /**
* @brief Load the specified PEM file
* @param[in] filename Name of the PEM file to load
* @param[out] buffer Memory buffer that holds the contents of the file
* @param[out] length Length of the file in bytes
**/ | https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/tls_adapter.c#L169-L306 | 83d3b29cbfc74e8f76f48f8782646c8e464055b2 |
teddycloud | github_2023 | toniebox-reverse-engineering | c | tlsParseCertificateList | error_t tlsParseCertificateList(TlsContext *context,
const uint8_t *p, size_t length)
{
error_t error;
error_t certValidResult;
uint_t i;
size_t n;
const char_t *subjectName;
X509CertInfo *certInfo;
X509CertInfo *issuerCertInfo;
// Initialize X.509 certificates
certInfo = NULL;
issuerCertInfo = NULL;
// Start of exception handling block
do
{
// Allocate a memory buffer to store X.509 certificate info
certInfo = tlsAllocMem(sizeof(X509CertInfo));
// Failed to allocate memory?
if (certInfo == NULL)
{
// Report an error
error = ERROR_OUT_OF_MEMORY;
break;
}
// Allocate a memory buffer to store the parent certificate
issuerCertInfo = tlsAllocMem(sizeof(X509CertInfo));
// Failed to allocate memory?
if (issuerCertInfo == NULL)
{
// Report an error
error = ERROR_OUT_OF_MEMORY;
break;
}
// The end-user certificate is preceded by a 3-byte length field
if (length < 3)
{
// Report an error
error = ERROR_DECODING_FAILED;
break;
}
// Get the size occupied by the certificate
n = LOAD24BE(p);
// Jump to the beginning of the DER-encoded certificate
p += 3;
length -= 3;
// Malformed Certificate message?
if (n == 0 || n > length)
{
// Report an error
error = ERROR_DECODING_FAILED;
break;
}
// Display ASN.1 structure
error = asn1DumpObject(p, n, 0);
// Any error to report?
if (error)
break;
// Parse end-user certificate
error = x509ParseCertificate(p, n, certInfo);
// Failed to parse the X.509 certificate?
if (error)
{
// Report an error
error = ERROR_BAD_CERTIFICATE;
break;
}
// Check certificate key usage
error = tlsCheckKeyUsage(certInfo, context->entity,
context->keyExchMethod);
// Any error to report?
if (error)
break;
// Extract the public key from the end-user certificate
error = tlsReadSubjectPublicKey(context,
&certInfo->tbsCert.subjectPublicKeyInfo);
// Any error to report?
if (error)
break;
#if (TLS_CLIENT_SUPPORT == ENABLED)
// Client mode?
if (context->entity == TLS_CONNECTION_END_CLIENT)
{
TlsCertificateType certType;
TlsNamedGroup namedCurve;
// Retrieve the type of the X.509 certificate
error = tlsGetCertificateType(certInfo, &certType, &namedCurve);
// Unsupported certificate?
if (error)
break;
// Version of TLS prior to TLS 1.3?
if (context->version <= TLS_VERSION_1_2)
{
// ECDSA certificate?
if (certType == TLS_CERT_ECDSA_SIGN)
{
// Make sure the elliptic curve is supported
if (tlsGetCurveInfo(context, namedCurve) == NULL)
{
error = ERROR_BAD_CERTIFICATE;
break;
}
}
}
// Point to the subject name
subjectName = context->serverName;
// Check the subject name in the server certificate against the actual
// FQDN name that is being requested
error = x509CheckSubjectName(certInfo, subjectName);
// Any error to report?
if (error)
{
// Debug message
TRACE_WARNING("Server name mismatch!\r\n");
// Report an error
error = ERROR_BAD_CERTIFICATE;
break;
}
}
else
#endif
// Server mode?
{
// Do not check name constraints
subjectName = NULL;
/* TeddyCloud customizations - copy certificate into TLS context */
copyAsString(context->client_cert_issuer, sizeof(context->client_cert_issuer), certInfo->tbsCert.issuer.commonName.length, certInfo->tbsCert.issuer.commonName.value);
copyAsString(context->client_cert_subject, sizeof(context->client_cert_subject), certInfo->tbsCert.subject.commonName.length, certInfo->tbsCert.subject.commonName.value);
copyAsHex(context->client_cert_serial, sizeof(context->client_cert_serial), certInfo->tbsCert.serialNumber.length, certInfo->tbsCert.serialNumber.value);
}
// Check if the end-user certificate can be matched with a trusted CA
certValidResult = tlsValidateCertificate(context, certInfo, 0,
subjectName);
// Check validation result
if (certValidResult != NO_ERROR && certValidResult != ERROR_UNKNOWN_CA)
{
// The certificate is not valid
error = certValidResult;
break;
}
// Next certificate
p += n;
length -= n;
#if (TLS_MAX_VERSION >= TLS_VERSION_1_3 && TLS_MIN_VERSION <= TLS_VERSION_1_3)
// TLS 1.3 currently selected?
if (context->version == TLS_VERSION_1_3)
{
// Parse the list of extensions for the current CertificateEntry
error = tls13ParseCertExtensions(p, length, &n);
// Any error to report?
if (error)
break;
// Point to the next field
p += n;
// Remaining bytes to process
length -= n;
}
#endif
// PKIX path validation
for (i = 0; length > 0; i++)
{
// Each intermediate certificate is preceded by a 3-byte length field
if (length < 3)
{
// Report an error
error = ERROR_DECODING_FAILED;
break;
}
// Get the size occupied by the certificate
n = LOAD24BE(p);
// Jump to the beginning of the DER-encoded certificate
p += 3;
// Remaining bytes to process
length -= 3;
// Malformed Certificate message?
if (n == 0 || n > length)
{
// Report an error
error = ERROR_DECODING_FAILED;
break;
}
// Display ASN.1 structure
error = asn1DumpObject(p, n, 0);
// Any error to report?
if (error)
break;
// Parse intermediate certificate
error = x509ParseCertificate(p, n, issuerCertInfo);
// Failed to parse the X.509 certificate?
if (error)
{
// Report an error
error = ERROR_BAD_CERTIFICATE;
break;
}
// Certificate chain validation in progress?
if (certValidResult == ERROR_UNKNOWN_CA)
{
// Validate current certificate
error = x509ValidateCertificate(certInfo, issuerCertInfo, i);
// Certificate validation failed?
if (error)
break;
// Check name constraints
error = x509CheckNameConstraints(subjectName, issuerCertInfo);
// Should the application reject the certificate?
if (error)
return ERROR_BAD_CERTIFICATE;
// Check the version of the certificate
if (issuerCertInfo->tbsCert.version < X509_VERSION_3)
{
// Conforming implementations may choose to reject all version 1
// and version 2 intermediate certificates (refer to RFC 5280,
// section 6.1.4)
error = ERROR_BAD_CERTIFICATE;
break;
}
// Check if the intermediate certificate can be matched with a
// trusted CA
certValidResult = tlsValidateCertificate(context, issuerCertInfo,
i, subjectName);
// Check validation result
if (certValidResult != NO_ERROR && certValidResult != ERROR_UNKNOWN_CA)
{
// The certificate is not valid
error = certValidResult;
break;
}
}
// Keep track of the issuer certificate
*certInfo = *issuerCertInfo;
// Next certificate
p += n;
length -= n;
#if (TLS_MAX_VERSION >= TLS_VERSION_1_3 && TLS_MIN_VERSION <= TLS_VERSION_1_3)
// TLS 1.3 currently selected?
if (context->version == TLS_VERSION_1_3)
{
// Parse the list of extensions for the current CertificateEntry
error = tls13ParseCertExtensions(p, length, &n);
// Any error to report?
if (error)
break;
// Point to the next field
p += n;
// Remaining bytes to process
length -= n;
}
#endif
}
// Certificate chain validation failed?
if (error == NO_ERROR && certValidResult != NO_ERROR)
{
// A valid certificate chain or partial chain was received, but the
// certificate was not accepted because the CA certificate could not
// be matched with a known, trusted CA
error = ERROR_UNKNOWN_CA;
}
// End of exception handling block
} while (0);
// Free previously allocated memory
tlsFreeMem(certInfo);
tlsFreeMem(issuerCertInfo);
// Return status code
return error;
} | /**
* @brief Parse certificate chain
* @param[in] context Pointer to the TLS context
* @param[in] p Input stream where to read the certificate chain
* @param[in] length Number of bytes available in the input stream
* @return Error code
**/ | https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/tls_adapter.c#L454-L759 | 83d3b29cbfc74e8f76f48f8782646c8e464055b2 |
teddycloud | github_2023 | toniebox-reverse-engineering | c | debugDisplayArray | void debugDisplayArray(FILE *stream,
const char_t *prepend, const void *data, size_t length)
{
uint_t i;
//Dump the contents of the array
for(i = 0; i < length; i++)
{
//Beginning of a new line?
if((i % 16) == 0)
{
TRACE_PRINTF("%s", prepend);
}
//Display current data byte
TRACE_PRINTF("%02" PRIX8 " ", *((const uint8_t *) data + i));
//End of current line?
if((i % 16) == 15 || i == (length - 1))
{
TRACE_PRINTF("\r\n");
}
}
} | /**
* @brief Display the contents of an array
* @param[in] stream Pointer to a FILE object that identifies an output stream
* @param[in] prepend String to prepend to the left of each line
* @param[in] data Pointer to the data array
* @param[in] length Number of bytes to display
**/ | https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/common/debug.c#L89-L112 | 83d3b29cbfc74e8f76f48f8782646c8e464055b2 |
teddycloud | github_2023 | toniebox-reverse-engineering | c | fsInit | error_t fsInit(void)
{
// Successful processing
return NO_ERROR;
} | /**
* @brief File system initialization
* @return Error code
**/ | https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/common/fs_port_windows.c#L93-L97 | 83d3b29cbfc74e8f76f48f8782646c8e464055b2 |
teddycloud | github_2023 | toniebox-reverse-engineering | c | fsFileExists | bool_t fsFileExists(const char_t *path)
{
error_t error;
bool_t found;
FsFileStat fileStat;
// Clear flag
found = FALSE;
// Make sure the pathname is valid
if (path != NULL)
{
// Retrieve the attributes of the specified file
error = fsGetFileStat(path, &fileStat);
// Check whether the file exists
if (!error)
{
// Valid file?
if ((fileStat.attributes & FS_FILE_ATTR_DIRECTORY) == 0)
{
found = TRUE;
}
}
}
// The function returns TRUE if the file exists
return found;
} | /**
* @brief Check whether a file exists
* @param[in] path NULL-terminated string specifying the filename
* @return The function returns TRUE if the file exists. Otherwise FALSE is returned
**/ | https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/common/fs_port_windows.c#L105-L133 | 83d3b29cbfc74e8f76f48f8782646c8e464055b2 |
teddycloud | github_2023 | toniebox-reverse-engineering | c | fsGetFileSize | error_t fsGetFileSize(const char_t *path, uint32_t *size)
{
error_t error;
FsFileStat fileStat;
// Check parameters
if (path == NULL || size == NULL)
{
return ERROR_INVALID_PARAMETER;
}
// Retrieve the attributes of the specified file
error = fsGetFileStat(path, &fileStat);
// Check whether the file exists
if (!error)
{
// Return the size of the file
*size = fileStat.size;
}
// Return status code
return error;
} | /**
* @brief Retrieve the size of the specified file
* @param[in] path NULL-terminated string specifying the filename
* @param[out] size Size of the file in bytes
* @return Error code
**/ | https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/common/fs_port_windows.c#L142-L165 | 83d3b29cbfc74e8f76f48f8782646c8e464055b2 |
teddycloud | github_2023 | toniebox-reverse-engineering | c | fsGetFileStat | error_t fsGetFileStat(const char_t *path, FsFileStat *fileStat)
{
error_t error = NO_ERROR;
wchar_t wpath[FS_MAX_PATH_LEN + 1];
WIN32_FILE_ATTRIBUTE_DATA fad;
strConvertToWchar(path, wpath, FS_MAX_PATH_LEN);
if (!GetFileAttributesExW(wpath, GetFileExInfoStandard, &fad))
{
error = GetLastError();
return error;
}
fileStat->attributes = fad.dwFileAttributes;
fileStat->size = fad.nFileSizeLow | ((uint64_t)fad.nFileSizeHigh << 32);
FILETIME ft;
FileTimeToLocalFileTime(&fad.ftLastWriteTime, &ft);
SYSTEMTIME st;
FileTimeToSystemTime(&ft, &st);
fileStat->modified.year = st.wYear;
fileStat->modified.month = st.wMonth;
fileStat->modified.day = st.wDay;
fileStat->modified.dayOfWeek = st.wDayOfWeek;
fileStat->modified.hours = st.wHour;
fileStat->modified.minutes = st.wMinute;
fileStat->modified.seconds = st.wSecond;
fileStat->modified.milliseconds = st.wMilliseconds;
return error;
} | /**
* @brief Retrieve the attributes of the specified file
* @param[in] path NULL-terminated string specifying the filename
* @param[out] fileStat File attributes
* @return Error code
**/ | https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/common/fs_port_windows.c#L173-L206 | 83d3b29cbfc74e8f76f48f8782646c8e464055b2 |
teddycloud | github_2023 | toniebox-reverse-engineering | c | fsRenameFile | error_t fsRenameFile(const char_t *oldPath, const char_t *newPath)
{
error_t error;
int_t ret;
// Check parameters
if (oldPath == NULL || newPath == NULL)
{
return ERROR_INVALID_PARAMETER;
}
// Rename the specified file
ret = rename(oldPath, newPath);
// On success, zero is returned
if (ret == 0)
{
error = NO_ERROR;
}
else
{
error = ERROR_FAILURE;
}
// Return status code
return error;
} | /**
* @brief Rename the specified file
* @param[in] oldPath NULL-terminated string specifying the pathname of the file to be renamed
* @param[in] newPath NULL-terminated string specifying the new filename
* @return Error code
**/ | https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/common/fs_port_windows.c#L215-L241 | 83d3b29cbfc74e8f76f48f8782646c8e464055b2 |
teddycloud | github_2023 | toniebox-reverse-engineering | c | fsDeleteFile | error_t fsDeleteFile(const char_t *path)
{
error_t error;
int_t ret;
// Make sure the pathname is valid
if (path == NULL)
{
return ERROR_INVALID_PARAMETER;
}
// Delete the specified file
ret = remove(path);
// On success, zero is returned
if (ret == 0)
{
error = NO_ERROR;
}
else
{
error = ERROR_FAILURE;
}
// Return status code
return error;
} | /**
* @brief Delete a file
* @param[in] path NULL-terminated string specifying the filename
* @return Error code
**/ | https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/common/fs_port_windows.c#L249-L275 | 83d3b29cbfc74e8f76f48f8782646c8e464055b2 |
teddycloud | github_2023 | toniebox-reverse-engineering | c | fsSeekFile | error_t fsSeekFile(FsFile *file, int_t offset, uint_t origin)
{
error_t error;
int_t ret;
// Make sure the file pointer is valid
if (file == NULL)
{
return ERROR_INVALID_PARAMETER;
}
// The origin is used as reference for the offset
if (origin == FS_SEEK_CUR)
{
// The offset is relative to the current file pointer
origin = SEEK_CUR;
}
else if (origin == FS_SEEK_END)
{
// The offset is relative to the end of the file
origin = SEEK_END;
}
else
{
// The offset is absolute
origin = SEEK_SET;
}
// Move read/write pointer
ret = fseek(file, offset, origin);
// On success, zero is returned
if (ret == 0)
{
error = NO_ERROR;
}
else
{
error = ERROR_FAILURE;
}
// Return status code
return error;
} | /**
* @brief Move to specified position in file
* @param[in] file Handle that identifies the file
* @param[in] offset Number of bytes to move from origin
* @param[in] origin Position used as reference for the offset (FS_SEEK_SET,
* FS_SEEK_CUR or FS_SEEK_END)
* @return Error code
**/ | https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/common/fs_port_windows.c#L306-L349 | 83d3b29cbfc74e8f76f48f8782646c8e464055b2 |
teddycloud | github_2023 | toniebox-reverse-engineering | c | fsWriteFile | error_t fsWriteFile(FsFile *file, void *data, size_t length)
{
if (file == NULL)
{
return ERROR_INVALID_PARAMETER;
}
size_t written = fwrite(data, length, 1, file);
if (written != 1)
{
return ERROR_FAILURE;
}
return NO_ERROR;
} | /**
* @brief Write data to the specified file
* @param[in] file Handle that identifies the file to be written
* @param[in] data Pointer to a buffer containing the data to be written
* @param[in] length Number of data bytes to write
* @return Error code
**/ | https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/common/fs_port_windows.c#L359-L374 | 83d3b29cbfc74e8f76f48f8782646c8e464055b2 |
teddycloud | github_2023 | toniebox-reverse-engineering | c | fsReadFile | error_t fsReadFile(FsFile *file, void *data, size_t size, size_t *length)
{
if (file == NULL || length == NULL)
{
return ERROR_INVALID_PARAMETER;
}
size_t n = fread(data, 1, size, file);
*length = n;
if (n == 0)
{
return ERROR_END_OF_FILE;
}
return NO_ERROR;
} | /**
* @brief Read data from the specified file
* @param[in] file Handle that identifies the file to be read
* @param[in] data Pointer to the buffer where to copy the data
* @param[in] size Size of the buffer, in bytes
* @param[out] length Number of data bytes that have been read
* @return Error code
**/ | https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/common/fs_port_windows.c#L385-L402 | 83d3b29cbfc74e8f76f48f8782646c8e464055b2 |
teddycloud | github_2023 | toniebox-reverse-engineering | c | fsCloseFile | void fsCloseFile(FsFile *file)
{
// Make sure the file pointer is valid
if (file != NULL)
{
// Close the specified file
fclose(file);
}
} | /**
* @brief Close a file
* @param[in] file Handle that identifies the file to be closed
**/ | https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/common/fs_port_windows.c#L409-L417 | 83d3b29cbfc74e8f76f48f8782646c8e464055b2 |
teddycloud | github_2023 | toniebox-reverse-engineering | c | fsDirExists | bool_t fsDirExists(const char_t *path)
{
error_t error;
bool_t found;
FsFileStat fileStat;
// Clear flag
found = FALSE;
// Retrieve the attributes of the specified file
error = fsGetFileStat(path, &fileStat);
// Check whether the file exists
if (!error)
{
// Valid directory?
if ((fileStat.attributes & FS_FILE_ATTR_DIRECTORY) != 0)
{
found = TRUE;
}
}
// The function returns TRUE if the directory exists
return found;
} | /**
* @brief Check whether a directory exists
* @param[in] path NULL-terminated string specifying the directory path
* @return The function returns TRUE if the directory exists. Otherwise FALSE is returned
**/ | https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/common/fs_port_windows.c#L425-L449 | 83d3b29cbfc74e8f76f48f8782646c8e464055b2 |
teddycloud | github_2023 | toniebox-reverse-engineering | c | fsCreateDir | error_t fsCreateDir(const char_t *path)
{
error_t error;
int_t ret;
// Make sure the pathname is valid
if (path == NULL)
{
return ERROR_INVALID_PARAMETER;
}
// Create a new directory
#ifdef _WIN32
ret = _mkdir(path);
#else
ret = mkdir(path, 0777);
#endif
// On success, zero is returned
if (ret == 0)
{
error = NO_ERROR;
}
else
{
error = ERROR_FAILURE;
}
// Return status code
return error;
} | /**
* @brief Create a directory
* @param[in] path NULL-terminated string specifying the directory path
* @return Error code
**/ | https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/common/fs_port_windows.c#L457-L487 | 83d3b29cbfc74e8f76f48f8782646c8e464055b2 |
teddycloud | github_2023 | toniebox-reverse-engineering | c | fsRemoveDir | error_t fsRemoveDir(const char_t *path)
{
error_t error;
int_t ret;
// Make sure the pathname is valid
if (path == NULL)
{
return ERROR_INVALID_PARAMETER;
}
// Remove the specified directory
#ifdef _WIN32
ret = _rmdir(path);
#else
ret = rmdir(path);
#endif
// On success, zero is returned
if (ret == 0)
{
error = NO_ERROR;
}
else
{
error = ERROR_FAILURE;
}
// Return status code
return error;
} | /**
* @brief Remove a directory
* @param[in] path NULL-terminated string specifying the directory path
* @return Error code
**/ | https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/common/fs_port_windows.c#L495-L525 | 83d3b29cbfc74e8f76f48f8782646c8e464055b2 |
teddycloud | github_2023 | toniebox-reverse-engineering | c | fsReadDir | error_t fsReadDir(FsDir *dir, FsDirEntry *dirEntry)
{
error_t error;
int_t ret;
struct dirent *entry;
struct stat fileStat;
char_t path[FS_MAX_PATH_LEN + 1];
wchar_t wpath[FS_MAX_PATH_LEN + 1];
// Check parameters
if (dir == NULL || dirEntry == NULL)
{
return ERROR_INVALID_PARAMETER;
}
// Clear directory entry
osMemset(dirEntry, 0, sizeof(FsDirEntry));
WIN32_FIND_DATAW FindFileData;
bool success = false;
strSafeCopy(path, dir->path, FS_MAX_PATH_LEN);
strcat(path, "*");
strConvertToWchar(path, wpath, FS_MAX_PATH_LEN);
if (dir->handle == NULL)
{
if ((dir->handle = FindFirstFileW(wpath, &FindFileData)) == INVALID_HANDLE_VALUE)
{
return ERROR_END_OF_STREAM;
}
}
else
{
if (!FindNextFileW(dir->handle, &FindFileData))
{
return ERROR_END_OF_STREAM;
}
}
// Copy the file name component
strConvertFromWchar(FindFileData.cFileName, dirEntry->name, FS_MAX_NAME_LEN);
// Check file attributes
if (FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
dirEntry->attributes |= FS_FILE_ATTR_DIRECTORY;
}
// Get the pathname of the directory being listed
strSafeCopy(path, dir->path, FS_MAX_PATH_LEN);
// Retrieve the full pathname
pathCombine(path, dirEntry->name, FS_MAX_PATH_LEN);
pathCanonicalize(path);
// Get file status
ret = stat(path, &fileStat);
// On success, zero is returned
if (ret == 0)
{
// File size
dirEntry->size = fileStat.st_size;
// Time of last modification
convertUnixTimeToDate(fileStat.st_mtime, &dirEntry->modified);
}
else
{
// File size
dirEntry->size = 0;
// Time of last modification
dirEntry->modified.year = 1970;
dirEntry->modified.month = 1;
dirEntry->modified.day = 1;
dirEntry->modified.dayOfWeek = 0;
dirEntry->modified.hours = 0;
dirEntry->modified.minutes = 0;
dirEntry->modified.seconds = 0;
dirEntry->modified.milliseconds = 0;
}
// Successful processing
error = NO_ERROR;
return error;
} | /**
* @brief Read an entry from the specified directory stream
* @param[in] dir Handle that identifies the directory
* @param[out] dirEntry Pointer to a directory entry
* @return Error code
**/ | https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/common/fs_port_windows.c#L552-L639 | 83d3b29cbfc74e8f76f48f8782646c8e464055b2 |
teddycloud | github_2023 | toniebox-reverse-engineering | c | fsCloseDir | void fsCloseDir(FsDir *dir)
{
// Make sure the directory pointer is valid
if (dir != NULL)
{
// Close the specified directory
FindClose(dir->handle);
// Release directory descriptor
osFreeMem(dir);
}
} | /**
* @brief Close a directory stream
* @param[in] dir Handle that identifies the directory to be closed
**/ | https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/common/fs_port_windows.c#L646-L657 | 83d3b29cbfc74e8f76f48f8782646c8e464055b2 |
teddycloud | github_2023 | toniebox-reverse-engineering | c | osInitKernel | void osInitKernel(void)
{
//Not implemented
} | /**
* @brief Kernel initialization
**/ | https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/common/os_port_posix.c#L54-L57 | 83d3b29cbfc74e8f76f48f8782646c8e464055b2 |
teddycloud | github_2023 | toniebox-reverse-engineering | c | osStartKernel | void osStartKernel(void)
{
//Not implemented
} | /**
* @brief Start kernel
**/ | https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/common/os_port_posix.c#L64-L67 | 83d3b29cbfc74e8f76f48f8782646c8e464055b2 |
teddycloud | github_2023 | toniebox-reverse-engineering | c | osCreateTask | OsTaskId osCreateTask(const char_t *name, OsTaskCode taskCode,
void *param, size_t stackSize, int_t priority)
{
int_t ret;
pthread_t thread;
//Create a new thread
ret = pthread_create(&thread, NULL, (PthreadTaskCode) taskCode, param);
//Return a pointer to the newly created thread
if(ret == 0)
{
return (OsTaskId) thread;
}
else
{
return OS_INVALID_TASK_ID;
}
} | /**
* @brief Create a task
* @param[in] name A name identifying the task
* @param[in] taskCode Pointer to the task entry function
* @param[in] param A pointer to a variable to be passed to the task
* @param[in] stackSize The initial size of the stack, in words
* @param[in] priority The priority at which the task should run
* @return Task identifier referencing the newly created task
**/ | https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/common/os_port_posix.c#L80-L98 | 83d3b29cbfc74e8f76f48f8782646c8e464055b2 |
teddycloud | github_2023 | toniebox-reverse-engineering | c | osDeleteTask | void osDeleteTask(OsTaskId taskId)
{
//Delete the calling thread?
if(taskId == OS_SELF_TASK_ID)
{
//Kill ourselves
pthread_exit(NULL);
}
else
{
pthread_t thread = (pthread_t)taskId;
pthread_cancel(thread);
}
} | /**
* @brief Delete a task
* @param[in] taskId Task identifier referencing the task to be deleted
**/ | https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/common/os_port_posix.c#L106-L120 | 83d3b29cbfc74e8f76f48f8782646c8e464055b2 |
teddycloud | github_2023 | toniebox-reverse-engineering | c | osDelayTask | void osDelayTask(systime_t delay)
{
//Delay the task for the specified duration
usleep(delay * 1000);
} | /**
* @brief Delay routine
* @param[in] delay Amount of time for which the calling task should block
**/ | https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/common/os_port_posix.c#L127-L131 | 83d3b29cbfc74e8f76f48f8782646c8e464055b2 |
teddycloud | github_2023 | toniebox-reverse-engineering | c | osSwitchTask | void osSwitchTask(void)
{
//Not implemented
} | /**
* @brief Yield control to the next task
**/ | https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/common/os_port_posix.c#L138-L141 | 83d3b29cbfc74e8f76f48f8782646c8e464055b2 |
teddycloud | github_2023 | toniebox-reverse-engineering | c | osSuspendAllTasks | void osSuspendAllTasks(void)
{
pthread_once(&init_once, osMutexInit);
pthread_mutex_lock(&mutex);
} | /**
* @brief Suspend scheduler activity
**/ | https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/common/os_port_posix.c#L158-L162 | 83d3b29cbfc74e8f76f48f8782646c8e464055b2 |
teddycloud | github_2023 | toniebox-reverse-engineering | c | osResumeAllTasks | void osResumeAllTasks(void)
{
pthread_mutex_unlock(&mutex);
} | /**
* @brief Resume scheduler activity
**/ | https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/common/os_port_posix.c#L167-L170 | 83d3b29cbfc74e8f76f48f8782646c8e464055b2 |
teddycloud | github_2023 | toniebox-reverse-engineering | c | osCreateEvent | bool_t osCreateEvent(OsEvent *event)
{
int_t ret;
//Create a semaphore object
ret = sem_init(event, 0, 0);
//Check whether the semaphore was successfully created
if(ret == 0)
{
return TRUE;
}
else
{
return FALSE;
}
} | /**
* @brief Create an event object
* @param[in] event Pointer to the event object
* @return The function returns TRUE if the event object was successfully
* created. Otherwise, FALSE is returned
**/ | https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/common/os_port_posix.c#L180-L196 | 83d3b29cbfc74e8f76f48f8782646c8e464055b2 |
teddycloud | github_2023 | toniebox-reverse-engineering | c | osDeleteEvent | void osDeleteEvent(OsEvent *event)
{
//Properly dispose the event object
sem_destroy(event);
} | /**
* @brief Delete an event object
* @param[in] event Pointer to the event object
**/ | https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/common/os_port_posix.c#L204-L208 | 83d3b29cbfc74e8f76f48f8782646c8e464055b2 |
teddycloud | github_2023 | toniebox-reverse-engineering | c | osSetEvent | void osSetEvent(OsEvent *event)
{
int_t ret;
int_t value;
//Get the current value of the semaphore
ret = sem_getvalue(event, &value);
//Nonsignaled state?
if(ret == 0 && value == 0)
{
//Set the specified event to the signaled state
sem_post(event);
}
} | /**
* @brief Set the specified event object to the signaled state
* @param[in] event Pointer to the event object
**/ | https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/common/os_port_posix.c#L216-L230 | 83d3b29cbfc74e8f76f48f8782646c8e464055b2 |
teddycloud | github_2023 | toniebox-reverse-engineering | c | osResetEvent | void osResetEvent(OsEvent *event)
{
int_t ret;
//Force the specified event to the nonsignaled state
do
{
//Decrement the semaphore's count by one
ret = sem_trywait(event);
//Check status
} while(ret == 0);
} | /**
* @brief Set the specified event object to the nonsignaled state
* @param[in] event Pointer to the event object
**/ | https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/common/os_port_posix.c#L238-L250 | 83d3b29cbfc74e8f76f48f8782646c8e464055b2 |
teddycloud | github_2023 | toniebox-reverse-engineering | c | osWaitForEvent | bool_t osWaitForEvent(OsEvent *event, systime_t timeout)
{
int_t ret;
struct timespec ts;
//Wait until the specified event is in the signaled state or the timeout
//interval elapses
if(timeout == 0)
{
//Non-blocking call
ret = sem_trywait(event);
}
else if(timeout == INFINITE_DELAY)
{
//Infinite timeout period
ret = sem_wait(event);
}
else
{
//Get current time
clock_gettime(CLOCK_REALTIME, &ts);
//Set absolute timeout
ts.tv_sec += timeout / 1000;
ts.tv_nsec += (timeout % 1000) * 1000000;
//Normalize time stamp value
if(ts.tv_nsec >= 1000000000)
{
ts.tv_sec += 1;
ts.tv_nsec -= 1000000000;
}
//Wait until the specified event becomes set
ret = sem_timedwait(event, &ts);
}
//Check whether the specified event is set
if(ret == 0)
{
//Force the event back to the nonsignaled state
do
{
//Decrement the semaphore's count by one
ret = sem_trywait(event);
//Check status
} while(ret == 0);
//The specified event is in the signaled state
return TRUE;
}
else
{
//The timeout interval elapsed
return FALSE;
}
} | /**
* @brief Wait until the specified event is in the signaled state
* @param[in] event Pointer to the event object
* @param[in] timeout Timeout interval
* @return The function returns TRUE if the state of the specified object is
* signaled. FALSE is returned if the timeout interval elapsed
**/ | https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/common/os_port_posix.c#L261-L318 | 83d3b29cbfc74e8f76f48f8782646c8e464055b2 |
teddycloud | github_2023 | toniebox-reverse-engineering | c | osSetEventFromIsr | bool_t osSetEventFromIsr(OsEvent *event)
{
//Not implemented
return FALSE;
} | /**
* @brief Set an event object to the signaled state from an interrupt service routine
* @param[in] event Pointer to the event object
* @return TRUE if setting the event to signaled state caused a task to unblock
* and the unblocked task has a priority higher than the currently running task
**/ | https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/common/os_port_posix.c#L328-L332 | 83d3b29cbfc74e8f76f48f8782646c8e464055b2 |
teddycloud | github_2023 | toniebox-reverse-engineering | c | osCreateSemaphore | bool_t osCreateSemaphore(OsSemaphore *semaphore, uint_t count)
{
int_t ret;
//Create a semaphore object
ret = sem_init(semaphore, 0, count);
//Check whether the semaphore was successfully created
if(ret == 0)
{
return TRUE;
}
else
{
return FALSE;
}
} | /**
* @brief Create a semaphore object
* @param[in] semaphore Pointer to the semaphore object
* @param[in] count The maximum count for the semaphore object. This value
* must be greater than zero
* @return The function returns TRUE if the semaphore was successfully
* created. Otherwise, FALSE is returned
**/ | https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/common/os_port_posix.c#L344-L360 | 83d3b29cbfc74e8f76f48f8782646c8e464055b2 |
teddycloud | github_2023 | toniebox-reverse-engineering | c | osDeleteSemaphore | void osDeleteSemaphore(OsSemaphore *semaphore)
{
//Properly dispose the semaphore object
sem_destroy(semaphore);
} | /**
* @brief Delete a semaphore object
* @param[in] semaphore Pointer to the semaphore object
**/ | https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/common/os_port_posix.c#L368-L372 | 83d3b29cbfc74e8f76f48f8782646c8e464055b2 |
teddycloud | github_2023 | toniebox-reverse-engineering | c | osWaitForSemaphore | bool_t osWaitForSemaphore(OsSemaphore *semaphore, systime_t timeout)
{
int_t ret;
struct timespec ts;
//Wait until the semaphore is available or the timeout interval elapses
if(timeout == 0)
{
//Non-blocking call
ret = sem_trywait(semaphore);
}
else if(timeout == INFINITE_DELAY)
{
//Infinite timeout period
ret = sem_wait(semaphore);
}
else
{
//Get current time
clock_gettime(CLOCK_REALTIME, &ts);
//Set absolute timeout
ts.tv_sec += timeout / 1000;
ts.tv_nsec += (timeout % 1000) * 1000000;
//Normalize time stamp value
if(ts.tv_nsec >= 1000000000)
{
ts.tv_sec += 1;
ts.tv_nsec -= 1000000000;
}
//Wait until the specified semaphore becomes available
ret = sem_timedwait(semaphore, &ts);
}
//Check whether the specified semaphore is available
if(ret == 0)
{
return TRUE;
}
else
{
return FALSE;
}
} | /**
* @brief Wait for the specified semaphore to be available
* @param[in] semaphore Pointer to the semaphore object
* @param[in] timeout Timeout interval
* @return The function returns TRUE if the semaphore is available. FALSE is
* returned if the timeout interval elapsed
**/ | https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/common/os_port_posix.c#L383-L428 | 83d3b29cbfc74e8f76f48f8782646c8e464055b2 |
teddycloud | github_2023 | toniebox-reverse-engineering | c | osReleaseSemaphore | void osReleaseSemaphore(OsSemaphore *semaphore)
{
if (semaphore == NULL)
{
TRACE_ERROR("osReleaseSemaphore() failed because semaphore is NULL\r\n");
return;
}
//Release the semaphore
sem_post(semaphore);
} | /**
* @brief Release the specified semaphore object
* @param[in] semaphore Pointer to the semaphore object
**/ | https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/common/os_port_posix.c#L436-L445 | 83d3b29cbfc74e8f76f48f8782646c8e464055b2 |
teddycloud | github_2023 | toniebox-reverse-engineering | c | osCreateMutex | bool_t osCreateMutex(OsMutex *mutex)
{
int_t ret;
//Create a mutex object
ret = pthread_mutex_init(mutex, NULL);
//Check whether the mutex was successfully created
if(ret == 0)
{
return TRUE;
}
else
{
return FALSE;
}
} | /**
* @brief Create a mutex object
* @param[in] mutex Pointer to the mutex object
* @return The function returns TRUE if the mutex was successfully
* created. Otherwise, FALSE is returned
**/ | https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/common/os_port_posix.c#L455-L471 | 83d3b29cbfc74e8f76f48f8782646c8e464055b2 |
teddycloud | github_2023 | toniebox-reverse-engineering | c | osDeleteMutex | void osDeleteMutex(OsMutex *mutex)
{
//Properly dispose the mutex object
pthread_mutex_destroy(mutex);
} | /**
* @brief Delete a mutex object
* @param[in] mutex Pointer to the mutex object
**/ | https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/common/os_port_posix.c#L479-L483 | 83d3b29cbfc74e8f76f48f8782646c8e464055b2 |
teddycloud | github_2023 | toniebox-reverse-engineering | c | osAcquireMutex | void osAcquireMutex(OsMutex *mutex)
{
//Obtain ownership of the mutex object
pthread_mutex_lock(mutex);
} | /**
* @brief Acquire ownership of the specified mutex object
* @param[in] mutex Pointer to the mutex object
**/ | https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/common/os_port_posix.c#L491-L495 | 83d3b29cbfc74e8f76f48f8782646c8e464055b2 |
teddycloud | github_2023 | toniebox-reverse-engineering | c | osReleaseMutex | void osReleaseMutex(OsMutex *mutex)
{
//Release ownership of the mutex object
pthread_mutex_unlock(mutex);
} | /**
* @brief Release ownership of the specified mutex object
* @param[in] mutex Pointer to the mutex object
**/ | https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/common/os_port_posix.c#L503-L507 | 83d3b29cbfc74e8f76f48f8782646c8e464055b2 |
teddycloud | github_2023 | toniebox-reverse-engineering | c | osGetSystemTime | systime_t osGetSystemTime(void)
{
struct timeval tv;
//Get current time
gettimeofday(&tv, NULL);
//Convert resulting value to milliseconds
return (tv.tv_sec * 1000) + (tv.tv_usec / 1000);
} | /**
* @brief Retrieve system time
* @return Number of milliseconds elapsed since the system was last started
**/ | https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/common/os_port_posix.c#L515-L524 | 83d3b29cbfc74e8f76f48f8782646c8e464055b2 |
teddycloud | github_2023 | toniebox-reverse-engineering | c | osFreeMem | __weak_func void osFreeMem(void *p)
{
//Free memory block
free(p);
} | /**
* @brief Release a previously allocated memory block
* @param[in] p Previously allocated memory block to be freed
**/ | https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/common/os_port_posix.c#L546-L550 | 83d3b29cbfc74e8f76f48f8782646c8e464055b2 |
teddycloud | github_2023 | toniebox-reverse-engineering | c | osInitKernel | void osInitKernel(void)
{
//Not implemented
} | /**
* @brief Kernel initialization
**/ | https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/common/os_port_windows.c#L53-L56 | 83d3b29cbfc74e8f76f48f8782646c8e464055b2 |
teddycloud | github_2023 | toniebox-reverse-engineering | c | osStartKernel | void osStartKernel(void)
{
//Not implemented
} | /**
* @brief Start kernel
**/ | https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/common/os_port_windows.c#L63-L66 | 83d3b29cbfc74e8f76f48f8782646c8e464055b2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.