Skip to content

Commit

Permalink
Fix error handling when thread cannot be created
Browse files Browse the repository at this point in the history
Update the Thread::start function to gracefully handle the failed
creation of a thread when there are no TCBs left. This patch does
the following:
1. Set memory handles to NULL after free to prevent double free
2. Post to the release semaphore so anything that tries to join this
    thread will join immediately
3. Remove dead return path since the new operator should never
    return NULL (it should trap instead)
  • Loading branch information
c1728p9 committed Sep 13, 2016
1 parent 9e4a479 commit 8447843
Showing 1 changed file with 7 additions and 5 deletions.
12 changes: 7 additions & 5 deletions rtos/rtos/Thread.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -83,10 +83,7 @@ osStatus Thread::start(Callback<void()> task) {
_thread_def.pthread = Thread::_thunk;
if (_thread_def.stack_pointer == NULL) {
_thread_def.stack_pointer = new uint32_t[_thread_def.stacksize/sizeof(uint32_t)];
if (_thread_def.stack_pointer == NULL) {
_mutex.unlock();
return osErrorNoMemory;
}
MBED_ASSERT(_thread_def.stack_pointer != NULL);
}

//Fill the stack with a magic word for maximum usage checking
Expand All @@ -97,8 +94,12 @@ osStatus Thread::start(Callback<void()> task) {
_task = task;
_tid = osThreadCreate(&_thread_def, this);
if (_tid == NULL) {
if (_dynamic_stack) delete[] (_thread_def.stack_pointer);
if (_dynamic_stack) {
delete[] (_thread_def.stack_pointer);
_thread_def.stack_pointer = (uint32_t*)NULL;
}
_mutex.unlock();
_join_sem.release();
return osErrorResource;
}

Expand Down Expand Up @@ -355,6 +356,7 @@ Thread::~Thread() {
#ifdef __MBED_CMSIS_RTOS_CM
if (_dynamic_stack) {
delete[] (_thread_def.stack_pointer);
_thread_def.stack_pointer = (uint32_t*)NULL;
}
#endif
}
Expand Down

0 comments on commit 8447843

Please sign in to comment.