Friday, 17 March 2023

Weird write file issue on a drive with no space left on it

We've found (different devices, different Android versions) that Android returns no errors when we're writing on an SD card with no space left on it!

I.e. I'm able to successfully create a new file and file write function returns OK status also, but it does not write anything actually. The real size of such file on disk stays 0 bytes.

We're using native C++ APIs.

I've tried to reproduce this on a new project on my Android 11 phone and yes - the issue is still there.

I did the following steps:

  1. Create a new Native C++ project using Android Studio.
  2. In its C++ code add test function and call it.
  3. Launch project using Android Studio - yes, we are able to see the same behavior.

The test code I was using:

#include <android/log.h>

bool test()
{
    std::srand(std::time(0));

    auto path = "/storage/150E-2D07/Download/test_1";

    FILE *f2 = nullptr;
    bool ok = true;

    std::int64_t bytesWritten = 0;

#define checkok if (!ok) goto _error

    ok = nullptr != (f2 = fopen(path, "wb"));
    checkok;
    ok = ferror(f2) == 0;
    checkok;

    for (int i = 0; ; ++i)
    {
        char a[16*1024];
        for (int i = 0; i < sizeof(a); ++i)
            a[i] = std::rand()%256;

        ok = sizeof(a) == fwrite(a, 1, sizeof(a), f2);
        checkok;

        ok = ferror(f2) == 0;
        checkok;

        ok = !fflush(f2);
        checkok;

        ok = ferror(f2) == 0;
        checkok;

        bytesWritten += sizeof(a);
        if (!(i % 1000))
            __android_log_print(ANDROID_LOG_VERBOSE, "TEST", "writing.. bytes written: %f", bytesWritten/1024.0/1024.0);
    }

    return true;

    _error:
    if (f2)
        fclose(f2);

    return false;
}

I've also noticed that when there is no space left, fwrite function works much faster (we get speeds which SD card can't afford).

Addition #1. I've created Android 13 virtual device with 500MB emulated SD card in it. Launched my test app in it. It wrote 1.4GB of data, then I terminated it. I copied this file to my computer and found that 1st 500MB are filled with actual data and the remained contents are just zeroes. Sounds like a total bug of Android OS to me. I'm wondering how is it possible that such a critical bug still exists and it seems like no one cares about it.



from Weird write file issue on a drive with no space left on it

No comments:

Post a Comment