2 * processes.c: Process handles
5 * Dick Porter (dick@ximian.com)
7 * (C) 2002-2011 Novell, Inc.
8 * Copyright 2011 Xamarin Inc
19 #include <sys/types.h>
25 #include <sys/resource.h>
27 #include <sys/param.h>
30 #ifdef HAVE_SYS_MKDEV_H
31 #include <sys/mkdev.h>
34 /* sys/resource.h (for rusage) is required when using osx 10.3 (but not 10.4) */
36 #include <TargetConditionals.h>
37 #include <sys/resource.h>
44 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__)
46 #include <sys/sysctl.h>
47 # if !defined(__OpenBSD__)
48 # include <sys/utsname.h>
52 #ifdef PLATFORM_SOLARIS
53 /* procfs.h cannot be included if this define is set, but it seems to work fine if it is undefined */
54 #if _FILE_OFFSET_BITS == 64
55 #undef _FILE_OFFSET_BITS
57 #define _FILE_OFFSET_BITS 64
64 #include <KernelKit.h>
67 #include <mono/io-layer/wapi.h>
68 #include <mono/io-layer/wapi-private.h>
69 #include <mono/io-layer/handles-private.h>
70 #include <mono/io-layer/misc-private.h>
71 #include <mono/io-layer/process-private.h>
72 #include <mono/io-layer/threads.h>
73 #include <mono/utils/strenc.h>
74 #include <mono/utils/mono-path.h>
75 #include <mono/io-layer/timefuncs-private.h>
76 #include <mono/utils/mono-time.h>
77 #include <mono/utils/mono-membar.h>
78 #include <mono/utils/mono-mutex.h>
79 #include <mono/utils/mono-signal-handler.h>
81 /* The process' environment strings */
82 #if defined(__APPLE__) && !defined (__arm__)
83 /* Apple defines this in crt_externs.h but doesn't provide that header for
84 * arm-apple-darwin9. We'll manually define the symbol on Apple as it does
85 * in fact exist on all implementations (so far)
87 gchar
***_NSGetEnviron(void);
88 #define environ (*_NSGetEnviron())
90 extern char **environ
;
94 #define DEBUG(...) g_message(__VA_ARGS__)
95 #define DEBUG_ENABLED 1
100 static guint32
process_wait (gpointer handle
, guint32 timeout
, gboolean alertable
);
101 static void process_close (gpointer handle
, gpointer data
);
102 static gboolean
is_pid_valid (pid_t pid
);
104 #if !defined(__OpenBSD__)
106 open_process_map (int pid
, const char *mode
);
109 struct _WapiHandleOps _wapi_process_ops
= {
110 process_close
, /* close_shared */
114 process_wait
, /* special_wait */
119 static struct sigaction previous_chld_sa
;
121 static mono_once_t process_sig_chld_once
= MONO_ONCE_INIT
;
122 static void process_add_sigchld_handler (void);
124 /* The signal-safe logic to use mono_processes goes like this:
125 * - The list must be safe to traverse for the signal handler at all times.
126 * It's safe to: prepend an entry (which is a single store to 'mono_processes'),
127 * unlink an entry (assuming the unlinked entry isn't freed and doesn't
128 * change its 'next' pointer so that it can still be traversed).
129 * When cleaning up we first unlink an entry, then we verify that
130 * the read lock isn't locked. Then we can free the entry, since
131 * we know that nobody is using the old version of the list (including
132 * the unlinked entry).
133 * We also need to lock when adding and cleaning up so that those two
134 * operations don't mess with eachother. (This lock is not used in the
137 static struct MonoProcess
*mono_processes
= NULL
;
138 static volatile gint32 mono_processes_read_lock
= 0;
139 static volatile gint32 mono_processes_cleaning_up
= 0;
140 static mono_mutex_t mono_processes_mutex
;
141 static void mono_processes_cleanup (void);
143 static mono_once_t process_current_once
=MONO_ONCE_INIT
;
144 static gpointer current_process
=NULL
;
146 static mono_once_t process_ops_once
=MONO_ONCE_INIT
;
148 static void process_ops_init (void)
150 _wapi_handle_register_capabilities (WAPI_HANDLE_PROCESS
,
151 WAPI_HANDLE_CAP_WAIT
|
152 WAPI_HANDLE_CAP_SPECIAL_WAIT
);
156 /* Check if a pid is valid - i.e. if a process exists with this pid. */
157 static gboolean
is_pid_valid (pid_t pid
)
159 gboolean result
= FALSE
;
161 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__)
162 if (((kill(pid
, 0) == 0) || (errno
== EPERM
)) && pid
!= 0)
164 #elif defined(__HAIKU__)
166 if (get_team_info ((team_id
)pid
, &teamInfo
) == B_OK
)
169 gchar
*dir
= g_strdup_printf ("/proc/%d", pid
);
170 if (!access (dir
, F_OK
))
178 static void process_set_defaults (struct _WapiHandle_process
*process_handle
)
180 /* These seem to be the defaults on w2k */
181 process_handle
->min_working_set
= 204800;
182 process_handle
->max_working_set
= 1413120;
184 _wapi_time_t_to_filetime (time (NULL
), &process_handle
->create_time
);
188 len16 (const gunichar2
*str
)
199 utf16_concat (const gunichar2
*first
, ...)
206 va_start (args
, first
);
207 total
+= len16 (first
);
208 for (s
= va_arg (args
, gunichar2
*); s
!= NULL
; s
= va_arg(args
, gunichar2
*)){
213 ret
= g_new (gunichar2
, total
+ 1);
219 for (s
= first
; *s
!= 0; s
++)
221 va_start (args
, first
);
222 for (s
= va_arg (args
, gunichar2
*); s
!= NULL
; s
= va_arg (args
, gunichar2
*)){
225 for (p
= s
; *p
!= 0; p
++)
233 #ifdef PLATFORM_MACOSX
235 /* 0 = no detection; -1 = not 10.5 or higher; 1 = 10.5 or higher */
236 static int osx_10_5_or_higher
;
239 detect_osx_10_5_or_higher (void)
245 if (uname (&u
) != 0){
246 osx_10_5_or_higher
= 1;
254 osx_10_5_or_higher
= -1;
256 osx_10_5_or_higher
= 1;
260 is_macos_10_5_or_higher (void)
262 if (osx_10_5_or_higher
== 0)
263 detect_osx_10_5_or_higher ();
265 return (osx_10_5_or_higher
== 1);
269 static const gunichar2 utf16_space_bytes
[2] = { 0x20, 0 };
270 static const gunichar2
*utf16_space
= utf16_space_bytes
;
271 static const gunichar2 utf16_quote_bytes
[2] = { 0x22, 0 };
272 static const gunichar2
*utf16_quote
= utf16_quote_bytes
;
277 print_utf16 (gunichar2
*str
)
281 res
= g_utf16_to_utf8 (str
, -1, NULL
, NULL
, NULL
);
282 g_print ("%s\n", res
);
287 /* Implemented as just a wrapper around CreateProcess () */
288 gboolean
ShellExecuteEx (WapiShellExecuteInfo
*sei
)
291 WapiProcessInformation process_info
;
295 /* w2k just segfaults here, but we can do better than
298 SetLastError (ERROR_INVALID_PARAMETER
);
302 if (sei
->lpFile
== NULL
) {
303 /* w2k returns TRUE for this, for some reason. */
307 /* Put both executable and parameters into the second argument
308 * to CreateProcess (), so it searches $PATH. The conversion
309 * into and back out of utf8 is because there is no
310 * g_strdup_printf () equivalent for gunichar2 :-(
312 args
= utf16_concat (utf16_quote
, sei
->lpFile
, utf16_quote
, sei
->lpParameters
== NULL
? NULL
: utf16_space
, sei
->lpParameters
, NULL
);
314 SetLastError (ERROR_INVALID_DATA
);
317 ret
= CreateProcess (NULL
, args
, NULL
, NULL
, TRUE
,
318 CREATE_UNICODE_ENVIRONMENT
, NULL
,
319 sei
->lpDirectory
, NULL
, &process_info
);
322 if (!ret
&& GetLastError () == ERROR_OUTOFMEMORY
)
326 static char *handler
;
327 static gunichar2
*handler_utf16
;
329 if (handler_utf16
== (gunichar2
*)-1)
332 #ifdef PLATFORM_MACOSX
333 handler
= g_strdup ("/usr/bin/open");
336 * On Linux, try: xdg-open, the FreeDesktop standard way of doing it,
337 * if that fails, try to use gnome-open, then kfmclient
339 handler
= g_find_program_in_path ("xdg-open");
340 if (handler
== NULL
){
341 handler
= g_find_program_in_path ("gnome-open");
342 if (handler
== NULL
){
343 handler
= g_find_program_in_path ("kfmclient");
344 if (handler
== NULL
){
345 handler_utf16
= (gunichar2
*) -1;
348 /* kfmclient needs exec argument */
350 handler
= g_strconcat (old
, " exec",
357 handler_utf16
= g_utf8_to_utf16 (handler
, -1, NULL
, NULL
, NULL
);
360 /* Put quotes around the filename, in case it's a url
361 * that contains #'s (CreateProcess() calls
362 * g_shell_parse_argv(), which deliberately throws
363 * away anything after an unquoted #). Fixes bug
366 args
= utf16_concat (handler_utf16
, utf16_space
, utf16_quote
,
367 sei
->lpFile
, utf16_quote
,
368 sei
->lpParameters
== NULL
? NULL
: utf16_space
,
369 sei
->lpParameters
, NULL
);
371 SetLastError (ERROR_INVALID_DATA
);
374 ret
= CreateProcess (NULL
, args
, NULL
, NULL
, TRUE
,
375 CREATE_UNICODE_ENVIRONMENT
, NULL
,
376 sei
->lpDirectory
, NULL
, &process_info
);
379 if (GetLastError () != ERROR_OUTOFMEMORY
)
380 SetLastError (ERROR_INVALID_DATA
);
385 if (sei
->fMask
& SEE_MASK_NOCLOSEPROCESS
) {
386 sei
->hProcess
= process_info
.hProcess
;
388 CloseHandle (process_info
.hProcess
);
395 is_managed_binary (const gchar
*filename
)
397 int original_errno
= errno
;
398 #if defined(HAVE_LARGE_FILE_SUPPORT) && defined(O_LARGEFILE)
399 int file
= open (filename
, O_RDONLY
| O_LARGEFILE
);
401 int file
= open (filename
, O_RDONLY
);
404 unsigned char buffer
[8];
405 off_t file_size
, optional_header_offset
;
406 off_t pe_header_offset
;
407 gboolean managed
= FALSE
;
409 guint32 first_word
, second_word
;
411 /* If we are unable to open the file, then we definitely
412 * can't say that it is managed. The child mono process
413 * probably wouldn't be able to open it anyway.
416 errno
= original_errno
;
420 /* Retrieve the length of the file for future sanity checks. */
421 file_size
= lseek (file
, 0, SEEK_END
);
422 lseek (file
, 0, SEEK_SET
);
424 /* We know we need to read a header field at offset 60. */
428 num_read
= read (file
, buffer
, 2);
430 if ((num_read
!= 2) || (buffer
[0] != 'M') || (buffer
[1] != 'Z'))
433 new_offset
= lseek (file
, 60, SEEK_SET
);
435 if (new_offset
!= 60)
438 num_read
= read (file
, buffer
, 4);
442 pe_header_offset
= buffer
[0]
447 if (pe_header_offset
+ 24 > file_size
)
450 new_offset
= lseek (file
, pe_header_offset
, SEEK_SET
);
452 if (new_offset
!= pe_header_offset
)
455 num_read
= read (file
, buffer
, 4);
457 if ((num_read
!= 4) || (buffer
[0] != 'P') || (buffer
[1] != 'E') || (buffer
[2] != 0) || (buffer
[3] != 0))
461 * Verify that the header we want in the optional header data
462 * is present in this binary.
464 new_offset
= lseek (file
, pe_header_offset
+ 20, SEEK_SET
);
466 if (new_offset
!= pe_header_offset
+ 20)
469 num_read
= read (file
, buffer
, 2);
471 if ((num_read
!= 2) || ((buffer
[0] | (buffer
[1] << 8)) < 216))
474 /* Read the CLR header address and size fields. These will be
475 * zero if the binary is not managed.
477 optional_header_offset
= pe_header_offset
+ 24;
478 new_offset
= lseek (file
, optional_header_offset
+ 208, SEEK_SET
);
480 if (new_offset
!= optional_header_offset
+ 208)
483 num_read
= read (file
, buffer
, 8);
485 /* We are not concerned with endianness, only with
486 * whether it is zero or not.
488 first_word
= *(guint32
*)&buffer
[0];
489 second_word
= *(guint32
*)&buffer
[4];
491 if ((num_read
!= 8) || (first_word
== 0) || (second_word
== 0))
498 errno
= original_errno
;
502 gboolean
CreateProcessWithLogonW (const gunichar2
*username
,
503 const gunichar2
*domain
,
504 const gunichar2
*password
,
505 const guint32 logonFlags
,
506 const gunichar2
*appname
,
507 const gunichar2
*cmdline
,
508 guint32 create_flags
,
510 const gunichar2
*cwd
,
511 WapiStartupInfo
*startup
,
512 WapiProcessInformation
*process_info
)
514 /* FIXME: use user information */
515 return CreateProcess (appname
, cmdline
, NULL
, NULL
, FALSE
, create_flags
, env
, cwd
, startup
, process_info
);
519 is_executable (const char *prog
)
522 if (access (prog
, X_OK
) != 0)
524 if (stat (prog
, &buf
))
526 if (S_ISREG (buf
.st_mode
))
532 switchDirectorySeparators(gchar
*path
)
534 size_t i
, pathLength
= strlen(path
);
536 /* Turn all the slashes round the right way, except for \' */
537 /* There are probably other characters that need to be excluded as well. */
538 for (i
= 0; i
< pathLength
; i
++)
540 if (path
[i
] == '\\' && i
< pathLength
- 1 && path
[i
+1] != '\'' ) {
546 gboolean
CreateProcess (const gunichar2
*appname
, const gunichar2
*cmdline
,
547 WapiSecurityAttributes
*process_attrs G_GNUC_UNUSED
,
548 WapiSecurityAttributes
*thread_attrs G_GNUC_UNUSED
,
549 gboolean inherit_handles
, guint32 create_flags
,
550 gpointer new_environ
, const gunichar2
*cwd
,
551 WapiStartupInfo
*startup
,
552 WapiProcessInformation
*process_info
)
554 gchar
*cmd
=NULL
, *prog
= NULL
, *full_prog
= NULL
, *args
= NULL
, *args_after_prog
= NULL
, *dir
= NULL
, **env_strings
= NULL
, **argv
= NULL
;
555 guint32 i
, env_count
= 0;
556 gboolean ret
= FALSE
;
558 struct _WapiHandle_process process_handle
= {0}, *process_handle_data
;
560 int in_fd
, out_fd
, err_fd
;
563 int startup_pipe
[2] = {-1, -1};
565 struct MonoProcess
*mono_process
;
566 gboolean fork_failed
= FALSE
;
568 mono_once (&process_ops_once
, process_ops_init
);
569 mono_once (&process_sig_chld_once
, process_add_sigchld_handler
);
571 /* appname and cmdline specify the executable and its args:
573 * If appname is not NULL, it is the name of the executable.
574 * Otherwise the executable is the first token in cmdline.
576 * Executable searching:
578 * If appname is not NULL, it can specify the full path and
579 * file name, or else a partial name and the current directory
580 * will be used. There is no additional searching.
582 * If appname is NULL, the first whitespace-delimited token in
583 * cmdline is used. If the name does not contain a full
584 * directory path, the search sequence is:
586 * 1) The directory containing the current process
587 * 2) The current working directory
588 * 3) The windows system directory (Ignored)
589 * 4) The windows directory (Ignored)
592 * Just to make things more interesting, tokens can contain
593 * white space if they are surrounded by quotation marks. I'm
594 * beginning to understand just why windows apps are generally
595 * so crap, with an API like this :-(
597 if (appname
!= NULL
) {
598 cmd
= mono_unicode_to_external (appname
);
600 DEBUG ("%s: unicode conversion returned NULL",
603 SetLastError (ERROR_PATH_NOT_FOUND
);
607 switchDirectorySeparators(cmd
);
610 if (cmdline
!= NULL
) {
611 args
= mono_unicode_to_external (cmdline
);
613 DEBUG ("%s: unicode conversion returned NULL", __func__
);
615 SetLastError (ERROR_PATH_NOT_FOUND
);
621 dir
= mono_unicode_to_external (cwd
);
623 DEBUG ("%s: unicode conversion returned NULL", __func__
);
625 SetLastError (ERROR_PATH_NOT_FOUND
);
629 /* Turn all the slashes round the right way */
630 switchDirectorySeparators(dir
);
634 /* We can't put off locating the executable any longer :-( */
637 if (g_ascii_isalpha (cmd
[0]) && (cmd
[1] == ':')) {
638 /* Strip off the drive letter. I can't
639 * believe that CP/M holdover is still
642 g_memmove (cmd
, cmd
+2, strlen (cmd
)-2);
643 cmd
[strlen (cmd
)-2] = '\0';
646 unquoted
= g_shell_unquote (cmd
, NULL
);
647 if (unquoted
[0] == '/') {
648 /* Assume full path given */
649 prog
= g_strdup (unquoted
);
651 /* Executable existing ? */
652 if (!is_executable (prog
)) {
653 DEBUG ("%s: Couldn't find executable %s",
656 SetLastError (ERROR_FILE_NOT_FOUND
);
660 /* Search for file named by cmd in the current
663 char *curdir
= g_get_current_dir ();
665 prog
= g_strdup_printf ("%s/%s", curdir
, unquoted
);
668 /* And make sure it's executable */
669 if (!is_executable (prog
)) {
670 DEBUG ("%s: Couldn't find executable %s",
673 SetLastError (ERROR_FILE_NOT_FOUND
);
679 args_after_prog
= args
;
684 /* Dig out the first token from args, taking quotation
688 /* First, strip off all leading whitespace */
689 args
= g_strchug (args
);
691 /* args_after_prog points to the contents of args
692 * after token has been set (otherwise argv[0] is
695 args_after_prog
= args
;
697 /* Assume the opening quote will always be the first
700 if (args
[0] == '\"' || args
[0] == '\'') {
702 for (i
= 1; args
[i
] != '\0' && args
[i
] != quote
; i
++);
703 if (args
[i
+ 1] == '\0' || g_ascii_isspace (args
[i
+1])) {
704 /* We found the first token */
705 token
= g_strndup (args
+1, i
-1);
706 args_after_prog
= g_strchug (args
+ i
+ 1);
708 /* Quotation mark appeared in the
709 * middle of the token. Just give the
710 * whole first token, quotes and all,
717 /* No quote mark, or malformed */
718 for (i
= 0; args
[i
] != '\0'; i
++) {
719 if (g_ascii_isspace (args
[i
])) {
720 token
= g_strndup (args
, i
);
721 args_after_prog
= args
+ i
+ 1;
727 if (token
== NULL
&& args
[0] != '\0') {
728 /* Must be just one token in the string */
729 token
= g_strdup (args
);
730 args_after_prog
= NULL
;
735 DEBUG ("%s: Couldn't find what to exec", __func__
);
737 SetLastError (ERROR_PATH_NOT_FOUND
);
741 /* Turn all the slashes round the right way. Only for
744 switchDirectorySeparators(token
);
746 if (g_ascii_isalpha (token
[0]) && (token
[1] == ':')) {
747 /* Strip off the drive letter. I can't
748 * believe that CP/M holdover is still
751 g_memmove (token
, token
+2, strlen (token
)-2);
752 token
[strlen (token
)-2] = '\0';
755 if (token
[0] == '/') {
756 /* Assume full path given */
757 prog
= g_strdup (token
);
759 /* Executable existing ? */
760 if (!is_executable (prog
)) {
761 DEBUG ("%s: Couldn't find executable %s",
764 SetLastError (ERROR_FILE_NOT_FOUND
);
769 char *curdir
= g_get_current_dir ();
771 /* FIXME: Need to record the directory
772 * containing the current process, and check
773 * that for the new executable as the first
777 prog
= g_strdup_printf ("%s/%s", curdir
, token
);
780 /* I assume X_OK is the criterion to use,
783 if (!is_executable (prog
)) {
785 prog
= g_find_program_in_path (token
);
787 DEBUG ("%s: Couldn't find executable %s", __func__
, token
);
790 SetLastError (ERROR_FILE_NOT_FOUND
);
799 DEBUG ("%s: Exec prog [%s] args [%s]", __func__
, prog
,
802 /* Check for CLR binaries; if found, we will try to invoke
803 * them using the same mono binary that started us.
805 if (is_managed_binary (prog
)) {
806 gunichar2
*newapp
, *newcmd
;
809 newapp
= mono_unicode_from_external ("mono", &bytes_ignored
);
811 if (newapp
!= NULL
) {
812 if (appname
!= NULL
) {
813 newcmd
= utf16_concat (newapp
, utf16_space
,
814 appname
, utf16_space
,
817 newcmd
= utf16_concat (newapp
, utf16_space
,
821 g_free ((gunichar2
*)newapp
);
823 if (newcmd
!= NULL
) {
824 ret
= CreateProcess (NULL
, newcmd
,
828 create_flags
, new_environ
,
832 g_free ((gunichar2
*)newcmd
);
839 if (args_after_prog
!= NULL
&& *args_after_prog
) {
842 qprog
= g_shell_quote (prog
);
843 full_prog
= g_strconcat (qprog
, " ", args_after_prog
, NULL
);
846 full_prog
= g_shell_quote (prog
);
849 ret
= g_shell_parse_argv (full_prog
, NULL
, &argv
, &gerr
);
851 g_message ("CreateProcess: %s\n", gerr
->message
);
857 if (startup
!= NULL
&& startup
->dwFlags
& STARTF_USESTDHANDLES
) {
858 in_fd
= GPOINTER_TO_UINT (startup
->hStdInput
);
859 out_fd
= GPOINTER_TO_UINT (startup
->hStdOutput
);
860 err_fd
= GPOINTER_TO_UINT (startup
->hStdError
);
862 in_fd
= GPOINTER_TO_UINT (GetStdHandle (STD_INPUT_HANDLE
));
863 out_fd
= GPOINTER_TO_UINT (GetStdHandle (STD_OUTPUT_HANDLE
));
864 err_fd
= GPOINTER_TO_UINT (GetStdHandle (STD_ERROR_HANDLE
));
867 g_strlcpy (process_handle
.proc_name
, prog
,
868 _WAPI_PROC_NAME_MAX_LEN
- 1);
870 process_set_defaults (&process_handle
);
872 handle
= _wapi_handle_new (WAPI_HANDLE_PROCESS
, &process_handle
);
873 if (handle
== _WAPI_HANDLE_INVALID
) {
874 g_warning ("%s: error creating process handle", __func__
);
877 SetLastError (ERROR_OUTOFMEMORY
);
881 /* new_environ is a block of NULL-terminated strings, which
882 * is itself NULL-terminated. Of course, passing an array of
883 * string pointers would have made things too easy :-(
885 * If new_environ is not NULL it specifies the entire set of
886 * environment variables in the new process. Otherwise the
887 * new process inherits the same environment.
889 if (new_environ
!= NULL
) {
890 gunichar2
*new_environp
;
892 /* Count the number of strings */
893 for (new_environp
= (gunichar2
*)new_environ
; *new_environp
;
896 while (*new_environp
) {
901 /* +2: one for the process handle value, and the last
904 env_strings
= g_new0 (gchar
*, env_count
+ 2);
906 /* Copy each environ string into 'strings' turning it
907 * into utf8 (or the requested encoding) at the same
911 for (new_environp
= (gunichar2
*)new_environ
; *new_environp
;
913 env_strings
[env_count
] = mono_unicode_to_external (new_environp
);
915 while (*new_environp
) {
920 for (i
= 0; environ
[i
] != NULL
; i
++) {
924 /* +2: one for the process handle value, and the last
927 env_strings
= g_new0 (gchar
*, env_count
+ 2);
929 /* Copy each environ string into 'strings' turning it
930 * into utf8 (or the requested encoding) at the same
934 for (i
= 0; environ
[i
] != NULL
; i
++) {
935 env_strings
[env_count
] = g_strdup (environ
[i
]);
939 /* pass process handle info to the child, so it doesn't have
940 * to do an expensive search over the whole list
942 if (env_strings
!= NULL
) {
943 struct _WapiHandleUnshared
*handle_data
;
944 struct _WapiHandle_shared_ref
*ref
;
946 handle_data
= &_WAPI_PRIVATE_HANDLES(GPOINTER_TO_UINT(handle
));
947 ref
= &handle_data
->u
.shared
;
949 env_strings
[env_count
] = g_strdup_printf ("_WAPI_PROCESS_HANDLE_OFFSET=%d", ref
->offset
);
952 /* Create a pipe to make sure the child doesn't exit before
953 * we can add the process to the linked list of mono_processes */
954 if (pipe (startup_pipe
) == -1) {
955 /* Could not create the pipe to synchroniz process startup. We'll just not synchronize.
956 * This is just for a very hard to hit race condition in the first place */
957 startup_pipe
[0] = startup_pipe
[1] = -1;
958 DEBUG ("%s: new process startup not synchronized. We may not notice if the newly created process exits immediately.", __func__
);
961 thr_ret
= _wapi_handle_lock_shared_handles ();
962 g_assert (thr_ret
== 0);
967 SetLastError (ERROR_OUTOFMEMORY
);
971 } else if (pid
== 0) {
974 if (startup_pipe
[0] != -1) {
975 /* Wait until the parent has updated it's internal data */
976 ssize_t _i G_GNUC_UNUSED
= read (startup_pipe
[0], &dummy
, 1);
977 DEBUG ("%s: child: parent has completed its setup", __func__
);
978 close (startup_pipe
[0]);
979 close (startup_pipe
[1]);
982 /* should we detach from the process group? */
984 /* Connect stdin, stdout and stderr */
989 if (inherit_handles
!= TRUE
) {
990 /* FIXME: do something here */
993 /* Close all file descriptors */
994 for (i
= getdtablesize () - 1; i
> 2; i
--) {
999 DEBUG ("%s: exec()ing [%s] in dir [%s]", __func__
, cmd
,
1001 for (i
= 0; argv
[i
] != NULL
; i
++) {
1002 g_message ("arg %d: [%s]", i
, argv
[i
]);
1005 for (i
= 0; env_strings
[i
] != NULL
; i
++) {
1006 g_message ("env %d: [%s]", i
, env_strings
[i
]);
1011 if (dir
!= NULL
&& chdir (dir
) == -1) {
1017 execve (argv
[0], argv
, env_strings
);
1024 ret
= _wapi_lookup_handle (handle
, WAPI_HANDLE_PROCESS
,
1025 (gpointer
*)&process_handle_data
);
1027 g_warning ("%s: error looking up process handle %p", __func__
,
1029 _wapi_handle_unref (handle
);
1033 process_handle_data
->id
= pid
;
1035 /* Add our mono_process into the linked list of mono_processes */
1036 mono_process
= (struct MonoProcess
*) g_malloc0 (sizeof (struct MonoProcess
));
1037 mono_process
->pid
= pid
;
1038 mono_process
->handle_count
= 1;
1039 if (MONO_SEM_INIT (&mono_process
->exit_sem
, 0) != 0) {
1040 /* If we can't create the exit semaphore, we just don't add anything
1041 * to our list of mono processes. Waiting on the process will return
1043 g_warning ("%s: could not create exit semaphore for process.", strerror (errno
));
1044 g_free (mono_process
);
1046 /* Keep the process handle artificially alive until the process
1047 * exits so that the information in the handle isn't lost. */
1048 _wapi_handle_ref (handle
);
1049 mono_process
->handle
= handle
;
1051 process_handle_data
->self
= _wapi_getpid ();
1052 process_handle_data
->mono_process
= mono_process
;
1054 mono_mutex_lock (&mono_processes_mutex
);
1055 mono_process
->next
= mono_processes
;
1056 mono_processes
= mono_process
;
1057 mono_mutex_unlock (&mono_processes_mutex
);
1060 if (process_info
!= NULL
) {
1061 process_info
->hProcess
= handle
;
1062 process_info
->dwProcessId
= pid
;
1064 /* FIXME: we might need to handle the thread info some
1067 process_info
->hThread
= INVALID_HANDLE_VALUE
;
1068 process_info
->dwThreadId
= 0;
1072 _wapi_handle_unlock_shared_handles ();
1075 _wapi_handle_unref (handle
);
1077 if (startup_pipe
[1] != -1) {
1078 /* Write 1 byte, doesn't matter what */
1079 ssize_t _i G_GNUC_UNUSED
= write (startup_pipe
[1], startup_pipe
, 1);
1080 close (startup_pipe
[0]);
1081 close (startup_pipe
[1]);
1088 if (full_prog
!= NULL
) {
1100 if(env_strings
!= NULL
) {
1101 g_strfreev (env_strings
);
1107 DEBUG ("%s: returning handle %p for pid %d", __func__
, handle
,
1110 /* Check if something needs to be cleaned up. */
1111 mono_processes_cleanup ();
1116 static void process_set_name (struct _WapiHandle_process
*process_handle
)
1118 gchar
*progname
, *utf8_progname
, *slash
;
1120 progname
=g_get_prgname ();
1121 utf8_progname
=mono_utf8_from_external (progname
);
1123 DEBUG ("%s: using [%s] as prog name", __func__
, progname
);
1125 if(utf8_progname
!=NULL
) {
1126 slash
=strrchr (utf8_progname
, '/');
1128 g_strlcpy (process_handle
->proc_name
, slash
+1,
1129 _WAPI_PROC_NAME_MAX_LEN
- 1);
1131 g_strlcpy (process_handle
->proc_name
, utf8_progname
,
1132 _WAPI_PROC_NAME_MAX_LEN
- 1);
1135 g_free (utf8_progname
);
1139 extern void _wapi_time_t_to_filetime (time_t timeval
, WapiFileTime
*filetime
);
1141 #if !GLIB_CHECK_VERSION (2,4,0)
1142 #define g_setenv(a,b,c) setenv(a,b,c)
1143 #define g_unsetenv(a) unsetenv(a)
1146 static void process_set_current (void)
1148 pid_t pid
= _wapi_getpid ();
1149 const char *handle_env
;
1150 struct _WapiHandle_process process_handle
= {0};
1152 mono_once (&process_ops_once
, process_ops_init
);
1154 handle_env
= g_getenv ("_WAPI_PROCESS_HANDLE_OFFSET");
1155 g_unsetenv ("_WAPI_PROCESS_HANDLE_OFFSET");
1157 if (handle_env
!= NULL
) {
1158 struct _WapiHandle_process
*process_handlep
;
1159 gchar
*procname
= NULL
;
1162 current_process
= _wapi_handle_new_from_offset (WAPI_HANDLE_PROCESS
, atoi (handle_env
), TRUE
);
1164 DEBUG ("%s: Found my process handle: %p (offset %d 0x%x)",
1165 __func__
, current_process
, atoi (handle_env
),
1168 ok
= _wapi_lookup_handle (current_process
, WAPI_HANDLE_PROCESS
,
1169 (gpointer
*)&process_handlep
);
1171 /* This test will probably break on linuxthreads, but
1172 * that should be ancient history on all distros we
1175 if (process_handlep
->id
== pid
) {
1176 procname
= process_handlep
->proc_name
;
1177 if (!strcmp (procname
, "mono")) {
1178 /* Set a better process name */
1179 DEBUG ("%s: Setting better process name", __func__
);
1181 process_set_name (process_handlep
);
1183 DEBUG ("%s: Leaving process name: %s", __func__
, procname
);
1189 /* Wrong pid, so drop this handle and fall through to
1192 _wapi_handle_unref (current_process
);
1196 /* We get here if the handle wasn't specified in the
1197 * environment, or if the process ID was wrong, or if the
1198 * handle lookup failed (eg if the parent process forked and
1199 * quit immediately, and deleted the shared data before the
1200 * child got a chance to attach it.)
1203 DEBUG ("%s: Need to create my own process handle", __func__
);
1205 process_handle
.id
= pid
;
1207 process_set_defaults (&process_handle
);
1208 process_set_name (&process_handle
);
1210 current_process
= _wapi_handle_new (WAPI_HANDLE_PROCESS
,
1212 if (current_process
== _WAPI_HANDLE_INVALID
) {
1213 g_warning ("%s: error creating process handle", __func__
);
1218 gpointer
_wapi_process_duplicate ()
1220 mono_once (&process_current_once
, process_set_current
);
1222 _wapi_handle_ref (current_process
);
1224 return(current_process
);
1227 /* Returns a pseudo handle that doesn't need to be closed afterwards */
1228 gpointer
GetCurrentProcess (void)
1230 mono_once (&process_current_once
, process_set_current
);
1232 return(_WAPI_PROCESS_CURRENT
);
1235 guint32
GetProcessId (gpointer handle
)
1237 struct _WapiHandle_process
*process_handle
;
1240 if ((GPOINTER_TO_UINT (handle
) & _WAPI_PROCESS_UNHANDLED
) == _WAPI_PROCESS_UNHANDLED
) {
1241 /* This is a pseudo handle */
1242 return(GPOINTER_TO_UINT (handle
) & _WAPI_PROCESS_UNHANDLED_PID_MASK
);
1245 ok
= _wapi_lookup_handle (handle
, WAPI_HANDLE_PROCESS
,
1246 (gpointer
*)&process_handle
);
1248 SetLastError (ERROR_INVALID_HANDLE
);
1252 return (process_handle
->id
);
1255 guint32
GetCurrentProcessId (void)
1257 mono_once (&process_current_once
, process_set_current
);
1259 return (GetProcessId (current_process
));
1262 /* Returns the process id as a convenience to the functions that call this */
1263 static pid_t
signal_process_if_gone (gpointer handle
)
1265 struct _WapiHandle_process
*process_handle
;
1268 g_assert ((GPOINTER_TO_UINT (handle
) & _WAPI_PROCESS_UNHANDLED
) != _WAPI_PROCESS_UNHANDLED
);
1270 /* Make sure the process is signalled if it has exited - if
1271 * the parent process didn't wait for it then it won't be
1273 ok
= _wapi_lookup_handle (handle
, WAPI_HANDLE_PROCESS
,
1274 (gpointer
*)&process_handle
);
1276 /* It's possible that the handle has vanished during
1277 * the _wapi_search_handle before it gets here, so
1278 * don't spam the console with warnings.
1280 /* g_warning ("%s: error looking up process handle %p",
1281 __func__, handle);*/
1286 DEBUG ("%s: looking at process %d", __func__
, process_handle
->id
);
1288 if (kill (process_handle
->id
, 0) == -1 &&
1291 /* The process is dead, (EPERM tells us a new process
1292 * has that ID, but as it's owned by someone else it
1293 * can't be the one listed in our shared memory file)
1295 _wapi_shared_handle_set_signal_state (handle
, TRUE
);
1298 return (process_handle
->id
);
1302 static gboolean
process_enum (gpointer handle
, gpointer user_data
)
1304 GArray
*processes
=user_data
;
1305 pid_t pid
= signal_process_if_gone (handle
);
1312 /* Ignore processes that have already exited (ie they are signalled) */
1313 if (_wapi_handle_issignalled (handle
) == FALSE
) {
1314 DEBUG ("%s: process %d added to array", __func__
, pid
);
1316 /* This ensures that duplicates aren't returned (see
1317 * the comment above _wapi_search_handle () for why
1320 for (i
= 0; i
< processes
->len
; i
++) {
1321 if (g_array_index (processes
, pid_t
, i
) == pid
) {
1322 /* We've already got this one, return
1323 * FALSE to keep searching
1329 g_array_append_val (processes
, pid
);
1332 /* Return false to keep searching */
1335 #endif /* UNUSED_CODE */
1337 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__)
1339 gboolean
EnumProcesses (guint32
*pids
, guint32 len
, guint32
*needed
)
1341 guint32 count
, fit
, i
, j
;
1344 size_t proclength
, size
;
1345 #if defined(__OpenBSD__)
1346 struct kinfo_proc2
*result
;
1349 name
[1] = KERN_PROC2
;
1350 name
[2] = KERN_PROC_ALL
;
1352 name
[4] = sizeof(struct kinfo_proc2
);
1355 struct kinfo_proc
*result
;
1356 static const int name
[] = { CTL_KERN
, KERN_PROC
, KERN_PROC_ALL
, 0 };
1359 mono_once (&process_current_once
, process_set_current
);
1366 #if defined(__OpenBSD__)
1367 size
= (sizeof(name
) / sizeof(*name
));
1369 size
= (sizeof(name
) / sizeof(*name
)) - 1;
1371 err
= sysctl ((int *)name
, size
, NULL
, &proclength
, NULL
, 0);
1374 result
= malloc (proclength
);
1379 #if defined(__OpenBSD__)
1380 name
[5] = (int)(proclength
/ sizeof(struct kinfo_proc2
));
1383 err
= sysctl ((int *) name
, size
, result
, &proclength
, NULL
, 0);
1390 } while (err
== 0 && !done
);
1393 if (result
!= NULL
) {
1400 #if defined(__OpenBSD__)
1401 count
= proclength
/ sizeof(struct kinfo_proc2
);
1403 count
= proclength
/ sizeof(struct kinfo_proc
);
1405 fit
= len
/ sizeof(guint32
);
1406 for (i
= 0, j
= 0; j
< fit
&& i
< count
; i
++) {
1407 #if defined(__OpenBSD__)
1408 pids
[j
++] = result
[i
].p_pid
;
1410 if (result
[i
].kp_proc
.p_pid
> 0) /* Pid 0 not supported */
1411 pids
[j
++] = result
[i
].kp_proc
.p_pid
;
1416 *needed
= j
* sizeof(guint32
);
1420 #elif defined(__HAIKU__)
1422 gboolean
EnumProcesses (guint32
*pids
, guint32 len
, guint32
*needed
)
1428 mono_once (&process_current_once
, process_set_current
);
1430 fit
= len
/ sizeof (guint32
);
1431 while (get_next_team_info (&cookie
, &teamInfo
) == B_OK
&& i
< fit
) {
1432 pids
[i
++] = teamInfo
.team
;
1434 *needed
= i
* sizeof (guint32
);
1439 gboolean
EnumProcesses (guint32
*pids
, guint32 len
, guint32
*needed
)
1443 struct dirent
*entry
;
1445 mono_once (&process_current_once
, process_set_current
);
1447 dir
= opendir ("/proc");
1453 fit
= len
/ sizeof (guint32
);
1454 while(i
< fit
&& (entry
= readdir (dir
)) != NULL
) {
1458 if (!isdigit (entry
->d_name
[0]))
1461 pid
= (pid_t
) strtol (entry
->d_name
, &endptr
, 10);
1462 if (*endptr
== '\0')
1463 pids
[i
++] = (guint32
) pid
;
1466 *needed
= i
* sizeof(guint32
);
1472 static gboolean
process_open_compare (gpointer handle
, gpointer user_data
)
1475 pid_t checking_pid
= signal_process_if_gone (handle
);
1477 if (checking_pid
== 0) {
1481 wanted_pid
= GPOINTER_TO_UINT (user_data
);
1483 /* It's possible to have more than one process handle with the
1484 * same pid, but only the one running process can be
1487 if (checking_pid
== wanted_pid
&&
1488 _wapi_handle_issignalled (handle
) == FALSE
) {
1489 /* If the handle is blown away in the window between
1490 * returning TRUE here and _wapi_search_handle pinging
1491 * the timestamp, the search will continue
1499 gboolean
CloseProcess(gpointer handle
)
1501 if ((GPOINTER_TO_UINT (handle
) & _WAPI_PROCESS_UNHANDLED
) == _WAPI_PROCESS_UNHANDLED
) {
1502 /* This is a pseudo handle */
1506 return CloseHandle (handle
);
1510 * The caller owns the returned handle and must call CloseProcess () on it to clean it up.
1512 gpointer
OpenProcess (guint32 req_access G_GNUC_UNUSED
, gboolean inherit G_GNUC_UNUSED
, guint32 pid
)
1514 /* Find the process handle that corresponds to pid */
1515 gpointer handle
= NULL
;
1517 mono_once (&process_current_once
, process_set_current
);
1519 DEBUG ("%s: looking for process %d", __func__
, pid
);
1521 handle
= _wapi_search_handle (WAPI_HANDLE_PROCESS
,
1522 process_open_compare
,
1523 GUINT_TO_POINTER (pid
), NULL
, TRUE
);
1525 if (is_pid_valid (pid
)) {
1526 /* Return a pseudo handle for processes we
1527 * don't have handles for
1529 return GINT_TO_POINTER (_WAPI_PROCESS_UNHANDLED
+ pid
);
1531 DEBUG ("%s: Can't find pid %d", __func__
, pid
);
1533 SetLastError (ERROR_PROC_NOT_FOUND
);
1539 /* _wapi_search_handle () already added a ref */
1543 gboolean
GetExitCodeProcess (gpointer process
, guint32
*code
)
1545 struct _WapiHandle_process
*process_handle
;
1549 mono_once (&process_current_once
, process_set_current
);
1555 pid
= GPOINTER_TO_UINT (process
) - _WAPI_PROCESS_UNHANDLED
;
1556 if ((GPOINTER_TO_UINT (process
) & _WAPI_PROCESS_UNHANDLED
) == _WAPI_PROCESS_UNHANDLED
) {
1557 /* This is a pseudo handle, so we don't know what the
1558 * exit code was, but we can check whether it's alive or not
1560 if (is_pid_valid (pid
)) {
1561 *code
= STILL_ACTIVE
;
1568 ok
=_wapi_lookup_handle (process
, WAPI_HANDLE_PROCESS
,
1569 (gpointer
*)&process_handle
);
1571 DEBUG ("%s: Can't find process %p", __func__
, process
);
1576 /* A process handle is only signalled if the process has exited
1577 * and has been waited for */
1579 /* Make sure any process exit has been noticed, before
1580 * checking if the process is signalled. Fixes bug 325463.
1582 process_wait (process
, 0, TRUE
);
1584 if (_wapi_handle_issignalled (process
) == TRUE
) {
1585 *code
= process_handle
->exitstatus
;
1587 *code
= STILL_ACTIVE
;
1593 gboolean
GetProcessTimes (gpointer process
, WapiFileTime
*create_time
,
1594 WapiFileTime
*exit_time
, WapiFileTime
*kernel_time
,
1595 WapiFileTime
*user_time
)
1597 struct _WapiHandle_process
*process_handle
;
1599 gboolean ku_times_set
= FALSE
;
1601 mono_once (&process_current_once
, process_set_current
);
1603 if(create_time
==NULL
|| exit_time
==NULL
|| kernel_time
==NULL
||
1605 /* Not sure if w32 allows NULLs here or not */
1609 if ((GPOINTER_TO_UINT (process
) & _WAPI_PROCESS_UNHANDLED
) == _WAPI_PROCESS_UNHANDLED
) {
1610 /* This is a pseudo handle, so just fail for now
1615 ok
=_wapi_lookup_handle (process
, WAPI_HANDLE_PROCESS
,
1616 (gpointer
*)&process_handle
);
1618 DEBUG ("%s: Can't find process %p", __func__
, process
);
1623 *create_time
=process_handle
->create_time
;
1625 /* A process handle is only signalled if the process has
1626 * exited. Otherwise exit_time isn't set
1628 if(_wapi_handle_issignalled (process
)==TRUE
) {
1629 *exit_time
=process_handle
->exit_time
;
1632 #ifdef HAVE_GETRUSAGE
1633 if (process_handle
->id
== getpid ()) {
1634 struct rusage time_data
;
1635 if (getrusage (RUSAGE_SELF
, &time_data
) == 0) {
1637 gint64
*tick_val_ptr
;
1638 ku_times_set
= TRUE
;
1639 tick_val
= time_data
.ru_utime
.tv_sec
* 10000000 + time_data
.ru_utime
.tv_usec
* 10;
1640 tick_val_ptr
= (gint64
*)user_time
;
1641 *tick_val_ptr
= tick_val
;
1642 tick_val
= time_data
.ru_stime
.tv_sec
* 10000000 + time_data
.ru_stime
.tv_usec
* 10;
1643 tick_val_ptr
= (gint64
*)kernel_time
;
1644 *tick_val_ptr
= tick_val
;
1648 if (!ku_times_set
) {
1649 memset (kernel_time
, 0, sizeof (WapiFileTime
));
1650 memset (user_time
, 0, sizeof (WapiFileTime
));
1658 gpointer address_start
;
1659 gpointer address_end
;
1661 gpointer address_offset
;
1667 static void free_procmodule (WapiProcModule
*mod
)
1669 if (mod
->perms
!= NULL
) {
1670 g_free (mod
->perms
);
1672 if (mod
->filename
!= NULL
) {
1673 g_free (mod
->filename
);
1678 static gint
find_procmodule (gconstpointer a
, gconstpointer b
)
1680 WapiProcModule
*want
= (WapiProcModule
*)a
;
1681 WapiProcModule
*compare
= (WapiProcModule
*)b
;
1683 if ((want
->device
== compare
->device
) &&
1684 (want
->inode
== compare
->inode
)) {
1691 #ifdef PLATFORM_MACOSX
1692 #include <mach-o/dyld.h>
1693 #include <mach-o/getsect.h>
1695 static GSList
*load_modules (void)
1698 WapiProcModule
*mod
;
1699 uint32_t count
= _dyld_image_count ();
1702 for (i
= 0; i
< count
; i
++) {
1703 #if SIZEOF_VOID_P == 8
1704 const struct mach_header_64
*hdr
;
1705 const struct section_64
*sec
;
1707 const struct mach_header
*hdr
;
1708 const struct section
*sec
;
1713 slide
= _dyld_get_image_vmaddr_slide (i
);
1714 name
= _dyld_get_image_name (i
);
1715 #if SIZEOF_VOID_P == 8
1716 hdr
= (const struct mach_header_64
*)_dyld_get_image_header (i
);
1717 sec
= getsectbynamefromheader_64 (hdr
, SEG_DATA
, SECT_DATA
);
1719 hdr
= _dyld_get_image_header (i
);
1720 sec
= getsectbynamefromheader (hdr
, SEG_DATA
, SECT_DATA
);
1723 /* Some dynlibs do not have data sections on osx (#533893) */
1728 mod
= g_new0 (WapiProcModule
, 1);
1729 mod
->address_start
= GINT_TO_POINTER (sec
->addr
);
1730 mod
->address_end
= GINT_TO_POINTER (sec
->addr
+sec
->size
);
1731 mod
->perms
= g_strdup ("r--p");
1732 mod
->address_offset
= 0;
1733 mod
->device
= makedev (0, 0);
1734 mod
->inode
= (ino_t
) i
;
1735 mod
->filename
= g_strdup (name
);
1737 if (g_slist_find_custom (ret
, mod
, find_procmodule
) == NULL
) {
1738 ret
= g_slist_prepend (ret
, mod
);
1740 free_procmodule (mod
);
1744 ret
= g_slist_reverse (ret
);
1748 #elif defined(__OpenBSD__)
1750 static int load_modules_callback (struct dl_phdr_info
*info
, size_t size
, void *ptr
)
1752 if (size
< offsetof (struct dl_phdr_info
, dlpi_phnum
)
1753 + sizeof (info
->dlpi_phnum
))
1756 struct dl_phdr_info
*cpy
= calloc(1, sizeof(struct dl_phdr_info
));
1760 memcpy(cpy
, info
, sizeof(*info
));
1762 g_ptr_array_add ((GPtrArray
*)ptr
, cpy
);
1767 static GSList
*load_modules (void)
1770 WapiProcModule
*mod
;
1771 GPtrArray
*dlarray
= g_ptr_array_new();
1774 if (dl_iterate_phdr(load_modules_callback
, dlarray
) < 0)
1777 for (i
= 0; i
< dlarray
->len
; i
++) {
1778 struct dl_phdr_info
*info
= g_ptr_array_index (dlarray
, i
);
1780 mod
= g_new0 (WapiProcModule
, 1);
1781 mod
->address_start
= (gpointer
)(info
->dlpi_addr
+ info
->dlpi_phdr
[0].p_vaddr
);
1782 mod
->address_end
= (gpointer
)(info
->dlpi_addr
+
1783 info
->dlpi_phdr
[info
->dlpi_phnum
- 1].p_vaddr
);
1784 mod
->perms
= g_strdup ("r--p");
1785 mod
->address_offset
= 0;
1786 mod
->inode
= (ino_t
) i
;
1787 mod
->filename
= g_strdup (info
->dlpi_name
);
1789 DEBUG ("%s: inode=%d, filename=%s, address_start=%p, address_end=%p", __func__
,
1790 mod
->inode
, mod
->filename
, mod
->address_start
, mod
->address_end
);
1794 if (g_slist_find_custom (ret
, mod
, find_procmodule
) == NULL
) {
1795 ret
= g_slist_prepend (ret
, mod
);
1797 free_procmodule (mod
);
1801 g_ptr_array_free (dlarray
, TRUE
);
1803 ret
= g_slist_reverse (ret
);
1807 #elif defined(__HAIKU__)
1809 static GSList
*load_modules (void)
1812 WapiProcModule
*mod
;
1814 image_info imageInfo
;
1816 while (get_next_image_info (B_CURRENT_TEAM
, &cookie
, &imageInfo
) == B_OK
) {
1817 mod
= g_new0 (WapiProcModule
, 1);
1818 mod
->device
= imageInfo
.device
;
1819 mod
->inode
= imageInfo
.node
;
1820 mod
->filename
= g_strdup (imageInfo
.name
);
1821 mod
->address_start
= MIN (imageInfo
.text
, imageInfo
.data
);
1822 mod
->address_end
= MAX ((uint8_t*)imageInfo
.text
+ imageInfo
.text_size
,
1823 (uint8_t*)imageInfo
.data
+ imageInfo
.data_size
);
1824 mod
->perms
= g_strdup ("r--p");
1825 mod
->address_offset
= 0;
1827 if (g_slist_find_custom (ret
, mod
, find_procmodule
) == NULL
) {
1828 ret
= g_slist_prepend (ret
, mod
);
1830 free_procmodule (mod
);
1834 ret
= g_slist_reverse (ret
);
1839 static GSList
*load_modules (FILE *fp
)
1842 WapiProcModule
*mod
;
1843 gchar buf
[MAXPATHLEN
+ 1], *p
, *endp
;
1844 gchar
*start_start
, *end_start
, *prot_start
, *offset_start
;
1845 gchar
*maj_dev_start
, *min_dev_start
, *inode_start
, prot_buf
[5];
1846 gpointer address_start
, address_end
, address_offset
;
1847 guint32 maj_dev
, min_dev
;
1851 while (fgets (buf
, sizeof(buf
), fp
)) {
1853 while (g_ascii_isspace (*p
)) ++p
;
1855 if (!g_ascii_isxdigit (*start_start
)) {
1858 address_start
= (gpointer
)strtoul (start_start
, &endp
, 16);
1866 if (!g_ascii_isxdigit (*end_start
)) {
1869 address_end
= (gpointer
)strtoul (end_start
, &endp
, 16);
1871 if (!g_ascii_isspace (*p
)) {
1875 while (g_ascii_isspace (*p
)) ++p
;
1877 if (*prot_start
!= 'r' && *prot_start
!= '-') {
1880 memcpy (prot_buf
, prot_start
, 4);
1882 while (!g_ascii_isspace (*p
)) ++p
;
1884 while (g_ascii_isspace (*p
)) ++p
;
1886 if (!g_ascii_isxdigit (*offset_start
)) {
1889 address_offset
= (gpointer
)strtoul (offset_start
, &endp
, 16);
1891 if (!g_ascii_isspace (*p
)) {
1895 while(g_ascii_isspace (*p
)) ++p
;
1897 if (!g_ascii_isxdigit (*maj_dev_start
)) {
1900 maj_dev
= strtoul (maj_dev_start
, &endp
, 16);
1908 if (!g_ascii_isxdigit (*min_dev_start
)) {
1911 min_dev
= strtoul (min_dev_start
, &endp
, 16);
1913 if (!g_ascii_isspace (*p
)) {
1917 while (g_ascii_isspace (*p
)) ++p
;
1919 if (!g_ascii_isxdigit (*inode_start
)) {
1922 inode
= (ino_t
)strtol (inode_start
, &endp
, 10);
1924 if (!g_ascii_isspace (*p
)) {
1928 device
= makedev ((int)maj_dev
, (int)min_dev
);
1929 if ((device
== 0) &&
1934 while(g_ascii_isspace (*p
)) ++p
;
1935 /* p now points to the filename */
1937 mod
= g_new0 (WapiProcModule
, 1);
1938 mod
->address_start
= address_start
;
1939 mod
->address_end
= address_end
;
1940 mod
->perms
= g_strdup (prot_buf
);
1941 mod
->address_offset
= address_offset
;
1942 mod
->device
= device
;
1944 mod
->filename
= g_strdup (g_strstrip (p
));
1946 if (g_slist_find_custom (ret
, mod
, find_procmodule
) == NULL
) {
1947 ret
= g_slist_prepend (ret
, mod
);
1949 free_procmodule (mod
);
1953 ret
= g_slist_reverse (ret
);
1959 static gboolean
match_procname_to_modulename (gchar
*procname
, gchar
*modulename
)
1961 char* lastsep
= NULL
;
1962 char* lastsep2
= NULL
;
1965 gboolean result
= FALSE
;
1967 if (procname
== NULL
|| modulename
== NULL
)
1970 pname
= mono_path_resolve_symlinks (procname
);
1971 mname
= mono_path_resolve_symlinks (modulename
);
1973 if (!strcmp (pname
, mname
))
1977 lastsep
= strrchr (mname
, '/');
1979 if (!strcmp (lastsep
+1, pname
))
1982 lastsep2
= strrchr (pname
, '/');
1985 if (!strcmp (lastsep
+1, lastsep2
+1))
1988 if (!strcmp (mname
, lastsep2
+1))
2001 #if !defined(__OpenBSD__)
2003 open_process_map (int pid
, const char *mode
)
2006 const gchar
*proc_path
[] = {
2007 "/proc/%d/maps", /* GNU/Linux */
2008 "/proc/%d/map", /* FreeBSD */
2014 for (i
= 0; fp
== NULL
&& proc_path
[i
]; i
++) {
2015 filename
= g_strdup_printf (proc_path
[i
], pid
);
2016 fp
= fopen (filename
, mode
);
2024 gboolean
EnumProcessModules (gpointer process
, gpointer
*modules
,
2025 guint32 size
, guint32
*needed
)
2027 struct _WapiHandle_process
*process_handle
;
2029 #if !defined(__OpenBSD__) && !defined(PLATFORM_MACOSX)
2032 GSList
*mods
= NULL
;
2033 WapiProcModule
*module
;
2034 guint32 count
, avail
= size
/ sizeof(gpointer
);
2037 gchar
*proc_name
= NULL
;
2039 /* Store modules in an array of pointers (main module as
2040 * modules[0]), using the load address for each module as a
2041 * token. (Use 'NULL' as an alternative for the main module
2042 * so that the simple implementation can just return one item
2043 * for now.) Get the info from /proc/<pid>/maps on linux,
2044 * /proc/<pid>/map on FreeBSD, other systems will have to
2045 * implement /dev/kmem reading or whatever other horrid
2046 * technique is needed.
2048 if (size
< sizeof(gpointer
)) {
2052 if ((GPOINTER_TO_UINT (process
) & _WAPI_PROCESS_UNHANDLED
) == _WAPI_PROCESS_UNHANDLED
) {
2053 /* This is a pseudo handle */
2054 pid
= (pid_t
)(GPOINTER_TO_UINT (process
) & _WAPI_PROCESS_UNHANDLED_PID_MASK
);
2056 ok
= _wapi_lookup_handle (process
, WAPI_HANDLE_PROCESS
,
2057 (gpointer
*)&process_handle
);
2059 DEBUG ("%s: Can't find process %p", __func__
, process
);
2063 pid
= process_handle
->id
;
2064 proc_name
= process_handle
->proc_name
;
2067 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__) || defined(__HAIKU__)
2069 mods
= load_modules ();
2071 if ((fp
= open_process_map (pid
, "r")) == NULL
) {
2072 /* No /proc/<pid>/maps so just return the main module
2076 *needed
= sizeof(gpointer
);
2078 mods
= load_modules (fp
);
2081 count
= g_slist_length (mods
);
2083 /* count + 1 to leave slot 0 for the main module */
2084 *needed
= sizeof(gpointer
) * (count
+ 1);
2086 /* Use the NULL shortcut, as the first line in
2087 * /proc/<pid>/maps isn't the executable, and we need
2088 * that first in the returned list. Check the module name
2089 * to see if it ends with the proc name and substitute
2090 * the first entry with it. FIXME if this turns out to
2094 for (i
= 0; i
< (avail
- 1) && i
< count
; i
++) {
2095 module
= (WapiProcModule
*)g_slist_nth_data (mods
, i
);
2096 if (modules
[0] != NULL
)
2097 modules
[i
] = module
->address_start
;
2098 else if (match_procname_to_modulename (proc_name
, module
->filename
))
2099 modules
[0] = module
->address_start
;
2101 modules
[i
+ 1] = module
->address_start
;
2104 for (i
= 0; i
< count
; i
++) {
2105 free_procmodule (g_slist_nth_data (mods
, i
));
2107 g_slist_free (mods
);
2113 static gchar
*get_process_name_from_proc (pid_t pid
)
2115 #if defined(__OpenBSD__)
2118 struct kinfo_proc2
*pi
;
2119 #elif defined(PLATFORM_MACOSX)
2120 #if !(!defined (__mono_ppc__) && defined (TARGET_OSX))
2122 struct kinfo_proc
*pi
;
2123 int mib
[] = { CTL_KERN
, KERN_PROC
, KERN_PROC_PID
, pid
};
2127 gchar
*filename
= NULL
;
2132 #if defined(PLATFORM_SOLARIS)
2133 filename
= g_strdup_printf ("/proc/%d/psinfo", pid
);
2134 if ((fp
= fopen (filename
, "r")) != NULL
) {
2138 nread
= fread (&info
, sizeof (info
), 1, fp
);
2140 ret
= g_strdup (info
.pr_fname
);
2146 #elif defined(PLATFORM_MACOSX)
2147 #if !defined (__mono_ppc__) && defined (TARGET_OSX)
2148 /* No proc name on OSX < 10.5 nor ppc nor iOS */
2149 memset (buf
, '\0', sizeof(buf
));
2150 proc_name (pid
, buf
, sizeof(buf
));
2151 if (strlen (buf
) > 0)
2152 ret
= g_strdup (buf
);
2154 if (sysctl(mib
, 4, NULL
, &size
, NULL
, 0) < 0)
2157 if ((pi
= malloc(size
)) == NULL
)
2160 if (sysctl (mib
, 4, pi
, &size
, NULL
, 0) < 0) {
2161 if (errno
== ENOMEM
) {
2163 DEBUG ("%s: Didn't allocate enough memory for kproc info", __func__
);
2168 if (strlen (pi
->kp_proc
.p_comm
) > 0)
2169 ret
= g_strdup (pi
->kp_proc
.p_comm
);
2173 #elif defined(__OpenBSD__)
2175 mib
[1] = KERN_PROC2
;
2176 mib
[2] = KERN_PROC_PID
;
2178 mib
[4] = sizeof(struct kinfo_proc2
);
2182 if (sysctl(mib
, 6, NULL
, &size
, NULL
, 0) < 0)
2185 if ((pi
= malloc(size
)) == NULL
)
2188 mib
[5] = (int)(size
/ sizeof(struct kinfo_proc2
));
2190 if ((sysctl (mib
, 6, pi
, &size
, NULL
, 0) < 0) ||
2191 (size
!= sizeof (struct kinfo_proc2
))) {
2192 if (errno
== ENOMEM
) {
2199 if (strlen (pi
->p_comm
) > 0)
2200 ret
= g_strdup (pi
->p_comm
);
2203 #elif defined(__HAIKU__)
2204 image_info imageInfo
;
2207 if (get_next_image_info ((team_id
)pid
, &cookie
, &imageInfo
) == B_OK
) {
2208 ret
= g_strdup (imageInfo
.name
);
2211 memset (buf
, '\0', sizeof(buf
));
2212 filename
= g_strdup_printf ("/proc/%d/exe", pid
);
2213 if (readlink (filename
, buf
, 255) > 0) {
2214 ret
= g_strdup (buf
);
2222 filename
= g_strdup_printf ("/proc/%d/cmdline", pid
);
2223 if ((fp
= fopen (filename
, "r")) != NULL
) {
2224 if (fgets (buf
, 256, fp
) != NULL
) {
2225 ret
= g_strdup (buf
);
2236 filename
= g_strdup_printf ("/proc/%d/stat", pid
);
2237 if ((fp
= fopen (filename
, "r")) != NULL
) {
2238 if (fgets (buf
, 256, fp
) != NULL
) {
2241 start
= strchr (buf
, '(');
2242 if (start
!= NULL
) {
2243 end
= strchr (start
+ 1, ')');
2246 ret
= g_strndup (start
+ 1,
2260 static guint32
get_module_name (gpointer process
, gpointer module
,
2261 gunichar2
*basename
, guint32 size
,
2264 struct _WapiHandle_process
*process_handle
;
2267 gunichar2
*procname
;
2268 gchar
*procname_ext
= NULL
;
2271 #if !defined(__OpenBSD__) && !defined(PLATFORM_MACOSX)
2274 GSList
*mods
= NULL
;
2275 WapiProcModule
*found_module
;
2278 gchar
*proc_name
= NULL
;
2280 mono_once (&process_current_once
, process_set_current
);
2282 DEBUG ("%s: Getting module base name, process handle %p module %p",
2283 __func__
, process
, module
);
2285 size
= size
*sizeof(gunichar2
); /* adjust for unicode characters */
2287 if (basename
== NULL
|| size
== 0) {
2291 if ((GPOINTER_TO_UINT (process
) & _WAPI_PROCESS_UNHANDLED
) == _WAPI_PROCESS_UNHANDLED
) {
2292 /* This is a pseudo handle */
2293 pid
= (pid_t
)(GPOINTER_TO_UINT (process
) & _WAPI_PROCESS_UNHANDLED_PID_MASK
);
2294 proc_name
= get_process_name_from_proc (pid
);
2296 ok
= _wapi_lookup_handle (process
, WAPI_HANDLE_PROCESS
,
2297 (gpointer
*)&process_handle
);
2299 DEBUG ("%s: Can't find process %p", __func__
,
2304 pid
= process_handle
->id
;
2305 proc_name
= g_strdup (process_handle
->proc_name
);
2308 /* Look up the address in /proc/<pid>/maps */
2309 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__) || defined(__HAIKU__)
2311 mods
= load_modules ();
2313 if ((fp
= open_process_map (pid
, "r")) == NULL
) {
2314 if (errno
== EACCES
&& module
== NULL
&& base
== TRUE
) {
2315 procname_ext
= get_process_name_from_proc (pid
);
2317 /* No /proc/<pid>/maps, so just return failure
2324 mods
= load_modules (fp
);
2327 count
= g_slist_length (mods
);
2329 /* If module != NULL compare the address.
2330 * If module == NULL we are looking for the main module.
2331 * The best we can do for now check it the module name end with the process name.
2333 for (i
= 0; i
< count
; i
++) {
2334 found_module
= (WapiProcModule
*)g_slist_nth_data (mods
, i
);
2335 if (procname_ext
== NULL
&&
2336 ((module
== NULL
&& match_procname_to_modulename (proc_name
, found_module
->filename
)) ||
2337 (module
!= NULL
&& found_module
->address_start
== module
))) {
2339 procname_ext
= g_path_get_basename (found_module
->filename
);
2341 procname_ext
= g_strdup (found_module
->filename
);
2345 free_procmodule (found_module
);
2348 if (procname_ext
== NULL
)
2350 /* If it's *still* null, we might have hit the
2351 * case where reading /proc/$pid/maps gives an
2352 * empty file for this user.
2354 procname_ext
= get_process_name_from_proc (pid
);
2357 g_slist_free (mods
);
2361 if (procname_ext
!= NULL
) {
2362 DEBUG ("%s: Process name is [%s]", __func__
,
2365 procname
= mono_unicode_from_external (procname_ext
, &bytes
);
2366 if (procname
== NULL
) {
2368 g_free (procname_ext
);
2374 /* Add the terminator */
2378 DEBUG ("%s: Size %d smaller than needed (%ld); truncating", __func__
, size
, bytes
);
2380 memcpy (basename
, procname
, size
);
2382 DEBUG ("%s: Size %d larger than needed (%ld)",
2383 __func__
, size
, bytes
);
2385 memcpy (basename
, procname
, bytes
);
2389 g_free (procname_ext
);
2397 guint32
GetModuleBaseName (gpointer process
, gpointer module
,
2398 gunichar2
*basename
, guint32 size
)
2400 return(get_module_name (process
, module
, basename
, size
, TRUE
));
2403 guint32
GetModuleFileNameEx (gpointer process
, gpointer module
,
2404 gunichar2
*filename
, guint32 size
)
2406 return(get_module_name (process
, module
, filename
, size
, FALSE
));
2409 gboolean
GetModuleInformation (gpointer process
, gpointer module
,
2410 WapiModuleInfo
*modinfo
, guint32 size
)
2412 struct _WapiHandle_process
*process_handle
;
2415 #if !defined(__OpenBSD__) && !defined(PLATFORM_MACOSX)
2418 GSList
*mods
= NULL
;
2419 WapiProcModule
*found_module
;
2422 gboolean ret
= FALSE
;
2423 gchar
*proc_name
= NULL
;
2425 mono_once (&process_current_once
, process_set_current
);
2427 DEBUG ("%s: Getting module info, process handle %p module %p",
2428 __func__
, process
, module
);
2430 if (modinfo
== NULL
|| size
< sizeof(WapiModuleInfo
)) {
2434 if ((GPOINTER_TO_UINT (process
) & _WAPI_PROCESS_UNHANDLED
) == _WAPI_PROCESS_UNHANDLED
) {
2435 /* This is a pseudo handle */
2436 pid
= (pid_t
)(GPOINTER_TO_UINT (process
) & _WAPI_PROCESS_UNHANDLED_PID_MASK
);
2437 proc_name
= get_process_name_from_proc (pid
);
2439 ok
= _wapi_lookup_handle (process
, WAPI_HANDLE_PROCESS
,
2440 (gpointer
*)&process_handle
);
2442 DEBUG ("%s: Can't find process %p", __func__
,
2447 pid
= process_handle
->id
;
2448 proc_name
= g_strdup (process_handle
->proc_name
);
2451 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__) || defined(__HAIKU__)
2453 mods
= load_modules ();
2455 /* Look up the address in /proc/<pid>/maps */
2456 if ((fp
= open_process_map (pid
, "r")) == NULL
) {
2457 /* No /proc/<pid>/maps, so just return failure
2463 mods
= load_modules (fp
);
2466 count
= g_slist_length (mods
);
2468 /* If module != NULL compare the address.
2469 * If module == NULL we are looking for the main module.
2470 * The best we can do for now check it the module name end with the process name.
2472 for (i
= 0; i
< count
; i
++) {
2473 found_module
= (WapiProcModule
*)g_slist_nth_data (mods
, i
);
2474 if ( ret
== FALSE
&&
2475 ((module
== NULL
&& match_procname_to_modulename (proc_name
, found_module
->filename
)) ||
2476 (module
!= NULL
&& found_module
->address_start
== module
))) {
2477 modinfo
->lpBaseOfDll
= found_module
->address_start
;
2478 modinfo
->SizeOfImage
= (gsize
)(found_module
->address_end
) - (gsize
)(found_module
->address_start
);
2479 modinfo
->EntryPoint
= found_module
->address_offset
;
2483 free_procmodule (found_module
);
2486 g_slist_free (mods
);
2493 gboolean
GetProcessWorkingSetSize (gpointer process
, size_t *min
, size_t *max
)
2495 struct _WapiHandle_process
*process_handle
;
2498 mono_once (&process_current_once
, process_set_current
);
2500 if(min
==NULL
|| max
==NULL
) {
2501 /* Not sure if w32 allows NULLs here or not */
2505 if ((GPOINTER_TO_UINT (process
) & _WAPI_PROCESS_UNHANDLED
) == _WAPI_PROCESS_UNHANDLED
) {
2506 /* This is a pseudo handle, so just fail for now
2511 ok
=_wapi_lookup_handle (process
, WAPI_HANDLE_PROCESS
,
2512 (gpointer
*)&process_handle
);
2514 DEBUG ("%s: Can't find process %p", __func__
, process
);
2519 *min
=process_handle
->min_working_set
;
2520 *max
=process_handle
->max_working_set
;
2525 gboolean
SetProcessWorkingSetSize (gpointer process
, size_t min
, size_t max
)
2527 struct _WapiHandle_process
*process_handle
;
2530 mono_once (&process_current_once
, process_set_current
);
2532 if ((GPOINTER_TO_UINT (process
) & _WAPI_PROCESS_UNHANDLED
) == _WAPI_PROCESS_UNHANDLED
) {
2533 /* This is a pseudo handle, so just fail for now
2538 ok
=_wapi_lookup_handle (process
, WAPI_HANDLE_PROCESS
,
2539 (gpointer
*)&process_handle
);
2541 DEBUG ("%s: Can't find process %p", __func__
, process
);
2546 process_handle
->min_working_set
=min
;
2547 process_handle
->max_working_set
=max
;
2554 TerminateProcess (gpointer process
, gint32 exitCode
)
2556 struct _WapiHandle_process
*process_handle
;
2562 if ((GPOINTER_TO_UINT (process
) & _WAPI_PROCESS_UNHANDLED
) == _WAPI_PROCESS_UNHANDLED
) {
2563 /* This is a pseudo handle */
2564 pid
= (pid_t
)(GPOINTER_TO_UINT (process
) & _WAPI_PROCESS_UNHANDLED_PID_MASK
);
2566 ok
= _wapi_lookup_handle (process
, WAPI_HANDLE_PROCESS
,
2567 (gpointer
*) &process_handle
);
2570 DEBUG ("%s: Can't find process %p", __func__
,
2572 SetLastError (ERROR_INVALID_HANDLE
);
2575 pid
= process_handle
->id
;
2578 signo
= (exitCode
== -1) ? SIGKILL
: SIGTERM
;
2579 ret
= kill (pid
, signo
);
2583 SetLastError (ERROR_INVALID_PARAMETER
);
2586 SetLastError (ERROR_ACCESS_DENIED
);
2589 SetLastError (ERROR_PROC_NOT_FOUND
);
2592 SetLastError (ERROR_GEN_FAILURE
);
2600 GetPriorityClass (gpointer process
)
2602 #ifdef HAVE_GETPRIORITY
2603 struct _WapiHandle_process
*process_handle
;
2608 if ((GPOINTER_TO_UINT (process
) & _WAPI_PROCESS_UNHANDLED
) == _WAPI_PROCESS_UNHANDLED
) {
2609 /* This is a pseudo handle */
2610 pid
= (pid_t
)(GPOINTER_TO_UINT (process
) & _WAPI_PROCESS_UNHANDLED_PID_MASK
);
2612 ok
= _wapi_lookup_handle (process
, WAPI_HANDLE_PROCESS
,
2613 (gpointer
*) &process_handle
);
2616 SetLastError (ERROR_INVALID_HANDLE
);
2619 pid
= process_handle
->id
;
2623 ret
= getpriority (PRIO_PROCESS
, pid
);
2624 if (ret
== -1 && errno
!= 0) {
2628 SetLastError (ERROR_ACCESS_DENIED
);
2631 SetLastError (ERROR_PROC_NOT_FOUND
);
2634 SetLastError (ERROR_GEN_FAILURE
);
2640 return NORMAL_PRIORITY_CLASS
;
2642 return REALTIME_PRIORITY_CLASS
;
2644 return HIGH_PRIORITY_CLASS
;
2646 return ABOVE_NORMAL_PRIORITY_CLASS
;
2648 return IDLE_PRIORITY_CLASS
;
2650 return BELOW_NORMAL_PRIORITY_CLASS
;
2652 return NORMAL_PRIORITY_CLASS
;
2654 SetLastError (ERROR_NOT_SUPPORTED
);
2660 SetPriorityClass (gpointer process
, guint32 priority_class
)
2662 #ifdef HAVE_SETPRIORITY
2663 struct _WapiHandle_process
*process_handle
;
2669 if ((GPOINTER_TO_UINT (process
) & _WAPI_PROCESS_UNHANDLED
) == _WAPI_PROCESS_UNHANDLED
) {
2670 /* This is a pseudo handle */
2671 pid
= (pid_t
)(GPOINTER_TO_UINT (process
) & _WAPI_PROCESS_UNHANDLED_PID_MASK
);
2673 ok
= _wapi_lookup_handle (process
, WAPI_HANDLE_PROCESS
,
2674 (gpointer
*) &process_handle
);
2677 SetLastError (ERROR_INVALID_HANDLE
);
2680 pid
= process_handle
->id
;
2683 switch (priority_class
) {
2684 case IDLE_PRIORITY_CLASS
:
2687 case BELOW_NORMAL_PRIORITY_CLASS
:
2690 case NORMAL_PRIORITY_CLASS
:
2693 case ABOVE_NORMAL_PRIORITY_CLASS
:
2696 case HIGH_PRIORITY_CLASS
:
2699 case REALTIME_PRIORITY_CLASS
:
2703 SetLastError (ERROR_INVALID_PARAMETER
);
2707 ret
= setpriority (PRIO_PROCESS
, pid
, prio
);
2712 SetLastError (ERROR_ACCESS_DENIED
);
2715 SetLastError (ERROR_PROC_NOT_FOUND
);
2718 SetLastError (ERROR_GEN_FAILURE
);
2724 SetLastError (ERROR_NOT_SUPPORTED
);
2730 mono_processes_cleanup (void)
2732 struct MonoProcess
*mp
;
2733 struct MonoProcess
*prev
= NULL
;
2734 struct MonoProcess
*candidate
= NULL
;
2735 gpointer unref_handle
;
2738 DEBUG ("%s", __func__
);
2740 /* Ensure we're not in here in multiple threads at once, nor recursive. */
2741 if (InterlockedCompareExchange (&mono_processes_cleaning_up
, 1, 0) != 0)
2744 mp
= mono_processes
;
2745 while (mp
!= NULL
) {
2746 if (mp
->pid
== 0 && mp
->handle
!= NULL
) {
2747 /* This process has exited and we need to remove the artifical ref
2749 mono_mutex_lock (&mono_processes_mutex
);
2750 unref_handle
= mp
->handle
;
2752 mono_mutex_unlock (&mono_processes_mutex
);
2754 _wapi_handle_unref (unref_handle
);
2760 mp
= mono_processes
;
2762 while (mp
!= NULL
) {
2763 if ((mp
->handle_count
== 0 && mp
->pid
== 0) || candidate
!= NULL
) {
2765 _wapi_handle_spin (spin
);
2769 /* We've found a candidate */
2770 mono_mutex_lock (&mono_processes_mutex
);
2771 if (candidate
== NULL
) {
2773 if (mp
== mono_processes
) {
2774 mono_processes
= mp
->next
;
2776 prev
->next
= mp
->next
;
2781 /* It's still safe to traverse the structure.*/
2782 mono_memory_barrier ();
2784 if (mono_processes_read_lock
!= 0) {
2785 /* The sigchld handler is watching us. Spin a bit and try again */
2788 } else if (spin
>= 8) {
2789 /* Just give up for now */
2790 mono_mutex_unlock (&mono_processes_mutex
);
2794 /* We've modified the list of processes, and we know the sigchld handler
2795 * isn't executing, so even if it executes at any moment, it'll see the
2796 * new version of the list. So now we can free the candidate. */
2797 DEBUG ("%s: freeing candidate %p", __func__
, candidate
);
2798 mp
= candidate
->next
;
2799 MONO_SEM_DESTROY (&candidate
->exit_sem
);
2804 mono_mutex_unlock (&mono_processes_mutex
);
2813 DEBUG ("%s done", __func__
);
2815 InterlockedDecrement (&mono_processes_cleaning_up
);
2819 process_close (gpointer handle
, gpointer data
)
2821 struct _WapiHandle_process
*process_handle
;
2823 DEBUG ("%s", __func__
);
2825 process_handle
= (struct _WapiHandle_process
*) data
;
2826 if (process_handle
->mono_process
&& process_handle
->self
== _wapi_getpid ())
2827 InterlockedDecrement (&process_handle
->mono_process
->handle_count
);
2828 mono_processes_cleanup ();
2832 MONO_SIGNAL_HANDLER_FUNC (static, mono_sigchld_signal_handler
, (int _dummy
, siginfo_t
*info
, void *context
))
2836 struct MonoProcess
*p
;
2839 fprintf (stdout
, "SIG CHILD handler for pid: %i\n", info
->si_pid
);
2842 InterlockedIncrement (&mono_processes_read_lock
);
2846 pid
= waitpid (-1, &status
, WNOHANG
);
2847 } while (pid
== -1 && errno
== EINTR
);
2853 fprintf (stdout
, "child ended: %i", pid
);
2857 if (p
->pid
== pid
) {
2858 p
->pid
= 0; /* this pid doesn't exist anymore, clear it */
2860 MONO_SEM_POST (&p
->exit_sem
);
2867 InterlockedDecrement (&mono_processes_read_lock
);
2870 fprintf (stdout
, "SIG CHILD handler: done looping.");
2876 static void process_add_sigchld_handler (void)
2879 struct sigaction sa
;
2881 sa
.sa_sigaction
= mono_sigchld_signal_handler
;
2882 sigemptyset (&sa
.sa_mask
);
2883 sa
.sa_flags
= SA_NOCLDSTOP
| SA_SIGINFO
;
2884 g_assert (sigaction (SIGCHLD
, &sa
, &previous_chld_sa
) != -1);
2885 DEBUG ("Added SIGCHLD handler");
2889 static guint32
process_wait (gpointer handle
, guint32 timeout
, gboolean alertable
)
2891 struct _WapiHandle_process
*process_handle
;
2897 struct MonoProcess
*mp
;
2899 gpointer current_thread
;
2901 current_thread
= _wapi_thread_handle_from_id (pthread_self ());
2902 if (current_thread
== NULL
) {
2903 SetLastError (ERROR_INVALID_HANDLE
);
2907 /* FIXME: We can now easily wait on processes that aren't our own children,
2908 * but WaitFor*Object won't call us for pseudo handles. */
2909 g_assert ((GPOINTER_TO_UINT (handle
) & _WAPI_PROCESS_UNHANDLED
) != _WAPI_PROCESS_UNHANDLED
);
2911 DEBUG ("%s (%p, %u)", __func__
, handle
, timeout
);
2913 ok
= _wapi_lookup_handle (handle
, WAPI_HANDLE_PROCESS
, (gpointer
*)&process_handle
);
2915 g_warning ("%s: error looking up process handle %p", __func__
, handle
);
2919 if (process_handle
->exited
) {
2920 /* We've already done this one */
2921 DEBUG ("%s (%p, %u): Process already exited", __func__
, handle
, timeout
);
2922 return WAIT_OBJECT_0
;
2925 pid
= process_handle
->id
;
2927 DEBUG ("%s (%p, %u): PID: %d", __func__
, handle
, timeout
, pid
);
2929 /* We don't need to lock mono_processes here, the entry
2930 * has a handle_count > 0 which means it will not be freed. */
2931 mp
= process_handle
->mono_process
;
2932 if (mp
&& process_handle
->self
!= _wapi_getpid ()) {
2933 /* mono_process points to memory in another process' address space: we can't use it */
2937 start
= mono_msec_ticks ();
2943 /* We have a semaphore we can wait on */
2944 if (timeout
!= INFINITE
) {
2945 DEBUG ("%s (%p, %u): waiting on semaphore for %li ms...",
2946 __func__
, handle
, timeout
, (timeout
- (now
- start
)));
2948 ret
= MONO_SEM_TIMEDWAIT_ALERTABLE (&mp
->exit_sem
, (timeout
- (now
- start
)), alertable
);
2950 DEBUG ("%s (%p, %u): waiting on semaphore forever...",
2951 __func__
, handle
, timeout
);
2952 ret
= MONO_SEM_WAIT_ALERTABLE (&mp
->exit_sem
, alertable
);
2955 if (ret
== -1 && errno
!= EINTR
&& errno
!= ETIMEDOUT
) {
2956 DEBUG ("%s (%p, %u): sem_timedwait failure: %s",
2957 __func__
, handle
, timeout
, g_strerror (errno
));
2958 /* Should we return a failure here? */
2962 /* Success, process has exited */
2963 MONO_SEM_POST (&mp
->exit_sem
);
2967 /* We did not create this process, so we can't waidpid / sem_wait it.
2968 * We need to poll for the pid existence */
2969 DEBUG ("%s (%p, %u): polling on pid...", __func__
, handle
, timeout
);
2970 if (!is_pid_valid (pid
)) {
2971 /* Success, process has exited */
2977 DEBUG ("%s (%p, %u): WAIT_TIMEOUT (timeout = 0)", __func__
, handle
, timeout
);
2978 return WAIT_TIMEOUT
;
2981 now
= mono_msec_ticks ();
2982 if (now
- start
>= timeout
) {
2983 DEBUG ("%s (%p, %u): WAIT_TIMEOUT", __func__
, handle
, timeout
);
2984 return WAIT_TIMEOUT
;
2988 /* "timeout - (now - start)" will not underflow, since timeout is always >=0,
2989 * and we passed the check just above */
2990 _wapi_handle_spin (MIN (100, timeout
- (now
- start
)));
2993 if (alertable
&& _wapi_thread_apc_pending (current_thread
)) {
2994 DEBUG ("%s (%p, %u): WAIT_IO_COMPLETION", __func__
, handle
, timeout
);
2995 return WAIT_IO_COMPLETION
;
2999 /* Process must have exited */
3000 DEBUG ("%s (%p, %u): Waited successfully", __func__
, handle
, timeout
);
3002 ret
= _wapi_handle_lock_shared_handles ();
3003 g_assert (ret
== 0);
3005 status
= mp
? mp
->status
: 0;
3006 if (WIFSIGNALED (status
)) {
3007 process_handle
->exitstatus
= 128 + WTERMSIG (status
);
3009 process_handle
->exitstatus
= WEXITSTATUS (status
);
3011 _wapi_time_t_to_filetime (time (NULL
), &process_handle
->exit_time
);
3013 process_handle
->exited
= TRUE
;
3015 DEBUG ("%s (%p, %u): Setting pid %d signalled, exit status %d",
3016 __func__
, handle
, timeout
, process_handle
->id
, process_handle
->exitstatus
);
3018 _wapi_shared_handle_set_signal_state (handle
, TRUE
);
3020 _wapi_handle_unlock_shared_handles ();
3022 return WAIT_OBJECT_0
;