SQLite Forum

Database disk image is malformed
I encountered a similar problem in HHVM.

The root cause of the corruption was that unrelated code in HHVM was sometimes writing to a closed file descriptor. When you write to a closed file descriptor, you’re playing Russian Roulette with the files you currently have open, and there’s a chance you’ll write unspecified data to an unspecified place in your SQLite DB, instead of writing to the file you wanted to write to.

I was able to debug this issue by writing a C program that ran `PRAGMA integrity_check` on my DB. I then compiled it with all optimizations off, and stepped through it with GDB. GDB showed me that an int had a value of 115, which was impossible if only SQLite were writing to the DB file. Reading this corrupted area as a sequence of bytes, I saw that someone had written the C string `"stop"` to the DB, causing the corruption. I then searched for `"stop"` to find the code that caused the issue. [Here was my fix](https://github.com/facebook/hhvm/commit/46721ee0ad8d7cfc94f36e20781a0e4215684ed8#diff-e30509bce63de23ea7d45a2091be9c4039bf4defc03c70b1576e48114ccf8eae), which didn’t touch SQLite code at all and instead ensured that, in this code, writes to a file descriptor only happen on the thread that will close the file descriptor.

I haven’t done a public-facing writeup on this, but [this public-facing writeup shows how to solve a harder version of the same bug.](https://engineering.fb.com/2014/08/12/ios/debugging-file-corruption-on-ios/)