-
Notifications
You must be signed in to change notification settings - Fork 480
/
Copy pathutils.cpp
1455 lines (1300 loc) · 44.4 KB
/
utils.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
// SPDX-License-Identifier: BSD-3-Clause
// Copyright (c) 2009-2022, Intel Corporation
// written by Andrey Semin and many others
#include <iostream>
#include <cassert>
#include <climits>
#include <algorithm>
#ifdef _MSC_VER
#include <windows.h>
#include <accctrl.h>
#include <aclapi.h>
#include <sddl.h>
#include <process.h>
#include <comdef.h>
#else
#include <sys/wait.h> // for waitpid()
#include <unistd.h> // for ::sleep
#endif
#include "utils.h"
#include "cpucounters.h"
#include <numeric>
#ifndef _MSC_VER
#include <execinfo.h>
extern char ** environ;
#endif
#ifdef __linux__
#include <glob.h>
#endif
namespace pcm {
bool startsWithPCM(const StringType& varName) {
const StringType prefix = PCM_STRING("PCM_");
return varName.compare(0, prefix.size(), prefix) == 0;
}
bool isInKeepList(const StringType& varName, const std::vector<StringType>& keepList) {
for (const auto& keepVar : keepList) {
if (varName == keepVar) {
return true;
}
}
return false;
}
#if defined(_MSC_VER)
void eraseEnvironmentVariables(const std::vector<std::wstring>& keepList) {
// Get a snapshot of the current environment block
LPWCH envBlock = GetEnvironmentStrings();
if (!envBlock) {
std::cerr << "Error getting environment strings." << std::endl;
return;
}
// Iterate over the environment block
for (LPWCH var = envBlock; *var != 0; var += std::wcslen(var) + 1) {
std::wstring varName(var);
size_t pos = varName.find('=');
if (pos != std::string::npos) {
varName = varName.substr(0, pos);
if (!startsWithPCM(varName) && !isInKeepList(varName, keepList)) {
SetEnvironmentVariable(varName.c_str(), NULL);
}
}
}
// Free the environment block
FreeEnvironmentStrings(envBlock);
}
#else
void eraseEnvironmentVariables(const std::vector<std::string>& keepList) {
std::vector<std::string> varsToDelete;
// Collect all the variables that need to be deleted
for (char **env = environ; *env != nullptr; ++env) {
std::string envEntry(*env);
size_t pos = envEntry.find('=');
if (pos != std::string::npos) {
std::string varName = envEntry.substr(0, pos);
if (!startsWithPCM(varName) && !isInKeepList(varName, keepList)) {
varsToDelete.push_back(varName);
}
}
}
// Delete the collected variables
for (const auto& varName : varsToDelete) {
unsetenv(varName.c_str());
}
}
#endif
void (*post_cleanup_callback)(void) = NULL;
//! \brief handler of exit() call
void exit_cleanup(void)
{
std::cout << std::flush;
restore_signal_handlers();
// this replaces same call in cleanup() from util.h
if (PCM::isInitialized()) PCM::getInstance()->cleanup(); // this replaces same call in cleanup() from util.h
//TODO: delete other shared objects.... if any.
if(post_cleanup_callback != NULL)
{
post_cleanup_callback();
}
}
bool colorEnabled = false;
void setColorEnabled(bool value)
{
colorEnabled = value;
}
const char * setColor (const char * colorStr)
{
return colorEnabled ? colorStr : "";
}
std::vector<const char *> colorTable = {
ASCII_GREEN,
ASCII_YELLOW,
ASCII_MAGENTA,
ASCII_CYAN,
ASCII_BRIGHT_GREEN,
ASCII_BRIGHT_YELLOW,
ASCII_BRIGHT_BLUE,
ASCII_BRIGHT_MAGENTA,
ASCII_BRIGHT_CYAN,
ASCII_BRIGHT_WHITE
};
size_t currentColor = 0;
const char * setNextColor()
{
const auto result = setColor(colorTable[currentColor++]);
if (currentColor == colorTable.size())
{
currentColor = 0;
}
return result;
}
const char * resetColor()
{
currentColor = 0;
return setColor(ASCII_RESET_COLOR);
}
void print_cpu_details()
{
const auto m = PCM::getInstance();
std::cerr << "\nDetected " << m->getCPUBrandString() << " \"Intel(r) microarchitecture codename " <<
m->getUArchCodename() << "\" stepping " << m->getCPUStepping();
const auto ucode_level = m->getCPUMicrocodeLevel();
if (ucode_level >= 0)
{
std::cerr << " microcode level 0x" << std::hex << ucode_level << std::dec;
}
std::cerr << "\n";
}
#ifdef __linux__
std::vector<std::string> findPathsFromPattern(const char* pattern)
{
std::vector<std::string> result;
glob_t glob_result;
memset(&glob_result, 0, sizeof(glob_result));
if (glob(pattern, GLOB_TILDE, nullptr, &glob_result) == 0)
{
for (size_t i = 0; i < glob_result.gl_pathc; ++i)
{
result.push_back(glob_result.gl_pathv[i]);
}
}
globfree(&glob_result);
return result;
};
#endif
#ifdef _MSC_VER
ThreadGroupTempAffinity::ThreadGroupTempAffinity(uint32 core_id, bool checkStatus, const bool restore_)
: restore(restore_)
{
GROUP_AFFINITY NewGroupAffinity;
SecureZeroMemory(&NewGroupAffinity, sizeof(GROUP_AFFINITY));
SecureZeroMemory(&PreviousGroupAffinity, sizeof(GROUP_AFFINITY));
DWORD currentGroupSize = 0;
while ((DWORD)core_id >= (currentGroupSize = GetActiveProcessorCount(NewGroupAffinity.Group)))
{
if (currentGroupSize == 0)
{
std::cerr << "ERROR: GetActiveProcessorCount for core " << core_id << " failed with error " << GetLastError() << "\n";
throw std::exception();
}
core_id -= (uint32)currentGroupSize;
++NewGroupAffinity.Group;
}
NewGroupAffinity.Mask = 1ULL << core_id;
if (GetThreadGroupAffinity(GetCurrentThread(), &PreviousGroupAffinity)
&& (std::memcmp(&NewGroupAffinity, &PreviousGroupAffinity, sizeof(GROUP_AFFINITY)) == 0))
{
restore = false;
return;
}
const auto res = SetThreadGroupAffinity(GetCurrentThread(), &NewGroupAffinity, &PreviousGroupAffinity);
if (res == FALSE && checkStatus)
{
std::cerr << "ERROR: SetThreadGroupAffinity for core " << core_id << " failed with error " << GetLastError() << "\n";
throw std::exception();
}
}
ThreadGroupTempAffinity::~ThreadGroupTempAffinity()
{
if (restore) SetThreadGroupAffinity(GetCurrentThread(), &PreviousGroupAffinity, NULL);
}
LONG unhandled_exception_handler(LPEXCEPTION_POINTERS p)
{
std::cerr << "DEBUG: Unhandled Exception event\n";
exit(EXIT_FAILURE);
}
/**
* \brief version of interrupt handled for Windows
*/
BOOL sigINT_handler(DWORD fdwCtrlType)
{
// output for DEBUG only
std::cerr << "DEBUG: caught signal to interrupt: ";
switch (fdwCtrlType)
{
// Handle the CTRL-C signal.
case CTRL_C_EVENT:
std::cerr << "Ctrl-C event\n";
break;
// CTRL-CLOSE: confirm that the user wants to exit.
case CTRL_CLOSE_EVENT:
std::cerr << "Ctrl-Close event\n";
break;
// Pass other signals to the next handler.
case CTRL_BREAK_EVENT:
std::cerr << "Ctrl-Break event\n";
break;
case CTRL_LOGOFF_EVENT:
std::cerr << "Ctrl-Logoff event\n";
break;
case CTRL_SHUTDOWN_EVENT:
std::cerr << "Ctrl-Shutdown event\n";
break;
default:
std::cerr << "Unknown event\n";
break;
}
// TODO: dump summary, if needed
// in case PCM is blocked just return and summary will be dumped in
// calling function, if needed
if (PCM::isInitialized() && PCM::getInstance()->isBlocked()) {
return FALSE;
} else {
exit_cleanup();
_exit(EXIT_SUCCESS);
return FALSE; // to prevent Warning
}
}
/**
* \brief started in a separate thread and blocks waiting for child application to exit.
* After child app exits: -> print Child's termination status and terminates PCM
*/
void waitForChild(void * proc_id)
{
intptr_t procHandle = (intptr_t)proc_id;
int termstat;
_cwait(&termstat, procHandle, _WAIT_CHILD);
std::cerr << "Program exited with status " << termstat << "\n";
exit(EXIT_SUCCESS);
}
#else
/**
* \brief handles signals that lead to termination of the program
* such as SIGINT, SIGQUIT, SIGABRT, SIGSEGV, SIGTERM, SIGCHLD
* this function specifically works when the client application launched
* by pcm -- terminates
*/
void sigINT_handler(int signum)
{
// output for DEBUG only
std::cerr << "DEBUG: caught signal to interrupt (" << strsignal(signum) << ").\n";
// TODO: dump summary, if needed
// in case PCM is blocked just return and summary will be dumped in
// calling function, if needed
if (PCM::isInitialized() && PCM::getInstance()->isBlocked()) {
return;
} else {
exit_cleanup();
if (signum == SIGABRT || signum == SIGSEGV)
{
_exit(EXIT_FAILURE);
}
else
{
_exit(EXIT_SUCCESS);
}
}
}
/**
* \brief handles SIGSEGV signals that lead to termination of the program
* this function specifically works when the client application launched
* by pcm -- terminates
*/
constexpr auto BACKTRACE_MAX_STACK_FRAME = 30;
void sigSEGV_handler(int signum)
{
void *backtrace_buffer[BACKTRACE_MAX_STACK_FRAME] = {0};
char **backtrace_strings = NULL;
size_t backtrace_size = 0;
backtrace_size = backtrace(backtrace_buffer, BACKTRACE_MAX_STACK_FRAME);
backtrace_strings = backtrace_symbols(backtrace_buffer, backtrace_size);
if (backtrace_strings == NULL)
{
std::cerr << "Debug: backtrace empty. \n";
}
else
{
std::cerr << "Debug: backtrace dump(" << backtrace_size << " stack frames).\n";
for (size_t i = 0; i < backtrace_size; i++)
{
std::cerr << backtrace_strings[i] << "\n";
}
freeAndNullify(backtrace_strings);
}
sigINT_handler(signum);
}
/**
* \brief handles signals that lead to restart the application
* such as SIGHUP.
* for example to re-read environment variables controlling PCM execution
*/
void sigHUP_handler(int /*signum*/)
{
// output for DEBUG only
std::cerr << "DEBUG: caught signal to hangup. Reloading configuration and continue...\n";
// TODO: restart; so far do nothing
return; // continue program execution
}
/**
* \brief handles signals that lead to update of configuration
* such as SIGUSR1 and SIGUSR2.
* for the future extensions
*/
void sigUSR_handler(int /*signum*/)
{
std::cerr << "DEBUG: caught USR signal. Continue.\n";
// TODO: reload configurationa, reset accumulative counters;
return;
}
/**
* \brief handles signals that lead to update of configuration
* such as SIGSTOP, SIGTSTP, SIGTTIN, SIGTTOU
*/
void sigSTOP_handler(int /*signum*/)
{
PCM * m = PCM::getInstance();
int runState = m->getRunState();
std::string state = (runState == 1 ? "suspend" : "continue");
std::cerr << "DEBUG: caught signal to " << state << " execution.\n"; // debug of signals only
if (runState == 1) {
// stop counters and sleep... almost forever;
m->setRunState(0);
sleep(INT_MAX);
} else {
// resume
m->setRunState(1);
alarm(1);
}
return;
}
/**
* \brief handles signals that lead to update of configuration
* such as SIGCONT
*/
void sigCONT_handler(int /*signum*/)
{
std::cout << "DEBUG: caught signal to continue execution.\n"; // debug of signals only
// TODO: clear counters, resume counting.
return;
}
#endif // ifdef _MSC_VER
//! \brief install various handlers for system signals
void set_signal_handlers(void)
{
if (atexit(exit_cleanup) != 0)
{
std::cerr << "ERROR: Failed to install exit handler.\n";
return;
}
#ifdef _MSC_VER
BOOL handlerStatus;
// Increase the priority a bit to improve context switching delays on Windows
SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
// to fix Cygwin/BASH setting Ctrl+C handler need first to restore the default one
handlerStatus = SetConsoleCtrlHandler(NULL, FALSE); // restores normal processing of CTRL+C input
if (handlerStatus == 0) {
tcerr << "Failed to set Ctrl+C handler. Error code: " << GetLastError() << " ";
const TCHAR * errorStr = _com_error(GetLastError()).ErrorMessage();
if (errorStr) tcerr << errorStr;
tcerr << "\n";
_exit(EXIT_FAILURE);
}
handlerStatus = SetConsoleCtrlHandler((PHANDLER_ROUTINE)sigINT_handler, TRUE);
if (handlerStatus == 0) {
tcerr << "Failed to set Ctrl+C handler. Error code: " << GetLastError() << " ";
const TCHAR * errorStr = _com_error(GetLastError()).ErrorMessage();
if (errorStr) tcerr << errorStr;
tcerr << "\n";
_exit(EXIT_FAILURE);
}
SetUnhandledExceptionFilter((LPTOP_LEVEL_EXCEPTION_FILTER)&unhandled_exception_handler);
char *envPath;
if (_dupenv_s(&envPath, NULL, "_"))
{
std::cerr << "\nPCM ERROR: _dupenv_s failed.\n";
_exit(EXIT_FAILURE);
}
if (envPath)
{
std::cerr << "\nPCM ERROR: Detected cygwin/mingw environment which does not allow to setup PMU clean-up handlers on Ctrl-C and other termination signals.\n";
std::cerr << "See https://www.mail-archive.com/[email protected]/msg74817.html\n";
std::cerr << "As a workaround please run pcm directly from a native windows shell (e.g. cmd).\n";
std::cerr << "Exiting...\n\n";
freeAndNullify(envPath);
_exit(EXIT_FAILURE);
}
freeAndNullify(envPath);
std::cerr << "DEBUG: Setting Ctrl+C done.\n";
#else
struct sigaction saINT, saHUP, saUSR, saSTOP, saCONT;
// install handlers that interrupt execution
saINT.sa_handler = sigINT_handler;
sigemptyset(&saINT.sa_mask);
saINT.sa_flags = SA_RESTART;
sigaction(SIGINT, &saINT, NULL);
sigaction(SIGQUIT, &saINT, NULL);
sigaction(SIGABRT, &saINT, NULL);
sigaction(SIGTERM, &saINT, NULL);
saINT.sa_flags = SA_RESTART | SA_NOCLDSTOP;
sigaction(SIGCHLD, &saINT, NULL); // get there is our child exits. do nothing if it stopped/continued
saINT.sa_handler = sigSEGV_handler;
sigemptyset(&saINT.sa_mask);
saINT.sa_flags = SA_RESTART;
sigaction(SIGSEGV, &saINT, NULL);
// install SIGHUP handler to restart
saHUP.sa_handler = sigHUP_handler;
sigemptyset(&saHUP.sa_mask);
saHUP.sa_flags = SA_RESTART;
sigaction(SIGHUP, &saHUP, NULL);
// install SIGHUP handler to restart
saUSR.sa_handler = sigUSR_handler;
sigemptyset(&saUSR.sa_mask);
saUSR.sa_flags = SA_RESTART;
sigaction(SIGUSR1, &saUSR, NULL);
sigaction(SIGUSR2, &saUSR, NULL);
// install SIGSTOP handler: pause/resume
saSTOP.sa_handler = sigSTOP_handler;
sigemptyset(&saSTOP.sa_mask);
saSTOP.sa_flags = SA_RESTART;
sigaction(SIGSTOP, &saSTOP, NULL);
sigaction(SIGTSTP, &saSTOP, NULL);
sigaction(SIGTTIN, &saSTOP, NULL);
sigaction(SIGTTOU, &saSTOP, NULL);
// install SIGCONT & SIGALRM handler
saCONT.sa_handler = sigCONT_handler;
sigemptyset(&saCONT.sa_mask);
saCONT.sa_flags = SA_RESTART;
sigaction(SIGCONT, &saCONT, NULL);
sigaction(SIGALRM, &saCONT, NULL);
#endif
return;
}
//! \brief Restores default signal handlers under Linux/UNIX
void restore_signal_handlers(void)
{
#ifndef _MSC_VER
struct sigaction action;
action.sa_handler = SIG_DFL;
action.sa_flags = 0;
sigemptyset(&action.sa_mask);
sigaction(SIGINT, &action, NULL);
sigaction(SIGQUIT, &action, NULL);
sigaction(SIGABRT, &action, NULL);
sigaction(SIGTERM, &action, NULL);
sigaction(SIGSEGV, &action, NULL);
sigaction(SIGCHLD, &action, NULL);
// restore SIGHUP handler to restart
sigaction(SIGHUP, &action, NULL);
// restore SIGHUP handler to restart
sigaction(SIGUSR1, &action, NULL);
sigaction(SIGUSR2, &action, NULL);
// restore SIGSTOP handler: pause/resume
// sigaction(SIGSTOP, &action, NULL); // cannot catch this
// handle SUSP character: normally C-z)
sigaction(SIGTSTP, &action, NULL);
sigaction(SIGTTIN, &action, NULL);
sigaction(SIGTTOU, &action, NULL);
// restore SIGCONT & SIGALRM handler
sigaction(SIGCONT, &action, NULL);
sigaction(SIGALRM, &action, NULL);
#endif
return;
}
void set_real_time_priority(const bool & silent)
{
if (!silent)
{
std::cerr << "Setting real time priority for the process\n";
}
#ifdef _MSC_VER
if (!SetPriorityClass(GetCurrentProcess(), REALTIME_PRIORITY_CLASS))
{
std::cerr << "ERROR: SetPriorityClass with REALTIME_PRIORITY_CLASS failed with error " << GetLastError() << "\n";
}
if (!SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL))
{
std::cerr << "ERROR: SetThreadPriority with THREAD_PRIORITY_TIME_CRITICAL failed with error " << GetLastError() << "\n";
}
#elif __linux__
const auto priority = sched_get_priority_max(SCHED_RR);
if (priority == -1)
{
std::cerr << "ERROR: Could not get SCHED_RR max priority: " << strerror(errno) << "\n";
}
else
{
struct sched_param sp = { .sched_priority = priority };
if (sched_setscheduler(0, SCHED_RR, &sp) == -1)
{
const auto errnosave = errno;
std::cerr << "ERROR: Could not set scheduler to realtime! Errno: " << errnosave << " Error message: \"" << strerror(errnosave) << "\"\n";
}
else
{
if (!silent)
{
std::cerr << "Scheduler changed to SCHED_RR and priority to " << priority << "\n";
}
}
}
#else
std::cerr << "Setting real time priority for the process not implemented on your OS.\n";
#endif
}
void set_post_cleanup_callback(void(*cb)(void))
{
post_cleanup_callback = cb;
}
//!\brief launches external program in a separate process
void MySystem(char * sysCmd, char ** sysArgv)
{
if (sysCmd == NULL) {
assert("No program provided. NULL pointer");
exit(EXIT_FAILURE);
}
std::cerr << "\nExecuting \"";
std::cerr << sysCmd;
std::cerr << "\" command:\n";
#ifdef _MSC_VER
intptr_t ret;
char cbuf[128];
if (PCM::getInstance()->isBlocked()) { // synchronous start: wait for child process completion
// in case PCM should be blocked waiting for the child application to end
// 1. returns and ret = -1 in case of error creating process is encountered
// 2.
ret = _spawnvp(_P_WAIT, sysCmd, sysArgv);
if (ret == -1) { // process creation failed.
strerror_s(cbuf, 128, errno);
std::cerr << "Failed to start program \"" << sysCmd << "\". " << cbuf << "\n";
exit(EXIT_FAILURE);
} else { // process created, worked, and completed with exist code in ret. ret=0 -> Success
std::cerr << "Program exited with status " << ret << "\n";
}
} else { // async start: PCM works in parallel with the child process, and exits when
ret = _spawnvp(_P_NOWAIT, sysCmd, sysArgv);
if (ret == -1) {
strerror_s(cbuf, 128, errno);
std::cerr << "Failed to start program \"" << sysCmd << "\". " << cbuf << "\n";
exit(EXIT_FAILURE);
} else { // ret here is the new process handle.
// start new thread which will wait for child completion, and continue PCM's execution
if (_beginthread(waitForChild, 0, (void *)ret) == -1L) {
strerror_s(cbuf, 128, errno);
std::cerr << "WARNING: Failed to set waitForChild. PCM will continue infinitely: finish it manually! " << cbuf << "\n";
}
}
}
#else
pid_t child_pid = fork();
if (child_pid == 0) {
execvp(sysCmd, sysArgv);
std::cerr << "Failed to start program \"" << sysCmd << "\"\n";
exit(EXIT_FAILURE);
}
else
{
if (PCM::getInstance()->isBlocked()) {
int res;
waitpid(child_pid, &res, 0);
std::cerr << "Program " << sysCmd << " launched with PID: " << std::dec << child_pid << "\n";
if (WIFEXITED(res)) {
std::cerr << "Program exited with status " << WEXITSTATUS(res) << "\n";
}
else if (WIFSIGNALED(res)) {
std::cerr << "Process " << child_pid << " was terminated with status " << WTERMSIG(res) << "\n";
}
}
}
#endif
}
#ifdef _MSC_VER
#define HORIZONTAL char(196)
#define VERTICAL char(179)
#define DOWN_AND_RIGHT char(218)
#define DOWN_AND_LEFT char(191)
#define UP_AND_RIGHT char(192)
#define UP_AND_LEFT char(217)
#else
#define HORIZONTAL u8"\u2500"
#define VERTICAL u8"\u2502"
#define DOWN_AND_RIGHT u8"\u250C"
#define DOWN_AND_LEFT u8"\u2510"
#define UP_AND_RIGHT u8"\u2514"
#define UP_AND_LEFT u8"\u2518"
#endif
template <class T>
void drawBar(const int nempty, const T & first, const int width, const T & last)
{
for (int c = 0; c < nempty; ++c)
{
std::cout << ' ';
}
std::cout << first;
for (int c = 0; c < width; ++c)
{
std::cout << HORIZONTAL;
}
std::cout << last << '\n';
}
void drawStackedBar(const std::string & label, std::vector<StackedBarItem> & h, const int width)
{
int real_width = 0;
auto scale = [&width](double fraction)
{
return int(round(fraction * double(width)));
};
for (const auto & i : h)
{
real_width += scale(i.fraction);
}
if (real_width > 2*width)
{
std::cout << "ERROR: sum of fractions > 2 ("<< real_width << " > " << width << ")\n";
return;
}
drawBar((int)label.length(), DOWN_AND_RIGHT, real_width, DOWN_AND_LEFT);
std::cout << label << VERTICAL;
for (const auto & i : h)
{
const int c_width = scale(i.fraction);
for (int c = 0; c < c_width; ++c)
{
std::cout << i.fill;
}
}
std::cout << VERTICAL << "\n";
drawBar((int)label.length(), UP_AND_RIGHT, real_width, UP_AND_LEFT);
}
bool CheckAndForceRTMAbortMode(const char * arg, PCM * m)
{
if (check_argument_equals(arg, {"-force-rtm-abort-mode"}))
{
if (nullptr == m)
{
m = PCM::getInstance();
assert(m);
}
m->enableForceRTMAbortMode();
return true;
}
return false;
}
std::vector<std::string> split(const std::string & str, const char delim)
{
std::string token;
std::vector<std::string> result;
std::istringstream strstr(str);
while (std::getline(strstr, token, delim))
{
result.push_back(token);
}
return result;
}
uint64 read_number(const char* str)
{
std::istringstream stream(str);
if (strstr(str, "x")) stream >> std::hex;
uint64 result = 0;
stream >> result;
return result;
}
// emulates scanf %i for hex 0x prefix otherwise assumes dec (no oct support)
bool match(const std::string& subtoken, const std::string& sname, uint64* result)
{
if (pcm_sscanf(subtoken) >> s_expect(sname + "0x") >> std::hex >> *result)
return true;
if (pcm_sscanf(subtoken) >> s_expect(sname) >> std::dec >> *result)
return true;
return false;
}
#define PCM_CALIBRATION_INTERVAL 50 // calibrate clock only every 50th iteration
int calibratedSleep(const double delay, const char* sysCmd, const MainLoop& mainLoop, PCM* m)
{
static uint64 TimeAfterSleep = 0;
int delay_ms = int(delay * 1000);
if (TimeAfterSleep) delay_ms -= (int)(m->getTickCount() - TimeAfterSleep);
if (delay_ms < 0) delay_ms = 0;
if (sysCmd == NULL || mainLoop.getNumberOfIterations() != 0 || m->isBlocked() == false)
{
if (delay_ms > 0)
{
// std::cerr << "DEBUG: sleeping for " << std::dec << delay_ms << " ms...\n";
MySleepMs(delay_ms);
}
}
TimeAfterSleep = m->getTickCount();
return delay_ms;
};
void print_help_force_rtm_abort_mode(const int alignment, const char * separator)
{
const auto m = PCM::getInstance();
if (m->isForceRTMAbortModeAvailable() && (m->getMaxCustomCoreEvents() < 4))
{
std::cout << " -force-rtm-abort-mode";
for (int i = 0; i < (alignment - 23); ++i)
{
std::cout << " ";
}
assert(separator);
std::cout << separator << " force RTM transaction abort mode to enable more programmable counters\n";
}
}
#ifdef _MSC_VER
std::string safe_getenv(const char* env)
{
char * buffer;
std::string result;
if (_dupenv_s(&buffer, NULL, env) == 0 && buffer != nullptr)
{
result = buffer;
freeAndNullify(buffer);
}
return result;
}
#else
std::string safe_getenv(const char* env)
{
const auto getenvResult = std::getenv(env);
return getenvResult ? std::string(getenvResult) : std::string("");
}
#endif
void print_pid_collection_message(int pid)
{
if (pid != -1)
{
std::cerr << "Collecting core metrics for process ID " << std::dec << pid << "\n";
}
}
double parse_delay(const char *arg, const std::string& progname, print_usage_func print_usage_func)
{
// any other options positional that is a floating point number is treated as <delay>,
// while the other options are ignored with a warning issues to stderr
double delay_input = 0.0;
std::istringstream is_str_stream(arg);
is_str_stream >> std::noskipws >> delay_input;
if(is_str_stream.eof() && !is_str_stream.fail())
{
if (delay_input < 0)
{
std::cerr << "Invalid delay specified: \"" << *arg << "\". Delay should be positive.\n";
if(print_usage_func)
{
print_usage_func(progname);
}
exit(EXIT_FAILURE);
}
return delay_input;
}
else
{
std::cerr << "WARNING: unknown command-line option: \"" << *arg << "\". Ignoring it.\n";
if(print_usage_func)
{
print_usage_func(progname);
}
exit(EXIT_FAILURE);
}
}
std::list<int> extract_integer_list(const char *optarg){
const char *pstr = optarg;
std::list<int> corelist;
std::string snum1, snum2;
std::string *pnow = &snum1;
char nchar = ',';
while(*pstr != '\0' || nchar != ','){
nchar = ',';
if (*pstr != '\0'){
nchar = *pstr;
pstr++;
}
//printf("c=%c\n",nchar);
if (nchar=='-' && pnow == &snum1 && snum1.size()>0){
pnow = &snum2;
}else if (nchar == ','){
if (!snum1.empty() && !snum2.empty()){
int num1 = atoi(snum1.c_str()), num2 =atoi(snum2.c_str());
if (num2 < num1) std::swap(num1,num2);
if (num1 < 0) num1 = 0;
for (int ix=num1; ix <= num2; ix++){
corelist.push_back(ix);
}
}else if (!snum1.empty()){
int num1 = atoi(snum1.c_str());
corelist.push_back(num1);
}
snum1.clear();
snum2.clear();
pnow = &snum1;
}else if (nchar != ' '){
pnow->push_back(nchar);
}
}
return(corelist);
}
bool extract_argument_value(const char* arg, std::initializer_list<const char*> arg_names, std::string& value)
{
const auto arg_len = strlen(arg);
for (const auto& arg_name: arg_names) {
const auto arg_name_len = strlen(arg_name);
if (arg_len > arg_name_len && strncmp(arg, arg_name, arg_name_len) == 0 && arg[arg_name_len] == '=') {
value = arg + arg_name_len + 1;
const auto last_pos = value.find_last_not_of("\"");
if (last_pos != std::string::npos) {
value.erase(last_pos + 1);
}
const auto first_pos = value.find_first_not_of("\"");
if (first_pos != std::string::npos) {
value.erase(0, first_pos);
}
return true;
}
}
return false;
}
bool check_argument_equals(const char* arg, std::initializer_list<const char*> arg_names)
{
const auto arg_len = strlen(arg);
for (const auto& arg_name: arg_names) {
if (arg_len == strlen(arg_name) && strncmp(arg, arg_name, arg_len) == 0) {
return true;
}
}
return false;
}
void check_and_set_silent(int argc, char * argv[], null_stream &nullStream2)
{
if (argc > 1) do
{
argv++;
argc--;
if (check_argument_equals(*argv, {"--help", "-h", "/h"}) ||
check_argument_equals(*argv, {"-silent", "/silent"}))
{
std::cerr.rdbuf(&nullStream2);
return;
}
} while (argc > 1);
}
bool check_for_injections(const std::string & str)
{
const std::array<char, 4> symbols = {'=', '+', '-', '@'};
if (std::find(std::begin(symbols), std::end(symbols), str[0]) != std::end(symbols)) {
std::cerr << "ERROR: First letter in event name: " << str << " cannot be \"" << str[0] << "\" , please use escape \"\\\" or remove it\n";
return true;
}
return false;
}
void print_enforce_flush_option_help()
{
std::cout << " -f | /f => enforce flushing output\n";
}
bool print_version(int argc, char * argv[])
{
if (argc > 1) do
{
argv++;
argc--;
if (check_argument_equals(*argv, {"--version"}))
{
std::cout << "version: " << PCM_VERSION << "\n";
return true;
}
} while (argc > 1);
return false;
}
std::string dos2unix(std::string in)