#1 Today 17:32:16

slapshot
Member
Registered: 2020-01-21
Posts: 18

TSqlDatabase.DBOpen: SQLite handle leak on failed open_v2 retry under

Hi everybody,

While developing and testing a multithreaded native computation engine using FPC and mORMot2, I came across a reproducible memory leak in `TSqlDatabase.DBOpen` under Linux.

We are currently testing concurrent read-only SQLite connections against a WAL database, with an independent Python writer process.

During our negative tests, opening a nonexistent database in read-only mode raised the expected `ESqlite3Exception`, but HeapTrc reported a memory leak and, in some cases, an access violation during application shutdown.

I isolated the issue from our application and reproduced it on two different Linux machines.

**Test environment**

- FPC 3.2.5
- mORMot2 2.4, commit `ead6470c0c4abba78c11ca8bc157e5cfee804972`
- SQLite 3.51.2, statically linked
- Linux x86_64
- Debian 13, kernel 6.12.118
- Arch Linux / Omarchy, kernel 7.2.15
- Compiler options: `-O1 -g -gl -gh`

**Minimal reproduction**

Compile the following simplified reproducer with HeapTrc enabled and make sure that the database path does not exist.

program sqlite_open_failure;

{$mode delphi}{$H+}

uses
  cthreads,
  SysUtils,
  mormot.core.base,
  mormot.db.raw.sqlite3,
  mormot.db.raw.sqlite3.static;

var
  DB: TSqlDatabase;

begin
  DB := nil;
  try
    try
      DB := TSqlDatabase.Create(
        ParamStr(1),
        '',
        SQLITE_OPEN_READONLY or SQLITE_OPEN_URI);
    except
      on E: ESqlite3Exception do
        WriteLn(E.ClassName, ': ', E.Message);
    end;
  finally
    DB.Free;
  end;

  WriteLn('END_MAIN');
end.

Pass a URI pointing to a nonexistent database, for example:

file:///tmp/nonexistent-test.sqlite3?mode=ro&vfs=unix

The expected SQLite exception is correctly raised and handled:

ESqlite3Exception:
Error SQLITE_CANTOPEN (14) [DBOpen]
using 3.51.2 with aDB=nil

However, our diagnostic program reports:

7 unfreed memory blocks : 1340

When executed in the main thread, an access violation also occurs during finalization, resulting in exit code 217.

Using addr2line, the address of the access violation resolves to:

HEAPTRC_$$_TRACEFREEMEMSIZE$POINTER$QWORD$$QWORD
heaptrc.pp:?

**Possible cause**

Looking at `mormot.db.raw.sqlite3.pas`, inside `TSqlDatabase.DBOpen`, I noticed the following POSIX-specific code:

result := sqlite3.open_v2(pointer(u), fDB,
  fOpenV2Flags, 'unix-excl');

if result <> SQLITE_OK then
  result := sqlite3.open_v2(pointer(u), fDB,
    fOpenV2Flags, nil);

According to the SQLite documentation, sqlite3_open_v2() can return a non-null database handle even when opening the database fails. That handle still needs to be released.

https://sqlite.org/c3ref/open.html

In this case, the second call appears to overwrite the handle returned by the first unsuccessful attempt.

I also tested both calls directly through the raw SQLite API. Both returned SQLITE_CANTOPEN (14), with a non-null database handle. Explicitly closing each handle resulted in zero memory leaks.

**Proposed fix**

I tested the following small modification in a temporary copy of the mORMot2 sources:

result := sqlite3.open_v2(pointer(u), fDB,
  fOpenV2Flags, 'unix-excl');

if result <> SQLITE_OK then
begin
  if fDB <> 0 then
    sqlite3.close(fDB);

  fDB := 0;

  result := sqlite3.open_v2(pointer(u), fDB,
    fOpenV2Flags, nil);
end;

**Experimental results**

I ran the original and modified framework on both machines, testing the main thread and an independent RTL TThread worker.

The results were identical on both systems:

Implementation     Context  Exit  Leaked blocks
------------------------------------------------
Raw SQLite API     Main       0   0
Raw SQLite API     Worker     0   0
Original mORMot2   Main     217   7 (1340 bytes)
Original mORMot2   Worker     0   7 (1340 bytes)
Patched mORMot2    Main       0   0
Patched mORMot2    Worker     0   0

With the proposed modification, all tests completed successfully, with zero unfreed memory blocks and no access violations.

The original framework checkout was left untouched. The only source modification in the experimental build was the cleanup of the first failed SQLite handle before retrying.

I have not investigated the internal HeapTrc access violation further, but it disappeared after applying this modification.

Could you please confirm whether this is the correct way to handle the failed open_v2 call?

I would also suggest adding a regression test for unsuccessful read-only database openings.

By the way, I have been working extensively with mORMot2 over the past few weeks, particularly its threading facilities, SQLite integration and native computation capabilities. The performance and flexibility of the framework have been impressive.

Thank you for your work!

Offline

Board footer

Powered by FluxBB