chore: migrate project into clean repository

This commit is contained in:
yuuux
2026-08-13 16:50:52 +08:00
commit d1d25a09e7
27405 changed files with 9422808 additions and 0 deletions

View File

@@ -0,0 +1,21 @@
# Copyright 2018-2023 Piotr Grygorczuk <grygorek@gmail.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
cmake_minimum_required(VERSION 3.0)

View File

@@ -0,0 +1,304 @@
/// Copyright 2018-2023 Piotr Grygorczuk <grygorek@gmail.com>
///
/// Permission is hereby granted, free of charge, to any person obtaining a copy
/// of this software and associated documentation files (the "Software"), to deal
/// in the Software without restriction, including without limitation the rights
/// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
/// copies of the Software, and to permit persons to whom the Software is
/// furnished to do so, subject to the following conditions:
///
/// The above copyright notice and this permission notice shall be included in all
/// copies or substantial portions of the Software.
///
/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
/// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
/// THE SOFTWARE.
#ifndef _GTHR_FREERTOS_X__H_
#define _GTHR_FREERTOS_X__H_
#include "FreeRTOS.h"
#include "task.h"
#include "semphr.h"
#include "thread_gthread.h"
#include "condition_variable.h"
#include "gthr_key.h"
#include <sys/time.h>
typedef free_rtos_std::gthr_freertos __gthread_t;
namespace free_rtos_std
{
struct Once
{
bool v = false;
SemaphoreHandle_t m = xSemaphoreCreateMutex();
~Once() { vSemaphoreDelete(m); }
};
}
extern "C"
{
#define __GTHREAD_COND_INIT_FUNCTION
#define __GTHREADS 1
// returns: 1 - thread system is active; 0 - thread system is not active
static int __gthread_active_p() { return 1; }
typedef free_rtos_std::Key *__gthread_key_t;
typedef free_rtos_std::Once __gthread_once_t;
typedef SemaphoreHandle_t __gthread_mutex_t;
typedef SemaphoreHandle_t __gthread_recursive_mutex_t;
typedef free_rtos_std::cv_task_list __gthread_cond_t;
#define __GTHREAD_ONCE_INIT free_rtos_std::Once()
static inline void __GTHREAD_RECURSIVE_MUTEX_INIT_FUNCTION(
__gthread_recursive_mutex_t *mutex)
{
*mutex = xSemaphoreCreateRecursiveMutex();
}
static inline void __GTHREAD_MUTEX_INIT_FUNCTION(__gthread_mutex_t *mutex)
{
*mutex = xSemaphoreCreateMutex();
}
static int __gthread_once(__gthread_once_t *once, void (*func)(void))
{
if (!once->m)
return 12; // POSIX error: ENOMEM
bool flag{true};
xSemaphoreTake(once->m, portMAX_DELAY);
std::swap(once->v, flag);
if (flag == false)
func();
xSemaphoreGive(once->m);
return 0;
}
static int __gthread_key_create(__gthread_key_t *keyp, void (*dtor)(void *))
{
return free_rtos_std::freertos_gthread_key_create(keyp, dtor);
}
static int __gthread_key_delete(__gthread_key_t key)
{
return free_rtos_std::freertos_gthread_key_delete(key);
}
static void *__gthread_getspecific(__gthread_key_t key)
{
return free_rtos_std::freertos_gthread_getspecific(key);
}
static int __gthread_setspecific(__gthread_key_t key, const void *ptr)
{
return free_rtos_std::freertos_gthread_setspecific(key, ptr);
}
//////////
//////////
static inline int __gthread_mutex_destroy(__gthread_mutex_t *mutex)
{
vSemaphoreDelete(*mutex);
return 0;
}
static inline int __gthread_recursive_mutex_destroy(
__gthread_recursive_mutex_t *mutex)
{
vSemaphoreDelete(*mutex);
return 0;
}
static inline int __gthread_mutex_lock(__gthread_mutex_t *mutex)
{
return (xSemaphoreTake(*mutex, portMAX_DELAY) == pdTRUE) ? 0 : 1;
}
static inline int __gthread_mutex_trylock(__gthread_mutex_t *mutex)
{
return (xSemaphoreTake(*mutex, 0) == pdTRUE) ? 0 : 1;
}
static inline int __gthread_mutex_unlock(__gthread_mutex_t *mutex)
{
return (xSemaphoreGive(*mutex) == pdTRUE) ? 0 : 1;
}
static inline int __gthread_recursive_mutex_lock(
__gthread_recursive_mutex_t *mutex)
{
return (xSemaphoreTakeRecursive(*mutex, portMAX_DELAY) == pdTRUE) ? 0 : 1;
}
static inline int __gthread_recursive_mutex_trylock(
__gthread_recursive_mutex_t *mutex)
{
return (xSemaphoreTakeRecursive(*mutex, 0) == pdTRUE) ? 0 : 1;
}
static inline int __gthread_recursive_mutex_unlock(
__gthread_recursive_mutex_t *mutex)
{
return (xSemaphoreGiveRecursive(*mutex) == pdTRUE) ? 0 : 1;
}
////////////
////////////
#define __GTHREADS_CXX0X 1
struct __gthread_time_t
{
long sec;
long nsec;
int64_t milliseconds() const
{
return int64_t(sec) * 1000 + nsec / 1'000'000;
}
};
static inline __gthread_time_t operator-(
const __gthread_time_t &lhs, const timeval &rhs)
{
int32_t s{lhs.sec - rhs.tv_sec};
int32_t ns{lhs.nsec - rhs.tv_usec * 1000};
return __gthread_time_t{s, ns};
}
static inline int __gthread_mutex_timedlock(
__gthread_mutex_t *m, const __gthread_time_t *abs_timeout)
{
timeval now{};
gettimeofday(&now, NULL);
auto t = (*abs_timeout - now).milliseconds();
return (xSemaphoreTake(*m, pdMS_TO_TICKS(t)) == pdTRUE) ? 0 : 1;
}
static inline int __gthread_recursive_mutex_timedlock(
__gthread_recursive_mutex_t *m, const __gthread_time_t *abs_time)
{
timeval now{};
gettimeofday(&now, NULL);
auto t = (*abs_time - now).milliseconds();
return (xSemaphoreTakeRecursive(*m, pdMS_TO_TICKS(t)) == pdTRUE) ? 0 : 1;
}
// All functions returning int should return zero on success or the error
// number. If the operation is not supported, -1 is returned.
static inline int __gthread_create(__gthread_t *thread, void (*func)(void *),
void *args)
{
return thread->create_thread(func, args) ? 0 : 1;
}
static inline int __gthread_join(__gthread_t &thread, void **value_ptr)
{
thread.join();
return 0;
}
static inline int __gthread_detach(__gthread_t &thread)
{
thread.detach();
return 0;
}
static inline int __gthread_equal(const __gthread_t &t1,
const __gthread_t &t2)
{
return t1 == t2 ? 0 : 1;
}
static inline __gthread_t __gthread_self(void) { return __gthread_t::self(); }
#define _GLIBCXX_USE_SCHED_YIELD
static inline int __gthread_yield(void)
{
taskYIELD();
return 0;
}
static inline int __gthread_cond_signal(__gthread_cond_t *cond)
{
cond->lock();
if (!cond->empty())
{
auto t = cond->front();
cond->pop();
xTaskNotifyGive(t);
}
cond->unlock();
return 0;
}
static inline int __gthread_cond_broadcast(__gthread_cond_t *cond)
{
cond->lock();
while (!cond->empty())
{
auto t = cond->front();
cond->pop();
xTaskNotifyGive(t);
}
cond->unlock();
return 0;
}
static inline int __gthread_cond_destroy(__gthread_cond_t *cond)
{
// nothing to do
return 0;
}
static inline int __gthread_cond_wait(__gthread_cond_t *cond, __gthread_mutex_t *mutex)
{
// Note: 'mutex' is taken before entering this function
cond->lock();
cond->push(__gthread_t::native_task_handle());
cond->unlock();
__gthread_mutex_unlock(mutex);
ulTaskNotifyTake(pdTRUE, portMAX_DELAY);
__gthread_mutex_lock(mutex); // lock and return
return 0;
}
static inline int __gthread_cond_timedwait(
__gthread_cond_t *cond, __gthread_mutex_t *mutex,
const __gthread_time_t *abs_timeout)
{
auto this_thrd_hndl{__gthread_t::native_task_handle()};
cond->lock();
cond->push(this_thrd_hndl);
cond->unlock();
timeval now{};
gettimeofday(&now, NULL);
auto ms{(*abs_timeout - now).milliseconds()};
__gthread_mutex_unlock(mutex);
auto fTimeout{0 == ulTaskNotifyTake(pdTRUE, pdMS_TO_TICKS(ms))};
__gthread_mutex_lock(mutex);
int result{0};
if (fTimeout)
{ // timeout - remove the thread from the waiting list
cond->lock();
cond->remove(this_thrd_hndl);
cond->unlock();
result = 138; // posix ETIMEDOUT
}
return result;
}
} // extern "C"
#endif // _GTHR_FREERTOS_X__H_

