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 #include <mono/io-layer/wapi.h>
39 #include <mono/io-layer/wapi-private.h>
40 #include <mono/io-layer/handles-private.h>
41 #include <mono/io-layer/misc-private.h>
42 #include <mono/io-layer/mono-mutex.h>
43 #include <mono/io-layer/process-private.h>
44 #include <mono/io-layer/threads.h>
45 #include <mono/utils/strenc.h>
46 #include <mono/io-layer/timefuncs-private.h>
48 /* The process' environment strings */
50 /* Apple defines this in crt_externs.h but doesn't provide that header for
51 * arm-apple-darwin9. We'll manually define the symbol on Apple as it does
52 * in fact exist on all implementations (so far)
54 gchar ***_NSGetEnviron();
55 #define environ (*_NSGetEnviron())
57 extern char **environ;
62 static guint32 process_wait (gpointer handle, guint32 timeout);
64 struct _WapiHandleOps _wapi_process_ops = {
65 NULL, /* close_shared */
69 process_wait, /* special_wait */
73 static mono_once_t process_current_once=MONO_ONCE_INIT;
74 static gpointer current_process=NULL;
76 static mono_once_t process_ops_once=MONO_ONCE_INIT;
78 static void process_ops_init (void)
80 _wapi_handle_register_capabilities (WAPI_HANDLE_PROCESS,
81 WAPI_HANDLE_CAP_WAIT |
82 WAPI_HANDLE_CAP_SPECIAL_WAIT);
85 static gboolean process_set_termination_details (gpointer handle, int status)
87 struct _WapiHandle_process *process_handle;
91 g_assert ((GPOINTER_TO_UINT (handle) & _WAPI_PROCESS_UNHANDLED) != _WAPI_PROCESS_UNHANDLED);
93 ok = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
94 (gpointer *)&process_handle);
96 g_warning ("%s: error looking up process handle %p",
101 thr_ret = _wapi_handle_lock_shared_handles ();
102 g_assert (thr_ret == 0);
104 if (WIFSIGNALED(status)) {
105 process_handle->exitstatus = 128 + WTERMSIG(status);
107 process_handle->exitstatus = WEXITSTATUS(status);
109 _wapi_time_t_to_filetime (time(NULL), &process_handle->exit_time);
111 /* Don't set process_handle->waited here, it needs to only
112 * happen in the parent when wait() has been called.
116 g_message ("%s: Setting handle %p pid %d signalled, exit status %d",
117 __func__, handle, process_handle->id,
118 process_handle->exitstatus);
121 _wapi_shared_handle_set_signal_state (handle, TRUE);
123 _wapi_handle_unlock_shared_handles ();
125 /* Drop the reference we hold so we have somewhere to store
126 * the exit details, now the process has in fact exited
128 _wapi_handle_unref (handle);
133 /* See if any child processes have terminated and wait() for them,
134 * updating process handle info. This function is called from the
135 * collection thread every few seconds.
137 static gboolean waitfor_pid (gpointer test, gpointer user_data)
139 struct _WapiHandle_process *process;
144 g_assert ((GPOINTER_TO_UINT (test) & _WAPI_PROCESS_UNHANDLED) != _WAPI_PROCESS_UNHANDLED);
146 ok = _wapi_lookup_handle (test, WAPI_HANDLE_PROCESS,
147 (gpointer *)&process);
149 /* The handle must have been too old and was reaped */
153 if (process->waited) {
154 /* We've already done this one */
159 ret = waitpid (process->id, &status, WNOHANG);
160 } while (errno == EINTR);
163 /* Process not ready for wait */
165 g_message ("%s: Process %d not ready for waiting for: %s",
166 __func__, process->id, g_strerror (errno));
173 g_message ("%s: Process %d finished", __func__, ret);
176 process->waited = TRUE;
178 *(int *)user_data = status;
183 void _wapi_process_reap (void)
189 g_message ("%s: Reaping child processes", __func__);
193 proc = _wapi_search_handle (WAPI_HANDLE_PROCESS, waitfor_pid,
194 &status, NULL, FALSE);
197 g_message ("%s: process handle %p exit code %d",
198 __func__, proc, status);
201 process_set_termination_details (proc, status);
203 /* _wapi_search_handle adds a reference, so
206 _wapi_handle_unref (proc);
208 } while (proc != NULL);
211 /* Limitations: This can only wait for processes that are our own
212 * children. Fixing this means resurrecting a daemon helper to manage
215 static guint32 process_wait (gpointer handle, guint32 timeout)
217 struct _WapiHandle_process *process_handle;
222 g_assert ((GPOINTER_TO_UINT (handle) & _WAPI_PROCESS_UNHANDLED) != _WAPI_PROCESS_UNHANDLED);
225 g_message ("%s: Waiting for process %p", __func__, handle);
228 ok = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
229 (gpointer *)&process_handle);
231 g_warning ("%s: error looking up process handle %p", __func__,
236 if (process_handle->waited) {
237 /* We've already done this one */
239 g_message ("%s: Process %p already signalled", __func__,
243 return (WAIT_OBJECT_0);
246 pid = process_handle->id;
249 g_message ("%s: PID is %d, timeout %d", __func__, pid, timeout);
252 if (timeout == INFINITE) {
253 if (pid == _wapi_getpid ()) {
258 while ((ret = waitpid (pid, &status, 0)) != pid) {
259 if (ret == (pid_t)-1 && errno != EINTR) {
264 } else if (timeout == 0) {
266 ret = waitpid (pid, &status, WNOHANG);
268 return (WAIT_TIMEOUT);
272 if (pid == _wapi_getpid ()) {
274 return(WAIT_TIMEOUT);
277 ret = waitpid (pid, &status, WNOHANG);
279 g_message ("%s: waitpid returns: %d, timeout is %d", __func__, ret, timeout);
284 } else if (ret == (pid_t)-1 &&
287 g_message ("%s: waitpid failure: %s",
292 if (errno == ECHILD &&
293 process_handle->waited) {
295 * process reaper must
299 g_message ("%s: Process %p already reaped", __func__, handle);
302 return(WAIT_OBJECT_0);
308 _wapi_handle_spin (100);
310 } while (timeout > 0);
314 return(WAIT_TIMEOUT);
318 /* Process must have exited */
320 g_message ("%s: Wait done, status %d", __func__, status);
323 ok = process_set_termination_details (handle, status);
325 SetLastError (ERROR_OUTOFMEMORY);
326 return (WAIT_FAILED);
328 process_handle->waited = TRUE;
330 return(WAIT_OBJECT_0);
333 void _wapi_process_signal_self ()
335 if (current_process != NULL) {
336 process_set_termination_details (current_process, 0);
340 static void process_set_defaults (struct _WapiHandle_process *process_handle)
342 /* These seem to be the defaults on w2k */
343 process_handle->min_working_set = 204800;
344 process_handle->max_working_set = 1413120;
346 process_handle->waited = FALSE;
348 _wapi_time_t_to_filetime (time (NULL), &process_handle->create_time);
352 len16 (const gunichar2 *str)
363 utf16_concat (const gunichar2 *first, ...)
370 va_start (args, first);
371 total += len16 (first);
372 for (s = va_arg (args, gunichar2 *); s != NULL; s = va_arg(args, gunichar2 *)){
377 ret = g_new (gunichar2, total + 1);
383 for (s = first; *s != 0; s++)
385 va_start (args, first);
386 for (s = va_arg (args, gunichar2 *); s != NULL; s = va_arg (args, gunichar2 *)){
389 for (p = s; *p != 0; p++)
397 #ifdef PLATFORM_MACOSX
398 #include <sys/utsname.h>
400 /* 0 = no detection; -1 = not 10.5 or higher; 1 = 10.5 or higher */
401 static int osx_10_5_or_higher;
404 detect_osx_10_5_or_higher ()
410 if (uname (&u) != 0){
411 osx_10_5_or_higher = 1;
419 osx_10_5_or_higher = -1;
421 osx_10_5_or_higher = 1;
425 is_macos_10_5_or_higher ()
427 if (osx_10_5_or_higher == 0)
428 detect_osx_10_5_or_higher ();
430 return (osx_10_5_or_higher == 1);
434 static const gunichar2 utf16_space_bytes [2] = { 0x20, 0 };
435 static const gunichar2 *utf16_space = utf16_space_bytes;
436 static const gunichar2 utf16_quote_bytes [2] = { 0x22, 0 };
437 static const gunichar2 *utf16_quote = utf16_quote_bytes;
439 /* Implemented as just a wrapper around CreateProcess () */
440 gboolean ShellExecuteEx (WapiShellExecuteInfo *sei)
443 WapiProcessInformation process_info;
447 /* w2k just segfaults here, but we can do better than
450 SetLastError (ERROR_INVALID_PARAMETER);
454 if (sei->lpFile == NULL) {
455 /* w2k returns TRUE for this, for some reason. */
459 /* Put both executable and parameters into the second argument
460 * to CreateProcess (), so it searches $PATH. The conversion
461 * into and back out of utf8 is because there is no
462 * g_strdup_printf () equivalent for gunichar2 :-(
464 args = utf16_concat (sei->lpFile, sei->lpParameters == NULL ? NULL : utf16_space, sei->lpParameters, NULL);
466 SetLastError (ERROR_INVALID_DATA);
469 ret = CreateProcess (NULL, args, NULL, NULL, TRUE,
470 CREATE_UNICODE_ENVIRONMENT, NULL,
471 sei->lpDirectory, NULL, &process_info);
475 static char *handler;
476 static gunichar2 *handler_utf16;
478 if (handler_utf16 == (gunichar2 *)-1)
481 #ifdef PLATFORM_MACOSX
482 if (is_macos_10_5_or_higher ())
483 handler = g_strdup ("/usr/bin/open -W");
485 handler = g_strdup ("/usr/bin/open");
488 * On Linux, try: xdg-open, the FreeDesktop standard way of doing it,
489 * if that fails, try to use gnome-open, then kfmclient
491 handler = g_find_program_in_path ("xdg-open");
492 if (handler == NULL){
493 handler = g_find_program_in_path ("gnome-open");
494 if (handler == NULL){
495 handler = g_find_program_in_path ("kfmclient");
496 if (handler == NULL){
497 handler_utf16 = (gunichar2 *) -1;
500 /* kfmclient needs exec argument */
502 handler = g_strconcat (old, " exec",
509 handler_utf16 = g_utf8_to_utf16 (handler, -1, NULL, NULL, NULL);
512 /* Put quotes around the filename, in case it's a url
513 * that contains #'s (CreateProcess() calls
514 * g_shell_parse_argv(), which deliberately throws
515 * away anything after an unquoted #). Fixes bug
518 args = utf16_concat (handler_utf16, utf16_space, utf16_quote,
519 sei->lpFile, utf16_quote,
520 sei->lpParameters == NULL ? NULL : utf16_space,
521 sei->lpParameters, NULL);
523 SetLastError (ERROR_INVALID_DATA);
526 ret = CreateProcess (NULL, args, NULL, NULL, TRUE,
527 CREATE_UNICODE_ENVIRONMENT, NULL,
528 sei->lpDirectory, NULL, &process_info);
531 SetLastError (ERROR_INVALID_DATA);
536 if (sei->fMask & SEE_MASK_NOCLOSEPROCESS) {
537 sei->hProcess = process_info.hProcess;
539 CloseHandle (process_info.hProcess);
546 is_managed_binary (const gchar *filename)
548 int original_errno = errno;
549 #if defined(HAVE_LARGE_FILE_SUPPORT) && defined(O_LARGEFILE)
550 int file = open (filename, O_RDONLY | O_LARGEFILE);
552 int file = open (filename, O_RDONLY);
555 unsigned char buffer[8];
556 off_t file_size, optional_header_offset;
557 off_t pe_header_offset;
558 gboolean managed = FALSE;
560 guint32 first_word, second_word;
562 /* If we are unable to open the file, then we definitely
563 * can't say that it is managed. The child mono process
564 * probably wouldn't be able to open it anyway.
567 errno = original_errno;
571 /* Retrieve the length of the file for future sanity checks. */
572 file_size = lseek (file, 0, SEEK_END);
573 lseek (file, 0, SEEK_SET);
575 /* We know we need to read a header field at offset 60. */
579 num_read = read (file, buffer, 2);
581 if ((num_read != 2) || (buffer[0] != 'M') || (buffer[1] != 'Z'))
584 new_offset = lseek (file, 60, SEEK_SET);
586 if (new_offset != 60)
589 num_read = read (file, buffer, 4);
593 pe_header_offset = buffer[0]
598 if (pe_header_offset + 24 > file_size)
601 new_offset = lseek (file, pe_header_offset, SEEK_SET);
603 if (new_offset != pe_header_offset)
606 num_read = read (file, buffer, 4);
608 if ((num_read != 4) || (buffer[0] != 'P') || (buffer[1] != 'E') || (buffer[2] != 0) || (buffer[3] != 0))
612 * Verify that the header we want in the optional header data
613 * is present in this binary.
615 new_offset = lseek (file, pe_header_offset + 20, SEEK_SET);
617 if (new_offset != pe_header_offset + 20)
620 num_read = read (file, buffer, 2);
622 if ((num_read != 2) || ((buffer[0] | (buffer[1] << 8)) < 216))
625 /* Read the CLR header address and size fields. These will be
626 * zero if the binary is not managed.
628 optional_header_offset = pe_header_offset + 24;
629 new_offset = lseek (file, optional_header_offset + 208, SEEK_SET);
631 if (new_offset != optional_header_offset + 208)
634 num_read = read (file, buffer, 8);
636 /* We are not concerned with endianness, only with
637 * whether it is zero or not.
639 first_word = *(guint32 *)&buffer[0];
640 second_word = *(guint32 *)&buffer[4];
642 if ((num_read != 8) || (first_word == 0) || (second_word == 0))
649 errno = original_errno;
653 gboolean CreateProcessWithLogonW (const gunichar2 *username,
654 const gunichar2 *domain,
655 const gunichar2 *password,
656 const guint32 logonFlags,
657 const gunichar2 *appname,
658 const gunichar2 *cmdline,
659 guint32 create_flags,
661 const gunichar2 *cwd,
662 WapiStartupInfo *startup,
663 WapiProcessInformation *process_info)
665 /* FIXME: use user information */
666 return CreateProcess (appname, cmdline, NULL, NULL, FALSE, create_flags, env, cwd, startup, process_info);
670 is_executable (const char *prog)
673 if (access (prog, X_OK) != 0)
675 if (stat (prog, &buf))
677 if (S_ISREG (buf.st_mode))
682 gboolean CreateProcess (const gunichar2 *appname, const gunichar2 *cmdline,
683 WapiSecurityAttributes *process_attrs G_GNUC_UNUSED,
684 WapiSecurityAttributes *thread_attrs G_GNUC_UNUSED,
685 gboolean inherit_handles, guint32 create_flags,
686 gpointer new_environ, const gunichar2 *cwd,
687 WapiStartupInfo *startup,
688 WapiProcessInformation *process_info)
690 gchar *cmd=NULL, *prog = NULL, *full_prog = NULL, *args = NULL, *args_after_prog = NULL, *dir = NULL, **env_strings = NULL, **argv = NULL;
691 guint32 i, env_count = 0;
692 gboolean ret = FALSE;
694 struct _WapiHandle_process process_handle = {0}, *process_handle_data;
696 int in_fd, out_fd, err_fd;
700 mono_once (&process_ops_once, process_ops_init);
702 /* appname and cmdline specify the executable and its args:
704 * If appname is not NULL, it is the name of the executable.
705 * Otherwise the executable is the first token in cmdline.
707 * Executable searching:
709 * If appname is not NULL, it can specify the full path and
710 * file name, or else a partial name and the current directory
711 * will be used. There is no additional searching.
713 * If appname is NULL, the first whitespace-delimited token in
714 * cmdline is used. If the name does not contain a full
715 * directory path, the search sequence is:
717 * 1) The directory containing the current process
718 * 2) The current working directory
719 * 3) The windows system directory (Ignored)
720 * 4) The windows directory (Ignored)
723 * Just to make things more interesting, tokens can contain
724 * white space if they are surrounded by quotation marks. I'm
725 * beginning to understand just why windows apps are generally
726 * so crap, with an API like this :-(
728 if (appname != NULL) {
729 cmd = mono_unicode_to_external (appname);
732 g_message ("%s: unicode conversion returned NULL",
736 SetLastError (ERROR_PATH_NOT_FOUND);
740 /* Turn all the slashes round the right way */
741 for (i = 0; i < strlen (cmd); i++) {
742 if (cmd[i] == '\\') {
748 if (cmdline != NULL) {
749 args = mono_unicode_to_external (cmdline);
752 g_message ("%s: unicode conversion returned NULL", __func__);
755 SetLastError (ERROR_PATH_NOT_FOUND);
761 dir = mono_unicode_to_external (cwd);
764 g_message ("%s: unicode conversion returned NULL", __func__);
767 SetLastError (ERROR_PATH_NOT_FOUND);
771 /* Turn all the slashes round the right way */
772 for (i = 0; i < strlen (dir); i++) {
773 if (dir[i] == '\\') {
780 /* We can't put off locating the executable any longer :-( */
783 if (g_ascii_isalpha (cmd[0]) && (cmd[1] == ':')) {
784 /* Strip off the drive letter. I can't
785 * believe that CP/M holdover is still
788 g_memmove (cmd, cmd+2, strlen (cmd)-2);
789 cmd[strlen (cmd)-2] = '\0';
792 unquoted = g_shell_unquote (cmd, NULL);
793 if (unquoted[0] == '/') {
794 /* Assume full path given */
795 prog = g_strdup (unquoted);
797 /* Executable existing ? */
798 if (!is_executable (prog)) {
800 g_message ("%s: Couldn't find executable %s",
804 SetLastError (ERROR_FILE_NOT_FOUND);
808 /* Search for file named by cmd in the current
811 char *curdir = g_get_current_dir ();
813 prog = g_strdup_printf ("%s/%s", curdir, unquoted);
816 /* And make sure it's executable */
817 if (!is_executable (prog)) {
819 g_message ("%s: Couldn't find executable %s",
823 SetLastError (ERROR_FILE_NOT_FOUND);
829 args_after_prog = args;
834 /* Dig out the first token from args, taking quotation
838 /* First, strip off all leading whitespace */
839 args = g_strchug (args);
841 /* args_after_prog points to the contents of args
842 * after token has been set (otherwise argv[0] is
845 args_after_prog = args;
847 /* Assume the opening quote will always be the first
850 if (args[0] == '\"' || args [0] == '\'') {
852 for (i = 1; args[i] != '\0' && args[i] != quote; i++);
853 if (g_ascii_isspace (args[i+1])) {
854 /* We found the first token */
855 token = g_strndup (args+1, i-1);
856 args_after_prog = args + i;
858 /* Quotation mark appeared in the
859 * middle of the token. Just give the
860 * whole first token, quotes and all,
867 /* No quote mark, or malformed */
868 for (i = 0; args[i] != '\0'; i++) {
869 if (g_ascii_isspace (args[i])) {
870 token = g_strndup (args, i);
871 args_after_prog = args + i + 1;
877 if (token == NULL && args[0] != '\0') {
878 /* Must be just one token in the string */
879 token = g_strdup (args);
880 args_after_prog = NULL;
886 g_message ("%s: Couldn't find what to exec", __func__);
889 SetLastError (ERROR_PATH_NOT_FOUND);
893 /* Turn all the slashes round the right way. Only for
896 for (i = 0; i < strlen (token); i++) {
897 if (token[i] == '\\') {
902 if (g_ascii_isalpha (token[0]) && (token[1] == ':')) {
903 /* Strip off the drive letter. I can't
904 * believe that CP/M holdover is still
907 g_memmove (token, token+2, strlen (token)-2);
908 token[strlen (token)-2] = '\0';
911 if (token[0] == '/') {
912 /* Assume full path given */
913 prog = g_strdup (token);
915 /* Executable existing ? */
916 if (!is_executable (prog)) {
918 g_message ("%s: Couldn't find executable %s",
922 SetLastError (ERROR_FILE_NOT_FOUND);
927 char *curdir = g_get_current_dir ();
929 /* FIXME: Need to record the directory
930 * containing the current process, and check
931 * that for the new executable as the first
935 prog = g_strdup_printf ("%s/%s", curdir, token);
938 /* I assume X_OK is the criterion to use,
941 if (!is_executable (prog)) {
943 prog = g_find_program_in_path (token);
946 g_message ("%s: Couldn't find executable %s", __func__, token);
950 SetLastError (ERROR_FILE_NOT_FOUND);
960 g_message ("%s: Exec prog [%s] args [%s]", __func__, prog,
964 /* Check for CLR binaries; if found, we will try to invoke
965 * them using the same mono binary that started us.
967 if (is_managed_binary (prog)) {
968 gunichar2 *newapp, *newcmd;
971 newapp = mono_unicode_from_external ("mono", &bytes_ignored);
973 if (newapp != NULL) {
974 if (appname != NULL) {
975 newcmd = utf16_concat (newapp, utf16_space,
976 appname, utf16_space,
979 newcmd = utf16_concat (newapp, utf16_space,
983 g_free ((gunichar2 *)newapp);
985 if (newcmd != NULL) {
986 ret = CreateProcess (NULL, newcmd,
990 create_flags, new_environ,
994 g_free ((gunichar2 *)newcmd);
1001 if (args_after_prog != NULL && *args_after_prog) {
1004 qprog = g_shell_quote (prog);
1005 full_prog = g_strconcat (qprog, " ", args_after_prog, NULL);
1008 full_prog = g_shell_quote (prog);
1011 ret = g_shell_parse_argv (full_prog, NULL, &argv, &gerr);
1013 /* FIXME: Could do something with the GError here
1017 if (startup != NULL && startup->dwFlags & STARTF_USESTDHANDLES) {
1018 in_fd = GPOINTER_TO_UINT (startup->hStdInput);
1019 out_fd = GPOINTER_TO_UINT (startup->hStdOutput);
1020 err_fd = GPOINTER_TO_UINT (startup->hStdError);
1022 in_fd = GPOINTER_TO_UINT (GetStdHandle (STD_INPUT_HANDLE));
1023 out_fd = GPOINTER_TO_UINT (GetStdHandle (STD_OUTPUT_HANDLE));
1024 err_fd = GPOINTER_TO_UINT (GetStdHandle (STD_ERROR_HANDLE));
1027 g_strlcpy (process_handle.proc_name, prog,
1028 _WAPI_PROC_NAME_MAX_LEN - 1);
1030 process_set_defaults (&process_handle);
1032 handle = _wapi_handle_new (WAPI_HANDLE_PROCESS, &process_handle);
1033 if (handle == _WAPI_HANDLE_INVALID) {
1034 g_warning ("%s: error creating process handle", __func__);
1036 SetLastError (ERROR_PATH_NOT_FOUND);
1040 /* Hold another reference so the process has somewhere to
1041 * store its exit data even if we drop this handle
1043 _wapi_handle_ref (handle);
1045 /* new_environ is a block of NULL-terminated strings, which
1046 * is itself NULL-terminated. Of course, passing an array of
1047 * string pointers would have made things too easy :-(
1049 * If new_environ is not NULL it specifies the entire set of
1050 * environment variables in the new process. Otherwise the
1051 * new process inherits the same environment.
1053 if (new_environ != NULL) {
1054 gunichar2 *new_environp;
1056 /* Count the number of strings */
1057 for (new_environp = (gunichar2 *)new_environ; *new_environp;
1060 while (*new_environp) {
1065 /* +2: one for the process handle value, and the last
1068 env_strings = g_new0 (gchar *, env_count + 2);
1070 /* Copy each environ string into 'strings' turning it
1071 * into utf8 (or the requested encoding) at the same
1075 for (new_environp = (gunichar2 *)new_environ; *new_environp;
1077 env_strings[env_count] = mono_unicode_to_external (new_environp);
1079 while (*new_environp) {
1084 for (i = 0; environ[i] != NULL; i++) {
1088 /* +2: one for the process handle value, and the last
1091 env_strings = g_new0 (gchar *, env_count + 2);
1093 /* Copy each environ string into 'strings' turning it
1094 * into utf8 (or the requested encoding) at the same
1098 for (i = 0; environ[i] != NULL; i++) {
1099 env_strings[env_count] = g_strdup (environ[i]);
1103 /* pass process handle info to the child, so it doesn't have
1104 * to do an expensive search over the whole list
1106 if (env_strings != NULL) {
1107 struct _WapiHandleUnshared *handle_data;
1108 struct _WapiHandle_shared_ref *ref;
1110 handle_data = &_WAPI_PRIVATE_HANDLES(GPOINTER_TO_UINT(handle));
1111 ref = &handle_data->u.shared;
1113 env_strings[env_count] = g_strdup_printf ("_WAPI_PROCESS_HANDLE_OFFSET=%d", ref->offset);
1116 thr_ret = _wapi_handle_lock_shared_handles ();
1117 g_assert (thr_ret == 0);
1122 SetLastError (ERROR_OUTOFMEMORY);
1123 _wapi_handle_unref (handle);
1125 } else if (pid == 0) {
1128 if (_wapi_shm_disabled == FALSE) {
1129 /* Wait for the parent to finish setting up
1130 * the handle. The semaphore lock is safe
1131 * because the sem_undo structures of a
1132 * semaphore aren't inherited across a fork
1133 * (), but we can't do this if we're not using
1136 thr_ret = _wapi_handle_lock_shared_handles ();
1137 g_assert (thr_ret == 0);
1139 _wapi_handle_unlock_shared_handles ();
1142 /* should we detach from the process group? */
1144 /* Connect stdin, stdout and stderr */
1149 if (inherit_handles != TRUE) {
1150 /* FIXME: do something here */
1153 /* Close all file descriptors */
1154 for (i = getdtablesize () - 1; i > 2; i--) {
1159 g_message ("%s: exec()ing [%s] in dir [%s]", __func__, cmd,
1161 for (i = 0; argv[i] != NULL; i++) {
1162 g_message ("arg %d: [%s]", i, argv[i]);
1165 for (i = 0; env_strings[i] != NULL; i++) {
1166 g_message ("env %d: [%s]", i, env_strings[i]);
1171 if (dir != NULL && chdir (dir) == -1) {
1177 execve (argv[0], argv, env_strings);
1184 ret = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
1185 (gpointer *)&process_handle_data);
1187 g_warning ("%s: error looking up process handle %p", __func__,
1189 _wapi_handle_unref (handle);
1193 process_handle_data->id = pid;
1195 if (process_info != NULL) {
1196 process_info->hProcess = handle;
1197 process_info->dwProcessId = pid;
1199 /* FIXME: we might need to handle the thread info some
1202 process_info->hThread = INVALID_HANDLE_VALUE;
1203 process_info->dwThreadId = 0;
1207 _wapi_handle_unlock_shared_handles ();
1213 if (full_prog != NULL) {
1225 if(env_strings != NULL) {
1226 g_strfreev (env_strings);
1233 g_message ("%s: returning handle %p for pid %d", __func__, handle,
1240 static void process_set_name (struct _WapiHandle_process *process_handle)
1242 gchar *progname, *utf8_progname, *slash;
1244 progname=g_get_prgname ();
1245 utf8_progname=mono_utf8_from_external (progname);
1248 g_message ("%s: using [%s] as prog name", __func__, progname);
1251 if(utf8_progname!=NULL) {
1252 slash=strrchr (utf8_progname, '/');
1254 g_strlcpy (process_handle->proc_name, slash+1,
1255 _WAPI_PROC_NAME_MAX_LEN - 1);
1257 g_strlcpy (process_handle->proc_name, utf8_progname,
1258 _WAPI_PROC_NAME_MAX_LEN - 1);
1261 g_free (utf8_progname);
1265 extern void _wapi_time_t_to_filetime (time_t timeval, WapiFileTime *filetime);
1267 #if !GLIB_CHECK_VERSION (2,4,0)
1268 #define g_setenv(a,b,c) setenv(a,b,c)
1269 #define g_unsetenv(a) unsetenv(a)
1272 static void process_set_current (void)
1274 pid_t pid = _wapi_getpid ();
1275 const char *handle_env;
1276 struct _WapiHandle_process process_handle = {0};
1278 mono_once (&process_ops_once, process_ops_init);
1280 handle_env = g_getenv ("_WAPI_PROCESS_HANDLE_OFFSET");
1281 g_unsetenv ("_WAPI_PROCESS_HANDLE_OFFSET");
1283 if (handle_env != NULL) {
1284 struct _WapiHandle_process *process_handlep;
1285 gchar *procname = NULL;
1288 current_process = _wapi_handle_new_from_offset (WAPI_HANDLE_PROCESS, atoi (handle_env), TRUE);
1291 g_message ("%s: Found my process handle: %p (offset %d 0x%x)",
1292 __func__, current_process, atoi (handle_env),
1296 ok = _wapi_lookup_handle (current_process, WAPI_HANDLE_PROCESS,
1297 (gpointer *)&process_handlep);
1299 /* This test will probably break on linuxthreads, but
1300 * that should be ancient history on all distros we
1303 if (process_handlep->id == pid) {
1304 procname = process_handlep->proc_name;
1305 if (!strcmp (procname, "mono")) {
1306 /* Set a better process name */
1308 g_message ("%s: Setting better process name", __func__);
1311 process_set_name (process_handlep);
1314 g_message ("%s: Leaving process name: %s", __func__, procname);
1321 /* Wrong pid, so drop this handle and fall through to
1324 _wapi_handle_unref (current_process);
1328 /* We get here if the handle wasn't specified in the
1329 * environment, or if the process ID was wrong, or if the
1330 * handle lookup failed (eg if the parent process forked and
1331 * quit immediately, and deleted the shared data before the
1332 * child got a chance to attach it.)
1336 g_message ("%s: Need to create my own process handle", __func__);
1339 process_handle.id = pid;
1341 process_set_defaults (&process_handle);
1342 process_set_name (&process_handle);
1344 current_process = _wapi_handle_new (WAPI_HANDLE_PROCESS,
1346 if (current_process == _WAPI_HANDLE_INVALID) {
1347 g_warning ("%s: error creating process handle", __func__);
1352 gpointer _wapi_process_duplicate ()
1354 mono_once (&process_current_once, process_set_current);
1356 _wapi_handle_ref (current_process);
1358 return(current_process);
1361 /* Returns a pseudo handle that doesn't need to be closed afterwards */
1362 gpointer GetCurrentProcess (void)
1364 mono_once (&process_current_once, process_set_current);
1366 return(_WAPI_PROCESS_CURRENT);
1369 guint32 GetProcessId (gpointer handle)
1371 struct _WapiHandle_process *process_handle;
1374 if ((GPOINTER_TO_UINT (handle) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
1375 /* This is a pseudo handle */
1376 return(GPOINTER_TO_UINT (handle) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
1379 ok = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
1380 (gpointer *)&process_handle);
1382 SetLastError (ERROR_INVALID_HANDLE);
1386 return (process_handle->id);
1389 guint32 GetCurrentProcessId (void)
1391 mono_once (&process_current_once, process_set_current);
1393 return (GetProcessId (current_process));
1396 /* Returns the process id as a convenience to the functions that call this */
1397 static pid_t signal_process_if_gone (gpointer handle)
1399 struct _WapiHandle_process *process_handle;
1402 g_assert ((GPOINTER_TO_UINT (handle) & _WAPI_PROCESS_UNHANDLED) != _WAPI_PROCESS_UNHANDLED);
1404 /* Make sure the process is signalled if it has exited - if
1405 * the parent process didn't wait for it then it won't be
1407 ok = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
1408 (gpointer *)&process_handle);
1410 /* It's possible that the handle has vanished during
1411 * the _wapi_search_handle before it gets here, so
1412 * don't spam the console with warnings.
1414 /* g_warning ("%s: error looking up process handle %p",
1415 __func__, handle);*/
1421 g_message ("%s: looking at process %d", __func__, process_handle->id);
1424 if (kill (process_handle->id, 0) == -1 &&
1427 /* The process is dead, (EPERM tells us a new process
1428 * has that ID, but as it's owned by someone else it
1429 * can't be the one listed in our shared memory file)
1431 _wapi_shared_handle_set_signal_state (handle, TRUE);
1434 return (process_handle->id);
1438 static gboolean process_enum (gpointer handle, gpointer user_data)
1440 GArray *processes=user_data;
1441 pid_t pid = signal_process_if_gone (handle);
1448 /* Ignore processes that have already exited (ie they are signalled) */
1449 if (_wapi_handle_issignalled (handle) == FALSE) {
1451 g_message ("%s: process %d added to array", __func__, pid);
1454 /* This ensures that duplicates aren't returned (see
1455 * the comment above _wapi_search_handle () for why
1458 for (i = 0; i < processes->len; i++) {
1459 if (g_array_index (processes, pid_t, i) == pid) {
1460 /* We've already got this one, return
1461 * FALSE to keep searching
1467 g_array_append_val (processes, pid);
1470 /* Return false to keep searching */
1473 #endif /* UNUSED_CODE */
1475 gboolean EnumProcesses (guint32 *pids, guint32 len, guint32 *needed)
1477 GArray *processes = g_array_new (FALSE, FALSE, sizeof(pid_t));
1480 struct dirent *entry;
1482 mono_once (&process_current_once, process_set_current);
1484 dir = opendir ("/proc");
1488 while((entry = readdir (dir)) != NULL) {
1489 if (isdigit (entry->d_name[0])) {
1491 pid_t pid = (pid_t)strtol (entry->d_name, &endptr, 10);
1493 if (*endptr == '\0') {
1494 /* Name was entirely numeric, so was a
1497 g_array_append_val (processes, pid);
1503 fit=len/sizeof(guint32);
1504 for (i = 0, j = 0; j < fit && i < processes->len; i++) {
1505 pids[j++] = g_array_index (processes, pid_t, i);
1508 g_array_free (processes, TRUE);
1510 *needed = j * sizeof(guint32);
1515 static gboolean process_open_compare (gpointer handle, gpointer user_data)
1518 pid_t checking_pid = signal_process_if_gone (handle);
1520 if (checking_pid == 0) {
1524 wanted_pid = GPOINTER_TO_UINT (user_data);
1526 /* It's possible to have more than one process handle with the
1527 * same pid, but only the one running process can be
1530 if (checking_pid == wanted_pid &&
1531 _wapi_handle_issignalled (handle) == FALSE) {
1532 /* If the handle is blown away in the window between
1533 * returning TRUE here and _wapi_search_handle pinging
1534 * the timestamp, the search will continue
1542 gpointer OpenProcess (guint32 req_access G_GNUC_UNUSED, gboolean inherit G_GNUC_UNUSED, guint32 pid)
1544 /* Find the process handle that corresponds to pid */
1547 mono_once (&process_current_once, process_set_current);
1550 g_message ("%s: looking for process %d", __func__, pid);
1553 handle = _wapi_search_handle (WAPI_HANDLE_PROCESS,
1554 process_open_compare,
1555 GUINT_TO_POINTER (pid), NULL, TRUE);
1557 gchar *dir = g_strdup_printf ("/proc/%d", pid);
1558 if (!access (dir, F_OK)) {
1559 /* Return a pseudo handle for processes we
1560 * don't have handles for
1562 return((gpointer)(_WAPI_PROCESS_UNHANDLED + pid));
1565 g_message ("%s: Can't find pid %d", __func__, pid);
1568 SetLastError (ERROR_PROC_NOT_FOUND);
1574 _wapi_handle_ref (handle);
1579 gboolean GetExitCodeProcess (gpointer process, guint32 *code)
1581 struct _WapiHandle_process *process_handle;
1584 mono_once (&process_current_once, process_set_current);
1590 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
1591 /* This is a pseudo handle, so we don't know what the
1597 ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
1598 (gpointer *)&process_handle);
1601 g_message ("%s: Can't find process %p", __func__, process);
1607 /* A process handle is only signalled if the process has exited
1608 * and has been waited for */
1610 /* Make sure any process exit has been noticed, before
1611 * checking if the process is signalled. Fixes bug 325463.
1613 process_wait (process, 0);
1615 if (_wapi_handle_issignalled (process) == TRUE) {
1616 *code = process_handle->exitstatus;
1618 *code = STILL_ACTIVE;
1624 gboolean GetProcessTimes (gpointer process, WapiFileTime *create_time,
1625 WapiFileTime *exit_time, WapiFileTime *kernel_time,
1626 WapiFileTime *user_time)
1628 struct _WapiHandle_process *process_handle;
1630 gboolean ku_times_set = FALSE;
1632 mono_once (&process_current_once, process_set_current);
1634 if(create_time==NULL || exit_time==NULL || kernel_time==NULL ||
1636 /* Not sure if w32 allows NULLs here or not */
1640 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
1641 /* This is a pseudo handle, so just fail for now
1646 ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
1647 (gpointer *)&process_handle);
1650 g_message ("%s: Can't find process %p", __func__, process);
1656 *create_time=process_handle->create_time;
1658 /* A process handle is only signalled if the process has
1659 * exited. Otherwise exit_time isn't set
1661 if(_wapi_handle_issignalled (process)==TRUE) {
1662 *exit_time=process_handle->exit_time;
1665 #ifdef HAVE_GETRUSAGE
1666 if (process_handle->id == getpid ()) {
1667 struct rusage time_data;
1668 if (getrusage (RUSAGE_SELF, &time_data) == 0) {
1670 gint64 *tick_val_ptr;
1671 ku_times_set = TRUE;
1672 tick_val = time_data.ru_utime.tv_sec * 10000000 + time_data.ru_utime.tv_usec * 10;
1673 tick_val_ptr = (gint64*)user_time;
1674 *tick_val_ptr = tick_val;
1675 tick_val = time_data.ru_stime.tv_sec * 10000000 + time_data.ru_stime.tv_usec * 10;
1676 tick_val_ptr = (gint64*)kernel_time;
1677 *tick_val_ptr = tick_val;
1681 if (!ku_times_set) {
1682 memset (kernel_time, 0, sizeof (WapiFileTime));
1683 memset (user_time, 0, sizeof (WapiFileTime));
1691 gpointer address_start;
1692 gpointer address_end;
1694 gpointer address_offset;
1700 static void free_procmodule (WapiProcModule *mod)
1702 if (mod->perms != NULL) {
1703 g_free (mod->perms);
1705 if (mod->filename != NULL) {
1706 g_free (mod->filename);
1711 static gint find_procmodule (gconstpointer a, gconstpointer b)
1713 WapiProcModule *want = (WapiProcModule *)a;
1714 WapiProcModule *compare = (WapiProcModule *)b;
1716 if ((want->device == compare->device) &&
1717 (want->inode == compare->inode)) {
1724 #ifdef PLATFORM_MACOSX
1725 #include <mach-o/dyld.h>
1727 static GSList *load_modules ()
1730 WapiProcModule *mod;
1731 uint32_t count = _dyld_image_count ();
1734 for (i = 0; i < count; i++) {
1735 const struct mach_header *hdr;
1736 const struct section *sec;
1740 slide = _dyld_get_image_vmaddr_slide (i);
1741 name = _dyld_get_image_name (i);
1742 hdr = _dyld_get_image_header (i);
1743 sec = getsectbynamefromheader (hdr, SEG_DATA, SECT_DATA);
1745 mod = g_new0 (WapiProcModule, 1);
1746 mod->address_start = sec->addr;
1747 mod->address_end = sec->addr+sec->size;
1748 mod->perms = g_strdup ("r--p");
1749 mod->address_offset = 0;
1750 mod->device = makedev (0, 0);
1751 mod->inode = (ino_t) i;
1752 mod->filename = g_strdup (name);
1754 if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
1755 ret = g_slist_prepend (ret, mod);
1757 free_procmodule (mod);
1761 ret = g_slist_reverse (ret);
1766 static GSList *load_modules (FILE *fp)
1769 WapiProcModule *mod;
1770 gchar buf[MAXPATHLEN + 1], *p, *endp;
1771 gchar *start_start, *end_start, *prot_start, *offset_start;
1772 gchar *maj_dev_start, *min_dev_start, *inode_start, prot_buf[5];
1773 gpointer address_start, address_end, address_offset;
1774 guint32 maj_dev, min_dev;
1778 while (fgets (buf, sizeof(buf), fp)) {
1780 while (g_ascii_isspace (*p)) ++p;
1782 if (!g_ascii_isxdigit (*start_start)) {
1785 address_start = (gpointer)strtoul (start_start, &endp, 16);
1793 if (!g_ascii_isxdigit (*end_start)) {
1796 address_end = (gpointer)strtoul (end_start, &endp, 16);
1798 if (!g_ascii_isspace (*p)) {
1802 while (g_ascii_isspace (*p)) ++p;
1804 if (*prot_start != 'r' && *prot_start != '-') {
1807 memcpy (prot_buf, prot_start, 4);
1809 while (!g_ascii_isspace (*p)) ++p;
1811 while (g_ascii_isspace (*p)) ++p;
1813 if (!g_ascii_isxdigit (*offset_start)) {
1816 address_offset = (gpointer)strtoul (offset_start, &endp, 16);
1818 if (!g_ascii_isspace (*p)) {
1822 while(g_ascii_isspace (*p)) ++p;
1824 if (!g_ascii_isxdigit (*maj_dev_start)) {
1827 maj_dev = strtoul (maj_dev_start, &endp, 16);
1835 if (!g_ascii_isxdigit (*min_dev_start)) {
1838 min_dev = strtoul (min_dev_start, &endp, 16);
1840 if (!g_ascii_isspace (*p)) {
1844 while (g_ascii_isspace (*p)) ++p;
1846 if (!g_ascii_isxdigit (*inode_start)) {
1849 inode = (ino_t)strtol (inode_start, &endp, 10);
1851 if (!g_ascii_isspace (*p)) {
1855 device = makedev ((int)maj_dev, (int)min_dev);
1856 if ((device == 0) &&
1861 while(g_ascii_isspace (*p)) ++p;
1862 /* p now points to the filename */
1864 mod = g_new0 (WapiProcModule, 1);
1865 mod->address_start = address_start;
1866 mod->address_end = address_end;
1867 mod->perms = g_strdup (prot_buf);
1868 mod->address_offset = address_offset;
1869 mod->device = device;
1871 mod->filename = g_strdup (g_strstrip (p));
1873 if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
1874 ret = g_slist_prepend (ret, mod);
1876 free_procmodule (mod);
1880 ret = g_slist_reverse (ret);
1886 static gboolean match_procname_to_modulename (gchar *procname, gchar *modulename)
1888 char* lastsep = NULL;
1890 if (procname == NULL || modulename == NULL)
1893 if (!strcmp (procname, modulename))
1896 lastsep = strrchr (modulename, '/');
1898 if (!strcmp (lastsep+1, procname))
1906 gboolean EnumProcessModules (gpointer process, gpointer *modules,
1907 guint32 size, guint32 *needed)
1909 struct _WapiHandle_process *process_handle;
1911 gchar *filename = NULL;
1913 GSList *mods = NULL;
1914 WapiProcModule *module;
1915 guint32 count, avail = size / sizeof(gpointer);
1918 gchar *proc_name = NULL;
1920 /* Store modules in an array of pointers (main module as
1921 * modules[0]), using the load address for each module as a
1922 * token. (Use 'NULL' as an alternative for the main module
1923 * so that the simple implementation can just return one item
1924 * for now.) Get the info from /proc/<pid>/maps on linux,
1925 * other systems will have to implement /dev/kmem reading or
1926 * whatever other horrid technique is needed.
1928 if (size < sizeof(gpointer)) {
1932 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
1933 /* This is a pseudo handle */
1934 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
1936 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
1937 (gpointer *)&process_handle);
1940 g_message ("%s: Can't find process %p", __func__, process);
1945 pid = process_handle->id;
1946 proc_name = process_handle->proc_name;
1949 #ifdef PLATFORM_MACOSX
1951 mods = load_modules ();
1953 filename = g_strdup_printf ("/proc/%d/maps", pid);
1954 if ((fp = fopen (filename, "r")) == NULL) {
1955 /* No /proc/<pid>/maps so just return the main module
1959 *needed = sizeof(gpointer);
1961 mods = load_modules (fp);
1964 count = g_slist_length (mods);
1966 /* count + 1 to leave slot 0 for the main module */
1967 *needed = sizeof(gpointer) * (count + 1);
1969 /* Use the NULL shortcut, as the first line in
1970 * /proc/<pid>/maps isn't the executable, and we need
1971 * that first in the returned list. Check the module name
1972 * to see if it ends with the proc name and substitute
1973 * the first entry with it. FIXME if this turns out to
1977 for (i = 0; i < (avail - 1) && i < count; i++) {
1978 module = (WapiProcModule *)g_slist_nth_data (mods, i);
1979 if (modules[0] != NULL)
1980 modules[i] = module->address_start;
1981 else if (match_procname_to_modulename (proc_name, module->filename))
1982 modules[0] = module->address_start;
1984 modules[i + 1] = module->address_start;
1987 for (i = 0; i < count; i++) {
1988 free_procmodule (g_slist_nth_data (mods, i));
1990 g_slist_free (mods);
1998 static gchar *get_process_name_from_proc (pid_t pid)
2000 gchar *filename = NULL;
2005 memset (buf, '\0', sizeof(buf));
2007 filename = g_strdup_printf ("/proc/%d/exe", pid);
2008 if (readlink (filename, buf, 255) > 0) {
2009 ret = g_strdup (buf);
2017 filename = g_strdup_printf ("/proc/%d/cmdline", pid);
2018 if ((fp = fopen (filename, "r")) != NULL) {
2019 if (fgets (buf, 256, fp) != NULL) {
2020 ret = g_strdup (buf);
2031 filename = g_strdup_printf ("/proc/%d/stat", pid);
2032 if ((fp = fopen (filename, "r")) != NULL) {
2033 if (fgets (buf, 256, fp) != NULL) {
2036 start = strchr (buf, '(');
2037 if (start != NULL) {
2038 end = strchr (start + 1, ')');
2041 ret = g_strndup (start + 1,
2058 static guint32 get_module_name (gpointer process, gpointer module,
2059 gunichar2 *basename, guint32 size,
2062 struct _WapiHandle_process *process_handle;
2065 gunichar2 *procname;
2066 gchar *procname_ext = NULL;
2069 gchar *filename = NULL;
2071 GSList *mods = NULL;
2072 WapiProcModule *found_module;
2075 gchar *proc_name = NULL;
2077 mono_once (&process_current_once, process_set_current);
2080 g_message ("%s: Getting module base name, process handle %p module %p",
2081 __func__, process, module);
2084 size = size*sizeof(gunichar2); /* adjust for unicode characters */
2086 if (basename == NULL || size == 0) {
2090 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2091 /* This is a pseudo handle */
2092 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2093 proc_name = get_process_name_from_proc (pid);
2095 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2096 (gpointer *)&process_handle);
2099 g_message ("%s: Can't find process %p", __func__,
2105 pid = process_handle->id;
2106 proc_name = g_strdup (process_handle->proc_name);
2109 /* Look up the address in /proc/<pid>/maps */
2110 #ifdef PLATFORM_MACOSX
2112 mods = load_modules ();
2114 filename = g_strdup_printf ("/proc/%d/maps", pid);
2115 if ((fp = fopen (filename, "r")) == NULL) {
2116 if (errno == EACCES && module == NULL && base == TRUE) {
2117 procname_ext = get_process_name_from_proc (pid);
2119 /* No /proc/<pid>/maps, so just return failure
2127 mods = load_modules (fp);
2130 count = g_slist_length (mods);
2132 /* If module != NULL compare the address.
2133 * If module == NULL we are looking for the main module.
2134 * The best we can do for now check it the module name end with the process name.
2136 for (i = 0; i < count; i++) {
2137 found_module = (WapiProcModule *)g_slist_nth_data (mods, i);
2138 if (procname_ext == NULL &&
2139 ((module == NULL && match_procname_to_modulename (proc_name, found_module->filename)) ||
2140 (module != NULL && found_module->address_start == module))) {
2142 procname_ext = g_path_get_basename (found_module->filename);
2144 procname_ext = g_strdup (found_module->filename);
2148 free_procmodule (found_module);
2151 if (procname_ext == NULL)
2153 /* If it's *still* null, we might have hit the
2154 * case where reading /proc/$pid/maps gives an
2155 * empty file for this user.
2157 procname_ext = get_process_name_from_proc (pid);
2160 g_slist_free (mods);
2165 if (procname_ext != NULL) {
2167 g_message ("%s: Process name is [%s]", __func__,
2171 procname = mono_unicode_from_external (procname_ext, &bytes);
2172 if (procname == NULL) {
2174 g_free (procname_ext);
2180 /* Add the terminator */
2185 g_message ("%s: Size %d smaller than needed (%ld); truncating", __func__, size, bytes);
2188 memcpy (basename, procname, size);
2191 g_message ("%s: Size %d larger than needed (%ld)",
2192 __func__, size, bytes);
2195 memcpy (basename, procname, bytes);
2199 g_free (procname_ext);
2207 guint32 GetModuleBaseName (gpointer process, gpointer module,
2208 gunichar2 *basename, guint32 size)
2210 return(get_module_name (process, module, basename, size, TRUE));
2213 guint32 GetModuleFileNameEx (gpointer process, gpointer module,
2214 gunichar2 *filename, guint32 size)
2216 return(get_module_name (process, module, filename, size, FALSE));
2219 gboolean GetModuleInformation (gpointer process, gpointer module,
2220 WapiModuleInfo *modinfo, guint32 size)
2222 struct _WapiHandle_process *process_handle;
2225 gchar *filename = NULL;
2227 GSList *mods = NULL;
2228 WapiProcModule *found_module;
2231 gboolean ret = FALSE;
2232 gchar *proc_name = NULL;
2234 mono_once (&process_current_once, process_set_current);
2237 g_message ("%s: Getting module info, process handle %p module %p",
2238 __func__, process, module);
2241 if (modinfo == NULL || size < sizeof(WapiModuleInfo)) {
2245 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2246 /* This is a pseudo handle */
2247 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2248 proc_name = get_process_name_from_proc (pid);
2250 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2251 (gpointer *)&process_handle);
2254 g_message ("%s: Can't find process %p", __func__,
2260 pid = process_handle->id;
2261 proc_name = g_strdup (process_handle->proc_name);
2264 #ifdef PLATFORM_MACOSX
2266 mods = load_modules ();
2268 /* Look up the address in /proc/<pid>/maps */
2269 filename = g_strdup_printf ("/proc/%d/maps", pid);
2270 if ((fp = fopen (filename, "r")) == NULL) {
2271 /* No /proc/<pid>/maps, so just return failure
2278 mods = load_modules (fp);
2281 count = g_slist_length (mods);
2283 /* If module != NULL compare the address.
2284 * If module == NULL we are looking for the main module.
2285 * The best we can do for now check it the module name end with the process name.
2287 for (i = 0; i < count; i++) {
2288 found_module = (WapiProcModule *)g_slist_nth_data (mods, i);
2289 if ( ret == FALSE &&
2290 ((module == NULL && match_procname_to_modulename (proc_name, found_module->filename)) ||
2291 (module != NULL && found_module->address_start == module))) {
2292 modinfo->lpBaseOfDll = found_module->address_start;
2293 modinfo->SizeOfImage = (gsize)(found_module->address_end) - (gsize)(found_module->address_start);
2294 modinfo->EntryPoint = found_module->address_offset;
2298 free_procmodule (found_module);
2301 g_slist_free (mods);
2309 gboolean GetProcessWorkingSetSize (gpointer process, size_t *min, size_t *max)
2311 struct _WapiHandle_process *process_handle;
2314 mono_once (&process_current_once, process_set_current);
2316 if(min==NULL || max==NULL) {
2317 /* Not sure if w32 allows NULLs here or not */
2321 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2322 /* This is a pseudo handle, so just fail for now
2327 ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2328 (gpointer *)&process_handle);
2331 g_message ("%s: Can't find process %p", __func__, process);
2337 *min=process_handle->min_working_set;
2338 *max=process_handle->max_working_set;
2343 gboolean SetProcessWorkingSetSize (gpointer process, size_t min, size_t max)
2345 struct _WapiHandle_process *process_handle;
2348 mono_once (&process_current_once, process_set_current);
2350 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2351 /* This is a pseudo handle, so just fail for now
2356 ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2357 (gpointer *)&process_handle);
2360 g_message ("%s: Can't find process %p", __func__, process);
2366 process_handle->min_working_set=min;
2367 process_handle->max_working_set=max;
2374 TerminateProcess (gpointer process, gint32 exitCode)
2376 struct _WapiHandle_process *process_handle;
2382 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2383 /* This is a pseudo handle */
2384 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2386 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2387 (gpointer *) &process_handle);
2391 g_message ("%s: Can't find process %p", __func__,
2394 SetLastError (ERROR_INVALID_HANDLE);
2397 pid = process_handle->id;
2400 signo = (exitCode == -1) ? SIGKILL : SIGTERM;
2401 ret = kill (pid, signo);
2405 SetLastError (ERROR_INVALID_PARAMETER);
2408 SetLastError (ERROR_ACCESS_DENIED);
2411 SetLastError (ERROR_PROC_NOT_FOUND);
2414 SetLastError (ERROR_GEN_FAILURE);
2422 GetPriorityClass (gpointer process)
2424 #ifdef HAVE_GETPRIORITY
2425 struct _WapiHandle_process *process_handle;
2430 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2431 /* This is a pseudo handle */
2432 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2434 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2435 (gpointer *) &process_handle);
2438 SetLastError (ERROR_INVALID_HANDLE);
2441 pid = process_handle->id;
2445 ret = getpriority (PRIO_PROCESS, pid);
2446 if (ret == -1 && errno != 0) {
2450 SetLastError (ERROR_ACCESS_DENIED);
2453 SetLastError (ERROR_PROC_NOT_FOUND);
2456 SetLastError (ERROR_GEN_FAILURE);
2462 return NORMAL_PRIORITY_CLASS;
2464 return REALTIME_PRIORITY_CLASS;
2466 return HIGH_PRIORITY_CLASS;
2468 return ABOVE_NORMAL_PRIORITY_CLASS;
2470 return IDLE_PRIORITY_CLASS;
2472 return BELOW_NORMAL_PRIORITY_CLASS;
2474 return NORMAL_PRIORITY_CLASS;
2476 SetLastError (ERROR_NOT_SUPPORTED);
2482 SetPriorityClass (gpointer process, guint32 priority_class)
2484 #ifdef HAVE_SETPRIORITY
2485 struct _WapiHandle_process *process_handle;
2491 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2492 /* This is a pseudo handle */
2493 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2495 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2496 (gpointer *) &process_handle);
2499 SetLastError (ERROR_INVALID_HANDLE);
2502 pid = process_handle->id;
2505 switch (priority_class) {
2506 case IDLE_PRIORITY_CLASS:
2509 case BELOW_NORMAL_PRIORITY_CLASS:
2512 case NORMAL_PRIORITY_CLASS:
2515 case ABOVE_NORMAL_PRIORITY_CLASS:
2518 case HIGH_PRIORITY_CLASS:
2521 case REALTIME_PRIORITY_CLASS:
2525 SetLastError (ERROR_INVALID_PARAMETER);
2529 ret = setpriority (PRIO_PROCESS, pid, prio);
2534 SetLastError (ERROR_ACCESS_DENIED);
2537 SetLastError (ERROR_PROC_NOT_FOUND);
2540 SetLastError (ERROR_GEN_FAILURE);
2546 SetLastError (ERROR_NOT_SUPPORTED);