Line data Source code
1 : /* Copyright (C) 2026 Wildfire Games.
2 : *
3 : * Permission is hereby granted, free of charge, to any person obtaining
4 : * a copy of this software and associated documentation files (the
5 : * "Software"), to deal in the Software without restriction, including
6 : * without limitation the rights to use, copy, modify, merge, publish,
7 : * distribute, sublicense, and/or sell copies of the Software, and to
8 : * permit persons to whom the Software is furnished to do so, subject to
9 : * the following conditions:
10 : *
11 : * The above copyright notice and this permission notice shall be included
12 : * in all copies or substantial portions of the Software.
13 : *
14 : * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15 : * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16 : * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
17 : * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
18 : * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
19 : * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
20 : * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21 : */
22 :
23 : #include "precompiled.h"
24 :
25 : #include "Profiler2.h"
26 :
27 : #include "lib/code_generation.h"
28 : #include "lib/os_path.h"
29 : #include "lib/path.h"
30 : #include "network/HttpServer.h"
31 : #include "ps/CLogger.h"
32 : #include "ps/CStr.h"
33 : #include "ps/ConfigDB.h"
34 : #include "ps/Future.h"
35 : #include "ps/Profiler2GPU.h"
36 : #include "ps/Pyrogenesis.h"
37 : #include "ps/TaskManager.h"
38 :
39 : #include <algorithm>
40 : #include <cstdio>
41 : #include <fmt/format.h>
42 : #include <fstream>
43 : #include <functional>
44 : #include <httplib.h>
45 : #include <iomanip>
46 : #include <map>
47 : #include <set>
48 : #include <sstream>
49 : #include <tuple>
50 : #include <unordered_map>
51 : #include <utility>
52 : #include <variant>
53 :
54 : CProfiler2 g_Profiler2;
55 :
56 : const size_t CProfiler2::MAX_ATTRIBUTE_LENGTH = 256;
57 :
58 : // TODO: what's a good size?
59 : const size_t CProfiler2::BUFFER_SIZE = 4 * 1024 * 1024;
60 :
61 : // A human-recognisable pattern (for debugging) followed by random bytes (for uniqueness)
62 : const std::uint8_t CProfiler2::RESYNC_MAGIC[8] = {0x11, 0x22, 0x33, 0x44, 0xf4, 0x93, 0xbe, 0x15};
63 :
64 : thread_local CProfiler2::ThreadStorage* CProfiler2::m_CurrentStorage = nullptr;
65 :
66 0 : CProfiler2::CProfiler2() :
67 0 : m_Initialised{false}, m_FrameNumber{0}, m_HttpServer{nullptr}, m_HttpServerThread{}, m_GPU{nullptr}
68 : {
69 0 : }
70 :
71 1 : CProfiler2::~CProfiler2()
72 : {
73 1 : if (m_Initialised)
74 0 : Shutdown();
75 1 : }
76 :
77 1 : void CProfiler2::Initialise()
78 : {
79 1 : ENSURE(!m_Initialised);
80 1 : m_Initialised = true;
81 :
82 1 : RegisterCurrentThread("main");
83 1 : }
84 :
85 0 : void CProfiler2::InitialiseGPU()
86 : {
87 0 : ENSURE(!m_GPU);
88 0 : m_GPU = new CProfiler2GPU(*this);
89 0 : }
90 :
91 0 : void CProfiler2::EnableHTTP()
92 : {
93 0 : ENSURE(m_Initialised);
94 0 : LOGMESSAGERENDER("Starting profiler2 HTTP server");
95 :
96 0 : std::lock_guard lock{m_Mutex};
97 :
98 : // Ignore multiple enablings
99 0 : if (m_HttpServer)
100 0 : return;
101 :
102 0 : m_HttpServer = PS::Net::createHttpServer();
103 :
104 0 : m_HttpServer->Get("/download", [this](const httplib::Request &, httplib::Response &) {
105 0 : SaveToFile();
106 : });
107 :
108 0 : m_HttpServer->Get("/overview", [this](const httplib::Request &, httplib::Response &res) {
109 0 : std::stringstream stream;
110 0 : ConstructJSONOverview(stream);
111 0 : res.set_content(stream.str(), "application/json");
112 0 : });
113 :
114 0 : m_HttpServer->Get("/query", [this](const httplib::Request &req, httplib::Response &res) {
115 0 : if (!req.has_param("thread"))
116 : {
117 0 : res.set_content("Request \"query\" needs parameter \"thread\"", "text/plain");
118 0 : res.status = httplib::StatusCode::BadRequest_400;
119 0 : return;
120 : }
121 :
122 0 : std::string thread = req.get_param_value("thread");
123 0 : std::stringstream stream;
124 0 : ConstructJSONResponse(stream, thread);
125 0 : res.set_content(stream.str(), "application/json");
126 0 : });
127 :
128 0 : m_HttpServer->set_post_routing_handler([](const httplib::Request&, httplib::Response& res) {
129 : // TODO: Not ideal for security reasons
130 0 : res.set_header("Access-Control-Allow-Origin", "*");
131 0 : });
132 :
133 0 : m_HttpServerThread = std::thread([this](){
134 0 : using namespace std::literals;
135 0 : const int listeningPort{CConfigDB::GetIfInitialised("profiler2.server.port", 8000)};
136 0 : const std::string listeningServer{CConfigDB::GetIfInitialised("profiler2.server", "127.0.0.1"s)};
137 :
138 0 : if (!m_HttpServer->listen(listeningServer, listeningPort))
139 : {
140 0 : LOGERROR("Failed to start http server");
141 : }
142 0 : });
143 0 : }
144 :
145 0 : void CProfiler2::EnableGPU()
146 : {
147 0 : ENSURE(m_Initialised);
148 0 : if (!m_GPU)
149 : {
150 0 : LOGMESSAGERENDER("Starting profiler2 GPU mode");
151 0 : InitialiseGPU();
152 : }
153 0 : }
154 :
155 0 : void CProfiler2::ShutdownGPU()
156 : {
157 0 : LOGMESSAGERENDER("Shutting down profiler2 GPU mode");
158 0 : SAFE_DELETE(m_GPU);
159 0 : }
160 :
161 0 : void CProfiler2::ShutDownHTTP()
162 : {
163 0 : LOGMESSAGERENDER("Shutting down profiler2 HTTP server");
164 0 : std::lock_guard lock{m_Mutex};
165 :
166 0 : if (!m_HttpServer)
167 0 : return;
168 :
169 0 : m_HttpServer->stop();
170 0 : if(m_HttpServerThread.joinable())
171 0 : m_HttpServerThread.join();
172 0 : m_HttpServer.reset();
173 0 : }
174 :
175 0 : void CProfiler2::Toggle()
176 : {
177 0 : LOGMESSAGERENDER("Toggle profiler http");
178 0 : if (m_GPU && m_HttpServer)
179 : {
180 0 : ShutdownGPU();
181 0 : ShutDownHTTP();
182 : }
183 0 : else if (!m_GPU && !m_HttpServer)
184 : {
185 0 : EnableGPU();
186 0 : EnableHTTP();
187 : }
188 : else
189 : {
190 0 : LOGMESSAGERENDER("Toggle profile bad state!");
191 : }
192 0 : }
193 :
194 1 : void CProfiler2::Shutdown()
195 : {
196 1 : ENSURE(m_Initialised);
197 :
198 1 : ENSURE(!m_GPU); // must shutdown GPU before profiler
199 1 : ENSURE(!m_HttpServer); // must shutdown HTTP server before profiler
200 :
201 : // the destructor is not called for the main thread
202 : // we have to call it manually to avoid memory leaks
203 1 : ENSURE(Threading::IsMainThread());
204 1 : m_Initialised = false;
205 1 : }
206 :
207 0 : void CProfiler2::RecordGPUFrameStart(Renderer::Backend::IDeviceCommandContext* deviceCommandContext)
208 : {
209 0 : if (m_GPU)
210 0 : m_GPU->FrameStart(deviceCommandContext);
211 0 : }
212 :
213 0 : void CProfiler2::RecordGPUFrameEnd(Renderer::Backend::IDeviceCommandContext* deviceCommandContext)
214 : {
215 0 : if (m_GPU)
216 0 : m_GPU->FrameEnd(deviceCommandContext);
217 0 : }
218 :
219 0 : void CProfiler2::RecordGPURegionEnter(Renderer::Backend::IDeviceCommandContext* deviceCommandContext, const char* id)
220 : {
221 0 : if (m_GPU)
222 0 : m_GPU->RegionEnter(deviceCommandContext, id);
223 0 : }
224 :
225 0 : void CProfiler2::RecordGPURegionLeave(Renderer::Backend::IDeviceCommandContext* deviceCommandContext, const char* id)
226 : {
227 0 : if (m_GPU)
228 0 : m_GPU->RegionLeave(deviceCommandContext, id);
229 0 : }
230 :
231 4 : void CProfiler2::RegisterCurrentThread(const std::string& name)
232 : {
233 4 : ENSURE(m_Initialised);
234 :
235 : // Must not register a thread more than once.
236 4 : ENSURE(m_CurrentStorage == nullptr);
237 :
238 4 : m_CurrentStorage = new ThreadStorage(*this, name);
239 4 : AddThreadStorage(m_CurrentStorage);
240 :
241 4 : RecordSyncMarker();
242 4 : RecordEvent("thread start");
243 4 : }
244 :
245 4 : void CProfiler2::AddThreadStorage(ThreadStorage* storage)
246 : {
247 4 : std::lock_guard<std::mutex> lock(m_Mutex);
248 4 : m_Threads.push_back(std::unique_ptr<ThreadStorage>(storage));
249 4 : }
250 :
251 0 : void CProfiler2::RemoveThreadStorage(ThreadStorage* storage)
252 : {
253 0 : std::lock_guard<std::mutex> lock(m_Mutex);
254 0 : m_Threads.erase(std::find_if(m_Threads.begin(), m_Threads.end(), [storage](const std::unique_ptr<ThreadStorage>& s) { return s.get() == storage; }));
255 0 : }
256 :
257 4 : CProfiler2::ThreadStorage::ThreadStorage(CProfiler2& profiler, const std::string& name) :
258 4 : m_Profiler(profiler), m_Name(name), m_LastTime(timer_Time())
259 : {
260 4 : m_Buffer = new std::uint8_t[BUFFER_SIZE];
261 4 : memset(m_Buffer, ITEM_NOP, BUFFER_SIZE);
262 4 : }
263 :
264 4 : CProfiler2::ThreadStorage::~ThreadStorage()
265 : {
266 4 : delete[] m_Buffer;
267 4 : }
268 :
269 24357 : void CProfiler2::ThreadStorage::Write(EItem type, const void* item, std::uint32_t itemSize)
270 : {
271 : // See RingBufferSpan for comments on synchronisation
272 :
273 24357 : std::uint32_t size = 1 + itemSize;
274 24357 : std::uint32_t start{m_ValidRange.begin.load()};
275 24357 : if (start + size > BUFFER_SIZE)
276 : {
277 : // The remainder of the buffer is too small - fill the rest
278 : // with NOPs then start from offset 0, so we don't have to
279 : // bother splitting the real item across the end of the buffer
280 :
281 0 : m_ValidRange.begin.store(size);
282 :
283 0 : memset(m_Buffer + start, 0, BUFFER_SIZE - start);
284 0 : start = 0;
285 : }
286 : else
287 : {
288 24357 : m_ValidRange.begin.store(start + size);
289 : }
290 :
291 24357 : m_Buffer[start] = static_cast<std::uint8_t>(type);
292 24357 : memcpy(&m_Buffer[start + 1], item, itemSize);
293 :
294 24357 : m_ValidRange.end.store(start + size);
295 24357 : }
296 :
297 0 : std::string CProfiler2::ThreadStorage::GetBuffer()
298 : {
299 : // Called from an arbitrary thread (not the one writing to the buffer).
300 : //
301 : // See comments on RingBufferSpan.
302 :
303 0 : std::unique_ptr<std::uint8_t[]> buffer{std::make_unique<std::uint8_t[]>(BUFFER_SIZE)};
304 :
305 0 : const std::uint32_t pos1{m_ValidRange.end.load()};
306 :
307 0 : memcpy(buffer.get(), m_Buffer, BUFFER_SIZE);
308 :
309 0 : const std::uint32_t pos0{m_ValidRange.begin.load()};
310 :
311 : // The range [pos1, pos0) modulo BUFFER_SIZE is invalid, so concatenate the rest of the buffer
312 :
313 0 : if (pos1 <= pos0) // invalid range is in the middle of the buffer
314 0 : return std::string(buffer.get()+pos0, buffer.get()+BUFFER_SIZE) + std::string(buffer.get(), buffer.get()+pos1);
315 : else // invalid wrap is wrapped around the end/start buffer
316 0 : return std::string(buffer.get()+pos0, buffer.get()+pos1);
317 0 : }
318 :
319 349 : void CProfiler2::ThreadStorage::RecordAttribute(const char* fmt, va_list argp)
320 : {
321 349 : char buffer[MAX_ATTRIBUTE_LENGTH + 4] = {0}; // first 4 bytes are used for storing length
322 349 : int len = vsnprintf(buffer + 4, MAX_ATTRIBUTE_LENGTH - 1, fmt, argp); // subtract 1 from length to make MSVC vsnprintf safe
323 : // (Don't use vsprintf_s because it treats overflow as fatal)
324 :
325 : // Terminate the string if the printing was truncated
326 349 : if (len < 0 || len >= (int)MAX_ATTRIBUTE_LENGTH - 1)
327 : {
328 0 : strncpy(buffer + 4 + MAX_ATTRIBUTE_LENGTH - 4, "...", 4);
329 0 : len = MAX_ATTRIBUTE_LENGTH - 1; // excluding null terminator
330 : }
331 :
332 : // Store the length in the buffer
333 349 : memcpy(buffer, &len, sizeof(len));
334 :
335 349 : Write(ITEM_ATTRIBUTE, buffer, 4 + len);
336 349 : }
337 :
338 : // this flattens the stack, use it sensibly
339 0 : void rewriteBuffer(std::uint8_t* buffer, std::uint32_t& bufferSize)
340 : {
341 0 : double startTime = timer_Time();
342 :
343 0 : std::uint32_t size = bufferSize;
344 0 : std::uint32_t readPos = 0;
345 :
346 0 : double initialTime = -1;
347 0 : double total_time = -1;
348 0 : const char* regionName;
349 0 : std::set<std::string> topLevelArgs;
350 :
351 0 : using infoPerType = std::tuple<const char*, double, std::set<std::string> >;
352 0 : using timeByTypeMap = std::unordered_map<std::string, infoPerType>;
353 :
354 0 : timeByTypeMap timeByType;
355 0 : std::vector<double> last_time_stack;
356 0 : std::vector<const char*> last_names;
357 :
358 : // never too many hacks
359 0 : std::string current_attribute = "";
360 0 : std::map<std::string, double> time_per_attribute;
361 :
362 : // Let's read the first event
363 0 : {
364 0 : std::uint8_t type = buffer[readPos];
365 0 : ++readPos;
366 0 : if (type != CProfiler2::ITEM_ENTER)
367 : {
368 0 : debug_warn("Profiler2: Condensing a region should run into ITEM_ENTER first");
369 0 : return; // do nothing
370 : }
371 0 : CProfiler2::SItem_dt_id item;
372 0 : memcpy(&item, buffer + readPos, sizeof(item));
373 0 : readPos += sizeof(item);
374 :
375 0 : regionName = item.id;
376 0 : last_names.push_back(item.id);
377 0 : initialTime = (double)item.dt;
378 : }
379 :
380 : // Read subsequent events. Flatten hierarchy because it would get too complicated otherwise.
381 : // To make sure time doesn't bloat, subtract time from nested events
382 0 : while (readPos < size)
383 : {
384 0 : std::uint8_t type = buffer[readPos];
385 0 : ++readPos;
386 :
387 0 : switch (type)
388 : {
389 : case CProfiler2::ITEM_NOP:
390 : {
391 : // ignore
392 : break;
393 : }
394 0 : case CProfiler2::ITEM_SYNC:
395 0 : {
396 0 : debug_warn("Aggregated regions should not be used across frames");
397 : // still try to act sane
398 0 : readPos += sizeof(double);
399 0 : readPos += sizeof(CProfiler2::RESYNC_MAGIC);
400 0 : break;
401 : }
402 0 : case CProfiler2::ITEM_EVENT:
403 0 : {
404 : // skip for now
405 0 : readPos += sizeof(CProfiler2::SItem_dt_id);
406 0 : break;
407 : }
408 0 : case CProfiler2::ITEM_ENTER:
409 0 : {
410 0 : CProfiler2::SItem_dt_id item;
411 0 : memcpy(&item, buffer + readPos, sizeof(item));
412 0 : readPos += sizeof(item);
413 0 : last_time_stack.push_back((double)item.dt);
414 0 : last_names.push_back(item.id);
415 0 : current_attribute = "";
416 0 : break;
417 : }
418 0 : case CProfiler2::ITEM_LEAVE:
419 0 : {
420 0 : float item_time;
421 0 : memcpy(&item_time, buffer + readPos, sizeof(float));
422 0 : readPos += sizeof(float);
423 :
424 0 : if (last_names.empty())
425 : {
426 : // we somehow lost the first entry in the process
427 0 : debug_warn("Invalid buffer for condensing");
428 : }
429 0 : const char* item_name = last_names.back();
430 0 : last_names.pop_back();
431 :
432 0 : if (last_time_stack.empty())
433 : {
434 : // this is the leave for the whole scope
435 0 : total_time = (double)item_time;
436 0 : break;
437 : }
438 0 : double time = (double)item_time - last_time_stack.back();
439 :
440 0 : std::string name = std::string(item_name);
441 0 : timeByTypeMap::iterator TimeForType = timeByType.find(name);
442 0 : if (TimeForType == timeByType.end())
443 : {
444 : // keep reference to the original char pointer to make sure we don't break things down the line
445 0 : std::get<0>(timeByType[name]) = item_name;
446 0 : std::get<1>(timeByType[name]) = 0;
447 : }
448 0 : std::get<1>(timeByType[name]) += time;
449 :
450 0 : last_time_stack.pop_back();
451 : // if we were nested, subtract our time from the below scope by making it look like it starts later
452 0 : if (!last_time_stack.empty())
453 0 : last_time_stack.back() += time;
454 :
455 0 : if (!current_attribute.empty())
456 : {
457 0 : time_per_attribute[current_attribute] += time;
458 : }
459 :
460 0 : break;
461 : }
462 0 : case CProfiler2::ITEM_ATTRIBUTE:
463 0 : {
464 : // skip for now
465 0 : std::uint32_t len;
466 0 : memcpy(&len, buffer + readPos, sizeof(len));
467 0 : ENSURE(len <= CProfiler2::MAX_ATTRIBUTE_LENGTH);
468 0 : readPos += sizeof(len);
469 :
470 0 : char message[CProfiler2::MAX_ATTRIBUTE_LENGTH] = {0};
471 0 : memcpy(&message[0], buffer + readPos, std::min(size_t(len), CProfiler2::MAX_ATTRIBUTE_LENGTH));
472 0 : CStr mess = CStr((const char*)message, len);
473 0 : if (!last_names.empty())
474 : {
475 0 : timeByTypeMap::iterator it = timeByType.find(std::string(last_names.back()));
476 0 : if (it == timeByType.end())
477 0 : topLevelArgs.insert(mess);
478 : else
479 0 : std::get<2>(timeByType[std::string(last_names.back())]).insert(mess);
480 : }
481 0 : readPos += len;
482 0 : current_attribute = mess;
483 0 : break;
484 : }
485 0 : default:
486 0 : debug_warn(L"Invalid profiler item when condensing buffer");
487 0 : continue;
488 0 : }
489 : }
490 :
491 : // rewrite the buffer
492 : // what we rewrite will always be smaller than the current buffer's size
493 0 : std::uint32_t writePos = 0;
494 0 : double curTime = initialTime;
495 : // the region enter
496 0 : {
497 0 : CProfiler2::SItem_dt_id item = { (float)curTime, regionName };
498 0 : buffer[writePos] = static_cast<std::uint8_t>(CProfiler2::ITEM_ENTER);
499 0 : memcpy(buffer + writePos + 1, &item, sizeof(item));
500 0 : writePos += sizeof(item) + 1;
501 : // add a nanosecond for sanity
502 0 : curTime += 0.000001;
503 : }
504 : // sub-events, aggregated
505 0 : for (const std::pair<const std::string, infoPerType>& type : timeByType)
506 : {
507 0 : CProfiler2::SItem_dt_id item = { (float)curTime, std::get<0>(type.second) };
508 0 : buffer[writePos] = static_cast<std::uint8_t>(CProfiler2::ITEM_ENTER);
509 0 : memcpy(buffer + writePos + 1, &item, sizeof(item));
510 0 : writePos += sizeof(item) + 1;
511 :
512 : // write relevant attributes if present
513 0 : for (const std::string& attrib : std::get<2>(type.second))
514 : {
515 0 : buffer[writePos] = static_cast<std::uint8_t>(CProfiler2::ITEM_ATTRIBUTE);
516 0 : writePos++;
517 0 : std::string basic = attrib;
518 0 : std::map<std::string, double>::iterator time_attrib = time_per_attribute.find(attrib);
519 0 : if (time_attrib != time_per_attribute.end())
520 0 : basic = fmt::format("{} {}us", basic, 1000000 * time_attrib->second);
521 :
522 0 : std::uint32_t length = static_cast<std::uint32_t>(basic.size());
523 0 : memcpy(buffer + writePos, &length, sizeof(length));
524 0 : writePos += sizeof(length);
525 0 : memcpy(buffer + writePos, basic.c_str(), length);
526 0 : writePos += length;
527 0 : }
528 :
529 0 : curTime += std::get<1>(type.second);
530 :
531 0 : float leave_time = (float)curTime;
532 0 : buffer[writePos] = static_cast<std::uint8_t>(CProfiler2::ITEM_LEAVE);
533 0 : memcpy(buffer + writePos + 1, &leave_time, sizeof(float));
534 0 : writePos += sizeof(float) + 1;
535 : }
536 : // Time of computation
537 0 : {
538 0 : CProfiler2::SItem_dt_id item = { (float)curTime, "CondenseBuffer" };
539 0 : buffer[writePos] = static_cast<std::uint8_t>(CProfiler2::ITEM_ENTER);
540 0 : memcpy(buffer + writePos + 1, &item, sizeof(item));
541 0 : writePos += sizeof(item) + 1;
542 : }
543 0 : {
544 0 : float time_out = (float)(curTime + timer_Time() - startTime);
545 0 : buffer[writePos] = static_cast<std::uint8_t>(CProfiler2::ITEM_LEAVE);
546 0 : memcpy(buffer + writePos + 1, &time_out, sizeof(float));
547 0 : writePos += sizeof(float) + 1;
548 : // add a nanosecond for sanity
549 0 : curTime += 0.000001;
550 : }
551 :
552 : // the region leave
553 0 : {
554 0 : if (total_time < 0)
555 : {
556 0 : total_time = curTime + 0.000001;
557 :
558 0 : buffer[writePos] = static_cast<std::uint8_t>(CProfiler2::ITEM_ATTRIBUTE);
559 0 : writePos++;
560 0 : std::uint32_t length = sizeof("buffer overflow");
561 0 : memcpy(buffer + writePos, &length, sizeof(length));
562 0 : writePos += sizeof(length);
563 0 : memcpy(buffer + writePos, "buffer overflow", length);
564 0 : writePos += length;
565 : }
566 : else if (total_time < curTime)
567 : {
568 : // this seems to happen on rare occasions.
569 0 : curTime = total_time;
570 : }
571 0 : float leave_time = (float)total_time;
572 0 : buffer[writePos] = static_cast<std::uint8_t>(CProfiler2::ITEM_LEAVE);
573 0 : memcpy(buffer + writePos + 1, &leave_time, sizeof(float));
574 0 : writePos += sizeof(float) + 1;
575 : }
576 0 : bufferSize = writePos;
577 0 : }
578 :
579 0 : void CProfiler2::ConstructJSONOverview(std::ostream& stream)
580 : {
581 0 : PROFILE2("CProfiler2::ConstructJSONOverview");
582 :
583 0 : std::lock_guard<std::mutex> lock(m_Mutex);
584 :
585 0 : stream << "{\"threads\":[";
586 0 : bool first_time = true;
587 0 : for (std::unique_ptr<ThreadStorage>& storage : m_Threads)
588 : {
589 0 : if (!first_time)
590 0 : stream << ",";
591 0 : stream << "{\"name\":\"" << CStr(storage->GetName()).EscapeToPrintableASCII() << "\"}";
592 0 : first_time = false;
593 : }
594 0 : stream << "]}";
595 0 : }
596 :
597 : /**
598 : * Given a buffer and a visitor class (with functions OnEvent, OnEnter, OnLeave, OnAttribute),
599 : * calls the visitor for every item in the buffer.
600 : */
601 : template<typename V>
602 0 : void RunBufferVisitor(const std::string& buffer, V& visitor)
603 : {
604 0 : PROFILE2("Profiler2 RunBufferVisitor");
605 :
606 : // The buffer doesn't necessarily start at the beginning of an item
607 : // (we just grabbed it from some arbitrary point in the middle),
608 : // so scan forwards until we find a sync marker.
609 : // (This is probably pretty inefficient.)
610 :
611 0 : std::uint32_t realStart = static_cast<std::uint32_t>(-1); // the start point decided by the scan algorithm
612 :
613 0 : for (std::uint32_t start = 0; start + 1 + sizeof(CProfiler2::RESYNC_MAGIC) <= buffer.length();
614 : ++start)
615 : {
616 0 : if (buffer[start] == CProfiler2::ITEM_SYNC
617 0 : && memcmp(buffer.c_str() + start + 1, &CProfiler2::RESYNC_MAGIC, sizeof(CProfiler2::RESYNC_MAGIC)) == 0)
618 : {
619 : realStart = start;
620 : break;
621 : }
622 : }
623 :
624 0 : ENSURE(realStart != static_cast<std::uint32_t>(-1)); // we should have found a sync point somewhere in the buffer
625 :
626 0 : std::uint32_t pos = realStart; // the position as we step through the buffer
627 :
628 0 : double lastTime = -1;
629 : // set to non-negative by EVENT_SYNC; we ignore all items before that
630 : // since we can't compute their absolute times
631 :
632 0 : while (pos < buffer.length())
633 : {
634 0 : std::uint8_t type = buffer[pos];
635 0 : ++pos;
636 :
637 0 : switch (type)
638 : {
639 : case CProfiler2::ITEM_NOP:
640 : {
641 : // ignore
642 : break;
643 : }
644 0 : case CProfiler2::ITEM_SYNC:
645 : {
646 : std::uint8_t magic[sizeof(CProfiler2::RESYNC_MAGIC)];
647 : double t;
648 0 : memcpy(magic, buffer.c_str()+pos, ARRAY_SIZE(magic));
649 0 : ENSURE(memcmp(magic, &CProfiler2::RESYNC_MAGIC, sizeof(CProfiler2::RESYNC_MAGIC)) == 0);
650 0 : pos += sizeof(CProfiler2::RESYNC_MAGIC);
651 0 : memcpy(&t, buffer.c_str()+pos, sizeof(t));
652 0 : pos += sizeof(t);
653 0 : lastTime = t;
654 0 : visitor.OnSync(lastTime);
655 : break;
656 : }
657 0 : case CProfiler2::ITEM_EVENT:
658 : {
659 : CProfiler2::SItem_dt_id item;
660 0 : memcpy(&item, buffer.c_str()+pos, sizeof(item));
661 0 : pos += sizeof(item);
662 0 : if (lastTime >= 0)
663 : {
664 0 : visitor.OnEvent(lastTime + (double)item.dt, item.id);
665 : }
666 : break;
667 : }
668 0 : case CProfiler2::ITEM_ENTER:
669 : {
670 : CProfiler2::SItem_dt_id item;
671 0 : memcpy(&item, buffer.c_str()+pos, sizeof(item));
672 0 : pos += sizeof(item);
673 0 : if (lastTime >= 0)
674 : {
675 0 : visitor.OnEnter(lastTime + (double)item.dt, item.id);
676 : }
677 : break;
678 : }
679 0 : case CProfiler2::ITEM_LEAVE:
680 : {
681 : float leave_time;
682 0 : memcpy(&leave_time, buffer.c_str() + pos, sizeof(float));
683 0 : pos += sizeof(float);
684 0 : if (lastTime >= 0)
685 : {
686 0 : visitor.OnLeave(lastTime + (double)leave_time);
687 : }
688 : break;
689 : }
690 0 : case CProfiler2::ITEM_ATTRIBUTE:
691 : {
692 : std::uint32_t len;
693 0 : memcpy(&len, buffer.c_str()+pos, sizeof(len));
694 0 : ENSURE(len <= CProfiler2::MAX_ATTRIBUTE_LENGTH);
695 0 : pos += sizeof(len);
696 0 : std::string attribute(buffer.c_str()+pos, buffer.c_str()+pos+len);
697 0 : pos += len;
698 0 : if (lastTime >= 0)
699 : {
700 0 : visitor.OnAttribute(attribute);
701 : }
702 : break;
703 0 : }
704 : default:
705 0 : debug_warn(L"Invalid profiler item when parsing buffer");
706 : return;
707 : }
708 : }
709 0 : };
710 :
711 : /**
712 : * Visitor class that dumps events as JSON.
713 : * TODO: this is pretty inefficient (in implementation and in output format).
714 : */
715 : struct BufferVisitor_Dump
716 : {
717 : NONCOPYABLE(BufferVisitor_Dump);
718 : public:
719 0 : BufferVisitor_Dump(std::ostream& stream) : m_Stream(stream)
720 : {
721 : }
722 :
723 0 : void OnSync(double /*time*/)
724 : {
725 : // Split the array of items into an array of array (arbitrarily splitting
726 : // around the sync points) to avoid array-too-large errors in JSON decoders
727 0 : m_Stream << "null], [\n";
728 0 : }
729 :
730 0 : void OnEvent(double time, const char* id)
731 : {
732 0 : m_Stream << "[1," << std::fixed << std::setprecision(9) << time;
733 0 : m_Stream << ",\"" << CStr(id).EscapeToPrintableASCII() << "\"],\n";
734 0 : }
735 :
736 0 : void OnEnter(double time, const char* id)
737 : {
738 0 : m_Stream << "[2," << std::fixed << std::setprecision(9) << time;
739 0 : m_Stream << ",\"" << CStr(id).EscapeToPrintableASCII() << "\"],\n";
740 0 : }
741 :
742 0 : void OnLeave(double time)
743 : {
744 0 : m_Stream << "[3," << std::fixed << std::setprecision(9) << time << "],\n";
745 0 : }
746 :
747 0 : void OnAttribute(const std::string& attr)
748 : {
749 0 : m_Stream << "[4,\"" << CStr(attr).EscapeToPrintableASCII() << "\"],\n";
750 0 : }
751 :
752 : std::ostream& m_Stream;
753 : };
754 :
755 0 : const char* CProfiler2::ConstructJSONResponse(std::ostream& stream, const std::string& thread)
756 : {
757 0 : PROFILE2("CProfiler2::ConstructJSONResponse");
758 :
759 0 : std::string buffer;
760 :
761 0 : {
762 0 : PROFILE2("Profiler2 get buffer");
763 :
764 0 : std::lock_guard<std::mutex> lock(m_Mutex); // lock against changes to m_Threads or deletions of ThreadStorage
765 :
766 0 : std::vector<std::unique_ptr<ThreadStorage>>::iterator it =
767 0 : std::find_if(m_Threads.begin(), m_Threads.end(), [&thread](std::unique_ptr<ThreadStorage>& storage) {
768 0 : return storage->GetName() == thread;
769 : });
770 :
771 0 : if (it == m_Threads.end())
772 0 : return "cannot find named thread";
773 :
774 0 : stream << "{\"events\":[\n";
775 :
776 0 : stream << "[\n";
777 0 : buffer = (*it)->GetBuffer();
778 0 : }
779 :
780 0 : BufferVisitor_Dump visitor(stream);
781 0 : RunBufferVisitor(buffer, visitor);
782 :
783 0 : stream << "null]\n]}";
784 :
785 : return NULL;
786 0 : }
787 :
788 0 : void CProfiler2::SaveToFile()
789 : {
790 0 : OsPath path = psLogDir()/"profile2.jsonp";
791 0 : debug_printf("Writing profile data to %s \n", path.string8().c_str());
792 0 : LOGMESSAGERENDER("Writing profile data to {}\n", path.string8());
793 0 : std::ofstream stream(OsString(path), std::ofstream::out | std::ofstream::trunc);
794 0 : ENSURE(stream.good());
795 :
796 0 : stream << "profileDataCB({\"threads\": [\n";
797 0 : bool first_time = true;
798 0 : for (std::unique_ptr<ThreadStorage>& storage : m_Threads)
799 : {
800 0 : if (!first_time)
801 0 : stream << ",\n";
802 0 : stream << "{\"name\":\"" << CStr(storage->GetName()).EscapeToPrintableASCII() << "\",\n";
803 0 : stream << "\"data\": ";
804 0 : ConstructJSONResponse(stream, storage->GetName());
805 0 : stream << "\n}";
806 0 : first_time = false;
807 : }
808 0 : stream << "\n]});\n";
809 0 : }
|