Release 1.4-rc5.
[wine] / programs / 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 <stdlib.h>
23 #include <windows.h>
24 #include <psapi.h>
25 #include <wine/unicode.h>
26
27 #include "taskkill.h"
28
29 static int force_termination;
30
31 static WCHAR **task_list;
32 static unsigned int task_count;
33
34 struct pid_close_info
35 {
36     DWORD pid;
37     BOOL found;
38 };
39
40 static int taskkill_vprintfW(const WCHAR *msg, __ms_va_list va_args)
41 {
42     int wlen;
43     DWORD count, ret;
44     WCHAR msg_buffer[8192];
45
46     wlen = FormatMessageW(FORMAT_MESSAGE_FROM_STRING, msg, 0, 0, msg_buffer,
47                           sizeof(msg_buffer)/sizeof(*msg_buffer), &va_args);
48
49     ret = WriteConsoleW(GetStdHandle(STD_OUTPUT_HANDLE), msg_buffer, wlen, &count, NULL);
50     if (!ret)
51     {
52         DWORD len;
53         char *msgA;
54
55         /* On Windows WriteConsoleW() fails if the output is redirected. So fall
56          * back to WriteFile(), assuming the console encoding is still the right
57          * one in that case.
58          */
59         len = WideCharToMultiByte(GetConsoleOutputCP(), 0, msg_buffer, wlen,
60             NULL, 0, NULL, NULL);
61         msgA = HeapAlloc(GetProcessHeap(), 0, len);
62         if (!msgA)
63             return 0;
64
65         WideCharToMultiByte(GetConsoleOutputCP(), 0, msg_buffer, wlen, msgA, len,
66             NULL, NULL);
67         WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), msgA, len, &count, FALSE);
68         HeapFree(GetProcessHeap(), 0, msgA);
69     }
70
71     return count;
72 }
73
74 static int CDECL taskkill_printfW(const WCHAR *msg, ...)
75 {
76     __ms_va_list va_args;
77     int len;
78
79     __ms_va_start(va_args, msg);
80     len = taskkill_vprintfW(msg, va_args);
81     __ms_va_end(va_args);
82
83     return len;
84 }
85
86 static int CDECL taskkill_message_printfW(int msg, ...)
87 {
88     __ms_va_list va_args;
89     WCHAR msg_buffer[8192];
90     int len;
91
92     LoadStringW(GetModuleHandleW(NULL), msg, msg_buffer,
93         sizeof(msg_buffer)/sizeof(WCHAR));
94
95     __ms_va_start(va_args, msg);
96     len = taskkill_vprintfW(msg_buffer, va_args);
97     __ms_va_end(va_args);
98
99     return len;
100 }
101
102 static int taskkill_message(int msg)
103 {
104     static const WCHAR formatW[] = {'%','1',0};
105     WCHAR msg_buffer[8192];
106
107     LoadStringW(GetModuleHandleW(NULL), msg, msg_buffer,
108         sizeof(msg_buffer)/sizeof(WCHAR));
109
110     return taskkill_printfW(formatW, msg_buffer);
111 }
112
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)
115 {
116     struct pid_close_info *info = (struct pid_close_info *)lParam;
117     DWORD hwnd_pid;
118
119     GetWindowThreadProcessId(hwnd, &hwnd_pid);
120
121     if (hwnd_pid == info->pid)
122     {
123         PostMessageW(hwnd, WM_CLOSE, 0, 0);
124         info->found = TRUE;
125     }
126
127     return TRUE;
128 }
129
130 static DWORD *enumerate_processes(DWORD *list_count)
131 {
132     DWORD *pid_list, alloc_bytes = 1024 * sizeof(*pid_list), needed_bytes;
133
134     pid_list = HeapAlloc(GetProcessHeap(), 0, alloc_bytes);
135     if (!pid_list)
136         return NULL;
137
138     for (;;)
139     {
140         DWORD *realloc_list;
141
142         if (!EnumProcesses(pid_list, alloc_bytes, &needed_bytes))
143         {
144             HeapFree(GetProcessHeap(), 0, pid_list);
145             return NULL;
146         }
147
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;
155
156         alloc_bytes *= 2;
157         realloc_list = HeapReAlloc(GetProcessHeap(), 0, pid_list, alloc_bytes);
158         if (!realloc_list)
159         {
160             HeapFree(GetProcessHeap(), 0, pid_list);
161             return NULL;
162         }
163         pid_list = realloc_list;
164     }
165
166     *list_count = needed_bytes / sizeof(*pid_list);
167     return pid_list;
168 }
169
170 static BOOL get_process_name_from_pid(DWORD pid, WCHAR *buf, DWORD chars)
171 {
172     HANDLE process;
173     HMODULE module;
174     DWORD required_size;
175
176     process = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, pid);
177     if (!process)
178         return FALSE;
179
180     if (!EnumProcessModules(process, &module, sizeof(module), &required_size))
181     {
182         CloseHandle(process);
183         return FALSE;
184     }
185
186     if (!GetModuleBaseNameW(process, module, buf, chars))
187     {
188         CloseHandle(process);
189         return FALSE;
190     }
191
192     CloseHandle(process);
193     return TRUE;
194 }
195
196 /* The implemented task enumeration and termination behavior does not
197  * exactly match native behavior. On Windows:
198  *
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.
204  *
205  * Successful terminations are all listed first in order, with failing
206  * terminations being listed at the end.
207  *
208  * A PID of zero causes taskkill to warn about the inability to terminate
209  * system processes. */
210 static int send_close_messages(void)
211 {
212     DWORD *pid_list, pid_list_size;
213     DWORD self_pid = GetCurrentProcessId();
214     unsigned int i;
215     int status_code = 0;
216
217     pid_list = enumerate_processes(&pid_list_size);
218     if (!pid_list)
219     {
220         taskkill_message(STRING_ENUM_FAILED);
221         return 1;
222     }
223
224     for (i = 0; i < task_count; i++)
225     {
226         WCHAR *p = task_list[i];
227         BOOL is_numeric = TRUE;
228
229         /* Determine whether the string is not numeric. */
230         while (*p)
231         {
232             if (!isdigitW(*p++))
233             {
234                 is_numeric = FALSE;
235                 break;
236             }
237         }
238
239         if (is_numeric)
240         {
241             DWORD pid = atoiW(task_list[i]);
242             struct pid_close_info info = { pid };
243
244             if (pid == self_pid)
245             {
246                 taskkill_message(STRING_SELF_TERMINATION);
247                 status_code = 1;
248                 continue;
249             }
250
251             EnumWindows(pid_enum_proc, (LPARAM)&info);
252             if (info.found)
253                 taskkill_message_printfW(STRING_CLOSE_PID_SEARCH, pid);
254             else
255             {
256                 taskkill_message_printfW(STRING_SEARCH_FAILED, task_list[i]);
257                 status_code = 128;
258             }
259         }
260         else
261         {
262             DWORD index;
263             BOOL found_process = FALSE;
264
265             for (index = 0; index < pid_list_size; index++)
266             {
267                 WCHAR process_name[MAX_PATH];
268
269                 if (get_process_name_from_pid(pid_list[index], process_name, MAX_PATH) &&
270                     !strcmpiW(process_name, task_list[i]))
271                 {
272                     struct pid_close_info info = { pid_list[index] };
273
274                     found_process = TRUE;
275                     if (pid_list[index] == self_pid)
276                     {
277                         taskkill_message(STRING_SELF_TERMINATION);
278                         status_code = 1;
279                         continue;
280                     }
281
282                     EnumWindows(pid_enum_proc, (LPARAM)&info);
283                     taskkill_message_printfW(STRING_CLOSE_PROC_SRCH, process_name, pid_list[index]);
284                 }
285             }
286
287             if (!found_process)
288             {
289                 taskkill_message_printfW(STRING_SEARCH_FAILED, task_list[i]);
290                 status_code = 128;
291             }
292         }
293     }
294
295     HeapFree(GetProcessHeap(), 0, pid_list);
296     return status_code;
297 }
298
299 static int terminate_processes(void)
300 {
301     DWORD *pid_list, pid_list_size;
302     DWORD self_pid = GetCurrentProcessId();
303     unsigned int i;
304     int status_code = 0;
305
306     pid_list = enumerate_processes(&pid_list_size);
307     if (!pid_list)
308     {
309         taskkill_message(STRING_ENUM_FAILED);
310         return 1;
311     }
312
313     for (i = 0; i < task_count; i++)
314     {
315         WCHAR *p = task_list[i];
316         BOOL is_numeric = TRUE;
317
318         /* Determine whether the string is not numeric. */
319         while (*p)
320         {
321             if (!isdigitW(*p++))
322             {
323                 is_numeric = FALSE;
324                 break;
325             }
326         }
327
328         if (is_numeric)
329         {
330             DWORD pid = atoiW(task_list[i]);
331             HANDLE process;
332
333             if (pid == self_pid)
334             {
335                 taskkill_message(STRING_SELF_TERMINATION);
336                 status_code = 1;
337                 continue;
338             }
339
340             process = OpenProcess(PROCESS_TERMINATE, FALSE, pid);
341             if (!process)
342             {
343                 taskkill_message_printfW(STRING_SEARCH_FAILED, task_list[i]);
344                 status_code = 128;
345                 continue;
346             }
347
348             if (!TerminateProcess(process, 0))
349             {
350                 taskkill_message_printfW(STRING_TERMINATE_FAILED, task_list[i]);
351                 status_code = 1;
352                 CloseHandle(process);
353                 continue;
354             }
355
356             taskkill_message_printfW(STRING_TERM_PID_SEARCH, pid);
357             CloseHandle(process);
358         }
359         else
360         {
361             DWORD index;
362             BOOL found_process = FALSE;
363
364             for (index = 0; index < pid_list_size; index++)
365             {
366                 WCHAR process_name[MAX_PATH];
367
368                 if (get_process_name_from_pid(pid_list[index], process_name, MAX_PATH) &&
369                     !strcmpiW(process_name, task_list[i]))
370                 {
371                     HANDLE process;
372
373                     if (pid_list[index] == self_pid)
374                     {
375                         taskkill_message(STRING_SELF_TERMINATION);
376                         status_code = 1;
377                         continue;
378                     }
379
380                     process = OpenProcess(PROCESS_TERMINATE, FALSE, pid_list[index]);
381                     if (!process)
382                     {
383                         taskkill_message_printfW(STRING_SEARCH_FAILED, task_list[i]);
384                         status_code = 128;
385                         continue;
386                     }
387
388                     if (!TerminateProcess(process, 0))
389                     {
390                         taskkill_message_printfW(STRING_TERMINATE_FAILED, task_list[i]);
391                         status_code = 1;
392                         CloseHandle(process);
393                         continue;
394                     }
395
396                     found_process = TRUE;
397                     taskkill_message_printfW(STRING_TERM_PROC_SEARCH, task_list[i], pid_list[index]);
398                     CloseHandle(process);
399                 }
400             }
401
402             if (!found_process)
403             {
404                 taskkill_message_printfW(STRING_SEARCH_FAILED, task_list[i]);
405                 status_code = 128;
406             }
407         }
408     }
409
410     HeapFree(GetProcessHeap(), 0, pid_list);
411     return status_code;
412 }
413
414 static BOOL add_to_task_list(WCHAR *name)
415 {
416     static unsigned int list_size = 16;
417
418     if (!task_list)
419     {
420         task_list = HeapAlloc(GetProcessHeap(), 0,
421                                    list_size * sizeof(*task_list));
422         if (!task_list)
423             return FALSE;
424     }
425     else if (task_count == list_size)
426     {
427         void *realloc_list;
428
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;
434
435         task_list = realloc_list;
436     }
437
438     task_list[task_count++] = name;
439     return TRUE;
440 }
441
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[])
446 {
447     static const WCHAR slashForceTerminate[] = {'/','f',0};
448     static const WCHAR slashImage[] = {'/','i','m',0};
449     static const WCHAR slashPID[] = {'/','p','i','d',0};
450     static const WCHAR slashHelp[] = {'/','?',0};
451
452     if (argc > 1)
453     {
454         int i;
455         BOOL has_im = 0, has_pid = 0;
456
457         /* Only the lone help option is recognized. */
458         if (argc == 2 && !strcmpW(slashHelp, argv[1]))
459         {
460             taskkill_message(STRING_USAGE);
461             exit(0);
462         }
463
464         for (i = 1; i < argc; i++)
465         {
466             int got_im = 0, got_pid = 0;
467
468             if (!strcmpiW(slashForceTerminate, argv[i]))
469                 force_termination = 1;
470             /* Options /IM and /PID appear to behave identically, except for
471              * the fact that they cannot be specified at the same time. */
472             else if ((got_im = !strcmpiW(slashImage, argv[i])) ||
473                      (got_pid = !strcmpiW(slashPID, argv[i])))
474             {
475                 if (!argv[i + 1])
476                 {
477                     taskkill_message_printfW(STRING_MISSING_PARAM, argv[i]);
478                     taskkill_message(STRING_USAGE);
479                     return FALSE;
480                 }
481
482                 if (got_im) has_im = 1;
483                 if (got_pid) has_pid = 1;
484
485                 if (has_im && has_pid)
486                 {
487                     taskkill_message(STRING_MUTUAL_EXCLUSIVE);
488                     taskkill_message(STRING_USAGE);
489                     return FALSE;
490                 }
491
492                 if (!add_to_task_list(argv[i + 1]))
493                     return FALSE;
494                 i++;
495             }
496             else
497             {
498                 taskkill_message(STRING_INVALID_OPTION);
499                 taskkill_message(STRING_USAGE);
500                 return FALSE;
501             }
502         }
503     }
504     else
505     {
506         taskkill_message(STRING_MISSING_OPTION);
507         taskkill_message(STRING_USAGE);
508         return FALSE;
509     }
510
511     return TRUE;
512 }
513
514 int wmain(int argc, WCHAR *argv[])
515 {
516     int status_code = 0;
517
518     if (!process_arguments(argc, argv))
519     {
520         HeapFree(GetProcessHeap(), 0, task_list);
521         return 1;
522     }
523
524     if (force_termination)
525         status_code = terminate_processes();
526     else
527         status_code = send_close_messages();
528
529     HeapFree(GetProcessHeap(), 0, task_list);
530     return status_code;
531 }