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:49:48 +0000 (08:49 +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 aa76d5c56a81176160e512165f2164a3aaa65ab5..2473c969b8028035197e30d4d6cce52b998750f8 100644 (file)
@@ -965,7 +965,8 @@ StartupPacketCopy(StartupPacket *sp)
 static POOL_CONNECTION_POOL * connect_backend(StartupPacket *sp, POOL_CONNECTION * frontend)
 {
        POOL_CONNECTION_POOL *backend;
-       StartupPacket *topmem_sp;
+       StartupPacket *volatile topmem_sp = NULL;
+       volatile bool   topmem_sp_set = false;
        int                     i;
 
        /* connect to the backend */
@@ -1005,6 +1006,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));
@@ -1028,10 +1030,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;
 }