[NTOS:IO]
[reactos.git] / reactos / base / applications / cmdutils / taskkill / taskkill.c
1 /*
2 * Task termination utility
3 *
4 * Copyright 2008 Andrew Riedi
5 * Copyright 2010 Andrew Nguyen
6 *
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
11 *
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
16 *
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
20 */
21
22 #include <stdarg.h>
23 #include <windef.h>
24 #include <winbase.h>
25 #include <wincon.h>
26 #include <winuser.h>
27 #include <psapi.h>
28 #include <wine/debug.h>
29 #include <wine/unicode.h>
30
31 #include "taskkill.h"
32
33 WINE_DEFAULT_DEBUG_CHANNEL(taskkill);
34
35 static int force_termination;
36
37 static WCHAR **task_list;
38 static unsigned int task_count;
39
40 struct pid_close_info
41 {
42 DWORD pid;
43 BOOL found;
44 };
45
46 static int taskkill_vprintfW(const WCHAR *msg, __ms_va_list va_args)
47 {
48 int wlen;
49 DWORD count, ret;
50 WCHAR msg_buffer[8192];
51
52 wlen = FormatMessageW(FORMAT_MESSAGE_FROM_STRING, msg, 0, 0, msg_buffer,
53 sizeof(msg_buffer)/sizeof(*msg_buffer), &va_args);
54
55 ret = WriteConsoleW(GetStdHandle(STD_OUTPUT_HANDLE), msg_buffer, wlen, &count, NULL);
56 if (!ret)
57 {
58 DWORD len;
59 char *msgA;
60
61 /* On Windows WriteConsoleW() fails if the output is redirected. So fall
62 * back to WriteFile(), assuming the console encoding is still the right
63 * one in that case.
64 */
65 len = WideCharToMultiByte(GetConsoleOutputCP(), 0, msg_buffer, wlen,
66 NULL, 0, NULL, NULL);
67 msgA = HeapAlloc(GetProcessHeap(), 0, len);
68 if (!msgA)
69 return 0;
70
71 WideCharToMultiByte(GetConsoleOutputCP(), 0, msg_buffer, wlen, msgA, len,
72 NULL, NULL);
73 WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), msgA, len, &count, FALSE);
74 HeapFree(GetProcessHeap(), 0, msgA);
75 }
76
77 return count;
78 }
79
80 static int CDECL taskkill_printfW(const WCHAR *msg, ...)
81 {
82 __ms_va_list va_args;
83 int len;
84
85 __ms_va_start(va_args, msg);
86 len = taskkill_vprintfW(msg, va_args);
87 __ms_va_end(va_args);
88
89 return len;
90 }
91
92 static int CDECL taskkill_message_printfW(int msg, ...)
93 {
94 __ms_va_list va_args;
95 WCHAR msg_buffer[8192];
96 int len;
97
98 LoadStringW(GetModuleHandleW(NULL), msg, msg_buffer,
99 sizeof(msg_buffer)/sizeof(WCHAR));
100
101 __ms_va_start(va_args, msg);
102 len = taskkill_vprintfW(msg_buffer, va_args);
103 __ms_va_end(va_args);
104
105 return len;
106 }
107
108 static int taskkill_message(int msg)
109 {
110 static const WCHAR formatW[] = {'%','1',0};
111 WCHAR msg_buffer[8192];
112
113 LoadStringW(GetModuleHandleW(NULL), msg, msg_buffer,
114 sizeof(msg_buffer)/sizeof(WCHAR));
115
116 return taskkill_printfW(formatW, msg_buffer);
117 }
118
119 /* Post WM_CLOSE to all top-level windows belonging to the process with specified PID. */
120 static BOOL CALLBACK pid_enum_proc(HWND hwnd, LPARAM lParam)
121 {
122 struct pid_close_info *info = (struct pid_close_info *)lParam;
123 DWORD hwnd_pid;
124
125 GetWindowThreadProcessId(hwnd, &hwnd_pid);
126
127 if (hwnd_pid == info->pid)
128 {
129 PostMessageW(hwnd, WM_CLOSE, 0, 0);
130 info->found = TRUE;
131 }
132
133 return TRUE;
134 }
135
136 static DWORD *enumerate_processes(DWORD *list_count)
137 {
138 DWORD *pid_list, alloc_bytes = 1024 * sizeof(*pid_list), needed_bytes;
139
140 pid_list = HeapAlloc(GetProcessHeap(), 0, alloc_bytes);
141 if (!pid_list)
142 return NULL;
143
144 for (;;)
145 {
146 DWORD *realloc_list;
147
148 if (!EnumProcesses(pid_list, alloc_bytes, &needed_bytes))
149 {
150 HeapFree(GetProcessHeap(), 0, pid_list);
151 return NULL;
152 }
153
154 /* EnumProcesses can't signal an insufficient buffer condition, so the
155 * only way to possibly determine whether a larger buffer is required
156 * is to see whether the written number of bytes is the same as the
157 * buffer size. If so, the buffer will be reallocated to twice the
158 * size. */
159 if (alloc_bytes != needed_bytes)
160 break;
161
162 alloc_bytes *= 2;
163 realloc_list = HeapReAlloc(GetProcessHeap(), 0, pid_list, alloc_bytes);
164 if (!realloc_list)
165 {
166 HeapFree(GetProcessHeap(), 0, pid_list);
167 return NULL;
168 }
169 pid_list = realloc_list;
170 }
171
172 *list_count = needed_bytes / sizeof(*pid_list);
173 return pid_list;
174 }
175
176 static BOOL get_process_name_from_pid(DWORD pid, WCHAR *buf, DWORD chars)
177 {
178 HANDLE process;
179 HMODULE module;
180 DWORD required_size;
181
182 process = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, pid);
183 if (!process)
184 return FALSE;
185
186 if (!EnumProcessModules(process, &module, sizeof(module), &required_size))
187 {
188 CloseHandle(process);
189 return FALSE;
190 }
191
192 if (!GetModuleBaseNameW(process, module, buf, chars))
193 {
194 CloseHandle(process);
195 return FALSE;
196 }
197
198 CloseHandle(process);
199 return TRUE;
200 }
201
202 /* The implemented task enumeration and termination behavior does not
203 * exactly match native behavior. On Windows:
204 *
205 * In the case of terminating by process name, specifying a particular
206 * process name more times than the number of running instances causes
207 * all instances to be terminated, but termination failure messages to
208 * be printed as many times as the difference between the specification
209 * quantity and the number of running instances.
210 *
211 * Successful terminations are all listed first in order, with failing
212 * terminations being listed at the end.
213 *
214 * A PID of zero causes taskkill to warn about the inability to terminate
215 * system processes. */
216 static int send_close_messages(void)
217 {
218 DWORD *pid_list, pid_list_size;
219 DWORD self_pid = GetCurrentProcessId();
220 unsigned int i;
221 int status_code = 0;
222
223 pid_list = enumerate_processes(&pid_list_size);
224 if (!pid_list)
225 {
226 taskkill_message(STRING_ENUM_FAILED);
227 return 1;
228 }
229
230 for (i = 0; i < task_count; i++)
231 {
232 WCHAR *p = task_list[i];
233 BOOL is_numeric = TRUE;
234
235 /* Determine whether the string is not numeric. */
236 while (*p)
237 {
238 if (!isdigitW(*p++))
239 {
240 is_numeric = FALSE;
241 break;
242 }
243 }
244
245 if (is_numeric)
246 {
247 DWORD pid = atoiW(task_list[i]);
248 struct pid_close_info info = { pid };
249
250 if (pid == self_pid)
251 {
252 taskkill_message(STRING_SELF_TERMINATION);
253 status_code = 1;
254 continue;
255 }
256
257 EnumWindows(pid_enum_proc, (LPARAM)&info);
258 if (info.found)
259 taskkill_message_printfW(STRING_CLOSE_PID_SEARCH, pid);
260 else
261 {
262 taskkill_message_printfW(STRING_SEARCH_FAILED, task_list[i]);
263 status_code = 128;
264 }
265 }
266 else
267 {
268 DWORD index;
269 BOOL found_process = FALSE;
270
271 for (index = 0; index < pid_list_size; index++)
272 {
273 WCHAR process_name[MAX_PATH];
274
275 if (get_process_name_from_pid(pid_list[index], process_name, MAX_PATH) &&
276 !strcmpiW(process_name, task_list[i]))
277 {
278 struct pid_close_info info = { pid_list[index] };
279
280 found_process = TRUE;
281 if (pid_list[index] == self_pid)
282 {
283 taskkill_message(STRING_SELF_TERMINATION);
284 status_code = 1;
285 continue;
286 }
287
288 EnumWindows(pid_enum_proc, (LPARAM)&info);
289 taskkill_message_printfW(STRING_CLOSE_PROC_SRCH, process_name, pid_list[index]);
290 }
291 }
292
293 if (!found_process)
294 {
295 taskkill_message_printfW(STRING_SEARCH_FAILED, task_list[i]);
296 status_code = 128;
297 }
298 }
299 }
300
301 HeapFree(GetProcessHeap(), 0, pid_list);
302 return status_code;
303 }
304
305 static int terminate_processes(void)
306 {
307 DWORD *pid_list, pid_list_size;
308 DWORD self_pid = GetCurrentProcessId();
309 unsigned int i;
310 int status_code = 0;
311
312 pid_list = enumerate_processes(&pid_list_size);
313 if (!pid_list)
314 {
315 taskkill_message(STRING_ENUM_FAILED);
316 return 1;
317 }
318
319 for (i = 0; i < task_count; i++)
320 {
321 WCHAR *p = task_list[i];
322 BOOL is_numeric = TRUE;
323
324 /* Determine whether the string is not numeric. */
325 while (*p)
326 {
327 if (!isdigitW(*p++))
328 {
329 is_numeric = FALSE;
330 break;
331 }
332 }
333
334 if (is_numeric)
335 {
336 DWORD pid = atoiW(task_list[i]);
337 HANDLE process;
338
339 if (pid == self_pid)
340 {
341 taskkill_message(STRING_SELF_TERMINATION);
342 status_code = 1;
343 continue;
344 }
345
346 process = OpenProcess(PROCESS_TERMINATE, FALSE, pid);
347 if (!process)
348 {
349 taskkill_message_printfW(STRING_SEARCH_FAILED, task_list[i]);
350 status_code = 128;
351 continue;
352 }
353
354 if (!TerminateProcess(process, 0))
355 {
356 taskkill_message_printfW(STRING_TERMINATE_FAILED, task_list[i]);
357 status_code = 1;
358 CloseHandle(process);
359 continue;
360 }
361
362 taskkill_message_printfW(STRING_TERM_PID_SEARCH, pid);
363 CloseHandle(process);
364 }
365 else
366 {
367 DWORD index;
368 BOOL found_process = FALSE;
369
370 for (index = 0; index < pid_list_size; index++)
371 {
372 WCHAR process_name[MAX_PATH];
373
374 if (get_process_name_from_pid(pid_list[index], process_name, MAX_PATH) &&
375 !strcmpiW(process_name, task_list[i]))
376 {
377 HANDLE process;
378
379 if (pid_list[index] == self_pid)
380 {
381 taskkill_message(STRING_SELF_TERMINATION);
382 status_code = 1;
383 continue;
384 }
385
386 process = OpenProcess(PROCESS_TERMINATE, FALSE, pid_list[index]);
387 if (!process)
388 {
389 taskkill_message_printfW(STRING_SEARCH_FAILED, task_list[i]);
390 status_code = 128;
391 continue;
392 }
393
394 if (!TerminateProcess(process, 0))
395 {
396 taskkill_message_printfW(STRING_TERMINATE_FAILED, task_list[i]);
397 status_code = 1;
398 CloseHandle(process);
399 continue;
400 }
401
402 found_process = TRUE;
403 taskkill_message_printfW(STRING_TERM_PROC_SEARCH, task_list[i], pid_list[index]);
404 CloseHandle(process);
405 }
406 }
407
408 if (!found_process)
409 {
410 taskkill_message_printfW(STRING_SEARCH_FAILED, task_list[i]);
411 status_code = 128;
412 }
413 }
414 }
415
416 HeapFree(GetProcessHeap(), 0, pid_list);
417 return status_code;
418 }
419
420 static BOOL add_to_task_list(WCHAR *name)
421 {
422 static unsigned int list_size = 16;
423
424 if (!task_list)
425 {
426 task_list = HeapAlloc(GetProcessHeap(), 0,
427 list_size * sizeof(*task_list));
428 if (!task_list)
429 return FALSE;
430 }
431 else if (task_count == list_size)
432 {
433 void *realloc_list;
434
435 list_size *= 2;
436 realloc_list = HeapReAlloc(GetProcessHeap(), 0, task_list,
437 list_size * sizeof(*task_list));
438 if (!realloc_list)
439 return FALSE;
440
441 task_list = realloc_list;
442 }
443
444 task_list[task_count++] = name;
445 return TRUE;
446 }
447
448 /* FIXME Argument processing does not match behavior observed on Windows.
449 * Stringent argument counting and processing is performed, and unrecognized
450 * options are detected as parameters when placed after options that accept one. */
451 static BOOL process_arguments(int argc, WCHAR *argv[])
452 {
453 static const WCHAR slashForceTerminate[] = {'/','f',0};
454 static const WCHAR slashImage[] = {'/','i','m',0};
455 static const WCHAR slashPID[] = {'/','p','i','d',0};
456 static const WCHAR slashHelp[] = {'/','?',0};
457 static const WCHAR slashTerminateChildren[] = {'/','t',0};
458
459 if (argc > 1)
460 {
461 int i;
462 BOOL has_im = 0, has_pid = 0;
463
464 /* Only the lone help option is recognized. */
465 if (argc == 2 && !strcmpW(slashHelp, argv[1]))
466 {
467 taskkill_message(STRING_USAGE);
468 exit(0);
469 }
470
471 for (i = 1; i < argc; i++)
472 {
473 int got_im = 0, got_pid = 0;
474
475 if (!strcmpiW(slashTerminateChildren, argv[i]))
476 WINE_FIXME("/T not supported\n");
477 if (!strcmpiW(slashForceTerminate, argv[i]))
478 force_termination = 1;
479 /* Options /IM and /PID appear to behave identically, except for
480 * the fact that they cannot be specified at the same time. */
481 else if ((got_im = !strcmpiW(slashImage, argv[i])) ||
482 (got_pid = !strcmpiW(slashPID, argv[i])))
483 {
484 if (!argv[i + 1])
485 {
486 taskkill_message_printfW(STRING_MISSING_PARAM, argv[i]);
487 taskkill_message(STRING_USAGE);
488 return FALSE;
489 }
490
491 if (got_im) has_im = 1;
492 if (got_pid) has_pid = 1;
493
494 if (has_im && has_pid)
495 {
496 taskkill_message(STRING_MUTUAL_EXCLUSIVE);
497 taskkill_message(STRING_USAGE);
498 return FALSE;
499 }
500
501 if (!add_to_task_list(argv[i + 1]))
502 return FALSE;
503 i++;
504 }
505 else
506 {
507 taskkill_message(STRING_INVALID_OPTION);
508 taskkill_message(STRING_USAGE);
509 return FALSE;
510 }
511 }
512 }
513 else
514 {
515 taskkill_message(STRING_MISSING_OPTION);
516 taskkill_message(STRING_USAGE);
517 return FALSE;
518 }
519
520 return TRUE;
521 }
522
523 int wmain(int argc, WCHAR *argv[])
524 {
525 int status_code = 0;
526
527 if (!process_arguments(argc, argv))
528 {
529 HeapFree(GetProcessHeap(), 0, task_list);
530 return 1;
531 }
532
533 if (force_termination)
534 status_code = terminate_processes();
535 else
536 status_code = send_close_messages();
537
538 HeapFree(GetProcessHeap(), 0, task_list);
539 return status_code;
540 }