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
;
462 print_utf16 (gunichar2
*str
)
466 res
= g_utf16_to_utf8 (str
, -1, NULL
, NULL
, NULL
);
467 g_print ("%s\n", res
);
472 /* Implemented as just a wrapper around CreateProcess () */
473 gboolean
ShellExecuteEx (WapiShellExecuteInfo
*sei
)
476 WapiProcessInformation process_info
;
480 /* w2k just segfaults here, but we can do better than
483 SetLastError (ERROR_INVALID_PARAMETER
);
487 if (sei
->lpFile
== NULL
) {
488 /* w2k returns TRUE for this, for some reason. */
492 /* Put both executable and parameters into the second argument
493 * to CreateProcess (), so it searches $PATH. The conversion
494 * into and back out of utf8 is because there is no
495 * g_strdup_printf () equivalent for gunichar2 :-(
497 args
= utf16_concat (utf16_quote
, sei
->lpFile
, utf16_quote
, sei
->lpParameters
== NULL
? NULL
: utf16_space
, sei
->lpParameters
, NULL
);
499 SetLastError (ERROR_INVALID_DATA
);
502 ret
= CreateProcess (NULL
, args
, NULL
, NULL
, TRUE
,
503 CREATE_UNICODE_ENVIRONMENT
, NULL
,
504 sei
->lpDirectory
, NULL
, &process_info
);
507 if (!ret
&& GetLastError () == ERROR_OUTOFMEMORY
)
511 static char *handler
;
512 static gunichar2
*handler_utf16
;
514 if (handler_utf16
== (gunichar2
*)-1)
517 #ifdef PLATFORM_MACOSX
518 if (is_macos_10_5_or_higher ())
519 handler
= g_strdup ("/usr/bin/open -W");
521 handler
= g_strdup ("/usr/bin/open");
524 * On Linux, try: xdg-open, the FreeDesktop standard way of doing it,
525 * if that fails, try to use gnome-open, then kfmclient
527 handler
= g_find_program_in_path ("xdg-open");
528 if (handler
== NULL
){
529 handler
= g_find_program_in_path ("gnome-open");
530 if (handler
== NULL
){
531 handler
= g_find_program_in_path ("kfmclient");
532 if (handler
== NULL
){
533 handler_utf16
= (gunichar2
*) -1;
536 /* kfmclient needs exec argument */
538 handler
= g_strconcat (old
, " exec",
545 handler_utf16
= g_utf8_to_utf16 (handler
, -1, NULL
, NULL
, NULL
);
548 /* Put quotes around the filename, in case it's a url
549 * that contains #'s (CreateProcess() calls
550 * g_shell_parse_argv(), which deliberately throws
551 * away anything after an unquoted #). Fixes bug
554 args
= utf16_concat (handler_utf16
, utf16_space
, utf16_quote
,
555 sei
->lpFile
, utf16_quote
,
556 sei
->lpParameters
== NULL
? NULL
: utf16_space
,
557 sei
->lpParameters
, NULL
);
559 SetLastError (ERROR_INVALID_DATA
);
562 ret
= CreateProcess (NULL
, args
, NULL
, NULL
, TRUE
,
563 CREATE_UNICODE_ENVIRONMENT
, NULL
,
564 sei
->lpDirectory
, NULL
, &process_info
);
567 SetLastError (ERROR_INVALID_DATA
);
572 if (sei
->fMask
& SEE_MASK_NOCLOSEPROCESS
) {
573 sei
->hProcess
= process_info
.hProcess
;
575 CloseHandle (process_info
.hProcess
);
582 is_managed_binary (const gchar
*filename
)
584 int original_errno
= errno
;
585 #if defined(HAVE_LARGE_FILE_SUPPORT) && defined(O_LARGEFILE)
586 int file
= open (filename
, O_RDONLY
| O_LARGEFILE
);
588 int file
= open (filename
, O_RDONLY
);
591 unsigned char buffer
[8];
592 off_t file_size
, optional_header_offset
;
593 off_t pe_header_offset
;
594 gboolean managed
= FALSE
;
596 guint32 first_word
, second_word
;
598 /* If we are unable to open the file, then we definitely
599 * can't say that it is managed. The child mono process
600 * probably wouldn't be able to open it anyway.
603 errno
= original_errno
;
607 /* Retrieve the length of the file for future sanity checks. */
608 file_size
= lseek (file
, 0, SEEK_END
);
609 lseek (file
, 0, SEEK_SET
);
611 /* We know we need to read a header field at offset 60. */
615 num_read
= read (file
, buffer
, 2);
617 if ((num_read
!= 2) || (buffer
[0] != 'M') || (buffer
[1] != 'Z'))
620 new_offset
= lseek (file
, 60, SEEK_SET
);
622 if (new_offset
!= 60)
625 num_read
= read (file
, buffer
, 4);
629 pe_header_offset
= buffer
[0]
634 if (pe_header_offset
+ 24 > file_size
)
637 new_offset
= lseek (file
, pe_header_offset
, SEEK_SET
);
639 if (new_offset
!= pe_header_offset
)
642 num_read
= read (file
, buffer
, 4);
644 if ((num_read
!= 4) || (buffer
[0] != 'P') || (buffer
[1] != 'E') || (buffer
[2] != 0) || (buffer
[3] != 0))
648 * Verify that the header we want in the optional header data
649 * is present in this binary.
651 new_offset
= lseek (file
, pe_header_offset
+ 20, SEEK_SET
);
653 if (new_offset
!= pe_header_offset
+ 20)
656 num_read
= read (file
, buffer
, 2);
658 if ((num_read
!= 2) || ((buffer
[0] | (buffer
[1] << 8)) < 216))
661 /* Read the CLR header address and size fields. These will be
662 * zero if the binary is not managed.
664 optional_header_offset
= pe_header_offset
+ 24;
665 new_offset
= lseek (file
, optional_header_offset
+ 208, SEEK_SET
);
667 if (new_offset
!= optional_header_offset
+ 208)
670 num_read
= read (file
, buffer
, 8);
672 /* We are not concerned with endianness, only with
673 * whether it is zero or not.
675 first_word
= *(guint32
*)&buffer
[0];
676 second_word
= *(guint32
*)&buffer
[4];
678 if ((num_read
!= 8) || (first_word
== 0) || (second_word
== 0))
685 errno
= original_errno
;
689 gboolean
CreateProcessWithLogonW (const gunichar2
*username
,
690 const gunichar2
*domain
,
691 const gunichar2
*password
,
692 const guint32 logonFlags
,
693 const gunichar2
*appname
,
694 const gunichar2
*cmdline
,
695 guint32 create_flags
,
697 const gunichar2
*cwd
,
698 WapiStartupInfo
*startup
,
699 WapiProcessInformation
*process_info
)
701 /* FIXME: use user information */
702 return CreateProcess (appname
, cmdline
, NULL
, NULL
, FALSE
, create_flags
, env
, cwd
, startup
, process_info
);
706 is_executable (const char *prog
)
709 if (access (prog
, X_OK
) != 0)
711 if (stat (prog
, &buf
))
713 if (S_ISREG (buf
.st_mode
))
718 gboolean
CreateProcess (const gunichar2
*appname
, const gunichar2
*cmdline
,
719 WapiSecurityAttributes
*process_attrs G_GNUC_UNUSED
,
720 WapiSecurityAttributes
*thread_attrs G_GNUC_UNUSED
,
721 gboolean inherit_handles
, guint32 create_flags
,
722 gpointer new_environ
, const gunichar2
*cwd
,
723 WapiStartupInfo
*startup
,
724 WapiProcessInformation
*process_info
)
726 gchar
*cmd
=NULL
, *prog
= NULL
, *full_prog
= NULL
, *args
= NULL
, *args_after_prog
= NULL
, *dir
= NULL
, **env_strings
= NULL
, **argv
= NULL
;
727 guint32 i
, env_count
= 0;
728 gboolean ret
= FALSE
;
730 struct _WapiHandle_process process_handle
= {0}, *process_handle_data
;
732 int in_fd
, out_fd
, err_fd
;
736 mono_once (&process_ops_once
, process_ops_init
);
738 /* appname and cmdline specify the executable and its args:
740 * If appname is not NULL, it is the name of the executable.
741 * Otherwise the executable is the first token in cmdline.
743 * Executable searching:
745 * If appname is not NULL, it can specify the full path and
746 * file name, or else a partial name and the current directory
747 * will be used. There is no additional searching.
749 * If appname is NULL, the first whitespace-delimited token in
750 * cmdline is used. If the name does not contain a full
751 * directory path, the search sequence is:
753 * 1) The directory containing the current process
754 * 2) The current working directory
755 * 3) The windows system directory (Ignored)
756 * 4) The windows directory (Ignored)
759 * Just to make things more interesting, tokens can contain
760 * white space if they are surrounded by quotation marks. I'm
761 * beginning to understand just why windows apps are generally
762 * so crap, with an API like this :-(
764 if (appname
!= NULL
) {
765 cmd
= mono_unicode_to_external (appname
);
768 g_message ("%s: unicode conversion returned NULL",
772 SetLastError (ERROR_PATH_NOT_FOUND
);
776 /* Turn all the slashes round the right way */
777 for (i
= 0; i
< strlen (cmd
); i
++) {
778 if (cmd
[i
] == '\\') {
784 if (cmdline
!= NULL
) {
785 args
= mono_unicode_to_external (cmdline
);
788 g_message ("%s: unicode conversion returned NULL", __func__
);
791 SetLastError (ERROR_PATH_NOT_FOUND
);
797 dir
= mono_unicode_to_external (cwd
);
800 g_message ("%s: unicode conversion returned NULL", __func__
);
803 SetLastError (ERROR_PATH_NOT_FOUND
);
807 /* Turn all the slashes round the right way */
808 for (i
= 0; i
< strlen (dir
); i
++) {
809 if (dir
[i
] == '\\') {
816 /* We can't put off locating the executable any longer :-( */
819 if (g_ascii_isalpha (cmd
[0]) && (cmd
[1] == ':')) {
820 /* Strip off the drive letter. I can't
821 * believe that CP/M holdover is still
824 g_memmove (cmd
, cmd
+2, strlen (cmd
)-2);
825 cmd
[strlen (cmd
)-2] = '\0';
828 unquoted
= g_shell_unquote (cmd
, NULL
);
829 if (unquoted
[0] == '/') {
830 /* Assume full path given */
831 prog
= g_strdup (unquoted
);
833 /* Executable existing ? */
834 if (!is_executable (prog
)) {
836 g_message ("%s: Couldn't find executable %s",
840 SetLastError (ERROR_FILE_NOT_FOUND
);
844 /* Search for file named by cmd in the current
847 char *curdir
= g_get_current_dir ();
849 prog
= g_strdup_printf ("%s/%s", curdir
, unquoted
);
852 /* And make sure it's executable */
853 if (!is_executable (prog
)) {
855 g_message ("%s: Couldn't find executable %s",
859 SetLastError (ERROR_FILE_NOT_FOUND
);
865 args_after_prog
= args
;
871 /* Dig out the first token from args, taking quotation
875 /* First, strip off all leading whitespace */
876 args
= g_strchug (args
);
878 /* args_after_prog points to the contents of args
879 * after token has been set (otherwise argv[0] is
882 args_after_prog
= args
;
884 /* Assume the opening quote will always be the first
887 if (args
[0] == '\"' || args
[0] == '\'') {
889 for (i
= 1; args
[i
] != '\0' && args
[i
] != quote
; i
++);
890 if (args
[i
+ 1] == '\0' || g_ascii_isspace (args
[i
+1])) {
891 /* We found the first token */
892 token
= g_strndup (args
+1, i
-1);
893 args_after_prog
= g_strchug (args
+ i
+ 1);
895 /* Quotation mark appeared in the
896 * middle of the token. Just give the
897 * whole first token, quotes and all,
904 /* No quote mark, or malformed */
905 for (i
= 0; args
[i
] != '\0'; i
++) {
906 if (g_ascii_isspace (args
[i
])) {
907 token
= g_strndup (args
, i
);
908 args_after_prog
= args
+ i
+ 1;
914 if (token
== NULL
&& args
[0] != '\0') {
915 /* Must be just one token in the string */
916 token
= g_strdup (args
);
917 args_after_prog
= NULL
;
923 g_message ("%s: Couldn't find what to exec", __func__
);
926 SetLastError (ERROR_PATH_NOT_FOUND
);
930 /* Turn all the slashes round the right way. Only for
933 token_len
= strlen (token
);
934 for (i
= 0; i
< token_len
; i
++) {
935 if (token
[i
] == '\\') {
940 if (g_ascii_isalpha (token
[0]) && (token
[1] == ':')) {
941 /* Strip off the drive letter. I can't
942 * believe that CP/M holdover is still
945 g_memmove (token
, token
+2, strlen (token
)-2);
946 token
[strlen (token
)-2] = '\0';
949 if (token
[0] == '/') {
950 /* Assume full path given */
951 prog
= g_strdup (token
);
953 /* Executable existing ? */
954 if (!is_executable (prog
)) {
956 g_message ("%s: Couldn't find executable %s",
960 SetLastError (ERROR_FILE_NOT_FOUND
);
965 char *curdir
= g_get_current_dir ();
967 /* FIXME: Need to record the directory
968 * containing the current process, and check
969 * that for the new executable as the first
973 prog
= g_strdup_printf ("%s/%s", curdir
, token
);
976 /* I assume X_OK is the criterion to use,
979 if (!is_executable (prog
)) {
981 prog
= g_find_program_in_path (token
);
984 g_message ("%s: Couldn't find executable %s", __func__
, token
);
988 SetLastError (ERROR_FILE_NOT_FOUND
);
998 g_message ("%s: Exec prog [%s] args [%s]", __func__
, prog
,
1002 /* Check for CLR binaries; if found, we will try to invoke
1003 * them using the same mono binary that started us.
1005 if (is_managed_binary (prog
)) {
1006 gunichar2
*newapp
, *newcmd
;
1007 gsize bytes_ignored
;
1009 newapp
= mono_unicode_from_external ("mono", &bytes_ignored
);
1011 if (newapp
!= NULL
) {
1012 if (appname
!= NULL
) {
1013 newcmd
= utf16_concat (newapp
, utf16_space
,
1014 appname
, utf16_space
,
1017 newcmd
= utf16_concat (newapp
, utf16_space
,
1021 g_free ((gunichar2
*)newapp
);
1023 if (newcmd
!= NULL
) {
1024 ret
= CreateProcess (NULL
, newcmd
,
1028 create_flags
, new_environ
,
1032 g_free ((gunichar2
*)newcmd
);
1039 if (args_after_prog
!= NULL
&& *args_after_prog
) {
1042 qprog
= g_shell_quote (prog
);
1043 full_prog
= g_strconcat (qprog
, " ", args_after_prog
, NULL
);
1046 full_prog
= g_shell_quote (prog
);
1049 ret
= g_shell_parse_argv (full_prog
, NULL
, &argv
, &gerr
);
1051 g_message ("CreateProcess: %s\n", gerr
->message
);
1052 g_error_free (gerr
);
1057 if (startup
!= NULL
&& startup
->dwFlags
& STARTF_USESTDHANDLES
) {
1058 in_fd
= GPOINTER_TO_UINT (startup
->hStdInput
);
1059 out_fd
= GPOINTER_TO_UINT (startup
->hStdOutput
);
1060 err_fd
= GPOINTER_TO_UINT (startup
->hStdError
);
1062 in_fd
= GPOINTER_TO_UINT (GetStdHandle (STD_INPUT_HANDLE
));
1063 out_fd
= GPOINTER_TO_UINT (GetStdHandle (STD_OUTPUT_HANDLE
));
1064 err_fd
= GPOINTER_TO_UINT (GetStdHandle (STD_ERROR_HANDLE
));
1067 g_strlcpy (process_handle
.proc_name
, prog
,
1068 _WAPI_PROC_NAME_MAX_LEN
- 1);
1070 process_set_defaults (&process_handle
);
1072 handle
= _wapi_handle_new (WAPI_HANDLE_PROCESS
, &process_handle
);
1073 if (handle
== _WAPI_HANDLE_INVALID
) {
1074 g_warning ("%s: error creating process handle", __func__
);
1077 SetLastError (ERROR_OUTOFMEMORY
);
1081 /* Hold another reference so the process has somewhere to
1082 * store its exit data even if we drop this handle
1084 _wapi_handle_ref (handle
);
1086 /* new_environ is a block of NULL-terminated strings, which
1087 * is itself NULL-terminated. Of course, passing an array of
1088 * string pointers would have made things too easy :-(
1090 * If new_environ is not NULL it specifies the entire set of
1091 * environment variables in the new process. Otherwise the
1092 * new process inherits the same environment.
1094 if (new_environ
!= NULL
) {
1095 gunichar2
*new_environp
;
1097 /* Count the number of strings */
1098 for (new_environp
= (gunichar2
*)new_environ
; *new_environp
;
1101 while (*new_environp
) {
1106 /* +2: one for the process handle value, and the last
1109 env_strings
= g_new0 (gchar
*, env_count
+ 2);
1111 /* Copy each environ string into 'strings' turning it
1112 * into utf8 (or the requested encoding) at the same
1116 for (new_environp
= (gunichar2
*)new_environ
; *new_environp
;
1118 env_strings
[env_count
] = mono_unicode_to_external (new_environp
);
1120 while (*new_environp
) {
1125 for (i
= 0; environ
[i
] != NULL
; i
++) {
1129 /* +2: one for the process handle value, and the last
1132 env_strings
= g_new0 (gchar
*, env_count
+ 2);
1134 /* Copy each environ string into 'strings' turning it
1135 * into utf8 (or the requested encoding) at the same
1139 for (i
= 0; environ
[i
] != NULL
; i
++) {
1140 env_strings
[env_count
] = g_strdup (environ
[i
]);
1144 /* pass process handle info to the child, so it doesn't have
1145 * to do an expensive search over the whole list
1147 if (env_strings
!= NULL
) {
1148 struct _WapiHandleUnshared
*handle_data
;
1149 struct _WapiHandle_shared_ref
*ref
;
1151 handle_data
= &_WAPI_PRIVATE_HANDLES(GPOINTER_TO_UINT(handle
));
1152 ref
= &handle_data
->u
.shared
;
1154 env_strings
[env_count
] = g_strdup_printf ("_WAPI_PROCESS_HANDLE_OFFSET=%d", ref
->offset
);
1157 thr_ret
= _wapi_handle_lock_shared_handles ();
1158 g_assert (thr_ret
== 0);
1163 SetLastError (ERROR_OUTOFMEMORY
);
1164 _wapi_handle_unref (handle
);
1166 } else if (pid
== 0) {
1169 if (_wapi_shm_disabled
== FALSE
) {
1170 /* Wait for the parent to finish setting up
1171 * the handle. The semaphore lock is safe
1172 * because the sem_undo structures of a
1173 * semaphore aren't inherited across a fork
1174 * (), but we can't do this if we're not using
1177 thr_ret
= _wapi_handle_lock_shared_handles ();
1178 g_assert (thr_ret
== 0);
1180 _wapi_handle_unlock_shared_handles ();
1183 /* should we detach from the process group? */
1185 /* Connect stdin, stdout and stderr */
1190 if (inherit_handles
!= TRUE
) {
1191 /* FIXME: do something here */
1194 /* Close all file descriptors */
1195 for (i
= getdtablesize () - 1; i
> 2; i
--) {
1200 g_message ("%s: exec()ing [%s] in dir [%s]", __func__
, cmd
,
1202 for (i
= 0; argv
[i
] != NULL
; i
++) {
1203 g_message ("arg %d: [%s]", i
, argv
[i
]);
1206 for (i
= 0; env_strings
[i
] != NULL
; i
++) {
1207 g_message ("env %d: [%s]", i
, env_strings
[i
]);
1212 if (dir
!= NULL
&& chdir (dir
) == -1) {
1218 execve (argv
[0], argv
, env_strings
);
1225 ret
= _wapi_lookup_handle (handle
, WAPI_HANDLE_PROCESS
,
1226 (gpointer
*)&process_handle_data
);
1228 g_warning ("%s: error looking up process handle %p", __func__
,
1230 _wapi_handle_unref (handle
);
1234 process_handle_data
->id
= pid
;
1236 if (process_info
!= NULL
) {
1237 process_info
->hProcess
= handle
;
1238 process_info
->dwProcessId
= pid
;
1240 /* FIXME: we might need to handle the thread info some
1243 process_info
->hThread
= INVALID_HANDLE_VALUE
;
1244 process_info
->dwThreadId
= 0;
1248 _wapi_handle_unlock_shared_handles ();
1254 if (full_prog
!= NULL
) {
1266 if(env_strings
!= NULL
) {
1267 g_strfreev (env_strings
);
1274 g_message ("%s: returning handle %p for pid %d", __func__
, handle
,
1281 static void process_set_name (struct _WapiHandle_process
*process_handle
)
1283 gchar
*progname
, *utf8_progname
, *slash
;
1285 progname
=g_get_prgname ();
1286 utf8_progname
=mono_utf8_from_external (progname
);
1289 g_message ("%s: using [%s] as prog name", __func__
, progname
);
1292 if(utf8_progname
!=NULL
) {
1293 slash
=strrchr (utf8_progname
, '/');
1295 g_strlcpy (process_handle
->proc_name
, slash
+1,
1296 _WAPI_PROC_NAME_MAX_LEN
- 1);
1298 g_strlcpy (process_handle
->proc_name
, utf8_progname
,
1299 _WAPI_PROC_NAME_MAX_LEN
- 1);
1302 g_free (utf8_progname
);
1306 extern void _wapi_time_t_to_filetime (time_t timeval
, WapiFileTime
*filetime
);
1308 #if !GLIB_CHECK_VERSION (2,4,0)
1309 #define g_setenv(a,b,c) setenv(a,b,c)
1310 #define g_unsetenv(a) unsetenv(a)
1313 static void process_set_current (void)
1315 pid_t pid
= _wapi_getpid ();
1316 const char *handle_env
;
1317 struct _WapiHandle_process process_handle
= {0};
1319 mono_once (&process_ops_once
, process_ops_init
);
1321 handle_env
= g_getenv ("_WAPI_PROCESS_HANDLE_OFFSET");
1322 g_unsetenv ("_WAPI_PROCESS_HANDLE_OFFSET");
1324 if (handle_env
!= NULL
) {
1325 struct _WapiHandle_process
*process_handlep
;
1326 gchar
*procname
= NULL
;
1329 current_process
= _wapi_handle_new_from_offset (WAPI_HANDLE_PROCESS
, atoi (handle_env
), TRUE
);
1332 g_message ("%s: Found my process handle: %p (offset %d 0x%x)",
1333 __func__
, current_process
, atoi (handle_env
),
1337 ok
= _wapi_lookup_handle (current_process
, WAPI_HANDLE_PROCESS
,
1338 (gpointer
*)&process_handlep
);
1340 /* This test will probably break on linuxthreads, but
1341 * that should be ancient history on all distros we
1344 if (process_handlep
->id
== pid
) {
1345 procname
= process_handlep
->proc_name
;
1346 if (!strcmp (procname
, "mono")) {
1347 /* Set a better process name */
1349 g_message ("%s: Setting better process name", __func__
);
1352 process_set_name (process_handlep
);
1355 g_message ("%s: Leaving process name: %s", __func__
, procname
);
1362 /* Wrong pid, so drop this handle and fall through to
1365 _wapi_handle_unref (current_process
);
1369 /* We get here if the handle wasn't specified in the
1370 * environment, or if the process ID was wrong, or if the
1371 * handle lookup failed (eg if the parent process forked and
1372 * quit immediately, and deleted the shared data before the
1373 * child got a chance to attach it.)
1377 g_message ("%s: Need to create my own process handle", __func__
);
1380 process_handle
.id
= pid
;
1382 process_set_defaults (&process_handle
);
1383 process_set_name (&process_handle
);
1385 current_process
= _wapi_handle_new (WAPI_HANDLE_PROCESS
,
1387 if (current_process
== _WAPI_HANDLE_INVALID
) {
1388 g_warning ("%s: error creating process handle", __func__
);
1393 gpointer
_wapi_process_duplicate ()
1395 mono_once (&process_current_once
, process_set_current
);
1397 _wapi_handle_ref (current_process
);
1399 return(current_process
);
1402 /* Returns a pseudo handle that doesn't need to be closed afterwards */
1403 gpointer
GetCurrentProcess (void)
1405 mono_once (&process_current_once
, process_set_current
);
1407 return(_WAPI_PROCESS_CURRENT
);
1410 guint32
GetProcessId (gpointer handle
)
1412 struct _WapiHandle_process
*process_handle
;
1415 if ((GPOINTER_TO_UINT (handle
) & _WAPI_PROCESS_UNHANDLED
) == _WAPI_PROCESS_UNHANDLED
) {
1416 /* This is a pseudo handle */
1417 return(GPOINTER_TO_UINT (handle
) & _WAPI_PROCESS_UNHANDLED_PID_MASK
);
1420 ok
= _wapi_lookup_handle (handle
, WAPI_HANDLE_PROCESS
,
1421 (gpointer
*)&process_handle
);
1423 SetLastError (ERROR_INVALID_HANDLE
);
1427 return (process_handle
->id
);
1430 guint32
GetCurrentProcessId (void)
1432 mono_once (&process_current_once
, process_set_current
);
1434 return (GetProcessId (current_process
));
1437 /* Returns the process id as a convenience to the functions that call this */
1438 static pid_t
signal_process_if_gone (gpointer handle
)
1440 struct _WapiHandle_process
*process_handle
;
1443 g_assert ((GPOINTER_TO_UINT (handle
) & _WAPI_PROCESS_UNHANDLED
) != _WAPI_PROCESS_UNHANDLED
);
1445 /* Make sure the process is signalled if it has exited - if
1446 * the parent process didn't wait for it then it won't be
1448 ok
= _wapi_lookup_handle (handle
, WAPI_HANDLE_PROCESS
,
1449 (gpointer
*)&process_handle
);
1451 /* It's possible that the handle has vanished during
1452 * the _wapi_search_handle before it gets here, so
1453 * don't spam the console with warnings.
1455 /* g_warning ("%s: error looking up process handle %p",
1456 __func__, handle);*/
1462 g_message ("%s: looking at process %d", __func__
, process_handle
->id
);
1465 if (kill (process_handle
->id
, 0) == -1 &&
1468 /* The process is dead, (EPERM tells us a new process
1469 * has that ID, but as it's owned by someone else it
1470 * can't be the one listed in our shared memory file)
1472 _wapi_shared_handle_set_signal_state (handle
, TRUE
);
1475 return (process_handle
->id
);
1479 static gboolean
process_enum (gpointer handle
, gpointer user_data
)
1481 GArray
*processes
=user_data
;
1482 pid_t pid
= signal_process_if_gone (handle
);
1489 /* Ignore processes that have already exited (ie they are signalled) */
1490 if (_wapi_handle_issignalled (handle
) == FALSE
) {
1492 g_message ("%s: process %d added to array", __func__
, pid
);
1495 /* This ensures that duplicates aren't returned (see
1496 * the comment above _wapi_search_handle () for why
1499 for (i
= 0; i
< processes
->len
; i
++) {
1500 if (g_array_index (processes
, pid_t
, i
) == pid
) {
1501 /* We've already got this one, return
1502 * FALSE to keep searching
1508 g_array_append_val (processes
, pid
);
1511 /* Return false to keep searching */
1514 #endif /* UNUSED_CODE */
1516 #ifdef PLATFORM_MACOSX
1518 gboolean
EnumProcesses (guint32
*pids
, guint32 len
, guint32
*needed
)
1520 guint32 count
, fit
, i
, j
;
1523 struct kinfo_proc
*result
;
1525 static const int name
[] = { CTL_KERN
, KERN_PROC
, KERN_PROC_ALL
, 0 };
1527 mono_once (&process_current_once
, process_set_current
);
1534 err
= sysctl ((int *)name
, (sizeof(name
) / sizeof(*name
)) - 1, NULL
, &proclength
, NULL
, 0);
1537 result
= malloc (proclength
);
1541 err
= sysctl ((int *) name
, (sizeof(name
) / sizeof(*name
)) - 1, result
, &proclength
, NULL
, 0);
1548 } while (err
== 0 && !done
);
1551 if (result
!= NULL
) {
1558 count
= proclength
/ sizeof(struct kinfo_proc
);
1559 fit
= len
/ sizeof(guint32
);
1560 for (i
= 0, j
= 0; j
< fit
&& i
< count
; i
++) {
1561 pids
[j
++] = result
[i
].kp_proc
.p_pid
;
1565 *needed
= j
* sizeof(guint32
);
1570 gboolean
EnumProcesses (guint32
*pids
, guint32 len
, guint32
*needed
)
1572 GArray
*processes
= g_array_new (FALSE
, FALSE
, sizeof(pid_t
));
1575 struct dirent
*entry
;
1577 mono_once (&process_current_once
, process_set_current
);
1579 dir
= opendir ("/proc");
1583 while((entry
= readdir (dir
)) != NULL
) {
1584 if (isdigit (entry
->d_name
[0])) {
1586 pid_t pid
= (pid_t
)strtol (entry
->d_name
, &endptr
, 10);
1588 if (*endptr
== '\0') {
1589 /* Name was entirely numeric, so was a
1592 g_array_append_val (processes
, pid
);
1598 fit
=len
/sizeof(guint32
);
1599 for (i
= 0, j
= 0; j
< fit
&& i
< processes
->len
; i
++) {
1600 pids
[j
++] = g_array_index (processes
, pid_t
, i
);
1603 g_array_free (processes
, TRUE
);
1605 *needed
= j
* sizeof(guint32
);
1611 static gboolean
process_open_compare (gpointer handle
, gpointer user_data
)
1614 pid_t checking_pid
= signal_process_if_gone (handle
);
1616 if (checking_pid
== 0) {
1620 wanted_pid
= GPOINTER_TO_UINT (user_data
);
1622 /* It's possible to have more than one process handle with the
1623 * same pid, but only the one running process can be
1626 if (checking_pid
== wanted_pid
&&
1627 _wapi_handle_issignalled (handle
) == FALSE
) {
1628 /* If the handle is blown away in the window between
1629 * returning TRUE here and _wapi_search_handle pinging
1630 * the timestamp, the search will continue
1638 gpointer
OpenProcess (guint32 req_access G_GNUC_UNUSED
, gboolean inherit G_GNUC_UNUSED
, guint32 pid
)
1640 /* Find the process handle that corresponds to pid */
1643 mono_once (&process_current_once
, process_set_current
);
1646 g_message ("%s: looking for process %d", __func__
, pid
);
1649 handle
= _wapi_search_handle (WAPI_HANDLE_PROCESS
,
1650 process_open_compare
,
1651 GUINT_TO_POINTER (pid
), NULL
, TRUE
);
1653 gchar
*dir
= g_strdup_printf ("/proc/%d", pid
);
1654 if (!access (dir
, F_OK
)) {
1655 /* Return a pseudo handle for processes we
1656 * don't have handles for
1658 return GINT_TO_POINTER (_WAPI_PROCESS_UNHANDLED
+ pid
);
1661 g_message ("%s: Can't find pid %d", __func__
, pid
);
1664 SetLastError (ERROR_PROC_NOT_FOUND
);
1670 _wapi_handle_ref (handle
);
1675 gboolean
GetExitCodeProcess (gpointer process
, guint32
*code
)
1677 struct _WapiHandle_process
*process_handle
;
1680 mono_once (&process_current_once
, process_set_current
);
1686 if ((GPOINTER_TO_UINT (process
) & _WAPI_PROCESS_UNHANDLED
) == _WAPI_PROCESS_UNHANDLED
) {
1687 /* This is a pseudo handle, so we don't know what the
1693 ok
=_wapi_lookup_handle (process
, WAPI_HANDLE_PROCESS
,
1694 (gpointer
*)&process_handle
);
1697 g_message ("%s: Can't find process %p", __func__
, process
);
1703 /* A process handle is only signalled if the process has exited
1704 * and has been waited for */
1706 /* Make sure any process exit has been noticed, before
1707 * checking if the process is signalled. Fixes bug 325463.
1709 process_wait (process
, 0);
1711 if (_wapi_handle_issignalled (process
) == TRUE
) {
1712 *code
= process_handle
->exitstatus
;
1714 *code
= STILL_ACTIVE
;
1720 gboolean
GetProcessTimes (gpointer process
, WapiFileTime
*create_time
,
1721 WapiFileTime
*exit_time
, WapiFileTime
*kernel_time
,
1722 WapiFileTime
*user_time
)
1724 struct _WapiHandle_process
*process_handle
;
1726 gboolean ku_times_set
= FALSE
;
1728 mono_once (&process_current_once
, process_set_current
);
1730 if(create_time
==NULL
|| exit_time
==NULL
|| kernel_time
==NULL
||
1732 /* Not sure if w32 allows NULLs here or not */
1736 if ((GPOINTER_TO_UINT (process
) & _WAPI_PROCESS_UNHANDLED
) == _WAPI_PROCESS_UNHANDLED
) {
1737 /* This is a pseudo handle, so just fail for now
1742 ok
=_wapi_lookup_handle (process
, WAPI_HANDLE_PROCESS
,
1743 (gpointer
*)&process_handle
);
1746 g_message ("%s: Can't find process %p", __func__
, process
);
1752 *create_time
=process_handle
->create_time
;
1754 /* A process handle is only signalled if the process has
1755 * exited. Otherwise exit_time isn't set
1757 if(_wapi_handle_issignalled (process
)==TRUE
) {
1758 *exit_time
=process_handle
->exit_time
;
1761 #ifdef HAVE_GETRUSAGE
1762 if (process_handle
->id
== getpid ()) {
1763 struct rusage time_data
;
1764 if (getrusage (RUSAGE_SELF
, &time_data
) == 0) {
1766 gint64
*tick_val_ptr
;
1767 ku_times_set
= TRUE
;
1768 tick_val
= time_data
.ru_utime
.tv_sec
* 10000000 + time_data
.ru_utime
.tv_usec
* 10;
1769 tick_val_ptr
= (gint64
*)user_time
;
1770 *tick_val_ptr
= tick_val
;
1771 tick_val
= time_data
.ru_stime
.tv_sec
* 10000000 + time_data
.ru_stime
.tv_usec
* 10;
1772 tick_val_ptr
= (gint64
*)kernel_time
;
1773 *tick_val_ptr
= tick_val
;
1777 if (!ku_times_set
) {
1778 memset (kernel_time
, 0, sizeof (WapiFileTime
));
1779 memset (user_time
, 0, sizeof (WapiFileTime
));
1787 gpointer address_start
;
1788 gpointer address_end
;
1790 gpointer address_offset
;
1796 static void free_procmodule (WapiProcModule
*mod
)
1798 if (mod
->perms
!= NULL
) {
1799 g_free (mod
->perms
);
1801 if (mod
->filename
!= NULL
) {
1802 g_free (mod
->filename
);
1807 static gint
find_procmodule (gconstpointer a
, gconstpointer b
)
1809 WapiProcModule
*want
= (WapiProcModule
*)a
;
1810 WapiProcModule
*compare
= (WapiProcModule
*)b
;
1812 if ((want
->device
== compare
->device
) &&
1813 (want
->inode
== compare
->inode
)) {
1820 #ifdef PLATFORM_MACOSX
1821 #include <mach-o/dyld.h>
1822 #include <mach-o/getsect.h>
1824 static GSList
*load_modules (void)
1827 WapiProcModule
*mod
;
1828 uint32_t count
= _dyld_image_count ();
1831 for (i
= 0; i
< count
; i
++) {
1832 const struct mach_header
*hdr
;
1833 const struct section
*sec
;
1837 slide
= _dyld_get_image_vmaddr_slide (i
);
1838 name
= _dyld_get_image_name (i
);
1839 hdr
= _dyld_get_image_header (i
);
1840 sec
= getsectbynamefromheader (hdr
, SEG_DATA
, SECT_DATA
);
1842 /* Some dynlibs do not have data sections on osx (#533893) */
1847 mod
= g_new0 (WapiProcModule
, 1);
1848 mod
->address_start
= GINT_TO_POINTER (sec
->addr
);
1849 mod
->address_end
= GINT_TO_POINTER (sec
->addr
+sec
->size
);
1850 mod
->perms
= g_strdup ("r--p");
1851 mod
->address_offset
= 0;
1852 mod
->device
= makedev (0, 0);
1853 mod
->inode
= (ino_t
) i
;
1854 mod
->filename
= g_strdup (name
);
1856 if (g_slist_find_custom (ret
, mod
, find_procmodule
) == NULL
) {
1857 ret
= g_slist_prepend (ret
, mod
);
1859 free_procmodule (mod
);
1863 ret
= g_slist_reverse (ret
);
1868 static GSList
*load_modules (FILE *fp
)
1871 WapiProcModule
*mod
;
1872 gchar buf
[MAXPATHLEN
+ 1], *p
, *endp
;
1873 gchar
*start_start
, *end_start
, *prot_start
, *offset_start
;
1874 gchar
*maj_dev_start
, *min_dev_start
, *inode_start
, prot_buf
[5];
1875 gpointer address_start
, address_end
, address_offset
;
1876 guint32 maj_dev
, min_dev
;
1880 while (fgets (buf
, sizeof(buf
), fp
)) {
1882 while (g_ascii_isspace (*p
)) ++p
;
1884 if (!g_ascii_isxdigit (*start_start
)) {
1887 address_start
= (gpointer
)strtoul (start_start
, &endp
, 16);
1895 if (!g_ascii_isxdigit (*end_start
)) {
1898 address_end
= (gpointer
)strtoul (end_start
, &endp
, 16);
1900 if (!g_ascii_isspace (*p
)) {
1904 while (g_ascii_isspace (*p
)) ++p
;
1906 if (*prot_start
!= 'r' && *prot_start
!= '-') {
1909 memcpy (prot_buf
, prot_start
, 4);
1911 while (!g_ascii_isspace (*p
)) ++p
;
1913 while (g_ascii_isspace (*p
)) ++p
;
1915 if (!g_ascii_isxdigit (*offset_start
)) {
1918 address_offset
= (gpointer
)strtoul (offset_start
, &endp
, 16);
1920 if (!g_ascii_isspace (*p
)) {
1924 while(g_ascii_isspace (*p
)) ++p
;
1926 if (!g_ascii_isxdigit (*maj_dev_start
)) {
1929 maj_dev
= strtoul (maj_dev_start
, &endp
, 16);
1937 if (!g_ascii_isxdigit (*min_dev_start
)) {
1940 min_dev
= strtoul (min_dev_start
, &endp
, 16);
1942 if (!g_ascii_isspace (*p
)) {
1946 while (g_ascii_isspace (*p
)) ++p
;
1948 if (!g_ascii_isxdigit (*inode_start
)) {
1951 inode
= (ino_t
)strtol (inode_start
, &endp
, 10);
1953 if (!g_ascii_isspace (*p
)) {
1957 device
= makedev ((int)maj_dev
, (int)min_dev
);
1958 if ((device
== 0) &&
1963 while(g_ascii_isspace (*p
)) ++p
;
1964 /* p now points to the filename */
1966 mod
= g_new0 (WapiProcModule
, 1);
1967 mod
->address_start
= address_start
;
1968 mod
->address_end
= address_end
;
1969 mod
->perms
= g_strdup (prot_buf
);
1970 mod
->address_offset
= address_offset
;
1971 mod
->device
= device
;
1973 mod
->filename
= g_strdup (g_strstrip (p
));
1975 if (g_slist_find_custom (ret
, mod
, find_procmodule
) == NULL
) {
1976 ret
= g_slist_prepend (ret
, mod
);
1978 free_procmodule (mod
);
1982 ret
= g_slist_reverse (ret
);
1988 static gboolean
match_procname_to_modulename (gchar
*procname
, gchar
*modulename
)
1990 char* lastsep
= NULL
;
1993 gboolean result
= FALSE
;
1995 if (procname
== NULL
|| modulename
== NULL
)
1998 pname
= mono_path_resolve_symlinks (procname
);
1999 mname
= mono_path_resolve_symlinks (modulename
);
2001 if (!strcmp (pname
, mname
))
2005 lastsep
= strrchr (mname
, '/');
2007 if (!strcmp (lastsep
+1, pname
))
2018 open_process_map (int pid
, const char *mode
)
2021 const gchar
*proc_path
[] = {
2022 "/proc/%d/maps", /* GNU/Linux */
2023 "/proc/%d/map", /* FreeBSD */
2029 for (i
= 0; fp
== NULL
&& proc_path
[i
]; i
++) {
2030 filename
= g_strdup_printf (proc_path
[i
], pid
);
2031 fp
= fopen (filename
, mode
);
2038 gboolean
EnumProcessModules (gpointer process
, gpointer
*modules
,
2039 guint32 size
, guint32
*needed
)
2041 struct _WapiHandle_process
*process_handle
;
2044 GSList
*mods
= NULL
;
2045 WapiProcModule
*module
;
2046 guint32 count
, avail
= size
/ sizeof(gpointer
);
2049 gchar
*proc_name
= NULL
;
2051 /* Store modules in an array of pointers (main module as
2052 * modules[0]), using the load address for each module as a
2053 * token. (Use 'NULL' as an alternative for the main module
2054 * so that the simple implementation can just return one item
2055 * for now.) Get the info from /proc/<pid>/maps on linux,
2056 * /proc/<pid>/map on FreeBSD, other systems will have to
2057 * implement /dev/kmem reading or whatever other horrid
2058 * technique is needed.
2060 if (size
< sizeof(gpointer
)) {
2064 if ((GPOINTER_TO_UINT (process
) & _WAPI_PROCESS_UNHANDLED
) == _WAPI_PROCESS_UNHANDLED
) {
2065 /* This is a pseudo handle */
2066 pid
= (pid_t
)(GPOINTER_TO_UINT (process
) & _WAPI_PROCESS_UNHANDLED_PID_MASK
);
2068 ok
= _wapi_lookup_handle (process
, WAPI_HANDLE_PROCESS
,
2069 (gpointer
*)&process_handle
);
2072 g_message ("%s: Can't find process %p", __func__
, process
);
2077 pid
= process_handle
->id
;
2078 proc_name
= process_handle
->proc_name
;
2081 #ifdef PLATFORM_MACOSX
2083 mods
= load_modules ();
2085 if ((fp
= open_process_map (pid
, "r")) == NULL
) {
2086 /* No /proc/<pid>/maps so just return the main module
2090 *needed
= sizeof(gpointer
);
2092 mods
= load_modules (fp
);
2095 count
= g_slist_length (mods
);
2097 /* count + 1 to leave slot 0 for the main module */
2098 *needed
= sizeof(gpointer
) * (count
+ 1);
2100 /* Use the NULL shortcut, as the first line in
2101 * /proc/<pid>/maps isn't the executable, and we need
2102 * that first in the returned list. Check the module name
2103 * to see if it ends with the proc name and substitute
2104 * the first entry with it. FIXME if this turns out to
2108 for (i
= 0; i
< (avail
- 1) && i
< count
; i
++) {
2109 module
= (WapiProcModule
*)g_slist_nth_data (mods
, i
);
2110 if (modules
[0] != NULL
)
2111 modules
[i
] = module
->address_start
;
2112 else if (match_procname_to_modulename (proc_name
, module
->filename
))
2113 modules
[0] = module
->address_start
;
2115 modules
[i
+ 1] = module
->address_start
;
2118 for (i
= 0; i
< count
; i
++) {
2119 free_procmodule (g_slist_nth_data (mods
, i
));
2121 g_slist_free (mods
);
2127 static gchar
*get_process_name_from_proc (pid_t pid
)
2129 gchar
*filename
= NULL
;
2134 #if defined(PLATFORM_SOLARIS)
2135 filename
= g_strdup_printf ("/proc/%d/psinfo", pid
);
2136 if ((fp
= fopen (filename
, "r")) != NULL
) {
2140 nread
= fread (&info
, sizeof (info
), 1, fp
);
2142 ret
= g_strdup (info
.pr_fname
);
2148 #elif defined(PLATFORM_MACOSX)
2149 memset (buf
, '\0', sizeof(buf
));
2150 proc_name (pid
, buf
, sizeof(buf
));
2151 if (strlen (buf
) > 0)
2152 ret
= g_strdup (buf
);
2154 memset (buf
, '\0', sizeof(buf
));
2155 filename
= g_strdup_printf ("/proc/%d/exe", pid
);
2156 if (readlink (filename
, buf
, 255) > 0) {
2157 ret
= g_strdup (buf
);
2165 filename
= g_strdup_printf ("/proc/%d/cmdline", pid
);
2166 if ((fp
= fopen (filename
, "r")) != NULL
) {
2167 if (fgets (buf
, 256, fp
) != NULL
) {
2168 ret
= g_strdup (buf
);
2179 filename
= g_strdup_printf ("/proc/%d/stat", pid
);
2180 if ((fp
= fopen (filename
, "r")) != NULL
) {
2181 if (fgets (buf
, 256, fp
) != NULL
) {
2184 start
= strchr (buf
, '(');
2185 if (start
!= NULL
) {
2186 end
= strchr (start
+ 1, ')');
2189 ret
= g_strndup (start
+ 1,
2207 static guint32
get_module_name (gpointer process
, gpointer module
,
2208 gunichar2
*basename
, guint32 size
,
2211 struct _WapiHandle_process
*process_handle
;
2214 gunichar2
*procname
;
2215 gchar
*procname_ext
= NULL
;
2219 GSList
*mods
= NULL
;
2220 WapiProcModule
*found_module
;
2223 gchar
*proc_name
= NULL
;
2225 mono_once (&process_current_once
, process_set_current
);
2228 g_message ("%s: Getting module base name, process handle %p module %p",
2229 __func__
, process
, module
);
2232 size
= size
*sizeof(gunichar2
); /* adjust for unicode characters */
2234 if (basename
== NULL
|| size
== 0) {
2238 if ((GPOINTER_TO_UINT (process
) & _WAPI_PROCESS_UNHANDLED
) == _WAPI_PROCESS_UNHANDLED
) {
2239 /* This is a pseudo handle */
2240 pid
= (pid_t
)(GPOINTER_TO_UINT (process
) & _WAPI_PROCESS_UNHANDLED_PID_MASK
);
2241 proc_name
= get_process_name_from_proc (pid
);
2243 ok
= _wapi_lookup_handle (process
, WAPI_HANDLE_PROCESS
,
2244 (gpointer
*)&process_handle
);
2247 g_message ("%s: Can't find process %p", __func__
,
2253 pid
= process_handle
->id
;
2254 proc_name
= g_strdup (process_handle
->proc_name
);
2257 /* Look up the address in /proc/<pid>/maps */
2258 #ifdef PLATFORM_MACOSX
2260 mods
= load_modules ();
2262 if ((fp
= open_process_map (pid
, "r")) == NULL
) {
2263 if (errno
== EACCES
&& module
== NULL
&& base
== TRUE
) {
2264 procname_ext
= get_process_name_from_proc (pid
);
2266 /* No /proc/<pid>/maps, so just return failure
2273 mods
= load_modules (fp
);
2276 count
= g_slist_length (mods
);
2278 /* If module != NULL compare the address.
2279 * If module == NULL we are looking for the main module.
2280 * The best we can do for now check it the module name end with the process name.
2282 for (i
= 0; i
< count
; i
++) {
2283 found_module
= (WapiProcModule
*)g_slist_nth_data (mods
, i
);
2284 if (procname_ext
== NULL
&&
2285 ((module
== NULL
&& match_procname_to_modulename (proc_name
, found_module
->filename
)) ||
2286 (module
!= NULL
&& found_module
->address_start
== module
))) {
2288 procname_ext
= g_path_get_basename (found_module
->filename
);
2290 procname_ext
= g_strdup (found_module
->filename
);
2294 free_procmodule (found_module
);
2297 if (procname_ext
== NULL
)
2299 /* If it's *still* null, we might have hit the
2300 * case where reading /proc/$pid/maps gives an
2301 * empty file for this user.
2303 procname_ext
= get_process_name_from_proc (pid
);
2306 g_slist_free (mods
);
2310 if (procname_ext
!= NULL
) {
2312 g_message ("%s: Process name is [%s]", __func__
,
2316 procname
= mono_unicode_from_external (procname_ext
, &bytes
);
2317 if (procname
== NULL
) {
2319 g_free (procname_ext
);
2325 /* Add the terminator */
2330 g_message ("%s: Size %d smaller than needed (%ld); truncating", __func__
, size
, bytes
);
2333 memcpy (basename
, procname
, size
);
2336 g_message ("%s: Size %d larger than needed (%ld)",
2337 __func__
, size
, bytes
);
2340 memcpy (basename
, procname
, bytes
);
2344 g_free (procname_ext
);
2352 guint32
GetModuleBaseName (gpointer process
, gpointer module
,
2353 gunichar2
*basename
, guint32 size
)
2355 return(get_module_name (process
, module
, basename
, size
, TRUE
));
2358 guint32
GetModuleFileNameEx (gpointer process
, gpointer module
,
2359 gunichar2
*filename
, guint32 size
)
2361 return(get_module_name (process
, module
, filename
, size
, FALSE
));
2364 gboolean
GetModuleInformation (gpointer process
, gpointer module
,
2365 WapiModuleInfo
*modinfo
, guint32 size
)
2367 struct _WapiHandle_process
*process_handle
;
2371 GSList
*mods
= NULL
;
2372 WapiProcModule
*found_module
;
2375 gboolean ret
= FALSE
;
2376 gchar
*proc_name
= NULL
;
2378 mono_once (&process_current_once
, process_set_current
);
2381 g_message ("%s: Getting module info, process handle %p module %p",
2382 __func__
, process
, module
);
2385 if (modinfo
== NULL
|| size
< sizeof(WapiModuleInfo
)) {
2389 if ((GPOINTER_TO_UINT (process
) & _WAPI_PROCESS_UNHANDLED
) == _WAPI_PROCESS_UNHANDLED
) {
2390 /* This is a pseudo handle */
2391 pid
= (pid_t
)(GPOINTER_TO_UINT (process
) & _WAPI_PROCESS_UNHANDLED_PID_MASK
);
2392 proc_name
= get_process_name_from_proc (pid
);
2394 ok
= _wapi_lookup_handle (process
, WAPI_HANDLE_PROCESS
,
2395 (gpointer
*)&process_handle
);
2398 g_message ("%s: Can't find process %p", __func__
,
2404 pid
= process_handle
->id
;
2405 proc_name
= g_strdup (process_handle
->proc_name
);
2408 #ifdef PLATFORM_MACOSX
2410 mods
= load_modules ();
2412 /* Look up the address in /proc/<pid>/maps */
2413 if ((fp
= open_process_map (pid
, "r")) == NULL
) {
2414 /* No /proc/<pid>/maps, so just return failure
2420 mods
= load_modules (fp
);
2423 count
= g_slist_length (mods
);
2425 /* If module != NULL compare the address.
2426 * If module == NULL we are looking for the main module.
2427 * The best we can do for now check it the module name end with the process name.
2429 for (i
= 0; i
< count
; i
++) {
2430 found_module
= (WapiProcModule
*)g_slist_nth_data (mods
, i
);
2431 if ( ret
== FALSE
&&
2432 ((module
== NULL
&& match_procname_to_modulename (proc_name
, found_module
->filename
)) ||
2433 (module
!= NULL
&& found_module
->address_start
== module
))) {
2434 modinfo
->lpBaseOfDll
= found_module
->address_start
;
2435 modinfo
->SizeOfImage
= (gsize
)(found_module
->address_end
) - (gsize
)(found_module
->address_start
);
2436 modinfo
->EntryPoint
= found_module
->address_offset
;
2440 free_procmodule (found_module
);
2443 g_slist_free (mods
);
2450 gboolean
GetProcessWorkingSetSize (gpointer process
, size_t *min
, size_t *max
)
2452 struct _WapiHandle_process
*process_handle
;
2455 mono_once (&process_current_once
, process_set_current
);
2457 if(min
==NULL
|| max
==NULL
) {
2458 /* Not sure if w32 allows NULLs here or not */
2462 if ((GPOINTER_TO_UINT (process
) & _WAPI_PROCESS_UNHANDLED
) == _WAPI_PROCESS_UNHANDLED
) {
2463 /* This is a pseudo handle, so just fail for now
2468 ok
=_wapi_lookup_handle (process
, WAPI_HANDLE_PROCESS
,
2469 (gpointer
*)&process_handle
);
2472 g_message ("%s: Can't find process %p", __func__
, process
);
2478 *min
=process_handle
->min_working_set
;
2479 *max
=process_handle
->max_working_set
;
2484 gboolean
SetProcessWorkingSetSize (gpointer process
, size_t min
, size_t max
)
2486 struct _WapiHandle_process
*process_handle
;
2489 mono_once (&process_current_once
, process_set_current
);
2491 if ((GPOINTER_TO_UINT (process
) & _WAPI_PROCESS_UNHANDLED
) == _WAPI_PROCESS_UNHANDLED
) {
2492 /* This is a pseudo handle, so just fail for now
2497 ok
=_wapi_lookup_handle (process
, WAPI_HANDLE_PROCESS
,
2498 (gpointer
*)&process_handle
);
2501 g_message ("%s: Can't find process %p", __func__
, process
);
2507 process_handle
->min_working_set
=min
;
2508 process_handle
->max_working_set
=max
;
2515 TerminateProcess (gpointer process
, gint32 exitCode
)
2517 struct _WapiHandle_process
*process_handle
;
2523 if ((GPOINTER_TO_UINT (process
) & _WAPI_PROCESS_UNHANDLED
) == _WAPI_PROCESS_UNHANDLED
) {
2524 /* This is a pseudo handle */
2525 pid
= (pid_t
)(GPOINTER_TO_UINT (process
) & _WAPI_PROCESS_UNHANDLED_PID_MASK
);
2527 ok
= _wapi_lookup_handle (process
, WAPI_HANDLE_PROCESS
,
2528 (gpointer
*) &process_handle
);
2532 g_message ("%s: Can't find process %p", __func__
,
2535 SetLastError (ERROR_INVALID_HANDLE
);
2538 pid
= process_handle
->id
;
2541 signo
= (exitCode
== -1) ? SIGKILL
: SIGTERM
;
2542 ret
= kill (pid
, signo
);
2546 SetLastError (ERROR_INVALID_PARAMETER
);
2549 SetLastError (ERROR_ACCESS_DENIED
);
2552 SetLastError (ERROR_PROC_NOT_FOUND
);
2555 SetLastError (ERROR_GEN_FAILURE
);
2563 GetPriorityClass (gpointer process
)
2565 #ifdef HAVE_GETPRIORITY
2566 struct _WapiHandle_process
*process_handle
;
2571 if ((GPOINTER_TO_UINT (process
) & _WAPI_PROCESS_UNHANDLED
) == _WAPI_PROCESS_UNHANDLED
) {
2572 /* This is a pseudo handle */
2573 pid
= (pid_t
)(GPOINTER_TO_UINT (process
) & _WAPI_PROCESS_UNHANDLED_PID_MASK
);
2575 ok
= _wapi_lookup_handle (process
, WAPI_HANDLE_PROCESS
,
2576 (gpointer
*) &process_handle
);
2579 SetLastError (ERROR_INVALID_HANDLE
);
2582 pid
= process_handle
->id
;
2586 ret
= getpriority (PRIO_PROCESS
, pid
);
2587 if (ret
== -1 && errno
!= 0) {
2591 SetLastError (ERROR_ACCESS_DENIED
);
2594 SetLastError (ERROR_PROC_NOT_FOUND
);
2597 SetLastError (ERROR_GEN_FAILURE
);
2603 return NORMAL_PRIORITY_CLASS
;
2605 return REALTIME_PRIORITY_CLASS
;
2607 return HIGH_PRIORITY_CLASS
;
2609 return ABOVE_NORMAL_PRIORITY_CLASS
;
2611 return IDLE_PRIORITY_CLASS
;
2613 return BELOW_NORMAL_PRIORITY_CLASS
;
2615 return NORMAL_PRIORITY_CLASS
;
2617 SetLastError (ERROR_NOT_SUPPORTED
);
2623 SetPriorityClass (gpointer process
, guint32 priority_class
)
2625 #ifdef HAVE_SETPRIORITY
2626 struct _WapiHandle_process
*process_handle
;
2632 if ((GPOINTER_TO_UINT (process
) & _WAPI_PROCESS_UNHANDLED
) == _WAPI_PROCESS_UNHANDLED
) {
2633 /* This is a pseudo handle */
2634 pid
= (pid_t
)(GPOINTER_TO_UINT (process
) & _WAPI_PROCESS_UNHANDLED_PID_MASK
);
2636 ok
= _wapi_lookup_handle (process
, WAPI_HANDLE_PROCESS
,
2637 (gpointer
*) &process_handle
);
2640 SetLastError (ERROR_INVALID_HANDLE
);
2643 pid
= process_handle
->id
;
2646 switch (priority_class
) {
2647 case IDLE_PRIORITY_CLASS
:
2650 case BELOW_NORMAL_PRIORITY_CLASS
:
2653 case NORMAL_PRIORITY_CLASS
:
2656 case ABOVE_NORMAL_PRIORITY_CLASS
:
2659 case HIGH_PRIORITY_CLASS
:
2662 case REALTIME_PRIORITY_CLASS
:
2666 SetLastError (ERROR_INVALID_PARAMETER
);
2670 ret
= setpriority (PRIO_PROCESS
, pid
, prio
);
2675 SetLastError (ERROR_ACCESS_DENIED
);
2678 SetLastError (ERROR_PROC_NOT_FOUND
);
2681 SetLastError (ERROR_GEN_FAILURE
);
2687 SetLastError (ERROR_NOT_SUPPORTED
);