1 | #include "thread.hpp" |
---|
2 | |
---|
3 | #include <cstdarg> // va_start, va_end |
---|
4 | #include <cstdio> |
---|
5 | #include <cstring> // strlen |
---|
6 | extern "C" { |
---|
7 | #include <unistd.h> // _exit, getpid |
---|
8 | #include <signal.h> |
---|
9 | #include <dlfcn.h> // dlopen, dlsym |
---|
10 | #include <execinfo.h> // backtrace, messages |
---|
11 | } |
---|
12 | |
---|
13 | #include <iostream> |
---|
14 | #include <string> |
---|
15 | |
---|
16 | using thrdlib::thread_t; |
---|
17 | |
---|
18 | thread_t (*thrdlib::create)( void (*main)( thread_t ) ) = nullptr; |
---|
19 | void (*thrdlib::join)( thread_t handle ) = nullptr; |
---|
20 | void (*thrdlib::park)( thread_t handle ) = nullptr; |
---|
21 | void (*thrdlib::unpark)( thread_t handle ) = nullptr; |
---|
22 | void (*thrdlib::yield)( void ) = nullptr; |
---|
23 | void (*lib_clean)(void) = nullptr; |
---|
24 | |
---|
25 | typedef void (*fptr_t)(); |
---|
26 | static fptr_t open_symbol( void * library, const char * symbol, bool required ) { |
---|
27 | void * ptr = dlsym( library, symbol ); |
---|
28 | |
---|
29 | const char * error = dlerror(); |
---|
30 | if ( required && error ) { |
---|
31 | std::cerr << "Fetching symbol '" << symbol << "' failed with error '" << error << "'\n"; |
---|
32 | std::abort(); |
---|
33 | } |
---|
34 | |
---|
35 | return (fptr_t)ptr; |
---|
36 | } |
---|
37 | |
---|
38 | //-------------------- |
---|
39 | // Basic kernel features |
---|
40 | void thrdlib::init( const char * name, int procs ) { |
---|
41 | std::string file = __FILE__; |
---|
42 | std::size_t found = file.find_last_of("/"); |
---|
43 | std::string libname = file.substr(0,found+1) + name + ".so"; |
---|
44 | |
---|
45 | std::cout << "Use framework " << name << "(" << libname << ")\n"; |
---|
46 | |
---|
47 | void * library = dlopen( libname.c_str(), RTLD_NOW ); |
---|
48 | if ( const char * error = dlerror() ) { |
---|
49 | std::cerr << "Could not open library '" << libname << "' from name '" << name <<"'\n"; |
---|
50 | std::cerr << "Error was : '" << error << "'\n"; |
---|
51 | std::abort(); |
---|
52 | } |
---|
53 | |
---|
54 | void (*lib_init)( int ) = (void (*)( int ))open_symbol( library, "thrdlib_init", false ); |
---|
55 | lib_clean = open_symbol( library, "thrdlib_clean" , false ); |
---|
56 | |
---|
57 | thrdlib::create = (typeof(thrdlib::create))open_symbol( library, "thrdlib_create", true ); |
---|
58 | thrdlib::join = (typeof(thrdlib::join ))open_symbol( library, "thrdlib_join" , true ); |
---|
59 | thrdlib::park = (typeof(thrdlib::park ))open_symbol( library, "thrdlib_park" , true ); |
---|
60 | thrdlib::unpark = (typeof(thrdlib::unpark))open_symbol( library, "thrdlib_unpark", true ); |
---|
61 | thrdlib::yield = (typeof(thrdlib::yield ))open_symbol( library, "thrdlib_yield" , true ); |
---|
62 | |
---|
63 | lib_init( procs ); |
---|
64 | } |
---|
65 | |
---|
66 | void thrdlib::clean( void ) { |
---|
67 | if(lib_clean) lib_clean(); |
---|
68 | } |
---|