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