View File

@@ -0,0 +1,106 @@
/// Copyright 2018-2023 Piotr Grygorczuk <grygorek@gmail.com>
///
/// Permission is hereby granted, free of charge, to any person obtaining a copy
/// of this software and associated documentation files (the "Software"), to deal
/// in the Software without restriction, including without limitation the rights
/// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
/// copies of the Software, and to permit persons to whom the Software is
/// furnished to do so, subject to the following conditions:
///
/// The above copyright notice and this permission notice shall be included in all
/// copies or substantial portions of the Software.
///
/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
/// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
/// THE SOFTWARE.
#ifndef GTHR_FREERTOS_INTERNAL_CV_H
#define GTHR_FREERTOS_INTERNAL_CV_H
#include "FreeRTOS.h"
#include "task.h"
#include "semphr.h"
#include "thread_gthread.h"
#include <list>
#include <bits/functexcept.h>
namespace free_rtos_std
{
class semaphore
{
public:
semaphore() : _xSemaphore { xSemaphoreCreateBinary() }
{
if (!_xSemaphore)
std::__throw_system_error(12); // POSIX error: no memory
xSemaphoreGive(_xSemaphore);
}
void lock() { xSemaphoreTake(_xSemaphore, portMAX_DELAY); }
void unlock() { xSemaphoreGive(_xSemaphore); }
~semaphore()
{
vSemaphoreDelete(_xSemaphore);
}
semaphore(const semaphore &) = delete;
semaphore(semaphore &&) = delete;
semaphore &operator=(semaphore &) = delete;
semaphore &operator=(semaphore &&) = delete;
private:
SemaphoreHandle_t _xSemaphore;
};
// Internal free rtos task's container to support condition variable.
// Condition variable must know all the threads waiting in a queue.
//
class cv_task_list
{
public:
using __gthread_t = free_rtos_std::gthr_freertos;
using thrd_type = __gthread_t::native_task_type;
using queue_type = std::list<thrd_type>;
cv_task_list() = default;
void remove(thrd_type thrd) { _que.remove(thrd); }
void push(thrd_type thrd) { _que.push_back(thrd); }
void pop() { _que.pop_front(); }
bool empty() const { return _que.empty(); }
~cv_task_list()
{
lock();
_que = queue_type{};
unlock();
}
// no copy and no move
cv_task_list &operator=(const cv_task_list &r) = delete;
cv_task_list &operator=(cv_task_list &&r) = delete;
cv_task_list(cv_task_list &&) = delete;
cv_task_list(const cv_task_list &) = delete;
thrd_type &front() { return _que.front(); }
const thrd_type &front() const { return _que.front(); }
thrd_type &back() { return _que.back(); }
const thrd_type &back() const { return _que.back(); }
void lock() { _sem.lock(); }
void unlock() { _sem.unlock(); }
private:
queue_type _que;
semaphore _sem;
};
} // namespace free_rtos_std
#endif // GTHR_FREERTOS_INTERNAL_CV_H

