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