2 * processes.c: Process handles
5 * Dick Porter (dick@ximian.com)
7 * (C) 2002-2011 Novell, Inc.
8 * Copyright 2011 Xamarin Inc
19 #include <sys/types.h>
27 #ifdef HAVE_SYS_PARAM_H
28 #include <sys/param.h>
32 #ifdef HAVE_SYS_WAIT_H
35 #ifdef HAVE_SYS_RESOURCE_H
36 #include <sys/resource.h>
39 #ifdef HAVE_SYS_MKDEV_H
40 #include <sys/mkdev.h>
47 /* sys/resource.h (for rusage) is required when using osx 10.3 (but not 10.4) */
49 #include <TargetConditionals.h>
50 #include <sys/resource.h>
57 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__) || defined(__FreeBSD__)
59 #include <sys/sysctl.h>
60 # if !defined(__OpenBSD__)
61 # include <sys/utsname.h>
63 # if defined(__FreeBSD__)
64 # include <sys/user.h> /* struct kinfo_proc */
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
73 #define _FILE_OFFSET_BITS 64
80 #include <KernelKit.h>
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>
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)
104 char ***_NSGetEnviron(void);
105 #define environ (*_NSGetEnviron())
107 extern char **environ;
111 #define DEBUG(...) g_message(__VA_ARGS__)
112 #define DEBUG_ENABLED 1
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);
121 #if !(defined(PLATFORM_MACOSX) || defined(__OpenBSD__) || defined(__FreeBSD__) || defined(__HAIKU__))
123 open_process_map (int pid, const char *mode);
126 struct _WapiHandleOps _wapi_process_ops = {
127 process_close, /* close_shared */
131 process_wait, /* special_wait */
136 static struct sigaction previous_chld_sa;
138 static mono_once_t process_sig_chld_once = MONO_ONCE_INIT;
139 static void process_add_sigchld_handler (void);
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
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);
159 static gpointer current_process;
160 static char *cli_launcher;
162 static WapiHandle_process *
163 lookup_process_handle (gpointer handle)
165 WapiHandle_process *process_data;
168 ret = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
169 (gpointer *)&process_data);
175 /* Check if a pid is valid - i.e. if a process exists with this pid. */
177 is_pid_valid (pid_t pid)
179 gboolean result = FALSE;
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)
186 #elif defined(__HAIKU__)
188 if (get_team_info ((team_id)pid, &teamInfo) == B_OK)
191 char *dir = g_strdup_printf ("/proc/%d", pid);
192 if (!access (dir, F_OK))
201 process_set_defaults (WapiHandle_process *process_handle)
203 /* These seem to be the defaults on w2k */
204 process_handle->min_working_set = 204800;
205 process_handle->max_working_set = 1413120;
207 _wapi_time_t_to_filetime (time (NULL), &process_handle->create_time);
211 len16 (const gunichar2 *str)
222 utf16_concat (const gunichar2 *first, ...)
229 va_start (args, first);
230 total += len16 (first);
231 for (s = va_arg (args, gunichar2 *); s != NULL; s = va_arg(args, gunichar2 *)){
236 ret = g_new (gunichar2, total + 1);
242 for (s = first; *s != 0; s++)
244 va_start (args, first);
245 for (s = va_arg (args, gunichar2 *); s != NULL; s = va_arg (args, gunichar2 *)){
248 for (p = s; *p != 0; p++)
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;
264 print_utf16 (gunichar2 *str)
268 res = g_utf16_to_utf8 (str, -1, NULL, NULL, NULL);
269 g_print ("%s\n", res);
274 /* Implemented as just a wrapper around CreateProcess () */
276 ShellExecuteEx (WapiShellExecuteInfo *sei)
279 WapiProcessInformation process_info;
283 /* w2k just segfaults here, but we can do better than
286 SetLastError (ERROR_INVALID_PARAMETER);
290 if (sei->lpFile == NULL)
291 /* w2k returns TRUE for this, for some reason. */
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 :-(
299 args = utf16_concat (utf16_quote, sei->lpFile, utf16_quote, sei->lpParameters == NULL ? NULL : utf16_space, sei->lpParameters, NULL);
301 SetLastError (ERROR_INVALID_DATA);
304 ret = CreateProcess (NULL, args, NULL, NULL, TRUE,
305 CREATE_UNICODE_ENVIRONMENT, NULL,
306 sei->lpDirectory, NULL, &process_info);
309 if (!ret && GetLastError () == ERROR_OUTOFMEMORY)
313 static char *handler;
314 static gunichar2 *handler_utf16;
316 if (handler_utf16 == (gunichar2 *)-1)
319 #ifdef PLATFORM_MACOSX
320 handler = g_strdup ("/usr/bin/open");
323 * On Linux, try: xdg-open, the FreeDesktop standard way of doing it,
324 * if that fails, try to use gnome-open, then kfmclient
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;
335 /* kfmclient needs exec argument */
337 handler = g_strconcat (old, " exec",
344 handler_utf16 = g_utf8_to_utf16 (handler, -1, NULL, NULL, NULL);
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
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);
358 SetLastError (ERROR_INVALID_DATA);
361 ret = CreateProcess (NULL, args, NULL, NULL, TRUE,
362 CREATE_UNICODE_ENVIRONMENT, NULL,
363 sei->lpDirectory, NULL, &process_info);
366 if (GetLastError () != ERROR_OUTOFMEMORY)
367 SetLastError (ERROR_INVALID_DATA);
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;
375 if (sei->fMask & SEE_MASK_NOCLOSEPROCESS)
376 sei->hProcess = process_info.hProcess;
378 CloseHandle (process_info.hProcess);
384 is_managed_binary (const char *filename)
386 int original_errno = errno;
387 #if defined(HAVE_LARGE_FILE_SUPPORT) && defined(O_LARGEFILE)
388 int file = open (filename, O_RDONLY | O_LARGEFILE);
390 int file = open (filename, O_RDONLY);
393 unsigned char buffer[8];
394 off_t file_size, optional_header_offset;
395 off_t pe_header_offset;
396 gboolean managed = FALSE;
398 guint32 first_word, second_word;
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.
405 errno = original_errno;
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);
413 /* We know we need to read a header field at offset 60. */
417 num_read = read (file, buffer, 2);
419 if ((num_read != 2) || (buffer[0] != 'M') || (buffer[1] != 'Z'))
422 new_offset = lseek (file, 60, SEEK_SET);
424 if (new_offset != 60)
427 num_read = read (file, buffer, 4);
431 pe_header_offset = buffer[0]
436 if (pe_header_offset + 24 > file_size)
439 new_offset = lseek (file, pe_header_offset, SEEK_SET);
441 if (new_offset != pe_header_offset)
444 num_read = read (file, buffer, 4);
446 if ((num_read != 4) || (buffer[0] != 'P') || (buffer[1] != 'E') || (buffer[2] != 0) || (buffer[3] != 0))
450 * Verify that the header we want in the optional header data
451 * is present in this binary.
453 new_offset = lseek (file, pe_header_offset + 20, SEEK_SET);
455 if (new_offset != pe_header_offset + 20)
458 num_read = read (file, buffer, 2);
460 if ((num_read != 2) || ((buffer[0] | (buffer[1] << 8)) < 216))
463 /* Read the CLR header address and size fields. These will be
464 * zero if the binary is not managed.
466 optional_header_offset = pe_header_offset + 24;
467 new_offset = lseek (file, optional_header_offset + 208, SEEK_SET);
469 if (new_offset != optional_header_offset + 208)
472 num_read = read (file, buffer, 8);
474 /* We are not concerned with endianness, only with
475 * whether it is zero or not.
477 first_word = *(guint32 *)&buffer[0];
478 second_word = *(guint32 *)&buffer[4];
480 if ((num_read != 8) || (first_word == 0) || (second_word == 0))
487 errno = original_errno;
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,
500 const gunichar2 *cwd,
501 WapiStartupInfo *startup,
502 WapiProcessInformation *process_info)
504 /* FIXME: use user information */
505 return CreateProcess (appname, cmdline, NULL, NULL, FALSE, create_flags, env, cwd, startup, process_info);
509 is_readable_or_executable (const char *prog)
512 int a = access (prog, R_OK);
513 int b = access (prog, X_OK);
514 if (a != 0 && b != 0)
516 if (stat (prog, &buf))
518 if (S_ISREG (buf.st_mode))
524 is_executable (const char *prog)
527 if (access (prog, X_OK) != 0)
529 if (stat (prog, &buf))
531 if (S_ISREG (buf.st_mode))
537 switch_dir_separators (char *path)
539 size_t i, pathLength = strlen(path);
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] != '\'' )
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)
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;
562 WapiHandle_process process_handle = {0}, *process_handle_data;
564 int in_fd, out_fd, err_fd;
567 int startup_pipe [2] = {-1, -1};
569 struct MonoProcess *mono_process;
570 gboolean fork_failed = FALSE;
572 mono_once (&process_sig_chld_once, process_add_sigchld_handler);
574 /* appname and cmdline specify the executable and its args:
576 * If appname is not NULL, it is the name of the executable.
577 * Otherwise the executable is the first token in cmdline.
579 * Executable searching:
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.
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:
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)
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 :-(
600 if (appname != NULL) {
601 cmd = mono_unicode_to_external (appname);
603 DEBUG ("%s: unicode conversion returned NULL",
606 SetLastError (ERROR_PATH_NOT_FOUND);
610 switch_dir_separators(cmd);
613 if (cmdline != NULL) {
614 args = mono_unicode_to_external (cmdline);
616 DEBUG ("%s: unicode conversion returned NULL", __func__);
618 SetLastError (ERROR_PATH_NOT_FOUND);
624 dir = mono_unicode_to_external (cwd);
626 DEBUG ("%s: unicode conversion returned NULL", __func__);
628 SetLastError (ERROR_PATH_NOT_FOUND);
632 /* Turn all the slashes round the right way */
633 switch_dir_separators(dir);
637 /* We can't put off locating the executable any longer :-( */
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
645 g_memmove (cmd, cmd+2, strlen (cmd)-2);
646 cmd[strlen (cmd)-2] = '\0';
649 unquoted = g_shell_unquote (cmd, NULL);
650 if (unquoted[0] == '/') {
651 /* Assume full path given */
652 prog = g_strdup (unquoted);
654 /* Executable existing ? */
655 if (!is_readable_or_executable (prog)) {
656 DEBUG ("%s: Couldn't find executable %s",
659 SetLastError (ERROR_FILE_NOT_FOUND);
663 /* Search for file named by cmd in the current
666 char *curdir = g_get_current_dir ();
668 prog = g_strdup_printf ("%s/%s", curdir, unquoted);
671 /* And make sure it's readable */
672 if (!is_readable_or_executable (prog)) {
673 DEBUG ("%s: Couldn't find executable %s",
676 SetLastError (ERROR_FILE_NOT_FOUND);
682 args_after_prog = args;
687 /* Dig out the first token from args, taking quotation
691 /* First, strip off all leading whitespace */
692 args = g_strchug (args);
694 /* args_after_prog points to the contents of args
695 * after token has been set (otherwise argv[0] is
698 args_after_prog = args;
700 /* Assume the opening quote will always be the first
703 if (args[0] == '\"' || 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);
711 /* Quotation mark appeared in the
712 * middle of the token. Just give the
713 * whole first token, quotes and all,
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;
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;
738 DEBUG ("%s: Couldn't find what to exec", __func__);
740 SetLastError (ERROR_PATH_NOT_FOUND);
744 /* Turn all the slashes round the right way. Only for
747 switch_dir_separators(token);
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
754 g_memmove (token, token+2, strlen (token)-2);
755 token[strlen (token)-2] = '\0';
758 if (token[0] == '/') {
759 /* Assume full path given */
760 prog = g_strdup (token);
762 /* Executable existing ? */
763 if (!is_readable_or_executable (prog)) {
764 DEBUG ("%s: Couldn't find executable %s",
767 SetLastError (ERROR_FILE_NOT_FOUND);
771 char *curdir = g_get_current_dir ();
773 /* FIXME: Need to record the directory
774 * containing the current process, and check
775 * that for the new executable as the first
779 prog = g_strdup_printf ("%s/%s", curdir, token);
782 /* I assume X_OK is the criterion to use,
785 * X_OK is too strict *if* the target is a CLR binary
787 if (!is_readable_or_executable (prog)) {
789 prog = g_find_program_in_path (token);
791 DEBUG ("%s: Couldn't find executable %s", __func__, token);
794 SetLastError (ERROR_FILE_NOT_FOUND);
803 DEBUG ("%s: Exec prog [%s] args [%s]", __func__, prog,
806 /* Check for CLR binaries; if found, we will try to invoke
807 * them using the same mono binary that started us.
809 if (is_managed_binary (prog)) {
810 gunichar2 *newapp = NULL, *newcmd;
814 newapp = mono_unicode_from_external (cli_launcher, &bytes_ignored);
816 newapp = mono_unicode_from_external ("mono", &bytes_ignored);
818 if (newapp != NULL) {
819 if (appname != NULL) {
820 newcmd = utf16_concat (utf16_quote, newapp, utf16_quote, utf16_space,
821 appname, utf16_space,
824 newcmd = utf16_concat (utf16_quote, newapp, utf16_quote, utf16_space,
828 g_free ((gunichar2 *)newapp);
830 if (newcmd != NULL) {
831 ret = CreateProcess (NULL, newcmd,
835 create_flags, new_environ,
839 g_free ((gunichar2 *)newcmd);
845 if (!is_executable (prog)) {
846 DEBUG ("%s: Executable permisson not set on %s", __func__, prog);
847 SetLastError (ERROR_ACCESS_DENIED);
852 if (args_after_prog != NULL && *args_after_prog) {
855 qprog = g_shell_quote (prog);
856 full_prog = g_strconcat (qprog, " ", args_after_prog, NULL);
859 full_prog = g_shell_quote (prog);
862 ret = g_shell_parse_argv (full_prog, NULL, &argv, &gerr);
864 g_message ("CreateProcess: %s\n", gerr->message);
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);
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));
880 process_handle.proc_name = g_strdup (prog);
882 process_set_defaults (&process_handle);
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__);
889 SetLastError (ERROR_OUTOFMEMORY);
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 :-(
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.
902 gunichar2 *new_environp;
904 /* Count the number of strings */
905 for (new_environp = (gunichar2 *)new_environ; *new_environp;
908 while (*new_environp) {
913 /* +2: one for the process handle value, and the last
916 env_strings = g_new0 (char *, env_count + 2);
918 /* Copy each environ string into 'strings' turning it
919 * into utf8 (or the requested encoding) at the same
923 for (new_environp = (gunichar2 *)new_environ; *new_environp;
925 env_strings[env_count] = mono_unicode_to_external (new_environp);
927 while (*new_environp) {
932 for (i = 0; environ[i] != NULL; i++)
935 /* +2: one for the process handle value, and the last
938 env_strings = g_new0 (char *, env_count + 2);
940 /* Copy each environ string into 'strings' turning it
941 * into utf8 (or the requested encoding) at the same
945 for (i = 0; environ[i] != NULL; i++) {
946 env_strings[env_count] = g_strdup (environ[i]);
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__);
960 thr_ret = _wapi_handle_lock_shared_handles ();
961 g_assert (thr_ret == 0);
966 SetLastError (ERROR_OUTOFMEMORY);
970 } else if (pid == 0) {
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]);
981 /* should we detach from the process group? */
983 /* Connect stdin, stdout and stderr */
988 if (inherit_handles != TRUE) {
989 /* FIXME: do something here */
992 /* Close all file descriptors */
993 for (i = wapi_getdtablesize () - 1; i > 2; i--)
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]);
1002 for (i = 0; env_strings[i] != NULL; i++)
1003 g_message ("env %d: [%s]", i, env_strings[i]);
1007 if (dir != NULL && chdir (dir) == -1) {
1013 execve (argv[0], argv, env_strings);
1020 process_handle_data = lookup_process_handle (handle);
1021 if (!process_handle_data) {
1022 g_warning ("%s: error looking up process handle %p", __func__,
1024 _wapi_handle_unref (handle);
1028 process_handle_data->id = pid;
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
1038 g_warning ("%s: could not create exit semaphore for process.", strerror (errno));
1039 g_free (mono_process);
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;
1046 process_handle_data->mono_process = mono_process;
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);
1054 if (process_info != NULL) {
1055 process_info->hProcess = handle;
1056 process_info->dwProcessId = pid;
1058 /* FIXME: we might need to handle the thread info some
1061 process_info->hThread = INVALID_HANDLE_VALUE;
1062 process_info->dwThreadId = 0;
1066 _wapi_handle_unlock_shared_handles ();
1069 _wapi_handle_unref (handle);
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]);
1090 g_strfreev (env_strings);
1094 DEBUG ("%s: returning handle %p for pid %d", __func__, handle,
1097 /* Check if something needs to be cleaned up. */
1098 mono_processes_cleanup ();
1104 process_set_name (WapiHandle_process *process_handle)
1106 char *progname, *utf8_progname, *slash;
1108 progname = g_get_prgname ();
1109 utf8_progname = mono_utf8_from_external (progname);
1111 DEBUG ("%s: using [%s] as prog name", __func__, progname);
1113 if (utf8_progname) {
1114 slash = strrchr (utf8_progname, '/');
1116 process_handle->proc_name = g_strdup (slash+1);
1118 process_handle->proc_name = g_strdup (utf8_progname);
1119 g_free (utf8_progname);
1124 wapi_processes_init (void)
1126 pid_t pid = _wapi_getpid ();
1127 WapiHandle_process process_handle = {0};
1129 _wapi_handle_register_capabilities (WAPI_HANDLE_PROCESS,
1130 WAPI_HANDLE_CAP_WAIT |
1131 WAPI_HANDLE_CAP_SPECIAL_WAIT);
1133 process_handle.id = pid;
1135 process_set_defaults (&process_handle);
1136 process_set_name (&process_handle);
1138 current_process = _wapi_handle_new (WAPI_HANDLE_PROCESS,
1140 g_assert (current_process);
1144 _wapi_process_duplicate (void)
1146 _wapi_handle_ref (current_process);
1148 return current_process;
1151 /* Returns a pseudo handle that doesn't need to be closed afterwards */
1153 GetCurrentProcess (void)
1155 return _WAPI_PROCESS_CURRENT;
1159 GetProcessId (gpointer handle)
1161 WapiHandle_process *process_handle;
1163 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (handle))
1164 /* This is a pseudo handle */
1165 return WAPI_HANDLE_TO_PID (handle);
1167 process_handle = lookup_process_handle (handle);
1168 if (!process_handle) {
1169 SetLastError (ERROR_INVALID_HANDLE);
1173 return process_handle->id;
1177 process_open_compare (gpointer handle, gpointer user_data)
1180 WapiHandle_process *process_handle;
1183 g_assert (!WAPI_IS_PSEUDO_PROCESS_HANDLE (handle));
1185 process_handle = lookup_process_handle (handle);
1186 g_assert (process_handle);
1188 DEBUG ("%s: looking at process %d", __func__, process_handle->id);
1190 checking_pid = process_handle->id;
1192 if (checking_pid == 0)
1195 wanted_pid = GPOINTER_TO_UINT (user_data);
1197 /* It's possible to have more than one process handle with the
1198 * same pid, but only the one running process can be
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
1214 CloseProcess (gpointer handle)
1216 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (handle))
1218 return CloseHandle (handle);
1222 * The caller owns the returned handle and must call CloseProcess () on it to clean it up.
1225 OpenProcess (guint32 req_access G_GNUC_UNUSED, gboolean inherit G_GNUC_UNUSED, guint32 pid)
1227 /* Find the process handle that corresponds to pid */
1228 gpointer handle = NULL;
1230 DEBUG ("%s: looking for process %d", __func__, pid);
1232 handle = _wapi_search_handle (WAPI_HANDLE_PROCESS,
1233 process_open_compare,
1234 GUINT_TO_POINTER (pid), NULL, TRUE);
1236 if (is_pid_valid (pid)) {
1237 /* Return a pseudo handle for processes we
1238 * don't have handles for
1240 return WAPI_PID_TO_HANDLE (pid);
1242 DEBUG ("%s: Can't find pid %d", __func__, pid);
1244 SetLastError (ERROR_PROC_NOT_FOUND);
1250 /* _wapi_search_handle () already added a ref */
1255 GetExitCodeProcess (gpointer process, guint32 *code)
1257 WapiHandle_process *process_handle;
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
1268 if (is_pid_valid (pid)) {
1269 *code = STILL_ACTIVE;
1276 process_handle = lookup_process_handle (process);
1277 if (!process_handle) {
1278 DEBUG ("%s: Can't find process %p", __func__, process);
1283 if (process_handle->id == _wapi_getpid ()) {
1284 *code = STILL_ACTIVE;
1288 /* A process handle is only signalled if the process has exited
1289 * and has been waited for */
1291 /* Make sure any process exit has been noticed, before
1292 * checking if the process is signalled. Fixes bug 325463.
1294 process_wait (process, 0, TRUE);
1296 if (_wapi_handle_issignalled (process))
1297 *code = process_handle->exitstatus;
1299 *code = STILL_ACTIVE;
1305 GetProcessTimes (gpointer process, WapiFileTime *create_time,
1306 WapiFileTime *exit_time, WapiFileTime *kernel_time,
1307 WapiFileTime *user_time)
1309 WapiHandle_process *process_handle;
1310 gboolean ku_times_set = FALSE;
1312 if (create_time == NULL || exit_time == NULL || kernel_time == NULL ||
1314 /* Not sure if w32 allows NULLs here or not */
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;
1321 mono_process_get_times (pid, &start_ticks, &user_ticks, &kernel_ticks);
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);
1330 process_handle = lookup_process_handle (process);
1331 if (!process_handle) {
1332 DEBUG ("%s: Can't find process %p", __func__, process);
1337 *create_time = process_handle->create_time;
1339 /* A process handle is only signalled if the process has
1340 * exited. Otherwise exit_time isn't set
1342 if (_wapi_handle_issignalled (process))
1343 *exit_time = process_handle->exit_time;
1345 #ifdef HAVE_GETRUSAGE
1346 if (process_handle->id == getpid ()) {
1347 struct rusage time_data;
1348 if (getrusage (RUSAGE_SELF, &time_data) == 0) {
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);
1358 if (!ku_times_set) {
1359 memset (kernel_time, 0, sizeof (WapiFileTime));
1360 memset (user_time, 0, sizeof (WapiFileTime));
1368 gpointer address_start;
1369 gpointer address_end;
1371 gpointer address_offset;
1377 static void free_procmodule (WapiProcModule *mod)
1379 if (mod->perms != NULL) {
1380 g_free (mod->perms);
1382 if (mod->filename != NULL) {
1383 g_free (mod->filename);
1388 static gint find_procmodule (gconstpointer a, gconstpointer b)
1390 WapiProcModule *want = (WapiProcModule *)a;
1391 WapiProcModule *compare = (WapiProcModule *)b;
1393 if ((want->device == compare->device) &&
1394 (want->inode == compare->inode)) {
1401 #ifdef PLATFORM_MACOSX
1402 #include <mach-o/dyld.h>
1403 #include <mach-o/getsect.h>
1405 static GSList *load_modules (void)
1408 WapiProcModule *mod;
1409 uint32_t count = _dyld_image_count ();
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;
1417 const struct mach_header *hdr;
1418 const struct section *sec;
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);
1427 hdr = _dyld_get_image_header (i);
1428 sec = getsectbynamefromheader (hdr, SEG_DATA, SECT_DATA);
1431 /* Some dynlibs do not have data sections on osx (#533893) */
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);
1443 mod->filename = g_strdup (name);
1445 if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
1446 ret = g_slist_prepend (ret, mod);
1448 free_procmodule (mod);
1452 ret = g_slist_reverse (ret);
1456 #elif defined(__OpenBSD__) || defined(__FreeBSD__)
1458 static int load_modules_callback (struct dl_phdr_info *info, size_t size, void *ptr)
1460 if (size < offsetof (struct dl_phdr_info, dlpi_phnum)
1461 + sizeof (info->dlpi_phnum))
1464 struct dl_phdr_info *cpy = calloc(1, sizeof(struct dl_phdr_info));
1468 memcpy(cpy, info, sizeof(*info));
1470 g_ptr_array_add ((GPtrArray *)ptr, cpy);
1475 static GSList *load_modules (void)
1478 WapiProcModule *mod;
1479 GPtrArray *dlarray = g_ptr_array_new();
1482 if (dl_iterate_phdr(load_modules_callback, dlarray) < 0)
1485 for (i = 0; i < dlarray->len; i++) {
1486 struct dl_phdr_info *info = g_ptr_array_index (dlarray, i);
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;
1495 mod->filename = g_strdup (info->dlpi_name);
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);
1502 if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
1503 ret = g_slist_prepend (ret, mod);
1505 free_procmodule (mod);
1509 g_ptr_array_free (dlarray, TRUE);
1511 ret = g_slist_reverse (ret);
1515 #elif defined(__HAIKU__)
1517 static GSList *load_modules (void)
1520 WapiProcModule *mod;
1522 image_info imageInfo;
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;
1535 if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
1536 ret = g_slist_prepend (ret, mod);
1538 free_procmodule (mod);
1542 ret = g_slist_reverse (ret);
1547 static GSList *load_modules (FILE *fp)
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;
1559 while (fgets (buf, sizeof(buf), fp)) {
1561 while (g_ascii_isspace (*p)) ++p;
1563 if (!g_ascii_isxdigit (*start_start)) {
1566 address_start = (gpointer)strtoul (start_start, &endp, 16);
1574 if (!g_ascii_isxdigit (*end_start)) {
1577 address_end = (gpointer)strtoul (end_start, &endp, 16);
1579 if (!g_ascii_isspace (*p)) {
1583 while (g_ascii_isspace (*p)) ++p;
1585 if (*prot_start != 'r' && *prot_start != '-') {
1588 memcpy (prot_buf, prot_start, 4);
1590 while (!g_ascii_isspace (*p)) ++p;
1592 while (g_ascii_isspace (*p)) ++p;
1594 if (!g_ascii_isxdigit (*offset_start)) {
1597 address_offset = (gpointer)strtoul (offset_start, &endp, 16);
1599 if (!g_ascii_isspace (*p)) {
1603 while(g_ascii_isspace (*p)) ++p;
1605 if (!g_ascii_isxdigit (*maj_dev_start)) {
1608 maj_dev = strtoul (maj_dev_start, &endp, 16);
1616 if (!g_ascii_isxdigit (*min_dev_start)) {
1619 min_dev = strtoul (min_dev_start, &endp, 16);
1621 if (!g_ascii_isspace (*p)) {
1625 while (g_ascii_isspace (*p)) ++p;
1627 if (!g_ascii_isxdigit (*inode_start)) {
1630 inode = (guint64)strtol (inode_start, &endp, 10);
1632 if (!g_ascii_isspace (*p)) {
1636 device = makedev ((int)maj_dev, (int)min_dev);
1637 if ((device == 0) &&
1642 while(g_ascii_isspace (*p)) ++p;
1643 /* p now points to the filename */
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;
1652 mod->filename = g_strdup (g_strstrip (p));
1654 if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
1655 ret = g_slist_prepend (ret, mod);
1657 free_procmodule (mod);
1661 ret = g_slist_reverse (ret);
1667 static gboolean match_procname_to_modulename (char *procname, char *modulename)
1669 char* lastsep = NULL;
1670 char* lastsep2 = NULL;
1673 gboolean result = FALSE;
1675 if (procname == NULL || modulename == NULL)
1678 DEBUG ("%s: procname=\"%s\", modulename=\"%s\"", __func__, procname, modulename);
1679 pname = mono_path_resolve_symlinks (procname);
1680 mname = mono_path_resolve_symlinks (modulename);
1682 if (!strcmp (pname, mname))
1686 lastsep = strrchr (mname, '/');
1688 if (!strcmp (lastsep+1, pname))
1691 lastsep2 = strrchr (pname, '/');
1694 if (!strcmp (lastsep+1, lastsep2+1))
1697 if (!strcmp (mname, lastsep2+1))
1707 DEBUG ("%s: result is %d", __func__, result);
1711 #if !(defined(PLATFORM_MACOSX) || defined(__OpenBSD__) || defined(__FreeBSD__) || defined(__HAIKU__))
1713 open_process_map (int pid, const char *mode)
1716 const char *proc_path[] = {
1717 "/proc/%d/maps", /* GNU/Linux */
1718 "/proc/%d/map", /* FreeBSD */
1724 for (i = 0; fp == NULL && proc_path [i]; i++) {
1725 filename = g_strdup_printf (proc_path[i], pid);
1726 fp = fopen (filename, mode);
1734 static char *get_process_name_from_proc (pid_t pid);
1736 gboolean EnumProcessModules (gpointer process, gpointer *modules,
1737 guint32 size, guint32 *needed)
1739 WapiHandle_process *process_handle;
1740 #if !defined(__OpenBSD__) && !defined(PLATFORM_MACOSX) && !defined(__FreeBSD__)
1743 GSList *mods = NULL;
1744 WapiProcModule *module;
1745 guint32 count, avail = size / sizeof(gpointer);
1748 char *proc_name = NULL;
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.
1759 if (size < sizeof(gpointer))
1762 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process)) {
1763 pid = WAPI_HANDLE_TO_PID (process);
1764 proc_name = get_process_name_from_proc (pid);
1766 process_handle = lookup_process_handle (process);
1767 if (!process_handle) {
1768 DEBUG ("%s: Can't find process %p", __func__, process);
1772 pid = process_handle->id;
1773 proc_name = process_handle->proc_name;
1776 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__) || defined(__FreeBSD__) || defined(__HAIKU__)
1777 mods = load_modules ();
1780 *needed = sizeof(gpointer);
1784 fp = open_process_map (pid, "r");
1786 /* No /proc/<pid>/maps so just return the main module
1790 *needed = sizeof(gpointer);
1793 mods = load_modules (fp);
1796 count = g_slist_length (mods);
1798 /* count + 1 to leave slot 0 for the main module */
1799 *needed = sizeof(gpointer) * (count + 1);
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
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;
1817 modules[i + 1] = module->address_start;
1820 for (i = 0; i < count; i++) {
1821 free_procmodule (g_slist_nth_data (mods, i));
1823 g_slist_free (mods);
1829 get_process_name_from_proc (pid_t pid)
1831 #if defined(__OpenBSD__) || defined(__FreeBSD__)
1834 struct kinfo_proc *pi;
1835 #elif defined(PLATFORM_MACOSX)
1836 #if !(!defined (__mono_ppc__) && defined (TARGET_OSX))
1838 struct kinfo_proc *pi;
1839 int mib[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, pid };
1843 char *filename = NULL;
1848 #if defined(PLATFORM_SOLARIS)
1849 filename = g_strdup_printf ("/proc/%d/psinfo", pid);
1850 if ((fp = fopen (filename, "r")) != NULL) {
1854 nread = fread (&info, sizeof (info), 1, fp);
1856 ret = g_strdup (info.pr_fname);
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);
1870 if (sysctl(mib, 4, NULL, &size, NULL, 0) < 0)
1873 if ((pi = malloc(size)) == NULL)
1876 if (sysctl (mib, 4, pi, &size, NULL, 0) < 0) {
1877 if (errno == ENOMEM) {
1879 DEBUG ("%s: Didn't allocate enough memory for kproc info", __func__);
1884 if (strlen (pi->kp_proc.p_comm) > 0)
1885 ret = g_strdup (pi->kp_proc.p_comm);
1889 #elif defined(__FreeBSD__)
1891 mib [1] = KERN_PROC;
1892 mib [2] = KERN_PROC_PID;
1894 if (sysctl(mib, 4, NULL, &size, NULL, 0) < 0) {
1895 DEBUG ("%s: sysctl() failed: %d", __func__, errno);
1899 if ((pi = malloc(size)) == NULL)
1902 if (sysctl (mib, 4, pi, &size, NULL, 0) < 0) {
1903 if (errno == ENOMEM) {
1905 DEBUG ("%s: Didn't allocate enough memory for kproc info", __func__);
1910 if (strlen (pi->ki_comm) > 0)
1911 ret = g_strdup (pi->ki_comm);
1913 #elif defined(__OpenBSD__)
1915 mib [1] = KERN_PROC;
1916 mib [2] = KERN_PROC_PID;
1918 mib [4] = sizeof(struct kinfo_proc);
1922 if (sysctl(mib, 6, NULL, &size, NULL, 0) < 0) {
1923 DEBUG ("%s: sysctl() failed: %d", __func__, errno);
1927 if ((pi = malloc(size)) == NULL)
1930 mib[5] = (int)(size / sizeof(struct kinfo_proc));
1932 if ((sysctl (mib, 6, pi, &size, NULL, 0) < 0) ||
1933 (size != sizeof (struct kinfo_proc))) {
1934 if (errno == ENOMEM) {
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);
1950 #elif defined(__HAIKU__)
1951 image_info imageInfo;
1954 if (get_next_image_info ((team_id)pid, &cookie, &imageInfo) == B_OK) {
1955 ret = g_strdup (imageInfo.name);
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);
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);
1983 filename = g_strdup_printf ("/proc/%d/stat", pid);
1984 if ((fp = fopen (filename, "r")) != NULL) {
1985 if (fgets (buf, 256, fp) != NULL) {
1988 start = strchr (buf, '(');
1989 if (start != NULL) {
1990 end = strchr (start + 1, ')');
1993 ret = g_strndup (start + 1,
2008 * wapi_process_get_path:
2010 * Return the full path of the executable of the process PID, or NULL if it cannot be determined.
2011 * Returns malloc-ed memory.
2014 wapi_process_get_path (pid_t pid)
2016 #if defined(PLATFORM_MACOSX) && !defined(__mono_ppc__) && defined(TARGET_OSX)
2017 char buf [PROC_PIDPATHINFO_MAXSIZE];
2020 res = proc_pidpath (pid, buf, sizeof (buf));
2023 if (buf [0] == '\0')
2025 return g_strdup (buf);
2027 return get_process_name_from_proc (pid);
2032 * wapi_process_set_cli_launcher:
2034 * Set the full path of the runtime executable used to launch managed exe's.
2037 wapi_process_set_cli_launcher (char *path)
2039 g_free (cli_launcher);
2040 cli_launcher = path ? g_strdup (path) : NULL;
2044 get_module_name (gpointer process, gpointer module,
2045 gunichar2 *basename, guint32 size,
2048 WapiHandle_process *process_handle;
2050 gunichar2 *procname;
2051 char *procname_ext = NULL;
2054 #if !defined(__OpenBSD__) && !defined(PLATFORM_MACOSX) && !defined(__FreeBSD__)
2057 GSList *mods = NULL;
2058 WapiProcModule *found_module;
2061 char *proc_name = NULL;
2063 DEBUG ("%s: Getting module base name, process handle %p module %p",
2064 __func__, process, module);
2066 size = size * sizeof (gunichar2); /* adjust for unicode characters */
2068 if (basename == NULL || size == 0)
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);
2076 process_handle = lookup_process_handle (process);
2077 if (!process_handle) {
2078 DEBUG ("%s: Can't find process %p", __func__,
2083 pid = process_handle->id;
2084 proc_name = g_strdup (process_handle->proc_name);
2087 /* Look up the address in /proc/<pid>/maps */
2088 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__) || defined(__FreeBSD__) || defined(__HAIKU__)
2089 mods = load_modules ();
2091 fp = open_process_map (pid, "r");
2093 if (errno == EACCES && module == NULL && base == TRUE) {
2094 procname_ext = get_process_name_from_proc (pid);
2096 /* No /proc/<pid>/maps, so just return failure
2103 mods = load_modules (fp);
2107 count = g_slist_length (mods);
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.
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))) {
2119 procname_ext = g_path_get_basename (found_module->filename);
2121 procname_ext = g_strdup (found_module->filename);
2124 free_procmodule (found_module);
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.
2132 procname_ext = get_process_name_from_proc (pid);
2135 g_slist_free (mods);
2139 DEBUG ("%s: Process name is [%s]", __func__,
2142 procname = mono_unicode_from_external (procname_ext, &bytes);
2143 if (procname == NULL) {
2145 g_free (procname_ext);
2151 /* Add the terminator */
2155 DEBUG ("%s: Size %d smaller than needed (%ld); truncating", __func__, size, bytes);
2157 memcpy (basename, procname, size);
2159 DEBUG ("%s: Size %d larger than needed (%ld)",
2160 __func__, size, bytes);
2162 memcpy (basename, procname, bytes);
2166 g_free (procname_ext);
2175 GetModuleBaseName (gpointer process, gpointer module,
2176 gunichar2 *basename, guint32 size)
2178 return get_module_name (process, module, basename, size, TRUE);
2182 GetModuleFileNameEx (gpointer process, gpointer module,
2183 gunichar2 *filename, guint32 size)
2185 return get_module_name (process, module, filename, size, FALSE);
2189 GetModuleInformation (gpointer process, gpointer module,
2190 WapiModuleInfo *modinfo, guint32 size)
2192 WapiHandle_process *process_handle;
2194 #if !defined(__OpenBSD__) && !defined(PLATFORM_MACOSX) && !defined(__FreeBSD__)
2197 GSList *mods = NULL;
2198 WapiProcModule *found_module;
2201 gboolean ret = FALSE;
2202 char *proc_name = NULL;
2204 DEBUG ("%s: Getting module info, process handle %p module %p",
2205 __func__, process, module);
2207 if (modinfo == NULL || size < sizeof (WapiModuleInfo))
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);
2214 process_handle = lookup_process_handle (process);
2215 if (!process_handle) {
2216 DEBUG ("%s: Can't find process %p", __func__,
2221 pid = process_handle->id;
2222 proc_name = g_strdup (process_handle->proc_name);
2225 #if defined(PLATFORM_MACOSX) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__HAIKU__)
2226 mods = load_modules ();
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
2236 mods = load_modules (fp);
2239 count = g_slist_length (mods);
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.
2245 for (i = 0; i < count; i++) {
2246 found_module = (WapiProcModule *)g_slist_nth_data (mods, i);
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;
2256 free_procmodule (found_module);
2259 g_slist_free (mods);
2266 GetProcessWorkingSetSize (gpointer process, size_t *min, size_t *max)
2268 WapiHandle_process *process_handle;
2270 if (min == NULL || max == NULL)
2271 /* Not sure if w32 allows NULLs here or not */
2274 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process))
2275 /* This is a pseudo handle, so just fail for now */
2278 process_handle = lookup_process_handle (process);
2279 if (!process_handle) {
2280 DEBUG ("%s: Can't find process %p", __func__, process);
2285 *min = process_handle->min_working_set;
2286 *max = process_handle->max_working_set;
2292 SetProcessWorkingSetSize (gpointer process, size_t min, size_t max)
2294 WapiHandle_process *process_handle;
2296 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process))
2297 /* This is a pseudo handle, so just fail for now
2301 process_handle = lookup_process_handle (process);
2302 if (!process_handle) {
2303 DEBUG ("%s: Can't find process %p", __func__, process);
2308 process_handle->min_working_set = min;
2309 process_handle->max_working_set = max;
2316 TerminateProcess (gpointer process, gint32 exitCode)
2318 #if defined(HAVE_KILL)
2319 WapiHandle_process *process_handle;
2324 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process)) {
2325 /* This is a pseudo handle */
2326 pid = (pid_t)WAPI_HANDLE_TO_PID (process);
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);
2334 pid = process_handle->id;
2337 signo = (exitCode == -1) ? SIGKILL : SIGTERM;
2338 ret = kill (pid, signo);
2342 SetLastError (ERROR_INVALID_PARAMETER);
2345 SetLastError (ERROR_ACCESS_DENIED);
2348 SetLastError (ERROR_PROC_NOT_FOUND);
2351 SetLastError (ERROR_GEN_FAILURE);
2357 g_error ("kill() is not supported by this platform");
2363 GetPriorityClass (gpointer process)
2365 #ifdef HAVE_GETPRIORITY
2366 WapiHandle_process *process_handle;
2370 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process)) {
2371 /* This is a pseudo handle */
2372 pid = (pid_t)WAPI_HANDLE_TO_PID (process);
2374 process_handle = lookup_process_handle (process);
2375 if (!process_handle) {
2376 SetLastError (ERROR_INVALID_HANDLE);
2379 pid = process_handle->id;
2383 ret = getpriority (PRIO_PROCESS, pid);
2384 if (ret == -1 && errno != 0) {
2388 SetLastError (ERROR_ACCESS_DENIED);
2391 SetLastError (ERROR_PROC_NOT_FOUND);
2394 SetLastError (ERROR_GEN_FAILURE);
2400 return NORMAL_PRIORITY_CLASS;
2402 return REALTIME_PRIORITY_CLASS;
2404 return HIGH_PRIORITY_CLASS;
2406 return ABOVE_NORMAL_PRIORITY_CLASS;
2408 return IDLE_PRIORITY_CLASS;
2410 return BELOW_NORMAL_PRIORITY_CLASS;
2412 return NORMAL_PRIORITY_CLASS;
2414 SetLastError (ERROR_NOT_SUPPORTED);
2420 SetPriorityClass (gpointer process, guint32 priority_class)
2422 #ifdef HAVE_SETPRIORITY
2423 WapiHandle_process *process_handle;
2428 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process)) {
2429 /* This is a pseudo handle */
2430 pid = (pid_t)WAPI_HANDLE_TO_PID (process);
2432 process_handle = lookup_process_handle (process);
2433 if (!process_handle) {
2434 SetLastError (ERROR_INVALID_HANDLE);
2437 pid = process_handle->id;
2440 switch (priority_class) {
2441 case IDLE_PRIORITY_CLASS:
2444 case BELOW_NORMAL_PRIORITY_CLASS:
2447 case NORMAL_PRIORITY_CLASS:
2450 case ABOVE_NORMAL_PRIORITY_CLASS:
2453 case HIGH_PRIORITY_CLASS:
2456 case REALTIME_PRIORITY_CLASS:
2460 SetLastError (ERROR_INVALID_PARAMETER);
2464 ret = setpriority (PRIO_PROCESS, pid, prio);
2469 SetLastError (ERROR_ACCESS_DENIED);
2472 SetLastError (ERROR_PROC_NOT_FOUND);
2475 SetLastError (ERROR_GEN_FAILURE);
2481 SetLastError (ERROR_NOT_SUPPORTED);
2487 mono_processes_cleanup (void)
2489 struct MonoProcess *mp;
2490 struct MonoProcess *prev = NULL;
2491 GSList *finished = NULL;
2493 gpointer unref_handle;
2495 DEBUG ("%s", __func__);
2497 /* Ensure we're not in here in multiple threads at once, nor recursive. */
2498 if (InterlockedCompareExchange (&mono_processes_cleaning_up, 1, 0) != 0)
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
2505 mono_mutex_lock (&mono_processes_mutex);
2506 unref_handle = mp->handle;
2508 mono_mutex_unlock (&mono_processes_mutex);
2510 _wapi_handle_unref (unref_handle);
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
2520 mono_mutex_lock (&mono_processes_mutex);
2522 mp = mono_processes;
2524 if (mp->handle_count == 0 && mp->freeable) {
2527 * This code can run parallel with the sigchld handler, but the
2528 * modifications it makes are safe.
2530 if (mp == mono_processes)
2531 mono_processes = mp->next;
2533 prev->next = mp->next;
2534 finished = g_slist_prepend (finished, mp);
2543 mono_memory_barrier ();
2545 for (l = finished; l; l = l->next) {
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
2552 MONO_SEM_DESTROY (&mp->exit_sem);
2555 g_slist_free (finished);
2557 mono_mutex_unlock (&mono_processes_mutex);
2559 DEBUG ("%s done", __func__);
2561 InterlockedDecrement (&mono_processes_cleaning_up);
2565 process_close (gpointer handle, gpointer data)
2567 WapiHandle_process *process_handle;
2569 DEBUG ("%s", __func__);
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 ();
2580 MONO_SIGNAL_HANDLER_FUNC (static, mono_sigchld_signal_handler, (int _dummy, siginfo_t *info, void *context))
2584 struct MonoProcess *p;
2586 DEBUG ("SIG CHILD handler for pid: %i\n", info->si_pid);
2590 pid = waitpid (-1, &status, WNOHANG);
2591 } while (pid == -1 && errno == EINTR);
2596 DEBUG ("child ended: %i", pid);
2599 * This can run concurrently with the code in the rest of this module.
2601 for (p = mono_processes; p; p = p->next) {
2602 if (p->pid == pid) {
2607 p->pid = 0; /* this pid doesn't exist anymore, clear it */
2609 MONO_SEM_POST (&p->exit_sem);
2610 mono_memory_barrier ();
2611 /* Mark this as freeable, the pointer becomes invalid afterwards */
2616 DEBUG ("SIG CHILD handler: done looping.");
2622 process_add_sigchld_handler (void)
2625 struct sigaction sa;
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");
2636 process_wait (gpointer handle, guint32 timeout, gboolean alertable)
2638 WapiHandle_process *process_handle;
2639 pid_t pid G_GNUC_UNUSED, ret;
2643 struct MonoProcess *mp;
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);
2649 DEBUG ("%s (%p, %u)", __func__, handle, timeout);
2651 process_handle = lookup_process_handle (handle);
2652 if (!process_handle) {
2653 g_warning ("%s: error looking up process handle %p", __func__, handle);
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;
2663 pid = process_handle->id;
2665 DEBUG ("%s (%p, %u): PID: %d", __func__, handle, timeout, pid);
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;
2672 start = mono_msec_ticks ();
2676 if (timeout != INFINITE) {
2677 DEBUG ("%s (%p, %u): waiting on semaphore for %li ms...",
2678 __func__, handle, timeout, (timeout - (now - start)));
2680 ret = MONO_SEM_TIMEDWAIT_ALERTABLE (&mp->exit_sem, (timeout - (now - start)), alertable);
2682 DEBUG ("%s (%p, %u): waiting on semaphore forever...",
2683 __func__, handle, timeout);
2684 ret = MONO_SEM_WAIT_ALERTABLE (&mp->exit_sem, alertable);
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? */
2694 /* Success, process has exited */
2695 MONO_SEM_POST (&mp->exit_sem);
2700 DEBUG ("%s (%p, %u): WAIT_TIMEOUT (timeout = 0)", __func__, handle, timeout);
2701 return WAIT_TIMEOUT;
2704 now = mono_msec_ticks ();
2705 if (now - start >= timeout) {
2706 DEBUG ("%s (%p, %u): WAIT_TIMEOUT", __func__, handle, timeout);
2707 return WAIT_TIMEOUT;
2710 if (alertable && _wapi_thread_cur_apc_pending ()) {
2711 DEBUG ("%s (%p, %u): WAIT_IO_COMPLETION", __func__, handle, timeout);
2712 return WAIT_IO_COMPLETION;
2716 /* Process must have exited */
2717 DEBUG ("%s (%p, %u): Waited successfully", __func__, handle, timeout);
2719 ret = _wapi_handle_lock_shared_handles ();
2720 g_assert (ret == 0);
2722 status = mp ? mp->status : 0;
2723 if (WIFSIGNALED (status))
2724 process_handle->exitstatus = 128 + WTERMSIG (status);
2726 process_handle->exitstatus = WEXITSTATUS (status);
2727 _wapi_time_t_to_filetime (time (NULL), &process_handle->exit_time);
2729 process_handle->exited = TRUE;
2731 DEBUG ("%s (%p, %u): Setting pid %d signalled, exit status %d",
2732 __func__, handle, timeout, process_handle->id, process_handle->exitstatus);
2734 _wapi_handle_set_signal_state (handle, TRUE, TRUE);
2736 _wapi_handle_unlock_shared_handles ();
2738 return WAIT_OBJECT_0;
2742 wapi_processes_cleanup (void)
2744 g_free (cli_launcher);