View File

@@ -0,0 +1,36 @@
/// Copyright 2018-2023 Piotr Grygorczuk <grygorek@gmail.com>
///
/// Permission is hereby granted, free of charge, to any person obtaining a copy
/// of this software and associated documentation files (the "Software"), to deal
/// in the Software without restriction, including without limitation the rights
/// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
/// copies of the Software, and to permit persons to whom the Software is
/// furnished to do so, subject to the following conditions:
///
/// The above copyright notice and this permission notice shall be included in all
/// copies or substantial portions of the Software.
///
/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
/// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
/// THE SOFTWARE.
#ifndef GTHR_FREERTOS_INTERNAL_CRITICAL_H
#define GTHR_FREERTOS_INTERNAL_CRITICAL_H
#include "FreeRTOS.h"
#include "task.h"
namespace free_rtos_std
{
struct critical_section
{
critical_section() { taskENTER_CRITICAL(); }
~critical_section() { taskEXIT_CRITICAL(); }
};
} // namespace free_rtos_std
#endif //GTHR_FREERTOS_INTERNAL_CRITICAL_H

View File

@@ -0,0 +1,50 @@
/// Copyright 2018-2023 Piotr Grygorczuk <grygorek@gmail.com>
///
/// Permission is hereby granted, free of charge, to any person obtaining a copy
/// of this software and associated documentation files (the "Software"), to deal
/// in the Software without restriction, including without limitation the rights
/// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
/// copies of the Software, and to permit persons to whom the Software is
/// furnished to do so, subject to the following conditions:
///
/// The above copyright notice and this permission notice shall be included in all
/// copies or substantial portions of the Software.
///
/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
/// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
/// THE SOFTWARE.
#ifndef FREERTOS_THREAD_ATTRIBUTES_H__
#define FREERTOS_THREAD_ATTRIBUTES_H__
#include "FreeRTOS.h"
namespace free_rtos_std
{
struct attributes
{
// Name length limit is defined by configMAX_TASK_NAME_LEN
const char *taskName = "Task";
#ifdef configDEFAULT_STD_THREAD_STACK_SIZE
configSTACK_DEPTH_TYPE stackWordCount{configDEFAULT_STD_THREAD_STACK_SIZE};
#else
// Default stack size is 512 words, so 2 kB
configSTACK_DEPTH_TYPE stackWordCount{512U};
#endif
UBaseType_t priority = tskIDLE_PRIORITY + 1;
};
constexpr attributes attr_stack_size(configSTACK_DEPTH_TYPE size) { return {.stackWordCount = size}; }
constexpr attributes attr_priority(UBaseType_t priority) { return {.priority = priority}; }
constexpr attributes attr_name(const char *n) { return {.taskName = n}; }
}
#endif // FREERTOS_THREAD_ATTRIBUTES_H__

