From 1f68d6775da5c3abfb36531a362c02d227bab282 Mon Sep 17 00:00:00 2001
From: Nadav Har'El <nyh@cloudius-systems.com>
Date: Mon, 8 Apr 2013 11:17:17 +0300
Subject: [PATCH] Free TCB (and thread-local storage) area on thread
 destruction.

We forgot to free the TCB allocated buffer on thread destruction, causing
a leak of around 1000 bytes per thread creation. We still have another
leak (exactly one page per thread object creation) that I'm trying to find :(
---
 arch/x64/arch-switch.hh | 5 +++++
 core/sched.cc           | 1 +
 include/sched.hh        | 1 +
 3 files changed, 7 insertions(+)

diff --git a/arch/x64/arch-switch.hh b/arch/x64/arch-switch.hh
index bfe5c7bc6..c3a1b6b42 100644
--- a/arch/x64/arch-switch.hh
+++ b/arch/x64/arch-switch.hh
@@ -93,6 +93,11 @@ void thread::setup_tcb()
     _tcb->tls_base = p;
 }
 
+void thread::free_tcb()
+{
+    free(_tcb->tls_base);
+}
+
 void thread_main_c(thread* t)
 {
     s_current = t;
diff --git a/core/sched.cc b/core/sched.cc
index 910517c34..29bc3a685 100644
--- a/core/sched.cc
+++ b/core/sched.cc
@@ -276,6 +276,7 @@ thread::~thread()
     if (_attr.stack.deleter) {
         _attr.stack.deleter(_attr.stack.begin);
     }
+    free_tcb();
 }
 
 void thread::start()
diff --git a/include/sched.hh b/include/sched.hh
index 0b67eeba1..445f473ed 100644
--- a/include/sched.hh
+++ b/include/sched.hh
@@ -175,6 +175,7 @@ private:
     void stop_wait();
     void init_stack();
     void setup_tcb();
+    void free_tcb();
     void complete();
     void suspend_timers();
     void resume_timers();
-- 
GitLab