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 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__)
40 #include <sys/sysctl.h>
41 # if !defined(__OpenBSD__)
42 # include <sys/utsname.h>
46 #ifdef PLATFORM_SOLARIS
47 /* procfs.h cannot be included if this define is set, but it seems to work fine if it is undefined */
48 #if _FILE_OFFSET_BITS == 64
49 #undef _FILE_OFFSET_BITS
51 #define _FILE_OFFSET_BITS 64
58 #include <KernelKit.h>
61 #include <mono/io-layer/wapi.h>
62 #include <mono/io-layer/wapi-private.h>
63 #include <mono/io-layer/handles-private.h>
64 #include <mono/io-layer/misc-private.h>
65 #include <mono/io-layer/mono-mutex.h>
66 #include <mono/io-layer/process-private.h>
67 #include <mono/io-layer/threads.h>
68 #include <mono/utils/strenc.h>
69 #include <mono/utils/mono-path.h>
70 #include <mono/io-layer/timefuncs-private.h>
72 /* The process' environment strings */
74 /* Apple defines this in crt_externs.h but doesn't provide that header for
75 * arm-apple-darwin9. We'll manually define the symbol on Apple as it does
76 * in fact exist on all implementations (so far)
78 gchar ***_NSGetEnviron(void);
79 #define environ (*_NSGetEnviron())
81 extern char **environ;
86 static guint32 process_wait (gpointer handle, guint32 timeout);
88 #if !defined(__OpenBSD__)
90 open_process_map (int pid, const char *mode);
93 struct _WapiHandleOps _wapi_process_ops = {
94 NULL, /* close_shared */
98 process_wait, /* special_wait */
102 static mono_once_t process_current_once=MONO_ONCE_INIT;
103 static gpointer current_process=NULL;
105 static mono_once_t process_ops_once=MONO_ONCE_INIT;
107 static void process_ops_init (void)
109 _wapi_handle_register_capabilities (WAPI_HANDLE_PROCESS,
110 WAPI_HANDLE_CAP_WAIT |
111 WAPI_HANDLE_CAP_SPECIAL_WAIT);
114 static gboolean process_set_termination_details (gpointer handle, int status)
116 struct _WapiHandle_process *process_handle;
120 g_assert ((GPOINTER_TO_UINT (handle) & _WAPI_PROCESS_UNHANDLED) != _WAPI_PROCESS_UNHANDLED);
122 ok = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
123 (gpointer *)&process_handle);
125 g_warning ("%s: error looking up process handle %p",
130 thr_ret = _wapi_handle_lock_shared_handles ();
131 g_assert (thr_ret == 0);
133 if (WIFSIGNALED(status)) {
134 process_handle->exitstatus = 128 + WTERMSIG(status);
136 process_handle->exitstatus = WEXITSTATUS(status);
138 _wapi_time_t_to_filetime (time(NULL), &process_handle->exit_time);
140 /* Don't set process_handle->waited here, it needs to only
141 * happen in the parent when wait() has been called.
145 g_message ("%s: Setting handle %p pid %d signalled, exit status %d",
146 __func__, handle, process_handle->id,
147 process_handle->exitstatus);
150 _wapi_shared_handle_set_signal_state (handle, TRUE);
152 _wapi_handle_unlock_shared_handles ();
154 /* Drop the reference we hold so we have somewhere to store
155 * the exit details, now the process has in fact exited
157 _wapi_handle_unref (handle);
162 /* See if any child processes have terminated and wait() for them,
163 * updating process handle info. This function is called from the
164 * collection thread every few seconds.
166 static gboolean waitfor_pid (gpointer test, gpointer user_data)
168 struct _WapiHandle_process *process;
173 g_assert ((GPOINTER_TO_UINT (test) & _WAPI_PROCESS_UNHANDLED) != _WAPI_PROCESS_UNHANDLED);
175 ok = _wapi_lookup_handle (test, WAPI_HANDLE_PROCESS,
176 (gpointer *)&process);
178 /* The handle must have been too old and was reaped */
182 if (process->waited) {
183 /* We've already done this one */
188 ret = waitpid (process->id, &status, WNOHANG);
189 } while (errno == EINTR);
192 /* Process not ready for wait */
194 g_message ("%s: Process %d not ready for waiting for: %s",
195 __func__, process->id, g_strerror (errno));
202 g_message ("%s: Process %d finished", __func__, ret);
205 process->waited = TRUE;
207 *(int *)user_data = status;
212 void _wapi_process_reap (void)
218 g_message ("%s: Reaping child processes", __func__);
222 proc = _wapi_search_handle (WAPI_HANDLE_PROCESS, waitfor_pid,
223 &status, NULL, FALSE);
226 g_message ("%s: process handle %p exit code %d",
227 __func__, proc, status);
230 process_set_termination_details (proc, status);
232 /* _wapi_search_handle adds a reference, so
235 _wapi_handle_unref (proc);
237 } while (proc != NULL);
240 /* Limitations: This can only wait for processes that are our own
241 * children. Fixing this means resurrecting a daemon helper to manage
244 static guint32 process_wait (gpointer handle, guint32 timeout)
246 struct _WapiHandle_process *process_handle;
251 g_assert ((GPOINTER_TO_UINT (handle) & _WAPI_PROCESS_UNHANDLED) != _WAPI_PROCESS_UNHANDLED);
254 g_message ("%s: Waiting for process %p", __func__, handle);
257 ok = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
258 (gpointer *)&process_handle);
260 g_warning ("%s: error looking up process handle %p", __func__,
265 if (process_handle->waited) {
266 /* We've already done this one */
268 g_message ("%s: Process %p already signalled", __func__,
272 return (WAIT_OBJECT_0);
275 pid = process_handle->id;
278 g_message ("%s: PID is %d, timeout %d", __func__, pid, timeout);
281 if (timeout == INFINITE) {
282 if (pid == _wapi_getpid ()) {
287 while ((ret = waitpid (pid, &status, 0)) != pid) {
288 if (ret == (pid_t)-1 && errno != EINTR) {
293 } else if (timeout == 0) {
295 ret = waitpid (pid, &status, WNOHANG);
297 return (WAIT_TIMEOUT);
301 if (pid == _wapi_getpid ()) {
303 return(WAIT_TIMEOUT);
306 ret = waitpid (pid, &status, WNOHANG);
308 g_message ("%s: waitpid returns: %d, timeout is %d", __func__, ret, timeout);
313 } else if (ret == (pid_t)-1 &&
316 g_message ("%s: waitpid failure: %s",
321 if (errno == ECHILD &&
322 process_handle->waited) {
324 * process reaper must
328 g_message ("%s: Process %p already reaped", __func__, handle);
331 return(WAIT_OBJECT_0);
337 _wapi_handle_spin (100);
339 } while (timeout > 0);
343 return(WAIT_TIMEOUT);
347 /* Process must have exited */
349 g_message ("%s: Wait done, status %d", __func__, status);
352 ok = process_set_termination_details (handle, status);
354 SetLastError (ERROR_OUTOFMEMORY);
355 return (WAIT_FAILED);
357 process_handle->waited = TRUE;
359 return(WAIT_OBJECT_0);
362 void _wapi_process_signal_self ()
364 if (current_process != NULL) {
365 process_set_termination_details (current_process, 0);
369 static void process_set_defaults (struct _WapiHandle_process *process_handle)
371 /* These seem to be the defaults on w2k */
372 process_handle->min_working_set = 204800;
373 process_handle->max_working_set = 1413120;
375 process_handle->waited = FALSE;
377 _wapi_time_t_to_filetime (time (NULL), &process_handle->create_time);
381 len16 (const gunichar2 *str)
392 utf16_concat (const gunichar2 *first, ...)
399 va_start (args, first);
400 total += len16 (first);
401 for (s = va_arg (args, gunichar2 *); s != NULL; s = va_arg(args, gunichar2 *)){
406 ret = g_new (gunichar2, total + 1);
412 for (s = first; *s != 0; s++)
414 va_start (args, first);
415 for (s = va_arg (args, gunichar2 *); s != NULL; s = va_arg (args, gunichar2 *)){
418 for (p = s; *p != 0; p++)
426 #ifdef PLATFORM_MACOSX
428 /* 0 = no detection; -1 = not 10.5 or higher; 1 = 10.5 or higher */
429 static int osx_10_5_or_higher;
432 detect_osx_10_5_or_higher (void)
438 if (uname (&u) != 0){
439 osx_10_5_or_higher = 1;
447 osx_10_5_or_higher = -1;
449 osx_10_5_or_higher = 1;
453 is_macos_10_5_or_higher (void)
455 if (osx_10_5_or_higher == 0)
456 detect_osx_10_5_or_higher ();
458 return (osx_10_5_or_higher == 1);
462 static const gunichar2 utf16_space_bytes [2] = { 0x20, 0 };
463 static const gunichar2 *utf16_space = utf16_space_bytes;
464 static const gunichar2 utf16_quote_bytes [2] = { 0x22, 0 };
465 static const gunichar2 *utf16_quote = utf16_quote_bytes;
470 print_utf16 (gunichar2 *str)
474 res = g_utf16_to_utf8 (str, -1, NULL, NULL, NULL);
475 g_print ("%s\n", res);
480 /* Implemented as just a wrapper around CreateProcess () */
481 gboolean ShellExecuteEx (WapiShellExecuteInfo *sei)
484 WapiProcessInformation process_info;
488 /* w2k just segfaults here, but we can do better than
491 SetLastError (ERROR_INVALID_PARAMETER);
495 if (sei->lpFile == NULL) {
496 /* w2k returns TRUE for this, for some reason. */
500 /* Put both executable and parameters into the second argument
501 * to CreateProcess (), so it searches $PATH. The conversion
502 * into and back out of utf8 is because there is no
503 * g_strdup_printf () equivalent for gunichar2 :-(
505 args = utf16_concat (utf16_quote, sei->lpFile, utf16_quote, sei->lpParameters == NULL ? NULL : utf16_space, sei->lpParameters, NULL);
507 SetLastError (ERROR_INVALID_DATA);
510 ret = CreateProcess (NULL, args, NULL, NULL, TRUE,
511 CREATE_UNICODE_ENVIRONMENT, NULL,
512 sei->lpDirectory, NULL, &process_info);
515 if (!ret && GetLastError () == ERROR_OUTOFMEMORY)
519 static char *handler;
520 static gunichar2 *handler_utf16;
522 if (handler_utf16 == (gunichar2 *)-1)
525 #ifdef PLATFORM_MACOSX
526 if (is_macos_10_5_or_higher ())
527 handler = g_strdup ("/usr/bin/open -W");
529 handler = g_strdup ("/usr/bin/open");
532 * On Linux, try: xdg-open, the FreeDesktop standard way of doing it,
533 * if that fails, try to use gnome-open, then kfmclient
535 handler = g_find_program_in_path ("xdg-open");
536 if (handler == NULL){
537 handler = g_find_program_in_path ("gnome-open");
538 if (handler == NULL){
539 handler = g_find_program_in_path ("kfmclient");
540 if (handler == NULL){
541 handler_utf16 = (gunichar2 *) -1;
544 /* kfmclient needs exec argument */
546 handler = g_strconcat (old, " exec",
553 handler_utf16 = g_utf8_to_utf16 (handler, -1, NULL, NULL, NULL);
556 /* Put quotes around the filename, in case it's a url
557 * that contains #'s (CreateProcess() calls
558 * g_shell_parse_argv(), which deliberately throws
559 * away anything after an unquoted #). Fixes bug
562 args = utf16_concat (handler_utf16, utf16_space, utf16_quote,
563 sei->lpFile, utf16_quote,
564 sei->lpParameters == NULL ? NULL : utf16_space,
565 sei->lpParameters, NULL);
567 SetLastError (ERROR_INVALID_DATA);
570 ret = CreateProcess (NULL, args, NULL, NULL, TRUE,
571 CREATE_UNICODE_ENVIRONMENT, NULL,
572 sei->lpDirectory, NULL, &process_info);
575 SetLastError (ERROR_INVALID_DATA);
580 if (sei->fMask & SEE_MASK_NOCLOSEPROCESS) {
581 sei->hProcess = process_info.hProcess;
583 CloseHandle (process_info.hProcess);
590 is_managed_binary (const gchar *filename)
592 int original_errno = errno;
593 #if defined(HAVE_LARGE_FILE_SUPPORT) && defined(O_LARGEFILE)
594 int file = open (filename, O_RDONLY | O_LARGEFILE);
596 int file = open (filename, O_RDONLY);
599 unsigned char buffer[8];
600 off_t file_size, optional_header_offset;
601 off_t pe_header_offset;
602 gboolean managed = FALSE;
604 guint32 first_word, second_word;
606 /* If we are unable to open the file, then we definitely
607 * can't say that it is managed. The child mono process
608 * probably wouldn't be able to open it anyway.
611 errno = original_errno;
615 /* Retrieve the length of the file for future sanity checks. */
616 file_size = lseek (file, 0, SEEK_END);
617 lseek (file, 0, SEEK_SET);
619 /* We know we need to read a header field at offset 60. */
623 num_read = read (file, buffer, 2);
625 if ((num_read != 2) || (buffer[0] != 'M') || (buffer[1] != 'Z'))
628 new_offset = lseek (file, 60, SEEK_SET);
630 if (new_offset != 60)
633 num_read = read (file, buffer, 4);
637 pe_header_offset = buffer[0]
642 if (pe_header_offset + 24 > file_size)
645 new_offset = lseek (file, pe_header_offset, SEEK_SET);
647 if (new_offset != pe_header_offset)
650 num_read = read (file, buffer, 4);
652 if ((num_read != 4) || (buffer[0] != 'P') || (buffer[1] != 'E') || (buffer[2] != 0) || (buffer[3] != 0))
656 * Verify that the header we want in the optional header data
657 * is present in this binary.
659 new_offset = lseek (file, pe_header_offset + 20, SEEK_SET);
661 if (new_offset != pe_header_offset + 20)
664 num_read = read (file, buffer, 2);
666 if ((num_read != 2) || ((buffer[0] | (buffer[1] << 8)) < 216))
669 /* Read the CLR header address and size fields. These will be
670 * zero if the binary is not managed.
672 optional_header_offset = pe_header_offset + 24;
673 new_offset = lseek (file, optional_header_offset + 208, SEEK_SET);
675 if (new_offset != optional_header_offset + 208)
678 num_read = read (file, buffer, 8);
680 /* We are not concerned with endianness, only with
681 * whether it is zero or not.
683 first_word = *(guint32 *)&buffer[0];
684 second_word = *(guint32 *)&buffer[4];
686 if ((num_read != 8) || (first_word == 0) || (second_word == 0))
693 errno = original_errno;
697 gboolean CreateProcessWithLogonW (const gunichar2 *username,
698 const gunichar2 *domain,
699 const gunichar2 *password,
700 const guint32 logonFlags,
701 const gunichar2 *appname,
702 const gunichar2 *cmdline,
703 guint32 create_flags,
705 const gunichar2 *cwd,
706 WapiStartupInfo *startup,
707 WapiProcessInformation *process_info)
709 /* FIXME: use user information */
710 return CreateProcess (appname, cmdline, NULL, NULL, FALSE, create_flags, env, cwd, startup, process_info);
714 is_executable (const char *prog)
717 if (access (prog, X_OK) != 0)
719 if (stat (prog, &buf))
721 if (S_ISREG (buf.st_mode))
726 gboolean CreateProcess (const gunichar2 *appname, const gunichar2 *cmdline,
727 WapiSecurityAttributes *process_attrs G_GNUC_UNUSED,
728 WapiSecurityAttributes *thread_attrs G_GNUC_UNUSED,
729 gboolean inherit_handles, guint32 create_flags,
730 gpointer new_environ, const gunichar2 *cwd,
731 WapiStartupInfo *startup,
732 WapiProcessInformation *process_info)
734 gchar *cmd=NULL, *prog = NULL, *full_prog = NULL, *args = NULL, *args_after_prog = NULL, *dir = NULL, **env_strings = NULL, **argv = NULL;
735 guint32 i, env_count = 0;
736 gboolean ret = FALSE;
738 struct _WapiHandle_process process_handle = {0}, *process_handle_data;
740 int in_fd, out_fd, err_fd;
744 mono_once (&process_ops_once, process_ops_init);
746 /* appname and cmdline specify the executable and its args:
748 * If appname is not NULL, it is the name of the executable.
749 * Otherwise the executable is the first token in cmdline.
751 * Executable searching:
753 * If appname is not NULL, it can specify the full path and
754 * file name, or else a partial name and the current directory
755 * will be used. There is no additional searching.
757 * If appname is NULL, the first whitespace-delimited token in
758 * cmdline is used. If the name does not contain a full
759 * directory path, the search sequence is:
761 * 1) The directory containing the current process
762 * 2) The current working directory
763 * 3) The windows system directory (Ignored)
764 * 4) The windows directory (Ignored)
767 * Just to make things more interesting, tokens can contain
768 * white space if they are surrounded by quotation marks. I'm
769 * beginning to understand just why windows apps are generally
770 * so crap, with an API like this :-(
772 if (appname != NULL) {
773 cmd = mono_unicode_to_external (appname);
776 g_message ("%s: unicode conversion returned NULL",
780 SetLastError (ERROR_PATH_NOT_FOUND);
784 /* Turn all the slashes round the right way */
785 for (i = 0; i < strlen (cmd); i++) {
786 if (cmd[i] == '\\') {
792 if (cmdline != NULL) {
793 args = mono_unicode_to_external (cmdline);
796 g_message ("%s: unicode conversion returned NULL", __func__);
799 SetLastError (ERROR_PATH_NOT_FOUND);
805 dir = mono_unicode_to_external (cwd);
808 g_message ("%s: unicode conversion returned NULL", __func__);
811 SetLastError (ERROR_PATH_NOT_FOUND);
815 /* Turn all the slashes round the right way */
816 for (i = 0; i < strlen (dir); i++) {
817 if (dir[i] == '\\') {
824 /* We can't put off locating the executable any longer :-( */
827 if (g_ascii_isalpha (cmd[0]) && (cmd[1] == ':')) {
828 /* Strip off the drive letter. I can't
829 * believe that CP/M holdover is still
832 g_memmove (cmd, cmd+2, strlen (cmd)-2);
833 cmd[strlen (cmd)-2] = '\0';
836 unquoted = g_shell_unquote (cmd, NULL);
837 if (unquoted[0] == '/') {
838 /* Assume full path given */
839 prog = g_strdup (unquoted);
841 /* Executable existing ? */
842 if (!is_executable (prog)) {
844 g_message ("%s: Couldn't find executable %s",
848 SetLastError (ERROR_FILE_NOT_FOUND);
852 /* Search for file named by cmd in the current
855 char *curdir = g_get_current_dir ();
857 prog = g_strdup_printf ("%s/%s", curdir, unquoted);
860 /* And make sure it's executable */
861 if (!is_executable (prog)) {
863 g_message ("%s: Couldn't find executable %s",
867 SetLastError (ERROR_FILE_NOT_FOUND);
873 args_after_prog = args;
879 /* Dig out the first token from args, taking quotation
883 /* First, strip off all leading whitespace */
884 args = g_strchug (args);
886 /* args_after_prog points to the contents of args
887 * after token has been set (otherwise argv[0] is
890 args_after_prog = args;
892 /* Assume the opening quote will always be the first
895 if (args[0] == '\"' || args [0] == '\'') {
897 for (i = 1; args[i] != '\0' && args[i] != quote; i++);
898 if (args [i + 1] == '\0' || g_ascii_isspace (args[i+1])) {
899 /* We found the first token */
900 token = g_strndup (args+1, i-1);
901 args_after_prog = g_strchug (args + i + 1);
903 /* Quotation mark appeared in the
904 * middle of the token. Just give the
905 * whole first token, quotes and all,
912 /* No quote mark, or malformed */
913 for (i = 0; args[i] != '\0'; i++) {
914 if (g_ascii_isspace (args[i])) {
915 token = g_strndup (args, i);
916 args_after_prog = args + i + 1;
922 if (token == NULL && args[0] != '\0') {
923 /* Must be just one token in the string */
924 token = g_strdup (args);
925 args_after_prog = NULL;
931 g_message ("%s: Couldn't find what to exec", __func__);
934 SetLastError (ERROR_PATH_NOT_FOUND);
938 /* Turn all the slashes round the right way. Only for
941 token_len = strlen (token);
942 for (i = 0; i < token_len; i++) {
943 if (token[i] == '\\') {
948 if (g_ascii_isalpha (token[0]) && (token[1] == ':')) {
949 /* Strip off the drive letter. I can't
950 * believe that CP/M holdover is still
953 g_memmove (token, token+2, strlen (token)-2);
954 token[strlen (token)-2] = '\0';
957 if (token[0] == '/') {
958 /* Assume full path given */
959 prog = g_strdup (token);
961 /* Executable existing ? */
962 if (!is_executable (prog)) {
964 g_message ("%s: Couldn't find executable %s",
968 SetLastError (ERROR_FILE_NOT_FOUND);
973 char *curdir = g_get_current_dir ();
975 /* FIXME: Need to record the directory
976 * containing the current process, and check
977 * that for the new executable as the first
981 prog = g_strdup_printf ("%s/%s", curdir, token);
984 /* I assume X_OK is the criterion to use,
987 if (!is_executable (prog)) {
989 prog = g_find_program_in_path (token);
992 g_message ("%s: Couldn't find executable %s", __func__, token);
996 SetLastError (ERROR_FILE_NOT_FOUND);
1006 g_message ("%s: Exec prog [%s] args [%s]", __func__, prog,
1010 /* Check for CLR binaries; if found, we will try to invoke
1011 * them using the same mono binary that started us.
1013 if (is_managed_binary (prog)) {
1014 gunichar2 *newapp, *newcmd;
1015 gsize bytes_ignored;
1017 newapp = mono_unicode_from_external ("mono", &bytes_ignored);
1019 if (newapp != NULL) {
1020 if (appname != NULL) {
1021 newcmd = utf16_concat (newapp, utf16_space,
1022 appname, utf16_space,
1025 newcmd = utf16_concat (newapp, utf16_space,
1029 g_free ((gunichar2 *)newapp);
1031 if (newcmd != NULL) {
1032 ret = CreateProcess (NULL, newcmd,
1036 create_flags, new_environ,
1040 g_free ((gunichar2 *)newcmd);
1047 if (args_after_prog != NULL && *args_after_prog) {
1050 qprog = g_shell_quote (prog);
1051 full_prog = g_strconcat (qprog, " ", args_after_prog, NULL);
1054 full_prog = g_shell_quote (prog);
1057 ret = g_shell_parse_argv (full_prog, NULL, &argv, &gerr);
1059 g_message ("CreateProcess: %s\n", gerr->message);
1060 g_error_free (gerr);
1065 if (startup != NULL && startup->dwFlags & STARTF_USESTDHANDLES) {
1066 in_fd = GPOINTER_TO_UINT (startup->hStdInput);
1067 out_fd = GPOINTER_TO_UINT (startup->hStdOutput);
1068 err_fd = GPOINTER_TO_UINT (startup->hStdError);
1070 in_fd = GPOINTER_TO_UINT (GetStdHandle (STD_INPUT_HANDLE));
1071 out_fd = GPOINTER_TO_UINT (GetStdHandle (STD_OUTPUT_HANDLE));
1072 err_fd = GPOINTER_TO_UINT (GetStdHandle (STD_ERROR_HANDLE));
1075 g_strlcpy (process_handle.proc_name, prog,
1076 _WAPI_PROC_NAME_MAX_LEN - 1);
1078 process_set_defaults (&process_handle);
1080 handle = _wapi_handle_new (WAPI_HANDLE_PROCESS, &process_handle);
1081 if (handle == _WAPI_HANDLE_INVALID) {
1082 g_warning ("%s: error creating process handle", __func__);
1085 SetLastError (ERROR_OUTOFMEMORY);
1089 /* Hold another reference so the process has somewhere to
1090 * store its exit data even if we drop this handle
1092 _wapi_handle_ref (handle);
1094 /* new_environ is a block of NULL-terminated strings, which
1095 * is itself NULL-terminated. Of course, passing an array of
1096 * string pointers would have made things too easy :-(
1098 * If new_environ is not NULL it specifies the entire set of
1099 * environment variables in the new process. Otherwise the
1100 * new process inherits the same environment.
1102 if (new_environ != NULL) {
1103 gunichar2 *new_environp;
1105 /* Count the number of strings */
1106 for (new_environp = (gunichar2 *)new_environ; *new_environp;
1109 while (*new_environp) {
1114 /* +2: one for the process handle value, and the last
1117 env_strings = g_new0 (gchar *, env_count + 2);
1119 /* Copy each environ string into 'strings' turning it
1120 * into utf8 (or the requested encoding) at the same
1124 for (new_environp = (gunichar2 *)new_environ; *new_environp;
1126 env_strings[env_count] = mono_unicode_to_external (new_environp);
1128 while (*new_environp) {
1133 for (i = 0; environ[i] != NULL; i++) {
1137 /* +2: one for the process handle value, and the last
1140 env_strings = g_new0 (gchar *, env_count + 2);
1142 /* Copy each environ string into 'strings' turning it
1143 * into utf8 (or the requested encoding) at the same
1147 for (i = 0; environ[i] != NULL; i++) {
1148 env_strings[env_count] = g_strdup (environ[i]);
1152 /* pass process handle info to the child, so it doesn't have
1153 * to do an expensive search over the whole list
1155 if (env_strings != NULL) {
1156 struct _WapiHandleUnshared *handle_data;
1157 struct _WapiHandle_shared_ref *ref;
1159 handle_data = &_WAPI_PRIVATE_HANDLES(GPOINTER_TO_UINT(handle));
1160 ref = &handle_data->u.shared;
1162 env_strings[env_count] = g_strdup_printf ("_WAPI_PROCESS_HANDLE_OFFSET=%d", ref->offset);
1165 thr_ret = _wapi_handle_lock_shared_handles ();
1166 g_assert (thr_ret == 0);
1171 SetLastError (ERROR_OUTOFMEMORY);
1172 _wapi_handle_unref (handle);
1174 } else if (pid == 0) {
1177 if (_wapi_shm_disabled == FALSE) {
1178 /* Wait for the parent to finish setting up
1179 * the handle. The semaphore lock is safe
1180 * because the sem_undo structures of a
1181 * semaphore aren't inherited across a fork
1182 * (), but we can't do this if we're not using
1185 thr_ret = _wapi_handle_lock_shared_handles ();
1186 g_assert (thr_ret == 0);
1188 _wapi_handle_unlock_shared_handles ();
1191 /* should we detach from the process group? */
1193 /* Connect stdin, stdout and stderr */
1198 if (inherit_handles != TRUE) {
1199 /* FIXME: do something here */
1202 /* Close all file descriptors */
1203 for (i = getdtablesize () - 1; i > 2; i--) {
1208 g_message ("%s: exec()ing [%s] in dir [%s]", __func__, cmd,
1210 for (i = 0; argv[i] != NULL; i++) {
1211 g_message ("arg %d: [%s]", i, argv[i]);
1214 for (i = 0; env_strings[i] != NULL; i++) {
1215 g_message ("env %d: [%s]", i, env_strings[i]);
1220 if (dir != NULL && chdir (dir) == -1) {
1226 execve (argv[0], argv, env_strings);
1233 ret = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
1234 (gpointer *)&process_handle_data);
1236 g_warning ("%s: error looking up process handle %p", __func__,
1238 _wapi_handle_unref (handle);
1242 process_handle_data->id = pid;
1244 if (process_info != NULL) {
1245 process_info->hProcess = handle;
1246 process_info->dwProcessId = pid;
1248 /* FIXME: we might need to handle the thread info some
1251 process_info->hThread = INVALID_HANDLE_VALUE;
1252 process_info->dwThreadId = 0;
1256 _wapi_handle_unlock_shared_handles ();
1262 if (full_prog != NULL) {
1274 if(env_strings != NULL) {
1275 g_strfreev (env_strings);
1282 g_message ("%s: returning handle %p for pid %d", __func__, handle,
1289 static void process_set_name (struct _WapiHandle_process *process_handle)
1291 gchar *progname, *utf8_progname, *slash;
1293 progname=g_get_prgname ();
1294 utf8_progname=mono_utf8_from_external (progname);
1297 g_message ("%s: using [%s] as prog name", __func__, progname);
1300 if(utf8_progname!=NULL) {
1301 slash=strrchr (utf8_progname, '/');
1303 g_strlcpy (process_handle->proc_name, slash+1,
1304 _WAPI_PROC_NAME_MAX_LEN - 1);
1306 g_strlcpy (process_handle->proc_name, utf8_progname,
1307 _WAPI_PROC_NAME_MAX_LEN - 1);
1310 g_free (utf8_progname);
1314 extern void _wapi_time_t_to_filetime (time_t timeval, WapiFileTime *filetime);
1316 #if !GLIB_CHECK_VERSION (2,4,0)
1317 #define g_setenv(a,b,c) setenv(a,b,c)
1318 #define g_unsetenv(a) unsetenv(a)
1321 static void process_set_current (void)
1323 pid_t pid = _wapi_getpid ();
1324 const char *handle_env;
1325 struct _WapiHandle_process process_handle = {0};
1327 mono_once (&process_ops_once, process_ops_init);
1329 handle_env = g_getenv ("_WAPI_PROCESS_HANDLE_OFFSET");
1330 g_unsetenv ("_WAPI_PROCESS_HANDLE_OFFSET");
1332 if (handle_env != NULL) {
1333 struct _WapiHandle_process *process_handlep;
1334 gchar *procname = NULL;
1337 current_process = _wapi_handle_new_from_offset (WAPI_HANDLE_PROCESS, atoi (handle_env), TRUE);
1340 g_message ("%s: Found my process handle: %p (offset %d 0x%x)",
1341 __func__, current_process, atoi (handle_env),
1345 ok = _wapi_lookup_handle (current_process, WAPI_HANDLE_PROCESS,
1346 (gpointer *)&process_handlep);
1348 /* This test will probably break on linuxthreads, but
1349 * that should be ancient history on all distros we
1352 if (process_handlep->id == pid) {
1353 procname = process_handlep->proc_name;
1354 if (!strcmp (procname, "mono")) {
1355 /* Set a better process name */
1357 g_message ("%s: Setting better process name", __func__);
1360 process_set_name (process_handlep);
1363 g_message ("%s: Leaving process name: %s", __func__, procname);
1370 /* Wrong pid, so drop this handle and fall through to
1373 _wapi_handle_unref (current_process);
1377 /* We get here if the handle wasn't specified in the
1378 * environment, or if the process ID was wrong, or if the
1379 * handle lookup failed (eg if the parent process forked and
1380 * quit immediately, and deleted the shared data before the
1381 * child got a chance to attach it.)
1385 g_message ("%s: Need to create my own process handle", __func__);
1388 process_handle.id = pid;
1390 process_set_defaults (&process_handle);
1391 process_set_name (&process_handle);
1393 current_process = _wapi_handle_new (WAPI_HANDLE_PROCESS,
1395 if (current_process == _WAPI_HANDLE_INVALID) {
1396 g_warning ("%s: error creating process handle", __func__);
1401 gpointer _wapi_process_duplicate ()
1403 mono_once (&process_current_once, process_set_current);
1405 _wapi_handle_ref (current_process);
1407 return(current_process);
1410 /* Returns a pseudo handle that doesn't need to be closed afterwards */
1411 gpointer GetCurrentProcess (void)
1413 mono_once (&process_current_once, process_set_current);
1415 return(_WAPI_PROCESS_CURRENT);
1418 guint32 GetProcessId (gpointer handle)
1420 struct _WapiHandle_process *process_handle;
1423 if ((GPOINTER_TO_UINT (handle) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
1424 /* This is a pseudo handle */
1425 return(GPOINTER_TO_UINT (handle) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
1428 ok = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
1429 (gpointer *)&process_handle);
1431 SetLastError (ERROR_INVALID_HANDLE);
1435 return (process_handle->id);
1438 guint32 GetCurrentProcessId (void)
1440 mono_once (&process_current_once, process_set_current);
1442 return (GetProcessId (current_process));
1445 /* Returns the process id as a convenience to the functions that call this */
1446 static pid_t signal_process_if_gone (gpointer handle)
1448 struct _WapiHandle_process *process_handle;
1451 g_assert ((GPOINTER_TO_UINT (handle) & _WAPI_PROCESS_UNHANDLED) != _WAPI_PROCESS_UNHANDLED);
1453 /* Make sure the process is signalled if it has exited - if
1454 * the parent process didn't wait for it then it won't be
1456 ok = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
1457 (gpointer *)&process_handle);
1459 /* It's possible that the handle has vanished during
1460 * the _wapi_search_handle before it gets here, so
1461 * don't spam the console with warnings.
1463 /* g_warning ("%s: error looking up process handle %p",
1464 __func__, handle);*/
1470 g_message ("%s: looking at process %d", __func__, process_handle->id);
1473 if (kill (process_handle->id, 0) == -1 &&
1476 /* The process is dead, (EPERM tells us a new process
1477 * has that ID, but as it's owned by someone else it
1478 * can't be the one listed in our shared memory file)
1480 _wapi_shared_handle_set_signal_state (handle, TRUE);
1483 return (process_handle->id);
1487 static gboolean process_enum (gpointer handle, gpointer user_data)
1489 GArray *processes=user_data;
1490 pid_t pid = signal_process_if_gone (handle);
1497 /* Ignore processes that have already exited (ie they are signalled) */
1498 if (_wapi_handle_issignalled (handle) == FALSE) {
1500 g_message ("%s: process %d added to array", __func__, pid);
1503 /* This ensures that duplicates aren't returned (see
1504 * the comment above _wapi_search_handle () for why
1507 for (i = 0; i < processes->len; i++) {
1508 if (g_array_index (processes, pid_t, i) == pid) {
1509 /* We've already got this one, return
1510 * FALSE to keep searching
1516 g_array_append_val (processes, pid);
1519 /* Return false to keep searching */
1522 #endif /* UNUSED_CODE */
1524 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__)
1526 gboolean EnumProcesses (guint32 *pids, guint32 len, guint32 *needed)
1528 guint32 count, fit, i, j;
1531 size_t proclength, size;
1532 #if defined(__OpenBSD__)
1533 struct kinfo_proc2 *result;
1536 name[1] = KERN_PROC2;
1537 name[2] = KERN_PROC_ALL;
1539 name[4] = sizeof(struct kinfo_proc2);
1542 struct kinfo_proc *result;
1543 static const int name[] = { CTL_KERN, KERN_PROC, KERN_PROC_ALL, 0 };
1546 mono_once (&process_current_once, process_set_current);
1553 #if defined(__OpenBSD__)
1554 size = (sizeof(name) / sizeof(*name));
1556 size = (sizeof(name) / sizeof(*name)) - 1;
1558 err = sysctl ((int *)name, size, NULL, &proclength, NULL, 0);
1561 result = malloc (proclength);
1566 #if defined(__OpenBSD__)
1567 name[5] = (int)(proclength / sizeof(struct kinfo_proc2));
1570 err = sysctl ((int *) name, size, result, &proclength, NULL, 0);
1577 } while (err == 0 && !done);
1580 if (result != NULL) {
1587 #if defined(__OpenBSD__)
1588 count = proclength / sizeof(struct kinfo_proc2);
1590 count = proclength / sizeof(struct kinfo_proc);
1592 fit = len / sizeof(guint32);
1593 for (i = 0, j = 0; j< fit && i < count; i++) {
1594 #if defined(__OpenBSD__)
1595 pids [j++] = result [i].p_pid;
1597 pids [j++] = result [i].kp_proc.p_pid;
1602 *needed = j * sizeof(guint32);
1606 #elif defined(__HAIKU__)
1608 gboolean EnumProcesses (guint32 *pids, guint32 len, guint32 *needed)
1614 mono_once (&process_current_once, process_set_current);
1616 fit = len / sizeof (guint32);
1617 while (get_next_team_info (&cookie, &teamInfo) == B_OK && i < fit) {
1618 pids [i++] = teamInfo.team;
1620 *needed = i * sizeof (guint32);
1625 gboolean EnumProcesses (guint32 *pids, guint32 len, guint32 *needed)
1627 GArray *processes = g_array_new (FALSE, FALSE, sizeof(pid_t));
1630 struct dirent *entry;
1632 mono_once (&process_current_once, process_set_current);
1634 dir = opendir ("/proc");
1638 while((entry = readdir (dir)) != NULL) {
1639 if (isdigit (entry->d_name[0])) {
1641 pid_t pid = (pid_t)strtol (entry->d_name, &endptr, 10);
1643 if (*endptr == '\0') {
1644 /* Name was entirely numeric, so was a
1647 g_array_append_val (processes, pid);
1653 fit=len/sizeof(guint32);
1654 for (i = 0, j = 0; j < fit && i < processes->len; i++) {
1655 pids[j++] = g_array_index (processes, pid_t, i);
1658 g_array_free (processes, TRUE);
1660 *needed = j * sizeof(guint32);
1666 static gboolean process_open_compare (gpointer handle, gpointer user_data)
1669 pid_t checking_pid = signal_process_if_gone (handle);
1671 if (checking_pid == 0) {
1675 wanted_pid = GPOINTER_TO_UINT (user_data);
1677 /* It's possible to have more than one process handle with the
1678 * same pid, but only the one running process can be
1681 if (checking_pid == wanted_pid &&
1682 _wapi_handle_issignalled (handle) == FALSE) {
1683 /* If the handle is blown away in the window between
1684 * returning TRUE here and _wapi_search_handle pinging
1685 * the timestamp, the search will continue
1693 gpointer OpenProcess (guint32 req_access G_GNUC_UNUSED, gboolean inherit G_GNUC_UNUSED, guint32 pid)
1695 /* Find the process handle that corresponds to pid */
1698 mono_once (&process_current_once, process_set_current);
1701 g_message ("%s: looking for process %d", __func__, pid);
1704 handle = _wapi_search_handle (WAPI_HANDLE_PROCESS,
1705 process_open_compare,
1706 GUINT_TO_POINTER (pid), NULL, TRUE);
1708 #if defined(__OpenBSD__)
1709 if ((kill(pid, 0) == 0) || (errno == EPERM)) {
1710 #elif defined(__HAIKU__)
1712 if (get_team_info ((team_id)pid, &teamInfo) == B_OK) {
1714 gchar *dir = g_strdup_printf ("/proc/%d", pid);
1715 if (!access (dir, F_OK)) {
1717 /* Return a pseudo handle for processes we
1718 * don't have handles for
1720 return GINT_TO_POINTER (_WAPI_PROCESS_UNHANDLED + pid);
1723 g_message ("%s: Can't find pid %d", __func__, pid);
1726 SetLastError (ERROR_PROC_NOT_FOUND);
1732 _wapi_handle_ref (handle);
1737 gboolean GetExitCodeProcess (gpointer process, guint32 *code)
1739 struct _WapiHandle_process *process_handle;
1742 mono_once (&process_current_once, process_set_current);
1748 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
1749 /* This is a pseudo handle, so we don't know what the
1755 ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
1756 (gpointer *)&process_handle);
1759 g_message ("%s: Can't find process %p", __func__, process);
1765 /* A process handle is only signalled if the process has exited
1766 * and has been waited for */
1768 /* Make sure any process exit has been noticed, before
1769 * checking if the process is signalled. Fixes bug 325463.
1771 process_wait (process, 0);
1773 if (_wapi_handle_issignalled (process) == TRUE) {
1774 *code = process_handle->exitstatus;
1776 *code = STILL_ACTIVE;
1782 gboolean GetProcessTimes (gpointer process, WapiFileTime *create_time,
1783 WapiFileTime *exit_time, WapiFileTime *kernel_time,
1784 WapiFileTime *user_time)
1786 struct _WapiHandle_process *process_handle;
1788 gboolean ku_times_set = FALSE;
1790 mono_once (&process_current_once, process_set_current);
1792 if(create_time==NULL || exit_time==NULL || kernel_time==NULL ||
1794 /* Not sure if w32 allows NULLs here or not */
1798 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
1799 /* This is a pseudo handle, so just fail for now
1804 ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
1805 (gpointer *)&process_handle);
1808 g_message ("%s: Can't find process %p", __func__, process);
1814 *create_time=process_handle->create_time;
1816 /* A process handle is only signalled if the process has
1817 * exited. Otherwise exit_time isn't set
1819 if(_wapi_handle_issignalled (process)==TRUE) {
1820 *exit_time=process_handle->exit_time;
1823 #ifdef HAVE_GETRUSAGE
1824 if (process_handle->id == getpid ()) {
1825 struct rusage time_data;
1826 if (getrusage (RUSAGE_SELF, &time_data) == 0) {
1828 gint64 *tick_val_ptr;
1829 ku_times_set = TRUE;
1830 tick_val = time_data.ru_utime.tv_sec * 10000000 + time_data.ru_utime.tv_usec * 10;
1831 tick_val_ptr = (gint64*)user_time;
1832 *tick_val_ptr = tick_val;
1833 tick_val = time_data.ru_stime.tv_sec * 10000000 + time_data.ru_stime.tv_usec * 10;
1834 tick_val_ptr = (gint64*)kernel_time;
1835 *tick_val_ptr = tick_val;
1839 if (!ku_times_set) {
1840 memset (kernel_time, 0, sizeof (WapiFileTime));
1841 memset (user_time, 0, sizeof (WapiFileTime));
1849 gpointer address_start;
1850 gpointer address_end;
1852 gpointer address_offset;
1858 static void free_procmodule (WapiProcModule *mod)
1860 if (mod->perms != NULL) {
1861 g_free (mod->perms);
1863 if (mod->filename != NULL) {
1864 g_free (mod->filename);
1869 static gint find_procmodule (gconstpointer a, gconstpointer b)
1871 WapiProcModule *want = (WapiProcModule *)a;
1872 WapiProcModule *compare = (WapiProcModule *)b;
1874 if ((want->device == compare->device) &&
1875 (want->inode == compare->inode)) {
1882 #ifdef PLATFORM_MACOSX
1883 #include <mach-o/dyld.h>
1884 #include <mach-o/getsect.h>
1886 static GSList *load_modules (void)
1889 WapiProcModule *mod;
1890 uint32_t count = _dyld_image_count ();
1893 for (i = 0; i < count; i++) {
1894 #if SIZEOF_VOID_P == 8
1895 const struct mach_header_64 *hdr;
1896 const struct section_64 *sec;
1898 const struct mach_header *hdr;
1899 const struct section *sec;
1904 slide = _dyld_get_image_vmaddr_slide (i);
1905 name = _dyld_get_image_name (i);
1906 hdr = _dyld_get_image_header (i);
1907 #if SIZEOF_VOID_P == 8
1908 sec = getsectbynamefromheader_64 (hdr, SEG_DATA, SECT_DATA);
1910 sec = getsectbynamefromheader (hdr, SEG_DATA, SECT_DATA);
1913 /* Some dynlibs do not have data sections on osx (#533893) */
1918 mod = g_new0 (WapiProcModule, 1);
1919 mod->address_start = GINT_TO_POINTER (sec->addr);
1920 mod->address_end = GINT_TO_POINTER (sec->addr+sec->size);
1921 mod->perms = g_strdup ("r--p");
1922 mod->address_offset = 0;
1923 mod->device = makedev (0, 0);
1924 mod->inode = (ino_t) i;
1925 mod->filename = g_strdup (name);
1927 if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
1928 ret = g_slist_prepend (ret, mod);
1930 free_procmodule (mod);
1934 ret = g_slist_reverse (ret);
1938 #elif defined(__OpenBSD__)
1940 static int load_modules_callback (struct dl_phdr_info *info, size_t size, void *ptr)
1942 if (size < offsetof (struct dl_phdr_info, dlpi_phnum)
1943 + sizeof (info->dlpi_phnum))
1946 struct dl_phdr_info *cpy = calloc(1, sizeof(struct dl_phdr_info));
1950 memcpy(cpy, info, sizeof(*info));
1952 g_ptr_array_add ((GPtrArray *)ptr, cpy);
1957 static GSList *load_modules (void)
1960 WapiProcModule *mod;
1961 GPtrArray *dlarray = g_ptr_array_new();
1964 if (dl_iterate_phdr(load_modules_callback, dlarray) < 0)
1967 for (i = 0; i < dlarray->len; i++) {
1968 struct dl_phdr_info *info = g_ptr_array_index (dlarray, i);
1970 mod = g_new0 (WapiProcModule, 1);
1971 mod->address_start = (gpointer)(info->dlpi_addr + info->dlpi_phdr[0].p_vaddr);
1972 mod->address_end = (gpointer)(info->dlpi_addr +
1973 info->dlpi_phdr[info->dlpi_phnum - 1].p_vaddr);
1974 mod->perms = g_strdup ("r--p");
1975 mod->address_offset = 0;
1976 mod->inode = (ino_t) i;
1977 mod->filename = g_strdup (info->dlpi_name);
1980 g_message ("%s: inode=%d, filename=%s, address_start=%p, address_end=%p", __func__,
1981 mod->inode, mod->filename, mod->address_start, mod->address_end);
1986 if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
1987 ret = g_slist_prepend (ret, mod);
1989 free_procmodule (mod);
1993 g_ptr_array_free (dlarray, TRUE);
1995 ret = g_slist_reverse (ret);
1999 #elif defined(__HAIKU__)
2001 static GSList *load_modules (void)
2004 WapiProcModule *mod;
2006 image_info imageInfo;
2008 while (get_next_image_info (B_CURRENT_TEAM, &cookie, &imageInfo) == B_OK) {
2009 mod = g_new0 (WapiProcModule, 1);
2010 mod->device = imageInfo.device;
2011 mod->inode = imageInfo.node;
2012 mod->filename = g_strdup (imageInfo.name);
2013 mod->address_start = MIN (imageInfo.text, imageInfo.data);
2014 mod->address_end = MAX ((uint8_t*)imageInfo.text + imageInfo.text_size,
2015 (uint8_t*)imageInfo.data + imageInfo.data_size);
2016 mod->perms = g_strdup ("r--p");
2017 mod->address_offset = 0;
2019 if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
2020 ret = g_slist_prepend (ret, mod);
2022 free_procmodule (mod);
2026 ret = g_slist_reverse (ret);
2031 static GSList *load_modules (FILE *fp)
2034 WapiProcModule *mod;
2035 gchar buf[MAXPATHLEN + 1], *p, *endp;
2036 gchar *start_start, *end_start, *prot_start, *offset_start;
2037 gchar *maj_dev_start, *min_dev_start, *inode_start, prot_buf[5];
2038 gpointer address_start, address_end, address_offset;
2039 guint32 maj_dev, min_dev;
2043 while (fgets (buf, sizeof(buf), fp)) {
2045 while (g_ascii_isspace (*p)) ++p;
2047 if (!g_ascii_isxdigit (*start_start)) {
2050 address_start = (gpointer)strtoul (start_start, &endp, 16);
2058 if (!g_ascii_isxdigit (*end_start)) {
2061 address_end = (gpointer)strtoul (end_start, &endp, 16);
2063 if (!g_ascii_isspace (*p)) {
2067 while (g_ascii_isspace (*p)) ++p;
2069 if (*prot_start != 'r' && *prot_start != '-') {
2072 memcpy (prot_buf, prot_start, 4);
2074 while (!g_ascii_isspace (*p)) ++p;
2076 while (g_ascii_isspace (*p)) ++p;
2078 if (!g_ascii_isxdigit (*offset_start)) {
2081 address_offset = (gpointer)strtoul (offset_start, &endp, 16);
2083 if (!g_ascii_isspace (*p)) {
2087 while(g_ascii_isspace (*p)) ++p;
2089 if (!g_ascii_isxdigit (*maj_dev_start)) {
2092 maj_dev = strtoul (maj_dev_start, &endp, 16);
2100 if (!g_ascii_isxdigit (*min_dev_start)) {
2103 min_dev = strtoul (min_dev_start, &endp, 16);
2105 if (!g_ascii_isspace (*p)) {
2109 while (g_ascii_isspace (*p)) ++p;
2111 if (!g_ascii_isxdigit (*inode_start)) {
2114 inode = (ino_t)strtol (inode_start, &endp, 10);
2116 if (!g_ascii_isspace (*p)) {
2120 device = makedev ((int)maj_dev, (int)min_dev);
2121 if ((device == 0) &&
2126 while(g_ascii_isspace (*p)) ++p;
2127 /* p now points to the filename */
2129 mod = g_new0 (WapiProcModule, 1);
2130 mod->address_start = address_start;
2131 mod->address_end = address_end;
2132 mod->perms = g_strdup (prot_buf);
2133 mod->address_offset = address_offset;
2134 mod->device = device;
2136 mod->filename = g_strdup (g_strstrip (p));
2138 if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
2139 ret = g_slist_prepend (ret, mod);
2141 free_procmodule (mod);
2145 ret = g_slist_reverse (ret);
2151 static gboolean match_procname_to_modulename (gchar *procname, gchar *modulename)
2153 char* lastsep = NULL;
2156 gboolean result = FALSE;
2158 if (procname == NULL || modulename == NULL)
2161 pname = mono_path_resolve_symlinks (procname);
2162 mname = mono_path_resolve_symlinks (modulename);
2164 if (!strcmp (pname, mname))
2168 lastsep = strrchr (mname, '/');
2170 if (!strcmp (lastsep+1, pname))
2180 #if !defined(__OpenBSD__)
2182 open_process_map (int pid, const char *mode)
2185 const gchar *proc_path[] = {
2186 "/proc/%d/maps", /* GNU/Linux */
2187 "/proc/%d/map", /* FreeBSD */
2193 for (i = 0; fp == NULL && proc_path [i]; i++) {
2194 filename = g_strdup_printf (proc_path[i], pid);
2195 fp = fopen (filename, mode);
2203 gboolean EnumProcessModules (gpointer process, gpointer *modules,
2204 guint32 size, guint32 *needed)
2206 struct _WapiHandle_process *process_handle;
2208 #if !defined(__OpenBSD__)
2211 GSList *mods = NULL;
2212 WapiProcModule *module;
2213 guint32 count, avail = size / sizeof(gpointer);
2216 gchar *proc_name = NULL;
2218 /* Store modules in an array of pointers (main module as
2219 * modules[0]), using the load address for each module as a
2220 * token. (Use 'NULL' as an alternative for the main module
2221 * so that the simple implementation can just return one item
2222 * for now.) Get the info from /proc/<pid>/maps on linux,
2223 * /proc/<pid>/map on FreeBSD, other systems will have to
2224 * implement /dev/kmem reading or whatever other horrid
2225 * technique is needed.
2227 if (size < sizeof(gpointer)) {
2231 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2232 /* This is a pseudo handle */
2233 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2235 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2236 (gpointer *)&process_handle);
2239 g_message ("%s: Can't find process %p", __func__, process);
2244 pid = process_handle->id;
2245 proc_name = process_handle->proc_name;
2248 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__) || defined(__HAIKU__)
2250 mods = load_modules ();
2252 if ((fp = open_process_map (pid, "r")) == NULL) {
2253 /* No /proc/<pid>/maps so just return the main module
2257 *needed = sizeof(gpointer);
2259 mods = load_modules (fp);
2262 count = g_slist_length (mods);
2264 /* count + 1 to leave slot 0 for the main module */
2265 *needed = sizeof(gpointer) * (count + 1);
2267 /* Use the NULL shortcut, as the first line in
2268 * /proc/<pid>/maps isn't the executable, and we need
2269 * that first in the returned list. Check the module name
2270 * to see if it ends with the proc name and substitute
2271 * the first entry with it. FIXME if this turns out to
2275 for (i = 0; i < (avail - 1) && i < count; i++) {
2276 module = (WapiProcModule *)g_slist_nth_data (mods, i);
2277 if (modules[0] != NULL)
2278 modules[i] = module->address_start;
2279 else if (match_procname_to_modulename (proc_name, module->filename))
2280 modules[0] = module->address_start;
2282 modules[i + 1] = module->address_start;
2285 for (i = 0; i < count; i++) {
2286 free_procmodule (g_slist_nth_data (mods, i));
2288 g_slist_free (mods);
2294 static gchar *get_process_name_from_proc (pid_t pid)
2296 #if !defined(__OpenBSD__)
2298 gchar *filename = NULL;
2303 #if defined(PLATFORM_SOLARIS)
2304 filename = g_strdup_printf ("/proc/%d/psinfo", pid);
2305 if ((fp = fopen (filename, "r")) != NULL) {
2309 nread = fread (&info, sizeof (info), 1, fp);
2311 ret = g_strdup (info.pr_fname);
2317 #elif defined(PLATFORM_MACOSX)
2318 memset (buf, '\0', sizeof(buf));
2319 proc_name (pid, buf, sizeof(buf));
2320 if (strlen (buf) > 0)
2321 ret = g_strdup (buf);
2322 #elif defined(__OpenBSD__)
2325 struct kinfo_proc2 *pi;
2328 mib [1] = KERN_PROC2;
2329 mib [2] = KERN_PROC_PID;
2331 mib [4] = sizeof(struct kinfo_proc2);
2335 if (sysctl(mib, 6, NULL, &size, NULL, 0) < 0)
2338 if ((pi = malloc(size)) == NULL)
2341 mib[5] = (int)(size / sizeof(struct kinfo_proc2));
2343 if ((sysctl (mib, 6, pi, &size, NULL, 0) < 0) ||
2344 (size != sizeof (struct kinfo_proc2))) {
2345 if (errno == ENOMEM) {
2352 if (strlen (pi->p_comm) > 0)
2353 ret = g_strdup (pi->p_comm);
2356 #elif defined(__HAIKU__)
2357 image_info imageInfo;
2360 if (get_next_image_info ((team_id)pid, &cookie, &imageInfo) == B_OK) {
2361 ret = g_strdup (imageInfo.name);
2364 memset (buf, '\0', sizeof(buf));
2365 filename = g_strdup_printf ("/proc/%d/exe", pid);
2366 if (readlink (filename, buf, 255) > 0) {
2367 ret = g_strdup (buf);
2375 filename = g_strdup_printf ("/proc/%d/cmdline", pid);
2376 if ((fp = fopen (filename, "r")) != NULL) {
2377 if (fgets (buf, 256, fp) != NULL) {
2378 ret = g_strdup (buf);
2389 filename = g_strdup_printf ("/proc/%d/stat", pid);
2390 if ((fp = fopen (filename, "r")) != NULL) {
2391 if (fgets (buf, 256, fp) != NULL) {
2394 start = strchr (buf, '(');
2395 if (start != NULL) {
2396 end = strchr (start + 1, ')');
2399 ret = g_strndup (start + 1,
2417 static guint32 get_module_name (gpointer process, gpointer module,
2418 gunichar2 *basename, guint32 size,
2421 struct _WapiHandle_process *process_handle;
2424 gunichar2 *procname;
2425 gchar *procname_ext = NULL;
2428 #if !defined(__OpenBSD__)
2431 GSList *mods = NULL;
2432 WapiProcModule *found_module;
2435 gchar *proc_name = NULL;
2437 mono_once (&process_current_once, process_set_current);
2440 g_message ("%s: Getting module base name, process handle %p module %p",
2441 __func__, process, module);
2444 size = size*sizeof(gunichar2); /* adjust for unicode characters */
2446 if (basename == NULL || size == 0) {
2450 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2451 /* This is a pseudo handle */
2452 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2453 proc_name = get_process_name_from_proc (pid);
2455 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2456 (gpointer *)&process_handle);
2459 g_message ("%s: Can't find process %p", __func__,
2465 pid = process_handle->id;
2466 proc_name = g_strdup (process_handle->proc_name);
2469 /* Look up the address in /proc/<pid>/maps */
2470 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__) || defined(__HAIKU__)
2472 mods = load_modules ();
2474 if ((fp = open_process_map (pid, "r")) == NULL) {
2475 if (errno == EACCES && module == NULL && base == TRUE) {
2476 procname_ext = get_process_name_from_proc (pid);
2478 /* No /proc/<pid>/maps, so just return failure
2485 mods = load_modules (fp);
2488 count = g_slist_length (mods);
2490 /* If module != NULL compare the address.
2491 * If module == NULL we are looking for the main module.
2492 * The best we can do for now check it the module name end with the process name.
2494 for (i = 0; i < count; i++) {
2495 found_module = (WapiProcModule *)g_slist_nth_data (mods, i);
2496 if (procname_ext == NULL &&
2497 ((module == NULL && match_procname_to_modulename (proc_name, found_module->filename)) ||
2498 (module != NULL && found_module->address_start == module))) {
2500 procname_ext = g_path_get_basename (found_module->filename);
2502 procname_ext = g_strdup (found_module->filename);
2506 free_procmodule (found_module);
2509 if (procname_ext == NULL)
2511 /* If it's *still* null, we might have hit the
2512 * case where reading /proc/$pid/maps gives an
2513 * empty file for this user.
2515 procname_ext = get_process_name_from_proc (pid);
2518 g_slist_free (mods);
2522 if (procname_ext != NULL) {
2524 g_message ("%s: Process name is [%s]", __func__,
2528 procname = mono_unicode_from_external (procname_ext, &bytes);
2529 if (procname == NULL) {
2531 g_free (procname_ext);
2537 /* Add the terminator */
2542 g_message ("%s: Size %d smaller than needed (%ld); truncating", __func__, size, bytes);
2545 memcpy (basename, procname, size);
2548 g_message ("%s: Size %d larger than needed (%ld)",
2549 __func__, size, bytes);
2552 memcpy (basename, procname, bytes);
2556 g_free (procname_ext);
2564 guint32 GetModuleBaseName (gpointer process, gpointer module,
2565 gunichar2 *basename, guint32 size)
2567 return(get_module_name (process, module, basename, size, TRUE));
2570 guint32 GetModuleFileNameEx (gpointer process, gpointer module,
2571 gunichar2 *filename, guint32 size)
2573 return(get_module_name (process, module, filename, size, FALSE));
2576 gboolean GetModuleInformation (gpointer process, gpointer module,
2577 WapiModuleInfo *modinfo, guint32 size)
2579 struct _WapiHandle_process *process_handle;
2582 #if !defined(__OpenBSD__)
2585 GSList *mods = NULL;
2586 WapiProcModule *found_module;
2589 gboolean ret = FALSE;
2590 gchar *proc_name = NULL;
2592 mono_once (&process_current_once, process_set_current);
2595 g_message ("%s: Getting module info, process handle %p module %p",
2596 __func__, process, module);
2599 if (modinfo == NULL || size < sizeof(WapiModuleInfo)) {
2603 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2604 /* This is a pseudo handle */
2605 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2606 proc_name = get_process_name_from_proc (pid);
2608 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2609 (gpointer *)&process_handle);
2612 g_message ("%s: Can't find process %p", __func__,
2618 pid = process_handle->id;
2619 proc_name = g_strdup (process_handle->proc_name);
2622 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__) || defined(__HAIKU__)
2624 mods = load_modules ();
2626 /* Look up the address in /proc/<pid>/maps */
2627 if ((fp = open_process_map (pid, "r")) == NULL) {
2628 /* No /proc/<pid>/maps, so just return failure
2634 mods = load_modules (fp);
2637 count = g_slist_length (mods);
2639 /* If module != NULL compare the address.
2640 * If module == NULL we are looking for the main module.
2641 * The best we can do for now check it the module name end with the process name.
2643 for (i = 0; i < count; i++) {
2644 found_module = (WapiProcModule *)g_slist_nth_data (mods, i);
2645 if ( ret == FALSE &&
2646 ((module == NULL && match_procname_to_modulename (proc_name, found_module->filename)) ||
2647 (module != NULL && found_module->address_start == module))) {
2648 modinfo->lpBaseOfDll = found_module->address_start;
2649 modinfo->SizeOfImage = (gsize)(found_module->address_end) - (gsize)(found_module->address_start);
2650 modinfo->EntryPoint = found_module->address_offset;
2654 free_procmodule (found_module);
2657 g_slist_free (mods);
2664 gboolean GetProcessWorkingSetSize (gpointer process, size_t *min, size_t *max)
2666 struct _WapiHandle_process *process_handle;
2669 mono_once (&process_current_once, process_set_current);
2671 if(min==NULL || max==NULL) {
2672 /* Not sure if w32 allows NULLs here or not */
2676 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2677 /* This is a pseudo handle, so just fail for now
2682 ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2683 (gpointer *)&process_handle);
2686 g_message ("%s: Can't find process %p", __func__, process);
2692 *min=process_handle->min_working_set;
2693 *max=process_handle->max_working_set;
2698 gboolean SetProcessWorkingSetSize (gpointer process, size_t min, size_t max)
2700 struct _WapiHandle_process *process_handle;
2703 mono_once (&process_current_once, process_set_current);
2705 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2706 /* This is a pseudo handle, so just fail for now
2711 ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2712 (gpointer *)&process_handle);
2715 g_message ("%s: Can't find process %p", __func__, process);
2721 process_handle->min_working_set=min;
2722 process_handle->max_working_set=max;
2729 TerminateProcess (gpointer process, gint32 exitCode)
2731 struct _WapiHandle_process *process_handle;
2737 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2738 /* This is a pseudo handle */
2739 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2741 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2742 (gpointer *) &process_handle);
2746 g_message ("%s: Can't find process %p", __func__,
2749 SetLastError (ERROR_INVALID_HANDLE);
2752 pid = process_handle->id;
2755 signo = (exitCode == -1) ? SIGKILL : SIGTERM;
2756 ret = kill (pid, signo);
2760 SetLastError (ERROR_INVALID_PARAMETER);
2763 SetLastError (ERROR_ACCESS_DENIED);
2766 SetLastError (ERROR_PROC_NOT_FOUND);
2769 SetLastError (ERROR_GEN_FAILURE);
2777 GetPriorityClass (gpointer process)
2779 #ifdef HAVE_GETPRIORITY
2780 struct _WapiHandle_process *process_handle;
2785 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2786 /* This is a pseudo handle */
2787 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2789 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2790 (gpointer *) &process_handle);
2793 SetLastError (ERROR_INVALID_HANDLE);
2796 pid = process_handle->id;
2800 ret = getpriority (PRIO_PROCESS, pid);
2801 if (ret == -1 && errno != 0) {
2805 SetLastError (ERROR_ACCESS_DENIED);
2808 SetLastError (ERROR_PROC_NOT_FOUND);
2811 SetLastError (ERROR_GEN_FAILURE);
2817 return NORMAL_PRIORITY_CLASS;
2819 return REALTIME_PRIORITY_CLASS;
2821 return HIGH_PRIORITY_CLASS;
2823 return ABOVE_NORMAL_PRIORITY_CLASS;
2825 return IDLE_PRIORITY_CLASS;
2827 return BELOW_NORMAL_PRIORITY_CLASS;
2829 return NORMAL_PRIORITY_CLASS;
2831 SetLastError (ERROR_NOT_SUPPORTED);
2837 SetPriorityClass (gpointer process, guint32 priority_class)
2839 #ifdef HAVE_SETPRIORITY
2840 struct _WapiHandle_process *process_handle;
2846 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2847 /* This is a pseudo handle */
2848 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2850 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2851 (gpointer *) &process_handle);
2854 SetLastError (ERROR_INVALID_HANDLE);
2857 pid = process_handle->id;
2860 switch (priority_class) {
2861 case IDLE_PRIORITY_CLASS:
2864 case BELOW_NORMAL_PRIORITY_CLASS:
2867 case NORMAL_PRIORITY_CLASS:
2870 case ABOVE_NORMAL_PRIORITY_CLASS:
2873 case HIGH_PRIORITY_CLASS:
2876 case REALTIME_PRIORITY_CLASS:
2880 SetLastError (ERROR_INVALID_PARAMETER);
2884 ret = setpriority (PRIO_PROCESS, pid, prio);
2889 SetLastError (ERROR_ACCESS_DENIED);
2892 SetLastError (ERROR_PROC_NOT_FOUND);
2895 SetLastError (ERROR_GEN_FAILURE);
2901 SetLastError (ERROR_NOT_SUPPORTED);