2 * processes.c: Process handles
5 * Dick Porter (dick@ximian.com)
7 * (C) 2002-2006 Novell, Inc.
17 #include <sys/types.h>
22 #include <sys/resource.h>
25 /* sys/resource.h (for rusage) is required when using osx 10.3 (but not 10.4) */
27 #include <sys/resource.h>
30 #include <mono/io-layer/wapi.h>
31 #include <mono/io-layer/wapi-private.h>
32 #include <mono/io-layer/handles-private.h>
33 #include <mono/io-layer/misc-private.h>
34 #include <mono/io-layer/mono-mutex.h>
35 #include <mono/io-layer/process-private.h>
36 #include <mono/io-layer/threads.h>
37 #include <mono/utils/strenc.h>
38 #include <mono/io-layer/timefuncs-private.h>
40 /* The process' environment strings */
41 extern char **environ;
45 static guint32 process_wait (gpointer handle, guint32 timeout);
47 struct _WapiHandleOps _wapi_process_ops = {
48 NULL, /* close_shared */
52 process_wait, /* special_wait */
56 static mono_once_t process_current_once=MONO_ONCE_INIT;
57 static gpointer current_process=NULL;
59 static mono_once_t process_ops_once=MONO_ONCE_INIT;
61 static void process_ops_init (void)
63 _wapi_handle_register_capabilities (WAPI_HANDLE_PROCESS,
64 WAPI_HANDLE_CAP_WAIT |
65 WAPI_HANDLE_CAP_SPECIAL_WAIT);
68 static gboolean process_set_termination_details (gpointer handle, int status)
70 struct _WapiHandle_process *process_handle;
74 ok = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
75 (gpointer *)&process_handle);
77 g_warning ("%s: error looking up process handle %p",
82 thr_ret = _wapi_handle_lock_shared_handles ();
83 g_assert (thr_ret == 0);
85 if (WIFSIGNALED(status)) {
86 process_handle->exitstatus = 128 + WTERMSIG(status);
88 process_handle->exitstatus = WEXITSTATUS(status);
90 _wapi_time_t_to_filetime (time(NULL), &process_handle->exit_time);
92 /* Don't set process_handle->waited here, it needs to only
93 * happen in the parent when wait() has been called.
97 g_message ("%s: Setting handle %p signalled", __func__, handle);
100 _wapi_shared_handle_set_signal_state (handle, TRUE);
102 _wapi_handle_unlock_shared_handles ();
104 /* Drop the reference we hold so we have somewhere to store
105 * the exit details, now the process has in fact exited
107 _wapi_handle_unref (handle);
112 /* See if any child processes have terminated and wait() for them,
113 * updating process handle info. This function is called from the
114 * collection thread every few seconds.
116 static gboolean waitfor_pid (gpointer test, gpointer user_data)
118 struct _WapiHandle_process *process;
123 ok = _wapi_lookup_handle (test, WAPI_HANDLE_PROCESS,
124 (gpointer *)&process);
126 /* The handle must have been too old and was reaped */
130 if (process->waited) {
131 /* We've already done this one */
136 ret = waitpid (process->id, &status, WNOHANG);
137 } while (errno == EINTR);
140 /* Process not ready for wait */
142 g_message ("%s: Process %d not ready for waiting for: %s",
143 __func__, process->id, g_strerror (errno));
150 g_message ("%s: Process %d finished", __func__, ret);
153 process->waited = TRUE;
155 *(int *)user_data = status;
160 void _wapi_process_reap (void)
166 g_message ("%s: Reaping child processes", __func__);
170 proc = _wapi_search_handle (WAPI_HANDLE_PROCESS, waitfor_pid,
171 &status, NULL, FALSE);
174 g_message ("%s: process handle %p exit code %d",
175 __func__, proc, status);
178 process_set_termination_details (proc, status);
180 /* _wapi_search_handle adds a reference, so
183 _wapi_handle_unref (proc);
185 } while (proc != NULL);
188 /* Limitations: This can only wait for processes that are our own
189 * children. Fixing this means resurrecting a daemon helper to manage
192 static guint32 process_wait (gpointer handle, guint32 timeout)
194 struct _WapiHandle_process *process_handle;
200 g_message ("%s: Waiting for process %p", __func__, handle);
203 ok = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
204 (gpointer *)&process_handle);
206 g_warning ("%s: error looking up process handle %p", __func__,
211 if (process_handle->waited) {
212 /* We've already done this one */
214 g_message ("%s: Process %p already signalled", __func__,
218 return (WAIT_OBJECT_0);
221 pid = process_handle->id;
224 g_message ("%s: PID is %d, timeout %d", __func__, pid, timeout);
227 if (timeout == INFINITE) {
228 if (pid == _wapi_getpid ()) {
233 while ((ret = waitpid (pid, &status, 0)) != pid) {
234 if (ret == (pid_t)-1 && errno != EINTR) {
239 } else if (timeout == 0) {
241 ret = waitpid (pid, &status, WNOHANG);
243 return (WAIT_TIMEOUT);
247 if (pid == _wapi_getpid ()) {
249 return(WAIT_TIMEOUT);
252 ret = waitpid (pid, &status, WNOHANG);
254 g_message ("%s: waitpid returns: %d, timeout is %d", __func__, ret, timeout);
259 } else if (ret == (pid_t)-1 &&
262 g_message ("%s: waitpid failure: %s",
267 if (errno == ECHILD &&
268 process_handle->waited) {
270 * process reaper must
274 g_message ("%s: Process %p already reaped", __func__, handle);
277 return(WAIT_OBJECT_0);
283 _wapi_handle_spin (100);
285 } while (timeout > 0);
289 return(WAIT_TIMEOUT);
293 /* Process must have exited */
295 g_message ("%s: Wait done, status %d", __func__, status);
298 ok = process_set_termination_details (handle, status);
300 SetLastError (ERROR_OUTOFMEMORY);
301 return (WAIT_FAILED);
303 process_handle->waited = TRUE;
305 return(WAIT_OBJECT_0);
308 void _wapi_process_signal_self ()
310 if (current_process != NULL) {
311 process_set_termination_details (current_process, 0);
315 static void process_set_defaults (struct _WapiHandle_process *process_handle)
317 /* These seem to be the defaults on w2k */
318 process_handle->min_working_set = 204800;
319 process_handle->max_working_set = 1413120;
321 process_handle->waited = FALSE;
323 _wapi_time_t_to_filetime (time (NULL), &process_handle->create_time);
327 len16 (const gunichar2 *str)
338 utf16_concat (const gunichar2 *first, ...)
345 va_start (args, first);
346 total += len16 (first);
347 for (s = va_arg (args, gunichar2 *); s != NULL; s = va_arg(args, gunichar2 *)){
352 ret = g_new (gunichar2, total + 1);
358 for (s = first; *s != 0; s++)
360 va_start (args, first);
361 for (s = va_arg (args, gunichar2 *); s != NULL; s = va_arg (args, gunichar2 *)){
364 for (p = s; *p != 0; p++)
372 static const gunichar2 utf16_space_bytes [2] = { 0x20, 0 };
373 static const gunichar2 *utf16_space = utf16_space_bytes;
375 /* Implemented as just a wrapper around CreateProcess () */
376 gboolean ShellExecuteEx (WapiShellExecuteInfo *sei)
379 WapiProcessInformation process_info;
383 /* w2k just segfaults here, but we can do better than
386 SetLastError (ERROR_INVALID_PARAMETER);
390 if (sei->lpFile == NULL) {
391 /* w2k returns TRUE for this, for some reason. */
395 /* Put both executable and parameters into the second argument
396 * to CreateProcess (), so it searches $PATH. The conversion
397 * into and back out of utf8 is because there is no
398 * g_strdup_printf () equivalent for gunichar2 :-(
400 args = utf16_concat (sei->lpFile, sei->lpParameters == NULL ? NULL : utf16_space, sei->lpParameters, NULL);
402 SetLastError (ERROR_INVALID_DATA);
405 ret = CreateProcess (NULL, args, NULL, NULL, TRUE,
406 CREATE_UNICODE_ENVIRONMENT, NULL,
407 sei->lpDirectory, NULL, &process_info);
411 static char *handler;
412 static gunichar2 *handler_utf16;
414 if (handler_utf16 == (gunichar2 *)-1)
417 #ifdef PLATFORM_MACOSX
418 handler = "/usr/bin/open";
421 * On Linux, try: xdg-open, the FreeDesktop standard way of doing it,
422 * if that fails, try to use gnome-open, then kfmclient
424 handler = g_find_program_in_path ("xdg-open");
425 if (handler == NULL){
426 handler = g_find_program_in_path ("gnome-open");
427 if (handler == NULL){
428 handler = g_find_program_in_path ("kfmclient");
429 if (handler == NULL){
430 handler_utf16 = (gunichar2 *) -1;
433 /* kfmclient needs exec argument */
435 handler = g_strconcat (old, " exec",
442 handler_utf16 = g_utf8_to_utf16 (handler, -1, NULL, NULL, NULL);
444 args = utf16_concat (handler_utf16, utf16_space, sei->lpFile,
445 sei->lpParameters == NULL ? NULL : utf16_space,
446 sei->lpParameters, NULL);
448 SetLastError (ERROR_INVALID_DATA);
451 ret = CreateProcess (NULL, args, NULL, NULL, TRUE,
452 CREATE_UNICODE_ENVIRONMENT, NULL,
453 sei->lpDirectory, NULL, &process_info);
456 SetLastError (ERROR_INVALID_DATA);
461 if (sei->fMask & SEE_MASK_NOCLOSEPROCESS) {
462 sei->hProcess = process_info.hProcess;
464 CloseHandle (process_info.hProcess);
471 is_managed_binary (const gchar *filename)
473 int original_errno = errno;
474 #if defined(HAVE_LARGE_FILE_SUPPORT) && defined(O_LARGEFILE)
475 int file = open (filename, O_RDONLY | O_LARGEFILE);
477 int file = open (filename, O_RDONLY);
480 unsigned char buffer[8];
481 off_t file_size, optional_header_offset;
482 off_t pe_header_offset;
483 gboolean managed = FALSE;
485 guint32 first_word, second_word;
487 /* If we are unable to open the file, then we definitely
488 * can't say that it is managed. The child mono process
489 * probably wouldn't be able to open it anyway.
492 errno = original_errno;
496 /* Retrieve the length of the file for future sanity checks. */
497 file_size = lseek (file, 0, SEEK_END);
498 lseek (file, 0, SEEK_SET);
500 /* We know we need to read a header field at offset 60. */
504 num_read = read (file, buffer, 2);
506 if ((num_read != 2) || (buffer[0] != 'M') || (buffer[1] != 'Z'))
509 new_offset = lseek (file, 60, SEEK_SET);
511 if (new_offset != 60)
514 num_read = read (file, buffer, 4);
518 pe_header_offset = buffer[0]
523 if (pe_header_offset + 24 > file_size)
526 new_offset = lseek (file, pe_header_offset, SEEK_SET);
528 if (new_offset != pe_header_offset)
531 num_read = read (file, buffer, 4);
533 if ((num_read != 4) || (buffer[0] != 'P') || (buffer[1] != 'E') || (buffer[2] != 0) || (buffer[3] != 0))
537 * Verify that the header we want in the optional header data
538 * is present in this binary.
540 new_offset = lseek (file, pe_header_offset + 20, SEEK_SET);
542 if (new_offset != pe_header_offset + 20)
545 num_read = read (file, buffer, 2);
547 if ((num_read != 2) || ((buffer[0] | (buffer[1] << 8)) < 216))
550 /* Read the CLR header address and size fields. These will be
551 * zero if the binary is not managed.
553 optional_header_offset = pe_header_offset + 24;
554 new_offset = lseek (file, optional_header_offset + 208, SEEK_SET);
556 if (new_offset != optional_header_offset + 208)
559 num_read = read (file, buffer, 8);
561 /* We are not concerned with endianness, only with
562 * whether it is zero or not.
564 first_word = *(guint32 *)&buffer[0];
565 second_word = *(guint32 *)&buffer[4];
567 if ((num_read != 8) || (first_word == 0) || (second_word == 0))
574 errno = original_errno;
578 gboolean CreateProcess (const gunichar2 *appname, const gunichar2 *cmdline,
579 WapiSecurityAttributes *process_attrs G_GNUC_UNUSED,
580 WapiSecurityAttributes *thread_attrs G_GNUC_UNUSED,
581 gboolean inherit_handles, guint32 create_flags,
582 gpointer new_environ, const gunichar2 *cwd,
583 WapiStartupInfo *startup,
584 WapiProcessInformation *process_info)
586 gchar *cmd=NULL, *prog = NULL, *full_prog = NULL, *args = NULL, *args_after_prog = NULL, *dir = NULL, **env_strings = NULL, **argv = NULL;
587 guint32 i, env_count = 0;
588 gboolean ret = FALSE;
590 struct _WapiHandle_process process_handle = {0}, *process_handle_data;
592 int in_fd, out_fd, err_fd;
596 mono_once (&process_ops_once, process_ops_init);
598 /* appname and cmdline specify the executable and its args:
600 * If appname is not NULL, it is the name of the executable.
601 * Otherwise the executable is the first token in cmdline.
603 * Executable searching:
605 * If appname is not NULL, it can specify the full path and
606 * file name, or else a partial name and the current directory
607 * will be used. There is no additional searching.
609 * If appname is NULL, the first whitespace-delimited token in
610 * cmdline is used. If the name does not contain a full
611 * directory path, the search sequence is:
613 * 1) The directory containing the current process
614 * 2) The current working directory
615 * 3) The windows system directory (Ignored)
616 * 4) The windows directory (Ignored)
619 * Just to make things more interesting, tokens can contain
620 * white space if they are surrounded by quotation marks. I'm
621 * beginning to understand just why windows apps are generally
622 * so crap, with an API like this :-(
624 if (appname != NULL) {
625 cmd = mono_unicode_to_external (appname);
628 g_message ("%s: unicode conversion returned NULL",
632 SetLastError (ERROR_PATH_NOT_FOUND);
636 /* Turn all the slashes round the right way */
637 for (i = 0; i < strlen (cmd); i++) {
638 if (cmd[i] == '\\') {
644 if (cmdline != NULL) {
645 args = mono_unicode_to_external (cmdline);
648 g_message ("%s: unicode conversion returned NULL", __func__);
651 SetLastError (ERROR_PATH_NOT_FOUND);
657 dir = mono_unicode_to_external (cwd);
660 g_message ("%s: unicode conversion returned NULL", __func__);
663 SetLastError (ERROR_PATH_NOT_FOUND);
667 /* Turn all the slashes round the right way */
668 for (i = 0; i < strlen (dir); i++) {
669 if (dir[i] == '\\') {
676 /* We can't put off locating the executable any longer :-( */
679 if (g_ascii_isalpha (cmd[0]) && (cmd[1] == ':')) {
680 /* Strip off the drive letter. I can't
681 * believe that CP/M holdover is still
684 g_memmove (cmd, cmd+2, strlen (cmd)-2);
685 cmd[strlen (cmd)-2] = '\0';
688 unquoted = g_shell_unquote (cmd, NULL);
689 if (unquoted[0] == '/') {
690 /* Assume full path given */
691 prog = g_strdup (unquoted);
693 /* Executable existing ? */
694 if (access (prog, X_OK) != 0) {
696 g_message ("%s: Couldn't find executable %s",
700 SetLastError (ERROR_FILE_NOT_FOUND);
704 /* Search for file named by cmd in the current
707 char *curdir = g_get_current_dir ();
709 prog = g_strdup_printf ("%s/%s", curdir, unquoted);
712 /* And make sure it's executable */
713 if (access (prog, X_OK) != 0) {
715 g_message ("%s: Couldn't find executable %s",
719 SetLastError (ERROR_FILE_NOT_FOUND);
725 args_after_prog = args;
730 /* Dig out the first token from args, taking quotation
734 /* First, strip off all leading whitespace */
735 args = g_strchug (args);
737 /* args_after_prog points to the contents of args
738 * after token has been set (otherwise argv[0] is
741 args_after_prog = args;
743 /* Assume the opening quote will always be the first
746 if (args[0] == '\"' || args [0] == '\'') {
748 for (i = 1; args[i] != '\0' && args[i] != quote; i++);
749 if (g_ascii_isspace (args[i+1])) {
750 /* We found the first token */
751 token = g_strndup (args+1, i-1);
752 args_after_prog = args + i;
754 /* Quotation mark appeared in the
755 * middle of the token. Just give the
756 * whole first token, quotes and all,
763 /* No quote mark, or malformed */
764 for (i = 0; args[i] != '\0'; i++) {
765 if (g_ascii_isspace (args[i])) {
766 token = g_strndup (args, i);
767 args_after_prog = args + i + 1;
773 if (token == NULL && args[0] != '\0') {
774 /* Must be just one token in the string */
775 token = g_strdup (args);
776 args_after_prog = NULL;
782 g_message ("%s: Couldn't find what to exec", __func__);
785 SetLastError (ERROR_PATH_NOT_FOUND);
789 /* Turn all the slashes round the right way. Only for
792 for (i = 0; i < strlen (token); i++) {
793 if (token[i] == '\\') {
798 if (g_ascii_isalpha (token[0]) && (token[1] == ':')) {
799 /* Strip off the drive letter. I can't
800 * believe that CP/M holdover is still
803 g_memmove (token, token+2, strlen (token)-2);
804 token[strlen (token)-2] = '\0';
807 if (token[0] == '/') {
808 /* Assume full path given */
809 prog = g_strdup (token);
811 /* Executable existing ? */
812 if (access (prog, X_OK) != 0) {
814 g_message ("%s: Couldn't find executable %s",
818 SetLastError (ERROR_FILE_NOT_FOUND);
823 char *curdir = g_get_current_dir ();
825 /* FIXME: Need to record the directory
826 * containing the current process, and check
827 * that for the new executable as the first
831 prog = g_strdup_printf ("%s/%s", curdir, token);
834 /* I assume X_OK is the criterion to use,
837 if (access (prog, X_OK) != 0) {
839 prog = g_find_program_in_path (token);
842 g_message ("%s: Couldn't find executable %s", __func__, token);
846 SetLastError (ERROR_FILE_NOT_FOUND);
856 g_message ("%s: Exec prog [%s] args [%s]", __func__, prog,
860 /* Check for CLR binaries; if found, we will try to invoke
861 * them using the same mono binary that started us.
863 if (is_managed_binary (prog) && (appname == NULL)) {
866 appname = mono_unicode_from_external ("mono", &bytes_ignored);
868 if (appname != NULL) {
869 cmdline = utf16_concat (appname, utf16_space, cmdline, NULL);
871 g_free ((gunichar2 *)appname);
873 if (cmdline != NULL) {
874 gboolean return_value = CreateProcess (
875 NULL, cmdline, process_attrs,
876 thread_attrs, inherit_handles, create_flags, new_environ,
877 cwd, startup, process_info);
879 g_free ((gunichar2 *)cmdline);
886 if (args_after_prog != NULL && *args_after_prog) {
889 qprog = g_shell_quote (prog);
890 full_prog = g_strconcat (qprog, " ", args_after_prog, NULL);
893 full_prog = g_shell_quote (prog);
896 ret = g_shell_parse_argv (full_prog, NULL, &argv, &gerr);
898 /* FIXME: Could do something with the GError here
902 if (startup != NULL && startup->dwFlags & STARTF_USESTDHANDLES) {
903 in_fd = GPOINTER_TO_UINT (startup->hStdInput);
904 out_fd = GPOINTER_TO_UINT (startup->hStdOutput);
905 err_fd = GPOINTER_TO_UINT (startup->hStdError);
907 in_fd = GPOINTER_TO_UINT (GetStdHandle (STD_INPUT_HANDLE));
908 out_fd = GPOINTER_TO_UINT (GetStdHandle (STD_OUTPUT_HANDLE));
909 err_fd = GPOINTER_TO_UINT (GetStdHandle (STD_ERROR_HANDLE));
912 g_strlcpy (process_handle.proc_name, prog,
913 _WAPI_PROC_NAME_MAX_LEN - 1);
915 process_set_defaults (&process_handle);
917 handle = _wapi_handle_new (WAPI_HANDLE_PROCESS, &process_handle);
918 if (handle == _WAPI_HANDLE_INVALID) {
919 g_warning ("%s: error creating process handle", __func__);
921 SetLastError (ERROR_PATH_NOT_FOUND);
925 /* Hold another reference so the process has somewhere to
926 * store its exit data even if we drop this handle
928 _wapi_handle_ref (handle);
930 /* new_environ is a block of NULL-terminated strings, which
931 * is itself NULL-terminated. Of course, passing an array of
932 * string pointers would have made things too easy :-(
934 * If new_environ is not NULL it specifies the entire set of
935 * environment variables in the new process. Otherwise the
936 * new process inherits the same environment.
938 if (new_environ != NULL) {
939 gunichar2 *new_environp;
941 /* Count the number of strings */
942 for (new_environp = (gunichar2 *)new_environ; *new_environp;
945 while (*new_environp) {
950 /* +2: one for the process handle value, and the last
953 env_strings = g_new0 (gchar *, env_count + 2);
955 /* Copy each environ string into 'strings' turning it
956 * into utf8 (or the requested encoding) at the same
960 for (new_environp = (gunichar2 *)new_environ; *new_environp;
962 env_strings[env_count] = mono_unicode_to_external (new_environp);
964 while (*new_environp) {
969 for (i = 0; environ[i] != NULL; i++) {
973 /* +2: one for the process handle value, and the last
976 env_strings = g_new0 (gchar *, env_count + 2);
978 /* Copy each environ string into 'strings' turning it
979 * into utf8 (or the requested encoding) at the same
983 for (i = 0; environ[i] != NULL; i++) {
984 env_strings[env_count] = g_strdup (environ[i]);
988 /* pass process handle info to the child, so it doesn't have
989 * to do an expensive search over the whole list
991 if (env_strings != NULL) {
992 struct _WapiHandleUnshared *handle_data;
993 struct _WapiHandle_shared_ref *ref;
995 handle_data = &_WAPI_PRIVATE_HANDLES(GPOINTER_TO_UINT(handle));
996 ref = &handle_data->u.shared;
998 env_strings[env_count] = g_strdup_printf ("_WAPI_PROCESS_HANDLE_OFFSET=%d", ref->offset);
1001 thr_ret = _wapi_handle_lock_shared_handles ();
1002 g_assert (thr_ret == 0);
1007 SetLastError (ERROR_OUTOFMEMORY);
1008 _wapi_handle_unref (handle);
1010 } else if (pid == 0) {
1013 if (_wapi_shm_disabled == FALSE) {
1014 /* Wait for the parent to finish setting up
1015 * the handle. The semaphore lock is safe
1016 * because the sem_undo structures of a
1017 * semaphore aren't inherited across a fork
1018 * (), but we can't do this if we're not using
1021 thr_ret = _wapi_handle_lock_shared_handles ();
1022 g_assert (thr_ret == 0);
1024 _wapi_handle_unlock_shared_handles ();
1027 /* should we detach from the process group? */
1029 /* Connect stdin, stdout and stderr */
1034 if (inherit_handles != TRUE) {
1035 /* FIXME: do something here */
1038 /* Close all file descriptors */
1039 for (i = getdtablesize () - 1; i > 2; i--) {
1044 g_message ("%s: exec()ing [%s] in dir [%s]", __func__, cmd,
1046 for (i = 0; argv[i] != NULL; i++) {
1047 g_message ("arg %d: [%s]", i, argv[i]);
1050 for (i = 0; env_strings[i] != NULL; i++) {
1051 g_message ("env %d: [%s]", i, env_strings[i]);
1056 if (dir != NULL && chdir (dir) == -1) {
1062 execve (argv[0], argv, env_strings);
1069 ret = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
1070 (gpointer *)&process_handle_data);
1072 g_warning ("%s: error looking up process handle %p", __func__,
1074 _wapi_handle_unref (handle);
1078 process_handle_data->id = pid;
1080 if (process_info != NULL) {
1081 process_info->hProcess = handle;
1082 process_info->dwProcessId = pid;
1084 /* FIXME: we might need to handle the thread info some
1087 process_info->hThread = INVALID_HANDLE_VALUE;
1088 process_info->dwThreadId = 0;
1092 _wapi_handle_unlock_shared_handles ();
1097 if (full_prog != NULL) {
1109 if(env_strings != NULL) {
1110 g_strfreev (env_strings);
1117 g_message ("%s: returning handle %p for pid %d", __func__, handle,
1124 static void process_set_name (struct _WapiHandle_process *process_handle)
1126 gchar *progname, *utf8_progname, *slash;
1128 progname=g_get_prgname ();
1129 utf8_progname=mono_utf8_from_external (progname);
1132 g_message ("%s: using [%s] as prog name", __func__, progname);
1135 if(utf8_progname!=NULL) {
1136 slash=strrchr (utf8_progname, '/');
1138 g_strlcpy (process_handle->proc_name, slash+1,
1139 _WAPI_PROC_NAME_MAX_LEN - 1);
1141 g_strlcpy (process_handle->proc_name, utf8_progname,
1142 _WAPI_PROC_NAME_MAX_LEN - 1);
1145 g_free (utf8_progname);
1149 extern void _wapi_time_t_to_filetime (time_t timeval, WapiFileTime *filetime);
1151 #if !GLIB_CHECK_VERSION (2,4,0)
1152 #define g_setenv(a,b,c) setenv(a,b,c)
1153 #define g_unsetenv(a) unsetenv(a)
1156 static void process_set_current (void)
1158 pid_t pid = _wapi_getpid ();
1159 const char *handle_env;
1160 struct _WapiHandle_process process_handle = {0};
1162 mono_once (&process_ops_once, process_ops_init);
1164 handle_env = g_getenv ("_WAPI_PROCESS_HANDLE_OFFSET");
1165 g_unsetenv ("_WAPI_PROCESS_HANDLE_OFFSET");
1167 if (handle_env != NULL) {
1168 struct _WapiHandle_process *process_handlep;
1169 gchar *procname = NULL;
1172 current_process = _wapi_handle_new_from_offset (WAPI_HANDLE_PROCESS, atoi (handle_env), TRUE);
1175 g_message ("%s: Found my process handle: %p (offset %d 0x%x)",
1176 __func__, current_process, atoi (handle_env),
1180 ok = _wapi_lookup_handle (current_process, WAPI_HANDLE_PROCESS,
1181 (gpointer *)&process_handlep);
1183 /* This test will probably break on linuxthreads, but
1184 * that should be ancient history on all distros we
1187 if (process_handlep->id == pid) {
1188 procname = process_handlep->proc_name;
1189 if (!strcmp (procname, "mono")) {
1190 /* Set a better process name */
1192 g_message ("%s: Setting better process name", __func__);
1195 process_set_name (process_handlep);
1198 g_message ("%s: Leaving process name: %s", __func__, procname);
1205 /* Wrong pid, so drop this handle and fall through to
1208 _wapi_handle_unref (current_process);
1212 /* We get here if the handle wasn't specified in the
1213 * environment, or if the process ID was wrong, or if the
1214 * handle lookup failed (eg if the parent process forked and
1215 * quit immediately, and deleted the shared data before the
1216 * child got a chance to attach it.)
1220 g_message ("%s: Need to create my own process handle", __func__);
1223 process_handle.id = pid;
1225 process_set_defaults (&process_handle);
1226 process_set_name (&process_handle);
1228 current_process = _wapi_handle_new (WAPI_HANDLE_PROCESS,
1230 if (current_process == _WAPI_HANDLE_INVALID) {
1231 g_warning ("%s: error creating process handle", __func__);
1236 gpointer _wapi_process_duplicate ()
1238 mono_once (&process_current_once, process_set_current);
1240 _wapi_handle_ref (current_process);
1242 return(current_process);
1245 /* Returns a pseudo handle that doesn't need to be closed afterwards */
1246 gpointer GetCurrentProcess (void)
1248 mono_once (&process_current_once, process_set_current);
1250 return(_WAPI_PROCESS_CURRENT);
1253 guint32 GetProcessId (gpointer handle)
1255 struct _WapiHandle_process *process_handle;
1258 ok = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
1259 (gpointer *)&process_handle);
1261 SetLastError (ERROR_INVALID_HANDLE);
1265 return (process_handle->id);
1268 guint32 GetCurrentProcessId (void)
1270 mono_once (&process_current_once, process_set_current);
1272 return (GetProcessId (current_process));
1275 /* Returns the process id as a convenience to the functions that call this */
1276 static pid_t signal_process_if_gone (gpointer handle)
1278 struct _WapiHandle_process *process_handle;
1281 /* Make sure the process is signalled if it has exited - if
1282 * the parent process didn't wait for it then it won't be
1284 ok = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
1285 (gpointer *)&process_handle);
1287 /* It's possible that the handle has vanished during
1288 * the _wapi_search_handle before it gets here, so
1289 * don't spam the console with warnings.
1291 /* g_warning ("%s: error looking up process handle %p",
1292 __func__, handle);*/
1298 g_message ("%s: looking at process %d", __func__, process_handle->id);
1301 if (kill (process_handle->id, 0) == -1 &&
1304 /* The process is dead, (EPERM tells us a new process
1305 * has that ID, but as it's owned by someone else it
1306 * can't be the one listed in our shared memory file)
1308 _wapi_shared_handle_set_signal_state (handle, TRUE);
1311 return (process_handle->id);
1314 static gboolean process_enum (gpointer handle, gpointer user_data)
1316 GArray *processes=user_data;
1317 pid_t pid = signal_process_if_gone (handle);
1324 /* Ignore processes that have already exited (ie they are signalled) */
1325 if (_wapi_handle_issignalled (handle) == FALSE) {
1327 g_message ("%s: process %d added to array", __func__, pid);
1330 /* This ensures that duplicates aren't returned (see
1331 * the comment above _wapi_search_handle () for why
1334 for (i = 0; i < processes->len; i++) {
1335 if (g_array_index (processes, pid_t, i) == pid) {
1336 /* We've already got this one, return
1337 * FALSE to keep searching
1343 g_array_append_val (processes, pid);
1346 /* Return false to keep searching */
1350 gboolean EnumProcesses (guint32 *pids, guint32 len, guint32 *needed)
1352 GArray *processes = g_array_new (FALSE, FALSE, sizeof(pid_t));
1355 mono_once (&process_current_once, process_set_current);
1357 _wapi_search_handle (WAPI_HANDLE_PROCESS, process_enum, processes,
1360 fit=len/sizeof(guint32);
1361 for (i = 0, j = 0; j < fit && i < processes->len; i++) {
1362 pids[j++] = g_array_index (processes, pid_t, i);
1365 g_array_free (processes, TRUE);
1367 *needed = j * sizeof(guint32);
1372 static gboolean process_open_compare (gpointer handle, gpointer user_data)
1375 pid_t checking_pid = signal_process_if_gone (handle);
1377 if (checking_pid == 0) {
1381 wanted_pid = GPOINTER_TO_UINT (user_data);
1383 /* It's possible to have more than one process handle with the
1384 * same pid, but only the one running process can be
1387 if (checking_pid == wanted_pid &&
1388 _wapi_handle_issignalled (handle) == FALSE) {
1389 /* If the handle is blown away in the window between
1390 * returning TRUE here and _wapi_search_handle pinging
1391 * the timestamp, the search will continue
1399 gpointer OpenProcess (guint32 access G_GNUC_UNUSED, gboolean inherit G_GNUC_UNUSED, guint32 pid)
1401 /* Find the process handle that corresponds to pid */
1404 mono_once (&process_current_once, process_set_current);
1407 g_message ("%s: looking for process %d", __func__, pid);
1410 handle = _wapi_search_handle (WAPI_HANDLE_PROCESS,
1411 process_open_compare,
1412 GUINT_TO_POINTER (pid), NULL, TRUE);
1415 g_message ("%s: Can't find pid %d", __func__, pid);
1418 SetLastError (ERROR_PROC_NOT_FOUND);
1423 _wapi_handle_ref (handle);
1428 gboolean GetExitCodeProcess (gpointer process, guint32 *code)
1430 struct _WapiHandle_process *process_handle;
1433 mono_once (&process_current_once, process_set_current);
1439 ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
1440 (gpointer *)&process_handle);
1443 g_message ("%s: Can't find process %p", __func__, process);
1449 /* A process handle is only signalled if the process has exited
1450 * and has been waited for */
1451 if (_wapi_handle_issignalled (process) == TRUE ||
1452 process_wait (process, 0) == WAIT_OBJECT_0) {
1453 *code = process_handle->exitstatus;
1455 *code = STILL_ACTIVE;
1461 gboolean GetProcessTimes (gpointer process, WapiFileTime *create_time,
1462 WapiFileTime *exit_time, WapiFileTime *kernel_time,
1463 WapiFileTime *user_time)
1465 struct _WapiHandle_process *process_handle;
1467 gboolean ku_times_set = FALSE;
1469 mono_once (&process_current_once, process_set_current);
1471 if(create_time==NULL || exit_time==NULL || kernel_time==NULL ||
1473 /* Not sure if w32 allows NULLs here or not */
1477 ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
1478 (gpointer *)&process_handle);
1481 g_message ("%s: Can't find process %p", __func__, process);
1487 *create_time=process_handle->create_time;
1489 /* A process handle is only signalled if the process has
1490 * exited. Otherwise exit_time isn't set
1492 if(_wapi_handle_issignalled (process)==TRUE) {
1493 *exit_time=process_handle->exit_time;
1496 #ifdef HAVE_GETRUSAGE
1497 if (process_handle->id == getpid ()) {
1498 struct rusage time_data;
1499 if (getrusage (RUSAGE_SELF, &time_data) == 0) {
1501 gint64 *tick_val_ptr;
1502 ku_times_set = TRUE;
1503 tick_val = time_data.ru_utime.tv_sec * 10000000 + time_data.ru_utime.tv_usec * 10;
1504 tick_val_ptr = (gint64*)user_time;
1505 *tick_val_ptr = tick_val;
1506 tick_val = time_data.ru_stime.tv_sec * 10000000 + time_data.ru_stime.tv_usec * 10;
1507 tick_val_ptr = (gint64*)kernel_time;
1508 *tick_val_ptr = tick_val;
1512 if (!ku_times_set) {
1513 memset (kernel_time, 0, sizeof (WapiFileTime));
1514 memset (user_time, 0, sizeof (WapiFileTime));
1520 gboolean EnumProcessModules (gpointer process, gpointer *modules,
1521 guint32 size, guint32 *needed)
1523 /* Store modules in an array of pointers (main module as
1524 * modules[0]), using the load address for each module as a
1525 * token. (Use 'NULL' as an alternative for the main module
1526 * so that the simple implementation can just return one item
1527 * for now.) Get the info from /proc/<pid>/maps on linux,
1528 * other systems will have to implement /dev/kmem reading or
1529 * whatever other horrid technique is needed.
1531 if(size<sizeof(gpointer)) {
1537 *needed=sizeof(gpointer);
1540 *needed=sizeof(gpointer);
1546 guint32 GetModuleBaseName (gpointer process, gpointer module,
1547 gunichar2 *basename, guint32 size)
1549 struct _WapiHandle_process *process_handle;
1552 mono_once (&process_current_once, process_set_current);
1555 g_message ("%s: Getting module base name, process handle %p module %p",
1556 __func__, process, module);
1559 if(basename==NULL || size==0) {
1563 ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
1564 (gpointer *)&process_handle);
1567 g_message ("%s: Can't find process %p", __func__, process);
1574 /* Shorthand for the main module, which has the
1575 * process name recorded in the handle data
1578 gunichar2 *procname;
1579 gchar *procname_utf8 = NULL;
1583 g_message ("%s: Returning main module name", __func__);
1586 pid=process_handle->id;
1587 procname_utf8 = process_handle->proc_name;
1590 g_message ("%s: Process name is [%s]", __func__,
1594 procname = g_utf8_to_utf16 (procname_utf8, -1, NULL, &len,
1596 if (procname == NULL) {
1601 /* Add the terminator, and convert chars to bytes */
1602 bytes = (len + 1) * 2;
1606 g_message ("%s: Size %d smaller than needed (%ld); truncating", __func__, size, bytes);
1609 memcpy (basename, procname, size);
1612 g_message ("%s: Size %d larger than needed (%ld)",
1613 __func__, size, bytes);
1616 memcpy (basename, procname, bytes);
1623 /* Look up the address in /proc/<pid>/maps */
1629 gboolean GetProcessWorkingSetSize (gpointer process, size_t *min, size_t *max)
1631 struct _WapiHandle_process *process_handle;
1634 mono_once (&process_current_once, process_set_current);
1636 if(min==NULL || max==NULL) {
1637 /* Not sure if w32 allows NULLs here or not */
1641 ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
1642 (gpointer *)&process_handle);
1645 g_message ("%s: Can't find process %p", __func__, process);
1651 *min=process_handle->min_working_set;
1652 *max=process_handle->max_working_set;
1657 gboolean SetProcessWorkingSetSize (gpointer process, size_t min, size_t max)
1659 struct _WapiHandle_process *process_handle;
1662 mono_once (&process_current_once, process_set_current);
1664 ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
1665 (gpointer *)&process_handle);
1668 g_message ("%s: Can't find process %p", __func__, process);
1674 process_handle->min_working_set=min;
1675 process_handle->max_working_set=max;
1682 TerminateProcess (gpointer process, gint32 exitCode)
1684 struct _WapiHandle_process *process_handle;
1689 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
1690 (gpointer *) &process_handle);
1694 g_message ("%s: Can't find process %p", __func__, process);
1696 SetLastError (ERROR_INVALID_HANDLE);
1700 signo = (exitCode == -1) ? SIGKILL : SIGTERM;
1701 ret = kill (process_handle->id, signo);
1705 SetLastError (ERROR_INVALID_PARAMETER);
1708 SetLastError (ERROR_ACCESS_DENIED);
1711 SetLastError (ERROR_PROC_NOT_FOUND);
1714 SetLastError (ERROR_GEN_FAILURE);
1722 GetPriorityClass (gpointer process)
1724 #ifdef HAVE_GETPRIORITY
1725 struct _WapiHandle_process *process_handle;
1729 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
1730 (gpointer *) &process_handle);
1733 SetLastError (ERROR_INVALID_HANDLE);
1738 ret = getpriority (PRIO_PROCESS, process_handle->id);
1739 if (ret == -1 && errno != 0) {
1743 SetLastError (ERROR_ACCESS_DENIED);
1746 SetLastError (ERROR_PROC_NOT_FOUND);
1749 SetLastError (ERROR_GEN_FAILURE);
1755 return NORMAL_PRIORITY_CLASS;
1757 return REALTIME_PRIORITY_CLASS;
1759 return HIGH_PRIORITY_CLASS;
1761 return ABOVE_NORMAL_PRIORITY_CLASS;
1763 return IDLE_PRIORITY_CLASS;
1765 return BELOW_NORMAL_PRIORITY_CLASS;
1767 return NORMAL_PRIORITY_CLASS;
1769 SetLastError (ERROR_NOT_SUPPORTED);
1775 SetPriorityClass (gpointer process, guint32 priority_class)
1777 #ifdef HAVE_SETPRIORITY
1778 struct _WapiHandle_process *process_handle;
1783 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
1784 (gpointer *) &process_handle);
1787 SetLastError (ERROR_INVALID_HANDLE);
1791 switch (priority_class) {
1792 case IDLE_PRIORITY_CLASS:
1795 case BELOW_NORMAL_PRIORITY_CLASS:
1798 case NORMAL_PRIORITY_CLASS:
1801 case ABOVE_NORMAL_PRIORITY_CLASS:
1804 case HIGH_PRIORITY_CLASS:
1807 case REALTIME_PRIORITY_CLASS:
1811 SetLastError (ERROR_INVALID_PARAMETER);
1815 ret = setpriority (PRIO_PROCESS, process_handle->id, prio);
1820 SetLastError (ERROR_ACCESS_DENIED);
1823 SetLastError (ERROR_PROC_NOT_FOUND);
1826 SetLastError (ERROR_GEN_FAILURE);
1832 SetLastError (ERROR_NOT_SUPPORTED);