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