Pages that are no longer in use are kept on the freelist, for SQLite to reuse before it makes the file longer. The database header gives the first trunk page at offset 52 and the number of free pages, trunks included, at offset 56.
Trunk pages
The header’s first free page is a trunk page. Each trunk lists free pages and points to the next trunk. Numbers are in the file’s byte order.
| Offset | Size | Type | Name | Description |
|---|---|---|---|---|
| 0 | 4 | u32 | next trunk | The next trunk page, or 0 on the last. |
| 4 | 4 | u32 | count | How many free page numbers follow, at most 254 (the struct FreelistInfo starts here). |
| 8 | 4 × count | u32[] | free pages | The numbers of the free pages this trunk lists. 8 + 254 × 4 = 1,024, so 254 fill the page. |
To find every free page:
- Start at the header’s first free page. If it is 0, the freelist is empty.
- Count the trunk itself, then read its count and that many page numbers.
- Go to the next trunk, and stop at 0.
- The pages found, trunks included, should equal the header’s free page count.
When a page is freed, SQLite adds it to the first trunk’s list if there is room. Otherwise the freed page becomes the new first trunk, with its contents cleared. Reusing a page takes one from the first trunk’s list (the one nearest the page wanted) or, when that list is empty, the trunk itself.
Trunk pages arrived with SQLite 2.4.0. The older freelist is below. SQLite 2.8 still reads such a chain, since each page then reads as a trunk with a count of 0.
The older freelist
SQLite 2.0 to 2.3 (the SQLite 2.0 and 2.1 layouts, and
format 1 files written by 2.2 and 2.3) keep free pages on a plain chain: each free
page’s first 4 bytes give the next free page, 0 on the last, and the rest of the page
is unused. The header’s first free page starts the chain, and every page on it counts
towards the free page count. FreelistInfo does not exist in these
releases.
A format 1 file can have either form, since SQLite 2.4 and 2.5 write trunk pages into any file they open. The explorer follows the chain, and uses it if it reaches the header’s free page count; otherwise it reads the first free page as a trunk.
Free pages
The pages a trunk lists are free pages, sometimes called leaves. Their contents mean nothing: they may still hold whatever the page held before it was freed.