Repo-Init
 
Loading...
Searching...
No Matches
Tracer.cpp
Go to the documentation of this file.
1#include "utils/Tracer.hpp"
2
3#include "Version.h"
4
5#include "client/crash_report_database.h"
6#include "client/crashpad_client.h"
7#include "client/settings.h"
8#include <spdlog/spdlog.h>
9
10#include <algorithm>
11#include <array>
12#include <fstream>
13#include <sstream>
14
15#include <sys/socket.h>
16#include <sys/stat.h>
17#include <sys/types.h>
18#include <unistd.h>
19
20constexpr int SLEEP_INTERVAL_MS = 50;
21constexpr auto CRASHPAD_RETRY_COUNT = 10;
22
24{
25 // Path to crashpad executable
26 const base::FilePath handler(_handlerPath);
27
28 // Must be writable or crashpad_handler will crash
29 const base::FilePath reportsDir(_reportPath);
30 const base::FilePath metricsDir(_reportPath);
31
32 // Initialize Crashpad database
33 auto database = crashpad::CrashReportDatabase::Initialize(reportsDir);
34 if (database == nullptr)
35 {
36 throw std::ios_base::failure("Can't initialize crash report database");
37 }
38
39 // Enable automated crash uploads
40 auto *settings = database->GetSettings();
41 if (settings == nullptr)
42 {
43 throw std::ios_base::failure("Can't get crash report database settings");
44 }
45 settings->SetUploadsEnabled(true);
46
47 // Start crash handler
48 if (!_clientHandler->StartHandler(handler, reportsDir, metricsDir, _serverPath, _serverProxy, _annotations,
49 {"--no-rate-limit"}, true, false, _attachments))
50 {
51 throw std::ios_base::failure("Can't start crash handler");
52 }
53
54 _thread = std::make_unique<std::jthread>([this](const std::stop_token &sToken) { threadFunc(sToken); });
55}
56
57void Tracer::threadFunc(const std::stop_token &stopToken) const noexcept
58{
59 int stopCounter = 0;
60 while (!stopToken.stop_requested())
61 {
62 try
63 {
64 if (!isRunning())
65 {
66 ++stopCounter;
67 if (stopCounter > CRASHPAD_RETRY_COUNT) // Give some time to restart handler
68 {
69 spdlog::info("Crashpad handler closed");
70 return;
71 }
72 }
73 if (_checkFlag)
74 {
75 _checkFlag->test_and_set();
76 }
77
78 stopCounter = 0;
79 }
80 catch (const std::exception &e)
81 {
82 spdlog::error("Crashpad failed: {}", e.what());
83 }
84 std::this_thread::sleep_for(std::chrono::milliseconds(SLEEP_INTERVAL_MS));
85 }
86}
87
88bool Tracer::checkPidIsRunning(pid_t processId) { return kill(processId, 0) == 0; }
89
91{
92 int error = 0;
93 socklen_t len = sizeof(error);
94
95 char buff = 0;
96 const int result = getsockopt(sockId, SOL_SOCKET, SO_ERROR, &error, &len);
97 return result == 0 && error == 0 && recv(sockId, &buff, 1, MSG_PEEK | MSG_DONTWAIT) != 0;
98}
99
101{
102 std::array<char, FILENAME_MAX> pathBuffer{'\0'};
103 auto bytes = readlink("/proc/self/exe", pathBuffer.data(), sizeof(pathBuffer));
104
105 auto path = std::string(pathBuffer.data(), bytes == -1 ? 0 : static_cast<size_t>(bytes));
106 auto lastDelimPos = path.find_last_of('/');
107 return (lastDelimPos == std::string::npos) ? "" : path.substr(0, lastDelimPos);
108}
109
111{
112 int sockId{-1};
113 pid_t processId{-1};
114
115 if (!crashpad::CrashpadClient::GetHandlerSocket(&sockId, &processId))
116 {
117 return false;
118 }
119
120 if (sockId >= 0 && !checkSocketIsRunning(sockId))
121 {
122 return false;
123 }
124 if (processId > 0 && !checkPidIsRunning(processId))
125 {
126 return false;
127 }
128 return true;
129}
130
131void Tracer::dumpSharedLibraryInfo(const std::string &filePath)
132{
133 // Open the output file
134 std::ofstream ofile(filePath);
135 if (!ofile.is_open())
136 {
137 throw std::invalid_argument("Can't open file: " + filePath);
138 }
139
140 // Get the shared library information
141 std::ifstream maps("/proc/self/maps");
142
143 std::string line;
144 while (std::getline(maps, line))
145 {
146 // The format of each line is: address perms offset dev inode pathname
147 // We only care about the address and the pathname, which are the first and last fields
148 std::istringstream iss(line);
149 std::string address;
150 std::string perms;
151 std::string offset;
152 std::string dev;
153 std::string inode;
154 std::string pathname;
155 iss >> address >> perms >> offset >> dev >> inode >> pathname;
156
157 // We only want the shared libraries, which have the .so extension and the read and execute permissions
158 if (pathname.find(".so") != std::string::npos && perms.find("r-x") != std::string::npos)
159 {
160 // The address field is in the form of start-end, we only need the start address
161 const std::string start = address.substr(0, address.find('-'));
162
163 // Convert the start address from hexadecimal string to unsigned long
164 const unsigned long addr = std::stoul(start, nullptr, 16);
165
166 ofile << pathname << " " << addr << '\n';
167 }
168 }
169}
170
171Tracer::Tracer(std::shared_ptr<std::atomic_flag> checkFlag, std::string serverPath, std::string serverProxy,
172 const std::string &crashpadHandlerPath, const std::string &reportPath,
173 std::vector<base::FilePath> attachments)
174 : _checkFlag(std::move(checkFlag)), _serverPath(std::move(serverPath)), _serverProxy(std::move(serverProxy)),
175 _attachments(std::move(attachments))
176{
177 auto selfDir = getSelfExecutableDir();
178
179 _handlerPath = crashpadHandlerPath.empty() ? selfDir + "/crashpad_handler" : crashpadHandlerPath;
180 _reportPath = reportPath.empty() ? selfDir : reportPath;
181 _clientHandler = std::make_unique<crashpad::CrashpadClient>();
182
183 _annotations = std::map<std::string, std::string>(
184 {{"name", PROJECT_NAME},
185 {"version", PROJECT_FULL_REVISION},
186 {"build_info", PROJECT_BUILD_DATE + std::string(" ") + PROJECT_BUILD_TIME + std::string(" ") + BUILD_TYPE},
187 {"compiler_info", COMPILER_NAME + std::string(" ") + COMPILER_VERSION}});
188
189 // Dump shared library information and add as attachment
190 dumpSharedLibraryInfo(_reportPath + "/shared_libs.txt");
191 _attachments.emplace_back(_reportPath + "/shared_libs.txt");
192
193 startHandler();
194}
195
196Tracer::~Tracer() = default;
constexpr int SLEEP_INTERVAL_MS
constexpr auto CRASHPAD_RETRY_COUNT
Definition Tracer.cpp:21
static bool checkSocketIsRunning(int sockId)
Definition Tracer.cpp:90
std::string _reportPath
Definition Tracer.hpp:19
static void dumpSharedLibraryInfo(const std::string &filePath)
Definition Tracer.cpp:131
static bool isRunning()
Definition Tracer.cpp:110
void startHandler()
Definition Tracer.cpp:23
std::unique_ptr< crashpad::CrashpadClient > _clientHandler
Definition Tracer.hpp:20
std::string _serverPath
Definition Tracer.hpp:14
std::string _serverProxy
Definition Tracer.hpp:15
std::unique_ptr< std::jthread > _thread
Definition Tracer.hpp:22
std::vector< base::FilePath > _attachments
Definition Tracer.hpp:18
std::shared_ptr< std::atomic_flag > _checkFlag
Definition Tracer.hpp:12
static std::string getSelfExecutableDir()
Definition Tracer.cpp:100
std::map< std::string, std::string > _annotations
Definition Tracer.hpp:17
void threadFunc(const std::stop_token &stopToken) const noexcept
Definition Tracer.cpp:57
std::string _handlerPath
Definition Tracer.hpp:16
Tracer(std::shared_ptr< std::atomic_flag > checkFlag, std::string serverPath="", std::string serverProxy="", const std::string &crashpadHandlerPath="", const std::string &reportPath="", std::vector< base::FilePath > attachments={})
Definition Tracer.cpp:171
static bool checkPidIsRunning(pid_t processId)
Definition Tracer.cpp:88