-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathMain.cpp
1987 lines (1656 loc) · 66.2 KB
/
Main.cpp
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) 2015 Advanced Micro Devices, Inc. All rights reserved.
/// \author AMD Developer Tools Team
/// \file
/// \brief This is the main command line application that will launch
/// all the agents.
//==============================================================================
#ifdef _WIN32
#include <windows.h>
#include "Interceptor.h"
#include <tchar.h>
#include <vector>
#include <string>
#else // LINUX
#include <sys/wait.h>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#endif
#include <iostream>
#include <iomanip>
#include <fstream>
#include <sstream>
#include <string>
#include <signal.h>
#include "ParseCmdLine.h"
#include "Analyze.h"
#include "OccupancyChart.h"
#include "OccupancyUtils.h"
#include "PerfMarkerAtpFile.h"
#include "CSVFileMerger.h"
#include <OSUtils.h>
#include <StringUtils.h>
#include <FileUtils.h>
#include <FileUtilsDefs.h>
#include <StackTraceAtpFile.h>
#include <Version.h>
#include <BinFileHeader.h>
#include <Logger.h>
#include "../CLTraceAgent/CLAtpFile.h"
#include "../HSAFdnTrace/HSAAtpFile.h"
#include "../CLOccupancyAgent/CLOccupancyFile.h"
#include <AMDTOSWrappers/Include/osDirectory.h>
#include <AMDTOSWrappers/Include/osFilePath.h>
#include <AMDTOSWrappers/Include/osEnvironmentVariable.h>
#include <AMDTOSWrappers/Include/osProcess.h>
#include <AMDTOSWrappers/Include/osFile.h>
#include <AMDTOSWrappers/Include/osOutOfMemoryHandling.h>
static Parameters params;
static Config config;
static osProcessId processId;
static gtString strTmpFilePath;
static bool bDoneMerging = false;
static void MergeFragFiles(int sig);
static void MergeTraceFile(int sig);
static void MergeOccupancyFile(int sig);
static bool SetAgent(const gtString& strDirPath);
#if defined (_LINUX) || defined (LINUX)
static bool SetPreLoadLibs();
#endif
static bool CheckIsAppValid(const gtString& strAppName, const int iProfilerNbrBits);
static int GetNbrAppBits(const gtString& strProfiler);
#ifdef _WIN32
typedef std::wstring EnvSysBlockString; ///< type of the system env block: std::wstring on Windows std::string on Linux
#define ENVBLOCKDELIMITER L'\0'
#define ENVVARSEPARATOR L'='
#elif defined (_LINUX) || defined (LINUX)
typedef std::string EnvSysBlockString; ///< type of the system env block: std::wstring on Windows std::string on Linux
#define ENVBLOCKDELIMITER '\0'
#define ENVVARSEPARATOR '='
#endif
/// Gets the environment block to be passed to the profiled program
/// \param mapUserBlock a map of the user-specified environment variables
/// \param bIncludeSystemEnv true if mapUserBlock should augment the system environment block, false if mapUserBlock should replace the system environment block
/// \return a string that can be passed to CreateProcess (or the Linux equivalent)
EnvSysBlockString GetEnvironmentBlock(EnvVarMap mapUserBlock, bool bIncludeSystemEnv);
static bool SetHSAServer(const gtString& strDirPath);
/// Set a maximum number of agents to be supported
const unsigned int MAX_NBR_AGENTS = 5;
///Constant strings
#define CL_AGENT_OCCUPANCY GPU_PROFILER_LIBRARY_NAME_PREFIX "CLOccupancyAgent"
#define CL_AGENT_TRACE GPU_PROFILER_LIBRARY_NAME_PREFIX "CLTraceAgent"
#define CL_AGENT_PERF_CTR GPU_PROFILER_LIBRARY_NAME_PREFIX "CLProfileAgent"
#define CL_AGENT_SUB_KRNL GPU_PROFILER_LIBRARY_NAME_PREFIX "CLSubKernelProfileAgent"
#define LOG_FILE_NAME "rcprof"
#define LOG_FILE_EXTENSION ".log"
#ifdef _WIN32
// print last error from the system
static bool PrintLastError(wchar_t* szPre)
{
wchar_t szError[1024];
DWORD dwError = GetLastError();
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,
NULL,
dwError,
0,
szError,
1024,
NULL);
std::cout << szPre << ": "
<< dwError << ": " << szError << std::endl;
return true;
}
static int CreateProcessWithDetour(gtString& strDirPath, gtString& strAppCommandLine, gtString& strAppWorkingDirectory, bool useDetours)
{
// set the detoured and microDLL server's path
std::string dirPathAsUTF8;
StringUtils::WideStringToUtf8String(strDirPath.asCharArray(), dirPathAsUTF8);
char szMicroDllPath[ MAX_PATH ];
SP_strcpy(szMicroDllPath, MAX_PATH, dirPathAsUTF8.c_str());
SP_strcat(szMicroDllPath, MAX_PATH, MICRO_DLL);
// Use Detours to launch the app and load our OpenCL server into the process
STARTUPINFO si;
memset(&si, 0, sizeof(si));
si.cb = sizeof(si);
PROCESS_INFORMATION pi;
memset(&pi, 0, sizeof(pi));
LPVOID pEnvBlock = NULL;
EnvSysBlockString strEnvBlock;
if (!config.mapEnvVars.empty())
{
strEnvBlock = GetEnvironmentBlock(config.mapEnvVars, !config.bFullEnvBlock);
if (!strEnvBlock.empty())
{
pEnvBlock = (LPVOID)strEnvBlock.c_str();
}
}
BOOL createProcRetVal = FALSE;
if (useDetours)
{
// Run the app with MicroDLL enabled
createProcRetVal = AMDT::CreateProcessAndInjectDllW(config.strInjectedApp.asCharArray(),
(LPWSTR)strAppCommandLine.asCharArray(),
NULL, NULL, TRUE,
CREATE_SUSPENDED | CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE | CREATE_UNICODE_ENVIRONMENT,
pEnvBlock,
strAppWorkingDirectory.asCharArray(),
&si,
&pi,
szMicroDllPath);
}
else
{
createProcRetVal = CreateProcess(config.strInjectedApp.asCharArray(),
(LPWSTR)strAppCommandLine.asCharArray(),
NULL, NULL, TRUE,
CREATE_SUSPENDED | CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE | CREATE_UNICODE_ENVIRONMENT,
pEnvBlock,
strAppWorkingDirectory.asCharArray(),
&si,
&pi);
}
if (!createProcRetVal)
{
PrintLastError(L"Failed to start application");
return -1;
}
// On Windows, always set processId > 0 so that we can do merging
processId = pi.dwProcessId;
// Resume thread and wait on the process..
if (ResumeThread(pi.hThread) == (DWORD) - 1)
{
PrintLastError(L"Failed to resume thread");
return -1;
}
WaitForSingleObject(pi.hProcess, INFINITE);
DWORD exitCode;
if (config.bTestMode && GetExitCodeProcess(pi.hProcess, &exitCode))
{
// if process returned an error code, return that error code from rcprof
if (exitCode != 0)
{
return exitCode;
}
}
return 0;
}
#endif
std::string GetExpectedOutputFile(const std::string& strOutputFileArg, const std::string& strReqdExtension)
{
std::string strExtension = FileUtils::GetFileExtension(strOutputFileArg);
std::string strProfileOutputFile("");
if (strExtension == strReqdExtension)
{
strProfileOutputFile = strOutputFileArg;
return strProfileOutputFile;
}
else
{
if ((strExtension == TRACE_EXT) ||
(strExtension == OCCUPANCY_EXT) ||
(strExtension == PERF_COUNTER_EXT))
{
strProfileOutputFile = FileUtils::GetBaseFileName(strOutputFileArg);
strProfileOutputFile += ".";
strProfileOutputFile += strReqdExtension;
return strProfileOutputFile;
}
else
{
strProfileOutputFile = strOutputFileArg + ".";
strProfileOutputFile += strReqdExtension;
return strProfileOutputFile;
}
}
}
void CheckOutputFile(const Config& configInner)
{
std::string strOutputFile("");
std::string strRequiredExt("");
if (configInner.bTrace || configInner.bHSATrace || configInner.bMergeMode)
{
strRequiredExt.assign(TRACE_EXT);
strOutputFile = GetExpectedOutputFile(configInner.strOutputFile, strRequiredExt);
if (FileUtils::FileExist(strOutputFile))
{
std::cout << "Session output path: " << strOutputFile << std::endl;
}
else
{
std::cout << "Failed to generate profile result " << strOutputFile << "." << std::endl;
}
}
if (configInner.bOccupancy && !configInner.bHSATrace)
{
strRequiredExt.assign(OCCUPANCY_EXT);
std::string occupancyFile = configInner.strOutputFile;
if ((configInner.bHSAPMC || configInner.bPerfCounter) && configInner.counterFileList.size() > 1)
{
size_t passStringPosition = config.strOutputFile.find("_pass");
if (passStringPosition != std::string::npos)
{
//Remove the appended "_pass"" string and the extension
occupancyFile = config.strOutputFile.substr(0, passStringPosition);
}
}
strOutputFile = GetExpectedOutputFile(occupancyFile, strRequiredExt);
if (FileUtils::FileExist(strOutputFile))
{
std::cout << "Session output path: " << strOutputFile << std::endl;
}
else
{
std::cout << "Failed to generate profile result " << strOutputFile << "." << std::endl;
}
}
if (configInner.bPerfCounter || configInner.bHSAPMC)
{
strRequiredExt.assign(PERF_COUNTER_EXT);
strOutputFile = GetExpectedOutputFile(configInner.strOutputFile, strRequiredExt);
if (FileUtils::FileExist(strOutputFile))
{
std::cout << "Session output path: " << strOutputFile << std::endl;
}
else
{
std::cout << "Failed to generate profile result " << strOutputFile << "." << std::endl;
}
}
}
int DisplayOccupancy(const std::string& strOutputFile)
{
int retVal = 0;
if (!config.strOccupancyParamsFile.empty())
{
OccupancyUtils::OccupancyParams paramsInner;
std::string occupancyError;
bool occupancyParamsRetrieved = false;
if (UNSPECIFIED_OCCUPANCY_INDEX == config.uiOccupancyIndex)
{
occupancyParamsRetrieved = OccupancyUtils::GetOccupancyParamsFromFile(config.strOccupancyParamsFile, paramsInner, occupancyError);
}
else
{
occupancyParamsRetrieved = OccupancyUtils::GetOccupancyParamsFromFile(config.strOccupancyParamsFile, config.uiOccupancyIndex, paramsInner, occupancyError);
}
//Generate HTML file
if (occupancyParamsRetrieved && GenerateOccupancyChart(paramsInner, strOutputFile, occupancyError))
{
retVal = 0;
}
else
{
std::cout << "Error generating occupancy display file." << std::endl << occupancyError << std::endl;
retVal = -1;
}
}
return retVal;
}
static const char* s_HSA_SOFTCP_ENV_VAR_NAME = "HSA_EMULATE_AQL"; ///< The SoftCP environment variable name
static const char* s_HSA_SOFTCP_ENV_VAR_VALUE = "1"; ///< The SoftCP environment variable value
bool SetHSASoftCPEnvVar(bool showMessage)
{
UNREFERENCED_PARAMETER(showMessage);
bool retVal = true;
#ifndef _WIN32
int result = setenv(s_HSA_SOFTCP_ENV_VAR_NAME, s_HSA_SOFTCP_ENV_VAR_VALUE, 1);
retVal = (0 == result);
if (showMessage)
{
if (!retVal)
{
std::cout << "Error: Unable to enable HSA Performance Counters in Driver\n";
}
else
{
std::cout << "Successfully enabled HSA Performance Counters in Driver\n";
}
}
#endif
return retVal;
}
bool UnsetHSASoftCPEnvVar(bool showMessage)
{
UNREFERENCED_PARAMETER(showMessage);
bool retVal = true;
#ifndef _WIN32
int result = unsetenv(s_HSA_SOFTCP_ENV_VAR_NAME);
retVal = (0 == result);
if (showMessage)
{
if (!retVal)
{
std::cout << "Error: Unable to disable HSA Performance Counters in Driver\n";
}
else
{
std::cout << "Successfully disabled HSA Performance Counters in Driver\n";
}
}
#endif
return retVal;
}
/// Sets the GPU Stable clock mode
/// \param mode the clock mode to use: 0 is default
void SetStableClocks(unsigned int mode)
{
if (!config.bNoStableClocks && config.bPerfCounter)
{
#ifdef _WIN32
const char* pStableClocksExe = "VkStableClocks" BITNESS ".exe";
std::stringstream args;
args << FileUtils::GetExePath().c_str() << "/" << pStableClocksExe << " " << mode;
PROCESSID pid = OSUtils::Instance()->ExecProcess(nullptr, args.str().c_str(), nullptr, nullptr, false, false);
#else
const char* pStableClocksExe = "VkStableClocks";
std::stringstream exe;
std::stringstream args;
exe << FileUtils::GetExePath().c_str() << "/" << pStableClocksExe;
args << mode;
PROCESSID pid = OSUtils::Instance()->ExecProcess(exe.str().c_str(), args.str().c_str(), nullptr, nullptr, false, false);
#endif
if (!OSUtils::Instance()->WaitForProcess(pid))
{
std::cout << "FAIL: error running: " << pStableClocksExe << std::endl;
}
}
}
int ProfileApplication(const std::string& strCounterFile, const int& profilerBits)
{
int retVal = 0;
std::string counterfile = strCounterFile;
if ((config.bTrace || config.bHSATrace) && config.bAnalyze && config.analyzeOps.strAtpFile.empty())
{
// use trace output as sanalyze module input
config.analyzeOps.strAtpFile = config.strOutputFile;
}
params.m_strOutputFile = config.strOutputFile;
params.m_strSessionName = config.strSessionName;
// Note: the following is a fix for CODEXL-50 -- use osDirectory to create the output directory
// if it does not already exist. Some of the code here can be removed when we move to
// use osFilePath/gtString in more places in the backend (i.e. like in all members in the
// "Config" sturcture declared in ParseCmdLine.h
gtString gtStringOutputFile;
gtStringOutputFile.fromUtf8String(params.m_strOutputFile.c_str());
osFilePath outputFilePath(gtStringOutputFile);
osDirectory outputDir;
outputFilePath.getFileDirectory(outputDir);
if (!outputDir.exists() && !outputDir.asFilePath().isEmpty())
{
outputDir.create();
}
// Note: end fix for CODEXL-50
//----------------------------------------
// Merge mode
//----------------------------------------
if (config.bMergeMode)
{
std::cout << "--- Merge Mode ---" << std::endl;
std::cout << "Temp files prefix (Process ID): " << config.uiPID << std::endl;
processId = config.uiPID;
if (config.strWorkingDirectory.isEmpty())
{
osFilePath tempPath;
tempPath.setPath(osFilePath::OS_CURRENT_DIRECTORY);
strTmpFilePath = tempPath.asString();
}
else
{
strTmpFilePath = config.strWorkingDirectory;
}
config.bTrace = true;
config.bHSATrace = true;
params.m_bTimeOutBasedOutput = true;
MergeFragFiles(1);
return 0;
}
//----------------------------------------
// Remove all tmp files
//----------------------------------------
FileUtils::RemoveFragFiles();
//----------------------------------------
// Get rcprof.exe's full path
//----------------------------------------
gtString strDirPath = FileUtils::GetExePathAsUnicode();
#if defined (_LINUX) || defined (LINUX)
{
//----------------------------------------
// Set replace tilde
//----------------------------------------
gtString retVal;
osGetCurrentProcessEnvVariableValue(L"HOME", retVal);
std::string strHomePath;
StringUtils::WideStringToUtf8String(retVal.asCharArray(), strHomePath);
FileUtils::ReplaceTilde(strHomePath, config.strOutputFile);
FileUtils::ReplaceTilde(strHomePath, counterfile);
// replace tilde using gtString
if (config.strInjectedApp[0] == '~')
{
config.strInjectedApp.extruct(0, 1);
gtString tempStr = config.strInjectedApp;
config.strInjectedApp = retVal;
config.strInjectedApp.appendFormattedString(L"%ls", tempStr.asCharArray());
}
// For linux, we need to check file existence before we fork
osFile fileToCheck(config.strInjectedApp);
if (!fileToCheck.exists())
{
std::cout << "Process failed to run. Make sure you have specified the correct path." << std::endl;
return -1;
}
}
#endif
bool bAnyAgentSet = false;
//----------------------------------------
// Set Agent
//----------------------------------------
if (config.bHSATrace || config.bHSAPMC)
{
bAnyAgentSet |= SetHSAServer(strDirPath);
}
bAnyAgentSet |= SetAgent(strDirPath);
if (!bAnyAgentSet)
{
if (!config.bAnalyzeOnly && !config.bMergeMode)
{
std::cout << "No profile mode specified. Nothing will be done." << std::endl;
}
return 1;
}
//----------------------------------------
// Pass params
//----------------------------------------
params.m_strCmdArgs = config.strInjectedAppArgs;
params.m_strWorkingDir = config.strWorkingDirectory;
params.m_strCounterFile = counterfile;
params.m_strKernelFile = config.strKernelFile;
params.m_strAPIFilterFile = config.strAPIFilterFile;
params.m_strDLLPath = strDirPath;
params.m_cOutputSeparator = config.cOutputSeparator;
params.m_bVerbose = config.bVerbose;
params.m_bPerfCounter = config.bPerfCounter;
params.m_bOutputIL = config.bOutputIL;
params.m_bOutputISA = config.bOutputISA;
params.m_bOutputCL = config.bOutputCL;
params.m_bOutputHSAIL = config.bOutputHSAIL;
params.m_bTrace = config.bTrace;
params.m_bTimeOutBasedOutput = config.bTimeOut;
params.m_uiTimeOutInterval = config.uiTimeOutInterval;
params.m_bTestMode = config.bTestMode;
params.m_bQueryRetStat = config.bQueryRetStat;
params.m_bCollapseClGetEventInfo = config.bCollapseClGetEventInfo;
params.m_bUserTimer = config.bUserTimer;
params.m_strTimerDLLFile = config.strTimerDLLFile;
params.m_strUserTimerFn = config.strUserTimerFn;
params.m_strUserTimerInitFn = config.strUserTimerInitFn;
params.m_strUserTimerDestroyFn = config.strUserTimerDestroyFn;
params.m_bStackTrace = config.bSym;
params.m_uiMaxNumOfAPICalls = config.uiMaxNumOfAPICalls;
params.m_uiMaxKernels = config.uiMaxKernels;
params.m_bKernelOccupancy = config.bOccupancy;
params.m_bUserPMC = config.bUserPMCSampler;
params.m_bCompatibilityMode = config.bCompatibilityMode;
params.m_strUserPMCLibPath = config.strUserPMCLibPath;
params.m_bHSATrace = config.bHSATrace;
params.m_bHSAPMC = config.bHSAPMC;
params.m_bGMTrace = config.bGMTrace;
params.m_mapEnvVars = config.mapEnvVars;
params.m_bFullEnvBlock = config.bFullEnvBlock;
params.m_bForceSinglePassPMC = config.bForceSinglePassPMC;
params.m_bGPUTimePMC = config.bGPUTimePMC;
params.m_bStartDisabled = config.bStartDisabled;
params.m_delayInMilliseconds = config.uiDelayInMilliseconds > 0 ? config.uiDelayInMilliseconds : 0;
params.m_bDelayStartEnabled = config.uiDelayInMilliseconds > 0;
params.m_durationInMilliseconds = config.uiDurationInMilliseconds > 0 ? config.uiDurationInMilliseconds : 0;
params.m_bProfilerDurationEnabled = config.uiDurationInMilliseconds > 0;
params.m_bForceSingleGPU = config.bForceSingleGPU;
params.m_uiForcedGpuIndex = config.uiForcedGpuIndex;
params.m_bAqlPacketTracing = config.bAqlPacketTracing;
params.m_bDisableKernelDemangling = config.bDisableKernelDemangling;
params.m_bNoHSATransferTime = config.bNoHSATransferTime;
#ifdef AMDT_INTERNAL
if ((params.m_bPerfCounter || params.m_bHSAPMC) && params.m_strCounterFile.empty())
{
std::cout << "A counter file must be specified when collecting perf counters in the internal build\n";
std::cout << "Use --counterfile (or -c) to specify a counter file\n";
return -1;
}
#endif
//for debugging
//cout << strDirPath << endl;
//cout << config.strInjectedApp << endl;
//cout << params.m_strOutputFile << endl;
FileUtils::PassParametersByFile(params);
//----------------------------------------
// Get App working dir
//----------------------------------------
gtString strAppWorkingDirectory;
if (config.strWorkingDirectory.isEmpty())
{
osFilePath injectedApp(config.strInjectedApp);
// remove file name and ext:
injectedApp.setFileName(L"");
injectedApp.setFileExtension(L"");
strAppWorkingDirectory = injectedApp.asString();
// FileUtils::GetWorkingDirectory(config.strInjectedApp, strAppWorkingDirectory);
}
else
{
strAppWorkingDirectory = config.strWorkingDirectory;
}
//----------------------------------------
// Set signal
//----------------------------------------
if (config.bTrace || config.bHSATrace || config.bOccupancy || config.bThreadTrace)
{
// set tmp file path
strTmpFilePath = FileUtils::GetTempFragFilePathAsUnicode();
signal(SIGABRT, MergeFragFiles);
signal(SIGTERM, MergeFragFiles);
signal(SIGINT, MergeFragFiles);
}
//----------------------------------------
// Create process
//----------------------------------------
//check that the application to be profiled is valid
if (!CheckIsAppValid(config.strInjectedApp, profilerBits))
{
std::wcout << config.strInjectedApp.asCharArray() << " is not a valid application" << std::endl;
return -1;
}
#ifdef _DEBUG
bool reportPerfCounterEnablement = true;
#else
bool reportPerfCounterEnablement = false;
#endif
if (config.bHSAPMC)
{
SetHSASoftCPEnvVar(reportPerfCounterEnablement);
}
#ifdef _WIN32
gtString strAppCommandLine;
strAppCommandLine.appendFormattedString(L"\"%ls\"", config.strInjectedApp.asCharArray());
// create a command line if the app argument list is not empty
// put arguments in quotes
if (!config.strInjectedAppArgs.isEmpty())
{
strAppCommandLine.appendFormattedString(L" %ls", config.strInjectedAppArgs.asCharArray());
}
int ret = CreateProcessWithDetour(strDirPath, strAppCommandLine, strAppWorkingDirectory, !config.bNoDetours);
if (ret != 0)
{
FileUtils::DeleteTmpFile();
return -1;
}
#else
if (!config.bNoStableClocks && config.bPerfCounter)
{
// For OpenCL perf counter collection on most Linux driver
// stacks, write access is required on a particular system
// file in order to set stable GPU clocks.
// This code checks if the system files are writeable and
// issues a message if not.
std::wstringstream wss;
gtString dpmBaseDir = L"/sys/class/drm/card";
gtString dpmRestOfPath = L"device";
gtString dpmFile = L"power_dpm_force_performance_level";
bool fileFound = true;
unsigned int cardIndex = 0;
while (fileFound)
{
wss.str(L"");
wss << dpmBaseDir.asCharArray() << cardIndex << L"/";
cardIndex++;
gtString baseDir = wss.str().c_str();;
osFilePath baseFilePath(baseDir);
if (baseFilePath.isDirectory())
{
baseFilePath.appendSubDirectory(dpmRestOfPath);
baseFilePath.setFileName(dpmFile);
if (baseFilePath.isRegularFile())
{
osFile sysFile;
// check if the file can be opened for writing
if (!sysFile.open(baseFilePath, osChannel::OS_ASCII_TEXT_CHANNEL, osFile::OS_OPEN_TO_WRITE))
{
// if not suggest to the user to either run as root or modify permissions on the file
std::cout << "\nInsufficient privileges. Either re-run as root or modify the permissions on\n"
<< baseFilePath.asString().asASCIICharArray() << std::endl
<< "to give the current user write access.\n\n";
return -1;
}
else
{
sysFile.close();
}
}
else
{
fileFound = false;
}
}
else
{
fileFound = false;
}
}
}
SetPreLoadLibs();
std::string strAppCommandLine;
// create a command line if the app argument list is not empty
// put arguments in quotes
size_t nCmdlineLength = 0;
if (!config.strInjectedAppArgs.isEmpty())
{
StringUtils::WideStringToUtf8String(config.strInjectedAppArgs.asCharArray(), strAppCommandLine);
nCmdlineLength = strAppCommandLine.length();
}
char* pszCmdline = new(std::nothrow) char[nCmdlineLength + 1];
if (pszCmdline == NULL)
{
std::cout << "Error processing command line\n";
return -1;
}
if (nCmdlineLength > 0)
{
strcpy(pszCmdline, strAppCommandLine.c_str());
}
else
{
pszCmdline[0] = '\0';
}
char szExe[SP_MAX_PATH] = { '\0' };
std::string convertedInjectApp;
StringUtils::WideStringToUtf8String(config.strInjectedApp.asCharArray(), convertedInjectApp);
strcpy(szExe, convertedInjectApp.c_str());
const char* pEnvBlock = NULL;
EnvSysBlockString strEnvBlock;
if (!config.mapEnvVars.empty())
{
strEnvBlock = GetEnvironmentBlock(config.mapEnvVars, !config.bFullEnvBlock);
if (!strEnvBlock.empty())
{
pEnvBlock = strEnvBlock.c_str();
}
}
std::string convertedWorkingDir;
StringUtils::WideStringToUtf8String(strAppWorkingDirectory.asCharArray(), convertedWorkingDir);
processId = OSUtils::Instance()->ExecProcess(szExe, pszCmdline, convertedWorkingDir.c_str(), pEnvBlock);
if (processId < 0)
{
// error
processId = 0;
std::cout << "error in fork()\n";
exit(1);
}
else if (processId > 0)
{
// parent code
int status;
waitpid(processId, &status, 0);
// if process returned an error, return that error code from rcprof
if (WIFEXITED(status) && WEXITSTATUS(status) != 0)
{
retVal = WEXITSTATUS(status);
}
// if process was terminated by a signal, return that signal number from rcprof
if (WIFSIGNALED(status) && WTERMSIG(status) != 0)
{
retVal = WTERMSIG(status);
}
}
delete[] pszCmdline;
#endif
// Work-around an OpenCL driver issue where it can leave the GPU
// in stable clock mode after collecting performance counters
SetStableClocks(0);
if (config.bHSAPMC)
{
UnsetHSASoftCPEnvVar(reportPerfCounterEnablement);
}
//----------------------------------------
// Unset agent before calling CLUtils to generate atp file header
//----------------------------------------
OSUtils::Instance()->UnsetEnvVar(OCL_ENABLE_PROFILING_ENV_VAR);
if (config.bHSATrace)
{
OSUtils::Instance()->UnsetEnvVar(HSA_ENABLE_PROFILING_ENV_VAR);
}
//----------------------------------------
// Merge result if needed
//----------------------------------------
MergeFragFiles(1);
CheckOutputFile(config);
return retVal;
}
int ProcessCommandLine(const std::string& strCounterFile)
{
int retVal = 0;
//If the occupancy switch is set, open the occupancy parameters file and parse
//Then, generate the HTML output.
if (config.bOccupancyDisplay)
{
if (!config.strOccupancyParamsFile.empty())
{
return DisplayOccupancy(config.strOutputFile);
}
}
if (!config.bAnalyzeOnly)
{
//Get the number of bits of the profiler
int iProfilerNbrBits = FileUtils::FILE_BITS_UNKNOWN;
gtString strProfiler = FileUtils::GetExeFullPathAsUnicode();
iProfilerNbrBits = GetNbrAppBits(strProfiler);
retVal = ProfileApplication(strCounterFile, iProfilerNbrBits);
}
//----------------------------------------
// Summary
//----------------------------------------
if (config.bAnalyze)
{
if (!APITraceAnalyze(config))
{
std::cout << "\nFailed to generate summary pages\n";
}
}
//----------------------------------------
// Cleanup
//----------------------------------------
FileUtils::DeleteTmpFile();
return retVal;
}
bool MergeKernelProfileOutputFiles(std::vector<std::string> counterFileList,
std::vector<std::string> outputFileList,
std::string defaultOutputFileName,
GPA_API_Type apiName,
bool includeTime)
{
bool isOutputFileExist = true;
for (std::vector<std::string>::iterator it = outputFileList.begin(); it != outputFileList.end(); ++it)
{
isOutputFileExist &= FileUtils::FileExist(*it);
}
if (!isOutputFileExist)
{
std::cout << "Profiling files are not generated. No Merging required.\n\n";
}
else
{
if (outputFileList.size() > 1 && counterFileList.size() > 1)
{
std::map<unsigned int, KernelRowData*> dataPerFile;
std::vector<CSVFileParser*> csvFileParsers;
// headers (or comments) in the csv file
std::vector<std::string> headers;
unsigned int count = 0;
// Load all the CSV files in Kernel Row Data
for (std::vector<std::string>::iterator it = outputFileList.begin(); it != outputFileList.end(); ++it)
{
CSVFileParser* csvParser = new(std::nothrow) CSVFileParser;
KernelRowData* rowData = new(std::nothrow) KernelRowData;
if (nullptr != csvParser && nullptr != rowData)
{
csvFileParsers.push_back(csvParser);
csvParser->AddListener(rowData);
if (csvParser->LoadFile(it->c_str()) && csvParser->Parse())
{
dataPerFile.insert(std::pair<unsigned int, KernelRowData*>(count, rowData));
count++;
}
// header will be same in all files - retreiving from 1st file
headers = csvParser->GetHeaders();
}
}
std::string collatedOutputFileName;
if (FileUtils::GetFileExtension(defaultOutputFileName).empty())
{
collatedOutputFileName = defaultOutputFileName + "." + PERF_COUNTER_EXT;
}
else
{
collatedOutputFileName = defaultOutputFileName;
}
CSVFileWriter mergedFileWriter(collatedOutputFileName);
std::map<std::string, std::vector<int>> counterColumns;
std::map<std::string, std::vector<int>>::iterator counterColumnsIterator;
std::vector<std::string> csvFileColumns;
std::string passString = "_pass_";
HeaderList headersWithFileIndex = KernelRowDataHelper::CreateHeader(counterFileList, apiName, includeTime);
HeaderList::iterator headersWithFileIndexIterator;
for (headersWithFileIndexIterator = headersWithFileIndex.begin(); headersWithFileIndexIterator != headersWithFileIndex.end(); ++headersWithFileIndexIterator)
{
csvFileColumns.push_back(StringUtils::Trim(headersWithFileIndexIterator->first));
}
for (std::vector<std::string>::const_iterator headerIter = headers.begin(); headerIter != headers.end(); ++headerIter)
{
mergedFileWriter.AddHeader(StringUtils::Trim(*headerIter));