Debian Codegraph @

src/platform/program_name.hpp

raw
1 #ifndef PROGRAM_NAME_HPP
2 #define PROGRAM_NAME_HPP
3
4 #include <mutex>
5 #include <string>
6
7 #include "platform/platform.hpp"
8
9 #if IS_WINDOWS
10 #ifndef WIN32_LEAN_AND_MEAN
11 #define WIN32_LEAN_AND_MEAN
12 #endif
13 #include <windows.h>
14
15 #define CPPTRACE_MAX_PATH MAX_PATH
16
17 CPPTRACE_BEGIN_NAMESPACE
18 namespace detail {
19 inline const char* program_name() {
20 static std::mutex mutex;
21 const std::lock_guard<std::mutex> lock(mutex);
22 static std::string name;
23 static bool did_init = false;
24 static bool valid = false;
25 if(!did_init) {
26 did_init = true;
27 char buffer[MAX_PATH + 1];
28 int res = GetModuleFileNameA(nullptr, buffer, MAX_PATH);
29 if(res) {
30 name = buffer;
31 valid = true;
32 }
33 }
34 return valid && !name.empty() ? name.c_str() : nullptr;
35 }
36 }
37 CPPTRACE_END_NAMESPACE
38
39 #elif IS_APPLE
40
41 #include <cstdint>
42 #include <mach-o/dyld.h>
43 #include <sys/syslimits.h>
44
45 #define CPPTRACE_MAX_PATH CPPTRACE_PATH_MAX
46
47 CPPTRACE_BEGIN_NAMESPACE
48 namespace detail {
49 inline const char* program_name() {
50 static std::mutex mutex;
51 const std::lock_guard<std::mutex> lock(mutex);
52 static std::string name;
53 static bool did_init = false;
54 static bool valid = false;
55 if(!did_init) {
56 did_init = true;
57 char buffer[CPPTRACE_PATH_MAX + 1];
58 std::uint32_t bufferSize = sizeof buffer;
59 if(_NSGetExecutablePath(buffer, &bufferSize) == 0) {
60 name.assign(buffer, bufferSize);
61 valid = true;
62 }
63 }
64 return valid && !name.empty() ? name.c_str() : nullptr;
65 }
66 }
67 CPPTRACE_END_NAMESPACE
68
69 #elif IS_LINUX
70
71 #include <sys/types.h>
72 #include <unistd.h>
73
74 #define CPPTRACE_MAX_PATH CPPTRACE_PATH_MAX
75
76 CPPTRACE_BEGIN_NAMESPACE
77 namespace detail {
78 inline const char* program_name() {
79 static std::mutex mutex;
80 const std::lock_guard<std::mutex> lock(mutex);
81 static std::string name;
82 static bool did_init = false;
83 static bool valid = false;
84 if(!did_init) {
85 did_init = true;
86 char buffer[CPPTRACE_PATH_MAX + 1];
87 const ssize_t size = readlink("/proc/self/exe", buffer, CPPTRACE_PATH_MAX);
88 if(size == -1) {
89 return nullptr;
90 }
91 buffer[size] = 0;
92 name = buffer;
93 valid = true;
94 }
95 return valid && !name.empty() ? name.c_str() : nullptr;
96 }
97 }
98 CPPTRACE_END_NAMESPACE
99
100 #endif
101
102 #endif