2 * processes.c: Process handles
5 * Dick Porter (dick@ximian.com)
7 * (C) 2002-2006 Novell, Inc.
18 #include <sys/types.h>
24 #include <sys/resource.h>
26 #include <sys/param.h>
29 #ifdef HAVE_SYS_MKDEV_H
30 #include <sys/mkdev.h>
33 /* sys/resource.h (for rusage) is required when using osx 10.3 (but not 10.4) */
35 #include <sys/resource.h>
38 #ifdef PLATFORM_MACOSX
40 #include <sys/sysctl.h>
41 #include <sys/utsname.h>
44 #ifdef PLATFORM_SOLARIS
45 /* procfs.h cannot be included if this define is set, but it seems to work fine if it is undefined */
46 #if _FILE_OFFSET_BITS == 64
47 #undef _FILE_OFFSET_BITS
49 #define _FILE_OFFSET_BITS 64
55 #include <mono/io-layer/wapi.h>
56 #include <mono/io-layer/wapi-private.h>
57 #include <mono/io-layer/handles-private.h>
58 #include <mono/io-layer/misc-private.h>
59 #include <mono/io-layer/mono-mutex.h>
60 #include <mono/io-layer/process-private.h>
61 #include <mono/io-layer/threads.h>
62 #include <mono/utils/strenc.h>
63 #include <mono/utils/mono-path.h>
64 #include <mono/io-layer/timefuncs-private.h>
66 /* The process' environment strings */
68 /* Apple defines this in crt_externs.h but doesn't provide that header for
69 * arm-apple-darwin9. We'll manually define the symbol on Apple as it does
70 * in fact exist on all implementations (so far)
72 gchar
***_NSGetEnviron(void);
73 #define environ (*_NSGetEnviron())
75 extern char **environ
;
80 static guint32
process_wait (gpointer handle
, guint32 timeout
);
83 open_process_map (int pid
, const char *mode
);
85 struct _WapiHandleOps _wapi_process_ops
= {
86 NULL
, /* close_shared */
90 process_wait
, /* special_wait */
94 static mono_once_t process_current_once
=MONO_ONCE_INIT
;
95 static gpointer current_process
=NULL
;
97 static mono_once_t process_ops_once
=MONO_ONCE_INIT
;
99 static void process_ops_init (void)
101 _wapi_handle_register_capabilities (WAPI_HANDLE_PROCESS
,
102 WAPI_HANDLE_CAP_WAIT
|
103 WAPI_HANDLE_CAP_SPECIAL_WAIT
);
106 static gboolean
process_set_termination_details (gpointer handle
, int status
)
108 struct _WapiHandle_process
*process_handle
;
112 g_assert ((GPOINTER_TO_UINT (handle
) & _WAPI_PROCESS_UNHANDLED
) != _WAPI_PROCESS_UNHANDLED
);
114 ok
= _wapi_lookup_handle (handle
, WAPI_HANDLE_PROCESS
,
115 (gpointer
*)&process_handle
);
117 g_warning ("%s: error looking up process handle %p",
122 thr_ret
= _wapi_handle_lock_shared_handles ();
123 g_assert (thr_ret
== 0);
125 if (WIFSIGNALED(status
)) {
126 process_handle
->exitstatus
= 128 + WTERMSIG(status
);
128 process_handle
->exitstatus
= WEXITSTATUS(status
);
130 _wapi_time_t_to_filetime (time(NULL
), &process_handle
->exit_time
);
132 /* Don't set process_handle->waited here, it needs to only
133 * happen in the parent when wait() has been called.
137 g_message ("%s: Setting handle %p pid %d signalled, exit status %d",
138 __func__
, handle
, process_handle
->id
,
139 process_handle
->exitstatus
);
142 _wapi_shared_handle_set_signal_state (handle
, TRUE
);
144 _wapi_handle_unlock_shared_handles ();
146 /* Drop the reference we hold so we have somewhere to store
147 * the exit details, now the process has in fact exited
149 _wapi_handle_unref (handle
);
154 /* See if any child processes have terminated and wait() for them,
155 * updating process handle info. This function is called from the
156 * collection thread every few seconds.
158 static gboolean
waitfor_pid (gpointer test
, gpointer user_data
)
160 struct _WapiHandle_process
*process
;
165 g_assert ((GPOINTER_TO_UINT (test
) & _WAPI_PROCESS_UNHANDLED
) != _WAPI_PROCESS_UNHANDLED
);
167 ok
= _wapi_lookup_handle (test
, WAPI_HANDLE_PROCESS
,
168 (gpointer
*)&process
);
170 /* The handle must have been too old and was reaped */
174 if (process
->waited
) {
175 /* We've already done this one */
180 ret
= waitpid (process
->id
, &status
, WNOHANG
);
181 } while (errno
== EINTR
);
184 /* Process not ready for wait */
186 g_message ("%s: Process %d not ready for waiting for: %s",
187 __func__
, process
->id
, g_strerror (errno
));
194 g_message ("%s: Process %d finished", __func__
, ret
);
197 process
->waited
= TRUE
;
199 *(int *)user_data
= status
;
204 void _wapi_process_reap (void)
210 g_message ("%s: Reaping child processes", __func__
);
214 proc
= _wapi_search_handle (WAPI_HANDLE_PROCESS
, waitfor_pid
,
215 &status
, NULL
, FALSE
);
218 g_message ("%s: process handle %p exit code %d",
219 __func__
, proc
, status
);
222 process_set_termination_details (proc
, status
);
224 /* _wapi_search_handle adds a reference, so
227 _wapi_handle_unref (proc
);
229 } while (proc
!= NULL
);
232 /* Limitations: This can only wait for processes that are our own
233 * children. Fixing this means resurrecting a daemon helper to manage
236 static guint32
process_wait (gpointer handle
, guint32 timeout
)
238 struct _WapiHandle_process
*process_handle
;
243 g_assert ((GPOINTER_TO_UINT (handle
) & _WAPI_PROCESS_UNHANDLED
) != _WAPI_PROCESS_UNHANDLED
);
246 g_message ("%s: Waiting for process %p", __func__
, handle
);
249 ok
= _wapi_lookup_handle (handle
, WAPI_HANDLE_PROCESS
,
250 (gpointer
*)&process_handle
);
252 g_warning ("%s: error looking up process handle %p", __func__
,
257 if (process_handle
->waited
) {
258 /* We've already done this one */
260 g_message ("%s: Process %p already signalled", __func__
,
264 return (WAIT_OBJECT_0
);
267 pid
= process_handle
->id
;
270 g_message ("%s: PID is %d, timeout %d", __func__
, pid
, timeout
);
273 if (timeout
== INFINITE
) {
274 if (pid
== _wapi_getpid ()) {
279 while ((ret
= waitpid (pid
, &status
, 0)) != pid
) {
280 if (ret
== (pid_t
)-1 && errno
!= EINTR
) {
285 } else if (timeout
== 0) {
287 ret
= waitpid (pid
, &status
, WNOHANG
);
289 return (WAIT_TIMEOUT
);
293 if (pid
== _wapi_getpid ()) {
295 return(WAIT_TIMEOUT
);
298 ret
= waitpid (pid
, &status
, WNOHANG
);
300 g_message ("%s: waitpid returns: %d, timeout is %d", __func__
, ret
, timeout
);
305 } else if (ret
== (pid_t
)-1 &&
308 g_message ("%s: waitpid failure: %s",
313 if (errno
== ECHILD
&&
314 process_handle
->waited
) {
316 * process reaper must
320 g_message ("%s: Process %p already reaped", __func__
, handle
);
323 return(WAIT_OBJECT_0
);
329 _wapi_handle_spin (100);
331 } while (timeout
> 0);
335 return(WAIT_TIMEOUT
);
339 /* Process must have exited */
341 g_message ("%s: Wait done, status %d", __func__
, status
);
344 ok
= process_set_termination_details (handle
, status
);
346 SetLastError (ERROR_OUTOFMEMORY
);
347 return (WAIT_FAILED
);
349 process_handle
->waited
= TRUE
;
351 return(WAIT_OBJECT_0
);
354 void _wapi_process_signal_self ()
356 if (current_process
!= NULL
) {
357 process_set_termination_details (current_process
, 0);
361 static void process_set_defaults (struct _WapiHandle_process
*process_handle
)
363 /* These seem to be the defaults on w2k */
364 process_handle
->min_working_set
= 204800;
365 process_handle
->max_working_set
= 1413120;
367 process_handle
->waited
= FALSE
;
369 _wapi_time_t_to_filetime (time (NULL
), &process_handle
->create_time
);
373 len16 (const gunichar2
*str
)
384 utf16_concat (const gunichar2
*first
, ...)
391 va_start (args
, first
);
392 total
+= len16 (first
);
393 for (s
= va_arg (args
, gunichar2
*); s
!= NULL
; s
= va_arg(args
, gunichar2
*)){
398 ret
= g_new (gunichar2
, total
+ 1);
404 for (s
= first
; *s
!= 0; s
++)
406 va_start (args
, first
);
407 for (s
= va_arg (args
, gunichar2
*); s
!= NULL
; s
= va_arg (args
, gunichar2
*)){
410 for (p
= s
; *p
!= 0; p
++)
418 #ifdef PLATFORM_MACOSX
420 /* 0 = no detection; -1 = not 10.5 or higher; 1 = 10.5 or higher */
421 static int osx_10_5_or_higher
;
424 detect_osx_10_5_or_higher (void)
430 if (uname (&u
) != 0){
431 osx_10_5_or_higher
= 1;
439 osx_10_5_or_higher
= -1;
441 osx_10_5_or_higher
= 1;
445 is_macos_10_5_or_higher (void)
447 if (osx_10_5_or_higher
== 0)
448 detect_osx_10_5_or_higher ();
450 return (osx_10_5_or_higher
== 1);
454 static const gunichar2 utf16_space_bytes
[2] = { 0x20, 0 };
455 static const gunichar2
*utf16_space
= utf16_space_bytes
;
456 static const gunichar2 utf16_quote_bytes
[2] = { 0x22, 0 };
457 static const gunichar2
*utf16_quote
= utf16_quote_bytes
;
459 /* Implemented as just a wrapper around CreateProcess () */
460 gboolean
ShellExecuteEx (WapiShellExecuteInfo
*sei
)
463 WapiProcessInformation process_info
;
467 /* w2k just segfaults here, but we can do better than
470 SetLastError (ERROR_INVALID_PARAMETER
);
474 if (sei
->lpFile
== NULL
) {
475 /* w2k returns TRUE for this, for some reason. */
479 /* Put both executable and parameters into the second argument
480 * to CreateProcess (), so it searches $PATH. The conversion
481 * into and back out of utf8 is because there is no
482 * g_strdup_printf () equivalent for gunichar2 :-(
484 args
= utf16_concat (sei
->lpFile
, sei
->lpParameters
== NULL
? NULL
: utf16_space
, sei
->lpParameters
, NULL
);
486 SetLastError (ERROR_INVALID_DATA
);
489 ret
= CreateProcess (NULL
, args
, NULL
, NULL
, TRUE
,
490 CREATE_UNICODE_ENVIRONMENT
, NULL
,
491 sei
->lpDirectory
, NULL
, &process_info
);
494 if (!ret
&& GetLastError () == ERROR_OUTOFMEMORY
)
498 static char *handler
;
499 static gunichar2
*handler_utf16
;
501 if (handler_utf16
== (gunichar2
*)-1)
504 #ifdef PLATFORM_MACOSX
505 if (is_macos_10_5_or_higher ())
506 handler
= g_strdup ("/usr/bin/open -W");
508 handler
= g_strdup ("/usr/bin/open");
511 * On Linux, try: xdg-open, the FreeDesktop standard way of doing it,
512 * if that fails, try to use gnome-open, then kfmclient
514 handler
= g_find_program_in_path ("xdg-open");
515 if (handler
== NULL
){
516 handler
= g_find_program_in_path ("gnome-open");
517 if (handler
== NULL
){
518 handler
= g_find_program_in_path ("kfmclient");
519 if (handler
== NULL
){
520 handler_utf16
= (gunichar2
*) -1;
523 /* kfmclient needs exec argument */
525 handler
= g_strconcat (old
, " exec",
532 handler_utf16
= g_utf8_to_utf16 (handler
, -1, NULL
, NULL
, NULL
);
535 /* Put quotes around the filename, in case it's a url
536 * that contains #'s (CreateProcess() calls
537 * g_shell_parse_argv(), which deliberately throws
538 * away anything after an unquoted #). Fixes bug
541 args
= utf16_concat (handler_utf16
, utf16_space
, utf16_quote
,
542 sei
->lpFile
, utf16_quote
,
543 sei
->lpParameters
== NULL
? NULL
: utf16_space
,
544 sei
->lpParameters
, NULL
);
546 SetLastError (ERROR_INVALID_DATA
);
549 ret
= CreateProcess (NULL
, args
, NULL
, NULL
, TRUE
,
550 CREATE_UNICODE_ENVIRONMENT
, NULL
,
551 sei
->lpDirectory
, NULL
, &process_info
);
554 SetLastError (ERROR_INVALID_DATA
);
559 if (sei
->fMask
& SEE_MASK_NOCLOSEPROCESS
) {
560 sei
->hProcess
= process_info
.hProcess
;
562 CloseHandle (process_info
.hProcess
);
569 is_managed_binary (const gchar
*filename
)
571 int original_errno
= errno
;
572 #if defined(HAVE_LARGE_FILE_SUPPORT) && defined(O_LARGEFILE)
573 int file
= open (filename
, O_RDONLY
| O_LARGEFILE
);
575 int file
= open (filename
, O_RDONLY
);
578 unsigned char buffer
[8];
579 off_t file_size
, optional_header_offset
;
580 off_t pe_header_offset
;
581 gboolean managed
= FALSE
;
583 guint32 first_word
, second_word
;
585 /* If we are unable to open the file, then we definitely
586 * can't say that it is managed. The child mono process
587 * probably wouldn't be able to open it anyway.
590 errno
= original_errno
;
594 /* Retrieve the length of the file for future sanity checks. */
595 file_size
= lseek (file
, 0, SEEK_END
);
596 lseek (file
, 0, SEEK_SET
);
598 /* We know we need to read a header field at offset 60. */
602 num_read
= read (file
, buffer
, 2);
604 if ((num_read
!= 2) || (buffer
[0] != 'M') || (buffer
[1] != 'Z'))
607 new_offset
= lseek (file
, 60, SEEK_SET
);
609 if (new_offset
!= 60)
612 num_read
= read (file
, buffer
, 4);
616 pe_header_offset
= buffer
[0]
621 if (pe_header_offset
+ 24 > file_size
)
624 new_offset
= lseek (file
, pe_header_offset
, SEEK_SET
);
626 if (new_offset
!= pe_header_offset
)
629 num_read
= read (file
, buffer
, 4);
631 if ((num_read
!= 4) || (buffer
[0] != 'P') || (buffer
[1] != 'E') || (buffer
[2] != 0) || (buffer
[3] != 0))
635 * Verify that the header we want in the optional header data
636 * is present in this binary.
638 new_offset
= lseek (file
, pe_header_offset
+ 20, SEEK_SET
);
640 if (new_offset
!= pe_header_offset
+ 20)
643 num_read
= read (file
, buffer
, 2);
645 if ((num_read
!= 2) || ((buffer
[0] | (buffer
[1] << 8)) < 216))
648 /* Read the CLR header address and size fields. These will be
649 * zero if the binary is not managed.
651 optional_header_offset
= pe_header_offset
+ 24;
652 new_offset
= lseek (file
, optional_header_offset
+ 208, SEEK_SET
);
654 if (new_offset
!= optional_header_offset
+ 208)
657 num_read
= read (file
, buffer
, 8);
659 /* We are not concerned with endianness, only with
660 * whether it is zero or not.
662 first_word
= *(guint32
*)&buffer
[0];
663 second_word
= *(guint32
*)&buffer
[4];
665 if ((num_read
!= 8) || (first_word
== 0) || (second_word
== 0))
672 errno
= original_errno
;
676 gboolean
CreateProcessWithLogonW (const gunichar2
*username
,
677 const gunichar2
*domain
,
678 const gunichar2
*password
,
679 const guint32 logonFlags
,
680 const gunichar2
*appname
,
681 const gunichar2
*cmdline
,
682 guint32 create_flags
,
684 const gunichar2
*cwd
,
685 WapiStartupInfo
*startup
,
686 WapiProcessInformation
*process_info
)
688 /* FIXME: use user information */
689 return CreateProcess (appname
, cmdline
, NULL
, NULL
, FALSE
, create_flags
, env
, cwd
, startup
, process_info
);
693 is_executable (const char *prog
)
696 if (access (prog
, X_OK
) != 0)
698 if (stat (prog
, &buf
))
700 if (S_ISREG (buf
.st_mode
))
705 gboolean
CreateProcess (const gunichar2
*appname
, const gunichar2
*cmdline
,
706 WapiSecurityAttributes
*process_attrs G_GNUC_UNUSED
,
707 WapiSecurityAttributes
*thread_attrs G_GNUC_UNUSED
,
708 gboolean inherit_handles
, guint32 create_flags
,
709 gpointer new_environ
, const gunichar2
*cwd
,
710 WapiStartupInfo
*startup
,
711 WapiProcessInformation
*process_info
)
713 gchar
*cmd
=NULL
, *prog
= NULL
, *full_prog
= NULL
, *args
= NULL
, *args_after_prog
= NULL
, *dir
= NULL
, **env_strings
= NULL
, **argv
= NULL
;
714 guint32 i
, env_count
= 0;
715 gboolean ret
= FALSE
;
717 struct _WapiHandle_process process_handle
= {0}, *process_handle_data
;
719 int in_fd
, out_fd
, err_fd
;
723 mono_once (&process_ops_once
, process_ops_init
);
725 /* appname and cmdline specify the executable and its args:
727 * If appname is not NULL, it is the name of the executable.
728 * Otherwise the executable is the first token in cmdline.
730 * Executable searching:
732 * If appname is not NULL, it can specify the full path and
733 * file name, or else a partial name and the current directory
734 * will be used. There is no additional searching.
736 * If appname is NULL, the first whitespace-delimited token in
737 * cmdline is used. If the name does not contain a full
738 * directory path, the search sequence is:
740 * 1) The directory containing the current process
741 * 2) The current working directory
742 * 3) The windows system directory (Ignored)
743 * 4) The windows directory (Ignored)
746 * Just to make things more interesting, tokens can contain
747 * white space if they are surrounded by quotation marks. I'm
748 * beginning to understand just why windows apps are generally
749 * so crap, with an API like this :-(
751 if (appname
!= NULL
) {
752 cmd
= mono_unicode_to_external (appname
);
755 g_message ("%s: unicode conversion returned NULL",
759 SetLastError (ERROR_PATH_NOT_FOUND
);
763 /* Turn all the slashes round the right way */
764 for (i
= 0; i
< strlen (cmd
); i
++) {
765 if (cmd
[i
] == '\\') {
771 if (cmdline
!= NULL
) {
772 args
= mono_unicode_to_external (cmdline
);
775 g_message ("%s: unicode conversion returned NULL", __func__
);
778 SetLastError (ERROR_PATH_NOT_FOUND
);
784 dir
= mono_unicode_to_external (cwd
);
787 g_message ("%s: unicode conversion returned NULL", __func__
);
790 SetLastError (ERROR_PATH_NOT_FOUND
);
794 /* Turn all the slashes round the right way */
795 for (i
= 0; i
< strlen (dir
); i
++) {
796 if (dir
[i
] == '\\') {
803 /* We can't put off locating the executable any longer :-( */
806 if (g_ascii_isalpha (cmd
[0]) && (cmd
[1] == ':')) {
807 /* Strip off the drive letter. I can't
808 * believe that CP/M holdover is still
811 g_memmove (cmd
, cmd
+2, strlen (cmd
)-2);
812 cmd
[strlen (cmd
)-2] = '\0';
815 unquoted
= g_shell_unquote (cmd
, NULL
);
816 if (unquoted
[0] == '/') {
817 /* Assume full path given */
818 prog
= g_strdup (unquoted
);
820 /* Executable existing ? */
821 if (!is_executable (prog
)) {
823 g_message ("%s: Couldn't find executable %s",
827 SetLastError (ERROR_FILE_NOT_FOUND
);
831 /* Search for file named by cmd in the current
834 char *curdir
= g_get_current_dir ();
836 prog
= g_strdup_printf ("%s/%s", curdir
, unquoted
);
839 /* And make sure it's executable */
840 if (!is_executable (prog
)) {
842 g_message ("%s: Couldn't find executable %s",
846 SetLastError (ERROR_FILE_NOT_FOUND
);
852 args_after_prog
= args
;
857 /* Dig out the first token from args, taking quotation
861 /* First, strip off all leading whitespace */
862 args
= g_strchug (args
);
864 /* args_after_prog points to the contents of args
865 * after token has been set (otherwise argv[0] is
868 args_after_prog
= args
;
870 /* Assume the opening quote will always be the first
873 if (args
[0] == '\"' || args
[0] == '\'') {
875 for (i
= 1; args
[i
] != '\0' && args
[i
] != quote
; i
++);
876 if (g_ascii_isspace (args
[i
+1])) {
877 /* We found the first token */
878 token
= g_strndup (args
+1, i
-1);
879 args_after_prog
= args
+ i
;
881 /* Quotation mark appeared in the
882 * middle of the token. Just give the
883 * whole first token, quotes and all,
890 /* No quote mark, or malformed */
891 for (i
= 0; args
[i
] != '\0'; i
++) {
892 if (g_ascii_isspace (args
[i
])) {
893 token
= g_strndup (args
, i
);
894 args_after_prog
= args
+ i
+ 1;
900 if (token
== NULL
&& args
[0] != '\0') {
901 /* Must be just one token in the string */
902 token
= g_strdup (args
);
903 args_after_prog
= NULL
;
909 g_message ("%s: Couldn't find what to exec", __func__
);
912 SetLastError (ERROR_PATH_NOT_FOUND
);
916 /* Turn all the slashes round the right way. Only for
919 for (i
= 0; i
< strlen (token
); i
++) {
920 if (token
[i
] == '\\') {
925 if (g_ascii_isalpha (token
[0]) && (token
[1] == ':')) {
926 /* Strip off the drive letter. I can't
927 * believe that CP/M holdover is still
930 g_memmove (token
, token
+2, strlen (token
)-2);
931 token
[strlen (token
)-2] = '\0';
934 if (token
[0] == '/') {
935 /* Assume full path given */
936 prog
= g_strdup (token
);
938 /* Executable existing ? */
939 if (!is_executable (prog
)) {
941 g_message ("%s: Couldn't find executable %s",
945 SetLastError (ERROR_FILE_NOT_FOUND
);
950 char *curdir
= g_get_current_dir ();
952 /* FIXME: Need to record the directory
953 * containing the current process, and check
954 * that for the new executable as the first
958 prog
= g_strdup_printf ("%s/%s", curdir
, token
);
961 /* I assume X_OK is the criterion to use,
964 if (!is_executable (prog
)) {
966 prog
= g_find_program_in_path (token
);
969 g_message ("%s: Couldn't find executable %s", __func__
, token
);
973 SetLastError (ERROR_FILE_NOT_FOUND
);
983 g_message ("%s: Exec prog [%s] args [%s]", __func__
, prog
,
987 /* Check for CLR binaries; if found, we will try to invoke
988 * them using the same mono binary that started us.
990 if (is_managed_binary (prog
)) {
991 gunichar2
*newapp
, *newcmd
;
994 newapp
= mono_unicode_from_external ("mono", &bytes_ignored
);
996 if (newapp
!= NULL
) {
997 if (appname
!= NULL
) {
998 newcmd
= utf16_concat (newapp
, utf16_space
,
999 appname
, utf16_space
,
1002 newcmd
= utf16_concat (newapp
, utf16_space
,
1006 g_free ((gunichar2
*)newapp
);
1008 if (newcmd
!= NULL
) {
1009 ret
= CreateProcess (NULL
, newcmd
,
1013 create_flags
, new_environ
,
1017 g_free ((gunichar2
*)newcmd
);
1024 if (args_after_prog
!= NULL
&& *args_after_prog
) {
1027 qprog
= g_shell_quote (prog
);
1028 full_prog
= g_strconcat (qprog
, " ", args_after_prog
, NULL
);
1031 full_prog
= g_shell_quote (prog
);
1034 ret
= g_shell_parse_argv (full_prog
, NULL
, &argv
, &gerr
);
1036 /* FIXME: Could do something with the GError here
1040 if (startup
!= NULL
&& startup
->dwFlags
& STARTF_USESTDHANDLES
) {
1041 in_fd
= GPOINTER_TO_UINT (startup
->hStdInput
);
1042 out_fd
= GPOINTER_TO_UINT (startup
->hStdOutput
);
1043 err_fd
= GPOINTER_TO_UINT (startup
->hStdError
);
1045 in_fd
= GPOINTER_TO_UINT (GetStdHandle (STD_INPUT_HANDLE
));
1046 out_fd
= GPOINTER_TO_UINT (GetStdHandle (STD_OUTPUT_HANDLE
));
1047 err_fd
= GPOINTER_TO_UINT (GetStdHandle (STD_ERROR_HANDLE
));
1050 g_strlcpy (process_handle
.proc_name
, prog
,
1051 _WAPI_PROC_NAME_MAX_LEN
- 1);
1053 process_set_defaults (&process_handle
);
1055 handle
= _wapi_handle_new (WAPI_HANDLE_PROCESS
, &process_handle
);
1056 if (handle
== _WAPI_HANDLE_INVALID
) {
1057 g_warning ("%s: error creating process handle", __func__
);
1060 SetLastError (ERROR_OUTOFMEMORY
);
1064 /* Hold another reference so the process has somewhere to
1065 * store its exit data even if we drop this handle
1067 _wapi_handle_ref (handle
);
1069 /* new_environ is a block of NULL-terminated strings, which
1070 * is itself NULL-terminated. Of course, passing an array of
1071 * string pointers would have made things too easy :-(
1073 * If new_environ is not NULL it specifies the entire set of
1074 * environment variables in the new process. Otherwise the
1075 * new process inherits the same environment.
1077 if (new_environ
!= NULL
) {
1078 gunichar2
*new_environp
;
1080 /* Count the number of strings */
1081 for (new_environp
= (gunichar2
*)new_environ
; *new_environp
;
1084 while (*new_environp
) {
1089 /* +2: one for the process handle value, and the last
1092 env_strings
= g_new0 (gchar
*, env_count
+ 2);
1094 /* Copy each environ string into 'strings' turning it
1095 * into utf8 (or the requested encoding) at the same
1099 for (new_environp
= (gunichar2
*)new_environ
; *new_environp
;
1101 env_strings
[env_count
] = mono_unicode_to_external (new_environp
);
1103 while (*new_environp
) {
1108 for (i
= 0; environ
[i
] != NULL
; i
++) {
1112 /* +2: one for the process handle value, and the last
1115 env_strings
= g_new0 (gchar
*, env_count
+ 2);
1117 /* Copy each environ string into 'strings' turning it
1118 * into utf8 (or the requested encoding) at the same
1122 for (i
= 0; environ
[i
] != NULL
; i
++) {
1123 env_strings
[env_count
] = g_strdup (environ
[i
]);
1127 /* pass process handle info to the child, so it doesn't have
1128 * to do an expensive search over the whole list
1130 if (env_strings
!= NULL
) {
1131 struct _WapiHandleUnshared
*handle_data
;
1132 struct _WapiHandle_shared_ref
*ref
;
1134 handle_data
= &_WAPI_PRIVATE_HANDLES(GPOINTER_TO_UINT(handle
));
1135 ref
= &handle_data
->u
.shared
;
1137 env_strings
[env_count
] = g_strdup_printf ("_WAPI_PROCESS_HANDLE_OFFSET=%d", ref
->offset
);
1140 thr_ret
= _wapi_handle_lock_shared_handles ();
1141 g_assert (thr_ret
== 0);
1146 SetLastError (ERROR_OUTOFMEMORY
);
1147 _wapi_handle_unref (handle
);
1149 } else if (pid
== 0) {
1152 if (_wapi_shm_disabled
== FALSE
) {
1153 /* Wait for the parent to finish setting up
1154 * the handle. The semaphore lock is safe
1155 * because the sem_undo structures of a
1156 * semaphore aren't inherited across a fork
1157 * (), but we can't do this if we're not using
1160 thr_ret
= _wapi_handle_lock_shared_handles ();
1161 g_assert (thr_ret
== 0);
1163 _wapi_handle_unlock_shared_handles ();
1166 /* should we detach from the process group? */
1168 /* Connect stdin, stdout and stderr */
1173 if (inherit_handles
!= TRUE
) {
1174 /* FIXME: do something here */
1177 /* Close all file descriptors */
1178 for (i
= getdtablesize () - 1; i
> 2; i
--) {
1183 g_message ("%s: exec()ing [%s] in dir [%s]", __func__
, cmd
,
1185 for (i
= 0; argv
[i
] != NULL
; i
++) {
1186 g_message ("arg %d: [%s]", i
, argv
[i
]);
1189 for (i
= 0; env_strings
[i
] != NULL
; i
++) {
1190 g_message ("env %d: [%s]", i
, env_strings
[i
]);
1195 if (dir
!= NULL
&& chdir (dir
) == -1) {
1201 execve (argv
[0], argv
, env_strings
);
1208 ret
= _wapi_lookup_handle (handle
, WAPI_HANDLE_PROCESS
,
1209 (gpointer
*)&process_handle_data
);
1211 g_warning ("%s: error looking up process handle %p", __func__
,
1213 _wapi_handle_unref (handle
);
1217 process_handle_data
->id
= pid
;
1219 if (process_info
!= NULL
) {
1220 process_info
->hProcess
= handle
;
1221 process_info
->dwProcessId
= pid
;
1223 /* FIXME: we might need to handle the thread info some
1226 process_info
->hThread
= INVALID_HANDLE_VALUE
;
1227 process_info
->dwThreadId
= 0;
1231 _wapi_handle_unlock_shared_handles ();
1237 if (full_prog
!= NULL
) {
1249 if(env_strings
!= NULL
) {
1250 g_strfreev (env_strings
);
1257 g_message ("%s: returning handle %p for pid %d", __func__
, handle
,
1264 static void process_set_name (struct _WapiHandle_process
*process_handle
)
1266 gchar
*progname
, *utf8_progname
, *slash
;
1268 progname
=g_get_prgname ();
1269 utf8_progname
=mono_utf8_from_external (progname
);
1272 g_message ("%s: using [%s] as prog name", __func__
, progname
);
1275 if(utf8_progname
!=NULL
) {
1276 slash
=strrchr (utf8_progname
, '/');
1278 g_strlcpy (process_handle
->proc_name
, slash
+1,
1279 _WAPI_PROC_NAME_MAX_LEN
- 1);
1281 g_strlcpy (process_handle
->proc_name
, utf8_progname
,
1282 _WAPI_PROC_NAME_MAX_LEN
- 1);
1285 g_free (utf8_progname
);
1289 extern void _wapi_time_t_to_filetime (time_t timeval
, WapiFileTime
*filetime
);
1291 #if !GLIB_CHECK_VERSION (2,4,0)
1292 #define g_setenv(a,b,c) setenv(a,b,c)
1293 #define g_unsetenv(a) unsetenv(a)
1296 static void process_set_current (void)
1298 pid_t pid
= _wapi_getpid ();
1299 const char *handle_env
;
1300 struct _WapiHandle_process process_handle
= {0};
1302 mono_once (&process_ops_once
, process_ops_init
);
1304 handle_env
= g_getenv ("_WAPI_PROCESS_HANDLE_OFFSET");
1305 g_unsetenv ("_WAPI_PROCESS_HANDLE_OFFSET");
1307 if (handle_env
!= NULL
) {
1308 struct _WapiHandle_process
*process_handlep
;
1309 gchar
*procname
= NULL
;
1312 current_process
= _wapi_handle_new_from_offset (WAPI_HANDLE_PROCESS
, atoi (handle_env
), TRUE
);
1315 g_message ("%s: Found my process handle: %p (offset %d 0x%x)",
1316 __func__
, current_process
, atoi (handle_env
),
1320 ok
= _wapi_lookup_handle (current_process
, WAPI_HANDLE_PROCESS
,
1321 (gpointer
*)&process_handlep
);
1323 /* This test will probably break on linuxthreads, but
1324 * that should be ancient history on all distros we
1327 if (process_handlep
->id
== pid
) {
1328 procname
= process_handlep
->proc_name
;
1329 if (!strcmp (procname
, "mono")) {
1330 /* Set a better process name */
1332 g_message ("%s: Setting better process name", __func__
);
1335 process_set_name (process_handlep
);
1338 g_message ("%s: Leaving process name: %s", __func__
, procname
);
1345 /* Wrong pid, so drop this handle and fall through to
1348 _wapi_handle_unref (current_process
);
1352 /* We get here if the handle wasn't specified in the
1353 * environment, or if the process ID was wrong, or if the
1354 * handle lookup failed (eg if the parent process forked and
1355 * quit immediately, and deleted the shared data before the
1356 * child got a chance to attach it.)
1360 g_message ("%s: Need to create my own process handle", __func__
);
1363 process_handle
.id
= pid
;
1365 process_set_defaults (&process_handle
);
1366 process_set_name (&process_handle
);
1368 current_process
= _wapi_handle_new (WAPI_HANDLE_PROCESS
,
1370 if (current_process
== _WAPI_HANDLE_INVALID
) {
1371 g_warning ("%s: error creating process handle", __func__
);
1376 gpointer
_wapi_process_duplicate ()
1378 mono_once (&process_current_once
, process_set_current
);
1380 _wapi_handle_ref (current_process
);
1382 return(current_process
);
1385 /* Returns a pseudo handle that doesn't need to be closed afterwards */
1386 gpointer
GetCurrentProcess (void)
1388 mono_once (&process_current_once
, process_set_current
);
1390 return(_WAPI_PROCESS_CURRENT
);
1393 guint32
GetProcessId (gpointer handle
)
1395 struct _WapiHandle_process
*process_handle
;
1398 if ((GPOINTER_TO_UINT (handle
) & _WAPI_PROCESS_UNHANDLED
) == _WAPI_PROCESS_UNHANDLED
) {
1399 /* This is a pseudo handle */
1400 return(GPOINTER_TO_UINT (handle
) & _WAPI_PROCESS_UNHANDLED_PID_MASK
);
1403 ok
= _wapi_lookup_handle (handle
, WAPI_HANDLE_PROCESS
,
1404 (gpointer
*)&process_handle
);
1406 SetLastError (ERROR_INVALID_HANDLE
);
1410 return (process_handle
->id
);
1413 guint32
GetCurrentProcessId (void)
1415 mono_once (&process_current_once
, process_set_current
);
1417 return (GetProcessId (current_process
));
1420 /* Returns the process id as a convenience to the functions that call this */
1421 static pid_t
signal_process_if_gone (gpointer handle
)
1423 struct _WapiHandle_process
*process_handle
;
1426 g_assert ((GPOINTER_TO_UINT (handle
) & _WAPI_PROCESS_UNHANDLED
) != _WAPI_PROCESS_UNHANDLED
);
1428 /* Make sure the process is signalled if it has exited - if
1429 * the parent process didn't wait for it then it won't be
1431 ok
= _wapi_lookup_handle (handle
, WAPI_HANDLE_PROCESS
,
1432 (gpointer
*)&process_handle
);
1434 /* It's possible that the handle has vanished during
1435 * the _wapi_search_handle before it gets here, so
1436 * don't spam the console with warnings.
1438 /* g_warning ("%s: error looking up process handle %p",
1439 __func__, handle);*/
1445 g_message ("%s: looking at process %d", __func__
, process_handle
->id
);
1448 if (kill (process_handle
->id
, 0) == -1 &&
1451 /* The process is dead, (EPERM tells us a new process
1452 * has that ID, but as it's owned by someone else it
1453 * can't be the one listed in our shared memory file)
1455 _wapi_shared_handle_set_signal_state (handle
, TRUE
);
1458 return (process_handle
->id
);
1462 static gboolean
process_enum (gpointer handle
, gpointer user_data
)
1464 GArray
*processes
=user_data
;
1465 pid_t pid
= signal_process_if_gone (handle
);
1472 /* Ignore processes that have already exited (ie they are signalled) */
1473 if (_wapi_handle_issignalled (handle
) == FALSE
) {
1475 g_message ("%s: process %d added to array", __func__
, pid
);
1478 /* This ensures that duplicates aren't returned (see
1479 * the comment above _wapi_search_handle () for why
1482 for (i
= 0; i
< processes
->len
; i
++) {
1483 if (g_array_index (processes
, pid_t
, i
) == pid
) {
1484 /* We've already got this one, return
1485 * FALSE to keep searching
1491 g_array_append_val (processes
, pid
);
1494 /* Return false to keep searching */
1497 #endif /* UNUSED_CODE */
1499 #ifdef PLATFORM_MACOSX
1501 gboolean
EnumProcesses (guint32
*pids
, guint32 len
, guint32
*needed
)
1503 guint32 count
, fit
, i
, j
;
1506 struct kinfo_proc
*result
;
1508 static const int name
[] = { CTL_KERN
, KERN_PROC
, KERN_PROC_ALL
, 0 };
1510 mono_once (&process_current_once
, process_set_current
);
1517 err
= sysctl ((int *)name
, (sizeof(name
) / sizeof(*name
)) - 1, NULL
, &proclength
, NULL
, 0);
1520 result
= malloc (proclength
);
1524 err
= sysctl ((int *) name
, (sizeof(name
) / sizeof(*name
)) - 1, result
, &proclength
, NULL
, 0);
1531 } while (err
== 0 && !done
);
1534 if (result
!= NULL
) {
1541 count
= proclength
/ sizeof(struct kinfo_proc
);
1542 fit
= len
/ sizeof(guint32
);
1543 for (i
= 0, j
= 0; j
< fit
&& i
< count
; i
++) {
1544 pids
[j
++] = result
[i
].kp_proc
.p_pid
;
1548 *needed
= j
* sizeof(guint32
);
1553 gboolean
EnumProcesses (guint32
*pids
, guint32 len
, guint32
*needed
)
1555 GArray
*processes
= g_array_new (FALSE
, FALSE
, sizeof(pid_t
));
1558 struct dirent
*entry
;
1560 mono_once (&process_current_once
, process_set_current
);
1562 dir
= opendir ("/proc");
1566 while((entry
= readdir (dir
)) != NULL
) {
1567 if (isdigit (entry
->d_name
[0])) {
1569 pid_t pid
= (pid_t
)strtol (entry
->d_name
, &endptr
, 10);
1571 if (*endptr
== '\0') {
1572 /* Name was entirely numeric, so was a
1575 g_array_append_val (processes
, pid
);
1581 fit
=len
/sizeof(guint32
);
1582 for (i
= 0, j
= 0; j
< fit
&& i
< processes
->len
; i
++) {
1583 pids
[j
++] = g_array_index (processes
, pid_t
, i
);
1586 g_array_free (processes
, TRUE
);
1588 *needed
= j
* sizeof(guint32
);
1594 static gboolean
process_open_compare (gpointer handle
, gpointer user_data
)
1597 pid_t checking_pid
= signal_process_if_gone (handle
);
1599 if (checking_pid
== 0) {
1603 wanted_pid
= GPOINTER_TO_UINT (user_data
);
1605 /* It's possible to have more than one process handle with the
1606 * same pid, but only the one running process can be
1609 if (checking_pid
== wanted_pid
&&
1610 _wapi_handle_issignalled (handle
) == FALSE
) {
1611 /* If the handle is blown away in the window between
1612 * returning TRUE here and _wapi_search_handle pinging
1613 * the timestamp, the search will continue
1621 gpointer
OpenProcess (guint32 req_access G_GNUC_UNUSED
, gboolean inherit G_GNUC_UNUSED
, guint32 pid
)
1623 /* Find the process handle that corresponds to pid */
1626 mono_once (&process_current_once
, process_set_current
);
1629 g_message ("%s: looking for process %d", __func__
, pid
);
1632 handle
= _wapi_search_handle (WAPI_HANDLE_PROCESS
,
1633 process_open_compare
,
1634 GUINT_TO_POINTER (pid
), NULL
, TRUE
);
1636 gchar
*dir
= g_strdup_printf ("/proc/%d", pid
);
1637 if (!access (dir
, F_OK
)) {
1638 /* Return a pseudo handle for processes we
1639 * don't have handles for
1641 return GINT_TO_POINTER (_WAPI_PROCESS_UNHANDLED
+ pid
);
1644 g_message ("%s: Can't find pid %d", __func__
, pid
);
1647 SetLastError (ERROR_PROC_NOT_FOUND
);
1653 _wapi_handle_ref (handle
);
1658 gboolean
GetExitCodeProcess (gpointer process
, guint32
*code
)
1660 struct _WapiHandle_process
*process_handle
;
1663 mono_once (&process_current_once
, process_set_current
);
1669 if ((GPOINTER_TO_UINT (process
) & _WAPI_PROCESS_UNHANDLED
) == _WAPI_PROCESS_UNHANDLED
) {
1670 /* This is a pseudo handle, so we don't know what the
1676 ok
=_wapi_lookup_handle (process
, WAPI_HANDLE_PROCESS
,
1677 (gpointer
*)&process_handle
);
1680 g_message ("%s: Can't find process %p", __func__
, process
);
1686 /* A process handle is only signalled if the process has exited
1687 * and has been waited for */
1689 /* Make sure any process exit has been noticed, before
1690 * checking if the process is signalled. Fixes bug 325463.
1692 process_wait (process
, 0);
1694 if (_wapi_handle_issignalled (process
) == TRUE
) {
1695 *code
= process_handle
->exitstatus
;
1697 *code
= STILL_ACTIVE
;
1703 gboolean
GetProcessTimes (gpointer process
, WapiFileTime
*create_time
,
1704 WapiFileTime
*exit_time
, WapiFileTime
*kernel_time
,
1705 WapiFileTime
*user_time
)
1707 struct _WapiHandle_process
*process_handle
;
1709 gboolean ku_times_set
= FALSE
;
1711 mono_once (&process_current_once
, process_set_current
);
1713 if(create_time
==NULL
|| exit_time
==NULL
|| kernel_time
==NULL
||
1715 /* Not sure if w32 allows NULLs here or not */
1719 if ((GPOINTER_TO_UINT (process
) & _WAPI_PROCESS_UNHANDLED
) == _WAPI_PROCESS_UNHANDLED
) {
1720 /* This is a pseudo handle, so just fail for now
1725 ok
=_wapi_lookup_handle (process
, WAPI_HANDLE_PROCESS
,
1726 (gpointer
*)&process_handle
);
1729 g_message ("%s: Can't find process %p", __func__
, process
);
1735 *create_time
=process_handle
->create_time
;
1737 /* A process handle is only signalled if the process has
1738 * exited. Otherwise exit_time isn't set
1740 if(_wapi_handle_issignalled (process
)==TRUE
) {
1741 *exit_time
=process_handle
->exit_time
;
1744 #ifdef HAVE_GETRUSAGE
1745 if (process_handle
->id
== getpid ()) {
1746 struct rusage time_data
;
1747 if (getrusage (RUSAGE_SELF
, &time_data
) == 0) {
1749 gint64
*tick_val_ptr
;
1750 ku_times_set
= TRUE
;
1751 tick_val
= time_data
.ru_utime
.tv_sec
* 10000000 + time_data
.ru_utime
.tv_usec
* 10;
1752 tick_val_ptr
= (gint64
*)user_time
;
1753 *tick_val_ptr
= tick_val
;
1754 tick_val
= time_data
.ru_stime
.tv_sec
* 10000000 + time_data
.ru_stime
.tv_usec
* 10;
1755 tick_val_ptr
= (gint64
*)kernel_time
;
1756 *tick_val_ptr
= tick_val
;
1760 if (!ku_times_set
) {
1761 memset (kernel_time
, 0, sizeof (WapiFileTime
));
1762 memset (user_time
, 0, sizeof (WapiFileTime
));
1770 gpointer address_start
;
1771 gpointer address_end
;
1773 gpointer address_offset
;
1779 static void free_procmodule (WapiProcModule
*mod
)
1781 if (mod
->perms
!= NULL
) {
1782 g_free (mod
->perms
);
1784 if (mod
->filename
!= NULL
) {
1785 g_free (mod
->filename
);
1790 static gint
find_procmodule (gconstpointer a
, gconstpointer b
)
1792 WapiProcModule
*want
= (WapiProcModule
*)a
;
1793 WapiProcModule
*compare
= (WapiProcModule
*)b
;
1795 if ((want
->device
== compare
->device
) &&
1796 (want
->inode
== compare
->inode
)) {
1803 #ifdef PLATFORM_MACOSX
1804 #include <mach-o/dyld.h>
1805 #include <mach-o/getsect.h>
1807 static GSList
*load_modules (void)
1810 WapiProcModule
*mod
;
1811 uint32_t count
= _dyld_image_count ();
1814 for (i
= 0; i
< count
; i
++) {
1815 const struct mach_header
*hdr
;
1816 const struct section
*sec
;
1820 slide
= _dyld_get_image_vmaddr_slide (i
);
1821 name
= _dyld_get_image_name (i
);
1822 hdr
= _dyld_get_image_header (i
);
1823 sec
= getsectbynamefromheader (hdr
, SEG_DATA
, SECT_DATA
);
1825 /* Some dynlibs do not have data sections on osx (#533893) */
1830 mod
= g_new0 (WapiProcModule
, 1);
1831 mod
->address_start
= GINT_TO_POINTER (sec
->addr
);
1832 mod
->address_end
= GINT_TO_POINTER (sec
->addr
+sec
->size
);
1833 mod
->perms
= g_strdup ("r--p");
1834 mod
->address_offset
= 0;
1835 mod
->device
= makedev (0, 0);
1836 mod
->inode
= (ino_t
) i
;
1837 mod
->filename
= g_strdup (name
);
1839 if (g_slist_find_custom (ret
, mod
, find_procmodule
) == NULL
) {
1840 ret
= g_slist_prepend (ret
, mod
);
1842 free_procmodule (mod
);
1846 ret
= g_slist_reverse (ret
);
1851 static GSList
*load_modules (FILE *fp
)
1854 WapiProcModule
*mod
;
1855 gchar buf
[MAXPATHLEN
+ 1], *p
, *endp
;
1856 gchar
*start_start
, *end_start
, *prot_start
, *offset_start
;
1857 gchar
*maj_dev_start
, *min_dev_start
, *inode_start
, prot_buf
[5];
1858 gpointer address_start
, address_end
, address_offset
;
1859 guint32 maj_dev
, min_dev
;
1863 while (fgets (buf
, sizeof(buf
), fp
)) {
1865 while (g_ascii_isspace (*p
)) ++p
;
1867 if (!g_ascii_isxdigit (*start_start
)) {
1870 address_start
= (gpointer
)strtoul (start_start
, &endp
, 16);
1878 if (!g_ascii_isxdigit (*end_start
)) {
1881 address_end
= (gpointer
)strtoul (end_start
, &endp
, 16);
1883 if (!g_ascii_isspace (*p
)) {
1887 while (g_ascii_isspace (*p
)) ++p
;
1889 if (*prot_start
!= 'r' && *prot_start
!= '-') {
1892 memcpy (prot_buf
, prot_start
, 4);
1894 while (!g_ascii_isspace (*p
)) ++p
;
1896 while (g_ascii_isspace (*p
)) ++p
;
1898 if (!g_ascii_isxdigit (*offset_start
)) {
1901 address_offset
= (gpointer
)strtoul (offset_start
, &endp
, 16);
1903 if (!g_ascii_isspace (*p
)) {
1907 while(g_ascii_isspace (*p
)) ++p
;
1909 if (!g_ascii_isxdigit (*maj_dev_start
)) {
1912 maj_dev
= strtoul (maj_dev_start
, &endp
, 16);
1920 if (!g_ascii_isxdigit (*min_dev_start
)) {
1923 min_dev
= strtoul (min_dev_start
, &endp
, 16);
1925 if (!g_ascii_isspace (*p
)) {
1929 while (g_ascii_isspace (*p
)) ++p
;
1931 if (!g_ascii_isxdigit (*inode_start
)) {
1934 inode
= (ino_t
)strtol (inode_start
, &endp
, 10);
1936 if (!g_ascii_isspace (*p
)) {
1940 device
= makedev ((int)maj_dev
, (int)min_dev
);
1941 if ((device
== 0) &&
1946 while(g_ascii_isspace (*p
)) ++p
;
1947 /* p now points to the filename */
1949 mod
= g_new0 (WapiProcModule
, 1);
1950 mod
->address_start
= address_start
;
1951 mod
->address_end
= address_end
;
1952 mod
->perms
= g_strdup (prot_buf
);
1953 mod
->address_offset
= address_offset
;
1954 mod
->device
= device
;
1956 mod
->filename
= g_strdup (g_strstrip (p
));
1958 if (g_slist_find_custom (ret
, mod
, find_procmodule
) == NULL
) {
1959 ret
= g_slist_prepend (ret
, mod
);
1961 free_procmodule (mod
);
1965 ret
= g_slist_reverse (ret
);
1971 static gboolean
match_procname_to_modulename (gchar
*procname
, gchar
*modulename
)
1973 char* lastsep
= NULL
;
1976 gboolean result
= FALSE
;
1978 if (procname
== NULL
|| modulename
== NULL
)
1981 pname
= mono_path_resolve_symlinks (procname
);
1982 mname
= mono_path_resolve_symlinks (modulename
);
1984 if (!strcmp (pname
, mname
))
1988 lastsep
= strrchr (mname
, '/');
1990 if (!strcmp (lastsep
+1, pname
))
2001 open_process_map (int pid
, const char *mode
)
2004 const gchar
*proc_path
[] = {
2005 "/proc/%d/maps", /* GNU/Linux */
2006 "/proc/%d/map", /* FreeBSD */
2012 for (i
= 0; fp
== NULL
&& proc_path
[i
]; i
++) {
2013 filename
= g_strdup_printf (proc_path
[i
], pid
);
2014 fp
= fopen (filename
, mode
);
2021 gboolean
EnumProcessModules (gpointer process
, gpointer
*modules
,
2022 guint32 size
, guint32
*needed
)
2024 struct _WapiHandle_process
*process_handle
;
2027 GSList
*mods
= NULL
;
2028 WapiProcModule
*module
;
2029 guint32 count
, avail
= size
/ sizeof(gpointer
);
2032 gchar
*proc_name
= NULL
;
2034 /* Store modules in an array of pointers (main module as
2035 * modules[0]), using the load address for each module as a
2036 * token. (Use 'NULL' as an alternative for the main module
2037 * so that the simple implementation can just return one item
2038 * for now.) Get the info from /proc/<pid>/maps on linux,
2039 * /proc/<pid>/map on FreeBSD, other systems will have to
2040 * implement /dev/kmem reading or whatever other horrid
2041 * technique is needed.
2043 if (size
< sizeof(gpointer
)) {
2047 if ((GPOINTER_TO_UINT (process
) & _WAPI_PROCESS_UNHANDLED
) == _WAPI_PROCESS_UNHANDLED
) {
2048 /* This is a pseudo handle */
2049 pid
= (pid_t
)(GPOINTER_TO_UINT (process
) & _WAPI_PROCESS_UNHANDLED_PID_MASK
);
2051 ok
= _wapi_lookup_handle (process
, WAPI_HANDLE_PROCESS
,
2052 (gpointer
*)&process_handle
);
2055 g_message ("%s: Can't find process %p", __func__
, process
);
2060 pid
= process_handle
->id
;
2061 proc_name
= process_handle
->proc_name
;
2064 #ifdef PLATFORM_MACOSX
2066 mods
= load_modules ();
2068 if ((fp
= open_process_map (pid
, "r")) == NULL
) {
2069 /* No /proc/<pid>/maps so just return the main module
2073 *needed
= sizeof(gpointer
);
2075 mods
= load_modules (fp
);
2078 count
= g_slist_length (mods
);
2080 /* count + 1 to leave slot 0 for the main module */
2081 *needed
= sizeof(gpointer
) * (count
+ 1);
2083 /* Use the NULL shortcut, as the first line in
2084 * /proc/<pid>/maps isn't the executable, and we need
2085 * that first in the returned list. Check the module name
2086 * to see if it ends with the proc name and substitute
2087 * the first entry with it. FIXME if this turns out to
2091 for (i
= 0; i
< (avail
- 1) && i
< count
; i
++) {
2092 module
= (WapiProcModule
*)g_slist_nth_data (mods
, i
);
2093 if (modules
[0] != NULL
)
2094 modules
[i
] = module
->address_start
;
2095 else if (match_procname_to_modulename (proc_name
, module
->filename
))
2096 modules
[0] = module
->address_start
;
2098 modules
[i
+ 1] = module
->address_start
;
2101 for (i
= 0; i
< count
; i
++) {
2102 free_procmodule (g_slist_nth_data (mods
, i
));
2104 g_slist_free (mods
);
2110 static gchar
*get_process_name_from_proc (pid_t pid
)
2112 gchar
*filename
= NULL
;
2117 #if defined(PLATFORM_SOLARIS)
2118 filename
= g_strdup_printf ("/proc/%d/psinfo", pid
);
2119 if ((fp
= fopen (filename
, "r")) != NULL
) {
2123 nread
= fread (&info
, sizeof (info
), 1, fp
);
2125 ret
= g_strdup (info
.pr_fname
);
2131 #elif defined(PLATFORM_MACOSX)
2132 memset (buf
, '\0', sizeof(buf
));
2133 proc_name (pid
, buf
, sizeof(buf
));
2134 if (strlen (buf
) > 0)
2135 ret
= g_strdup (buf
);
2137 memset (buf
, '\0', sizeof(buf
));
2138 filename
= g_strdup_printf ("/proc/%d/exe", pid
);
2139 if (readlink (filename
, buf
, 255) > 0) {
2140 ret
= g_strdup (buf
);
2148 filename
= g_strdup_printf ("/proc/%d/cmdline", pid
);
2149 if ((fp
= fopen (filename
, "r")) != NULL
) {
2150 if (fgets (buf
, 256, fp
) != NULL
) {
2151 ret
= g_strdup (buf
);
2162 filename
= g_strdup_printf ("/proc/%d/stat", pid
);
2163 if ((fp
= fopen (filename
, "r")) != NULL
) {
2164 if (fgets (buf
, 256, fp
) != NULL
) {
2167 start
= strchr (buf
, '(');
2168 if (start
!= NULL
) {
2169 end
= strchr (start
+ 1, ')');
2172 ret
= g_strndup (start
+ 1,
2190 static guint32
get_module_name (gpointer process
, gpointer module
,
2191 gunichar2
*basename
, guint32 size
,
2194 struct _WapiHandle_process
*process_handle
;
2197 gunichar2
*procname
;
2198 gchar
*procname_ext
= NULL
;
2202 GSList
*mods
= NULL
;
2203 WapiProcModule
*found_module
;
2206 gchar
*proc_name
= NULL
;
2208 mono_once (&process_current_once
, process_set_current
);
2211 g_message ("%s: Getting module base name, process handle %p module %p",
2212 __func__
, process
, module
);
2215 size
= size
*sizeof(gunichar2
); /* adjust for unicode characters */
2217 if (basename
== NULL
|| size
== 0) {
2221 if ((GPOINTER_TO_UINT (process
) & _WAPI_PROCESS_UNHANDLED
) == _WAPI_PROCESS_UNHANDLED
) {
2222 /* This is a pseudo handle */
2223 pid
= (pid_t
)(GPOINTER_TO_UINT (process
) & _WAPI_PROCESS_UNHANDLED_PID_MASK
);
2224 proc_name
= get_process_name_from_proc (pid
);
2226 ok
= _wapi_lookup_handle (process
, WAPI_HANDLE_PROCESS
,
2227 (gpointer
*)&process_handle
);
2230 g_message ("%s: Can't find process %p", __func__
,
2236 pid
= process_handle
->id
;
2237 proc_name
= g_strdup (process_handle
->proc_name
);
2240 /* Look up the address in /proc/<pid>/maps */
2241 #ifdef PLATFORM_MACOSX
2243 mods
= load_modules ();
2245 if ((fp
= open_process_map (pid
, "r")) == NULL
) {
2246 if (errno
== EACCES
&& module
== NULL
&& base
== TRUE
) {
2247 procname_ext
= get_process_name_from_proc (pid
);
2249 /* No /proc/<pid>/maps, so just return failure
2256 mods
= load_modules (fp
);
2259 count
= g_slist_length (mods
);
2261 /* If module != NULL compare the address.
2262 * If module == NULL we are looking for the main module.
2263 * The best we can do for now check it the module name end with the process name.
2265 for (i
= 0; i
< count
; i
++) {
2266 found_module
= (WapiProcModule
*)g_slist_nth_data (mods
, i
);
2267 if (procname_ext
== NULL
&&
2268 ((module
== NULL
&& match_procname_to_modulename (proc_name
, found_module
->filename
)) ||
2269 (module
!= NULL
&& found_module
->address_start
== module
))) {
2271 procname_ext
= g_path_get_basename (found_module
->filename
);
2273 procname_ext
= g_strdup (found_module
->filename
);
2277 free_procmodule (found_module
);
2280 if (procname_ext
== NULL
)
2282 /* If it's *still* null, we might have hit the
2283 * case where reading /proc/$pid/maps gives an
2284 * empty file for this user.
2286 procname_ext
= get_process_name_from_proc (pid
);
2289 g_slist_free (mods
);
2293 if (procname_ext
!= NULL
) {
2295 g_message ("%s: Process name is [%s]", __func__
,
2299 procname
= mono_unicode_from_external (procname_ext
, &bytes
);
2300 if (procname
== NULL
) {
2302 g_free (procname_ext
);
2308 /* Add the terminator */
2313 g_message ("%s: Size %d smaller than needed (%ld); truncating", __func__
, size
, bytes
);
2316 memcpy (basename
, procname
, size
);
2319 g_message ("%s: Size %d larger than needed (%ld)",
2320 __func__
, size
, bytes
);
2323 memcpy (basename
, procname
, bytes
);
2327 g_free (procname_ext
);
2335 guint32
GetModuleBaseName (gpointer process
, gpointer module
,
2336 gunichar2
*basename
, guint32 size
)
2338 return(get_module_name (process
, module
, basename
, size
, TRUE
));
2341 guint32
GetModuleFileNameEx (gpointer process
, gpointer module
,
2342 gunichar2
*filename
, guint32 size
)
2344 return(get_module_name (process
, module
, filename
, size
, FALSE
));
2347 gboolean
GetModuleInformation (gpointer process
, gpointer module
,
2348 WapiModuleInfo
*modinfo
, guint32 size
)
2350 struct _WapiHandle_process
*process_handle
;
2354 GSList
*mods
= NULL
;
2355 WapiProcModule
*found_module
;
2358 gboolean ret
= FALSE
;
2359 gchar
*proc_name
= NULL
;
2361 mono_once (&process_current_once
, process_set_current
);
2364 g_message ("%s: Getting module info, process handle %p module %p",
2365 __func__
, process
, module
);
2368 if (modinfo
== NULL
|| size
< sizeof(WapiModuleInfo
)) {
2372 if ((GPOINTER_TO_UINT (process
) & _WAPI_PROCESS_UNHANDLED
) == _WAPI_PROCESS_UNHANDLED
) {
2373 /* This is a pseudo handle */
2374 pid
= (pid_t
)(GPOINTER_TO_UINT (process
) & _WAPI_PROCESS_UNHANDLED_PID_MASK
);
2375 proc_name
= get_process_name_from_proc (pid
);
2377 ok
= _wapi_lookup_handle (process
, WAPI_HANDLE_PROCESS
,
2378 (gpointer
*)&process_handle
);
2381 g_message ("%s: Can't find process %p", __func__
,
2387 pid
= process_handle
->id
;
2388 proc_name
= g_strdup (process_handle
->proc_name
);
2391 #ifdef PLATFORM_MACOSX
2393 mods
= load_modules ();
2395 /* Look up the address in /proc/<pid>/maps */
2396 if ((fp
= open_process_map (pid
, "r")) == NULL
) {
2397 /* No /proc/<pid>/maps, so just return failure
2403 mods
= load_modules (fp
);
2406 count
= g_slist_length (mods
);
2408 /* If module != NULL compare the address.
2409 * If module == NULL we are looking for the main module.
2410 * The best we can do for now check it the module name end with the process name.
2412 for (i
= 0; i
< count
; i
++) {
2413 found_module
= (WapiProcModule
*)g_slist_nth_data (mods
, i
);
2414 if ( ret
== FALSE
&&
2415 ((module
== NULL
&& match_procname_to_modulename (proc_name
, found_module
->filename
)) ||
2416 (module
!= NULL
&& found_module
->address_start
== module
))) {
2417 modinfo
->lpBaseOfDll
= found_module
->address_start
;
2418 modinfo
->SizeOfImage
= (gsize
)(found_module
->address_end
) - (gsize
)(found_module
->address_start
);
2419 modinfo
->EntryPoint
= found_module
->address_offset
;
2423 free_procmodule (found_module
);
2426 g_slist_free (mods
);
2433 gboolean
GetProcessWorkingSetSize (gpointer process
, size_t *min
, size_t *max
)
2435 struct _WapiHandle_process
*process_handle
;
2438 mono_once (&process_current_once
, process_set_current
);
2440 if(min
==NULL
|| max
==NULL
) {
2441 /* Not sure if w32 allows NULLs here or not */
2445 if ((GPOINTER_TO_UINT (process
) & _WAPI_PROCESS_UNHANDLED
) == _WAPI_PROCESS_UNHANDLED
) {
2446 /* This is a pseudo handle, so just fail for now
2451 ok
=_wapi_lookup_handle (process
, WAPI_HANDLE_PROCESS
,
2452 (gpointer
*)&process_handle
);
2455 g_message ("%s: Can't find process %p", __func__
, process
);
2461 *min
=process_handle
->min_working_set
;
2462 *max
=process_handle
->max_working_set
;
2467 gboolean
SetProcessWorkingSetSize (gpointer process
, size_t min
, size_t max
)
2469 struct _WapiHandle_process
*process_handle
;
2472 mono_once (&process_current_once
, process_set_current
);
2474 if ((GPOINTER_TO_UINT (process
) & _WAPI_PROCESS_UNHANDLED
) == _WAPI_PROCESS_UNHANDLED
) {
2475 /* This is a pseudo handle, so just fail for now
2480 ok
=_wapi_lookup_handle (process
, WAPI_HANDLE_PROCESS
,
2481 (gpointer
*)&process_handle
);
2484 g_message ("%s: Can't find process %p", __func__
, process
);
2490 process_handle
->min_working_set
=min
;
2491 process_handle
->max_working_set
=max
;
2498 TerminateProcess (gpointer process
, gint32 exitCode
)
2500 struct _WapiHandle_process
*process_handle
;
2506 if ((GPOINTER_TO_UINT (process
) & _WAPI_PROCESS_UNHANDLED
) == _WAPI_PROCESS_UNHANDLED
) {
2507 /* This is a pseudo handle */
2508 pid
= (pid_t
)(GPOINTER_TO_UINT (process
) & _WAPI_PROCESS_UNHANDLED_PID_MASK
);
2510 ok
= _wapi_lookup_handle (process
, WAPI_HANDLE_PROCESS
,
2511 (gpointer
*) &process_handle
);
2515 g_message ("%s: Can't find process %p", __func__
,
2518 SetLastError (ERROR_INVALID_HANDLE
);
2521 pid
= process_handle
->id
;
2524 signo
= (exitCode
== -1) ? SIGKILL
: SIGTERM
;
2525 ret
= kill (pid
, signo
);
2529 SetLastError (ERROR_INVALID_PARAMETER
);
2532 SetLastError (ERROR_ACCESS_DENIED
);
2535 SetLastError (ERROR_PROC_NOT_FOUND
);
2538 SetLastError (ERROR_GEN_FAILURE
);
2546 GetPriorityClass (gpointer process
)
2548 #ifdef HAVE_GETPRIORITY
2549 struct _WapiHandle_process
*process_handle
;
2554 if ((GPOINTER_TO_UINT (process
) & _WAPI_PROCESS_UNHANDLED
) == _WAPI_PROCESS_UNHANDLED
) {
2555 /* This is a pseudo handle */
2556 pid
= (pid_t
)(GPOINTER_TO_UINT (process
) & _WAPI_PROCESS_UNHANDLED_PID_MASK
);
2558 ok
= _wapi_lookup_handle (process
, WAPI_HANDLE_PROCESS
,
2559 (gpointer
*) &process_handle
);
2562 SetLastError (ERROR_INVALID_HANDLE
);
2565 pid
= process_handle
->id
;
2569 ret
= getpriority (PRIO_PROCESS
, pid
);
2570 if (ret
== -1 && errno
!= 0) {
2574 SetLastError (ERROR_ACCESS_DENIED
);
2577 SetLastError (ERROR_PROC_NOT_FOUND
);
2580 SetLastError (ERROR_GEN_FAILURE
);
2586 return NORMAL_PRIORITY_CLASS
;
2588 return REALTIME_PRIORITY_CLASS
;
2590 return HIGH_PRIORITY_CLASS
;
2592 return ABOVE_NORMAL_PRIORITY_CLASS
;
2594 return IDLE_PRIORITY_CLASS
;
2596 return BELOW_NORMAL_PRIORITY_CLASS
;
2598 return NORMAL_PRIORITY_CLASS
;
2600 SetLastError (ERROR_NOT_SUPPORTED
);
2606 SetPriorityClass (gpointer process
, guint32 priority_class
)
2608 #ifdef HAVE_SETPRIORITY
2609 struct _WapiHandle_process
*process_handle
;
2615 if ((GPOINTER_TO_UINT (process
) & _WAPI_PROCESS_UNHANDLED
) == _WAPI_PROCESS_UNHANDLED
) {
2616 /* This is a pseudo handle */
2617 pid
= (pid_t
)(GPOINTER_TO_UINT (process
) & _WAPI_PROCESS_UNHANDLED_PID_MASK
);
2619 ok
= _wapi_lookup_handle (process
, WAPI_HANDLE_PROCESS
,
2620 (gpointer
*) &process_handle
);
2623 SetLastError (ERROR_INVALID_HANDLE
);
2626 pid
= process_handle
->id
;
2629 switch (priority_class
) {
2630 case IDLE_PRIORITY_CLASS
:
2633 case BELOW_NORMAL_PRIORITY_CLASS
:
2636 case NORMAL_PRIORITY_CLASS
:
2639 case ABOVE_NORMAL_PRIORITY_CLASS
:
2642 case HIGH_PRIORITY_CLASS
:
2645 case REALTIME_PRIORITY_CLASS
:
2649 SetLastError (ERROR_INVALID_PARAMETER
);
2653 ret
= setpriority (PRIO_PROCESS
, pid
, prio
);
2658 SetLastError (ERROR_ACCESS_DENIED
);
2661 SetLastError (ERROR_PROC_NOT_FOUND
);
2664 SetLastError (ERROR_GEN_FAILURE
);
2670 SetLastError (ERROR_NOT_SUPPORTED
);