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