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