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
|
#include "env.h"
#include "envmetrics.h"
#include "envmodule.h"
#include "envsecurity.h"
#include "envshortcut.h"
#include "envwindows.h"
#include "settings.h"
#include <log.h>
#include <utility.h>
namespace env
{
using namespace MOBase;
Console::Console()
: m_hasConsole(false), m_in(nullptr), m_out(nullptr), m_err(nullptr)
{
// open a console
if (!AllocConsole()) {
// failed, ignore
}
m_hasConsole = true;
// redirect stdin, stdout and stderr to it
freopen_s(&m_in, "CONIN$", "r", stdin);
freopen_s(&m_out, "CONOUT$", "w", stdout);
freopen_s(&m_err, "CONOUT$", "w", stderr);
}
Console::~Console()
{
// close redirected handles and redirect standard stream to NUL in case
// they're used after this
if (m_err) {
std::fclose(m_err);
freopen_s(&m_err, "NUL", "w", stderr);
}
if (m_out) {
std::fclose(m_out);
freopen_s(&m_out, "NUL", "w", stdout);
}
if (m_in) {
std::fclose(m_in);
freopen_s(&m_in, "NUL", "r", stdin);
}
// close console
if (m_hasConsole) {
FreeConsole();
}
}
Environment::Environment()
{
}
// anchor
Environment::~Environment() = default;
const std::vector<Module>& Environment::loadedModules() const
{
if (m_modules.empty()){
m_modules = getLoadedModules();
}
return m_modules;
}
std::vector<Process> Environment::runningProcesses() const
{
return getRunningProcesses();
}
const WindowsInfo& Environment::windowsInfo() const
{
if (!m_windows) {
m_windows.reset(new WindowsInfo);
}
return *m_windows;
}
const std::vector<SecurityProduct>& Environment::securityProducts() const
{
if (m_security.empty()) {
m_security = getSecurityProducts();
}
return m_security;
}
const Metrics& Environment::metrics() const
{
if (!m_metrics) {
m_metrics.reset(new Metrics);
}
return *m_metrics;
}
QString Environment::timezone() const
{
TIME_ZONE_INFORMATION tz = {};
const auto r = GetTimeZoneInformation(&tz);
if (r == TIME_ZONE_ID_INVALID) {
const auto e = GetLastError();
log::error("failed to get timezone, {}", formatSystemMessage(e));
return "unknown";
}
auto offsetString = [](int o) {
return
QString("%1%2:%3")
.arg(o < 0 ? "" : "+")
.arg(QString::number(o / 60), 2, QChar::fromLatin1('0'))
.arg(QString::number(o % 60), 2, QChar::fromLatin1('0'));
};
const auto stdName = QString::fromWCharArray(tz.StandardName);
const auto stdOffset = -(tz.Bias + tz.StandardBias);
const auto std = QString("%1, %2")
.arg(stdName)
.arg(offsetString(stdOffset));
const auto dstName = QString::fromWCharArray(tz.DaylightName);
const auto dstOffset = -(tz.Bias + tz.DaylightBias);
const auto dst = QString("%1, %2")
.arg(dstName)
.arg(offsetString(dstOffset));
QString s;
if (r == TIME_ZONE_ID_DAYLIGHT) {
s = dst + " (dst is active, std is " + std + ")";
} else {
s = std + " (std is active, dst is " + dst + ")";
}
return s;
}
void Environment::dump(const Settings& s) const
{
log::debug("windows: {}", windowsInfo().toString());
log::debug("time zone: {}", timezone());
if (windowsInfo().compatibilityMode()) {
log::warn("MO seems to be running in compatibility mode");
}
log::debug("security products:");
{
// ignore products with identical names, some AVs register themselves with
// the same names and provider, but different guids
std::set<QString> productNames;
for (const auto& sp : securityProducts()) {
productNames.insert(sp.toString());
}
for (auto&& name : productNames) {
log::debug(" . {}", name);
}
}
log::debug("modules loaded in process:");
for (const auto& m : loadedModules()) {
log::debug(" . {}", m.toString());
}
log::debug("displays:");
for (const auto& d : metrics().displays()) {
log::debug(" . {}", d.toString());
}
const auto r = metrics().desktopGeometry();
log::debug(
"desktop geometry: ({},{})-({},{})",
r.left(), r.top(), r.right(), r.bottom());
dumpDisks(s);
}
void Environment::dumpDisks(const Settings& s) const
{
std::set<QString> rootPaths;
auto dump = [&](auto&& path) {
const QFileInfo fi(path);
const QStorageInfo si(fi.absoluteFilePath());
if (rootPaths.contains(si.rootPath())) {
// already seen
return;
}
// remember
rootPaths.insert(si.rootPath());
log::debug(
" . {} free={} MB{}",
si.rootPath(),
(si.bytesFree() / 1000 / 1000),
(si.isReadOnly() ? " (readonly)" : ""));
};
log::debug("drives:");
dump(QStorageInfo::root().rootPath());
dump(s.paths().base());
dump(s.paths().downloads());
dump(s.paths().mods());
dump(s.paths().cache());
dump(s.paths().profiles());
dump(s.paths().overwrite());
dump(QCoreApplication::applicationDirPath());
}
QString path()
{
return get("PATH");
}
QString addPath(const QString& s)
{
auto old = path();
set("PATH", get("PATH") + ";" + s);
return old;
}
QString setPath(const QString& s)
{
return set("PATH", s);
}
QString get(const QString& name)
{
std::size_t bufferSize = 4000;
auto buffer = std::make_unique<wchar_t[]>(bufferSize);
DWORD realSize = ::GetEnvironmentVariableW(
name.toStdWString().c_str(),
buffer.get(), static_cast<DWORD>(bufferSize));
if (realSize > bufferSize) {
bufferSize = realSize;
buffer = std::make_unique<wchar_t[]>(bufferSize);
realSize = ::GetEnvironmentVariableW(
name.toStdWString().c_str(),
buffer.get(), static_cast<DWORD>(bufferSize));
}
if (realSize == 0) {
const auto e = ::GetLastError();
// don't log if not found
if (e != ERROR_ENVVAR_NOT_FOUND) {
log::error(
"failed to get environment variable '{}', {}",
name, formatSystemMessage(e));
}
return {};
}
return QString::fromWCharArray(buffer.get(), realSize);
}
QString set(const QString& n, const QString& v)
{
auto old = get(n);
::SetEnvironmentVariableW(n.toStdWString().c_str(), v.toStdWString().c_str());
return old;
}
Service::Service(QString name)
: Service(std::move(name), StartType::None, Status::None)
{
}
Service::Service(QString name, StartType st, Status s)
: m_name(std::move(name)), m_startType(st), m_status(s)
{
}
const QString& Service::name() const
{
return m_name;
}
bool Service::isValid() const
{
return (m_startType != StartType::None) && (m_status != Status::None);
}
Service::StartType Service::startType() const
{
return m_startType;
}
Service::Status Service::status() const
{
return m_status;
}
QString Service::toString() const
{
return QString("service '%1', start=%2, status=%3")
.arg(m_name)
.arg(env::toString(m_startType))
.arg(env::toString(m_status));
}
QString toString(Service::StartType st)
{
using ST = Service::StartType;
switch (st)
{
case ST::None:
return "none";
case ST::Disabled:
return "disabled";
case ST::Enabled:
return "enabled";
default:
return QString("unknown %1").arg(static_cast<int>(st));
}
}
QString toString(Service::Status st)
{
using S = Service::Status;
switch (st)
{
case S::None:
return "none";
case S::Stopped:
return "stopped";
case S::Running:
return "running";
default:
return QString("unknown %1").arg(static_cast<int>(st));
}
}
Service::StartType getServiceStartType(SC_HANDLE s, const QString& name)
{
DWORD needed = 0;
if (!QueryServiceConfig(s, NULL, 0, &needed)) {
const auto e = GetLastError();
if (e != ERROR_INSUFFICIENT_BUFFER) {
log::error(
"QueryServiceConfig() for size for '{}' failed, {}",
name, GetLastError());
return Service::StartType::None;
}
}
const auto size = needed;
MallocPtr<QUERY_SERVICE_CONFIG> config(
static_cast<QUERY_SERVICE_CONFIG*>(std::malloc(size)));
if (!QueryServiceConfig(s, config.get(), size, &needed)) {
const auto e = GetLastError();
log::error(
"QueryServiceConfig() for '{}' failed", name, formatSystemMessage(e));
return Service::StartType::None;
}
switch (config->dwStartType)
{
case SERVICE_AUTO_START: // fall-through
case SERVICE_BOOT_START:
case SERVICE_DEMAND_START:
case SERVICE_SYSTEM_START:
{
return Service::StartType::Enabled;
}
case SERVICE_DISABLED:
{
return Service::StartType::Disabled;
}
default:
{
log::error(
"unknown service start type {} for '{}'",
config->dwStartType, name);
return Service::StartType::None;
}
}
}
Service::Status getServiceStatus(SC_HANDLE s, const QString& name)
{
DWORD needed = 0;
if (!QueryServiceStatusEx(s, SC_STATUS_PROCESS_INFO, NULL, 0, &needed)) {
const auto e = GetLastError();
if (e != ERROR_INSUFFICIENT_BUFFER) {
log::error(
"QueryServiceStatusEx() for size for '{}' failed, {}",
name, GetLastError());
return Service::Status::None;
}
}
const auto size = needed;
MallocPtr<SERVICE_STATUS_PROCESS> status(
static_cast<SERVICE_STATUS_PROCESS*>(std::malloc(size)));
const auto r = QueryServiceStatusEx(
s, SC_STATUS_PROCESS_INFO, reinterpret_cast<BYTE*>(status.get()),
size, &needed);
if (!r) {
const auto e = GetLastError();
log::error(
"QueryServiceStatusEx() failed for '{}', {}",
name, formatSystemMessage(e));
return Service::Status::None;
}
switch (status->dwCurrentState)
{
case SERVICE_START_PENDING: // fall-through
case SERVICE_CONTINUE_PENDING:
case SERVICE_RUNNING:
{
return Service::Status::Running;
}
case SERVICE_STOPPED: // fall-through
case SERVICE_STOP_PENDING:
case SERVICE_PAUSE_PENDING:
case SERVICE_PAUSED:
{
return Service::Status::Stopped;
}
default:
{
log::error(
"unknown service status {} for '{}'",
status->dwCurrentState, name);
return Service::Status::None;
}
}
}
Service getService(const QString& name)
{
// service manager
const LocalPtr<SC_HANDLE> scm(OpenSCManager(
NULL, NULL, SERVICE_QUERY_STATUS | SERVICE_QUERY_CONFIG));
if (!scm) {
const auto e = GetLastError();
log::error("OpenSCManager() failed, {}", formatSystemMessage(e));
return Service(name);
}
// service
const LocalPtr<SC_HANDLE> s(OpenService(
scm.get(), name.toStdWString().c_str(),
SERVICE_QUERY_STATUS | SERVICE_QUERY_CONFIG));
if (!s) {
const auto e = GetLastError();
log::error("OpenService() failed for '{}', {}", name, formatSystemMessage(e));
return Service(name);
}
const auto startType = getServiceStartType(s.get(), name);
const auto status = getServiceStatus(s.get(), name);
return {name, startType, status};
}
// returns the filename of the given process or the current one
//
std::wstring processFilename(HANDLE process=INVALID_HANDLE_VALUE)
{
// double the buffer size 10 times
const int MaxTries = 10;
DWORD bufferSize = MAX_PATH;
for (int tries=0; tries<MaxTries; ++tries)
{
auto buffer = std::make_unique<wchar_t[]>(bufferSize + 1);
std::fill(buffer.get(), buffer.get() + bufferSize + 1, 0);
DWORD writtenSize = 0;
if (process == INVALID_HANDLE_VALUE) {
// query this process
writtenSize = GetModuleFileNameW(0, buffer.get(), bufferSize);
} else {
// query another process
writtenSize = GetModuleBaseNameW(process, 0, buffer.get(), bufferSize);
}
if (writtenSize == 0) {
// hard failure
const auto e = GetLastError();
std::wcerr << formatSystemMessage(e) << L"\n";
break;
} else if (writtenSize >= bufferSize) {
// buffer is too small, try again
bufferSize *= 2;
} else {
// if GetModuleFileName() works, `writtenSize` does not include the null
// terminator
const std::wstring s(buffer.get(), writtenSize);
const std::filesystem::path path(s);
return path.filename().native();
}
}
// something failed or the path is way too long to make sense
std::wstring what;
if (process == INVALID_HANDLE_VALUE) {
what = L"the current process";
} else {
what = L"pid " + std::to_wstring(reinterpret_cast<std::uintptr_t>(process));
}
std::wcerr << L"failed to get filename for " << what << L"\n";
return {};
}
DWORD findOtherPid()
{
const std::wstring defaultName = L"ModOrganizer.exe";
std::wclog << L"looking for the other process...\n";
// used to skip the current process below
const auto thisPid = GetCurrentProcessId();
std::wclog << L"this process id is " << thisPid << L"\n";
// getting the filename for this process, assumes the other process has the
// same one
auto filename = processFilename();
if (filename.empty()) {
std::wcerr
<< L"can't get current process filename, defaulting to "
<< defaultName << L"\n";
filename = defaultName;
} else {
std::wclog << L"this process filename is " << filename << L"\n";
}
// getting all running processes
const auto processes = getRunningProcesses();
std::wclog << L"there are " << processes.size() << L" processes running\n";
// going through processes, trying to find one with the same name and a
// different pid than this process has
for (const auto& p : processes) {
if (p.name() == filename) {
if (p.pid() != thisPid) {
return p.pid();
}
}
}
std::wclog
<< L"no process with this filename\n"
<< L"MO may not be running, or it may be running as administrator\n"
<< L"you can try running this again as administrator\n";
return 0;
}
std::wstring tempDir()
{
const DWORD bufferSize = MAX_PATH + 1;
wchar_t buffer[bufferSize + 1] = {};
const auto written = GetTempPathW(bufferSize, buffer);
if (written == 0) {
const auto e = GetLastError();
std::wcerr
<< L"failed to get temp path, " << formatSystemMessage(e) << L"\n";
return {};
}
// `written` does not include the null terminator
return std::wstring(buffer, buffer + written);
}
HandlePtr tempFile(const std::wstring dir)
{
// maximum tries of incrementing the counter
const int MaxTries = 100;
// UTC time and date will be in the filename
const auto now = std::time(0);
const auto tm = std::gmtime(&now);
// "ModOrganizer-YYYYMMDDThhmmss.dmp", with a possible "-i" appended, where
// i can go until MaxTries
std::wostringstream oss;
oss
<< L"ModOrganizer-"
<< std::setw(4) << (1900 + tm->tm_year)
<< std::setw(2) << std::setfill(L'0') << (tm->tm_mon + 1)
<< std::setw(2) << std::setfill(L'0') << tm->tm_mday << "T"
<< std::setw(2) << std::setfill(L'0') << tm->tm_hour
<< std::setw(2) << std::setfill(L'0') << tm->tm_min
<< std::setw(2) << std::setfill(L'0') << tm->tm_sec;
const std::wstring prefix = oss.str();
const std::wstring ext = L".dmp";
// first path to try, without counter in it
std::wstring path = dir + L"\\" + prefix + ext;
for (int i=0; i<MaxTries; ++i) {
std::wclog << L"trying file '" << path << L"'\n";
HandlePtr h (CreateFileW(
path.c_str(), GENERIC_WRITE, 0, nullptr,
CREATE_NEW, FILE_ATTRIBUTE_NORMAL, nullptr));
if (h.get() != INVALID_HANDLE_VALUE) {
// worked
return h;
}
const auto e = GetLastError();
if (e != ERROR_FILE_EXISTS) {
// probably no write access
std::wcerr
<< L"failed to create dump file, " << formatSystemMessage(e) << L"\n";
return {};
}
// try again with "-i"
path = dir + L"\\" + prefix + L"-" + std::to_wstring(i + 1) + ext;
}
std::wcerr << L"can't create dump file, ran out of filenames\n";
return {};
}
HandlePtr dumpFile()
{
// try the current directory
HandlePtr h = tempFile(L".");
if (h.get() != INVALID_HANDLE_VALUE) {
return h;
}
std::wclog << L"cannot write dump file in current directory\n";
// try the temp directory
const auto dir = tempDir();
if (!dir.empty()) {
h = tempFile(dir.c_str());
if (h.get() != INVALID_HANDLE_VALUE) {
return h;
}
}
return {};
}
bool createMiniDump(HANDLE process, CoreDumpTypes type)
{
const DWORD pid = GetProcessId(process);
const HandlePtr file = dumpFile();
if (!file) {
std::wcerr << L"nowhere to write the dump file\n";
return false;
}
auto flags = _MINIDUMP_TYPE(
MiniDumpNormal |
MiniDumpWithHandleData |
MiniDumpWithUnloadedModules |
MiniDumpWithProcessThreadData);
if (type == CoreDumpTypes::Data) {
std::wclog << L"writing minidump with data\n";
flags = _MINIDUMP_TYPE(flags | MiniDumpWithDataSegs);
} else if (type == CoreDumpTypes::Full) {
std::wclog << L"writing full minidump\n";
flags = _MINIDUMP_TYPE(flags | MiniDumpWithFullMemory);
} else {
std::wclog << L"writing mini minidump\n";
}
const auto ret = MiniDumpWriteDump(
process, pid, file.get(), flags, nullptr, nullptr, nullptr);
if (!ret) {
const auto e = GetLastError();
std::wcerr
<< L"failed to write mini dump, " << formatSystemMessage(e) << L"\n";
return false;
}
std::wclog << L"minidump written correctly\n";
return true;
}
bool coredump(CoreDumpTypes type)
{
std::wclog << L"creating minidump for the current process\n";
return createMiniDump(GetCurrentProcess(), type);
}
bool coredumpOther(CoreDumpTypes type)
{
std::wclog << L"creating minidump for an running process\n";
const auto pid = findOtherPid();
if (pid == 0) {
std::wcerr << L"no other process found\n";
return false;
}
std::wclog << L"found other process with pid " << pid << L"\n";
HandlePtr handle(OpenProcess(
PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, pid));
if (!handle) {
const auto e = GetLastError();
std::wcerr
<< L"failed to open process " << pid << L", "
<< formatSystemMessage(e) << L"\n";
return false;
}
return createMiniDump(handle.get(), type);
}
} // namespace
|