jordansissel / xdotool

fake keyboard/mouse input, window management, and more
Other
3.18k stars 316 forks source link

`xdo_get_focused_window_sane` leaks memory #202

Open ghost opened 6 years ago

ghost commented 6 years ago

Tested on Ubuntu 16.04, gcc version 5.4.0., libxdo version 3.20150503.1.

xdo_get_focused_window_sane, xdo_get_active_window and xdo_get_window_name calls leak memory. Seems to be down to calling libX11's XGetWindowProperty. The leak scales with the number of function calls, so repeatedly checking the focused window eats up a growing amount of memory. Related to #189 ?

#include <stdio.h>
#include <unistd.h>
#include <xdo.h>

int main() {

  Window window;
  unsigned char *name;
  int name_len;
  int name_type;
  xdo_t *xdo = xdo_new(":0");

  for (int i=1; i<=10000; i++) {
    xdo_get_focused_window_sane(xdo, &window);
    xdo_get_window_name(xdo, window, &name, &name_len, &name_type);
    printf("%s\n", name);
    usleep(1000);
  }

  xdo_free(xdo);
  return 0;
}
=================================================================
==9208==ERROR: LeakSanitizer: detected memory leaks

Direct leak of 373050 byte(s) in 10000 object(s) allocated from:
    #0 0x7fe25381b602 in malloc (/usr/lib/x86_64-linux-gnu/libasan.so.2+0x98602)
    #1 0x7fe251f0ecd8 in XGetWindowProperty (/usr/lib/x86_64-linux-gnu/libX11.so.6+0x23cd8)

Direct leak of 170000 byte(s) in 10000 object(s) allocated from:
    #0 0x7fe25381b602 in malloc (/usr/lib/x86_64-linux-gnu/libasan.so.2+0x98602)
    #1 0x7fe251f0ec18 in XGetWindowProperty (/usr/lib/x86_64-linux-gnu/libX11.so.6+0x23c18)

Direct leak of 72 byte(s) in 1 object(s) allocated from:
    #0 0x7fe25381b79a in __interceptor_calloc (/usr/lib/x86_64-linux-gnu/libasan.so.2+0x9879a)
    #1 0x7fe251f788a0 in XkbGetMap (/usr/lib/x86_64-linux-gnu/libX11.so.6+0x8d8a0)

[... a few indirect leaks ...]

SUMMARY: AddressSanitizer: 555158 byte(s) leaked in 20035 allocation(s).
alexzk1 commented 6 years ago

shouldn't you clear memory returned from call ? (i.e. name array)

dpellegr commented 3 years ago

The first leak is your fault, see @alexzk1 comment.

The second is actually a problem in xdolib, but fixing it is easy, see: https://github.com/dpellegr/xdotool/commit/b88a8802d78a0225daf7f5e5c41cbd8769746af7

The third one is discussed and fixed here: https://github.com/jordansissel/xdotool/issues/189

It would be nice to have them pulled in a new release... note that in my fork I have those and a few other pulled in.