Avoid adding a ref in OpenProcess (), it is already added in _wapi_search_handle...
[mono.git] / mono / io-layer / processes.c
1 /*
2  * processes.c:  Process handles
3  *
4  * Author:
5  *      Dick Porter (dick@ximian.com)
6  *
7  * (C) 2002-2006 Novell, Inc.
8  */
9
10 #include <config.h>
11 #include <glib.h>
12 #include <stdio.h>
13 #include <string.h>
14 #include <pthread.h>
15 #include <sched.h>
16 #include <sys/time.h>
17 #include <errno.h>
18 #include <sys/types.h>
19 #include <sys/stat.h>
20 #include <unistd.h>
21 #include <signal.h>
22 #include <sys/wait.h>
23 #include <sys/time.h>
24 #include <sys/resource.h>
25 #include <fcntl.h>
26 #include <sys/param.h>
27 #include <ctype.h>
28
29 #ifdef HAVE_SYS_MKDEV_H
30 #include <sys/mkdev.h>
31 #endif
32
33 /* sys/resource.h (for rusage) is required when using osx 10.3 (but not 10.4) */
34 #ifdef __APPLE__
35 #include <sys/resource.h>
36 #endif
37
38 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__)
39 #include <sys/proc.h>
40 #include <sys/sysctl.h>
41 #  if !defined(__OpenBSD__)
42 #    include <sys/utsname.h>
43 #  endif
44 #endif
45
46 #ifdef PLATFORM_SOLARIS
47 /* procfs.h cannot be included if this define is set, but it seems to work fine if it is undefined */
48 #if _FILE_OFFSET_BITS == 64
49 #undef _FILE_OFFSET_BITS
50 #include <procfs.h>
51 #define _FILE_OFFSET_BITS 64
52 #else
53 #include <procfs.h>
54 #endif
55 #endif
56
57 #ifdef __HAIKU__
58 #include <KernelKit.h>
59 #endif
60
61 #include <mono/io-layer/wapi.h>
62 #include <mono/io-layer/wapi-private.h>
63 #include <mono/io-layer/handles-private.h>
64 #include <mono/io-layer/misc-private.h>
65 #include <mono/io-layer/mono-mutex.h>
66 #include <mono/io-layer/process-private.h>
67 #include <mono/io-layer/threads.h>
68 #include <mono/utils/strenc.h>
69 #include <mono/utils/mono-path.h>
70 #include <mono/io-layer/timefuncs-private.h>
71 #include <mono/utils/mono-time.h>
72 #include <mono/utils/mono-membar.h>
73
74 /* The process' environment strings */
75 #if defined(__APPLE__) && !defined (__arm__)
76 /* Apple defines this in crt_externs.h but doesn't provide that header for 
77  * arm-apple-darwin9.  We'll manually define the symbol on Apple as it does
78  * in fact exist on all implementations (so far) 
79  */
80 gchar ***_NSGetEnviron(void);
81 #define environ (*_NSGetEnviron())
82 #else
83 extern char **environ;
84 #endif
85
86 #undef DEBUG
87
88 static guint32 process_wait (gpointer handle, guint32 timeout, gboolean alertable);
89 static void process_close (gpointer handle, gpointer data);
90 static gboolean is_pid_valid (pid_t pid);
91
92 #if !defined(__OpenBSD__)
93 static FILE *
94 open_process_map (int pid, const char *mode);
95 #endif
96
97 struct _WapiHandleOps _wapi_process_ops = {
98         process_close,          /* close_shared */
99         NULL,                           /* signal */
100         NULL,                           /* own */
101         NULL,                           /* is_owned */
102         process_wait,                   /* special_wait */
103         NULL                            /* prewait */   
104 };
105
106 #if HAVE_SIGACTION
107 static struct sigaction previous_chld_sa;
108 #endif
109 static mono_once_t process_sig_chld_once = MONO_ONCE_INIT;
110 static void process_add_sigchld_handler (void);
111
112 /* The signal-safe logic to use mono_processes goes like this:
113  * - The list must be safe to traverse for the signal handler at all times.
114  *   It's safe to: prepend an entry (which is a single store to 'mono_processes'),
115  *   unlink an entry (assuming the unlinked entry isn't freed and doesn't 
116  *   change its 'next' pointer so that it can still be traversed).
117  * When cleaning up we first unlink an entry, then we verify that
118  * the read lock isn't locked. Then we can free the entry, since
119  * we know that nobody is using the old version of the list (including
120  * the unlinked entry).
121  * We also need to lock when adding and cleaning up so that those two
122  * operations don't mess with eachother. (This lock is not used in the
123  * signal handler)
124  */
125 static struct MonoProcess *mono_processes = NULL;
126 static volatile gint32 mono_processes_read_lock = 0;
127 static volatile gint32 mono_processes_cleaning_up = 0;
128 static mono_mutex_t mono_processes_mutex;
129 static void mono_processes_cleanup (void);
130
131 static mono_once_t process_current_once=MONO_ONCE_INIT;
132 static gpointer current_process=NULL;
133
134 static mono_once_t process_ops_once=MONO_ONCE_INIT;
135
136 static void process_ops_init (void)
137 {
138         _wapi_handle_register_capabilities (WAPI_HANDLE_PROCESS,
139                                             WAPI_HANDLE_CAP_WAIT |
140                                             WAPI_HANDLE_CAP_SPECIAL_WAIT);
141 }
142
143
144 /* Check if a pid is valid - i.e. if a process exists with this pid. */
145 static gboolean is_pid_valid (pid_t pid)
146 {
147         gboolean result = FALSE;
148
149 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__)
150         if (((kill(pid, 0) == 0) || (errno == EPERM)) && pid != 0)
151                 result = TRUE;
152 #elif defined(__HAIKU__)
153         team_info teamInfo;
154         if (get_team_info ((team_id)pid, &teamInfo) == B_OK)
155                 result = TRUE;
156 #else
157         gchar *dir = g_strdup_printf ("/proc/%d", pid);
158         if (!access (dir, F_OK))
159                 result = TRUE;
160         g_free (dir);
161 #endif
162         
163         return result;
164 }
165
166 static void process_set_defaults (struct _WapiHandle_process *process_handle)
167 {
168         /* These seem to be the defaults on w2k */
169         process_handle->min_working_set = 204800;
170         process_handle->max_working_set = 1413120;
171         
172         _wapi_time_t_to_filetime (time (NULL), &process_handle->create_time);
173 }
174
175 static int
176 len16 (const gunichar2 *str)
177 {
178         int len = 0;
179         
180         while (*str++ != 0)
181                 len++;
182
183         return len;
184 }
185
186 static gunichar2 *
187 utf16_concat (const gunichar2 *first, ...)
188 {
189         va_list args;
190         int total = 0, i;
191         const gunichar2 *s;
192         gunichar2 *ret;
193
194         va_start (args, first);
195         total += len16 (first);
196         for (s = va_arg (args, gunichar2 *); s != NULL; s = va_arg(args, gunichar2 *)){
197                 total += len16 (s);
198         }
199         va_end (args);
200
201         ret = g_new (gunichar2, total + 1);
202         if (ret == NULL)
203                 return NULL;
204
205         ret [total] = 0;
206         i = 0;
207         for (s = first; *s != 0; s++)
208                 ret [i++] = *s;
209         va_start (args, first);
210         for (s = va_arg (args, gunichar2 *); s != NULL; s = va_arg (args, gunichar2 *)){
211                 const gunichar2 *p;
212                 
213                 for (p = s; *p != 0; p++)
214                         ret [i++] = *p;
215         }
216         va_end (args);
217         
218         return ret;
219 }
220
221 #ifdef PLATFORM_MACOSX
222
223 /* 0 = no detection; -1 = not 10.5 or higher;  1 = 10.5 or higher */
224 static int osx_10_5_or_higher;
225
226 static void
227 detect_osx_10_5_or_higher (void)
228 {
229         struct utsname u;
230         char *p;
231         int v;
232         
233         if (uname (&u) != 0){
234                 osx_10_5_or_higher = 1;
235                 return;
236         }
237
238         p = u.release;
239         v = atoi (p);
240         
241         if (v < 9)
242                 osx_10_5_or_higher = -1;
243         else 
244                 osx_10_5_or_higher = 1;
245 }
246
247 static gboolean
248 is_macos_10_5_or_higher (void)
249 {
250         if (osx_10_5_or_higher == 0)
251                 detect_osx_10_5_or_higher ();
252         
253         return (osx_10_5_or_higher == 1);
254 }
255 #endif
256
257 static const gunichar2 utf16_space_bytes [2] = { 0x20, 0 };
258 static const gunichar2 *utf16_space = utf16_space_bytes; 
259 static const gunichar2 utf16_quote_bytes [2] = { 0x22, 0 };
260 static const gunichar2 *utf16_quote = utf16_quote_bytes;
261
262 #ifdef DEBUG
263 /* Useful in gdb */
264 void
265 print_utf16 (gunichar2 *str)
266 {
267         gchar *res;
268
269         res = g_utf16_to_utf8 (str, -1, NULL, NULL, NULL);
270         g_print ("%s\n", res);
271         g_free (res);
272 }
273 #endif
274
275 /* Implemented as just a wrapper around CreateProcess () */
276 gboolean ShellExecuteEx (WapiShellExecuteInfo *sei)
277 {
278         gboolean ret;
279         WapiProcessInformation process_info;
280         gunichar2 *args;
281         
282         if (sei == NULL) {
283                 /* w2k just segfaults here, but we can do better than
284                  * that
285                  */
286                 SetLastError (ERROR_INVALID_PARAMETER);
287                 return (FALSE);
288         }
289
290         if (sei->lpFile == NULL) {
291                 /* w2k returns TRUE for this, for some reason. */
292                 return (TRUE);
293         }
294         
295         /* Put both executable and parameters into the second argument
296          * to CreateProcess (), so it searches $PATH.  The conversion
297          * into and back out of utf8 is because there is no
298          * g_strdup_printf () equivalent for gunichar2 :-(
299          */
300         args = utf16_concat (utf16_quote, sei->lpFile, utf16_quote, sei->lpParameters == NULL ? NULL : utf16_space, sei->lpParameters, NULL);
301         if (args == NULL){
302                 SetLastError (ERROR_INVALID_DATA);
303                 return (FALSE);
304         }
305         ret = CreateProcess (NULL, args, NULL, NULL, TRUE,
306                              CREATE_UNICODE_ENVIRONMENT, NULL,
307                              sei->lpDirectory, NULL, &process_info);
308         g_free (args);
309
310         if (!ret && GetLastError () == ERROR_OUTOFMEMORY)
311                 return ret;
312         
313         if (!ret) {
314                 static char *handler;
315                 static gunichar2 *handler_utf16;
316                 
317                 if (handler_utf16 == (gunichar2 *)-1)
318                         return FALSE;
319
320 #ifdef PLATFORM_MACOSX
321                 if (is_macos_10_5_or_higher ())
322                         handler = g_strdup ("/usr/bin/open -W");
323                 else
324                         handler = g_strdup ("/usr/bin/open");
325 #else
326                 /*
327                  * On Linux, try: xdg-open, the FreeDesktop standard way of doing it,
328                  * if that fails, try to use gnome-open, then kfmclient
329                  */
330                 handler = g_find_program_in_path ("xdg-open");
331                 if (handler == NULL){
332                         handler = g_find_program_in_path ("gnome-open");
333                         if (handler == NULL){
334                                 handler = g_find_program_in_path ("kfmclient");
335                                 if (handler == NULL){
336                                         handler_utf16 = (gunichar2 *) -1;
337                                         return (FALSE);
338                                 } else {
339                                         /* kfmclient needs exec argument */
340                                         char *old = handler;
341                                         handler = g_strconcat (old, " exec",
342                                                                NULL);
343                                         g_free (old);
344                                 }
345                         }
346                 }
347 #endif
348                 handler_utf16 = g_utf8_to_utf16 (handler, -1, NULL, NULL, NULL);
349                 g_free (handler);
350
351                 /* Put quotes around the filename, in case it's a url
352                  * that contains #'s (CreateProcess() calls
353                  * g_shell_parse_argv(), which deliberately throws
354                  * away anything after an unquoted #).  Fixes bug
355                  * 371567.
356                  */
357                 args = utf16_concat (handler_utf16, utf16_space, utf16_quote,
358                                      sei->lpFile, utf16_quote,
359                                      sei->lpParameters == NULL ? NULL : utf16_space,
360                                      sei->lpParameters, NULL);
361                 if (args == NULL){
362                         SetLastError (ERROR_INVALID_DATA);
363                         return FALSE;
364                 }
365                 ret = CreateProcess (NULL, args, NULL, NULL, TRUE,
366                                      CREATE_UNICODE_ENVIRONMENT, NULL,
367                                      sei->lpDirectory, NULL, &process_info);
368                 g_free (args);
369                 if (!ret){
370                         SetLastError (ERROR_INVALID_DATA);
371                         return FALSE;
372                 }
373         }
374         
375         if (sei->fMask & SEE_MASK_NOCLOSEPROCESS) {
376                 sei->hProcess = process_info.hProcess;
377         } else {
378                 CloseHandle (process_info.hProcess);
379         }
380         
381         return (ret);
382 }
383
384 static gboolean
385 is_managed_binary (const gchar *filename)
386 {
387         int original_errno = errno;
388 #if defined(HAVE_LARGE_FILE_SUPPORT) && defined(O_LARGEFILE)
389         int file = open (filename, O_RDONLY | O_LARGEFILE);
390 #else
391         int file = open (filename, O_RDONLY);
392 #endif
393         off_t new_offset;
394         unsigned char buffer[8];
395         off_t file_size, optional_header_offset;
396         off_t pe_header_offset;
397         gboolean managed = FALSE;
398         int num_read;
399         guint32 first_word, second_word;
400         
401         /* If we are unable to open the file, then we definitely
402          * can't say that it is managed. The child mono process
403          * probably wouldn't be able to open it anyway.
404          */
405         if (file < 0) {
406                 errno = original_errno;
407                 return FALSE;
408         }
409
410         /* Retrieve the length of the file for future sanity checks. */
411         file_size = lseek (file, 0, SEEK_END);
412         lseek (file, 0, SEEK_SET);
413
414         /* We know we need to read a header field at offset 60. */
415         if (file_size < 64)
416                 goto leave;
417
418         num_read = read (file, buffer, 2);
419
420         if ((num_read != 2) || (buffer[0] != 'M') || (buffer[1] != 'Z'))
421                 goto leave;
422
423         new_offset = lseek (file, 60, SEEK_SET);
424
425         if (new_offset != 60)
426                 goto leave;
427         
428         num_read = read (file, buffer, 4);
429
430         if (num_read != 4)
431                 goto leave;
432         pe_header_offset =  buffer[0]
433                 | (buffer[1] <<  8)
434                 | (buffer[2] << 16)
435                 | (buffer[3] << 24);
436         
437         if (pe_header_offset + 24 > file_size)
438                 goto leave;
439
440         new_offset = lseek (file, pe_header_offset, SEEK_SET);
441
442         if (new_offset != pe_header_offset)
443                 goto leave;
444
445         num_read = read (file, buffer, 4);
446
447         if ((num_read != 4) || (buffer[0] != 'P') || (buffer[1] != 'E') || (buffer[2] != 0) || (buffer[3] != 0))
448                 goto leave;
449
450         /*
451          * Verify that the header we want in the optional header data
452          * is present in this binary.
453          */
454         new_offset = lseek (file, pe_header_offset + 20, SEEK_SET);
455
456         if (new_offset != pe_header_offset + 20)
457                 goto leave;
458
459         num_read = read (file, buffer, 2);
460
461         if ((num_read != 2) || ((buffer[0] | (buffer[1] << 8)) < 216))
462                 goto leave;
463
464         /* Read the CLR header address and size fields. These will be
465          * zero if the binary is not managed.
466          */
467         optional_header_offset = pe_header_offset + 24;
468         new_offset = lseek (file, optional_header_offset + 208, SEEK_SET);
469
470         if (new_offset != optional_header_offset + 208)
471                 goto leave;
472
473         num_read = read (file, buffer, 8);
474         
475         /* We are not concerned with endianness, only with
476          * whether it is zero or not.
477          */
478         first_word = *(guint32 *)&buffer[0];
479         second_word = *(guint32 *)&buffer[4];
480         
481         if ((num_read != 8) || (first_word == 0) || (second_word == 0))
482                 goto leave;
483         
484         managed = TRUE;
485
486 leave:
487         close (file);
488         errno = original_errno;
489         return managed;
490 }
491
492 gboolean CreateProcessWithLogonW (const gunichar2 *username,
493                                   const gunichar2 *domain,
494                                   const gunichar2 *password,
495                                   const guint32 logonFlags,
496                                   const gunichar2 *appname,
497                                   const gunichar2 *cmdline,
498                                   guint32 create_flags,
499                                   gpointer env,
500                                   const gunichar2 *cwd,
501                                   WapiStartupInfo *startup,
502                                   WapiProcessInformation *process_info)
503 {
504         /* FIXME: use user information */
505         return CreateProcess (appname, cmdline, NULL, NULL, FALSE, create_flags, env, cwd, startup, process_info);
506 }
507
508 static gboolean
509 is_executable (const char *prog)
510 {
511         struct stat buf;
512         if (access (prog, X_OK) != 0)
513                 return FALSE;
514         if (stat (prog, &buf))
515                 return FALSE;
516         if (S_ISREG (buf.st_mode))
517                 return TRUE;
518         return FALSE;
519 }
520
521 static void
522 switchDirectorySeparators(gchar *path)
523 {
524         size_t i, pathLength = strlen(path);
525         
526         /* Turn all the slashes round the right way, except for \' */
527         /* There are probably other characters that need to be excluded as well. */
528         for (i = 0; i < pathLength; i++)
529         {
530                 if (path[i] == '\\' && i < pathLength - 1 && path[i+1] != '\'' ) {
531                         path[i] = '/';
532                 }
533         }
534 }
535
536 gboolean CreateProcess (const gunichar2 *appname, const gunichar2 *cmdline,
537                         WapiSecurityAttributes *process_attrs G_GNUC_UNUSED,
538                         WapiSecurityAttributes *thread_attrs G_GNUC_UNUSED,
539                         gboolean inherit_handles, guint32 create_flags,
540                         gpointer new_environ, const gunichar2 *cwd,
541                         WapiStartupInfo *startup,
542                         WapiProcessInformation *process_info)
543 {
544         gchar *cmd=NULL, *prog = NULL, *full_prog = NULL, *args = NULL, *args_after_prog = NULL, *dir = NULL, **env_strings = NULL, **argv = NULL;
545         guint32 i, env_count = 0;
546         gboolean ret = FALSE;
547         gpointer handle;
548         struct _WapiHandle_process process_handle = {0}, *process_handle_data;
549         GError *gerr = NULL;
550         int in_fd, out_fd, err_fd;
551         pid_t pid;
552         int thr_ret;
553         int startup_pipe [2] = {-1, -1};
554         int dummy;
555         struct MonoProcess *mono_process;
556         
557         mono_once (&process_ops_once, process_ops_init);
558         mono_once (&process_sig_chld_once, process_add_sigchld_handler);
559         
560         /* appname and cmdline specify the executable and its args:
561          *
562          * If appname is not NULL, it is the name of the executable.
563          * Otherwise the executable is the first token in cmdline.
564          *
565          * Executable searching:
566          *
567          * If appname is not NULL, it can specify the full path and
568          * file name, or else a partial name and the current directory
569          * will be used.  There is no additional searching.
570          *
571          * If appname is NULL, the first whitespace-delimited token in
572          * cmdline is used.  If the name does not contain a full
573          * directory path, the search sequence is:
574          *
575          * 1) The directory containing the current process
576          * 2) The current working directory
577          * 3) The windows system directory  (Ignored)
578          * 4) The windows directory (Ignored)
579          * 5) $PATH
580          *
581          * Just to make things more interesting, tokens can contain
582          * white space if they are surrounded by quotation marks.  I'm
583          * beginning to understand just why windows apps are generally
584          * so crap, with an API like this :-(
585          */
586         if (appname != NULL) {
587                 cmd = mono_unicode_to_external (appname);
588                 if (cmd == NULL) {
589 #ifdef DEBUG
590                         g_message ("%s: unicode conversion returned NULL",
591                                    __func__);
592 #endif
593
594                         SetLastError (ERROR_PATH_NOT_FOUND);
595                         goto free_strings;
596                 }
597
598                 switchDirectorySeparators(cmd);
599         }
600         
601         if (cmdline != NULL) {
602                 args = mono_unicode_to_external (cmdline);
603                 if (args == NULL) {
604 #ifdef DEBUG
605                         g_message ("%s: unicode conversion returned NULL", __func__);
606 #endif
607
608                         SetLastError (ERROR_PATH_NOT_FOUND);
609                         goto free_strings;
610                 }
611         }
612
613         if (cwd != NULL) {
614                 dir = mono_unicode_to_external (cwd);
615                 if (dir == NULL) {
616 #ifdef DEBUG
617                         g_message ("%s: unicode conversion returned NULL", __func__);
618 #endif
619
620                         SetLastError (ERROR_PATH_NOT_FOUND);
621                         goto free_strings;
622                 }
623
624                 /* Turn all the slashes round the right way */
625                 switchDirectorySeparators(dir);
626         }
627         
628
629         /* We can't put off locating the executable any longer :-( */
630         if (cmd != NULL) {
631                 gchar *unquoted;
632                 if (g_ascii_isalpha (cmd[0]) && (cmd[1] == ':')) {
633                         /* Strip off the drive letter.  I can't
634                          * believe that CP/M holdover is still
635                          * visible...
636                          */
637                         g_memmove (cmd, cmd+2, strlen (cmd)-2);
638                         cmd[strlen (cmd)-2] = '\0';
639                 }
640
641                 unquoted = g_shell_unquote (cmd, NULL);
642                 if (unquoted[0] == '/') {
643                         /* Assume full path given */
644                         prog = g_strdup (unquoted);
645
646                         /* Executable existing ? */
647                         if (!is_executable (prog)) {
648 #ifdef DEBUG
649                                 g_message ("%s: Couldn't find executable %s",
650                                            __func__, prog);
651 #endif
652                                 g_free (unquoted);
653                                 SetLastError (ERROR_FILE_NOT_FOUND);
654                                 goto free_strings;
655                         }
656                 } else {
657                         /* Search for file named by cmd in the current
658                          * directory
659                          */
660                         char *curdir = g_get_current_dir ();
661
662                         prog = g_strdup_printf ("%s/%s", curdir, unquoted);
663                         g_free (curdir);
664
665                         /* And make sure it's executable */
666                         if (!is_executable (prog)) {
667 #ifdef DEBUG
668                                 g_message ("%s: Couldn't find executable %s",
669                                            __func__, prog);
670 #endif
671                                 g_free (unquoted);
672                                 SetLastError (ERROR_FILE_NOT_FOUND);
673                                 goto free_strings;
674                         }
675                 }
676                 g_free (unquoted);
677
678                 args_after_prog = args;
679         } else {
680                 gchar *token = NULL;
681                 char quote;
682                 
683                 /* Dig out the first token from args, taking quotation
684                  * marks into account
685                  */
686
687                 /* First, strip off all leading whitespace */
688                 args = g_strchug (args);
689                 
690                 /* args_after_prog points to the contents of args
691                  * after token has been set (otherwise argv[0] is
692                  * duplicated)
693                  */
694                 args_after_prog = args;
695
696                 /* Assume the opening quote will always be the first
697                  * character
698                  */
699                 if (args[0] == '\"' || args [0] == '\'') {
700                         quote = args [0];
701                         for (i = 1; args[i] != '\0' && args[i] != quote; i++);
702                         if (args [i + 1] == '\0' || g_ascii_isspace (args[i+1])) {
703                                 /* We found the first token */
704                                 token = g_strndup (args+1, i-1);
705                                 args_after_prog = g_strchug (args + i + 1);
706                         } else {
707                                 /* Quotation mark appeared in the
708                                  * middle of the token.  Just give the
709                                  * whole first token, quotes and all,
710                                  * to exec.
711                                  */
712                         }
713                 }
714                 
715                 if (token == NULL) {
716                         /* No quote mark, or malformed */
717                         for (i = 0; args[i] != '\0'; i++) {
718                                 if (g_ascii_isspace (args[i])) {
719                                         token = g_strndup (args, i);
720                                         args_after_prog = args + i + 1;
721                                         break;
722                                 }
723                         }
724                 }
725
726                 if (token == NULL && args[0] != '\0') {
727                         /* Must be just one token in the string */
728                         token = g_strdup (args);
729                         args_after_prog = NULL;
730                 }
731                 
732                 if (token == NULL) {
733                         /* Give up */
734 #ifdef DEBUG
735                         g_message ("%s: Couldn't find what to exec", __func__);
736 #endif
737
738                         SetLastError (ERROR_PATH_NOT_FOUND);
739                         goto free_strings;
740                 }
741                 
742                 /* Turn all the slashes round the right way. Only for
743                  * the prg. name
744                  */
745                 switchDirectorySeparators(token);
746
747                 if (g_ascii_isalpha (token[0]) && (token[1] == ':')) {
748                         /* Strip off the drive letter.  I can't
749                          * believe that CP/M holdover is still
750                          * visible...
751                          */
752                         g_memmove (token, token+2, strlen (token)-2);
753                         token[strlen (token)-2] = '\0';
754                 }
755
756                 if (token[0] == '/') {
757                         /* Assume full path given */
758                         prog = g_strdup (token);
759                         
760                         /* Executable existing ? */
761                         if (!is_executable (prog)) {
762 #ifdef DEBUG
763                                 g_message ("%s: Couldn't find executable %s",
764                                            __func__, token);
765 #endif
766                                 g_free (token);
767                                 SetLastError (ERROR_FILE_NOT_FOUND);
768                                 goto free_strings;
769                         }
770
771                 } else {
772                         char *curdir = g_get_current_dir ();
773
774                         /* FIXME: Need to record the directory
775                          * containing the current process, and check
776                          * that for the new executable as the first
777                          * place to look
778                          */
779
780                         prog = g_strdup_printf ("%s/%s", curdir, token);
781                         g_free (curdir);
782
783                         /* I assume X_OK is the criterion to use,
784                          * rather than F_OK
785                          */
786                         if (!is_executable (prog)) {
787                                 g_free (prog);
788                                 prog = g_find_program_in_path (token);
789                                 if (prog == NULL) {
790 #ifdef DEBUG
791                                         g_message ("%s: Couldn't find executable %s", __func__, token);
792 #endif
793
794                                         g_free (token);
795                                         SetLastError (ERROR_FILE_NOT_FOUND);
796                                         goto free_strings;
797                                 }
798                         }
799                 }
800
801                 g_free (token);
802         }
803
804 #ifdef DEBUG
805         g_message ("%s: Exec prog [%s] args [%s]", __func__, prog,
806                    args_after_prog);
807 #endif
808         
809         /* Check for CLR binaries; if found, we will try to invoke
810          * them using the same mono binary that started us.
811          */
812         if (is_managed_binary (prog)) {
813                 gunichar2 *newapp, *newcmd;
814                 gsize bytes_ignored;
815
816                 newapp = mono_unicode_from_external ("mono", &bytes_ignored);
817
818                 if (newapp != NULL) {
819                         if (appname != NULL) {
820                                 newcmd = utf16_concat (newapp, utf16_space,
821                                                        appname, utf16_space,
822                                                        cmdline, NULL);
823                         } else {
824                                 newcmd = utf16_concat (newapp, utf16_space,
825                                                        cmdline, NULL);
826                         }
827                         
828                         g_free ((gunichar2 *)newapp);
829                         
830                         if (newcmd != NULL) {
831                                 ret = CreateProcess (NULL, newcmd,
832                                                      process_attrs,
833                                                      thread_attrs,
834                                                      inherit_handles,
835                                                      create_flags, new_environ,
836                                                      cwd, startup,
837                                                      process_info);
838                                 
839                                 g_free ((gunichar2 *)newcmd);
840                                 
841                                 goto free_strings;
842                         }
843                 }
844         }
845
846         if (args_after_prog != NULL && *args_after_prog) {
847                 gchar *qprog;
848
849                 qprog = g_shell_quote (prog);
850                 full_prog = g_strconcat (qprog, " ", args_after_prog, NULL);
851                 g_free (qprog);
852         } else {
853                 full_prog = g_shell_quote (prog);
854         }
855
856         ret = g_shell_parse_argv (full_prog, NULL, &argv, &gerr);
857         if (ret == FALSE) {
858                 g_message ("CreateProcess: %s\n", gerr->message);
859                 g_error_free (gerr);
860                 gerr = NULL;
861                 goto free_strings;
862         }
863
864         if (startup != NULL && startup->dwFlags & STARTF_USESTDHANDLES) {
865                 in_fd = GPOINTER_TO_UINT (startup->hStdInput);
866                 out_fd = GPOINTER_TO_UINT (startup->hStdOutput);
867                 err_fd = GPOINTER_TO_UINT (startup->hStdError);
868         } else {
869                 in_fd = GPOINTER_TO_UINT (GetStdHandle (STD_INPUT_HANDLE));
870                 out_fd = GPOINTER_TO_UINT (GetStdHandle (STD_OUTPUT_HANDLE));
871                 err_fd = GPOINTER_TO_UINT (GetStdHandle (STD_ERROR_HANDLE));
872         }
873         
874         g_strlcpy (process_handle.proc_name, prog,
875                    _WAPI_PROC_NAME_MAX_LEN - 1);
876
877         process_set_defaults (&process_handle);
878         
879         handle = _wapi_handle_new (WAPI_HANDLE_PROCESS, &process_handle);
880         if (handle == _WAPI_HANDLE_INVALID) {
881                 g_warning ("%s: error creating process handle", __func__);
882
883                 ret = FALSE;
884                 SetLastError (ERROR_OUTOFMEMORY);
885                 goto free_strings;
886         }
887
888         /* new_environ is a block of NULL-terminated strings, which
889          * is itself NULL-terminated. Of course, passing an array of
890          * string pointers would have made things too easy :-(
891          *
892          * If new_environ is not NULL it specifies the entire set of
893          * environment variables in the new process.  Otherwise the
894          * new process inherits the same environment.
895          */
896         if (new_environ != NULL) {
897                 gunichar2 *new_environp;
898
899                 /* Count the number of strings */
900                 for (new_environp = (gunichar2 *)new_environ; *new_environp;
901                      new_environp++) {
902                         env_count++;
903                         while (*new_environp) {
904                                 new_environp++;
905                         }
906                 }
907
908                 /* +2: one for the process handle value, and the last
909                  * one is NULL
910                  */
911                 env_strings = g_new0 (gchar *, env_count + 2);
912                 
913                 /* Copy each environ string into 'strings' turning it
914                  * into utf8 (or the requested encoding) at the same
915                  * time
916                  */
917                 env_count = 0;
918                 for (new_environp = (gunichar2 *)new_environ; *new_environp;
919                      new_environp++) {
920                         env_strings[env_count] = mono_unicode_to_external (new_environp);
921                         env_count++;
922                         while (*new_environp) {
923                                 new_environp++;
924                         }
925                 }
926         } else {
927                 for (i = 0; environ[i] != NULL; i++) {
928                         env_count++;
929                 }
930
931                 /* +2: one for the process handle value, and the last
932                  * one is NULL
933                  */
934                 env_strings = g_new0 (gchar *, env_count + 2);
935                 
936                 /* Copy each environ string into 'strings' turning it
937                  * into utf8 (or the requested encoding) at the same
938                  * time
939                  */
940                 env_count = 0;
941                 for (i = 0; environ[i] != NULL; i++) {
942                         env_strings[env_count] = g_strdup (environ[i]);
943                         env_count++;
944                 }
945         }
946         /* pass process handle info to the child, so it doesn't have
947          * to do an expensive search over the whole list
948          */
949         if (env_strings != NULL) {
950                 struct _WapiHandleUnshared *handle_data;
951                 struct _WapiHandle_shared_ref *ref;
952                 
953                 handle_data = &_WAPI_PRIVATE_HANDLES(GPOINTER_TO_UINT(handle));
954                 ref = &handle_data->u.shared;
955                 
956                 env_strings[env_count] = g_strdup_printf ("_WAPI_PROCESS_HANDLE_OFFSET=%d", ref->offset);
957         }
958
959         /* Create a pipe to make sure the child doesn't exit before 
960          * we can add the process to the linked list of mono_processes */
961         if (pipe (startup_pipe) == -1) {
962                 /* Could not create the pipe to synchroniz process startup. We'll just not synchronize.
963                  * This is just for a very hard to hit race condition in the first place */
964                 startup_pipe [0] = startup_pipe [1] = -1;
965 #if DEBUG
966                 g_warning ("%s: new process startup not synchronized. We may not notice if the newly created process exits immediately.", __func__);
967 #endif
968         }
969
970         thr_ret = _wapi_handle_lock_shared_handles ();
971         g_assert (thr_ret == 0);
972         
973         pid = fork ();
974         if (pid == -1) {
975                 /* Error */
976                 SetLastError (ERROR_OUTOFMEMORY);
977                 _wapi_handle_unref (handle);
978                 goto cleanup;
979         } else if (pid == 0) {
980                 /* Child */
981                 
982                 if (startup_pipe [0] != -1) {
983                         /* Wait until the parent has updated it's internal data */
984                         read (startup_pipe [0], &dummy, 1);
985 #if DEBUG
986                         g_warning ("%s: child: parent has completed its setup", __func__);
987 #endif
988                         close (startup_pipe [0]);
989                         close (startup_pipe [1]);
990                 }
991                 
992                 /* should we detach from the process group? */
993
994                 /* Connect stdin, stdout and stderr */
995                 dup2 (in_fd, 0);
996                 dup2 (out_fd, 1);
997                 dup2 (err_fd, 2);
998
999                 if (inherit_handles != TRUE) {
1000                         /* FIXME: do something here */
1001                 }
1002                 
1003                 /* Close all file descriptors */
1004                 for (i = getdtablesize () - 1; i > 2; i--) {
1005                         close (i);
1006                 }
1007
1008 #ifdef DEBUG
1009                 g_message ("%s: exec()ing [%s] in dir [%s]", __func__, cmd,
1010                            dir==NULL?".":dir);
1011                 for (i = 0; argv[i] != NULL; i++) {
1012                         g_message ("arg %d: [%s]", i, argv[i]);
1013                 }
1014                 
1015                 for (i = 0; env_strings[i] != NULL; i++) {
1016                         g_message ("env %d: [%s]", i, env_strings[i]);
1017                 }
1018 #endif
1019
1020                 /* set cwd */
1021                 if (dir != NULL && chdir (dir) == -1) {
1022                         /* set error */
1023                         _exit (-1);
1024                 }
1025                 
1026                 /* exec */
1027                 execve (argv[0], argv, env_strings);
1028                 
1029                 /* set error */
1030                 _exit (-1);
1031         }
1032         /* parent */
1033         
1034         ret = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
1035                                    (gpointer *)&process_handle_data);
1036         if (ret == FALSE) {
1037                 g_warning ("%s: error looking up process handle %p", __func__,
1038                            handle);
1039                 _wapi_handle_unref (handle);
1040                 goto cleanup;
1041         }
1042         
1043         process_handle_data->id = pid;
1044
1045         /* Add our mono_process into the linked list of mono_processes */
1046         mono_process = (struct MonoProcess *) g_malloc0 (sizeof (struct MonoProcess));
1047         mono_process->pid = pid;
1048         mono_process->handle_count = 1;
1049         if (MONO_SEM_INIT (&mono_process->exit_sem, 0) != 0) {
1050                 /* If we can't create the exit semaphore, we just don't add anything
1051                  * to our list of mono processes. Waiting on the process will return 
1052                  * immediately. */
1053                 g_warning ("%s: could not create exit semaphore for process.", strerror (errno));
1054                 g_free (mono_process);
1055         } else {
1056                 /* Keep the process handle artificially alive until the process
1057                  * exits so that the information in the handle isn't lost. */
1058                 _wapi_handle_ref (handle);
1059                 mono_process->handle = handle;
1060
1061                 process_handle_data->self = _wapi_getpid ();
1062                 process_handle_data->mono_process = mono_process;
1063
1064                 mono_mutex_lock (&mono_processes_mutex);
1065                 mono_process->next = mono_processes;
1066                 mono_processes = mono_process;
1067                 mono_mutex_unlock (&mono_processes_mutex);
1068         }
1069         
1070         if (process_info != NULL) {
1071                 process_info->hProcess = handle;
1072                 process_info->dwProcessId = pid;
1073
1074                 /* FIXME: we might need to handle the thread info some
1075                  * day
1076                  */
1077                 process_info->hThread = INVALID_HANDLE_VALUE;
1078                 process_info->dwThreadId = 0;
1079         }
1080
1081 cleanup:
1082         _wapi_handle_unlock_shared_handles ();
1083
1084         if (startup_pipe [1] != -1) {
1085                 /* Write 1 byte, doesn't matter what */
1086                 write (startup_pipe [1], startup_pipe, 1);
1087                 close (startup_pipe [0]);
1088                 close (startup_pipe [1]);
1089         }
1090
1091 free_strings:
1092         if (cmd != NULL) {
1093                 g_free (cmd);
1094         }
1095         if (full_prog != NULL) {
1096                 g_free (full_prog);
1097         }
1098         if (prog != NULL) {
1099                 g_free (prog);
1100         }
1101         if (args != NULL) {
1102                 g_free (args);
1103         }
1104         if (dir != NULL) {
1105                 g_free (dir);
1106         }
1107         if(env_strings != NULL) {
1108                 g_strfreev (env_strings);
1109         }
1110         if (argv != NULL) {
1111                 g_strfreev (argv);
1112         }
1113         
1114 #ifdef DEBUG
1115         g_message ("%s: returning handle %p for pid %d", __func__, handle,
1116                    pid);
1117 #endif
1118
1119         /* Check if something needs to be cleaned up. */
1120         mono_processes_cleanup ();
1121         
1122         return(ret);
1123 }
1124                 
1125 static void process_set_name (struct _WapiHandle_process *process_handle)
1126 {
1127         gchar *progname, *utf8_progname, *slash;
1128         
1129         progname=g_get_prgname ();
1130         utf8_progname=mono_utf8_from_external (progname);
1131
1132 #ifdef DEBUG
1133         g_message ("%s: using [%s] as prog name", __func__, progname);
1134 #endif
1135
1136         if(utf8_progname!=NULL) {
1137                 slash=strrchr (utf8_progname, '/');
1138                 if(slash!=NULL) {
1139                         g_strlcpy (process_handle->proc_name, slash+1,
1140                                    _WAPI_PROC_NAME_MAX_LEN - 1);
1141                 } else {
1142                         g_strlcpy (process_handle->proc_name, utf8_progname,
1143                                    _WAPI_PROC_NAME_MAX_LEN - 1);
1144                 }
1145
1146                 g_free (utf8_progname);
1147         }
1148 }
1149
1150 extern void _wapi_time_t_to_filetime (time_t timeval, WapiFileTime *filetime);
1151
1152 #if !GLIB_CHECK_VERSION (2,4,0)
1153 #define g_setenv(a,b,c) setenv(a,b,c)
1154 #define g_unsetenv(a) unsetenv(a)
1155 #endif
1156
1157 static void process_set_current (void)
1158 {
1159         pid_t pid = _wapi_getpid ();
1160         const char *handle_env;
1161         struct _WapiHandle_process process_handle = {0};
1162         
1163         mono_once (&process_ops_once, process_ops_init);
1164         
1165         handle_env = g_getenv ("_WAPI_PROCESS_HANDLE_OFFSET");
1166         g_unsetenv ("_WAPI_PROCESS_HANDLE_OFFSET");
1167         
1168         if (handle_env != NULL) {
1169                 struct _WapiHandle_process *process_handlep;
1170                 gchar *procname = NULL;
1171                 gboolean ok;
1172                 
1173                 current_process = _wapi_handle_new_from_offset (WAPI_HANDLE_PROCESS, atoi (handle_env), TRUE);
1174                 
1175 #ifdef DEBUG
1176                 g_message ("%s: Found my process handle: %p (offset %d 0x%x)",
1177                            __func__, current_process, atoi (handle_env),
1178                            atoi (handle_env));
1179 #endif
1180
1181                 ok = _wapi_lookup_handle (current_process, WAPI_HANDLE_PROCESS,
1182                                           (gpointer *)&process_handlep);
1183                 if (ok) {
1184                         /* This test will probably break on linuxthreads, but
1185                          * that should be ancient history on all distros we
1186                          * care about by now
1187                          */
1188                         if (process_handlep->id == pid) {
1189                                 procname = process_handlep->proc_name;
1190                                 if (!strcmp (procname, "mono")) {
1191                                         /* Set a better process name */
1192 #ifdef DEBUG
1193                                         g_message ("%s: Setting better process name", __func__);
1194 #endif
1195                                         
1196                                         process_set_name (process_handlep);
1197                                 } else {
1198 #ifdef DEBUG
1199                                         g_message ("%s: Leaving process name: %s", __func__, procname);
1200 #endif
1201                                 }
1202
1203                                 return;
1204                         }
1205
1206                         /* Wrong pid, so drop this handle and fall through to
1207                          * create a new one
1208                          */
1209                         _wapi_handle_unref (current_process);
1210                 }
1211         }
1212
1213         /* We get here if the handle wasn't specified in the
1214          * environment, or if the process ID was wrong, or if the
1215          * handle lookup failed (eg if the parent process forked and
1216          * quit immediately, and deleted the shared data before the
1217          * child got a chance to attach it.)
1218          */
1219
1220 #ifdef DEBUG
1221         g_message ("%s: Need to create my own process handle", __func__);
1222 #endif
1223
1224         process_handle.id = pid;
1225
1226         process_set_defaults (&process_handle);
1227         process_set_name (&process_handle);
1228
1229         current_process = _wapi_handle_new (WAPI_HANDLE_PROCESS,
1230                                             &process_handle);
1231         if (current_process == _WAPI_HANDLE_INVALID) {
1232                 g_warning ("%s: error creating process handle", __func__);
1233                 return;
1234         }
1235 }
1236
1237 gpointer _wapi_process_duplicate ()
1238 {
1239         mono_once (&process_current_once, process_set_current);
1240         
1241         _wapi_handle_ref (current_process);
1242         
1243         return(current_process);
1244 }
1245
1246 /* Returns a pseudo handle that doesn't need to be closed afterwards */
1247 gpointer GetCurrentProcess (void)
1248 {
1249         mono_once (&process_current_once, process_set_current);
1250                 
1251         return(_WAPI_PROCESS_CURRENT);
1252 }
1253
1254 guint32 GetProcessId (gpointer handle)
1255 {
1256         struct _WapiHandle_process *process_handle;
1257         gboolean ok;
1258
1259         if ((GPOINTER_TO_UINT (handle) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
1260                 /* This is a pseudo handle */
1261                 return(GPOINTER_TO_UINT (handle) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
1262         }
1263         
1264         ok = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
1265                                   (gpointer *)&process_handle);
1266         if (ok == FALSE) {
1267                 SetLastError (ERROR_INVALID_HANDLE);
1268                 return (0);
1269         }
1270         
1271         return (process_handle->id);
1272 }
1273
1274 guint32 GetCurrentProcessId (void)
1275 {
1276         mono_once (&process_current_once, process_set_current);
1277                 
1278         return (GetProcessId (current_process));
1279 }
1280
1281 /* Returns the process id as a convenience to the functions that call this */
1282 static pid_t signal_process_if_gone (gpointer handle)
1283 {
1284         struct _WapiHandle_process *process_handle;
1285         gboolean ok;
1286         
1287         g_assert ((GPOINTER_TO_UINT (handle) & _WAPI_PROCESS_UNHANDLED) != _WAPI_PROCESS_UNHANDLED);
1288         
1289         /* Make sure the process is signalled if it has exited - if
1290          * the parent process didn't wait for it then it won't be
1291          */
1292         ok = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
1293                                   (gpointer *)&process_handle);
1294         if (ok == FALSE) {
1295                 /* It's possible that the handle has vanished during
1296                  * the _wapi_search_handle before it gets here, so
1297                  * don't spam the console with warnings.
1298                  */
1299 /*              g_warning ("%s: error looking up process handle %p",
1300   __func__, handle);*/
1301                 
1302                 return (0);
1303         }
1304         
1305 #ifdef DEBUG
1306         g_message ("%s: looking at process %d", __func__, process_handle->id);
1307 #endif
1308
1309         if (kill (process_handle->id, 0) == -1 &&
1310             (errno == ESRCH ||
1311              errno == EPERM)) {
1312                 /* The process is dead, (EPERM tells us a new process
1313                  * has that ID, but as it's owned by someone else it
1314                  * can't be the one listed in our shared memory file)
1315                  */
1316                 _wapi_shared_handle_set_signal_state (handle, TRUE);
1317         }
1318
1319         return (process_handle->id);
1320 }
1321
1322 #ifdef UNUSED_CODE
1323 static gboolean process_enum (gpointer handle, gpointer user_data)
1324 {
1325         GArray *processes=user_data;
1326         pid_t pid = signal_process_if_gone (handle);
1327         int i;
1328         
1329         if (pid == 0) {
1330                 return (FALSE);
1331         }
1332         
1333         /* Ignore processes that have already exited (ie they are signalled) */
1334         if (_wapi_handle_issignalled (handle) == FALSE) {
1335 #ifdef DEBUG
1336                 g_message ("%s: process %d added to array", __func__, pid);
1337 #endif
1338
1339                 /* This ensures that duplicates aren't returned (see
1340                  * the comment above _wapi_search_handle () for why
1341                  * it's needed
1342                  */
1343                 for (i = 0; i < processes->len; i++) {
1344                         if (g_array_index (processes, pid_t, i) == pid) {
1345                                 /* We've already got this one, return
1346                                  * FALSE to keep searching
1347                                  */
1348                                 return (FALSE);
1349                         }
1350                 }
1351                 
1352                 g_array_append_val (processes, pid);
1353         }
1354         
1355         /* Return false to keep searching */
1356         return(FALSE);
1357 }
1358 #endif /* UNUSED_CODE */
1359
1360 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__)
1361
1362 gboolean EnumProcesses (guint32 *pids, guint32 len, guint32 *needed)
1363 {
1364         guint32 count, fit, i, j;
1365         gint32 err;
1366         gboolean done;
1367         size_t proclength, size;
1368 #if defined(__OpenBSD__)
1369         struct kinfo_proc2 *result;
1370         int name[6];
1371         name[0] = CTL_KERN;
1372         name[1] = KERN_PROC2;
1373         name[2] = KERN_PROC_ALL;
1374         name[3] = 0;
1375         name[4] = sizeof(struct kinfo_proc2);
1376         name[5] = 0;
1377 #else
1378         struct kinfo_proc *result;
1379         static const int name[] = { CTL_KERN, KERN_PROC, KERN_PROC_ALL, 0 };
1380 #endif
1381
1382         mono_once (&process_current_once, process_set_current);
1383
1384         result = NULL;
1385         done = FALSE;
1386
1387         do {
1388                 proclength = 0;
1389 #if defined(__OpenBSD__)
1390                 size = (sizeof(name) / sizeof(*name));
1391 #else
1392                 size = (sizeof(name) / sizeof(*name)) - 1;
1393 #endif
1394                 err = sysctl ((int *)name, size, NULL, &proclength, NULL, 0);
1395
1396                 if (err == 0) {
1397                         result = malloc (proclength);
1398
1399                         if (result == NULL)
1400                                 return FALSE;
1401
1402 #if defined(__OpenBSD__)
1403                         name[5] = (int)(proclength / sizeof(struct kinfo_proc2));
1404 #endif
1405
1406                         err = sysctl ((int *) name, size, result, &proclength, NULL, 0);
1407
1408                         if (err == 0) 
1409                                 done = TRUE;
1410                         else
1411                                 free (result);
1412                 }
1413         } while (err == 0 && !done);
1414         
1415         if (err != 0) {
1416                 if (result != NULL) {
1417                         free (result);
1418                         result = NULL;
1419                 }
1420                 return(FALSE);
1421         }       
1422
1423 #if defined(__OpenBSD__)
1424         count = proclength / sizeof(struct kinfo_proc2);
1425 #else
1426         count = proclength / sizeof(struct kinfo_proc);
1427 #endif
1428         fit = len / sizeof(guint32);
1429         for (i = 0, j = 0; j< fit && i < count; i++) {
1430 #if defined(__OpenBSD__)
1431                 pids [j++] = result [i].p_pid;
1432 #else
1433                 if (result[i].kp_proc.p_pid > 0) /* Pid 0 not supported */
1434                         pids [j++] = result [i].kp_proc.p_pid;
1435 #endif
1436         }
1437         free (result);
1438         result = NULL;
1439         *needed = j * sizeof(guint32);
1440         
1441         return(TRUE);
1442 }
1443 #elif defined(__HAIKU__)
1444
1445 gboolean EnumProcesses (guint32 *pids, guint32 len, guint32 *needed)
1446 {
1447         guint32 fit, i = 0;
1448         int32 cookie = 0;
1449         team_info teamInfo;
1450
1451         mono_once (&process_current_once, process_set_current);
1452
1453         fit = len / sizeof (guint32);
1454         while (get_next_team_info (&cookie, &teamInfo) == B_OK && i < fit) {
1455                 pids [i++] = teamInfo.team;
1456         }
1457         *needed = i * sizeof (guint32);
1458
1459         return TRUE;
1460 }
1461 #else
1462 gboolean EnumProcesses (guint32 *pids, guint32 len, guint32 *needed)
1463 {
1464         guint32 fit, i;
1465         DIR *dir;
1466         struct dirent *entry;
1467         
1468         mono_once (&process_current_once, process_set_current);
1469
1470         dir = opendir ("/proc");
1471         if (dir == NULL) {
1472                 return(FALSE);
1473         }
1474
1475         i = 0;
1476         fit = len / sizeof (guint32);
1477         while(i < fit && (entry = readdir (dir)) != NULL) {
1478                 pid_t pid;
1479                 char *endptr;
1480
1481                 if (!isdigit (entry->d_name[0]))
1482                         continue;
1483
1484                 pid = (pid_t) strtol (entry->d_name, &endptr, 10);
1485                 if (*endptr == '\0')
1486                         pids [i++] = (guint32) pid;
1487         }
1488         closedir (dir);
1489         *needed = i * sizeof(guint32);
1490         
1491         return(TRUE);
1492 }
1493 #endif
1494
1495 static gboolean process_open_compare (gpointer handle, gpointer user_data)
1496 {
1497         pid_t wanted_pid;
1498         pid_t checking_pid = signal_process_if_gone (handle);
1499
1500         if (checking_pid == 0) {
1501                 return(FALSE);
1502         }
1503         
1504         wanted_pid = GPOINTER_TO_UINT (user_data);
1505
1506         /* It's possible to have more than one process handle with the
1507          * same pid, but only the one running process can be
1508          * unsignalled
1509          */
1510         if (checking_pid == wanted_pid &&
1511             _wapi_handle_issignalled (handle) == FALSE) {
1512                 /* If the handle is blown away in the window between
1513                  * returning TRUE here and _wapi_search_handle pinging
1514                  * the timestamp, the search will continue
1515                  */
1516                 return(TRUE);
1517         } else {
1518                 return(FALSE);
1519         }
1520 }
1521
1522 gboolean CloseProcess(gpointer handle)
1523 {
1524         if ((GPOINTER_TO_UINT (handle) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
1525                 /* This is a pseudo handle */
1526                 return(TRUE);
1527         }
1528
1529         return CloseHandle (handle);
1530 }
1531
1532 /*
1533  * The caller owns the returned handle and must call CloseProcess () on it to clean it up.
1534  */
1535 gpointer OpenProcess (guint32 req_access G_GNUC_UNUSED, gboolean inherit G_GNUC_UNUSED, guint32 pid)
1536 {
1537         /* Find the process handle that corresponds to pid */
1538         gpointer handle = NULL;
1539         
1540         mono_once (&process_current_once, process_set_current);
1541
1542 #ifdef DEBUG
1543         g_message ("%s: looking for process %d", __func__, pid);
1544 #endif
1545
1546         handle = _wapi_search_handle (WAPI_HANDLE_PROCESS,
1547                                       process_open_compare,
1548                                       GUINT_TO_POINTER (pid), NULL, TRUE);
1549         if (handle == 0) {
1550                 if (is_pid_valid (pid)) {
1551                         /* Return a pseudo handle for processes we
1552                          * don't have handles for
1553                          */
1554                         return GINT_TO_POINTER (_WAPI_PROCESS_UNHANDLED + pid);
1555                 } else {
1556 #ifdef DEBUG
1557                         g_message ("%s: Can't find pid %d", __func__, pid);
1558 #endif
1559
1560                         SetLastError (ERROR_PROC_NOT_FOUND);
1561         
1562                         return(NULL);
1563                 }
1564         }
1565
1566         /* _wapi_search_handle () already added a ref */
1567         return(handle);
1568 }
1569
1570 gboolean GetExitCodeProcess (gpointer process, guint32 *code)
1571 {
1572         struct _WapiHandle_process *process_handle;
1573         gboolean ok;
1574         guint32 pid = -1;
1575         
1576         mono_once (&process_current_once, process_set_current);
1577
1578         if(code==NULL) {
1579                 return(FALSE);
1580         }
1581         
1582         pid = GPOINTER_TO_UINT (process) - _WAPI_PROCESS_UNHANDLED;
1583         if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
1584                 /* This is a pseudo handle, so we don't know what the
1585                  * exit code was, but we can check whether it's alive or not
1586                  */
1587                 if (is_pid_valid (pid)) {
1588                         *code = STILL_ACTIVE;
1589                         return TRUE;
1590                 } else {
1591                         return FALSE;
1592                 }
1593         }
1594
1595         ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
1596                                 (gpointer *)&process_handle);
1597         if(ok==FALSE) {
1598 #ifdef DEBUG
1599                 g_message ("%s: Can't find process %p", __func__, process);
1600 #endif
1601                 
1602                 return(FALSE);
1603         }
1604         
1605         /* A process handle is only signalled if the process has exited
1606          * and has been waited for */
1607
1608         /* Make sure any process exit has been noticed, before
1609          * checking if the process is signalled.  Fixes bug 325463.
1610          */
1611         process_wait (process, 0, TRUE);
1612         
1613         if (_wapi_handle_issignalled (process) == TRUE) {
1614                 *code = process_handle->exitstatus;
1615         } else {
1616                 *code = STILL_ACTIVE;
1617         }
1618         
1619         return(TRUE);
1620 }
1621
1622 gboolean GetProcessTimes (gpointer process, WapiFileTime *create_time,
1623                           WapiFileTime *exit_time, WapiFileTime *kernel_time,
1624                           WapiFileTime *user_time)
1625 {
1626         struct _WapiHandle_process *process_handle;
1627         gboolean ok;
1628         gboolean ku_times_set = FALSE;
1629         
1630         mono_once (&process_current_once, process_set_current);
1631
1632         if(create_time==NULL || exit_time==NULL || kernel_time==NULL ||
1633            user_time==NULL) {
1634                 /* Not sure if w32 allows NULLs here or not */
1635                 return(FALSE);
1636         }
1637         
1638         if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
1639                 /* This is a pseudo handle, so just fail for now
1640                  */
1641                 return(FALSE);
1642         }
1643         
1644         ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
1645                                 (gpointer *)&process_handle);
1646         if(ok==FALSE) {
1647 #ifdef DEBUG
1648                 g_message ("%s: Can't find process %p", __func__, process);
1649 #endif
1650                 
1651                 return(FALSE);
1652         }
1653         
1654         *create_time=process_handle->create_time;
1655
1656         /* A process handle is only signalled if the process has
1657          * exited.  Otherwise exit_time isn't set
1658          */
1659         if(_wapi_handle_issignalled (process)==TRUE) {
1660                 *exit_time=process_handle->exit_time;
1661         }
1662
1663 #ifdef HAVE_GETRUSAGE
1664         if (process_handle->id == getpid ()) {
1665                 struct rusage time_data;
1666                 if (getrusage (RUSAGE_SELF, &time_data) == 0) {
1667                         gint64 tick_val;
1668                         gint64 *tick_val_ptr;
1669                         ku_times_set = TRUE;
1670                         tick_val = time_data.ru_utime.tv_sec * 10000000 + time_data.ru_utime.tv_usec * 10;
1671                         tick_val_ptr = (gint64*)user_time;
1672                         *tick_val_ptr = tick_val;
1673                         tick_val = time_data.ru_stime.tv_sec * 10000000 + time_data.ru_stime.tv_usec * 10;
1674                         tick_val_ptr = (gint64*)kernel_time;
1675                         *tick_val_ptr = tick_val;
1676                 }
1677         }
1678 #endif
1679         if (!ku_times_set) {
1680                 memset (kernel_time, 0, sizeof (WapiFileTime));
1681                 memset (user_time, 0, sizeof (WapiFileTime));
1682         }
1683
1684         return(TRUE);
1685 }
1686
1687 typedef struct
1688 {
1689         gpointer address_start;
1690         gpointer address_end;
1691         gchar *perms;
1692         gpointer address_offset;
1693         dev_t device;
1694         ino_t inode;
1695         gchar *filename;
1696 } WapiProcModule;
1697
1698 static void free_procmodule (WapiProcModule *mod)
1699 {
1700         if (mod->perms != NULL) {
1701                 g_free (mod->perms);
1702         }
1703         if (mod->filename != NULL) {
1704                 g_free (mod->filename);
1705         }
1706         g_free (mod);
1707 }
1708
1709 static gint find_procmodule (gconstpointer a, gconstpointer b)
1710 {
1711         WapiProcModule *want = (WapiProcModule *)a;
1712         WapiProcModule *compare = (WapiProcModule *)b;
1713         
1714         if ((want->device == compare->device) &&
1715             (want->inode == compare->inode)) {
1716                 return(0);
1717         } else {
1718                 return(1);
1719         }
1720 }
1721
1722 #ifdef PLATFORM_MACOSX
1723 #include <mach-o/dyld.h>
1724 #include <mach-o/getsect.h>
1725
1726 static GSList *load_modules (void)
1727 {
1728         GSList *ret = NULL;
1729         WapiProcModule *mod;
1730         uint32_t count = _dyld_image_count ();
1731         int i = 0;
1732
1733         for (i = 0; i < count; i++) {
1734 #if SIZEOF_VOID_P == 8
1735                 const struct mach_header_64 *hdr;
1736                 const struct section_64 *sec;
1737 #else
1738                 const struct mach_header *hdr;
1739                 const struct section *sec;
1740 #endif
1741                 const char *name;
1742                 intptr_t slide;
1743
1744                 slide = _dyld_get_image_vmaddr_slide (i);
1745                 name = _dyld_get_image_name (i);
1746                 hdr = _dyld_get_image_header (i);
1747 #if SIZEOF_VOID_P == 8
1748                 sec = getsectbynamefromheader_64 (hdr, SEG_DATA, SECT_DATA);
1749 #else
1750                 sec = getsectbynamefromheader (hdr, SEG_DATA, SECT_DATA);
1751 #endif
1752
1753                 /* Some dynlibs do not have data sections on osx (#533893) */
1754                 if (sec == 0) {
1755                         continue;
1756                 }
1757                         
1758                 mod = g_new0 (WapiProcModule, 1);
1759                 mod->address_start = GINT_TO_POINTER (sec->addr);
1760                 mod->address_end = GINT_TO_POINTER (sec->addr+sec->size);
1761                 mod->perms = g_strdup ("r--p");
1762                 mod->address_offset = 0;
1763                 mod->device = makedev (0, 0);
1764                 mod->inode = (ino_t) i;
1765                 mod->filename = g_strdup (name); 
1766                 
1767                 if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
1768                         ret = g_slist_prepend (ret, mod);
1769                 } else {
1770                         free_procmodule (mod);
1771                 }
1772         }
1773
1774         ret = g_slist_reverse (ret);
1775         
1776         return(ret);
1777 }
1778 #elif defined(__OpenBSD__)
1779 #include <link.h>
1780 static int load_modules_callback (struct dl_phdr_info *info, size_t size, void *ptr)
1781 {
1782         if (size < offsetof (struct dl_phdr_info, dlpi_phnum)
1783             + sizeof (info->dlpi_phnum))
1784                 return (-1);
1785
1786         struct dl_phdr_info *cpy = calloc(1, sizeof(struct dl_phdr_info));
1787         if (!cpy)
1788                 return (-1);
1789
1790         memcpy(cpy, info, sizeof(*info));
1791
1792         g_ptr_array_add ((GPtrArray *)ptr, cpy);
1793
1794         return (0);
1795 }
1796
1797 static GSList *load_modules (void)
1798 {
1799         GSList *ret = NULL;
1800         WapiProcModule *mod;
1801         GPtrArray *dlarray = g_ptr_array_new();
1802         int i;
1803
1804         if (dl_iterate_phdr(load_modules_callback, dlarray) < 0)
1805                 return (ret);
1806
1807         for (i = 0; i < dlarray->len; i++) {
1808                 struct dl_phdr_info *info = g_ptr_array_index (dlarray, i);
1809
1810                 mod = g_new0 (WapiProcModule, 1);
1811                 mod->address_start = (gpointer)(info->dlpi_addr + info->dlpi_phdr[0].p_vaddr);
1812                 mod->address_end = (gpointer)(info->dlpi_addr +
1813                                        info->dlpi_phdr[info->dlpi_phnum - 1].p_vaddr);
1814                 mod->perms = g_strdup ("r--p");
1815                 mod->address_offset = 0;
1816                 mod->inode = (ino_t) i;
1817                 mod->filename = g_strdup (info->dlpi_name); 
1818
1819 #ifdef DEBUG
1820                 g_message ("%s: inode=%d, filename=%s, address_start=%p, address_end=%p", __func__,
1821                                    mod->inode, mod->filename, mod->address_start, mod->address_end);
1822 #endif
1823
1824                 free(info);
1825
1826                 if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
1827                         ret = g_slist_prepend (ret, mod);
1828                 } else {
1829                         free_procmodule (mod);
1830                 }
1831         }
1832
1833         g_ptr_array_free (dlarray, TRUE);
1834
1835         ret = g_slist_reverse (ret);
1836
1837         return(ret);
1838 }
1839 #elif defined(__HAIKU__)
1840
1841 static GSList *load_modules (void)
1842 {
1843         GSList *ret = NULL;
1844         WapiProcModule *mod;
1845         int32 cookie = 0;
1846         image_info imageInfo;
1847
1848         while (get_next_image_info (B_CURRENT_TEAM, &cookie, &imageInfo) == B_OK) {
1849                 mod = g_new0 (WapiProcModule, 1);
1850                 mod->device = imageInfo.device;
1851                 mod->inode = imageInfo.node;
1852                 mod->filename = g_strdup (imageInfo.name);
1853                 mod->address_start = MIN (imageInfo.text, imageInfo.data);
1854                 mod->address_end = MAX ((uint8_t*)imageInfo.text + imageInfo.text_size,
1855                         (uint8_t*)imageInfo.data + imageInfo.data_size);
1856                 mod->perms = g_strdup ("r--p");
1857                 mod->address_offset = 0;
1858
1859                 if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
1860                         ret = g_slist_prepend (ret, mod);
1861                 } else {
1862                         free_procmodule (mod);
1863                 }
1864         }
1865
1866         ret = g_slist_reverse (ret);
1867
1868         return ret;
1869 }
1870 #else
1871 static GSList *load_modules (FILE *fp)
1872 {
1873         GSList *ret = NULL;
1874         WapiProcModule *mod;
1875         gchar buf[MAXPATHLEN + 1], *p, *endp;
1876         gchar *start_start, *end_start, *prot_start, *offset_start;
1877         gchar *maj_dev_start, *min_dev_start, *inode_start, prot_buf[5];
1878         gpointer address_start, address_end, address_offset;
1879         guint32 maj_dev, min_dev;
1880         ino_t inode;
1881         dev_t device;
1882         
1883         while (fgets (buf, sizeof(buf), fp)) {
1884                 p = buf;
1885                 while (g_ascii_isspace (*p)) ++p;
1886                 start_start = p;
1887                 if (!g_ascii_isxdigit (*start_start)) {
1888                         continue;
1889                 }
1890                 address_start = (gpointer)strtoul (start_start, &endp, 16);
1891                 p = endp;
1892                 if (*p != '-') {
1893                         continue;
1894                 }
1895                 
1896                 ++p;
1897                 end_start = p;
1898                 if (!g_ascii_isxdigit (*end_start)) {
1899                         continue;
1900                 }
1901                 address_end = (gpointer)strtoul (end_start, &endp, 16);
1902                 p = endp;
1903                 if (!g_ascii_isspace (*p)) {
1904                         continue;
1905                 }
1906                 
1907                 while (g_ascii_isspace (*p)) ++p;
1908                 prot_start = p;
1909                 if (*prot_start != 'r' && *prot_start != '-') {
1910                         continue;
1911                 }
1912                 memcpy (prot_buf, prot_start, 4);
1913                 prot_buf[4] = '\0';
1914                 while (!g_ascii_isspace (*p)) ++p;
1915                 
1916                 while (g_ascii_isspace (*p)) ++p;
1917                 offset_start = p;
1918                 if (!g_ascii_isxdigit (*offset_start)) {
1919                         continue;
1920                 }
1921                 address_offset = (gpointer)strtoul (offset_start, &endp, 16);
1922                 p = endp;
1923                 if (!g_ascii_isspace (*p)) {
1924                         continue;
1925                 }
1926                 
1927                 while(g_ascii_isspace (*p)) ++p;
1928                 maj_dev_start = p;
1929                 if (!g_ascii_isxdigit (*maj_dev_start)) {
1930                         continue;
1931                 }
1932                 maj_dev = strtoul (maj_dev_start, &endp, 16);
1933                 p = endp;
1934                 if (*p != ':') {
1935                         continue;
1936                 }
1937                 
1938                 ++p;
1939                 min_dev_start = p;
1940                 if (!g_ascii_isxdigit (*min_dev_start)) {
1941                         continue;
1942                 }
1943                 min_dev = strtoul (min_dev_start, &endp, 16);
1944                 p = endp;
1945                 if (!g_ascii_isspace (*p)) {
1946                         continue;
1947                 }
1948                 
1949                 while (g_ascii_isspace (*p)) ++p;
1950                 inode_start = p;
1951                 if (!g_ascii_isxdigit (*inode_start)) {
1952                         continue;
1953                 }
1954                 inode = (ino_t)strtol (inode_start, &endp, 10);
1955                 p = endp;
1956                 if (!g_ascii_isspace (*p)) {
1957                         continue;
1958                 }
1959
1960                 device = makedev ((int)maj_dev, (int)min_dev);
1961                 if ((device == 0) &&
1962                     (inode == 0)) {
1963                         continue;
1964                 }
1965                 
1966                 while(g_ascii_isspace (*p)) ++p;
1967                 /* p now points to the filename */
1968
1969                 mod = g_new0 (WapiProcModule, 1);
1970                 mod->address_start = address_start;
1971                 mod->address_end = address_end;
1972                 mod->perms = g_strdup (prot_buf);
1973                 mod->address_offset = address_offset;
1974                 mod->device = device;
1975                 mod->inode = inode;
1976                 mod->filename = g_strdup (g_strstrip (p));
1977                 
1978                 if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
1979                         ret = g_slist_prepend (ret, mod);
1980                 } else {
1981                         free_procmodule (mod);
1982                 }
1983         }
1984
1985         ret = g_slist_reverse (ret);
1986         
1987         return(ret);
1988 }
1989 #endif
1990
1991 static gboolean match_procname_to_modulename (gchar *procname, gchar *modulename)
1992 {
1993         char* lastsep = NULL;
1994         char* pname = NULL;
1995         char* mname = NULL;
1996         gboolean result = FALSE;
1997
1998         if (procname == NULL || modulename == NULL)
1999                 return (FALSE);
2000
2001         pname = mono_path_resolve_symlinks (procname);
2002         mname = mono_path_resolve_symlinks (modulename);
2003
2004         if (!strcmp (pname, mname))
2005                 result = TRUE;
2006
2007         if (!result) {
2008                 lastsep = strrchr (mname, '/');
2009                 if (lastsep)
2010                         if (!strcmp (lastsep+1, pname))
2011                                 result = TRUE;
2012         }
2013
2014         g_free (pname);
2015         g_free (mname);
2016
2017         return result;
2018 }
2019
2020 #if !defined(__OpenBSD__)
2021 static FILE *
2022 open_process_map (int pid, const char *mode)
2023 {
2024         FILE *fp = NULL;
2025         const gchar *proc_path[] = {
2026                 "/proc/%d/maps",        /* GNU/Linux */
2027                 "/proc/%d/map",         /* FreeBSD */
2028                 NULL
2029         };
2030         int i;
2031         gchar *filename;
2032
2033         for (i = 0; fp == NULL && proc_path [i]; i++) {
2034                 filename = g_strdup_printf (proc_path[i], pid);
2035                 fp = fopen (filename, mode);
2036                 g_free (filename);
2037         }
2038
2039         return fp;
2040 }
2041 #endif
2042
2043 gboolean EnumProcessModules (gpointer process, gpointer *modules,
2044                              guint32 size, guint32 *needed)
2045 {
2046         struct _WapiHandle_process *process_handle;
2047         gboolean ok;
2048 #if !defined(__OpenBSD__) && !defined(PLATFORM_MACOSX)
2049         FILE *fp;
2050 #endif
2051         GSList *mods = NULL;
2052         WapiProcModule *module;
2053         guint32 count, avail = size / sizeof(gpointer);
2054         int i;
2055         pid_t pid;
2056         gchar *proc_name = NULL;
2057         
2058         /* Store modules in an array of pointers (main module as
2059          * modules[0]), using the load address for each module as a
2060          * token.  (Use 'NULL' as an alternative for the main module
2061          * so that the simple implementation can just return one item
2062          * for now.)  Get the info from /proc/<pid>/maps on linux,
2063          * /proc/<pid>/map on FreeBSD, other systems will have to
2064          * implement /dev/kmem reading or whatever other horrid
2065          * technique is needed.
2066          */
2067         if (size < sizeof(gpointer)) {
2068                 return(FALSE);
2069         }
2070
2071         if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2072                 /* This is a pseudo handle */
2073                 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2074         } else {
2075                 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2076                                           (gpointer *)&process_handle);
2077                 if (ok == FALSE) {
2078 #ifdef DEBUG
2079                         g_message ("%s: Can't find process %p", __func__, process);
2080 #endif
2081                 
2082                         return(FALSE);
2083                 }
2084                 pid = process_handle->id;
2085                 proc_name = process_handle->proc_name;
2086         }
2087         
2088 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__) || defined(__HAIKU__)
2089         {
2090                 mods = load_modules ();
2091 #else
2092         if ((fp = open_process_map (pid, "r")) == NULL) {
2093                 /* No /proc/<pid>/maps so just return the main module
2094                  * shortcut for now
2095                  */
2096                 modules[0] = NULL;
2097                 *needed = sizeof(gpointer);
2098         } else {
2099                 mods = load_modules (fp);
2100                 fclose (fp);
2101 #endif
2102                 count = g_slist_length (mods);
2103                 
2104                 /* count + 1 to leave slot 0 for the main module */
2105                 *needed = sizeof(gpointer) * (count + 1);
2106
2107                 /* Use the NULL shortcut, as the first line in
2108                  * /proc/<pid>/maps isn't the executable, and we need
2109                  * that first in the returned list. Check the module name 
2110                  * to see if it ends with the proc name and substitute 
2111                  * the first entry with it.  FIXME if this turns out to 
2112                  * be a problem.
2113                  */
2114                 modules[0] = NULL;
2115                 for (i = 0; i < (avail - 1) && i < count; i++) {
2116                         module = (WapiProcModule *)g_slist_nth_data (mods, i);
2117                         if (modules[0] != NULL)
2118                                 modules[i] = module->address_start;
2119                         else if (match_procname_to_modulename (proc_name, module->filename))
2120                                 modules[0] = module->address_start;
2121                         else
2122                                 modules[i + 1] = module->address_start;
2123                 }
2124                 
2125                 for (i = 0; i < count; i++) {
2126                         free_procmodule (g_slist_nth_data (mods, i));
2127                 }
2128                 g_slist_free (mods);
2129         }
2130
2131         return(TRUE);
2132 }
2133
2134 static gchar *get_process_name_from_proc (pid_t pid)
2135 {
2136 #if defined(__OpenBSD__)
2137         int mib [6];
2138         size_t size;
2139         struct kinfo_proc2 *pi;
2140 #elif defined(PLATFORM_MACOSX)
2141         size_t size;
2142         struct kinfo_proc *pi;
2143         int mib[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, pid };
2144 #else
2145         FILE *fp;
2146         gchar *filename = NULL;
2147 #endif
2148         gchar buf[256];
2149         gchar *ret = NULL;
2150
2151 #if defined(PLATFORM_SOLARIS)
2152         filename = g_strdup_printf ("/proc/%d/psinfo", pid);
2153         if ((fp = fopen (filename, "r")) != NULL) {
2154                 struct psinfo info;
2155                 int nread;
2156
2157                 nread = fread (&info, sizeof (info), 1, fp);
2158                 if (nread == 1) {
2159                         ret = g_strdup (info.pr_fname);
2160                 }
2161
2162                 fclose (fp);
2163         }
2164         g_free (filename);
2165 #elif defined(PLATFORM_MACOSX)
2166 #if (MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5) && !defined (__mono_ppc__) && !defined(__arm__)
2167         /* No proc name on OSX < 10.5 nor ppc nor iOS */
2168         memset (buf, '\0', sizeof(buf));
2169         proc_name (pid, buf, sizeof(buf));
2170         if (strlen (buf) > 0)
2171                 ret = g_strdup (buf);
2172 #else
2173         if (sysctl(mib, 4, NULL, &size, NULL, 0) < 0)
2174                 return(ret);
2175
2176         if ((pi = malloc(size)) == NULL)
2177                 return(ret);
2178
2179         if (sysctl (mib, 4, pi, &size, NULL, 0) < 0) {
2180                 if (errno == ENOMEM) {
2181                         free(pi);
2182 #ifdef DEBUG
2183                         g_message ("%s: Didn't allocate enough memory for kproc info", __func__);
2184 #endif
2185                 }
2186                 return(ret);
2187         }
2188
2189         if (strlen (pi->kp_proc.p_comm) > 0)
2190                 ret = g_strdup (pi->kp_proc.p_comm);
2191
2192         free(pi);
2193 #endif
2194 #elif defined(__OpenBSD__)
2195         mib [0] = CTL_KERN;
2196         mib [1] = KERN_PROC2;
2197         mib [2] = KERN_PROC_PID;
2198         mib [3] = pid;
2199         mib [4] = sizeof(struct kinfo_proc2);
2200         mib [5] = 0;
2201
2202 retry:
2203         if (sysctl(mib, 6, NULL, &size, NULL, 0) < 0)
2204                 return(ret);
2205
2206         if ((pi = malloc(size)) == NULL)
2207                 return(ret);
2208
2209         mib[5] = (int)(size / sizeof(struct kinfo_proc2));
2210
2211         if ((sysctl (mib, 6, pi, &size, NULL, 0) < 0) ||
2212                 (size != sizeof (struct kinfo_proc2))) {
2213                 if (errno == ENOMEM) {
2214                         free(pi);
2215                         goto retry;
2216                 }
2217                 return(ret);
2218         }
2219
2220         if (strlen (pi->p_comm) > 0)
2221                 ret = g_strdup (pi->p_comm);
2222
2223         free(pi);
2224 #elif defined(__HAIKU__)
2225         image_info imageInfo;
2226         int32 cookie = 0;
2227
2228         if (get_next_image_info ((team_id)pid, &cookie, &imageInfo) == B_OK) {
2229                 ret = g_strdup (imageInfo.name);
2230         }
2231 #else
2232         memset (buf, '\0', sizeof(buf));
2233         filename = g_strdup_printf ("/proc/%d/exe", pid);
2234         if (readlink (filename, buf, 255) > 0) {
2235                 ret = g_strdup (buf);
2236         }
2237         g_free (filename);
2238
2239         if (ret != NULL) {
2240                 return(ret);
2241         }
2242
2243         filename = g_strdup_printf ("/proc/%d/cmdline", pid);
2244         if ((fp = fopen (filename, "r")) != NULL) {
2245                 if (fgets (buf, 256, fp) != NULL) {
2246                         ret = g_strdup (buf);
2247                 }
2248                 
2249                 fclose (fp);
2250         }
2251         g_free (filename);
2252
2253         if (ret != NULL) {
2254                 return(ret);
2255         }
2256         
2257         filename = g_strdup_printf ("/proc/%d/stat", pid);
2258         if ((fp = fopen (filename, "r")) != NULL) {
2259                 if (fgets (buf, 256, fp) != NULL) {
2260                         gchar *start, *end;
2261                         
2262                         start = strchr (buf, '(');
2263                         if (start != NULL) {
2264                                 end = strchr (start + 1, ')');
2265                                 
2266                                 if (end != NULL) {
2267                                         ret = g_strndup (start + 1,
2268                                                          end - start - 1);
2269                                 }
2270                         }
2271                 }
2272                 
2273                 fclose (fp);
2274         }
2275         g_free (filename);
2276 #endif
2277
2278         return ret;
2279 }
2280
2281 static guint32 get_module_name (gpointer process, gpointer module,
2282                                 gunichar2 *basename, guint32 size,
2283                                 gboolean base)
2284 {
2285         struct _WapiHandle_process *process_handle;
2286         gboolean ok;
2287         pid_t pid;
2288         gunichar2 *procname;
2289         gchar *procname_ext = NULL;
2290         glong len;
2291         gsize bytes;
2292 #if !defined(__OpenBSD__) && !defined(PLATFORM_MACOSX)
2293         FILE *fp;
2294 #endif
2295         GSList *mods = NULL;
2296         WapiProcModule *found_module;
2297         guint32 count;
2298         int i;
2299         gchar *proc_name = NULL;
2300         
2301         mono_once (&process_current_once, process_set_current);
2302
2303 #ifdef DEBUG
2304         g_message ("%s: Getting module base name, process handle %p module %p",
2305                    __func__, process, module);
2306 #endif
2307
2308         size = size*sizeof(gunichar2); /* adjust for unicode characters */
2309
2310         if (basename == NULL || size == 0) {
2311                 return(0);
2312         }
2313         
2314         if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2315                 /* This is a pseudo handle */
2316                 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2317                 proc_name = get_process_name_from_proc (pid);
2318         } else {
2319                 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2320                                           (gpointer *)&process_handle);
2321                 if (ok == FALSE) {
2322 #ifdef DEBUG
2323                         g_message ("%s: Can't find process %p", __func__,
2324                                    process);
2325 #endif
2326                         
2327                         return(0);
2328                 }
2329                 pid = process_handle->id;
2330                 proc_name = g_strdup (process_handle->proc_name);
2331         }
2332
2333         /* Look up the address in /proc/<pid>/maps */
2334 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__) || defined(__HAIKU__)
2335         {
2336                 mods = load_modules ();
2337 #else
2338         if ((fp = open_process_map (pid, "r")) == NULL) {
2339                 if (errno == EACCES && module == NULL && base == TRUE) {
2340                         procname_ext = get_process_name_from_proc (pid);
2341                 } else {
2342                         /* No /proc/<pid>/maps, so just return failure
2343                          * for now
2344                          */
2345                         g_free (proc_name);
2346                         return(0);
2347                 }
2348         } else {
2349                 mods = load_modules (fp);
2350                 fclose (fp);
2351 #endif
2352                 count = g_slist_length (mods);
2353
2354                 /* If module != NULL compare the address.
2355                  * If module == NULL we are looking for the main module.
2356                  * The best we can do for now check it the module name end with the process name.
2357                  */
2358                 for (i = 0; i < count; i++) {
2359                         found_module = (WapiProcModule *)g_slist_nth_data (mods, i);
2360                         if (procname_ext == NULL &&
2361                             ((module == NULL && match_procname_to_modulename (proc_name, found_module->filename)) ||    
2362                              (module != NULL && found_module->address_start == module))) {
2363                                 if (base) {
2364                                         procname_ext = g_path_get_basename (found_module->filename);
2365                                 } else {
2366                                         procname_ext = g_strdup (found_module->filename);
2367                                 }
2368                         }
2369
2370                         free_procmodule (found_module);
2371                 }
2372
2373                 if (procname_ext == NULL)
2374                 {
2375                         /* If it's *still* null, we might have hit the
2376                          * case where reading /proc/$pid/maps gives an
2377                          * empty file for this user.
2378                          */
2379                         procname_ext = get_process_name_from_proc (pid);
2380                 }
2381
2382                 g_slist_free (mods);
2383                 g_free (proc_name);
2384         }
2385
2386         if (procname_ext != NULL) {
2387 #ifdef DEBUG
2388                 g_message ("%s: Process name is [%s]", __func__,
2389                            procname_ext);
2390 #endif
2391
2392                 procname = mono_unicode_from_external (procname_ext, &bytes);
2393                 if (procname == NULL) {
2394                         /* bugger */
2395                         g_free (procname_ext);
2396                         return(0);
2397                 }
2398                 
2399                 len = (bytes / 2);
2400                 
2401                 /* Add the terminator */
2402                 bytes += 2;
2403                 
2404                 if (size < bytes) {
2405 #ifdef DEBUG
2406                         g_message ("%s: Size %d smaller than needed (%ld); truncating", __func__, size, bytes);
2407 #endif
2408
2409                         memcpy (basename, procname, size);
2410                 } else {
2411 #ifdef DEBUG
2412                         g_message ("%s: Size %d larger than needed (%ld)",
2413                                    __func__, size, bytes);
2414 #endif
2415
2416                         memcpy (basename, procname, bytes);
2417                 }
2418                 
2419                 g_free (procname);
2420                 g_free (procname_ext);
2421                 
2422                 return(len);
2423         }
2424         
2425         return(0);
2426 }
2427
2428 guint32 GetModuleBaseName (gpointer process, gpointer module,
2429                            gunichar2 *basename, guint32 size)
2430 {
2431         return(get_module_name (process, module, basename, size, TRUE));
2432 }
2433
2434 guint32 GetModuleFileNameEx (gpointer process, gpointer module,
2435                              gunichar2 *filename, guint32 size)
2436 {
2437         return(get_module_name (process, module, filename, size, FALSE));
2438 }
2439
2440 gboolean GetModuleInformation (gpointer process, gpointer module,
2441                                WapiModuleInfo *modinfo, guint32 size)
2442 {
2443         struct _WapiHandle_process *process_handle;
2444         gboolean ok;
2445         pid_t pid;
2446 #if !defined(__OpenBSD__) && !defined(PLATFORM_MACOSX)
2447         FILE *fp;
2448 #endif
2449         GSList *mods = NULL;
2450         WapiProcModule *found_module;
2451         guint32 count;
2452         int i;
2453         gboolean ret = FALSE;
2454         gchar *proc_name = NULL;
2455         
2456         mono_once (&process_current_once, process_set_current);
2457         
2458 #ifdef DEBUG
2459         g_message ("%s: Getting module info, process handle %p module %p",
2460                    __func__, process, module);
2461 #endif
2462
2463         if (modinfo == NULL || size < sizeof(WapiModuleInfo)) {
2464                 return(FALSE);
2465         }
2466         
2467         if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2468                 /* This is a pseudo handle */
2469                 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2470                 proc_name = get_process_name_from_proc (pid);
2471         } else {
2472                 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2473                                           (gpointer *)&process_handle);
2474                 if (ok == FALSE) {
2475 #ifdef DEBUG
2476                         g_message ("%s: Can't find process %p", __func__,
2477                                    process);
2478 #endif
2479                         
2480                         return(FALSE);
2481                 }
2482                 pid = process_handle->id;
2483                 proc_name = g_strdup (process_handle->proc_name);
2484         }
2485
2486 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__) || defined(__HAIKU__)
2487         {
2488                 mods = load_modules ();
2489 #else
2490         /* Look up the address in /proc/<pid>/maps */
2491         if ((fp = open_process_map (pid, "r")) == NULL) {
2492                 /* No /proc/<pid>/maps, so just return failure
2493                  * for now
2494                  */
2495                 g_free (proc_name);
2496                 return(FALSE);
2497         } else {
2498                 mods = load_modules (fp);
2499                 fclose (fp);
2500 #endif
2501                 count = g_slist_length (mods);
2502
2503                 /* If module != NULL compare the address.
2504                  * If module == NULL we are looking for the main module.
2505                  * The best we can do for now check it the module name end with the process name.
2506                  */
2507                 for (i = 0; i < count; i++) {
2508                         found_module = (WapiProcModule *)g_slist_nth_data (mods, i);
2509                         if ( ret == FALSE &&
2510                              ((module == NULL && match_procname_to_modulename (proc_name, found_module->filename)) ||
2511                               (module != NULL && found_module->address_start == module))) {
2512                                 modinfo->lpBaseOfDll = found_module->address_start;
2513                                 modinfo->SizeOfImage = (gsize)(found_module->address_end) - (gsize)(found_module->address_start);
2514                                 modinfo->EntryPoint = found_module->address_offset;
2515                                 ret = TRUE;
2516                         }
2517
2518                         free_procmodule (found_module);
2519                 }
2520
2521                 g_slist_free (mods);
2522                 g_free (proc_name);
2523         }
2524
2525         return(ret);
2526 }
2527
2528 gboolean GetProcessWorkingSetSize (gpointer process, size_t *min, size_t *max)
2529 {
2530         struct _WapiHandle_process *process_handle;
2531         gboolean ok;
2532         
2533         mono_once (&process_current_once, process_set_current);
2534
2535         if(min==NULL || max==NULL) {
2536                 /* Not sure if w32 allows NULLs here or not */
2537                 return(FALSE);
2538         }
2539         
2540         if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2541                 /* This is a pseudo handle, so just fail for now
2542                  */
2543                 return(FALSE);
2544         }
2545         
2546         ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2547                                 (gpointer *)&process_handle);
2548         if(ok==FALSE) {
2549 #ifdef DEBUG
2550                 g_message ("%s: Can't find process %p", __func__, process);
2551 #endif
2552                 
2553                 return(FALSE);
2554         }
2555
2556         *min=process_handle->min_working_set;
2557         *max=process_handle->max_working_set;
2558         
2559         return(TRUE);
2560 }
2561
2562 gboolean SetProcessWorkingSetSize (gpointer process, size_t min, size_t max)
2563 {
2564         struct _WapiHandle_process *process_handle;
2565         gboolean ok;
2566
2567         mono_once (&process_current_once, process_set_current);
2568         
2569         if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2570                 /* This is a pseudo handle, so just fail for now
2571                  */
2572                 return(FALSE);
2573         }
2574
2575         ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2576                                 (gpointer *)&process_handle);
2577         if(ok==FALSE) {
2578 #ifdef DEBUG
2579                 g_message ("%s: Can't find process %p", __func__, process);
2580 #endif
2581                 
2582                 return(FALSE);
2583         }
2584
2585         process_handle->min_working_set=min;
2586         process_handle->max_working_set=max;
2587         
2588         return(TRUE);
2589 }
2590
2591
2592 gboolean
2593 TerminateProcess (gpointer process, gint32 exitCode)
2594 {
2595         struct _WapiHandle_process *process_handle;
2596         gboolean ok;
2597         int signo;
2598         int ret;
2599         pid_t pid;
2600         
2601         if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2602                 /* This is a pseudo handle */
2603                 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2604         } else {
2605                 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2606                                           (gpointer *) &process_handle);
2607
2608                 if (ok == FALSE) {
2609 #ifdef DEBUG
2610                         g_message ("%s: Can't find process %p", __func__,
2611                                    process);
2612 #endif
2613                         SetLastError (ERROR_INVALID_HANDLE);
2614                         return FALSE;
2615                 }
2616                 pid = process_handle->id;
2617         }
2618
2619         signo = (exitCode == -1) ? SIGKILL : SIGTERM;
2620         ret = kill (pid, signo);
2621         if (ret == -1) {
2622                 switch (errno) {
2623                 case EINVAL:
2624                         SetLastError (ERROR_INVALID_PARAMETER);
2625                         break;
2626                 case EPERM:
2627                         SetLastError (ERROR_ACCESS_DENIED);
2628                         break;
2629                 case ESRCH:
2630                         SetLastError (ERROR_PROC_NOT_FOUND);
2631                         break;
2632                 default:
2633                         SetLastError (ERROR_GEN_FAILURE);
2634                 }
2635         }
2636         
2637         return (ret == 0);
2638 }
2639
2640 guint32
2641 GetPriorityClass (gpointer process)
2642 {
2643 #ifdef HAVE_GETPRIORITY
2644         struct _WapiHandle_process *process_handle;
2645         gboolean ok;
2646         int ret;
2647         pid_t pid;
2648         
2649         if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2650                 /* This is a pseudo handle */
2651                 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2652         } else {
2653                 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2654                                           (gpointer *) &process_handle);
2655
2656                 if (!ok) {
2657                         SetLastError (ERROR_INVALID_HANDLE);
2658                         return FALSE;
2659                 }
2660                 pid = process_handle->id;
2661         }
2662
2663         errno = 0;
2664         ret = getpriority (PRIO_PROCESS, pid);
2665         if (ret == -1 && errno != 0) {
2666                 switch (errno) {
2667                 case EPERM:
2668                 case EACCES:
2669                         SetLastError (ERROR_ACCESS_DENIED);
2670                         break;
2671                 case ESRCH:
2672                         SetLastError (ERROR_PROC_NOT_FOUND);
2673                         break;
2674                 default:
2675                         SetLastError (ERROR_GEN_FAILURE);
2676                 }
2677                 return FALSE;
2678         }
2679
2680         if (ret == 0)
2681                 return NORMAL_PRIORITY_CLASS;
2682         else if (ret < -15)
2683                 return REALTIME_PRIORITY_CLASS;
2684         else if (ret < -10)
2685                 return HIGH_PRIORITY_CLASS;
2686         else if (ret < 0)
2687                 return ABOVE_NORMAL_PRIORITY_CLASS;
2688         else if (ret > 10)
2689                 return IDLE_PRIORITY_CLASS;
2690         else if (ret > 0)
2691                 return BELOW_NORMAL_PRIORITY_CLASS;
2692
2693         return NORMAL_PRIORITY_CLASS;
2694 #else
2695         SetLastError (ERROR_NOT_SUPPORTED);
2696         return 0;
2697 #endif
2698 }
2699
2700 gboolean
2701 SetPriorityClass (gpointer process, guint32  priority_class)
2702 {
2703 #ifdef HAVE_SETPRIORITY
2704         struct _WapiHandle_process *process_handle;
2705         gboolean ok;
2706         int ret;
2707         int prio;
2708         pid_t pid;
2709         
2710         if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2711                 /* This is a pseudo handle */
2712                 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2713         } else {
2714                 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2715                                           (gpointer *) &process_handle);
2716
2717                 if (!ok) {
2718                         SetLastError (ERROR_INVALID_HANDLE);
2719                         return FALSE;
2720                 }
2721                 pid = process_handle->id;
2722         }
2723
2724         switch (priority_class) {
2725         case IDLE_PRIORITY_CLASS:
2726                 prio = 19;
2727                 break;
2728         case BELOW_NORMAL_PRIORITY_CLASS:
2729                 prio = 10;
2730                 break;
2731         case NORMAL_PRIORITY_CLASS:
2732                 prio = 0;
2733                 break;
2734         case ABOVE_NORMAL_PRIORITY_CLASS:
2735                 prio = -5;
2736                 break;
2737         case HIGH_PRIORITY_CLASS:
2738                 prio = -11;
2739                 break;
2740         case REALTIME_PRIORITY_CLASS:
2741                 prio = -20;
2742                 break;
2743         default:
2744                 SetLastError (ERROR_INVALID_PARAMETER);
2745                 return FALSE;
2746         }
2747
2748         ret = setpriority (PRIO_PROCESS, pid, prio);
2749         if (ret == -1) {
2750                 switch (errno) {
2751                 case EPERM:
2752                 case EACCES:
2753                         SetLastError (ERROR_ACCESS_DENIED);
2754                         break;
2755                 case ESRCH:
2756                         SetLastError (ERROR_PROC_NOT_FOUND);
2757                         break;
2758                 default:
2759                         SetLastError (ERROR_GEN_FAILURE);
2760                 }
2761         }
2762
2763         return ret == 0;
2764 #else
2765         SetLastError (ERROR_NOT_SUPPORTED);
2766         return FALSE;
2767 #endif
2768 }
2769
2770 static void
2771 mono_processes_cleanup (void)
2772 {
2773         struct MonoProcess *mp;
2774         struct MonoProcess *prev = NULL;
2775         struct MonoProcess *candidate = NULL;
2776         gpointer unref_handle;
2777         int spin;
2778
2779 #if DEBUG
2780         g_warning ("%s", __func__);
2781 #endif
2782
2783         /* Ensure we're not in here in multiple threads at once, nor recursive. */
2784         if (InterlockedCompareExchange (&mono_processes_cleaning_up, 1, 0) != 0)
2785                 return;
2786
2787         mp = mono_processes;
2788         while (mp != NULL) {
2789                 if (mp->pid == 0 && mp->handle != NULL) {
2790                         /* This process has exited and we need to remove the artifical ref
2791                          * on the handle */
2792                         mono_mutex_lock (&mono_processes_mutex);
2793                         unref_handle = mp->handle;
2794                         mp->handle = NULL;
2795                         mono_mutex_unlock (&mono_processes_mutex);
2796                         if (unref_handle)
2797                                 _wapi_handle_unref (unref_handle);
2798                         continue;
2799                 }
2800                 mp = mp->next;
2801         }
2802
2803         mp = mono_processes;
2804         spin = 0;
2805         while (mp != NULL) {
2806                 if ((mp->handle_count == 0 && mp->pid == 0) || candidate != NULL) {
2807                         if (spin > 0) {
2808                                 _wapi_handle_spin (spin);
2809                                 spin <<= 1;
2810                         }
2811
2812                         /* We've found a candidate */
2813                         mono_mutex_lock (&mono_processes_mutex);
2814                         if (candidate == NULL) {
2815                                 /* unlink it */
2816                                 if (mp == mono_processes) {
2817                                         mono_processes = mp->next;
2818                                 } else {
2819                                         prev->next = mp->next;
2820                                 }
2821                                 candidate = mp;
2822                         }
2823
2824                         /* It's still safe to traverse the structure.*/
2825                         mono_memory_barrier ();
2826
2827                         if (mono_processes_read_lock != 0) {
2828                                 /* The sigchld handler is watching us. Spin a bit and try again */
2829                                 if (spin == 0) {
2830                                         spin = 1;
2831                                 } else if (spin >= 8) {
2832                                         /* Just give up for now */
2833                                         mono_mutex_unlock (&mono_processes_mutex);
2834                                         break;
2835                                 }
2836                         } else {
2837                                 /* We've modified the list of processes, and we know the sigchld handler
2838                                  * isn't executing, so even if it executes at any moment, it'll see the
2839                                  * new version of the list. So now we can free the candidate. */
2840 #if DEBUG
2841                                 g_warning ("%s: freeing candidate %p", __func__, candidate);
2842 #endif
2843                                 mp = candidate->next;
2844                                 MONO_SEM_DESTROY (&candidate->exit_sem);
2845                                 g_free (candidate);
2846                                 candidate = NULL;
2847                         }
2848
2849                         mono_mutex_unlock (&mono_processes_mutex);
2850
2851                         continue;
2852                 }
2853                 spin = 0;
2854                 prev = mp;
2855                 mp = mp->next;
2856         }
2857
2858 #if DEBUG
2859         g_warning ("%s done", __func__);
2860 #endif
2861
2862         InterlockedDecrement (&mono_processes_cleaning_up);
2863 }
2864
2865 static void
2866 process_close (gpointer handle, gpointer data)
2867 {
2868         struct _WapiHandle_process *process_handle;
2869
2870 #if DEBUG
2871         g_warning ("%s", __func__);
2872 #endif
2873
2874         process_handle = (struct _WapiHandle_process *) data;
2875         if (process_handle->mono_process && process_handle->self == _wapi_getpid ())
2876                 InterlockedDecrement (&process_handle->mono_process->handle_count);
2877         mono_processes_cleanup ();
2878 }
2879
2880 #if HAVE_SIGACTION
2881 static void
2882 mono_sigchld_signal_handler (int _dummy, siginfo_t *info, void *context)
2883 {
2884         int status;
2885         int pid;
2886         struct MonoProcess *p;
2887
2888 #if DEBUG       
2889         fprintf (stdout, "SIG CHILD handler for pid: %i\n", info->si_pid);
2890 #endif
2891
2892         InterlockedIncrement (&mono_processes_read_lock);
2893
2894         do {
2895                 do {
2896                         pid = waitpid (-1, &status, WNOHANG);
2897                 } while (pid == -1 && errno == EINTR);
2898
2899                 if (pid <= 0)
2900                         break;
2901
2902 #if DEBUG
2903                 fprintf (stdout, "child ended: %i", pid);
2904 #endif
2905                 p = mono_processes;
2906                 while (p != NULL) {
2907                         if (p->pid == pid) {
2908                                 p->pid = 0; /* this pid doesn't exist anymore, clear it */
2909                                 p->status = status;
2910                                 MONO_SEM_POST (&p->exit_sem);
2911                                 break;
2912                         }
2913                         p = p->next;
2914                 }
2915         } while (1);
2916
2917         InterlockedDecrement (&mono_processes_read_lock);
2918
2919 #if DEBUG
2920         fprintf (stdout, "SIG CHILD handler: done looping.");
2921 #endif
2922 }
2923 #endif
2924
2925 static void process_add_sigchld_handler (void)
2926 {
2927 #if HAVE_SIGACTION
2928         struct sigaction sa;
2929
2930         sa.sa_sigaction = mono_sigchld_signal_handler;
2931         sigemptyset (&sa.sa_mask);
2932         sa.sa_flags = SA_NOCLDSTOP | SA_SIGINFO;
2933         g_assert (sigaction (SIGCHLD, &sa, &previous_chld_sa) != -1);
2934 #if DEBUG
2935         g_warning ("Added SIGCHLD handler");
2936 #endif
2937 #endif
2938 }
2939
2940 static guint32 process_wait (gpointer handle, guint32 timeout, gboolean alertable)
2941 {
2942         struct _WapiHandle_process *process_handle;
2943         gboolean ok;
2944         pid_t pid, ret;
2945         int status;
2946         guint32 start;
2947         guint32 now;
2948         struct MonoProcess *mp;
2949         gboolean spin;
2950         gpointer current_thread;
2951
2952         current_thread = _wapi_thread_handle_from_id (pthread_self ());
2953         if (current_thread == NULL) {
2954                 SetLastError (ERROR_INVALID_HANDLE);
2955                 return WAIT_FAILED;
2956         }
2957
2958         /* FIXME: We can now easily wait on processes that aren't our own children,
2959          * but WaitFor*Object won't call us for pseudo handles. */
2960         g_assert ((GPOINTER_TO_UINT (handle) & _WAPI_PROCESS_UNHANDLED) != _WAPI_PROCESS_UNHANDLED);
2961
2962 #if DEBUG
2963         g_warning ("%s (%p, %u)", __func__, handle, timeout);
2964 #endif
2965
2966         ok = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS, (gpointer *)&process_handle);
2967         if (ok == FALSE) {
2968                 g_warning ("%s: error looking up process handle %p", __func__, handle);
2969                 return WAIT_FAILED;
2970         }
2971
2972         if (process_handle->exited) {
2973                 /* We've already done this one */
2974 #if DEBUG
2975                 g_warning ("%s (%p, %u): Process already exited", __func__, handle, timeout);
2976 #endif
2977                 return WAIT_OBJECT_0;
2978         }
2979
2980         pid = process_handle->id;
2981
2982 #if DEBUG
2983         g_warning ("%s (%p, %u): PID: %d", __func__, handle, timeout, pid);
2984 #endif
2985
2986         /* We don't need to lock mono_processes here, the entry
2987          * has a handle_count > 0 which means it will not be freed. */
2988         mp = process_handle->mono_process;
2989         if (mp && process_handle->self != _wapi_getpid ()) {
2990                 /* mono_process points to memory in another process' address space: we can't use it */
2991                 mp = NULL;
2992         }
2993
2994         start = mono_msec_ticks ();
2995         now = start;
2996         spin = mp == NULL;
2997
2998         while (1) {
2999                 if (mp != NULL) {
3000                         /* We have a semaphore we can wait on */
3001                         if (timeout != INFINITE) {
3002 #if DEBUG
3003                                 g_warning ("%s (%p, %u): waiting on semaphore for %li ms...", 
3004                                         __func__, handle, timeout, (timeout - (now - start)));
3005 #endif
3006
3007                                 ret = MONO_SEM_TIMEDWAIT_ALERTABLE (&mp->exit_sem, (timeout - (now - start)), alertable);
3008                         } else {
3009 #if DEBUG
3010                                 g_warning ("%s (%p, %u): waiting on semaphore forever...", 
3011                                         __func__, handle, timeout);
3012 #endif
3013                                 ret = MONO_SEM_WAIT_ALERTABLE (&mp->exit_sem, alertable);
3014                         }
3015
3016                         if (ret == -1 && errno != EINTR && errno != ETIMEDOUT) {
3017 #if DEBUG
3018                                 g_warning ("%s (%p, %u): sem_timedwait failure: %s", 
3019                                         __func__, handle, timeout, g_strerror (errno));
3020 #endif
3021                                 /* Should we return a failure here? */
3022                         }
3023
3024                         if (ret == 0) {
3025                                 /* Success, process has exited */
3026                                 MONO_SEM_POST (&mp->exit_sem);
3027                                 break;
3028                         }
3029                 } else {
3030                         /* We did not create this process, so we can't waidpid / sem_wait it.
3031                          * We need to poll for the pid existence */
3032 #if DEBUG
3033                         g_warning ("%s (%p, %u): polling on pid...", __func__, handle, timeout);
3034 #endif
3035                         if (!is_pid_valid (pid)) {
3036                                 /* Success, process has exited */
3037                                 break;
3038                         }
3039                 }
3040
3041                 if (timeout == 0) {
3042 #if DEBUG
3043                         g_warning ("%s (%p, %u): WAIT_TIMEOUT (timeout = 0)", __func__, handle, timeout);
3044 #endif
3045                         return WAIT_TIMEOUT;
3046                 }
3047
3048                 now = mono_msec_ticks ();
3049                 if (now - start >= timeout) {
3050 #if DEBUG
3051                         g_warning ("%s (%p, %u): WAIT_TIMEOUT", __func__, handle, timeout);
3052 #endif
3053                         return WAIT_TIMEOUT;
3054                 }
3055
3056                 if (spin) {
3057                         /* "timeout - (now - start)" will not underflow, since timeout is always >=0,
3058                          * and we passed the check just above */
3059                         _wapi_handle_spin (MIN (100, timeout - (now - start)));
3060                 }
3061                 
3062                 if (alertable && _wapi_thread_apc_pending (current_thread)) {
3063 #if DEBUG
3064                         g_warning ("%s (%p, %u): WAIT_IO_COMPLETION", __func__, handle, timeout);
3065 #endif
3066                         return WAIT_IO_COMPLETION;
3067                 }
3068         }
3069
3070         /* Process must have exited */
3071 #if DEBUG
3072         g_warning ("%s (%p, %u): Waited successfully", __func__, handle, timeout);
3073 #endif
3074
3075         ret = _wapi_handle_lock_shared_handles ();
3076         g_assert (ret == 0);
3077
3078         status = mp ? mp->status : 0;
3079         if (WIFSIGNALED (status)) {
3080                 process_handle->exitstatus = 128 + WTERMSIG (status);
3081         } else {
3082                 process_handle->exitstatus = WEXITSTATUS (status);
3083         }
3084         _wapi_time_t_to_filetime (time (NULL), &process_handle->exit_time);
3085
3086         process_handle->exited = TRUE;
3087
3088 #if DEBUG
3089         g_warning ("%s (%p, %u): Setting pid %d signalled, exit status %d",
3090                    __func__, handle, timeout, process_handle->id, process_handle->exitstatus);
3091 #endif
3092
3093         _wapi_shared_handle_set_signal_state (handle, TRUE);
3094
3095         _wapi_handle_unlock_shared_handles ();
3096
3097         return WAIT_OBJECT_0;
3098 }
3099