Fix thinko spotted by Gonzalo
[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 Ximian, 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 };
46
47 static mono_once_t process_current_once=MONO_ONCE_INIT;
48 static gpointer current_process=NULL;
49
50 static mono_once_t process_ops_once=MONO_ONCE_INIT;
51
52 static void process_ops_init (void)
53 {
54         _wapi_handle_register_capabilities (WAPI_HANDLE_PROCESS,
55                                             WAPI_HANDLE_CAP_WAIT |
56                                             WAPI_HANDLE_CAP_SPECIAL_WAIT);
57 }
58
59 static gboolean process_set_termination_details (gpointer handle, int status)
60 {
61         struct _WapiHandleShared shared_handle;
62         struct _WapiHandle_process *process_handle;
63         gboolean ok;
64         
65         ok = _wapi_copy_handle (handle, WAPI_HANDLE_PROCESS, &shared_handle);
66         if (ok == FALSE) {
67                 g_warning ("%s: error looking up process handle %p",
68                            __func__, handle);
69                 return(FALSE);
70         }
71         
72         process_handle = &shared_handle.u.process;
73
74         if (WIFSIGNALED(status)) {
75                 process_handle->exitstatus = 128 + WTERMSIG(status);
76         } else {
77                 process_handle->exitstatus = WEXITSTATUS(status);
78         }
79         _wapi_time_t_to_filetime (time(NULL), &process_handle->exit_time);
80         
81         ok = _wapi_replace_handle (handle, WAPI_HANDLE_PROCESS,
82                                    &shared_handle);
83         
84         _wapi_shared_handle_set_signal_state (handle, TRUE);
85
86         return (ok);
87 }
88
89 /* See if any child processes have terminated and wait() for them,
90  * updating process handle info.  This function is called from the
91  * collection thread every few seconds.
92  */
93 static gboolean waitfor_pid (gpointer test, gpointer user_data G_GNUC_UNUSED)
94 {
95         struct _WapiHandle_process *process;
96         gboolean ok;
97         int status;
98         pid_t ret;
99         
100         ok = _wapi_lookup_handle (test, WAPI_HANDLE_PROCESS,
101                                   (gpointer *)&process);
102         if (ok == FALSE) {
103                 return (FALSE);
104         }
105         
106         do {
107                 ret == waitpid (process->id, &status, WNOHANG);
108         } while (errno == EINTR);
109         
110         if (ret <= 0) {
111                 /* Process not ready for wait */
112 #ifdef DEBUG
113                 g_message ("%s: Process %d not ready for waiting for",
114                            __func__, ret);
115 #endif
116
117                 return (FALSE);
118         }
119         
120 #ifdef DEBUG
121         g_message ("%s: Process %d finished", __func__, ret);
122 #endif
123
124         process_set_termination_details (test, status);
125         
126         /* return FALSE to keep searching */
127         return (FALSE);
128 }
129
130 void _wapi_process_reap (void)
131 {
132 #ifdef DEBUG
133         g_message ("%s: Reaping child processes", __func__);
134 #endif
135
136         _wapi_search_handle (WAPI_HANDLE_PROCESS, waitfor_pid, NULL, NULL);
137 }
138
139 /* Limitations: This can only wait for processes that are our own
140  * children.  Fixing this means resurrecting a daemon helper to manage
141  * processes.
142  */
143 static guint32 process_wait (gpointer handle, guint32 timeout)
144 {
145         struct _WapiHandle_process *process_handle;
146         gboolean ok;
147         pid_t pid, ret;
148         int status;
149         
150 #ifdef DEBUG
151         g_message ("%s: Waiting for process %p", __func__, handle);
152 #endif
153
154         ok = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
155                                   (gpointer *)&process_handle);
156         if (ok == FALSE) {
157                 g_warning ("%s: error looking up process handle %p", __func__,
158                            handle);
159                 return(WAIT_FAILED);
160         }
161         
162         pid = process_handle->id;
163         
164 #ifdef DEBUG
165         g_message ("%s: PID is %d", __func__, pid);
166 #endif
167
168         if (timeout == INFINITE) {
169                 while ((ret = waitpid (pid, &status, 0)) != pid) {
170                         if (ret == (pid_t)-1 && errno != EINTR) {
171                                 return(WAIT_FAILED);
172                         }
173                 }
174         } else if (timeout == 0) {
175                 /* Just poll */
176                 ret = waitpid (pid, &status, WNOHANG);
177                 if (ret != pid) {
178                         return (WAIT_TIMEOUT);
179                 }
180         } else {
181                 /* Poll in a loop */
182                 do {
183                         ret = waitpid (pid, &status, WNOHANG);
184                         if (ret == pid) {
185                                 break;
186                         } else if (ret == (pid_t)-1 && errno != EINTR) {
187                                 return(WAIT_FAILED);
188                         }
189
190                         _wapi_handle_spin (100);
191                         timeout -= 100;
192                 } while (timeout > 0);
193
194                 if (timeout <= 0) {
195                         return(WAIT_TIMEOUT);
196                 }
197         }
198
199         /* Process must have exited */
200 #ifdef DEBUG
201         g_message ("%s: Wait done", __func__);
202 #endif
203
204         ok = process_set_termination_details (handle, status);
205         if (ok == FALSE) {
206                 SetLastError (ERROR_OUTOFMEMORY);
207                 return (WAIT_FAILED);
208         }
209
210         return(WAIT_OBJECT_0);
211 }
212         
213 static void process_set_defaults (struct _WapiHandle_process *process_handle)
214 {
215         /* These seem to be the defaults on w2k */
216         process_handle->min_working_set = 204800;
217         process_handle->max_working_set = 1413120;
218
219         _wapi_time_t_to_filetime (time (NULL), &process_handle->create_time);
220 }
221
222 gboolean CreateProcess (const gunichar2 *appname, gunichar2 *cmdline,
223                         WapiSecurityAttributes *process_attrs G_GNUC_UNUSED,
224                         WapiSecurityAttributes *thread_attrs G_GNUC_UNUSED,
225                         gboolean inherit_handles, guint32 create_flags,
226                         gpointer new_environ, const gunichar2 *cwd,
227                         WapiStartupInfo *startup,
228                         WapiProcessInformation *process_info)
229 {
230         gchar *cmd=NULL, *prog = NULL, *full_prog = NULL, *args = NULL, *args_after_prog = NULL, *dir = NULL, **env_strings = NULL, **argv;
231         guint32 i, env_count = 0;
232         gboolean ret = FALSE;
233         gpointer handle;
234         struct _WapiHandleShared shared_handle;
235         struct _WapiHandle_process process_handle = {0};
236         GError *gerr = NULL;
237         int in_fd, out_fd, err_fd;
238         pid_t pid;
239         int lockpipe [2];
240         
241         mono_once (&process_ops_once, process_ops_init);
242         
243         /* appname and cmdline specify the executable and its args:
244          *
245          * If appname is not NULL, it is the name of the executable.
246          * Otherwise the executable is the first token in cmdline.
247          *
248          * Executable searching:
249          *
250          * If appname is not NULL, it can specify the full path and
251          * file name, or else a partial name and the current directory
252          * will be used.  There is no additional searching.
253          *
254          * If appname is NULL, the first whitespace-delimited token in
255          * cmdline is used.  If the name does not contain a full
256          * directory path, the search sequence is:
257          *
258          * 1) The directory containing the current process
259          * 2) The current working directory
260          * 3) The windows system directory  (Ignored)
261          * 4) The windows directory (Ignored)
262          * 5) $PATH
263          *
264          * Just to make things more interesting, tokens can contain
265          * white space if they are surrounded by quotation marks.  I'm
266          * beginning to understand just why windows apps are generally
267          * so crap, with an API like this :-(
268          */
269         if (appname != NULL) {
270                 cmd = mono_unicode_to_external (appname);
271                 if (cmd == NULL) {
272 #ifdef DEBUG
273                         g_message ("%s: unicode conversion returned NULL",
274                                    __func__);
275 #endif
276
277                         SetLastError (ERROR_PATH_NOT_FOUND);
278                         goto cleanup;
279                 }
280
281                 /* Turn all the slashes round the right way */
282                 for (i = 0; i < strlen (cmd); i++) {
283                         if (cmd[i] == '\\') {
284                                 cmd[i] = '/';
285                         }
286                 }
287         }
288         
289         if (cmdline != NULL) {
290                 args = mono_unicode_to_external (cmdline);
291                 if (args == NULL) {
292 #ifdef DEBUG
293                         g_message ("%s: unicode conversion returned NULL", __func__);
294 #endif
295
296                         SetLastError (ERROR_PATH_NOT_FOUND);
297                         goto cleanup;
298                 }
299         }
300
301         if (cwd != NULL) {
302                 dir = mono_unicode_to_external (cwd);
303                 if (dir == NULL) {
304 #ifdef DEBUG
305                         g_message ("%s: unicode conversion returned NULL", __func__);
306 #endif
307
308                         SetLastError (ERROR_PATH_NOT_FOUND);
309                         goto cleanup;
310                 }
311
312                 /* Turn all the slashes round the right way */
313                 for (i = 0; i < strlen (dir); i++) {
314                         if (dir[i] == '\\') {
315                                 dir[i] = '/';
316                         }
317                 }
318         } else {
319                 dir = g_get_current_dir ();
320         }
321         
322
323         /* We can't put off locating the executable any longer :-( */
324         if (cmd != NULL) {
325                 gchar *unquoted;
326                 if (g_ascii_isalpha (cmd[0]) && (cmd[1] == ':')) {
327                         /* Strip off the drive letter.  I can't
328                          * believe that CP/M holdover is still
329                          * visible...
330                          */
331                         g_memmove (cmd, cmd+2, strlen (cmd)-2);
332                         cmd[strlen (cmd)-2] = '\0';
333                 }
334
335                 unquoted = g_shell_unquote (cmd, NULL);
336                 if (unquoted[0] == '/') {
337                         /* Assume full path given */
338                         prog = g_strdup (unquoted);
339
340                         /* Executable existing ? */
341                         if (access (prog, X_OK) != 0) {
342 #ifdef DEBUG
343                                 g_message ("%s: Couldn't find executable %s",
344                                            __func__, prog);
345 #endif
346                                 g_free (prog);
347                                 g_free (unquoted);
348                                 SetLastError (ERROR_FILE_NOT_FOUND);
349                                 goto cleanup;
350                         }
351                 } else {
352                         /* Search for file named by cmd in the current
353                          * directory
354                          */
355                         char *curdir = g_get_current_dir ();
356
357                         prog = g_strdup_printf ("%s/%s", curdir, unquoted);
358                         g_free (unquoted);
359                         g_free (curdir);
360                 }
361
362                 args_after_prog = args;
363         } else {
364                 gchar *token = NULL;
365                 char quote;
366                 
367                 /* Dig out the first token from args, taking quotation
368                  * marks into account
369                  */
370
371                 /* First, strip off all leading whitespace */
372                 args = g_strchug (args);
373                 
374                 /* args_after_prog points to the contents of args
375                  * after token has been set (otherwise argv[0] is
376                  * duplicated)
377                  */
378                 args_after_prog = args;
379
380                 /* Assume the opening quote will always be the first
381                  * character
382                  */
383                 if (args[0] == '\"' || args [0] == '\'') {
384                         quote = args [0];
385                         for (i = 1; args[i] != '\0' && args[i] != quote; i++);
386                         if (g_ascii_isspace (args[i+1])) {
387                                 /* We found the first token */
388                                 token = g_strndup (args+1, i-1);
389                                 args_after_prog = args + i;
390                         } else {
391                                 /* Quotation mark appeared in the
392                                  * middle of the token.  Just give the
393                                  * whole first token, quotes and all,
394                                  * to exec.
395                                  */
396                         }
397                 }
398                 
399                 if (token == NULL) {
400                         /* No quote mark, or malformed */
401                         for (i = 0; args[i] != '\0'; i++) {
402                                 if (g_ascii_isspace (args[i])) {
403                                         token = g_strndup (args, i);
404                                         args_after_prog = args + i + 1;
405                                         break;
406                                 }
407                         }
408                 }
409
410                 if (token == NULL && args[0] != '\0') {
411                         /* Must be just one token in the string */
412                         token = g_strdup (args);
413                         args_after_prog = NULL;
414                 }
415                 
416                 if (token == NULL) {
417                         /* Give up */
418 #ifdef DEBUG
419                         g_message ("%s: Couldn't find what to exec", __func__);
420 #endif
421
422                         SetLastError (ERROR_PATH_NOT_FOUND);
423                         goto cleanup;
424                 }
425                 
426                 /* Turn all the slashes round the right way. Only for
427                  * the prg. name
428                  */
429                 for (i = 0; i < strlen (token); i++) {
430                         if (token[i] == '\\') {
431                                 token[i] = '/';
432                         }
433                 }
434
435                 if (g_ascii_isalpha (token[0]) && (token[1] == ':')) {
436                         /* Strip off the drive letter.  I can't
437                          * believe that CP/M holdover is still
438                          * visible...
439                          */
440                         g_memmove (token, token+2, strlen (token)-2);
441                         token[strlen (token)-2] = '\0';
442                 }
443
444                 if (token[0] == '/') {
445                         /* Assume full path given */
446                         prog = g_strdup (token);
447                         
448                         /* Executable existing ? */
449                         if (access (prog, X_OK) != 0) {
450                                 g_free (prog);
451 #ifdef DEBUG
452                                 g_message ("%s: Couldn't find executable %s",
453                                            __func__, token);
454 #endif
455                                 g_free (token);
456                                 SetLastError (ERROR_FILE_NOT_FOUND);
457                                 goto cleanup;
458                         }
459
460                 } else {
461                         char *curdir = g_get_current_dir ();
462
463                         /* FIXME: Need to record the directory
464                          * containing the current process, and check
465                          * that for the new executable as the first
466                          * place to look
467                          */
468
469                         prog = g_strdup_printf ("%s/%s", curdir, token);
470                         g_free (curdir);
471
472                         /* I assume X_OK is the criterion to use,
473                          * rather than F_OK
474                          */
475                         if (access (prog, X_OK) != 0) {
476                                 g_free (prog);
477                                 prog = g_find_program_in_path (token);
478                                 if (prog == NULL) {
479 #ifdef DEBUG
480                                         g_message ("%s: Couldn't find executable %s", __func__, token);
481 #endif
482
483                                         g_free (token);
484                                         SetLastError (ERROR_FILE_NOT_FOUND);
485                                         goto cleanup;
486                                 }
487                         }
488                 }
489
490                 g_free (token);
491         }
492
493 #ifdef DEBUG
494         g_message ("%s: Exec prog [%s] args [%s]", __func__, prog,
495                    args_after_prog);
496 #endif
497         
498         if (args_after_prog != NULL && *args_after_prog) {
499                 gchar *qprog;
500
501                 qprog = g_shell_quote (prog);
502                 full_prog = g_strconcat (qprog, " ", args_after_prog, NULL);
503                 g_free (qprog);
504         } else {
505                 full_prog = g_shell_quote (prog);
506         }
507
508         ret = g_shell_parse_argv (full_prog, NULL, &argv, &gerr);
509         if (ret == FALSE) {
510                 /* FIXME: Could do something with the GError here
511                  */
512         }
513
514         if (startup != NULL && startup->dwFlags & STARTF_USESTDHANDLES) {
515                 in_fd = GPOINTER_TO_UINT (startup->hStdInput);
516                 out_fd = GPOINTER_TO_UINT (startup->hStdOutput);
517                 err_fd = GPOINTER_TO_UINT (startup->hStdError);
518         } else {
519                 in_fd = GPOINTER_TO_UINT (GetStdHandle (STD_INPUT_HANDLE));
520                 out_fd = GPOINTER_TO_UINT (GetStdHandle (STD_OUTPUT_HANDLE));
521                 err_fd = GPOINTER_TO_UINT (GetStdHandle (STD_ERROR_HANDLE));
522         }
523         
524         g_strlcpy (process_handle.proc_name, prog, _POSIX_PATH_MAX-1);
525
526         process_set_defaults (&process_handle);
527         
528         handle = _wapi_handle_new (WAPI_HANDLE_PROCESS, &process_handle);
529         if (handle == _WAPI_HANDLE_INVALID) {
530                 g_warning ("%s: error creating process handle", __func__);
531
532                 SetLastError (ERROR_PATH_NOT_FOUND);
533                 goto cleanup;
534         }
535         
536         /* new_environ is a block of NULL-terminated strings, which
537          * is itself NULL-terminated. Of course, passing an array of
538          * string pointers would have made things too easy :-(
539          *
540          * If new_environ is not NULL it specifies the entire set of
541          * environment variables in the new process.  Otherwise the
542          * new process inherits the same environment.
543          */
544         if (new_environ != NULL) {
545                 gunichar2 *new_environp;
546
547                 /* Count the number of strings */
548                 for (new_environp = (gunichar2 *)new_environ; *new_environp;
549                      new_environp++) {
550                         env_count++;
551                         while (*new_environp) {
552                                 new_environp++;
553                         }
554                 }
555
556                 /* +2: one for the process handle value, and the last
557                  * one is NULL
558                  */
559                 env_strings = g_new0 (gchar *, env_count + 2);
560                 
561                 /* Copy each environ string into 'strings' turning it
562                  * into utf8 (or the requested encoding) at the same
563                  * time
564                  */
565                 env_count = 0;
566                 for (new_environp = (gunichar2 *)new_environ; *new_environp;
567                      new_environp++) {
568                         env_strings[env_count] = mono_unicode_to_external (new_environp);
569                         env_count++;
570                         while (*new_environp) {
571                                 new_environp++;
572                         }
573                 }
574         } else {
575                 for (i = 0; environ[i] != NULL; i++) {
576                         env_count++;
577                 }
578
579                 /* +2: one for the process handle value, and the last
580                  * one is NULL
581                  */
582                 env_strings = g_new0 (gchar *, env_count + 2);
583                 
584                 /* Copy each environ string into 'strings' turning it
585                  * into utf8 (or the requested encoding) at the same
586                  * time
587                  */
588                 env_count = 0;
589                 for (i = 0; environ[i] != NULL; i++) {
590                         env_strings[env_count] = g_strdup (environ[i]);
591                         env_count++;
592                 }
593         }
594         /* pass process handle info to the child, so it doesn't have
595          * to do an expensive search over the whole list
596          */
597         if (env_strings != NULL) {
598                 struct _WapiHandleUnshared *handle_data;
599                 struct _WapiHandle_shared_ref *ref;
600                 
601                 handle_data = &_WAPI_PRIVATE_HANDLES(GPOINTER_TO_UINT(handle));
602                 ref = &handle_data->u.shared;
603                 
604                 env_strings[env_count] = g_strdup_printf ("_WAPI_PROCESS_HANDLE_OFFSET=%d", ref->offset);
605         }
606         
607         pipe (lockpipe);
608         
609         pid = fork ();
610         if (pid == -1) {
611                 /* Error */
612                 SetLastError (ERROR_OUTOFMEMORY);
613                 _wapi_handle_unref (handle);
614                 goto cleanup;
615         } else if (pid == 0) {
616                 /* Child */
617                 char c [1];
618                 
619                 /* Wait for the parent to finish setting up the handle */
620                 close (lockpipe [1]);
621                 while (read (lockpipe [0], c, 1) == -1 &&
622                        errno == EINTR);
623                 close (lockpipe [0]);
624                 
625                 /* should we detach from the process group? */
626
627                 /* Connect stdin, stdout and stderr */
628                 dup2 (in_fd, 0);
629                 dup2 (out_fd, 1);
630                 dup2 (err_fd, 2);
631
632                 if (inherit_handles != TRUE) {
633                         /* FIXME: do something here */
634                 }
635                 
636                 /* Close all file descriptors */
637                 for (i = getdtablesize () - 1; i > 2; i--) {
638                         close (i);
639                 }
640
641 #ifdef DEBUG
642                 g_message ("%s: exec()ing [%s] in dir [%s]", __func__, cmd,
643                            dir);
644                 for (i = 0; argv[i] != NULL; i++) {
645                         g_message ("arg %d: [%s]", i, argv[i]);
646                 }
647                 
648                 for (i = 0; env_strings[i] != NULL; i++) {
649                         g_message ("env %d: [%s]", i, env_strings[i]);
650                 }
651 #endif
652
653                 /* set cwd */
654                 if (chdir (dir) == -1) {
655                         /* set error */
656                         exit (-1);
657                 }
658                 
659                 /* exec */
660                 execve (argv[0], argv, env_strings);
661                 
662                 /* set error */
663                 exit (-1);
664         }
665         /* parent */
666
667         ret = _wapi_copy_handle (handle, WAPI_HANDLE_PROCESS, &shared_handle);
668         if (ret == FALSE) {
669                 g_warning ("%s: error copying process handle %p", __func__,
670                            handle);
671                 _wapi_handle_unref (handle);
672                 goto cleanup;
673         }
674         
675         shared_handle.u.process.id = pid;
676
677         ret = _wapi_replace_handle (handle, WAPI_HANDLE_PROCESS,
678                                     &shared_handle);
679         if (ret == FALSE) {
680                 SetLastError (ERROR_OUTOFMEMORY);
681                 _wapi_handle_unref (handle);
682                 goto cleanup;
683         }
684         
685         write (lockpipe [1], cmd, 1);
686         
687         if (process_info != NULL) {
688                 process_info->hProcess = handle;
689                 process_info->dwProcessId = pid;
690
691                 /* FIXME: we might need to handle the thread info some
692                  * day
693                  */
694                 process_info->hThread = NULL;
695                 process_info->dwThreadId = 0;
696         }
697
698 cleanup:
699         close (lockpipe [0]);
700         close (lockpipe [1]);
701         
702         if (cmd != NULL) {
703                 g_free (cmd);
704         }
705         if (full_prog != NULL) {
706                 g_free (prog);
707         }
708         if (args != NULL) {
709                 g_free (args);
710         }
711         if (dir != NULL) {
712                 g_free (dir);
713         }
714         if(env_strings != NULL) {
715                 g_strfreev (env_strings);
716         }
717         
718         return(ret);
719 }
720                 
721 static void process_set_name (struct _WapiHandle_process *process_handle)
722 {
723         gchar *progname, *utf8_progname, *slash;
724         
725         progname=g_get_prgname ();
726         utf8_progname=mono_utf8_from_external (progname);
727
728 #ifdef DEBUG
729         g_message ("%s: using [%s] as prog name", __func__, progname);
730 #endif
731
732         if(utf8_progname!=NULL) {
733                 slash=strrchr (utf8_progname, '/');
734                 if(slash!=NULL) {
735                         g_strlcpy (process_handle->proc_name, slash+1,
736                                    _POSIX_PATH_MAX-1);
737                 } else {
738                         g_strlcpy (process_handle->proc_name, utf8_progname,
739                                    _POSIX_PATH_MAX-1);
740                 }
741
742                 g_free (utf8_progname);
743         }
744 }
745
746 extern void _wapi_time_t_to_filetime (time_t timeval, WapiFileTime *filetime);
747
748 static void process_set_current (void)
749 {
750         pid_t pid = getpid ();
751         char *handle_env;
752         
753         handle_env = getenv ("_WAPI_PROCESS_HANDLE_OFFSET");
754         if (handle_env == NULL) {
755                 struct _WapiHandle_process process_handle = {0};
756
757 #ifdef DEBUG
758                 g_message ("%s: Need to create my own process handle",
759                            __func__);
760 #endif
761
762                 process_handle.id = pid;
763
764                 process_set_defaults (&process_handle);
765                 process_set_name (&process_handle);
766
767                 current_process = _wapi_handle_new (WAPI_HANDLE_PROCESS,
768                                                     &process_handle);
769                 if (current_process == _WAPI_HANDLE_INVALID) {
770                         g_warning ("%s: error creating process handle",
771                                    __func__);
772                         return;
773                 }
774                 
775                 /* Make sure the new handle has a reference so it wont go away
776                  * until this process exits
777                  */
778                 _wapi_handle_ref (current_process);
779         } else {
780                 struct _WapiHandle_process *process_handle;
781                 guchar *procname = NULL;
782                 gboolean ok;
783                 
784                 current_process = _wapi_handle_new_from_offset (WAPI_HANDLE_PROCESS, atoi (handle_env));
785                 
786 #ifdef DEBUG
787                 g_message ("%s: Found my process handle: %p (offset %d)",
788                            __func__, current_process, atoi (handle_env));
789 #endif
790
791                 ok = _wapi_lookup_handle (current_process, WAPI_HANDLE_PROCESS,
792                                           (gpointer *)&process_handle);
793                 if (ok == FALSE) {
794                         g_warning ("%s: error looking up process handle %p",
795                                    __func__, current_process);
796                         return;
797                 }
798
799                 procname = process_handle->proc_name;
800                 if (!strcmp (procname, "mono")) {
801                         /* Set a better process name */
802 #ifdef DEBUG
803                         g_message ("%s: Setting better process name",
804                                    __func__);
805 #endif
806
807                         process_set_name (process_handle);
808                 } else {
809 #ifdef DEBUG
810                         g_message ("%s: Leaving process name: %s", __func__,
811                                    procname);
812 #endif
813                 }
814         }
815 }
816
817 /* Returns a pseudo handle that doesn't need to be closed afterwards */
818 gpointer GetCurrentProcess (void)
819 {
820         mono_once (&process_current_once, process_set_current);
821                 
822         return((gpointer)-1);
823 }
824
825 guint32 GetCurrentProcessId (void)
826 {
827         struct _WapiHandle_process *current_process_handle;
828         gboolean ok;
829         
830         mono_once (&process_current_once, process_set_current);
831                 
832         ok=_wapi_lookup_handle (current_process, WAPI_HANDLE_PROCESS,
833                                 (gpointer *)&current_process_handle);
834         if(ok==FALSE) {
835                 g_warning ("%s: error looking up current process handle %p",
836                            __func__, current_process);
837                 /* No failure return is defined.  PID 0 is invalid.
838                  * This should only be reached when something else has
839                  * gone badly wrong anyway.
840                  */
841                 return(0);
842         }
843         
844         return(current_process_handle->id);
845 }
846
847 /* Returns the process id as a convenience to the functions that call this */
848 static pid_t signal_process_if_gone (gpointer handle)
849 {
850         struct _WapiHandle_process *process_handle;
851         gboolean ok;
852         
853         /* Make sure the process is signalled if it has exited - if
854          * the parent process didn't wait for it then it won't be
855          */
856         ok = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
857                                   (gpointer *)&process_handle);
858         if (ok == FALSE) {
859                 g_warning ("%s: error looking up process handle %p",
860                            __func__, handle);
861                 
862                 return (0);
863         }
864         
865 #ifdef DEBUG
866         g_message ("%s: looking at process %d", __func__, process_handle->id);
867 #endif
868
869         if (kill (process_handle->id, 0) == -1 &&
870             (errno == ESRCH ||
871              errno == EPERM)) {
872                 /* The process is dead, (EPERM tells us a new process
873                  * has that ID, but as it's owned by someone else it
874                  * can't be the one listed in our shared memory file)
875                  */
876                 _wapi_shared_handle_set_signal_state (handle, TRUE);
877         }
878
879         return (process_handle->id);
880 }
881
882 static gboolean process_enum (gpointer handle, gpointer user_data)
883 {
884         GArray *processes=user_data;
885         pid_t pid = signal_process_if_gone (handle);
886         int i;
887         
888         if (pid == 0) {
889                 return (FALSE);
890         }
891         
892         /* Ignore processes that have already exited (ie they are signalled) */
893         if (_wapi_handle_issignalled (handle) == FALSE) {
894 #ifdef DEBUG
895                 g_message ("%s: process %d added to array", __func__, pid);
896 #endif
897
898                 /* This ensures that duplicates aren't returned (see
899                  * the comment above _wapi_search_handle () for why
900                  * it's needed
901                  */
902                 for (i = 0; i < processes->len; i++) {
903                         if (g_array_index (processes, pid_t, i) == pid) {
904                                 /* We've already got this one, return
905                                  * FALSE to keep searching
906                                  */
907                                 return (FALSE);
908                         }
909                 }
910                 
911                 g_array_append_val (processes, pid);
912         }
913         
914         /* Return false to keep searching */
915         return(FALSE);
916 }
917
918 gboolean EnumProcesses (guint32 *pids, guint32 len, guint32 *needed)
919 {
920         GArray *processes = g_array_new (FALSE, FALSE, sizeof(pid_t));
921         guint32 fit, i, j;
922         
923         mono_once (&process_current_once, process_set_current);
924         
925         _wapi_search_handle (WAPI_HANDLE_PROCESS, process_enum, processes,
926                              NULL);
927         
928         fit=len/sizeof(guint32);
929         for (i = 0, j = 0; j < fit && i < processes->len; i++) {
930                 pids[j++] = g_array_index (processes, pid_t, i);
931         }
932
933         g_array_free (processes, TRUE);
934         
935         *needed = j * sizeof(guint32);
936         
937         return(TRUE);
938 }
939
940 static gboolean process_open_compare (gpointer handle, gpointer user_data)
941 {
942         pid_t wanted_pid;
943         pid_t checking_pid = signal_process_if_gone (handle);
944
945         if (checking_pid == 0) {
946                 return(FALSE);
947         }
948         
949         wanted_pid = GPOINTER_TO_UINT (user_data);
950
951         /* It's possible to have more than one process handle with the
952          * same pid, but only the one running process can be
953          * unsignalled
954          */
955         if (checking_pid == wanted_pid &&
956             _wapi_handle_issignalled (handle) == FALSE) {
957                 return(TRUE);
958         } else {
959                 return(FALSE);
960         }
961 }
962
963 gpointer OpenProcess (guint32 access G_GNUC_UNUSED, gboolean inherit G_GNUC_UNUSED, guint32 pid)
964 {
965         /* Find the process handle that corresponds to pid */
966         gpointer handle;
967         
968         mono_once (&process_current_once, process_set_current);
969
970 #ifdef DEBUG
971         g_message ("%s: looking for process %d", __func__, pid);
972 #endif
973
974         handle = _wapi_search_handle (WAPI_HANDLE_PROCESS,
975                                       process_open_compare,
976                                       GUINT_TO_POINTER (pid), NULL);
977         if (handle == 0) {
978 #ifdef DEBUG
979                 g_message ("%s: Can't find pid %d", __func__, pid);
980 #endif
981
982                 SetLastError (ERROR_PROC_NOT_FOUND);
983         
984                 return(NULL);
985         }
986
987         _wapi_handle_ref (handle);
988         
989         return(handle);
990 }
991
992 gboolean GetExitCodeProcess (gpointer process, guint32 *code)
993 {
994         struct _WapiHandle_process *process_handle;
995         gboolean ok;
996         
997         mono_once (&process_current_once, process_set_current);
998
999         if(code==NULL) {
1000                 return(FALSE);
1001         }
1002         
1003         ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
1004                                 (gpointer *)&process_handle);
1005         if(ok==FALSE) {
1006 #ifdef DEBUG
1007                 g_message ("%s: Can't find process %p", __func__, process);
1008 #endif
1009                 
1010                 return(FALSE);
1011         }
1012         
1013         /* A process handle is only signalled if the process has exited
1014          * and has been waited for */
1015         if (_wapi_handle_issignalled (process) == TRUE ||
1016             process_wait (process, 0) == WAIT_OBJECT_0) {
1017                 *code = process_handle->exitstatus;
1018         } else {
1019                 *code = STILL_ACTIVE;
1020         }
1021         
1022         return(TRUE);
1023 }
1024
1025 gboolean GetProcessTimes (gpointer process, WapiFileTime *create_time,
1026                           WapiFileTime *exit_time, WapiFileTime *kernel_time,
1027                           WapiFileTime *user_time)
1028 {
1029         struct _WapiHandle_process *process_handle;
1030         gboolean ok;
1031         
1032         mono_once (&process_current_once, process_set_current);
1033
1034         if(create_time==NULL || exit_time==NULL || kernel_time==NULL ||
1035            user_time==NULL) {
1036                 /* Not sure if w32 allows NULLs here or not */
1037                 return(FALSE);
1038         }
1039         
1040         ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
1041                                 (gpointer *)&process_handle);
1042         if(ok==FALSE) {
1043 #ifdef DEBUG
1044                 g_message ("%s: Can't find process %p", __func__, process);
1045 #endif
1046                 
1047                 return(FALSE);
1048         }
1049         
1050         *create_time=process_handle->create_time;
1051
1052         /* A process handle is only signalled if the process has
1053          * exited.  Otherwise exit_time isn't set
1054          */
1055         if(_wapi_handle_issignalled (process)==TRUE) {
1056                 *exit_time=process_handle->exit_time;
1057         }
1058         
1059         return(TRUE);
1060 }
1061
1062 gboolean EnumProcessModules (gpointer process, gpointer *modules,
1063                              guint32 size, guint32 *needed)
1064 {
1065         /* Store modules in an array of pointers (main module as
1066          * modules[0]), using the load address for each module as a
1067          * token.  (Use 'NULL' as an alternative for the main module
1068          * so that the simple implementation can just return one item
1069          * for now.)  Get the info from /proc/<pid>/maps on linux,
1070          * other systems will have to implement /dev/kmem reading or
1071          * whatever other horrid technique is needed.
1072          */
1073         if(size<sizeof(gpointer)) {
1074                 return(FALSE);
1075         }
1076         
1077 #ifdef linux
1078         modules[0]=NULL;
1079         *needed=sizeof(gpointer);
1080 #else
1081         modules[0]=NULL;
1082         *needed=sizeof(gpointer);
1083 #endif
1084         
1085         return(TRUE);
1086 }
1087
1088 guint32 GetModuleBaseName (gpointer process, gpointer module,
1089                            gunichar2 *basename, guint32 size)
1090 {
1091         struct _WapiHandle_process *process_handle;
1092         gboolean ok;
1093         
1094         mono_once (&process_current_once, process_set_current);
1095
1096 #ifdef DEBUG
1097         g_message ("%s: Getting module base name, process handle %p module %p",
1098                    __func__, process, module);
1099 #endif
1100
1101         if(basename==NULL || size==0) {
1102                 return(FALSE);
1103         }
1104         
1105         ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
1106                                 (gpointer *)&process_handle);
1107         if(ok==FALSE) {
1108 #ifdef DEBUG
1109                 g_message ("%s: Can't find process %p", __func__, process);
1110 #endif
1111                 
1112                 return(FALSE);
1113         }
1114
1115         if(module==NULL) {
1116                 /* Shorthand for the main module, which has the
1117                  * process name recorded in the handle data
1118                  */
1119                 pid_t pid;
1120                 gunichar2 *procname;
1121                 guchar *procname_utf8 = NULL;
1122                 glong len, bytes;
1123                 
1124 #ifdef DEBUG
1125                 g_message ("%s: Returning main module name", __func__);
1126 #endif
1127
1128                 pid=process_handle->id;
1129                 procname_utf8 = process_handle->proc_name;
1130         
1131 #ifdef DEBUG
1132                 g_message ("%s: Process name is [%s]", __func__,
1133                            procname_utf8);
1134 #endif
1135
1136                 procname = g_utf8_to_utf16 (procname_utf8, -1, NULL, &len,
1137                                             NULL);
1138                 if (procname == NULL) {
1139                         /* bugger */
1140                         return(0);
1141                 }
1142
1143                 /* Add the terminator, and convert chars to bytes */
1144                 bytes = (len + 1) * 2;
1145                 
1146                 if (size < bytes) {
1147 #ifdef DEBUG
1148                         g_message ("%s: Size %d smaller than needed (%ld); truncating", __func__, size, bytes);
1149 #endif
1150
1151                         memcpy (basename, procname, size);
1152                 } else {
1153 #ifdef DEBUG
1154                         g_message ("%s: Size %d larger than needed (%ld)",
1155                                    __func__, size, bytes);
1156 #endif
1157
1158                         memcpy (basename, procname, bytes);
1159                 }
1160                 
1161                 g_free (procname);
1162
1163                 return(len);
1164         } else {
1165                 /* Look up the address in /proc/<pid>/maps */
1166         }
1167         
1168         return(0);
1169 }
1170
1171 gboolean GetProcessWorkingSetSize (gpointer process, size_t *min, size_t *max)
1172 {
1173         struct _WapiHandle_process *process_handle;
1174         gboolean ok;
1175         
1176         mono_once (&process_current_once, process_set_current);
1177
1178         if(min==NULL || max==NULL) {
1179                 /* Not sure if w32 allows NULLs here or not */
1180                 return(FALSE);
1181         }
1182         
1183         ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
1184                                 (gpointer *)&process_handle);
1185         if(ok==FALSE) {
1186 #ifdef DEBUG
1187                 g_message ("%s: Can't find process %p", __func__, process);
1188 #endif
1189                 
1190                 return(FALSE);
1191         }
1192
1193         *min=process_handle->min_working_set;
1194         *max=process_handle->max_working_set;
1195         
1196         return(TRUE);
1197 }
1198
1199 gboolean SetProcessWorkingSetSize (gpointer process, size_t min, size_t max)
1200 {
1201         struct _WapiHandle_process *process_handle;
1202         gboolean ok;
1203
1204         mono_once (&process_current_once, process_set_current);
1205
1206         ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
1207                                 (gpointer *)&process_handle);
1208         if(ok==FALSE) {
1209 #ifdef DEBUG
1210                 g_message ("%s: Can't find process %p", __func__, process);
1211 #endif
1212                 
1213                 return(FALSE);
1214         }
1215
1216         process_handle->min_working_set=min;
1217         process_handle->max_working_set=max;
1218         
1219         return(TRUE);
1220 }
1221
1222
1223 gboolean
1224 TerminateProcess (gpointer process, gint32 exitCode)
1225 {
1226         struct _WapiHandle_process *process_handle;
1227         gboolean ok;
1228         int signo;
1229         int ret;
1230
1231         ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
1232                                   (gpointer *) &process_handle);
1233
1234         if (ok == FALSE) {
1235 #ifdef DEBUG
1236                 g_message ("%s: Can't find process %p", __func__, process);
1237 #endif
1238                 SetLastError (ERROR_INVALID_HANDLE);
1239                 return FALSE;
1240         }
1241
1242         signo = (exitCode == -1) ? SIGKILL : SIGTERM;
1243         ret = kill (process_handle->id, signo);
1244         if (ret == -1) {
1245                 switch (errno) {
1246                 case EINVAL:
1247                         SetLastError (ERROR_INVALID_PARAMETER);
1248                         break;
1249                 case EPERM:
1250                         SetLastError (ERROR_ACCESS_DENIED);
1251                         break;
1252                 case ESRCH:
1253                         SetLastError (ERROR_PROC_NOT_FOUND);
1254                         break;
1255                 default:
1256                         SetLastError (ERROR_GEN_FAILURE);
1257                 }
1258         }
1259         
1260         return (ret == 0);
1261 }
1262