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 static const gunichar2 utf16_space_bytes [2] = { 0x20, 0 };
398 static const gunichar2 *utf16_space = utf16_space_bytes;
399 static const gunichar2 utf16_quote_bytes [2] = { 0x22, 0 };
400 static const gunichar2 *utf16_quote = utf16_quote_bytes;
402 /* Implemented as just a wrapper around CreateProcess () */
403 gboolean ShellExecuteEx (WapiShellExecuteInfo *sei)
406 WapiProcessInformation process_info;
410 /* w2k just segfaults here, but we can do better than
413 SetLastError (ERROR_INVALID_PARAMETER);
417 if (sei->lpFile == NULL) {
418 /* w2k returns TRUE for this, for some reason. */
422 /* Put both executable and parameters into the second argument
423 * to CreateProcess (), so it searches $PATH. The conversion
424 * into and back out of utf8 is because there is no
425 * g_strdup_printf () equivalent for gunichar2 :-(
427 args = utf16_concat (sei->lpFile, sei->lpParameters == NULL ? NULL : utf16_space, sei->lpParameters, NULL);
429 SetLastError (ERROR_INVALID_DATA);
432 ret = CreateProcess (NULL, args, NULL, NULL, TRUE,
433 CREATE_UNICODE_ENVIRONMENT, NULL,
434 sei->lpDirectory, NULL, &process_info);
438 static char *handler;
439 static gunichar2 *handler_utf16;
441 if (handler_utf16 == (gunichar2 *)-1)
444 #ifdef PLATFORM_MACOSX
445 handler = g_strdup ("/usr/bin/open -W");
448 * On Linux, try: xdg-open, the FreeDesktop standard way of doing it,
449 * if that fails, try to use gnome-open, then kfmclient
451 handler = g_find_program_in_path ("xdg-open");
452 if (handler == NULL){
453 handler = g_find_program_in_path ("gnome-open");
454 if (handler == NULL){
455 handler = g_find_program_in_path ("kfmclient");
456 if (handler == NULL){
457 handler_utf16 = (gunichar2 *) -1;
460 /* kfmclient needs exec argument */
462 handler = g_strconcat (old, " exec",
469 handler_utf16 = g_utf8_to_utf16 (handler, -1, NULL, NULL, NULL);
472 /* Put quotes around the filename, in case it's a url
473 * that contains #'s (CreateProcess() calls
474 * g_shell_parse_argv(), which deliberately throws
475 * away anything after an unquoted #). Fixes bug
478 args = utf16_concat (handler_utf16, utf16_space, utf16_quote,
479 sei->lpFile, utf16_quote,
480 sei->lpParameters == NULL ? NULL : utf16_space,
481 sei->lpParameters, NULL);
483 SetLastError (ERROR_INVALID_DATA);
486 ret = CreateProcess (NULL, args, NULL, NULL, TRUE,
487 CREATE_UNICODE_ENVIRONMENT, NULL,
488 sei->lpDirectory, NULL, &process_info);
491 SetLastError (ERROR_INVALID_DATA);
496 if (sei->fMask & SEE_MASK_NOCLOSEPROCESS) {
497 sei->hProcess = process_info.hProcess;
499 CloseHandle (process_info.hProcess);
506 is_managed_binary (const gchar *filename)
508 int original_errno = errno;
509 #if defined(HAVE_LARGE_FILE_SUPPORT) && defined(O_LARGEFILE)
510 int file = open (filename, O_RDONLY | O_LARGEFILE);
512 int file = open (filename, O_RDONLY);
515 unsigned char buffer[8];
516 off_t file_size, optional_header_offset;
517 off_t pe_header_offset;
518 gboolean managed = FALSE;
520 guint32 first_word, second_word;
522 /* If we are unable to open the file, then we definitely
523 * can't say that it is managed. The child mono process
524 * probably wouldn't be able to open it anyway.
527 errno = original_errno;
531 /* Retrieve the length of the file for future sanity checks. */
532 file_size = lseek (file, 0, SEEK_END);
533 lseek (file, 0, SEEK_SET);
535 /* We know we need to read a header field at offset 60. */
539 num_read = read (file, buffer, 2);
541 if ((num_read != 2) || (buffer[0] != 'M') || (buffer[1] != 'Z'))
544 new_offset = lseek (file, 60, SEEK_SET);
546 if (new_offset != 60)
549 num_read = read (file, buffer, 4);
553 pe_header_offset = buffer[0]
558 if (pe_header_offset + 24 > file_size)
561 new_offset = lseek (file, pe_header_offset, SEEK_SET);
563 if (new_offset != pe_header_offset)
566 num_read = read (file, buffer, 4);
568 if ((num_read != 4) || (buffer[0] != 'P') || (buffer[1] != 'E') || (buffer[2] != 0) || (buffer[3] != 0))
572 * Verify that the header we want in the optional header data
573 * is present in this binary.
575 new_offset = lseek (file, pe_header_offset + 20, SEEK_SET);
577 if (new_offset != pe_header_offset + 20)
580 num_read = read (file, buffer, 2);
582 if ((num_read != 2) || ((buffer[0] | (buffer[1] << 8)) < 216))
585 /* Read the CLR header address and size fields. These will be
586 * zero if the binary is not managed.
588 optional_header_offset = pe_header_offset + 24;
589 new_offset = lseek (file, optional_header_offset + 208, SEEK_SET);
591 if (new_offset != optional_header_offset + 208)
594 num_read = read (file, buffer, 8);
596 /* We are not concerned with endianness, only with
597 * whether it is zero or not.
599 first_word = *(guint32 *)&buffer[0];
600 second_word = *(guint32 *)&buffer[4];
602 if ((num_read != 8) || (first_word == 0) || (second_word == 0))
609 errno = original_errno;
613 gboolean CreateProcessWithLogonW (const gunichar2 *username,
614 const gunichar2 *domain,
615 const gunichar2 *password,
616 const guint32 logonFlags,
617 const gunichar2 *appname,
618 const gunichar2 *cmdline,
619 guint32 create_flags,
621 const gunichar2 *cwd,
622 WapiStartupInfo *startup,
623 WapiProcessInformation *process_info)
625 /* FIXME: use user information */
626 return CreateProcess (appname, cmdline, NULL, NULL, FALSE, create_flags, env, cwd, startup, process_info);
630 is_executable (const char *prog)
633 if (access (prog, X_OK) != 0)
635 if (stat (prog, &buf))
637 if (S_ISREG (buf.st_mode))
642 gboolean CreateProcess (const gunichar2 *appname, const gunichar2 *cmdline,
643 WapiSecurityAttributes *process_attrs G_GNUC_UNUSED,
644 WapiSecurityAttributes *thread_attrs G_GNUC_UNUSED,
645 gboolean inherit_handles, guint32 create_flags,
646 gpointer new_environ, const gunichar2 *cwd,
647 WapiStartupInfo *startup,
648 WapiProcessInformation *process_info)
650 gchar *cmd=NULL, *prog = NULL, *full_prog = NULL, *args = NULL, *args_after_prog = NULL, *dir = NULL, **env_strings = NULL, **argv = NULL;
651 guint32 i, env_count = 0;
652 gboolean ret = FALSE;
654 struct _WapiHandle_process process_handle = {0}, *process_handle_data;
656 int in_fd, out_fd, err_fd;
660 mono_once (&process_ops_once, process_ops_init);
662 /* appname and cmdline specify the executable and its args:
664 * If appname is not NULL, it is the name of the executable.
665 * Otherwise the executable is the first token in cmdline.
667 * Executable searching:
669 * If appname is not NULL, it can specify the full path and
670 * file name, or else a partial name and the current directory
671 * will be used. There is no additional searching.
673 * If appname is NULL, the first whitespace-delimited token in
674 * cmdline is used. If the name does not contain a full
675 * directory path, the search sequence is:
677 * 1) The directory containing the current process
678 * 2) The current working directory
679 * 3) The windows system directory (Ignored)
680 * 4) The windows directory (Ignored)
683 * Just to make things more interesting, tokens can contain
684 * white space if they are surrounded by quotation marks. I'm
685 * beginning to understand just why windows apps are generally
686 * so crap, with an API like this :-(
688 if (appname != NULL) {
689 cmd = mono_unicode_to_external (appname);
692 g_message ("%s: unicode conversion returned NULL",
696 SetLastError (ERROR_PATH_NOT_FOUND);
700 /* Turn all the slashes round the right way */
701 for (i = 0; i < strlen (cmd); i++) {
702 if (cmd[i] == '\\') {
708 if (cmdline != NULL) {
709 args = mono_unicode_to_external (cmdline);
712 g_message ("%s: unicode conversion returned NULL", __func__);
715 SetLastError (ERROR_PATH_NOT_FOUND);
721 dir = mono_unicode_to_external (cwd);
724 g_message ("%s: unicode conversion returned NULL", __func__);
727 SetLastError (ERROR_PATH_NOT_FOUND);
731 /* Turn all the slashes round the right way */
732 for (i = 0; i < strlen (dir); i++) {
733 if (dir[i] == '\\') {
740 /* We can't put off locating the executable any longer :-( */
743 if (g_ascii_isalpha (cmd[0]) && (cmd[1] == ':')) {
744 /* Strip off the drive letter. I can't
745 * believe that CP/M holdover is still
748 g_memmove (cmd, cmd+2, strlen (cmd)-2);
749 cmd[strlen (cmd)-2] = '\0';
752 unquoted = g_shell_unquote (cmd, NULL);
753 if (unquoted[0] == '/') {
754 /* Assume full path given */
755 prog = g_strdup (unquoted);
757 /* Executable existing ? */
758 if (!is_executable (prog)) {
760 g_message ("%s: Couldn't find executable %s",
764 SetLastError (ERROR_FILE_NOT_FOUND);
768 /* Search for file named by cmd in the current
771 char *curdir = g_get_current_dir ();
773 prog = g_strdup_printf ("%s/%s", curdir, unquoted);
776 /* And make sure it's executable */
777 if (!is_executable (prog)) {
779 g_message ("%s: Couldn't find executable %s",
783 SetLastError (ERROR_FILE_NOT_FOUND);
789 args_after_prog = args;
794 /* Dig out the first token from args, taking quotation
798 /* First, strip off all leading whitespace */
799 args = g_strchug (args);
801 /* args_after_prog points to the contents of args
802 * after token has been set (otherwise argv[0] is
805 args_after_prog = args;
807 /* Assume the opening quote will always be the first
810 if (args[0] == '\"' || args [0] == '\'') {
812 for (i = 1; args[i] != '\0' && args[i] != quote; i++);
813 if (g_ascii_isspace (args[i+1])) {
814 /* We found the first token */
815 token = g_strndup (args+1, i-1);
816 args_after_prog = args + i;
818 /* Quotation mark appeared in the
819 * middle of the token. Just give the
820 * whole first token, quotes and all,
827 /* No quote mark, or malformed */
828 for (i = 0; args[i] != '\0'; i++) {
829 if (g_ascii_isspace (args[i])) {
830 token = g_strndup (args, i);
831 args_after_prog = args + i + 1;
837 if (token == NULL && args[0] != '\0') {
838 /* Must be just one token in the string */
839 token = g_strdup (args);
840 args_after_prog = NULL;
846 g_message ("%s: Couldn't find what to exec", __func__);
849 SetLastError (ERROR_PATH_NOT_FOUND);
853 /* Turn all the slashes round the right way. Only for
856 for (i = 0; i < strlen (token); i++) {
857 if (token[i] == '\\') {
862 if (g_ascii_isalpha (token[0]) && (token[1] == ':')) {
863 /* Strip off the drive letter. I can't
864 * believe that CP/M holdover is still
867 g_memmove (token, token+2, strlen (token)-2);
868 token[strlen (token)-2] = '\0';
871 if (token[0] == '/') {
872 /* Assume full path given */
873 prog = g_strdup (token);
875 /* Executable existing ? */
876 if (!is_executable (prog)) {
878 g_message ("%s: Couldn't find executable %s",
882 SetLastError (ERROR_FILE_NOT_FOUND);
887 char *curdir = g_get_current_dir ();
889 /* FIXME: Need to record the directory
890 * containing the current process, and check
891 * that for the new executable as the first
895 prog = g_strdup_printf ("%s/%s", curdir, token);
898 /* I assume X_OK is the criterion to use,
901 if (!is_executable (prog)) {
903 prog = g_find_program_in_path (token);
906 g_message ("%s: Couldn't find executable %s", __func__, token);
910 SetLastError (ERROR_FILE_NOT_FOUND);
920 g_message ("%s: Exec prog [%s] args [%s]", __func__, prog,
924 /* Check for CLR binaries; if found, we will try to invoke
925 * them using the same mono binary that started us.
927 if (is_managed_binary (prog)) {
928 gunichar2 *newapp, *newcmd;
931 newapp = mono_unicode_from_external ("mono", &bytes_ignored);
933 if (newapp != NULL) {
934 if (appname != NULL) {
935 newcmd = utf16_concat (newapp, utf16_space,
936 appname, utf16_space,
939 newcmd = utf16_concat (newapp, utf16_space,
943 g_free ((gunichar2 *)newapp);
945 if (newcmd != NULL) {
946 ret = CreateProcess (NULL, newcmd,
950 create_flags, new_environ,
954 g_free ((gunichar2 *)newcmd);
961 if (args_after_prog != NULL && *args_after_prog) {
964 qprog = g_shell_quote (prog);
965 full_prog = g_strconcat (qprog, " ", args_after_prog, NULL);
968 full_prog = g_shell_quote (prog);
971 ret = g_shell_parse_argv (full_prog, NULL, &argv, &gerr);
973 /* FIXME: Could do something with the GError here
977 if (startup != NULL && startup->dwFlags & STARTF_USESTDHANDLES) {
978 in_fd = GPOINTER_TO_UINT (startup->hStdInput);
979 out_fd = GPOINTER_TO_UINT (startup->hStdOutput);
980 err_fd = GPOINTER_TO_UINT (startup->hStdError);
982 in_fd = GPOINTER_TO_UINT (GetStdHandle (STD_INPUT_HANDLE));
983 out_fd = GPOINTER_TO_UINT (GetStdHandle (STD_OUTPUT_HANDLE));
984 err_fd = GPOINTER_TO_UINT (GetStdHandle (STD_ERROR_HANDLE));
987 g_strlcpy (process_handle.proc_name, prog,
988 _WAPI_PROC_NAME_MAX_LEN - 1);
990 process_set_defaults (&process_handle);
992 handle = _wapi_handle_new (WAPI_HANDLE_PROCESS, &process_handle);
993 if (handle == _WAPI_HANDLE_INVALID) {
994 g_warning ("%s: error creating process handle", __func__);
996 SetLastError (ERROR_PATH_NOT_FOUND);
1000 /* Hold another reference so the process has somewhere to
1001 * store its exit data even if we drop this handle
1003 _wapi_handle_ref (handle);
1005 /* new_environ is a block of NULL-terminated strings, which
1006 * is itself NULL-terminated. Of course, passing an array of
1007 * string pointers would have made things too easy :-(
1009 * If new_environ is not NULL it specifies the entire set of
1010 * environment variables in the new process. Otherwise the
1011 * new process inherits the same environment.
1013 if (new_environ != NULL) {
1014 gunichar2 *new_environp;
1016 /* Count the number of strings */
1017 for (new_environp = (gunichar2 *)new_environ; *new_environp;
1020 while (*new_environp) {
1025 /* +2: one for the process handle value, and the last
1028 env_strings = g_new0 (gchar *, env_count + 2);
1030 /* Copy each environ string into 'strings' turning it
1031 * into utf8 (or the requested encoding) at the same
1035 for (new_environp = (gunichar2 *)new_environ; *new_environp;
1037 env_strings[env_count] = mono_unicode_to_external (new_environp);
1039 while (*new_environp) {
1044 for (i = 0; environ[i] != NULL; i++) {
1048 /* +2: one for the process handle value, and the last
1051 env_strings = g_new0 (gchar *, env_count + 2);
1053 /* Copy each environ string into 'strings' turning it
1054 * into utf8 (or the requested encoding) at the same
1058 for (i = 0; environ[i] != NULL; i++) {
1059 env_strings[env_count] = g_strdup (environ[i]);
1063 /* pass process handle info to the child, so it doesn't have
1064 * to do an expensive search over the whole list
1066 if (env_strings != NULL) {
1067 struct _WapiHandleUnshared *handle_data;
1068 struct _WapiHandle_shared_ref *ref;
1070 handle_data = &_WAPI_PRIVATE_HANDLES(GPOINTER_TO_UINT(handle));
1071 ref = &handle_data->u.shared;
1073 env_strings[env_count] = g_strdup_printf ("_WAPI_PROCESS_HANDLE_OFFSET=%d", ref->offset);
1076 thr_ret = _wapi_handle_lock_shared_handles ();
1077 g_assert (thr_ret == 0);
1082 SetLastError (ERROR_OUTOFMEMORY);
1083 _wapi_handle_unref (handle);
1085 } else if (pid == 0) {
1088 if (_wapi_shm_disabled == FALSE) {
1089 /* Wait for the parent to finish setting up
1090 * the handle. The semaphore lock is safe
1091 * because the sem_undo structures of a
1092 * semaphore aren't inherited across a fork
1093 * (), but we can't do this if we're not using
1096 thr_ret = _wapi_handle_lock_shared_handles ();
1097 g_assert (thr_ret == 0);
1099 _wapi_handle_unlock_shared_handles ();
1102 /* should we detach from the process group? */
1104 /* Connect stdin, stdout and stderr */
1109 if (inherit_handles != TRUE) {
1110 /* FIXME: do something here */
1113 /* Close all file descriptors */
1114 for (i = getdtablesize () - 1; i > 2; i--) {
1119 g_message ("%s: exec()ing [%s] in dir [%s]", __func__, cmd,
1121 for (i = 0; argv[i] != NULL; i++) {
1122 g_message ("arg %d: [%s]", i, argv[i]);
1125 for (i = 0; env_strings[i] != NULL; i++) {
1126 g_message ("env %d: [%s]", i, env_strings[i]);
1131 if (dir != NULL && chdir (dir) == -1) {
1137 execve (argv[0], argv, env_strings);
1144 ret = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
1145 (gpointer *)&process_handle_data);
1147 g_warning ("%s: error looking up process handle %p", __func__,
1149 _wapi_handle_unref (handle);
1153 process_handle_data->id = pid;
1155 if (process_info != NULL) {
1156 process_info->hProcess = handle;
1157 process_info->dwProcessId = pid;
1159 /* FIXME: we might need to handle the thread info some
1162 process_info->hThread = INVALID_HANDLE_VALUE;
1163 process_info->dwThreadId = 0;
1167 _wapi_handle_unlock_shared_handles ();
1173 if (full_prog != NULL) {
1185 if(env_strings != NULL) {
1186 g_strfreev (env_strings);
1193 g_message ("%s: returning handle %p for pid %d", __func__, handle,
1200 static void process_set_name (struct _WapiHandle_process *process_handle)
1202 gchar *progname, *utf8_progname, *slash;
1204 progname=g_get_prgname ();
1205 utf8_progname=mono_utf8_from_external (progname);
1208 g_message ("%s: using [%s] as prog name", __func__, progname);
1211 if(utf8_progname!=NULL) {
1212 slash=strrchr (utf8_progname, '/');
1214 g_strlcpy (process_handle->proc_name, slash+1,
1215 _WAPI_PROC_NAME_MAX_LEN - 1);
1217 g_strlcpy (process_handle->proc_name, utf8_progname,
1218 _WAPI_PROC_NAME_MAX_LEN - 1);
1221 g_free (utf8_progname);
1225 extern void _wapi_time_t_to_filetime (time_t timeval, WapiFileTime *filetime);
1227 #if !GLIB_CHECK_VERSION (2,4,0)
1228 #define g_setenv(a,b,c) setenv(a,b,c)
1229 #define g_unsetenv(a) unsetenv(a)
1232 static void process_set_current (void)
1234 pid_t pid = _wapi_getpid ();
1235 const char *handle_env;
1236 struct _WapiHandle_process process_handle = {0};
1238 mono_once (&process_ops_once, process_ops_init);
1240 handle_env = g_getenv ("_WAPI_PROCESS_HANDLE_OFFSET");
1241 g_unsetenv ("_WAPI_PROCESS_HANDLE_OFFSET");
1243 if (handle_env != NULL) {
1244 struct _WapiHandle_process *process_handlep;
1245 gchar *procname = NULL;
1248 current_process = _wapi_handle_new_from_offset (WAPI_HANDLE_PROCESS, atoi (handle_env), TRUE);
1251 g_message ("%s: Found my process handle: %p (offset %d 0x%x)",
1252 __func__, current_process, atoi (handle_env),
1256 ok = _wapi_lookup_handle (current_process, WAPI_HANDLE_PROCESS,
1257 (gpointer *)&process_handlep);
1259 /* This test will probably break on linuxthreads, but
1260 * that should be ancient history on all distros we
1263 if (process_handlep->id == pid) {
1264 procname = process_handlep->proc_name;
1265 if (!strcmp (procname, "mono")) {
1266 /* Set a better process name */
1268 g_message ("%s: Setting better process name", __func__);
1271 process_set_name (process_handlep);
1274 g_message ("%s: Leaving process name: %s", __func__, procname);
1281 /* Wrong pid, so drop this handle and fall through to
1284 _wapi_handle_unref (current_process);
1288 /* We get here if the handle wasn't specified in the
1289 * environment, or if the process ID was wrong, or if the
1290 * handle lookup failed (eg if the parent process forked and
1291 * quit immediately, and deleted the shared data before the
1292 * child got a chance to attach it.)
1296 g_message ("%s: Need to create my own process handle", __func__);
1299 process_handle.id = pid;
1301 process_set_defaults (&process_handle);
1302 process_set_name (&process_handle);
1304 current_process = _wapi_handle_new (WAPI_HANDLE_PROCESS,
1306 if (current_process == _WAPI_HANDLE_INVALID) {
1307 g_warning ("%s: error creating process handle", __func__);
1312 gpointer _wapi_process_duplicate ()
1314 mono_once (&process_current_once, process_set_current);
1316 _wapi_handle_ref (current_process);
1318 return(current_process);
1321 /* Returns a pseudo handle that doesn't need to be closed afterwards */
1322 gpointer GetCurrentProcess (void)
1324 mono_once (&process_current_once, process_set_current);
1326 return(_WAPI_PROCESS_CURRENT);
1329 guint32 GetProcessId (gpointer handle)
1331 struct _WapiHandle_process *process_handle;
1334 if ((GPOINTER_TO_UINT (handle) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
1335 /* This is a pseudo handle */
1336 return(GPOINTER_TO_UINT (handle) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
1339 ok = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
1340 (gpointer *)&process_handle);
1342 SetLastError (ERROR_INVALID_HANDLE);
1346 return (process_handle->id);
1349 guint32 GetCurrentProcessId (void)
1351 mono_once (&process_current_once, process_set_current);
1353 return (GetProcessId (current_process));
1356 /* Returns the process id as a convenience to the functions that call this */
1357 static pid_t signal_process_if_gone (gpointer handle)
1359 struct _WapiHandle_process *process_handle;
1362 g_assert ((GPOINTER_TO_UINT (handle) & _WAPI_PROCESS_UNHANDLED) != _WAPI_PROCESS_UNHANDLED);
1364 /* Make sure the process is signalled if it has exited - if
1365 * the parent process didn't wait for it then it won't be
1367 ok = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
1368 (gpointer *)&process_handle);
1370 /* It's possible that the handle has vanished during
1371 * the _wapi_search_handle before it gets here, so
1372 * don't spam the console with warnings.
1374 /* g_warning ("%s: error looking up process handle %p",
1375 __func__, handle);*/
1381 g_message ("%s: looking at process %d", __func__, process_handle->id);
1384 if (kill (process_handle->id, 0) == -1 &&
1387 /* The process is dead, (EPERM tells us a new process
1388 * has that ID, but as it's owned by someone else it
1389 * can't be the one listed in our shared memory file)
1391 _wapi_shared_handle_set_signal_state (handle, TRUE);
1394 return (process_handle->id);
1398 static gboolean process_enum (gpointer handle, gpointer user_data)
1400 GArray *processes=user_data;
1401 pid_t pid = signal_process_if_gone (handle);
1408 /* Ignore processes that have already exited (ie they are signalled) */
1409 if (_wapi_handle_issignalled (handle) == FALSE) {
1411 g_message ("%s: process %d added to array", __func__, pid);
1414 /* This ensures that duplicates aren't returned (see
1415 * the comment above _wapi_search_handle () for why
1418 for (i = 0; i < processes->len; i++) {
1419 if (g_array_index (processes, pid_t, i) == pid) {
1420 /* We've already got this one, return
1421 * FALSE to keep searching
1427 g_array_append_val (processes, pid);
1430 /* Return false to keep searching */
1433 #endif /* UNUSED_CODE */
1435 gboolean EnumProcesses (guint32 *pids, guint32 len, guint32 *needed)
1437 GArray *processes = g_array_new (FALSE, FALSE, sizeof(pid_t));
1440 struct dirent *entry;
1442 mono_once (&process_current_once, process_set_current);
1444 dir = opendir ("/proc");
1448 while((entry = readdir (dir)) != NULL) {
1449 if (isdigit (entry->d_name[0])) {
1451 pid_t pid = (pid_t)strtol (entry->d_name, &endptr, 10);
1453 if (*endptr == '\0') {
1454 /* Name was entirely numeric, so was a
1457 g_array_append_val (processes, pid);
1463 fit=len/sizeof(guint32);
1464 for (i = 0, j = 0; j < fit && i < processes->len; i++) {
1465 pids[j++] = g_array_index (processes, pid_t, i);
1468 g_array_free (processes, TRUE);
1470 *needed = j * sizeof(guint32);
1475 static gboolean process_open_compare (gpointer handle, gpointer user_data)
1478 pid_t checking_pid = signal_process_if_gone (handle);
1480 if (checking_pid == 0) {
1484 wanted_pid = GPOINTER_TO_UINT (user_data);
1486 /* It's possible to have more than one process handle with the
1487 * same pid, but only the one running process can be
1490 if (checking_pid == wanted_pid &&
1491 _wapi_handle_issignalled (handle) == FALSE) {
1492 /* If the handle is blown away in the window between
1493 * returning TRUE here and _wapi_search_handle pinging
1494 * the timestamp, the search will continue
1502 gpointer OpenProcess (guint32 req_access G_GNUC_UNUSED, gboolean inherit G_GNUC_UNUSED, guint32 pid)
1504 /* Find the process handle that corresponds to pid */
1507 mono_once (&process_current_once, process_set_current);
1510 g_message ("%s: looking for process %d", __func__, pid);
1513 handle = _wapi_search_handle (WAPI_HANDLE_PROCESS,
1514 process_open_compare,
1515 GUINT_TO_POINTER (pid), NULL, TRUE);
1517 gchar *dir = g_strdup_printf ("/proc/%d", pid);
1518 if (!access (dir, F_OK)) {
1519 /* Return a pseudo handle for processes we
1520 * don't have handles for
1522 return((gpointer)(_WAPI_PROCESS_UNHANDLED + pid));
1525 g_message ("%s: Can't find pid %d", __func__, pid);
1528 SetLastError (ERROR_PROC_NOT_FOUND);
1534 _wapi_handle_ref (handle);
1539 gboolean GetExitCodeProcess (gpointer process, guint32 *code)
1541 struct _WapiHandle_process *process_handle;
1544 mono_once (&process_current_once, process_set_current);
1550 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
1551 /* This is a pseudo handle, so we don't know what the
1557 ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
1558 (gpointer *)&process_handle);
1561 g_message ("%s: Can't find process %p", __func__, process);
1567 /* A process handle is only signalled if the process has exited
1568 * and has been waited for */
1570 /* Make sure any process exit has been noticed, before
1571 * checking if the process is signalled. Fixes bug 325463.
1573 process_wait (process, 0);
1575 if (_wapi_handle_issignalled (process) == TRUE) {
1576 *code = process_handle->exitstatus;
1578 *code = STILL_ACTIVE;
1584 gboolean GetProcessTimes (gpointer process, WapiFileTime *create_time,
1585 WapiFileTime *exit_time, WapiFileTime *kernel_time,
1586 WapiFileTime *user_time)
1588 struct _WapiHandle_process *process_handle;
1590 gboolean ku_times_set = FALSE;
1592 mono_once (&process_current_once, process_set_current);
1594 if(create_time==NULL || exit_time==NULL || kernel_time==NULL ||
1596 /* Not sure if w32 allows NULLs here or not */
1600 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
1601 /* This is a pseudo handle, so just fail for now
1606 ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
1607 (gpointer *)&process_handle);
1610 g_message ("%s: Can't find process %p", __func__, process);
1616 *create_time=process_handle->create_time;
1618 /* A process handle is only signalled if the process has
1619 * exited. Otherwise exit_time isn't set
1621 if(_wapi_handle_issignalled (process)==TRUE) {
1622 *exit_time=process_handle->exit_time;
1625 #ifdef HAVE_GETRUSAGE
1626 if (process_handle->id == getpid ()) {
1627 struct rusage time_data;
1628 if (getrusage (RUSAGE_SELF, &time_data) == 0) {
1630 gint64 *tick_val_ptr;
1631 ku_times_set = TRUE;
1632 tick_val = time_data.ru_utime.tv_sec * 10000000 + time_data.ru_utime.tv_usec * 10;
1633 tick_val_ptr = (gint64*)user_time;
1634 *tick_val_ptr = tick_val;
1635 tick_val = time_data.ru_stime.tv_sec * 10000000 + time_data.ru_stime.tv_usec * 10;
1636 tick_val_ptr = (gint64*)kernel_time;
1637 *tick_val_ptr = tick_val;
1641 if (!ku_times_set) {
1642 memset (kernel_time, 0, sizeof (WapiFileTime));
1643 memset (user_time, 0, sizeof (WapiFileTime));
1651 gpointer address_start;
1652 gpointer address_end;
1654 gpointer address_offset;
1660 static void free_procmodule (WapiProcModule *mod)
1662 if (mod->perms != NULL) {
1663 g_free (mod->perms);
1665 if (mod->filename != NULL) {
1666 g_free (mod->filename);
1671 static gint find_procmodule (gconstpointer a, gconstpointer b)
1673 WapiProcModule *want = (WapiProcModule *)a;
1674 WapiProcModule *compare = (WapiProcModule *)b;
1676 if ((want->device == compare->device) &&
1677 (want->inode == compare->inode)) {
1684 static GSList *load_modules (FILE *fp)
1687 WapiProcModule *mod;
1688 gchar buf[MAXPATHLEN + 1], *p, *endp;
1689 gchar *start_start, *end_start, *prot_start, *offset_start;
1690 gchar *maj_dev_start, *min_dev_start, *inode_start, prot_buf[5];
1691 gpointer address_start, address_end, address_offset;
1692 guint32 maj_dev, min_dev;
1696 while (fgets (buf, sizeof(buf), fp)) {
1698 while (g_ascii_isspace (*p)) ++p;
1700 if (!g_ascii_isxdigit (*start_start)) {
1703 address_start = (gpointer)strtoul (start_start, &endp, 16);
1711 if (!g_ascii_isxdigit (*end_start)) {
1714 address_end = (gpointer)strtoul (end_start, &endp, 16);
1716 if (!g_ascii_isspace (*p)) {
1720 while (g_ascii_isspace (*p)) ++p;
1722 if (*prot_start != 'r' && *prot_start != '-') {
1725 memcpy (prot_buf, prot_start, 4);
1727 while (!g_ascii_isspace (*p)) ++p;
1729 while (g_ascii_isspace (*p)) ++p;
1731 if (!g_ascii_isxdigit (*offset_start)) {
1734 address_offset = (gpointer)strtoul (offset_start, &endp, 16);
1736 if (!g_ascii_isspace (*p)) {
1740 while(g_ascii_isspace (*p)) ++p;
1742 if (!g_ascii_isxdigit (*maj_dev_start)) {
1745 maj_dev = strtoul (maj_dev_start, &endp, 16);
1753 if (!g_ascii_isxdigit (*min_dev_start)) {
1756 min_dev = strtoul (min_dev_start, &endp, 16);
1758 if (!g_ascii_isspace (*p)) {
1762 while (g_ascii_isspace (*p)) ++p;
1764 if (!g_ascii_isxdigit (*inode_start)) {
1767 inode = (ino_t)strtol (inode_start, &endp, 10);
1769 if (!g_ascii_isspace (*p)) {
1773 device = makedev ((int)maj_dev, (int)min_dev);
1774 if ((device == 0) &&
1779 while(g_ascii_isspace (*p)) ++p;
1780 /* p now points to the filename */
1782 mod = g_new0 (WapiProcModule, 1);
1783 mod->address_start = address_start;
1784 mod->address_end = address_end;
1785 mod->perms = g_strdup (prot_buf);
1786 mod->address_offset = address_offset;
1787 mod->device = device;
1789 mod->filename = g_strdup (g_strstrip (p));
1791 if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
1792 ret = g_slist_prepend (ret, mod);
1794 free_procmodule (mod);
1798 ret = g_slist_reverse (ret);
1803 static gboolean match_procname_to_modulename (gchar *procname, gchar *modulename)
1805 char* lastsep = NULL;
1807 if (procname == NULL || modulename == NULL)
1810 if (!strcmp (procname, modulename))
1813 lastsep = strrchr (modulename, '/');
1815 if (!strcmp (lastsep+1, procname))
1823 gboolean EnumProcessModules (gpointer process, gpointer *modules,
1824 guint32 size, guint32 *needed)
1826 struct _WapiHandle_process *process_handle;
1830 GSList *mods = NULL;
1831 WapiProcModule *module;
1832 guint32 count, avail = size / sizeof(gpointer);
1835 gchar *proc_name = NULL;
1837 /* Store modules in an array of pointers (main module as
1838 * modules[0]), using the load address for each module as a
1839 * token. (Use 'NULL' as an alternative for the main module
1840 * so that the simple implementation can just return one item
1841 * for now.) Get the info from /proc/<pid>/maps on linux,
1842 * other systems will have to implement /dev/kmem reading or
1843 * whatever other horrid technique is needed.
1845 if (size < sizeof(gpointer)) {
1849 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
1850 /* This is a pseudo handle */
1851 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
1853 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
1854 (gpointer *)&process_handle);
1857 g_message ("%s: Can't find process %p", __func__, process);
1862 pid = process_handle->id;
1863 proc_name = process_handle->proc_name;
1866 filename = g_strdup_printf ("/proc/%d/maps", pid);
1867 if ((fp = fopen (filename, "r")) == NULL) {
1868 /* No /proc/<pid>/maps so just return the main module
1872 *needed = sizeof(gpointer);
1874 mods = load_modules (fp);
1876 count = g_slist_length (mods);
1878 /* count + 1 to leave slot 0 for the main module */
1879 *needed = sizeof(gpointer) * (count + 1);
1881 /* Use the NULL shortcut, as the first line in
1882 * /proc/<pid>/maps isn't the executable, and we need
1883 * that first in the returned list. Check the module name
1884 * to see if it ends with the proc name and substitute
1885 * the first entry with it. FIXME if this turns out to
1889 for (i = 0; i < (avail - 1) && i < count; i++) {
1890 module = (WapiProcModule *)g_slist_nth_data (mods, i);
1891 if (modules[0] != NULL)
1892 modules[i] = module->address_start;
1893 else if (match_procname_to_modulename (proc_name, module->filename))
1894 modules[0] = module->address_start;
1896 modules[i + 1] = module->address_start;
1899 for (i = 0; i < count; i++) {
1900 free_procmodule (g_slist_nth_data (mods, i));
1902 g_slist_free (mods);
1910 static gchar *get_process_name_from_proc (pid_t pid)
1917 memset (buf, '\0', sizeof(buf));
1919 filename = g_strdup_printf ("/proc/%d/exe", pid);
1920 if (readlink (filename, buf, 255) > 0) {
1921 ret = g_strdup (buf);
1929 filename = g_strdup_printf ("/proc/%d/cmdline", pid);
1930 if ((fp = fopen (filename, "r")) != NULL) {
1931 if (fgets (buf, 256, fp) != NULL) {
1932 ret = g_strdup (buf);
1943 filename = g_strdup_printf ("/proc/%d/stat", pid);
1944 if ((fp = fopen (filename, "r")) != NULL) {
1945 if (fgets (buf, 256, fp) != NULL) {
1948 start = strchr (buf, '(');
1949 if (start != NULL) {
1950 end = strchr (start + 1, ')');
1953 ret = g_strndup (start + 1,
1970 static guint32 get_module_name (gpointer process, gpointer module,
1971 gunichar2 *basename, guint32 size,
1974 struct _WapiHandle_process *process_handle;
1977 gunichar2 *procname;
1978 gchar *procname_ext = NULL;
1983 GSList *mods = NULL;
1984 WapiProcModule *found_module;
1987 gchar *proc_name = NULL;
1989 mono_once (&process_current_once, process_set_current);
1992 g_message ("%s: Getting module base name, process handle %p module %p",
1993 __func__, process, module);
1996 if (basename == NULL || size == 0) {
2000 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2001 /* This is a pseudo handle */
2002 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2003 proc_name = get_process_name_from_proc (pid);
2005 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2006 (gpointer *)&process_handle);
2009 g_message ("%s: Can't find process %p", __func__,
2015 pid = process_handle->id;
2016 proc_name = g_strdup (process_handle->proc_name);
2019 /* Look up the address in /proc/<pid>/maps */
2020 filename = g_strdup_printf ("/proc/%d/maps", pid);
2021 if ((fp = fopen (filename, "r")) == NULL) {
2022 if (errno == EACCES && module == NULL && base == TRUE) {
2023 procname_ext = get_process_name_from_proc (pid);
2025 /* No /proc/<pid>/maps, so just return failure
2033 mods = load_modules (fp);
2035 count = g_slist_length (mods);
2037 /* If module != NULL compare the address.
2038 * If module == NULL we are looking for the main module.
2039 * The best we can do for now check it the module name end with the process name.
2041 for (i = 0; i < count; i++) {
2042 found_module = (WapiProcModule *)g_slist_nth_data (mods, i);
2043 if (procname_ext == NULL &&
2044 ((module == NULL && match_procname_to_modulename (proc_name, found_module->filename)) ||
2045 (module != NULL && found_module->address_start == module))) {
2047 procname_ext = g_path_get_basename (found_module->filename);
2049 procname_ext = g_strdup (found_module->filename);
2053 free_procmodule (found_module);
2056 if (procname_ext == NULL)
2058 /* If it's *still* null, we might have hit the
2059 * case where reading /proc/$pid/maps gives an
2060 * empty file for this user.
2062 procname_ext = get_process_name_from_proc (pid);
2065 g_slist_free (mods);
2070 if (procname_ext != NULL) {
2072 g_message ("%s: Process name is [%s]", __func__,
2076 procname = mono_unicode_from_external (procname_ext, &bytes);
2077 if (procname == NULL) {
2079 g_free (procname_ext);
2085 /* Add the terminator */
2090 g_message ("%s: Size %d smaller than needed (%ld); truncating", __func__, size, bytes);
2093 memcpy (basename, procname, size);
2096 g_message ("%s: Size %d larger than needed (%ld)",
2097 __func__, size, bytes);
2100 memcpy (basename, procname, bytes);
2104 g_free (procname_ext);
2112 guint32 GetModuleBaseName (gpointer process, gpointer module,
2113 gunichar2 *basename, guint32 size)
2115 return(get_module_name (process, module, basename, size, TRUE));
2118 guint32 GetModuleFileNameEx (gpointer process, gpointer module,
2119 gunichar2 *filename, guint32 size)
2121 return(get_module_name (process, module, filename, size, FALSE));
2124 gboolean GetModuleInformation (gpointer process, gpointer module,
2125 WapiModuleInfo *modinfo, guint32 size)
2127 struct _WapiHandle_process *process_handle;
2132 GSList *mods = NULL;
2133 WapiProcModule *found_module;
2136 gboolean ret = FALSE;
2137 gchar *proc_name = NULL;
2139 mono_once (&process_current_once, process_set_current);
2142 g_message ("%s: Getting module info, process handle %p module %p",
2143 __func__, process, module);
2146 if (modinfo == NULL || size < sizeof(WapiModuleInfo)) {
2150 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2151 /* This is a pseudo handle */
2152 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2153 proc_name = get_process_name_from_proc (pid);
2155 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2156 (gpointer *)&process_handle);
2159 g_message ("%s: Can't find process %p", __func__,
2165 pid = process_handle->id;
2166 proc_name = g_strdup (process_handle->proc_name);
2169 /* Look up the address in /proc/<pid>/maps */
2170 filename = g_strdup_printf ("/proc/%d/maps", pid);
2171 if ((fp = fopen (filename, "r")) == NULL) {
2172 /* No /proc/<pid>/maps, so just return failure
2179 mods = load_modules (fp);
2181 count = g_slist_length (mods);
2183 /* If module != NULL compare the address.
2184 * If module == NULL we are looking for the main module.
2185 * The best we can do for now check it the module name end with the process name.
2187 for (i = 0; i < count; i++) {
2188 found_module = (WapiProcModule *)g_slist_nth_data (mods, i);
2189 if ( ret == FALSE &&
2190 ((module == NULL && match_procname_to_modulename (proc_name, found_module->filename)) ||
2191 (module != NULL && found_module->address_start == module))) {
2192 modinfo->lpBaseOfDll = found_module->address_start;
2193 modinfo->SizeOfImage = (gsize)(found_module->address_end) - (gsize)(found_module->address_start);
2194 modinfo->EntryPoint = found_module->address_offset;
2198 free_procmodule (found_module);
2201 g_slist_free (mods);
2209 gboolean GetProcessWorkingSetSize (gpointer process, size_t *min, size_t *max)
2211 struct _WapiHandle_process *process_handle;
2214 mono_once (&process_current_once, process_set_current);
2216 if(min==NULL || max==NULL) {
2217 /* Not sure if w32 allows NULLs here or not */
2221 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2222 /* This is a pseudo handle, so just fail for now
2227 ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2228 (gpointer *)&process_handle);
2231 g_message ("%s: Can't find process %p", __func__, process);
2237 *min=process_handle->min_working_set;
2238 *max=process_handle->max_working_set;
2243 gboolean SetProcessWorkingSetSize (gpointer process, size_t min, size_t max)
2245 struct _WapiHandle_process *process_handle;
2248 mono_once (&process_current_once, process_set_current);
2250 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2251 /* This is a pseudo handle, so just fail for now
2256 ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2257 (gpointer *)&process_handle);
2260 g_message ("%s: Can't find process %p", __func__, process);
2266 process_handle->min_working_set=min;
2267 process_handle->max_working_set=max;
2274 TerminateProcess (gpointer process, gint32 exitCode)
2276 struct _WapiHandle_process *process_handle;
2282 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2283 /* This is a pseudo handle */
2284 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2286 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2287 (gpointer *) &process_handle);
2291 g_message ("%s: Can't find process %p", __func__,
2294 SetLastError (ERROR_INVALID_HANDLE);
2297 pid = process_handle->id;
2300 signo = (exitCode == -1) ? SIGKILL : SIGTERM;
2301 ret = kill (pid, signo);
2305 SetLastError (ERROR_INVALID_PARAMETER);
2308 SetLastError (ERROR_ACCESS_DENIED);
2311 SetLastError (ERROR_PROC_NOT_FOUND);
2314 SetLastError (ERROR_GEN_FAILURE);
2322 GetPriorityClass (gpointer process)
2324 #ifdef HAVE_GETPRIORITY
2325 struct _WapiHandle_process *process_handle;
2330 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2331 /* This is a pseudo handle */
2332 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2334 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2335 (gpointer *) &process_handle);
2338 SetLastError (ERROR_INVALID_HANDLE);
2341 pid = process_handle->id;
2345 ret = getpriority (PRIO_PROCESS, pid);
2346 if (ret == -1 && errno != 0) {
2350 SetLastError (ERROR_ACCESS_DENIED);
2353 SetLastError (ERROR_PROC_NOT_FOUND);
2356 SetLastError (ERROR_GEN_FAILURE);
2362 return NORMAL_PRIORITY_CLASS;
2364 return REALTIME_PRIORITY_CLASS;
2366 return HIGH_PRIORITY_CLASS;
2368 return ABOVE_NORMAL_PRIORITY_CLASS;
2370 return IDLE_PRIORITY_CLASS;
2372 return BELOW_NORMAL_PRIORITY_CLASS;
2374 return NORMAL_PRIORITY_CLASS;
2376 SetLastError (ERROR_NOT_SUPPORTED);
2382 SetPriorityClass (gpointer process, guint32 priority_class)
2384 #ifdef HAVE_SETPRIORITY
2385 struct _WapiHandle_process *process_handle;
2391 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2392 /* This is a pseudo handle */
2393 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2395 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2396 (gpointer *) &process_handle);
2399 SetLastError (ERROR_INVALID_HANDLE);
2402 pid = process_handle->id;
2405 switch (priority_class) {
2406 case IDLE_PRIORITY_CLASS:
2409 case BELOW_NORMAL_PRIORITY_CLASS:
2412 case NORMAL_PRIORITY_CLASS:
2415 case ABOVE_NORMAL_PRIORITY_CLASS:
2418 case HIGH_PRIORITY_CLASS:
2421 case REALTIME_PRIORITY_CLASS:
2425 SetLastError (ERROR_INVALID_PARAMETER);
2429 ret = setpriority (PRIO_PROCESS, pid, prio);
2434 SetLastError (ERROR_ACCESS_DENIED);
2437 SetLastError (ERROR_PROC_NOT_FOUND);
2440 SetLastError (ERROR_GEN_FAILURE);
2446 SetLastError (ERROR_NOT_SUPPORTED);