-
Notifications
You must be signed in to change notification settings - Fork 86
Expand file tree
/
Copy pathintercept.cpp
More file actions
15000 lines (13245 loc) · 454 KB
/
Copy pathintercept.cpp
File metadata and controls
15000 lines (13245 loc) · 454 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
/*
// Copyright (c) 2018-2023 Intel Corporation
//
// SPDX-License-Identifier: MIT
*/
#include <algorithm>
#include <errno.h>
#include <fstream>
#include <iostream>
#include <iomanip>
#include <stdarg.h>
#include <sstream>
#include <time.h> // strdate
#include <cmath>
#include "common.h"
#include "demangle.h"
#include "emulate.h"
#include "intercept.h"
/*****************************************************************************\
Inline Function:
Hash
Description:
Calculates hash from sequence of 32-bit values.
Jenkins 96-bit mixing function with 32-bit feedback-loop and 64-bit state.
All magic values are DWORDs of SHA2-256 mixing data:
0x428a2f98 0x71374491 0xb5c0fbcf 0xe9b5dba5
0x3956c25b 0x59f111f1 0x923f82a4 0xab1c5ed5
From: http://www.burtleburtle.net/bob/c/lookup2.c
lookup2.c, by Bob Jenkins, December 1996, Public Domain.
hash(), hash2(), hash3, and mix() are externally useful functions.
Routines to test the hash are included if SELF_TEST is defined.
You can use this free for any purpose. It has no warranty.
\*****************************************************************************/
#define HASH_JENKINS_MIX(a,b,c) \
{ \
a -= b; a -= c; a ^= (c>>13); \
b -= c; b -= a; b ^= (a<<8); \
c -= a; c -= b; c ^= (b>>13); \
a -= b; a -= c; a ^= (c>>12); \
b -= c; b -= a; b ^= (a<<16); \
c -= a; c -= b; c ^= (b>>5); \
a -= b; a -= c; a ^= (c>>3); \
b -= c; b -= a; b ^= (a<<10); \
c -= a; c -= b; c ^= (b>>15); \
}
static inline uint64_t Hash(
const void* ptr,
size_t count )
{
unsigned int a = 0x428a2f98, hi = 0x71374491, lo = 0xb5c0fbcf;
const uint32_t* dwData = reinterpret_cast<const uint32_t*>(ptr);
size_t dwCount = count / sizeof(uint32_t);
while( dwCount-- )
{
a ^= *(dwData++);
HASH_JENKINS_MIX( a, hi, lo );
}
size_t extra = count % sizeof(uint32_t);
if( extra != 0 )
{
uint32_t extraValue = 0;
const uint8_t* data = reinterpret_cast<const uint8_t*>(ptr);
data += count - extra;
for( size_t i = 0; i < extra; i++) {
extraValue += *(data++) << (i * 8);
}
a ^= extraValue;
HASH_JENKINS_MIX( a, hi, lo );
}
return (((uint64_t)hi)<<32)|lo;
}
#undef HASH_JENKINS_MIX
const char* CLIntercept::sc_URL = "https://github.com/intel/opencl-intercept-layer";
const char* CLIntercept::sc_DumpDirectoryName = "CLIntercept_Dump";
const char* CLIntercept::sc_ReportFileName = "clintercept_report.txt";
const char* CLIntercept::sc_LogFileName = "clintercept_log.txt";
const char* CLIntercept::sc_DumpPerfCountersFileNamePrefix = "clintercept_perfcounter";
const char* CLIntercept::sc_TraceFileName = "clintercept_trace.json";
///////////////////////////////////////////////////////////////////////////////
//
bool CLIntercept::Create( void* pGlobalData, CLIntercept*& pIntercept )
{
bool success = false;
pIntercept = new CLIntercept( pGlobalData );
if( pIntercept )
{
success = pIntercept->init();
if( success == false )
{
Delete( pIntercept );
}
}
return success;
}
///////////////////////////////////////////////////////////////////////////////
//
void CLIntercept::Delete( CLIntercept*& pIntercept )
{
delete pIntercept;
pIntercept = NULL;
}
///////////////////////////////////////////////////////////////////////////////
//
CLIntercept::CLIntercept( void* pGlobalData )
: m_OS( pGlobalData )
{
m_ProcessId = m_OS.GetProcessID();
m_Dispatch = {0};
m_DispatchX[NULL] = {0};
m_OpenCLLibraryHandle = NULL;
m_LoggedCLInfo = false;
m_EnqueueCounter.store(0, std::memory_order::memory_order_relaxed);
m_EventsChromeTraced = 0;
m_ProgramNumber = 0;
m_KernelID = 0;
#if defined(USE_MDAPI)
m_pMDHelper = NULL;
#endif
m_QueueNumber = 0;
m_MemAllocNumber = 0;
m_AubCaptureStarted = false;
m_AubCaptureKernelEnqueueSkipCounter = 0;
m_AubCaptureKernelEnqueueCaptureCounter = 0;
#define CLI_CONTROL( _type, _name, _init, _desc ) m_Config . _name = _init;
#include "controls.h"
#undef CLI_CONTROL
#if defined(USE_ITT)
m_ITTInitialized = false;
m_ITTDomain = NULL;
//m_ITTQueuedState = NULL;
//m_ITTSubmittedState = NULL;
//m_ITTExecutingState = NULL;
//m_ITTQueueTrackGroup = NULL;
#endif
}
///////////////////////////////////////////////////////////////////////////////
//
CLIntercept::~CLIntercept()
{
stopAubCapture( NULL );
report();
std::lock_guard<std::mutex> lock(m_Mutex);
log( "CLIntercept is shutting down...\n" );
// Set the dispatch to the dummy dispatch. The destructor is called
// as the process is terminating. We don't know when each DLL gets
// unloaded, so it's not safe to call into any OpenCL functions in
// our destructor. Setting to the dummy dispatch ensures that no
// OpenCL functions get called. Note that this means we do potentially
// leave some events, kernels, or programs un-released, but since
// the process is terminating, that's probably OK.
m_Dispatch = {0};
#if defined(USE_MDAPI)
if( m_pMDHelper )
{
if( config().DevicePerfCounterTimeBasedSampling )
{
m_pMDHelper->CloseStream();
}
MetricsDiscovery::MDHelper::Delete( m_pMDHelper );
}
#endif
if( m_OpenCLLibraryHandle != NULL )
{
OS().UnloadLibrary( m_OpenCLLibraryHandle );
m_OpenCLLibraryHandle = NULL;
}
{
CContextCallbackInfoMap::iterator i = m_ContextCallbackInfoMap.begin();
while( i != m_ContextCallbackInfoMap.end() )
{
SContextCallbackInfo* pContextCallbackInfo = (*i).second;
if( pContextCallbackInfo )
{
delete pContextCallbackInfo;
}
(*i).second = NULL;
++i;
}
}
{
CPrecompiledKernelOverridesMap::iterator i = m_PrecompiledKernelOverridesMap.begin();
while( i != m_PrecompiledKernelOverridesMap.end() )
{
SPrecompiledKernelOverrides* pOverrides = (*i).second;
if( pOverrides )
{
// If we were able to release kernels or programs, we'd release
// the override kernels and program here.
delete pOverrides;
}
(*i).second = NULL;
++i;
}
}
{
CBuiltinKernelOverridesMap::iterator i = m_BuiltinKernelOverridesMap.begin();
while( i != m_BuiltinKernelOverridesMap.end() )
{
SBuiltinKernelOverrides* pOverrides = (*i).second;
if( pOverrides )
{
// If we were able to release kernels or programs, we'd release
// the override kernels and program here.
delete pOverrides;
}
(*i).second = NULL;
++i;
}
}
log( "... shutdown complete.\n" );
m_InterceptLog.close();
m_InterceptTrace.close();
}
///////////////////////////////////////////////////////////////////////////////
//
template <class T>
static bool GetControl(
const OS::Services& OS,
const char* name,
T& value )
{
unsigned int readValue = 0;
bool success = OS.GetControl( name, &readValue, sizeof(readValue) );
if( success )
{
value = readValue;
}
return success;
}
template <>
bool GetControl<bool>(
const OS::Services& OS,
const char* name,
bool& value )
{
unsigned int readValue = 0;
bool success = OS.GetControl( name, &readValue, sizeof(readValue) );
if( success )
{
value = ( readValue != 0 );
}
return success;
}
template <>
bool GetControl<std::string>(
const OS::Services& OS,
const char* name,
std::string& value )
{
char readValue[256] = "";
bool success = OS.GetControl( name, readValue, sizeof(readValue) );
if( success )
{
value = readValue;
}
return success;
}
template<class T>
static std::string GetNonDefaultString(
const char* name,
const T& value )
{
std::ostringstream ss;
ss << std::boolalpha;
ss << "Control " << name << " is set to non-default value: " << value << "\n";
return ss.str();
}
///////////////////////////////////////////////////////////////////////////////
//
bool CLIntercept::init()
{
std::lock_guard<std::mutex> lock(m_Mutex);
if( m_OS.Init() == false )
{
#ifdef __ANDROID__
__android_log_print(ANDROID_LOG_INFO, "clIntercept", "OS.Init FAILED!\n" );
#endif
return false;
}
#if defined(_WIN32)
OS::Services_Common::ENV_PREFIX = "CLI_";
OS::Services_Common::REGISTRY_KEY = "SOFTWARE\\INTEL\\IGFX\\CLINTERCEPT";
#elif defined(__linux__) || defined(__FreeBSD__) || defined(__APPLE__)
OS::Services_Common::ENV_PREFIX = "CLI_";
OS::Services_Common::CONFIG_FILE = "clintercept.conf";
OS::Services_Common::SYSTEM_DIR = "/etc/OpenCL";
#endif
bool breakOnLoad = false;
GetControl( m_OS, "BreakOnLoad", breakOnLoad );
if( breakOnLoad )
{
CLI_DEBUG_BREAK();
}
// A few control aliases, for backwards compatibility:
GetControl( m_OS, "DevicePerformanceTimeHashTracking",m_Config.KernelNameHashTracking );
GetControl( m_OS, "SimpleDumpProgram", m_Config.SimpleDumpProgramSource );
GetControl( m_OS, "DumpProgramsScript", m_Config.DumpProgramSourceScript );
GetControl( m_OS, "DumpProgramsInject", m_Config.DumpProgramSource );
GetControl( m_OS, "InjectPrograms", m_Config.InjectProgramSource );
GetControl( m_OS, "LogDir", m_Config.DumpDir );
std::string libName = "";
GetControl( m_OS, "DllName", libName ); // alias
GetControl( m_OS, "OpenCLFileName", libName );
#define CLI_CONTROL( _type, _name, _init, _desc ) GetControl( m_OS, #_name, m_Config . _name );
#include "controls.h"
#undef CLI_CONTROL
#if defined(_WIN32) || defined(__linux__) || defined(__FreeBSD__) || defined(__APPLE__)
if( !m_Config.DumpDir.empty() )
{
std::replace( m_Config.DumpDir.begin(), m_Config.DumpDir.end(), '\\', '/' );
OS::Services_Common::LOG_DIR = m_Config.DumpDir.c_str();
}
OS::Services_Common::APPEND_PID = m_Config.AppendPid;
#endif
if( m_Config.LogToFile )
{
std::string fileName = "";
OS().GetDumpDirectoryName( sc_DumpDirectoryName, fileName );
fileName += "/";
fileName += sc_LogFileName;
OS().MakeDumpDirectories( fileName );
if( m_Config.AppendFiles )
{
m_InterceptLog.open(
fileName.c_str(),
std::ios::out | std::ios::binary | std::ios::app );
}
else
{
m_InterceptLog.open(
fileName.c_str(),
std::ios::out | std::ios::binary );
}
}
if( m_Config.ChromeCallLogging ||
m_Config.ChromePerformanceTiming )
{
std::string fileName = "";
OS().GetDumpDirectoryName( sc_DumpDirectoryName, fileName );
fileName += "/";
fileName += sc_TraceFileName;
OS().MakeDumpDirectories( fileName );
m_InterceptTrace.open(
fileName.c_str(),
std::ios::out | std::ios::binary );
m_InterceptTrace << "[\n";
uint64_t threadId = OS().GetThreadID();
std::string processName = OS().GetProcessName();
m_InterceptTrace
<< "{\"ph\":\"M\", \"name\":\"process_name\", \"pid\":" << m_ProcessId
<< ", \"tid\":" << threadId
<< ", \"args\":{\"name\":\"" << processName
<< "\"}},\n";
//m_InterceptTrace
// << "{\"ph\":\"M\", \"name\":\"thread_name\", \"pid\":" << processId
// << ", \"tid\":" << threadId
// << ", \"args\":{\"name\":\"Host APIs\"}},\n";
}
std::string name = "";
OS().GetCLInterceptName( name );
std::string bits =
( sizeof(void*) == 8 ) ? "64-bit" :
( sizeof(void*) == 4 ) ? "32-bit" :
"XX-bit";
log( "-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n" );
log( "CLIntercept (" + bits + ") is loading...\n" );
log( "CLIntercept file location: " + name + "\n" );
log( "CLIntercept URL: " + std::string(sc_URL) + "\n" );
#if defined(CLINTERCEPT_CMAKE)
log( "CLIntercept git description: " + std::string(sc_GitDescribe) + "\n" );
log( "CLIntercept git refspec: " + std::string(sc_GitRefSpec) + "\n" );
log( "CLIntercept git hash: " + std::string(sc_GitHash) + "\n" );
#endif
log( "CLIntercept optional features:\n"
// extra code only needed for Windows
#if defined(CLINTERCEPT_CLILOADER) || !defined(_WIN32)
" cliloader(supported)\n"
" cliprof(supported)\n"
#else
" cliloader(NOT supported)\n"
" cliprof(NOT supported)\n"
#endif
#if defined(USE_KERNEL_OVERRIDES)
" kernel overrides(supported)\n"
#else
" kernel overrides(NOT supported)\n"
#endif
#if defined(USE_ITT)
" ITT tracing(supported)\n"
#else
" ITT tracing(NOT supported)\n"
#endif
#if defined(USE_MDAPI)
" MDAPI(supported)\n"
#else
" MDAPI(NOT supported)\n"
#endif
#if defined(USE_DEMANGLE)
" Demangling(supported)\n"
#else
" Demangling(NOT supported)\n"
#endif
#if defined(CLINTERCEPT_HIGH_RESOLUTON_CLOCK)
" clock(high_resolution_clock)\n"
#else
" clock(steady_clock)\n"
#endif
);
#if defined(_WIN32)
log( "CLIntercept environment variable prefix: " + std::string( OS::Services_Common::ENV_PREFIX ) + "\n" );
log( "CLIntercept registry key: " + std::string( OS::Services_Common::REGISTRY_KEY ) + "\n" );
#elif defined(__linux__) || defined(__FreeBSD__) || defined(__APPLE__)
log( "CLIntercept environment variable prefix: " + std::string( OS::Services_Common::ENV_PREFIX ) + "\n" );
log( "CLIntercept config file: " + std::string( OS::Services_Common::CONFIG_FILE ) + "\n" );
#endif
// Windows and Linux load the real OpenCL library and retrieve
// the OpenCL entry points from the real library dynamically.
#if defined(_WIN32) || defined(__linux__) || defined(__FreeBSD__)
if( libName != "" )
{
log( "Read OpenCL file name from user parameters: " + libName + "\n" );
log( "Trying to load dispatch from: " + libName + "\n" );
if( initDispatch( libName ) )
{
log( "... success!\n" );
}
}
else
{
#if defined(_WIN32)
char* windir = NULL;
size_t length = 0;
_dupenv_s( &windir, &length, "windir" );
// Try some common DLL names.
const std::string libNames[] =
{
"real_opencl.dll",
#if defined(WIN32)
std::string(windir) + "/syswow64/opencl.dll",
#endif
std::string(windir) + "/system32/opencl.dll",
};
free( windir );
#elif defined(__ANDROID__)
const std::string libNames[] =
{
"/system/vendor/lib/real_libOpenCL.so",
"real_libOpenCL.so",
};
#elif defined(__linux__) || defined(__FreeBSD__)
const std::string libNames[] =
{
"./real_libOpenCL.so",
#ifdef CLINTERCEPT_LIBRARY_ARCHITECTURE
"/usr/lib/" CLINTERCEPT_LIBRARY_ARCHITECTURE "/libOpenCL.so.1",
"/usr/lib/" CLINTERCEPT_LIBRARY_ARCHITECTURE "/libOpenCL.so",
#endif
"/usr/lib/libOpenCL.so.1",
"/usr/lib/libOpenCL.so",
"/usr/local/lib/libOpenCL.so.1",
"/usr/local/lib/libOpenCL.so",
"/opt/intel/opencl/lib64/libOpenCL.so.1",
"/opt/intel/opencl/lib64/libOpenCL.so",
"/glob/development-tools/oneapi/inteloneapi/compiler/latest/linux/lib/libOpenCL.so.1",
"/glob/development-tools/oneapi/inteloneapi/compiler/latest/linux/lib/libOpenCL.so",
};
#else
#error Unknown OS!
#endif
const int numNames = sizeof(libNames) / sizeof(libNames[0]);
int i = 0;
for( i = 0; i < numNames; i++ )
{
log( "Trying to load dispatch from: " + libNames[i] + "\n" );
if( initDispatch( libNames[i] ) )
{
log( "... success!\n" );
break;
}
}
}
#elif defined(__APPLE__)
if( initDispatch() )
{
log( "Dispatch table initialized.\n" );
}
#else
#error Unknown OS!
#endif
#define CLI_CONTROL( _type, _name, _init, _desc ) \
if ( m_Config . _name != _init ) { \
log( GetNonDefaultString( #_name, m_Config . _name ) ); \
}
#include "controls.h"
#undef CLI_CONTROL
#if defined(USE_MDAPI)
if( !m_Config.DevicePerfCounterCustom.empty() ||
!m_Config.DevicePerfCounterFile.empty() )
{
if( !m_Config.DevicePerfCounterEventBasedSampling &&
!m_Config.DevicePerfCounterTimeBasedSampling )
{
log("NOTE: Device Performance Counters are enabled without setting\n");
log(" DevicePerfCounterEventBasedSampling or DevicePerfCounterTimeBasedSampling.\n");
log(" Enabling DevicePerfCounterEventBasedSampling. This behavior may be changed\n");
log(" in a future version!\n");
m_Config.DevicePerfCounterEventBasedSampling = true;
}
if( m_Config.DevicePerfCounterEventBasedSampling &&
m_Config.DevicePerfCounterTimeBasedSampling )
{
log("NOTE: Both DevicePerfCounterEventBasedSampling and DevicePerfCounterTimeBasedSampling\n");
log(" are enabled, but simultaneous collection of both types of counters is not\n");
log(" currently supported. Disabling DevicePerfCounterTimeBasedSampling.\n");
m_Config.DevicePerfCounterTimeBasedSampling = false;
}
initCustomPerfCounters();
}
#endif
m_StartTime = clock::now();
log( "Timer Started!\n" );
if( m_Config.ChromeCallLogging ||
m_Config.ChromePerformanceTiming )
{
uint64_t threadId = OS().GetThreadID();
using us = std::chrono::microseconds;
uint64_t usStartTime =
std::chrono::duration_cast<us>(m_StartTime.time_since_epoch()).count();
m_InterceptTrace
<< "{\"ph\":\"M\", \"name\":\"clintercept_start_time\", \"pid\":" << m_ProcessId
<< ", \"tid\":" << threadId
<< ", \"args\":{\"start_time\":" << usStartTime
<< "}},\n";
}
log( "... loading complete.\n" );
return true;
}
///////////////////////////////////////////////////////////////////////////////
//
void CLIntercept::report()
{
std::lock_guard<std::mutex> lock(m_Mutex);
char filepath[MAX_PATH] = "";
#if defined(_WIN32)
if( config().DumpProgramSourceScript )
{
char dirname[MAX_PATH] = "";
char filename[MAX_PATH] = "";
size_t remaining = MAX_PATH;
char date[9] = "";
char time[9] = "";
char* curPos = NULL;
char* nextToken = NULL;
char* pch = NULL;
// Directory:
curPos = dirname;
remaining = MAX_PATH;
memset( curPos, 0, MAX_PATH );
_strdate_s( date, 9 );
_strtime_s( time, 9 );
memcpy_s( curPos, remaining, "CLShaderDump_", 14 );
curPos += 13;
remaining -= 13;
memcpy_s( curPos, remaining, strtok_s( date, "/", &nextToken ), 2 );
curPos += 2;
remaining -= 2;
memcpy_s( curPos, remaining, strtok_s( NULL, "/", &nextToken ), 2 );
curPos += 2;
remaining -= 2;
memcpy_s( curPos, remaining, strtok_s( NULL, "/", &nextToken ), 2 );
curPos += 2;
remaining -= 2;
::CreateDirectoryA( dirname, NULL );
// File:
curPos = filename;
remaining = MAX_PATH;
memset( curPos, 0, MAX_PATH );
if( GetModuleFileNameA( NULL, filename, MAX_PATH-1 ) == 0 )
{
CLI_ASSERT( 0 );
strcpy_s( curPos, remaining, "process.exe" );
}
pch = strrchr( filename, '\\' );
pch++;
memcpy_s( curPos, remaining, pch, strlen( pch ) );
curPos += strlen( pch ) - 4; // -4 to cut off ".exe"
remaining -= strlen( pch ) - 4;
memcpy_s( curPos, remaining, "_", 2 );
curPos += 1;
remaining -= 1;
memcpy_s( curPos, remaining, strtok_s( time, ":", &nextToken ), 2 );
curPos += 2;
remaining -= 2;
memcpy_s( curPos, remaining, strtok_s( NULL, ":", &nextToken ), 2 );
curPos += 2;
remaining -= 2;
memcpy_s( curPos, remaining, strtok_s( NULL, ":", &nextToken ), 2 );
curPos += 2;
remaining -= 2;
CLI_SPRINTF( curPos, remaining, "" );
curPos += 1;
remaining -= 1;
CLI_SPRINTF( filepath, MAX_PATH, "%s/%s.%s", dirname, filename, "log" );
}
else
#endif
{
std::string fileName = "";
OS().GetDumpDirectoryName( sc_DumpDirectoryName, fileName );
fileName += "/";
fileName += sc_ReportFileName;
OS().MakeDumpDirectories( fileName );
CLI_SPRINTF( filepath, MAX_PATH, "%s", fileName.c_str() );
}
// Report
if( m_Config.ReportToStderr )
{
writeReport( std::cerr );
}
if( m_Config.ReportToFile )
{
std::ofstream os;
if( m_Config.AppendFiles )
{
os.open(
filepath,
std::ios::out | std::ios::binary | std::ios::app );
}
else
{
os.open(
filepath,
std::ios::out | std::ios::binary );
}
if( os.good() )
{
writeReport( os );
os.close();
}
else
{
logf( "Failed to open report file for writing: %s\n", filepath );
}
}
}
///////////////////////////////////////////////////////////////////////////////
//
void CLIntercept::writeReport(
std::ostream& os )
{
if( config().FinishAfterEnqueue )
{
os << "*** WARNING *** FinishAfterEnqueue Enabled!" << std::endl << std::endl;
}
if( config().FlushAfterEnqueue )
{
os << "*** WARNING *** FlushAfterEnqueue Enabled!" << std::endl << std::endl;
}
if( config().NullEnqueue )
{
os << "*** WARNING *** NullEnqueue Enabled!" << std::endl << std::endl;
}
os << "Total Enqueues: " << m_EnqueueCounter.load(std::memory_order_relaxed) << std::endl << std::endl;
if( config().LeakChecking )
{
os << std::endl << "Leak Checking:" << std::endl;
m_ObjectTracker.writeReport( os );
}
if( !m_LongKernelNameMap.empty() )
{
os << std::endl << "Kernel name mapping:" << std::endl;
os << std::endl
<< std::right << std::setw(10) << "Short Name" << ", "
<< std::right << std::setw(1) << "Long Name" << std::endl;
CLongKernelNameMap::const_iterator i = m_LongKernelNameMap.begin();
while( i != m_LongKernelNameMap.end() )
{
os << std::right << std::setw(10) << i->second << ", "
<< std::right << std::setw(1) << i->first << std::endl;
++i;
}
}
if( config().HostPerformanceTiming &&
!m_HostTimingStatsMap.empty() )
{
os << std::endl << "Host Performance Timing Results:" << std::endl;
std::vector<std::string> keys;
keys.reserve(m_HostTimingStatsMap.size());
uint64_t totalTotalNS = 0;
size_t longestName = 32;
CHostTimingStatsMap::const_iterator i = m_HostTimingStatsMap.begin();
while( i != m_HostTimingStatsMap.end() )
{
const std::string& name = (*i).first;
const SHostTimingStats& hostTimingStats = (*i).second;
if( !name.empty() )
{
keys.push_back(name);
totalTotalNS += hostTimingStats.TotalNS;
longestName = std::max< size_t >( name.length(), longestName );
}
++i;
}
std::sort(keys.begin(), keys.end());
os << std::endl << "Total Time (ns): " << totalTotalNS << std::endl;
os << std::endl
<< std::right << std::setw(longestName) << "Function Name" << ", "
<< std::right << std::setw( 6) << "Calls" << ", "
<< std::right << std::setw(13) << "Time (ns)" << ", "
<< std::right << std::setw( 8) << "Time (%)" << ", "
<< std::right << std::setw(13) << "Average (ns)" << ", "
<< std::right << std::setw(13) << "Min (ns)" << ", "
<< std::right << std::setw(13) << "Max (ns)" << std::endl;
for( const auto& name : keys )
{
const SHostTimingStats& hostTimingStats = m_HostTimingStatsMap.at(name);
os << std::right << std::setw(longestName) << name << ", "
<< std::right << std::setw( 6) << hostTimingStats.NumberOfCalls << ", "
<< std::right << std::setw(13) << hostTimingStats.TotalNS << ", "
<< std::right << std::setw( 7) << std::fixed << std::setprecision(2) << hostTimingStats.TotalNS * 100.0f / totalTotalNS << "%, "
<< std::right << std::setw(13) << hostTimingStats.TotalNS / hostTimingStats.NumberOfCalls << ", "
<< std::right << std::setw(13) << hostTimingStats.MinNS << ", "
<< std::right << std::setw(13) << hostTimingStats.MaxNS << std::endl;
}
}
if( config().DevicePerformanceTiming &&
!m_DeviceTimingStatsMap.empty() )
{
CDeviceDeviceTimingStatsMap::const_iterator id = m_DeviceTimingStatsMap.begin();
while( id != m_DeviceTimingStatsMap.end() )
{
const cl_device_id device = (*id).first;
const CDeviceTimingStatsMap& dtsm = (*id).second;
const SDeviceInfo& deviceInfo = m_DeviceInfoMap[device];
os << std::endl << "Device Performance Timing Results for " << deviceInfo.NameForReport << ":" << std::endl;
std::vector<std::string> keys;
keys.reserve(dtsm.size());
cl_ulong totalTotalNS = 0;
size_t longestName = 32;
CDeviceTimingStatsMap::const_iterator i = dtsm.begin();
while( i != dtsm.end() )
{
const std::string& name = (*i).first;
const SDeviceTimingStats& deviceTimingStats = (*i).second;
if( !name.empty() )
{
keys.push_back(name);
totalTotalNS += deviceTimingStats.TotalNS;
longestName = std::max< size_t >( name.length(), longestName );
}
++i;
}
std::sort(keys.begin(), keys.end());
os << std::endl << "Total Time (ns): " << totalTotalNS << std::endl;
os << std::endl
<< std::right << std::setw(longestName) << "Function Name" << ", "
<< std::right << std::setw( 6) << "Calls" << ", "
<< std::right << std::setw(13) << "Time (ns)" << ", "
<< std::right << std::setw( 8) << "Time (%)" << ", "
<< std::right << std::setw(13) << "Average (ns)" << ", "
<< std::right << std::setw(13) << "Min (ns)" << ", "
<< std::right << std::setw(13) << "Max (ns)" << std::endl;
for( const auto& name : keys )
{
const SDeviceTimingStats& deviceTimingStats = dtsm.at(name);
os << std::right << std::setw(longestName) << name << ", "
<< std::right << std::setw( 6) << deviceTimingStats.NumberOfCalls << ", "
<< std::right << std::setw(13) << deviceTimingStats.TotalNS << ", "
<< std::right << std::setw( 7) << std::fixed << std::setprecision(2) << deviceTimingStats.TotalNS * 100.0f / totalTotalNS << "%, "
<< std::right << std::setw(13) << deviceTimingStats.TotalNS / deviceTimingStats.NumberOfCalls << ", "
<< std::right << std::setw(13) << deviceTimingStats.MinNS << ", "
<< std::right << std::setw(13) << deviceTimingStats.MaxNS << std::endl;
}
++id;
}
}
#if defined(USE_MDAPI)
if( config().DevicePerfCounterEventBasedSampling )
{
reportMDAPICounters( os );
}
#endif
}
///////////////////////////////////////////////////////////////////////////////
//
void CLIntercept::addShortKernelName(
const std::string& kernelName )
{
if( kernelName.length() > m_Config.LongKernelNameCutoff )
{
std::string shortKernelName("k_");
shortKernelName += std::to_string(m_KernelID);
m_LongKernelNameMap[ kernelName ] = shortKernelName;
logf( "Added kernel name mapping: %s to %s\n",
kernelName.c_str(),
shortKernelName.c_str() );
m_KernelID++;
}
}
///////////////////////////////////////////////////////////////////////////////
//
void CLIntercept::getCallLoggingPrefix(
std::string& str )
{
if( m_Config.CallLoggingElapsedTime )
{
using us = std::chrono::microseconds;
uint64_t usDelta =
std::chrono::duration_cast<us>(clock::now() - m_StartTime).count();
std::ostringstream ss;
ss << "Time: ";
ss << usDelta;
ss << " ";
str += ss.str();
}
if( m_Config.CallLoggingThreadId ||
m_Config.CallLoggingThreadNumber )
{
uint64_t threadId = OS().GetThreadID();
std::ostringstream ss;
if( m_Config.CallLoggingThreadId )
{
ss << "TID = ";
ss << threadId;
ss << " ";
}
if( m_Config.CallLoggingThreadNumber )