]> git.sven.stormbind.net Git - sven/jattach.git/blob - src/windows/jattach.c
releasing package jattach version 2.2-1
[sven/jattach.git] / src / windows / jattach.c
1 /*
2  * Copyright 2016 Andrei Pangin
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <stdio.h>
18 #include <stdlib.h>
19 #include <windows.h>
20 #include <sddl.h>
21
22 typedef HMODULE (WINAPI *GetModuleHandle_t)(LPCTSTR lpModuleName);
23 typedef FARPROC (WINAPI *GetProcAddress_t)(HMODULE hModule, LPCSTR lpProcName);
24 typedef int (__stdcall *JVM_EnqueueOperation_t)(char* cmd, char* arg0, char* arg1, char* arg2, char* pipename);
25
26 typedef struct {
27     GetModuleHandle_t GetModuleHandleA;
28     GetProcAddress_t GetProcAddress;
29     char strJvm[32];
30     char strEnqueue[32];
31     char pipeName[MAX_PATH];
32     char args[4][MAX_PATH];
33 } CallData;
34
35
36 #pragma check_stack(off)
37
38 // This code is executed in remote JVM process; be careful with memory it accesses
39 static DWORD WINAPI remote_thread_entry(LPVOID param) {
40     CallData* data = (CallData*)param;
41
42     HMODULE libJvm = data->GetModuleHandleA(data->strJvm);
43     if (libJvm == NULL) {
44         return 1001;
45     }
46
47     JVM_EnqueueOperation_t JVM_EnqueueOperation = (JVM_EnqueueOperation_t)data->GetProcAddress(libJvm, data->strEnqueue + 1);
48     if (JVM_EnqueueOperation == NULL) {
49         // Try alternative name: _JVM_EnqueueOperation@20
50         data->strEnqueue[21] = '@';
51         data->strEnqueue[22] = '2';
52         data->strEnqueue[23] = '0';
53         data->strEnqueue[24] = 0;
54
55         JVM_EnqueueOperation = (JVM_EnqueueOperation_t)data->GetProcAddress(libJvm, data->strEnqueue);
56         if (JVM_EnqueueOperation == NULL) {
57             return 1002;
58         }
59     }
60
61     return (DWORD)JVM_EnqueueOperation(data->args[0], data->args[1], data->args[2], data->args[3], data->pipeName);
62 }
63
64 static VOID WINAPI remote_thread_entry_end() {
65 }
66
67 #pragma check_stack
68
69
70 // Allocate executable memory in remote process
71 static LPTHREAD_START_ROUTINE allocate_code(HANDLE hProcess) {
72     SIZE_T codeSize = (SIZE_T)remote_thread_entry_end - (SIZE_T)remote_thread_entry;
73     LPVOID code = VirtualAllocEx(hProcess, NULL, codeSize, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
74     if (code != NULL) {
75         WriteProcessMemory(hProcess, code, remote_thread_entry, codeSize, NULL);
76     }
77     return (LPTHREAD_START_ROUTINE)code;
78 }
79
80 // Allocate memory for CallData in remote process
81 static LPVOID allocate_data(HANDLE hProcess, char* pipeName, int argc, char** argv) {
82     CallData data;
83     data.GetModuleHandleA = GetModuleHandleA;
84     data.GetProcAddress = GetProcAddress;
85     strcpy(data.strJvm, "jvm");
86     strcpy(data.strEnqueue, "_JVM_EnqueueOperation");
87     strcpy(data.pipeName, pipeName);
88
89     int i;
90     for (i = 0; i < 4; i++) {
91         strcpy(data.args[i], i < argc ? argv[i] : "");
92     }
93
94     LPVOID remoteData = VirtualAllocEx(hProcess, NULL, sizeof(CallData), MEM_COMMIT, PAGE_READWRITE);
95     if (remoteData != NULL) {
96         WriteProcessMemory(hProcess, remoteData, &data, sizeof(data), NULL);
97     }
98     return remoteData;
99 }
100
101 static void print_error(const char* msg, DWORD code) {
102     printf("%s (error code = %d)\n", msg, code);
103 }
104
105 // If the process is owned by another user, request SeDebugPrivilege to open it.
106 // Debug privileges are typically granted to Administrators.
107 static int enable_debug_privileges() {
108     HANDLE hToken;
109     if (!OpenThreadToken(GetCurrentThread(), TOKEN_ADJUST_PRIVILEGES, FALSE, &hToken)) {
110         if (!ImpersonateSelf(SecurityImpersonation) ||
111             !OpenThreadToken(GetCurrentThread(), TOKEN_ADJUST_PRIVILEGES, FALSE, &hToken)) {
112             return 0;
113         }
114     }
115
116     LUID luid;
117     if (!LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &luid)) {
118         return 0;
119     }
120
121     TOKEN_PRIVILEGES tp;
122     tp.PrivilegeCount = 1;
123     tp.Privileges[0].Luid = luid;
124     tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
125
126     BOOL success = AdjustTokenPrivileges(hToken, FALSE, &tp, sizeof(tp), NULL, NULL);
127     CloseHandle(hToken);
128     return success ? 1 : 0;
129 }
130
131 // Fail if attaching 64-bit jattach to 32-bit JVM or vice versa
132 static int check_bitness(HANDLE hProcess) {
133 #ifdef _WIN64
134     BOOL targetWow64 = FALSE;
135     if (IsWow64Process(hProcess, &targetWow64) && targetWow64) {
136         printf("Cannot attach 64-bit process to 32-bit JVM\n");
137         return 0;
138     }
139 #else
140     BOOL thisWow64 = FALSE;
141     BOOL targetWow64 = FALSE;
142     if (IsWow64Process(GetCurrentProcess(), &thisWow64) && IsWow64Process(hProcess, &targetWow64)) {
143         if (thisWow64 != targetWow64)  {
144             printf("Cannot attach 32-bit process to 64-bit JVM\n");
145             return 0;
146         }
147     }
148 #endif
149     return 1;
150 }
151
152 // The idea of Dynamic Attach on Windows is to inject a thread into remote JVM
153 // that calls JVM_EnqueueOperation() function exported by HotSpot DLL
154 static int inject_thread(int pid, char* pipeName, int argc, char** argv) {
155     HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, (DWORD)pid);
156     if (hProcess == NULL && GetLastError() == ERROR_ACCESS_DENIED) {
157         if (!enable_debug_privileges()) {
158             print_error("Not enough privileges", GetLastError());
159             return 0;
160         }
161         hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, (DWORD)pid);
162     }
163     if (hProcess == NULL) {
164         print_error("Could not open process", GetLastError());
165         return 0;
166     }
167
168     if (!check_bitness(hProcess)) {
169         CloseHandle(hProcess);
170         return 0;
171     }
172
173     LPTHREAD_START_ROUTINE code = allocate_code(hProcess);
174     LPVOID data = code != NULL ? allocate_data(hProcess, pipeName, argc, argv) : NULL;
175     if (data == NULL) {
176         print_error("Could not allocate memory in target process", GetLastError());
177         CloseHandle(hProcess);
178         return 0;
179     }
180
181     int success = 1;
182     HANDLE hThread = CreateRemoteThread(hProcess, NULL, 0, code, data, 0, NULL);
183     if (hThread == NULL) {
184         print_error("Could not create remote thread", GetLastError());
185         success = 0;
186     } else {
187         printf("Connected to remote process\n");
188         WaitForSingleObject(hThread, INFINITE);
189         DWORD exitCode;
190         GetExitCodeThread(hThread, &exitCode);
191         if (exitCode != 0) {
192             print_error("Attach is not supported by the target process", exitCode);
193             success = 0;
194         }
195         CloseHandle(hThread);
196     }
197
198     VirtualFreeEx(hProcess, code, 0, MEM_RELEASE);
199     VirtualFreeEx(hProcess, data, 0, MEM_RELEASE);
200     CloseHandle(hProcess);
201
202     return success;
203 }
204
205 // JVM response is read from the pipe and mirrored to stdout
206 static int read_response(HANDLE hPipe) {
207     ConnectNamedPipe(hPipe, NULL);
208
209     char buf[8192];
210     DWORD bytesRead;
211     if (!ReadFile(hPipe, buf, sizeof(buf) - 1, &bytesRead, NULL)) {
212         print_error("Error reading response", GetLastError());
213         return 1;
214     }
215
216     // First line of response is the command result code
217     buf[bytesRead] = 0;
218     int result = atoi(buf);
219
220     do {
221         fwrite(buf, 1, bytesRead, stdout);
222     } while (ReadFile(hPipe, buf, sizeof(buf), &bytesRead, NULL));
223
224     return result;
225 }
226
227 int jattach(int pid, int argc, char** argv) {
228     // When attaching as an Administrator, make sure the target process can connect to our pipe,
229     // i.e. allow read-write access to everyone. For the complete format description, see
230     // https://docs.microsoft.com/en-us/windows/win32/secauthz/security-descriptor-string-format
231     SECURITY_ATTRIBUTES sec = {sizeof(SECURITY_ATTRIBUTES), NULL, FALSE};
232     ConvertStringSecurityDescriptorToSecurityDescriptor("D:(A;;GRGW;;;WD)", SDDL_REVISION_1,
233                                                         &sec.lpSecurityDescriptor, NULL);
234
235     char pipeName[MAX_PATH];
236     sprintf(pipeName, "\\\\.\\pipe\\javatool%d", GetTickCount());
237     HANDLE hPipe = CreateNamedPipe(pipeName, PIPE_ACCESS_INBOUND, PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT,
238                                    1, 4096, 8192, NMPWAIT_USE_DEFAULT_WAIT, &sec);
239     if (hPipe == NULL) {
240         print_error("Could not create pipe", GetLastError());
241         LocalFree(sec.lpSecurityDescriptor);
242         return 1;
243     }
244
245     LocalFree(sec.lpSecurityDescriptor);
246
247     if (!inject_thread(pid, pipeName, argc, argv)) {
248         CloseHandle(hPipe);
249         return 1;
250     }
251
252     printf("Response code = ");
253     fflush(stdout);
254
255     int result = read_response(hPipe);
256     printf("\n");
257     CloseHandle(hPipe);
258
259     return result;
260 }
261
262 #ifdef JATTACH_VERSION
263
264 int main(int argc, char** argv) {
265     if (argc < 3) {
266         printf("jattach " JATTACH_VERSION " built on " __DATE__ "\n"
267                "Copyright 2021 Andrei Pangin\n"
268                "\n"
269                "Usage: jattach <pid> <cmd> [args ...]\n"
270                "\n"
271                "Commands:\n"
272                "    load  threaddump   dumpheap  setflag    properties\n"
273                "    jcmd  inspectheap  datadump  printflag  agentProperties\n"
274                );
275         return 1;
276     }
277
278     int pid = atoi(argv[1]);
279     if (pid <= 0) {
280         fprintf(stderr, "%s is not a valid process ID\n", argv[1]);
281         return 1;
282     }
283
284     return jattach(pid, argc - 2, argv + 2);
285 }
286
287 #endif // JATTACH_VERSION