View File

@@ -0,0 +1,97 @@
/// Copyright 2018-2023 Piotr Grygorczuk <grygorek@gmail.com>
///
/// Permission is hereby granted, free of charge, to any person obtaining a copy
/// of this software and associated documentation files (the "Software"), to deal
/// in the Software without restriction, including without limitation the rights
/// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
/// copies of the Software, and to permit persons to whom the Software is
/// furnished to do so, subject to the following conditions:
///
/// The above copyright notice and this permission notice shall be included in all
/// copies or substantial portions of the Software.
///
/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
/// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
/// THE SOFTWARE.
#include "freertos_time.h"
#include "critical_section.h"
#include <sys/time.h>
#include <chrono>
#include "FreeRTOS.h"
#include "task.h"
namespace free_rtos_std
{
class wall_clock
{
public:
struct time_data
{
timeval offset;
TickType_t ticks;
};
static time_data time()
{ //atomic
critical_section critical;
return time_data{_timeOffset, xTaskGetTickCount()};
}
static void time(const timeval &time)
{ //atomic
critical_section critical;
_timeOffset = time;
}
private:
static timeval _timeOffset;
};
timeval wall_clock::_timeOffset;
} // namespace free_rtos_std
using namespace std::chrono;
void SetSystemClockTime(
const time_point<system_clock, system_clock::duration> &time)
{
auto delta{time - time_point<system_clock>(
milliseconds(pdTICKS_TO_MS(xTaskGetTickCount())))};
long long sec{duration_cast<seconds>(delta).count()};
long usec = duration_cast<microseconds>(delta).count() - sec * 1'000'000; //narrowing type
free_rtos_std::wall_clock::time({sec, usec});
}
static timeval operator+(const timeval &l, const timeval &r)
{
timeval t{l.tv_sec + r.tv_sec, l.tv_usec + r.tv_usec};
if (t.tv_usec >= 1'000'000)
{
t.tv_sec++;
t.tv_usec -= 1'000'000;
}
return t;
}
extern "C" int _gettimeofday(timeval *tv, void *tzvp)
{
(void)tzvp;
auto t{free_rtos_std::wall_clock::time()};
long long ms{(long long)pdTICKS_TO_MS(t.ticks)};
long long sec{ms / 1000};
long usec = (ms - sec * 1000) * 1000; //narrowing type
*tv = t.offset + timeval{sec, usec};
return 0; // return non-zero for error
}

View File

@@ -0,0 +1,30 @@
/// Copyright 2018-2023 Piotr Grygorczuk <grygorek@gmail.com>
///
/// Permission is hereby granted, free of charge, to any person obtaining a copy
/// of this software and associated documentation files (the "Software"), to deal
/// in the Software without restriction, including without limitation the rights
/// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
/// copies of the Software, and to permit persons to whom the Software is
/// furnished to do so, subject to the following conditions:
///
/// The above copyright notice and this permission notice shall be included in all
/// copies or substantial portions of the Software.
///
/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
/// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
/// THE SOFTWARE.
#ifndef __FREE_RTOS_PORT_TIME_H__
#define __FREE_RTOS_PORT_TIME_H__
#include <chrono>
void SetSystemClockTime(
const std::chrono::time_point<std::chrono::system_clock,
std::chrono::system_clock::duration> &time);
#endif //__FREE_RTOS_PORT_TIME_H__

View File

@@ -0,0 +1,73 @@
/// Copyright 2018-2023 Piotr Grygorczuk <grygorek@gmail.com>
///
/// Permission is hereby granted, free of charge, to any person obtaining a copy
/// of this software and associated documentation files (the "Software"), to deal
/// in the Software without restriction, including without limitation the rights
/// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
/// copies of the Software, and to permit persons to whom the Software is
/// furnished to do so, subject to the following conditions:
///
/// The above copyright notice and this permission notice shall be included in all
/// copies or substantial portions of the Software.
///
/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
/// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
/// THE SOFTWARE.
#include "gthr_key_type.h"
#include <cassert>
namespace free_rtos_std
{
Key *s_key;
int freertos_gthread_key_create(Key **keyp, void (*dtor)(void *))
{
// There is only one key for all threads. If more keys are needed
// a list must be implemented.
assert(!s_key);
s_key = new Key(dtor);
*keyp = s_key;
return 0;
}
int freertos_gthread_key_delete(Key *)
{
// no synchronization here:
// It is up to the applicaiton to delete (or maintain a reference)
// the thread specific data associated with the key.
delete s_key;
s_key = nullptr;
return 0;
}
void *freertos_gthread_getspecific(Key *key)
{
std::lock_guard<std::mutex> lg{key->_mtx};
auto item = key->_specValue.find(__gthread_t::self().native_task_handle());
if (item == key->_specValue.end())
return nullptr;
return const_cast<void *>(item->second);
}
int freertos_gthread_setspecific(Key *key, const void *ptr)
{
std::lock_guard<std::mutex> lg{key->_mtx};
auto &cont{key->_specValue};
auto task{__gthread_t::self().native_task_handle()};
if (ptr)
cont[task] = ptr;
else
(void)cont.erase(task);
return 0;
}
} // namespace free_rtos_std

