From cb8d888c42aa9504db2df686f0e963b99079e287 Mon Sep 17 00:00:00 2001
From: Sujatha Sivakumar <sujatha.sivakumar@mariadb.com>
Date: Wed, 24 Apr 2019 11:40:52 +0530
Subject: [PATCH] MDEV-17260: Memory leaks in mysqlbinlog

Problem:
========
The mysqlbinlog tool is leaking memory, causing failures in various tests when
compiling and testing with AddressSanitizer or LeakSanitizer like this:

cmake -DCMAKE_BUILD_TYPE=Debug -DWITH_ASAN:BOOL=ON /path/to/source
make -j$(nproc)
cd mysql-test
ASAN_OPTIONS=abort_on_error=1 ./mtr --parallel=auto rpl.rpl_row_mysqlbinlog

CURRENT_TEST: rpl.rpl_row_mysqlbinlog

Direct leak of 112 byte(s) in 1 object(s) allocated from:
#0 0x4eff87 in __interceptor_malloc (/dev/shm/5.5/client/mysqlbinlog+0x4eff87)
#1 0x60eaab in my_malloc /mariadb/5.5/mysys/my_malloc.c:41:10
#2 0x5300dd in Log_event::read_log_event(char const*, unsigned int, char const**,
   Format_description_log_event const*, char) /mariadb/5.5/sql/log_event.cc:1568:
#3 0x564a9c in dump_remote_log_entries(st_print_event_info*, char const*)
/mariadb/5.5/client/mysqlbinlog.cc:1978:17

Analysis:
========
'mysqlbinlog' tool is being used to read binary log events from a remote server.
While reading binary log, if a fake rotate event is found following actions are
taken.

If 'to-last-log' option is specified, then fake rotate event is processed.
In the absence of 'to-last-log' skip the fake rotate event.

In this skipped case the fake rotate event object is not getting cleaned up
resulting in memory leak.

Fix:
===
Cleanup the fake rotate event.

This issues is already fixed in MariaDB 10.0.23 and higher versions as part of
commit c3018b0ff4fb02c029787d03867adf0530607bab
---
 client/mysqlbinlog.cc | 2 ++
 1 file changed, 2 insertions(+)

diff --git a/client/mysqlbinlog.cc b/client/mysqlbinlog.cc
index 250dc609891..1a11e3e697b 100644
--- a/client/mysqlbinlog.cc
+++ b/client/mysqlbinlog.cc
@@ -2020,6 +2020,7 @@ static Exit_status dump_remote_log_entries(PRINT_EVENT_INFO *print_event_info,
             if ((rev->ident_len != logname_len) ||
                 memcmp(rev->new_log_ident, logname, logname_len))
             {
+              delete ev;
               DBUG_RETURN(OK_CONTINUE);
             }
             /*
@@ -2028,6 +2029,7 @@ static Exit_status dump_remote_log_entries(PRINT_EVENT_INFO *print_event_info,
               log. If we are running with to_last_remote_log, we print it,
               because it serves as a useful marker between binlogs then.
             */
+            delete ev;
             continue;
           }
           len= 1; // fake Rotate, so don't increment old_off