/
wtools.cpp
1637 lines (1419 loc) · 54.3 KB
/
wtools.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
// Windows Tools
#include "stdafx.h"
#define WIN32_LEAN_AND_MEAN
#include <WinSock2.h>
#include <stdio.h>
#include <windows.h>
#include <cstdint>
#include <iostream>
#include <string>
#include "cap.h"
#include "cfg.h"
#include "logger.h"
#include "tools/_raii.h"
#include "tools/_xlog.h"
#include "upgrade.h"
#include "wtools.h"
#pragma comment(lib, "wbemuuid.lib") /// Microsoft Specific
namespace wtools {
uint32_t AppRunner::goExec(std::wstring CommandLine, bool Wait,
bool InheritHandle, bool PipeOutput) noexcept {
try {
if (process_id_) {
XLOG::l.bp("Attempt to reuse AppRunner");
return 0;
}
if (PipeOutput) {
stdio_.create();
stderr_.create();
}
cmd_line_ = CommandLine;
job_handle_ = nullptr;
process_handle_ = nullptr;
if (use_job_) {
auto [pid, jh, ph] = cma::tools::RunStdCommandAsJob(
CommandLine.c_str(), InheritHandle, stdio_.getWrite(),
stderr_.getWrite());
// store data to reuse
process_id_ = pid;
job_handle_ = jh;
process_handle_ = ph;
} else
process_id_ = cma::tools::RunStdCommand(
CommandLine.c_str(), Wait, InheritHandle, stdio_.getWrite(),
stderr_.getWrite());
// check and return on success
if (process_id_) return process_id_;
// failure s here
XLOG::l(XLOG_FLINE + " Failed RunStd: [{}]*", GetLastError());
job_handle_ = nullptr;
process_handle_ = nullptr;
stdio_.shutdown();
stderr_.shutdown();
return 0;
} catch (const std::exception& e) {
XLOG::l.crit(XLOG_FLINE + " unexpected exception: '{}'", e.what());
}
return 0;
}
std::mutex ServiceController::s_lock_;
ServiceController* ServiceController::s_controller_ = nullptr;
// normal API
ServiceController::ServiceController(
std::unique_ptr<wtools::BaseServiceProcessor> Processor) {
if (nullptr == Processor) {
XLOG::l.crit("Processor is nullptr unique");
return;
}
std::lock_guard lk(s_lock_);
if (processor_ == nullptr && s_controller_ == nullptr) {
processor_ = std::move(Processor);
s_controller_ = this;
}
}
void WINAPI ServiceController::ServiceMain(DWORD Argc, wchar_t** Argv) {
// Register the handler function for the service
XLOG::l.i("Service Main");
s_controller_->Start(Argc, Argv);
}
// no return from here
// can print on screen
bool ServiceController::registerAndRun(const wchar_t* ServiceName, //
bool CanStop, // t
bool CanShutdown, // t
bool CanPauseContinue) { // t
if (!processor_) {
XLOG::l.bp("No processor");
return false;
}
if (!ServiceName) {
XLOG::l.bp("No Service name");
return false;
}
// strange code below
auto allocated = new wchar_t[wcslen(ServiceName) + 1];
#pragma warning(push)
#pragma warning(disable : 4996) //_CRT_SECURE_NO_WARNINGS
wcscpy(allocated, ServiceName);
#pragma warning(pop)
name_.reset(allocated);
initStatus(CanStop, CanShutdown, CanPauseContinue);
SERVICE_TABLE_ENTRY serviceTable[] = {{allocated, ServiceMain},
{NULL, NULL}};
// Connects the main thread of a service process to the service
// control manager, which causes the thread to be the service
// control dispatcher thread for the calling process. This call
// returns when the service has stopped. The process should simply
// terminate when the call returns. Two words: Blocks Here
try {
auto ret = StartServiceCtrlDispatcher(serviceTable);
if (!ret) {
XLOG::l(XLOG::kStdio)
.crit("Cannot Start Service '{}' error = [{}]",
ConvertToUTF8(ServiceName), GetLastError());
}
return ret == 0;
} catch (std::exception& e) {
XLOG::l(XLOG::kStdio)
.crit("Exception '{}' in Service start with error {}", e.what(),
GetLastError());
} catch (...) {
XLOG::l(XLOG::kStdio)
.crit("Exception in Service start with error {}", GetLastError());
}
return false;
}
//
// FUNCTION: InstallService
//
// PURPOSE: Install the current application as a service to the local
// service control manager database.
//
// PARAMETERS:
// * ServiceName - the name of the service to be installed
// * DisplayName - the display name of the service
// * dwStartType - the service start option. This parameter can be one of
// the following values: SERVICE_AUTO_START, SERVICE_BOOT_START,
// SERVICE_DEMAND_START, SERVICE_DISABLED, SERVICE_SYSTEM_START.
// * Dependencies - a pointer to a double null-terminated array of null-
// separated names of services or load ordering groups that the system
// must start before this service.
// * Account - the name of the account under which the service runs.
// * Password - the password to the account name.
//
// NOTE: If the function fails to install the service, it prints the error
// in the standard output stream for users to diagnose the problem.
//
bool InstallService(const wchar_t* ServiceName, const wchar_t* DisplayName,
uint32_t dwStartType, const wchar_t* Dependencies,
const wchar_t* Account, const wchar_t* Password) {
wchar_t service_path[MAX_PATH];
XLOG::setup::ColoredOutputOnStdio(true);
auto ret = ::GetModuleFileName(NULL, service_path, ARRAYSIZE(service_path));
if (ret == 0) {
XLOG::l(XLOG::kStdio)
.crit("GetModuleFileName failed w/err {:#X}", GetLastError());
return false;
}
// Open the local default service control manager database
auto service_manager = ::OpenSCManager(
NULL, NULL, SC_MANAGER_CONNECT | SC_MANAGER_CREATE_SERVICE);
if (!service_manager) {
XLOG::l(XLOG::kStdio)
.crit("OpenSCManager failed w/err {:#X}", GetLastError());
return false;
}
ON_OUT_OF_SCOPE(CloseServiceHandle(service_manager););
// Install the service into SCM by calling CreateService
auto service = ::CreateService(service_manager, // SCManager database
ServiceName, // Name of service
DisplayName, // Name to display
SERVICE_QUERY_STATUS, // Desired access
SERVICE_WIN32_OWN_PROCESS, // Service type
dwStartType, // Service start type
SERVICE_ERROR_NORMAL, // Error control type
service_path, // Service's binary
NULL, // No load ordering group
NULL, // No tag identifier
Dependencies, // Dependencies
Account, // Service running account
Password // Password of the account
);
if (!service) {
XLOG::l(XLOG::kStdio)
.crit("CreateService failed w/err {}", GetLastError());
return false;
}
ON_OUT_OF_SCOPE(CloseServiceHandle(service););
XLOG::l(XLOG::kStdio).i("'{}' is installed.", ConvertToUTF8(ServiceName));
return true;
}
//
// FUNCTION: UninstallService
//
// PURPOSE: Stop and remove the service from the local service control
// manager database.
//
// PARAMETERS:
// * ServiceName - the name of the service to be removed.
//
// NOTE: If the function fails to uninstall the service, it prints the
// error in the standard output stream for users to diagnose the problem.
//
bool UninstallService(const wchar_t* ServiceName) {
XLOG::setup::ColoredOutputOnStdio(true);
// Open the local default service control manager database
auto service_manager = ::OpenSCManager(NULL, NULL, SC_MANAGER_CONNECT);
if (!service_manager) {
XLOG::l(XLOG::kStdio)
.crit("OpenSCManager failed w/err {:#X}", GetLastError());
return false;
}
ON_OUT_OF_SCOPE(::CloseServiceHandle(service_manager););
// Open the service with delete, stop, and query status permissions
auto service = ::OpenService(service_manager, ServiceName,
SERVICE_STOP | SERVICE_QUERY_STATUS | DELETE);
if (!service) {
XLOG::l(XLOG::kStdio)
.crit("OpenService failed w/err {:#X}", GetLastError());
return false;
}
ON_OUT_OF_SCOPE(::CloseServiceHandle(service););
// Try to stop the service
SERVICE_STATUS ssSvcStatus = {};
auto service_name = wtools::ConvertToUTF8(ServiceName);
if (::ControlService(service, SERVICE_CONTROL_STOP, &ssSvcStatus)) {
XLOG::l(XLOG::kStdio).i("Stopping '{}'.", service_name);
Sleep(1000);
while (::QueryServiceStatus(service, &ssSvcStatus)) {
if (ssSvcStatus.dwCurrentState == SERVICE_STOP_PENDING) {
xlog::sendStringToStdio(".");
Sleep(1000);
} else
break;
}
if (ssSvcStatus.dwCurrentState == SERVICE_STOPPED) {
XLOG::l(XLOG::kStdio).i("\n{} is stopped.", service_name);
} else {
XLOG::l(XLOG::kStdio).i("\n{} failed to stop.", service_name);
}
}
// Now remove the service by calling DeleteService.
if (!::DeleteService(service)) {
XLOG::l(XLOG::kStdio)
.i("DeleteService failed w/err {:#X}\n", GetLastError());
return false;
}
XLOG::l(XLOG::kStdio)
.i("%s is removed.\n", wtools::ConvertToUTF8(ServiceName));
return true;
}
void ServiceController::initStatus(bool CanStop, bool CanShutdown,
bool CanPauseContinue) {
// The service runs in its own process.
status_.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
// The service is starting.
status_.dwCurrentState = SERVICE_START_PENDING;
// The accepted commands of the service.
DWORD controls_accepted = 0;
if (CanStop) controls_accepted |= SERVICE_ACCEPT_STOP;
if (CanShutdown) controls_accepted |= SERVICE_ACCEPT_SHUTDOWN;
if (CanPauseContinue) controls_accepted |= SERVICE_ACCEPT_PAUSE_CONTINUE;
status_.dwControlsAccepted = controls_accepted;
status_.dwWin32ExitCode = NO_ERROR;
status_.dwServiceSpecificExitCode = 0;
status_.dwCheckPoint = 0;
status_.dwWaitHint = 0;
}
//
// FUNCTION: ServiceController::Stop()
//
// PURPOSE: The function stops the service. It calls the OnStop
// virtual function in which you can specify the actions to take when
// the service stops. If an error occurs, the error will be logged in
// the Application event log, and the service will be restored to the
// original state.
//
void ServiceController::Stop() {
if (!processor_) return; // #TODO: trace
auto original_state = status_.dwCurrentState;
auto log_name = processor_->getMainLogName();
try {
// Tell SCM that the service is stopping.
setServiceStatus(SERVICE_STOP_PENDING);
// Perform service-specific stop operations.
processor_->stopService();
// Tell SCM that the service is stopped.
setServiceStatus(SERVICE_STOPPED);
} catch (DWORD dwError) {
// Log the error.
xlog::SysLogEvent(log_name, xlog::LogEvents::kError, dwError,
L"Stop Service");
// Set the original service status.
setServiceStatus(original_state);
} catch (...) {
// Log the error.
xlog::SysLogEvent(log_name, xlog::LogEvents::kError, 0,
L"Service failed to stop.");
// Set the original service status.
setServiceStatus(original_state);
}
}
//
// FUNCTION: ServiceController::Start(DWORD, wchar_t* *)
//
// PURPOSE: The function starts the service. It calls the OnStart
// virtual function in which you can specify the actions to take when
// the service starts. If an error occurs during the startup, the
// error will be logged in the Application event log, and the service
// will be stopped.
//
// PARAMETERS:
// * Argc - number of command line arguments
// * Argv - array of command line arguments
//
void ServiceController::Start(DWORD Argc, wchar_t** Argv) {
if (!processor_) {
XLOG::l.crit("Unbelievable, but process_ is nullptr");
return;
}
// Register the handler function for the service
status_handle_ =
RegisterServiceCtrlHandler(name_.get(), ServiceCtrlHandler);
if (!status_handle_) {
XLOG::l(XLOG::kStdio)("I cannot register damned handlers {}",
GetLastError());
throw GetLastError(); // crash here - we have rights
return;
}
XLOG::l.i("Damned handlers registered");
try {
// Tell SCM that the service is starting.
setServiceStatus(SERVICE_START_PENDING);
cma::cfg::upgrade::UpgradeLegacy(false);
cma::cfg::cap::Install();
// Perform service-specific initialization.
processor_->startService();
// Tell SCM that the service is started.
setServiceStatus(SERVICE_RUNNING);
} catch (DWORD dwError) {
// Log the error.
xlog::SysLogEvent(processor_->getMainLogName(), xlog::LogEvents::kError,
dwError, L"Service Start");
// Set the service status to be stopped.
setServiceStatus(SERVICE_STOPPED, dwError);
} catch (...) {
// Log the error.
xlog::SysLogEvent(processor_->getMainLogName(), xlog::LogEvents::kError,
0, L"Service failed to start.");
// Set the service status to be stopped.
setServiceStatus(SERVICE_STOPPED);
}
}
//
// FUNCTION: ServiceController::Pause()
//
// PURPOSE: The function pauses the service if the service supports
// pause and continue. It calls the OnPause virtual function in which
// you can specify the actions to take when the service pauses. If an
// error occurs, the error will be logged in the Application event
// log, and the service will become running.
//
void ServiceController::Pause() {
if (!processor_) return; // #TODO: trace, this is bad
try {
// Tell SCM that the service is pausing.
setServiceStatus(SERVICE_PAUSE_PENDING);
// Perform service-specific pause operations.
processor_->pauseService();
// Tell SCM that the service is paused.
setServiceStatus(SERVICE_PAUSED);
} catch (DWORD dwError) {
// Log the error.
xlog::SysLogEvent(processor_->getMainLogName(), xlog::LogEvents::kError,
dwError, L"Service Pause");
// Tell SCM that the service is still running.
setServiceStatus(SERVICE_RUNNING);
} catch (...) {
// Log the error.
xlog::SysLogEvent(processor_->getMainLogName(), xlog::LogEvents::kError,
0, L"Service failed to pause.");
// Tell SCM that the service is still running.
setServiceStatus(SERVICE_RUNNING);
}
}
//
// FUNCTION: ServiceController::Continue()
//
// PURPOSE: The function resumes normal functioning after being paused
// if the service supports pause and continue. It calls the OnContinue
// virtual function in which you can specify the actions to take when
// the service continues. If an error occurs, the error will be logged
// in the Application event log, and the service will still be paused.
//
void ServiceController::Continue() {
try {
// Tell SCM that the service is resuming.
setServiceStatus(SERVICE_CONTINUE_PENDING);
// Perform service-specific continue operations.
processor_->continueService();
// Tell SCM that the service is running.
setServiceStatus(SERVICE_RUNNING);
} catch (DWORD dwError) {
// Log the error.
xlog::SysLogEvent(processor_->getMainLogName(), xlog::LogEvents::kError,
dwError, L"Service Continue");
// Tell SCM that the service is still paused.
setServiceStatus(SERVICE_PAUSED);
} catch (...) {
// Log the error.
xlog::SysLogEvent(processor_->getMainLogName(), xlog::LogEvents::kError,
0, L"Service failed to continue.");
// Tell SCM that the service is still paused.
setServiceStatus(SERVICE_PAUSED);
}
}
//
// FUNCTION: ServiceController::Shutdown()
//
// PURPOSE: The function executes when the system is shutting down. It
// calls the OnShutdown virtual function in which you can specify what
// should occur immediately prior to the system shutting down. If an
// error occurs, the error will be logged in the Application event
// log.
//
void ServiceController::Shutdown() {
try {
// Perform service-specific shutdown operations.
processor_->shutdownService();
// Tell SCM that the service is stopped.
setServiceStatus(SERVICE_STOPPED);
} catch (DWORD dwError) {
// Log the error.
xlog::SysLogEvent(processor_->getMainLogName(), xlog::LogEvents::kError,
dwError, L"Service Shutdown");
} catch (...) {
// Log the error.
xlog::SysLogEvent(processor_->getMainLogName(), xlog::LogEvents::kError,
0, L"Service failed to shutdown.");
}
}
// Window s specific performance counters
// Functions are from OWA/MSDN
// No exceptions
// C-like here to be more windows
namespace perf {
// read MULTI_SZ string from the registry
// #TODO gtest
std::vector<wchar_t> ReadPerfCounterKeyFromRegistry(bool LocalLanguage) {
DWORD counters_size = 0;
auto key = LocalLanguage ? HKEY_PERFORMANCE_NLSTEXT : HKEY_PERFORMANCE_TEXT;
// preflight
::RegQueryValueExW(key, L"Counter", nullptr, nullptr, nullptr,
&counters_size);
if (counters_size == 0) {
XLOG::l("SOmething is really wrong");
return {};
}
// one char more
std::vector<wchar_t> result(counters_size + 2 / sizeof(wchar_t));
// actual read op
::RegQueryValueExW(key, L"Counter", nullptr, nullptr,
reinterpret_cast<LPBYTE>(result.data()), &counters_size);
result[counters_size] = 0; // to stop all possible strlens here
return result;
}
// simple scanner of multi_sz strings
// #TODO gtest?
const wchar_t* GetMultiSzEntry(wchar_t*& Pos, const wchar_t* End) {
auto sz = Pos;
if (sz >= End) return nullptr;
auto len = wcslen(sz);
if (len == 0) return nullptr; // last string in multi_sz
Pos += len + 1;
return sz;
}
std::optional<uint32_t> FindPerfIndexInRegistry(const std::wstring& Key) {
if (Key.empty()) return {};
for (auto national : {true, false}) {
auto counter_str =
wtools::perf::ReadPerfCounterKeyFromRegistry(national);
auto data = counter_str.data();
const auto end = counter_str.data() + counter_str.size();
for (;;) {
// get id
auto potential_id = GetMultiSzEntry(data, end);
if (!potential_id) break;
// get name
auto potential_name = GetMultiSzEntry(data, end);
if (!potential_name) break;
// check name
if (Key == potential_name) {
return cma::tools::ConvertToUint32(potential_id);
}
}
}
return {};
}
// read default ENGLISH registry entry and build map with
// id - name
NameMap GenerateNameMap() {
NameMap nm;
auto counter_str = wtools::perf::ReadPerfCounterKeyFromRegistry(false);
auto data = counter_str.data();
const auto end = counter_str.data() + counter_str.size();
for (;;) {
// get id
auto id_as_text = GetMultiSzEntry(data, end);
if (!id_as_text) break;
// get name
auto potential_name = GetMultiSzEntry(data, end);
if (!potential_name) break;
// check name
auto id = ::wcstol(id_as_text, nullptr, 10);
if (id > 0) nm[id] = potential_name;
}
return nm;
}
// Low level API to access to performance data
// Code below is not clean
// #TODO refactor to normal CMK standard
inline auto FindFirstObject(const PERF_DATA_BLOCK* PerfDataBlock) {
using namespace cma::tools;
return static_cast<const PERF_OBJECT_TYPE*>(
GetOffsetInBytes(PerfDataBlock, PerfDataBlock->HeaderLength));
}
inline auto FindNextObject(const PERF_OBJECT_TYPE* Object) {
return reinterpret_cast<const PERF_OBJECT_TYPE*>((BYTE*)Object +
Object->TotalByteLength);
}
inline auto FirstCounter(const PERF_OBJECT_TYPE* Object) {
return reinterpret_cast<const PERF_COUNTER_DEFINITION*>(
(BYTE*)Object + Object->HeaderLength);
}
inline auto NextCounter(const PERF_COUNTER_DEFINITION* PerfCounter) {
return reinterpret_cast<const PERF_COUNTER_DEFINITION*>(
(BYTE*)PerfCounter + PerfCounter->ByteLength);
}
inline auto GetCounterBlock(PERF_INSTANCE_DEFINITION* Instance) {
return reinterpret_cast<PERF_COUNTER_BLOCK*>((BYTE*)Instance +
Instance->ByteLength);
}
inline auto GetCounterBlock(const PERF_INSTANCE_DEFINITION* Instance) {
return reinterpret_cast<const PERF_COUNTER_BLOCK*>((const BYTE*)Instance +
Instance->ByteLength);
}
inline auto FirstInstance(PERF_OBJECT_TYPE* Object) {
return reinterpret_cast<PERF_INSTANCE_DEFINITION*>(
(BYTE*)Object + Object->DefinitionLength);
}
inline auto FirstInstance(const PERF_OBJECT_TYPE* Object) {
return reinterpret_cast<const PERF_INSTANCE_DEFINITION*>(
(const BYTE*)Object + Object->DefinitionLength);
}
inline auto NextInstance(PERF_INSTANCE_DEFINITION* Instance) {
return reinterpret_cast<PERF_INSTANCE_DEFINITION*>(
(BYTE*)Instance + Instance->ByteLength +
GetCounterBlock(Instance)->ByteLength);
}
inline auto NextInstance(const PERF_INSTANCE_DEFINITION* Instance) {
return reinterpret_cast<const PERF_INSTANCE_DEFINITION*>(
(const BYTE*)Instance + Instance->ByteLength +
GetCounterBlock(Instance)->ByteLength);
}
// main reader from registry
// #TODO gtest
// DataSequence is primitive wrapper over data buffer
// DataSequence takes ownership over buffer
DataSequence ReadPerformanceDataFromRegistry(
const std::wstring& CounterName) noexcept {
DWORD buf_size = 40000;
BYTE* buffer = nullptr;
while (1) {
// allocation(a bit stupid, but we do not want top have STL inside
try {
buffer = new BYTE[buf_size];
} catch (...) {
return cma::tools::DataBlock<BYTE>(); // ups
}
DWORD type = 0;
auto ret =
::RegQueryValueExW(HKEY_PERFORMANCE_DATA, CounterName.c_str(),
nullptr, &type, buffer, &buf_size);
RegCloseKey(HKEY_PERFORMANCE_DATA); // MSDN requirement
if (ret == ERROR_SUCCESS) break; // normal exit
if (ret == ERROR_MORE_DATA) {
buf_size *= 2; // :)
delete[] buffer; // realloc part one
continue; // to be safe
} else
return {};
}
return DataSequence((int)buf_size, buffer);
}
const PERF_OBJECT_TYPE* FindPerfObject(const DataSequence& Db,
DWORD counter_index) noexcept {
auto data = Db.data_;
auto max_offset = Db.len_;
if (!data || !max_offset) return nullptr;
auto data_block = reinterpret_cast<PERF_DATA_BLOCK*>(data);
auto object = FindFirstObject(data_block);
for (DWORD i = 0; i < data_block->NumObjectTypes; ++i) {
// iterate to the object we requested since apparently there can be more
// than that in the buffer returned
if (object->ObjectNameTitleIndex == counter_index) {
return object;
} else {
object = FindNextObject(object);
}
}
return nullptr;
}
std::vector<const PERF_INSTANCE_DEFINITION*> GenerateInstances(
const PERF_OBJECT_TYPE* Object) noexcept {
if (Object->NumInstances <= 0L) return {};
std::vector<const PERF_INSTANCE_DEFINITION*> result;
try {
result.reserve(Object->NumInstances); // optimization
auto instance = FirstInstance(Object);
for (auto i = 0L; i < Object->NumInstances; ++i) {
result.push_back(instance);
instance = NextInstance(instance);
}
} catch (const std::exception& e) {
xlog::l(XLOG_FLINE + " exception: %s", e.what());
}
return result;
}
std::vector<std::wstring> GenerateInstanceNames(
const PERF_OBJECT_TYPE* Object) noexcept {
// check for nothing
if (Object->NumInstances <= 0L) return {};
std::vector<std::wstring> result;
try {
result.reserve(Object->NumInstances); // optimization
auto instance = FirstInstance(Object);
for (auto i = 0L; i < Object->NumInstances; ++i) {
result.push_back(
(LPCWSTR)((BYTE*)(instance) + instance->NameOffset));
instance = NextInstance(instance);
}
} catch (const std::exception& e) {
XLOG::l(XLOG_FLINE + " disaster in names: {}", e.what());
}
return result;
}
// Instance less support
// DataBlock is filled when NumInstances below or equal 0
std::vector<const PERF_COUNTER_DEFINITION*> GenerateCounters(
const PERF_OBJECT_TYPE* Object,
const PERF_COUNTER_BLOCK*& DataBlock) noexcept {
std::vector<const PERF_COUNTER_DEFINITION*> result;
DataBlock = nullptr;
try {
result.reserve(Object->NumCounters); // optimization
auto counter = FirstCounter(Object);
for (DWORD i = 0UL; i < Object->NumCounters; ++i) {
result.push_back(counter);
counter = NextCounter(counter);
}
// when object has no instances immediately after the counters
// we have data block, ergo a code a bit strange
if (Object->NumInstances <= 0)
DataBlock = reinterpret_cast<const PERF_COUNTER_BLOCK*>(counter);
} catch (const std::exception& e) {
XLOG::l(XLOG_FLINE + " disaster in instance less counters: {}",
e.what());
}
return result;
}
// simplified version ignoring datablock
std::vector<const PERF_COUNTER_DEFINITION*> GenerateCounters(
const PERF_OBJECT_TYPE* Object) noexcept {
const PERF_COUNTER_BLOCK* block = nullptr;
return perf::GenerateCounters(Object, block);
}
// used only in skype
// build map of the <id:name>
std::vector<std::wstring> GenerateCounterNames(const PERF_OBJECT_TYPE* Object,
const NameMap& Map) {
std::vector<std::wstring> result;
auto counter = FirstCounter(Object);
for (DWORD i = 0UL; i < Object->NumCounters; ++i) {
auto iter = Map.find(counter->CounterNameTitleIndex);
if (iter != Map.end()) {
result.push_back(iter->second);
} else {
// not found in map
result.push_back(std::to_wstring(counter->CounterNameTitleIndex));
}
counter = NextCounter(counter);
}
return result;
}
// Windows special function to extract data
// Based on OWA => INVALID
// #TODO http://msdn.microsoft.com/en-us/library/aa373178%28v=vs.85%29.aspx
static uint64_t GetCounterValueFromBlock(
const PERF_COUNTER_DEFINITION& Counter,
const PERF_COUNTER_BLOCK* Block) noexcept {
unsigned offset = Counter.CounterOffset;
const auto data = cma::tools::GetOffsetInBytes(Block, offset);
constexpr const DWORD kPerfSizeMaks = 0x00000300;
auto dwords = static_cast<const uint32_t*>(data);
switch (Counter.CounterType & kPerfSizeMaks) {
case PERF_SIZE_DWORD:
return static_cast<uint64_t>(dwords[0]);
case PERF_SIZE_LARGE:
return *(UNALIGNED uint64_t*)data;
case PERF_SIZE_ZERO:
return 0;
case PERF_SIZE_VARIABLE_LEN:
default: {
// handle other data generically. This is wrong in some situation.
// Once upon a time in future we might implement a conversion as
// described in
// http://msdn.microsoft.com/en-us/library/aa373178%28v=vs.85%29.aspx
int size = Counter.CounterSize;
if (size == 4) return static_cast<uint64_t>(dwords[0]);
if (size == 8) {
// i am not sure that this must be should so complicated
return static_cast<uint64_t>(dwords[0]) +
(static_cast<uint64_t>(dwords[1]) << 32);
}
// abnormal situation....
return 0ULL;
}
}
}
std::vector<uint64_t> GenerateValues(
const PERF_COUNTER_DEFINITION& Counter,
std::vector<const PERF_INSTANCE_DEFINITION*>& Instances) noexcept {
std::vector<uint64_t> result;
try {
if (Instances.size() > 0) {
result.reserve(Instances.size());
for (const auto instance : Instances) {
auto counter_block = GetCounterBlock(instance);
result.emplace_back(
GetCounterValueFromBlock(Counter, counter_block));
}
}
} catch (const std::exception& e) {
xlog::l(XLOG_FLINE + " exception:%s", e.what());
return {};
}
return result;
}
uint64_t GetValueFromBlock(const PERF_COUNTER_DEFINITION& Counter,
const PERF_COUNTER_BLOCK* Block) noexcept {
if (Block) {
return GetCounterValueFromBlock(Counter, Block);
}
return 0;
}
// from OWA
// #TODO gtest is required
std::string GetName(uint32_t CounterType) noexcept {
// probably we need a map here
// looks terrible
switch (CounterType) {
case PERF_COUNTER_COUNTER:
return "counter";
case PERF_COUNTER_TIMER:
return "timer";
case PERF_COUNTER_QUEUELEN_TYPE:
return "queuelen_type";
case PERF_COUNTER_BULK_COUNT:
return "bulk_count";
case PERF_COUNTER_TEXT:
return "text";
case PERF_COUNTER_RAWCOUNT:
return "rawcount";
case PERF_COUNTER_LARGE_RAWCOUNT:
return "large_rawcount";
case PERF_COUNTER_RAWCOUNT_HEX:
return "rawcount_hex";
case PERF_COUNTER_LARGE_RAWCOUNT_HEX:
return "large_rawcount_HEX";
case PERF_SAMPLE_FRACTION:
return "sample_fraction";
case PERF_SAMPLE_COUNTER:
return "sample_counter";
case PERF_COUNTER_NODATA:
return "nodata";
case PERF_COUNTER_TIMER_INV:
return "timer_inv";
case PERF_SAMPLE_BASE:
return "sample_base";
case PERF_AVERAGE_TIMER:
return "average_timer";
case PERF_AVERAGE_BASE:
return "average_base";
case PERF_AVERAGE_BULK:
return "average_bulk";
case PERF_100NSEC_TIMER:
return "100nsec_timer";
case PERF_100NSEC_TIMER_INV:
return "100nsec_timer_inv";
case PERF_COUNTER_MULTI_TIMER:
return "multi_timer";
case PERF_COUNTER_MULTI_TIMER_INV:
return "multi_timer_inV";
case PERF_COUNTER_MULTI_BASE:
return "multi_base";
case PERF_100NSEC_MULTI_TIMER:
return "100nsec_multi_timer";
case PERF_100NSEC_MULTI_TIMER_INV:
return "100nsec_multi_timer_inV";
case PERF_RAW_FRACTION:
return "raw_fraction";
case PERF_RAW_BASE:
return "raw_base";
case PERF_ELAPSED_TIME:
return "elapsed_time";
default: {
char out[32];
sprintf(out, "type(%X)", CounterType);
return out;
} break;
}
}
} // namespace perf
static std::mutex ComLock;
static bool WindowsComInitialized = false; // #VIP #Global
// controls availability of WMI
bool InitWindowsComSecurity() { // Initialize
auto hres =
CoInitializeSecurity(nullptr,
-1, // COM negotiates service
nullptr, // Authentication services
nullptr, // Reserved
RPC_C_AUTHN_LEVEL_DEFAULT, // authentication
RPC_C_IMP_LEVEL_IMPERSONATE, // Impersonation
nullptr, // Authentication info
EOAC_NONE, // Additional capabilities
nullptr // Reserved
);
if (hres == RPC_E_TOO_LATE) {
XLOG::l.w("Stupid Windows {:#X}", (unsigned)hres);
return true;
}
if (FAILED(hres)) {
XLOG::l.crit("Error Windows Security {:X}", (unsigned)hres);
return false; // Program has failed.
}
XLOG::l.i("COM Initialized");
return true;
}
void InitWindowsCom() {
std::lock_guard lk(ComLock);
if (WindowsComInitialized) return;
auto hres = CoInitializeEx(0, COINIT_MULTITHREADED);
WORD wVersionRequested;
WSADATA wsaData;
int err;
/* Use the MAKEWORD(lowbyte, highbyte) macro declared in Windef.h */
wVersionRequested = MAKEWORD(2, 2);
err = WSAStartup(wVersionRequested, &wsaData);
if (err != 0) {
/* Tell the user that we could not find a usable */
/* Winsock DLL. */
printf("WSAStartup failed with error: %d\n", err);
return;
}
if (FAILED(hres)) {
XLOG::l.crit("Can't init COM {:#X}", (unsigned)hres);
return;
}
auto ret = InitWindowsComSecurity();
if (!ret) {