Fix memory leak while attempting to connect to backend.
authorTatsuo Ishii <ishii@sraoss.co.jp>
Tue, 24 Sep 2019 23:49:48 +0000 (08:49 +0900)
committerTatsuo Ishii <ishii@sraoss.co.jp>
Tue, 24 Sep 2019 23:59:19 +0000 (08:59 +0900)
If no backend is up and running, memory for copy of startup packet
will be lost. This was brought by commit cdb49d3b7. Per coverity.

src/protocol/child.c

index 59e1e7fd1f7ccb1f4d708bfb5311d17543857742..4da2914b00cc49ba6a00c8fd9e30e6772f511d82 100644 (file)
@@ -910,8 +910,9 @@ static StartupPacket *StartupPacketCopy(StartupPacket *sp)
 static POOL_CONNECTION_POOL *connect_backend(StartupPacket *sp, POOL_CONNECTION *frontend)
 {
        POOL_CONNECTION_POOL *backend;
-       StartupPacket *topmem_sp;
-       int i;
+       StartupPacket *volatile topmem_sp = NULL;
+       volatile bool   topmem_sp_set = false;
+       int                     i;
 
        /* connect to the backend */
        backend = pool_create_cp();
@@ -948,6 +949,7 @@ static POOL_CONNECTION_POOL *connect_backend(StartupPacket *sp, POOL_CONNECTION
                                 * save startup packet info
                                 */
                                CONNECTION_SLOT(backend, i)->sp = topmem_sp;
+                               topmem_sp_set = true;
 
                                /* send startup packet */
                                send_startup_packet(CONNECTION_SLOT(backend, i));
@@ -961,10 +963,17 @@ static POOL_CONNECTION_POOL *connect_backend(StartupPacket *sp, POOL_CONNECTION
        PG_CATCH();
        {
                pool_discard_cp(sp->user, sp->database, sp->major);
+               topmem_sp = NULL;
                PG_RE_THROW();
        }
        PG_END_TRY();
 
+       /* At this point, we need to free previously allocated memory for the
+        * startup packet if no backend is up.
+        */
+       if (!topmem_sp_set && topmem_sp != NULL)
+               pfree(topmem_sp);
+
        return backend;
 }