tracy-client-sys 0.29.0

Low level bindings to the client libraries for the Tracy profiler
Documentation
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
#ifdef _MSC_VER
#  pragma warning(disable:4996)
#endif
#if defined _WIN32
#  ifndef WIN32_LEAN_AND_MEAN
#    define WIN32_LEAN_AND_MEAN
#  endif
#  ifndef NOMINMAX
#    define NOMINMAX
#  endif
#  define SECURITY_WIN32
#  include <windows.h>
#  include <malloc.h>
#  include <lmcons.h>
#  include <security.h>
#  include "TracyWinFamily.hpp"
#  ifdef _MSC_VER
#    pragma comment(lib, "secur32.lib")
#  endif
#else
#  include <pthread.h>
#  include <pwd.h>
#  include <string.h>
#  include <unistd.h>
#endif

#ifdef __linux__
#  ifdef __ANDROID__
#    include <sys/types.h>
#  else
#    include <sys/syscall.h>
#  endif
#  include <fcntl.h>
#elif defined __FreeBSD__
#  include <sys/thr.h>
#elif defined __NetBSD__
#  include <lwp.h>
#elif defined __DragonFly__
#  include <sys/lwp.h>
#elif defined __QNX__
#  include <process.h>
#  include <sys/neutrino.h>
#endif

#ifdef __MINGW32__
#  define __STDC_FORMAT_MACROS
#endif
#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>

#include "TracySystem.hpp"

#ifdef TRACY_PLATFORM_HEADER
#  include TRACY_PLATFORM_HEADER
#endif

#if defined _WIN32
extern "C" typedef HRESULT (WINAPI *t_SetThreadDescription)( HANDLE, PCWSTR );
extern "C" typedef HRESULT (WINAPI *t_GetThreadDescription)( HANDLE, PWSTR* );
#endif

#ifdef TRACY_ENABLE
#  include <atomic>
#  include "TracyAlloc.hpp"
#endif

