Index: kernel/generic/src/proc/thread.c
===================================================================
--- kernel/generic/src/proc/thread.c	(revision c98e6ee244a8e271a395a052069c23bca4f8b538)
+++ kernel/generic/src/proc/thread.c	(revision 4e5aa028b3e3564dbecb289e17ebf39d83e2161e)
@@ -181,4 +181,8 @@
 	}
 
+#ifdef CONFIG_UDEBUG
+	mutex_initialize(&t->udebug.lock, MUTEX_PASSIVE);
+#endif
+
 	return 0;
 }
@@ -348,4 +352,9 @@
 	t->threads_tree_node.key = (uintptr_t) t;
 
+#ifdef CONFIG_UDEBUG
+	/* Init debugging stuff */
+	udebug_thread_initialize(&t->udebug);
+#endif
+
 	/* might depend on previous initialization */
 	thread_create_arch(t);	
@@ -410,10 +419,15 @@
 
 	/*
-	 * Attach to the current task.
+	 * Attach to the specified task.
 	 */
 	ipl = interrupts_disable();
 	spinlock_lock(&task->lock);
+
 	atomic_inc(&task->refcount);
-	atomic_inc(&task->lifecount);
+
+	/* Must not count kbox thread into lifecount */
+	if (t->flags & THREAD_FLAG_USPACE)
+		atomic_inc(&task->lifecount);
+
 	list_append(&t->th_link, &task->th_head);
 	spinlock_unlock(&task->lock);
@@ -438,12 +452,17 @@
 	ipl_t ipl;
 
-	if (atomic_predec(&TASK->lifecount) == 0) {
-		/*
-		 * We are the last thread in the task that still has not exited.
-		 * With the exception of the moment the task was created, new
-		 * threads can only be created by threads of the same task.
-		 * We are safe to perform cleanup.
-		 */
-		if (THREAD->flags & THREAD_FLAG_USPACE) {
+	if (THREAD->flags & THREAD_FLAG_USPACE) {
+#ifdef CONFIG_UDEBUG
+		/* Generate udebug THREAD_E event */
+		udebug_thread_e_event();
+#endif
+		if (atomic_predec(&TASK->lifecount) == 0) {
+			/*
+			 * We are the last userspace thread in the task that
+			 * still has not exited. With the exception of the
+			 * moment the task was created, new userspace threads
+			 * can only be created by threads of the same task.
+			 * We are safe to perform cleanup.
+			 */
 			ipc_cleanup();
 			futex_cleanup();
@@ -742,4 +761,9 @@
 		thread_ready(t);
 
+#ifdef CONFIG_UDEBUG
+		/* Generate udebug THREAD_B event */
+		udebug_thread_b_event(t);
+#endif
+
 		return 0;
 	} else