View File

@@ -0,0 +1,34 @@
/// Copyright 2018-2023 Piotr Grygorczuk <grygorek@gmail.com>
///
/// Permission is hereby granted, free of charge, to any person obtaining a copy
/// of this software and associated documentation files (the "Software"), to deal
/// in the Software without restriction, including without limitation the rights
/// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
/// copies of the Software, and to permit persons to whom the Software is
/// furnished to do so, subject to the following conditions:
///
/// The above copyright notice and this permission notice shall be included in all
/// copies or substantial portions of the Software.
///
/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
/// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
/// THE SOFTWARE.
#ifndef __FREERTOS_GTHR_KEY_H__
#define __FREERTOS_GTHR_KEY_H__
namespace free_rtos_std
{
struct Key;
int freertos_gthread_key_create(Key **keyp, void (*dtor)(void *));
int freertos_gthread_key_delete(Key *key);
void *freertos_gthread_getspecific(Key *key);
int freertos_gthread_setspecific(Key *key, const void *ptr);
} // namespace free_rtos_std
#endif //__FREERTOS_GTHR_KEY_H__

View File

@@ -0,0 +1,65 @@
/// Copyright 2018-2023 Piotr Grygorczuk <grygorek@gmail.com>
///
/// Permission is hereby granted, free of charge, to any person obtaining a copy
/// of this software and associated documentation files (the "Software"), to deal
/// in the Software without restriction, including without limitation the rights
/// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
/// copies of the Software, and to permit persons to whom the Software is
/// furnished to do so, subject to the following conditions:
///
/// The above copyright notice and this permission notice shall be included in all
/// copies or substantial portions of the Software.
///
/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
/// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
/// THE SOFTWARE.
#ifndef __FREERTOS_GTHR_KEY_KEY_H__
#define __FREERTOS_GTHR_KEY_KEY_H__
#include "thread_gthread.h"
#include <unordered_map>
#include <mutex>
namespace free_rtos_std
{
struct Key
{
using __gthread_t = free_rtos_std::gthr_freertos;
typedef void (*DestructorFoo)(void *);
Key() = delete;
explicit Key(DestructorFoo des) : _desFoo{des} {}
void CallDestructor(__gthread_t::native_task_type task)
{
void *val;
{
std::lock_guard<std::mutex> lg{_mtx};
auto item{_specValue.find(task)};
if (item == _specValue.end())
return;
val = const_cast<void *>(item->second);
_specValue.erase(item);
}
if (_desFoo && val)
_desFoo(val);
}
std::mutex _mtx;
DestructorFoo _desFoo;
std::unordered_map<__gthread_t::native_task_type, const void *> _specValue;
};
} // namespace free_rtos_std
#endif //__FREERTOS_GTHR_KEY_KEY_H__

View File

