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