forked from zig-gamedev/ztracy
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTracyProfiler.cpp
More file actions
5007 lines (4576 loc) · 167 KB
/
TracyProfiler.cpp
File metadata and controls
5007 lines (4576 loc) · 167 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#ifdef TRACY_ENABLE
#ifdef _WIN32
# ifndef NOMINMAX
# define NOMINMAX
# endif
# include <winsock2.h>
# include <windows.h>
# include <tlhelp32.h>
# include <inttypes.h>
# include <intrin.h>
# include "../common/TracyUwp.hpp"
# ifndef _MSC_VER
# include <excpt.h>
# endif
#else
# include <sys/time.h>
# include <sys/param.h>
#endif
#ifdef _GNU_SOURCE
# include <errno.h>
#endif
#ifdef __linux__
# include <dirent.h>
# include <pthread.h>
# include <sys/types.h>
# include <sys/syscall.h>
#endif
#if defined __APPLE__ || defined BSD
# include <sys/types.h>
# include <sys/sysctl.h>
#endif
#if defined __APPLE__
# include "TargetConditionals.h"
# include <mach-o/dyld.h>
#endif
#ifdef __ANDROID__
# include <sys/mman.h>
# include <sys/system_properties.h>
# include <stdio.h>
# include <stdint.h>
# include <algorithm>
# include <vector>
#endif
#ifdef __QNX__
# include <stdint.h>
# include <stdio.h>
# include <string.h>
# include <sys/syspage.h>
# include <sys/stat.h>
#endif
#include <algorithm>
#include <assert.h>
#include <atomic>
#include <chrono>
#include <limits>
#include <new>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <thread>
#include "../common/TracyAlign.hpp"
#include "../common/TracyAlloc.hpp"
#include "../common/TracySocket.hpp"
#include "../common/TracySystem.hpp"
#include "../common/TracyYield.hpp"
#include "../common/tracy_lz4.hpp"
#include "tracy_rpmalloc.hpp"
#include "TracyCallstack.hpp"
#include "TracyDebug.hpp"
#include "TracyDxt1.hpp"
#include "TracyScoped.hpp"
#include "TracyProfiler.hpp"
#include "TracyThread.hpp"
#include "TracyArmCpuTable.hpp"
#include "TracySysTrace.hpp"
#include "../tracy/TracyC.h"
#if defined TRACY_MANUAL_LIFETIME && !defined(TRACY_DELAYED_INIT)
# error "TRACY_MANUAL_LIFETIME requires enabled TRACY_DELAYED_INIT"
#endif
#ifdef TRACY_PORT
# ifndef TRACY_DATA_PORT
# define TRACY_DATA_PORT TRACY_PORT
# endif
# ifndef TRACY_BROADCAST_PORT
# define TRACY_BROADCAST_PORT TRACY_PORT
# endif
#endif
#ifdef __APPLE__
# ifndef TRACY_DELAYED_INIT
# define TRACY_DELAYED_INIT
# endif
#else
# ifdef __GNUC__
# define init_order( val ) __attribute__ ((init_priority(val)))
# else
# define init_order(x)
# endif
#endif
#if defined _WIN32
# include <lmcons.h>
extern "C" typedef LONG (WINAPI *t_RtlGetVersion)( PRTL_OSVERSIONINFOW );
extern "C" typedef BOOL (WINAPI *t_GetLogicalProcessorInformationEx)( LOGICAL_PROCESSOR_RELATIONSHIP, PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX, PDWORD );
extern "C" typedef char* (WINAPI *t_WineGetVersion)();
extern "C" typedef char* (WINAPI *t_WineGetBuildId)();
#else
# include <unistd.h>
# include <limits.h>
# include <fcntl.h>
#endif
#if defined __linux__
# include <sys/sysinfo.h>
# include <sys/utsname.h>
#endif
#if !defined _WIN32 && ( defined __i386 || defined _M_IX86 || defined __x86_64__ || defined _M_X64 )
# include "TracyCpuid.hpp"
#endif
#if !( ( defined _WIN32 && _WIN32_WINNT >= _WIN32_WINNT_VISTA ) || defined __linux__ )
# include <mutex>
#endif
#ifdef __QNX__
extern char* __progname;
#endif
namespace tracy
{
#ifdef __ANDROID__
// Implementation helpers of EnsureReadable(address).
// This is so far only needed on Android, where it is common for libraries to be mapped
// with only executable, not readable, permissions. Typical example (line from /proc/self/maps):
/*
746b63b000-746b6dc000 --xp 00042000 07:48 35 /apex/com.android.runtime/lib64/bionic/libc.so
*/
// See https://github.com/wolfpld/tracy/issues/125 .
// To work around this, we parse /proc/self/maps and we use mprotect to set read permissions
// on any mappings that contain symbols addresses hit by HandleSymbolCodeQuery.
namespace {
// Holds some information about a single memory mapping.
struct MappingInfo {
// Start of address range. Inclusive.
uintptr_t start_address;
// End of address range. Exclusive, so the mapping is the half-open interval
// [start, end) and its length in bytes is `end - start`. As in /proc/self/maps.
uintptr_t end_address;
// Read/Write/Executable permissions.
bool perm_r, perm_w, perm_x;
};
} // anonymous namespace
// Internal implementation helper for LookUpMapping(address).
//
// Parses /proc/self/maps returning a vector<MappingInfo>.
// /proc/self/maps is assumed to be sorted by ascending address, so the resulting
// vector is sorted by ascending address too.
static std::vector<MappingInfo> ParseMappings()
{
std::vector<MappingInfo> result;
FILE* file = fopen( "/proc/self/maps", "r" );
if( !file ) return result;
char line[1024];
while( fgets( line, sizeof( line ), file ) )
{
uintptr_t start_addr;
uintptr_t end_addr;
#if defined(__LP64__)
if( sscanf( line, "%lx-%lx", &start_addr, &end_addr ) != 2 ) continue;
#else
if (sscanf( line, "%dx-%dx", &start_addr, &end_addr ) != 2 ) continue;
#endif
char* first_space = strchr( line, ' ' );
if( !first_space ) continue;
char* perm = first_space + 1;
char* second_space = strchr( perm, ' ' );
if( !second_space || second_space - perm != 4 ) continue;
result.emplace_back();
auto& mapping = result.back();
mapping.start_address = start_addr;
mapping.end_address = end_addr;
mapping.perm_r = perm[0] == 'r';
mapping.perm_w = perm[1] == 'w';
mapping.perm_x = perm[2] == 'x';
}
fclose( file );
return result;
}
// Internal implementation helper for LookUpMapping(address).
//
// Takes as input an `address` and a known vector `mappings`, assumed to be
// sorted by increasing addresses, as /proc/self/maps seems to be.
// Returns a pointer to the MappingInfo describing the mapping that this
// address belongs to, or nullptr if the address isn't in `mappings`.
static MappingInfo* LookUpMapping(std::vector<MappingInfo>& mappings, uintptr_t address)
{
// Comparison function for std::lower_bound. Returns true if all addresses in `m1`
// are lower than `addr`.
auto Compare = []( const MappingInfo& m1, uintptr_t addr ) {
// '<=' because the address ranges are half-open intervals, [start, end).
return m1.end_address <= addr;
};
auto iter = std::lower_bound( mappings.begin(), mappings.end(), address, Compare );
if( iter == mappings.end() || iter->start_address > address) {
return nullptr;
}
return &*iter;
}
// Internal implementation helper for EnsureReadable(address).
//
// Takes as input an `address` and returns a pointer to a MappingInfo
// describing the mapping that this address belongs to, or nullptr if
// the address isn't in any known mapping.
//
// This function is stateful and not reentrant (assumes to be called from
// only one thread). It holds a vector of mappings parsed from /proc/self/maps.
//
// Attempts to react to mappings changes by re-parsing /proc/self/maps.
static MappingInfo* LookUpMapping(uintptr_t address)
{
// Static state managed by this function. Not constant, we mutate that state as
// we turn some mappings readable. Initially parsed once here, updated as needed below.
static std::vector<MappingInfo> s_mappings = ParseMappings();
MappingInfo* mapping = LookUpMapping( s_mappings, address );
if( mapping ) return mapping;
// This address isn't in any known mapping. Try parsing again, maybe
// mappings changed.
s_mappings = ParseMappings();
return LookUpMapping( s_mappings, address );
}
// Internal implementation helper for EnsureReadable(address).
//
// Attempts to make the specified `mapping` readable if it isn't already.
// Returns true if and only if the mapping is readable.
static bool EnsureReadable( MappingInfo& mapping )
{
if( mapping.perm_r )
{
// The mapping is already readable.
return true;
}
int prot = PROT_READ;
if( mapping.perm_w ) prot |= PROT_WRITE;
if( mapping.perm_x ) prot |= PROT_EXEC;
if( mprotect( reinterpret_cast<void*>( mapping.start_address ),
mapping.end_address - mapping.start_address, prot ) == -1 )
{
// Failed to make the mapping readable. Shouldn't happen, hasn't
// been observed yet. If it happened in practice, we should consider
// adding a bool to MappingInfo to track this to avoid retrying mprotect
// everytime on such mappings.
return false;
}
// The mapping is now readable. Update `mapping` so the next call will be fast.
mapping.perm_r = true;
return true;
}
// Attempts to set the read permission on the entire mapping containing the
// specified address. Returns true if and only if the mapping is now readable.
static bool EnsureReadable( uintptr_t address )
{
MappingInfo* mapping = LookUpMapping(address);
return mapping && EnsureReadable( *mapping );
}
#elif defined WIN32
static bool EnsureReadable( uintptr_t address )
{
MEMORY_BASIC_INFORMATION memInfo;
VirtualQuery( reinterpret_cast<void*>( address ), &memInfo, sizeof( memInfo ) );
return memInfo.Protect != PAGE_NOACCESS;
}
#else
static bool EnsureReadable( uintptr_t address )
{
return true;
}
#endif
#ifndef TRACY_DELAYED_INIT
struct InitTimeWrapper
{
int64_t val;
};
struct ProducerWrapper
{
tracy::moodycamel::ConcurrentQueue<QueueItem>::ExplicitProducer* ptr;
};
struct ThreadHandleWrapper
{
uint32_t val;
};
#endif
#if defined __i386 || defined _M_IX86 || defined __x86_64__ || defined _M_X64
static inline void CpuId( uint32_t* regs, uint32_t leaf )
{
memset(regs, 0, sizeof(uint32_t) * 4);
#if defined _MSC_VER
__cpuidex( (int*)regs, leaf, 0 );
#else
__get_cpuid( leaf, regs, regs+1, regs+2, regs+3 );
#endif
}
static void InitFailure( const char* msg )
{
#if defined _WIN32
bool hasConsole = false;
bool reopen = false;
const auto attached = AttachConsole( ATTACH_PARENT_PROCESS );
if( attached )
{
hasConsole = true;
reopen = true;
}
else
{
const auto err = GetLastError();
if( err == ERROR_ACCESS_DENIED )
{
hasConsole = true;
}
}
if( hasConsole )
{
fprintf( stderr, "Tracy Profiler initialization failure: %s\n", msg );
if( reopen )
{
freopen( "CONOUT$", "w", stderr );
fprintf( stderr, "Tracy Profiler initialization failure: %s\n", msg );
}
}
else
{
# ifndef TRACY_UWP
MessageBoxA( nullptr, msg, "Tracy Profiler initialization failure", MB_ICONSTOP );
# endif
}
#else
fprintf( stderr, "Tracy Profiler initialization failure: %s\n", msg );
#endif
exit( 1 );
}
static bool CheckHardwareSupportsInvariantTSC()
{
const char* noCheck = GetEnvVar( "TRACY_NO_INVARIANT_CHECK" );
if( noCheck && noCheck[0] == '1' ) return true;
uint32_t regs[4];
CpuId( regs, 1 );
if( !( regs[3] & ( 1 << 4 ) ) )
{
#if !defined TRACY_TIMER_QPC && !defined TRACY_TIMER_FALLBACK
InitFailure( "CPU doesn't support RDTSC instruction." );
#else
return false;
#endif
}
CpuId( regs, 0x80000007 );
if( regs[3] & ( 1 << 8 ) ) return true;
return false;
}
#if defined TRACY_TIMER_FALLBACK && defined TRACY_HW_TIMER
bool HardwareSupportsInvariantTSC()
{
static bool cachedResult = CheckHardwareSupportsInvariantTSC();
return cachedResult;
}
#endif
static int64_t SetupHwTimer()
{
#if !defined TRACY_TIMER_QPC && !defined TRACY_TIMER_FALLBACK
if( !CheckHardwareSupportsInvariantTSC() )
{
#if defined _WIN32
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." );
#else
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." );
#endif
}
#endif
return Profiler::GetTime();
}
#else
static int64_t SetupHwTimer()
{
return Profiler::GetTime();
}
#endif
static const char* GetProcessName()
{
const char* processName = "unknown";
#ifdef _WIN32
static char buf[_MAX_PATH];
GetModuleFileNameA( nullptr, buf, _MAX_PATH );
const char* ptr = buf;
while( *ptr != '\0' ) ptr++;
while( ptr > buf && *ptr != '\\' && *ptr != '/' ) ptr--;
if( ptr > buf ) ptr++;
processName = ptr;
#elif defined __ANDROID__
# if __ANDROID_API__ >= 21
auto buf = getprogname();
if( buf ) processName = buf;
# endif
#elif defined __linux__ && defined _GNU_SOURCE
if( program_invocation_short_name ) processName = program_invocation_short_name;
#elif defined __APPLE__ || defined BSD
auto buf = getprogname();
if( buf ) processName = buf;
#elif defined __QNX__
processName = __progname;
#endif
return processName;
}
static const char* GetProcessExecutablePath()
{
#ifdef _WIN32
static char buf[_MAX_PATH];
GetModuleFileNameA( nullptr, buf, _MAX_PATH );
return buf;
#elif defined __ANDROID__
return nullptr;
#elif defined __linux__ && defined _GNU_SOURCE
return program_invocation_name;
#elif defined __APPLE__
static char buf[1024];
uint32_t size = 1024;
_NSGetExecutablePath( buf, &size );
return buf;
#elif defined __DragonFly__
static char buf[1024];
readlink( "/proc/curproc/file", buf, 1024 );
return buf;
#elif defined __FreeBSD__
static char buf[1024];
int mib[4];
mib[0] = CTL_KERN;
mib[1] = KERN_PROC;
mib[2] = KERN_PROC_PATHNAME;
mib[3] = -1;
size_t cb = 1024;
sysctl( mib, 4, buf, &cb, nullptr, 0 );
return buf;
#elif defined __NetBSD__
static char buf[1024];
readlink( "/proc/curproc/exe", buf, 1024 );
return buf;
#elif defined __QNX__
static char buf[_PC_PATH_MAX + 1];
_cmdname(buf);
return buf;
#else
return nullptr;
#endif
}
#if defined __linux__ && defined __ARM_ARCH
static uint32_t GetHex( char*& ptr, int skip )
{
uint32_t ret;
ptr += skip;
char* end;
if( ptr[0] == '0' && ptr[1] == 'x' )
{
ptr += 2;
ret = strtol( ptr, &end, 16 );
}
else
{
ret = strtol( ptr, &end, 10 );
}
ptr = end;
return ret;
}
#endif
static const char* GetHostInfo()
{
static char buf[1024];
auto ptr = buf;
#if defined _WIN32
# ifdef TRACY_UWP
auto GetVersion = &::GetVersionEx;
# else
auto GetVersion = (t_RtlGetVersion)GetProcAddress( GetModuleHandleA( "ntdll.dll" ), "RtlGetVersion" );
# endif
if( !GetVersion )
{
# ifdef __MINGW32__
ptr += sprintf( ptr, "OS: Windows (MingW)\n" );
# else
ptr += sprintf( ptr, "OS: Windows\n" );
# endif
}
else
{
RTL_OSVERSIONINFOW ver = { sizeof( RTL_OSVERSIONINFOW ) };
GetVersion( &ver );
# ifdef __MINGW32__
ptr += sprintf( ptr, "OS: Windows %i.%i.%i (MingW)\n", (int)ver.dwMajorVersion, (int)ver.dwMinorVersion, (int)ver.dwBuildNumber );
# else
auto WineGetVersion = (t_WineGetVersion)GetProcAddress( GetModuleHandleA( "ntdll.dll" ), "wine_get_version" );
auto WineGetBuildId = (t_WineGetBuildId)GetProcAddress( GetModuleHandleA( "ntdll.dll" ), "wine_get_build_id" );
if( WineGetVersion && WineGetBuildId )
{
ptr += sprintf( ptr, "OS: Windows %lu.%lu.%lu (Wine %s [%s])\n", ver.dwMajorVersion, ver.dwMinorVersion, ver.dwBuildNumber, WineGetVersion(), WineGetBuildId() );
}
else
{
ptr += sprintf( ptr, "OS: Windows %lu.%lu.%lu\n", ver.dwMajorVersion, ver.dwMinorVersion, ver.dwBuildNumber );
}
# endif
}
#elif defined __linux__
struct utsname utsName;
uname( &utsName );
# if defined __ANDROID__
ptr += sprintf( ptr, "OS: Linux %s (Android)\n", utsName.release );
# else
ptr += sprintf( ptr, "OS: Linux %s\n", utsName.release );
# endif
#elif defined __APPLE__
# if TARGET_OS_IPHONE == 1
ptr += sprintf( ptr, "OS: Darwin (iOS)\n" );
# elif TARGET_OS_MAC == 1
ptr += sprintf( ptr, "OS: Darwin (OSX)\n" );
# else
ptr += sprintf( ptr, "OS: Darwin (unknown)\n" );
# endif
#elif defined __DragonFly__
ptr += sprintf( ptr, "OS: BSD (DragonFly)\n" );
#elif defined __FreeBSD__
ptr += sprintf( ptr, "OS: BSD (FreeBSD)\n" );
#elif defined __NetBSD__
ptr += sprintf( ptr, "OS: BSD (NetBSD)\n" );
#elif defined __OpenBSD__
ptr += sprintf( ptr, "OS: BSD (OpenBSD)\n" );
#elif defined __QNX__
ptr += sprintf( ptr, "OS: QNX\n" );
#else
ptr += sprintf( ptr, "OS: unknown\n" );
#endif
#if defined _MSC_VER
# if defined __clang__
ptr += sprintf( ptr, "Compiler: MSVC clang-cl %i.%i.%i\n", __clang_major__, __clang_minor__, __clang_patchlevel__ );
# else
ptr += sprintf( ptr, "Compiler: MSVC %i\n", _MSC_VER );
# endif
#elif defined __clang__
ptr += sprintf( ptr, "Compiler: clang %i.%i.%i\n", __clang_major__, __clang_minor__, __clang_patchlevel__ );
#elif defined __GNUC__
ptr += sprintf( ptr, "Compiler: gcc %i.%i.%i\n", __GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__ );
#else
ptr += sprintf( ptr, "Compiler: unknown\n" );
#endif
#if defined _WIN32
InitWinSock();
char hostname[512];
gethostname( hostname, 512 );
# ifdef TRACY_UWP
const char* user = "";
# else
DWORD userSz = UNLEN+1;
char user[UNLEN+1];
GetUserNameA( user, &userSz );
# endif
ptr += sprintf( ptr, "User: %s@%s\n", user, hostname );
#else
char hostname[_POSIX_HOST_NAME_MAX]{};
char user[_POSIX_LOGIN_NAME_MAX]{};
gethostname( hostname, _POSIX_HOST_NAME_MAX );
# if defined __ANDROID__
const auto login = getlogin();
if( login )
{
strcpy( user, login );
}
else
{
memcpy( user, "(?)", 4 );
}
# else
getlogin_r( user, _POSIX_LOGIN_NAME_MAX );
# endif
ptr += sprintf( ptr, "User: %s@%s\n", user, hostname );
#endif
#if defined __i386 || defined _M_IX86
ptr += sprintf( ptr, "Arch: x86\n" );
#elif defined __x86_64__ || defined _M_X64
ptr += sprintf( ptr, "Arch: x64\n" );
#elif defined __aarch64__
ptr += sprintf( ptr, "Arch: ARM64\n" );
#elif defined __ARM_ARCH
ptr += sprintf( ptr, "Arch: ARM\n" );
#else
ptr += sprintf( ptr, "Arch: unknown\n" );
#endif
#if defined __i386 || defined _M_IX86 || defined __x86_64__ || defined _M_X64
uint32_t regs[4];
char cpuModel[4*4*3+1] = {};
auto modelPtr = cpuModel;
for( uint32_t i=0x80000002; i<0x80000005; ++i )
{
CpuId( regs, i );
memcpy( modelPtr, regs, sizeof( regs ) ); modelPtr += sizeof( regs );
}
ptr += sprintf( ptr, "CPU: %s\n", cpuModel );
#elif defined __linux__ && defined __ARM_ARCH
bool cpuFound = false;
FILE* fcpuinfo = fopen( "/proc/cpuinfo", "rb" );
if( fcpuinfo )
{
enum { BufSize = 4*1024 };
char buf[BufSize];
const auto sz = fread( buf, 1, BufSize, fcpuinfo );
fclose( fcpuinfo );
const auto end = buf + sz;
auto cptr = buf;
uint32_t impl = 0;
uint32_t var = 0;
uint32_t part = 0;
uint32_t rev = 0;
while( end - cptr > 20 )
{
while( end - cptr > 20 && memcmp( cptr, "CPU ", 4 ) != 0 )
{
cptr += 4;
while( end - cptr > 20 && *cptr != '\n' ) cptr++;
cptr++;
}
if( end - cptr <= 20 ) break;
cptr += 4;
if( memcmp( cptr, "implementer\t: ", 14 ) == 0 )
{
if( impl != 0 ) break;
impl = GetHex( cptr, 14 );
}
else if( memcmp( cptr, "variant\t: ", 10 ) == 0 ) var = GetHex( cptr, 10 );
else if( memcmp( cptr, "part\t: ", 7 ) == 0 ) part = GetHex( cptr, 7 );
else if( memcmp( cptr, "revision\t: ", 11 ) == 0 ) rev = GetHex( cptr, 11 );
while( *cptr != '\n' && *cptr != '\0' ) cptr++;
cptr++;
}
if( impl != 0 || var != 0 || part != 0 || rev != 0 )
{
cpuFound = true;
ptr += sprintf( ptr, "CPU: %s%s r%ip%i\n", DecodeArmImplementer( impl ), DecodeArmPart( impl, part ), var, rev );
}
}
if( !cpuFound )
{
ptr += sprintf( ptr, "CPU: unknown\n" );
}
#elif defined __APPLE__ && TARGET_OS_IPHONE == 1
{
size_t sz;
sysctlbyname( "hw.machine", nullptr, &sz, nullptr, 0 );
auto str = (char*)tracy_malloc( sz );
sysctlbyname( "hw.machine", str, &sz, nullptr, 0 );
ptr += sprintf( ptr, "Device: %s\n", DecodeIosDevice( str ) );
tracy_free( str );
}
#else
ptr += sprintf( ptr, "CPU: unknown\n" );
#endif
#ifdef __ANDROID__
char deviceModel[PROP_VALUE_MAX+1];
char deviceManufacturer[PROP_VALUE_MAX+1];
__system_property_get( "ro.product.model", deviceModel );
__system_property_get( "ro.product.manufacturer", deviceManufacturer );
ptr += sprintf( ptr, "Device: %s %s\n", deviceManufacturer, deviceModel );
#endif
ptr += sprintf( ptr, "CPU cores: %i\n", std::thread::hardware_concurrency() );
#if defined _WIN32
MEMORYSTATUSEX statex;
statex.dwLength = sizeof( statex );
GlobalMemoryStatusEx( &statex );
# ifdef _MSC_VER
ptr += sprintf( ptr, "RAM: %I64u MB\n", statex.ullTotalPhys / 1024 / 1024 );
# else
ptr += sprintf( ptr, "RAM: %llu MB\n", statex.ullTotalPhys / 1024 / 1024 );
# endif
#elif defined __linux__
struct sysinfo sysInfo;
sysinfo( &sysInfo );
ptr += sprintf( ptr, "RAM: %lu MB\n", sysInfo.totalram / 1024 / 1024 );
#elif defined __APPLE__
size_t memSize;
size_t sz = sizeof( memSize );
sysctlbyname( "hw.memsize", &memSize, &sz, nullptr, 0 );
ptr += sprintf( ptr, "RAM: %zu MB\n", memSize / 1024 / 1024 );
#elif defined BSD
size_t memSize;
size_t sz = sizeof( memSize );
sysctlbyname( "hw.physmem", &memSize, &sz, nullptr, 0 );
ptr += sprintf( ptr, "RAM: %zu MB\n", memSize / 1024 / 1024 );
#elif defined __QNX__
struct asinfo_entry *entries = SYSPAGE_ENTRY(asinfo);
size_t count = SYSPAGE_ENTRY_SIZE(asinfo) / sizeof(struct asinfo_entry);
char *strings = SYSPAGE_ENTRY(strings)->data;
uint64_t memSize = 0;
size_t i;
for (i = 0; i < count; i++) {
struct asinfo_entry *entry = &entries[i];
if (strcmp(strings + entry->name, "ram") == 0) {
memSize += entry->end - entry->start + 1;
}
}
memSize = memSize / 1024 / 1024;
ptr += sprintf( ptr, "RAM: %llu MB\n", memSize);
#else
ptr += sprintf( ptr, "RAM: unknown\n" );
#endif
return buf;
}
static uint64_t GetPid()
{
#if defined _WIN32
return uint64_t( GetCurrentProcessId() );
#else
return uint64_t( getpid() );
#endif
}
void Profiler::AckServerQuery()
{
QueueItem item;
MemWrite( &item.hdr.type, QueueType::AckServerQueryNoop );
NeedDataSize( QueueDataSize[(int)QueueType::AckServerQueryNoop] );
AppendDataUnsafe( &item, QueueDataSize[(int)QueueType::AckServerQueryNoop] );
}
void Profiler::AckSymbolCodeNotAvailable()
{
QueueItem item;
MemWrite( &item.hdr.type, QueueType::AckSymbolCodeNotAvailable );
NeedDataSize( QueueDataSize[(int)QueueType::AckSymbolCodeNotAvailable] );
AppendDataUnsafe( &item, QueueDataSize[(int)QueueType::AckSymbolCodeNotAvailable] );
}
static BroadcastMessage& GetBroadcastMessage( const char* procname, size_t pnsz, int& len, int port )
{
static BroadcastMessage msg;
msg.broadcastVersion = BroadcastVersion;
msg.protocolVersion = ProtocolVersion;
msg.listenPort = port;
msg.pid = GetPid();
memcpy( msg.programName, procname, pnsz );
memset( msg.programName + pnsz, 0, WelcomeMessageProgramNameSize - pnsz );
len = int( offsetof( BroadcastMessage, programName ) + pnsz + 1 );
return msg;
}
#if defined _WIN32 && !defined TRACY_UWP && !defined TRACY_NO_CRASH_HANDLER
static DWORD s_profilerThreadId = 0;
static DWORD s_symbolThreadId = 0;
static char s_crashText[1024];
LONG WINAPI CrashFilter( PEXCEPTION_POINTERS pExp )
{
if( !GetProfiler().IsConnected() ) return EXCEPTION_CONTINUE_SEARCH;
const unsigned ec = pExp->ExceptionRecord->ExceptionCode;
auto msgPtr = s_crashText;
switch( ec )
{
case EXCEPTION_ACCESS_VIOLATION:
msgPtr += sprintf( msgPtr, "Exception EXCEPTION_ACCESS_VIOLATION (0x%x). ", ec );
switch( pExp->ExceptionRecord->ExceptionInformation[0] )
{
case 0:
msgPtr += sprintf( msgPtr, "Read violation at address 0x%" PRIxPTR ".", pExp->ExceptionRecord->ExceptionInformation[1] );
break;
case 1:
msgPtr += sprintf( msgPtr, "Write violation at address 0x%" PRIxPTR ".", pExp->ExceptionRecord->ExceptionInformation[1] );
break;
case 8:
msgPtr += sprintf( msgPtr, "DEP violation at address 0x%" PRIxPTR ".", pExp->ExceptionRecord->ExceptionInformation[1] );
break;
default:
break;
}
break;
case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
msgPtr += sprintf( msgPtr, "Exception EXCEPTION_ARRAY_BOUNDS_EXCEEDED (0x%x). ", ec );
break;
case EXCEPTION_DATATYPE_MISALIGNMENT:
msgPtr += sprintf( msgPtr, "Exception EXCEPTION_DATATYPE_MISALIGNMENT (0x%x). ", ec );
break;
case EXCEPTION_FLT_DIVIDE_BY_ZERO:
msgPtr += sprintf( msgPtr, "Exception EXCEPTION_FLT_DIVIDE_BY_ZERO (0x%x). ", ec );
break;
case EXCEPTION_ILLEGAL_INSTRUCTION:
msgPtr += sprintf( msgPtr, "Exception EXCEPTION_ILLEGAL_INSTRUCTION (0x%x). ", ec );
break;
case EXCEPTION_IN_PAGE_ERROR:
msgPtr += sprintf( msgPtr, "Exception EXCEPTION_IN_PAGE_ERROR (0x%x). ", ec );
break;
case EXCEPTION_INT_DIVIDE_BY_ZERO:
msgPtr += sprintf( msgPtr, "Exception EXCEPTION_INT_DIVIDE_BY_ZERO (0x%x). ", ec );
break;
case EXCEPTION_PRIV_INSTRUCTION:
msgPtr += sprintf( msgPtr, "Exception EXCEPTION_PRIV_INSTRUCTION (0x%x). ", ec );
break;
case EXCEPTION_STACK_OVERFLOW:
msgPtr += sprintf( msgPtr, "Exception EXCEPTION_STACK_OVERFLOW (0x%x). ", ec );
break;
default:
return EXCEPTION_CONTINUE_SEARCH;
}
{
GetProfiler().SendCallstack( 60, "KiUserExceptionDispatcher" );
TracyQueuePrepare( QueueType::CrashReport );
item->crashReport.time = Profiler::GetTime();
item->crashReport.text = (uint64_t)s_crashText;
TracyQueueCommit( crashReportThread );
}
HANDLE h = CreateToolhelp32Snapshot( TH32CS_SNAPTHREAD, 0 );
if( h == INVALID_HANDLE_VALUE ) return EXCEPTION_CONTINUE_SEARCH;
THREADENTRY32 te = { sizeof( te ) };
if( !Thread32First( h, &te ) )
{
CloseHandle( h );
return EXCEPTION_CONTINUE_SEARCH;
}
const auto pid = GetCurrentProcessId();
const auto tid = GetCurrentThreadId();
do
{
if( te.th32OwnerProcessID == pid && te.th32ThreadID != tid && te.th32ThreadID != s_profilerThreadId && te.th32ThreadID != s_symbolThreadId )
{
HANDLE th = OpenThread( THREAD_SUSPEND_RESUME, FALSE, te.th32ThreadID );
if( th != INVALID_HANDLE_VALUE )
{
SuspendThread( th );
CloseHandle( th );
}
}
}
while( Thread32Next( h, &te ) );
CloseHandle( h );
{
TracyLfqPrepare( QueueType::Crash );
TracyLfqCommit;
}
std::this_thread::sleep_for( std::chrono::milliseconds( 500 ) );
GetProfiler().RequestShutdown();
while( !GetProfiler().HasShutdownFinished() ) { std::this_thread::sleep_for( std::chrono::milliseconds( 10 ) ); };
return EXCEPTION_CONTINUE_SEARCH;
}
#endif
#if defined _WIN32 && !defined _MSC_VER
LONG WINAPI CrashFilterExecute( PEXCEPTION_POINTERS pExp )
{
return EXCEPTION_EXECUTE_HANDLER;
}
#endif
static Profiler* s_instance = nullptr;
static Thread* s_thread;
#ifndef TRACY_NO_FRAME_IMAGE
static Thread* s_compressThread;
#endif
#ifdef TRACY_HAS_CALLSTACK
static Thread* s_symbolThread;
std::atomic<bool> s_symbolThreadGone { false };
#endif
#ifdef TRACY_HAS_SYSTEM_TRACING
static Thread* s_sysTraceThread = nullptr;
#endif
#if defined __linux__ && !defined TRACY_NO_CRASH_HANDLER
# ifndef TRACY_CRASH_SIGNAL
# define TRACY_CRASH_SIGNAL SIGPWR
# endif
static long s_profilerTid = 0;
static long s_symbolTid = 0;
static char s_crashText[1024];
static std::atomic<bool> s_alreadyCrashed( false );
static void ThreadFreezer( int /*signal*/ )
{
for(;;) sleep( 1000 );
}
static inline void HexPrint( char*& ptr, uint64_t val )
{
if( val == 0 )
{
*ptr++ = '0';
return;
}
static const char HexTable[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
char buf[16];
auto bptr = buf;
do
{
*bptr++ = HexTable[val%16];
val /= 16;
}
while( val > 0 );
do
{
*ptr++ = *--bptr;
}
while( bptr != buf );
}
static void CrashHandler( int signal, siginfo_t* info, void* /*ucontext*/ )
{
bool expected = false;
if( !s_alreadyCrashed.compare_exchange_strong( expected, true ) ) ThreadFreezer( signal );
struct sigaction act = {};
act.sa_handler = SIG_DFL;
sigaction( SIGABRT, &act, nullptr );
auto msgPtr = s_crashText;
switch( signal )
{
case SIGILL:
strcpy( msgPtr, "Illegal Instruction.\n" );
while( *msgPtr ) msgPtr++;
switch( info->si_code )
{
case ILL_ILLOPC:
strcpy( msgPtr, "Illegal opcode.\n" );
break;
case ILL_ILLOPN:
strcpy( msgPtr, "Illegal operand.\n" );
break;
case ILL_ILLADR:
strcpy( msgPtr, "Illegal addressing mode.\n" );