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