Debian Codegraph @

3rdparty/tracy/public/client/TracyProfiler.cpp

raw symbols SCIP
1 #ifdef TRACY_ENABLE
2
3 #ifdef _WIN32
4 # ifndef NOMINMAX
5 # define NOMINMAX
6 # endif
7 # include <winsock2.h>
8 # include <windows.h>
9 # include <tlhelp32.h>
10 # include <inttypes.h>
11 # include <intrin.h>
12 # include "../common/TracyUwp.hpp"
13 #else
14 # include <sys/time.h>
15 # include <sys/param.h>
16 #endif
17
18 #ifdef _GNU_SOURCE
19 # include <errno.h>
20 #endif
21
22 #ifdef __linux__
23 # include <dirent.h>
24 # include <pthread.h>
25 # include <sys/types.h>
26 # include <sys/syscall.h>
27 #endif
28
29 #if defined __APPLE__ || defined BSD
30 # include <sys/types.h>
31 # include <sys/sysctl.h>
32 #endif
33
34 #if defined __APPLE__
35 # include "TargetConditionals.h"
36 # include <mach-o/dyld.h>
37 #endif
38
39 #ifdef __ANDROID__
40 # include <sys/mman.h>
41 # include <sys/system_properties.h>
42 # include <stdio.h>
43 # include <stdint.h>
44 # include <algorithm>
45 # include <vector>
46 #endif
47
48 #include <algorithm>
49 #include <assert.h>
50 #include <atomic>
51 #include <chrono>
52 #include <limits>
53 #include <new>
54 #include <stdlib.h>
55 #include <string.h>
56 #include <sys/stat.h>
57 #include <thread>
58
59 #include "../common/TracyAlign.hpp"
60 #include "../common/TracyAlloc.hpp"
61 #include "../common/TracySocket.hpp"
62 #include "../common/TracySystem.hpp"
63 #include "../common/TracyYield.hpp"
64 #include "../common/tracy_lz4.hpp"
65 #include "tracy_rpmalloc.hpp"
66 #include "TracyCallstack.hpp"
67 #include "TracyDebug.hpp"
68 #include "TracyDxt1.hpp"
69 #include "TracyScoped.hpp"
70 #include "TracyProfiler.hpp"
71 #include "TracyThread.hpp"
72 #include "TracyArmCpuTable.hpp"
73 #include "TracySysTrace.hpp"
74 #include "../tracy/TracyC.h"
75
76 #ifdef TRACY_PORT
77 # ifndef TRACY_DATA_PORT
78 # define TRACY_DATA_PORT TRACY_PORT
79 # endif
80 # ifndef TRACY_BROADCAST_PORT
81 # define TRACY_BROADCAST_PORT TRACY_PORT
82 # endif
83 #endif
84
85 #ifdef __APPLE__
86 # define TRACY_DELAYED_INIT
87 #else
88 # ifdef __GNUC__
89 # define init_order( val ) __attribute__ ((init_priority(val)))
90 # else
91 # define init_order(x)
92 # endif
93 #endif
94
95 #if defined _WIN32
96 # include <lmcons.h>
97 extern "C" typedef LONG (WINAPI *t_RtlGetVersion)( PRTL_OSVERSIONINFOW );
98 extern "C" typedef BOOL (WINAPI *t_GetLogicalProcessorInformationEx)( LOGICAL_PROCESSOR_RELATIONSHIP, PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX, PDWORD );
99 #else
100 # include <unistd.h>
101 # include <limits.h>
102 #endif
103 #if defined __linux__
104 # include <sys/sysinfo.h>
105 # include <sys/utsname.h>
106 #endif
107
108 #if !defined _WIN32 && ( defined __i386 || defined _M_IX86 || defined __x86_64__ || defined _M_X64 )
109 # include "TracyCpuid.hpp"
110 #endif
111
112 #if !( ( defined _WIN32 && _WIN32_WINNT >= _WIN32_WINNT_VISTA ) || defined __linux__ )
113 # include <mutex>
114 #endif
115
116 namespace tracy
117 {
118
119 #ifdef __ANDROID__
120 // Implementation helpers of EnsureReadable(address).
121 // This is so far only needed on Android, where it is common for libraries to be mapped
122 // with only executable, not readable, permissions. Typical example (line from /proc/self/maps):
123 /*
124 746b63b000-746b6dc000 --xp 00042000 07:48 35 /apex/com.android.runtime/lib64/bionic/libc.so
125 */
126 // See https://github.com/wolfpld/tracy/issues/125 .
127 // To work around this, we parse /proc/self/maps and we use mprotect to set read permissions
128 // on any mappings that contain symbols addresses hit by HandleSymbolCodeQuery.
129
130 namespace {
131 // Holds some information about a single memory mapping.
132 struct MappingInfo {
133 // Start of address range. Inclusive.
134 uintptr_t start_address;
135 // End of address range. Exclusive, so the mapping is the half-open interval
136 // [start, end) and its length in bytes is `end - start`. As in /proc/self/maps.
137 uintptr_t end_address;
138 // Read/Write/Executable permissions.
139 bool perm_r, perm_w, perm_x;
140 };
141 } // anonymous namespace
142
143 // Internal implementation helper for LookUpMapping(address).
144 //
145 // Parses /proc/self/maps returning a vector<MappingInfo>.
146 // /proc/self/maps is assumed to be sorted by ascending address, so the resulting
147 // vector is sorted by ascending address too.
148 static std::vector<MappingInfo> ParseMappings()
149 {
150 std::vector<MappingInfo> result;
151 FILE* file = fopen( "/proc/self/maps", "r" );
152 if( !file ) return result;
153 char line[1024];
154 while( fgets( line, sizeof( line ), file ) )
155 {
156 uintptr_t start_addr;
157 uintptr_t end_addr;
158 if( sscanf( line, "%lx-%lx", &start_addr, &end_addr ) != 2 ) continue;
159 char* first_space = strchr( line, ' ' );
160 if( !first_space ) continue;
161 char* perm = first_space + 1;
162 char* second_space = strchr( perm, ' ' );
163 if( !second_space || second_space - perm != 4 ) continue;
164 result.emplace_back();
165 auto& mapping = result.back();
166 mapping.start_address = start_addr;
167 mapping.end_address = end_addr;
168 mapping.perm_r = perm[0] == 'r';
169 mapping.perm_w = perm[1] == 'w';
170 mapping.perm_x = perm[2] == 'x';
171 }
172 fclose( file );
173 return result;
174 }
175
176 // Internal implementation helper for LookUpMapping(address).
177 //
178 // Takes as input an `address` and a known vector `mappings`, assumed to be
179 // sorted by increasing addresses, as /proc/self/maps seems to be.
180 // Returns a pointer to the MappingInfo describing the mapping that this
181 // address belongs to, or nullptr if the address isn't in `mappings`.
182 static MappingInfo* LookUpMapping(std::vector<MappingInfo>& mappings, uintptr_t address)
183 {
184 // Comparison function for std::lower_bound. Returns true if all addresses in `m1`
185 // are lower than `addr`.
186 auto Compare = []( const MappingInfo& m1, uintptr_t addr ) {
187 // '<=' because the address ranges are half-open intervals, [start, end).
188 return m1.end_address <= addr;
189 };
190 auto iter = std::lower_bound( mappings.begin(), mappings.end(), address, Compare );
191 if( iter == mappings.end() || iter->start_address > address) {
192 return nullptr;
193 }
194 return &*iter;
195 }
196
197 // Internal implementation helper for EnsureReadable(address).
198 //
199 // Takes as input an `address` and returns a pointer to a MappingInfo
200 // describing the mapping that this address belongs to, or nullptr if
201 // the address isn't in any known mapping.
202 //
203 // This function is stateful and not reentrant (assumes to be called from
204 // only one thread). It holds a vector of mappings parsed from /proc/self/maps.
205 //
206 // Attempts to react to mappings changes by re-parsing /proc/self/maps.
207 static MappingInfo* LookUpMapping(uintptr_t address)
208 {
209 // Static state managed by this function. Not constant, we mutate that state as
210 // we turn some mappings readable. Initially parsed once here, updated as needed below.
211 static std::vector<MappingInfo> s_mappings = ParseMappings();
212 MappingInfo* mapping = LookUpMapping( s_mappings, address );
213 if( mapping ) return mapping;
214
215 // This address isn't in any known mapping. Try parsing again, maybe
216 // mappings changed.
217 s_mappings = ParseMappings();
218 return LookUpMapping( s_mappings, address );
219 }
220
221 // Internal implementation helper for EnsureReadable(address).
222 //
223 // Attempts to make the specified `mapping` readable if it isn't already.
224 // Returns true if and only if the mapping is readable.
225 static bool EnsureReadable( MappingInfo& mapping )
226 {
227 if( mapping.perm_r )
228 {
229 // The mapping is already readable.
230 return true;
231 }
232 int prot = PROT_READ;
233 if( mapping.perm_w ) prot |= PROT_WRITE;
234 if( mapping.perm_x ) prot |= PROT_EXEC;
235 if( mprotect( reinterpret_cast<void*>( mapping.start_address ),
236 mapping.end_address - mapping.start_address, prot ) == -1 )
237 {
238 // Failed to make the mapping readable. Shouldn't happen, hasn't
239 // been observed yet. If it happened in practice, we should consider
240 // adding a bool to MappingInfo to track this to avoid retrying mprotect
241 // everytime on such mappings.
242 return false;
243 }
244 // The mapping is now readable. Update `mapping` so the next call will be fast.
245 mapping.perm_r = true;
246 return true;
247 }
248
249 // Attempts to set the read permission on the entire mapping containing the
250 // specified address. Returns true if and only if the mapping is now readable.
251 static bool EnsureReadable( uintptr_t address )
252 {
253 MappingInfo* mapping = LookUpMapping(address);
254 return mapping && EnsureReadable( *mapping );
255 }
256
257 #endif // defined __ANDROID__
258
259 #ifndef TRACY_DELAYED_INIT
260
261 struct InitTimeWrapper
262 {
263 int64_t val;
264 };
265
266 struct ProducerWrapper
267 {
268 tracy::moodycamel::ConcurrentQueue<QueueItem>::ExplicitProducer* ptr;
269 };
270
271 struct ThreadHandleWrapper
272 {
273 uint32_t val;
274 };
275 #endif
276
277
278 #if defined __i386 || defined _M_IX86 || defined __x86_64__ || defined _M_X64
279 static inline void CpuId( uint32_t* regs, uint32_t leaf )
280 {
281 memset(regs, 0, sizeof(uint32_t) * 4);
282 #if defined _WIN32
283 __cpuidex( (int*)regs, leaf, 0 );
284 #else
285 __get_cpuid( leaf, regs, regs+1, regs+2, regs+3 );
286 #endif
287 }
288
289 static void InitFailure( const char* msg )
290 {
291 #if defined _WIN32
292 bool hasConsole = false;
293 bool reopen = false;
294 const auto attached = AttachConsole( ATTACH_PARENT_PROCESS );
295 if( attached )
296 {
297 hasConsole = true;
298 reopen = true;
299 }
300 else
301 {
302 const auto err = GetLastError();
303 if( err == ERROR_ACCESS_DENIED )
304 {
305 hasConsole = true;
306 }
307 }
308 if( hasConsole )
309 {
310 fprintf( stderr, "Tracy Profiler initialization failure: %s\n", msg );
311 if( reopen )
312 {
313 freopen( "CONOUT$", "w", stderr );
314 fprintf( stderr, "Tracy Profiler initialization failure: %s\n", msg );
315 }
316 }
317 else
318 {
319 # ifndef TRACY_UWP
320 MessageBoxA( nullptr, msg, "Tracy Profiler initialization failure", MB_ICONSTOP );
321 # endif
322 }
323 #else
324 fprintf( stderr, "Tracy Profiler initialization failure: %s\n", msg );
325 #endif
326 exit( 1 );
327 }
328
329 static bool CheckHardwareSupportsInvariantTSC()
330 {
331 const char* noCheck = GetEnvVar( "TRACY_NO_INVARIANT_CHECK" );
332 if( noCheck && noCheck[0] == '1' ) return true;
333
334 uint32_t regs[4];
335 CpuId( regs, 1 );
336 if( !( regs[3] & ( 1 << 4 ) ) )
337 {
338 #if !defined TRACY_TIMER_QPC && !defined TRACY_TIMER_FALLBACK
339 InitFailure( "CPU doesn't support RDTSC instruction." );
340 #else
341 return false;
342 #endif
343 }
344 CpuId( regs, 0x80000007 );
345 if( regs[3] & ( 1 << 8 ) ) return true;
346
347 return false;
348 }
349
350 #if defined TRACY_TIMER_FALLBACK && defined TRACY_HW_TIMER
351 bool HardwareSupportsInvariantTSC()
352 {
353 static bool cachedResult = CheckHardwareSupportsInvariantTSC();
354 return cachedResult;
355 }
356 #endif
357
358 static int64_t SetupHwTimer()
359 {
360 #if !defined TRACY_TIMER_QPC && !defined TRACY_TIMER_FALLBACK
361 if( !CheckHardwareSupportsInvariantTSC() )
362 {
363 #if defined _WIN32
364 InitFailure( "CPU doesn't support invariant TSC.\nDefine TRACY_NO_INVARIANT_CHECK=1 to ignore this error, *if you know what you are doing*.\nAlternatively you may rebuild the application with the TRACY_TIMER_QPC or TRACY_TIMER_FALLBACK define to use lower resolution timer." );
365 #else
366 InitFailure( "CPU doesn't support invariant TSC.\nDefine TRACY_NO_INVARIANT_CHECK=1 to ignore this error, *if you know what you are doing*.\nAlternatively you may rebuild the application with the TRACY_TIMER_FALLBACK define to use lower resolution timer." );
367 #endif
368 }
369 #endif
370
371 return Profiler::GetTime();
372 }
373 #else
374 static int64_t SetupHwTimer()
375 {
376 return Profiler::GetTime();
377 }
378 #endif
379
380 static const char* GetProcessName()
381 {
382 const char* processName = "unknown";
383 #ifdef _WIN32
384 static char buf[_MAX_PATH];
385 GetModuleFileNameA( nullptr, buf, _MAX_PATH );
386 const char* ptr = buf;
387 while( *ptr != '\0' ) ptr++;
388 while( ptr > buf && *ptr != '\\' && *ptr != '/' ) ptr--;
389 if( ptr > buf ) ptr++;
390 processName = ptr;
391 #elif defined __ANDROID__
392 # if __ANDROID_API__ >= 21
393 auto buf = getprogname();
394 if( buf ) processName = buf;
395 # endif
396 #elif defined __linux__ && defined _GNU_SOURCE
397 if( program_invocation_short_name ) processName = program_invocation_short_name;
398 #elif defined __APPLE__ || defined BSD
399 auto buf = getprogname();
400 if( buf ) processName = buf;
401 #endif
402 return processName;
403 }
404
405 static const char* GetProcessExecutablePath()
406 {
407 #ifdef _WIN32
408 static char buf[_MAX_PATH];
409 GetModuleFileNameA( nullptr, buf, _MAX_PATH );
410 return buf;
411 #elif defined __ANDROID__
412 return nullptr;
413 #elif defined __linux__ && defined _GNU_SOURCE
414 return program_invocation_name;
415 #elif defined __APPLE__
416 static char buf[1024];
417 uint32_t size = 1024;
418 _NSGetExecutablePath( buf, &size );
419 return buf;
420 #elif defined __DragonFly__
421 static char buf[1024];
422 readlink( "/proc/curproc/file", buf, 1024 );
423 return buf;
424 #elif defined __FreeBSD__
425 static char buf[1024];
426 int mib[4];
427 mib[0] = CTL_KERN;
428 mib[1] = KERN_PROC;
429 mib[2] = KERN_PROC_PATHNAME;
430 mib[3] = -1;
431 size_t cb = 1024;
432 sysctl( mib, 4, buf, &cb, nullptr, 0 );
433 return buf;
434 #elif defined __NetBSD__
435 static char buf[1024];
436 readlink( "/proc/curproc/exe", buf, 1024 );
437 return buf;
438 #else
439 return nullptr;
440 #endif
441 }
442
443 #if defined __linux__ && defined __ARM_ARCH
444 static uint32_t GetHex( char*& ptr, int skip )
445 {
446 uint32_t ret;
447 ptr += skip;
448 char* end;
449 if( ptr[0] == '0' && ptr[1] == 'x' )
450 {
451 ptr += 2;
452 ret = strtol( ptr, &end, 16 );
453 }
454 else
455 {
456 ret = strtol( ptr, &end, 10 );
457 }
458 ptr = end;
459 return ret;
460 }
461 #endif
462
463 static const char* GetHostInfo()
464 {
465 static char buf[1024];
466 auto ptr = buf;
467 #if defined _WIN32
468 # ifdef TRACY_UWP
469 auto GetVersion = &::GetVersionEx;
470 # else
471 auto GetVersion = (t_RtlGetVersion)GetProcAddress( GetModuleHandleA( "ntdll.dll" ), "RtlGetVersion" );
472 # endif
473 if( !GetVersion )
474 {
475 # ifdef __MINGW32__
476 ptr += sprintf( ptr, "OS: Windows (MingW)\n" );
477 # else
478 ptr += sprintf( ptr, "OS: Windows\n" );
479 # endif
480 }
481 else
482 {
483 RTL_OSVERSIONINFOW ver = { sizeof( RTL_OSVERSIONINFOW ) };
484 GetVersion( &ver );
485
486 # ifdef __MINGW32__
487 ptr += sprintf( ptr, "OS: Windows %i.%i.%i (MingW)\n", (int)ver.dwMajorVersion, (int)ver.dwMinorVersion, (int)ver.dwBuildNumber );
488 # else
489 ptr += sprintf( ptr, "OS: Windows %i.%i.%i\n", ver.dwMajorVersion, ver.dwMinorVersion, ver.dwBuildNumber );
490 # endif
491 }
492 #elif defined __linux__
493 struct utsname utsName;
494 uname( &utsName );
495 # if defined __ANDROID__
496 ptr += sprintf( ptr, "OS: Linux %s (Android)\n", utsName.release );
497 # else
498 ptr += sprintf( ptr, "OS: Linux %s\n", utsName.release );
499 # endif
500 #elif defined __APPLE__
501 # if TARGET_OS_IPHONE == 1
502 ptr += sprintf( ptr, "OS: Darwin (iOS)\n" );
503 # elif TARGET_OS_MAC == 1
504 ptr += sprintf( ptr, "OS: Darwin (OSX)\n" );
505 # else
506 ptr += sprintf( ptr, "OS: Darwin (unknown)\n" );
507 # endif
508 #elif defined __DragonFly__
509 ptr += sprintf( ptr, "OS: BSD (DragonFly)\n" );
510 #elif defined __FreeBSD__
511 ptr += sprintf( ptr, "OS: BSD (FreeBSD)\n" );
512 #elif defined __NetBSD__
513 ptr += sprintf( ptr, "OS: BSD (NetBSD)\n" );
514 #elif defined __OpenBSD__
515 ptr += sprintf( ptr, "OS: BSD (OpenBSD)\n" );
516 #else
517 ptr += sprintf( ptr, "OS: unknown\n" );
518 #endif
519
520 #if defined _MSC_VER
521 # if defined __clang__
522 ptr += sprintf( ptr, "Compiler: MSVC clang-cl %i.%i.%i\n", __clang_major__, __clang_minor__, __clang_patchlevel__ );
523 # else
524 ptr += sprintf( ptr, "Compiler: MSVC %i\n", _MSC_VER );
525 # endif
526 #elif defined __clang__
527 ptr += sprintf( ptr, "Compiler: clang %i.%i.%i\n", __clang_major__, __clang_minor__, __clang_patchlevel__ );
528 #elif defined __GNUC__
529 ptr += sprintf( ptr, "Compiler: gcc %i.%i.%i\n", __GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__ );
530 #else
531 ptr += sprintf( ptr, "Compiler: unknown\n" );
532 #endif
533
534 #if defined _WIN32
535 InitWinSock();
536
537 char hostname[512];
538 gethostname( hostname, 512 );
539
540 # ifdef TRACY_UWP
541 const char* user = "";
542 # else
543 DWORD userSz = UNLEN+1;
544 char user[UNLEN+1];
545 GetUserNameA( user, &userSz );
546 # endif
547
548 ptr += sprintf( ptr, "User: %s@%s\n", user, hostname );
549 #else
550 char hostname[_POSIX_HOST_NAME_MAX]{};
551 char user[_POSIX_LOGIN_NAME_MAX]{};
552
553 gethostname( hostname, _POSIX_HOST_NAME_MAX );
554 # if defined __ANDROID__
555 const auto login = getlogin();
556 if( login )
557 {
558 strcpy( user, login );
559 }
560 else
561 {
562 memcpy( user, "(?)", 4 );
563 }
564 # else
565 getlogin_r( user, _POSIX_LOGIN_NAME_MAX );
566 # endif
567
568 ptr += sprintf( ptr, "User: %s@%s\n", user, hostname );
569 #endif
570
571 #if defined __i386 || defined _M_IX86
572 ptr += sprintf( ptr, "Arch: x86\n" );
573 #elif defined __x86_64__ || defined _M_X64
574 ptr += sprintf( ptr, "Arch: x64\n" );
575 #elif defined __aarch64__
576 ptr += sprintf( ptr, "Arch: ARM64\n" );
577 #elif defined __ARM_ARCH
578 ptr += sprintf( ptr, "Arch: ARM\n" );
579 #else
580 ptr += sprintf( ptr, "Arch: unknown\n" );
581 #endif
582
583 #if defined __i386 || defined _M_IX86 || defined __x86_64__ || defined _M_X64
584 uint32_t regs[4];
585 char cpuModel[4*4*3+1] = {};
586 auto modelPtr = cpuModel;
587 for( uint32_t i=0x80000002; i<0x80000005; ++i )
588 {
589 CpuId( regs, i );
590 memcpy( modelPtr, regs, sizeof( regs ) ); modelPtr += sizeof( regs );
591 }
592
593 ptr += sprintf( ptr, "CPU: %s\n", cpuModel );
594 #elif defined __linux__ && defined __ARM_ARCH
595 bool cpuFound = false;
596 FILE* fcpuinfo = fopen( "/proc/cpuinfo", "rb" );
597 if( fcpuinfo )
598 {
599 enum { BufSize = 4*1024 };
600 char buf[BufSize];
601 const auto sz = fread( buf, 1, BufSize, fcpuinfo );
602 fclose( fcpuinfo );
603 const auto end = buf + sz;
604 auto cptr = buf;
605
606 uint32_t impl = 0;
607 uint32_t var = 0;
608 uint32_t part = 0;
609 uint32_t rev = 0;
610
611 while( end - cptr > 20 )
612 {
613 while( end - cptr > 20 && memcmp( cptr, "CPU ", 4 ) != 0 )
614 {
615 cptr += 4;
616 while( end - cptr > 20 && *cptr != '\n' ) cptr++;
617 cptr++;
618 }
619 if( end - cptr <= 20 ) break;
620 cptr += 4;
621 if( memcmp( cptr, "implementer\t: ", 14 ) == 0 )
622 {
623 if( impl != 0 ) break;
624 impl = GetHex( cptr, 14 );
625 }
626 else if( memcmp( cptr, "variant\t: ", 10 ) == 0 ) var = GetHex( cptr, 10 );
627 else if( memcmp( cptr, "part\t: ", 7 ) == 0 ) part = GetHex( cptr, 7 );
628 else if( memcmp( cptr, "revision\t: ", 11 ) == 0 ) rev = GetHex( cptr, 11 );
629 while( *cptr != '\n' && *cptr != '\0' ) cptr++;
630 cptr++;
631 }
632
633 if( impl != 0 || var != 0 || part != 0 || rev != 0 )
634 {
635 cpuFound = true;
636 ptr += sprintf( ptr, "CPU: %s%s r%ip%i\n", DecodeArmImplementer( impl ), DecodeArmPart( impl, part ), var, rev );
637 }
638 }
639 if( !cpuFound )
640 {
641 ptr += sprintf( ptr, "CPU: unknown\n" );
642 }
643 #elif defined __APPLE__ && TARGET_OS_IPHONE == 1
644 {
645 size_t sz;
646 sysctlbyname( "hw.machine", nullptr, &sz, nullptr, 0 );
647 auto str = (char*)tracy_malloc( sz );
648 sysctlbyname( "hw.machine", str, &sz, nullptr, 0 );
649 ptr += sprintf( ptr, "Device: %s\n", DecodeIosDevice( str ) );
650 tracy_free( str );
651 }
652 #else
653 ptr += sprintf( ptr, "CPU: unknown\n" );
654 #endif
655 #ifdef __ANDROID__
656 char deviceModel[PROP_VALUE_MAX+1];
657 char deviceManufacturer[PROP_VALUE_MAX+1];
658 __system_property_get( "ro.product.model", deviceModel );
659 __system_property_get( "ro.product.manufacturer", deviceManufacturer );
660 ptr += sprintf( ptr, "Device: %s %s\n", deviceManufacturer, deviceModel );
661 #endif
662
663 ptr += sprintf( ptr, "CPU cores: %i\n", std::thread::hardware_concurrency() );
664
665 #if defined _WIN32
666 MEMORYSTATUSEX statex;
667 statex.dwLength = sizeof( statex );
668 GlobalMemoryStatusEx( &statex );
669 # ifdef _MSC_VER
670 ptr += sprintf( ptr, "RAM: %I64u MB\n", statex.ullTotalPhys / 1024 / 1024 );
671 # else
672 ptr += sprintf( ptr, "RAM: %llu MB\n", statex.ullTotalPhys / 1024 / 1024 );
673 # endif
674 #elif defined __linux__
675 struct sysinfo sysInfo;
676 sysinfo( &sysInfo );
677 ptr += sprintf( ptr, "RAM: %lu MB\n", sysInfo.totalram / 1024 / 1024 );
678 #elif defined __APPLE__
679 size_t memSize;
680 size_t sz = sizeof( memSize );
681 sysctlbyname( "hw.memsize", &memSize, &sz, nullptr, 0 );
682 ptr += sprintf( ptr, "RAM: %zu MB\n", memSize / 1024 / 1024 );
683 #elif defined BSD
684 size_t memSize;
685 size_t sz = sizeof( memSize );
686 sysctlbyname( "hw.physmem", &memSize, &sz, nullptr, 0 );
687 ptr += sprintf( ptr, "RAM: %zu MB\n", memSize / 1024 / 1024 );
688 #else
689 ptr += sprintf( ptr, "RAM: unknown\n" );
690 #endif
691
692 return buf;
693 }
694
695 static uint64_t GetPid()
696 {
697 #if defined _WIN32
698 return uint64_t( GetCurrentProcessId() );
699 #else
700 return uint64_t( getpid() );
701 #endif
702 }
703
704 void Profiler::AckServerQuery()
705 {
706 QueueItem item;
707 MemWrite( &item.hdr.type, QueueType::AckServerQueryNoop );
708 NeedDataSize( QueueDataSize[(int)QueueType::AckServerQueryNoop] );
709 AppendDataUnsafe( &item, QueueDataSize[(int)QueueType::AckServerQueryNoop] );
710 }
711
712 void Profiler::AckSymbolCodeNotAvailable()
713 {
714 QueueItem item;
715 MemWrite( &item.hdr.type, QueueType::AckSymbolCodeNotAvailable );
716 NeedDataSize( QueueDataSize[(int)QueueType::AckSymbolCodeNotAvailable] );
717 AppendDataUnsafe( &item, QueueDataSize[(int)QueueType::AckSymbolCodeNotAvailable] );
718 }
719
720 static BroadcastMessage& GetBroadcastMessage( const char* procname, size_t pnsz, int& len, int port )
721 {
722 static BroadcastMessage msg;
723
724 msg.broadcastVersion = BroadcastVersion;
725 msg.protocolVersion = ProtocolVersion;
726 msg.listenPort = port;
727 msg.pid = GetPid();
728
729 memcpy( msg.programName, procname, pnsz );
730 memset( msg.programName + pnsz, 0, WelcomeMessageProgramNameSize - pnsz );
731
732 len = int( offsetof( BroadcastMessage, programName ) + pnsz + 1 );
733 return msg;
734 }
735
736 #if defined _WIN32 && !defined TRACY_UWP && !defined TRACY_NO_CRASH_HANDLER
737 static DWORD s_profilerThreadId = 0;
738 static DWORD s_symbolThreadId = 0;
739 static char s_crashText[1024];
740
741 LONG WINAPI CrashFilter( PEXCEPTION_POINTERS pExp )
742 {
743 if( !GetProfiler().IsConnected() ) return EXCEPTION_CONTINUE_SEARCH;
744
745 const unsigned ec = pExp->ExceptionRecord->ExceptionCode;
746 auto msgPtr = s_crashText;
747 switch( ec )
748 {
749 case EXCEPTION_ACCESS_VIOLATION:
750 msgPtr += sprintf( msgPtr, "Exception EXCEPTION_ACCESS_VIOLATION (0x%x). ", ec );
751 switch( pExp->ExceptionRecord->ExceptionInformation[0] )
752 {
753 case 0:
754 msgPtr += sprintf( msgPtr, "Read violation at address 0x%" PRIxPTR ".", pExp->ExceptionRecord->ExceptionInformation[1] );
755 break;
756 case 1:
757 msgPtr += sprintf( msgPtr, "Write violation at address 0x%" PRIxPTR ".", pExp->ExceptionRecord->ExceptionInformation[1] );
758 break;
759 case 8:
760 msgPtr += sprintf( msgPtr, "DEP violation at address 0x%" PRIxPTR ".", pExp->ExceptionRecord->ExceptionInformation[1] );
761 break;
762 default:
763 break;
764 }
765 break;
766 case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
767 msgPtr += sprintf( msgPtr, "Exception EXCEPTION_ARRAY_BOUNDS_EXCEEDED (0x%x). ", ec );
768 break;
769 case EXCEPTION_DATATYPE_MISALIGNMENT:
770 msgPtr += sprintf( msgPtr, "Exception EXCEPTION_DATATYPE_MISALIGNMENT (0x%x). ", ec );
771 break;
772 case EXCEPTION_FLT_DIVIDE_BY_ZERO:
773 msgPtr += sprintf( msgPtr, "Exception EXCEPTION_FLT_DIVIDE_BY_ZERO (0x%x). ", ec );
774 break;
775 case EXCEPTION_ILLEGAL_INSTRUCTION:
776 msgPtr += sprintf( msgPtr, "Exception EXCEPTION_ILLEGAL_INSTRUCTION (0x%x). ", ec );
777 break;
778 case EXCEPTION_IN_PAGE_ERROR:
779 msgPtr += sprintf( msgPtr, "Exception EXCEPTION_IN_PAGE_ERROR (0x%x). ", ec );
780 break;
781 case EXCEPTION_INT_DIVIDE_BY_ZERO:
782 msgPtr += sprintf( msgPtr, "Exception EXCEPTION_INT_DIVIDE_BY_ZERO (0x%x). ", ec );
783 break;
784 case EXCEPTION_PRIV_INSTRUCTION:
785 msgPtr += sprintf( msgPtr, "Exception EXCEPTION_PRIV_INSTRUCTION (0x%x). ", ec );
786 break;
787 case EXCEPTION_STACK_OVERFLOW:
788 msgPtr += sprintf( msgPtr, "Exception EXCEPTION_STACK_OVERFLOW (0x%x). ", ec );
789 break;
790 default:
791 return EXCEPTION_CONTINUE_SEARCH;
792 }
793
794 {
795 GetProfiler().SendCallstack( 60, "KiUserExceptionDispatcher" );
796
797 TracyQueuePrepare( QueueType::CrashReport );
798 item->crashReport.time = Profiler::GetTime();
799 item->crashReport.text = (uint64_t)s_crashText;
800 TracyQueueCommit( crashReportThread );
801 }
802
803 HANDLE h = CreateToolhelp32Snapshot( TH32CS_SNAPTHREAD, 0 );
804 if( h == INVALID_HANDLE_VALUE ) return EXCEPTION_CONTINUE_SEARCH;
805
806 THREADENTRY32 te = { sizeof( te ) };
807 if( !Thread32First( h, &te ) )
808 {
809 CloseHandle( h );
810 return EXCEPTION_CONTINUE_SEARCH;
811 }
812
813 const auto pid = GetCurrentProcessId();
814 const auto tid = GetCurrentThreadId();
815
816 do
817 {
818 if( te.th32OwnerProcessID == pid && te.th32ThreadID != tid && te.th32ThreadID != s_profilerThreadId && te.th32ThreadID != s_symbolThreadId )
819 {
820 HANDLE th = OpenThread( THREAD_SUSPEND_RESUME, FALSE, te.th32ThreadID );
821 if( th != INVALID_HANDLE_VALUE )
822 {
823 SuspendThread( th );
824 CloseHandle( th );
825 }
826 }
827 }
828 while( Thread32Next( h, &te ) );
829 CloseHandle( h );
830
831 {
832 TracyLfqPrepare( QueueType::Crash );
833 TracyLfqCommit;
834 }
835
836 std::this_thread::sleep_for( std::chrono::milliseconds( 500 ) );
837 GetProfiler().RequestShutdown();
838 while( !GetProfiler().HasShutdownFinished() ) { std::this_thread::sleep_for( std::chrono::milliseconds( 10 ) ); };
839
840 return EXCEPTION_CONTINUE_SEARCH;
841 }
842 #endif
843
844 static Profiler* s_instance = nullptr;
845 static Thread* s_thread;
846 #ifndef TRACY_NO_FRAME_IMAGE
847 static Thread* s_compressThread;
848 #endif
849 #ifdef TRACY_HAS_CALLSTACK
850 static Thread* s_symbolThread;
851 std::atomic<bool> s_symbolThreadGone { false };
852 #endif
853 #ifdef TRACY_HAS_SYSTEM_TRACING
854 static Thread* s_sysTraceThread = nullptr;
855 #endif
856
857 #if defined __linux__ && !defined TRACY_NO_CRASH_HANDLER
858 # ifndef TRACY_CRASH_SIGNAL
859 # define TRACY_CRASH_SIGNAL SIGPWR
860 # endif
861
862 static long s_profilerTid = 0;
863 static long s_symbolTid = 0;
864 static char s_crashText[1024];
865 static std::atomic<bool> s_alreadyCrashed( false );
866
867 static void ThreadFreezer( int /*signal*/ )
868 {
869 for(;;) sleep( 1000 );
870 }
871
872 static inline void HexPrint( char*& ptr, uint64_t val )
873 {
874 if( val == 0 )
875 {
876 *ptr++ = '0';
877 return;
878 }
879
880 static const char HexTable[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
881 char buf[16];
882 auto bptr = buf;
883
884 do
885 {
886 *bptr++ = HexTable[val%16];
887 val /= 16;
888 }
889 while( val > 0 );
890
891 do
892 {
893 *ptr++ = *--bptr;
894 }
895 while( bptr != buf );
896 }
897
898 static void CrashHandler( int signal, siginfo_t* info, void* /*ucontext*/ )
899 {
900 bool expected = false;
901 if( !s_alreadyCrashed.compare_exchange_strong( expected, true ) ) ThreadFreezer( signal );
902
903 struct sigaction act = {};
904 act.sa_handler = SIG_DFL;
905 sigaction( SIGABRT, &act, nullptr );
906
907 auto msgPtr = s_crashText;
908 switch( signal )
909 {
910 case SIGILL:
911 strcpy( msgPtr, "Illegal Instruction.\n" );
912 while( *msgPtr ) msgPtr++;
913 switch( info->si_code )
914 {
915 case ILL_ILLOPC:
916 strcpy( msgPtr, "Illegal opcode.\n" );
917 break;
918 case ILL_ILLOPN:
919 strcpy( msgPtr, "Illegal operand.\n" );
920 break;
921 case ILL_ILLADR:
922 strcpy( msgPtr, "Illegal addressing mode.\n" );
923 break;
924 case ILL_ILLTRP:
925 strcpy( msgPtr, "Illegal trap.\n" );
926 break;
927 case ILL_PRVOPC:
928 strcpy( msgPtr, "Privileged opcode.\n" );
929 break;
930 case ILL_PRVREG:
931 strcpy( msgPtr, "Privileged register.\n" );
932 break;
933 case ILL_COPROC:
934 strcpy( msgPtr, "Coprocessor error.\n" );
935 break;
936 case ILL_BADSTK:
937 strcpy( msgPtr, "Internal stack error.\n" );
938 break;
939 default:
940 break;
941 }
942 break;
943 case SIGFPE:
944 strcpy( msgPtr, "Floating-point exception.\n" );
945 while( *msgPtr ) msgPtr++;
946 switch( info->si_code )
947 {
948 case FPE_INTDIV:
949 strcpy( msgPtr, "Integer divide by zero.\n" );
950 break;
951 case FPE_INTOVF:
952 strcpy( msgPtr, "Integer overflow.\n" );
953 break;
954 case FPE_FLTDIV:
955 strcpy( msgPtr, "Floating-point divide by zero.\n" );
956 break;
957 case FPE_FLTOVF:
958 strcpy( msgPtr, "Floating-point overflow.\n" );
959 break;
960 case FPE_FLTUND:
961 strcpy( msgPtr, "Floating-point underflow.\n" );
962 break;
963 case FPE_FLTRES:
964 strcpy( msgPtr, "Floating-point inexact result.\n" );
965 break;
966 case FPE_FLTINV:
967 strcpy( msgPtr, "Floating-point invalid operation.\n" );
968 break;
969 case FPE_FLTSUB:
970 strcpy( msgPtr, "Subscript out of range.\n" );
971 break;
972 default:
973 break;
974 }
975 break;
976 case SIGSEGV:
977 strcpy( msgPtr, "Invalid memory reference.\n" );
978 while( *msgPtr ) msgPtr++;
979 switch( info->si_code )
980 {
981 case SEGV_MAPERR:
982 strcpy( msgPtr, "Address not mapped to object.\n" );
983 break;
984 case SEGV_ACCERR:
985 strcpy( msgPtr, "Invalid permissions for mapped object.\n" );
986 break;
987 # ifdef SEGV_BNDERR
988 case SEGV_BNDERR:
989 strcpy( msgPtr, "Failed address bound checks.\n" );
990 break;
991 # endif
992 # ifdef SEGV_PKUERR
993 case SEGV_PKUERR:
994 strcpy( msgPtr, "Access was denied by memory protection keys.\n" );
995 break;
996 # endif
997 default:
998 break;
999 }
1000 break;
1001 case SIGPIPE:
1002 strcpy( msgPtr, "Broken pipe.\n" );
1003 while( *msgPtr ) msgPtr++;
1004 break;
1005 case SIGBUS:
1006 strcpy( msgPtr, "Bus error.\n" );
1007 while( *msgPtr ) msgPtr++;
1008 switch( info->si_code )
1009 {
1010 case BUS_ADRALN:
1011 strcpy( msgPtr, "Invalid address alignment.\n" );
1012 break;
1013 case BUS_ADRERR:
1014 strcpy( msgPtr, "Nonexistent physical address.\n" );
1015 break;
1016 case BUS_OBJERR:
1017 strcpy( msgPtr, "Object-specific hardware error.\n" );
1018 break;
1019 # ifdef BUS_MCEERR_AR
1020 case BUS_MCEERR_AR:
1021 strcpy( msgPtr, "Hardware memory error consumed on a machine check; action required.\n" );
1022 break;
1023 # endif
1024 # ifdef BUS_MCEERR_AO
1025 case BUS_MCEERR_AO:
1026 strcpy( msgPtr, "Hardware memory error detected in process but not consumed; action optional.\n" );
1027 break;
1028 # endif
1029 default:
1030 break;
1031 }
1032 break;
1033 case SIGABRT:
1034 strcpy( msgPtr, "Abort signal from abort().\n" );
1035 break;
1036 default:
1037 abort();
1038 }
1039 while( *msgPtr ) msgPtr++;
1040
1041 if( signal != SIGPIPE )
1042 {
1043 strcpy( msgPtr, "Fault address: 0x" );
1044 while( *msgPtr ) msgPtr++;
1045 HexPrint( msgPtr, uint64_t( info->si_addr ) );
1046 *msgPtr++ = '\n';
1047 }
1048
1049 {
1050 GetProfiler().SendCallstack( 60, "__kernel_rt_sigreturn" );
1051
1052 TracyQueuePrepare( QueueType::CrashReport );
1053 item->crashReport.time = Profiler::GetTime();
1054 item->crashReport.text = (uint64_t)s_crashText;
1055 TracyQueueCommit( crashReportThread );
1056 }
1057
1058 DIR* dp = opendir( "/proc/self/task" );
1059 if( !dp ) abort();
1060
1061 const auto selfTid = syscall( SYS_gettid );
1062
1063 struct dirent* ep;
1064 while( ( ep = readdir( dp ) ) != nullptr )
1065 {
1066 if( ep->d_name[0] == '.' ) continue;
1067 int tid = atoi( ep->d_name );
1068 if( tid != selfTid && tid != s_profilerTid && tid != s_symbolTid )
1069 {
1070 syscall( SYS_tkill, tid, TRACY_CRASH_SIGNAL );
1071 }
1072 }
1073 closedir( dp );
1074
1075 if( selfTid == s_symbolTid ) s_symbolThreadGone.store( true, std::memory_order_release );
1076
1077 TracyLfqPrepare( QueueType::Crash );
1078 TracyLfqCommit;
1079
1080 std::this_thread::sleep_for( std::chrono::milliseconds( 500 ) );
1081 GetProfiler().RequestShutdown();
1082 while( !GetProfiler().HasShutdownFinished() ) { std::this_thread::sleep_for( std::chrono::milliseconds( 10 ) ); };
1083
1084 abort();
1085 }
1086 #endif
1087
1088
1089 enum { QueuePrealloc = 256 * 1024 };
1090
1091 TRACY_API int64_t GetFrequencyQpc()
1092 {
1093 #if defined _WIN32
1094 LARGE_INTEGER t;
1095 QueryPerformanceFrequency( &t );
1096 return t.QuadPart;
1097 #else
1098 return 0;
1099 #endif
1100 }
1101
1102 #ifdef TRACY_DELAYED_INIT
1103 struct ThreadNameData;
1104 TRACY_API moodycamel::ConcurrentQueue<QueueItem>& GetQueue();
1105
1106 struct ProfilerData
1107 {
1108 int64_t initTime = SetupHwTimer();
1109 moodycamel::ConcurrentQueue<QueueItem> queue;
1110 Profiler profiler;
1111 std::atomic<uint32_t> lockCounter { 0 };
1112 std::atomic<uint8_t> gpuCtxCounter { 0 };
1113 std::atomic<ThreadNameData*> threadNameData { nullptr };
1114 };
1115
1116 struct ProducerWrapper
1117 {
1118 ProducerWrapper( ProfilerData& data ) : detail( data.queue ), ptr( data.queue.get_explicit_producer( detail ) ) {}
1119 moodycamel::ProducerToken detail;
1120 tracy::moodycamel::ConcurrentQueue<QueueItem>::ExplicitProducer* ptr;
1121 };
1122
1123 struct ProfilerThreadData
1124 {
1125 ProfilerThreadData( ProfilerData& data ) : token( data ), gpuCtx( { nullptr } ) {}
1126 ProducerWrapper token;
1127 GpuCtxWrapper gpuCtx;
1128 # ifdef TRACY_ON_DEMAND
1129 LuaZoneState luaZoneState;
1130 # endif
1131 };
1132
1133 std::atomic<int> RpInitDone { 0 };
1134 std::atomic<int> RpInitLock { 0 };
1135 thread_local bool RpThreadInitDone = false;
1136 thread_local bool RpThreadShutdown = false;
1137
1138 # ifdef TRACY_MANUAL_LIFETIME
1139 ProfilerData* s_profilerData = nullptr;
1140 static ProfilerThreadData& GetProfilerThreadData();
1141 TRACY_API void StartupProfiler()
1142 {
1143 s_profilerData = (ProfilerData*)tracy_malloc( sizeof( ProfilerData ) );
1144 new (s_profilerData) ProfilerData();
1145 s_profilerData->profiler.SpawnWorkerThreads();
1146 GetProfilerThreadData().token = ProducerWrapper( *s_profilerData );
1147 }
1148 static ProfilerData& GetProfilerData()
1149 {
1150 assert( s_profilerData );
1151 return *s_profilerData;
1152 }
1153 TRACY_API void ShutdownProfiler()
1154 {
1155 s_profilerData->~ProfilerData();
1156 tracy_free( s_profilerData );
1157 s_profilerData = nullptr;
1158 rpmalloc_finalize();
1159 RpThreadInitDone = false;
1160 RpInitDone.store( 0, std::memory_order_release );
1161 }
1162 # else
1163 static std::atomic<int> profilerDataLock { 0 };
1164 static std::atomic<ProfilerData*> profilerData { nullptr };
1165
1166 static ProfilerData& GetProfilerData()
1167 {
1168 auto ptr = profilerData.load( std::memory_order_acquire );
1169 if( !ptr )
1170 {
1171 int expected = 0;
1172 while( !profilerDataLock.compare_exchange_weak( expected, 1, std::memory_order_release, std::memory_order_relaxed ) ) { expected = 0; YieldThread(); }
1173 ptr = profilerData.load( std::memory_order_acquire );
1174 if( !ptr )
1175 {
1176 ptr = (ProfilerData*)tracy_malloc( sizeof( ProfilerData ) );
1177 new (ptr) ProfilerData();
1178 profilerData.store( ptr, std::memory_order_release );
1179 }
1180 profilerDataLock.store( 0, std::memory_order_release );
1181 }
1182 return *ptr;
1183 }
1184 # endif
1185
1186 // GCC prior to 8.4 had a bug with function-inline thread_local variables. Versions of glibc beginning with
1187 // 2.18 may attempt to work around this issue, which manifests as a crash while running static destructors
1188 // if this function is compiled into a shared object. Unfortunately, centos7 ships with glibc 2.17. If running
1189 // on old GCC, use the old-fashioned way as a workaround
1190 // See: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=85400
1191 #if !defined(__clang__) && defined(__GNUC__) && ((__GNUC__ < 8) || ((__GNUC__ == 8) && (__GNUC_MINOR__ < 4)))
1192 struct ProfilerThreadDataKey
1193 {
1194 public:
1195 ProfilerThreadDataKey()
1196 {
1197 int val = pthread_key_create(&m_key, sDestructor);
1198 static_cast<void>(val); // unused
1199 assert(val == 0);
1200 }
1201 ~ProfilerThreadDataKey()
1202 {
1203 int val = pthread_key_delete(m_key);
1204 static_cast<void>(val); // unused
1205 assert(val == 0);
1206 }
1207 ProfilerThreadData& get()
1208 {
1209 void* p = pthread_getspecific(m_key);
1210 if (!p)
1211 {
1212 p = (ProfilerThreadData*)tracy_malloc( sizeof( ProfilerThreadData ) );
1213 new (p) ProfilerThreadData(GetProfilerData());
1214 pthread_setspecific(m_key, p);
1215 }
1216 return *static_cast<ProfilerThreadData*>(p);
1217 }
1218 private:
1219 pthread_key_t m_key;
1220
1221 static void sDestructor(void* p)
1222 {
1223 ((ProfilerThreadData*)p)->~ProfilerThreadData();
1224 tracy_free(p);
1225 }
1226 };
1227
1228 static ProfilerThreadData& GetProfilerThreadData()
1229 {
1230 static ProfilerThreadDataKey key;
1231 return key.get();
1232 }
1233 #else
1234 static ProfilerThreadData& GetProfilerThreadData()
1235 {
1236 thread_local ProfilerThreadData data( GetProfilerData() );
1237 return data;
1238 }
1239 #endif
1240
1241 TRACY_API moodycamel::ConcurrentQueue<QueueItem>::ExplicitProducer* GetToken() { return GetProfilerThreadData().token.ptr; }
1242 TRACY_API Profiler& GetProfiler() { return GetProfilerData().profiler; }
1243 TRACY_API moodycamel::ConcurrentQueue<QueueItem>& GetQueue() { return GetProfilerData().queue; }
1244 TRACY_API int64_t GetInitTime() { return GetProfilerData().initTime; }
1245 TRACY_API std::atomic<uint32_t>& GetLockCounter() { return GetProfilerData().lockCounter; }
1246 TRACY_API std::atomic<uint8_t>& GetGpuCtxCounter() { return GetProfilerData().gpuCtxCounter; }
1247 TRACY_API GpuCtxWrapper& GetGpuCtx() { return GetProfilerThreadData().gpuCtx; }
1248 TRACY_API uint32_t GetThreadHandle() { return detail::GetThreadHandleImpl(); }
1249 std::atomic<ThreadNameData*>& GetThreadNameData() { return GetProfilerData().threadNameData; }
1250
1251 # ifdef TRACY_ON_DEMAND
1252 TRACY_API LuaZoneState& GetLuaZoneState() { return GetProfilerThreadData().luaZoneState; }
1253 # endif
1254
1255 # ifndef TRACY_MANUAL_LIFETIME
1256 namespace
1257 {
1258 const auto& __profiler_init = GetProfiler();
1259 }
1260 # endif
1261
1262 #else
1263
1264 // MSVC static initialization order solution. gcc/clang uses init_order() to avoid all this.
1265
1266 // 1a. But s_queue is needed for initialization of variables in point 2.
1267 extern moodycamel::ConcurrentQueue<QueueItem> s_queue;
1268
1269 // 2. If these variables would be in the .CRT$XCB section, they would be initialized only in main thread.
1270 thread_local moodycamel::ProducerToken init_order(107) s_token_detail( s_queue );
1271 thread_local ProducerWrapper init_order(108) s_token { s_queue.get_explicit_producer( s_token_detail ) };
1272 thread_local ThreadHandleWrapper init_order(104) s_threadHandle { detail::GetThreadHandleImpl() };
1273
1274 # ifdef _MSC_VER
1275 // 1. Initialize these static variables before all other variables.
1276 # pragma warning( disable : 4075 )
1277 # pragma init_seg( ".CRT$XCB" )
1278 # endif
1279
1280 static InitTimeWrapper init_order(101) s_initTime { SetupHwTimer() };
1281 std::atomic<int> init_order(102) RpInitDone( 0 );
1282 std::atomic<int> init_order(102) RpInitLock( 0 );
1283 thread_local bool RpThreadInitDone = false;
1284 thread_local bool RpThreadShutdown = false;
1285 moodycamel::ConcurrentQueue<QueueItem> init_order(103) s_queue( QueuePrealloc );
1286 std::atomic<uint32_t> init_order(104) s_lockCounter( 0 );
1287 std::atomic<uint8_t> init_order(104) s_gpuCtxCounter( 0 );
1288
1289 thread_local GpuCtxWrapper init_order(104) s_gpuCtx { nullptr };
1290
1291 struct ThreadNameData;
1292 static std::atomic<ThreadNameData*> init_order(104) s_threadNameDataInstance( nullptr );
1293 std::atomic<ThreadNameData*>& s_threadNameData = s_threadNameDataInstance;
1294
1295 # ifdef TRACY_ON_DEMAND
1296 thread_local LuaZoneState init_order(104) s_luaZoneState { 0, false };
1297 # endif
1298
1299 static Profiler init_order(105) s_profiler;
1300
1301 TRACY_API moodycamel::ConcurrentQueue<QueueItem>::ExplicitProducer* GetToken() { return s_token.ptr; }
1302 TRACY_API Profiler& GetProfiler() { return s_profiler; }
1303 TRACY_API moodycamel::ConcurrentQueue<QueueItem>& GetQueue() { return s_queue; }
1304 TRACY_API int64_t GetInitTime() { return s_initTime.val; }
1305 TRACY_API std::atomic<uint32_t>& GetLockCounter() { return s_lockCounter; }
1306 TRACY_API std::atomic<uint8_t>& GetGpuCtxCounter() { return s_gpuCtxCounter; }
1307 TRACY_API GpuCtxWrapper& GetGpuCtx() { return s_gpuCtx; }
1308 TRACY_API uint32_t GetThreadHandle() { return s_threadHandle.val; }
1309
1310 std::atomic<ThreadNameData*>& GetThreadNameData() { return s_threadNameData; }
1311
1312 # ifdef TRACY_ON_DEMAND
1313 TRACY_API LuaZoneState& GetLuaZoneState() { return s_luaZoneState; }
1314 # endif
1315 #endif
1316
1317 TRACY_API bool ProfilerAvailable() { return s_instance != nullptr; }
1318 TRACY_API bool ProfilerAllocatorAvailable() { return !RpThreadShutdown; }
1319
1320 Profiler::Profiler()
1321 : m_timeBegin( 0 )
1322 , m_mainThread( detail::GetThreadHandleImpl() )
1323 , m_epoch( std::chrono::duration_cast<std::chrono::seconds>( std::chrono::system_clock::now().time_since_epoch() ).count() )
1324 , m_shutdown( false )
1325 , m_shutdownManual( false )
1326 , m_shutdownFinished( false )
1327 , m_sock( nullptr )
1328 , m_broadcast( nullptr )
1329 , m_noExit( false )
1330 , m_userPort( 0 )
1331 , m_zoneId( 1 )
1332 , m_samplingPeriod( 0 )
1333 , m_stream( LZ4_createStream() )
1334 , m_buffer( (char*)tracy_malloc( TargetFrameSize*3 ) )
1335 , m_bufferOffset( 0 )
1336 , m_bufferStart( 0 )
1337 , m_lz4Buf( (char*)tracy_malloc( LZ4Size + sizeof( lz4sz_t ) ) )
1338 , m_serialQueue( 1024*1024 )
1339 , m_serialDequeue( 1024*1024 )
1340 #ifndef TRACY_NO_FRAME_IMAGE
1341 , m_fiQueue( 16 )
1342 , m_fiDequeue( 16 )
1343 #endif
1344 , m_symbolQueue( 8*1024 )
1345 , m_frameCount( 0 )
1346 , m_isConnected( false )
1347 #ifdef TRACY_ON_DEMAND
1348 , m_connectionId( 0 )
1349 , m_deferredQueue( 64*1024 )
1350 #endif
1351 , m_paramCallback( nullptr )
1352 , m_sourceCallback( nullptr )
1353 , m_queryImage( nullptr )
1354 , m_queryData( nullptr )
1355 , m_crashHandlerInstalled( false )
1356 {
1357 assert( !s_instance );
1358 s_instance = this;
1359
1360 #ifndef TRACY_DELAYED_INIT
1361 # ifdef _MSC_VER
1362 // 3. But these variables need to be initialized in main thread within the .CRT$XCB section. Do it here.
1363 s_token_detail = moodycamel::ProducerToken( s_queue );
1364 s_token = ProducerWrapper { s_queue.get_explicit_producer( s_token_detail ) };
1365 s_threadHandle = ThreadHandleWrapper { m_mainThread };
1366 # endif
1367 #endif
1368
1369 CalibrateTimer();
1370 CalibrateDelay();
1371 ReportTopology();
1372
1373 #ifndef TRACY_NO_EXIT
1374 const char* noExitEnv = GetEnvVar( "TRACY_NO_EXIT" );
1375 if( noExitEnv && noExitEnv[0] == '1' )
1376 {
1377 m_noExit = true;
1378 }
1379 #endif
1380
1381 const char* userPort = GetEnvVar( "TRACY_PORT" );
1382 if( userPort )
1383 {
1384 m_userPort = atoi( userPort );
1385 }
1386
1387 #if !defined(TRACY_DELAYED_INIT) || !defined(TRACY_MANUAL_LIFETIME)
1388 SpawnWorkerThreads();
1389 #endif
1390 }
1391
1392 void Profiler::SpawnWorkerThreads()
1393 {
1394 #ifdef TRACY_HAS_SYSTEM_TRACING
1395 if( SysTraceStart( m_samplingPeriod ) )
1396 {
1397 s_sysTraceThread = (Thread*)tracy_malloc( sizeof( Thread ) );
1398 new(s_sysTraceThread) Thread( SysTraceWorker, nullptr );
1399 std::this_thread::sleep_for( std::chrono::milliseconds( 1 ) );
1400 }
1401 #endif
1402
1403 s_thread = (Thread*)tracy_malloc( sizeof( Thread ) );
1404 new(s_thread) Thread( LaunchWorker, this );
1405
1406 #ifndef TRACY_NO_FRAME_IMAGE
1407 s_compressThread = (Thread*)tracy_malloc( sizeof( Thread ) );
1408 new(s_compressThread) Thread( LaunchCompressWorker, this );
1409 #endif
1410
1411 #ifdef TRACY_HAS_CALLSTACK
1412 s_symbolThread = (Thread*)tracy_malloc( sizeof( Thread ) );
1413 new(s_symbolThread) Thread( LaunchSymbolWorker, this );
1414 #endif
1415
1416 #if defined _WIN32 && !defined TRACY_UWP && !defined TRACY_NO_CRASH_HANDLER
1417 s_profilerThreadId = GetThreadId( s_thread->Handle() );
1418 # ifdef TRACY_HAS_CALLSTACK
1419 s_symbolThreadId = GetThreadId( s_symbolThread->Handle() );
1420 # endif
1421 m_exceptionHandler = AddVectoredExceptionHandler( 1, CrashFilter );
1422 #endif
1423
1424 #if defined __linux__ && !defined TRACY_NO_CRASH_HANDLER
1425 struct sigaction threadFreezer = {};
1426 threadFreezer.sa_handler = ThreadFreezer;
1427 sigaction( TRACY_CRASH_SIGNAL, &threadFreezer, &m_prevSignal.pwr );
1428
1429 struct sigaction crashHandler = {};
1430 crashHandler.sa_sigaction = CrashHandler;
1431 crashHandler.sa_flags = SA_SIGINFO;
1432 sigaction( SIGILL, &crashHandler, &m_prevSignal.ill );
1433 sigaction( SIGFPE, &crashHandler, &m_prevSignal.fpe );
1434 sigaction( SIGSEGV, &crashHandler, &m_prevSignal.segv );
1435 sigaction( SIGPIPE, &crashHandler, &m_prevSignal.pipe );
1436 sigaction( SIGBUS, &crashHandler, &m_prevSignal.bus );
1437 sigaction( SIGABRT, &crashHandler, &m_prevSignal.abrt );
1438 #endif
1439
1440 #ifndef TRACY_NO_CRASH_HANDLER
1441 m_crashHandlerInstalled = true;
1442 #endif
1443
1444 #ifdef TRACY_HAS_CALLSTACK
1445 InitCallstackCritical();
1446 #endif
1447
1448 m_timeBegin.store( GetTime(), std::memory_order_relaxed );
1449 }
1450
1451 Profiler::~Profiler()
1452 {
1453 m_shutdown.store( true, std::memory_order_relaxed );
1454
1455 #if defined _WIN32 && !defined TRACY_UWP
1456 if( m_crashHandlerInstalled ) RemoveVectoredExceptionHandler( m_exceptionHandler );
1457 #endif
1458
1459 #if defined __linux__ && !defined TRACY_NO_CRASH_HANDLER
1460 if( m_crashHandlerInstalled )
1461 {
1462 sigaction( TRACY_CRASH_SIGNAL, &m_prevSignal.pwr, nullptr );
1463 sigaction( SIGILL, &m_prevSignal.ill, nullptr );
1464 sigaction( SIGFPE, &m_prevSignal.fpe, nullptr );
1465 sigaction( SIGSEGV, &m_prevSignal.segv, nullptr );
1466 sigaction( SIGPIPE, &m_prevSignal.pipe, nullptr );
1467 sigaction( SIGBUS, &m_prevSignal.bus, nullptr );
1468 sigaction( SIGABRT, &m_prevSignal.abrt, nullptr );
1469 }
1470 #endif
1471
1472 #ifdef TRACY_HAS_SYSTEM_TRACING
1473 if( s_sysTraceThread )
1474 {
1475 SysTraceStop();
1476 s_sysTraceThread->~Thread();
1477 tracy_free( s_sysTraceThread );
1478 }
1479 #endif
1480
1481 #ifdef TRACY_HAS_CALLSTACK
1482 s_symbolThread->~Thread();
1483 tracy_free( s_symbolThread );
1484 #endif
1485
1486 #ifndef TRACY_NO_FRAME_IMAGE
1487 s_compressThread->~Thread();
1488 tracy_free( s_compressThread );
1489 #endif
1490
1491 s_thread->~Thread();
1492 tracy_free( s_thread );
1493
1494 #ifdef TRACY_HAS_CALLSTACK
1495 EndCallstack();
1496 #endif
1497
1498 tracy_free( m_lz4Buf );
1499 tracy_free( m_buffer );
1500 LZ4_freeStream( (LZ4_stream_t*)m_stream );
1501
1502 if( m_sock )
1503 {
1504 m_sock->~Socket();
1505 tracy_free( m_sock );
1506 }
1507
1508 if( m_broadcast )
1509 {
1510 m_broadcast->~UdpBroadcast();
1511 tracy_free( m_broadcast );
1512 }
1513
1514 assert( s_instance );
1515 s_instance = nullptr;
1516 }
1517
1518 bool Profiler::ShouldExit()
1519 {
1520 return s_instance->m_shutdown.load( std::memory_order_relaxed );
1521 }
1522
1523 void Profiler::Worker()
1524 {
1525 #if defined __linux__ && !defined TRACY_NO_CRASH_HANDLER
1526 s_profilerTid = syscall( SYS_gettid );
1527 #endif
1528
1529 ThreadExitHandler threadExitHandler;
1530
1531 SetThreadName( "Tracy Profiler" );
1532
1533 #ifdef TRACY_DATA_PORT
1534 const bool dataPortSearch = false;
1535 auto dataPort = m_userPort != 0 ? m_userPort : TRACY_DATA_PORT;
1536 #else
1537 const bool dataPortSearch = m_userPort == 0;
1538 auto dataPort = m_userPort != 0 ? m_userPort : 8086;
1539 #endif
1540 #ifdef TRACY_BROADCAST_PORT
1541 const auto broadcastPort = TRACY_BROADCAST_PORT;
1542 #else
1543 const auto broadcastPort = 8086;
1544 #endif
1545
1546 while( m_timeBegin.load( std::memory_order_relaxed ) == 0 ) std::this_thread::sleep_for( std::chrono::milliseconds( 10 ) );
1547
1548 #ifdef TRACY_USE_RPMALLOC
1549 rpmalloc_thread_initialize();
1550 #endif
1551
1552 m_exectime = 0;
1553 const auto execname = GetProcessExecutablePath();
1554 if( execname )
1555 {
1556 struct stat st;
1557 if( stat( execname, &st ) == 0 )
1558 {
1559 m_exectime = (uint64_t)st.st_mtime;
1560 }
1561 }
1562
1563 const auto procname = GetProcessName();
1564 const auto pnsz = std::min<size_t>( strlen( procname ), WelcomeMessageProgramNameSize - 1 );
1565
1566 const auto hostinfo = GetHostInfo();
1567 const auto hisz = std::min<size_t>( strlen( hostinfo ), WelcomeMessageHostInfoSize - 1 );
1568
1569 const uint64_t pid = GetPid();
1570
1571 uint8_t flags = 0;
1572
1573 #ifdef TRACY_ON_DEMAND
1574 flags |= WelcomeFlag::OnDemand;
1575 #endif
1576 #ifdef __APPLE__
1577 flags |= WelcomeFlag::IsApple;
1578 #endif
1579 #ifndef TRACY_NO_CODE_TRANSFER
1580 flags |= WelcomeFlag::CodeTransfer;
1581 #endif
1582 #ifdef _WIN32
1583 flags |= WelcomeFlag::CombineSamples;
1584 # ifndef TRACY_NO_CONTEXT_SWITCH
1585 flags |= WelcomeFlag::IdentifySamples;
1586 # endif
1587 #endif
1588
1589 #if defined __i386 || defined _M_IX86
1590 uint8_t cpuArch = CpuArchX86;
1591 #elif defined __x86_64__ || defined _M_X64
1592 uint8_t cpuArch = CpuArchX64;
1593 #elif defined __aarch64__
1594 uint8_t cpuArch = CpuArchArm64;
1595 #elif defined __ARM_ARCH
1596 uint8_t cpuArch = CpuArchArm32;
1597 #else
1598 uint8_t cpuArch = CpuArchUnknown;
1599 #endif
1600
1601 #if defined __i386 || defined _M_IX86 || defined __x86_64__ || defined _M_X64
1602 uint32_t regs[4];
1603 char manufacturer[12];
1604 CpuId( regs, 0 );
1605 memcpy( manufacturer, regs+1, 4 );
1606 memcpy( manufacturer+4, regs+3, 4 );
1607 memcpy( manufacturer+8, regs+2, 4 );
1608
1609 CpuId( regs, 1 );
1610 uint32_t cpuId = ( regs[0] & 0xFFF ) | ( ( regs[0] & 0xFFF0000 ) >> 4 );
1611 #else
1612 const char manufacturer[12] = {};
1613 uint32_t cpuId = 0;
1614 #endif
1615
1616 WelcomeMessage welcome;
1617 MemWrite( &welcome.timerMul, m_timerMul );
1618 MemWrite( &welcome.initBegin, GetInitTime() );
1619 MemWrite( &welcome.initEnd, m_timeBegin.load( std::memory_order_relaxed ) );
1620 MemWrite( &welcome.delay, m_delay );
1621 MemWrite( &welcome.resolution, m_resolution );
1622 MemWrite( &welcome.epoch, m_epoch );
1623 MemWrite( &welcome.exectime, m_exectime );
1624 MemWrite( &welcome.pid, pid );
1625 MemWrite( &welcome.samplingPeriod, m_samplingPeriod );
1626 MemWrite( &welcome.flags, flags );
1627 MemWrite( &welcome.cpuArch, cpuArch );
1628 memcpy( welcome.cpuManufacturer, manufacturer, 12 );
1629 MemWrite( &welcome.cpuId, cpuId );
1630 memcpy( welcome.programName, procname, pnsz );
1631 memset( welcome.programName + pnsz, 0, WelcomeMessageProgramNameSize - pnsz );
1632 memcpy( welcome.hostInfo, hostinfo, hisz );
1633 memset( welcome.hostInfo + hisz, 0, WelcomeMessageHostInfoSize - hisz );
1634
1635 moodycamel::ConsumerToken token( GetQueue() );
1636
1637 ListenSocket listen;
1638 bool isListening = false;
1639 if( !dataPortSearch )
1640 {
1641 isListening = listen.Listen( dataPort, 4 );
1642 }
1643 else
1644 {
1645 for( uint32_t i=0; i<20; i++ )
1646 {
1647 if( listen.Listen( dataPort+i, 4 ) )
1648 {
1649 dataPort += i;
1650 isListening = true;
1651 break;
1652 }
1653 }
1654 }
1655 if( !isListening )
1656 {
1657 for(;;)
1658 {
1659 if( ShouldExit() )
1660 {
1661 m_shutdownFinished.store( true, std::memory_order_relaxed );
1662 return;
1663 }
1664
1665 ClearQueues( token );
1666 std::this_thread::sleep_for( std::chrono::milliseconds( 10 ) );
1667 }
1668 }
1669
1670 #ifndef TRACY_NO_BROADCAST
1671 m_broadcast = (UdpBroadcast*)tracy_malloc( sizeof( UdpBroadcast ) );
1672 new(m_broadcast) UdpBroadcast();
1673 # ifdef TRACY_ONLY_LOCALHOST
1674 const char* addr = "127.255.255.255";
1675 # else
1676 const char* addr = "255.255.255.255";
1677 # endif
1678 if( !m_broadcast->Open( addr, broadcastPort ) )
1679 {
1680 m_broadcast->~UdpBroadcast();
1681 tracy_free( m_broadcast );
1682 m_broadcast = nullptr;
1683 }
1684 #endif
1685
1686 int broadcastLen = 0;
1687 auto& broadcastMsg = GetBroadcastMessage( procname, pnsz, broadcastLen, dataPort );
1688 uint64_t lastBroadcast = 0;
1689
1690 // Connections loop.
1691 // Each iteration of the loop handles whole connection. Multiple iterations will only
1692 // happen in the on-demand mode or when handshake fails.
1693 for(;;)
1694 {
1695 // Wait for incoming connection
1696 for(;;)
1697 {
1698 #ifndef TRACY_NO_EXIT
1699 if( !m_noExit && ShouldExit() )
1700 {
1701 if( m_broadcast )
1702 {
1703 broadcastMsg.activeTime = -1;
1704 m_broadcast->Send( broadcastPort, &broadcastMsg, broadcastLen );
1705 }
1706 m_shutdownFinished.store( true, std::memory_order_relaxed );
1707 return;
1708 }
1709 #endif
1710 m_sock = listen.Accept();
1711 if( m_sock ) break;
1712 #ifndef TRACY_ON_DEMAND
1713 ProcessSysTime();
1714 #endif
1715
1716 if( m_broadcast )
1717 {
1718 const auto t = std::chrono::high_resolution_clock::now().time_since_epoch().count();
1719 if( t - lastBroadcast > 3000000000 ) // 3s
1720 {
1721 lastBroadcast = t;
1722 const auto ts = std::chrono::duration_cast<std::chrono::seconds>( std::chrono::system_clock::now().time_since_epoch() ).count();
1723 broadcastMsg.activeTime = int32_t( ts - m_epoch );
1724 assert( broadcastMsg.activeTime >= 0 );
1725 m_broadcast->Send( broadcastPort, &broadcastMsg, broadcastLen );
1726 }
1727 }
1728 }
1729
1730 if( m_broadcast )
1731 {
1732 lastBroadcast = 0;
1733 broadcastMsg.activeTime = -1;
1734 m_broadcast->Send( broadcastPort, &broadcastMsg, broadcastLen );
1735 }
1736
1737 // Handshake
1738 {
1739 char shibboleth[HandshakeShibbolethSize];
1740 auto res = m_sock->ReadRaw( shibboleth, HandshakeShibbolethSize, 2000 );
1741 if( !res || memcmp( shibboleth, HandshakeShibboleth, HandshakeShibbolethSize ) != 0 )
1742 {
1743 m_sock->~Socket();
1744 tracy_free( m_sock );
1745 m_sock = nullptr;
1746 continue;
1747 }
1748
1749 uint32_t protocolVersion;
1750 res = m_sock->ReadRaw( &protocolVersion, sizeof( protocolVersion ), 2000 );
1751 if( !res )
1752 {
1753 m_sock->~Socket();
1754 tracy_free( m_sock );
1755 m_sock = nullptr;
1756 continue;
1757 }
1758
1759 if( protocolVersion != ProtocolVersion )
1760 {
1761 HandshakeStatus status = HandshakeProtocolMismatch;
1762 m_sock->Send( &status, sizeof( status ) );
1763 m_sock->~Socket();
1764 tracy_free( m_sock );
1765 m_sock = nullptr;
1766 continue;
1767 }
1768 }
1769
1770 #ifdef TRACY_ON_DEMAND
1771 const auto currentTime = GetTime();
1772 ClearQueues( token );
1773 m_connectionId.fetch_add( 1, std::memory_order_release );
1774 #endif
1775 m_isConnected.store( true, std::memory_order_release );
1776
1777 HandshakeStatus handshake = HandshakeWelcome;
1778 m_sock->Send( &handshake, sizeof( handshake ) );
1779
1780 LZ4_resetStream( (LZ4_stream_t*)m_stream );
1781 m_sock->Send( &welcome, sizeof( welcome ) );
1782
1783 m_threadCtx = 0;
1784 m_refTimeSerial = 0;
1785 m_refTimeCtx = 0;
1786 m_refTimeGpu = 0;
1787
1788 #ifdef TRACY_ON_DEMAND
1789 OnDemandPayloadMessage onDemand;
1790 onDemand.frames = m_frameCount.load( std::memory_order_relaxed );
1791 onDemand.currentTime = currentTime;
1792
1793 m_sock->Send( &onDemand, sizeof( onDemand ) );
1794
1795 m_deferredLock.lock();
1796 for( auto& item : m_deferredQueue )
1797 {
1798 uint64_t ptr;
1799 uint16_t size;
1800 const auto idx = MemRead<uint8_t>( &item.hdr.idx );
1801 switch( (QueueType)idx )
1802 {
1803 case QueueType::MessageAppInfo:
1804 ptr = MemRead<uint64_t>( &item.messageFat.text );
1805 size = MemRead<uint16_t>( &item.messageFat.size );
1806 SendSingleString( (const char*)ptr, size );
1807 break;
1808 case QueueType::LockName:
1809 ptr = MemRead<uint64_t>( &item.lockNameFat.name );
1810 size = MemRead<uint16_t>( &item.lockNameFat.size );
1811 SendSingleString( (const char*)ptr, size );
1812 break;
1813 case QueueType::GpuContextName:
1814 ptr = MemRead<uint64_t>( &item.gpuContextNameFat.ptr );
1815 size = MemRead<uint16_t>( &item.gpuContextNameFat.size );
1816 SendSingleString( (const char*)ptr, size );
1817 break;
1818 default:
1819 break;
1820 }
1821 AppendData( &item, QueueDataSize[idx] );
1822 }
1823 m_deferredLock.unlock();
1824 #endif
1825
1826 // Main communications loop
1827 int keepAlive = 0;
1828 for(;;)
1829 {
1830 ProcessSysTime();
1831 const auto status = Dequeue( token );
1832 const auto serialStatus = DequeueSerial();
1833 if( status == DequeueStatus::ConnectionLost || serialStatus == DequeueStatus::ConnectionLost )
1834 {
1835 break;
1836 }
1837 else if( status == DequeueStatus::QueueEmpty && serialStatus == DequeueStatus::QueueEmpty )
1838 {
1839 if( ShouldExit() ) break;
1840 if( m_bufferOffset != m_bufferStart )
1841 {
1842 if( !CommitData() ) break;
1843 }
1844 if( keepAlive == 500 )
1845 {
1846 QueueItem ka;
1847 ka.hdr.type = QueueType::KeepAlive;
1848 AppendData( &ka, QueueDataSize[ka.hdr.idx] );
1849 if( !CommitData() ) break;
1850
1851 keepAlive = 0;
1852 }
1853 else if( !m_sock->HasData() )
1854 {
1855 keepAlive++;
1856 std::this_thread::sleep_for( std::chrono::milliseconds( 10 ) );
1857 }
1858 }
1859 else
1860 {
1861 keepAlive = 0;
1862 }
1863
1864 bool connActive = true;
1865 while( m_sock->HasData() )
1866 {
1867 connActive = HandleServerQuery();
1868 if( !connActive ) break;
1869 }
1870 if( !connActive ) break;
1871 }
1872 if( ShouldExit() ) break;
1873
1874 m_isConnected.store( false, std::memory_order_release );
1875 #ifdef TRACY_ON_DEMAND
1876 m_bufferOffset = 0;
1877 m_bufferStart = 0;
1878 #endif
1879
1880 m_sock->~Socket();
1881 tracy_free( m_sock );
1882 m_sock = nullptr;
1883
1884 #ifndef TRACY_ON_DEMAND
1885 // Client is no longer available here. Accept incoming connections, but reject handshake.
1886 for(;;)
1887 {
1888 if( ShouldExit() )
1889 {
1890 m_shutdownFinished.store( true, std::memory_order_relaxed );
1891 return;
1892 }
1893
1894 ClearQueues( token );
1895
1896 m_sock = listen.Accept();
1897 if( m_sock )
1898 {
1899 char shibboleth[HandshakeShibbolethSize];
1900 auto res = m_sock->ReadRaw( shibboleth, HandshakeShibbolethSize, 1000 );
1901 if( !res || memcmp( shibboleth, HandshakeShibboleth, HandshakeShibbolethSize ) != 0 )
1902 {
1903 m_sock->~Socket();
1904 tracy_free( m_sock );
1905 m_sock = nullptr;
1906 continue;
1907 }
1908
1909 uint32_t protocolVersion;
1910 res = m_sock->ReadRaw( &protocolVersion, sizeof( protocolVersion ), 1000 );
1911 if( !res )
1912 {
1913 m_sock->~Socket();
1914 tracy_free( m_sock );
1915 m_sock = nullptr;
1916 continue;
1917 }
1918
1919 HandshakeStatus status = HandshakeNotAvailable;
1920 m_sock->Send( &status, sizeof( status ) );
1921 m_sock->~Socket();
1922 tracy_free( m_sock );
1923 }
1924 }
1925 #endif
1926 }
1927 // End of connections loop
1928
1929 // Wait for symbols thread to terminate. Symbol resolution will continue in this thread.
1930 #ifdef TRACY_HAS_CALLSTACK
1931 while( s_symbolThreadGone.load() == false ) { YieldThread(); }
1932 #endif
1933
1934 // Client is exiting. Send items remaining in queues.
1935 for(;;)
1936 {
1937 const auto status = Dequeue( token );
1938 const auto serialStatus = DequeueSerial();
1939 if( status == DequeueStatus::ConnectionLost || serialStatus == DequeueStatus::ConnectionLost )
1940 {
1941 m_shutdownFinished.store( true, std::memory_order_relaxed );
1942 return;
1943 }
1944 else if( status == DequeueStatus::QueueEmpty && serialStatus == DequeueStatus::QueueEmpty )
1945 {
1946 if( m_bufferOffset != m_bufferStart ) CommitData();
1947 break;
1948 }
1949
1950 while( m_sock->HasData() )
1951 {
1952 if( !HandleServerQuery() )
1953 {
1954 m_shutdownFinished.store( true, std::memory_order_relaxed );
1955 return;
1956 }
1957 }
1958
1959 #ifdef TRACY_HAS_CALLSTACK
1960 for(;;)
1961 {
1962 auto si = m_symbolQueue.front();
1963 if( !si ) break;
1964 HandleSymbolQueueItem( *si );
1965 m_symbolQueue.pop();
1966 }
1967 #endif
1968 }
1969
1970 // Send client termination notice to the server
1971 QueueItem terminate;
1972 MemWrite( &terminate.hdr.type, QueueType::Terminate );
1973 if( !SendData( (const char*)&terminate, 1 ) )
1974 {
1975 m_shutdownFinished.store( true, std::memory_order_relaxed );
1976 return;
1977 }
1978 // Handle remaining server queries
1979 for(;;)
1980 {
1981 while( m_sock->HasData() )
1982 {
1983 if( !HandleServerQuery() )
1984 {
1985 m_shutdownFinished.store( true, std::memory_order_relaxed );
1986 return;
1987 }
1988 }
1989 #ifdef TRACY_HAS_CALLSTACK
1990 for(;;)
1991 {
1992 auto si = m_symbolQueue.front();
1993 if( !si ) break;
1994 HandleSymbolQueueItem( *si );
1995 m_symbolQueue.pop();
1996 }
1997 #endif
1998 const auto status = Dequeue( token );
1999 const auto serialStatus = DequeueSerial();
2000 if( status == DequeueStatus::ConnectionLost || serialStatus == DequeueStatus::ConnectionLost )
2001 {
2002 m_shutdownFinished.store( true, std::memory_order_relaxed );
2003 return;
2004 }
2005 if( m_bufferOffset != m_bufferStart )
2006 {
2007 if( !CommitData() )
2008 {
2009 m_shutdownFinished.store( true, std::memory_order_relaxed );
2010 return;
2011 }
2012 }
2013 }
2014 }
2015
2016 #ifndef TRACY_NO_FRAME_IMAGE
2017 void Profiler::CompressWorker()
2018 {
2019 ThreadExitHandler threadExitHandler;
2020 SetThreadName( "Tracy DXT1" );
2021 while( m_timeBegin.load( std::memory_order_relaxed ) == 0 ) std::this_thread::sleep_for( std::chrono::milliseconds( 10 ) );
2022
2023 #ifdef TRACY_USE_RPMALLOC
2024 rpmalloc_thread_initialize();
2025 #endif
2026
2027 for(;;)
2028 {
2029 const auto shouldExit = ShouldExit();
2030
2031 {
2032 bool lockHeld = true;
2033 while( !m_fiLock.try_lock() )
2034 {
2035 if( m_shutdownManual.load( std::memory_order_relaxed ) )
2036 {
2037 lockHeld = false;
2038 break;
2039 }
2040 }
2041 if( !m_fiQueue.empty() ) m_fiQueue.swap( m_fiDequeue );
2042 if( lockHeld )
2043 {
2044 m_fiLock.unlock();
2045 }
2046 }
2047
2048 const auto sz = m_fiDequeue.size();
2049 if( sz > 0 )
2050 {
2051 auto fi = m_fiDequeue.data();
2052 auto end = fi + sz;
2053 while( fi != end )
2054 {
2055 const auto w = fi->w;
2056 const auto h = fi->h;
2057 const auto csz = size_t( w * h / 2 );
2058 auto etc1buf = (char*)tracy_malloc( csz );
2059 CompressImageDxt1( (const char*)fi->image, etc1buf, w, h );
2060 tracy_free( fi->image );
2061
2062 TracyLfqPrepare( QueueType::FrameImage );
2063 MemWrite( &item->frameImageFat.image, (uint64_t)etc1buf );
2064 MemWrite( &item->frameImageFat.frame, fi->frame );
2065 MemWrite( &item->frameImageFat.w, w );
2066 MemWrite( &item->frameImageFat.h, h );
2067 uint8_t flip = fi->flip;
2068 MemWrite( &item->frameImageFat.flip, flip );
2069 TracyLfqCommit;
2070
2071 fi++;
2072 }
2073 m_fiDequeue.clear();
2074 }
2075 else
2076 {
2077 std::this_thread::sleep_for( std::chrono::milliseconds( 20 ) );
2078 }
2079
2080 if( shouldExit )
2081 {
2082 return;
2083 }
2084 }
2085 }
2086 #endif
2087
2088 static void FreeAssociatedMemory( const QueueItem& item )
2089 {
2090 if( item.hdr.idx >= (int)QueueType::Terminate ) return;
2091
2092 uint64_t ptr;
2093 switch( item.hdr.type )
2094 {
2095 case QueueType::ZoneText:
2096 case QueueType::ZoneName:
2097 ptr = MemRead<uint64_t>( &item.zoneTextFat.text );
2098 tracy_free( (void*)ptr );
2099 break;
2100 case QueueType::MessageColor:
2101 case QueueType::MessageColorCallstack:
2102 ptr = MemRead<uint64_t>( &item.messageColorFat.text );
2103 tracy_free( (void*)ptr );
2104 break;
2105 case QueueType::Message:
2106 case QueueType::MessageCallstack:
2107 #ifndef TRACY_ON_DEMAND
2108 case QueueType::MessageAppInfo:
2109 #endif
2110 ptr = MemRead<uint64_t>( &item.messageFat.text );
2111 tracy_free( (void*)ptr );
2112 break;
2113 case QueueType::ZoneBeginAllocSrcLoc:
2114 case QueueType::ZoneBeginAllocSrcLocCallstack:
2115 ptr = MemRead<uint64_t>( &item.zoneBegin.srcloc );
2116 tracy_free( (void*)ptr );
2117 break;
2118 case QueueType::GpuZoneBeginAllocSrcLoc:
2119 case QueueType::GpuZoneBeginAllocSrcLocCallstack:
2120 case QueueType::GpuZoneBeginAllocSrcLocSerial:
2121 case QueueType::GpuZoneBeginAllocSrcLocCallstackSerial:
2122 ptr = MemRead<uint64_t>( &item.gpuZoneBegin.srcloc );
2123 tracy_free( (void*)ptr );
2124 break;
2125 case QueueType::CallstackSerial:
2126 case QueueType::Callstack:
2127 ptr = MemRead<uint64_t>( &item.callstackFat.ptr );
2128 tracy_free( (void*)ptr );
2129 break;
2130 case QueueType::CallstackAlloc:
2131 ptr = MemRead<uint64_t>( &item.callstackAllocFat.nativePtr );
2132 tracy_free( (void*)ptr );
2133 ptr = MemRead<uint64_t>( &item.callstackAllocFat.ptr );
2134 tracy_free( (void*)ptr );
2135 break;
2136 case QueueType::CallstackSample:
2137 case QueueType::CallstackSampleContextSwitch:
2138 ptr = MemRead<uint64_t>( &item.callstackSampleFat.ptr );
2139 tracy_free( (void*)ptr );
2140 break;
2141 case QueueType::FrameImage:
2142 ptr = MemRead<uint64_t>( &item.frameImageFat.image );
2143 tracy_free( (void*)ptr );
2144 break;
2145 #ifdef TRACY_HAS_CALLSTACK
2146 case QueueType::CallstackFrameSize:
2147 {
2148 InitRpmalloc();
2149 auto size = MemRead<uint8_t>( &item.callstackFrameSizeFat.size );
2150 auto data = (const CallstackEntry*)MemRead<uint64_t>( &item.callstackFrameSizeFat.data );
2151 for( uint8_t i=0; i<size; i++ )
2152 {
2153 const auto& frame = data[i];
2154 tracy_free_fast( (void*)frame.name );
2155 tracy_free_fast( (void*)frame.file );
2156 }
2157 tracy_free_fast( (void*)data );
2158 break;
2159 }
2160 case QueueType::SymbolInformation:
2161 {
2162 uint8_t needFree = MemRead<uint8_t>( &item.symbolInformationFat.needFree );
2163 if( needFree )
2164 {
2165 ptr = MemRead<uint64_t>( &item.symbolInformationFat.fileString );
2166 tracy_free( (void*)ptr );
2167 }
2168 break;
2169 }
2170 case QueueType::SymbolCodeMetadata:
2171 ptr = MemRead<uint64_t>( &item.symbolCodeMetadata.ptr );
2172 tracy_free( (void*)ptr );
2173 break;
2174 #endif
2175 #ifndef TRACY_ON_DEMAND
2176 case QueueType::LockName:
2177 ptr = MemRead<uint64_t>( &item.lockNameFat.name );
2178 tracy_free( (void*)ptr );
2179 break;
2180 case QueueType::GpuContextName:
2181 ptr = MemRead<uint64_t>( &item.gpuContextNameFat.ptr );
2182 tracy_free( (void*)ptr );
2183 break;
2184 #endif
2185 #ifdef TRACY_ON_DEMAND
2186 case QueueType::MessageAppInfo:
2187 case QueueType::GpuContextName:
2188 // Don't free memory associated with deferred messages.
2189 break;
2190 #endif
2191 #ifdef TRACY_HAS_SYSTEM_TRACING
2192 case QueueType::ExternalNameMetadata:
2193 ptr = MemRead<uint64_t>( &item.externalNameMetadata.name );
2194 tracy_free( (void*)ptr );
2195 ptr = MemRead<uint64_t>( &item.externalNameMetadata.threadName );
2196 tracy_free_fast( (void*)ptr );
2197 break;
2198 #endif
2199 case QueueType::SourceCodeMetadata:
2200 ptr = MemRead<uint64_t>( &item.sourceCodeMetadata.ptr );
2201 tracy_free( (void*)ptr );
2202 break;
2203 default:
2204 break;
2205 }
2206 }
2207
2208 void Profiler::ClearQueues( moodycamel::ConsumerToken& token )
2209 {
2210 for(;;)
2211 {
2212 const auto sz = GetQueue().try_dequeue_bulk_single( token, [](const uint64_t&){}, []( QueueItem* item, size_t sz ) { assert( sz > 0 ); while( sz-- > 0 ) FreeAssociatedMemory( *item++ ); } );
2213 if( sz == 0 ) break;
2214 }
2215
2216 ClearSerial();
2217 }
2218
2219 void Profiler::ClearSerial()
2220 {
2221 bool lockHeld = true;
2222 while( !m_serialLock.try_lock() )
2223 {
2224 if( m_shutdownManual.load( std::memory_order_relaxed ) )
2225 {
2226 lockHeld = false;
2227 break;
2228 }
2229 }
2230 for( auto& v : m_serialQueue ) FreeAssociatedMemory( v );
2231 m_serialQueue.clear();
2232 if( lockHeld )
2233 {
2234 m_serialLock.unlock();
2235 }
2236
2237 for( auto& v : m_serialDequeue ) FreeAssociatedMemory( v );
2238 m_serialDequeue.clear();
2239 }
2240
2241 Profiler::DequeueStatus Profiler::Dequeue( moodycamel::ConsumerToken& token )
2242 {
2243 bool connectionLost = false;
2244 const auto sz = GetQueue().try_dequeue_bulk_single( token,
2245 [this, &connectionLost] ( const uint32_t& threadId )
2246 {
2247 if( ThreadCtxCheck( threadId ) == ThreadCtxStatus::ConnectionLost ) connectionLost = true;
2248 },
2249 [this, &connectionLost] ( QueueItem* item, size_t sz )
2250 {
2251 if( connectionLost ) return;
2252 InitRpmalloc();
2253 assert( sz > 0 );
2254 int64_t refThread = m_refTimeThread;
2255 int64_t refCtx = m_refTimeCtx;
2256 int64_t refGpu = m_refTimeGpu;
2257 while( sz-- > 0 )
2258 {
2259 uint64_t ptr;
2260 uint16_t size;
2261 auto idx = MemRead<uint8_t>( &item->hdr.idx );
2262 if( idx < (int)QueueType::Terminate )
2263 {
2264 switch( (QueueType)idx )
2265 {
2266 case QueueType::ZoneText:
2267 case QueueType::ZoneName:
2268 ptr = MemRead<uint64_t>( &item->zoneTextFat.text );
2269 size = MemRead<uint16_t>( &item->zoneTextFat.size );
2270 SendSingleString( (const char*)ptr, size );
2271 tracy_free_fast( (void*)ptr );
2272 break;
2273 case QueueType::Message:
2274 case QueueType::MessageCallstack:
2275 ptr = MemRead<uint64_t>( &item->messageFat.text );
2276 size = MemRead<uint16_t>( &item->messageFat.size );
2277 SendSingleString( (const char*)ptr, size );
2278 tracy_free_fast( (void*)ptr );
2279 break;
2280 case QueueType::MessageColor:
2281 case QueueType::MessageColorCallstack:
2282 ptr = MemRead<uint64_t>( &item->messageColorFat.text );
2283 size = MemRead<uint16_t>( &item->messageColorFat.size );
2284 SendSingleString( (const char*)ptr, size );
2285 tracy_free_fast( (void*)ptr );
2286 break;
2287 case QueueType::MessageAppInfo:
2288 ptr = MemRead<uint64_t>( &item->messageFat.text );
2289 size = MemRead<uint16_t>( &item->messageFat.size );
2290 SendSingleString( (const char*)ptr, size );
2291 #ifndef TRACY_ON_DEMAND
2292 tracy_free_fast( (void*)ptr );
2293 #endif
2294 break;
2295 case QueueType::ZoneBeginAllocSrcLoc:
2296 case QueueType::ZoneBeginAllocSrcLocCallstack:
2297 {
2298 int64_t t = MemRead<int64_t>( &item->zoneBegin.time );
2299 int64_t dt = t - refThread;
2300 refThread = t;
2301 MemWrite( &item->zoneBegin.time, dt );
2302 ptr = MemRead<uint64_t>( &item->zoneBegin.srcloc );
2303 SendSourceLocationPayload( ptr );
2304 tracy_free_fast( (void*)ptr );
2305 break;
2306 }
2307 case QueueType::Callstack:
2308 ptr = MemRead<uint64_t>( &item->callstackFat.ptr );
2309 SendCallstackPayload( ptr );
2310 tracy_free_fast( (void*)ptr );
2311 break;
2312 case QueueType::CallstackAlloc:
2313 ptr = MemRead<uint64_t>( &item->callstackAllocFat.nativePtr );
2314 if( ptr != 0 )
2315 {
2316 CutCallstack( (void*)ptr, "lua_pcall" );
2317 SendCallstackPayload( ptr );
2318 tracy_free_fast( (void*)ptr );
2319 }
2320 ptr = MemRead<uint64_t>( &item->callstackAllocFat.ptr );
2321 SendCallstackAlloc( ptr );
2322 tracy_free_fast( (void*)ptr );
2323 break;
2324 case QueueType::CallstackSample:
2325 case QueueType::CallstackSampleContextSwitch:
2326 {
2327 ptr = MemRead<uint64_t>( &item->callstackSampleFat.ptr );
2328 SendCallstackPayload64( ptr );
2329 tracy_free_fast( (void*)ptr );
2330 int64_t t = MemRead<int64_t>( &item->callstackSampleFat.time );
2331 int64_t dt = t - refCtx;
2332 refCtx = t;
2333 MemWrite( &item->callstackSampleFat.time, dt );
2334 break;
2335 }
2336 case QueueType::FrameImage:
2337 {
2338 ptr = MemRead<uint64_t>( &item->frameImageFat.image );
2339 const auto w = MemRead<uint16_t>( &item->frameImageFat.w );
2340 const auto h = MemRead<uint16_t>( &item->frameImageFat.h );
2341 const auto csz = size_t( w * h / 2 );
2342 SendLongString( ptr, (const char*)ptr, csz, QueueType::FrameImageData );
2343 tracy_free_fast( (void*)ptr );
2344 break;
2345 }
2346 case QueueType::ZoneBegin:
2347 case QueueType::ZoneBeginCallstack:
2348 {
2349 int64_t t = MemRead<int64_t>( &item->zoneBegin.time );
2350 int64_t dt = t - refThread;
2351 refThread = t;
2352 MemWrite( &item->zoneBegin.time, dt );
2353 break;
2354 }
2355 case QueueType::ZoneEnd:
2356 {
2357 int64_t t = MemRead<int64_t>( &item->zoneEnd.time );
2358 int64_t dt = t - refThread;
2359 refThread = t;
2360 MemWrite( &item->zoneEnd.time, dt );
2361 break;
2362 }
2363 case QueueType::GpuZoneBegin:
2364 case QueueType::GpuZoneBeginCallstack:
2365 {
2366 int64_t t = MemRead<int64_t>( &item->gpuZoneBegin.cpuTime );
2367 int64_t dt = t - refThread;
2368 refThread = t;
2369 MemWrite( &item->gpuZoneBegin.cpuTime, dt );
2370 break;
2371 }
2372 case QueueType::GpuZoneBeginAllocSrcLoc:
2373 case QueueType::GpuZoneBeginAllocSrcLocCallstack:
2374 {
2375 int64_t t = MemRead<int64_t>( &item->gpuZoneBegin.cpuTime );
2376 int64_t dt = t - refThread;
2377 refThread = t;
2378 MemWrite( &item->gpuZoneBegin.cpuTime, dt );
2379 ptr = MemRead<uint64_t>( &item->gpuZoneBegin.srcloc );
2380 SendSourceLocationPayload( ptr );
2381 tracy_free_fast( (void*)ptr );
2382 break;
2383 }
2384 case QueueType::GpuZoneEnd:
2385 {
2386 int64_t t = MemRead<int64_t>( &item->gpuZoneEnd.cpuTime );
2387 int64_t dt = t - refThread;
2388 refThread = t;
2389 MemWrite( &item->gpuZoneEnd.cpuTime, dt );
2390 break;
2391 }
2392 case QueueType::GpuContextName:
2393 ptr = MemRead<uint64_t>( &item->gpuContextNameFat.ptr );
2394 size = MemRead<uint16_t>( &item->gpuContextNameFat.size );
2395 SendSingleString( (const char*)ptr, size );
2396 #ifndef TRACY_ON_DEMAND
2397 tracy_free_fast( (void*)ptr );
2398 #endif
2399 break;
2400 case QueueType::PlotDataInt:
2401 case QueueType::PlotDataFloat:
2402 case QueueType::PlotDataDouble:
2403 {
2404 int64_t t = MemRead<int64_t>( &item->plotDataInt.time );
2405 int64_t dt = t - refThread;
2406 refThread = t;
2407 MemWrite( &item->plotDataInt.time, dt );
2408 break;
2409 }
2410 case QueueType::ContextSwitch:
2411 {
2412 int64_t t = MemRead<int64_t>( &item->contextSwitch.time );
2413 int64_t dt = t - refCtx;
2414 refCtx = t;
2415 MemWrite( &item->contextSwitch.time, dt );
2416 break;
2417 }
2418 case QueueType::ThreadWakeup:
2419 {
2420 int64_t t = MemRead<int64_t>( &item->threadWakeup.time );
2421 int64_t dt = t - refCtx;
2422 refCtx = t;
2423 MemWrite( &item->threadWakeup.time, dt );
2424 break;
2425 }
2426 case QueueType::GpuTime:
2427 {
2428 int64_t t = MemRead<int64_t>( &item->gpuTime.gpuTime );
2429 int64_t dt = t - refGpu;
2430 refGpu = t;
2431 MemWrite( &item->gpuTime.gpuTime, dt );
2432 break;
2433 }
2434 #ifdef TRACY_HAS_CALLSTACK
2435 case QueueType::CallstackFrameSize:
2436 {
2437 auto data = (const CallstackEntry*)MemRead<uint64_t>( &item->callstackFrameSizeFat.data );
2438 auto datasz = MemRead<uint8_t>( &item->callstackFrameSizeFat.size );
2439 auto imageName = (const char*)MemRead<uint64_t>( &item->callstackFrameSizeFat.imageName );
2440 SendSingleString( imageName );
2441 AppendData( item++, QueueDataSize[idx] );
2442
2443 for( uint8_t i=0; i<datasz; i++ )
2444 {
2445 const auto& frame = data[i];
2446
2447 SendSingleString( frame.name );
2448 SendSecondString( frame.file );
2449
2450 QueueItem item;
2451 MemWrite( &item.hdr.type, QueueType::CallstackFrame );
2452 MemWrite( &item.callstackFrame.line, frame.line );
2453 MemWrite( &item.callstackFrame.symAddr, frame.symAddr );
2454 MemWrite( &item.callstackFrame.symLen, frame.symLen );
2455
2456 AppendData( &item, QueueDataSize[(int)QueueType::CallstackFrame] );
2457
2458 tracy_free_fast( (void*)frame.name );
2459 tracy_free_fast( (void*)frame.file );
2460 }
2461 tracy_free_fast( (void*)data );
2462 continue;
2463 }
2464 case QueueType::SymbolInformation:
2465 {
2466 auto fileString = (const char*)MemRead<uint64_t>( &item->symbolInformationFat.fileString );
2467 auto needFree = MemRead<uint8_t>( &item->symbolInformationFat.needFree );
2468 SendSingleString( fileString );
2469 if( needFree ) tracy_free_fast( (void*)fileString );
2470 break;
2471 }
2472 case QueueType::SymbolCodeMetadata:
2473 {
2474 auto symbol = MemRead<uint64_t>( &item->symbolCodeMetadata.symbol );
2475 auto ptr = (const char*)MemRead<uint64_t>( &item->symbolCodeMetadata.ptr );
2476 auto size = MemRead<uint32_t>( &item->symbolCodeMetadata.size );
2477 SendLongString( symbol, ptr, size, QueueType::SymbolCode );
2478 tracy_free_fast( (void*)ptr );
2479 ++item;
2480 continue;
2481 }
2482 #endif
2483 #ifdef TRACY_HAS_SYSTEM_TRACING
2484 case QueueType::ExternalNameMetadata:
2485 {
2486 auto thread = MemRead<uint64_t>( &item->externalNameMetadata.thread );
2487 auto name = (const char*)MemRead<uint64_t>( &item->externalNameMetadata.name );
2488 auto threadName = (const char*)MemRead<uint64_t>( &item->externalNameMetadata.threadName );
2489 SendString( thread, threadName, QueueType::ExternalThreadName );
2490 SendString( thread, name, QueueType::ExternalName );
2491 tracy_free_fast( (void*)threadName );
2492 tracy_free_fast( (void*)name );
2493 ++item;
2494 continue;
2495 }
2496 #endif
2497 case QueueType::SourceCodeMetadata:
2498 {
2499 auto ptr = (const char*)MemRead<uint64_t>( &item->sourceCodeMetadata.ptr );
2500 auto size = MemRead<uint32_t>( &item->sourceCodeMetadata.size );
2501 auto id = MemRead<uint32_t>( &item->sourceCodeMetadata.id );
2502 SendLongString( (uint64_t)id, ptr, size, QueueType::SourceCode );
2503 tracy_free_fast( (void*)ptr );
2504 ++item;
2505 continue;
2506 }
2507 default:
2508 assert( false );
2509 break;
2510 }
2511 }
2512 if( !AppendData( item++, QueueDataSize[idx] ) )
2513 {
2514 connectionLost = true;
2515 m_refTimeThread = refThread;
2516 m_refTimeCtx = refCtx;
2517 m_refTimeGpu = refGpu;
2518 return;
2519 }
2520 }
2521 m_refTimeThread = refThread;
2522 m_refTimeCtx = refCtx;
2523 m_refTimeGpu = refGpu;
2524 }
2525 );
2526 if( connectionLost ) return DequeueStatus::ConnectionLost;
2527 return sz > 0 ? DequeueStatus::DataDequeued : DequeueStatus::QueueEmpty;
2528 }
2529
2530 Profiler::DequeueStatus Profiler::DequeueContextSwitches( tracy::moodycamel::ConsumerToken& token, int64_t& timeStop )
2531 {
2532 const auto sz = GetQueue().try_dequeue_bulk_single( token, [] ( const uint64_t& ) {},
2533 [this, &timeStop] ( QueueItem* item, size_t sz )
2534 {
2535 assert( sz > 0 );
2536 int64_t refCtx = m_refTimeCtx;
2537 while( sz-- > 0 )
2538 {
2539 FreeAssociatedMemory( *item );
2540 if( timeStop < 0 ) return;
2541 const auto idx = MemRead<uint8_t>( &item->hdr.idx );
2542 if( idx == (uint8_t)QueueType::ContextSwitch )
2543 {
2544 const auto csTime = MemRead<int64_t>( &item->contextSwitch.time );
2545 if( csTime > timeStop )
2546 {
2547 timeStop = -1;
2548 m_refTimeCtx = refCtx;
2549 return;
2550 }
2551 int64_t dt = csTime - refCtx;
2552 refCtx = csTime;
2553 MemWrite( &item->contextSwitch.time, dt );
2554 if( !AppendData( item, QueueDataSize[(int)QueueType::ContextSwitch] ) )
2555 {
2556 timeStop = -2;
2557 m_refTimeCtx = refCtx;
2558 return;
2559 }
2560 }
2561 else if( idx == (uint8_t)QueueType::ThreadWakeup )
2562 {
2563 const auto csTime = MemRead<int64_t>( &item->threadWakeup.time );
2564 if( csTime > timeStop )
2565 {
2566 timeStop = -1;
2567 m_refTimeCtx = refCtx;
2568 return;
2569 }
2570 int64_t dt = csTime - refCtx;
2571 refCtx = csTime;
2572 MemWrite( &item->threadWakeup.time, dt );
2573 if( !AppendData( item, QueueDataSize[(int)QueueType::ThreadWakeup] ) )
2574 {
2575 timeStop = -2;
2576 m_refTimeCtx = refCtx;
2577 return;
2578 }
2579 }
2580 item++;
2581 }
2582 m_refTimeCtx = refCtx;
2583 }
2584 );
2585
2586 if( timeStop == -2 ) return DequeueStatus::ConnectionLost;
2587 return ( timeStop == -1 || sz > 0 ) ? DequeueStatus::DataDequeued : DequeueStatus::QueueEmpty;
2588 }
2589
2590 #define ThreadCtxCheckSerial( _name ) \
2591 uint32_t thread = MemRead<uint32_t>( &item->_name.thread ); \
2592 switch( ThreadCtxCheck( thread ) ) \
2593 { \
2594 case ThreadCtxStatus::Same: break; \
2595 case ThreadCtxStatus::Changed: assert( m_refTimeThread == 0 ); refThread = 0; break; \
2596 case ThreadCtxStatus::ConnectionLost: return DequeueStatus::ConnectionLost; \
2597 default: assert( false ); break; \
2598 }
2599
2600 Profiler::DequeueStatus Profiler::DequeueSerial()
2601 {
2602 {
2603 bool lockHeld = true;
2604 while( !m_serialLock.try_lock() )
2605 {
2606 if( m_shutdownManual.load( std::memory_order_relaxed ) )
2607 {
2608 lockHeld = false;
2609 break;
2610 }
2611 }
2612 if( !m_serialQueue.empty() ) m_serialQueue.swap( m_serialDequeue );
2613 if( lockHeld )
2614 {
2615 m_serialLock.unlock();
2616 }
2617 }
2618
2619 const auto sz = m_serialDequeue.size();
2620 if( sz > 0 )
2621 {
2622 InitRpmalloc();
2623 int64_t refSerial = m_refTimeSerial;
2624 int64_t refGpu = m_refTimeGpu;
2625 #ifdef TRACY_FIBERS
2626 int64_t refThread = m_refTimeThread;
2627 #endif
2628 auto item = m_serialDequeue.data();
2629 auto end = item + sz;
2630 while( item != end )
2631 {
2632 uint64_t ptr;
2633 auto idx = MemRead<uint8_t>( &item->hdr.idx );
2634 if( idx < (int)QueueType::Terminate )
2635 {
2636 switch( (QueueType)idx )
2637 {
2638 case QueueType::CallstackSerial:
2639 ptr = MemRead<uint64_t>( &item->callstackFat.ptr );
2640 SendCallstackPayload( ptr );
2641 tracy_free_fast( (void*)ptr );
2642 break;
2643 case QueueType::LockWait:
2644 case QueueType::LockSharedWait:
2645 {
2646 int64_t t = MemRead<int64_t>( &item->lockWait.time );
2647 int64_t dt = t - refSerial;
2648 refSerial = t;
2649 MemWrite( &item->lockWait.time, dt );
2650 break;
2651 }
2652 case QueueType::LockObtain:
2653 case QueueType::LockSharedObtain:
2654 {
2655 int64_t t = MemRead<int64_t>( &item->lockObtain.time );
2656 int64_t dt = t - refSerial;
2657 refSerial = t;
2658 MemWrite( &item->lockObtain.time, dt );
2659 break;
2660 }
2661 case QueueType::LockRelease:
2662 case QueueType::LockSharedRelease:
2663 {
2664 int64_t t = MemRead<int64_t>( &item->lockRelease.time );
2665 int64_t dt = t - refSerial;
2666 refSerial = t;
2667 MemWrite( &item->lockRelease.time, dt );
2668 break;
2669 }
2670 case QueueType::LockName:
2671 {
2672 ptr = MemRead<uint64_t>( &item->lockNameFat.name );
2673 uint16_t size = MemRead<uint16_t>( &item->lockNameFat.size );
2674 SendSingleString( (const char*)ptr, size );
2675 #ifndef TRACY_ON_DEMAND
2676 tracy_free_fast( (void*)ptr );
2677 #endif
2678 break;
2679 }
2680 case QueueType::MemAlloc:
2681 case QueueType::MemAllocNamed:
2682 case QueueType::MemAllocCallstack:
2683 case QueueType::MemAllocCallstackNamed:
2684 {
2685 int64_t t = MemRead<int64_t>( &item->memAlloc.time );
2686 int64_t dt = t - refSerial;
2687 refSerial = t;
2688 MemWrite( &item->memAlloc.time, dt );
2689 break;
2690 }
2691 case QueueType::MemFree:
2692 case QueueType::MemFreeNamed:
2693 case QueueType::MemFreeCallstack:
2694 case QueueType::MemFreeCallstackNamed:
2695 {
2696 int64_t t = MemRead<int64_t>( &item->memFree.time );
2697 int64_t dt = t - refSerial;
2698 refSerial = t;
2699 MemWrite( &item->memFree.time, dt );
2700 break;
2701 }
2702 case QueueType::GpuZoneBeginSerial:
2703 case QueueType::GpuZoneBeginCallstackSerial:
2704 {
2705 int64_t t = MemRead<int64_t>( &item->gpuZoneBegin.cpuTime );
2706 int64_t dt = t - refSerial;
2707 refSerial = t;
2708 MemWrite( &item->gpuZoneBegin.cpuTime, dt );
2709 break;
2710 }
2711 case QueueType::GpuZoneBeginAllocSrcLocSerial:
2712 case QueueType::GpuZoneBeginAllocSrcLocCallstackSerial:
2713 {
2714 int64_t t = MemRead<int64_t>( &item->gpuZoneBegin.cpuTime );
2715 int64_t dt = t - refSerial;
2716 refSerial = t;
2717 MemWrite( &item->gpuZoneBegin.cpuTime, dt );
2718 ptr = MemRead<uint64_t>( &item->gpuZoneBegin.srcloc );
2719 SendSourceLocationPayload( ptr );
2720 tracy_free_fast( (void*)ptr );
2721 break;
2722 }
2723 case QueueType::GpuZoneEndSerial:
2724 {
2725 int64_t t = MemRead<int64_t>( &item->gpuZoneEnd.cpuTime );
2726 int64_t dt = t - refSerial;
2727 refSerial = t;
2728 MemWrite( &item->gpuZoneEnd.cpuTime, dt );
2729 break;
2730 }
2731 case QueueType::GpuTime:
2732 {
2733 int64_t t = MemRead<int64_t>( &item->gpuTime.gpuTime );
2734 int64_t dt = t - refGpu;
2735 refGpu = t;
2736 MemWrite( &item->gpuTime.gpuTime, dt );
2737 break;
2738 }
2739 case QueueType::GpuContextName:
2740 {
2741 ptr = MemRead<uint64_t>( &item->gpuContextNameFat.ptr );
2742 uint16_t size = MemRead<uint16_t>( &item->gpuContextNameFat.size );
2743 SendSingleString( (const char*)ptr, size );
2744 #ifndef TRACY_ON_DEMAND
2745 tracy_free_fast( (void*)ptr );
2746 #endif
2747 break;
2748 }
2749 #ifdef TRACY_FIBERS
2750 case QueueType::ZoneBegin:
2751 case QueueType::ZoneBeginCallstack:
2752 {
2753 ThreadCtxCheckSerial( zoneBeginThread );
2754 int64_t t = MemRead<int64_t>( &item->zoneBegin.time );
2755 int64_t dt = t - refThread;
2756 refThread = t;
2757 MemWrite( &item->zoneBegin.time, dt );
2758 break;
2759 }
2760 case QueueType::ZoneBeginAllocSrcLoc:
2761 case QueueType::ZoneBeginAllocSrcLocCallstack:
2762 {
2763 ThreadCtxCheckSerial( zoneBeginThread );
2764 int64_t t = MemRead<int64_t>( &item->zoneBegin.time );
2765 int64_t dt = t - refThread;
2766 refThread = t;
2767 MemWrite( &item->zoneBegin.time, dt );
2768 ptr = MemRead<uint64_t>( &item->zoneBegin.srcloc );
2769 SendSourceLocationPayload( ptr );
2770 tracy_free_fast( (void*)ptr );
2771 break;
2772 }
2773 case QueueType::ZoneEnd:
2774 {
2775 ThreadCtxCheckSerial( zoneEndThread );
2776 int64_t t = MemRead<int64_t>( &item->zoneEnd.time );
2777 int64_t dt = t - refThread;
2778 refThread = t;
2779 MemWrite( &item->zoneEnd.time, dt );
2780 break;
2781 }
2782 case QueueType::ZoneText:
2783 case QueueType::ZoneName:
2784 {
2785 ThreadCtxCheckSerial( zoneTextFatThread );
2786 ptr = MemRead<uint64_t>( &item->zoneTextFat.text );
2787 uint16_t size = MemRead<uint16_t>( &item->zoneTextFat.size );
2788 SendSingleString( (const char*)ptr, size );
2789 tracy_free_fast( (void*)ptr );
2790 break;
2791 }
2792 case QueueType::Message:
2793 case QueueType::MessageCallstack:
2794 {
2795 ThreadCtxCheckSerial( messageFatThread );
2796 ptr = MemRead<uint64_t>( &item->messageFat.text );
2797 uint16_t size = MemRead<uint16_t>( &item->messageFat.size );
2798 SendSingleString( (const char*)ptr, size );
2799 tracy_free_fast( (void*)ptr );
2800 break;
2801 }
2802 case QueueType::MessageColor:
2803 case QueueType::MessageColorCallstack:
2804 {
2805 ThreadCtxCheckSerial( messageColorFatThread );
2806 ptr = MemRead<uint64_t>( &item->messageColorFat.text );
2807 uint16_t size = MemRead<uint16_t>( &item->messageColorFat.size );
2808 SendSingleString( (const char*)ptr, size );
2809 tracy_free_fast( (void*)ptr );
2810 break;
2811 }
2812 case QueueType::Callstack:
2813 {
2814 ThreadCtxCheckSerial( callstackFatThread );
2815 ptr = MemRead<uint64_t>( &item->callstackFat.ptr );
2816 SendCallstackPayload( ptr );
2817 tracy_free_fast( (void*)ptr );
2818 break;
2819 }
2820 case QueueType::CallstackAlloc:
2821 {
2822 ThreadCtxCheckSerial( callstackAllocFatThread );
2823 ptr = MemRead<uint64_t>( &item->callstackAllocFat.nativePtr );
2824 if( ptr != 0 )
2825 {
2826 CutCallstack( (void*)ptr, "lua_pcall" );
2827 SendCallstackPayload( ptr );
2828 tracy_free_fast( (void*)ptr );
2829 }
2830 ptr = MemRead<uint64_t>( &item->callstackAllocFat.ptr );
2831 SendCallstackAlloc( ptr );
2832 tracy_free_fast( (void*)ptr );
2833 break;
2834 }
2835 case QueueType::FiberEnter:
2836 {
2837 ThreadCtxCheckSerial( fiberEnter );
2838 int64_t t = MemRead<int64_t>( &item->fiberEnter.time );
2839 int64_t dt = t - refThread;
2840 refThread = t;
2841 MemWrite( &item->fiberEnter.time, dt );
2842 break;
2843 }
2844 case QueueType::FiberLeave:
2845 {
2846 ThreadCtxCheckSerial( fiberLeave );
2847 int64_t t = MemRead<int64_t>( &item->fiberLeave.time );
2848 int64_t dt = t - refThread;
2849 refThread = t;
2850 MemWrite( &item->fiberLeave.time, dt );
2851 break;
2852 }
2853 #endif
2854 default:
2855 assert( false );
2856 break;
2857 }
2858 }
2859 #ifdef TRACY_FIBERS
2860 else
2861 {
2862 switch( (QueueType)idx )
2863 {
2864 case QueueType::ZoneColor:
2865 {
2866 ThreadCtxCheckSerial( zoneColorThread );
2867 break;
2868 }
2869 case QueueType::ZoneValue:
2870 {
2871 ThreadCtxCheckSerial( zoneValueThread );
2872 break;
2873 }
2874 case QueueType::ZoneValidation:
2875 {
2876 ThreadCtxCheckSerial( zoneValidationThread );
2877 break;
2878 }
2879 case QueueType::MessageLiteral:
2880 case QueueType::MessageLiteralCallstack:
2881 {
2882 ThreadCtxCheckSerial( messageLiteralThread );
2883 break;
2884 }
2885 case QueueType::MessageLiteralColor:
2886 case QueueType::MessageLiteralColorCallstack:
2887 {
2888 ThreadCtxCheckSerial( messageColorLiteralThread );
2889 break;
2890 }
2891 case QueueType::CrashReport:
2892 {
2893 ThreadCtxCheckSerial( crashReportThread );
2894 break;
2895 }
2896 default:
2897 break;
2898 }
2899 }
2900 #endif
2901 if( !AppendData( item, QueueDataSize[idx] ) ) return DequeueStatus::ConnectionLost;
2902 item++;
2903 }
2904 m_refTimeSerial = refSerial;
2905 m_refTimeGpu = refGpu;
2906 #ifdef TRACY_FIBERS
2907 m_refTimeThread = refThread;
2908 #endif
2909 m_serialDequeue.clear();
2910 }
2911 else
2912 {
2913 return DequeueStatus::QueueEmpty;
2914 }
2915 return DequeueStatus::DataDequeued;
2916 }
2917
2918 Profiler::ThreadCtxStatus Profiler::ThreadCtxCheck( uint32_t threadId )
2919 {
2920 if( m_threadCtx == threadId ) return ThreadCtxStatus::Same;
2921 QueueItem item;
2922 MemWrite( &item.hdr.type, QueueType::ThreadContext );
2923 MemWrite( &item.threadCtx.thread, threadId );
2924 if( !AppendData( &item, QueueDataSize[(int)QueueType::ThreadContext] ) ) return ThreadCtxStatus::ConnectionLost;
2925 m_threadCtx = threadId;
2926 m_refTimeThread = 0;
2927 return ThreadCtxStatus::Changed;
2928 }
2929
2930 bool Profiler::CommitData()
2931 {
2932 bool ret = SendData( m_buffer + m_bufferStart, m_bufferOffset - m_bufferStart );
2933 if( m_bufferOffset > TargetFrameSize * 2 ) m_bufferOffset = 0;
2934 m_bufferStart = m_bufferOffset;
2935 return ret;
2936 }
2937
2938 bool Profiler::SendData( const char* data, size_t len )
2939 {
2940 const lz4sz_t lz4sz = LZ4_compress_fast_continue( (LZ4_stream_t*)m_stream, data, m_lz4Buf + sizeof( lz4sz_t ), (int)len, LZ4Size, 1 );
2941 memcpy( m_lz4Buf, &lz4sz, sizeof( lz4sz ) );
2942 return m_sock->Send( m_lz4Buf, lz4sz + sizeof( lz4sz_t ) ) != -1;
2943 }
2944
2945 void Profiler::SendString( uint64_t str, const char* ptr, size_t len, QueueType type )
2946 {
2947 assert( type == QueueType::StringData ||
2948 type == QueueType::ThreadName ||
2949 type == QueueType::PlotName ||
2950 type == QueueType::FrameName ||
2951 type == QueueType::ExternalName ||
2952 type == QueueType::ExternalThreadName ||
2953 type == QueueType::FiberName );
2954
2955 QueueItem item;
2956 MemWrite( &item.hdr.type, type );
2957 MemWrite( &item.stringTransfer.ptr, str );
2958
2959 assert( len <= std::numeric_limits<uint16_t>::max() );
2960 auto l16 = uint16_t( len );
2961
2962 NeedDataSize( QueueDataSize[(int)type] + sizeof( l16 ) + l16 );
2963
2964 AppendDataUnsafe( &item, QueueDataSize[(int)type] );
2965 AppendDataUnsafe( &l16, sizeof( l16 ) );
2966 AppendDataUnsafe( ptr, l16 );
2967 }
2968
2969 void Profiler::SendSingleString( const char* ptr, size_t len )
2970 {
2971 QueueItem item;
2972 MemWrite( &item.hdr.type, QueueType::SingleStringData );
2973
2974 assert( len <= std::numeric_limits<uint16_t>::max() );
2975 auto l16 = uint16_t( len );
2976
2977 NeedDataSize( QueueDataSize[(int)QueueType::SingleStringData] + sizeof( l16 ) + l16 );
2978
2979 AppendDataUnsafe( &item, QueueDataSize[(int)QueueType::SingleStringData] );
2980 AppendDataUnsafe( &l16, sizeof( l16 ) );
2981 AppendDataUnsafe( ptr, l16 );
2982 }
2983
2984 void Profiler::SendSecondString( const char* ptr, size_t len )
2985 {
2986 QueueItem item;
2987 MemWrite( &item.hdr.type, QueueType::SecondStringData );
2988
2989 assert( len <= std::numeric_limits<uint16_t>::max() );
2990 auto l16 = uint16_t( len );
2991
2992 NeedDataSize( QueueDataSize[(int)QueueType::SecondStringData] + sizeof( l16 ) + l16 );
2993
2994 AppendDataUnsafe( &item, QueueDataSize[(int)QueueType::SecondStringData] );
2995 AppendDataUnsafe( &l16, sizeof( l16 ) );
2996 AppendDataUnsafe( ptr, l16 );
2997 }
2998
2999 void Profiler::SendLongString( uint64_t str, const char* ptr, size_t len, QueueType type )
3000 {
3001 assert( type == QueueType::FrameImageData ||
3002 type == QueueType::SymbolCode ||
3003 type == QueueType::SourceCode );
3004
3005 QueueItem item;
3006 MemWrite( &item.hdr.type, type );
3007 MemWrite( &item.stringTransfer.ptr, str );
3008
3009 assert( len <= std::numeric_limits<uint32_t>::max() );
3010 assert( QueueDataSize[(int)type] + sizeof( uint32_t ) + len <= TargetFrameSize );
3011 auto l32 = uint32_t( len );
3012
3013 NeedDataSize( QueueDataSize[(int)type] + sizeof( l32 ) + l32 );
3014
3015 AppendDataUnsafe( &item, QueueDataSize[(int)type] );
3016 AppendDataUnsafe( &l32, sizeof( l32 ) );
3017 AppendDataUnsafe( ptr, l32 );
3018 }
3019
3020 void Profiler::SendSourceLocation( uint64_t ptr )
3021 {
3022 auto srcloc = (const SourceLocationData*)ptr;
3023 QueueItem item;
3024 MemWrite( &item.hdr.type, QueueType::SourceLocation );
3025 MemWrite( &item.srcloc.name, (uint64_t)srcloc->name );
3026 MemWrite( &item.srcloc.file, (uint64_t)srcloc->file );
3027 MemWrite( &item.srcloc.function, (uint64_t)srcloc->function );
3028 MemWrite( &item.srcloc.line, srcloc->line );
3029 MemWrite( &item.srcloc.b, uint8_t( ( srcloc->color ) & 0xFF ) );
3030 MemWrite( &item.srcloc.g, uint8_t( ( srcloc->color >> 8 ) & 0xFF ) );
3031 MemWrite( &item.srcloc.r, uint8_t( ( srcloc->color >> 16 ) & 0xFF ) );
3032 AppendData( &item, QueueDataSize[(int)QueueType::SourceLocation] );
3033 }
3034
3035 void Profiler::SendSourceLocationPayload( uint64_t _ptr )
3036 {
3037 auto ptr = (const char*)_ptr;
3038
3039 QueueItem item;
3040 MemWrite( &item.hdr.type, QueueType::SourceLocationPayload );
3041 MemWrite( &item.stringTransfer.ptr, _ptr );
3042
3043 uint16_t len;
3044 memcpy( &len, ptr, sizeof( len ) );
3045 assert( len > 2 );
3046 len -= 2;
3047 ptr += 2;
3048
3049 NeedDataSize( QueueDataSize[(int)QueueType::SourceLocationPayload] + sizeof( len ) + len );
3050
3051 AppendDataUnsafe( &item, QueueDataSize[(int)QueueType::SourceLocationPayload] );
3052 AppendDataUnsafe( &len, sizeof( len ) );
3053 AppendDataUnsafe( ptr, len );
3054 }
3055
3056 void Profiler::SendCallstackPayload( uint64_t _ptr )
3057 {
3058 auto ptr = (uintptr_t*)_ptr;
3059
3060 QueueItem item;
3061 MemWrite( &item.hdr.type, QueueType::CallstackPayload );
3062 MemWrite( &item.stringTransfer.ptr, _ptr );
3063
3064 const auto sz = *ptr++;
3065 const auto len = sz * sizeof( uint64_t );
3066 const auto l16 = uint16_t( len );
3067
3068 NeedDataSize( QueueDataSize[(int)QueueType::CallstackPayload] + sizeof( l16 ) + l16 );
3069
3070 AppendDataUnsafe( &item, QueueDataSize[(int)QueueType::CallstackPayload] );
3071 AppendDataUnsafe( &l16, sizeof( l16 ) );
3072
3073 if( compile_time_condition<sizeof( uintptr_t ) == sizeof( uint64_t )>::value )
3074 {
3075 AppendDataUnsafe( ptr, sizeof( uint64_t ) * sz );
3076 }
3077 else
3078 {
3079 for( uintptr_t i=0; i<sz; i++ )
3080 {
3081 const auto val = uint64_t( *ptr++ );
3082 AppendDataUnsafe( &val, sizeof( uint64_t ) );
3083 }
3084 }
3085 }
3086
3087 void Profiler::SendCallstackPayload64( uint64_t _ptr )
3088 {
3089 auto ptr = (uint64_t*)_ptr;
3090
3091 QueueItem item;
3092 MemWrite( &item.hdr.type, QueueType::CallstackPayload );
3093 MemWrite( &item.stringTransfer.ptr, _ptr );
3094
3095 const auto sz = *ptr++;
3096 const auto len = sz * sizeof( uint64_t );
3097 const auto l16 = uint16_t( len );
3098
3099 NeedDataSize( QueueDataSize[(int)QueueType::CallstackPayload] + sizeof( l16 ) + l16 );
3100
3101 AppendDataUnsafe( &item, QueueDataSize[(int)QueueType::CallstackPayload] );
3102 AppendDataUnsafe( &l16, sizeof( l16 ) );
3103 AppendDataUnsafe( ptr, sizeof( uint64_t ) * sz );
3104 }
3105
3106 void Profiler::SendCallstackAlloc( uint64_t _ptr )
3107 {
3108 auto ptr = (const char*)_ptr;
3109
3110 QueueItem item;
3111 MemWrite( &item.hdr.type, QueueType::CallstackAllocPayload );
3112 MemWrite( &item.stringTransfer.ptr, _ptr );
3113
3114 uint16_t len;
3115 memcpy( &len, ptr, 2 );
3116 ptr += 2;
3117
3118 NeedDataSize( QueueDataSize[(int)QueueType::CallstackAllocPayload] + sizeof( len ) + len );
3119
3120 AppendDataUnsafe( &item, QueueDataSize[(int)QueueType::CallstackAllocPayload] );
3121 AppendDataUnsafe( &len, sizeof( len ) );
3122 AppendDataUnsafe( ptr, len );
3123 }
3124
3125 void Profiler::QueueCallstackFrame( uint64_t ptr )
3126 {
3127 #ifdef TRACY_HAS_CALLSTACK
3128 m_symbolQueue.emplace( SymbolQueueItem { SymbolQueueItemType::CallstackFrame, ptr } );
3129 #else
3130 AckServerQuery();
3131 #endif
3132 }
3133
3134 void Profiler::QueueSymbolQuery( uint64_t symbol )
3135 {
3136 #ifdef TRACY_HAS_CALLSTACK
3137 // Special handling for kernel frames
3138 if( symbol >> 63 != 0 )
3139 {
3140 SendSingleString( "<kernel>" );
3141 QueueItem item;
3142 MemWrite( &item.hdr.type, QueueType::SymbolInformation );
3143 MemWrite( &item.symbolInformation.line, 0 );
3144 MemWrite( &item.symbolInformation.symAddr, symbol );
3145 AppendData( &item, QueueDataSize[(int)QueueType::SymbolInformation] );
3146 }
3147 else
3148 {
3149 m_symbolQueue.emplace( SymbolQueueItem { SymbolQueueItemType::SymbolQuery, symbol } );
3150 }
3151 #else
3152 AckServerQuery();
3153 #endif
3154 }
3155
3156 void Profiler::QueueExternalName( uint64_t ptr )
3157 {
3158 #ifdef TRACY_HAS_SYSTEM_TRACING
3159 m_symbolQueue.emplace( SymbolQueueItem { SymbolQueueItemType::ExternalName, ptr } );
3160 #endif
3161 }
3162
3163 void Profiler::QueueKernelCode( uint64_t symbol, uint32_t size )
3164 {
3165 assert( symbol >> 63 != 0 );
3166 #ifdef TRACY_HAS_CALLSTACK
3167 m_symbolQueue.emplace( SymbolQueueItem { SymbolQueueItemType::KernelCode, symbol, size } );
3168 #else
3169 AckSymbolCodeNotAvailable();
3170 #endif
3171 }
3172
3173 void Profiler::QueueSourceCodeQuery( uint32_t id )
3174 {
3175 assert( m_exectime != 0 );
3176 assert( m_queryData );
3177 m_symbolQueue.emplace( SymbolQueueItem { SymbolQueueItemType::SourceCode, uint64_t( m_queryData ), uint64_t( m_queryImage ), id } );
3178 m_queryData = nullptr;
3179 m_queryImage = nullptr;
3180 }
3181
3182 #ifdef TRACY_HAS_CALLSTACK
3183 void Profiler::HandleSymbolQueueItem( const SymbolQueueItem& si )
3184 {
3185 switch( si.type )
3186 {
3187 case SymbolQueueItemType::CallstackFrame:
3188 {
3189 const auto frameData = DecodeCallstackPtr( si.ptr );
3190 auto data = tracy_malloc_fast( sizeof( CallstackEntry ) * frameData.size );
3191 memcpy( data, frameData.data, sizeof( CallstackEntry ) * frameData.size );
3192 TracyLfqPrepare( QueueType::CallstackFrameSize );
3193 MemWrite( &item->callstackFrameSizeFat.ptr, si.ptr );
3194 MemWrite( &item->callstackFrameSizeFat.size, frameData.size );
3195 MemWrite( &item->callstackFrameSizeFat.data, (uint64_t)data );
3196 MemWrite( &item->callstackFrameSizeFat.imageName, (uint64_t)frameData.imageName );
3197 TracyLfqCommit;
3198 break;
3199 }
3200 case SymbolQueueItemType::SymbolQuery:
3201 {
3202 #ifdef __ANDROID__
3203 // On Android it's common for code to be in mappings that are only executable
3204 // but not readable.
3205 if( !EnsureReadable( si.ptr ) )
3206 {
3207 TracyLfqPrepare( QueueType::AckServerQueryNoop );
3208 TracyLfqCommit;
3209 break;
3210 }
3211 #endif
3212 const auto sym = DecodeSymbolAddress( si.ptr );
3213 TracyLfqPrepare( QueueType::SymbolInformation );
3214 MemWrite( &item->symbolInformationFat.line, sym.line );
3215 MemWrite( &item->symbolInformationFat.symAddr, si.ptr );
3216 MemWrite( &item->symbolInformationFat.fileString, (uint64_t)sym.file );
3217 MemWrite( &item->symbolInformationFat.needFree, (uint8_t)sym.needFree );
3218 TracyLfqCommit;
3219 break;
3220 }
3221 #ifdef TRACY_HAS_SYSTEM_TRACING
3222 case SymbolQueueItemType::ExternalName:
3223 {
3224 const char* threadName;
3225 const char* name;
3226 SysTraceGetExternalName( si.ptr, threadName, name );
3227 TracyLfqPrepare( QueueType::ExternalNameMetadata );
3228 MemWrite( &item->externalNameMetadata.thread, si.ptr );
3229 MemWrite( &item->externalNameMetadata.name, (uint64_t)name );
3230 MemWrite( &item->externalNameMetadata.threadName, (uint64_t)threadName );
3231 TracyLfqCommit;
3232 break;
3233 }
3234 #endif
3235 case SymbolQueueItemType::KernelCode:
3236 {
3237 #ifdef _WIN32
3238 auto mod = GetKernelModulePath( si.ptr );
3239 if( mod )
3240 {
3241 auto fn = DecodeCallstackPtrFast( si.ptr );
3242 if( *fn )
3243 {
3244 auto hnd = LoadLibraryExA( mod, nullptr, DONT_RESOLVE_DLL_REFERENCES );
3245 if( hnd )
3246 {
3247 auto ptr = (const void*)GetProcAddress( hnd, fn );
3248 if( ptr )
3249 {
3250 auto buf = (char*)tracy_malloc( si.extra );
3251 memcpy( buf, ptr, si.extra );
3252 FreeLibrary( hnd );
3253 TracyLfqPrepare( QueueType::SymbolCodeMetadata );
3254 MemWrite( &item->symbolCodeMetadata.symbol, si.ptr );
3255 MemWrite( &item->symbolCodeMetadata.ptr, (uint64_t)buf );
3256 MemWrite( &item->symbolCodeMetadata.size, (uint32_t)si.extra );
3257 TracyLfqCommit;
3258 break;
3259 }
3260 FreeLibrary( hnd );
3261 }
3262 }
3263 }
3264 #endif
3265 TracyLfqPrepare( QueueType::AckSymbolCodeNotAvailable );
3266 TracyLfqCommit;
3267 break;
3268 }
3269 case SymbolQueueItemType::SourceCode:
3270 HandleSourceCodeQuery( (char*)si.ptr, (char*)si.extra, si.id );
3271 break;
3272 default:
3273 assert( false );
3274 break;
3275 }
3276 }
3277
3278 void Profiler::SymbolWorker()
3279 {
3280 #if defined __linux__ && !defined TRACY_NO_CRASH_HANDLER
3281 s_symbolTid = syscall( SYS_gettid );
3282 #endif
3283
3284 ThreadExitHandler threadExitHandler;
3285 SetThreadName( "Tracy Symbol Worker" );
3286 #ifdef TRACY_USE_RPMALLOC
3287 InitRpmalloc();
3288 #endif
3289 InitCallstack();
3290 while( m_timeBegin.load( std::memory_order_relaxed ) == 0 ) std::this_thread::sleep_for( std::chrono::milliseconds( 10 ) );
3291
3292 for(;;)
3293 {
3294 const auto shouldExit = ShouldExit();
3295 #ifdef TRACY_ON_DEMAND
3296 if( !IsConnected() )
3297 {
3298 if( shouldExit )
3299 {
3300 s_symbolThreadGone.store( true, std::memory_order_release );
3301 return;
3302 }
3303 while( m_symbolQueue.front() ) m_symbolQueue.pop();
3304 std::this_thread::sleep_for( std::chrono::milliseconds( 20 ) );
3305 continue;
3306 }
3307 #endif
3308 auto si = m_symbolQueue.front();
3309 if( si )
3310 {
3311 HandleSymbolQueueItem( *si );
3312 m_symbolQueue.pop();
3313 }
3314 else
3315 {
3316 if( shouldExit )
3317 {
3318 s_symbolThreadGone.store( true, std::memory_order_release );
3319 return;
3320 }
3321 std::this_thread::sleep_for( std::chrono::milliseconds( 20 ) );
3322 }
3323 }
3324 }
3325 #endif
3326
3327 bool Profiler::HandleServerQuery()
3328 {
3329 ServerQueryPacket payload;
3330 if( !m_sock->Read( &payload, sizeof( payload ), 10 ) ) return false;
3331
3332 uint8_t type;
3333 uint64_t ptr;
3334 memcpy( &type, &payload.type, sizeof( payload.type ) );
3335 memcpy( &ptr, &payload.ptr, sizeof( payload.ptr ) );
3336
3337 switch( type )
3338 {
3339 case ServerQueryString:
3340 SendString( ptr, (const char*)ptr, QueueType::StringData );
3341 break;
3342 case ServerQueryThreadString:
3343 if( ptr == m_mainThread )
3344 {
3345 SendString( ptr, "Main thread", 11, QueueType::ThreadName );
3346 }
3347 else
3348 {
3349 SendString( ptr, GetThreadName( ptr ), QueueType::ThreadName );
3350 }
3351 break;
3352 case ServerQuerySourceLocation:
3353 SendSourceLocation( ptr );
3354 break;
3355 case ServerQueryPlotName:
3356 SendString( ptr, (const char*)ptr, QueueType::PlotName );
3357 break;
3358 case ServerQueryTerminate:
3359 return false;
3360 case ServerQueryCallstackFrame:
3361 QueueCallstackFrame( ptr );
3362 break;
3363 case ServerQueryFrameName:
3364 SendString( ptr, (const char*)ptr, QueueType::FrameName );
3365 break;
3366 case ServerQueryDisconnect:
3367 HandleDisconnect();
3368 return false;
3369 #ifdef TRACY_HAS_SYSTEM_TRACING
3370 case ServerQueryExternalName:
3371 QueueExternalName( ptr );
3372 break;
3373 #endif
3374 case ServerQueryParameter:
3375 HandleParameter( ptr );
3376 break;
3377 case ServerQuerySymbol:
3378 QueueSymbolQuery( ptr );
3379 break;
3380 #ifndef TRACY_NO_CODE_TRANSFER
3381 case ServerQuerySymbolCode:
3382 HandleSymbolCodeQuery( ptr, payload.extra );
3383 break;
3384 #endif
3385 case ServerQuerySourceCode:
3386 QueueSourceCodeQuery( uint32_t( ptr ) );
3387 break;
3388 case ServerQueryDataTransfer:
3389 if( m_queryData )
3390 {
3391 assert( !m_queryImage );
3392 m_queryImage = m_queryData;
3393 }
3394 m_queryDataPtr = m_queryData = (char*)tracy_malloc( ptr + 11 );
3395 AckServerQuery();
3396 break;
3397 case ServerQueryDataTransferPart:
3398 memcpy( m_queryDataPtr, &ptr, 8 );
3399 memcpy( m_queryDataPtr+8, &payload.extra, 4 );
3400 m_queryDataPtr += 12;
3401 AckServerQuery();
3402 break;
3403 #ifdef TRACY_FIBERS
3404 case ServerQueryFiberName:
3405 SendString( ptr, (const char*)ptr, QueueType::FiberName );
3406 break;
3407 #endif
3408 default:
3409 assert( false );
3410 break;
3411 }
3412
3413 return true;
3414 }
3415
3416 void Profiler::HandleDisconnect()
3417 {
3418 moodycamel::ConsumerToken token( GetQueue() );
3419
3420 #ifdef TRACY_HAS_SYSTEM_TRACING
3421 if( s_sysTraceThread )
3422 {
3423 auto timestamp = GetTime();
3424 for(;;)
3425 {
3426 const auto status = DequeueContextSwitches( token, timestamp );
3427 if( status == DequeueStatus::ConnectionLost )
3428 {
3429 return;
3430 }
3431 else if( status == DequeueStatus::QueueEmpty )
3432 {
3433 if( m_bufferOffset != m_bufferStart )
3434 {
3435 if( !CommitData() ) return;
3436 }
3437 }
3438 if( timestamp < 0 )
3439 {
3440 if( m_bufferOffset != m_bufferStart )
3441 {
3442 if( !CommitData() ) return;
3443 }
3444 break;
3445 }
3446 ClearSerial();
3447 if( m_sock->HasData() )
3448 {
3449 while( m_sock->HasData() )
3450 {
3451 if( !HandleServerQuery() ) return;
3452 }
3453 if( m_bufferOffset != m_bufferStart )
3454 {
3455 if( !CommitData() ) return;
3456 }
3457 }
3458 else
3459 {
3460 if( m_bufferOffset != m_bufferStart )
3461 {
3462 if( !CommitData() ) return;
3463 }
3464 std::this_thread::sleep_for( std::chrono::milliseconds( 10 ) );
3465 }
3466 }
3467 }
3468 #endif
3469
3470 QueueItem terminate;
3471 MemWrite( &terminate.hdr.type, QueueType::Terminate );
3472 if( !SendData( (const char*)&terminate, 1 ) ) return;
3473 for(;;)
3474 {
3475 ClearQueues( token );
3476 if( m_sock->HasData() )
3477 {
3478 while( m_sock->HasData() )
3479 {
3480 if( !HandleServerQuery() ) return;
3481 }
3482 if( m_bufferOffset != m_bufferStart )
3483 {
3484 if( !CommitData() ) return;
3485 }
3486 }
3487 else
3488 {
3489 if( m_bufferOffset != m_bufferStart )
3490 {
3491 if( !CommitData() ) return;
3492 }
3493 std::this_thread::sleep_for( std::chrono::milliseconds( 10 ) );
3494 }
3495 }
3496 }
3497
3498 void Profiler::CalibrateTimer()
3499 {
3500 m_timerMul = 1.;
3501
3502 #ifdef TRACY_HW_TIMER
3503
3504 # if !defined TRACY_TIMER_QPC && defined TRACY_TIMER_FALLBACK
3505 const bool needCalibration = HardwareSupportsInvariantTSC();
3506 # else
3507 const bool needCalibration = true;
3508 # endif
3509 if( needCalibration )
3510 {
3511 std::atomic_signal_fence( std::memory_order_acq_rel );
3512 const auto t0 = std::chrono::high_resolution_clock::now();
3513 const auto r0 = GetTime();
3514 std::atomic_signal_fence( std::memory_order_acq_rel );
3515 std::this_thread::sleep_for( std::chrono::milliseconds( 200 ) );
3516 std::atomic_signal_fence( std::memory_order_acq_rel );
3517 const auto t1 = std::chrono::high_resolution_clock::now();
3518 const auto r1 = GetTime();
3519 std::atomic_signal_fence( std::memory_order_acq_rel );
3520
3521 const auto dt = std::chrono::duration_cast<std::chrono::nanoseconds>( t1 - t0 ).count();
3522 const auto dr = r1 - r0;
3523
3524 m_timerMul = double( dt ) / double( dr );
3525 }
3526 #endif
3527 }
3528
3529 void Profiler::CalibrateDelay()
3530 {
3531 constexpr int Iterations = 50000;
3532
3533 auto mindiff = std::numeric_limits<int64_t>::max();
3534 for( int i=0; i<Iterations * 10; i++ )
3535 {
3536 const auto t0i = GetTime();
3537 const auto t1i = GetTime();
3538 const auto dti = t1i - t0i;
3539 if( dti > 0 && dti < mindiff ) mindiff = dti;
3540 }
3541 m_resolution = mindiff;
3542
3543 #ifdef TRACY_DELAYED_INIT
3544 m_delay = m_resolution;
3545 #else
3546 constexpr int Events = Iterations * 2; // start + end
3547 static_assert( Events < QueuePrealloc, "Delay calibration loop will allocate memory in queue" );
3548
3549 static const tracy::SourceLocationData __tracy_source_location { nullptr, TracyFunction, TracyFile, (uint32_t)TracyLine, 0 };
3550 const auto t0 = GetTime();
3551 for( int i=0; i<Iterations; i++ )
3552 {
3553 {
3554 TracyLfqPrepare( QueueType::ZoneBegin );
3555 MemWrite( &item->zoneBegin.time, Profiler::GetTime() );
3556 MemWrite( &item->zoneBegin.srcloc, (uint64_t)&__tracy_source_location );
3557 TracyLfqCommit;
3558 }
3559 {
3560 TracyLfqPrepare( QueueType::ZoneEnd );
3561 MemWrite( &item->zoneEnd.time, GetTime() );
3562 TracyLfqCommit;
3563 }
3564 }
3565 const auto t1 = GetTime();
3566 const auto dt = t1 - t0;
3567 m_delay = dt / Events;
3568
3569 moodycamel::ConsumerToken token( GetQueue() );
3570 int left = Events;
3571 while( left != 0 )
3572 {
3573 const auto sz = GetQueue().try_dequeue_bulk_single( token, [](const uint64_t&){}, [](QueueItem* item, size_t sz){} );
3574 assert( sz > 0 );
3575 left -= (int)sz;
3576 }
3577 assert( GetQueue().size_approx() == 0 );
3578 #endif
3579 }
3580
3581 void Profiler::ReportTopology()
3582 {
3583 #ifndef TRACY_DELAYED_INIT
3584 struct CpuData
3585 {
3586 uint32_t package;
3587 uint32_t core;
3588 uint32_t thread;
3589 };
3590
3591 #if defined _WIN32
3592 # ifdef TRACY_UWP
3593 t_GetLogicalProcessorInformationEx _GetLogicalProcessorInformationEx = &::GetLogicalProcessorInformationEx;
3594 # else
3595 t_GetLogicalProcessorInformationEx _GetLogicalProcessorInformationEx = (t_GetLogicalProcessorInformationEx)GetProcAddress( GetModuleHandleA( "kernel32.dll" ), "GetLogicalProcessorInformationEx" );
3596 # endif
3597 if( !_GetLogicalProcessorInformationEx ) return;
3598
3599 DWORD psz = 0;
3600 _GetLogicalProcessorInformationEx( RelationProcessorPackage, nullptr, &psz );
3601 auto packageInfo = (SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX*)tracy_malloc( psz );
3602 auto res = _GetLogicalProcessorInformationEx( RelationProcessorPackage, packageInfo, &psz );
3603 assert( res );
3604
3605 DWORD csz = 0;
3606 _GetLogicalProcessorInformationEx( RelationProcessorCore, nullptr, &csz );
3607 auto coreInfo = (SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX*)tracy_malloc( csz );
3608 res = _GetLogicalProcessorInformationEx( RelationProcessorCore, coreInfo, &csz );
3609 assert( res );
3610
3611 SYSTEM_INFO sysinfo;
3612 GetSystemInfo( &sysinfo );
3613 const uint32_t numcpus = sysinfo.dwNumberOfProcessors;
3614
3615 auto cpuData = (CpuData*)tracy_malloc( sizeof( CpuData ) * numcpus );
3616 for( uint32_t i=0; i<numcpus; i++ ) cpuData[i].thread = i;
3617
3618 int idx = 0;
3619 auto ptr = packageInfo;
3620 while( (char*)ptr < ((char*)packageInfo) + psz )
3621 {
3622 assert( ptr->Relationship == RelationProcessorPackage );
3623 // FIXME account for GroupCount
3624 auto mask = ptr->Processor.GroupMask[0].Mask;
3625 int core = 0;
3626 while( mask != 0 )
3627 {
3628 if( mask & 1 ) cpuData[core].package = idx;
3629 core++;
3630 mask >>= 1;
3631 }
3632 ptr = (SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX*)(((char*)ptr) + ptr->Size);
3633 idx++;
3634 }
3635
3636 idx = 0;
3637 ptr = coreInfo;
3638 while( (char*)ptr < ((char*)coreInfo) + csz )
3639 {
3640 assert( ptr->Relationship == RelationProcessorCore );
3641 // FIXME account for GroupCount
3642 auto mask = ptr->Processor.GroupMask[0].Mask;
3643 int core = 0;
3644 while( mask != 0 )
3645 {
3646 if( mask & 1 ) cpuData[core].core = idx;
3647 core++;
3648 mask >>= 1;
3649 }
3650 ptr = (SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX*)(((char*)ptr) + ptr->Size);
3651 idx++;
3652 }
3653
3654 for( uint32_t i=0; i<numcpus; i++ )
3655 {
3656 auto& data = cpuData[i];
3657
3658 TracyLfqPrepare( QueueType::CpuTopology );
3659 MemWrite( &item->cpuTopology.package, data.package );
3660 MemWrite( &item->cpuTopology.core, data.core );
3661 MemWrite( &item->cpuTopology.thread, data.thread );
3662
3663 #ifdef TRACY_ON_DEMAND
3664 DeferItem( *item );
3665 #endif
3666
3667 TracyLfqCommit;
3668 }
3669
3670 tracy_free( cpuData );
3671 tracy_free( coreInfo );
3672 tracy_free( packageInfo );
3673 #elif defined __linux__
3674 const int numcpus = std::thread::hardware_concurrency();
3675 auto cpuData = (CpuData*)tracy_malloc( sizeof( CpuData ) * numcpus );
3676 memset( cpuData, 0, sizeof( CpuData ) * numcpus );
3677
3678 const char* basePath = "/sys/devices/system/cpu/cpu";
3679 for( int i=0; i<numcpus; i++ )
3680 {
3681 char path[1024];
3682 sprintf( path, "%s%i/topology/physical_package_id", basePath, i );
3683 char buf[1024];
3684 FILE* f = fopen( path, "rb" );
3685 if( !f )
3686 {
3687 tracy_free( cpuData );
3688 return;
3689 }
3690 auto read = fread( buf, 1, 1024, f );
3691 buf[read] = '\0';
3692 fclose( f );
3693 cpuData[i].package = uint32_t( atoi( buf ) );
3694 cpuData[i].thread = i;
3695 sprintf( path, "%s%i/topology/core_id", basePath, i );
3696 f = fopen( path, "rb" );
3697 read = fread( buf, 1, 1024, f );
3698 buf[read] = '\0';
3699 fclose( f );
3700 cpuData[i].core = uint32_t( atoi( buf ) );
3701 }
3702
3703 for( int i=0; i<numcpus; i++ )
3704 {
3705 auto& data = cpuData[i];
3706
3707 TracyLfqPrepare( QueueType::CpuTopology );
3708 MemWrite( &item->cpuTopology.package, data.package );
3709 MemWrite( &item->cpuTopology.core, data.core );
3710 MemWrite( &item->cpuTopology.thread, data.thread );
3711
3712 #ifdef TRACY_ON_DEMAND
3713 DeferItem( *item );
3714 #endif
3715
3716 TracyLfqCommit;
3717 }
3718
3719 tracy_free( cpuData );
3720 #endif
3721 #endif
3722 }
3723
3724 void Profiler::SendCallstack( int depth, const char* skipBefore )
3725 {
3726 #ifdef TRACY_HAS_CALLSTACK
3727 auto ptr = Callstack( depth );
3728 CutCallstack( ptr, skipBefore );
3729
3730 TracyQueuePrepare( QueueType::Callstack );
3731 MemWrite( &item->callstackFat.ptr, (uint64_t)ptr );
3732 TracyQueueCommit( callstackFatThread );
3733 #endif
3734 }
3735
3736 void Profiler::CutCallstack( void* callstack, const char* skipBefore )
3737 {
3738 #ifdef TRACY_HAS_CALLSTACK
3739 auto data = (uintptr_t*)callstack;
3740 const auto sz = *data++;
3741 uintptr_t i;
3742 for( i=0; i<sz; i++ )
3743 {
3744 auto name = DecodeCallstackPtrFast( uint64_t( data[i] ) );
3745 const bool found = strcmp( name, skipBefore ) == 0;
3746 if( found )
3747 {
3748 i++;
3749 break;
3750 }
3751 }
3752
3753 if( i != sz )
3754 {
3755 memmove( data, data + i, ( sz - i ) * sizeof( uintptr_t* ) );
3756 *--data = sz - i;
3757 }
3758 #endif
3759 }
3760
3761 #ifdef TRACY_HAS_SYSTIME
3762 void Profiler::ProcessSysTime()
3763 {
3764 if( m_shutdown.load( std::memory_order_relaxed ) ) return;
3765 auto t = std::chrono::high_resolution_clock::now().time_since_epoch().count();
3766 if( t - m_sysTimeLast > 100000000 ) // 100 ms
3767 {
3768 auto sysTime = m_sysTime.Get();
3769 if( sysTime >= 0 )
3770 {
3771 m_sysTimeLast = t;
3772
3773 TracyLfqPrepare( QueueType::SysTimeReport );
3774 MemWrite( &item->sysTime.time, GetTime() );
3775 MemWrite( &item->sysTime.sysTime, sysTime );
3776 TracyLfqCommit;
3777 }
3778 }
3779 }
3780 #endif
3781
3782 void Profiler::HandleParameter( uint64_t payload )
3783 {
3784 assert( m_paramCallback );
3785 const auto idx = uint32_t( payload >> 32 );
3786 const auto val = int32_t( payload & 0xFFFFFFFF );
3787 m_paramCallback( m_paramCallbackData, idx, val );
3788 AckServerQuery();
3789 }
3790
3791 void Profiler::HandleSymbolCodeQuery( uint64_t symbol, uint32_t size )
3792 {
3793 if( symbol >> 63 != 0 )
3794 {
3795 QueueKernelCode( symbol, size );
3796 }
3797 else
3798 {
3799 #ifdef __ANDROID__
3800 // On Android it's common for code to be in mappings that are only executable
3801 // but not readable.
3802 if( !EnsureReadable( symbol ) )
3803 {
3804 AckSymbolCodeNotAvailable();
3805 return;
3806 }
3807 #endif
3808 SendLongString( symbol, (const char*)symbol, size, QueueType::SymbolCode );
3809 }
3810 }
3811
3812 void Profiler::HandleSourceCodeQuery( char* data, char* image, uint32_t id )
3813 {
3814 bool ok = false;
3815 struct stat st;
3816 if( stat( data, &st ) == 0 && (uint64_t)st.st_mtime < m_exectime )
3817 {
3818 if( st.st_size < ( TargetFrameSize - 16 ) )
3819 {
3820 FILE* f = fopen( data, "rb" );
3821 if( f )
3822 {
3823 auto ptr = (char*)tracy_malloc_fast( st.st_size );
3824 auto rd = fread( ptr, 1, st.st_size, f );
3825 fclose( f );
3826 if( rd == (size_t)st.st_size )
3827 {
3828 TracyLfqPrepare( QueueType::SourceCodeMetadata );
3829 MemWrite( &item->sourceCodeMetadata.ptr, (uint64_t)ptr );
3830 MemWrite( &item->sourceCodeMetadata.size, (uint32_t)rd );
3831 MemWrite( &item->sourceCodeMetadata.id, id );
3832 TracyLfqCommit;
3833 ok = true;
3834 }
3835 }
3836 }
3837 }
3838
3839 #ifdef TRACY_DEBUGINFOD
3840 else if( image && data[0] == '/' )
3841 {
3842 size_t size;
3843 auto buildid = GetBuildIdForImage( image, size );
3844 if( buildid )
3845 {
3846 auto d = debuginfod_find_source( GetDebuginfodClient(), buildid, size, data, nullptr );
3847 TracyDebug( "DebugInfo source query: %s, fn: %s, image: %s\n", d >= 0 ? " ok " : "fail", data, image );
3848 if( d >= 0 )
3849 {
3850 struct stat st;
3851 fstat( d, &st );
3852 if( st.st_size < ( TargetFrameSize - 16 ) )
3853 {
3854 lseek( d, 0, SEEK_SET );
3855 auto ptr = (char*)tracy_malloc_fast( st.st_size );
3856 auto rd = read( d, ptr, st.st_size );
3857 if( rd == (size_t)st.st_size )
3858 {
3859 TracyLfqPrepare( QueueType::SourceCodeMetadata );
3860 MemWrite( &item->sourceCodeMetadata.ptr, (uint64_t)ptr );
3861 MemWrite( &item->sourceCodeMetadata.size, (uint32_t)rd );
3862 MemWrite( &item->sourceCodeMetadata.id, id );
3863 TracyLfqCommit;
3864 ok = true;
3865 }
3866 }
3867 close( d );
3868 }
3869 }
3870 }
3871 else
3872 {
3873 TracyDebug( "DebugInfo invalid query fn: %s, image: %s\n", data, image );
3874 }
3875 #endif
3876
3877 if( !ok && m_sourceCallback )
3878 {
3879 size_t sz;
3880 char* ptr = m_sourceCallback( m_sourceCallbackData, data, sz );
3881 if( ptr )
3882 {
3883 if( sz < ( TargetFrameSize - 16 ) )
3884 {
3885 TracyLfqPrepare( QueueType::SourceCodeMetadata );
3886 MemWrite( &item->sourceCodeMetadata.ptr, (uint64_t)ptr );
3887 MemWrite( &item->sourceCodeMetadata.size, (uint32_t)sz );
3888 MemWrite( &item->sourceCodeMetadata.id, id );
3889 TracyLfqCommit;
3890 ok = true;
3891 }
3892 }
3893 }
3894
3895 if( !ok )
3896 {
3897 TracyLfqPrepare( QueueType::AckSourceCodeNotAvailable );
3898 MemWrite( &item->sourceCodeNotAvailable, id );
3899 TracyLfqCommit;
3900 }
3901
3902 tracy_free_fast( data );
3903 tracy_free_fast( image );
3904 }
3905
3906 #if defined _WIN32 && defined TRACY_TIMER_QPC
3907 int64_t Profiler::GetTimeQpc()
3908 {
3909 LARGE_INTEGER t;
3910 QueryPerformanceCounter( &t );
3911 return t.QuadPart;
3912 }
3913 #endif
3914
3915 }
3916
3917 #ifdef __cplusplus
3918 extern "C" {
3919 #endif
3920
3921 TRACY_API TracyCZoneCtx ___tracy_emit_zone_begin( const struct ___tracy_source_location_data* srcloc, int active )
3922 {
3923 ___tracy_c_zone_context ctx;
3924 #ifdef TRACY_ON_DEMAND
3925 ctx.active = active && tracy::GetProfiler().IsConnected();
3926 #else
3927 ctx.active = active;
3928 #endif
3929 if( !ctx.active ) return ctx;
3930 const auto id = tracy::GetProfiler().GetNextZoneId();
3931 ctx.id = id;
3932
3933 #ifndef TRACY_NO_VERIFY
3934 {
3935 TracyQueuePrepareC( tracy::QueueType::ZoneValidation );
3936 tracy::MemWrite( &item->zoneValidation.id, id );
3937 TracyQueueCommitC( zoneValidationThread );
3938 }
3939 #endif
3940 {
3941 TracyQueuePrepareC( tracy::QueueType::ZoneBegin );
3942 tracy::MemWrite( &item->zoneBegin.time, tracy::Profiler::GetTime() );
3943 tracy::MemWrite( &item->zoneBegin.srcloc, (uint64_t)srcloc );
3944 TracyQueueCommitC( zoneBeginThread );
3945 }
3946 return ctx;
3947 }
3948
3949 TRACY_API TracyCZoneCtx ___tracy_emit_zone_begin_callstack( const struct ___tracy_source_location_data* srcloc, int depth, int active )
3950 {
3951 ___tracy_c_zone_context ctx;
3952 #ifdef TRACY_ON_DEMAND
3953 ctx.active = active && tracy::GetProfiler().IsConnected();
3954 #else
3955 ctx.active = active;
3956 #endif
3957 if( !ctx.active ) return ctx;
3958 const auto id = tracy::GetProfiler().GetNextZoneId();
3959 ctx.id = id;
3960
3961 #ifndef TRACY_NO_VERIFY
3962 {
3963 TracyQueuePrepareC( tracy::QueueType::ZoneValidation );
3964 tracy::MemWrite( &item->zoneValidation.id, id );
3965 TracyQueueCommitC( zoneValidationThread );
3966 }
3967 #endif
3968 tracy::GetProfiler().SendCallstack( depth );
3969 {
3970 TracyQueuePrepareC( tracy::QueueType::ZoneBeginCallstack );
3971 tracy::MemWrite( &item->zoneBegin.time, tracy::Profiler::GetTime() );
3972 tracy::MemWrite( &item->zoneBegin.srcloc, (uint64_t)srcloc );
3973 TracyQueueCommitC( zoneBeginThread );
3974 }
3975 return ctx;
3976 }
3977
3978 TRACY_API TracyCZoneCtx ___tracy_emit_zone_begin_alloc( uint64_t srcloc, int active )
3979 {
3980 ___tracy_c_zone_context ctx;
3981 #ifdef TRACY_ON_DEMAND
3982 ctx.active = active && tracy::GetProfiler().IsConnected();
3983 #else
3984 ctx.active = active;
3985 #endif
3986 if( !ctx.active )
3987 {
3988 tracy::tracy_free( (void*)srcloc );
3989 return ctx;
3990 }
3991 const auto id = tracy::GetProfiler().GetNextZoneId();
3992 ctx.id = id;
3993
3994 #ifndef TRACY_NO_VERIFY
3995 {
3996 TracyQueuePrepareC( tracy::QueueType::ZoneValidation );
3997 tracy::MemWrite( &item->zoneValidation.id, id );
3998 TracyQueueCommitC( zoneValidationThread );
3999 }
4000 #endif
4001 {
4002 TracyQueuePrepareC( tracy::QueueType::ZoneBeginAllocSrcLoc );
4003 tracy::MemWrite( &item->zoneBegin.time, tracy::Profiler::GetTime() );
4004 tracy::MemWrite( &item->zoneBegin.srcloc, srcloc );
4005 TracyQueueCommitC( zoneBeginThread );
4006 }
4007 return ctx;
4008 }
4009
4010 TRACY_API TracyCZoneCtx ___tracy_emit_zone_begin_alloc_callstack( uint64_t srcloc, int depth, int active )
4011 {
4012 ___tracy_c_zone_context ctx;
4013 #ifdef TRACY_ON_DEMAND
4014 ctx.active = active && tracy::GetProfiler().IsConnected();
4015 #else
4016 ctx.active = active;
4017 #endif
4018 if( !ctx.active )
4019 {
4020 tracy::tracy_free( (void*)srcloc );
4021 return ctx;
4022 }
4023 const auto id = tracy::GetProfiler().GetNextZoneId();
4024 ctx.id = id;
4025
4026 #ifndef TRACY_NO_VERIFY
4027 {
4028 TracyQueuePrepareC( tracy::QueueType::ZoneValidation );
4029 tracy::MemWrite( &item->zoneValidation.id, id );
4030 TracyQueueCommitC( zoneValidationThread );
4031 }
4032 #endif
4033 tracy::GetProfiler().SendCallstack( depth );
4034 {
4035 TracyQueuePrepareC( tracy::QueueType::ZoneBeginAllocSrcLocCallstack );
4036 tracy::MemWrite( &item->zoneBegin.time, tracy::Profiler::GetTime() );
4037 tracy::MemWrite( &item->zoneBegin.srcloc, srcloc );
4038 TracyQueueCommitC( zoneBeginThread );
4039 }
4040 return ctx;
4041 }
4042
4043 TRACY_API void ___tracy_emit_zone_end( TracyCZoneCtx ctx )
4044 {
4045 if( !ctx.active ) return;
4046 #ifndef TRACY_NO_VERIFY
4047 {
4048 TracyQueuePrepareC( tracy::QueueType::ZoneValidation );
4049 tracy::MemWrite( &item->zoneValidation.id, ctx.id );
4050 TracyQueueCommitC( zoneValidationThread );
4051 }
4052 #endif
4053 {
4054 TracyQueuePrepareC( tracy::QueueType::ZoneEnd );
4055 tracy::MemWrite( &item->zoneEnd.time, tracy::Profiler::GetTime() );
4056 TracyQueueCommitC( zoneEndThread );
4057 }
4058 }
4059
4060 TRACY_API void ___tracy_emit_zone_text( TracyCZoneCtx ctx, const char* txt, size_t size )
4061 {
4062 assert( size < std::numeric_limits<uint16_t>::max() );
4063 if( !ctx.active ) return;
4064 auto ptr = (char*)tracy::tracy_malloc( size );
4065 memcpy( ptr, txt, size );
4066 #ifndef TRACY_NO_VERIFY
4067 {
4068 TracyQueuePrepareC( tracy::QueueType::ZoneValidation );
4069 tracy::MemWrite( &item->zoneValidation.id, ctx.id );
4070 TracyQueueCommitC( zoneValidationThread );
4071 }
4072 #endif
4073 {
4074 TracyQueuePrepareC( tracy::QueueType::ZoneText );
4075 tracy::MemWrite( &item->zoneTextFat.text, (uint64_t)ptr );
4076 tracy::MemWrite( &item->zoneTextFat.size, (uint16_t)size );
4077 TracyQueueCommitC( zoneTextFatThread );
4078 }
4079 }
4080
4081 TRACY_API void ___tracy_emit_zone_name( TracyCZoneCtx ctx, const char* txt, size_t size )
4082 {
4083 assert( size < std::numeric_limits<uint16_t>::max() );
4084 if( !ctx.active ) return;
4085 auto ptr = (char*)tracy::tracy_malloc( size );
4086 memcpy( ptr, txt, size );
4087 #ifndef TRACY_NO_VERIFY
4088 {
4089 TracyQueuePrepareC( tracy::QueueType::ZoneValidation );
4090 tracy::MemWrite( &item->zoneValidation.id, ctx.id );
4091 TracyQueueCommitC( zoneValidationThread );
4092 }
4093 #endif
4094 {
4095 TracyQueuePrepareC( tracy::QueueType::ZoneName );
4096 tracy::MemWrite( &item->zoneTextFat.text, (uint64_t)ptr );
4097 tracy::MemWrite( &item->zoneTextFat.size, (uint16_t)size );
4098 TracyQueueCommitC( zoneTextFatThread );
4099 }
4100 }
4101
4102 TRACY_API void ___tracy_emit_zone_color( TracyCZoneCtx ctx, uint32_t color ) {
4103 if( !ctx.active ) return;
4104 #ifndef TRACY_NO_VERIFY
4105 {
4106 TracyQueuePrepareC( tracy::QueueType::ZoneValidation );
4107 tracy::MemWrite( &item->zoneValidation.id, ctx.id );
4108 TracyQueueCommitC( zoneValidationThread );
4109 }
4110 #endif
4111 {
4112 TracyQueuePrepareC( tracy::QueueType::ZoneColor );
4113 tracy::MemWrite( &item->zoneColor.b, uint8_t( ( color ) & 0xFF ) );
4114 tracy::MemWrite( &item->zoneColor.g, uint8_t( ( color >> 8 ) & 0xFF ) );
4115 tracy::MemWrite( &item->zoneColor.r, uint8_t( ( color >> 16 ) & 0xFF ) );
4116 TracyQueueCommitC( zoneColorThread );
4117 }
4118 }
4119
4120 TRACY_API void ___tracy_emit_zone_value( TracyCZoneCtx ctx, uint64_t value )
4121 {
4122 if( !ctx.active ) return;
4123 #ifndef TRACY_NO_VERIFY
4124 {
4125 TracyQueuePrepareC( tracy::QueueType::ZoneValidation );
4126 tracy::MemWrite( &item->zoneValidation.id, ctx.id );
4127 TracyQueueCommitC( zoneValidationThread );
4128 }
4129 #endif
4130 {
4131 TracyQueuePrepareC( tracy::QueueType::ZoneValue );
4132 tracy::MemWrite( &item->zoneValue.value, value );
4133 TracyQueueCommitC( zoneValueThread );
4134 }
4135 }
4136
4137 TRACY_API void ___tracy_emit_memory_alloc( const void* ptr, size_t size, int secure ) { tracy::Profiler::MemAlloc( ptr, size, secure != 0 ); }
4138 TRACY_API void ___tracy_emit_memory_alloc_callstack( const void* ptr, size_t size, int depth, int secure ) { tracy::Profiler::MemAllocCallstack( ptr, size, depth, secure != 0 ); }
4139 TRACY_API void ___tracy_emit_memory_free( const void* ptr, int secure ) { tracy::Profiler::MemFree( ptr, secure != 0 ); }
4140 TRACY_API void ___tracy_emit_memory_free_callstack( const void* ptr, int depth, int secure ) { tracy::Profiler::MemFreeCallstack( ptr, depth, secure != 0 ); }
4141 TRACY_API void ___tracy_emit_memory_alloc_named( const void* ptr, size_t size, int secure, const char* name ) { tracy::Profiler::MemAllocNamed( ptr, size, secure != 0, name ); }
4142 TRACY_API void ___tracy_emit_memory_alloc_callstack_named( const void* ptr, size_t size, int depth, int secure, const char* name ) { tracy::Profiler::MemAllocCallstackNamed( ptr, size, depth, secure != 0, name ); }
4143 TRACY_API void ___tracy_emit_memory_free_named( const void* ptr, int secure, const char* name ) { tracy::Profiler::MemFreeNamed( ptr, secure != 0, name ); }
4144 TRACY_API void ___tracy_emit_memory_free_callstack_named( const void* ptr, int depth, int secure, const char* name ) { tracy::Profiler::MemFreeCallstackNamed( ptr, depth, secure != 0, name ); }
4145 TRACY_API void ___tracy_emit_frame_mark( const char* name ) { tracy::Profiler::SendFrameMark( name ); }
4146 TRACY_API void ___tracy_emit_frame_mark_start( const char* name ) { tracy::Profiler::SendFrameMark( name, tracy::QueueType::FrameMarkMsgStart ); }
4147 TRACY_API void ___tracy_emit_frame_mark_end( const char* name ) { tracy::Profiler::SendFrameMark( name, tracy::QueueType::FrameMarkMsgEnd ); }
4148 TRACY_API void ___tracy_emit_frame_image( const void* image, uint16_t w, uint16_t h, uint8_t offset, int flip ) { tracy::Profiler::SendFrameImage( image, w, h, offset, flip ); }
4149 TRACY_API void ___tracy_emit_plot( const char* name, double val ) { tracy::Profiler::PlotData( name, val ); }
4150 TRACY_API void ___tracy_emit_plot_float( const char* name, float val ) { tracy::Profiler::PlotData( name, val ); }
4151 TRACY_API void ___tracy_emit_plot_int( const char* name, int64_t val ) { tracy::Profiler::PlotData( name, val ); }
4152 TRACY_API void ___tracy_emit_message( const char* txt, size_t size, int callstack ) { tracy::Profiler::Message( txt, size, callstack ); }
4153 TRACY_API void ___tracy_emit_messageL( const char* txt, int callstack ) { tracy::Profiler::Message( txt, callstack ); }
4154 TRACY_API void ___tracy_emit_messageC( const char* txt, size_t size, uint32_t color, int callstack ) { tracy::Profiler::MessageColor( txt, size, color, callstack ); }
4155 TRACY_API void ___tracy_emit_messageLC( const char* txt, uint32_t color, int callstack ) { tracy::Profiler::MessageColor( txt, color, callstack ); }
4156 TRACY_API void ___tracy_emit_message_appinfo( const char* txt, size_t size ) { tracy::Profiler::MessageAppInfo( txt, size ); }
4157
4158 TRACY_API uint64_t ___tracy_alloc_srcloc( uint32_t line, const char* source, size_t sourceSz, const char* function, size_t functionSz ) {
4159 return tracy::Profiler::AllocSourceLocation( line, source, sourceSz, function, functionSz );
4160 }
4161
4162 TRACY_API uint64_t ___tracy_alloc_srcloc_name( uint32_t line, const char* source, size_t sourceSz, const char* function, size_t functionSz, const char* name, size_t nameSz ) {
4163 return tracy::Profiler::AllocSourceLocation( line, source, sourceSz, function, functionSz, name, nameSz );
4164 }
4165
4166 TRACY_API void ___tracy_emit_gpu_zone_begin( const struct ___tracy_gpu_zone_begin_data data )
4167 {
4168 TracyLfqPrepareC( tracy::QueueType::GpuZoneBegin );
4169 tracy::MemWrite( &item->gpuZoneBegin.cpuTime, tracy::Profiler::GetTime() );
4170 tracy::MemWrite( &item->gpuNewContext.thread, tracy::GetThreadHandle() );
4171 tracy::MemWrite( &item->gpuZoneBegin.srcloc, data.srcloc );
4172 tracy::MemWrite( &item->gpuZoneBegin.queryId, data.queryId );
4173 tracy::MemWrite( &item->gpuZoneBegin.context, data.context );
4174 TracyLfqCommitC;
4175 }
4176
4177 TRACY_API void ___tracy_emit_gpu_zone_begin_callstack( const struct ___tracy_gpu_zone_begin_callstack_data data )
4178 {
4179 tracy::GetProfiler().SendCallstack( data.depth );
4180 TracyLfqPrepareC( tracy::QueueType::GpuZoneBeginCallstack );
4181 tracy::MemWrite( &item->gpuZoneBegin.thread, tracy::GetThreadHandle() );
4182 tracy::MemWrite( &item->gpuZoneBegin.cpuTime, tracy::Profiler::GetTime() );
4183 tracy::MemWrite( &item->gpuZoneBegin.queryId, data.queryId );
4184 tracy::MemWrite( &item->gpuZoneBegin.context, data.context );
4185 tracy::MemWrite( &item->gpuZoneBegin.srcloc, data.srcloc );
4186 TracyLfqCommitC;
4187 }
4188
4189 TRACY_API void ___tracy_emit_gpu_zone_begin_alloc( const struct ___tracy_gpu_zone_begin_data data )
4190 {
4191 TracyLfqPrepareC( tracy::QueueType::GpuZoneBeginAllocSrcLoc );
4192 tracy::MemWrite( &item->gpuZoneBegin.cpuTime, tracy::Profiler::GetTime() );
4193 tracy::MemWrite( &item->gpuNewContext.thread, tracy::GetThreadHandle() );
4194 tracy::MemWrite( &item->gpuZoneBegin.srcloc, data.srcloc );
4195 tracy::MemWrite( &item->gpuZoneBegin.queryId, data.queryId );
4196 tracy::MemWrite( &item->gpuZoneBegin.context, data.context );
4197 TracyLfqCommitC;
4198 }
4199
4200 TRACY_API void ___tracy_emit_gpu_zone_begin_alloc_callstack( const struct ___tracy_gpu_zone_begin_callstack_data data )
4201 {
4202 tracy::GetProfiler().SendCallstack( data.depth );
4203 TracyLfqPrepareC( tracy::QueueType::GpuZoneBeginAllocSrcLocCallstack );
4204 tracy::MemWrite( &item->gpuZoneBegin.cpuTime, tracy::Profiler::GetTime() );
4205 tracy::MemWrite( &item->gpuNewContext.thread, tracy::GetThreadHandle() );
4206 tracy::MemWrite( &item->gpuZoneBegin.srcloc, data.srcloc );
4207 tracy::MemWrite( &item->gpuZoneBegin.queryId, data.queryId );
4208 tracy::MemWrite( &item->gpuZoneBegin.context, data.context );
4209 TracyLfqCommitC;
4210 }
4211
4212 TRACY_API void ___tracy_emit_gpu_time( const struct ___tracy_gpu_time_data data )
4213 {
4214 TracyLfqPrepareC( tracy::QueueType::GpuTime );
4215 tracy::MemWrite( &item->gpuTime.gpuTime, data.gpuTime );
4216 tracy::MemWrite( &item->gpuTime.queryId, data.queryId );
4217 tracy::MemWrite( &item->gpuTime.context, data.context );
4218 TracyLfqCommitC;
4219 }
4220
4221 TRACY_API void ___tracy_emit_gpu_zone_end( const struct ___tracy_gpu_zone_end_data data )
4222 {
4223 TracyLfqPrepareC( tracy::QueueType::GpuZoneEnd );
4224 tracy::MemWrite( &item->gpuZoneEnd.cpuTime, tracy::Profiler::GetTime() );
4225 memset( &item->gpuZoneEnd.thread, 0, sizeof( item->gpuZoneEnd.thread ) );
4226 tracy::MemWrite( &item->gpuZoneEnd.queryId, data.queryId );
4227 tracy::MemWrite( &item->gpuZoneEnd.context, data.context );
4228 TracyLfqCommitC;
4229 }
4230
4231 TRACY_API void ___tracy_emit_gpu_new_context( ___tracy_gpu_new_context_data data )
4232 {
4233 TracyLfqPrepareC( tracy::QueueType::GpuNewContext );
4234 tracy::MemWrite( &item->gpuNewContext.cpuTime, tracy::Profiler::GetTime() );
4235 tracy::MemWrite( &item->gpuNewContext.thread, tracy::GetThreadHandle() );
4236 tracy::MemWrite( &item->gpuNewContext.gpuTime, data.gpuTime );
4237 tracy::MemWrite( &item->gpuNewContext.period, data.period );
4238 tracy::MemWrite( &item->gpuNewContext.context, data.context );
4239 tracy::MemWrite( &item->gpuNewContext.flags, data.flags );
4240 tracy::MemWrite( &item->gpuNewContext.type, data.type );
4241 TracyLfqCommitC;
4242 }
4243
4244 TRACY_API void ___tracy_emit_gpu_context_name( const struct ___tracy_gpu_context_name_data data )
4245 {
4246 auto ptr = (char*)tracy::tracy_malloc( data.len );
4247 memcpy( ptr, data.name, data.len );
4248
4249 TracyLfqPrepareC( tracy::QueueType::GpuContextName );
4250 tracy::MemWrite( &item->gpuContextNameFat.context, data.context );
4251 tracy::MemWrite( &item->gpuContextNameFat.ptr, (uint64_t)ptr );
4252 tracy::MemWrite( &item->gpuContextNameFat.size, data.len );
4253 TracyLfqCommitC;
4254 }
4255
4256 TRACY_API void ___tracy_emit_gpu_calibration( const struct ___tracy_gpu_calibration_data data )
4257 {
4258 TracyLfqPrepareC( tracy::QueueType::GpuCalibration );
4259 tracy::MemWrite( &item->gpuCalibration.cpuTime, tracy::Profiler::GetTime() );
4260 tracy::MemWrite( &item->gpuCalibration.gpuTime, data.gpuTime );
4261 tracy::MemWrite( &item->gpuCalibration.cpuDelta, data.cpuDelta );
4262 tracy::MemWrite( &item->gpuCalibration.context, data.context );
4263 TracyLfqCommitC;
4264 }
4265
4266 TRACY_API void ___tracy_emit_gpu_zone_begin_serial( const struct ___tracy_gpu_zone_begin_data data )
4267 {
4268 auto item = tracy::Profiler::QueueSerial();
4269 tracy::MemWrite( &item->hdr.type, tracy::QueueType::GpuZoneBeginSerial );
4270 tracy::MemWrite( &item->gpuZoneBegin.cpuTime, tracy::Profiler::GetTime() );
4271 tracy::MemWrite( &item->gpuZoneBegin.srcloc, data.srcloc );
4272 tracy::MemWrite( &item->gpuZoneBegin.thread, tracy::GetThreadHandle() );
4273 tracy::MemWrite( &item->gpuZoneBegin.queryId, data.queryId );
4274 tracy::MemWrite( &item->gpuZoneBegin.context, data.context );
4275 tracy::Profiler::QueueSerialFinish();
4276 }
4277
4278 TRACY_API void ___tracy_emit_gpu_zone_begin_callstack_serial( const struct ___tracy_gpu_zone_begin_callstack_data data )
4279 {
4280 auto item = tracy::Profiler::QueueSerialCallstack( tracy::Callstack( data.depth ) );
4281 tracy::MemWrite( &item->hdr.type, tracy::QueueType::GpuZoneBeginCallstackSerial );
4282 tracy::MemWrite( &item->gpuZoneBegin.cpuTime, tracy::Profiler::GetTime() );
4283 tracy::MemWrite( &item->gpuZoneBegin.srcloc, data.srcloc );
4284 tracy::MemWrite( &item->gpuZoneBegin.thread, tracy::GetThreadHandle() );
4285 tracy::MemWrite( &item->gpuZoneBegin.queryId, data.queryId );
4286 tracy::MemWrite( &item->gpuZoneBegin.context, data.context );
4287 tracy::Profiler::QueueSerialFinish();
4288 }
4289
4290 TRACY_API void ___tracy_emit_gpu_zone_begin_alloc_serial( const struct ___tracy_gpu_zone_begin_data data )
4291 {
4292 auto item = tracy::Profiler::QueueSerial();
4293 tracy::MemWrite( &item->hdr.type, tracy::QueueType::GpuZoneBeginAllocSrcLocSerial );
4294 tracy::MemWrite( &item->gpuZoneBegin.cpuTime, tracy::Profiler::GetTime() );
4295 tracy::MemWrite( &item->gpuNewContext.thread, tracy::GetThreadHandle() );
4296 tracy::MemWrite( &item->gpuZoneBegin.srcloc, data.srcloc );
4297 tracy::MemWrite( &item->gpuZoneBegin.queryId, data.queryId );
4298 tracy::MemWrite( &item->gpuZoneBegin.context, data.context );
4299 tracy::Profiler::QueueSerialFinish();
4300 }
4301
4302 TRACY_API void ___tracy_emit_gpu_zone_begin_alloc_callstack_serial( const struct ___tracy_gpu_zone_begin_callstack_data data )
4303 {
4304 auto item = tracy::Profiler::QueueSerialCallstack( tracy::Callstack( data.depth ) );
4305 tracy::MemWrite( &item->hdr.type, tracy::QueueType::GpuZoneBeginAllocSrcLocCallstackSerial );
4306 tracy::MemWrite( &item->gpuZoneBegin.cpuTime, tracy::Profiler::GetTime() );
4307 tracy::MemWrite( &item->gpuNewContext.thread, tracy::GetThreadHandle() );
4308 tracy::MemWrite( &item->gpuZoneBegin.srcloc, data.srcloc );
4309 tracy::MemWrite( &item->gpuZoneBegin.queryId, data.queryId );
4310 tracy::MemWrite( &item->gpuZoneBegin.context, data.context );
4311 tracy::Profiler::QueueSerialFinish();
4312 }
4313
4314 TRACY_API void ___tracy_emit_gpu_time_serial( const struct ___tracy_gpu_time_data data )
4315 {
4316 auto item = tracy::Profiler::QueueSerial();
4317 tracy::MemWrite( &item->hdr.type, tracy::QueueType::GpuTime );
4318 tracy::MemWrite( &item->gpuTime.gpuTime, data.gpuTime );
4319 tracy::MemWrite( &item->gpuTime.queryId, data.queryId );
4320 tracy::MemWrite( &item->gpuTime.context, data.context );
4321 tracy::Profiler::QueueSerialFinish();
4322 }
4323
4324 TRACY_API void ___tracy_emit_gpu_zone_end_serial( const struct ___tracy_gpu_zone_end_data data )
4325 {
4326 auto item = tracy::Profiler::QueueSerial();
4327 tracy::MemWrite( &item->hdr.type, tracy::QueueType::GpuZoneEndSerial );
4328 tracy::MemWrite( &item->gpuZoneEnd.cpuTime, tracy::Profiler::GetTime() );
4329 memset( &item->gpuZoneEnd.thread, 0, sizeof( item->gpuZoneEnd.thread ) );
4330 tracy::MemWrite( &item->gpuZoneEnd.queryId, data.queryId );
4331 tracy::MemWrite( &item->gpuZoneEnd.context, data.context );
4332 tracy::Profiler::QueueSerialFinish();
4333 }
4334
4335 TRACY_API void ___tracy_emit_gpu_new_context_serial( ___tracy_gpu_new_context_data data )
4336 {
4337 auto item = tracy::Profiler::QueueSerial();
4338 tracy::MemWrite( &item->hdr.type, tracy::QueueType::GpuNewContext );
4339 tracy::MemWrite( &item->gpuNewContext.cpuTime, tracy::Profiler::GetTime() );
4340 tracy::MemWrite( &item->gpuNewContext.thread, tracy::GetThreadHandle() );
4341 tracy::MemWrite( &item->gpuNewContext.gpuTime, data.gpuTime );
4342 tracy::MemWrite( &item->gpuNewContext.period, data.period );
4343 tracy::MemWrite( &item->gpuNewContext.context, data.context );
4344 tracy::MemWrite( &item->gpuNewContext.flags, data.flags );
4345 tracy::MemWrite( &item->gpuNewContext.type, data.type );
4346 tracy::Profiler::QueueSerialFinish();
4347 }
4348
4349 TRACY_API void ___tracy_emit_gpu_context_name_serial( const struct ___tracy_gpu_context_name_data data )
4350 {
4351 auto ptr = (char*)tracy::tracy_malloc( data.len );
4352 memcpy( ptr, data.name, data.len );
4353
4354 auto item = tracy::Profiler::QueueSerial();
4355 tracy::MemWrite( &item->hdr.type, tracy::QueueType::GpuContextName );
4356 tracy::MemWrite( &item->gpuContextNameFat.context, data.context );
4357 tracy::MemWrite( &item->gpuContextNameFat.ptr, (uint64_t)ptr );
4358 tracy::MemWrite( &item->gpuContextNameFat.size, data.len );
4359 tracy::Profiler::QueueSerialFinish();
4360 }
4361
4362 TRACY_API void ___tracy_emit_gpu_calibration_serial( const struct ___tracy_gpu_calibration_data data )
4363 {
4364 auto item = tracy::Profiler::QueueSerial();
4365 tracy::MemWrite( &item->hdr.type, tracy::QueueType::GpuCalibration );
4366 tracy::MemWrite( &item->gpuCalibration.cpuTime, tracy::Profiler::GetTime() );
4367 tracy::MemWrite( &item->gpuCalibration.gpuTime, data.gpuTime );
4368 tracy::MemWrite( &item->gpuCalibration.cpuDelta, data.cpuDelta );
4369 tracy::MemWrite( &item->gpuCalibration.context, data.context );
4370 tracy::Profiler::QueueSerialFinish();
4371 }
4372
4373 TRACY_API int ___tracy_connected( void )
4374 {
4375 return tracy::GetProfiler().IsConnected();
4376 }
4377
4378 #ifdef TRACY_FIBERS
4379 TRACY_API void ___tracy_fiber_enter( const char* fiber ){ tracy::Profiler::EnterFiber( fiber ); }
4380 TRACY_API void ___tracy_fiber_leave( void ){ tracy::Profiler::LeaveFiber(); }
4381 #endif
4382
4383 # ifdef TRACY_MANUAL_LIFETIME
4384 TRACY_API void ___tracy_startup_profiler( void )
4385 {
4386 tracy::StartupProfiler();
4387 }
4388
4389 TRACY_API void ___tracy_shutdown_profiler( void )
4390 {
4391 tracy::ShutdownProfiler();
4392 }
4393 # endif
4394
4395 #ifdef __cplusplus
4396 }
4397 #endif
4398
4399 #endif