@@ -0,0 +1,114 @@
/// Copyright 2018-2023 Piotr Grygorczuk <grygorek@gmail.com>
/// Copyright 2023 by NXP. All rights reserved.
///
/// Permission is hereby granted, free of charge, to any person obtaining a copy
/// of this software and associated documentation files (the "Software"), to deal
/// in the Software without restriction, including without limitation the rights
/// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
/// copies of the Software, and to permit persons to whom the Software is
/// furnished to do so, subject to the following conditions:
///
/// The above copyright notice and this permission notice shall be included in all
/// copies or substantial portions of the Software.
///
/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
/// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
/// THE SOFTWARE.
#define _GLIBCXX_THREAD_IMPL 1
#include <thread>
#include <system_error>
#include <cerrno>
#include "FreeRTOS.h"
#include "gthr_key_type.h"
#include "freertos_thread_attributes.h"
namespace free_rtos_std
{
extern Key *s_key;
const attributes *internal::attributes_lock::_attrib{&internal::attributes_lock::_default};
} // namespace free_rtos_std
namespace std
{
static void __execute_native_thread_routine(void *__p)
{
__gthread_t local{*static_cast<__gthread_t *>(__p)}; // copy
{ // we own the arg now; it must be deleted after run() returns
thread::_State_ptr __t{static_cast<thread::_State *>(local.arg())};
local.notify_started(); // copy has been made; tell we are running
__t->_M_run();
}
if (free_rtos_std::s_key)
free_rtos_std::s_key->CallDestructor(__gthread_t::self().native_task_handle());
local.notify_joined(); // finished; release joined threads
}
thread::_State::~_State() = default;
void thread::_M_start_thread(_State_ptr state, void (*)())
{
const int err = __gthread_create(
&_M_id._M_thread, __execute_native_thread_routine, state.get());
if (err)
__throw_system_error(err);
state.release();
}
void thread::join()
{
id invalid;
if (_M_id._M_thread != invalid._M_thread)
__gthread_join(_M_id._M_thread, nullptr);
else
__throw_system_error(EINVAL);
// destroy the handle explicitly - next call to join/detach will throw
_M_id = std::move(invalid);
}
void thread::detach()
{
id invalid;
if (_M_id._M_thread != invalid._M_thread)
__gthread_detach(_M_id._M_thread);
else
__throw_system_error(EINVAL);
// destroy the handle explicitly - next call to join/detach will throw
_M_id = std::move(invalid);
}
// Returns the number of concurrent threads supported by the implementation.
// The value should be considered only a hint.
//
// Return value
// Number of concurrent threads supported. If the value is not well defined
// or not computable, returns ​0​.
unsigned int thread::hardware_concurrency() noexcept
{
return 0; // not computable
}
void this_thread::__sleep_for(chrono::seconds sec, chrono::nanoseconds nsec)
{
long ms = nsec.count() / 1'000'000;
if (sec.count() == 0 && ms == 0 && nsec.count() > 0)
ms = 1; // round up to 1 ms => if sleep time != 0, sleep at least 1ms
vTaskDelay(pdMS_TO_TICKS(chrono::milliseconds(sec).count() + ms));
}
} // namespace std

View File

