aboutsummaryrefslogtreecommitdiffstats
path: root/src/libs/nanotrace/nanotracehr.cpp
blob: 00062274340d66d1e6581cad94a9ffc8073a8f6a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
// Copyright (C) 2023 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only

#include "nanotracehr.h"

#include <utils/smallstringio.h>

#include <QCoreApplication>
#include <QImage>
#include <QThread>

#include <fstream>
#include <iomanip>
#include <limits>
#include <thread>

#ifdef Q_OS_UNIX
#  include <pthread.h>
#endif

namespace NanotraceHR {

namespace {

bool hasId(char phase)
{
    switch (phase) {
    case 'b':
    case 'n':
    case 'e':
        return true;
    }

    return false;
}

template<typename Id>
unsigned int getUnsignedIntegerHash(Id id)
{
    return static_cast<unsigned int>(id & 0xFFFFFFFF);
}

unsigned int getUnsignedIntegerHash(std::thread::id id)
{
    return static_cast<unsigned int>(std::hash<std::thread::id>{}(id) & 0xFFFFFFFF);
}

template<std::size_t capacity>
constexpr bool isArgumentValid(const StaticString<capacity> &string)
{
    return string.isValid() && string.size();
}

template<typename String>
constexpr bool isArgumentValid(const String &string)
{
    return string.size();
}

template<typename TraceEvent>
void printEvent(std::ostream &out, const TraceEvent &event, qint64 processId, std::thread::id threadId)
{
    out << R"({"ph":")" << event.type << R"(","name":")" << event.name << R"(","cat":")"
        << event.category << R"(","ts":)"
        << static_cast<double>(event.time.time_since_epoch().count()) / 1000 << R"(,"pid":)"
        << getUnsignedIntegerHash(processId) << R"(,"tid":)" << getUnsignedIntegerHash(threadId);

    if (event.type == 'X')
        out << R"(,"dur":)" << static_cast<double>(event.duration.count()) / 1000;

    if (hasId(event.type))
        out << R"(,"id":)" << event.id;

    if (event.bindId) {
        out << R"(,"bind_id":)" << event.bindId;
        if (event.flow & IsFlow::Out)
            out << R"(,"flow_out":true)";
        if (event.flow & IsFlow::In)
            out << R"(,"flow_in":true)";
    }

    if (isArgumentValid(event.arguments)) {
        out << R"(,"args":)" << event.arguments;
    }

    out << "}";
}

void writeMetaEvent(TraceFile<Tracing::IsEnabled> &file, std::string_view key, std::string_view value)
{
    std::lock_guard lock{file.fileMutex};
    auto &out = file.out;

    if (out.is_open()) {
        file.out << R"({"name":")" << key << R"(","ph":"M", "pid":)"
                 << getUnsignedIntegerHash(QCoreApplication::applicationPid()) << R"(,"tid":)"
                 << getUnsignedIntegerHash(std::this_thread::get_id()) << R"(,"args":{"name":")"
                 << value << R"("}})"
                 << ",\n";
    }
}

std::string getThreadName()
{
    std::array<char, 200> buffer;
    buffer[0] = 0;
#ifdef Q_OS_UNIX
    auto rc = pthread_getname_np(pthread_self(), buffer.data(), buffer.size());
    if (rc != 0)
        return {};

#endif

    return buffer.data();
}

} // namespace

template<typename String>
void convertToString(String &string, const QImage &image)
{
    using namespace std::string_view_literals;
    auto dict = dictonary(keyValue("width", image.width()),
                          keyValue("height", image.height()),
                          keyValue("bytes", image.sizeInBytes()),
                          keyValue("has alpha channel", image.hasAlphaChannel()),
                          keyValue("is color", !image.isGrayscale()),
                          keyValue("pixel format",
                                   dictonary(keyValue("bits per pixel",
                                                      image.pixelFormat().bitsPerPixel()),
                                             keyValue("byte order",
                                                      [&] {
                                                          if (image.pixelFormat().byteOrder()
                                                              == QPixelFormat::BigEndian)
                                                              return "big endian"sv;
                                                          else
                                                              return "little endian"sv;
                                                      }),
                                             keyValue("premultiplied", [&] {
                                                 if (image.pixelFormat().premultiplied()
                                                     == QPixelFormat::Premultiplied)
                                                     return "premultiplied"sv;
                                                 else
                                                     return "alpha premultiplied"sv;
                                             }))));

    convertToString(string, dict);
}

template NANOTRACE_EXPORT void convertToString(ArgumentsString &string, const QImage &image);

template<typename TraceEvent>
void flushEvents(const Utils::span<TraceEvent> events,
                 std::thread::id threadId,
                 EnabledEventQueue<TraceEvent> &eventQueue)
{
    if (events.empty())
        return;

    std::lock_guard lock{eventQueue.file.fileMutex};
    auto &out = eventQueue.file.out;

    if (out.is_open()) {
        auto processId = QCoreApplication::applicationPid();
        for (const auto &event : events) {
            printEvent(out, event, processId, threadId);
            out << ",\n";
        }
    }
}

