blob: 9889c07a4e6ebdd45fade15694fce36897c7c3cb [file] [log] [blame]
Brian Silvermanb0893882014-02-10 14:48:30 -08001#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
8namespace aos {
9namespace logging {
10namespace internal {
11namespace {
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 Silverman01be0002014-05-10 15:44:38 -070023 PDie("prctl(PR_GET_NAME, %p) failed", thread_name_array);
Brian Silvermanb0893882014-02-10 14:48:30 -080024 }
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
40AOS_THREAD_LOCAL Context *my_context(NULL);
41
42} // namespace
43
44Context *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
57void Context::Delete() {
58 delete my_context;
59 my_context = NULL;
60}
61
62} // namespace internal
63} // namespace logging
64} // namespace aos