Skip to content

Commit 700b7e6

Browse files
authored
[macOS] fix potential leaks in error paths (#2707)
...affecting Process memory_full_info() and threads()
1 parent 7cc7923 commit 700b7e6

2 files changed

Lines changed: 18 additions & 0 deletions

File tree

HISTORY.rst

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@ XXXX-XX
1818

1919
- 2701_, [macOS]: fix compilation error on macOS < 10.7. (patch by Sergey
2020
Fedorov)
21+
- 2707_, [macOS]: fix potential memory leaks in error paths of
22+
`Process.memory_full_info()` and `Process.threads()`.
2123

2224
7.2.1
2325
=====

psutil/arch/osx/proc.c

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -291,6 +291,7 @@ psutil_proc_memory_uss(PyObject *self, PyObject *args) {
291291
if (psutil_sysctlbyname("sysctl.proc_cputype", &cpu_type, sizeof(cpu_type))
292292
!= 0)
293293
{
294+
mach_port_deallocate(mach_task_self(), task);
294295
return NULL;
295296
}
296297

@@ -299,6 +300,7 @@ psutil_proc_memory_uss(PyObject *self, PyObject *args) {
299300
for (addr = MACH_VM_MIN_ADDRESS;; addr += size) {
300301
prev_addr = addr;
301302
info_count = VM_REGION_TOP_INFO_COUNT; // reset before each call
303+
object_name = MACH_PORT_NULL;
302304

303305
kr = mach_vm_region(
304306
task,
@@ -309,6 +311,12 @@ psutil_proc_memory_uss(PyObject *self, PyObject *args) {
309311
&info_count,
310312
&object_name
311313
);
314+
315+
if (object_name != MACH_PORT_NULL) {
316+
mach_port_deallocate(mach_task_self(), object_name);
317+
object_name = MACH_PORT_NULL;
318+
}
319+
312320
if (kr == KERN_INVALID_ADDRESS) {
313321
// Done iterating VM regions.
314322
break;
@@ -439,15 +447,20 @@ psutil_proc_threads(PyObject *self, PyObject *args) {
439447
Py_CLEAR(py_tuple);
440448
}
441449

450+
// deallocate thread_list if it was allocated
442451
if (thread_list != NULL) {
443452
vm_deallocate(
444453
mach_task_self(),
445454
(vm_address_t)thread_list,
446455
thread_count * sizeof(thread_act_t)
447456
);
457+
thread_list = NULL;
448458
}
459+
460+
// deallocate the task port
449461
if (task != MACH_PORT_NULL) {
450462
mach_port_deallocate(mach_task_self(), task);
463+
task = MACH_PORT_NULL;
451464
}
452465

453466
return py_retlist;
@@ -462,9 +475,12 @@ psutil_proc_threads(PyObject *self, PyObject *args) {
462475
(vm_address_t)thread_list,
463476
thread_count * sizeof(thread_act_t)
464477
);
478+
thread_list = NULL;
465479
}
480+
466481
if (task != MACH_PORT_NULL) {
467482
mach_port_deallocate(mach_task_self(), task);
483+
task = MACH_PORT_NULL;
468484
}
469485

470486
return NULL;

0 commit comments

Comments
 (0)