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:37 +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 d91b011cfbf950b6c16ba7652d916519c4979d49..ca021febd5889987b466f14a66d4eaccc8100529 100644 (file)
@@ -916,8 +916,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();
@@ -954,6 +955,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));
@@ -967,10 +969,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;
 }