@@ -0,0 +1,378 @@
/// Copyright 2018-2023 Piotr Grygorczuk <grygorek@gmail.com>
/// Copyright 2023 by NXP. All rights reserved.
///
/// Permission is hereby granted, free of charge, to any person obtaining a copy
/// of this software and associated documentation files (the "Software"), to deal
/// in the Software without restriction, including without limitation the rights
/// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
/// copies of the Software, and to permit persons to whom the Software is
/// furnished to do so, subject to the following conditions:
///
/// The above copyright notice and this permission notice shall be included in all
/// copies or substantial portions of the Software.
///
/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
/// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
/// THE SOFTWARE.
#ifndef GTHR_FREERTOS_INTERNAL_H
#define GTHR_FREERTOS_INTERNAL_H
#include "FreeRTOS.h"
#include "task.h"
#include "event_groups.h"
#include "critical_section.h"
#include "freertos_thread_attributes.h"
#include <utility> // std::forward
#include <exception> // std::terminate
#if __cplusplus > 201703L
#include <compare>
#endif
namespace std
{
class thread;
}
namespace free_rtos_std
{
namespace internal
{
// Derive from the cticical_section. As long as an instance of attributes_lock exists
// it is safe to create a thread with custom attributes.
struct attributes_lock : critical_section
{
// Note - attributes_lock should not be used by the end user. Helper API is
// provided in 'thread_with_attributes.h'. That header should be included by the
// end user when using custom attributes is required.
//
// It is possible to manually specify the task attributes when creating a
// `std::thread` instance as follows:
// ```
// std::thread t{[&] {
// free_rtos_std::internal::attributes_lock lock{{.stackWordCount = 4096U}}; // 16 kB
// return std::thread{fn, args};
// }()};
// ```
// This way, we are sure that only this one thread will have the specified
// attributes, while keeping the convenient `std::thread` API.
//
// Please note that the following will result in a deadlock:
// ```
// std::thread t;
// {
// free_rtos_std::internal::attributes_lock lock{{.stackWordCount = 4096U}}; // 16 kB
// t = std::thread{fn, args};
// }
// ```
// The reason is that the move assignment operator of std::thread calls the
// `gthr_freertos::wait_for_start` method, which waits for a different
// task. Since scheduling is disabled during the lifetime of
// `attributes_lock`, that waiting will never return. Instead, if
// the `std::thread` object only needs to be assigned, we can proceed as
// follows:
// ```
// t = [&] {
// free_rtos_std::internal::attributes_lock lock{{.stackWordCount = 4096U}}; // 16 kB
// return std::thread{fn, args};
// }();
// ```
// In this case, the move assignment operator is called only after the
// `attributes_lock` instance is destroyed, so the scheduler is
// running again, but the thread has already been created.
//
attributes_lock(const attributes &attrib) { _attrib = &attrib; }
~attributes_lock() { _attrib = &_default; }
static const attributes *_attrib;
private:
static constexpr attributes _default{};
};
}
class gthr_freertos
{
// 1. std::thread class has a single member variable representing
// a native thread handle
// 2. Detach requires that the native thread function will execute
// even if the std::thread instance has been destroyed. The native
// thread function must take the ownership of any resources allocated
// during the thread creation. This could be the thread handle itself.
// Detach must make sure that the thread has started execution and
// the ownership has been taken.
// 3. Join requires a way to switch the current context to a waiting
// state. The native thread function must have a way to unlock
// a joined thread.
// 4. FreeRTOS does not have an interface implementing join. It is possible
// to suspend a thread but the thread we are waiting for to join is not
// aware which thread is waiting. Is this statement wrong?
// 5. Solution is to use events group.
// The handle life time must be handled by this class.
// 6. Life time of thread handle and events group handle is not the same.
// There are two cases:
// a) detach is called and std::thread instance is destroyed; in this case
// thread function outlives the thread instance
// b) thread function exits first; in this case the thread instance
// outlives the thread function; join must have access to the events
// group to check whether the thread function has finished or not.
// So, the thread handle must exist as long as thread function executes.
// The events group must live as long as std::thread instance exists.
// 7. Although the living time is different for two handles,
// see pt. 1 -only one member variable to handle free rtos interface.
// For this reason a single class is a container for the two handles.
friend std::thread;
enum
{
eEvStoragePos = 0,
eStartedEv = 1 << 22,
eJoinEv = 1 << 23
};
public:
typedef void (*task_foo)(void *);
typedef TaskHandle_t native_task_type;
gthr_freertos(const gthr_freertos &r)
{
critical_section critical;
_taskHandle = r._taskHandle;
_evHandle = r._evHandle;
_arg = r._arg;
_fOwner = false; // it is just a copy
}
gthr_freertos(gthr_freertos &&r)
{
taskENTER_CRITICAL();
if (r._fOwner)
{
taskEXIT_CRITICAL();
// make sure it has already started
// - native thread function must make local copies first
r.wait_for_start();
taskENTER_CRITICAL();
}
// 'this' becomes the owner if r is the owner
move(std::forward<gthr_freertos>(r));
taskEXIT_CRITICAL();
}
bool create_thread(task_foo foo, void *arg)
{
_arg = arg;
_evHandle = xEventGroupCreate();
if (!_evHandle)
std::terminate();
{
critical_section critical;
const auto &attr = *internal::attributes_lock::_attrib;
xTaskCreate(foo, attr.taskName, attr.stackWordCount, this, attr.priority, &_taskHandle);
if (!_taskHandle)
std::terminate();
vTaskSetThreadLocalStoragePointer(_taskHandle, eEvStoragePos, _evHandle);
_fOwner = true;
}
return true;
}
void join()
{ // note 1: _evHandle must be valid here. Even if the native thread function
// has finished and got destroyed the _taskHandle, it
// must not release the _evHandle!
//
// note 2: The native thread function must call notify_joined when it has
// finished. Even if 'join' is called after that, the bits are set
// and event group will not block. So it is safe to call wait here.
//
// note 3: Instead of keeping _evHandle, it could be possible to read
// it from the local storage of the task. However, that would require
// checking if the task still exists and use critical section if it does.
// It is faster to use _evHandle directly, even if it is an extra item to
// copy each time when this instance is copied.
while (0 == xEventGroupWaitBits(_evHandle,
eJoinEv | eStartedEv,
pdFALSE,
pdTRUE,
portMAX_DELAY))
;
}
void detach()
{ // Detaching is removing the event's object. It can be done
// only if the thread has started execution.
wait_for_start();
{ // unfortunately critical section is needed here to make sure
// the task is not deleted while accessing the task's local storage.
critical_section critical;
if (eDeleted != eTaskGetState(_taskHandle))
{
vTaskSetThreadLocalStoragePointer(_taskHandle, eEvStoragePos, nullptr);
vEventGroupDelete(_evHandle);
// Thread still exists but detach removes ownership.
// Ownership belongs to the native thread. It will release the task
// handle once user's thread function exits.
_fOwner = false;
}
}
}
void notify_started()
{ // Function should be called only from the controlled task
// and only when the (internal, not application's one) thread function
// has started execution.
xEventGroupSetBits(_evHandle, eStartedEv);
}
void notify_joined()
{ // Function should be called only from the controlled task
// and only when the thread function has finished execution.
{
critical_section critical;
// Note: The _evHandle may be invalid if thread has been detached.
// It is required to get the handle from the thread itself.
// The detach function will set this handle to nullptr.
auto evHnd = static_cast<EventGroupHandle_t>(
pvTaskGetThreadLocalStoragePointer(_taskHandle, eEvStoragePos));
if (evHnd)
{
xEventGroupSetBits(evHnd, eJoinEv);
}
else
{
// thread has been detached, nothing to do
}
}
// vTaskDelete will not return
vTaskDelete(nullptr);
}
static gthr_freertos self()
{
auto tHnd = xTaskGetCurrentTaskHandle();
auto evHnd = static_cast<EventGroupHandle_t>(
pvTaskGetThreadLocalStoragePointer(tHnd, eEvStoragePos));
return gthr_freertos{tHnd, evHnd};
}
static native_task_type native_task_handle()
{
return xTaskGetCurrentTaskHandle();
}
constexpr friend bool operator==(const gthr_freertos &l, const gthr_freertos &r) noexcept
{
return l._taskHandle == r._taskHandle;
}
#if __cpp_lib_three_way_comparison
constexpr friend std::strong_ordering operator<=>(const gthr_freertos &l, const gthr_freertos &r) noexcept
{
return l._taskHandle <=> r._taskHandle;
}
#else
constexpr friend bool operator!=(const gthr_freertos &l, const gthr_freertos &r) noexcept
{
return l._taskHandle != r._taskHandle;
}
constexpr friend bool operator<(const gthr_freertos &l, const gthr_freertos &r) noexcept
{
return l._taskHandle < r._taskHandle;
}
#endif
constexpr void *arg() const
{
return _arg;
}
~gthr_freertos() = default;
gthr_freertos &operator=(const gthr_freertos &r) = delete;
gthr_freertos() = default;
constexpr gthr_freertos(native_task_type thnd, EventGroupHandle_t ehnd)
: _taskHandle{thnd}, _evHandle{ehnd}
{
}
gthr_freertos &operator=(gthr_freertos &&r)
{
if (this == &r)
return *this;
taskENTER_CRITICAL();
if (_fOwner)
{ // If 'r' is the owner then 'this' will get the
// new ownership. If 'r' is not the owner then
// just a copy is being moved. Either way 'this'
// ownership is lost and handles must be deleted.
if (eDeleted != eTaskGetState(_taskHandle))
vTaskDelete(_taskHandle);
if (_evHandle)
vEventGroupDelete(_evHandle);
_fOwner = false;
}
else if (r._fOwner)
{
taskEXIT_CRITICAL();
// make sure it has already started
// - native thread function must make local copies first
r.wait_for_start();
taskENTER_CRITICAL();
}
// 'this' becomes the owner if r is the owner
move(std::forward<gthr_freertos>(r));
taskEXIT_CRITICAL();
return *this;
}
private:
constexpr void move(gthr_freertos &&r)
{
_taskHandle = r._taskHandle;
_evHandle = r._evHandle;
_arg = r._arg;
_fOwner = r._fOwner;
r._taskHandle = nullptr;
r._evHandle = nullptr;
r._arg = nullptr;
r._fOwner = false;
}
void wait_for_start()
{
while (0 == xEventGroupWaitBits(
_evHandle, eStartedEv, pdFALSE, pdTRUE, portMAX_DELAY))
;
}
native_task_type _taskHandle{nullptr};
EventGroupHandle_t _evHandle{nullptr};
void *_arg{nullptr};
bool _fOwner{false};
};
} // namespace free_rtos_std
#endif // GTHR_FREERTOS_INTERNAL_H

