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