conhost: Introduce IOCTL_CONDRV_READ_CONSOLE ioctl.
[wine.git] / programs / taskkill / taskkill.c
blob600bab14fde49a65d0c796629b71e33221280497
1 /*
2 * Task termination utility
4 * Copyright 2008 Andrew Riedi
5 * Copyright 2010 Andrew Nguyen
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.
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.
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
22 #include <stdlib.h>
23 #include <windows.h>
24 #include <psapi.h>
25 #include <wine/debug.h>
27 #include "taskkill.h"
29 WINE_DEFAULT_DEBUG_CHANNEL(taskkill);
31 static BOOL force_termination = FALSE;
33 static WCHAR **task_list;
34 static unsigned int task_count;
36 struct pid_close_info
38 DWORD pid;
39 BOOL found;
42 static int taskkill_vprintfW(const WCHAR *msg, __ms_va_list va_args)
44 int wlen;
45 DWORD count, ret;
46 WCHAR msg_buffer[8192];
48 wlen = FormatMessageW(FORMAT_MESSAGE_FROM_STRING, msg, 0, 0, msg_buffer,
49 ARRAY_SIZE(msg_buffer), &va_args);
51 ret = WriteConsoleW(GetStdHandle(STD_OUTPUT_HANDLE), msg_buffer, wlen, &count, NULL);
52 if (!ret)
54 DWORD len;
55 char *msgA;
57 /* On Windows WriteConsoleW() fails if the output is redirected. So fall
58 * back to WriteFile(), assuming the console encoding is still the right
59 * one in that case.
61 len = WideCharToMultiByte(GetConsoleOutputCP(), 0, msg_buffer, wlen,
62 NULL, 0, NULL, NULL);
63 msgA = HeapAlloc(GetProcessHeap(), 0, len);
64 if (!msgA)
65 return 0;
67 WideCharToMultiByte(GetConsoleOutputCP(), 0, msg_buffer, wlen, msgA, len,
68 NULL, NULL);
69 WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), msgA, len, &count, FALSE);
70 HeapFree(GetProcessHeap(), 0, msgA);
73 return count;
76 static int WINAPIV taskkill_printfW(const WCHAR *msg, ...)
78 __ms_va_list va_args;
79 int len;
81 __ms_va_start(va_args, msg);
82 len = taskkill_vprintfW(msg, va_args);
83 __ms_va_end(va_args);
85 return len;
88 static int WINAPIV taskkill_message_printfW(int msg, ...)
90 __ms_va_list va_args;
91 WCHAR msg_buffer[8192];
92 int len;
94 LoadStringW(GetModuleHandleW(NULL), msg, msg_buffer, ARRAY_SIZE(msg_buffer));
96 __ms_va_start(va_args, msg);
97 len = taskkill_vprintfW(msg_buffer, va_args);
98 __ms_va_end(va_args);
100 return len;
103 static int taskkill_message(int msg)
105 static const WCHAR formatW[] = {'%','1',0};
106 WCHAR msg_buffer[8192];
108 LoadStringW(GetModuleHandleW(NULL), msg, msg_buffer, ARRAY_SIZE(msg_buffer));
110 return taskkill_printfW(formatW, msg_buffer);
113 /* Post WM_CLOSE to all top-level windows belonging to the process with specified PID. */
114 static BOOL CALLBACK pid_enum_proc(HWND hwnd, LPARAM lParam)
116 struct pid_close_info *info = (struct pid_close_info *)lParam;
117 DWORD hwnd_pid;
119 GetWindowThreadProcessId(hwnd, &hwnd_pid);
121 if (hwnd_pid == info->pid)
123 PostMessageW(hwnd, WM_CLOSE, 0, 0);
124 info->found = TRUE;
127 return TRUE;
130 static DWORD *enumerate_processes(DWORD *list_count)
132 DWORD *pid_list, alloc_bytes = 1024 * sizeof(*pid_list), needed_bytes;
134 pid_list = HeapAlloc(GetProcessHeap(), 0, alloc_bytes);
135 if (!pid_list)
136 return NULL;
138 for (;;)
140 DWORD *realloc_list;
142 if (!EnumProcesses(pid_list, alloc_bytes, &needed_bytes))
144 HeapFree(GetProcessHeap(), 0, pid_list);
145 return NULL;
148 /* EnumProcesses can't signal an insufficient buffer condition, so the
149 * only way to possibly determine whether a larger buffer is required
150 * is to see whether the written number of bytes is the same as the
151 * buffer size. If so, the buffer will be reallocated to twice the
152 * size. */
153 if (alloc_bytes != needed_bytes)
154 break;
156 alloc_bytes *= 2;
157 realloc_list = HeapReAlloc(GetProcessHeap(), 0, pid_list, alloc_bytes);
158 if (!realloc_list)
160 HeapFree(GetProcessHeap(), 0, pid_list);
161 return NULL;
163 pid_list = realloc_list;
166 *list_count = needed_bytes / sizeof(*pid_list);
167 return pid_list;
170 static BOOL get_process_name_from_pid(DWORD pid, WCHAR *buf, DWORD chars)
172 HANDLE process;
173 HMODULE module;
174 DWORD required_size;
176 process = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, pid);
177 if (!process)
178 return FALSE;
180 if (!EnumProcessModules(process, &module, sizeof(module), &required_size))
182 CloseHandle(process);
183 return FALSE;
186 if (!GetModuleBaseNameW(process, module, buf, chars))
188 CloseHandle(process);
189 return FALSE;
192 CloseHandle(process);
193 return TRUE;
196 /* The implemented task enumeration and termination behavior does not
197 * exactly match native behavior. On Windows:
199 * In the case of terminating by process name, specifying a particular
200 * process name more times than the number of running instances causes
201 * all instances to be terminated, but termination failure messages to
202 * be printed as many times as the difference between the specification
203 * quantity and the number of running instances.
205 * Successful terminations are all listed first in order, with failing
206 * terminations being listed at the end.
208 * A PID of zero causes taskkill to warn about the inability to terminate
209 * system processes. */
210 static int send_close_messages(void)
212 DWORD *pid_list, pid_list_size;
213 DWORD self_pid = GetCurrentProcessId();
214 unsigned int i;
215 int status_code = 0;
217 pid_list = enumerate_processes(&pid_list_size);
218 if (!pid_list)
220 taskkill_message(STRING_ENUM_FAILED);
221 return 1;
224 for (i = 0; i < task_count; i++)
226 WCHAR *p = task_list[i];
227 BOOL is_numeric = TRUE;
229 /* Determine whether the string is not numeric. */
230 while (*p)
232 if (!iswdigit(*p++))
234 is_numeric = FALSE;
235 break;
239 if (is_numeric)
241 DWORD pid = wcstol(task_list[i], NULL, 10);
242 struct pid_close_info info = { pid };
244 if (pid == self_pid)
246 taskkill_message(STRING_SELF_TERMINATION);
247 status_code = 1;
248 continue;
251 EnumWindows(pid_enum_proc, (LPARAM)&info);
252 if (info.found)
253 taskkill_message_printfW(STRING_CLOSE_PID_SEARCH, pid);
254 else
256 taskkill_message_printfW(STRING_SEARCH_FAILED, task_list[i]);
257 status_code = 128;
260 else
262 DWORD index;
263 BOOL found_process = FALSE;
265 for (index = 0; index < pid_list_size; index++)
267 WCHAR process_name[MAX_PATH];
269 if (get_process_name_from_pid(pid_list[index], process_name, MAX_PATH) &&
270 !wcsicmp(process_name, task_list[i]))
272 struct pid_close_info info = { pid_list[index] };
274 found_process = TRUE;
275 if (pid_list[index] == self_pid)
277 taskkill_message(STRING_SELF_TERMINATION);
278 status_code = 1;
279 continue;
282 EnumWindows(pid_enum_proc, (LPARAM)&info);
283 taskkill_message_printfW(STRING_CLOSE_PROC_SRCH, process_name, pid_list[index]);
287 if (!found_process)
289 taskkill_message_printfW(STRING_SEARCH_FAILED, task_list[i]);
290 status_code = 128;
295 HeapFree(GetProcessHeap(), 0, pid_list);
296 return status_code;
299 static int terminate_processes(void)
301 DWORD *pid_list, pid_list_size;
302 DWORD self_pid = GetCurrentProcessId();
303 unsigned int i;
304 int status_code = 0;
306 pid_list = enumerate_processes(&pid_list_size);
307 if (!pid_list)
309 taskkill_message(STRING_ENUM_FAILED);
310 return 1;
313 for (i = 0; i < task_count; i++)
315 WCHAR *p = task_list[i];
316 BOOL is_numeric = TRUE;
318 /* Determine whether the string is not numeric. */
319 while (*p)
321 if (!iswdigit(*p++))
323 is_numeric = FALSE;
324 break;
328 if (is_numeric)
330 DWORD pid = wcstol(task_list[i], NULL, 10);
331 HANDLE process;
333 if (pid == self_pid)
335 taskkill_message(STRING_SELF_TERMINATION);
336 status_code = 1;
337 continue;
340 process = OpenProcess(PROCESS_TERMINATE, FALSE, pid);
341 if (!process)
343 taskkill_message_printfW(STRING_SEARCH_FAILED, task_list[i]);
344 status_code = 128;
345 continue;
348 if (!TerminateProcess(process, 0))
350 taskkill_message_printfW(STRING_TERMINATE_FAILED, task_list[i]);
351 status_code = 1;
352 CloseHandle(process);
353 continue;
356 taskkill_message_printfW(STRING_TERM_PID_SEARCH, pid);
357 CloseHandle(process);
359 else
361 DWORD index;
362 BOOL found_process = FALSE;
364 for (index = 0; index < pid_list_size; index++)
366 WCHAR process_name[MAX_PATH];
368 if (get_process_name_from_pid(pid_list[index], process_name, MAX_PATH) &&
369 !wcsicmp(process_name, task_list[i]))
371 HANDLE process;
373 if (pid_list[index] == self_pid)
375 taskkill_message(STRING_SELF_TERMINATION);
376 status_code = 1;
377 continue;
380 process = OpenProcess(PROCESS_TERMINATE, FALSE, pid_list[index]);
381 if (!process)
383 taskkill_message_printfW(STRING_SEARCH_FAILED, task_list[i]);
384 status_code = 128;
385 continue;
388 if (!TerminateProcess(process, 0))
390 taskkill_message_printfW(STRING_TERMINATE_FAILED, task_list[i]);
391 status_code = 1;
392 CloseHandle(process);
393 continue;
396 found_process = TRUE;
397 taskkill_message_printfW(STRING_TERM_PROC_SEARCH, task_list[i], pid_list[index]);
398 CloseHandle(process);
402 if (!found_process)
404 taskkill_message_printfW(STRING_SEARCH_FAILED, task_list[i]);
405 status_code = 128;
410 HeapFree(GetProcessHeap(), 0, pid_list);
411 return status_code;
414 static BOOL add_to_task_list(WCHAR *name)
416 static unsigned int list_size = 16;
418 if (!task_list)
420 task_list = HeapAlloc(GetProcessHeap(), 0,
421 list_size * sizeof(*task_list));
422 if (!task_list)
423 return FALSE;
425 else if (task_count == list_size)
427 void *realloc_list;
429 list_size *= 2;
430 realloc_list = HeapReAlloc(GetProcessHeap(), 0, task_list,
431 list_size * sizeof(*task_list));
432 if (!realloc_list)
433 return FALSE;
435 task_list = realloc_list;
438 task_list[task_count++] = name;
439 return TRUE;
442 /* FIXME Argument processing does not match behavior observed on Windows.
443 * Stringent argument counting and processing is performed, and unrecognized
444 * options are detected as parameters when placed after options that accept one. */
445 static BOOL process_arguments(int argc, WCHAR *argv[])
447 static const WCHAR opForceTerminate[] = {'f',0};
448 static const WCHAR opImage[] = {'i','m',0};
449 static const WCHAR opPID[] = {'p','i','d',0};
450 static const WCHAR opHelp[] = {'?',0};
451 static const WCHAR opTerminateChildren[] = {'t',0};
453 if (argc > 1)
455 int i;
456 WCHAR *argdata;
457 BOOL has_im = FALSE, has_pid = FALSE;
459 /* Only the lone help option is recognized. */
460 if (argc == 2)
462 argdata = argv[1];
463 if ((*argdata == '/' || *argdata == '-') && !lstrcmpW(opHelp, argdata + 1))
465 taskkill_message(STRING_USAGE);
466 exit(0);
470 for (i = 1; i < argc; i++)
472 BOOL got_im = FALSE, got_pid = FALSE;
474 argdata = argv[i];
475 if (*argdata != '/' && *argdata != '-')
476 goto invalid;
477 argdata++;
479 if (!wcsicmp(opTerminateChildren, argdata))
480 WINE_FIXME("argument T not supported\n");
481 if (!wcsicmp(opForceTerminate, argdata))
482 force_termination = TRUE;
483 /* Options /IM and /PID appear to behave identically, except for
484 * the fact that they cannot be specified at the same time. */
485 else if ((got_im = !wcsicmp(opImage, argdata)) ||
486 (got_pid = !wcsicmp(opPID, argdata)))
488 if (!argv[i + 1])
490 taskkill_message_printfW(STRING_MISSING_PARAM, argv[i]);
491 taskkill_message(STRING_USAGE);
492 return FALSE;
495 if (got_im) has_im = TRUE;
496 if (got_pid) has_pid = TRUE;
498 if (has_im && has_pid)
500 taskkill_message(STRING_MUTUAL_EXCLUSIVE);
501 taskkill_message(STRING_USAGE);
502 return FALSE;
505 if (!add_to_task_list(argv[i + 1]))
506 return FALSE;
507 i++;
509 else
511 invalid:
512 taskkill_message(STRING_INVALID_OPTION);
513 taskkill_message(STRING_USAGE);
514 return FALSE;
518 else
520 taskkill_message(STRING_MISSING_OPTION);
521 taskkill_message(STRING_USAGE);
522 return FALSE;
525 return TRUE;
528 int __cdecl wmain(int argc, WCHAR *argv[])
530 int status_code = 0;
532 if (!process_arguments(argc, argv))
534 HeapFree(GetProcessHeap(), 0, task_list);
535 return 1;
538 if (force_termination)
539 status_code = terminate_processes();
540 else
541 status_code = send_close_messages();
543 HeapFree(GetProcessHeap(), 0, task_list);
544 return status_code;