View File

@@ -0,0 +1,65 @@
/// Copyright 2018-2023 Piotr Grygorczuk <grygorek@gmail.com>
///
/// Permission is hereby granted, free of charge, to any person obtaining a copy
/// of this software and associated documentation files (the "Software"), to deal
/// in the Software without restriction, including without limitation the rights
/// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
/// copies of the Software, and to permit persons to whom the Software is
/// furnished to do so, subject to the following conditions:
///
/// The above copyright notice and this permission notice shall be included in all
/// copies or substantial portions of the Software.
///
/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
/// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
/// THE SOFTWARE.
#ifndef FREERTOS_THREAD_WITH_ATTRIBUTES_H__
#define FREERTOS_THREAD_WITH_ATTRIBUTES_H__
#include <thread>
#include <utility> // std::forward
#include "freertos_thread_attributes.h"
namespace free_rtos_std
{
// Helper functions to create std::thread and std::jthread with attributes.
// See free_rtos_std::attributes in freertos_thread_attributes.h for available attributes.
//
// Example:
// ```
// void thr_f(int i) { std::cout << i; }
//
// void f()
// {
// // Create a jtread with 4kB stack size
// std::jthread t = free_rtos_std::std_jthread(
// free_rtos_std::attr_stack_size(1024u), thr_f, 5);
// }
// ```
// @param args - see arguments of std::thread
template <typename... Args>
std::thread std_thread(const free_rtos_std::attributes &attr, Args &&...args)
{
free_rtos_std::internal::attributes_lock lock{attr};
return std::thread(std::forward<Args>(args)...);
}
// @param args - see arguments of std::jthread
template <typename... Args>
std::jthread std_jthread(const free_rtos_std::attributes &attr, Args &&...args)
{
free_rtos_std::internal::attributes_lock lock{attr};
return std::jthread(std::forward<Args>(args)...);
}
}
#endif // FREERTOS_THREAD_WITH_ATTRIBUTES_H__