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