-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathGetCmdLine.cpp
68 lines (56 loc) · 2.15 KB
/
GetCmdLine.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
#include <windows.h>
#include <stdio.h>
#include <Winternl.h>
#include <tchar.h>
#include <memory>
#include <vector>
#include "arg.inl"
template <class T>
auto CreateUnique(HANDLE h, T* f)
{
return std::unique_ptr<std::remove_pointer<HANDLE>::type, T*>(h, f);
}
auto CreateUnique(HANDLE h)
{
return CreateUnique(h, CloseHandle);
}
inline int StrLen(const PUNICODE_STRING s)
{
return (int) (s->Length / sizeof(WCHAR));
}
#define CHECK(x, m) if (!(x)) { _fputts((m), stderr); return GetLastError(); }
int _tmain(int argc, TCHAR *argv[])
{
arginit(argc, argv, _T("Show command line for a process"));
const int pid = _tstoi(argnumdesc(1, _T("0"), _T("pid"), _T("Process id")));
if (!argcleanup())
return EXIT_FAILURE;
if (argusage(pid == 0))
return EXIT_SUCCESS;
auto hProcess = CreateUnique(OpenProcess(
PROCESS_QUERY_INFORMATION | /* required for NtQueryInformationProcess */
PROCESS_VM_READ, /* required for ReadProcessMemory */
FALSE, pid));
CHECK(hProcess, _T("Could not open process!\n"));
PROCESS_BASIC_INFORMATION pbi;
CHECK(NT_SUCCESS(NtQueryInformationProcess(hProcess.get(),
ProcessBasicInformation,
&pbi, sizeof(pbi), NULL)),
_T("Could not read process basic information!\n"));
PRTL_USER_PROCESS_PARAMETERS rtlUserProcParamsAddress;
CHECK(ReadProcessMemory(hProcess.get(),
&(pbi.PebBaseAddress->ProcessParameters),
&rtlUserProcParamsAddress, sizeof(rtlUserProcParamsAddress), NULL),
_T("Could not read the address of ProcessParameters!\n"));
UNICODE_STRING commandLine;
CHECK(ReadProcessMemory(hProcess.get(),
&(rtlUserProcParamsAddress->CommandLine),
&commandLine, sizeof(commandLine), NULL),
_T("Could not read CommandLine!\n"));
std::vector<WCHAR> commandLineContents(StrLen(&commandLine));
CHECK(ReadProcessMemory(hProcess.get(), commandLine.Buffer,
commandLineContents.data(), commandLine.Length, NULL),
_T("Could not read the command line string!\n"));
fwprintf(stdout, L"%.*s\n", static_cast<int>(commandLineContents.size()), commandLineContents.data());
return ERROR_SUCCESS;
}