template NANOTRACE_EXPORT void flushEvents(const Utils::span<StringViewTraceEvent> events,
                                           std::thread::id threadId,
                                           EnabledEventQueue<StringViewTraceEvent> &eventQueue);
template NANOTRACE_EXPORT void flushEvents(const Utils::span<StringTraceEvent> events,
                                           std::thread::id threadId,
                                           EnabledEventQueue<StringTraceEvent> &eventQueue);
template NANOTRACE_EXPORT void flushEvents(
    const Utils::span<StringViewWithStringArgumentsTraceEvent> events,
    std::thread::id threadId,
    EnabledEventQueue<StringViewWithStringArgumentsTraceEvent> &eventQueue);

void openFile(EnabledTraceFile &file)
{
    std::lock_guard lock{file.fileMutex};

    if (file.out = std::ofstream{file.filePath, std::ios::trunc}; file.out.good()) {
        file.out << std::fixed << std::setprecision(3) << R"({"traceEvents": [)";
        file.out << R"({"name":"process_name","ph":"M", "pid":)"
                 << QCoreApplication::applicationPid() << R"(,"args":{"name":"QtCreator"}})"
                 << ",\n";
    }
}

void finalizeFile(EnabledTraceFile &file)
{
    std::lock_guard lock{file.fileMutex};
    auto &out = file.out;

    if (out.is_open()) {
        out.seekp(-2, std::ios_base::cur); // removes last comma and new line
        out << R"(],"displayTimeUnit":"ns","otherData":{"version": "Qt Creator )";
        out << QCoreApplication::applicationVersion().toStdString();
        out << R"("}})";
        out.close();
    }
}

template<typename TraceEvent>
void flushInThread(EnabledEventQueue<TraceEvent> &eventQueue)
{
    if (eventQueue.file.processing.valid())
        eventQueue.file.processing.wait();

    auto flush = [&](const Utils::span<TraceEvent> &events, std::thread::id threadId) {
        flushEvents(events, threadId, eventQueue);
    };

    eventQueue.file.processing = std::async(std::launch::async,
                                            flush,
                                            eventQueue.currentEvents.subspan(0, eventQueue.eventsIndex),
                                            eventQueue.threadId);
    eventQueue.currentEvents = eventQueue.currentEvents.data() == eventQueue.eventsOne.data()
                                   ? eventQueue.eventsTwo
                                   : eventQueue.eventsOne;
    eventQueue.eventsIndex = 0;
}

template NANOTRACE_EXPORT void flushInThread(EnabledEventQueue<StringViewTraceEvent> &eventQueue);
template NANOTRACE_EXPORT void flushInThread(EnabledEventQueue<StringTraceEvent> &eventQueue);
template NANOTRACE_EXPORT void flushInThread(
    EnabledEventQueue<StringViewWithStringArgumentsTraceEvent> &eventQueue);

template<typename TraceEvent>
EventQueue<TraceEvent, Tracing::IsEnabled>::EventQueue(EnabledTraceFile &file)
    : file{file}
    , threadId{std::this_thread::get_id()}
{
    setEventsSpans(*eventArrayOne.get(), *eventArrayTwo.get());
    Internal::EventQueueTracker<TraceEvent>::get().addQueue(this);
    if (auto thread = QThread::currentThread()) {
        auto name = getThreadName();
        if (name.size()) {
            writeMetaEvent(file, "thread_name", name);
        }
    }
}

template<typename TraceEvent>
EventQueue<TraceEvent, Tracing::IsEnabled>::~EventQueue()
{
    Internal::EventQueueTracker<TraceEvent>::get().removeQueue(this);

    flush();
}

template<typename TraceEvent>
void EventQueue<TraceEvent, Tracing::IsEnabled>::setEventsSpans(TraceEventsSpan eventsSpanOne,
                                                                TraceEventsSpan eventsSpanTwo)
{
    eventsOne = eventsSpanOne;
    eventsTwo = eventsSpanTwo;
    currentEvents = eventsSpanOne;
}

template<typename TraceEvent>
void EventQueue<TraceEvent, Tracing::IsEnabled>::flush()
{
    std::lock_guard lock{mutex};
    if (isEnabled == IsEnabled::Yes && eventsIndex > 0) {
        flushEvents(currentEvents.subspan(0, eventsIndex), threadId, *this);
        eventsIndex = 0;
    }
}

template class NANOTRACE_EXPORT_TEMPLATE EventQueue<StringViewTraceEvent, Tracing::IsEnabled>;
template class NANOTRACE_EXPORT_TEMPLATE EventQueue<StringTraceEvent, Tracing::IsEnabled>;
template class NANOTRACE_EXPORT_TEMPLATE
    EventQueue<StringViewWithStringArgumentsTraceEvent, Tracing::IsEnabled>;

} // namespace NanotraceHR