Initialize argv.
[mono.git] / mono / io-layer / processes.c
1 /*
2  * processes.c:  Process handles
3  *
4  * Author:
5  *      Dick Porter (dick@ximian.com)
6  *
7  * (C) 2002-2006 Novell, Inc.
8  */
9
10 #include <config.h>
11 #include <glib.h>
12 #include <string.h>
13 #include <pthread.h>
14 #include <sched.h>
15 #include <sys/time.h>
16 #include <errno.h>
17 #include <sys/types.h>
18 #include <unistd.h>
19 #include <signal.h>
20 #include <sys/wait.h>
21
22 #include <mono/io-layer/wapi.h>
23 #include <mono/io-layer/wapi-private.h>
24 #include <mono/io-layer/handles-private.h>
25 #include <mono/io-layer/misc-private.h>
26 #include <mono/io-layer/mono-mutex.h>
27 #include <mono/io-layer/process-private.h>
28 #include <mono/io-layer/threads.h>
29 #include <mono/utils/strenc.h>
30 #include <mono/io-layer/timefuncs-private.h>
31
32 /* The process' environment strings */
33 extern char **environ;
34
35 #undef DEBUG
36
37 static guint32 process_wait (gpointer handle, guint32 timeout);
38
39 struct _WapiHandleOps _wapi_process_ops = {
40         NULL,                           /* close_shared */
41         NULL,                           /* signal */
42         NULL,                           /* own */
43         NULL,                           /* is_owned */
44         process_wait,                   /* special_wait */
45         NULL                            /* prewait */   
46 };
47
48 static mono_once_t process_current_once=MONO_ONCE_INIT;
49 static gpointer current_process=NULL;
50
51 static mono_once_t process_ops_once=MONO_ONCE_INIT;
52
53 static void process_ops_init (void)
54 {
55         _wapi_handle_register_capabilities (WAPI_HANDLE_PROCESS,
56                                             WAPI_HANDLE_CAP_WAIT |
57                                             WAPI_HANDLE_CAP_SPECIAL_WAIT);
58 }
59
60 static gboolean process_set_termination_details (gpointer handle, int status)
61 {
62         struct _WapiHandle_process *process_handle;
63         gboolean ok;
64         int thr_ret;
65         
66         ok = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
67                                   (gpointer *)&process_handle);
68         if (ok == FALSE) {
69                 g_warning ("%s: error looking up process handle %p",
70                            __func__, handle);
71                 return(FALSE);
72         }
73         
74         thr_ret = _wapi_handle_lock_shared_handles ();
75         g_assert (thr_ret == 0);
76
77         if (WIFSIGNALED(status)) {
78                 process_handle->exitstatus = 128 + WTERMSIG(status);
79         } else {
80                 process_handle->exitstatus = WEXITSTATUS(status);
81         }
82         _wapi_time_t_to_filetime (time(NULL), &process_handle->exit_time);
83
84         /* Don't set process_handle->waited here, it needs to only
85          * happen in the parent when wait() has been called.
86          */
87         
88 #ifdef DEBUG
89         g_message ("%s: Setting handle %p signalled", __func__, handle);
90 #endif
91
92         _wapi_shared_handle_set_signal_state (handle, TRUE);
93
94         _wapi_handle_unlock_shared_handles ();
95
96         /* Drop the reference we hold so we have somewhere to store
97          * the exit details, now the process has in fact exited
98          */
99         _wapi_handle_unref (handle);
100         
101         return (ok);
102 }
103
104 /* See if any child processes have terminated and wait() for them,
105  * updating process handle info.  This function is called from the
106  * collection thread every few seconds.
107  */
108 static gboolean waitfor_pid (gpointer test, gpointer user_data)
109 {
110         struct _WapiHandle_process *process;
111         gboolean ok;
112         int status;
113         pid_t ret;
114         
115         ok = _wapi_lookup_handle (test, WAPI_HANDLE_PROCESS,
116                                   (gpointer *)&process);
117         if (ok == FALSE) {
118                 /* The handle must have been too old and was reaped */
119                 return (FALSE);
120         }
121
122         if (process->waited) {
123                 /* We've already done this one */
124                 return(FALSE);
125         }
126         
127         do {
128                 ret = waitpid (process->id, &status, WNOHANG);
129         } while (errno == EINTR);
130         
131         if (ret <= 0) {
132                 /* Process not ready for wait */
133 #ifdef DEBUG
134                 g_message ("%s: Process %d not ready for waiting for: %s",
135                            __func__, process->id, g_strerror (errno));
136 #endif
137
138                 return (FALSE);
139         }
140         
141 #ifdef DEBUG
142         g_message ("%s: Process %d finished", __func__, ret);
143 #endif
144
145         process->waited = TRUE;
146         
147         *(int *)user_data = status;
148         
149         return (TRUE);
150 }
151
152 void _wapi_process_reap (void)
153 {
154         gpointer proc;
155         int status;
156         
157 #ifdef DEBUG
158         g_message ("%s: Reaping child processes", __func__);
159 #endif
160
161         do {
162                 proc = _wapi_search_handle (WAPI_HANDLE_PROCESS, waitfor_pid,
163                                             &status, NULL, FALSE);
164                 if (proc != NULL) {
165 #ifdef DEBUG
166                         g_message ("%s: process handle %p exit code %d",
167                                    __func__, proc, status);
168 #endif
169                         
170                         process_set_termination_details (proc, status);
171
172                         /* _wapi_search_handle adds a reference, so
173                          * drop it here
174                          */
175                         _wapi_handle_unref (proc);
176                 }
177         } while (proc != NULL);
178 }
179
180 /* Limitations: This can only wait for processes that are our own
181  * children.  Fixing this means resurrecting a daemon helper to manage
182  * processes.
183  */
184 static guint32 process_wait (gpointer handle, guint32 timeout)
185 {
186         struct _WapiHandle_process *process_handle;
187         gboolean ok;
188         pid_t pid, ret;
189         int status;
190         
191 #ifdef DEBUG
192         g_message ("%s: Waiting for process %p", __func__, handle);
193 #endif
194
195         ok = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
196                                   (gpointer *)&process_handle);
197         if (ok == FALSE) {
198                 g_warning ("%s: error looking up process handle %p", __func__,
199                            handle);
200                 return(WAIT_FAILED);
201         }
202         
203         if (process_handle->waited) {
204                 /* We've already done this one */
205 #ifdef DEBUG
206                 g_message ("%s: Process %p already signalled", __func__,
207                            handle);
208 #endif
209
210                 return (WAIT_OBJECT_0);
211         }
212         
213         pid = process_handle->id;
214         
215 #ifdef DEBUG
216         g_message ("%s: PID is %d, timeout %d", __func__, pid, timeout);
217 #endif
218
219         if (timeout == INFINITE) {
220                 if (pid == _wapi_getpid ()) {
221                         do {
222                                 Sleep (10000);
223                         } while(1);
224                 } else {
225                         while ((ret = waitpid (pid, &status, 0)) != pid) {
226                                 if (ret == (pid_t)-1 && errno != EINTR) {
227                                         return(WAIT_FAILED);
228                                 }
229                         }
230                 }
231         } else if (timeout == 0) {
232                 /* Just poll */
233                 ret = waitpid (pid, &status, WNOHANG);
234                 if (ret != pid) {
235                         return (WAIT_TIMEOUT);
236                 }
237         } else {
238                 /* Poll in a loop */
239                 if (pid == _wapi_getpid ()) {
240                         Sleep (timeout);
241                         return(WAIT_TIMEOUT);
242                 } else {
243                         do {
244                                 ret = waitpid (pid, &status, WNOHANG);
245 #ifdef DEBUG
246                                 g_message ("%s: waitpid returns: %d, timeout is %d", __func__, ret, timeout);
247 #endif
248                                 
249                                 if (ret == pid) {
250                                         break;
251                                 } else if (ret == (pid_t)-1 &&
252                                            errno != EINTR) {
253 #ifdef DEBUG
254                                         g_message ("%s: waitpid failure: %s",
255                                                    __func__,
256                                                    g_strerror (errno));
257 #endif
258
259                                         if (errno == ECHILD &&
260                                             process_handle->waited) {
261                                                 /* The background
262                                                  * process reaper must
263                                                  * have got this one
264                                                  */
265 #ifdef DEBUG
266                                                 g_message ("%s: Process %p already reaped", __func__, handle);
267 #endif
268
269                                                 return(WAIT_OBJECT_0);
270                                         } else {
271                                                 return(WAIT_FAILED);
272                                         }
273                                 }
274
275                                 _wapi_handle_spin (100);
276                                 timeout -= 100;
277                         } while (timeout > 0);
278                 }
279                 
280                 if (timeout <= 0) {
281                         return(WAIT_TIMEOUT);
282                 }
283         }
284
285         /* Process must have exited */
286 #ifdef DEBUG
287         g_message ("%s: Wait done, status %d", __func__, status);
288 #endif
289
290         ok = process_set_termination_details (handle, status);
291         if (ok == FALSE) {
292                 SetLastError (ERROR_OUTOFMEMORY);
293                 return (WAIT_FAILED);
294         }
295         process_handle->waited = TRUE;
296         
297         return(WAIT_OBJECT_0);
298 }
299
300 void _wapi_process_signal_self ()
301 {
302         if (current_process != NULL) {
303                 process_set_termination_details (current_process, 0);
304         }
305 }
306         
307 static void process_set_defaults (struct _WapiHandle_process *process_handle)
308 {
309         /* These seem to be the defaults on w2k */
310         process_handle->min_working_set = 204800;
311         process_handle->max_working_set = 1413120;
312
313         process_handle->waited = FALSE;
314         
315         _wapi_time_t_to_filetime (time (NULL), &process_handle->create_time);
316 }
317
318 static int
319 len16 (const gunichar2 *str)
320 {
321         int len = 0;
322         
323         while (*str++ != 0)
324                 len++;
325
326         return len;
327 }
328
329 static gunichar2 *
330 utf16_concat (const gunichar2 *first, ...)
331 {
332         va_list args;
333         int total = 0, i;
334         const gunichar2 *s;
335         gunichar2 *ret;
336
337         va_start (args, first);
338         total += len16 (first);
339         for (s = va_arg (args, gunichar2 *); s != NULL; s = va_arg(args, gunichar2 *)){
340                 total += len16 (s);
341         }
342         va_end (args);
343
344         ret = g_new (gunichar2, total + 1);
345         if (ret == NULL)
346                 return NULL;
347
348         ret [total] = 0;
349         i = 0;
350         for (s = first; *s != 0; s++)
351                 ret [i++] = *s;
352         va_start (args, first);
353         for (s = va_arg (args, gunichar2 *); s != NULL; s = va_arg (args, gunichar2 *)){
354                 const gunichar2 *p;
355                 
356                 for (p = s; *p != 0; p++)
357                         ret [i++] = *p;
358         }
359         va_end (args);
360         
361         return ret;
362 }
363
364 static const gunichar2 utf16_space_bytes [2] = { 0x20, 0 };
365 static const gunichar2 *utf16_space = utf16_space_bytes; 
366
367 /* Implemented as just a wrapper around CreateProcess () */
368 gboolean ShellExecuteEx (WapiShellExecuteInfo *sei)
369 {
370         gboolean ret;
371         WapiProcessInformation process_info;
372         gunichar2 *args;
373         
374         if (sei == NULL) {
375                 /* w2k just segfaults here, but we can do better than
376                  * that
377                  */
378                 SetLastError (ERROR_INVALID_PARAMETER);
379                 return (FALSE);
380         }
381
382         if (sei->lpFile == NULL) {
383                 /* w2k returns TRUE for this, for some reason. */
384                 return (TRUE);
385         }
386         
387         /* Put both executable and parameters into the second argument
388          * to CreateProcess (), so it searches $PATH.  The conversion
389          * into and back out of utf8 is because there is no
390          * g_strdup_printf () equivalent for gunichar2 :-(
391          */
392         args = utf16_concat (sei->lpFile, sei->lpParameters == NULL ? NULL : utf16_space, sei->lpParameters, NULL);
393         if (args == NULL){
394                 SetLastError (ERROR_INVALID_DATA);
395                 return (FALSE);
396         }
397         ret = CreateProcess (NULL, args, NULL, NULL, TRUE,
398                              CREATE_UNICODE_ENVIRONMENT, NULL,
399                              sei->lpDirectory, NULL, &process_info);
400         g_free (args);
401         
402         if (!ret) {
403                 static char *handler;
404                 static gunichar2 *handler_utf16;
405                 
406                 if (handler_utf16 == (gunichar2 *)-1)
407                         return FALSE;
408
409 #ifdef PLATFORM_MACOSX
410                 handler = "/usr/bin/open";
411 #else
412                 /*
413                  * On Linux, try: xdg-open, the FreeDesktop standard way of doing it,
414                  * if that fails, try to use gnome-open, then kfmclient
415                  */
416                 handler = g_find_program_in_path ("xdg-open");
417                 if (handler == NULL){
418                         handler = g_find_program_in_path ("gnome-open");
419                         if (handler == NULL){
420                                 handler = g_find_program_in_path ("kfmclient");
421                                 if (handler == NULL){
422                                         handler_utf16 = (gunichar2 *) -1;
423                                         return (FALSE);
424                                 } else {
425                                         /* kfmclient needs exec argument */
426                                         char *old = handler;
427                                         handler = g_strconcat (old, " exec",
428                                                                NULL);
429                                         g_free (old);
430                                 }
431                         }
432                 }
433 #endif
434                 handler_utf16 = g_utf8_to_utf16 (handler, -1, NULL, NULL, NULL);
435                 g_free (handler);
436                 args = utf16_concat (handler_utf16, utf16_space, sei->lpFile,
437                                      sei->lpParameters == NULL ? NULL : utf16_space,
438                                      sei->lpParameters, NULL);
439                 if (args == NULL){
440                         SetLastError (ERROR_INVALID_DATA);
441                         return FALSE;
442                 }
443                 ret = CreateProcess (NULL, args, NULL, NULL, TRUE,
444                                      CREATE_UNICODE_ENVIRONMENT, NULL,
445                                      sei->lpDirectory, NULL, &process_info);
446                 g_free (args);
447                 if (!ret){
448                         SetLastError (ERROR_INVALID_DATA);
449                         return FALSE;
450                 }
451         }
452         
453         if (sei->fMask & SEE_MASK_NOCLOSEPROCESS) {
454                 sei->hProcess = process_info.hProcess;
455         } else {
456                 CloseHandle (process_info.hProcess);
457         }
458         
459         return (ret);
460 }
461
462 gboolean CreateProcess (const gunichar2 *appname, const gunichar2 *cmdline,
463                         WapiSecurityAttributes *process_attrs G_GNUC_UNUSED,
464                         WapiSecurityAttributes *thread_attrs G_GNUC_UNUSED,
465                         gboolean inherit_handles, guint32 create_flags,
466                         gpointer new_environ, const gunichar2 *cwd,
467                         WapiStartupInfo *startup,
468                         WapiProcessInformation *process_info)
469 {
470         gchar *cmd=NULL, *prog = NULL, *full_prog = NULL, *args = NULL, *args_after_prog = NULL, *dir = NULL, **env_strings = NULL, **argv = NULL;
471         guint32 i, env_count = 0;
472         gboolean ret = FALSE;
473         gpointer handle;
474         struct _WapiHandle_process process_handle = {0}, *process_handle_data;
475         GError *gerr = NULL;
476         int in_fd, out_fd, err_fd;
477         pid_t pid;
478         int thr_ret;
479         
480         mono_once (&process_ops_once, process_ops_init);
481         
482         /* appname and cmdline specify the executable and its args:
483          *
484          * If appname is not NULL, it is the name of the executable.
485          * Otherwise the executable is the first token in cmdline.
486          *
487          * Executable searching:
488          *
489          * If appname is not NULL, it can specify the full path and
490          * file name, or else a partial name and the current directory
491          * will be used.  There is no additional searching.
492          *
493          * If appname is NULL, the first whitespace-delimited token in
494          * cmdline is used.  If the name does not contain a full
495          * directory path, the search sequence is:
496          *
497          * 1) The directory containing the current process
498          * 2) The current working directory
499          * 3) The windows system directory  (Ignored)
500          * 4) The windows directory (Ignored)
501          * 5) $PATH
502          *
503          * Just to make things more interesting, tokens can contain
504          * white space if they are surrounded by quotation marks.  I'm
505          * beginning to understand just why windows apps are generally
506          * so crap, with an API like this :-(
507          */
508         if (appname != NULL) {
509                 cmd = mono_unicode_to_external (appname);
510                 if (cmd == NULL) {
511 #ifdef DEBUG
512                         g_message ("%s: unicode conversion returned NULL",
513                                    __func__);
514 #endif
515
516                         SetLastError (ERROR_PATH_NOT_FOUND);
517                         goto cleanup;
518                 }
519
520                 /* Turn all the slashes round the right way */
521                 for (i = 0; i < strlen (cmd); i++) {
522                         if (cmd[i] == '\\') {
523                                 cmd[i] = '/';
524                         }
525                 }
526         }
527         
528         if (cmdline != NULL) {
529                 args = mono_unicode_to_external (cmdline);
530                 if (args == NULL) {
531 #ifdef DEBUG
532                         g_message ("%s: unicode conversion returned NULL", __func__);
533 #endif
534
535                         SetLastError (ERROR_PATH_NOT_FOUND);
536                         goto cleanup;
537                 }
538         }
539
540         if (cwd != NULL) {
541                 dir = mono_unicode_to_external (cwd);
542                 if (dir == NULL) {
543 #ifdef DEBUG
544                         g_message ("%s: unicode conversion returned NULL", __func__);
545 #endif
546
547                         SetLastError (ERROR_PATH_NOT_FOUND);
548                         goto cleanup;
549                 }
550
551                 /* Turn all the slashes round the right way */
552                 for (i = 0; i < strlen (dir); i++) {
553                         if (dir[i] == '\\') {
554                                 dir[i] = '/';
555                         }
556                 }
557         }
558         
559
560         /* We can't put off locating the executable any longer :-( */
561         if (cmd != NULL) {
562                 gchar *unquoted;
563                 if (g_ascii_isalpha (cmd[0]) && (cmd[1] == ':')) {
564                         /* Strip off the drive letter.  I can't
565                          * believe that CP/M holdover is still
566                          * visible...
567                          */
568                         g_memmove (cmd, cmd+2, strlen (cmd)-2);
569                         cmd[strlen (cmd)-2] = '\0';
570                 }
571
572                 unquoted = g_shell_unquote (cmd, NULL);
573                 if (unquoted[0] == '/') {
574                         /* Assume full path given */
575                         prog = g_strdup (unquoted);
576
577                         /* Executable existing ? */
578                         if (access (prog, X_OK) != 0) {
579 #ifdef DEBUG
580                                 g_message ("%s: Couldn't find executable %s",
581                                            __func__, prog);
582 #endif
583                                 g_free (unquoted);
584                                 SetLastError (ERROR_FILE_NOT_FOUND);
585                                 goto cleanup;
586                         }
587                 } else {
588                         /* Search for file named by cmd in the current
589                          * directory
590                          */
591                         char *curdir = g_get_current_dir ();
592
593                         prog = g_strdup_printf ("%s/%s", curdir, unquoted);
594                         g_free (curdir);
595
596                         /* And make sure it's executable */
597                         if (access (prog, X_OK) != 0) {
598 #ifdef DEBUG
599                                 g_message ("%s: Couldn't find executable %s",
600                                            __func__, prog);
601 #endif
602                                 g_free (unquoted);
603                                 SetLastError (ERROR_FILE_NOT_FOUND);
604                                 goto cleanup;
605                         }
606                 }
607                 g_free (unquoted);
608
609                 args_after_prog = args;
610         } else {
611                 gchar *token = NULL;
612                 char quote;
613                 
614                 /* Dig out the first token from args, taking quotation
615                  * marks into account
616                  */
617
618                 /* First, strip off all leading whitespace */
619                 args = g_strchug (args);
620                 
621                 /* args_after_prog points to the contents of args
622                  * after token has been set (otherwise argv[0] is
623                  * duplicated)
624                  */
625                 args_after_prog = args;
626
627                 /* Assume the opening quote will always be the first
628                  * character
629                  */
630                 if (args[0] == '\"' || args [0] == '\'') {
631                         quote = args [0];
632                         for (i = 1; args[i] != '\0' && args[i] != quote; i++);
633                         if (g_ascii_isspace (args[i+1])) {
634                                 /* We found the first token */
635                                 token = g_strndup (args+1, i-1);
636                                 args_after_prog = args + i;
637                         } else {
638                                 /* Quotation mark appeared in the
639                                  * middle of the token.  Just give the
640                                  * whole first token, quotes and all,
641                                  * to exec.
642                                  */
643                         }
644                 }
645                 
646                 if (token == NULL) {
647                         /* No quote mark, or malformed */
648                         for (i = 0; args[i] != '\0'; i++) {
649                                 if (g_ascii_isspace (args[i])) {
650                                         token = g_strndup (args, i);
651                                         args_after_prog = args + i + 1;
652                                         break;
653                                 }
654                         }
655                 }
656
657                 if (token == NULL && args[0] != '\0') {
658                         /* Must be just one token in the string */
659                         token = g_strdup (args);
660                         args_after_prog = NULL;
661                 }
662                 
663                 if (token == NULL) {
664                         /* Give up */
665 #ifdef DEBUG
666                         g_message ("%s: Couldn't find what to exec", __func__);
667 #endif
668
669                         SetLastError (ERROR_PATH_NOT_FOUND);
670                         goto cleanup;
671                 }
672                 
673                 /* Turn all the slashes round the right way. Only for
674                  * the prg. name
675                  */
676                 for (i = 0; i < strlen (token); i++) {
677                         if (token[i] == '\\') {
678                                 token[i] = '/';
679                         }
680                 }
681
682                 if (g_ascii_isalpha (token[0]) && (token[1] == ':')) {
683                         /* Strip off the drive letter.  I can't
684                          * believe that CP/M holdover is still
685                          * visible...
686                          */
687                         g_memmove (token, token+2, strlen (token)-2);
688                         token[strlen (token)-2] = '\0';
689                 }
690
691                 if (token[0] == '/') {
692                         /* Assume full path given */
693                         prog = g_strdup (token);
694                         
695                         /* Executable existing ? */
696                         if (access (prog, X_OK) != 0) {
697 #ifdef DEBUG
698                                 g_message ("%s: Couldn't find executable %s",
699                                            __func__, token);
700 #endif
701                                 g_free (token);
702                                 SetLastError (ERROR_FILE_NOT_FOUND);
703                                 goto cleanup;
704                         }
705
706                 } else {
707                         char *curdir = g_get_current_dir ();
708
709                         /* FIXME: Need to record the directory
710                          * containing the current process, and check
711                          * that for the new executable as the first
712                          * place to look
713                          */
714
715                         prog = g_strdup_printf ("%s/%s", curdir, token);
716                         g_free (curdir);
717
718                         /* I assume X_OK is the criterion to use,
719                          * rather than F_OK
720                          */
721                         if (access (prog, X_OK) != 0) {
722                                 g_free (prog);
723                                 prog = g_find_program_in_path (token);
724                                 if (prog == NULL) {
725 #ifdef DEBUG
726                                         g_message ("%s: Couldn't find executable %s", __func__, token);
727 #endif
728
729                                         g_free (token);
730                                         SetLastError (ERROR_FILE_NOT_FOUND);
731                                         goto cleanup;
732                                 }
733                         }
734                 }
735
736                 g_free (token);
737         }
738
739 #ifdef DEBUG
740         g_message ("%s: Exec prog [%s] args [%s]", __func__, prog,
741                    args_after_prog);
742 #endif
743         
744         if (args_after_prog != NULL && *args_after_prog) {
745                 gchar *qprog;
746
747                 qprog = g_shell_quote (prog);
748                 full_prog = g_strconcat (qprog, " ", args_after_prog, NULL);
749                 g_free (qprog);
750         } else {
751                 full_prog = g_shell_quote (prog);
752         }
753
754         ret = g_shell_parse_argv (full_prog, NULL, &argv, &gerr);
755         if (ret == FALSE) {
756                 /* FIXME: Could do something with the GError here
757                  */
758         }
759
760         if (startup != NULL && startup->dwFlags & STARTF_USESTDHANDLES) {
761                 in_fd = GPOINTER_TO_UINT (startup->hStdInput);
762                 out_fd = GPOINTER_TO_UINT (startup->hStdOutput);
763                 err_fd = GPOINTER_TO_UINT (startup->hStdError);
764         } else {
765                 in_fd = GPOINTER_TO_UINT (GetStdHandle (STD_INPUT_HANDLE));
766                 out_fd = GPOINTER_TO_UINT (GetStdHandle (STD_OUTPUT_HANDLE));
767                 err_fd = GPOINTER_TO_UINT (GetStdHandle (STD_ERROR_HANDLE));
768         }
769         
770         g_strlcpy (process_handle.proc_name, prog,
771                    _WAPI_PROC_NAME_MAX_LEN - 1);
772
773         process_set_defaults (&process_handle);
774         
775         handle = _wapi_handle_new (WAPI_HANDLE_PROCESS, &process_handle);
776         if (handle == _WAPI_HANDLE_INVALID) {
777                 g_warning ("%s: error creating process handle", __func__);
778
779                 SetLastError (ERROR_PATH_NOT_FOUND);
780                 goto cleanup;
781         }
782
783         /* Hold another reference so the process has somewhere to
784          * store its exit data even if we drop this handle
785          */
786         _wapi_handle_ref (handle);
787         
788         /* new_environ is a block of NULL-terminated strings, which
789          * is itself NULL-terminated. Of course, passing an array of
790          * string pointers would have made things too easy :-(
791          *
792          * If new_environ is not NULL it specifies the entire set of
793          * environment variables in the new process.  Otherwise the
794          * new process inherits the same environment.
795          */
796         if (new_environ != NULL) {
797                 gunichar2 *new_environp;
798
799                 /* Count the number of strings */
800                 for (new_environp = (gunichar2 *)new_environ; *new_environp;
801                      new_environp++) {
802                         env_count++;
803                         while (*new_environp) {
804                                 new_environp++;
805                         }
806                 }
807
808                 /* +2: one for the process handle value, and the last
809                  * one is NULL
810                  */
811                 env_strings = g_new0 (gchar *, env_count + 2);
812                 
813                 /* Copy each environ string into 'strings' turning it
814                  * into utf8 (or the requested encoding) at the same
815                  * time
816                  */
817                 env_count = 0;
818                 for (new_environp = (gunichar2 *)new_environ; *new_environp;
819                      new_environp++) {
820                         env_strings[env_count] = mono_unicode_to_external (new_environp);
821                         env_count++;
822                         while (*new_environp) {
823                                 new_environp++;
824                         }
825                 }
826         } else {
827                 for (i = 0; environ[i] != NULL; i++) {
828                         env_count++;
829                 }
830
831                 /* +2: one for the process handle value, and the last
832                  * one is NULL
833                  */
834                 env_strings = g_new0 (gchar *, env_count + 2);
835                 
836                 /* Copy each environ string into 'strings' turning it
837                  * into utf8 (or the requested encoding) at the same
838                  * time
839                  */
840                 env_count = 0;
841                 for (i = 0; environ[i] != NULL; i++) {
842                         env_strings[env_count] = g_strdup (environ[i]);
843                         env_count++;
844                 }
845         }
846         /* pass process handle info to the child, so it doesn't have
847          * to do an expensive search over the whole list
848          */
849         if (env_strings != NULL) {
850                 struct _WapiHandleUnshared *handle_data;
851                 struct _WapiHandle_shared_ref *ref;
852                 
853                 handle_data = &_WAPI_PRIVATE_HANDLES(GPOINTER_TO_UINT(handle));
854                 ref = &handle_data->u.shared;
855                 
856                 env_strings[env_count] = g_strdup_printf ("_WAPI_PROCESS_HANDLE_OFFSET=%d", ref->offset);
857         }
858
859         thr_ret = _wapi_handle_lock_shared_handles ();
860         g_assert (thr_ret == 0);
861         
862         pid = fork ();
863         if (pid == -1) {
864                 /* Error */
865                 SetLastError (ERROR_OUTOFMEMORY);
866                 _wapi_handle_unref (handle);
867                 goto cleanup;
868         } else if (pid == 0) {
869                 /* Child */
870                 
871                 /* Wait for the parent to finish setting up the
872                  * handle.  The semaphore lock is safe because the
873                  * sem_undo structures of a semaphore aren't inherited
874                  * across a fork ()
875                  */
876                 thr_ret = _wapi_handle_lock_shared_handles ();
877                 g_assert (thr_ret == 0);
878         
879                 _wapi_handle_unlock_shared_handles ();
880                 
881                 /* should we detach from the process group? */
882
883                 /* Connect stdin, stdout and stderr */
884                 dup2 (in_fd, 0);
885                 dup2 (out_fd, 1);
886                 dup2 (err_fd, 2);
887
888                 if (inherit_handles != TRUE) {
889                         /* FIXME: do something here */
890                 }
891                 
892                 /* Close all file descriptors */
893                 for (i = getdtablesize () - 1; i > 2; i--) {
894                         close (i);
895                 }
896
897 #ifdef DEBUG
898                 g_message ("%s: exec()ing [%s] in dir [%s]", __func__, cmd,
899                            dir==NULL?".":dir);
900                 for (i = 0; argv[i] != NULL; i++) {
901                         g_message ("arg %d: [%s]", i, argv[i]);
902                 }
903                 
904                 for (i = 0; env_strings[i] != NULL; i++) {
905                         g_message ("env %d: [%s]", i, env_strings[i]);
906                 }
907 #endif
908
909                 /* set cwd */
910                 if (dir != NULL && chdir (dir) == -1) {
911                         /* set error */
912                         _exit (-1);
913                 }
914                 
915                 /* exec */
916                 execve (argv[0], argv, env_strings);
917                 
918                 /* set error */
919                 _exit (-1);
920         }
921         /* parent */
922         
923         ret = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
924                                    (gpointer *)&process_handle_data);
925         if (ret == FALSE) {
926                 g_warning ("%s: error looking up process handle %p", __func__,
927                            handle);
928                 _wapi_handle_unref (handle);
929                 goto cleanup;
930         }
931         
932         process_handle_data->id = pid;
933         
934         if (process_info != NULL) {
935                 process_info->hProcess = handle;
936                 process_info->dwProcessId = pid;
937
938                 /* FIXME: we might need to handle the thread info some
939                  * day
940                  */
941                 process_info->hThread = INVALID_HANDLE_VALUE;
942                 process_info->dwThreadId = 0;
943         }
944
945 cleanup:
946         _wapi_handle_unlock_shared_handles ();
947
948         if (cmd != NULL) {
949                 g_free (cmd);
950         }
951         if (full_prog != NULL) {
952                 g_free (full_prog);
953         }
954         if (prog != NULL) {
955                 g_free (prog);
956         }
957         if (args != NULL) {
958                 g_free (args);
959         }
960         if (dir != NULL) {
961                 g_free (dir);
962         }
963         if(env_strings != NULL) {
964                 g_strfreev (env_strings);
965         }
966         if (argv != NULL) {
967                 g_strfreev (argv);
968         }
969         
970 #ifdef DEBUG
971         g_message ("%s: returning handle %p for pid %d", __func__, handle,
972                    pid);
973 #endif
974
975         return(ret);
976 }
977                 
978 static void process_set_name (struct _WapiHandle_process *process_handle)
979 {
980         gchar *progname, *utf8_progname, *slash;
981         
982         progname=g_get_prgname ();
983         utf8_progname=mono_utf8_from_external (progname);
984
985 #ifdef DEBUG
986         g_message ("%s: using [%s] as prog name", __func__, progname);
987 #endif
988
989         if(utf8_progname!=NULL) {
990                 slash=strrchr (utf8_progname, '/');
991                 if(slash!=NULL) {
992                         g_strlcpy (process_handle->proc_name, slash+1,
993                                    _WAPI_PROC_NAME_MAX_LEN - 1);
994                 } else {
995                         g_strlcpy (process_handle->proc_name, utf8_progname,
996                                    _WAPI_PROC_NAME_MAX_LEN - 1);
997                 }
998
999                 g_free (utf8_progname);
1000         }
1001 }
1002
1003 extern void _wapi_time_t_to_filetime (time_t timeval, WapiFileTime *filetime);
1004
1005 #if !GLIB_CHECK_VERSION (2,4,0)
1006 #define g_setenv(a,b,c) setenv(a,b,c)
1007 #define g_unsetenv(a) unsetenv(a)
1008 #endif
1009
1010 static void process_set_current (void)
1011 {
1012         pid_t pid = _wapi_getpid ();
1013         const char *handle_env;
1014         struct _WapiHandle_process process_handle = {0};
1015         
1016         mono_once (&process_ops_once, process_ops_init);
1017         
1018         handle_env = g_getenv ("_WAPI_PROCESS_HANDLE_OFFSET");
1019         g_unsetenv ("_WAPI_PROCESS_HANDLE_OFFSET");
1020         
1021         if (handle_env != NULL) {
1022                 struct _WapiHandle_process *process_handlep;
1023                 gchar *procname = NULL;
1024                 gboolean ok;
1025                 
1026                 current_process = _wapi_handle_new_from_offset (WAPI_HANDLE_PROCESS, atoi (handle_env), TRUE);
1027                 
1028 #ifdef DEBUG
1029                 g_message ("%s: Found my process handle: %p (offset %d 0x%x)",
1030                            __func__, current_process, atoi (handle_env),
1031                            atoi (handle_env));
1032 #endif
1033
1034                 ok = _wapi_lookup_handle (current_process, WAPI_HANDLE_PROCESS,
1035                                           (gpointer *)&process_handlep);
1036                 if (ok) {
1037                         /* This test will probably break on linuxthreads, but
1038                          * that should be ancient history on all distros we
1039                          * care about by now
1040                          */
1041                         if (process_handlep->id == pid) {
1042                                 procname = process_handlep->proc_name;
1043                                 if (!strcmp (procname, "mono")) {
1044                                         /* Set a better process name */
1045 #ifdef DEBUG
1046                                         g_message ("%s: Setting better process name", __func__);
1047 #endif
1048                                         
1049                                         process_set_name (process_handlep);
1050                                 } else {
1051 #ifdef DEBUG
1052                                         g_message ("%s: Leaving process name: %s", __func__, procname);
1053 #endif
1054                                 }
1055
1056                                 return;
1057                         }
1058
1059                         /* Wrong pid, so drop this handle and fall through to
1060                          * create a new one
1061                          */
1062                         _wapi_handle_unref (current_process);
1063                 }
1064         }
1065
1066         /* We get here if the handle wasn't specified in the
1067          * environment, or if the process ID was wrong, or if the
1068          * handle lookup failed (eg if the parent process forked and
1069          * quit immediately, and deleted the shared data before the
1070          * child got a chance to attach it.)
1071          */
1072
1073 #ifdef DEBUG
1074         g_message ("%s: Need to create my own process handle", __func__);
1075 #endif
1076
1077         process_handle.id = pid;
1078
1079         process_set_defaults (&process_handle);
1080         process_set_name (&process_handle);
1081
1082         current_process = _wapi_handle_new (WAPI_HANDLE_PROCESS,
1083                                             &process_handle);
1084         if (current_process == _WAPI_HANDLE_INVALID) {
1085                 g_warning ("%s: error creating process handle", __func__);
1086                 return;
1087         }
1088 }
1089
1090 gpointer _wapi_process_duplicate ()
1091 {
1092         mono_once (&process_current_once, process_set_current);
1093         
1094         _wapi_handle_ref (current_process);
1095         
1096         return(current_process);
1097 }
1098
1099 /* Returns a pseudo handle that doesn't need to be closed afterwards */
1100 gpointer GetCurrentProcess (void)
1101 {
1102         mono_once (&process_current_once, process_set_current);
1103                 
1104         return(_WAPI_PROCESS_CURRENT);
1105 }
1106
1107 guint32 GetProcessId (gpointer handle)
1108 {
1109         struct _WapiHandle_process *process_handle;
1110         gboolean ok;
1111         
1112         ok = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
1113                                   (gpointer *)&process_handle);
1114         if (ok == FALSE) {
1115                 SetLastError (ERROR_INVALID_HANDLE);
1116                 return (0);
1117         }
1118         
1119         return (process_handle->id);
1120 }
1121
1122 guint32 GetCurrentProcessId (void)
1123 {
1124         mono_once (&process_current_once, process_set_current);
1125                 
1126         return (GetProcessId (current_process));
1127 }
1128
1129 /* Returns the process id as a convenience to the functions that call this */
1130 static pid_t signal_process_if_gone (gpointer handle)
1131 {
1132         struct _WapiHandle_process *process_handle;
1133         gboolean ok;
1134         
1135         /* Make sure the process is signalled if it has exited - if
1136          * the parent process didn't wait for it then it won't be
1137          */
1138         ok = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
1139                                   (gpointer *)&process_handle);
1140         if (ok == FALSE) {
1141                 /* It's possible that the handle has vanished during
1142                  * the _wapi_search_handle before it gets here, so
1143                  * don't spam the console with warnings.
1144                  */
1145 /*              g_warning ("%s: error looking up process handle %p",
1146   __func__, handle);*/
1147                 
1148                 return (0);
1149         }
1150         
1151 #ifdef DEBUG
1152         g_message ("%s: looking at process %d", __func__, process_handle->id);
1153 #endif
1154
1155         if (kill (process_handle->id, 0) == -1 &&
1156             (errno == ESRCH ||
1157              errno == EPERM)) {
1158                 /* The process is dead, (EPERM tells us a new process
1159                  * has that ID, but as it's owned by someone else it
1160                  * can't be the one listed in our shared memory file)
1161                  */
1162                 _wapi_shared_handle_set_signal_state (handle, TRUE);
1163         }
1164
1165         return (process_handle->id);
1166 }
1167
1168 static gboolean process_enum (gpointer handle, gpointer user_data)
1169 {
1170         GArray *processes=user_data;
1171         pid_t pid = signal_process_if_gone (handle);
1172         int i;
1173         
1174         if (pid == 0) {
1175                 return (FALSE);
1176         }
1177         
1178         /* Ignore processes that have already exited (ie they are signalled) */
1179         if (_wapi_handle_issignalled (handle) == FALSE) {
1180 #ifdef DEBUG
1181                 g_message ("%s: process %d added to array", __func__, pid);
1182 #endif
1183
1184                 /* This ensures that duplicates aren't returned (see
1185                  * the comment above _wapi_search_handle () for why
1186                  * it's needed
1187                  */
1188                 for (i = 0; i < processes->len; i++) {
1189                         if (g_array_index (processes, pid_t, i) == pid) {
1190                                 /* We've already got this one, return
1191                                  * FALSE to keep searching
1192                                  */
1193                                 return (FALSE);
1194                         }
1195                 }
1196                 
1197                 g_array_append_val (processes, pid);
1198         }
1199         
1200         /* Return false to keep searching */
1201         return(FALSE);
1202 }
1203
1204 gboolean EnumProcesses (guint32 *pids, guint32 len, guint32 *needed)
1205 {
1206         GArray *processes = g_array_new (FALSE, FALSE, sizeof(pid_t));
1207         guint32 fit, i, j;
1208         
1209         mono_once (&process_current_once, process_set_current);
1210         
1211         _wapi_search_handle (WAPI_HANDLE_PROCESS, process_enum, processes,
1212                              NULL, TRUE);
1213         
1214         fit=len/sizeof(guint32);
1215         for (i = 0, j = 0; j < fit && i < processes->len; i++) {
1216                 pids[j++] = g_array_index (processes, pid_t, i);
1217         }
1218
1219         g_array_free (processes, TRUE);
1220         
1221         *needed = j * sizeof(guint32);
1222         
1223         return(TRUE);
1224 }
1225
1226 static gboolean process_open_compare (gpointer handle, gpointer user_data)
1227 {
1228         pid_t wanted_pid;
1229         pid_t checking_pid = signal_process_if_gone (handle);
1230
1231         if (checking_pid == 0) {
1232                 return(FALSE);
1233         }
1234         
1235         wanted_pid = GPOINTER_TO_UINT (user_data);
1236
1237         /* It's possible to have more than one process handle with the
1238          * same pid, but only the one running process can be
1239          * unsignalled
1240          */
1241         if (checking_pid == wanted_pid &&
1242             _wapi_handle_issignalled (handle) == FALSE) {
1243                 /* If the handle is blown away in the window between
1244                  * returning TRUE here and _wapi_search_handle pinging
1245                  * the timestamp, the search will continue
1246                  */
1247                 return(TRUE);
1248         } else {
1249                 return(FALSE);
1250         }
1251 }
1252
1253 gpointer OpenProcess (guint32 access G_GNUC_UNUSED, gboolean inherit G_GNUC_UNUSED, guint32 pid)
1254 {
1255         /* Find the process handle that corresponds to pid */
1256         gpointer handle;
1257         
1258         mono_once (&process_current_once, process_set_current);
1259
1260 #ifdef DEBUG
1261         g_message ("%s: looking for process %d", __func__, pid);
1262 #endif
1263
1264         handle = _wapi_search_handle (WAPI_HANDLE_PROCESS,
1265                                       process_open_compare,
1266                                       GUINT_TO_POINTER (pid), NULL, TRUE);
1267         if (handle == 0) {
1268 #ifdef DEBUG
1269                 g_message ("%s: Can't find pid %d", __func__, pid);
1270 #endif
1271
1272                 SetLastError (ERROR_PROC_NOT_FOUND);
1273         
1274                 return(NULL);
1275         }
1276
1277         _wapi_handle_ref (handle);
1278         
1279         return(handle);
1280 }
1281
1282 gboolean GetExitCodeProcess (gpointer process, guint32 *code)
1283 {
1284         struct _WapiHandle_process *process_handle;
1285         gboolean ok;
1286         
1287         mono_once (&process_current_once, process_set_current);
1288
1289         if(code==NULL) {
1290                 return(FALSE);
1291         }
1292         
1293         ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
1294                                 (gpointer *)&process_handle);
1295         if(ok==FALSE) {
1296 #ifdef DEBUG
1297                 g_message ("%s: Can't find process %p", __func__, process);
1298 #endif
1299                 
1300                 return(FALSE);
1301         }
1302         
1303         /* A process handle is only signalled if the process has exited
1304          * and has been waited for */
1305         if (_wapi_handle_issignalled (process) == TRUE ||
1306             process_wait (process, 0) == WAIT_OBJECT_0) {
1307                 *code = process_handle->exitstatus;
1308         } else {
1309                 *code = STILL_ACTIVE;
1310         }
1311         
1312         return(TRUE);
1313 }
1314
1315 gboolean GetProcessTimes (gpointer process, WapiFileTime *create_time,
1316                           WapiFileTime *exit_time, WapiFileTime *kernel_time,
1317                           WapiFileTime *user_time)
1318 {
1319         struct _WapiHandle_process *process_handle;
1320         gboolean ok;
1321         
1322         mono_once (&process_current_once, process_set_current);
1323
1324         if(create_time==NULL || exit_time==NULL || kernel_time==NULL ||
1325            user_time==NULL) {
1326                 /* Not sure if w32 allows NULLs here or not */
1327                 return(FALSE);
1328         }
1329         
1330         ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
1331                                 (gpointer *)&process_handle);
1332         if(ok==FALSE) {
1333 #ifdef DEBUG
1334                 g_message ("%s: Can't find process %p", __func__, process);
1335 #endif
1336                 
1337                 return(FALSE);
1338         }
1339         
1340         *create_time=process_handle->create_time;
1341
1342         /* A process handle is only signalled if the process has
1343          * exited.  Otherwise exit_time isn't set
1344          */
1345         if(_wapi_handle_issignalled (process)==TRUE) {
1346                 *exit_time=process_handle->exit_time;
1347         }
1348         
1349         return(TRUE);
1350 }
1351
1352 gboolean EnumProcessModules (gpointer process, gpointer *modules,
1353                              guint32 size, guint32 *needed)
1354 {
1355         /* Store modules in an array of pointers (main module as
1356          * modules[0]), using the load address for each module as a
1357          * token.  (Use 'NULL' as an alternative for the main module
1358          * so that the simple implementation can just return one item
1359          * for now.)  Get the info from /proc/<pid>/maps on linux,
1360          * other systems will have to implement /dev/kmem reading or
1361          * whatever other horrid technique is needed.
1362          */
1363         if(size<sizeof(gpointer)) {
1364                 return(FALSE);
1365         }
1366         
1367 #ifdef linux
1368         modules[0]=NULL;
1369         *needed=sizeof(gpointer);
1370 #else
1371         modules[0]=NULL;
1372         *needed=sizeof(gpointer);
1373 #endif
1374         
1375         return(TRUE);
1376 }
1377
1378 guint32 GetModuleBaseName (gpointer process, gpointer module,
1379                            gunichar2 *basename, guint32 size)
1380 {
1381         struct _WapiHandle_process *process_handle;
1382         gboolean ok;
1383         
1384         mono_once (&process_current_once, process_set_current);
1385
1386 #ifdef DEBUG
1387         g_message ("%s: Getting module base name, process handle %p module %p",
1388                    __func__, process, module);
1389 #endif
1390
1391         if(basename==NULL || size==0) {
1392                 return(FALSE);
1393         }
1394         
1395         ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
1396                                 (gpointer *)&process_handle);
1397         if(ok==FALSE) {
1398 #ifdef DEBUG
1399                 g_message ("%s: Can't find process %p", __func__, process);
1400 #endif
1401                 
1402                 return(FALSE);
1403         }
1404
1405         if(module==NULL) {
1406                 /* Shorthand for the main module, which has the
1407                  * process name recorded in the handle data
1408                  */
1409                 pid_t pid;
1410                 gunichar2 *procname;
1411                 gchar *procname_utf8 = NULL;
1412                 glong len, bytes;
1413                 
1414 #ifdef DEBUG
1415                 g_message ("%s: Returning main module name", __func__);
1416 #endif
1417
1418                 pid=process_handle->id;
1419                 procname_utf8 = process_handle->proc_name;
1420         
1421 #ifdef DEBUG
1422                 g_message ("%s: Process name is [%s]", __func__,
1423                            procname_utf8);
1424 #endif
1425
1426                 procname = g_utf8_to_utf16 (procname_utf8, -1, NULL, &len,
1427                                             NULL);
1428                 if (procname == NULL) {
1429                         /* bugger */
1430                         return(0);
1431                 }
1432
1433                 /* Add the terminator, and convert chars to bytes */
1434                 bytes = (len + 1) * 2;
1435                 
1436                 if (size < bytes) {
1437 #ifdef DEBUG
1438                         g_message ("%s: Size %d smaller than needed (%ld); truncating", __func__, size, bytes);
1439 #endif
1440
1441                         memcpy (basename, procname, size);
1442                 } else {
1443 #ifdef DEBUG
1444                         g_message ("%s: Size %d larger than needed (%ld)",
1445                                    __func__, size, bytes);
1446 #endif
1447
1448                         memcpy (basename, procname, bytes);
1449                 }
1450                 
1451                 g_free (procname);
1452
1453                 return(len);
1454         } else {
1455                 /* Look up the address in /proc/<pid>/maps */
1456         }
1457         
1458         return(0);
1459 }
1460
1461 gboolean GetProcessWorkingSetSize (gpointer process, size_t *min, size_t *max)
1462 {
1463         struct _WapiHandle_process *process_handle;
1464         gboolean ok;
1465         
1466         mono_once (&process_current_once, process_set_current);
1467
1468         if(min==NULL || max==NULL) {
1469                 /* Not sure if w32 allows NULLs here or not */
1470                 return(FALSE);
1471         }
1472         
1473         ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
1474                                 (gpointer *)&process_handle);
1475         if(ok==FALSE) {
1476 #ifdef DEBUG
1477                 g_message ("%s: Can't find process %p", __func__, process);
1478 #endif
1479                 
1480                 return(FALSE);
1481         }
1482
1483         *min=process_handle->min_working_set;
1484         *max=process_handle->max_working_set;
1485         
1486         return(TRUE);
1487 }
1488
1489 gboolean SetProcessWorkingSetSize (gpointer process, size_t min, size_t max)
1490 {
1491         struct _WapiHandle_process *process_handle;
1492         gboolean ok;
1493
1494         mono_once (&process_current_once, process_set_current);
1495
1496         ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
1497                                 (gpointer *)&process_handle);
1498         if(ok==FALSE) {
1499 #ifdef DEBUG
1500                 g_message ("%s: Can't find process %p", __func__, process);
1501 #endif
1502                 
1503                 return(FALSE);
1504         }
1505
1506         process_handle->min_working_set=min;
1507         process_handle->max_working_set=max;
1508         
1509         return(TRUE);
1510 }
1511
1512
1513 gboolean
1514 TerminateProcess (gpointer process, gint32 exitCode)
1515 {
1516         struct _WapiHandle_process *process_handle;
1517         gboolean ok;
1518         int signo;
1519         int ret;
1520
1521         ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
1522                                   (gpointer *) &process_handle);
1523
1524         if (ok == FALSE) {
1525 #ifdef DEBUG
1526                 g_message ("%s: Can't find process %p", __func__, process);
1527 #endif
1528                 SetLastError (ERROR_INVALID_HANDLE);
1529                 return FALSE;
1530         }
1531
1532         signo = (exitCode == -1) ? SIGKILL : SIGTERM;
1533         ret = kill (process_handle->id, signo);
1534         if (ret == -1) {
1535                 switch (errno) {
1536                 case EINVAL:
1537                         SetLastError (ERROR_INVALID_PARAMETER);
1538                         break;
1539                 case EPERM:
1540                         SetLastError (ERROR_ACCESS_DENIED);
1541                         break;
1542                 case ESRCH:
1543                         SetLastError (ERROR_PROC_NOT_FOUND);
1544                         break;
1545                 default:
1546                         SetLastError (ERROR_GEN_FAILURE);
1547                 }
1548         }
1549         
1550         return (ret == 0);
1551 }
1552