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