Brian Silverman | b089388 | 2014-02-10 14:48:30 -0800 | [diff] [blame] | 1 | #include "aos/linux_code/logging/linux_logging.h" |
| 2 | |
| 3 | #include <sys/prctl.h> |
| 4 | |
| 5 | #include "aos/linux_code/thread_local.h" |
| 6 | #include "aos/common/die.h" |
| 7 | |
| 8 | namespace aos { |
| 9 | namespace logging { |
| 10 | namespace internal { |
| 11 | namespace { |
| 12 | |
| 13 | ::std::string GetMyName() { |
| 14 | // The maximum number of characters that can make up a thread name. |
| 15 | // The docs are unclear if it can be 16 characters with no '\0', so we'll be |
| 16 | // safe by adding our own where necessary. |
| 17 | static const size_t kThreadNameLength = 16; |
| 18 | |
| 19 | ::std::string process_name(program_invocation_short_name); |
| 20 | |
| 21 | char thread_name_array[kThreadNameLength + 1]; |
| 22 | if (prctl(PR_GET_NAME, thread_name_array) != 0) { |
Brian Silverman | 01be000 | 2014-05-10 15:44:38 -0700 | [diff] [blame^] | 23 | PDie("prctl(PR_GET_NAME, %p) failed", thread_name_array); |
Brian Silverman | b089388 | 2014-02-10 14:48:30 -0800 | [diff] [blame] | 24 | } |
| 25 | thread_name_array[sizeof(thread_name_array) - 1] = '\0'; |
| 26 | ::std::string thread_name(thread_name_array); |
| 27 | |
| 28 | // If the first bunch of characters are the same. |
| 29 | // We cut off comparing at the shorter of the 2 strings because one or the |
| 30 | // other often ends up cut off. |
| 31 | if (strncmp(thread_name.c_str(), process_name.c_str(), |
| 32 | ::std::min(thread_name.length(), process_name.length())) == 0) { |
| 33 | // This thread doesn't have an actual name. |
| 34 | return process_name; |
| 35 | } |
| 36 | |
| 37 | return process_name + '.' + thread_name; |
| 38 | } |
| 39 | |
| 40 | AOS_THREAD_LOCAL Context *my_context(NULL); |
| 41 | |
| 42 | } // namespace |
| 43 | |
| 44 | Context *Context::Get() { |
| 45 | if (my_context == NULL) { |
| 46 | my_context = new Context(); |
| 47 | my_context->name = GetMyName(); |
| 48 | if (my_context->name.size() + 1 > sizeof(LogMessage::name)) { |
| 49 | Die("logging: process/thread name '%s' is too long\n", |
| 50 | my_context->name.c_str()); |
| 51 | } |
| 52 | my_context->source = getpid(); |
| 53 | } |
| 54 | return my_context; |
| 55 | } |
| 56 | |
| 57 | void Context::Delete() { |
| 58 | delete my_context; |
| 59 | my_context = NULL; |
| 60 | } |
| 61 | |
| 62 | } // namespace internal |
| 63 | } // namespace logging |
| 64 | } // namespace aos |