-
Notifications
You must be signed in to change notification settings - Fork 0
/
glx_hook.c
2766 lines (2476 loc) · 79.9 KB
/
glx_hook.c
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
#define _GNU_SOURCE
#include <dlfcn.h> /* for RTLD_NEXT */
#include <pthread.h> /* for mutextes */
#include <unistd.h> /* for usleep(3) */
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <stdarg.h>
#include <ctype.h>
#include <limits.h>
#include <GL/glx.h>
#include <GL/glxext.h>
#ifdef GH_CONTEXT_TRACKING
#include <time.h> /* for clock_gettime */
#include <GL/glext.h>
#endif
#include "dlsym_wrapper.h"
#ifdef __GLIBC__
#if (__GLIBC__ > 2) || ( (__GLIBC__ == 2 ) && (__GLIBC_MINOR__ >= 34))
/* glibc >= 2.34 does not export _dl_sym() any more, we MUST use the dlvsym approach */
#if (GH_DLSYM_METHOD == 1)
#error GH_DLSYM_METHOD 1 is not available with this libc version
#endif
#endif
#endif
/* we use this value as swap interval to mark the situation that we should
* not set the swap interval at all. Note that with
* GLX_EXT_swap_control_tear, negative intervals are allowed, and the
* absolute value specifies the real interval, so we use just INT_MIN to
* avoid conflicts with values an application might set. */
#define GH_SWAP_DONT_SET INT_MIN
/***************************************************************************
* GH_DLSYM_METHOD selection *
***************************************************************************/
/* supported methods:
* 0: _dl_sym()
* 1: dlvsym()
* 2: dlsym_wrapper.so
* See README.md for details
*/
#if (GH_DLSYM_METHOD == 1) /* METHOD 1*/
#define GH_DLSYM_NEED_LOCK /* METHOD 2*/
#elif (GH_DLSYM_METHOD == 2)
#if defined(__x86_64__) /* platforms */
#define GH_DLSYM_ABI_VERSION "2.2.5"
#elif defined(__i386__)
#define GH_DLSYM_ABI_VERSION "2.0"
#else
/* if you need support for your platform, get the exact version for dlsym
* for the glibc ABI of your platform */
#error platform not supported
#endif /* platforms */
#elif (GH_DLSYM_METHOD == 3) /* METHOD 3*/
#define GH_DLSYM_NEED_LOCK
#else
#error GH_DLSYM_METHOD not supported
#endif /* GH_DLSYM_METHOD */
/***************************************************************************
* helpers *
***************************************************************************/
static const char *
get_envs(const char *name, const char *def)
{
const char *s=getenv(name);
return (s)?s:def;
}
static int
get_envi(const char *name, int def)
{
const char *s=getenv(name);
int i;
if (s) {
i=(int)strtol(s,NULL,0);
} else {
i=def;
}
return i;
}
#ifdef GH_CONTEXT_TRACKING
static unsigned int
get_envui(const char *name, unsigned int def)
{
const char *s=getenv(name);
int i;
if (s) {
i=(unsigned)strtoul(s,NULL,0);
} else {
i=def;
}
return i;
}
#endif
static size_t
buf_printf(char *buf, size_t pos, size_t size, const char *fmt, ...)
{
va_list args;
size_t left=size-pos;
int r;
va_start(args, fmt);
r=vsnprintf(buf+pos, left, fmt, args);
va_end(args);
if (r > 0) {
size_t written=(size_t)r;
pos += (written >= left)?left:written;
}
return pos;
}
static void
parse_name(char *buf, size_t size, const char *name_template, unsigned int ctx_num)
{
struct timespec ts_now;
int in_escape=0;
size_t pos=0;
char c;
buf[--size]=0; /* resverve space for final NUL terminator */
while ( (pos < size) && (c=*(name_template++)) ) {
if (in_escape) {
switch(c) {
case '%':
buf[pos++]=c;
break;
case 'c':
pos=buf_printf(buf,pos,size,"%u",ctx_num);
break;
case 'p':
pos=buf_printf(buf,pos,size,"%u",(unsigned)getpid());
break;
case 't':
clock_gettime(CLOCK_REALTIME, &ts_now);
pos=buf_printf(buf,pos,size,"%09lld.%ld",
(long long)ts_now.tv_sec,
ts_now.tv_nsec);
break;
default:
pos=buf_printf(buf,pos,size,"%%%c",c);
}
in_escape=0;
} else {
switch(c) {
case '%':
in_escape=1;
break;
default:
buf[pos++]=c;
}
}
}
buf[pos]=0;
}
/***************************************************************************
* MESSAGE OUTPUT *
***************************************************************************/
typedef enum {
GH_MSG_NONE=0,
GH_MSG_ERROR,
GH_MSG_WARNING,
GH_MSG_INFO,
GH_MSG_DEBUG,
GH_MSG_DEBUG_INTERCEPTION
} GH_msglevel;
#ifdef NDEBUG
#define GH_MSG_LEVEL_DEFAULT GH_MSG_WARNING
#else
#define GH_MSG_LEVEL_DEFAULT GH_MSG_DEBUG_INTERCEPTION
#endif
#define GH_DEFAULT_OUTPUT_STREAM stderr
static void GH_verbose(int level, const char *fmt, ...)
{
static int verbosity=-1;
static FILE *output_stream=NULL;
static int stream_initialized=0;
va_list args;
if (verbosity < 0) {
verbosity=get_envi("GH_VERBOSE", GH_MSG_LEVEL_DEFAULT);
}
if (level > verbosity) {
return;
}
if (!stream_initialized) {
const char *file=getenv("GH_VERBOSE_FILE");
if (file) {
char buf[PATH_MAX];
parse_name(buf, sizeof(buf), file, 0);
output_stream=fopen(buf,"a+t");
}
if (!output_stream)
output_stream=GH_DEFAULT_OUTPUT_STREAM;
stream_initialized=1;
}
fprintf(output_stream,"GH: ");
va_start(args, fmt);
vfprintf(output_stream, fmt, args);
va_end(args);
fflush(output_stream);
}
/***************************************************************************
* FUNCTION INTERCEPTOR LOGIC *
***************************************************************************/
typedef void (*GH_fptr)();
typedef void * (*GH_resolve_func)(const char *);
#ifdef GH_DLSYM_NEED_LOCK
/* mutex used during GH_dlsym_internal () */
static pthread_mutex_t GH_mutex=PTHREAD_MUTEX_INITIALIZER;
#endif
#if (GH_DLSYM_METHOD == 1)
/* THIS IS AN EVIL HACK: we directly call _dl_sym() of the glibc
* NOTE: the approrpiate function prototype could be
* extern void *_dl_sym(void *, const char *, void (*)() );
* but we use it only with some specific argument for the
* last parameter, and use the function pointer type
* directly in this declaration, which avoids us to do a
* cast between (technically incompatible) function pointer
* types. Hiding the cast in the declatation is of course
* as broken as before from a C correctness point of view,
* but the compiler won't notice any more... ;) */
extern void *_dl_sym(void *, const char *, void* (*)(void *, const char *) );
#elif (GH_DLSYM_METHOD == 3)
/* Use the dlsym_wrapper. We can use dlopen(), but we can not
* use dlsym() or dlvsym(), as these functions are hooked by ourselves.
* However, dlsym_wrapper will execute an intialization function when
* dlopen() is called. The trick is the we load dlsym_wrapper.so
* with RTLD_LOCAL | RTLD_DEEPBIND, so that it gets its own private
* linker map to the libdl.so, without falling back on the dlsym()
* defined here. It then forwards the pointer via an environment
* variable (as hex via printf %p format string) */
static void *dlsym_wrapper_get(void* handle, const char *name)
{
char dlsym_wrapper_name[4096];
void *wrapper;
const char * ptr_str;
void *res = NULL;
void *ptr = NULL;
Dl_info self;
size_t len;
char *pos;
size_t idx;
size_t slen;
(void)handle;
(void)name;
memset(&self,0, sizeof(self));
if (!dladdr(dlsym_wrapper_get, &self)) {
GH_verbose(GH_MSG_ERROR,"dlsym_wrapper: failed to find myself!\n");
return NULL;
}
if (!self.dli_fname) {
GH_verbose(GH_MSG_ERROR,"dlsym_wrapper: failed to find my path!\n");
return NULL;
}
GH_verbose(GH_MSG_DEBUG,"dlsym_wrapper: I am at '%s'\n", self.dli_fname);
len = strlen(self.dli_fname);
if (len >= sizeof(dlsym_wrapper_name)) {
GH_verbose(GH_MSG_ERROR,"dlsym_wrapper: my path '%s' is too long: %zu >= %zu\n", self.dli_fname, len, sizeof(dlsym_wrapper_name));
return NULL;
}
memcpy(dlsym_wrapper_name, self.dli_fname, len+1);
pos = strrchr(dlsym_wrapper_name, '/');
if (pos) {
idx = pos - dlsym_wrapper_name + 1;
} else {
idx = 0;
}
if (idx > len) {
GH_verbose(GH_MSG_ERROR,"dlsym_wrapper: failed to process my path '%s'\n", dlsym_wrapper_name);
return NULL;
}
len = sizeof(dlsym_wrapper_name) - idx;
slen = strlen(DLSYM_WRAPPER_NAME) + 1;
if (len < slen) {
GH_verbose(GH_MSG_ERROR,"dlsym_wrapper: failed to build path to the wrapper library: avail %zu < needed %zu\n", len, slen);
return NULL;
}
memcpy(dlsym_wrapper_name + idx, DLSYM_WRAPPER_NAME, slen);
GH_verbose(GH_MSG_ERROR,"dlsym_wrapper: wrapper library should be at '%s'\n", dlsym_wrapper_name);
if (getenv(DLSYM_WRAPPER_ENVNAME)) {
GH_verbose(GH_MSG_WARNING,"dlsym_wrapper: '%s' already defined, shouldn't be\n", DLSYM_WRAPPER_ENVNAME);
}
wrapper = dlopen(dlsym_wrapper_name, RTLD_LAZY | RTLD_LOCAL | RTLD_DEEPBIND | RTLD_NOLOAD);
if (wrapper) {
GH_verbose(GH_MSG_ERROR,"dlsym_wrapper: '%s' already loaded, this does not work!\n", dlsym_wrapper_name);
dlclose(wrapper);
return NULL;
}
wrapper = dlopen(dlsym_wrapper_name, RTLD_LAZY | RTLD_LOCAL | RTLD_DEEPBIND);
if (!wrapper) {
GH_verbose(GH_MSG_ERROR,"dlsym_wrapper: '%s' could not be loaded!\n", dlsym_wrapper_name);
return NULL;
}
ptr_str = getenv(DLSYM_WRAPPER_ENVNAME);
if (!ptr_str) {
GH_verbose(GH_MSG_ERROR,"dlsym_wrapper: '%s' was not defined by the wrapper library\n", DLSYM_WRAPPER_ENVNAME);
dlclose(wrapper);
return NULL;
}
GH_verbose(GH_MSG_DEBUG, "dlsym_wrapper: got '%s'='%s'\n", DLSYM_WRAPPER_ENVNAME, ptr_str);
if (sscanf(ptr_str, "%p", &ptr) == 1) {
if (ptr) {
GH_verbose(GH_MSG_DEBUG, "dlsym_wrapper: using %p as original dlsym()\n", ptr);
res = ptr;
} else {
GH_verbose(GH_MSG_ERROR, "dlsym_wrapper: original dlsym() pointer is invalid\n", ptr);
}
} else {
GH_verbose(GH_MSG_WARNING,"dlsym_wrapper: failed to parse pointer from '%s'='%s'\n", DLSYM_WRAPPER_ENVNAME, ptr_str);
}
dlclose(wrapper);
if (res) {
GH_verbose(GH_MSG_ERROR, "dlsym_wrapper: successfilly queried '%s' = %p\n", name, res);
} else {
GH_verbose(GH_MSG_ERROR, "dlsym_wrapper: failed to query '%s'\n", name);
}
return res;
}
#endif
/* Mutex for the function pointers. We only guard the
* if (ptr == NULL) ptr=...; part. The pointers will never
* change after being set to a non-NULL value for the first time,
* so it is safe to dereference them without locking */
static pthread_mutex_t GH_fptr_mutex=PTHREAD_MUTEX_INITIALIZER;
/* Wrapper function called in place of dlsym(), since we intercept dlsym().
* We use this ONLY to get the original dlsym() itself, all other symbol
* resolutions are done via that original function, then.
*/
static void *GH_dlsym_internal(void *handle, const char *name)
{
void *ptr;
#ifdef GH_DLSYM_NEED_LOCK
/* ARGH: we are bypassing glibc's locking for dlsym(), so we
* must do this on our own */
pthread_mutex_lock(&GH_mutex);
#endif
#if (GH_DLSYM_METHOD == 1)
GH_verbose(GH_MSG_DEBUG, "using _dl_sym() method\n");
/* Third argument is the address of the caller, (glibc uses stack
* unwinding internally to get this), we just use the address of our
* wrapper function itself, which is wrong when this is called on
* behalf of the real application doing a dlsycm, but we do not
* care... */
ptr=_dl_sym(handle, name, GH_dlsym_internal);
#elif (GH_DLSYM_METHOD == 2)
GH_verbose(GH_MSG_DEBUG, "using dlvsym() method\n");
ptr=dlvsym(handle, name, "GLIBC_" GH_DLSYM_ABI_VERSION);
#elif (GH_DLSYM_METHOD == 3)
GH_verbose(GH_MSG_DEBUG, "using dlsym_wrapper.so method\n");
ptr=dlsym_wrapper_get(handle, name);
#else
#error GH_DLSYM_METHOD not supported
#endif /* GH_DLSYM_METHOD */
#ifdef GH_DLSYM_NEED_LOCK
pthread_mutex_unlock(&GH_mutex);
#endif
return ptr;
}
/* Wrapper funtcion to query an original function avoiding
* recursively calls to the interceptor dlsym() below */
static void *GH_dlsym_internal_next(const char *name)
{
return GH_dlsym_internal(RTLD_NEXT, name);
}
/* return intercepted function pointer for a symbol */
static void *GH_get_interceptor(const char*, GH_resolve_func, const char *);
/* function pointers to call the real functions that we did intercept */
static void * (* volatile GH_dlsym)(void *, const char*)=NULL;
static void * (* volatile GH_dlvsym)(void *, const char*, const char *)=NULL;
static GH_fptr (* volatile GH_glXGetProcAddress)(const char*)=NULL;
static GH_fptr (* volatile GH_glXGetProcAddressARB)(const char *)=NULL;
static void (* volatile GH_glXSwapBuffers)(Display *, GLXDrawable);
static void (* volatile GH_glXSwapIntervalEXT)(Display *, GLXDrawable, int);
static int (* volatile GH_glXSwapIntervalSGI)(int);
static int (* volatile GH_glXSwapIntervalMESA)(unsigned int);
static GLXContext (* volatile GH_glXCreateContext)(Display*, XVisualInfo *, GLXContext, Bool);
static GLXContext (* volatile GH_glXCreateNewContext)(Display *, GLXFBConfig, int, GLXContext, Bool);
static GLXContext (* volatile GH_glXCreateContextAttribsARB)(Display *, GLXFBConfig, GLXContext, Bool, const int *);
static GLXContext (* volatile GH_glXImportContextEXT)(Display *, GLXContextID);
static GLXContext (* volatile GH_glXCreateContextWithConfigSGIX)(Display *, GLXFBConfigSGIX, int, GLXContext, Bool);
static void (* volatile GH_glXDestroyContext)(Display *, GLXContext);
static void (* volatile GH_glXFreeContextEXT)(Display *, GLXContext);
static Bool (* volatile GH_glXMakeCurrent)(Display *, GLXDrawable, GLXContext);
static Bool (* volatile GH_glXMakeContextCurrent)(Display *, GLXDrawable, GLXDrawable, GLXContext);
static Bool (* volatile GH_glXMakeCurrentReadSGI)(Display *, GLXDrawable, GLXDrawable, GLXContext);
static void (* volatile GH_glDebugMessageCallback)(GLDEBUGPROC, const GLvoid*);
static void (* volatile GH_glDebugMessageCallbackARB)(GLDEBUGPROC, const GLvoid*);
static void (* volatile GH_glDebugMessageCallbackKHR)(GLDEBUGPROC, const GLvoid*);
static void (* volatile GH_glDebugMessageCallbackAMD)(GLDEBUGPROCAMD, GLvoid*);
/* function pointers we just might qeury */
static void (* volatile GH_glFlush)(void);
static void (* volatile GH_glFinish)(void);
static GLXFBConfig* (* volatile GH_glXGetFBConfigs)(Display*, int, int*);
static int (* volatile GH_glXGetFBConfigAttrib)(Display*, GLXFBConfig, int, int*);
static int (* volatile GH_XFree)(void*);
#ifdef GH_CONTEXT_TRACKING
/* OpenGL extension functions we might query */
static PFNGLGENQUERIESPROC GH_glGenQueries=NULL;
static PFNGLDELETEQUERIESPROC GH_glDeleteQueries=NULL;
static PFNGLGETINTEGER64VPROC GH_glGetInteger64v=NULL;
static PFNGLQUERYCOUNTERPROC GH_glQueryCounter=NULL;
static PFNGLGETQUERYOBJECTUI64VPROC GH_glGetQueryObjectui64v=NULL;
static PFNGLFENCESYNCPROC GH_glFenceSync=NULL;
static PFNGLDELETESYNCPROC GH_glDeleteSync=NULL;
static PFNGLCLIENTWAITSYNCPROC GH_glClientWaitSync=NULL;
#endif /* GH_CONTEXT_TRACKING */
/* Resolve an unintercepted symbol via the original dlsym() */
static void *GH_dlsym_next(const char *name)
{
if (GH_dlsym) {
return GH_dlsym(RTLD_NEXT, name);
}
GH_verbose(GH_MSG_WARNING, "failed to dynamically query '%s' because I don't have a dlsym\n", name);
return NULL;
}
/* Wrapper funtcion to query the original dlsym() function avoiding
* recursively calls to the interceptor dlsym() below */
static void GH_dlsym_internal_dlsym()
{
static const char *dlsymname = "dlsym";
static const char *dlvsymname = "dlvsym";
DLSYM_PROC_T orig_dlsym = NULL;
if (GH_dlsym == NULL) {
GH_dlsym = GH_dlsym_internal_next(dlsymname);
orig_dlsym = GH_dlsym;
if (GH_dlsym) {
void *ptr;
GH_verbose(GH_MSG_DEBUG_INTERCEPTION,"INTERNAL: (%s) = %p, ours is %p\n",dlsymname,GH_dlsym,dlsym);
ptr = GH_dlsym_next(dlsymname);
if (ptr != (void*)GH_dlsym) {
if (ptr) {
if (get_envi("GH_ALLOW_DLSYM_REDIRECTION", 1)) {
GH_verbose(GH_MSG_DEBUG_INTERCEPTION,"INTERNAL: (%s) = %p intercepted to %p\n",dlsymname,GH_dlsym,ptr);
GH_dlsym = ptr;
} else {
GH_verbose(GH_MSG_WARNING, "INTERNAL: (%s) = %p would be intercepted to %p but ignoring it\n",dlsymname,GH_dlsym,ptr);
}
} else {
GH_verbose(GH_MSG_WARNING,"INTERNAL: (%s) would be intercepted to NULL, ignoring it\n",dlsymname);
}
}
} else {
GH_verbose(GH_MSG_WARNING, "failed to dynamically query '%s'\n", dlsymname);
}
}
/* use the original dlsym, not a potentially redirected one */
if (orig_dlsym && (GH_dlvsym == NULL)) {
Dl_info info;
memset(&info,0,sizeof(info));
GH_dlvsym = orig_dlsym(RTLD_NEXT,dlvsymname);
}
}
/* Resolve an unintercepted symbol via the original dlsym(),
* special libGL variant: if not found, dymically try to
* load libGL.so */
static void *GH_dlsym_gl(const char *name)
{
static void *libgl_handle=NULL;
static int try_load_libgl=1;
void *ptr=GH_dlsym(RTLD_NEXT, name);
if (!ptr) {
if (try_load_libgl && !libgl_handle) {
const char *libname=get_envs("GH_LIBGL_FILE", "libGL.so");
if (libname[0]) {
GH_verbose(GH_MSG_DEBUG, "trying to load libGL manually: '%s'\n", libname);
libgl_handle=dlopen(libname, RTLD_GLOBAL | RTLD_LAZY);
if (!libgl_handle) {
GH_verbose(GH_MSG_WARNING, "failed to load '%s' manually\n", libname);
/* give up on loading libGL */
try_load_libgl=0;
}
} else {
try_load_libgl=0;
}
}
if (libgl_handle) {
GH_verbose(GH_MSG_DEBUG, "trying to find '%s' in manually loaded libGL\n", name);
ptr=GH_dlsym(libgl_handle, name);
}
}
return ptr;
}
/* helper macro: query the symbol pointer if it is NULL
* handle the locking */
#define GH_GET_PTR(func) \
pthread_mutex_lock(&GH_fptr_mutex); \
if(GH_ ##func == NULL) \
GH_ ##func = GH_dlsym_next(#func);\
pthread_mutex_unlock(&GH_fptr_mutex)
/* helper macro: query the symbol pointer if it is NULL
* handle the locking, special libGL variant */
#define GH_GET_PTR_GL(func) \
pthread_mutex_lock(&GH_fptr_mutex); \
if(GH_ ##func == NULL) \
GH_ ##func = GH_dlsym_gl(#func);\
pthread_mutex_unlock(&GH_fptr_mutex)
#ifdef GH_CONTEXT_TRACKING
/* try to get an OpenGL function */
static void *
GH_get_gl_proc(const char *name)
{
static void *proc;
/* try glXGetProcAddressARB first */
GH_GET_PTR(glXGetProcAddressARB);
if (GH_glXGetProcAddressARB && (proc=GH_glXGetProcAddressARB(name)) )
return proc;
/* try glXGetProcAddress as second chance */
GH_GET_PTR(glXGetProcAddress);
if (GH_glXGetProcAddress && (proc=GH_glXGetProcAddress(name)) )
return proc;
/* try dlsym as last resort */
return GH_dlsym_gl(name);
}
#define GH_GET_GL_PROC(func) \
pthread_mutex_lock(&GH_fptr_mutex); \
if ( (GH_ ##func == NULL)) { \
void *ptr; \
pthread_mutex_unlock(&GH_fptr_mutex); \
ptr = GH_get_gl_proc(#func); \
GH_verbose(GH_MSG_DEBUG,"queried internal GL %s: %p\n", \
#func, ptr); \
pthread_mutex_lock(&GH_fptr_mutex); \
GH_ ##func = ptr; \
} \
pthread_mutex_unlock(&GH_fptr_mutex);
#define GH_GET_GL_PROC_OR_FAIL(func, level, fail_code) \
GH_GET_GL_PROC(func); \
if (GH_ ##func == NULL) { \
GH_verbose(level, "%s not available!\n", #func); \
return fail_code; \
} \
(void)0
/***************************************************************************
* LATENCY LIMITER *
***************************************************************************/
/* we support different modes for the frame time measurements */
typedef enum {
GH_LATENCY_NOP=-2, /* do nothing */
GH_LATENCY_FINISH_AFTER, /* force a finish after buffer swaps */
GH_LATENCY_FINISH_BEFORE, /* force a finish before buffer swaps */
/* values above 0 indicate use of GL_ARB_sync to limit to n frames */
} GH_latency_mode;
typedef struct {
int latency;
GLsync *sync_object;
unsigned int cur_pos;
unsigned int flags;
GLuint64 gl_wait_timeout;
GLuint64 gl_wait_interval;
useconds_t self_wait_interval;
} GH_latency;
/* latency flags */
#define GH_LATENCY_FLAG_MANUAL_WAIT 0x1
static int
latency_gl_init()
{
GH_GET_GL_PROC_OR_FAIL(glFenceSync, GH_MSG_WARNING, -1);
GH_GET_GL_PROC_OR_FAIL(glDeleteSync, GH_MSG_WARNING, -1);
GH_GET_GL_PROC_OR_FAIL(glClientWaitSync, GH_MSG_WARNING, -1);
return 0;
}
static void
latency_init(GH_latency *lat, int latency, int manual_wait, unsigned gl_wait_timeout_usecs, unsigned int gl_wait_interval_usecs, unsigned int self_wait_interval_usecs)
{
lat->latency=latency;
lat->sync_object=NULL;
lat->cur_pos=0;
lat->flags=0;
lat->gl_wait_timeout=(GLuint64)gl_wait_timeout_usecs * (GLuint64)1000;
lat->gl_wait_interval=(GLuint64)gl_wait_interval_usecs * (GLuint64)1000;
lat->self_wait_interval=(useconds_t)self_wait_interval_usecs;
if (manual_wait > 0) {
lat->flags |= GH_LATENCY_FLAG_MANUAL_WAIT;
} else if (manual_wait < 0) {
if ((gl_wait_interval_usecs > 0) || (self_wait_interval_usecs > 0)) {
lat->flags |= GH_LATENCY_FLAG_MANUAL_WAIT;
}
}
if (latency != GH_LATENCY_NOP) {
GH_verbose(GH_MSG_INFO, "setting up latency limiter mode %d\n", latency);
}
if (latency > 0) {
if (latency_gl_init()) {
lat->latency=GH_LATENCY_FINISH_BEFORE;
GH_verbose(GH_MSG_WARNING, "GPU sync not available, using latency mode %d\n",
GH_LATENCY_FINISH_BEFORE);
}
}
if (lat->latency > 0) {
unsigned int cnt=(unsigned)lat->latency;
lat->sync_object=malloc(sizeof(*lat->sync_object) * cnt);
if (!lat->sync_object) {
lat->latency=GH_LATENCY_FINISH_BEFORE;
GH_verbose(GH_MSG_WARNING, "out of memory for sync objects, using latency mode %d\n");
} else {
unsigned int i;
for (i=0; i<cnt; i++) {
lat->sync_object[i]=NULL;
}
GH_verbose(GH_MSG_DEBUG, "enabling latency limiter: %d\n",lat->latency);
if (lat->flags & GH_LATENCY_FLAG_MANUAL_WAIT) {
GH_verbose(GH_MSG_INFO, "latency limiter with manual waits GL: %u usecs + self: %u usecs\n",
gl_wait_interval_usecs, self_wait_interval_usecs);
} else {
GH_verbose(GH_MSG_INFO, "latency limiter with timeout: %u usecs\n",
gl_wait_timeout_usecs);
}
}
}
}
static void
latency_destroy(GH_latency *lat)
{
if (lat) {
if (lat->sync_object && lat->latency > 0) {
unsigned int i;
for (i=0; i<(unsigned)lat->latency; i++) {
if (lat->sync_object[i]) {
GH_glDeleteSync(lat->sync_object[i]);
}
}
}
}
}
static void
latency_before_swap(GH_latency *lat)
{
GLsync sync;
switch(lat->latency) {
case GH_LATENCY_NOP:
case GH_LATENCY_FINISH_AFTER:
(void)lat;
break;
case GH_LATENCY_FINISH_BEFORE:
GH_glFinish();
break;
default:
if ( (sync=lat->sync_object[lat->cur_pos]) ) {
if (lat->flags & GH_LATENCY_FLAG_MANUAL_WAIT) {
/* check for the fence in a loop */
while(GH_glClientWaitSync(sync, GL_SYNC_FLUSH_COMMANDS_BIT, lat->gl_wait_interval) == GL_TIMEOUT_EXPIRED) {
if (lat->self_wait_interval) {
usleep(lat->self_wait_interval);
}
}
} else {
/* just wait for the fence */
GH_glClientWaitSync(sync, GL_SYNC_FLUSH_COMMANDS_BIT, lat->gl_wait_timeout);
/* NOTE: we do not care about the result */
}
}
}
}
static void
latency_after_swap(GH_latency *lat)
{
switch(lat->latency) {
case GH_LATENCY_NOP:
case GH_LATENCY_FINISH_BEFORE:
(void)lat;
break;
case GH_LATENCY_FINISH_AFTER:
GH_glFinish();
break;
default:
if ( (lat->sync_object[lat->cur_pos]) ) {
GH_glDeleteSync(lat->sync_object[lat->cur_pos]);
}
lat->sync_object[lat->cur_pos]=GH_glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0);
if (++lat->cur_pos == (unsigned)lat->latency) {
lat->cur_pos=0;
}
}
}
/***************************************************************************
* FRAME TIMING MEASUREMENTS *
***************************************************************************/
/* we support different modes for the frame time measurements */
typedef enum {
GH_FRAMETIME_NONE=0, /* do not measure any frame times */
GH_FRAMETIME_CPU, /* measure only on CPU */
GH_FRAMETIME_CPU_GPU, /* measure both on CPU and GPU */
} GH_frametime_mode;
/* a single timestamp */
typedef struct {
struct timespec timestamp_cpu; /* CPU timestamp */
GLuint64 timestamp_gl; /* OpenGL timestamp (client side) */
GLuint query_object; /* the OpenGL timer query object */
} GH_timestamp;
/* the _result_ of the measurement */
typedef struct {
uint64_t cpu;
uint64_t gl;
uint64_t gpu;
} GH_frametime;
/* the complete state needed for frametime measurements */
typedef struct {
GH_frametime_mode mode; /* the mode we are in */
unsigned int delay; /* number of frames for delay */
unsigned int num_timestamps; /* number of timestamps per frame */
unsigned int num_results; /* number of frames to store results */
GH_timestamp *timestamp; /* the array of timestamps, used as ring buffer */
unsigned int cur_pos; /* the current frame in the delay ring buffer */
GH_frametime *frametime; /* the array of frametimes */
unsigned int cur_result; /* the current result index */
unsigned int frame; /* the current frame */
FILE *dump; /* the stream to dump the results to */
} GH_frametimes;
/* the probes we take each frame */
typedef enum {
GH_FRAMETIME_BEFORE_SWAPBUFFERS=0,
GH_FRAMETIME_AFTER_SWAPBUFFERS,
GH_FRAMETIME_COUNT
} GH_frametime_probe;
static void
timestamp_init(GH_timestamp *ts)
{
ts->query_object=0;
ts->timestamp_gl=0;
ts->timestamp_cpu.tv_sec=0;
ts->timestamp_cpu.tv_nsec=0;
}
static void
timestamp_cleanup(GH_timestamp *ts)
{
if (ts->query_object && GH_glDeleteQueries) {
GH_glDeleteQueries(1, &ts->query_object);
ts->query_object=0;
}
}
static void
timestamp_set(GH_timestamp *ts, GH_frametime *rs, GH_frametime_mode mode)
{
/* CPU */
/* collect previous result */
rs->cpu=(uint64_t)ts->timestamp_cpu.tv_sec * (uint64_t)1000000000UL
+ (uint64_t)ts->timestamp_cpu.tv_nsec;
/* new query */
clock_gettime(CLOCK_REALTIME, &ts->timestamp_cpu);
/* GPU */
if (mode >= GH_FRAMETIME_CPU_GPU) {
/* collect previous result */
if (ts->query_object) {
GLuint64 value;
GH_glGetQueryObjectui64v(ts->query_object, GL_QUERY_RESULT, &value);
rs->gpu=(uint64_t)value;
} else {
GH_glGenQueries(1, &ts->query_object);
}
rs->gl=(uint64_t)(ts->timestamp_gl);
/* new query */
GH_glQueryCounter(ts->query_object, GL_TIMESTAMP);
GH_glGetInteger64v(GL_TIMESTAMP, (GLint64*)&ts->timestamp_gl);
}
}
static void
frametime_init(GH_frametime *rs)
{
rs->cpu = 0;
rs->gl = 0;
rs->gpu = 0;
}
static int
frametimes_gl_init()
{
GH_GET_GL_PROC_OR_FAIL(glGenQueries, GH_MSG_WARNING, -1);
GH_GET_GL_PROC_OR_FAIL(glDeleteQueries, GH_MSG_WARNING, -1);
GH_GET_GL_PROC_OR_FAIL(glGetInteger64v, GH_MSG_WARNING, -1);
GH_GET_GL_PROC_OR_FAIL(glQueryCounter, GH_MSG_WARNING, -1);
GH_GET_GL_PROC_OR_FAIL(glGetQueryObjectui64v, GH_MSG_WARNING, -1);
return 0;
}
static void
frametimes_init(GH_frametimes *ft, GH_frametime_mode mode, unsigned int delay, unsigned int num_timestamps, unsigned int num_results, unsigned int ctx_num)
{
ft->cur_pos=0;
ft->cur_result=0;
ft->frame=0;
ft->dump=NULL;
if (mode >= GH_FRAMETIME_CPU_GPU) {
if (frametimes_gl_init()) {
GH_verbose(GH_MSG_WARNING, "GPU timer queries not available, using CPU only\n");
mode = GH_FRAMETIME_CPU;
}
}
if (mode && delay && num_timestamps && num_results) {
ft->mode=mode;
ft->delay=delay;
ft->num_timestamps=num_timestamps;
ft->num_results=num_results;
if ((ft->frametime=malloc(sizeof(*ft->frametime) * (num_results+1) * num_timestamps))) {
if ((ft->timestamp=malloc(sizeof(*ft->timestamp) * delay * num_timestamps))) {
unsigned int i;
GH_verbose(GH_MSG_DEBUG, "enabling frametime measurements mode %d, %u x %u timestamps\n",
(int)mode, delay, num_timestamps);
for (i=0; i<delay * num_timestamps; i++) {
timestamp_init(&ft->timestamp[i]);
}
} else {
GH_verbose(GH_MSG_WARNING, "failed to allocate memory for %u x %u timestamps, "
"disbaling timestamps\n",
delay, num_timestamps);
mode=GH_FRAMETIME_NONE;
}
} else {
GH_verbose(GH_MSG_WARNING, "failed to allocate memory for %u x %u frametime results, "
"disbaling timestamps\n",
num_results, num_timestamps);
mode=GH_FRAMETIME_NONE;
}
}
if (!mode || !delay || !num_timestamps || !num_results) {
ft->mode=GH_FRAMETIME_NONE;
ft->delay=0;
ft->num_timestamps=0;
ft->num_results=0;
ft->timestamp=NULL;
ft->frametime=NULL;
}
if (ft->mode) {
const char *file=get_envs("GH_FRAMETIME_FILE","glx_hook_frametimes-ctx%c.csv");
if (file) {
char buf[PATH_MAX];
parse_name(buf, sizeof(buf), file, ctx_num);
ft->dump=fopen(buf,"wt");
}
if (!ft->dump) {
ft->dump=stderr;
}
}
}
static void
frametimes_init_base(GH_frametimes *ft)
{
/* get the base timestamp */
if (ft->mode > GH_FRAMETIME_NONE) {
GH_timestamp base;
unsigned int i;
GH_frametime *last=&ft->frametime[ft->num_results * ft->num_timestamps];
timestamp_init(&base);
timestamp_set(&base, &last[0], ft->mode);
timestamp_set(&base, &last[0], ft->mode);
for (i=1; i<ft->num_timestamps; i++) {
last[i]=last[0];
}
timestamp_cleanup(&base);
}
}
static void
frametimes_dump_diff(const GH_frametimes *ft, uint64_t val, uint64_t base)
{
fprintf(ft->dump, "\t%llu", (unsigned long long) (val-base));
}
static void
frametimes_dump_result(const GH_frametimes *ft, const GH_frametime *rs, const GH_frametime *base)
{
frametimes_dump_diff(ft, rs->cpu, base->cpu);
frametimes_dump_diff(ft, rs->gpu, base->gpu);
frametimes_dump_diff(ft, rs->gpu, rs->gl);
}
static void
frametimes_dump_results(const GH_frametimes *ft, const GH_frametime *rs, const GH_frametime *prev)
{
unsigned int i;
for (i=0; i<ft->num_timestamps; i++) {
frametimes_dump_result(ft, &rs[i], &prev[GH_FRAMETIME_AFTER_SWAPBUFFERS]);
}
}
static void
frametimes_flush(GH_frametimes *ft)
{
unsigned int i;
GH_frametime *last;
const GH_frametime *cur,*prev=&ft->frametime[ft->num_results * ft->num_timestamps];
if (ft->cur_result == 0) {
return;
}
GH_verbose(GH_MSG_DEBUG, "frametimes: dumping results of %u frames\n", ft->cur_result);
for (i=0; i<ft->cur_result; i++) {
unsigned int frame=ft->frame - ft->cur_result + i;
if (frame >= ft->delay) {
fprintf(ft->dump, "%u", frame - ft->delay);
cur=&ft->frametime[i * ft->num_timestamps];
frametimes_dump_results(ft, cur, prev);
prev=cur;
fputc('\n', ft->dump);
}
}
fflush(ft->dump);
/* copy the last result */
last=&ft->frametime[ft->num_results * ft->num_timestamps];
cur=&ft->frametime[(ft->cur_result-1) * ft->num_timestamps];
for (i=0; i<ft->num_timestamps; i++) {
last[i]=cur[i];
}
ft->cur_result=0;
}
static void