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