namespace tracy
{

namespace detail
{

TRACY_API uint32_t GetThreadHandleImpl()
{
#if defined TRACY_HAS_CUSTOM_THREAD_ID
    return PlatformGetThreadId();
#elif defined _WIN32
    static_assert( sizeof( decltype( GetCurrentThreadId() ) ) <= sizeof( uint32_t ), "Thread handle too big to fit in protocol" );
    return uint32_t( GetCurrentThreadId() );
#elif defined __APPLE__
    uint64_t id;
    pthread_threadid_np( pthread_self(), &id );
    return uint32_t( id );
#elif defined __ANDROID__
    return (uint32_t)gettid();
#elif defined __linux__
    return (uint32_t)syscall( SYS_gettid );
#elif defined __FreeBSD__
    long id;
    thr_self( &id );
    return id;
#elif defined __NetBSD__
    return _lwp_self();
#elif defined __DragonFly__
    return lwp_gettid();
#elif defined __OpenBSD__
    return getthrid();
#elif defined __QNX__
    return (uint32_t) gettid();
#elif defined __EMSCRIPTEN__
    // Not supported, but let it compile.
    return 0;
#else
    // To add support for a platform, retrieve and return the kernel thread identifier here.
    //
    // Note that pthread_t (as for example returned by pthread_self()) is *not* a kernel
    // thread identifier. It is a pointer to a library-allocated data structure instead.
    // Such pointers will be reused heavily, making the pthread_t non-unique. Additionally
    // a 64-bit pointer cannot be reliably truncated to 32 bits.
    #error "Unsupported platform!"
#endif

}

}

#ifdef TRACY_ENABLE
std::atomic<ThreadNameData*>& GetThreadNameData();
#endif

#if defined _MSC_VER && !defined __clang__
#  pragma pack( push, 8 )
struct THREADNAME_INFO
{
    DWORD dwType;
    LPCSTR szName;
    DWORD dwThreadID;
    DWORD dwFlags;
};
#  pragma pack( pop )

void ThreadNameMsvcMagic( const THREADNAME_INFO& info )
{
    __try
    {
        RaiseException( 0x406D1388, 0, sizeof(info)/sizeof(ULONG_PTR), (ULONG_PTR*)&info );
    }
    __except(EXCEPTION_EXECUTE_HANDLER)
    {
    }
}
#endif

TRACY_API void SetThreadName( const char* name )
{
    SetThreadNameWithHint( name, 0 );
}

TRACY_API void SetThreadNameWithHint( const char* name, int32_t groupHint )
{
#if defined _WIN32
#  if defined TRACY_WIN32_NO_DESKTOP
    static auto _SetThreadDescription = &::SetThreadDescription;
#  else
    static auto _SetThreadDescription = (t_SetThreadDescription)GetProcAddress( GetModuleHandleA( "kernel32.dll" ), "SetThreadDescription" );
#  endif
    if( _SetThreadDescription )
    {
        wchar_t buf[256];
        mbstowcs( buf, name, 256 );
        _SetThreadDescription( GetCurrentThread(), buf );
    }
    else
    {
#  if defined _MSC_VER && !defined __clang__
        THREADNAME_INFO info;
        info.dwType = 0x1000;
        info.szName = name;
        info.dwThreadID = GetCurrentThreadId();
        info.dwFlags = 0;
        ThreadNameMsvcMagic( info );
#  endif
    }
#elif defined _GNU_SOURCE && !defined __EMSCRIPTEN__
    {
#if defined __APPLE__
        pthread_setname_np( name );
#else
        const auto sz = strlen( name );
        if( sz <= 15 )
        {
            pthread_setname_np( pthread_self(), name );
        }
        else
        {
            char buf[16];
            memcpy( buf, name, 15 );
            buf[15] = '\0';
            pthread_setname_np( pthread_self(), buf );
        }
#endif
    }
#elif defined __QNX__
    {
        const auto sz = strlen( name );
        if( sz <= _NTO_THREAD_NAME_MAX )
        {
            pthread_setname_np( pthread_self(), name );
        }
        else
        {
            char buf[_NTO_THREAD_NAME_MAX + 1];
            memcpy( buf, name, _NTO_THREAD_NAME_MAX );
            buf[_NTO_THREAD_NAME_MAX] = '\0';
            pthread_setname_np( pthread_self(), buf );
        }
    };
#endif
#ifdef TRACY_ENABLE
    {
        const auto sz = strlen( name );
        char* buf = (char*)tracy_malloc( sz+1 );
        memcpy( buf, name, sz );
        buf[sz] = '\0';
        auto data = (ThreadNameData*)tracy_malloc_fast( sizeof( ThreadNameData ) );
        data->id = detail::GetThreadHandleImpl();
        data->groupHint = groupHint;
        data->name = buf;
        data->next = GetThreadNameData().load( std::memory_order_relaxed );
        while( !GetThreadNameData().compare_exchange_weak( data->next, data, std::memory_order_release, std::memory_order_relaxed ) ) {}
    }
#endif
}

#ifdef TRACY_ENABLE
ThreadNameData* GetThreadNameData( uint32_t id )
{
    auto ptr = GetThreadNameData().load( std::memory_order_relaxed );
    while( ptr )
    {
        if( ptr->id == id )
        {
            return ptr;
        }
        ptr = ptr->next;
    }
    return nullptr;
}
#endif

TRACY_API const char* GetThreadName( uint32_t id )
{
    static char buf[256];
#ifdef TRACY_ENABLE
    auto ptr = GetThreadNameData().load( std::memory_order_relaxed );
    while( ptr )
    {
        if( ptr->id == id )
        {
            return ptr->name;
        }
        ptr = ptr->next;
    }
#endif

#if defined _WIN32
# if defined TRACY_WIN32_NO_DESKTOP
   static auto _GetThreadDescription = &::GetThreadDescription;
# else
   static auto _GetThreadDescription = (t_GetThreadDescription)GetProcAddress( GetModuleHandleA( "kernel32.dll" ), "GetThreadDescription" );
# endif
    if( _GetThreadDescription )
    {
        auto hnd = OpenThread( THREAD_QUERY_LIMITED_INFORMATION, FALSE, (DWORD)id );
        if( hnd != 0 )
        {
            PWSTR tmp;
            if( SUCCEEDED( _GetThreadDescription( hnd, &tmp ) ) )
            {
                auto ret = wcstombs( buf, tmp, 256 );
                CloseHandle( hnd );
                LocalFree( tmp );
                if( ret != static_cast<size_t>( -1 ) )
                {
                    return buf;
                }
            }
        }
    }
#elif defined __linux__
  int cs, fd;
  char path[32];
  snprintf( path, sizeof( path ), "/proc/self/task/%d/comm", id );
  sprintf( buf, "%" PRIu32, id );
# ifndef __ANDROID__
   pthread_setcancelstate( PTHREAD_CANCEL_DISABLE, &cs );
# endif
  if ( ( fd = open( path, O_RDONLY ) ) > 0) {
      int len = read( fd, buf, 255 );
      if( len > 0 )
      {
          buf[len] = 0;
          if( len > 1 && buf[len-1] == '\n' )
          {
              buf[len-1] = 0;
          }
      }
      close( fd );
  }
# ifndef __ANDROID__
   pthread_setcancelstate( cs, 0 );
# endif
  return buf;
#elif defined __QNX__
    static char qnxNameBuf[_NTO_THREAD_NAME_MAX + 1] = {0};
    if (pthread_getname_np(static_cast<int>(id), qnxNameBuf, _NTO_THREAD_NAME_MAX) == 0) {
        return qnxNameBuf;
    };
#endif

  sprintf( buf, "%" PRIu32, id );
  return buf;
}

TRACY_API const char* GetEnvVar( const char* name )
{
#if defined _WIN32
    // unfortunately getenv() on Windows is just fundamentally broken.  It caches the entire
    // environment block once on startup, then never refreshes it again.  If any environment
    // strings are added or modified after startup of the CRT, those changes will not be
    // seen by getenv().  This removes the possibility of an app using this SDK from
    // programmatically setting any of the behaviour controlling envvars here.
    //
    // To work around this, we'll instead go directly to the Win32 environment strings APIs
    // to get the current value.
    static char buffer[1024];
    DWORD const kBufferSize = DWORD(sizeof(buffer) / sizeof(buffer[0]));
    DWORD count = GetEnvironmentVariableA(name, buffer, kBufferSize);

    if( count == 0 )
        return nullptr;

    if( count >= kBufferSize )
    {
        char* buf = reinterpret_cast<char*>(_alloca(count + 1));
        count = GetEnvironmentVariableA(name, buf, count + 1);
        memcpy(buffer, buf, kBufferSize);
        buffer[kBufferSize - 1] = 0;
    }

    return buffer;
#else
    return getenv(name);
#endif
}

TRACY_API const char* GetUserLogin()
{
#if defined TRACY_HAS_CUSTOM_USER_INFO
    return PlatformGetUserLogin();
#elif defined _WIN32
#  if defined TRACY_WIN32_NO_DESKTOP
    return "(?)";
#  else
    DWORD userSz = UNLEN+1;
    static char user[UNLEN+1];
    GetUserNameA( user, &userSz );
    return user;
#  endif
#elif defined __ANDROID__
    const auto user = getlogin();
    if( user ) return user;
    return "(?)";
#else
    static char user[1024] = {};
    getlogin_r( user, sizeof( user ) );
    return user;
#endif
}

TRACY_API const char* GetUserFullName()
{
#if defined TRACY_HAS_CUSTOM_USER_INFO
    return PlatformGetUserFullName();
#elif defined _WIN32
#  if !defined TRACY_WIN32_NO_DESKTOP
    static char buf[1024];
    ULONG size = sizeof( buf );
    if( GetUserNameExA( NameDisplay, buf, &size ) ) return buf;
#  endif
    return nullptr;
#elif defined __ANDROID__
    const auto passwd = getpwuid( getuid() );
    if( passwd && passwd->pw_gecos && *passwd->pw_gecos ) return passwd->pw_gecos;
    return nullptr;
#else
    static char buf[4*1024];
    struct passwd pwd;
    struct passwd* ptr;
    if( getpwuid_r( getuid(), &pwd, buf, sizeof( buf ), &ptr ) == 0 && ptr == &pwd && *pwd.pw_gecos )
    {
        return pwd.pw_gecos;
    }
    return nullptr;
#endif
}

}

#ifdef __cplusplus
extern "C" {
#endif

TRACY_API void ___tracy_set_thread_name( const char* name ) { tracy::SetThreadName( name ); }

#ifdef __cplusplus
}
#endif