New tests.
[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 #ifdef __APPLE__
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         GArray *processes = g_array_new (FALSE, FALSE, sizeof(pid_t));
1628         guint32 fit, i, j;
1629         DIR *dir;
1630         struct dirent *entry;
1631         
1632         mono_once (&process_current_once, process_set_current);
1633
1634         dir = opendir ("/proc");
1635         if (dir == NULL) {
1636                 return(FALSE);
1637         }
1638         while((entry = readdir (dir)) != NULL) {
1639                 if (isdigit (entry->d_name[0])) {
1640                         char *endptr;
1641                         pid_t pid = (pid_t)strtol (entry->d_name, &endptr, 10);
1642
1643                         if (*endptr == '\0') {
1644                                 /* Name was entirely numeric, so was a
1645                                  * process ID
1646                                  */
1647                                 g_array_append_val (processes, pid);
1648                         }
1649                 }
1650         }
1651         closedir (dir);
1652
1653         fit=len/sizeof(guint32);
1654         for (i = 0, j = 0; j < fit && i < processes->len; i++) {
1655                 pids[j++] = g_array_index (processes, pid_t, i);
1656         }
1657
1658         g_array_free (processes, TRUE);
1659         
1660         *needed = j * sizeof(guint32);
1661         
1662         return(TRUE);
1663 }
1664 #endif
1665
1666 static gboolean process_open_compare (gpointer handle, gpointer user_data)
1667 {
1668         pid_t wanted_pid;
1669         pid_t checking_pid = signal_process_if_gone (handle);
1670
1671         if (checking_pid == 0) {
1672                 return(FALSE);
1673         }
1674         
1675         wanted_pid = GPOINTER_TO_UINT (user_data);
1676
1677         /* It's possible to have more than one process handle with the
1678          * same pid, but only the one running process can be
1679          * unsignalled
1680          */
1681         if (checking_pid == wanted_pid &&
1682             _wapi_handle_issignalled (handle) == FALSE) {
1683                 /* If the handle is blown away in the window between
1684                  * returning TRUE here and _wapi_search_handle pinging
1685                  * the timestamp, the search will continue
1686                  */
1687                 return(TRUE);
1688         } else {
1689                 return(FALSE);
1690         }
1691 }
1692
1693 gpointer OpenProcess (guint32 req_access G_GNUC_UNUSED, gboolean inherit G_GNUC_UNUSED, guint32 pid)
1694 {
1695         /* Find the process handle that corresponds to pid */
1696         gpointer handle;
1697         
1698         mono_once (&process_current_once, process_set_current);
1699
1700 #ifdef DEBUG
1701         g_message ("%s: looking for process %d", __func__, pid);
1702 #endif
1703
1704         handle = _wapi_search_handle (WAPI_HANDLE_PROCESS,
1705                                       process_open_compare,
1706                                       GUINT_TO_POINTER (pid), NULL, TRUE);
1707         if (handle == 0) {
1708 #if defined(__OpenBSD__)
1709                 if ((kill(pid, 0) == 0) || (errno == EPERM)) {
1710 #elif defined(__HAIKU__)
1711                 team_info teamInfo;
1712                 if (get_team_info ((team_id)pid, &teamInfo) == B_OK) {
1713 #else
1714                 gchar *dir = g_strdup_printf ("/proc/%d", pid);
1715                 if (!access (dir, F_OK)) {
1716 #endif
1717                         /* Return a pseudo handle for processes we
1718                          * don't have handles for
1719                          */
1720                         return GINT_TO_POINTER (_WAPI_PROCESS_UNHANDLED + pid);
1721                 } else {
1722 #ifdef DEBUG
1723                         g_message ("%s: Can't find pid %d", __func__, pid);
1724 #endif
1725
1726                         SetLastError (ERROR_PROC_NOT_FOUND);
1727         
1728                         return(NULL);
1729                 }
1730         }
1731
1732         _wapi_handle_ref (handle);
1733         
1734         return(handle);
1735 }
1736
1737 gboolean GetExitCodeProcess (gpointer process, guint32 *code)
1738 {
1739         struct _WapiHandle_process *process_handle;
1740         gboolean ok;
1741         
1742         mono_once (&process_current_once, process_set_current);
1743
1744         if(code==NULL) {
1745                 return(FALSE);
1746         }
1747         
1748         if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
1749                 /* This is a pseudo handle, so we don't know what the
1750                  * exit code was
1751                  */
1752                 return(FALSE);
1753         }
1754         
1755         ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
1756                                 (gpointer *)&process_handle);
1757         if(ok==FALSE) {
1758 #ifdef DEBUG
1759                 g_message ("%s: Can't find process %p", __func__, process);
1760 #endif
1761                 
1762                 return(FALSE);
1763         }
1764         
1765         /* A process handle is only signalled if the process has exited
1766          * and has been waited for */
1767
1768         /* Make sure any process exit has been noticed, before
1769          * checking if the process is signalled.  Fixes bug 325463.
1770          */
1771         process_wait (process, 0);
1772         
1773         if (_wapi_handle_issignalled (process) == TRUE) {
1774                 *code = process_handle->exitstatus;
1775         } else {
1776                 *code = STILL_ACTIVE;
1777         }
1778         
1779         return(TRUE);
1780 }
1781
1782 gboolean GetProcessTimes (gpointer process, WapiFileTime *create_time,
1783                           WapiFileTime *exit_time, WapiFileTime *kernel_time,
1784                           WapiFileTime *user_time)
1785 {
1786         struct _WapiHandle_process *process_handle;
1787         gboolean ok;
1788         gboolean ku_times_set = FALSE;
1789         
1790         mono_once (&process_current_once, process_set_current);
1791
1792         if(create_time==NULL || exit_time==NULL || kernel_time==NULL ||
1793            user_time==NULL) {
1794                 /* Not sure if w32 allows NULLs here or not */
1795                 return(FALSE);
1796         }
1797         
1798         if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
1799                 /* This is a pseudo handle, so just fail for now
1800                  */
1801                 return(FALSE);
1802         }
1803         
1804         ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
1805                                 (gpointer *)&process_handle);
1806         if(ok==FALSE) {
1807 #ifdef DEBUG
1808                 g_message ("%s: Can't find process %p", __func__, process);
1809 #endif
1810                 
1811                 return(FALSE);
1812         }
1813         
1814         *create_time=process_handle->create_time;
1815
1816         /* A process handle is only signalled if the process has
1817          * exited.  Otherwise exit_time isn't set
1818          */
1819         if(_wapi_handle_issignalled (process)==TRUE) {
1820                 *exit_time=process_handle->exit_time;
1821         }
1822
1823 #ifdef HAVE_GETRUSAGE
1824         if (process_handle->id == getpid ()) {
1825                 struct rusage time_data;
1826                 if (getrusage (RUSAGE_SELF, &time_data) == 0) {
1827                         gint64 tick_val;
1828                         gint64 *tick_val_ptr;
1829                         ku_times_set = TRUE;
1830                         tick_val = time_data.ru_utime.tv_sec * 10000000 + time_data.ru_utime.tv_usec * 10;
1831                         tick_val_ptr = (gint64*)user_time;
1832                         *tick_val_ptr = tick_val;
1833                         tick_val = time_data.ru_stime.tv_sec * 10000000 + time_data.ru_stime.tv_usec * 10;
1834                         tick_val_ptr = (gint64*)kernel_time;
1835                         *tick_val_ptr = tick_val;
1836                 }
1837         }
1838 #endif
1839         if (!ku_times_set) {
1840                 memset (kernel_time, 0, sizeof (WapiFileTime));
1841                 memset (user_time, 0, sizeof (WapiFileTime));
1842         }
1843
1844         return(TRUE);
1845 }
1846
1847 typedef struct
1848 {
1849         gpointer address_start;
1850         gpointer address_end;
1851         gchar *perms;
1852         gpointer address_offset;
1853         dev_t device;
1854         ino_t inode;
1855         gchar *filename;
1856 } WapiProcModule;
1857
1858 static void free_procmodule (WapiProcModule *mod)
1859 {
1860         if (mod->perms != NULL) {
1861                 g_free (mod->perms);
1862         }
1863         if (mod->filename != NULL) {
1864                 g_free (mod->filename);
1865         }
1866         g_free (mod);
1867 }
1868
1869 static gint find_procmodule (gconstpointer a, gconstpointer b)
1870 {
1871         WapiProcModule *want = (WapiProcModule *)a;
1872         WapiProcModule *compare = (WapiProcModule *)b;
1873         
1874         if ((want->device == compare->device) &&
1875             (want->inode == compare->inode)) {
1876                 return(0);
1877         } else {
1878                 return(1);
1879         }
1880 }
1881
1882 #ifdef PLATFORM_MACOSX
1883 #include <mach-o/dyld.h>
1884 #include <mach-o/getsect.h>
1885
1886 static GSList *load_modules (void)
1887 {
1888         GSList *ret = NULL;
1889         WapiProcModule *mod;
1890         uint32_t count = _dyld_image_count ();
1891         int i = 0;
1892
1893         for (i = 0; i < count; i++) {
1894 #if SIZEOF_VOID_P == 8
1895                 const struct mach_header_64 *hdr;
1896                 const struct section_64 *sec;
1897 #else
1898                 const struct mach_header *hdr;
1899                 const struct section *sec;
1900 #endif
1901                 const char *name;
1902                 intptr_t slide;
1903
1904                 slide = _dyld_get_image_vmaddr_slide (i);
1905                 name = _dyld_get_image_name (i);
1906                 hdr = _dyld_get_image_header (i);
1907 #if SIZEOF_VOID_P == 8
1908                 sec = getsectbynamefromheader_64 (hdr, SEG_DATA, SECT_DATA);
1909 #else
1910                 sec = getsectbynamefromheader (hdr, SEG_DATA, SECT_DATA);
1911 #endif
1912
1913                 /* Some dynlibs do not have data sections on osx (#533893) */
1914                 if (sec == 0) {
1915                         continue;
1916                 }
1917                         
1918                 mod = g_new0 (WapiProcModule, 1);
1919                 mod->address_start = GINT_TO_POINTER (sec->addr);
1920                 mod->address_end = GINT_TO_POINTER (sec->addr+sec->size);
1921                 mod->perms = g_strdup ("r--p");
1922                 mod->address_offset = 0;
1923                 mod->device = makedev (0, 0);
1924                 mod->inode = (ino_t) i;
1925                 mod->filename = g_strdup (name); 
1926                 
1927                 if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
1928                         ret = g_slist_prepend (ret, mod);
1929                 } else {
1930                         free_procmodule (mod);
1931                 }
1932         }
1933
1934         ret = g_slist_reverse (ret);
1935         
1936         return(ret);
1937 }
1938 #elif defined(__OpenBSD__)
1939 #include <link.h>
1940 static int load_modules_callback (struct dl_phdr_info *info, size_t size, void *ptr)
1941 {
1942         if (size < offsetof (struct dl_phdr_info, dlpi_phnum)
1943             + sizeof (info->dlpi_phnum))
1944                 return (-1);
1945
1946         struct dl_phdr_info *cpy = calloc(1, sizeof(struct dl_phdr_info));
1947         if (!cpy)
1948                 return (-1);
1949
1950         memcpy(cpy, info, sizeof(*info));
1951
1952         g_ptr_array_add ((GPtrArray *)ptr, cpy);
1953
1954         return (0);
1955 }
1956
1957 static GSList *load_modules (void)
1958 {
1959         GSList *ret = NULL;
1960         WapiProcModule *mod;
1961         GPtrArray *dlarray = g_ptr_array_new();
1962         int i;
1963
1964         if (dl_iterate_phdr(load_modules_callback, dlarray) < 0)
1965                 return (ret);
1966
1967         for (i = 0; i < dlarray->len; i++) {
1968                 struct dl_phdr_info *info = g_ptr_array_index (dlarray, i);
1969
1970                 mod = g_new0 (WapiProcModule, 1);
1971                 mod->address_start = (gpointer)(info->dlpi_addr + info->dlpi_phdr[0].p_vaddr);
1972                 mod->address_end = (gpointer)(info->dlpi_addr +
1973                                        info->dlpi_phdr[info->dlpi_phnum - 1].p_vaddr);
1974                 mod->perms = g_strdup ("r--p");
1975                 mod->address_offset = 0;
1976                 mod->inode = (ino_t) i;
1977                 mod->filename = g_strdup (info->dlpi_name); 
1978
1979 #ifdef DEBUG
1980                 g_message ("%s: inode=%d, filename=%s, address_start=%p, address_end=%p", __func__,
1981                                    mod->inode, mod->filename, mod->address_start, mod->address_end);
1982 #endif
1983
1984                 free(info);
1985
1986                 if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
1987                         ret = g_slist_prepend (ret, mod);
1988                 } else {
1989                         free_procmodule (mod);
1990                 }
1991         }
1992
1993         g_ptr_array_free (dlarray, TRUE);
1994
1995         ret = g_slist_reverse (ret);
1996
1997         return(ret);
1998 }
1999 #elif defined(__HAIKU__)
2000
2001 static GSList *load_modules (void)
2002 {
2003         GSList *ret = NULL;
2004         WapiProcModule *mod;
2005         int32 cookie = 0;
2006         image_info imageInfo;
2007
2008         while (get_next_image_info (B_CURRENT_TEAM, &cookie, &imageInfo) == B_OK) {
2009                 mod = g_new0 (WapiProcModule, 1);
2010                 mod->device = imageInfo.device;
2011                 mod->inode = imageInfo.node;
2012                 mod->filename = g_strdup (imageInfo.name);
2013                 mod->address_start = MIN (imageInfo.text, imageInfo.data);
2014                 mod->address_end = MAX ((uint8_t*)imageInfo.text + imageInfo.text_size,
2015                         (uint8_t*)imageInfo.data + imageInfo.data_size);
2016                 mod->perms = g_strdup ("r--p");
2017                 mod->address_offset = 0;
2018
2019                 if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
2020                         ret = g_slist_prepend (ret, mod);
2021                 } else {
2022                         free_procmodule (mod);
2023                 }
2024         }
2025
2026         ret = g_slist_reverse (ret);
2027
2028         return ret;
2029 }
2030 #else
2031 static GSList *load_modules (FILE *fp)
2032 {
2033         GSList *ret = NULL;
2034         WapiProcModule *mod;
2035         gchar buf[MAXPATHLEN + 1], *p, *endp;
2036         gchar *start_start, *end_start, *prot_start, *offset_start;
2037         gchar *maj_dev_start, *min_dev_start, *inode_start, prot_buf[5];
2038         gpointer address_start, address_end, address_offset;
2039         guint32 maj_dev, min_dev;
2040         ino_t inode;
2041         dev_t device;
2042         
2043         while (fgets (buf, sizeof(buf), fp)) {
2044                 p = buf;
2045                 while (g_ascii_isspace (*p)) ++p;
2046                 start_start = p;
2047                 if (!g_ascii_isxdigit (*start_start)) {
2048                         continue;
2049                 }
2050                 address_start = (gpointer)strtoul (start_start, &endp, 16);
2051                 p = endp;
2052                 if (*p != '-') {
2053                         continue;
2054                 }
2055                 
2056                 ++p;
2057                 end_start = p;
2058                 if (!g_ascii_isxdigit (*end_start)) {
2059                         continue;
2060                 }
2061                 address_end = (gpointer)strtoul (end_start, &endp, 16);
2062                 p = endp;
2063                 if (!g_ascii_isspace (*p)) {
2064                         continue;
2065                 }
2066                 
2067                 while (g_ascii_isspace (*p)) ++p;
2068                 prot_start = p;
2069                 if (*prot_start != 'r' && *prot_start != '-') {
2070                         continue;
2071                 }
2072                 memcpy (prot_buf, prot_start, 4);
2073                 prot_buf[4] = '\0';
2074                 while (!g_ascii_isspace (*p)) ++p;
2075                 
2076                 while (g_ascii_isspace (*p)) ++p;
2077                 offset_start = p;
2078                 if (!g_ascii_isxdigit (*offset_start)) {
2079                         continue;
2080                 }
2081                 address_offset = (gpointer)strtoul (offset_start, &endp, 16);
2082                 p = endp;
2083                 if (!g_ascii_isspace (*p)) {
2084                         continue;
2085                 }
2086                 
2087                 while(g_ascii_isspace (*p)) ++p;
2088                 maj_dev_start = p;
2089                 if (!g_ascii_isxdigit (*maj_dev_start)) {
2090                         continue;
2091                 }
2092                 maj_dev = strtoul (maj_dev_start, &endp, 16);
2093                 p = endp;
2094                 if (*p != ':') {
2095                         continue;
2096                 }
2097                 
2098                 ++p;
2099                 min_dev_start = p;
2100                 if (!g_ascii_isxdigit (*min_dev_start)) {
2101                         continue;
2102                 }
2103                 min_dev = strtoul (min_dev_start, &endp, 16);
2104                 p = endp;
2105                 if (!g_ascii_isspace (*p)) {
2106                         continue;
2107                 }
2108                 
2109                 while (g_ascii_isspace (*p)) ++p;
2110                 inode_start = p;
2111                 if (!g_ascii_isxdigit (*inode_start)) {
2112                         continue;
2113                 }
2114                 inode = (ino_t)strtol (inode_start, &endp, 10);
2115                 p = endp;
2116                 if (!g_ascii_isspace (*p)) {
2117                         continue;
2118                 }
2119
2120                 device = makedev ((int)maj_dev, (int)min_dev);
2121                 if ((device == 0) &&
2122                     (inode == 0)) {
2123                         continue;
2124                 }
2125                 
2126                 while(g_ascii_isspace (*p)) ++p;
2127                 /* p now points to the filename */
2128
2129                 mod = g_new0 (WapiProcModule, 1);
2130                 mod->address_start = address_start;
2131                 mod->address_end = address_end;
2132                 mod->perms = g_strdup (prot_buf);
2133                 mod->address_offset = address_offset;
2134                 mod->device = device;
2135                 mod->inode = inode;
2136                 mod->filename = g_strdup (g_strstrip (p));
2137                 
2138                 if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
2139                         ret = g_slist_prepend (ret, mod);
2140                 } else {
2141                         free_procmodule (mod);
2142                 }
2143         }
2144
2145         ret = g_slist_reverse (ret);
2146         
2147         return(ret);
2148 }
2149 #endif
2150
2151 static gboolean match_procname_to_modulename (gchar *procname, gchar *modulename)
2152 {
2153         char* lastsep = NULL;
2154         char* pname = NULL;
2155         char* mname = NULL;
2156         gboolean result = FALSE;
2157
2158         if (procname == NULL || modulename == NULL)
2159                 return (FALSE);
2160
2161         pname = mono_path_resolve_symlinks (procname);
2162         mname = mono_path_resolve_symlinks (modulename);
2163
2164         if (!strcmp (pname, mname))
2165                 result = TRUE;
2166
2167         if (!result) {
2168                 lastsep = strrchr (mname, '/');
2169                 if (lastsep)
2170                         if (!strcmp (lastsep+1, pname))
2171                                 result = TRUE;
2172         }
2173
2174         g_free (pname);
2175         g_free (mname);
2176
2177         return result;
2178 }
2179
2180 #if !defined(__OpenBSD__)
2181 static FILE *
2182 open_process_map (int pid, const char *mode)
2183 {
2184         FILE *fp = NULL;
2185         const gchar *proc_path[] = {
2186                 "/proc/%d/maps",        /* GNU/Linux */
2187                 "/proc/%d/map",         /* FreeBSD */
2188                 NULL
2189         };
2190         int i;
2191         gchar *filename;
2192
2193         for (i = 0; fp == NULL && proc_path [i]; i++) {
2194                 filename = g_strdup_printf (proc_path[i], pid);
2195                 fp = fopen (filename, mode);
2196                 g_free (filename);
2197         }
2198
2199         return fp;
2200 }
2201 #endif
2202
2203 gboolean EnumProcessModules (gpointer process, gpointer *modules,
2204                              guint32 size, guint32 *needed)
2205 {
2206         struct _WapiHandle_process *process_handle;
2207         gboolean ok;
2208 #if !defined(__OpenBSD__)
2209         FILE *fp;
2210 #endif
2211         GSList *mods = NULL;
2212         WapiProcModule *module;
2213         guint32 count, avail = size / sizeof(gpointer);
2214         int i;
2215         pid_t pid;
2216         gchar *proc_name = NULL;
2217         
2218         /* Store modules in an array of pointers (main module as
2219          * modules[0]), using the load address for each module as a
2220          * token.  (Use 'NULL' as an alternative for the main module
2221          * so that the simple implementation can just return one item
2222          * for now.)  Get the info from /proc/<pid>/maps on linux,
2223          * /proc/<pid>/map on FreeBSD, other systems will have to
2224          * implement /dev/kmem reading or whatever other horrid
2225          * technique is needed.
2226          */
2227         if (size < sizeof(gpointer)) {
2228                 return(FALSE);
2229         }
2230
2231         if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2232                 /* This is a pseudo handle */
2233                 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2234         } else {
2235                 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2236                                           (gpointer *)&process_handle);
2237                 if (ok == FALSE) {
2238 #ifdef DEBUG
2239                         g_message ("%s: Can't find process %p", __func__, process);
2240 #endif
2241                 
2242                         return(FALSE);
2243                 }
2244                 pid = process_handle->id;
2245                 proc_name = process_handle->proc_name;
2246         }
2247         
2248 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__) || defined(__HAIKU__)
2249         {
2250                 mods = load_modules ();
2251 #else
2252         if ((fp = open_process_map (pid, "r")) == NULL) {
2253                 /* No /proc/<pid>/maps so just return the main module
2254                  * shortcut for now
2255                  */
2256                 modules[0] = NULL;
2257                 *needed = sizeof(gpointer);
2258         } else {
2259                 mods = load_modules (fp);
2260                 fclose (fp);
2261 #endif
2262                 count = g_slist_length (mods);
2263                 
2264                 /* count + 1 to leave slot 0 for the main module */
2265                 *needed = sizeof(gpointer) * (count + 1);
2266
2267                 /* Use the NULL shortcut, as the first line in
2268                  * /proc/<pid>/maps isn't the executable, and we need
2269                  * that first in the returned list. Check the module name 
2270                  * to see if it ends with the proc name and substitute 
2271                  * the first entry with it.  FIXME if this turns out to 
2272                  * be a problem.
2273                  */
2274                 modules[0] = NULL;
2275                 for (i = 0; i < (avail - 1) && i < count; i++) {
2276                         module = (WapiProcModule *)g_slist_nth_data (mods, i);
2277                         if (modules[0] != NULL)
2278                                 modules[i] = module->address_start;
2279                         else if (match_procname_to_modulename (proc_name, module->filename))
2280                                 modules[0] = module->address_start;
2281                         else
2282                                 modules[i + 1] = module->address_start;
2283                 }
2284                 
2285                 for (i = 0; i < count; i++) {
2286                         free_procmodule (g_slist_nth_data (mods, i));
2287                 }
2288                 g_slist_free (mods);
2289         }
2290
2291         return(TRUE);
2292 }
2293
2294 static gchar *get_process_name_from_proc (pid_t pid)
2295 {
2296 #if !defined(__OpenBSD__)
2297         FILE *fp;
2298         gchar *filename = NULL;
2299         gchar buf[256];
2300 #endif
2301         gchar *ret = NULL;
2302
2303 #if defined(PLATFORM_SOLARIS)
2304         filename = g_strdup_printf ("/proc/%d/psinfo", pid);
2305         if ((fp = fopen (filename, "r")) != NULL) {
2306                 struct psinfo info;
2307                 int nread;
2308
2309                 nread = fread (&info, sizeof (info), 1, fp);
2310                 if (nread == 1) {
2311                         ret = g_strdup (info.pr_fname);
2312                 }
2313
2314                 fclose (fp);
2315         }
2316         g_free (filename);
2317 #elif defined(PLATFORM_MACOSX)
2318         memset (buf, '\0', sizeof(buf));
2319         proc_name (pid, buf, sizeof(buf));
2320         if (strlen (buf) > 0)
2321                 ret = g_strdup (buf);
2322 #elif defined(__OpenBSD__)
2323         int mib [6];
2324         size_t size;
2325         struct kinfo_proc2 *pi;
2326
2327         mib [0] = CTL_KERN;
2328         mib [1] = KERN_PROC2;
2329         mib [2] = KERN_PROC_PID;
2330         mib [3] = pid;
2331         mib [4] = sizeof(struct kinfo_proc2);
2332         mib [5] = 0;
2333
2334 retry:
2335         if (sysctl(mib, 6, NULL, &size, NULL, 0) < 0)
2336                 return(ret);
2337
2338         if ((pi = malloc(size)) == NULL)
2339                 return(ret);
2340
2341         mib[5] = (int)(size / sizeof(struct kinfo_proc2));
2342
2343         if ((sysctl (mib, 6, pi, &size, NULL, 0) < 0) ||
2344                 (size != sizeof (struct kinfo_proc2))) {
2345                 if (errno == ENOMEM) {
2346                         free(pi);
2347                         goto retry;
2348                 }
2349                 return(ret);
2350         }
2351
2352         if (strlen (pi->p_comm) > 0)
2353                 ret = g_strdup (pi->p_comm);
2354
2355         free(pi);
2356 #elif defined(__HAIKU__)
2357         image_info imageInfo;
2358         int32 cookie = 0;
2359
2360         if (get_next_image_info ((team_id)pid, &cookie, &imageInfo) == B_OK) {
2361                 ret = g_strdup (imageInfo.name);
2362         }
2363 #else
2364         memset (buf, '\0', sizeof(buf));
2365         filename = g_strdup_printf ("/proc/%d/exe", pid);
2366         if (readlink (filename, buf, 255) > 0) {
2367                 ret = g_strdup (buf);
2368         }
2369         g_free (filename);
2370
2371         if (ret != NULL) {
2372                 return(ret);
2373         }
2374
2375         filename = g_strdup_printf ("/proc/%d/cmdline", pid);
2376         if ((fp = fopen (filename, "r")) != NULL) {
2377                 if (fgets (buf, 256, fp) != NULL) {
2378                         ret = g_strdup (buf);
2379                 }
2380                 
2381                 fclose (fp);
2382         }
2383         g_free (filename);
2384
2385         if (ret != NULL) {
2386                 return(ret);
2387         }
2388         
2389         filename = g_strdup_printf ("/proc/%d/stat", pid);
2390         if ((fp = fopen (filename, "r")) != NULL) {
2391                 if (fgets (buf, 256, fp) != NULL) {
2392                         gchar *start, *end;
2393                         
2394                         start = strchr (buf, '(');
2395                         if (start != NULL) {
2396                                 end = strchr (start + 1, ')');
2397                                 
2398                                 if (end != NULL) {
2399                                         ret = g_strndup (start + 1,
2400                                                          end - start - 1);
2401                                 }
2402                         }
2403                 }
2404                 
2405                 fclose (fp);
2406         }
2407         g_free (filename);
2408 #endif
2409
2410         if (ret != NULL) {
2411                 return(ret);
2412         }
2413
2414         return(NULL);
2415 }
2416
2417 static guint32 get_module_name (gpointer process, gpointer module,
2418                                 gunichar2 *basename, guint32 size,
2419                                 gboolean base)
2420 {
2421         struct _WapiHandle_process *process_handle;
2422         gboolean ok;
2423         pid_t pid;
2424         gunichar2 *procname;
2425         gchar *procname_ext = NULL;
2426         glong len;
2427         gsize bytes;
2428 #if !defined(__OpenBSD__)
2429         FILE *fp;
2430 #endif
2431         GSList *mods = NULL;
2432         WapiProcModule *found_module;
2433         guint32 count;
2434         int i;
2435         gchar *proc_name = NULL;
2436         
2437         mono_once (&process_current_once, process_set_current);
2438
2439 #ifdef DEBUG
2440         g_message ("%s: Getting module base name, process handle %p module %p",
2441                    __func__, process, module);
2442 #endif
2443
2444         size = size*sizeof(gunichar2); /* adjust for unicode characters */
2445
2446         if (basename == NULL || size == 0) {
2447                 return(0);
2448         }
2449         
2450         if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2451                 /* This is a pseudo handle */
2452                 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2453                 proc_name = get_process_name_from_proc (pid);
2454         } else {
2455                 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2456                                           (gpointer *)&process_handle);
2457                 if (ok == FALSE) {
2458 #ifdef DEBUG
2459                         g_message ("%s: Can't find process %p", __func__,
2460                                    process);
2461 #endif
2462                         
2463                         return(0);
2464                 }
2465                 pid = process_handle->id;
2466                 proc_name = g_strdup (process_handle->proc_name);
2467         }
2468
2469         /* Look up the address in /proc/<pid>/maps */
2470 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__) || defined(__HAIKU__)
2471         {
2472                 mods = load_modules ();
2473 #else
2474         if ((fp = open_process_map (pid, "r")) == NULL) {
2475                 if (errno == EACCES && module == NULL && base == TRUE) {
2476                         procname_ext = get_process_name_from_proc (pid);
2477                 } else {
2478                         /* No /proc/<pid>/maps, so just return failure
2479                          * for now
2480                          */
2481                         g_free (proc_name);
2482                         return(0);
2483                 }
2484         } else {
2485                 mods = load_modules (fp);
2486                 fclose (fp);
2487 #endif
2488                 count = g_slist_length (mods);
2489
2490                 /* If module != NULL compare the address.
2491                  * If module == NULL we are looking for the main module.
2492                  * The best we can do for now check it the module name end with the process name.
2493                  */
2494                 for (i = 0; i < count; i++) {
2495                         found_module = (WapiProcModule *)g_slist_nth_data (mods, i);
2496                         if (procname_ext == NULL &&
2497                             ((module == NULL && match_procname_to_modulename (proc_name, found_module->filename)) ||    
2498                              (module != NULL && found_module->address_start == module))) {
2499                                 if (base) {
2500                                         procname_ext = g_path_get_basename (found_module->filename);
2501                                 } else {
2502                                         procname_ext = g_strdup (found_module->filename);
2503                                 }
2504                         }
2505
2506                         free_procmodule (found_module);
2507                 }
2508
2509                 if (procname_ext == NULL)
2510                 {
2511                         /* If it's *still* null, we might have hit the
2512                          * case where reading /proc/$pid/maps gives an
2513                          * empty file for this user.
2514                          */
2515                         procname_ext = get_process_name_from_proc (pid);
2516                 }
2517
2518                 g_slist_free (mods);
2519                 g_free (proc_name);
2520         }
2521
2522         if (procname_ext != NULL) {
2523 #ifdef DEBUG
2524                 g_message ("%s: Process name is [%s]", __func__,
2525                            procname_ext);
2526 #endif
2527
2528                 procname = mono_unicode_from_external (procname_ext, &bytes);
2529                 if (procname == NULL) {
2530                         /* bugger */
2531                         g_free (procname_ext);
2532                         return(0);
2533                 }
2534                 
2535                 len = (bytes / 2);
2536                 
2537                 /* Add the terminator */
2538                 bytes += 2;
2539                 
2540                 if (size < bytes) {
2541 #ifdef DEBUG
2542                         g_message ("%s: Size %d smaller than needed (%ld); truncating", __func__, size, bytes);
2543 #endif
2544
2545                         memcpy (basename, procname, size);
2546                 } else {
2547 #ifdef DEBUG
2548                         g_message ("%s: Size %d larger than needed (%ld)",
2549                                    __func__, size, bytes);
2550 #endif
2551
2552                         memcpy (basename, procname, bytes);
2553                 }
2554                 
2555                 g_free (procname);
2556                 g_free (procname_ext);
2557                 
2558                 return(len);
2559         }
2560         
2561         return(0);
2562 }
2563
2564 guint32 GetModuleBaseName (gpointer process, gpointer module,
2565                            gunichar2 *basename, guint32 size)
2566 {
2567         return(get_module_name (process, module, basename, size, TRUE));
2568 }
2569
2570 guint32 GetModuleFileNameEx (gpointer process, gpointer module,
2571                              gunichar2 *filename, guint32 size)
2572 {
2573         return(get_module_name (process, module, filename, size, FALSE));
2574 }
2575
2576 gboolean GetModuleInformation (gpointer process, gpointer module,
2577                                WapiModuleInfo *modinfo, guint32 size)
2578 {
2579         struct _WapiHandle_process *process_handle;
2580         gboolean ok;
2581         pid_t pid;
2582 #if !defined(__OpenBSD__)
2583         FILE *fp;
2584 #endif
2585         GSList *mods = NULL;
2586         WapiProcModule *found_module;
2587         guint32 count;
2588         int i;
2589         gboolean ret = FALSE;
2590         gchar *proc_name = NULL;
2591         
2592         mono_once (&process_current_once, process_set_current);
2593         
2594 #ifdef DEBUG
2595         g_message ("%s: Getting module info, process handle %p module %p",
2596                    __func__, process, module);
2597 #endif
2598
2599         if (modinfo == NULL || size < sizeof(WapiModuleInfo)) {
2600                 return(FALSE);
2601         }
2602         
2603         if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2604                 /* This is a pseudo handle */
2605                 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2606                 proc_name = get_process_name_from_proc (pid);
2607         } else {
2608                 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2609                                           (gpointer *)&process_handle);
2610                 if (ok == FALSE) {
2611 #ifdef DEBUG
2612                         g_message ("%s: Can't find process %p", __func__,
2613                                    process);
2614 #endif
2615                         
2616                         return(FALSE);
2617                 }
2618                 pid = process_handle->id;
2619                 proc_name = g_strdup (process_handle->proc_name);
2620         }
2621
2622 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__) || defined(__HAIKU__)
2623         {
2624                 mods = load_modules ();
2625 #else
2626         /* Look up the address in /proc/<pid>/maps */
2627         if ((fp = open_process_map (pid, "r")) == NULL) {
2628                 /* No /proc/<pid>/maps, so just return failure
2629                  * for now
2630                  */
2631                 g_free (proc_name);
2632                 return(FALSE);
2633         } else {
2634                 mods = load_modules (fp);
2635                 fclose (fp);
2636 #endif
2637                 count = g_slist_length (mods);
2638
2639                 /* If module != NULL compare the address.
2640                  * If module == NULL we are looking for the main module.
2641                  * The best we can do for now check it the module name end with the process name.
2642                  */
2643                 for (i = 0; i < count; i++) {
2644                         found_module = (WapiProcModule *)g_slist_nth_data (mods, i);
2645                         if ( ret == FALSE &&
2646                              ((module == NULL && match_procname_to_modulename (proc_name, found_module->filename)) ||
2647                               (module != NULL && found_module->address_start == module))) {
2648                                 modinfo->lpBaseOfDll = found_module->address_start;
2649                                 modinfo->SizeOfImage = (gsize)(found_module->address_end) - (gsize)(found_module->address_start);
2650                                 modinfo->EntryPoint = found_module->address_offset;
2651                                 ret = TRUE;
2652                         }
2653
2654                         free_procmodule (found_module);
2655                 }
2656
2657                 g_slist_free (mods);
2658                 g_free (proc_name);
2659         }
2660
2661         return(ret);
2662 }
2663
2664 gboolean GetProcessWorkingSetSize (gpointer process, size_t *min, size_t *max)
2665 {
2666         struct _WapiHandle_process *process_handle;
2667         gboolean ok;
2668         
2669         mono_once (&process_current_once, process_set_current);
2670
2671         if(min==NULL || max==NULL) {
2672                 /* Not sure if w32 allows NULLs here or not */
2673                 return(FALSE);
2674         }
2675         
2676         if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2677                 /* This is a pseudo handle, so just fail for now
2678                  */
2679                 return(FALSE);
2680         }
2681         
2682         ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2683                                 (gpointer *)&process_handle);
2684         if(ok==FALSE) {
2685 #ifdef DEBUG
2686                 g_message ("%s: Can't find process %p", __func__, process);
2687 #endif
2688                 
2689                 return(FALSE);
2690         }
2691
2692         *min=process_handle->min_working_set;
2693         *max=process_handle->max_working_set;
2694         
2695         return(TRUE);
2696 }
2697
2698 gboolean SetProcessWorkingSetSize (gpointer process, size_t min, size_t max)
2699 {
2700         struct _WapiHandle_process *process_handle;
2701         gboolean ok;
2702
2703         mono_once (&process_current_once, process_set_current);
2704         
2705         if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2706                 /* This is a pseudo handle, so just fail for now
2707                  */
2708                 return(FALSE);
2709         }
2710
2711         ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2712                                 (gpointer *)&process_handle);
2713         if(ok==FALSE) {
2714 #ifdef DEBUG
2715                 g_message ("%s: Can't find process %p", __func__, process);
2716 #endif
2717                 
2718                 return(FALSE);
2719         }
2720
2721         process_handle->min_working_set=min;
2722         process_handle->max_working_set=max;
2723         
2724         return(TRUE);
2725 }
2726
2727
2728 gboolean
2729 TerminateProcess (gpointer process, gint32 exitCode)
2730 {
2731         struct _WapiHandle_process *process_handle;
2732         gboolean ok;
2733         int signo;
2734         int ret;
2735         pid_t pid;
2736         
2737         if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2738                 /* This is a pseudo handle */
2739                 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2740         } else {
2741                 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2742                                           (gpointer *) &process_handle);
2743
2744                 if (ok == FALSE) {
2745 #ifdef DEBUG
2746                         g_message ("%s: Can't find process %p", __func__,
2747                                    process);
2748 #endif
2749                         SetLastError (ERROR_INVALID_HANDLE);
2750                         return FALSE;
2751                 }
2752                 pid = process_handle->id;
2753         }
2754
2755         signo = (exitCode == -1) ? SIGKILL : SIGTERM;
2756         ret = kill (pid, signo);
2757         if (ret == -1) {
2758                 switch (errno) {
2759                 case EINVAL:
2760                         SetLastError (ERROR_INVALID_PARAMETER);
2761                         break;
2762                 case EPERM:
2763                         SetLastError (ERROR_ACCESS_DENIED);
2764                         break;
2765                 case ESRCH:
2766                         SetLastError (ERROR_PROC_NOT_FOUND);
2767                         break;
2768                 default:
2769                         SetLastError (ERROR_GEN_FAILURE);
2770                 }
2771         }
2772         
2773         return (ret == 0);
2774 }
2775
2776 guint32
2777 GetPriorityClass (gpointer process)
2778 {
2779 #ifdef HAVE_GETPRIORITY
2780         struct _WapiHandle_process *process_handle;
2781         gboolean ok;
2782         int ret;
2783         pid_t pid;
2784         
2785         if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2786                 /* This is a pseudo handle */
2787                 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2788         } else {
2789                 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2790                                           (gpointer *) &process_handle);
2791
2792                 if (!ok) {
2793                         SetLastError (ERROR_INVALID_HANDLE);
2794                         return FALSE;
2795                 }
2796                 pid = process_handle->id;
2797         }
2798
2799         errno = 0;
2800         ret = getpriority (PRIO_PROCESS, pid);
2801         if (ret == -1 && errno != 0) {
2802                 switch (errno) {
2803                 case EPERM:
2804                 case EACCES:
2805                         SetLastError (ERROR_ACCESS_DENIED);
2806                         break;
2807                 case ESRCH:
2808                         SetLastError (ERROR_PROC_NOT_FOUND);
2809                         break;
2810                 default:
2811                         SetLastError (ERROR_GEN_FAILURE);
2812                 }
2813                 return FALSE;
2814         }
2815
2816         if (ret == 0)
2817                 return NORMAL_PRIORITY_CLASS;
2818         else if (ret < -15)
2819                 return REALTIME_PRIORITY_CLASS;
2820         else if (ret < -10)
2821                 return HIGH_PRIORITY_CLASS;
2822         else if (ret < 0)
2823                 return ABOVE_NORMAL_PRIORITY_CLASS;
2824         else if (ret > 10)
2825                 return IDLE_PRIORITY_CLASS;
2826         else if (ret > 0)
2827                 return BELOW_NORMAL_PRIORITY_CLASS;
2828
2829         return NORMAL_PRIORITY_CLASS;
2830 #else
2831         SetLastError (ERROR_NOT_SUPPORTED);
2832         return 0;
2833 #endif
2834 }
2835
2836 gboolean
2837 SetPriorityClass (gpointer process, guint32  priority_class)
2838 {
2839 #ifdef HAVE_SETPRIORITY
2840         struct _WapiHandle_process *process_handle;
2841         gboolean ok;
2842         int ret;
2843         int prio;
2844         pid_t pid;
2845         
2846         if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2847                 /* This is a pseudo handle */
2848                 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2849         } else {
2850                 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2851                                           (gpointer *) &process_handle);
2852
2853                 if (!ok) {
2854                         SetLastError (ERROR_INVALID_HANDLE);
2855                         return FALSE;
2856                 }
2857                 pid = process_handle->id;
2858         }
2859
2860         switch (priority_class) {
2861         case IDLE_PRIORITY_CLASS:
2862                 prio = 19;
2863                 break;
2864         case BELOW_NORMAL_PRIORITY_CLASS:
2865                 prio = 10;
2866                 break;
2867         case NORMAL_PRIORITY_CLASS:
2868                 prio = 0;
2869                 break;
2870         case ABOVE_NORMAL_PRIORITY_CLASS:
2871                 prio = -5;
2872                 break;
2873         case HIGH_PRIORITY_CLASS:
2874                 prio = -11;
2875                 break;
2876         case REALTIME_PRIORITY_CLASS:
2877                 prio = -20;
2878                 break;
2879         default:
2880                 SetLastError (ERROR_INVALID_PARAMETER);
2881                 return FALSE;
2882         }
2883
2884         ret = setpriority (PRIO_PROCESS, pid, prio);
2885         if (ret == -1) {
2886                 switch (errno) {
2887                 case EPERM:
2888                 case EACCES:
2889                         SetLastError (ERROR_ACCESS_DENIED);
2890                         break;
2891                 case ESRCH:
2892                         SetLastError (ERROR_PROC_NOT_FOUND);
2893                         break;
2894                 default:
2895                         SetLastError (ERROR_GEN_FAILURE);
2896                 }
2897         }
2898
2899         return ret == 0;
2900 #else
2901         SetLastError (ERROR_NOT_SUPPORTED);
2902         return FALSE;
2903 #endif
2904 }