2 * processes.c: Process handles
5 * Dick Porter (dick@ximian.com)
7 * (C) 2002-2006 Novell, Inc.
18 #include <sys/types.h>
24 #include <sys/resource.h>
26 #include <sys/param.h>
29 #ifdef HAVE_SYS_MKDEV_H
30 #include <sys/mkdev.h>
33 /* sys/resource.h (for rusage) is required when using osx 10.3 (but not 10.4) */
35 #include <sys/resource.h>
38 #ifdef PLATFORM_MACOSX
40 #include <sys/sysctl.h>
41 #include <sys/utsname.h>
44 #ifdef PLATFORM_SOLARIS
45 /* procfs.h cannot be included if this define is set, but it seems to work fine if it is undefined */
46 #if _FILE_OFFSET_BITS == 64
47 #undef _FILE_OFFSET_BITS
49 #define _FILE_OFFSET_BITS 64
55 #include <mono/io-layer/wapi.h>
56 #include <mono/io-layer/wapi-private.h>
57 #include <mono/io-layer/handles-private.h>
58 #include <mono/io-layer/misc-private.h>
59 #include <mono/io-layer/mono-mutex.h>
60 #include <mono/io-layer/process-private.h>
61 #include <mono/io-layer/threads.h>
62 #include <mono/utils/strenc.h>
63 #include <mono/utils/mono-path.h>
64 #include <mono/io-layer/timefuncs-private.h>
66 /* The process' environment strings */
68 /* Apple defines this in crt_externs.h but doesn't provide that header for
69 * arm-apple-darwin9. We'll manually define the symbol on Apple as it does
70 * in fact exist on all implementations (so far)
72 gchar ***_NSGetEnviron(void);
73 #define environ (*_NSGetEnviron())
75 extern char **environ;
80 static guint32 process_wait (gpointer handle, guint32 timeout);
81 FILE *open_process_map (int pid, const char *mode);
83 struct _WapiHandleOps _wapi_process_ops = {
84 NULL, /* close_shared */
88 process_wait, /* special_wait */
92 static mono_once_t process_current_once=MONO_ONCE_INIT;
93 static gpointer current_process=NULL;
95 static mono_once_t process_ops_once=MONO_ONCE_INIT;
97 static void process_ops_init (void)
99 _wapi_handle_register_capabilities (WAPI_HANDLE_PROCESS,
100 WAPI_HANDLE_CAP_WAIT |
101 WAPI_HANDLE_CAP_SPECIAL_WAIT);
104 static gboolean process_set_termination_details (gpointer handle, int status)
106 struct _WapiHandle_process *process_handle;
110 g_assert ((GPOINTER_TO_UINT (handle) & _WAPI_PROCESS_UNHANDLED) != _WAPI_PROCESS_UNHANDLED);
112 ok = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
113 (gpointer *)&process_handle);
115 g_warning ("%s: error looking up process handle %p",
120 thr_ret = _wapi_handle_lock_shared_handles ();
121 g_assert (thr_ret == 0);
123 if (WIFSIGNALED(status)) {
124 process_handle->exitstatus = 128 + WTERMSIG(status);
126 process_handle->exitstatus = WEXITSTATUS(status);
128 _wapi_time_t_to_filetime (time(NULL), &process_handle->exit_time);
130 /* Don't set process_handle->waited here, it needs to only
131 * happen in the parent when wait() has been called.
135 g_message ("%s: Setting handle %p pid %d signalled, exit status %d",
136 __func__, handle, process_handle->id,
137 process_handle->exitstatus);
140 _wapi_shared_handle_set_signal_state (handle, TRUE);
142 _wapi_handle_unlock_shared_handles ();
144 /* Drop the reference we hold so we have somewhere to store
145 * the exit details, now the process has in fact exited
147 _wapi_handle_unref (handle);
152 /* See if any child processes have terminated and wait() for them,
153 * updating process handle info. This function is called from the
154 * collection thread every few seconds.
156 static gboolean waitfor_pid (gpointer test, gpointer user_data)
158 struct _WapiHandle_process *process;
163 g_assert ((GPOINTER_TO_UINT (test) & _WAPI_PROCESS_UNHANDLED) != _WAPI_PROCESS_UNHANDLED);
165 ok = _wapi_lookup_handle (test, WAPI_HANDLE_PROCESS,
166 (gpointer *)&process);
168 /* The handle must have been too old and was reaped */
172 if (process->waited) {
173 /* We've already done this one */
178 ret = waitpid (process->id, &status, WNOHANG);
179 } while (errno == EINTR);
182 /* Process not ready for wait */
184 g_message ("%s: Process %d not ready for waiting for: %s",
185 __func__, process->id, g_strerror (errno));
192 g_message ("%s: Process %d finished", __func__, ret);
195 process->waited = TRUE;
197 *(int *)user_data = status;
202 void _wapi_process_reap (void)
208 g_message ("%s: Reaping child processes", __func__);
212 proc = _wapi_search_handle (WAPI_HANDLE_PROCESS, waitfor_pid,
213 &status, NULL, FALSE);
216 g_message ("%s: process handle %p exit code %d",
217 __func__, proc, status);
220 process_set_termination_details (proc, status);
222 /* _wapi_search_handle adds a reference, so
225 _wapi_handle_unref (proc);
227 } while (proc != NULL);
230 /* Limitations: This can only wait for processes that are our own
231 * children. Fixing this means resurrecting a daemon helper to manage
234 static guint32 process_wait (gpointer handle, guint32 timeout)
236 struct _WapiHandle_process *process_handle;
241 g_assert ((GPOINTER_TO_UINT (handle) & _WAPI_PROCESS_UNHANDLED) != _WAPI_PROCESS_UNHANDLED);
244 g_message ("%s: Waiting for process %p", __func__, handle);
247 ok = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
248 (gpointer *)&process_handle);
250 g_warning ("%s: error looking up process handle %p", __func__,
255 if (process_handle->waited) {
256 /* We've already done this one */
258 g_message ("%s: Process %p already signalled", __func__,
262 return (WAIT_OBJECT_0);
265 pid = process_handle->id;
268 g_message ("%s: PID is %d, timeout %d", __func__, pid, timeout);
271 if (timeout == INFINITE) {
272 if (pid == _wapi_getpid ()) {
277 while ((ret = waitpid (pid, &status, 0)) != pid) {
278 if (ret == (pid_t)-1 && errno != EINTR) {
283 } else if (timeout == 0) {
285 ret = waitpid (pid, &status, WNOHANG);
287 return (WAIT_TIMEOUT);
291 if (pid == _wapi_getpid ()) {
293 return(WAIT_TIMEOUT);
296 ret = waitpid (pid, &status, WNOHANG);
298 g_message ("%s: waitpid returns: %d, timeout is %d", __func__, ret, timeout);
303 } else if (ret == (pid_t)-1 &&
306 g_message ("%s: waitpid failure: %s",
311 if (errno == ECHILD &&
312 process_handle->waited) {
314 * process reaper must
318 g_message ("%s: Process %p already reaped", __func__, handle);
321 return(WAIT_OBJECT_0);
327 _wapi_handle_spin (100);
329 } while (timeout > 0);
333 return(WAIT_TIMEOUT);
337 /* Process must have exited */
339 g_message ("%s: Wait done, status %d", __func__, status);
342 ok = process_set_termination_details (handle, status);
344 SetLastError (ERROR_OUTOFMEMORY);
345 return (WAIT_FAILED);
347 process_handle->waited = TRUE;
349 return(WAIT_OBJECT_0);
352 void _wapi_process_signal_self ()
354 if (current_process != NULL) {
355 process_set_termination_details (current_process, 0);
359 static void process_set_defaults (struct _WapiHandle_process *process_handle)
361 /* These seem to be the defaults on w2k */
362 process_handle->min_working_set = 204800;
363 process_handle->max_working_set = 1413120;
365 process_handle->waited = FALSE;
367 _wapi_time_t_to_filetime (time (NULL), &process_handle->create_time);
371 len16 (const gunichar2 *str)
382 utf16_concat (const gunichar2 *first, ...)
389 va_start (args, first);
390 total += len16 (first);
391 for (s = va_arg (args, gunichar2 *); s != NULL; s = va_arg(args, gunichar2 *)){
396 ret = g_new (gunichar2, total + 1);
402 for (s = first; *s != 0; s++)
404 va_start (args, first);
405 for (s = va_arg (args, gunichar2 *); s != NULL; s = va_arg (args, gunichar2 *)){
408 for (p = s; *p != 0; p++)
416 #ifdef PLATFORM_MACOSX
418 /* 0 = no detection; -1 = not 10.5 or higher; 1 = 10.5 or higher */
419 static int osx_10_5_or_higher;
422 detect_osx_10_5_or_higher (void)
428 if (uname (&u) != 0){
429 osx_10_5_or_higher = 1;
437 osx_10_5_or_higher = -1;
439 osx_10_5_or_higher = 1;
443 is_macos_10_5_or_higher (void)
445 if (osx_10_5_or_higher == 0)
446 detect_osx_10_5_or_higher ();
448 return (osx_10_5_or_higher == 1);
452 static const gunichar2 utf16_space_bytes [2] = { 0x20, 0 };
453 static const gunichar2 *utf16_space = utf16_space_bytes;
454 static const gunichar2 utf16_quote_bytes [2] = { 0x22, 0 };
455 static const gunichar2 *utf16_quote = utf16_quote_bytes;
457 /* Implemented as just a wrapper around CreateProcess () */
458 gboolean ShellExecuteEx (WapiShellExecuteInfo *sei)
461 WapiProcessInformation process_info;
465 /* w2k just segfaults here, but we can do better than
468 SetLastError (ERROR_INVALID_PARAMETER);
472 if (sei->lpFile == NULL) {
473 /* w2k returns TRUE for this, for some reason. */
477 /* Put both executable and parameters into the second argument
478 * to CreateProcess (), so it searches $PATH. The conversion
479 * into and back out of utf8 is because there is no
480 * g_strdup_printf () equivalent for gunichar2 :-(
482 args = utf16_concat (sei->lpFile, sei->lpParameters == NULL ? NULL : utf16_space, sei->lpParameters, NULL);
484 SetLastError (ERROR_INVALID_DATA);
487 ret = CreateProcess (NULL, args, NULL, NULL, TRUE,
488 CREATE_UNICODE_ENVIRONMENT, NULL,
489 sei->lpDirectory, NULL, &process_info);
492 if (!ret && GetLastError () == ERROR_OUTOFMEMORY)
496 static char *handler;
497 static gunichar2 *handler_utf16;
499 if (handler_utf16 == (gunichar2 *)-1)
502 #ifdef PLATFORM_MACOSX
503 if (is_macos_10_5_or_higher ())
504 handler = g_strdup ("/usr/bin/open -W");
506 handler = g_strdup ("/usr/bin/open");
509 * On Linux, try: xdg-open, the FreeDesktop standard way of doing it,
510 * if that fails, try to use gnome-open, then kfmclient
512 handler = g_find_program_in_path ("xdg-open");
513 if (handler == NULL){
514 handler = g_find_program_in_path ("gnome-open");
515 if (handler == NULL){
516 handler = g_find_program_in_path ("kfmclient");
517 if (handler == NULL){
518 handler_utf16 = (gunichar2 *) -1;
521 /* kfmclient needs exec argument */
523 handler = g_strconcat (old, " exec",
530 handler_utf16 = g_utf8_to_utf16 (handler, -1, NULL, NULL, NULL);
533 /* Put quotes around the filename, in case it's a url
534 * that contains #'s (CreateProcess() calls
535 * g_shell_parse_argv(), which deliberately throws
536 * away anything after an unquoted #). Fixes bug
539 args = utf16_concat (handler_utf16, utf16_space, utf16_quote,
540 sei->lpFile, utf16_quote,
541 sei->lpParameters == NULL ? NULL : utf16_space,
542 sei->lpParameters, NULL);
544 SetLastError (ERROR_INVALID_DATA);
547 ret = CreateProcess (NULL, args, NULL, NULL, TRUE,
548 CREATE_UNICODE_ENVIRONMENT, NULL,
549 sei->lpDirectory, NULL, &process_info);
552 SetLastError (ERROR_INVALID_DATA);
557 if (sei->fMask & SEE_MASK_NOCLOSEPROCESS) {
558 sei->hProcess = process_info.hProcess;
560 CloseHandle (process_info.hProcess);
567 is_managed_binary (const gchar *filename)
569 int original_errno = errno;
570 #if defined(HAVE_LARGE_FILE_SUPPORT) && defined(O_LARGEFILE)
571 int file = open (filename, O_RDONLY | O_LARGEFILE);
573 int file = open (filename, O_RDONLY);
576 unsigned char buffer[8];
577 off_t file_size, optional_header_offset;
578 off_t pe_header_offset;
579 gboolean managed = FALSE;
581 guint32 first_word, second_word;
583 /* If we are unable to open the file, then we definitely
584 * can't say that it is managed. The child mono process
585 * probably wouldn't be able to open it anyway.
588 errno = original_errno;
592 /* Retrieve the length of the file for future sanity checks. */
593 file_size = lseek (file, 0, SEEK_END);
594 lseek (file, 0, SEEK_SET);
596 /* We know we need to read a header field at offset 60. */
600 num_read = read (file, buffer, 2);
602 if ((num_read != 2) || (buffer[0] != 'M') || (buffer[1] != 'Z'))
605 new_offset = lseek (file, 60, SEEK_SET);
607 if (new_offset != 60)
610 num_read = read (file, buffer, 4);
614 pe_header_offset = buffer[0]
619 if (pe_header_offset + 24 > file_size)
622 new_offset = lseek (file, pe_header_offset, SEEK_SET);
624 if (new_offset != pe_header_offset)
627 num_read = read (file, buffer, 4);
629 if ((num_read != 4) || (buffer[0] != 'P') || (buffer[1] != 'E') || (buffer[2] != 0) || (buffer[3] != 0))
633 * Verify that the header we want in the optional header data
634 * is present in this binary.
636 new_offset = lseek (file, pe_header_offset + 20, SEEK_SET);
638 if (new_offset != pe_header_offset + 20)
641 num_read = read (file, buffer, 2);
643 if ((num_read != 2) || ((buffer[0] | (buffer[1] << 8)) < 216))
646 /* Read the CLR header address and size fields. These will be
647 * zero if the binary is not managed.
649 optional_header_offset = pe_header_offset + 24;
650 new_offset = lseek (file, optional_header_offset + 208, SEEK_SET);
652 if (new_offset != optional_header_offset + 208)
655 num_read = read (file, buffer, 8);
657 /* We are not concerned with endianness, only with
658 * whether it is zero or not.
660 first_word = *(guint32 *)&buffer[0];
661 second_word = *(guint32 *)&buffer[4];
663 if ((num_read != 8) || (first_word == 0) || (second_word == 0))
670 errno = original_errno;
674 gboolean CreateProcessWithLogonW (const gunichar2 *username,
675 const gunichar2 *domain,
676 const gunichar2 *password,
677 const guint32 logonFlags,
678 const gunichar2 *appname,
679 const gunichar2 *cmdline,
680 guint32 create_flags,
682 const gunichar2 *cwd,
683 WapiStartupInfo *startup,
684 WapiProcessInformation *process_info)
686 /* FIXME: use user information */
687 return CreateProcess (appname, cmdline, NULL, NULL, FALSE, create_flags, env, cwd, startup, process_info);
691 is_executable (const char *prog)
694 if (access (prog, X_OK) != 0)
696 if (stat (prog, &buf))
698 if (S_ISREG (buf.st_mode))
703 gboolean CreateProcess (const gunichar2 *appname, const gunichar2 *cmdline,
704 WapiSecurityAttributes *process_attrs G_GNUC_UNUSED,
705 WapiSecurityAttributes *thread_attrs G_GNUC_UNUSED,
706 gboolean inherit_handles, guint32 create_flags,
707 gpointer new_environ, const gunichar2 *cwd,
708 WapiStartupInfo *startup,
709 WapiProcessInformation *process_info)
711 gchar *cmd=NULL, *prog = NULL, *full_prog = NULL, *args = NULL, *args_after_prog = NULL, *dir = NULL, **env_strings = NULL, **argv = NULL;
712 guint32 i, env_count = 0;
713 gboolean ret = FALSE;
715 struct _WapiHandle_process process_handle = {0}, *process_handle_data;
717 int in_fd, out_fd, err_fd;
721 mono_once (&process_ops_once, process_ops_init);
723 /* appname and cmdline specify the executable and its args:
725 * If appname is not NULL, it is the name of the executable.
726 * Otherwise the executable is the first token in cmdline.
728 * Executable searching:
730 * If appname is not NULL, it can specify the full path and
731 * file name, or else a partial name and the current directory
732 * will be used. There is no additional searching.
734 * If appname is NULL, the first whitespace-delimited token in
735 * cmdline is used. If the name does not contain a full
736 * directory path, the search sequence is:
738 * 1) The directory containing the current process
739 * 2) The current working directory
740 * 3) The windows system directory (Ignored)
741 * 4) The windows directory (Ignored)
744 * Just to make things more interesting, tokens can contain
745 * white space if they are surrounded by quotation marks. I'm
746 * beginning to understand just why windows apps are generally
747 * so crap, with an API like this :-(
749 if (appname != NULL) {
750 cmd = mono_unicode_to_external (appname);
753 g_message ("%s: unicode conversion returned NULL",
757 SetLastError (ERROR_PATH_NOT_FOUND);
761 /* Turn all the slashes round the right way */
762 for (i = 0; i < strlen (cmd); i++) {
763 if (cmd[i] == '\\') {
769 if (cmdline != NULL) {
770 args = mono_unicode_to_external (cmdline);
773 g_message ("%s: unicode conversion returned NULL", __func__);
776 SetLastError (ERROR_PATH_NOT_FOUND);
782 dir = mono_unicode_to_external (cwd);
785 g_message ("%s: unicode conversion returned NULL", __func__);
788 SetLastError (ERROR_PATH_NOT_FOUND);
792 /* Turn all the slashes round the right way */
793 for (i = 0; i < strlen (dir); i++) {
794 if (dir[i] == '\\') {
801 /* We can't put off locating the executable any longer :-( */
804 if (g_ascii_isalpha (cmd[0]) && (cmd[1] == ':')) {
805 /* Strip off the drive letter. I can't
806 * believe that CP/M holdover is still
809 g_memmove (cmd, cmd+2, strlen (cmd)-2);
810 cmd[strlen (cmd)-2] = '\0';
813 unquoted = g_shell_unquote (cmd, NULL);
814 if (unquoted[0] == '/') {
815 /* Assume full path given */
816 prog = g_strdup (unquoted);
818 /* Executable existing ? */
819 if (!is_executable (prog)) {
821 g_message ("%s: Couldn't find executable %s",
825 SetLastError (ERROR_FILE_NOT_FOUND);
829 /* Search for file named by cmd in the current
832 char *curdir = g_get_current_dir ();
834 prog = g_strdup_printf ("%s/%s", curdir, unquoted);
837 /* And make sure it's executable */
838 if (!is_executable (prog)) {
840 g_message ("%s: Couldn't find executable %s",
844 SetLastError (ERROR_FILE_NOT_FOUND);
850 args_after_prog = args;
855 /* Dig out the first token from args, taking quotation
859 /* First, strip off all leading whitespace */
860 args = g_strchug (args);
862 /* args_after_prog points to the contents of args
863 * after token has been set (otherwise argv[0] is
866 args_after_prog = args;
868 /* Assume the opening quote will always be the first
871 if (args[0] == '\"' || args [0] == '\'') {
873 for (i = 1; args[i] != '\0' && args[i] != quote; i++);
874 if (g_ascii_isspace (args[i+1])) {
875 /* We found the first token */
876 token = g_strndup (args+1, i-1);
877 args_after_prog = args + i;
879 /* Quotation mark appeared in the
880 * middle of the token. Just give the
881 * whole first token, quotes and all,
888 /* No quote mark, or malformed */
889 for (i = 0; args[i] != '\0'; i++) {
890 if (g_ascii_isspace (args[i])) {
891 token = g_strndup (args, i);
892 args_after_prog = args + i + 1;
898 if (token == NULL && args[0] != '\0') {
899 /* Must be just one token in the string */
900 token = g_strdup (args);
901 args_after_prog = NULL;
907 g_message ("%s: Couldn't find what to exec", __func__);
910 SetLastError (ERROR_PATH_NOT_FOUND);
914 /* Turn all the slashes round the right way. Only for
917 for (i = 0; i < strlen (token); i++) {
918 if (token[i] == '\\') {
923 if (g_ascii_isalpha (token[0]) && (token[1] == ':')) {
924 /* Strip off the drive letter. I can't
925 * believe that CP/M holdover is still
928 g_memmove (token, token+2, strlen (token)-2);
929 token[strlen (token)-2] = '\0';
932 if (token[0] == '/') {
933 /* Assume full path given */
934 prog = g_strdup (token);
936 /* Executable existing ? */
937 if (!is_executable (prog)) {
939 g_message ("%s: Couldn't find executable %s",
943 SetLastError (ERROR_FILE_NOT_FOUND);
948 char *curdir = g_get_current_dir ();
950 /* FIXME: Need to record the directory
951 * containing the current process, and check
952 * that for the new executable as the first
956 prog = g_strdup_printf ("%s/%s", curdir, token);
959 /* I assume X_OK is the criterion to use,
962 if (!is_executable (prog)) {
964 prog = g_find_program_in_path (token);
967 g_message ("%s: Couldn't find executable %s", __func__, token);
971 SetLastError (ERROR_FILE_NOT_FOUND);
981 g_message ("%s: Exec prog [%s] args [%s]", __func__, prog,
985 /* Check for CLR binaries; if found, we will try to invoke
986 * them using the same mono binary that started us.
988 if (is_managed_binary (prog)) {
989 gunichar2 *newapp, *newcmd;
992 newapp = mono_unicode_from_external ("mono", &bytes_ignored);
994 if (newapp != NULL) {
995 if (appname != NULL) {
996 newcmd = utf16_concat (newapp, utf16_space,
997 appname, utf16_space,
1000 newcmd = utf16_concat (newapp, utf16_space,
1004 g_free ((gunichar2 *)newapp);
1006 if (newcmd != NULL) {
1007 ret = CreateProcess (NULL, newcmd,
1011 create_flags, new_environ,
1015 g_free ((gunichar2 *)newcmd);
1022 if (args_after_prog != NULL && *args_after_prog) {
1025 qprog = g_shell_quote (prog);
1026 full_prog = g_strconcat (qprog, " ", args_after_prog, NULL);
1029 full_prog = g_shell_quote (prog);
1032 ret = g_shell_parse_argv (full_prog, NULL, &argv, &gerr);
1034 /* FIXME: Could do something with the GError here
1038 if (startup != NULL && startup->dwFlags & STARTF_USESTDHANDLES) {
1039 in_fd = GPOINTER_TO_UINT (startup->hStdInput);
1040 out_fd = GPOINTER_TO_UINT (startup->hStdOutput);
1041 err_fd = GPOINTER_TO_UINT (startup->hStdError);
1043 in_fd = GPOINTER_TO_UINT (GetStdHandle (STD_INPUT_HANDLE));
1044 out_fd = GPOINTER_TO_UINT (GetStdHandle (STD_OUTPUT_HANDLE));
1045 err_fd = GPOINTER_TO_UINT (GetStdHandle (STD_ERROR_HANDLE));
1048 g_strlcpy (process_handle.proc_name, prog,
1049 _WAPI_PROC_NAME_MAX_LEN - 1);
1051 process_set_defaults (&process_handle);
1053 handle = _wapi_handle_new (WAPI_HANDLE_PROCESS, &process_handle);
1054 if (handle == _WAPI_HANDLE_INVALID) {
1055 g_warning ("%s: error creating process handle", __func__);
1058 SetLastError (ERROR_OUTOFMEMORY);
1062 /* Hold another reference so the process has somewhere to
1063 * store its exit data even if we drop this handle
1065 _wapi_handle_ref (handle);
1067 /* new_environ is a block of NULL-terminated strings, which
1068 * is itself NULL-terminated. Of course, passing an array of
1069 * string pointers would have made things too easy :-(
1071 * If new_environ is not NULL it specifies the entire set of
1072 * environment variables in the new process. Otherwise the
1073 * new process inherits the same environment.
1075 if (new_environ != NULL) {
1076 gunichar2 *new_environp;
1078 /* Count the number of strings */
1079 for (new_environp = (gunichar2 *)new_environ; *new_environp;
1082 while (*new_environp) {
1087 /* +2: one for the process handle value, and the last
1090 env_strings = g_new0 (gchar *, env_count + 2);
1092 /* Copy each environ string into 'strings' turning it
1093 * into utf8 (or the requested encoding) at the same
1097 for (new_environp = (gunichar2 *)new_environ; *new_environp;
1099 env_strings[env_count] = mono_unicode_to_external (new_environp);
1101 while (*new_environp) {
1106 for (i = 0; environ[i] != NULL; i++) {
1110 /* +2: one for the process handle value, and the last
1113 env_strings = g_new0 (gchar *, env_count + 2);
1115 /* Copy each environ string into 'strings' turning it
1116 * into utf8 (or the requested encoding) at the same
1120 for (i = 0; environ[i] != NULL; i++) {
1121 env_strings[env_count] = g_strdup (environ[i]);
1125 /* pass process handle info to the child, so it doesn't have
1126 * to do an expensive search over the whole list
1128 if (env_strings != NULL) {
1129 struct _WapiHandleUnshared *handle_data;
1130 struct _WapiHandle_shared_ref *ref;
1132 handle_data = &_WAPI_PRIVATE_HANDLES(GPOINTER_TO_UINT(handle));
1133 ref = &handle_data->u.shared;
1135 env_strings[env_count] = g_strdup_printf ("_WAPI_PROCESS_HANDLE_OFFSET=%d", ref->offset);
1138 thr_ret = _wapi_handle_lock_shared_handles ();
1139 g_assert (thr_ret == 0);
1144 SetLastError (ERROR_OUTOFMEMORY);
1145 _wapi_handle_unref (handle);
1147 } else if (pid == 0) {
1150 if (_wapi_shm_disabled == FALSE) {
1151 /* Wait for the parent to finish setting up
1152 * the handle. The semaphore lock is safe
1153 * because the sem_undo structures of a
1154 * semaphore aren't inherited across a fork
1155 * (), but we can't do this if we're not using
1158 thr_ret = _wapi_handle_lock_shared_handles ();
1159 g_assert (thr_ret == 0);
1161 _wapi_handle_unlock_shared_handles ();
1164 /* should we detach from the process group? */
1166 /* Connect stdin, stdout and stderr */
1171 if (inherit_handles != TRUE) {
1172 /* FIXME: do something here */
1175 /* Close all file descriptors */
1176 for (i = getdtablesize () - 1; i > 2; i--) {
1181 g_message ("%s: exec()ing [%s] in dir [%s]", __func__, cmd,
1183 for (i = 0; argv[i] != NULL; i++) {
1184 g_message ("arg %d: [%s]", i, argv[i]);
1187 for (i = 0; env_strings[i] != NULL; i++) {
1188 g_message ("env %d: [%s]", i, env_strings[i]);
1193 if (dir != NULL && chdir (dir) == -1) {
1199 execve (argv[0], argv, env_strings);
1206 ret = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
1207 (gpointer *)&process_handle_data);
1209 g_warning ("%s: error looking up process handle %p", __func__,
1211 _wapi_handle_unref (handle);
1215 process_handle_data->id = pid;
1217 if (process_info != NULL) {
1218 process_info->hProcess = handle;
1219 process_info->dwProcessId = pid;
1221 /* FIXME: we might need to handle the thread info some
1224 process_info->hThread = INVALID_HANDLE_VALUE;
1225 process_info->dwThreadId = 0;
1229 _wapi_handle_unlock_shared_handles ();
1235 if (full_prog != NULL) {
1247 if(env_strings != NULL) {
1248 g_strfreev (env_strings);
1255 g_message ("%s: returning handle %p for pid %d", __func__, handle,
1262 static void process_set_name (struct _WapiHandle_process *process_handle)
1264 gchar *progname, *utf8_progname, *slash;
1266 progname=g_get_prgname ();
1267 utf8_progname=mono_utf8_from_external (progname);
1270 g_message ("%s: using [%s] as prog name", __func__, progname);
1273 if(utf8_progname!=NULL) {
1274 slash=strrchr (utf8_progname, '/');
1276 g_strlcpy (process_handle->proc_name, slash+1,
1277 _WAPI_PROC_NAME_MAX_LEN - 1);
1279 g_strlcpy (process_handle->proc_name, utf8_progname,
1280 _WAPI_PROC_NAME_MAX_LEN - 1);
1283 g_free (utf8_progname);
1287 extern void _wapi_time_t_to_filetime (time_t timeval, WapiFileTime *filetime);
1289 #if !GLIB_CHECK_VERSION (2,4,0)
1290 #define g_setenv(a,b,c) setenv(a,b,c)
1291 #define g_unsetenv(a) unsetenv(a)
1294 static void process_set_current (void)
1296 pid_t pid = _wapi_getpid ();
1297 const char *handle_env;
1298 struct _WapiHandle_process process_handle = {0};
1300 mono_once (&process_ops_once, process_ops_init);
1302 handle_env = g_getenv ("_WAPI_PROCESS_HANDLE_OFFSET");
1303 g_unsetenv ("_WAPI_PROCESS_HANDLE_OFFSET");
1305 if (handle_env != NULL) {
1306 struct _WapiHandle_process *process_handlep;
1307 gchar *procname = NULL;
1310 current_process = _wapi_handle_new_from_offset (WAPI_HANDLE_PROCESS, atoi (handle_env), TRUE);
1313 g_message ("%s: Found my process handle: %p (offset %d 0x%x)",
1314 __func__, current_process, atoi (handle_env),
1318 ok = _wapi_lookup_handle (current_process, WAPI_HANDLE_PROCESS,
1319 (gpointer *)&process_handlep);
1321 /* This test will probably break on linuxthreads, but
1322 * that should be ancient history on all distros we
1325 if (process_handlep->id == pid) {
1326 procname = process_handlep->proc_name;
1327 if (!strcmp (procname, "mono")) {
1328 /* Set a better process name */
1330 g_message ("%s: Setting better process name", __func__);
1333 process_set_name (process_handlep);
1336 g_message ("%s: Leaving process name: %s", __func__, procname);
1343 /* Wrong pid, so drop this handle and fall through to
1346 _wapi_handle_unref (current_process);
1350 /* We get here if the handle wasn't specified in the
1351 * environment, or if the process ID was wrong, or if the
1352 * handle lookup failed (eg if the parent process forked and
1353 * quit immediately, and deleted the shared data before the
1354 * child got a chance to attach it.)
1358 g_message ("%s: Need to create my own process handle", __func__);
1361 process_handle.id = pid;
1363 process_set_defaults (&process_handle);
1364 process_set_name (&process_handle);
1366 current_process = _wapi_handle_new (WAPI_HANDLE_PROCESS,
1368 if (current_process == _WAPI_HANDLE_INVALID) {
1369 g_warning ("%s: error creating process handle", __func__);
1374 gpointer _wapi_process_duplicate ()
1376 mono_once (&process_current_once, process_set_current);
1378 _wapi_handle_ref (current_process);
1380 return(current_process);
1383 /* Returns a pseudo handle that doesn't need to be closed afterwards */
1384 gpointer GetCurrentProcess (void)
1386 mono_once (&process_current_once, process_set_current);
1388 return(_WAPI_PROCESS_CURRENT);
1391 guint32 GetProcessId (gpointer handle)
1393 struct _WapiHandle_process *process_handle;
1396 if ((GPOINTER_TO_UINT (handle) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
1397 /* This is a pseudo handle */
1398 return(GPOINTER_TO_UINT (handle) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
1401 ok = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
1402 (gpointer *)&process_handle);
1404 SetLastError (ERROR_INVALID_HANDLE);
1408 return (process_handle->id);
1411 guint32 GetCurrentProcessId (void)
1413 mono_once (&process_current_once, process_set_current);
1415 return (GetProcessId (current_process));
1418 /* Returns the process id as a convenience to the functions that call this */
1419 static pid_t signal_process_if_gone (gpointer handle)
1421 struct _WapiHandle_process *process_handle;
1424 g_assert ((GPOINTER_TO_UINT (handle) & _WAPI_PROCESS_UNHANDLED) != _WAPI_PROCESS_UNHANDLED);
1426 /* Make sure the process is signalled if it has exited - if
1427 * the parent process didn't wait for it then it won't be
1429 ok = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
1430 (gpointer *)&process_handle);
1432 /* It's possible that the handle has vanished during
1433 * the _wapi_search_handle before it gets here, so
1434 * don't spam the console with warnings.
1436 /* g_warning ("%s: error looking up process handle %p",
1437 __func__, handle);*/
1443 g_message ("%s: looking at process %d", __func__, process_handle->id);
1446 if (kill (process_handle->id, 0) == -1 &&
1449 /* The process is dead, (EPERM tells us a new process
1450 * has that ID, but as it's owned by someone else it
1451 * can't be the one listed in our shared memory file)
1453 _wapi_shared_handle_set_signal_state (handle, TRUE);
1456 return (process_handle->id);
1460 static gboolean process_enum (gpointer handle, gpointer user_data)
1462 GArray *processes=user_data;
1463 pid_t pid = signal_process_if_gone (handle);
1470 /* Ignore processes that have already exited (ie they are signalled) */
1471 if (_wapi_handle_issignalled (handle) == FALSE) {
1473 g_message ("%s: process %d added to array", __func__, pid);
1476 /* This ensures that duplicates aren't returned (see
1477 * the comment above _wapi_search_handle () for why
1480 for (i = 0; i < processes->len; i++) {
1481 if (g_array_index (processes, pid_t, i) == pid) {
1482 /* We've already got this one, return
1483 * FALSE to keep searching
1489 g_array_append_val (processes, pid);
1492 /* Return false to keep searching */
1495 #endif /* UNUSED_CODE */
1497 #ifdef PLATFORM_MACOSX
1499 gboolean EnumProcesses (guint32 *pids, guint32 len, guint32 *needed)
1501 guint32 count, fit, i, j;
1504 struct kinfo_proc *result;
1506 static const int name[] = { CTL_KERN, KERN_PROC, KERN_PROC_ALL, 0 };
1508 mono_once (&process_current_once, process_set_current);
1515 err = sysctl ((int *)name, (sizeof(name) / sizeof(*name)) - 1, NULL, &proclength, NULL, 0);
1518 result = malloc (proclength);
1522 err = sysctl ((int *) name, (sizeof(name) / sizeof(*name)) - 1, result, &proclength, NULL, 0);
1529 } while (err == 0 && !done);
1532 if (result != NULL) {
1539 count = proclength / sizeof(struct kinfo_proc);
1540 fit = len / sizeof(guint32);
1541 for (i = 0, j = 0; j< fit && i < count; i++) {
1542 pids [j++] = result [i].kp_proc.p_pid;
1546 *needed = j * sizeof(guint32);
1551 gboolean EnumProcesses (guint32 *pids, guint32 len, guint32 *needed)
1553 GArray *processes = g_array_new (FALSE, FALSE, sizeof(pid_t));
1556 struct dirent *entry;
1558 mono_once (&process_current_once, process_set_current);
1560 dir = opendir ("/proc");
1564 while((entry = readdir (dir)) != NULL) {
1565 if (isdigit (entry->d_name[0])) {
1567 pid_t pid = (pid_t)strtol (entry->d_name, &endptr, 10);
1569 if (*endptr == '\0') {
1570 /* Name was entirely numeric, so was a
1573 g_array_append_val (processes, pid);
1579 fit=len/sizeof(guint32);
1580 for (i = 0, j = 0; j < fit && i < processes->len; i++) {
1581 pids[j++] = g_array_index (processes, pid_t, i);
1584 g_array_free (processes, TRUE);
1586 *needed = j * sizeof(guint32);
1592 static gboolean process_open_compare (gpointer handle, gpointer user_data)
1595 pid_t checking_pid = signal_process_if_gone (handle);
1597 if (checking_pid == 0) {
1601 wanted_pid = GPOINTER_TO_UINT (user_data);
1603 /* It's possible to have more than one process handle with the
1604 * same pid, but only the one running process can be
1607 if (checking_pid == wanted_pid &&
1608 _wapi_handle_issignalled (handle) == FALSE) {
1609 /* If the handle is blown away in the window between
1610 * returning TRUE here and _wapi_search_handle pinging
1611 * the timestamp, the search will continue
1619 gpointer OpenProcess (guint32 req_access G_GNUC_UNUSED, gboolean inherit G_GNUC_UNUSED, guint32 pid)
1621 /* Find the process handle that corresponds to pid */
1624 mono_once (&process_current_once, process_set_current);
1627 g_message ("%s: looking for process %d", __func__, pid);
1630 handle = _wapi_search_handle (WAPI_HANDLE_PROCESS,
1631 process_open_compare,
1632 GUINT_TO_POINTER (pid), NULL, TRUE);
1634 gchar *dir = g_strdup_printf ("/proc/%d", pid);
1635 if (!access (dir, F_OK)) {
1636 /* Return a pseudo handle for processes we
1637 * don't have handles for
1639 return GINT_TO_POINTER (_WAPI_PROCESS_UNHANDLED + pid);
1642 g_message ("%s: Can't find pid %d", __func__, pid);
1645 SetLastError (ERROR_PROC_NOT_FOUND);
1651 _wapi_handle_ref (handle);
1656 gboolean GetExitCodeProcess (gpointer process, guint32 *code)
1658 struct _WapiHandle_process *process_handle;
1661 mono_once (&process_current_once, process_set_current);
1667 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
1668 /* This is a pseudo handle, so we don't know what the
1674 ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
1675 (gpointer *)&process_handle);
1678 g_message ("%s: Can't find process %p", __func__, process);
1684 /* A process handle is only signalled if the process has exited
1685 * and has been waited for */
1687 /* Make sure any process exit has been noticed, before
1688 * checking if the process is signalled. Fixes bug 325463.
1690 process_wait (process, 0);
1692 if (_wapi_handle_issignalled (process) == TRUE) {
1693 *code = process_handle->exitstatus;
1695 *code = STILL_ACTIVE;
1701 gboolean GetProcessTimes (gpointer process, WapiFileTime *create_time,
1702 WapiFileTime *exit_time, WapiFileTime *kernel_time,
1703 WapiFileTime *user_time)
1705 struct _WapiHandle_process *process_handle;
1707 gboolean ku_times_set = FALSE;
1709 mono_once (&process_current_once, process_set_current);
1711 if(create_time==NULL || exit_time==NULL || kernel_time==NULL ||
1713 /* Not sure if w32 allows NULLs here or not */
1717 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
1718 /* This is a pseudo handle, so just fail for now
1723 ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
1724 (gpointer *)&process_handle);
1727 g_message ("%s: Can't find process %p", __func__, process);
1733 *create_time=process_handle->create_time;
1735 /* A process handle is only signalled if the process has
1736 * exited. Otherwise exit_time isn't set
1738 if(_wapi_handle_issignalled (process)==TRUE) {
1739 *exit_time=process_handle->exit_time;
1742 #ifdef HAVE_GETRUSAGE
1743 if (process_handle->id == getpid ()) {
1744 struct rusage time_data;
1745 if (getrusage (RUSAGE_SELF, &time_data) == 0) {
1747 gint64 *tick_val_ptr;
1748 ku_times_set = TRUE;
1749 tick_val = time_data.ru_utime.tv_sec * 10000000 + time_data.ru_utime.tv_usec * 10;
1750 tick_val_ptr = (gint64*)user_time;
1751 *tick_val_ptr = tick_val;
1752 tick_val = time_data.ru_stime.tv_sec * 10000000 + time_data.ru_stime.tv_usec * 10;
1753 tick_val_ptr = (gint64*)kernel_time;
1754 *tick_val_ptr = tick_val;
1758 if (!ku_times_set) {
1759 memset (kernel_time, 0, sizeof (WapiFileTime));
1760 memset (user_time, 0, sizeof (WapiFileTime));
1768 gpointer address_start;
1769 gpointer address_end;
1771 gpointer address_offset;
1777 static void free_procmodule (WapiProcModule *mod)
1779 if (mod->perms != NULL) {
1780 g_free (mod->perms);
1782 if (mod->filename != NULL) {
1783 g_free (mod->filename);
1788 static gint find_procmodule (gconstpointer a, gconstpointer b)
1790 WapiProcModule *want = (WapiProcModule *)a;
1791 WapiProcModule *compare = (WapiProcModule *)b;
1793 if ((want->device == compare->device) &&
1794 (want->inode == compare->inode)) {
1801 #ifdef PLATFORM_MACOSX
1802 #include <mach-o/dyld.h>
1803 #include <mach-o/getsect.h>
1805 static GSList *load_modules (void)
1808 WapiProcModule *mod;
1809 uint32_t count = _dyld_image_count ();
1812 for (i = 0; i < count; i++) {
1813 const struct mach_header *hdr;
1814 const struct section *sec;
1818 slide = _dyld_get_image_vmaddr_slide (i);
1819 name = _dyld_get_image_name (i);
1820 hdr = _dyld_get_image_header (i);
1821 sec = getsectbynamefromheader (hdr, SEG_DATA, SECT_DATA);
1823 /* Some dynlibs do not have data sections on osx (#533893) */
1828 mod = g_new0 (WapiProcModule, 1);
1829 mod->address_start = GINT_TO_POINTER (sec->addr);
1830 mod->address_end = GINT_TO_POINTER (sec->addr+sec->size);
1831 mod->perms = g_strdup ("r--p");
1832 mod->address_offset = 0;
1833 mod->device = makedev (0, 0);
1834 mod->inode = (ino_t) i;
1835 mod->filename = g_strdup (name);
1837 if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
1838 ret = g_slist_prepend (ret, mod);
1840 free_procmodule (mod);
1844 ret = g_slist_reverse (ret);
1849 static GSList *load_modules (FILE *fp)
1852 WapiProcModule *mod;
1853 gchar buf[MAXPATHLEN + 1], *p, *endp;
1854 gchar *start_start, *end_start, *prot_start, *offset_start;
1855 gchar *maj_dev_start, *min_dev_start, *inode_start, prot_buf[5];
1856 gpointer address_start, address_end, address_offset;
1857 guint32 maj_dev, min_dev;
1861 while (fgets (buf, sizeof(buf), fp)) {
1863 while (g_ascii_isspace (*p)) ++p;
1865 if (!g_ascii_isxdigit (*start_start)) {
1868 address_start = (gpointer)strtoul (start_start, &endp, 16);
1876 if (!g_ascii_isxdigit (*end_start)) {
1879 address_end = (gpointer)strtoul (end_start, &endp, 16);
1881 if (!g_ascii_isspace (*p)) {
1885 while (g_ascii_isspace (*p)) ++p;
1887 if (*prot_start != 'r' && *prot_start != '-') {
1890 memcpy (prot_buf, prot_start, 4);
1892 while (!g_ascii_isspace (*p)) ++p;
1894 while (g_ascii_isspace (*p)) ++p;
1896 if (!g_ascii_isxdigit (*offset_start)) {
1899 address_offset = (gpointer)strtoul (offset_start, &endp, 16);
1901 if (!g_ascii_isspace (*p)) {
1905 while(g_ascii_isspace (*p)) ++p;
1907 if (!g_ascii_isxdigit (*maj_dev_start)) {
1910 maj_dev = strtoul (maj_dev_start, &endp, 16);
1918 if (!g_ascii_isxdigit (*min_dev_start)) {
1921 min_dev = strtoul (min_dev_start, &endp, 16);
1923 if (!g_ascii_isspace (*p)) {
1927 while (g_ascii_isspace (*p)) ++p;
1929 if (!g_ascii_isxdigit (*inode_start)) {
1932 inode = (ino_t)strtol (inode_start, &endp, 10);
1934 if (!g_ascii_isspace (*p)) {
1938 device = makedev ((int)maj_dev, (int)min_dev);
1939 if ((device == 0) &&
1944 while(g_ascii_isspace (*p)) ++p;
1945 /* p now points to the filename */
1947 mod = g_new0 (WapiProcModule, 1);
1948 mod->address_start = address_start;
1949 mod->address_end = address_end;
1950 mod->perms = g_strdup (prot_buf);
1951 mod->address_offset = address_offset;
1952 mod->device = device;
1954 mod->filename = g_strdup (g_strstrip (p));
1956 if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
1957 ret = g_slist_prepend (ret, mod);
1959 free_procmodule (mod);
1963 ret = g_slist_reverse (ret);
1969 static gboolean match_procname_to_modulename (gchar *procname, gchar *modulename)
1971 char* lastsep = NULL;
1974 gboolean result = FALSE;
1976 if (procname == NULL || modulename == NULL)
1979 pname = mono_path_resolve_symlinks (procname);
1980 mname = mono_path_resolve_symlinks (modulename);
1982 if (!strcmp (pname, mname))
1986 lastsep = strrchr (mname, '/');
1988 if (!strcmp (lastsep+1, pname))
1998 FILE *open_process_map (int pid, const char *mode)
2001 const gchar *proc_path[] = {
2002 "/proc/%d/maps", /* GNU/Linux */
2003 "/proc/%d/map", /* FreeBSD */
2009 for (i = 0; fp == NULL && proc_path [i]; i++) {
2010 filename = g_strdup_printf (proc_path[i], pid);
2011 fp = fopen (filename, mode);
2018 gboolean EnumProcessModules (gpointer process, gpointer *modules,
2019 guint32 size, guint32 *needed)
2021 struct _WapiHandle_process *process_handle;
2024 GSList *mods = NULL;
2025 WapiProcModule *module;
2026 guint32 count, avail = size / sizeof(gpointer);
2029 gchar *proc_name = NULL;
2031 /* Store modules in an array of pointers (main module as
2032 * modules[0]), using the load address for each module as a
2033 * token. (Use 'NULL' as an alternative for the main module
2034 * so that the simple implementation can just return one item
2035 * for now.) Get the info from /proc/<pid>/maps on linux,
2036 * /proc/<pid>/map on FreeBSD, other systems will have to
2037 * implement /dev/kmem reading or whatever other horrid
2038 * technique is needed.
2040 if (size < sizeof(gpointer)) {
2044 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2045 /* This is a pseudo handle */
2046 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2048 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2049 (gpointer *)&process_handle);
2052 g_message ("%s: Can't find process %p", __func__, process);
2057 pid = process_handle->id;
2058 proc_name = process_handle->proc_name;
2061 #ifdef PLATFORM_MACOSX
2063 mods = load_modules ();
2065 if ((fp = open_process_map (pid, "r")) == NULL) {
2066 /* No /proc/<pid>/maps so just return the main module
2070 *needed = sizeof(gpointer);
2072 mods = load_modules (fp);
2075 count = g_slist_length (mods);
2077 /* count + 1 to leave slot 0 for the main module */
2078 *needed = sizeof(gpointer) * (count + 1);
2080 /* Use the NULL shortcut, as the first line in
2081 * /proc/<pid>/maps isn't the executable, and we need
2082 * that first in the returned list. Check the module name
2083 * to see if it ends with the proc name and substitute
2084 * the first entry with it. FIXME if this turns out to
2088 for (i = 0; i < (avail - 1) && i < count; i++) {
2089 module = (WapiProcModule *)g_slist_nth_data (mods, i);
2090 if (modules[0] != NULL)
2091 modules[i] = module->address_start;
2092 else if (match_procname_to_modulename (proc_name, module->filename))
2093 modules[0] = module->address_start;
2095 modules[i + 1] = module->address_start;
2098 for (i = 0; i < count; i++) {
2099 free_procmodule (g_slist_nth_data (mods, i));
2101 g_slist_free (mods);
2107 static gchar *get_process_name_from_proc (pid_t pid)
2109 gchar *filename = NULL;
2114 #if defined(PLATFORM_SOLARIS)
2115 filename = g_strdup_printf ("/proc/%d/psinfo", pid);
2116 if ((fp = fopen (filename, "r")) != NULL) {
2120 nread = fread (&info, sizeof (info), 1, fp);
2122 ret = g_strdup (info.pr_fname);
2128 #elif defined(PLATFORM_MACOSX)
2129 memset (buf, '\0', sizeof(buf));
2130 proc_name (pid, buf, sizeof(buf));
2131 if (strlen (buf) > 0)
2132 ret = g_strdup (buf);
2134 memset (buf, '\0', sizeof(buf));
2135 filename = g_strdup_printf ("/proc/%d/exe", pid);
2136 if (readlink (filename, buf, 255) > 0) {
2137 ret = g_strdup (buf);
2145 filename = g_strdup_printf ("/proc/%d/cmdline", pid);
2146 if ((fp = fopen (filename, "r")) != NULL) {
2147 if (fgets (buf, 256, fp) != NULL) {
2148 ret = g_strdup (buf);
2159 filename = g_strdup_printf ("/proc/%d/stat", pid);
2160 if ((fp = fopen (filename, "r")) != NULL) {
2161 if (fgets (buf, 256, fp) != NULL) {
2164 start = strchr (buf, '(');
2165 if (start != NULL) {
2166 end = strchr (start + 1, ')');
2169 ret = g_strndup (start + 1,
2187 static guint32 get_module_name (gpointer process, gpointer module,
2188 gunichar2 *basename, guint32 size,
2191 struct _WapiHandle_process *process_handle;
2194 gunichar2 *procname;
2195 gchar *procname_ext = NULL;
2199 GSList *mods = NULL;
2200 WapiProcModule *found_module;
2203 gchar *proc_name = NULL;
2205 mono_once (&process_current_once, process_set_current);
2208 g_message ("%s: Getting module base name, process handle %p module %p",
2209 __func__, process, module);
2212 size = size*sizeof(gunichar2); /* adjust for unicode characters */
2214 if (basename == NULL || size == 0) {
2218 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2219 /* This is a pseudo handle */
2220 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2221 proc_name = get_process_name_from_proc (pid);
2223 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2224 (gpointer *)&process_handle);
2227 g_message ("%s: Can't find process %p", __func__,
2233 pid = process_handle->id;
2234 proc_name = g_strdup (process_handle->proc_name);
2237 /* Look up the address in /proc/<pid>/maps */
2238 #ifdef PLATFORM_MACOSX
2240 mods = load_modules ();
2242 if ((fp = open_process_map (pid, "r")) == NULL) {
2243 if (errno == EACCES && module == NULL && base == TRUE) {
2244 procname_ext = get_process_name_from_proc (pid);
2246 /* No /proc/<pid>/maps, so just return failure
2253 mods = load_modules (fp);
2256 count = g_slist_length (mods);
2258 /* If module != NULL compare the address.
2259 * If module == NULL we are looking for the main module.
2260 * The best we can do for now check it the module name end with the process name.
2262 for (i = 0; i < count; i++) {
2263 found_module = (WapiProcModule *)g_slist_nth_data (mods, i);
2264 if (procname_ext == NULL &&
2265 ((module == NULL && match_procname_to_modulename (proc_name, found_module->filename)) ||
2266 (module != NULL && found_module->address_start == module))) {
2268 procname_ext = g_path_get_basename (found_module->filename);
2270 procname_ext = g_strdup (found_module->filename);
2274 free_procmodule (found_module);
2277 if (procname_ext == NULL)
2279 /* If it's *still* null, we might have hit the
2280 * case where reading /proc/$pid/maps gives an
2281 * empty file for this user.
2283 procname_ext = get_process_name_from_proc (pid);
2286 g_slist_free (mods);
2290 if (procname_ext != NULL) {
2292 g_message ("%s: Process name is [%s]", __func__,
2296 procname = mono_unicode_from_external (procname_ext, &bytes);
2297 if (procname == NULL) {
2299 g_free (procname_ext);
2305 /* Add the terminator */
2310 g_message ("%s: Size %d smaller than needed (%ld); truncating", __func__, size, bytes);
2313 memcpy (basename, procname, size);
2316 g_message ("%s: Size %d larger than needed (%ld)",
2317 __func__, size, bytes);
2320 memcpy (basename, procname, bytes);
2324 g_free (procname_ext);
2332 guint32 GetModuleBaseName (gpointer process, gpointer module,
2333 gunichar2 *basename, guint32 size)
2335 return(get_module_name (process, module, basename, size, TRUE));
2338 guint32 GetModuleFileNameEx (gpointer process, gpointer module,
2339 gunichar2 *filename, guint32 size)
2341 return(get_module_name (process, module, filename, size, FALSE));
2344 gboolean GetModuleInformation (gpointer process, gpointer module,
2345 WapiModuleInfo *modinfo, guint32 size)
2347 struct _WapiHandle_process *process_handle;
2351 GSList *mods = NULL;
2352 WapiProcModule *found_module;
2355 gboolean ret = FALSE;
2356 gchar *proc_name = NULL;
2358 mono_once (&process_current_once, process_set_current);
2361 g_message ("%s: Getting module info, process handle %p module %p",
2362 __func__, process, module);
2365 if (modinfo == NULL || size < sizeof(WapiModuleInfo)) {
2369 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2370 /* This is a pseudo handle */
2371 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2372 proc_name = get_process_name_from_proc (pid);
2374 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2375 (gpointer *)&process_handle);
2378 g_message ("%s: Can't find process %p", __func__,
2384 pid = process_handle->id;
2385 proc_name = g_strdup (process_handle->proc_name);
2388 #ifdef PLATFORM_MACOSX
2390 mods = load_modules ();
2392 /* Look up the address in /proc/<pid>/maps */
2393 if ((fp = open_process_map (pid, "r")) == NULL) {
2394 /* No /proc/<pid>/maps, so just return failure
2400 mods = load_modules (fp);
2403 count = g_slist_length (mods);
2405 /* If module != NULL compare the address.
2406 * If module == NULL we are looking for the main module.
2407 * The best we can do for now check it the module name end with the process name.
2409 for (i = 0; i < count; i++) {
2410 found_module = (WapiProcModule *)g_slist_nth_data (mods, i);
2411 if ( ret == FALSE &&
2412 ((module == NULL && match_procname_to_modulename (proc_name, found_module->filename)) ||
2413 (module != NULL && found_module->address_start == module))) {
2414 modinfo->lpBaseOfDll = found_module->address_start;
2415 modinfo->SizeOfImage = (gsize)(found_module->address_end) - (gsize)(found_module->address_start);
2416 modinfo->EntryPoint = found_module->address_offset;
2420 free_procmodule (found_module);
2423 g_slist_free (mods);
2430 gboolean GetProcessWorkingSetSize (gpointer process, size_t *min, size_t *max)
2432 struct _WapiHandle_process *process_handle;
2435 mono_once (&process_current_once, process_set_current);
2437 if(min==NULL || max==NULL) {
2438 /* Not sure if w32 allows NULLs here or not */
2442 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2443 /* This is a pseudo handle, so just fail for now
2448 ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2449 (gpointer *)&process_handle);
2452 g_message ("%s: Can't find process %p", __func__, process);
2458 *min=process_handle->min_working_set;
2459 *max=process_handle->max_working_set;
2464 gboolean SetProcessWorkingSetSize (gpointer process, size_t min, size_t max)
2466 struct _WapiHandle_process *process_handle;
2469 mono_once (&process_current_once, process_set_current);
2471 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2472 /* This is a pseudo handle, so just fail for now
2477 ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2478 (gpointer *)&process_handle);
2481 g_message ("%s: Can't find process %p", __func__, process);
2487 process_handle->min_working_set=min;
2488 process_handle->max_working_set=max;
2495 TerminateProcess (gpointer process, gint32 exitCode)
2497 struct _WapiHandle_process *process_handle;
2503 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2504 /* This is a pseudo handle */
2505 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2507 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2508 (gpointer *) &process_handle);
2512 g_message ("%s: Can't find process %p", __func__,
2515 SetLastError (ERROR_INVALID_HANDLE);
2518 pid = process_handle->id;
2521 signo = (exitCode == -1) ? SIGKILL : SIGTERM;
2522 ret = kill (pid, signo);
2526 SetLastError (ERROR_INVALID_PARAMETER);
2529 SetLastError (ERROR_ACCESS_DENIED);
2532 SetLastError (ERROR_PROC_NOT_FOUND);
2535 SetLastError (ERROR_GEN_FAILURE);
2543 GetPriorityClass (gpointer process)
2545 #ifdef HAVE_GETPRIORITY
2546 struct _WapiHandle_process *process_handle;
2551 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2552 /* This is a pseudo handle */
2553 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2555 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2556 (gpointer *) &process_handle);
2559 SetLastError (ERROR_INVALID_HANDLE);
2562 pid = process_handle->id;
2566 ret = getpriority (PRIO_PROCESS, pid);
2567 if (ret == -1 && errno != 0) {
2571 SetLastError (ERROR_ACCESS_DENIED);
2574 SetLastError (ERROR_PROC_NOT_FOUND);
2577 SetLastError (ERROR_GEN_FAILURE);
2583 return NORMAL_PRIORITY_CLASS;
2585 return REALTIME_PRIORITY_CLASS;
2587 return HIGH_PRIORITY_CLASS;
2589 return ABOVE_NORMAL_PRIORITY_CLASS;
2591 return IDLE_PRIORITY_CLASS;
2593 return BELOW_NORMAL_PRIORITY_CLASS;
2595 return NORMAL_PRIORITY_CLASS;
2597 SetLastError (ERROR_NOT_SUPPORTED);
2603 SetPriorityClass (gpointer process, guint32 priority_class)
2605 #ifdef HAVE_SETPRIORITY
2606 struct _WapiHandle_process *process_handle;
2612 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2613 /* This is a pseudo handle */
2614 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2616 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2617 (gpointer *) &process_handle);
2620 SetLastError (ERROR_INVALID_HANDLE);
2623 pid = process_handle->id;
2626 switch (priority_class) {
2627 case IDLE_PRIORITY_CLASS:
2630 case BELOW_NORMAL_PRIORITY_CLASS:
2633 case NORMAL_PRIORITY_CLASS:
2636 case ABOVE_NORMAL_PRIORITY_CLASS:
2639 case HIGH_PRIORITY_CLASS:
2642 case REALTIME_PRIORITY_CLASS:
2646 SetLastError (ERROR_INVALID_PARAMETER);
2650 ret = setpriority (PRIO_PROCESS, pid, prio);
2655 SetLastError (ERROR_ACCESS_DENIED);
2658 SetLastError (ERROR_PROC_NOT_FOUND);
2661 SetLastError (ERROR_GEN_FAILURE);
2667 SetLastError (ERROR_NOT_SUPPORTED);