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