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