From 3f1a4be6701b07770253f0e14f8643c2079255bc Mon Sep 17 00:00:00 2001 From: Robin Jones Date: Mon, 6 Feb 2023 16:18:27 +0000 Subject: [PATCH 01/11] Add emulated smoke tests Run ROMs in Ares emulator Improves testability. --- .../build-toolchain-library-and-roms.yml | 7 + .github/workflows/run-rom-tests.yml | 154 ++++++++++++++++++ 2 files changed, 161 insertions(+) create mode 100644 .github/workflows/run-rom-tests.yml diff --git a/.github/workflows/build-toolchain-library-and-roms.yml b/.github/workflows/build-toolchain-library-and-roms.yml index 84b127bbbd..5897e58e98 100644 --- a/.github/workflows/build-toolchain-library-and-roms.yml +++ b/.github/workflows/build-toolchain-library-and-roms.yml @@ -131,3 +131,10 @@ jobs: tags: ghcr.io/${{ steps.vars.outputs.repository_name }}:latest cache-from: type=gha cache-to: type=gha,mode=max + + Run-Rom-Tests: + name: "Run ROM tests" + needs: Toolchain-Library-And-Examples + uses: ./.github/workflows/run-rom-tests.yml + secrets: + token: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/run-rom-tests.yml b/.github/workflows/run-rom-tests.yml new file mode 100644 index 0000000000..1e4cb104dd --- /dev/null +++ b/.github/workflows/run-rom-tests.yml @@ -0,0 +1,154 @@ +name: Run ROM Tests + +on: + workflow_call: + secrets: + token: + description: 'A github token passed from the caller workflow' + required: true + +jobs: + + ROM-Smoke-Tests-Ares-Windows: + name: Ares Emulator Smoke tests + runs-on: windows-latest + + # Run each ROM using on ares emulator. + strategy: + fail-fast: false + matrix: + include: [ + { rom-name: testrom_emu, ares-ci-compatible: true, rom-path: tests }, + { rom-name: testrom, ares-ci-compatible: true, rom-path: tests }, + { rom-name: audioplayer, ares-ci-compatible: false, rom-path: examples/audioplayer }, + { rom-name: cpptest, ares-ci-compatible: true, rom-path: examples/cpptest }, + { rom-name: ctest, ares-ci-compatible: true, rom-path: examples/ctest }, + { rom-name: dfsdemo, ares-ci-compatible: true, rom-path: examples/dfsdemo }, + { rom-name: eepromfstest_16k, ares-ci-compatible: true, rom-path: examples/eepromfstest }, + { rom-name: eepromfstest_4k, ares-ci-compatible: true, rom-path: examples/eepromfstest }, + { rom-name: mixertest, ares-ci-compatible: true, rom-path: examples/mixertest }, + { rom-name: mptest, ares-ci-compatible: true, rom-path: examples/mptest }, + { rom-name: mputest, ares-ci-compatible: true, rom-path: examples/mputest }, + { rom-name: rspqdemo, ares-ci-compatible: true, rom-path: examples/rspqdemo }, + { rom-name: spritemap, ares-ci-compatible: true, rom-path: examples/spritemap }, + { rom-name: test, ares-ci-compatible: true, rom-path: examples/test }, + { rom-name: timers, ares-ci-compatible: true, rom-path: examples/timers }, + { rom-name: ucodetest, ares-ci-compatible: true, rom-path: examples/ucodetest }, + { rom-name: vrutest, ares-ci-compatible: true, rom-path: examples/vrutest }, + { rom-name: vtest, ares-ci-compatible: true, rom-path: examples/vtest } + ] + + env: + Delay_Time_Seconds: 15 + Enable_Screenshot: 'no' # false by default + + steps: + + - name: Download ROM artifact + id: download-rom-artifact + uses: actions/download-artifact@v3 + with: + name: roms + path: ${{ runner.temp }}/roms + continue-on-error: true + + # - name: Show ROM Paths # helps with creating new matrix paths + # run: | + # cd ${{ runner.temp }}/roms + # ls -R + # continue-on-error: true + + - name: Install ares emulator + if: ${{ matrix.ares-ci-compatible }} + run: | + Write-Output "Installing ares emulator!" + curl -LO https://github.com/ares-emulator/ares/releases/download/nightly/ares-windows-msvc-x64.zip + unzip ares-windows-msvc-x64.zip + rd -r ./ares-windows-msvc-x64.zip + continue-on-error: true + + + - name: Setup Ares + if: ${{ matrix.ares-ci-compatible }} + run: | + # NOTE: we need to change some of the settings that cannot be setup through the CLI. + # to make it compatible with the CI host. + # FIXME: ares should have a parameter to tell it that it is running on a github host + + Write-Output "Step 1 - Run a valid ROM so the settings are actually generated." + Write-Output " ROM will fail to run due to missing graphics acceleration..." + . ares-nightly/ares ${{ runner.temp }}/roms/${{ matrix.rom-path }}/${{ matrix.rom-name }}.z64 + + Write-Output "Step 2 - Sleep a little to make sure settings.bml is generated." + # 5 seconds delay seems to run reliably. + Start-Sleep -Seconds 5 + + Write-Output "Step 3 - adjust the settings to disable graphics acceleration and audio" + Write-Verbose "Disable graphics acceleration" + ((Get-Content -path ares-nightly/settings.bml -Raw) -replace 'EnableVulkan: true','EnableVulkan: false') | Set-Content -Path ares-nightly/settings.bml + Write-Verbose "Disable video interface processing" + ((Get-Content -path ares-nightly/settings.bml -Raw) -replace 'DisableVideoInterfaceProcessing: false','DisableVideoInterfaceProcessing: true') | Set-Content -Path ares-nightly/settings.bml + Write-Verbose "Change to a compatible graphics option" + # https://github.com/ares-emulator/ares/blob/b1d216b8affbfb811a681dca1bd603d3369624fc/ruby/video/video.cpp#L154 + ((Get-Content -path ares-nightly/settings.bml -Raw) -replace 'Driver: OpenGL 3.2','Driver: Direct3D 9.0') | Set-Content -Path ares-nightly/settings.bml + Write-Verbose "Disable audio" + # https://github.com/ares-emulator/ares/blob/3ca1f9ebb4ae3f472f7fba661746058f84126536/ruby/audio/audio.cpp#L268 + ((Get-Content -path ares-nightly/settings.bml -Raw) -replace 'Driver: WASAPI','Driver: None') | Set-Content -Path ares-nightly/settings.bml + + - name: Run ROM in Ares for logs + if: ${{ matrix.ares-ci-compatible }} + run: | + Start-Process -FilePath "ares-nightly/ares" -ArgumentList "${{ runner.temp }}/roms/${{ matrix.rom-path }}/${{ matrix.rom-name }}.z64" -RedirectStandardOutput ${{ matrix.rom-name }}-${{ env.Delay_Time_Seconds }}s-ares-output-log.txt + + Start-Sleep -Seconds ${{ env.Delay_Time_Seconds }} + + # the emulator is still running! we need to stop it. + Stop-Process -Name "ares" + # Add a delay to make sure that the process has been closed. + Start-Sleep -Seconds 1 + + if ((get-item "${{ matrix.rom-name }}-${{ env.Delay_Time_Seconds }}s-ares-output-log.txt").Length -gt 0) + { + Write-Warning "Log File is not empty!" + Write-Verbose "Or match it against a golden copy to see if it is expected." + Write-Output "Enable_Screenshot=yes" | Out-File -FilePath $Env:GITHUB_ENV -Encoding utf8 -Append + + # appending to CI summary info! + Write-Output ":warning: You might want to check: ${{ matrix.rom-name }}.z64 for issues!" | Out-File -FilePath $Env:GITHUB_STEP_SUMMARY -Encoding utf8 -Append + } + else + { + Write-Output "File is empty, trying to remove it." + remove-item -fo ${{ matrix.rom-name }}-${{ env.Delay_Time_Seconds }}s-ares-output-log.txt -ErrorAction Ignore + } + continue-on-error: true + + - name: Upload files + if: ${{ matrix.ares-ci-compatible }} + uses: actions/upload-artifact@v3 + with: + name: ${{ matrix.rom-name }}-${{ env.Delay_Time_Seconds }}s-ares-output-log.txt + if-no-files-found: ignore + path: | + ${{ matrix.rom-name }}-${{ env.Delay_Time_Seconds }}s-ares-output-log.txt + continue-on-error: true + + + - name: Run ROM in Ares for screenshot + if: ${{ env.Enable_Screenshot == 'yes' }} # FIXME: should also take into account ${{ matrix.ares-ci-compatible }} + run: | + Start-Process -FilePath "ares-nightly/ares" -ArgumentList "${{ runner.temp }}/roms/${{ matrix.rom-path }}/${{ matrix.rom-name }}.z64 --fullscreen" + Start-Sleep -Seconds ${{ env.Delay_Time_Seconds }} + continue-on-error: true + + - name: Take screenshot + if: ${{ env.Enable_Screenshot == 'yes' }} # FIXME: should also take into account ${{ matrix.ares-ci-compatible }} + uses: networkfusion/desktop-screenshot-action@0.2 + with: + file-name: '${{ matrix.rom-name }}-emu-screenshot_${{ env.Delay_Time_Seconds }}s.jpg' + + - name: Cleanup ares process + if: ${{ env.Enable_Screenshot == 'yes' }} # FIXME: should also take into account ${{ matrix.ares-ci-compatible }} + run: | + Stop-Process -Name "ares" + continue-on-error: true From 703850bb89a39b88212b4df58fd2407aea971bec Mon Sep 17 00:00:00 2001 From: Robin Jones Date: Thu, 9 Feb 2023 02:41:16 +0000 Subject: [PATCH 02/11] Update fatfs to R0.15 Main causes of concern: #define FF_PRINT_LLI 1 #define FF_PRINT_FLOAT 1 --- src/fatfs/00history.txt | 23 + src/fatfs/00readme.txt | 2 +- src/fatfs/ff.c | 1594 ++++++++++++++++++++++----------------- src/fatfs/ff.h | 135 ++-- src/fatfs/ffconf.h | 80 +- src/fatfs/ffunicode.c | 44 +- 6 files changed, 1058 insertions(+), 820 deletions(-) diff --git a/src/fatfs/00history.txt b/src/fatfs/00history.txt index d0ae4cdc4f..4fa1d7a1b5 100644 --- a/src/fatfs/00history.txt +++ b/src/fatfs/00history.txt @@ -344,3 +344,26 @@ R0.14a (December 5, 2020) Fixed old floppy disks formatted with MS-DOS 2.x and 3.x cannot be mounted. Fixed some compiler warnings. + + +R0.14b (April 17, 2021) + Made FatFs uses standard library for copy, compare and search instead of built-in string functions. + Added support for long long integer and floating point to f_printf(). (FF_STRF_LLI and FF_STRF_FP) + Made path name parser ignore the terminating separator to allow "dir/". + Improved the compatibility in Unix style path name feature. + Fixed the file gets dead-locked when f_open() failed with some conditions. (appeared at R0.12a) + Fixed f_mkfs() can create wrong exFAT volume due to a timing dependent error. (appeared at R0.12) + Fixed code page 855 cannot be set by f_setcp(). + Fixed some compiler warnings. + + + +R0.15 (November 6, 2022) + Changed user provided synchronization functions in order to completely eliminate the platform dependency from FatFs code. + FF_SYNC_t is removed from the configuration options. + Fixed a potential error in f_mount when FF_FS_REENTRANT. + Fixed file lock control FF_FS_LOCK is not mutal excluded when FF_FS_REENTRANT && FF_VOLUMES > 1 is true. + Fixed f_mkfs() creates broken exFAT volume when the size of volume is >= 2^32 sectors. + Fixed string functions cannot write the unicode characters not in BMP when FF_LFN_UNICODE == 2 (UTF-8). + Fixed a compatibility issue in identification of GPT header. + diff --git a/src/fatfs/00readme.txt b/src/fatfs/00readme.txt index 809be15407..39f6c8ce72 100644 --- a/src/fatfs/00readme.txt +++ b/src/fatfs/00readme.txt @@ -1,4 +1,4 @@ -FatFs Module Source Files R0.14a +FatFs Module Source Files R0.15 FILES diff --git a/src/fatfs/ff.c b/src/fatfs/ff.c index a378cf1ca9..07412bb273 100644 --- a/src/fatfs/ff.c +++ b/src/fatfs/ff.c @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------/ -/ FatFs - Generic FAT Filesystem Module R0.14a / +/ FatFs - Generic FAT Filesystem Module R0.15 w/patch1 / /-----------------------------------------------------------------------------/ / -/ Copyright (C) 2020, ChaN, all right reserved. +/ Copyright (C) 2022, ChaN, all right reserved. / / FatFs module is an open source software. Redistribution and use of FatFs in / source and binary forms, with or without modification, are permitted provided @@ -19,6 +19,7 @@ /----------------------------------------------------------------------------*/ +#include #include "ff.h" /* Declarations of FatFs API */ #include "diskio.h" /* Declarations of device I/O functions */ @@ -29,7 +30,7 @@ ---------------------------------------------------------------------------*/ -#if FF_DEFINED != 80196 /* Revision ID */ +#if FF_DEFINED != 80286 /* Revision ID */ #error Wrong include file (ff.h). #endif @@ -47,6 +48,8 @@ #define IsUpper(c) ((c) >= 'A' && (c) <= 'Z') #define IsLower(c) ((c) >= 'a' && (c) <= 'z') #define IsDigit(c) ((c) >= '0' && (c) <= '9') +#define IsSeparator(c) ((c) == '/' || (c) == '\\') +#define IsTerminator(c) ((UINT)(c) < (FF_USE_LFN ? ' ' : '!')) #define IsSurrogate(c) ((c) >= 0xD800 && (c) <= 0xDFFF) #define IsSurrogateH(c) ((c) >= 0xD800 && (c) <= 0xDBFF) #define IsSurrogateL(c) ((c) >= 0xDC00 && (c) <= 0xDFFF) @@ -61,7 +64,8 @@ /* Additional file attribute bits for internal use */ #define AM_VOL 0x08 /* Volume label */ #define AM_LFN 0x0F /* LFN entry */ -#define AM_MASK 0x3F /* Mask of defined bits */ +#define AM_MASK 0x3F /* Mask of defined bits in FAT */ +#define AM_MASKX 0x37 /* Mask of defined bits in exFAT */ /* Name status flags in fn[11] */ @@ -204,26 +208,26 @@ #define PTE_StLba 8 /* MBR PTE: Start in LBA */ #define PTE_SizLba 12 /* MBR PTE: Size in LBA */ -#define GPTH_Sign 0 /* GPT: Header signature (8-byte) */ -#define GPTH_Rev 8 /* GPT: Revision (DWORD) */ -#define GPTH_Size 12 /* GPT: Header size (DWORD) */ -#define GPTH_Bcc 16 /* GPT: Header BCC (DWORD) */ -#define GPTH_CurLba 24 /* GPT: Main header LBA (QWORD) */ -#define GPTH_BakLba 32 /* GPT: Backup header LBA (QWORD) */ -#define GPTH_FstLba 40 /* GPT: First LBA for partitions (QWORD) */ -#define GPTH_LstLba 48 /* GPT: Last LBA for partitions (QWORD) */ -#define GPTH_DskGuid 56 /* GPT: Disk GUID (16-byte) */ -#define GPTH_PtOfs 72 /* GPT: Partation table LBA (QWORD) */ -#define GPTH_PtNum 80 /* GPT: Number of table entries (DWORD) */ -#define GPTH_PteSize 84 /* GPT: Size of table entry (DWORD) */ -#define GPTH_PtBcc 88 /* GPT: Partation table BCC (DWORD) */ -#define SZ_GPTE 128 /* GPT: Size of partition table entry */ +#define GPTH_Sign 0 /* GPT HDR: Signature (8-byte) */ +#define GPTH_Rev 8 /* GPT HDR: Revision (DWORD) */ +#define GPTH_Size 12 /* GPT HDR: Header size (DWORD) */ +#define GPTH_Bcc 16 /* GPT HDR: Header BCC (DWORD) */ +#define GPTH_CurLba 24 /* GPT HDR: This header LBA (QWORD) */ +#define GPTH_BakLba 32 /* GPT HDR: Another header LBA (QWORD) */ +#define GPTH_FstLba 40 /* GPT HDR: First LBA for partition data (QWORD) */ +#define GPTH_LstLba 48 /* GPT HDR: Last LBA for partition data (QWORD) */ +#define GPTH_DskGuid 56 /* GPT HDR: Disk GUID (16-byte) */ +#define GPTH_PtOfs 72 /* GPT HDR: Partition table LBA (QWORD) */ +#define GPTH_PtNum 80 /* GPT HDR: Number of table entries (DWORD) */ +#define GPTH_PteSize 84 /* GPT HDR: Size of table entry (DWORD) */ +#define GPTH_PtBcc 88 /* GPT HDR: Partition table BCC (DWORD) */ +#define SZ_GPTE 128 /* GPT PTE: Size of partition table entry */ #define GPTE_PtGuid 0 /* GPT PTE: Partition type GUID (16-byte) */ #define GPTE_UpGuid 16 /* GPT PTE: Partition unique GUID (16-byte) */ -#define GPTE_FstLba 32 /* GPT PTE: First LBA (QWORD) */ -#define GPTE_LstLba 40 /* GPT PTE: Last LBA inclusive (QWORD) */ -#define GPTE_Flags 48 /* GPT PTE: Flags (QWORD) */ -#define GPTE_Name 56 /* GPT PTE: Name */ +#define GPTE_FstLba 32 /* GPT PTE: First LBA of partition (QWORD) */ +#define GPTE_LstLba 40 /* GPT PTE: Last LBA of partition (QWORD) */ +#define GPTE_Flags 48 /* GPT PTE: Partition flags (QWORD) */ +#define GPTE_Name 56 /* GPT PTE: Partition name */ /* Post process on fatal error in the file operations */ @@ -233,9 +237,9 @@ /* Re-entrancy related */ #if FF_FS_REENTRANT #if FF_USE_LFN == 1 -#error Static LFN work area cannot be used at thread-safe configuration +#error Static LFN work area cannot be used in thread-safe configuration #endif -#define LEAVE_FF(fs, res) { unlock_fs(fs, res); return res; } +#define LEAVE_FF(fs, res) { unlock_volume(fs, res); return res; } #else #define LEAVE_FF(fs, res) return res #endif @@ -244,10 +248,10 @@ /* Definitions of logical drive - physical location conversion */ #if FF_MULTI_PARTITION #define LD2PD(vol) VolToPart[vol].pd /* Get physical drive number */ -#define LD2PT(vol) VolToPart[vol].pt /* Get partition index */ +#define LD2PT(vol) VolToPart[vol].pt /* Get partition number (0:auto search, 1..:forced partition number) */ #else #define LD2PD(vol) (BYTE)(vol) /* Each logical drive is associated with the same physical drive number */ -#define LD2PT(vol) 0 /* Find first valid partition or in SFD */ +#define LD2PT(vol) 0 /* Auto partition search */ #endif @@ -274,15 +278,15 @@ /* File lock controls */ -#if FF_FS_LOCK != 0 +#if FF_FS_LOCK #if FF_FS_READONLY #error FF_FS_LOCK must be 0 at read-only configuration #endif typedef struct { - FATFS *fs; /* Object ID 1, volume (NULL:blank entry) */ + FATFS* fs; /* Object ID 1, volume (NULL:blank entry) */ DWORD clu; /* Object ID 2, containing directory (0:root) */ DWORD ofs; /* Object ID 3, offset in the directory */ - WORD ctr; /* Object open counter, 0:none, 0x01..0xFF:read mode open count, 0x100:write mode */ + UINT ctr; /* Object open counter, 0:none, 0x01..0xFF:read mode open count, 0x100:write mode */ } FILESEM; #endif @@ -457,20 +461,23 @@ typedef struct { #if FF_VOLUMES < 1 || FF_VOLUMES > 10 #error Wrong FF_VOLUMES setting #endif -static FATFS* FatFs[FF_VOLUMES]; /* Pointer to the filesystem objects (logical drives) */ +static FATFS *FatFs[FF_VOLUMES]; /* Pointer to the filesystem objects (logical drives) */ static WORD Fsid; /* Filesystem mount ID */ #if FF_FS_RPATH != 0 -static BYTE CurrVol; /* Current drive */ +static BYTE CurrVol; /* Current drive set by f_chdrive() */ #endif #if FF_FS_LOCK != 0 static FILESEM Files[FF_FS_LOCK]; /* Open object lock semaphores */ +#if FF_FS_REENTRANT +static BYTE SysLock; /* System lock flag (0:no mutex, 1:unlocked, 2:locked) */ +#endif #endif #if FF_STR_VOLUME_ID #ifdef FF_VOLUME_STRS -static const char* const VolumeStr[FF_VOLUMES] = {FF_VOLUME_STRS}; /* Pre-defined volume ID */ +static const char *const VolumeStr[FF_VOLUMES] = {FF_VOLUME_STRS}; /* Pre-defined volume ID */ #endif #endif @@ -556,10 +563,11 @@ static WCHAR LfnBuf[FF_MAX_LFN + 1]; /* LFN working buffer */ /* Code conversion tables */ /*--------------------------------*/ -#if FF_CODE_PAGE == 0 /* Run-time code page configuration */ +#if FF_CODE_PAGE == 0 /* Run-time code page configuration */ #define CODEPAGE CodePage static WORD CodePage; /* Current code page */ -static const BYTE *ExCvt, *DbcTbl; /* Pointer to current SBCS up-case table and DBCS code range table below */ +static const BYTE* ExCvt; /* Ptr to SBCS up-case table Ct???[] (null:not used) */ +static const BYTE* DbcTbl; /* Ptr to DBCS code range table Dc???[] (null:not used) */ static const BYTE Ct437[] = TBL_CT437; static const BYTE Ct720[] = TBL_CT720; @@ -680,53 +688,6 @@ static void st_qword (BYTE* ptr, QWORD val) /* Store an 8-byte word in little-en /* String functions */ /*-----------------------------------------------------------------------*/ -/* Copy memory to memory */ -static void mem_cpy (void* dst, const void* src, UINT cnt) -{ - BYTE *d = (BYTE*)dst; - const BYTE *s = (const BYTE*)src; - - if (cnt != 0) { - do { - *d++ = *s++; - } while (--cnt); - } -} - - -/* Fill memory block */ -static void mem_set (void* dst, int val, UINT cnt) -{ - BYTE *d = (BYTE*)dst; - - do { - *d++ = (BYTE)val; - } while (--cnt); -} - - -/* Compare memory block */ -static int mem_cmp (const void* dst, const void* src, UINT cnt) /* ZR:same, NZ:different */ -{ - const BYTE *d = (const BYTE *)dst, *s = (const BYTE *)src; - int r = 0; - - do { - r = *d++ - *s++; - } while (--cnt && r == 0); - - return r; -} - - -/* Check if chr is contained in the string */ -static int chk_chr (const char* str, int chr) /* NZ:contained, ZR:not contained */ -{ - while (*str && *str != chr) str++; - return *str; -} - - /* Test if the byte is DBC 1st byte */ static int dbc_1st (BYTE c) { @@ -795,18 +756,14 @@ static DWORD tchar2uni ( /* Returns a character in UTF-16 encoding (>=0x10000 on uc = (BYTE)*p++; /* Get an encoding unit */ if (uc & 0x80) { /* Multiple byte code? */ - if ((uc & 0xE0) == 0xC0) { /* 2-byte sequence? */ + if ((uc & 0xE0) == 0xC0) { /* 2-byte sequence? */ uc &= 0x1F; nf = 1; - } else { - if ((uc & 0xF0) == 0xE0) { /* 3-byte sequence? */ - uc &= 0x0F; nf = 2; - } else { - if ((uc & 0xF8) == 0xF0) { /* 4-byte sequence? */ - uc &= 0x07; nf = 3; - } else { /* Wrong sequence */ - return 0xFFFFFFFF; - } - } + } else if ((uc & 0xF0) == 0xE0) { /* 3-byte sequence? */ + uc &= 0x0F; nf = 2; + } else if ((uc & 0xF8) == 0xF0) { /* 4-byte sequence? */ + uc &= 0x07; nf = 3; + } else { /* Wrong sequence */ + return 0xFFFFFFFF; } do { /* Get trailing bytes */ b = (BYTE)*p++; @@ -844,8 +801,8 @@ static DWORD tchar2uni ( /* Returns a character in UTF-16 encoding (>=0x10000 on } -/* Output a TCHAR string in defined API encoding */ -static BYTE put_utf ( /* Returns number of encoding units written (0:buffer overflow or wrong encoding) */ +/* Store a Unicode char in defined API encoding */ +static UINT put_utf ( /* Returns number of encoding units written (0:buffer overflow or wrong encoding) */ DWORD chr, /* UTF-16 encoded character (Surrogate pair if >=0x10000) */ TCHAR* buf, /* Output buffer */ UINT szb /* Size of the buffer */ @@ -934,21 +891,45 @@ static BYTE put_utf ( /* Returns number of encoding units written (0:buffer over /*-----------------------------------------------------------------------*/ /* Request/Release grant to access the volume */ /*-----------------------------------------------------------------------*/ -static int lock_fs ( /* 1:Ok, 0:timeout */ - FATFS* fs /* Filesystem object */ + +static int lock_volume ( /* 1:Ok, 0:timeout */ + FATFS* fs, /* Filesystem object to lock */ + int syslock /* System lock required */ ) { - return ff_req_grant(fs->sobj); + int rv; + + +#if FF_FS_LOCK + rv = ff_mutex_take(fs->ldrv); /* Lock the volume */ + if (rv && syslock) { /* System lock reqiered? */ + rv = ff_mutex_take(FF_VOLUMES); /* Lock the system */ + if (rv) { + SysLock = 2; /* System lock succeeded */ + } else { + ff_mutex_give(fs->ldrv); /* Failed system lock */ + } + } +#else + rv = syslock ? ff_mutex_take(fs->ldrv) : ff_mutex_take(fs->ldrv); /* Lock the volume (this is to prevent compiler warning) */ +#endif + return rv; } -static void unlock_fs ( +static void unlock_volume ( FATFS* fs, /* Filesystem object */ FRESULT res /* Result code to be returned */ ) { if (fs && res != FR_NOT_ENABLED && res != FR_INVALID_DRIVE && res != FR_TIMEOUT) { - ff_rel_grant(fs->sobj); +#if FF_FS_LOCK + if (SysLock == 2) { /* Is the system locked? */ + SysLock = 1; + ff_mutex_give(FF_VOLUMES); + } +#endif + ff_mutex_give(fs->ldrv); /* Unlock the volume */ } } @@ -956,12 +937,12 @@ static void unlock_fs ( -#if FF_FS_LOCK != 0 +#if FF_FS_LOCK /*-----------------------------------------------------------------------*/ -/* File lock control functions */ +/* File shareing control functions */ /*-----------------------------------------------------------------------*/ -static FRESULT chk_lock ( /* Check if the file can be accessed */ +static FRESULT chk_share ( /* Check if the file can be accessed */ DIR* dp, /* Directory object pointing the file to be checked */ int acc /* Desired access type (0:Read mode open, 1:Write mode open, 2:Delete or rename) */ ) @@ -988,16 +969,16 @@ static FRESULT chk_lock ( /* Check if the file can be accessed */ } -static int enq_lock (void) /* Check if an entry is available for a new object */ +static int enq_share (void) /* Check if an entry is available for a new object */ { UINT i; - for (i = 0; i < FF_FS_LOCK && Files[i].fs; i++) ; + for (i = 0; i < FF_FS_LOCK && Files[i].fs; i++) ; /* Find a free entry */ return (i == FF_FS_LOCK) ? 0 : 1; } -static UINT inc_lock ( /* Increment object open counter and returns its index (0:Internal error) */ +static UINT inc_share ( /* Increment object open counter and returns its index (0:Internal error) */ DIR* dp, /* Directory object pointing the file to register or increment */ int acc /* Desired access (0:Read, 1:Write, 2:Delete/Rename) */ ) @@ -1011,8 +992,8 @@ static UINT inc_lock ( /* Increment object open counter and returns its index (0 && Files[i].ofs == dp->dptr) break; } - if (i == FF_FS_LOCK) { /* Not opened. Register it as new. */ - for (i = 0; i < FF_FS_LOCK && Files[i].fs; i++) ; + if (i == FF_FS_LOCK) { /* Not opened. Register it as new. */ + for (i = 0; i < FF_FS_LOCK && Files[i].fs; i++) ; /* Find a free entry */ if (i == FF_FS_LOCK) return 0; /* No free entry to register (int err) */ Files[i].fs = dp->obj.fs; Files[i].clu = dp->obj.sclust; @@ -1028,30 +1009,32 @@ static UINT inc_lock ( /* Increment object open counter and returns its index (0 } -static FRESULT dec_lock ( /* Decrement object open counter */ +static FRESULT dec_share ( /* Decrement object open counter */ UINT i /* Semaphore index (1..) */ ) { - WORD n; + UINT n; FRESULT res; if (--i < FF_FS_LOCK) { /* Index number origin from 0 */ n = Files[i].ctr; - if (n == 0x100) n = 0; /* If write mode open, delete the entry */ - if (n > 0) n--; /* Decrement read mode open count */ + if (n == 0x100) n = 0; /* If write mode open, delete the object semaphore */ + if (n > 0) n--; /* Decrement read mode open count */ Files[i].ctr = n; - if (n == 0) Files[i].fs = 0; /* Delete the entry if open count gets zero */ + if (n == 0) { /* Delete the object semaphore if open count becomes zero */ + Files[i].fs = 0; /* Free the entry << 1, there is a potential error in this process >>> */ + } res = FR_OK; } else { - res = FR_INT_ERR; /* Invalid index nunber */ + res = FR_INT_ERR; /* Invalid index number */ } return res; } -static void clear_lock ( /* Clear lock entries of the volume */ - FATFS *fs +static void clear_share ( /* Clear all lock entries of the volume */ + FATFS* fs ) { UINT i; @@ -1061,7 +1044,7 @@ static void clear_lock ( /* Clear lock entries of the volume */ } } -#endif /* FF_FS_LOCK != 0 */ +#endif /* FF_FS_LOCK */ @@ -1133,7 +1116,7 @@ static FRESULT sync_fs ( /* Returns FR_OK or FR_DISK_ERR */ if (res == FR_OK) { if (fs->fs_type == FS_FAT32 && fs->fsi_flag == 1) { /* FAT32: Update FSInfo sector if needed */ /* Create FSInfo structure */ - mem_set(fs->win, 0, sizeof fs->win); + memset(fs->win, 0, sizeof fs->win); st_word(fs->win + BS_55AA, 0xAA55); /* Boot signature */ st_dword(fs->win + FSI_LeadSig, 0x41615252); /* Leading signature */ st_dword(fs->win + FSI_StrucSig, 0x61417272); /* Structure signature */ @@ -1172,7 +1155,7 @@ static LBA_t clst2sect ( /* !=0:Sector number, 0:Failed (invalid cluster#) */ /*-----------------------------------------------------------------------*/ -/* FAT access - Read value of a FAT entry */ +/* FAT access - Read value of an FAT entry */ /*-----------------------------------------------------------------------*/ static DWORD get_fat ( /* 0xFFFFFFFF:Disk error, 1:Internal error, 2..0x7FFFFFFF:Cluster status */ @@ -1250,7 +1233,7 @@ static DWORD get_fat ( /* 0xFFFFFFFF:Disk error, 1:Internal error, 2..0x7FFFFFF #if !FF_FS_READONLY /*-----------------------------------------------------------------------*/ -/* FAT access - Change value of a FAT entry */ +/* FAT access - Change value of an FAT entry */ /*-----------------------------------------------------------------------*/ static FRESULT put_fat ( /* FR_OK(0):succeeded, !=0:error */ @@ -1271,7 +1254,7 @@ static FRESULT put_fat ( /* FR_OK(0):succeeded, !=0:error */ res = move_window(fs, fs->fatbase + (bc / SS(fs))); if (res != FR_OK) break; p = fs->win + bc++ % SS(fs); - *p = (clst & 1) ? ((*p & 0x0F) | ((BYTE)val << 4)) : (BYTE)val; /* Update 1st byte */ + *p = (clst & 1) ? ((*p & 0x0F) | ((BYTE)val << 4)) : (BYTE)val; /* Update 1st byte */ fs->wflag = 1; res = move_window(fs, fs->fatbase + (bc / SS(fs))); if (res != FR_OK) break; @@ -1646,7 +1629,8 @@ static DWORD clmt_clust ( /* <2:Error, >=2:Cluster number */ FSIZE_t ofs /* File offset to be converted to cluster# */ ) { - DWORD cl, ncl, *tbl; + DWORD cl, ncl; + DWORD *tbl; FATFS *fs = fp->obj.fs; @@ -1684,12 +1668,12 @@ static FRESULT dir_clear ( /* Returns FR_OK or FR_DISK_ERR */ if (sync_window(fs) != FR_OK) return FR_DISK_ERR; /* Flush disk access window */ sect = clst2sect(fs, clst); /* Top of the cluster */ fs->winsect = sect; /* Set window to top of the cluster */ - mem_set(fs->win, 0, sizeof fs->win); /* Clear window buffer */ + memset(fs->win, 0, sizeof fs->win); /* Clear window buffer */ #if FF_USE_LFN == 3 /* Quick table clear by using multi-secter write */ /* Allocate a temporary buffer */ for (szb = ((DWORD)fs->csize * SS(fs) >= MAX_MALLOC) ? MAX_MALLOC : fs->csize * SS(fs), ibuf = 0; szb > SS(fs) && (ibuf = ff_memalloc(szb)) == 0; szb /= 2) ; if (szb > SS(fs)) { /* Buffer allocated? */ - mem_set(ibuf, 0, szb); + memset(ibuf, 0, szb); szb /= SS(fs); /* Bytes -> Sectors */ for (n = 0; n < fs->csize && disk_write(fs->pdrv, ibuf, sect + n, szb) == RES_OK; n += szb) ; /* Fill the cluster with 0 */ ff_memfree(ibuf); @@ -1993,7 +1977,7 @@ static void put_lfn ( do { if (wc != 0xFFFF) wc = lfn[i++]; /* Get an effective character */ st_word(dir + LfnOfs[s], wc); /* Put it */ - if (wc == 0) wc = 0xFFFF; /* Padding characters for following items */ + if (wc == 0) wc = 0xFFFF; /* Padding characters for following items */ } while (++s < 13); if (wc == 0xFFFF || !lfn[i]) ord |= LLEF; /* Last LFN part is the start of LFN sequence */ dir[LDIR_Ord] = ord; /* Set the LFN order */ @@ -2011,7 +1995,7 @@ static void put_lfn ( static void gen_numname ( BYTE* dst, /* Pointer to the buffer to store numbered SFN */ - const BYTE* src, /* Pointer to SFN */ + const BYTE* src, /* Pointer to SFN in directory form */ const WCHAR* lfn, /* Pointer to LFN */ UINT seq /* Sequence number */ ) @@ -2022,7 +2006,7 @@ static void gen_numname ( DWORD sreg; - mem_cpy(dst, src, 11); + memcpy(dst, src, 11); /* Prepare the SFN to be modified */ if (seq > 5) { /* In case of many collisions, generate a hash number instead of sequential number */ sreg = seq; @@ -2037,24 +2021,23 @@ static void gen_numname ( seq = (UINT)sreg; } - /* itoa (hexdecimal) */ + /* Make suffix (~ + hexadecimal) */ i = 7; do { - c = (BYTE)((seq % 16) + '0'); + c = (BYTE)((seq % 16) + '0'); seq /= 16; if (c > '9') c += 7; ns[i--] = c; - seq /= 16; - } while (seq); + } while (i && seq); ns[i] = '~'; - /* Append the number to the SFN body */ - for (j = 0; j < i && dst[j] != ' '; j++) { - if (dbc_1st(dst[j])) { + /* Append the suffix to the SFN body */ + for (j = 0; j < i && dst[j] != ' '; j++) { /* Find the offset to append */ + if (dbc_1st(dst[j])) { /* To avoid DBC break up */ if (j == i - 1) break; j++; } } - do { + do { /* Append the suffix */ dst[j++] = (i < 8) ? ns[i++] : ' '; } while (j < 8); } @@ -2139,80 +2122,39 @@ static DWORD xsum32 ( /* Returns 32-bit checksum */ #endif -#if FF_FS_MINIMIZE <= 1 || FF_FS_RPATH >= 2 -/*------------------------------------------------------*/ -/* exFAT: Get object information from a directory block */ -/*------------------------------------------------------*/ - -static void get_xfileinfo ( - BYTE* dirb, /* Pointer to the direcotry entry block 85+C0+C1s */ - FILINFO* fno /* Buffer to store the extracted file information */ -) -{ - WCHAR wc, hs; - UINT di, si, nc; - - /* Get file name from the entry block */ - si = SZDIRE * 2; /* 1st C1 entry */ - nc = 0; hs = 0; di = 0; - while (nc < dirb[XDIR_NumName]) { - if (si >= MAXDIRB(FF_MAX_LFN)) { di = 0; break; } /* Truncated directory block? */ - if ((si % SZDIRE) == 0) si += 2; /* Skip entry type field */ - wc = ld_word(dirb + si); si += 2; nc++; /* Get a character */ - if (hs == 0 && IsSurrogate(wc)) { /* Is it a surrogate? */ - hs = wc; continue; /* Get low surrogate */ - } - wc = put_utf((DWORD)hs << 16 | wc, &fno->fname[di], FF_LFN_BUF - di); /* Store it in API encoding */ - if (wc == 0) { di = 0; break; } /* Buffer overflow or wrong encoding? */ - di += wc; - hs = 0; - } - if (hs != 0) di = 0; /* Broken surrogate pair? */ - if (di == 0) fno->fname[di++] = '?'; /* Inaccessible object name? */ - fno->fname[di] = 0; /* Terminate the name */ - fno->altname[0] = 0; /* exFAT does not support SFN */ - - fno->fattrib = dirb[XDIR_Attr]; /* Attribute */ - fno->fsize = (fno->fattrib & AM_DIR) ? 0 : ld_qword(dirb + XDIR_FileSize); /* Size */ - fno->ftime = ld_word(dirb + XDIR_ModTime + 0); /* Time */ - fno->fdate = ld_word(dirb + XDIR_ModTime + 2); /* Date */ -} - -#endif /* FF_FS_MINIMIZE <= 1 || FF_FS_RPATH >= 2 */ - -/*-----------------------------------*/ -/* exFAT: Get a directry entry block */ -/*-----------------------------------*/ +/*------------------------------------*/ +/* exFAT: Get a directory entry block */ +/*------------------------------------*/ static FRESULT load_xdir ( /* FR_INT_ERR: invalid entry block */ - DIR* dp /* Reading direcotry object pointing top of the entry block to load */ + DIR* dp /* Reading directory object pointing top of the entry block to load */ ) { FRESULT res; UINT i, sz_ent; - BYTE* dirb = dp->obj.fs->dirbuf; /* Pointer to the on-memory direcotry entry block 85+C0+C1s */ + BYTE *dirb = dp->obj.fs->dirbuf; /* Pointer to the on-memory directory entry block 85+C0+C1s */ - /* Load file-directory entry */ + /* Load file directory entry */ res = move_window(dp->obj.fs, dp->sect); if (res != FR_OK) return res; if (dp->dir[XDIR_Type] != ET_FILEDIR) return FR_INT_ERR; /* Invalid order */ - mem_cpy(dirb + 0 * SZDIRE, dp->dir, SZDIRE); + memcpy(dirb + 0 * SZDIRE, dp->dir, SZDIRE); sz_ent = (dirb[XDIR_NumSec] + 1) * SZDIRE; if (sz_ent < 3 * SZDIRE || sz_ent > 19 * SZDIRE) return FR_INT_ERR; - /* Load stream-extension entry */ + /* Load stream extension entry */ res = dir_next(dp, 0); if (res == FR_NO_FILE) res = FR_INT_ERR; /* It cannot be */ if (res != FR_OK) return res; res = move_window(dp->obj.fs, dp->sect); if (res != FR_OK) return res; if (dp->dir[XDIR_Type] != ET_STREAM) return FR_INT_ERR; /* Invalid order */ - mem_cpy(dirb + 1 * SZDIRE, dp->dir, SZDIRE); + memcpy(dirb + 1 * SZDIRE, dp->dir, SZDIRE); if (MAXDIRB(dirb[XDIR_NumName]) > sz_ent) return FR_INT_ERR; - /* Load file-name entries */ + /* Load file name entries */ i = 2 * SZDIRE; /* Name offset to load */ do { res = dir_next(dp, 0); @@ -2221,7 +2163,7 @@ static FRESULT load_xdir ( /* FR_INT_ERR: invalid entry block */ res = move_window(dp->obj.fs, dp->sect); if (res != FR_OK) return res; if (dp->dir[XDIR_Type] != ET_FILENAME) return FR_INT_ERR; /* Invalid order */ - if (i < MAXDIRB(FF_MAX_LFN)) mem_cpy(dirb + i, dp->dir, SZDIRE); + if (i < MAXDIRB(FF_MAX_LFN)) memcpy(dirb + i, dp->dir, SZDIRE); } while ((i += SZDIRE) < sz_ent); /* Sanity check (do it for only accessible object) */ @@ -2255,7 +2197,7 @@ static void init_alloc_info ( /*------------------------------------------------*/ static FRESULT load_obj_xdir ( - DIR* dp, /* Blank directory object to be used to access containing direcotry */ + DIR* dp, /* Blank directory object to be used to access containing directory */ const FFOBJID* obj /* Object with its containing directory information */ ) { @@ -2284,23 +2226,23 @@ static FRESULT load_obj_xdir ( /*----------------------------------------*/ static FRESULT store_xdir ( - DIR* dp /* Pointer to the direcotry object */ + DIR* dp /* Pointer to the directory object */ ) { FRESULT res; UINT nent; - BYTE* dirb = dp->obj.fs->dirbuf; /* Pointer to the direcotry entry block 85+C0+C1s */ + BYTE *dirb = dp->obj.fs->dirbuf; /* Pointer to the directory entry block 85+C0+C1s */ /* Create set sum */ st_word(dirb + XDIR_SetSum, xdir_sum(dirb)); nent = dirb[XDIR_NumSec] + 1; - /* Store the direcotry entry block to the directory */ + /* Store the directory entry block to the directory */ res = dir_sdi(dp, dp->blk_ofs); while (res == FR_OK) { res = move_window(dp->obj.fs, dp->sect); if (res != FR_OK) break; - mem_cpy(dp->dir, dirb, SZDIRE); + memcpy(dp->dir, dirb, SZDIRE); dp->obj.fs->wflag = 1; if (--nent == 0) break; dirb += SZDIRE; @@ -2312,11 +2254,11 @@ static FRESULT store_xdir ( /*-------------------------------------------*/ -/* exFAT: Create a new directory enrty block */ +/* exFAT: Create a new directory entry block */ /*-------------------------------------------*/ static void create_xdir ( - BYTE* dirb, /* Pointer to the direcotry entry block buffer */ + BYTE* dirb, /* Pointer to the directory entry block buffer */ const WCHAR* lfn /* Pointer to the object name */ ) { @@ -2326,7 +2268,7 @@ static void create_xdir ( /* Create file-directory and stream-extension entry */ - mem_set(dirb, 0, 2 * SZDIRE); + memset(dirb, 0, 2 * SZDIRE); dirb[0 * SZDIRE + XDIR_Type] = ET_FILEDIR; dirb[1 * SZDIRE + XDIR_Type] = ET_STREAM; @@ -2337,7 +2279,7 @@ static void create_xdir ( dirb[i++] = ET_FILENAME; dirb[i++] = 0; do { /* Fill name field */ if (wc != 0 && (wc = lfn[nlen]) != 0) nlen++; /* Get a character if exist */ - st_word(dirb + i, wc); /* Store it */ + st_word(dirb + i, wc); /* Store it */ i += 2; } while (i % SZDIRE != 0); nc1++; @@ -2402,17 +2344,17 @@ static FRESULT dir_read ( if (b == DDEM || b == '.' || (int)((attr & ~AM_ARC) == AM_VOL) != vol) { /* An entry without valid data */ ord = 0xFF; } else { - if (attr == AM_LFN) { /* An LFN entry is found */ - if (b & LLEF) { /* Is it start of an LFN sequence? */ + if (attr == AM_LFN) { /* An LFN entry is found */ + if (b & LLEF) { /* Is it start of an LFN sequence? */ sum = dp->dir[LDIR_Chksum]; b &= (BYTE)~LLEF; ord = b; dp->blk_ofs = dp->dptr; } /* Check LFN validity and capture it */ ord = (b == ord && sum == dp->dir[LDIR_Chksum] && pick_lfn(fs->lfnbuf, dp->dir)) ? ord - 1 : 0xFF; - } else { /* An SFN entry is found */ + } else { /* An SFN entry is found */ if (ord != 0 || sum != sum_sfn(dp->dir)) { /* Is there a valid LFN? */ - dp->blk_ofs = 0xFFFFFFFF; /* It has no LFN. */ + dp->blk_ofs = 0xFFFFFFFF; /* It has no LFN. */ } break; } @@ -2460,7 +2402,7 @@ static FRESULT dir_find ( /* FR_OK(0):succeeded, !=0:error */ while ((res = DIR_READ_FILE(dp)) == FR_OK) { /* Read an item */ #if FF_MAX_LFN < 255 - if (fs->dirbuf[XDIR_NumName] > FF_MAX_LFN) continue; /* Skip comparison if inaccessible object name */ + if (fs->dirbuf[XDIR_NumName] > FF_MAX_LFN) continue; /* Skip comparison if inaccessible object name */ #endif if (ld_word(fs->dirbuf + XDIR_NameHash) != hash) continue; /* Skip comparison if hash mismatched */ for (nc = fs->dirbuf[XDIR_NumName], di = SZDIRE * 2, ni = 0; nc; nc--, di += 2, ni++) { /* Compare the name */ @@ -2498,13 +2440,13 @@ static FRESULT dir_find ( /* FR_OK(0):succeeded, !=0:error */ } } else { /* An SFN entry is found */ if (ord == 0 && sum == sum_sfn(dp->dir)) break; /* LFN matched? */ - if (!(dp->fn[NSFLAG] & NS_LOSS) && !mem_cmp(dp->dir, dp->fn, 11)) break; /* SFN matched? */ + if (!(dp->fn[NSFLAG] & NS_LOSS) && !memcmp(dp->dir, dp->fn, 11)) break; /* SFN matched? */ ord = 0xFF; dp->blk_ofs = 0xFFFFFFFF; /* Reset LFN sequence */ } } #else /* Non LFN configuration */ dp->obj.attr = dp->dir[DIR_Attr] & AM_MASK; - if (!(dp->dir[DIR_Attr] & AM_VOL) && !mem_cmp(dp->dir, dp->fn, 11)) break; /* Is it a valid entry? */ + if (!(dp->dir[DIR_Attr] & AM_VOL) && !memcmp(dp->dir, dp->fn, 11)) break; /* Is it a valid entry? */ #endif res = dir_next(dp, 0); /* Next entry */ } while (res == FR_OK); @@ -2552,10 +2494,10 @@ static FRESULT dir_register ( /* FR_OK:succeeded, FR_DENIED:no free entry or too res = load_obj_xdir(&dj, &dp->obj); /* Load the object status */ if (res != FR_OK) return res; - dp->obj.objsize += (DWORD)fs->csize * SS(fs); /* Increase the directory size by cluster size */ + dp->obj.objsize += (DWORD)fs->csize * SS(fs); /* Increase the directory size by cluster size */ st_qword(fs->dirbuf + XDIR_FileSize, dp->obj.objsize); st_qword(fs->dirbuf + XDIR_ValidFileSize, dp->obj.objsize); - fs->dirbuf[XDIR_GenFlags] = dp->obj.stat | 1; /* Update the allocation status */ + fs->dirbuf[XDIR_GenFlags] = dp->obj.stat | 1; /* Update the allocation status */ res = store_xdir(&dj); /* Store the object status */ if (res != FR_OK) return res; } @@ -2566,7 +2508,7 @@ static FRESULT dir_register ( /* FR_OK:succeeded, FR_DENIED:no free entry or too } #endif /* On the FAT/FAT32 volume */ - mem_cpy(sn, dp->fn, 12); + memcpy(sn, dp->fn, 12); if (sn[NSFLAG] & NS_LOSS) { /* When LFN is out of 8.3 format, generate a numbered name */ dp->fn[NSFLAG] = NS_NOLFN; /* Find only SFN */ for (n = 1; n < 100; n++) { @@ -2605,8 +2547,8 @@ static FRESULT dir_register ( /* FR_OK:succeeded, FR_DENIED:no free entry or too if (res == FR_OK) { res = move_window(fs, dp->sect); if (res == FR_OK) { - mem_set(dp->dir, 0, SZDIRE); /* Clean the entry */ - mem_cpy(dp->dir + DIR_Name, dp->fn, 11); /* Put SFN */ + memset(dp->dir, 0, SZDIRE); /* Clean the entry */ + memcpy(dp->dir + DIR_Name, dp->fn, 11); /* Put SFN */ #if FF_USE_LFN dp->dir[DIR_NTres] = dp->fn[NSFLAG] & (NS_BODY | NS_EXT); /* Put NT flag */ #endif @@ -2642,7 +2584,7 @@ static FRESULT dir_remove ( /* FR_OK:Succeeded, FR_DISK_ERR:A disk error */ if (res != FR_OK) break; if (FF_FS_EXFAT && fs->fs_type == FS_EXFAT) { /* On the exFAT volume */ dp->dir[XDIR_Type] &= 0x7F; /* Clear the entry InUse flag. */ - } else { /* On the FAT/FAT32 volume */ + } else { /* On the FAT/FAT32 volume */ dp->dir[DIR_Name] = DDEM; /* Mark the entry 'deleted'. */ } fs->wflag = 1; @@ -2682,6 +2624,7 @@ static void get_fileinfo ( BYTE lcf; WCHAR wc, hs; FATFS *fs = dp->obj.fs; + UINT nw; #else TCHAR c; #endif @@ -2692,22 +2635,53 @@ static void get_fileinfo ( #if FF_USE_LFN /* LFN configuration */ #if FF_FS_EXFAT - if (fs->fs_type == FS_EXFAT) { /* On the exFAT volume */ - get_xfileinfo(fs->dirbuf, fno); + if (fs->fs_type == FS_EXFAT) { /* exFAT volume */ + UINT nc = 0; + + si = SZDIRE * 2; di = 0; /* 1st C1 entry in the entry block */ + hs = 0; + while (nc < fs->dirbuf[XDIR_NumName]) { + if (si >= MAXDIRB(FF_MAX_LFN)) { /* Truncated directory block? */ + di = 0; break; + } + if ((si % SZDIRE) == 0) si += 2; /* Skip entry type field */ + wc = ld_word(fs->dirbuf + si); si += 2; nc++; /* Get a character */ + if (hs == 0 && IsSurrogate(wc)) { /* Is it a surrogate? */ + hs = wc; continue; /* Get low surrogate */ + } + nw = put_utf((DWORD)hs << 16 | wc, &fno->fname[di], FF_LFN_BUF - di); /* Store it in API encoding */ + if (nw == 0) { /* Buffer overflow or wrong char? */ + di = 0; break; + } + di += nw; + hs = 0; + } + if (hs != 0) di = 0; /* Broken surrogate pair? */ + if (di == 0) fno->fname[di++] = '\?'; /* Inaccessible object name? */ + fno->fname[di] = 0; /* Terminate the name */ + fno->altname[0] = 0; /* exFAT does not support SFN */ + + fno->fattrib = fs->dirbuf[XDIR_Attr] & AM_MASKX; /* Attribute */ + fno->fsize = (fno->fattrib & AM_DIR) ? 0 : ld_qword(fs->dirbuf + XDIR_FileSize); /* Size */ + fno->ftime = ld_word(fs->dirbuf + XDIR_ModTime + 0); /* Time */ + fno->fdate = ld_word(fs->dirbuf + XDIR_ModTime + 2); /* Date */ return; } else #endif - { /* On the FAT/FAT32 volume */ + { /* FAT/FAT32 volume */ if (dp->blk_ofs != 0xFFFFFFFF) { /* Get LFN if available */ - si = di = hs = 0; + si = di = 0; + hs = 0; while (fs->lfnbuf[si] != 0) { wc = fs->lfnbuf[si++]; /* Get an LFN character (UTF-16) */ if (hs == 0 && IsSurrogate(wc)) { /* Is it a surrogate? */ hs = wc; continue; /* Get low surrogate */ } - wc = put_utf((DWORD)hs << 16 | wc, &fno->fname[di], FF_LFN_BUF - di); /* Store it in UTF-16 or UTF-8 encoding */ - if (wc == 0) { di = 0; break; } /* Invalid char or buffer overflow? */ - di += wc; + nw = put_utf((DWORD)hs << 16 | wc, &fno->fname[di], FF_LFN_BUF - di); /* Store it in API encoding */ + if (nw == 0) { /* Buffer overflow or wrong char? */ + di = 0; break; + } + di += nw; hs = 0; } if (hs != 0) di = 0; /* Broken surrogate pair? */ @@ -2726,10 +2700,14 @@ static void get_fileinfo ( wc = wc << 8 | dp->dir[si++]; } wc = ff_oem2uni(wc, CODEPAGE); /* ANSI/OEM -> Unicode */ - if (wc == 0) { di = 0; break; } /* Wrong char in the current code page? */ - wc = put_utf(wc, &fno->altname[di], FF_SFN_BUF - di); /* Store it in Unicode */ - if (wc == 0) { di = 0; break; } /* Buffer overflow? */ - di += wc; + if (wc == 0) { /* Wrong char in the current code page? */ + di = 0; break; + } + nw = put_utf(wc, &fno->altname[di], FF_SFN_BUF - di); /* Store it in API encoding */ + if (nw == 0) { /* Buffer overflow? */ + di = 0; break; + } + di += nw; #else /* ANSI/OEM output */ fno->altname[di++] = (TCHAR)wc; /* Store it without any conversion */ #endif @@ -2737,8 +2715,8 @@ static void get_fileinfo ( fno->altname[di] = 0; /* Terminate the SFN (null string means SFN is invalid) */ if (fno->fname[0] == 0) { /* If LFN is invalid, altname[] needs to be copied to fname[] */ - if (di == 0) { /* If LFN and SFN both are invalid, this object is inaccesible */ - fno->fname[di++] = '?'; + if (di == 0) { /* If LFN and SFN both are invalid, this object is inaccessible */ + fno->fname[di++] = '\?'; } else { for (si = di = 0, lcf = NS_BODY; fno->altname[si]; si++, di++) { /* Copy altname[] to fname[] with case information */ wc = (WCHAR)fno->altname[si]; @@ -2760,10 +2738,10 @@ static void get_fileinfo ( if (si == 9) fno->fname[di++] = '.';/* Insert a . if extension is exist */ fno->fname[di++] = c; } - fno->fname[di] = 0; + fno->fname[di] = 0; /* Terminate the SFN */ #endif - fno->fattrib = dp->dir[DIR_Attr]; /* Attribute */ + fno->fattrib = dp->dir[DIR_Attr] & AM_MASK; /* Attribute */ fno->fsize = ld_dword(dp->dir + DIR_FileSize); /* Size */ fno->ftime = ld_word(dp->dir + DIR_ModTime + 0); /* Time */ fno->fdate = ld_word(dp->dir + DIR_ModTime + 2); /* Date */ @@ -2819,7 +2797,8 @@ static int pattern_match ( /* 0:mismatched, 1:matched */ UINT recur /* Recursion count */ ) { - const TCHAR *pptr, *nptr; + const TCHAR *pptr; + const TCHAR *nptr; DWORD pchr, nchr; UINT sk; @@ -2833,12 +2812,16 @@ static int pattern_match ( /* 0:mismatched, 1:matched */ do { pptr = pat; nptr = nam; /* Top of pattern and name to match */ for (;;) { - if (*pptr == '?' || *pptr == '*') { /* Wildcard term? */ + if (*pptr == '\?' || *pptr == '*') { /* Wildcard term? */ if (recur == 0) return 0; /* Too many wildcard terms? */ sk = 0; do { /* Analyze the wildcard term */ - if (*pptr++ == '?') sk++; else sk |= 0x100; - } while (*pptr == '?' || *pptr == '*'); + if (*pptr++ == '\?') { + sk++; + } else { + sk |= 0x100; + } + } while (*pptr == '\?' || *pptr == '*'); if (pattern_match(pptr, nptr, sk, recur - 1)) return 1; /* Test new branch (recursive call) */ nchr = *nptr; break; /* Branch mismatched */ } @@ -2868,10 +2851,11 @@ static FRESULT create_name ( /* FR_OK: successful, FR_INVALID_NAME: could not cr { #if FF_USE_LFN /* LFN configuration */ BYTE b, cf; - WCHAR wc, *lfn; + WCHAR wc; + WCHAR *lfn; + const TCHAR* p; DWORD uc; UINT i, ni, si, di; - const TCHAR *p; /* Create LFN into LFN working buffer */ @@ -2881,16 +2865,17 @@ static FRESULT create_name ( /* FR_OK: successful, FR_INVALID_NAME: could not cr if (uc == 0xFFFFFFFF) return FR_INVALID_NAME; /* Invalid code or UTF decode error */ if (uc >= 0x10000) lfn[di++] = (WCHAR)(uc >> 16); /* Store high surrogate if needed */ wc = (WCHAR)uc; - if (wc < ' ' || wc == '/' || wc == '\\') break; /* Break if end of the path or a separator is found */ - if (wc < 0x80 && chk_chr("\"*:<>\?|\x7F", wc)) return FR_INVALID_NAME; /* Reject illegal characters for LFN */ + if (wc < ' ' || IsSeparator(wc)) break; /* Break if end of the path or a separator is found */ + if (wc < 0x80 && strchr("*:<>|\"\?\x7F", (int)wc)) return FR_INVALID_NAME; /* Reject illegal characters for LFN */ if (di >= FF_MAX_LFN) return FR_INVALID_NAME; /* Reject too long name */ - lfn[di++] = wc; /* Store the Unicode character */ + lfn[di++] = wc; /* Store the Unicode character */ } - if (wc < ' ') { /* End of path? */ - cf = NS_LAST; /* Set last segment flag */ - } else { - cf = 0; /* Next segment follows */ - while (*p == '/' || *p == '\\') p++; /* Skip duplicated separators if exist */ + if (wc < ' ') { /* Stopped at end of the path? */ + cf = NS_LAST; /* Last segment */ + } else { /* Stopped at a separator */ + while (IsSeparator(*p)) p++; /* Skip duplicated separators if exist */ + cf = 0; /* Next segment may follow */ + if (IsTerminator(*p)) cf = NS_LAST; /* Ignore terminating separator */ } *path = p; /* Return pointer to the next segment */ @@ -2898,14 +2883,14 @@ static FRESULT create_name ( /* FR_OK: successful, FR_INVALID_NAME: could not cr if ((di == 1 && lfn[di - 1] == '.') || (di == 2 && lfn[di - 1] == '.' && lfn[di - 2] == '.')) { /* Is this segment a dot name? */ lfn[di] = 0; - for (i = 0; i < 11; i++) { /* Create dot name for SFN entry */ + for (i = 0; i < 11; i++) { /* Create dot name for SFN entry */ dp->fn[i] = (i < di) ? '.' : ' '; } - dp->fn[i] = cf | NS_DOT; /* This is a dot entry */ + dp->fn[i] = cf | NS_DOT; /* This is a dot entry */ return FR_OK; } #endif - while (di) { /* Snip off trailing spaces and dots if exist */ + while (di) { /* Snip off trailing spaces and dots if exist */ wc = lfn[di - 1]; if (wc != ' ' && wc != '.') break; di--; @@ -2918,7 +2903,7 @@ static FRESULT create_name ( /* FR_OK: successful, FR_INVALID_NAME: could not cr if (si > 0 || lfn[si] == '.') cf |= NS_LOSS | NS_LFN; /* Is there any leading space or dot? */ while (di > 0 && lfn[di - 1] != '.') di--; /* Find last dot (di<=si: no extension) */ - mem_set(dp->fn, ' ', 11); + memset(dp->fn, ' ', 11); i = b = 0; ni = 8; for (;;) { wc = lfn[si++]; /* Get an LFN character */ @@ -2939,20 +2924,20 @@ static FRESULT create_name ( /* FR_OK: successful, FR_INVALID_NAME: could not cr continue; } - if (wc >= 0x80) { /* Is this a non-ASCII character? */ + if (wc >= 0x80) { /* Is this an extended character? */ cf |= NS_LFN; /* LFN entry needs to be created */ #if FF_CODE_PAGE == 0 - if (ExCvt) { /* At SBCS */ + if (ExCvt) { /* In SBCS cfg */ wc = ff_uni2oem(wc, CODEPAGE); /* Unicode ==> ANSI/OEM code */ if (wc & 0x80) wc = ExCvt[wc & 0x7F]; /* Convert extended character to upper (SBCS) */ - } else { /* At DBCS */ - wc = ff_uni2oem(ff_wtoupper(wc), CODEPAGE); /* Unicode ==> Upper convert ==> ANSI/OEM code */ + } else { /* In DBCS cfg */ + wc = ff_uni2oem(ff_wtoupper(wc), CODEPAGE); /* Unicode ==> Up-convert ==> ANSI/OEM code */ } -#elif FF_CODE_PAGE < 900 /* SBCS cfg */ +#elif FF_CODE_PAGE < 900 /* In SBCS cfg */ wc = ff_uni2oem(wc, CODEPAGE); /* Unicode ==> ANSI/OEM code */ if (wc & 0x80) wc = ExCvt[wc & 0x7F]; /* Convert extended character to upper (SBCS) */ -#else /* DBCS cfg */ - wc = ff_uni2oem(ff_wtoupper(wc), CODEPAGE); /* Unicode ==> Upper convert ==> ANSI/OEM code */ +#else /* In DBCS cfg */ + wc = ff_uni2oem(ff_wtoupper(wc), CODEPAGE); /* Unicode ==> Up-convert ==> ANSI/OEM code */ #endif } @@ -2963,7 +2948,7 @@ static FRESULT create_name ( /* FR_OK: successful, FR_INVALID_NAME: could not cr } dp->fn[i++] = (BYTE)(wc >> 8); /* Put 1st byte */ } else { /* SBC */ - if (wc == 0 || chk_chr("+,;=[]", wc)) { /* Replace illegal characters for SFN if needed */ + if (wc == 0 || strchr("+,;=[]", (int)wc)) { /* Replace illegal characters for SFN */ wc = '_'; cf |= NS_LOSS | NS_LFN;/* Lossy conversion */ } else { if (IsUpper(wc)) { /* ASCII upper case? */ @@ -2992,13 +2977,14 @@ static FRESULT create_name ( /* FR_OK: successful, FR_INVALID_NAME: could not cr #else /* FF_USE_LFN : Non-LFN configuration */ - BYTE c, d, *sfn; + BYTE c, d; + BYTE *sfn; UINT ni, si, i; const char *p; /* Create file name in directory form */ p = *path; sfn = dp->fn; - mem_set(sfn, ' ', 11); + memset(sfn, ' ', 11); si = i = 0; ni = 8; #if FF_FS_RPATH != 0 if (p[si] == '.') { /* Is this a dot entry? */ @@ -3007,8 +2993,8 @@ static FRESULT create_name ( /* FR_OK: successful, FR_INVALID_NAME: could not cr if (c != '.' || si >= 3) break; sfn[i++] = c; } - if (c != '/' && c != '\\' && c > ' ') return FR_INVALID_NAME; - *path = p + si; /* Return pointer to the next segment */ + if (!IsSeparator(c) && c > ' ') return FR_INVALID_NAME; + *path = p + si; /* Return pointer to the next segment */ sfn[NSFLAG] = (c <= ' ') ? NS_LAST | NS_DOT : NS_DOT; /* Set last segment flag if end of the path */ return FR_OK; } @@ -3016,8 +3002,8 @@ static FRESULT create_name ( /* FR_OK: successful, FR_INVALID_NAME: could not cr for (;;) { c = (BYTE)p[si++]; /* Get a byte */ if (c <= ' ') break; /* Break if end of the path name */ - if (c == '/' || c == '\\') { /* Break if a separator is found */ - while (p[si] == '/' || p[si] == '\\') si++; /* Skip duplicated separator if exist */ + if (IsSeparator(c)) { /* Break if a separator is found */ + while (IsSeparator(p[si])) si++; /* Skip duplicated separator if exist */ break; } if (c == '.' || i >= ni) { /* End of body or field overflow? */ @@ -3040,16 +3026,16 @@ static FRESULT create_name ( /* FR_OK: successful, FR_INVALID_NAME: could not cr sfn[i++] = c; sfn[i++] = d; } else { /* SBC */ - if (chk_chr("\"*+,:;<=>\?[]|\x7F", c)) return FR_INVALID_NAME; /* Reject illegal chrs for SFN */ + if (strchr("*+,:;<=>[]|\"\?\x7F", (int)c)) return FR_INVALID_NAME; /* Reject illegal chrs for SFN */ if (IsLower(c)) c -= 0x20; /* To upper */ sfn[i++] = c; } } - *path = p + si; /* Return pointer to the next segment */ + *path = &p[si]; /* Return pointer to the next segment */ if (i == 0) return FR_INVALID_NAME; /* Reject nul string */ if (sfn[0] == DDEM) sfn[0] = RDDEM; /* If the first character collides with DDEM, replace it with RDDEM */ - sfn[NSFLAG] = (c <= ' ') ? NS_LAST : 0; /* Set last segment flag if end of the path */ + sfn[NSFLAG] = (c <= ' ' || p[si] <= ' ') ? NS_LAST : 0; /* Set last segment flag if end of the path */ return FR_OK; #endif /* FF_USE_LFN */ @@ -3073,13 +3059,13 @@ static FRESULT follow_path ( /* FR_OK(0): successful, !=0: error code */ #if FF_FS_RPATH != 0 - if (*path != '/' && *path != '\\') { /* Without heading separator */ - dp->obj.sclust = fs->cdir; /* Start from current directory */ + if (!IsSeparator(*path) && (FF_STR_VOLUME_ID != 2 || !IsTerminator(*path))) { /* Without heading separator */ + dp->obj.sclust = fs->cdir; /* Start at the current directory */ } else #endif { /* With heading separator */ - while (*path == '/' || *path == '\\') path++; /* Strip heading separator */ - dp->obj.sclust = 0; /* Start from root directory */ + while (IsSeparator(*path)) path++; /* Strip separators */ + dp->obj.sclust = 0; /* Start from the root directory */ } #if FF_FS_EXFAT dp->obj.n_frag = 0; /* Invalidate last fragment counter of the object */ @@ -3120,13 +3106,13 @@ static FRESULT follow_path ( /* FR_OK(0): successful, !=0: error code */ } break; } - if (ns & NS_LAST) break; /* Last segment matched. Function completed. */ + if (ns & NS_LAST) break; /* Last segment matched. Function completed. */ /* Get into the sub-directory */ - if (!(dp->obj.attr & AM_DIR)) { /* It is not a sub-directory and cannot follow */ + if (!(dp->obj.attr & AM_DIR)) { /* It is not a sub-directory and cannot follow */ res = FR_NO_PATH; break; } #if FF_FS_EXFAT - if (fs->fs_type == FS_EXFAT) { /* Save containing directory information for next dir */ + if (fs->fs_type == FS_EXFAT) { /* Save containing directory information for next dir */ dp->obj.c_scl = dp->obj.sclust; dp->obj.c_size = ((DWORD)dp->obj.objsize & 0xFFFFFF00) | dp->obj.stat; dp->obj.c_ofs = dp->blk_ofs; @@ -3153,9 +3139,11 @@ static int get_ldnumber ( /* Returns logical drive number (-1:invalid drive numb const TCHAR** path /* Pointer to pointer to the path name */ ) { - const TCHAR *tp, *tt; + const TCHAR *tp; + const TCHAR *tt; TCHAR tc; - int i, vol = -1; + int i; + int vol = -1; #if FF_STR_VOLUME_ID /* Find string volume ID */ const char *sp; char c; @@ -3163,7 +3151,9 @@ static int get_ldnumber ( /* Returns logical drive number (-1:invalid drive numb tt = tp = *path; if (!tp) return vol; /* Invalid path name? */ - do tc = *tt++; while ((UINT)tc >= (FF_USE_LFN ? ' ' : '!') && tc != ':'); /* Find a colon in the path */ + do { /* Find a colon in the path */ + tc = *tt++; + } while (!IsTerminator(tc) && tc != ':'); if (tc == ':') { /* DOS/Windows style volume ID? */ i = FF_VOLUMES; @@ -3190,21 +3180,22 @@ static int get_ldnumber ( /* Returns logical drive number (-1:invalid drive numb return vol; } #if FF_STR_VOLUME_ID == 2 /* Unix style volume ID is enabled */ - if (*tp == '/') { + if (*tp == '/') { /* Is there a volume ID? */ + while (*(tp + 1) == '/') tp++; /* Skip duplicated separator */ i = 0; do { - sp = VolumeStr[i]; tp = *path; /* This string volume ID and path name */ + tt = tp; sp = VolumeStr[i]; /* Path name and this string volume ID */ do { /* Compare the volume ID with path name */ - c = *sp++; tc = *(++tp); + c = *sp++; tc = *(++tt); if (IsLower(c)) c -= 0x20; if (IsLower(tc)) tc -= 0x20; } while (c && (TCHAR)c == tc); - } while ((c || (tc != '/' && (UINT)tc >= (FF_USE_LFN ? ' ' : '!'))) && ++i < FF_VOLUMES); /* Repeat for each ID until pattern match */ + } while ((c || (tc != '/' && !IsTerminator(tc))) && ++i < FF_VOLUMES); /* Repeat for each ID until pattern match */ if (i < FF_VOLUMES) { /* If a volume ID is found, get the drive number and strip it */ vol = i; /* Drive number */ - *path = tp; /* Snip the drive prefix off */ - return vol; + *path = tt; /* Snip the drive prefix off */ } + return vol; } #endif /* No drive prefix is found */ @@ -3250,16 +3241,18 @@ static int test_gpt_header ( /* 0:Invalid, 1:Valid */ ) { UINT i; - DWORD bcc; + DWORD bcc, hlen; - if (mem_cmp(gpth + GPTH_Sign, "EFI PART" "\0\0\1\0" "\x5C\0\0", 16)) return 0; /* Check sign, version (1.0) and length (92) */ - for (i = 0, bcc = 0xFFFFFFFF; i < 92; i++) { /* Check header BCC */ + 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) */ + if (ld_dword(gpth + GPTH_PtNum) > 128) return 0; /* Table size (must be 128 entries or less) */ return 1; } @@ -3269,7 +3262,7 @@ static int test_gpt_header ( /* 0:Invalid, 1:Valid */ /* Generate random value */ static DWORD make_rand ( DWORD seed, /* Seed value */ - BYTE* buff, /* Output buffer */ + BYTE *buff, /* Output buffer */ UINT n /* Data length */ ) { @@ -3295,7 +3288,7 @@ static DWORD make_rand ( /* Check what the sector is */ -static UINT check_fs ( /* 0:FAT VBR, 1:exFAT VBR, 2:Not FAT and valid BS, 3:Not FAT and invalid BS, 4:Disk error */ +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 */ ) @@ -3308,21 +3301,24 @@ static UINT check_fs ( /* 0:FAT VBR, 1:exFAT VBR, 2:Not FAT and valid BS, 3:Not 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 && !mem_cmp(fs->win + BS_JmpBoot, "\xEB\x76\x90" "EXFAT ", 11)) return 1; /* It is an exFAT VBR */ + 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 && !mem_cmp(fs->win + BS_FilSysType32, "FAT32 ", 8)) return 0; /* It is an FAT32 VBR */ - /* FAT volumes formatted with early MS-DOS lack boot signature and FAT string, so that we need to identify the FAT VBR without them. */ + 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); - if ((w & (w - 1)) == 0 && w >= FF_MIN_SS && w <= FF_MAX_SS) { /* Properness of sector size */ - b = fs->win[BPB_SecPerClus]; - if (b != 0 && (b & (b - 1)) == 0 /* Properness of cluster size */ - && (fs->win[BPB_NumFATs] == 1 || fs->win[BPB_NumFATs] == 2) /* Properness of number of FATs */ - && ld_word(fs->win + BPB_RootEntCnt) != 0 /* Properness of root entry count */ - && ld_word(fs->win + BPB_FATSz16) != 0) { /* Properness of FAT size */ - return 0; /* Sector can be presumed an FAT VBR */ - } + 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) */ @@ -3334,15 +3330,15 @@ static UINT check_fs ( /* 0:FAT VBR, 1:exFAT VBR, 2:Not FAT and valid BS, 3:Not static UINT find_volume ( /* Returns BS status found in the hosting drive */ FATFS* fs, /* Filesystem object */ - UINT part /* Partition to fined = 0:auto, 1..:forced */ + 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 */ - if (fmt != 2 && (fmt >= 3 || part == 0)) return fmt; /* Returns if it is a FAT VBR as auto scan, not a BS or disk error */ + 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 */ @@ -3358,7 +3354,7 @@ static UINT find_volume ( /* Returns BS status found in the hosting drive */ 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 (!mem_cmp(fs->win + ofs + GPTE_PtGuid, GUID_MS_Basic, 16)) { /* MS basic data partition? */ + 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) */ @@ -3389,15 +3385,15 @@ static UINT find_volume ( /* Returns BS status found in the hosting drive */ 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 /* !=0: Check write protection for write access */ + 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; - FATFS *fs; UINT fmt; @@ -3410,7 +3406,7 @@ static FRESULT mount_volume ( /* FR_OK(0): successful, !=0: an error occurred */ 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_fs(fs)) return FR_TIMEOUT; /* Lock the volume */ + if (!lock_volume(fs, 1)) return FR_TIMEOUT; /* Lock the volume, and system if needed */ #endif *rfs = fs; /* Return pointer to the filesystem object */ @@ -3426,11 +3422,10 @@ static FRESULT mount_volume ( /* FR_OK(0): successful, !=0: an error occurred */ } /* The filesystem object is not valid. */ - /* Following code attempts to mount the volume. (find a FAT volume, analyze the BPB and initialize the filesystem object) */ + /* Following code attempts to mount the volume. (find an FAT volume, analyze the BPB and initialize the filesystem object) */ - fs->fs_type = 0; /* Clear the filesystem object */ - fs->pdrv = LD2PD(vol); /* Volume hosting physical drive */ - stat = disk_initialize(fs->pdrv); /* Initialize the physical drive */ + 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 */ } @@ -3442,11 +3437,11 @@ static FRESULT mount_volume ( /* FR_OK(0): successful, !=0: an error occurred */ 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 drive */ + /* Find an FAT volume on the hosting drive */ fmt = find_volume(fs, LD2PT(vol)); - if (fmt == 4) return FR_DISK_ERR; /* An error occured in the disk I/O layer */ + 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 location */ + bsect = fs->winsect; /* Volume offset in the hosting physical drive */ /* An FAT volume is found (bsect). Following code initializes the filesystem object */ @@ -3464,8 +3459,8 @@ static FRESULT mount_volume ( /* FR_OK(0): successful, !=0: an error occurred */ return FR_NO_FILESYSTEM; } - maxlba = ld_qword(fs->win + BPB_TotSecEx) + bsect; /* Last LBA + 1 of the volume */ - if (!FF_LBA64 && maxlba >= 0x100000000) return FR_NO_FILESYSTEM; /* (It cannot be handled in 32-bit LBA) */ + 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 */ @@ -3473,7 +3468,7 @@ static FRESULT mount_volume ( /* FR_OK(0): successful, !=0: an error occurred */ 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) */ + 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) */ @@ -3483,7 +3478,7 @@ static FRESULT mount_volume ( /* FR_OK(0): successful, !=0: an error occurred */ 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 requiered) */ + 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) */ @@ -3494,17 +3489,17 @@ static FRESULT mount_volume ( /* FR_OK(0): successful, !=0: an error occurred */ 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? */ + 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; + 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? */ + if (cv != ++bcl) return FR_NO_FILESYSTEM; /* Fragmented bitmap? */ } #if !FF_FS_READONLY @@ -3591,7 +3586,7 @@ static FRESULT mount_volume ( /* FR_OK(0): successful, !=0: an error occurred */ #endif /* !FF_FS_READONLY */ } - fs->fs_type = (BYTE)fmt;/* FAT sub-type */ + 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 */ @@ -3602,8 +3597,8 @@ static FRESULT mount_volume ( /* FR_OK(0): successful, !=0: an error occurred */ #if FF_FS_RPATH != 0 fs->cdir = 0; /* Initialize current directory */ #endif -#if FF_FS_LOCK != 0 /* Clear file lock semaphores */ - clear_lock(fs); +#if FF_FS_LOCK /* Clear file lock semaphores */ + clear_share(fs); #endif return FR_OK; } @@ -3616,7 +3611,7 @@ static FRESULT mount_volume ( /* FR_OK(0): successful, !=0: an error occurred */ /*-----------------------------------------------------------------------*/ static FRESULT validate ( /* Returns FR_OK or FR_INVALID_OBJECT */ - FFOBJID* obj, /* Pointer to the FFOBJID, the 1st member in the FIL/DIR object, to check validity */ + 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 */ ) { @@ -3625,22 +3620,22 @@ static FRESULT validate ( /* Returns FR_OK or 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_fs(obj->fs)) { /* Obtain the filesystem object */ - if (!(disk_status(obj->fs->pdrv) & STA_NOINIT)) { /* Test if the phsical drive is kept initialized */ + 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_fs(obj->fs, FR_OK); + unlock_volume(obj->fs, FR_OK); /* Invalidated volume, abort to access */ } - } else { + } else { /* Could not take */ res = FR_TIMEOUT; } #else - if (!(disk_status(obj->fs->pdrv) & STA_NOINIT)) { /* Test if the phsical drive is kept initialized */ + 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; /* Corresponding filesystem object */ + *rfs = (res == FR_OK) ? obj->fs : 0; /* Return corresponding filesystem object if it is valid */ return res; } @@ -3660,9 +3655,9 @@ static FRESULT validate ( /* Returns FR_OK or FR_INVALID_OBJECT */ /*-----------------------------------------------------------------------*/ FRESULT f_mount ( - FATFS* fs, /* Pointer to the filesystem object (NULL:unmount)*/ + FATFS* fs, /* Pointer to the filesystem object to be registered (NULL:unmount)*/ const TCHAR* path, /* Logical drive number to be mounted/unmounted */ - BYTE opt /* Mode option 0:Do not mount (delayed mount), 1:Mount immediately */ + BYTE opt /* Mount option: 0=Do not mount (delayed mount), 1=Mount immediately */ ) { FATFS *cfs; @@ -3671,30 +3666,42 @@ FRESULT f_mount ( const TCHAR *rp = path; - /* Get logical drive number */ + /* Get volume ID (logical drive number) */ vol = get_ldnumber(&rp); if (vol < 0) return FR_INVALID_DRIVE; - cfs = FatFs[vol]; /* Pointer to fs object */ + cfs = FatFs[vol]; /* Pointer to the filesystem object of the volume */ - if (cfs) { -#if FF_FS_LOCK != 0 - clear_lock(cfs); + if (cfs) { /* Unregister current filesystem object if regsitered */ + FatFs[vol] = 0; +#if FF_FS_LOCK + clear_share(cfs); #endif -#if FF_FS_REENTRANT /* Discard sync object of the current volume */ - if (!ff_del_syncobj(cfs->sobj)) return FR_INT_ERR; +#if FF_FS_REENTRANT /* Discard mutex of the current volume */ + ff_mutex_delete(vol); #endif - cfs->fs_type = 0; /* Clear old fs object */ + cfs->fs_type = 0; /* Invalidate the filesystem object to be unregistered */ } - if (fs) { - fs->fs_type = 0; /* Clear new fs object */ -#if FF_FS_REENTRANT /* Create sync object for the new volume */ - if (!ff_cre_syncobj((BYTE)vol, &fs->sobj)) return FR_INT_ERR; + 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 */ } - FatFs[vol] = fs; /* Register new fs object */ - if (opt == 0) return FR_OK; /* Do not mount now, it will be mounted later */ + 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); @@ -3710,14 +3717,14 @@ FRESULT f_mount ( FRESULT f_open ( FIL* fp, /* Pointer to the blank file object */ const TCHAR* path, /* Pointer to the file name */ - BYTE mode /* Access mode and file open mode flags */ + BYTE mode /* Access mode and open mode flags */ ) { FRESULT res; DIR dj; FATFS *fs; #if !FF_FS_READONLY - DWORD cl, bcs, clst, tm; + DWORD cl, bcs, clst, tm; LBA_t sc; FSIZE_t ofs; #endif @@ -3738,9 +3745,9 @@ FRESULT f_open ( if (dj.fn[NSFLAG] & NS_NONAME) { /* Origin directory itself? */ res = FR_INVALID_NAME; } -#if FF_FS_LOCK != 0 +#if FF_FS_LOCK else { - res = chk_lock(&dj, (mode & ~FA_READ) ? 1 : 0); /* Check if the file can be used */ + res = chk_share(&dj, (mode & ~FA_READ) ? 1 : 0); /* Check if the file can be used */ } #endif } @@ -3748,8 +3755,8 @@ FRESULT f_open ( 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 != 0 - res = enq_lock() ? dir_register(&dj) : FR_TOO_MANY_OPEN_FILES; +#if FF_FS_LOCK + res = enq_share() ? dir_register(&dj) : FR_TOO_MANY_OPEN_FILES; #else res = dir_register(&dj); #endif @@ -3770,8 +3777,8 @@ FRESULT f_open ( fp->obj.fs = fs; init_alloc_info(fs, &fp->obj); /* Set directory entry block initial state */ - mem_set(fs->dirbuf + 2, 0, 30); /* Clear 85 entry except for NumSec */ - mem_set(fs->dirbuf + 38, 0, 26); /* Clear C0 entry except for NumName and NameHash */ + 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; @@ -3818,8 +3825,8 @@ FRESULT f_open ( 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 != 0 - fp->obj.lockid = inc_lock(&dj, (mode & ~FA_READ) ? 1 : 0); /* Lock the file for this session */ +#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 } @@ -3849,17 +3856,17 @@ FRESULT f_open ( fp->obj.objsize = ld_dword(dj.dir + DIR_FileSize); } #if FF_USE_FASTSEEK - fp->cltbl = 0; /* Disable fast seek mode */ + fp->cltbl = 0; /* Disable fast seek mode */ #endif - fp->obj.fs = fs; /* Validate the file object */ + 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 */ + 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 - mem_set(fp->buf, 0, sizeof fp->buf); /* Clear sector buffer */ + 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 */ @@ -3882,6 +3889,9 @@ FRESULT f_open ( #endif } } +#if FF_FS_LOCK + if (res != FR_OK) dec_share(fp->obj.lockid); /* Decrement file open counter if seek failed */ +#endif } #endif } @@ -3902,10 +3912,10 @@ FRESULT f_open ( /*-----------------------------------------------------------------------*/ FRESULT f_read ( - FIL* fp, /* Pointer to the file object */ - void* buff, /* Pointer to data buffer */ + 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 /* Pointer to number of bytes read */ + UINT* br /* Number of bytes read */ ) { FRESULT res; @@ -3924,8 +3934,7 @@ FRESULT f_read ( remain = fp->obj.objsize - fp->fptr; if (btr > remain) btr = (UINT)remain; /* Truncate btr by remaining bytes */ - for ( ; btr; /* Repeat until btr bytes read */ - btr -= rcnt, *br += rcnt, rbuff += rcnt, fp->fptr += rcnt) { + 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? */ @@ -3957,11 +3966,11 @@ FRESULT f_read ( #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) { - mem_cpy(rbuff + ((fs->winsect - sect) * SS(fs)), fs->win, SS(fs)); + memcpy(rbuff + ((fs->winsect - sect) * SS(fs)), fs->win, SS(fs)); } #else if ((fp->flag & FA_DIRTY) && fp->sect - sect < cc) { - mem_cpy(rbuff + ((fp->sect - sect) * SS(fs)), fp->buf, SS(fs)); + memcpy(rbuff + ((fp->sect - sect) * SS(fs)), fp->buf, SS(fs)); } #endif #endif @@ -3976,7 +3985,7 @@ FRESULT f_read ( 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 */ + if (disk_read(fs->pdrv, fp->buf, sect, 1) != RES_OK) ABORT(fs, FR_DISK_ERR); /* Fill sector cache */ } #endif fp->sect = sect; @@ -3985,9 +3994,9 @@ FRESULT f_read ( 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 */ - mem_cpy(rbuff, fs->win + fp->fptr % SS(fs), rcnt); /* Extract partial sector */ + memcpy(rbuff, fs->win + fp->fptr % SS(fs), rcnt); /* Extract partial sector */ #else - mem_cpy(rbuff, fp->buf + fp->fptr % SS(fs), rcnt); /* Extract partial sector */ + memcpy(rbuff, fp->buf + fp->fptr % SS(fs), rcnt); /* Extract partial sector */ #endif } @@ -4003,10 +4012,10 @@ FRESULT f_read ( /*-----------------------------------------------------------------------*/ FRESULT f_write ( - FIL* fp, /* Pointer to the file object */ - const void* buff, /* Pointer to the data to be written */ + FIL* fp, /* Open file to be written */ + const void* buff, /* Data to be written */ UINT btw, /* Number of bytes to write */ - UINT* bw /* Pointer to number of bytes written */ + UINT* bw /* Number of bytes written */ ) { FRESULT res; @@ -4027,8 +4036,7 @@ FRESULT f_write ( btw = (UINT)(0xFFFFFFFF - (DWORD)fp->fptr); } - for ( ; btw; /* Repeat until all data written */ - btw -= wcnt, *bw += wcnt, wbuff += wcnt, fp->fptr += wcnt, fp->obj.objsize = (fp->fptr > fp->obj.objsize) ? fp->fptr : fp->obj.objsize) { + 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? */ @@ -4073,12 +4081,12 @@ FRESULT f_write ( #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 */ - mem_cpy(fs->win, wbuff + ((fs->winsect - sect) * SS(fs)), SS(fs)); + 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 */ - mem_cpy(fp->buf, wbuff + ((fp->sect - sect) * SS(fs)), SS(fs)); + memcpy(fp->buf, wbuff + ((fp->sect - sect) * SS(fs)), SS(fs)); fp->flag &= (BYTE)~FA_DIRTY; } #endif @@ -4104,10 +4112,10 @@ FRESULT f_write ( 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 */ - mem_cpy(fs->win + fp->fptr % SS(fs), wbuff, wcnt); /* Fit data to the sector */ + memcpy(fs->win + fp->fptr % SS(fs), wbuff, wcnt); /* Fit data to the sector */ fs->wflag = 1; #else - mem_cpy(fp->buf + fp->fptr % SS(fs), wbuff, wcnt); /* Fit data to the sector */ + memcpy(fp->buf + fp->fptr % SS(fs), wbuff, wcnt); /* Fit data to the sector */ fp->flag |= FA_DIRTY; #endif } @@ -4125,7 +4133,7 @@ FRESULT f_write ( /*-----------------------------------------------------------------------*/ FRESULT f_sync ( - FIL* fp /* Pointer to the file object */ + FIL* fp /* Open file to be synced */ ) { FRESULT res; @@ -4206,7 +4214,7 @@ FRESULT f_sync ( /*-----------------------------------------------------------------------*/ FRESULT f_close ( - FIL* fp /* Pointer to the file object to be closed */ + FIL* fp /* Open file to be closed */ ) { FRESULT res; @@ -4219,14 +4227,14 @@ FRESULT f_close ( { res = validate(&fp->obj, &fs); /* Lock volume */ if (res == FR_OK) { -#if FF_FS_LOCK != 0 - res = dec_lock(fp->obj.lockid); /* Decrement file open counter */ +#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_fs(fs, FR_OK); /* Unlock volume */ + unlock_volume(fs, FR_OK); /* Unlock volume */ #endif } } @@ -4307,7 +4315,7 @@ FRESULT f_chdir ( } FREE_NAMBUF(); if (res == FR_NO_FILE) res = FR_NO_PATH; -#if FF_STR_VOLUME_ID == 2 /* Also current drive is changed at Unix style volume ID */ +#if FF_STR_VOLUME_ID == 2 /* Also current drive is changed if in Unix style volume ID */ if (res == FR_OK) { for (i = FF_VOLUMES - 1; i && fs != FatFs[i]; i--) ; /* Set current drive */ CurrVol = (BYTE)i; @@ -4400,7 +4408,9 @@ FRESULT f_getcwd ( #endif /* Add current directory path */ if (res == FR_OK) { - do *tp++ = buff[i++]; while (i < len); /* Copy stacked path string */ + do { /* Copy stacked path string */ + *tp++ = buff[i++]; + } while (i < len); } } FREE_NAMBUF(); @@ -4431,7 +4441,8 @@ FRESULT f_lseek ( LBA_t nsect; FSIZE_t ifptr; #if FF_USE_FASTSEEK - DWORD cl, pcl, ncl, tcl, tlen, ulen, *tbl; + DWORD cl, pcl, ncl, tcl, tlen, ulen; + DWORD *tbl; LBA_t dsc; #endif @@ -4606,7 +4617,7 @@ FRESULT f_opendir ( 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_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 */ @@ -4622,10 +4633,10 @@ FRESULT f_opendir ( if (res == FR_OK) { dp->obj.id = fs->id; res = dir_sdi(dp, 0); /* Rewind directory */ -#if FF_FS_LOCK != 0 +#if FF_FS_LOCK if (res == FR_OK) { if (dp->obj.sclust != 0) { - dp->obj.lockid = inc_lock(dp, 0); /* Lock the sub directory */ + 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 */ @@ -4637,7 +4648,7 @@ FRESULT f_opendir ( 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 faild */ + if (res != FR_OK) dp->obj.fs = 0; /* Invalidate the directory object if function failed */ LEAVE_FF(fs, res); } @@ -4659,14 +4670,14 @@ FRESULT f_closedir ( res = validate(&dp->obj, &fs); /* Check validity of the file object */ if (res == FR_OK) { -#if FF_FS_LOCK != 0 - if (dp->obj.lockid) res = dec_lock(dp->obj.lockid); /* Decrement sub-directory open counter */ +#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_fs(fs, FR_OK); /* Unlock volume */ + unlock_volume(fs, FR_OK); /* Unlock volume */ #endif } return res; @@ -4692,7 +4703,7 @@ FRESULT f_readdir ( 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 */ + res = dir_sdi(dp, 0); /* Rewind the directory object */ } else { INIT_NAMBUF(fs); res = DIR_READ_FILE(dp); /* Read an item */ @@ -4830,8 +4841,12 @@ FRESULT f_getfree ( 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 == 0xFFFFFFFF) { + res = FR_DISK_ERR; break; + } + if (stat == 1) { + res = FR_INT_ERR; break; + } if (stat == 0) nfree++; } while (++clst < fs->n_fatent); } else { @@ -4844,12 +4859,12 @@ FRESULT f_getfree ( sect = fs->bitbase; /* Bitmap sector */ i = 0; /* Offset in the sector */ do { /* Counts numbuer of bits with zero in the bitmap */ - if (i == 0) { + 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--) { - if (!(bm & 1)) nfree++; + for (b = 8, bm = ~fs->win[i]; b && clst; b--, clst--) { + nfree += bm & 1; bm >>= 1; } i = (i + 1) % SS(fs); @@ -4861,7 +4876,7 @@ FRESULT f_getfree ( 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) { + if (i == 0) { /* New sector? */ res = move_window(fs, sect++); if (res != FR_OK) break; } @@ -4876,9 +4891,11 @@ FRESULT f_getfree ( } while (--clst); } } - *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 */ + 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 */ + } } } @@ -4947,9 +4964,9 @@ FRESULT f_unlink ( ) { FRESULT res; + FATFS *fs; DIR dj, sdj; DWORD dclst = 0; - FATFS *fs; #if FF_FS_EXFAT FFOBJID obj; #endif @@ -4965,8 +4982,8 @@ FRESULT f_unlink ( if (FF_FS_RPATH && res == FR_OK && (dj.fn[NSFLAG] & NS_DOT)) { res = FR_INVALID_NAME; /* Cannot remove dot entry */ } -#if FF_FS_LOCK != 0 - if (res == FR_OK) res = chk_lock(&dj, 2); /* Check if it is an open object */ +#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) { @@ -4989,12 +5006,12 @@ FRESULT f_unlink ( } 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? */ + if (dclst == fs->cdir) { /* Is it the current directory? */ res = FR_DENIED; } else #endif { - sdj.obj.fs = fs; /* Open the sub-directory */ + sdj.obj.fs = fs; /* Open the sub-directory */ sdj.obj.sclust = dclst; #if FF_FS_EXFAT if (fs->fs_type == FS_EXFAT) { @@ -5041,9 +5058,9 @@ FRESULT f_mkdir ( ) { FRESULT res; + FATFS *fs; DIR dj; FFOBJID sobj; - FATFS *fs; DWORD dcl, pcl, tm; DEF_NAMBUF @@ -5069,12 +5086,12 @@ FRESULT f_mkdir ( 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) */ - mem_set(fs->win + DIR_Name, ' ', 11); /* Create "." entry */ + 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); - mem_cpy(fs->win + SZDIRE, fs->win, SZDIRE); /* Create ".." entry */ + 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; @@ -5126,8 +5143,8 @@ FRESULT f_rename ( ) { FRESULT res; - DIR djo, djn; FATFS *fs; + DIR djo, djn; BYTE buf[FF_FS_EXFAT ? SZDIRE * 2 : SZDIRE], *dir; LBA_t sect; DEF_NAMBUF @@ -5138,21 +5155,21 @@ FRESULT f_rename ( if (res == FR_OK) { djo.obj.fs = fs; INIT_NAMBUF(fs); - res = follow_path(&djo, path_old); /* Check old object */ + 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 != 0 +#if FF_FS_LOCK if (res == FR_OK) { - res = chk_lock(&djo, 2); + res = chk_share(&djo, 2); } #endif - if (res == FR_OK) { /* Object to be renamed is found */ + 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; - mem_cpy(buf, fs->dirbuf, SZDIRE * 2); /* Save 85+C0 entry of old object */ - mem_cpy(&djn, &djo, sizeof djo); + 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; @@ -5162,7 +5179,7 @@ FRESULT f_rename ( if (res == FR_OK) { nf = fs->dirbuf[XDIR_NumSec]; nn = fs->dirbuf[XDIR_NumName]; nh = ld_word(fs->dirbuf + XDIR_NameHash); - mem_cpy(fs->dirbuf, buf, SZDIRE * 2); /* Restore 85+C0 entry */ + 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 */ @@ -5173,8 +5190,8 @@ FRESULT f_rename ( } else #endif { /* At FAT/FAT32 volume */ - mem_cpy(buf, djo.dir, SZDIRE); /* Save directory entry of the object */ - mem_cpy(&djn, &djo, sizeof (DIR)); /* Duplicate the directory object */ + 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; @@ -5183,7 +5200,7 @@ FRESULT f_rename ( res = dir_register(&djn); /* Register the new entry */ if (res == FR_OK) { dir = djn.dir; /* Copy directory entry of the object except name */ - mem_cpy(dir + 13, buf + 13, SZDIRE - 13); + 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; @@ -5237,8 +5254,8 @@ FRESULT f_chmod ( ) { FRESULT res; - DIR dj; FATFS *fs; + DIR dj; DEF_NAMBUF @@ -5283,8 +5300,8 @@ FRESULT f_utime ( ) { FRESULT res; - DIR dj; FATFS *fs; + DIR dj; DEF_NAMBUF @@ -5331,8 +5348,8 @@ FRESULT f_getlabel ( ) { FRESULT res; - DIR dj; FATFS *fs; + DIR dj; UINT si, di; WCHAR wc; @@ -5349,15 +5366,18 @@ FRESULT f_getlabel ( #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; } - wc = put_utf((DWORD)hs << 16 | wc, &label[di], 4); - if (wc == 0) { di = 0; break; } - di += wc; + 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? */ @@ -5370,10 +5390,11 @@ FRESULT f_getlabel ( 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) wc = put_utf(wc, &label[di], 4); /* Put it in Unicode */ - if (wc == 0) { di = 0; break; } - di += wc; + 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 @@ -5426,12 +5447,12 @@ FRESULT f_setlabel ( ) { FRESULT res; - DIR dj; FATFS *fs; + DIR dj; BYTE dirvn[22]; UINT di; WCHAR wc; - static const char badchr[] = "+.,;=[]/\\\"*:<>\?|\x7F"; /* [0..] for FAT, [7..] for exFAT */ + static const char badchr[18] = "+.,;=[]" "/*:<>|\\\"\?\x7F"; /* [0..16] for FAT, [7..16] for exFAT */ #if FF_USE_LFN DWORD dc; #endif @@ -5442,7 +5463,7 @@ FRESULT f_setlabel ( #if FF_FS_EXFAT if (fs->fs_type == FS_EXFAT) { /* On the exFAT volume */ - mem_set(dirvn, 0, 22); + memset(dirvn, 0, 22); di = 0; while ((UINT)*label >= ' ') { /* Create volume label */ dc = tchar2uni(&label); /* Get a Unicode character */ @@ -5453,7 +5474,7 @@ FRESULT f_setlabel ( st_word(dirvn + di * 2, (WCHAR)(dc >> 16)); di++; } } - if (dc == 0 || chk_chr(badchr + 7, (int)dc) || di >= 11) { /* Check validity of the volume label */ + 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++; @@ -5461,7 +5482,7 @@ FRESULT f_setlabel ( } else #endif { /* On the FAT/FAT32 volume */ - mem_set(dirvn, ' ', 11); + memset(dirvn, ' ', 11); di = 0; while ((UINT)*label >= ' ') { /* Create volume label */ #if FF_USE_LFN @@ -5477,7 +5498,7 @@ FRESULT f_setlabel ( if (wc >= 0x80) wc = ExCvt[wc - 0x80]; /* To upper extended characters (SBCS cfg) */ #endif #endif - if (wc == 0 || chk_chr(badchr + 0, (int)wc) || di >= (UINT)((wc >= 0x100) ? 10 : 11)) { /* Reject invalid characters for volume label */ + 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); @@ -5495,10 +5516,10 @@ FRESULT f_setlabel ( if (res == FR_OK) { if (FF_FS_EXFAT && fs->fs_type == FS_EXFAT) { dj.dir[XDIR_NumLabel] = (BYTE)di; /* Change the volume label */ - mem_cpy(dj.dir + XDIR_Label, dirvn, 22); + memcpy(dj.dir + XDIR_Label, dirvn, 22); } else { if (di != 0) { - mem_cpy(dj.dir, dirvn, 11); /* Change the volume label */ + memcpy(dj.dir, dirvn, 11); /* Change the volume label */ } else { dj.dir[DIR_Name] = DDEM; /* Remove the volume label */ } @@ -5511,14 +5532,14 @@ FRESULT f_setlabel ( if (di != 0) { /* Create a volume label entry */ res = dir_alloc(&dj, 1); /* Allocate an entry */ if (res == FR_OK) { - mem_set(dj.dir, 0, SZDIRE); /* Clean the entry */ + 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; - mem_cpy(dj.dir + XDIR_Label, dirvn, 22); + memcpy(dj.dir + XDIR_Label, dirvn, 22); } else { dj.dir[DIR_Attr] = AM_VOL; /* Create volume label entry */ - mem_cpy(dj.dir, dirvn, 11); + memcpy(dj.dir, dirvn, 11); } fs->wflag = 1; res = sync_fs(fs); @@ -5583,14 +5604,20 @@ FRESULT f_expand ( 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 == 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) { res = FR_DENIED; break; } /* No contiguous 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 */ @@ -5655,8 +5682,7 @@ FRESULT f_forward ( remain = fp->obj.objsize - fp->fptr; if (btf > remain) btf = (UINT)remain; /* Truncate btf by remaining bytes */ - for ( ; btf && (*func)(0, 0); /* Repeat until all data transferred or stream goes busy */ - fp->fptr += rcnt, *bf += rcnt, btf -= rcnt) { + 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? */ @@ -5700,7 +5726,7 @@ FRESULT f_forward ( #if !FF_FS_READONLY && FF_USE_MKFS /*-----------------------------------------------------------------------*/ -/* Create FAT/exFAT volume */ +/* Create FAT/exFAT volume (with sub-functions) */ /*-----------------------------------------------------------------------*/ #define N_SEC_TRACK 63 /* Sectors per track for determination of drive CHS */ @@ -5713,24 +5739,25 @@ FRESULT f_forward ( static FRESULT create_partition ( BYTE drv, /* Physical drive number */ const LBA_t plst[], /* Partition list */ - BYTE sys, /* System ID (for only MBR, temp setting) */ - BYTE* buf /* Working buffer for a sector */ + 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, s_lba32, n_lba32; - BYTE *pte, hd, n_hd, sc, n_sc; + DWORD sz_drv32, nxt_alloc32, sz_part32; + BYTE *pte; + BYTE hd, n_hd, sc, n_sc; - /* Get drive size */ + /* 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 */ + if (sz_drv >= FF_MIN_GPT) { /* Create partitions in GPT format */ WORD ss; - UINT sz_pt, pi, si, ofs; + UINT sz_ptbl, pi, si, ofs; DWORD bcc, rnd, align; - QWORD s_lba64, n_lba64, sz_pool, s_bpt; + 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 @@ -5739,103 +5766,103 @@ static FRESULT create_partition ( #else ss = FF_MAX_SS; #endif - rnd = GET_FATTIME(); /* Random seed */ - align = GPT_ALIGN / ss; /* Partition alignment [sector] */ - sz_pt = GPT_ITEMS * SZ_GPTE / ss; /* Size of PT [sector] */ - s_bpt = sz_drv - sz_pt - 1; /* Backup PT start sector */ - s_lba64 = 2 + sz_pt; /* First allocatable sector */ - sz_pool = s_bpt - s_lba64; /* Size of allocatable area */ - bcc = 0xFFFFFFFF; n_lba64 = 1; + 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) mem_set(buf, 0, ss); /* Clean the buffer if needed */ - if (n_lba64 != 0) { /* Is the size table not termintated? */ - s_lba64 = (s_lba64 + align - 1) & ((QWORD)0 - align); /* Align partition start */ - n_lba64 = plst[si++]; /* Get a partition size */ - if (n_lba64 <= 100) { /* Is the size in percentage? */ - n_lba64 = sz_pool * n_lba64 / 100; - n_lba64 = (n_lba64 + align - 1) & ((QWORD)0 - align); /* Align partition end (only if in percentage) */ + 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 (s_lba64 + n_lba64 > s_bpt) { /* Clip at end of the pool */ - n_lba64 = (s_lba64 < s_bpt) ? s_bpt - s_lba64 : 0; + 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 (n_lba64 != 0) { /* Add a partition? */ + if (sz_part != 0) { /* Add a partition? */ ofs = pi * SZ_GPTE % ss; - mem_cpy(buf + ofs + GPTE_PtGuid, GUID_MS_Basic, 16); /* Partition GUID (Microsoft Basic Data) */ - rnd = make_rand(rnd, buf + ofs + GPTE_UpGuid, 16); /* Unique partition GUID */ - st_qword(buf + ofs + GPTE_FstLba, s_lba64); /* Partition start LBA */ - st_qword(buf + ofs + GPTE_LstLba, s_lba64 + n_lba64 - 1); /* Partition end LBA */ - s_lba64 += n_lba64; /* Next partition LBA */ + 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; /* Primary table */ - if (disk_write(drv, buf, s_bpt + pi * SZ_GPTE / ss, 1) != RES_OK) return FR_DISK_ERR; /* Secondary table */ + 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 */ - mem_set(buf, 0, ss); - mem_cpy(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 another header */ - st_qword(buf + GPTH_FstLba, 2 + sz_pt); /* LBA of first allocatable sector */ - st_qword(buf + GPTH_LstLba, s_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 */ + 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 */ + 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 another header */ - st_qword(buf + GPTH_PtOfs, s_bpt); /* LBA of this table */ + 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 */ + 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 */ - mem_set(buf, 0, ss); - mem_cpy(buf + MBR_Table, gpt_mbr, 16); /* Create a GPT partition */ + 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 */ + { /* 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 */ + 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 */ + if (n_hd == 0) n_hd = 255; /* Number of heads needs to be <256 */ - mem_set(buf, 0, FF_MAX_SS); /* Clear MBR */ + memset(buf, 0, FF_MAX_SS); /* Clear MBR */ pte = buf + MBR_Table; /* Partition table in the MBR */ - for (i = 0, s_lba32 = n_sc; i < 4 && s_lba32 != 0 && s_lba32 < sz_drv32; i++, s_lba32 += n_lba32) { - n_lba32 = (DWORD)plst[i]; /* Get partition size */ - if (n_lba32 <= 100) n_lba32 = (n_lba32 == 100) ? sz_drv32 : sz_drv32 / 100 * n_lba32; /* Size in percentage? */ - if (s_lba32 + n_lba32 > sz_drv32 || s_lba32 + n_lba32 < s_lba32) n_lba32 = sz_drv32 - s_lba32; /* Clip at drive size */ - if (n_lba32 == 0) break; /* End of table or no sector to allocate? */ - - st_dword(pte + PTE_StLba, s_lba32); /* Start LBA */ - st_dword(pte + PTE_SizLba, n_lba32); /* Number of sectors */ + 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)(s_lba32 / n_sc / n_hd); /* Start cylinder */ - hd = (BYTE)(s_lba32 / n_sc % n_hd); /* Start head */ - sc = (BYTE)(s_lba32 % n_sc + 1); /* Start sector */ + 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)((s_lba32 + n_lba32 - 1) / n_sc / n_hd); /* End cylinder */ - hd = (BYTE)((s_lba32 + n_lba32 - 1) / n_sc % n_hd); /* End head */ - sc = (BYTE)((s_lba32 + n_lba32 - 1) % n_sc + 1); /* End sector */ + 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; @@ -5855,46 +5882,51 @@ static FRESULT create_partition ( FRESULT f_mkfs ( const TCHAR* path, /* Logical drive number */ const MKFS_PARM* opt, /* Format options */ - void* work, /* Pointer to working buffer (null: use heap memory) */ + void* work, /* Pointer to working buffer (null: use len bytes of heap memory) */ UINT len /* Size of working buffer [byte] */ ) { static const WORD cst[] = {1, 4, 16, 64, 256, 512, 0}; /* Cluster size boundary for FAT volume (4Ks unit) */ static const WORD cst32[] = {1, 2, 4, 8, 16, 32, 0}; /* Cluster size boundary for FAT32 volume (128Ks unit) */ static const MKFS_PARM defopt = {FM_ANY, 0, 0, 0, 0}; /* Default parameter */ - BYTE fsopt, fsty, sys, *buf, *pte, pdrv, ipart; + BYTE fsopt, fsty, sys, pdrv, ipart; + BYTE *buf; + BYTE *pte; WORD ss; /* Sector size */ - DWORD sz_buf, sz_blk, n_clst, pau, nsect, n; + DWORD sz_buf, sz_blk, n_clst, pau, nsect, n, vsn; LBA_t sz_vol, b_vol, b_fat, b_data; /* Size of volume, Base LBA of volume, fat, data */ LBA_t sect, lba[2]; DWORD sz_rsv, sz_fat, sz_dir, sz_au; /* Size of reserved, fat, dir, data, cluster */ UINT n_fat, n_root, i; /* Index, Number of FATs and Number of roor dir entries */ int vol; DSTATUS ds; - FRESULT fr; + FRESULT res; /* Check mounted drive and clear work area */ vol = get_ldnumber(&path); /* Get target logical drive */ if (vol < 0) return FR_INVALID_DRIVE; if (FatFs[vol]) FatFs[vol]->fs_type = 0; /* Clear the fs object if mounted */ - pdrv = LD2PD(vol); /* Physical drive */ - ipart = LD2PT(vol); /* Partition (0:create as new, 1..:get from partition table) */ - if (!opt) opt = &defopt; /* Use default parameter if it is not given */ + pdrv = LD2PD(vol); /* Hosting physical drive */ + ipart = LD2PT(vol); /* Hosting partition (0:create as new, 1..:existing partition) */ - /* Get physical drive status (sz_drv, sz_blk, ss) */ + /* Initialize the hosting physical drive */ ds = disk_initialize(pdrv); if (ds & STA_NOINIT) return FR_NOT_READY; if (ds & STA_PROTECT) return FR_WRITE_PROTECTED; + + /* Get physical drive parameters (sz_drv, sz_blk and ss) */ + if (!opt) opt = &defopt; /* Use default parameter if it is not given */ sz_blk = opt->align; - if (sz_blk == 0 && disk_ioctl(pdrv, GET_BLOCK_SIZE, &sz_blk) != RES_OK) sz_blk = 1; - if (sz_blk == 0 || sz_blk > 0x8000 || (sz_blk & (sz_blk - 1))) sz_blk = 1; + if (sz_blk == 0) disk_ioctl(pdrv, GET_BLOCK_SIZE, &sz_blk); /* Block size from the paramter or lower layer */ + if (sz_blk == 0 || sz_blk > 0x8000 || (sz_blk & (sz_blk - 1))) sz_blk = 1; /* Use default if the block size is invalid */ #if FF_MAX_SS != FF_MIN_SS if (disk_ioctl(pdrv, GET_SECTOR_SIZE, &ss) != RES_OK) return FR_DISK_ERR; if (ss > FF_MAX_SS || ss < FF_MIN_SS || (ss & (ss - 1))) return FR_DISK_ERR; #else ss = FF_MAX_SS; #endif + /* Options for FAT sub-type and FAT parameters */ fsopt = opt->fmt & (FM_ANY | FM_SFD); n_fat = (opt->n_fat >= 1 && opt->n_fat <= 2) ? opt->n_fat : 1; @@ -5930,7 +5962,7 @@ FRESULT f_mkfs ( ofs = i = 0; while (n_ent) { /* Find MS Basic partition with order of ipart */ if (ofs == 0 && disk_read(pdrv, buf, pt_lba++, 1) != RES_OK) LEAVE_MKFS(FR_DISK_ERR); /* Get PT sector */ - if (!mem_cmp(buf + ofs + GPTE_PtGuid, GUID_MS_Basic, 16) && ++i == ipart) { /* MS basic data partition? */ + if (!memcmp(buf + ofs + GPTE_PtGuid, GUID_MS_Basic, 16) && ++i == ipart) { /* MS basic data partition? */ b_vol = ld_qword(buf + ofs + GPTE_FstLba); sz_vol = ld_qword(buf + ofs + GPTE_LstLba) - b_vol + 1; break; @@ -5966,7 +5998,7 @@ FRESULT f_mkfs ( } if (sz_vol < 128) LEAVE_MKFS(FR_MKFS_ABORTED); /* Check if volume size is >=128s */ - /* Now start to create a FAT volume at b_vol and sz_vol */ + /* Now start to create an FAT volume at b_vol and sz_vol */ do { /* Pre-determine the FAT type */ if (FF_FS_EXFAT && (fsopt & FM_EXFAT)) { /* exFAT possible? */ @@ -5987,6 +6019,8 @@ FRESULT f_mkfs ( fsty = FS_FAT16; } while (0); + vsn = (DWORD)sz_vol + GET_FATTIME(); /* VSN generated from current time and partitiion size */ + #if FF_FS_EXFAT if (fsty == FS_EXFAT) { /* Create an exFAT volume */ DWORD szb_bit, szb_case, sum, nbit, clu, clen[3]; @@ -6008,7 +6042,7 @@ FRESULT f_mkfs ( sz_fat = (DWORD)((sz_vol / sz_au + 2) * 4 + ss - 1) / ss; /* Number of FAT sectors */ b_data = (b_fat + sz_fat + sz_blk - 1) & ~((LBA_t)sz_blk - 1); /* Align data area to the erase block boundary */ if (b_data - b_vol >= sz_vol / 2) LEAVE_MKFS(FR_MKFS_ABORTED); /* Too small volume? */ - n_clst = (DWORD)(sz_vol - (b_data - b_vol)) / sz_au; /* Number of clusters */ + n_clst = (DWORD)((sz_vol - (b_data - b_vol)) / sz_au); /* Number of clusters */ if (n_clst <16) LEAVE_MKFS(FR_MKFS_ABORTED); /* Too few clusters? */ if (n_clst > MAX_EXFAT) LEAVE_MKFS(FR_MKFS_ABORTED); /* Too many clusters? */ @@ -6041,7 +6075,7 @@ FRESULT f_mkfs ( ch = (WCHAR)j; si += (WCHAR)j; /* Number of chars to skip */ st = 0; } - sum = xsum32(buf[i + 0] = (BYTE)ch, sum); /* Put it into the write buffer */ + sum = xsum32(buf[i + 0] = (BYTE)ch, sum); /* Put it into the write buffer */ sum = xsum32(buf[i + 1] = (BYTE)(ch >> 8), sum); i += 2; szb_case += 2; if (si == 0 || i == sz_buf * ss) { /* Write buffered data when buffer full or end of process */ @@ -6057,7 +6091,7 @@ FRESULT f_mkfs ( sect = b_data; nsect = (szb_bit + ss - 1) / ss; /* Start of bitmap and number of bitmap sectors */ nbit = clen[0] + clen[1] + clen[2]; /* Number of clusters in-use by system (bitmap, up-case and root-dir) */ do { - mem_set(buf, 0, sz_buf * ss); /* Initialize bitmap buffer */ + memset(buf, 0, sz_buf * ss); /* Initialize bitmap buffer */ for (i = 0; nbit != 0 && i / 8 < sz_buf * ss; buf[i / 8] |= 1 << (i % 8), i++, nbit--) ; /* Mark used clusters */ n = (nsect > sz_buf) ? sz_buf : nsect; /* Write the buffered data */ if (disk_write(pdrv, buf, sect, n) != RES_OK) LEAVE_MKFS(FR_DISK_ERR); @@ -6068,7 +6102,7 @@ FRESULT f_mkfs ( sect = b_fat; nsect = sz_fat; /* Start of FAT and number of FAT sectors */ j = nbit = clu = 0; do { - mem_set(buf, 0, sz_buf * ss); i = 0; /* Clear work area and reset write offset */ + memset(buf, 0, sz_buf * ss); i = 0; /* Clear work area and reset write offset */ if (clu == 0) { /* Initialize FAT [0] and FAT[1] */ st_dword(buf + i, 0xFFFFFFF8); i += 4; clu++; st_dword(buf + i, 0xFFFFFFFF); i += 4; clu++; @@ -6086,20 +6120,20 @@ FRESULT f_mkfs ( } while (nsect); /* Initialize the root directory */ - mem_set(buf, 0, sz_buf * ss); - buf[SZDIRE * 0 + 0] = ET_VLABEL; /* Volume label entry (no label) */ - buf[SZDIRE * 1 + 0] = ET_BITMAP; /* Bitmap entry */ - st_dword(buf + SZDIRE * 1 + 20, 2); /* cluster */ - st_dword(buf + SZDIRE * 1 + 24, szb_bit); /* size */ - buf[SZDIRE * 2 + 0] = ET_UPCASE; /* Up-case table entry */ - st_dword(buf + SZDIRE * 2 + 4, sum); /* sum */ - st_dword(buf + SZDIRE * 2 + 20, 2 + clen[0]); /* cluster */ - st_dword(buf + SZDIRE * 2 + 24, szb_case); /* size */ + memset(buf, 0, sz_buf * ss); + buf[SZDIRE * 0 + 0] = ET_VLABEL; /* Volume label entry (no label) */ + buf[SZDIRE * 1 + 0] = ET_BITMAP; /* Bitmap entry */ + st_dword(buf + SZDIRE * 1 + 20, 2); /* cluster */ + st_dword(buf + SZDIRE * 1 + 24, szb_bit); /* size */ + buf[SZDIRE * 2 + 0] = ET_UPCASE; /* Up-case table entry */ + st_dword(buf + SZDIRE * 2 + 4, sum); /* sum */ + st_dword(buf + SZDIRE * 2 + 20, 2 + clen[0]); /* cluster */ + st_dword(buf + SZDIRE * 2 + 24, szb_case); /* size */ sect = b_data + sz_au * (clen[0] + clen[1]); nsect = sz_au; /* Start of the root directory and number of sectors */ do { /* Fill root directory sectors */ n = (nsect > sz_buf) ? sz_buf : nsect; if (disk_write(pdrv, buf, sect, n) != RES_OK) LEAVE_MKFS(FR_DISK_ERR); - mem_set(buf, 0, ss); /* Rest of entries are filled with zero */ + memset(buf, 0, ss); /* Rest of entries are filled with zero */ sect += n; nsect -= n; } while (nsect); @@ -6107,8 +6141,8 @@ FRESULT f_mkfs ( sect = b_vol; for (n = 0; n < 2; n++) { /* Main record (+0) */ - mem_set(buf, 0, ss); - mem_cpy(buf + BS_JmpBoot, "\xEB\x76\x90" "EXFAT ", 11); /* Boot jump code (x86), OEM name */ + memset(buf, 0, ss); + memcpy(buf + BS_JmpBoot, "\xEB\x76\x90" "EXFAT ", 11); /* Boot jump code (x86), OEM name */ st_qword(buf + BPB_VolOfsEx, b_vol); /* Volume offset in the physical drive [sector] */ st_qword(buf + BPB_TotSecEx, sz_vol); /* Volume size [sector] */ st_dword(buf + BPB_FatOfsEx, (DWORD)(b_fat - b_vol)); /* FAT offset [sector] */ @@ -6116,7 +6150,7 @@ FRESULT f_mkfs ( st_dword(buf + BPB_DataOfsEx, (DWORD)(b_data - b_vol)); /* Data offset [sector] */ st_dword(buf + BPB_NumClusEx, n_clst); /* Number of clusters */ st_dword(buf + BPB_RootClusEx, 2 + clen[0] + clen[1]); /* Root dir cluster # */ - st_dword(buf + BPB_VolIDEx, GET_FATTIME()); /* VSN */ + st_dword(buf + BPB_VolIDEx, vsn); /* VSN */ st_word(buf + BPB_FSVerEx, 0x100); /* Filesystem version (1.00) */ for (buf[BPB_BytsPerSecEx] = 0, i = ss; i >>= 1; buf[BPB_BytsPerSecEx]++) ; /* Log2 of sector size [byte] */ for (buf[BPB_SecPerClusEx] = 0, i = sz_au; i >>= 1; buf[BPB_SecPerClusEx]++) ; /* Log2 of cluster size [sector] */ @@ -6129,14 +6163,14 @@ FRESULT f_mkfs ( } if (disk_write(pdrv, buf, sect++, 1) != RES_OK) LEAVE_MKFS(FR_DISK_ERR); /* Extended bootstrap record (+1..+8) */ - mem_set(buf, 0, ss); + memset(buf, 0, ss); st_word(buf + ss - 2, 0xAA55); /* Signature (placed at end of sector) */ for (j = 1; j < 9; j++) { for (i = 0; i < ss; sum = xsum32(buf[i++], sum)) ; /* VBR checksum */ if (disk_write(pdrv, buf, sect++, 1) != RES_OK) LEAVE_MKFS(FR_DISK_ERR); } /* OEM/Reserved record (+9..+10) */ - mem_set(buf, 0, ss); + memset(buf, 0, ss); for ( ; j < 11; j++) { for (i = 0; i < ss; sum = xsum32(buf[i++], sum)) ; /* VBR checksum */ if (disk_write(pdrv, buf, sect++, 1) != RES_OK) LEAVE_MKFS(FR_DISK_ERR); @@ -6204,7 +6238,7 @@ FRESULT f_mkfs ( if (fsty == FS_FAT16) { if (n_clst > MAX_FAT16) { /* Too many clusters for FAT16 */ if (sz_au == 0 && (pau * 2) <= 64) { - sz_au = pau * 2; continue; /* Adjust cluster size and retry */ + sz_au = pau * 2; continue; /* Adjust cluster size and retry */ } if ((fsopt & FM_FAT32)) { fsty = FS_FAT32; continue; /* Switch type to FAT32 and retry */ @@ -6228,8 +6262,8 @@ FRESULT f_mkfs ( disk_ioctl(pdrv, CTRL_TRIM, lba); #endif /* Create FAT VBR */ - mem_set(buf, 0, ss); - mem_cpy(buf + BS_JmpBoot, "\xEB\xFE\x90" "MSDOS5.0", 11);/* Boot jump code (x86), OEM name */ + memset(buf, 0, ss); + memcpy(buf + BS_JmpBoot, "\xEB\xFE\x90" "MSDOS5.0", 11); /* Boot jump code (x86), OEM name */ st_word(buf + BPB_BytsPerSec, ss); /* Sector size [byte] */ buf[BPB_SecPerClus] = (BYTE)pau; /* Cluster size [sector] */ st_word(buf + BPB_RsvdSecCnt, (WORD)sz_rsv); /* Size of reserved area */ @@ -6245,20 +6279,20 @@ FRESULT f_mkfs ( st_word(buf + BPB_NumHeads, 255); /* Number of heads (for int13) */ st_dword(buf + BPB_HiddSec, (DWORD)b_vol); /* Volume offset in the physical drive [sector] */ if (fsty == FS_FAT32) { - st_dword(buf + BS_VolID32, GET_FATTIME()); /* VSN */ + st_dword(buf + BS_VolID32, vsn); /* VSN */ st_dword(buf + BPB_FATSz32, sz_fat); /* FAT size [sector] */ st_dword(buf + BPB_RootClus32, 2); /* Root directory cluster # (2) */ st_word(buf + BPB_FSInfo32, 1); /* Offset of FSINFO sector (VBR + 1) */ st_word(buf + BPB_BkBootSec32, 6); /* Offset of backup VBR (VBR + 6) */ buf[BS_DrvNum32] = 0x80; /* Drive number (for int13) */ buf[BS_BootSig32] = 0x29; /* Extended boot signature */ - mem_cpy(buf + BS_VolLab32, "NO NAME " "FAT32 ", 19); /* Volume label, FAT signature */ + memcpy(buf + BS_VolLab32, "NO NAME " "FAT32 ", 19); /* Volume label, FAT signature */ } else { - st_dword(buf + BS_VolID, GET_FATTIME()); /* VSN */ + st_dword(buf + BS_VolID, vsn); /* VSN */ st_word(buf + BPB_FATSz16, (WORD)sz_fat); /* FAT size [sector] */ buf[BS_DrvNum] = 0x80; /* Drive number (for int13) */ buf[BS_BootSig] = 0x29; /* Extended boot signature */ - mem_cpy(buf + BS_VolLab, "NO NAME " "FAT ", 19); /* Volume label, FAT signature */ + memcpy(buf + BS_VolLab, "NO NAME " "FAT ", 19); /* Volume label, FAT signature */ } st_word(buf + BS_55AA, 0xAA55); /* Signature (offset is fixed here regardless of sector size) */ if (disk_write(pdrv, buf, b_vol, 1) != RES_OK) LEAVE_MKFS(FR_DISK_ERR); /* Write it to the VBR sector */ @@ -6266,7 +6300,7 @@ FRESULT f_mkfs ( /* Create FSINFO record if needed */ if (fsty == FS_FAT32) { disk_write(pdrv, buf, b_vol + 6, 1); /* Write backup VBR (VBR + 6) */ - mem_set(buf, 0, ss); + memset(buf, 0, ss); st_dword(buf + FSI_LeadSig, 0x41615252); st_dword(buf + FSI_StrucSig, 0x61417272); st_dword(buf + FSI_Free_Count, n_clst - 1); /* Number of free clusters */ @@ -6277,7 +6311,7 @@ FRESULT f_mkfs ( } /* Initialize FAT area */ - mem_set(buf, 0, sz_buf * ss); + memset(buf, 0, sz_buf * ss); sect = b_fat; /* FAT start sector */ for (i = 0; i < n_fat; i++) { /* Initialize FATs each */ if (fsty == FS_FAT32) { @@ -6291,7 +6325,7 @@ FRESULT f_mkfs ( do { /* Fill FAT sectors */ n = (nsect > sz_buf) ? sz_buf : nsect; if (disk_write(pdrv, buf, sect, (UINT)n) != RES_OK) LEAVE_MKFS(FR_DISK_ERR); - mem_set(buf, 0, ss); /* Rest of FAT all are cleared */ + memset(buf, 0, ss); /* Rest of FAT all are cleared */ sect += n; nsect -= n; } while (nsect); } @@ -6309,32 +6343,30 @@ FRESULT f_mkfs ( /* Determine system ID in the MBR partition table */ if (FF_FS_EXFAT && fsty == FS_EXFAT) { - sys = 0x07; /* exFAT */ + sys = 0x07; /* exFAT */ + } else if (fsty == FS_FAT32) { + sys = 0x0C; /* FAT32X */ + } else if (sz_vol >= 0x10000) { + sys = 0x06; /* FAT12/16 (large) */ + } else if (fsty == FS_FAT16) { + sys = 0x04; /* FAT16 */ } else { - if (fsty == FS_FAT32) { - sys = 0x0C; /* FAT32X */ - } else { - if (sz_vol >= 0x10000) { - sys = 0x06; /* FAT12/16 (large) */ - } else { - sys = (fsty == FS_FAT16) ? 0x04 : 0x01; /* FAT16 : FAT12 */ - } - } + sys = 0x01; /* FAT12 */ } /* Update partition information */ if (FF_MULTI_PARTITION && ipart != 0) { /* Volume is in the existing partition */ - if (!FF_LBA64 || !(fsopt & 0x80)) { + if (!FF_LBA64 || !(fsopt & 0x80)) { /* Is the partition in MBR? */ /* Update system ID in the partition table */ if (disk_read(pdrv, buf, 0, 1) != RES_OK) LEAVE_MKFS(FR_DISK_ERR); /* Read the MBR */ buf[MBR_Table + (ipart - 1) * SZ_PTE + PTE_System] = sys; /* Set system ID */ if (disk_write(pdrv, buf, 0, 1) != RES_OK) LEAVE_MKFS(FR_DISK_ERR); /* Write it back to the MBR */ } } else { /* Volume as a new single partition */ - if (!(fsopt & FM_SFD)) { /* Create partition table if not in SFD */ - lba[0] = sz_vol, lba[1] = 0; - fr = create_partition(pdrv, lba, sys, buf); - if (fr != FR_OK) LEAVE_MKFS(fr); + if (!(fsopt & FM_SFD)) { /* Create partition table if not in SFD format */ + lba[0] = sz_vol; lba[1] = 0; + res = create_partition(pdrv, lba, sys, buf); + if (res != FR_OK) LEAVE_MKFS(res); } } @@ -6359,17 +6391,22 @@ FRESULT f_fdisk ( { 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; - LEAVE_MKFS(create_partition(pdrv, ptbl, 0x07, buf)); + res = create_partition(pdrv, ptbl, 0x07, buf); /* Create partitions (system ID is temporary setting and determined by f_mkfs) */ + + LEAVE_MKFS(res); } #endif /* FF_MULTI_PARTITION */ @@ -6415,12 +6452,12 @@ TCHAR* f_gets ( if (rc != 1) break; /* EOF? */ wc = s[0]; if (dbc_1st((BYTE)wc)) { /* DBC 1st byte? */ - f_read(fp, s, 1, &rc); /* Get DBC 2nd byte */ + f_read(fp, s, 1, &rc); /* Get 2nd byte */ if (rc != 1 || !dbc_2nd(s[0])) continue; /* Wrong code? */ wc = wc << 8 | s[0]; } - dc = ff_oem2uni(wc, CODEPAGE); /* OEM --> */ - if (dc == 0) continue; + dc = ff_oem2uni(wc, CODEPAGE); /* Convert ANSI/OEM into Unicode */ + if (dc == 0) continue; /* Conversion error? */ #elif FF_STRF_ENCODE == 1 || FF_STRF_ENCODE == 2 /* Read a character in UTF-16LE/BE */ f_read(fp, s, 2, &rc); /* Get a code unit */ if (rc != 2) break; /* EOF? */ @@ -6439,11 +6476,17 @@ TCHAR* f_gets ( dc = s[0]; if (dc >= 0x80) { /* Multi-byte sequence? */ ct = 0; - if ((dc & 0xE0) == 0xC0) { dc &= 0x1F; ct = 1; } /* 2-byte sequence? */ - if ((dc & 0xF0) == 0xE0) { dc &= 0x0F; ct = 2; } /* 3-byte sequence? */ - if ((dc & 0xF8) == 0xF0) { dc &= 0x07; ct = 3; } /* 4-byte sequence? */ + if ((dc & 0xE0) == 0xC0) { /* 2-byte sequence? */ + dc &= 0x1F; ct = 1; + } + if ((dc & 0xF0) == 0xE0) { /* 3-byte sequence? */ + dc &= 0x0F; ct = 2; + } + if ((dc & 0xF8) == 0xF0) { /* 4-byte sequence? */ + dc &= 0x07; ct = 3; + } if (ct == 0) continue; - f_read(fp, s, ct, &rc); /* Get trailing bytes */ + f_read(fp, s, ct, &rc); /* Get trailing bytes */ if (rc != ct) break; rc = 0; do { /* Merge the byte sequence */ @@ -6468,25 +6511,21 @@ TCHAR* f_gets ( *p++ = (TCHAR)dc; nc++; if (dc == '\n') break; /* End of line? */ - } else { - if (dc < 0x800) { /* 2-byte sequence? */ - *p++ = (TCHAR)(0xC0 | (dc >> 6 & 0x1F)); - *p++ = (TCHAR)(0x80 | (dc >> 0 & 0x3F)); - nc += 2; - } else { - if (dc < 0x10000) { /* 3-byte sequence? */ - *p++ = (TCHAR)(0xE0 | (dc >> 12 & 0x0F)); - *p++ = (TCHAR)(0x80 | (dc >> 6 & 0x3F)); - *p++ = (TCHAR)(0x80 | (dc >> 0 & 0x3F)); - nc += 3; - } else { /* 4-byte sequence? */ - *p++ = (TCHAR)(0xF0 | (dc >> 18 & 0x07)); - *p++ = (TCHAR)(0x80 | (dc >> 12 & 0x3F)); - *p++ = (TCHAR)(0x80 | (dc >> 6 & 0x3F)); - *p++ = (TCHAR)(0x80 | (dc >> 0 & 0x3F)); - nc += 4; - } - } + } else if (dc < 0x800) { /* 2-byte sequence? */ + *p++ = (TCHAR)(0xC0 | (dc >> 6 & 0x1F)); + *p++ = (TCHAR)(0x80 | (dc >> 0 & 0x3F)); + nc += 2; + } else if (dc < 0x10000) { /* 3-byte sequence? */ + *p++ = (TCHAR)(0xE0 | (dc >> 12 & 0x0F)); + *p++ = (TCHAR)(0x80 | (dc >> 6 & 0x3F)); + *p++ = (TCHAR)(0x80 | (dc >> 0 & 0x3F)); + nc += 3; + } else { /* 4-byte sequence */ + *p++ = (TCHAR)(0xF0 | (dc >> 18 & 0x07)); + *p++ = (TCHAR)(0x80 | (dc >> 12 & 0x3F)); + *p++ = (TCHAR)(0x80 | (dc >> 6 & 0x3F)); + *p++ = (TCHAR)(0x80 | (dc >> 0 & 0x3F)); + nc += 4; } #endif } @@ -6512,11 +6551,14 @@ TCHAR* f_gets ( #if !FF_FS_READONLY #include +#define SZ_PUTC_BUF 64 +#define SZ_NUM_BUF 32 + /*-----------------------------------------------------------------------*/ -/* Put a Character to the File (sub-functions) */ +/* Put a Character to the File (with sub-functions) */ /*-----------------------------------------------------------------------*/ -/* Putchar output buffer and work area */ +/* Output buffer and work area */ typedef struct { FIL *fp; /* Ptr to the writing file */ @@ -6527,11 +6569,11 @@ typedef struct { BYTE bs[4]; UINT wi, ct; #endif - BYTE buf[64]; /* Write buffer */ + BYTE buf[SZ_PUTC_BUF]; /* Write buffer */ } putbuff; -/* Buffered write with code conversion */ +/* Buffered file write with code conversion */ static void putc_bfd (putbuff* pb, TCHAR c) { @@ -6541,7 +6583,7 @@ static void putc_bfd (putbuff* pb, TCHAR c) WCHAR hs, wc; #if FF_LFN_UNICODE == 2 DWORD dc; - const TCHAR *tp; + const TCHAR* tp; #endif #endif @@ -6550,44 +6592,44 @@ static void putc_bfd (putbuff* pb, TCHAR c) } i = pb->idx; /* Write index of pb->buf[] */ - if (i < 0) return; + 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)) { /* High surrogate? */ + 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) { /* There is a leading high surrogate */ - if (!IsSurrogateL(c)) hs = 0; /* Discard high surrogate if not a surrogate pair */ + 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 */ + 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? */ + 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 & 0xF1) == 0xF0) pb->ct = 3; /* 4-byte sequence? */ - return; + 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; + pb->ct = 0; continue; /* Discard the sequense */ } pb->bs[++pb->wi] = (BYTE)c; /* Save the trailing byte */ - if (--pb->ct == 0) break; /* End of multi-byte sequence? */ + if (--pb->ct == 0) break; /* End of the sequence? */ return; } } tp = (const TCHAR*)pb->bs; - dc = tchar2uni(&tp); /* UTF-8 ==> UTF-16 */ + dc = tchar2uni(&tp); /* UTF-8 ==> UTF-16 */ if (dc == 0xFFFFFFFF) return; /* Wrong code? */ - wc = (WCHAR)dc; 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? */ @@ -6649,7 +6691,7 @@ static void putc_bfd (putbuff* pb, TCHAR c) pb->buf[i++] = (BYTE)wc; #endif -#else /* ANSI/OEM input (without re-encoding) */ +#else /* ANSI/OEM input (without re-encoding) */ pb->buf[i++] = (BYTE)c; #endif @@ -6679,7 +6721,7 @@ static int putc_flush (putbuff* pb) static void putc_init (putbuff* pb, FIL* fp) { - mem_set(pb, 0, sizeof (putbuff)); + memset(pb, 0, sizeof (putbuff)); pb->fp = fp; } @@ -6722,8 +6764,131 @@ int f_puts ( /*-----------------------------------------------------------------------*/ -/* Put a Formatted String to the File */ +/* Put a Formatted String to the File (with sub-functions) */ /*-----------------------------------------------------------------------*/ +#if FF_PRINT_FLOAT && FF_INTDEF == 2 +#include + +static int ilog10 (double n) /* Calculate log10(n) in integer output */ +{ + int rv = 0; + + while (n >= 10) { /* Decimate digit in right shift */ + if (n >= 100000) { + n /= 100000; rv += 5; + } else { + n /= 10; rv++; + } + } + while (n < 1) { /* Decimate digit in left shift */ + if (n < 0.00001) { + n *= 100000; rv -= 5; + } else { + n *= 10; rv--; + } + } + return rv; +} + + +static double i10x (int n) /* Calculate 10^n in integer input */ +{ + double rv = 1; + + while (n > 0) { /* Left shift */ + if (n >= 5) { + rv *= 100000; n -= 5; + } else { + rv *= 10; n--; + } + } + while (n < 0) { /* Right shift */ + if (n <= -5) { + rv /= 100000; n += 5; + } else { + rv /= 10; n++; + } + } + return rv; +} + + +static void ftoa ( + char* buf, /* Buffer to output the floating point string */ + double val, /* Value to output */ + int prec, /* Number of fractional digits */ + TCHAR fmt /* Notation */ +) +{ + int d; + int e = 0, m = 0; + char sign = 0; + double w; + const char *er = 0; + const char ds = FF_PRINT_FLOAT == 2 ? ',' : '.'; + + + if (isnan(val)) { /* Not a number? */ + er = "NaN"; + } else { + if (prec < 0) prec = 6; /* Default precision? (6 fractional digits) */ + if (val < 0) { /* Negative? */ + val = 0 - val; sign = '-'; + } else { + sign = '+'; + } + if (isinf(val)) { /* Infinite? */ + er = "INF"; + } else { + if (fmt == 'f') { /* Decimal notation? */ + val += i10x(0 - prec) / 2; /* Round (nearest) */ + m = ilog10(val); + if (m < 0) m = 0; + if (m + prec + 3 >= SZ_NUM_BUF) er = "OV"; /* Buffer overflow? */ + } else { /* E notation */ + if (val != 0) { /* Not a true zero? */ + val += i10x(ilog10(val) - prec) / 2; /* Round (nearest) */ + e = ilog10(val); + if (e > 99 || prec + 7 >= SZ_NUM_BUF) { /* Buffer overflow or E > +99? */ + er = "OV"; + } else { + if (e < -99) e = -99; + val /= i10x(e); /* Normalize */ + } + } + } + } + if (!er) { /* Not error condition */ + if (sign == '-') *buf++ = sign; /* Add a - if negative value */ + do { /* Put decimal number */ + if (m == -1) *buf++ = ds; /* Insert a decimal separator when get into fractional part */ + w = i10x(m); /* Snip the highest digit d */ + d = (int)(val / w); val -= d * w; + *buf++ = (char)('0' + d); /* Put the digit */ + } while (--m >= -prec); /* Output all digits specified by prec */ + if (fmt != 'f') { /* Put exponent if needed */ + *buf++ = (char)fmt; + if (e < 0) { + e = 0 - e; *buf++ = '-'; + } else { + *buf++ = '+'; + } + *buf++ = (char)('0' + e / 10); + *buf++ = (char)('0' + e % 10); + } + } + } + if (er) { /* Error condition */ + if (sign) *buf++ = sign; /* Add sign if needed */ + do { /* Put error symbol */ + *buf++ = *er++; + } while (*er); + } + *buf = 0; /* Term */ +} +#endif /* FF_PRINT_FLOAT && FF_INTDEF == 2 */ + + int f_printf ( FIL* fp, /* Pointer to the file object */ @@ -6733,10 +6898,17 @@ int f_printf ( { va_list arp; putbuff pb; - BYTE f, r; - UINT i, j, w; + UINT i, j, w, f, r; + int prec; +#if FF_PRINT_LLI && FF_INTDEF == 2 + QWORD v; +#else DWORD v; - TCHAR c, d, str[32], *p; +#endif + TCHAR *tp; + TCHAR tc, pad; + TCHAR nul = 0; + char d, str[SZ_NUM_BUF]; putc_init(&pb, fp); @@ -6744,93 +6916,131 @@ int f_printf ( va_start(arp, fmt); for (;;) { - c = *fmt++; - if (c == 0) break; /* End of string */ - if (c != '%') { /* Non escape character */ - putc_bfd(&pb, c); + tc = *fmt++; + if (tc == 0) break; /* End of format string */ + if (tc != '%') { /* Not an escape character (pass-through) */ + putc_bfd(&pb, tc); continue; } - w = f = 0; - c = *fmt++; - if (c == '0') { /* Flag: '0' padding */ - f = 1; c = *fmt++; - } else { - if (c == '-') { /* Flag: left justified */ - f = 2; c = *fmt++; - } + 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 (c == '*') { /* Minimum width by argument */ + if (tc == '*') { /* Minimum width from an argument */ w = va_arg(arp, int); - c = *fmt++; + tc = *fmt++; } else { - while (IsDigit(c)) { /* Minimum width */ - w = w * 10 + c - '0'; - c = *fmt++; - } - } - if (c == 'l' || c == 'L') { /* Type prefix: Size is long int */ - f |= 4; c = *fmt++; - } - if (c == 0) break; - d = c; - if (IsLower(d)) d -= 0x20; - switch (d) { /* Atgument type is... */ - case 'S': /* String */ - p = va_arg(arp, TCHAR*); - for (j = 0; p[j]; j++) ; - if (!(f & 2)) { /* Right padded */ - while (j++ < w) putc_bfd(&pb, ' ') ; - } - while (*p) putc_bfd(&pb, *p++) ; /* String body */ - while (j++ < w) putc_bfd(&pb, ' ') ; /* Left padded */ - continue; - - case 'C': /* Character */ - putc_bfd(&pb, (TCHAR)va_arg(arp, int)); - continue; + 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 'B': /* Unsigned binary */ - r = 2; - break; + case 'o': /* Unsigned octal */ + r = 8; break; - case 'O': /* Unsigned octal */ - r = 8; - break; + case 'd': /* Signed decimal */ + case 'u': /* Unsigned decimal */ + r = 10; 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 'X': /* Unsigned hexdecimal */ - 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, c); continue; + putc_bfd(&pb, tc); continue; } - /* Get an argument and put it in numeral */ - v = (f & 4) ? (DWORD)va_arg(arp, long) : ((d == 'D') ? (DWORD)(long)va_arg(arp, int) : (DWORD)va_arg(arp, unsigned int)); - if (d == 'D' && (v & 0x80000000)) { - v = 0 - v; - f |= 8; + /* 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 { - d = (TCHAR)(v % r); v /= r; - if (d > 9) d += (c == 'x') ? 0x27 : 0x07; + 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 < sizeof str / sizeof *str); - if (f & 8) str[i++] = '-'; - j = i; d = (f & 1) ? '0' : ' '; - if (!(f & 2)) { - while (j++ < w) putc_bfd(&pb, d); /* Right pad */ - } - do { - putc_bfd(&pb, str[--i]); /* Number body */ + } 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) putc_bfd(&pb, d); /* Left pad */ + while (j++ < w) { /* Right pads */ + putc_bfd(&pb, ' '); + } } va_end(arp); @@ -6852,13 +7062,13 @@ FRESULT f_setcp ( WORD cp /* Value to be set as active code page */ ) { - static const WORD validcp[] = { 437, 720, 737, 771, 775, 850, 852, 857, 860, 861, 862, 863, 864, 865, 866, 869, 932, 936, 949, 950, 0}; - static const BYTE* const tables[] = {Ct437, Ct720, Ct737, Ct771, Ct775, Ct850, Ct852, Ct857, Ct860, Ct861, Ct862, Ct863, Ct864, Ct865, Ct866, Ct869, Dc932, Dc936, Dc949, Dc950, 0}; + 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? */ + if (validcp[i] != cp) return FR_INVALID_PARAMETER; /* Not found? */ CodePage = cp; if (cp >= 900) { /* DBCS */ diff --git a/src/fatfs/ff.h b/src/fatfs/ff.h index b1dffc2301..d88febc12d 100644 --- a/src/fatfs/ff.h +++ b/src/fatfs/ff.h @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------/ -/ FatFs - Generic FAT Filesystem module R0.14a / +/ FatFs - Generic FAT Filesystem module R0.15 / /-----------------------------------------------------------------------------/ / -/ Copyright (C) 2020, ChaN, all right reserved. +/ Copyright (C) 2022, ChaN, all right reserved. / / FatFs module is an open source software. Redistribution and use of FatFs in / source and binary forms, with or without modification, are permitted provided @@ -20,7 +20,7 @@ #ifndef FF_DEFINED -#define FF_DEFINED 80196 /* Revision ID */ +#define FF_DEFINED 80286 /* Revision ID */ #ifdef __cplusplus extern "C" { @@ -35,10 +35,14 @@ extern "C" { /* Integer types used for FatFs API */ -#if defined(_WIN32) /* Main development platform */ +#if defined(_WIN32) /* Windows VC++ (for development only) */ #define FF_INTDEF 2 #include typedef unsigned __int64 QWORD; +#include +#define isnan(v) _isnan(v) +#define isinf(v) (!_finite(v)) + #elif (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L) || defined(__cplusplus) /* C99 or later */ #define FF_INTDEF 2 #include @@ -48,6 +52,7 @@ typedef uint16_t WORD; /* 16-bit unsigned integer */ typedef uint32_t DWORD; /* 32-bit unsigned integer */ typedef uint64_t QWORD; /* 64-bit unsigned integer */ typedef WORD WCHAR; /* UTF-16 character type */ + #else /* Earlier than C99 */ #define FF_INTDEF 1 typedef unsigned int UINT; /* int must be 16-bit or 32-bit */ @@ -58,28 +63,29 @@ typedef WORD WCHAR; /* UTF-16 character type */ #endif -/* Definitions of volume management */ +/* Type of file size and LBA variables */ -#if FF_MULTI_PARTITION /* Multiple partition configuration */ -typedef struct { - BYTE pd; /* Physical drive number */ - BYTE pt; /* Partition: 0:Auto detect, 1-4:Forced partition) */ -} PARTITION; -extern PARTITION VolToPart[]; /* Volume - Partition mapping table */ +#if FF_FS_EXFAT +#if FF_INTDEF != 2 +#error exFAT feature wants C99 or later #endif - -#if FF_STR_VOLUME_ID -#ifndef FF_VOLUME_STRS -extern const char* VolumeStr[FF_VOLUMES]; /* User defied volume ID */ +typedef QWORD FSIZE_t; +#if FF_LBA64 +typedef QWORD LBA_t; +#else +typedef DWORD LBA_t; #endif +#else +#if FF_LBA64 +#error exFAT needs to be enabled when enable 64-bit LBA +#endif +typedef DWORD FSIZE_t; +typedef DWORD LBA_t; #endif -/* Type of path name strings on FatFs API */ - -#ifndef _INC_TCHAR -#define _INC_TCHAR +/* Type of path name strings on FatFs API (TCHAR) */ #if FF_USE_LFN && FF_LFN_UNICODE == 1 /* Unicode in UTF-16 encoding */ typedef WCHAR TCHAR; @@ -101,28 +107,22 @@ typedef char TCHAR; #define _TEXT(x) x #endif -#endif - -/* Type of file size and LBA variables */ +/* Definitions of volume management */ -#if FF_FS_EXFAT -#if FF_INTDEF != 2 -#error exFAT feature wants C99 or later -#endif -typedef QWORD FSIZE_t; -#if FF_LBA64 -typedef QWORD LBA_t; -#else -typedef DWORD LBA_t; +#if FF_MULTI_PARTITION /* Multiple partition configuration */ +typedef struct { + BYTE pd; /* Physical drive number */ + BYTE pt; /* Partition: 0:Auto detect, 1-4:Forced partition) */ +} PARTITION; +extern PARTITION VolToPart[]; /* Volume - Partition mapping table */ #endif -#else -#if FF_LBA64 -#error exFAT needs to be enabled when enable 64-bit LBA + +#if FF_STR_VOLUME_ID +#ifndef FF_VOLUME_STRS +extern const char* VolumeStr[FF_VOLUMES]; /* User defied volume ID */ #endif -typedef DWORD FSIZE_t; -typedef DWORD LBA_t; #endif @@ -131,10 +131,11 @@ typedef DWORD LBA_t; typedef struct { BYTE fs_type; /* Filesystem type (0:not mounted) */ - BYTE pdrv; /* Associated physical drive */ + BYTE pdrv; /* Volume hosting physical drive */ + BYTE ldrv; /* Logical drive number (used only when FF_FS_REENTRANT) */ BYTE n_fats; /* Number of FATs (1 or 2) */ - BYTE wflag; /* win[] flag (b0:dirty) */ - BYTE fsi_flag; /* FSINFO flags (b7:disabled, b0:dirty) */ + BYTE wflag; /* win[] status (b0:dirty) */ + BYTE fsi_flag; /* FSINFO status (b7:disabled, b0:dirty) */ WORD id; /* Volume mount ID */ WORD n_rootdir; /* Number of root directory entries (FAT12/16) */ WORD csize; /* Cluster size [sectors] */ @@ -147,9 +148,6 @@ typedef struct { #if FF_FS_EXFAT BYTE* dirbuf; /* Directory entry block scratchpad buffer for exFAT */ #endif -#if FF_FS_REENTRANT - FF_SYNC_t sobj; /* Identifier of sync object */ -#endif #if !FF_FS_READONLY DWORD last_clst; /* Last allocated cluster */ DWORD free_clst; /* Number of free clusters */ @@ -163,10 +161,10 @@ typedef struct { #endif #endif DWORD n_fatent; /* Number of FAT entries (number of clusters + 2) */ - DWORD fsize; /* Size of an FAT [sectors] */ + DWORD fsize; /* Number of sectors per FAT */ LBA_t volbase; /* Volume base sector */ LBA_t fatbase; /* FAT base sector */ - LBA_t dirbase; /* Root directory base sector/cluster */ + LBA_t dirbase; /* Root directory base sector (FAT12/16) or cluster (FAT32/exFAT) */ LBA_t database; /* Data base sector */ #if FF_FS_EXFAT LBA_t bitbase; /* Allocation bitmap base sector */ @@ -181,7 +179,7 @@ typedef struct { typedef struct { FATFS* fs; /* Pointer to the hosting volume of this object */ - WORD id; /* Hosting volume mount ID */ + WORD id; /* Hosting volume's mount ID */ BYTE attr; /* Object attribute */ BYTE stat; /* Object chain status (b1-0: =0:not contiguous, =2:contiguous, =3:fragmented in this session, b2:sub-directory stretched) */ DWORD sclust; /* Object data start cluster (0:no cluster or root directory) */ @@ -250,7 +248,7 @@ typedef struct { WORD ftime; /* Modified time */ BYTE fattrib; /* File attribute */ #if FF_USE_LFN - TCHAR altname[FF_SFN_BUF + 1];/* Altenative file name */ + TCHAR altname[FF_SFN_BUF + 1];/* Alternative file name */ TCHAR fname[FF_LFN_BUF + 1]; /* Primary file name */ #else TCHAR fname[12 + 1]; /* File name */ @@ -298,8 +296,10 @@ typedef enum { + +/*--------------------------------------------------------------*/ +/* FatFs Module Application Interface */ /*--------------------------------------------------------------*/ -/* FatFs module application interface */ FRESULT f_open (FIL* fp, const TCHAR* path, BYTE mode); /* Open or create a file */ FRESULT f_close (FIL* fp); /* Close an open file object */ @@ -336,6 +336,8 @@ int f_puts (const TCHAR* str, FIL* cp); /* Put a string to the file */ int f_printf (FIL* fp, const TCHAR* str, ...); /* Put a formatted string to the file */ TCHAR* f_gets (TCHAR* buff, int len, FIL* fp); /* Get a string from the file */ +/* Some API fucntions are implemented as macro */ + #define f_eof(fp) ((int)((fp)->fptr == (fp)->obj.objsize)) #define f_error(fp) ((fp)->err) #define f_tell(fp) ((fp)->fptr) @@ -349,38 +351,43 @@ TCHAR* f_gets (TCHAR* buff, int len, FIL* fp); /* Get a string from the fil /*--------------------------------------------------------------*/ -/* Additional user defined functions */ +/* Additional Functions */ +/*--------------------------------------------------------------*/ -/* RTC function */ +/* RTC function (provided by user) */ #if !FF_FS_READONLY && !FF_FS_NORTC -DWORD get_fattime (void); +DWORD get_fattime (void); /* Get current time */ #endif -/* LFN support functions */ -#if FF_USE_LFN >= 1 /* Code conversion (defined in unicode.c) */ + +/* LFN support functions (defined in ffunicode.c) */ + +#if FF_USE_LFN >= 1 WCHAR ff_oem2uni (WCHAR oem, WORD cp); /* OEM code to Unicode conversion */ WCHAR ff_uni2oem (DWORD uni, WORD cp); /* Unicode to OEM code conversion */ DWORD ff_wtoupper (DWORD uni); /* Unicode upper-case conversion */ #endif -#if FF_USE_LFN == 3 /* Dynamic memory allocation */ -void* ff_memalloc (UINT msize); /* Allocate memory block */ -void ff_memfree (void* mblock); /* Free memory block */ -#endif -/* Sync functions */ -#if FF_FS_REENTRANT -int ff_cre_syncobj (BYTE vol, FF_SYNC_t* sobj); /* Create a sync object */ -int ff_req_grant (FF_SYNC_t sobj); /* Lock sync object */ -void ff_rel_grant (FF_SYNC_t sobj); /* Unlock sync object */ -int ff_del_syncobj (FF_SYNC_t sobj); /* Delete a sync object */ + +/* O/S dependent functions (samples available in ffsystem.c) */ + +#if FF_USE_LFN == 3 /* Dynamic memory allocation */ +void* ff_memalloc (UINT msize); /* Allocate memory block */ +void ff_memfree (void* mblock); /* Free memory block */ +#endif +#if FF_FS_REENTRANT /* Sync functions */ +int ff_mutex_create (int vol); /* Create a sync object */ +void ff_mutex_delete (int vol); /* Delete a sync object */ +int ff_mutex_take (int vol); /* Lock sync object */ +void ff_mutex_give (int vol); /* Unlock sync object */ #endif /*--------------------------------------------------------------*/ -/* Flags and offset address */ - +/* Flags and Offset Address */ +/*--------------------------------------------------------------*/ /* File access mode and open method flags (3rd argument of f_open) */ #define FA_READ 0x01 diff --git a/src/fatfs/ffconf.h b/src/fatfs/ffconf.h index dd2ef3f366..973cde964d 100644 --- a/src/fatfs/ffconf.h +++ b/src/fatfs/ffconf.h @@ -1,8 +1,8 @@ /*---------------------------------------------------------------------------/ -/ FatFs Functional Configurations +/ Configurations of FatFs Module /---------------------------------------------------------------------------*/ -#define FFCONF_DEF 80196 /* Revision ID */ +#define FFCONF_DEF 80286 /* Revision ID */ /*---------------------------------------------------------------------------/ / Function Configurations @@ -25,14 +25,6 @@ / 3: f_lseek() function is removed in addition to 2. */ -#define FF_USE_STRFUNC 0 -/* This option switches string functions, f_gets(), f_putc(), f_puts() and f_printf(). -/ -/ 0: Disable string functions. -/ 1: Enable without LF-CRLF conversion. -/ 2: Enable with LF-CRLF conversion. */ - - #define FF_USE_FIND 1 /* This option switches filtered directory read functions, f_findfirst() and / f_findnext(). (0:Disable, 1:Enable 2:Enable with matching altname[] too) */ @@ -64,6 +56,30 @@ /* This option switches f_forward() function. (0:Disable or 1:Enable) */ +#define FF_USE_STRFUNC 0 +#define FF_PRINT_LLI 1 +#define FF_PRINT_FLOAT 1 +#define FF_STRF_ENCODE 3 +/* FF_USE_STRFUNC switches string functions, f_gets(), f_putc(), f_puts() and +/ f_printf(). +/ +/ 0: Disable. FF_PRINT_LLI, FF_PRINT_FLOAT and FF_STRF_ENCODE have no effect. +/ 1: Enable without LF-CRLF conversion. +/ 2: Enable with LF-CRLF conversion. +/ +/ FF_PRINT_LLI = 1 makes f_printf() support long long argument and FF_PRINT_FLOAT = 1/2 +/ makes f_printf() support floating point argument. These features want C99 or later. +/ When FF_LFN_UNICODE >= 1 with LFN enabled, string functions convert the character +/ encoding in it. FF_STRF_ENCODE selects assumption of character encoding ON THE FILE +/ to be read/written via those functions. +/ +/ 0: ANSI/OEM in current CP +/ 1: Unicode in UTF-16LE +/ 2: Unicode in UTF-16BE +/ 3: Unicode in UTF-8 +*/ + + /*---------------------------------------------------------------------------/ / Locale and Namespace Configurations /---------------------------------------------------------------------------*/ @@ -137,19 +153,6 @@ / on character encoding. When LFN is not enabled, these options have no effect. */ -#define FF_STRF_ENCODE 3 -/* When FF_LFN_UNICODE >= 1 with LFN enabled, string I/O functions, f_gets(), -/ f_putc(), f_puts and f_printf() convert the character encoding in it. -/ This option selects assumption of character encoding ON THE FILE to be -/ read/written via those functions. -/ -/ 0: ANSI/OEM in current CP -/ 1: Unicode in UTF-16LE -/ 2: Unicode in UTF-16BE -/ 3: Unicode in UTF-8 -*/ - - #define FF_FS_RPATH 0 /* This option configures support for relative path. / @@ -175,7 +178,7 @@ / logical drives. Number of items must not be less than FF_VOLUMES. Valid / characters for the volume ID strings are A-Z, a-z and 0-9, however, they are / compared in case-insensitive. If FF_STR_VOLUME_ID >= 1 and FF_VOLUME_STRS is -/ not defined, a user defined volume string table needs to be defined as: +/ not defined, a user defined volume string table is needed as: / / const char* VolumeStr[FF_VOLUMES] = {"ram","flash","sd","usb",... */ @@ -187,14 +190,14 @@ / number and only an FAT volume found on the physical drive will be mounted. / When this function is enabled (1), each logical drive number can be bound to / arbitrary physical drive and partition listed in the VolToPart[]. Also f_fdisk() -/ funciton will be available. */ +/ function will be available. */ #define FF_MIN_SS 512 #define FF_MAX_SS 512 /* This set of options configures the range of sector size to be supported. (512, / 1024, 2048 or 4096) Always set both 512 for most systems, generic memory card and -/ harddisk. But a larger value may be required for on-board flash memory and some +/ harddisk, but a larger value may be required for on-board flash memory and some / type of optical media. When FF_MAX_SS is larger than FF_MIN_SS, FatFs is configured / for variable sector size mode and disk_ioctl() function needs to implement / GET_SECTOR_SIZE command. */ @@ -238,9 +241,9 @@ #define FF_NORTC_MON 1 #define FF_NORTC_MDAY 1 #define FF_NORTC_YEAR 2020 -/* The option FF_FS_NORTC switches timestamp functiton. If the system does not have -/ any RTC function or valid timestamp is not needed, set FF_FS_NORTC = 1 to disable -/ the timestamp function. Every object modified by FatFs will have a fixed timestamp +/* The option FF_FS_NORTC switches timestamp feature. If the system does not have +/ an RTC or valid timestamp is not needed, set FF_FS_NORTC = 1 to disable the +/ timestamp feature. Every object modified by FatFs will have a fixed timestamp / defined by FF_NORTC_MON, FF_NORTC_MDAY and FF_NORTC_YEAR in local time. / To enable timestamp function (FF_FS_NORTC = 0), get_fattime() function need to be / added to the project to read current time form real-time clock. FF_NORTC_MON, @@ -250,7 +253,7 @@ #define FF_FS_NOFSINFO 0 /* If you need to know correct free space on the FAT32 volume, set bit 0 of this -/ option, and f_getfree() function at first time after volume mount will force +/ option, and f_getfree() function at the first time after volume mount will force / a full FAT scan. Bit 1 controls the use of last allocated cluster number. / / bit0=0: Use free cluster count in the FSINFO if available. @@ -272,26 +275,21 @@ / lock control is independent of re-entrancy. */ -/* #include // O/S definitions */ #define FF_FS_REENTRANT 0 #define FF_FS_TIMEOUT 1000 -#define FF_SYNC_t HANDLE /* The option FF_FS_REENTRANT switches the re-entrancy (thread safe) of the FatFs / module itself. Note that regardless of this option, file access to different / volume is always re-entrant and volume control functions, f_mount(), f_mkfs() / and f_fdisk() function, are always not re-entrant. Only file/directory access -/ to the same volume is under control of this function. +/ to the same volume is under control of this featuer. / -/ 0: Disable re-entrancy. FF_FS_TIMEOUT and FF_SYNC_t have no effect. +/ 0: Disable re-entrancy. FF_FS_TIMEOUT have no effect. / 1: Enable re-entrancy. Also user provided synchronization handlers, -/ ff_req_grant(), ff_rel_grant(), ff_del_syncobj() and ff_cre_syncobj() -/ function, must be added to the project. Samples are available in -/ option/syscall.c. +/ ff_mutex_create(), ff_mutex_delete(), ff_mutex_take() and ff_mutex_give() +/ function, must be added to the project. Samples are available in ffsystem.c. / -/ The FF_FS_TIMEOUT defines timeout period in unit of time tick. -/ The FF_SYNC_t defines O/S dependent sync object type. e.g. HANDLE, ID, OS_EVENT*, -/ SemaphoreHandle_t and etc. A header file for O/S definitions needs to be -/ included somewhere in the scope of ff.h. */ +/ The FF_FS_TIMEOUT defines timeout period in unit of O/S time tick. +*/ diff --git a/src/fatfs/ffunicode.c b/src/fatfs/ffunicode.c index 784a10e564..54ad526710 100644 --- a/src/fatfs/ffunicode.c +++ b/src/fatfs/ffunicode.c @@ -1,13 +1,13 @@ /*------------------------------------------------------------------------*/ -/* Unicode handling functions for FatFs R0.13+ */ +/* Unicode Handling Functions for FatFs R0.13 and Later */ +/*------------------------------------------------------------------------*/ +/* This module will occupy a huge memory in the .rodata section when the */ +/* FatFs is configured for LFN with DBCS. If the system has a Unicode */ +/* library for the code conversion, this module should be modified to use */ +/* it to avoid silly memory consumption. */ /*------------------------------------------------------------------------*/ -/* This module will occupy a huge memory in the .const section when the / -/ FatFs is configured for LFN with DBCS. If the system has any Unicode / -/ utilitiy for the code conversion, this module should be modified to use / -/ that function to avoid silly memory consumption. / -/-------------------------------------------------------------------------*/ /* -/ Copyright (C) 2014, ChaN, all right reserved. +/ Copyright (C) 2022, ChaN, all right reserved. / / FatFs module is an open source software. Redistribution and use of FatFs in / source and binary forms, with or without modification, are permitted provided @@ -25,7 +25,7 @@ #include "ff.h" -#if FF_USE_LFN /* This module will be blanked if non-LFN configuration */ +#if FF_USE_LFN != 0 /* This module will be blanked if in non-LFN configuration */ #define MERGE2(a, b) a ## b #define CVTBL(tbl, cp) MERGE2(tbl, cp) @@ -15214,8 +15214,8 @@ static const WCHAR uc869[] = { /* CP869(Greek 2) to Unicode conversion table */ /*------------------------------------------------------------------------*/ -/* OEM <==> Unicode conversions for static code page configuration */ -/* SBCS fixed code page */ +/* OEM <==> Unicode Conversions for Static Code Page Configuration with */ +/* SBCS Fixed Code Page */ /*------------------------------------------------------------------------*/ #if FF_CODE_PAGE != 0 && FF_CODE_PAGE < 900 @@ -15225,7 +15225,7 @@ WCHAR ff_uni2oem ( /* Returns OEM code character, zero on error */ ) { WCHAR c = 0; - const WCHAR *p = CVTBL(uc, FF_CODE_PAGE); + const WCHAR* p = CVTBL(uc, FF_CODE_PAGE); if (uni < 0x80) { /* ASCII? */ @@ -15247,7 +15247,7 @@ WCHAR ff_oem2uni ( /* Returns Unicode character in UTF-16, zero on error */ ) { WCHAR c = 0; - const WCHAR *p = CVTBL(uc, FF_CODE_PAGE); + const WCHAR* p = CVTBL(uc, FF_CODE_PAGE); if (oem < 0x80) { /* ASCII? */ @@ -15267,8 +15267,8 @@ WCHAR ff_oem2uni ( /* Returns Unicode character in UTF-16, zero on error */ /*------------------------------------------------------------------------*/ -/* OEM <==> Unicode conversions for static code page configuration */ -/* DBCS fixed code page */ +/* OEM <==> Unicode Conversions for Static Code Page Configuration with */ +/* DBCS Fixed Code Page */ /*------------------------------------------------------------------------*/ #if FF_CODE_PAGE >= 900 @@ -15277,7 +15277,7 @@ WCHAR ff_uni2oem ( /* Returns OEM code character, zero on error */ WORD cp /* Code page for the conversion */ ) { - const WCHAR *p; + const WCHAR* p; WCHAR c = 0, uc; UINT i = 0, n, li, hi; @@ -15313,7 +15313,7 @@ WCHAR ff_oem2uni ( /* Returns Unicode character in UTF-16, zero on error */ WORD cp /* Code page for the conversion */ ) { - const WCHAR *p; + const WCHAR* p; WCHAR c = 0; UINT i = 0, n, li, hi; @@ -15346,7 +15346,7 @@ WCHAR ff_oem2uni ( /* Returns Unicode character in UTF-16, zero on error */ /*------------------------------------------------------------------------*/ -/* OEM <==> Unicode conversions for dynamic code page configuration */ +/* OEM <==> Unicode Conversions for Dynamic Code Page Configuration */ /*------------------------------------------------------------------------*/ #if FF_CODE_PAGE == 0 @@ -15360,7 +15360,7 @@ WCHAR ff_uni2oem ( /* Returns OEM code character, zero on error */ WORD cp /* Code page for the conversion */ ) { - const WCHAR *p; + const WCHAR* p; WCHAR c = 0, uc; UINT i, n, li, hi; @@ -15412,7 +15412,7 @@ WCHAR ff_oem2uni ( /* Returns Unicode character in UTF-16, zero on error */ WORD cp /* Code page for the conversion */ ) { - const WCHAR *p; + const WCHAR* p; WCHAR c = 0; UINT i, n, li, hi; @@ -15458,14 +15458,14 @@ WCHAR ff_oem2uni ( /* Returns Unicode character in UTF-16, zero on error */ /*------------------------------------------------------------------------*/ -/* Unicode up-case conversion */ +/* Unicode Up-case Conversion */ /*------------------------------------------------------------------------*/ DWORD ff_wtoupper ( /* Returns up-converted code point */ DWORD uni /* Unicode code point to be up-converted */ ) { - const WORD *p; + const WORD* p; WORD uc, bc, nc, cmd; static const WORD cvt1[] = { /* Compressed up conversion table for U+0000 - U+0FFF */ /* Basic Latin */ @@ -15590,4 +15590,4 @@ DWORD ff_wtoupper ( /* Returns up-converted code point */ } -#endif /* #if FF_USE_LFN */ +#endif /* #if FF_USE_LFN != 0 */ From 28a3858cfff076c5a002dfa5957345d1d44fe11b Mon Sep 17 00:00:00 2001 From: Robin Jones Date: Thu, 9 Feb 2023 03:07:53 +0000 Subject: [PATCH 03/11] Add ifdef to ffconf header to allow override. --- src/fatfs/ffconf.h | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/fatfs/ffconf.h b/src/fatfs/ffconf.h index 973cde964d..0c824c1dc8 100644 --- a/src/fatfs/ffconf.h +++ b/src/fatfs/ffconf.h @@ -1,3 +1,6 @@ +#ifndef FFCONF_H +#define FFCONF_H + /*---------------------------------------------------------------------------/ / Configurations of FatFs Module /---------------------------------------------------------------------------*/ @@ -294,3 +297,5 @@ /*--- End of configuration options ---*/ + +#endif /* FFCONF_H */ From afae4493726cd96ec5a89f0920a5d38a2e9250c3 Mon Sep 17 00:00:00 2001 From: Robin Jones Date: Thu, 9 Feb 2023 03:57:34 +0000 Subject: [PATCH 04/11] Attempt at license scrutiny --- src/fatfs/License.md | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 src/fatfs/License.md diff --git a/src/fatfs/License.md b/src/fatfs/License.md new file mode 100644 index 0000000000..6aca15615d --- /dev/null +++ b/src/fatfs/License.md @@ -0,0 +1,26 @@ +# FatFs License + +The following code block shows a copy of the FatFs header included in the source files (with wildcards for the date and version). +``` +/*----------------------------------------------------------------------------/ +/ FatFs - Generic FAT Filesystem Module Rx.xx / +/-----------------------------------------------------------------------------/ +/ +/ Copyright (C) 20xx, ChaN, all right reserved. +/ +/ FatFs module is an open source software. Redistribution and use of FatFs in +/ source and binary forms, with or without modification, are permitted provided +/ that the following condition is met: +/ +/ 1. Redistributions of source code must retain the above copyright notice, +/ this condition and the following disclaimer. +/ +/ This software is provided by the copyright holder and contributors "AS IS" +/ and any warranties related to this software are DISCLAIMED. +/ The copyright owner or contributors be NOT LIABLE for any damages caused +/ by use of this software. +/ +/----------------------------------------------------------------------------*/ +``` + +When you redistribute the FatFs source code with changes or create a fork, please ensure that they are compatible with the license. From b8457200a9963d8bc6e030349d52122be87ff151 Mon Sep 17 00:00:00 2001 From: Robin Jones Date: Sun, 30 Jul 2023 14:08:13 +0100 Subject: [PATCH 05/11] Update build-toolchain-library-and-roms.yml --- .github/workflows/build-toolchain-library-and-roms.yml | 7 ------- 1 file changed, 7 deletions(-) diff --git a/.github/workflows/build-toolchain-library-and-roms.yml b/.github/workflows/build-toolchain-library-and-roms.yml index 5897e58e98..84b127bbbd 100644 --- a/.github/workflows/build-toolchain-library-and-roms.yml +++ b/.github/workflows/build-toolchain-library-and-roms.yml @@ -131,10 +131,3 @@ jobs: tags: ghcr.io/${{ steps.vars.outputs.repository_name }}:latest cache-from: type=gha cache-to: type=gha,mode=max - - Run-Rom-Tests: - name: "Run ROM tests" - needs: Toolchain-Library-And-Examples - uses: ./.github/workflows/run-rom-tests.yml - secrets: - token: ${{ secrets.GITHUB_TOKEN }} From 28d297e0ca668440733b461ee7da2ccb01c1bfe2 Mon Sep 17 00:00:00 2001 From: Robin Jones Date: Sun, 30 Jul 2023 14:08:37 +0100 Subject: [PATCH 06/11] Delete run-rom-tests.yml --- .github/workflows/run-rom-tests.yml | 154 ---------------------------- 1 file changed, 154 deletions(-) delete mode 100644 .github/workflows/run-rom-tests.yml diff --git a/.github/workflows/run-rom-tests.yml b/.github/workflows/run-rom-tests.yml deleted file mode 100644 index 1e4cb104dd..0000000000 --- a/.github/workflows/run-rom-tests.yml +++ /dev/null @@ -1,154 +0,0 @@ -name: Run ROM Tests - -on: - workflow_call: - secrets: - token: - description: 'A github token passed from the caller workflow' - required: true - -jobs: - - ROM-Smoke-Tests-Ares-Windows: - name: Ares Emulator Smoke tests - runs-on: windows-latest - - # Run each ROM using on ares emulator. - strategy: - fail-fast: false - matrix: - include: [ - { rom-name: testrom_emu, ares-ci-compatible: true, rom-path: tests }, - { rom-name: testrom, ares-ci-compatible: true, rom-path: tests }, - { rom-name: audioplayer, ares-ci-compatible: false, rom-path: examples/audioplayer }, - { rom-name: cpptest, ares-ci-compatible: true, rom-path: examples/cpptest }, - { rom-name: ctest, ares-ci-compatible: true, rom-path: examples/ctest }, - { rom-name: dfsdemo, ares-ci-compatible: true, rom-path: examples/dfsdemo }, - { rom-name: eepromfstest_16k, ares-ci-compatible: true, rom-path: examples/eepromfstest }, - { rom-name: eepromfstest_4k, ares-ci-compatible: true, rom-path: examples/eepromfstest }, - { rom-name: mixertest, ares-ci-compatible: true, rom-path: examples/mixertest }, - { rom-name: mptest, ares-ci-compatible: true, rom-path: examples/mptest }, - { rom-name: mputest, ares-ci-compatible: true, rom-path: examples/mputest }, - { rom-name: rspqdemo, ares-ci-compatible: true, rom-path: examples/rspqdemo }, - { rom-name: spritemap, ares-ci-compatible: true, rom-path: examples/spritemap }, - { rom-name: test, ares-ci-compatible: true, rom-path: examples/test }, - { rom-name: timers, ares-ci-compatible: true, rom-path: examples/timers }, - { rom-name: ucodetest, ares-ci-compatible: true, rom-path: examples/ucodetest }, - { rom-name: vrutest, ares-ci-compatible: true, rom-path: examples/vrutest }, - { rom-name: vtest, ares-ci-compatible: true, rom-path: examples/vtest } - ] - - env: - Delay_Time_Seconds: 15 - Enable_Screenshot: 'no' # false by default - - steps: - - - name: Download ROM artifact - id: download-rom-artifact - uses: actions/download-artifact@v3 - with: - name: roms - path: ${{ runner.temp }}/roms - continue-on-error: true - - # - name: Show ROM Paths # helps with creating new matrix paths - # run: | - # cd ${{ runner.temp }}/roms - # ls -R - # continue-on-error: true - - - name: Install ares emulator - if: ${{ matrix.ares-ci-compatible }} - run: | - Write-Output "Installing ares emulator!" - curl -LO https://github.com/ares-emulator/ares/releases/download/nightly/ares-windows-msvc-x64.zip - unzip ares-windows-msvc-x64.zip - rd -r ./ares-windows-msvc-x64.zip - continue-on-error: true - - - - name: Setup Ares - if: ${{ matrix.ares-ci-compatible }} - run: | - # NOTE: we need to change some of the settings that cannot be setup through the CLI. - # to make it compatible with the CI host. - # FIXME: ares should have a parameter to tell it that it is running on a github host - - Write-Output "Step 1 - Run a valid ROM so the settings are actually generated." - Write-Output " ROM will fail to run due to missing graphics acceleration..." - . ares-nightly/ares ${{ runner.temp }}/roms/${{ matrix.rom-path }}/${{ matrix.rom-name }}.z64 - - Write-Output "Step 2 - Sleep a little to make sure settings.bml is generated." - # 5 seconds delay seems to run reliably. - Start-Sleep -Seconds 5 - - Write-Output "Step 3 - adjust the settings to disable graphics acceleration and audio" - Write-Verbose "Disable graphics acceleration" - ((Get-Content -path ares-nightly/settings.bml -Raw) -replace 'EnableVulkan: true','EnableVulkan: false') | Set-Content -Path ares-nightly/settings.bml - Write-Verbose "Disable video interface processing" - ((Get-Content -path ares-nightly/settings.bml -Raw) -replace 'DisableVideoInterfaceProcessing: false','DisableVideoInterfaceProcessing: true') | Set-Content -Path ares-nightly/settings.bml - Write-Verbose "Change to a compatible graphics option" - # https://github.com/ares-emulator/ares/blob/b1d216b8affbfb811a681dca1bd603d3369624fc/ruby/video/video.cpp#L154 - ((Get-Content -path ares-nightly/settings.bml -Raw) -replace 'Driver: OpenGL 3.2','Driver: Direct3D 9.0') | Set-Content -Path ares-nightly/settings.bml - Write-Verbose "Disable audio" - # https://github.com/ares-emulator/ares/blob/3ca1f9ebb4ae3f472f7fba661746058f84126536/ruby/audio/audio.cpp#L268 - ((Get-Content -path ares-nightly/settings.bml -Raw) -replace 'Driver: WASAPI','Driver: None') | Set-Content -Path ares-nightly/settings.bml - - - name: Run ROM in Ares for logs - if: ${{ matrix.ares-ci-compatible }} - run: | - Start-Process -FilePath "ares-nightly/ares" -ArgumentList "${{ runner.temp }}/roms/${{ matrix.rom-path }}/${{ matrix.rom-name }}.z64" -RedirectStandardOutput ${{ matrix.rom-name }}-${{ env.Delay_Time_Seconds }}s-ares-output-log.txt - - Start-Sleep -Seconds ${{ env.Delay_Time_Seconds }} - - # the emulator is still running! we need to stop it. - Stop-Process -Name "ares" - # Add a delay to make sure that the process has been closed. - Start-Sleep -Seconds 1 - - if ((get-item "${{ matrix.rom-name }}-${{ env.Delay_Time_Seconds }}s-ares-output-log.txt").Length -gt 0) - { - Write-Warning "Log File is not empty!" - Write-Verbose "Or match it against a golden copy to see if it is expected." - Write-Output "Enable_Screenshot=yes" | Out-File -FilePath $Env:GITHUB_ENV -Encoding utf8 -Append - - # appending to CI summary info! - Write-Output ":warning: You might want to check: ${{ matrix.rom-name }}.z64 for issues!" | Out-File -FilePath $Env:GITHUB_STEP_SUMMARY -Encoding utf8 -Append - } - else - { - Write-Output "File is empty, trying to remove it." - remove-item -fo ${{ matrix.rom-name }}-${{ env.Delay_Time_Seconds }}s-ares-output-log.txt -ErrorAction Ignore - } - continue-on-error: true - - - name: Upload files - if: ${{ matrix.ares-ci-compatible }} - uses: actions/upload-artifact@v3 - with: - name: ${{ matrix.rom-name }}-${{ env.Delay_Time_Seconds }}s-ares-output-log.txt - if-no-files-found: ignore - path: | - ${{ matrix.rom-name }}-${{ env.Delay_Time_Seconds }}s-ares-output-log.txt - continue-on-error: true - - - - name: Run ROM in Ares for screenshot - if: ${{ env.Enable_Screenshot == 'yes' }} # FIXME: should also take into account ${{ matrix.ares-ci-compatible }} - run: | - Start-Process -FilePath "ares-nightly/ares" -ArgumentList "${{ runner.temp }}/roms/${{ matrix.rom-path }}/${{ matrix.rom-name }}.z64 --fullscreen" - Start-Sleep -Seconds ${{ env.Delay_Time_Seconds }} - continue-on-error: true - - - name: Take screenshot - if: ${{ env.Enable_Screenshot == 'yes' }} # FIXME: should also take into account ${{ matrix.ares-ci-compatible }} - uses: networkfusion/desktop-screenshot-action@0.2 - with: - file-name: '${{ matrix.rom-name }}-emu-screenshot_${{ env.Delay_Time_Seconds }}s.jpg' - - - name: Cleanup ares process - if: ${{ env.Enable_Screenshot == 'yes' }} # FIXME: should also take into account ${{ matrix.ares-ci-compatible }} - run: | - Stop-Process -Name "ares" - continue-on-error: true From 9ad2bd298f651543af5053be2ca6f32feaad0e27 Mon Sep 17 00:00:00 2001 From: Robin Jones Date: Sun, 30 Jul 2023 14:26:15 +0100 Subject: [PATCH 07/11] Update ff.c Apply patch 2 --- src/fatfs/ff.c | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/src/fatfs/ff.c b/src/fatfs/ff.c index 07412bb273..492f48b7f7 100644 --- a/src/fatfs/ff.c +++ b/src/fatfs/ff.c @@ -1,5 +1,5 @@ /*----------------------------------------------------------------------------/ -/ FatFs - Generic FAT Filesystem Module R0.15 w/patch1 / +/ FatFs - Generic FAT Filesystem Module R0.15 w/patch2 / /-----------------------------------------------------------------------------/ / / Copyright (C) 2022, ChaN, all right reserved. @@ -468,10 +468,11 @@ static WORD Fsid; /* Filesystem mount ID */ static BYTE CurrVol; /* Current drive set by f_chdrive() */ #endif -#if FF_FS_LOCK != 0 +#if FF_FS_LOCK static FILESEM Files[FF_FS_LOCK]; /* Open object lock semaphores */ #if FF_FS_REENTRANT -static BYTE SysLock; /* System lock flag (0:no mutex, 1:unlocked, 2:locked) */ +static volatile BYTE SysLock; /* System lock flag to protect Files[] (0:no mutex, 1:unlocked, 2:locked) */ +static volatile BYTE SysLockVolume; /* Volume id who is locking Files[] */ #endif #endif @@ -905,6 +906,7 @@ static int lock_volume ( /* 1:Ok, 0:timeout */ if (rv && syslock) { /* System lock reqiered? */ rv = ff_mutex_take(FF_VOLUMES); /* Lock the system */ if (rv) { + SysLockVolume = fs->ldrv; SysLock = 2; /* System lock succeeded */ } else { ff_mutex_give(fs->ldrv); /* Failed system lock */ @@ -924,7 +926,7 @@ static void unlock_volume ( { if (fs && res != FR_NOT_ENABLED && res != FR_INVALID_DRIVE && res != FR_TIMEOUT) { #if FF_FS_LOCK - if (SysLock == 2) { /* Is the system locked? */ + if (SysLock == 2 && SysLockVolume == fs->ldrv) { /* Unlock system if it has been locked by this task */ SysLock = 1; ff_mutex_give(FF_VOLUMES); } From f8bc9babc4ed9b18bd7ed8426a8478726eea7d4d Mon Sep 17 00:00:00 2001 From: Robin Jones Date: Sun, 30 Jul 2023 14:52:23 +0100 Subject: [PATCH 08/11] Update ffconf.h Re-add #ifndef FF_USE_STRFUNC --- src/fatfs/ffconf.h | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/fatfs/ffconf.h b/src/fatfs/ffconf.h index 8e02e5b067..1a930c2bbf 100644 --- a/src/fatfs/ffconf.h +++ b/src/fatfs/ffconf.h @@ -59,7 +59,10 @@ /* This option switches f_forward() function. (0:Disable or 1:Enable) */ +// FIXME: remove this, do not merge to stable without further discussion +#ifndef FF_USE_STRFUNC #define FF_USE_STRFUNC 0 +#endif #define FF_PRINT_LLI 1 #define FF_PRINT_FLOAT 1 #define FF_STRF_ENCODE 3 From a46a1d4caca4a250f3ede6412949b17476b90a2e Mon Sep 17 00:00:00 2001 From: Robin Jones Date: Tue, 15 Aug 2023 20:34:00 +0100 Subject: [PATCH 09/11] Enable FF_USE_CHMOD Improve readme to include patch version --- src/fatfs/00readme.txt | 2 +- src/fatfs/ff.h | 2 +- src/fatfs/ffconf.h | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/fatfs/00readme.txt b/src/fatfs/00readme.txt index 39f6c8ce72..8f91b675b2 100644 --- a/src/fatfs/00readme.txt +++ b/src/fatfs/00readme.txt @@ -1,4 +1,4 @@ -FatFs Module Source Files R0.15 +FatFs Module Source Files R0.15 w/patch2 FILES diff --git a/src/fatfs/ff.h b/src/fatfs/ff.h index d88febc12d..7030a32c7e 100644 --- a/src/fatfs/ff.h +++ b/src/fatfs/ff.h @@ -1,5 +1,5 @@ /*----------------------------------------------------------------------------/ -/ FatFs - Generic FAT Filesystem module R0.15 / +/ FatFs - Generic FAT Filesystem module R0.15 w/patch2 / /-----------------------------------------------------------------------------/ / / Copyright (C) 2022, ChaN, all right reserved. diff --git a/src/fatfs/ffconf.h b/src/fatfs/ffconf.h index 1a930c2bbf..07ab13ed72 100644 --- a/src/fatfs/ffconf.h +++ b/src/fatfs/ffconf.h @@ -45,7 +45,7 @@ /* This option switches f_expand function. (0:Disable or 1:Enable) */ -#define FF_USE_CHMOD 0 +#define FF_USE_CHMOD 1 /* This option switches attribute manipulation functions, f_chmod() and f_utime(). / (0:Disable or 1:Enable) Also FF_FS_READONLY needs to be 0 to enable this option. */ From 1732edf8765a8d19babedd6979d9359b248760a2 Mon Sep 17 00:00:00 2001 From: Robin Jones Date: Mon, 4 Sep 2023 16:31:41 +0100 Subject: [PATCH 10/11] Remove ifdef It was added for a specific circumstance that is no longer required. --- src/fatfs/ffconf.h | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/fatfs/ffconf.h b/src/fatfs/ffconf.h index 07ab13ed72..032249f472 100644 --- a/src/fatfs/ffconf.h +++ b/src/fatfs/ffconf.h @@ -59,10 +59,7 @@ /* This option switches f_forward() function. (0:Disable or 1:Enable) */ -// FIXME: remove this, do not merge to stable without further discussion -#ifndef FF_USE_STRFUNC #define FF_USE_STRFUNC 0 -#endif #define FF_PRINT_LLI 1 #define FF_PRINT_FLOAT 1 #define FF_STRF_ENCODE 3 From a8203553d17b1818318c84aa8d737248a4b26d82 Mon Sep 17 00:00:00 2001 From: Robin Jones Date: Mon, 4 Sep 2023 16:36:17 +0100 Subject: [PATCH 11/11] Apply patch 3 --- src/fatfs/ff.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/fatfs/ff.c b/src/fatfs/ff.c index 492f48b7f7..5cf83ca764 100644 --- a/src/fatfs/ff.c +++ b/src/fatfs/ff.c @@ -1,5 +1,5 @@ /*----------------------------------------------------------------------------/ -/ FatFs - Generic FAT Filesystem Module R0.15 w/patch2 / +/ FatFs - Generic FAT Filesystem Module R0.15 w/patch3 / /-----------------------------------------------------------------------------/ / / Copyright (C) 2022, ChaN, all right reserved. @@ -5462,6 +5462,9 @@ FRESULT f_setlabel ( /* Get logical drive */ res = mount_volume(&label, &fs, FA_WRITE); if (res != FR_OK) LEAVE_FF(fs, res); +#if FF_STR_VOLUME_ID == 2 + for ( ; *label == '/'; label++) ; /* Snip the separators off */ +#endif #if FF_FS_EXFAT if (fs->fs_type == FS_EXFAT) { /* On the exFAT volume */