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
;
145 static char *cli_launcher
;
147 static mono_once_t process_ops_once
=MONO_ONCE_INIT
;
149 static void process_ops_init (void)
151 _wapi_handle_register_capabilities (WAPI_HANDLE_PROCESS
,
152 WAPI_HANDLE_CAP_WAIT
|
153 WAPI_HANDLE_CAP_SPECIAL_WAIT
);
157 /* Check if a pid is valid - i.e. if a process exists with this pid. */
158 static gboolean
is_pid_valid (pid_t pid
)
160 gboolean result
= FALSE
;
162 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__)
163 if (((kill(pid
, 0) == 0) || (errno
== EPERM
)) && pid
!= 0)
165 #elif defined(__HAIKU__)
167 if (get_team_info ((team_id
)pid
, &teamInfo
) == B_OK
)
170 gchar
*dir
= g_strdup_printf ("/proc/%d", pid
);
171 if (!access (dir
, F_OK
))
179 static void process_set_defaults (struct _WapiHandle_process
*process_handle
)
181 /* These seem to be the defaults on w2k */
182 process_handle
->min_working_set
= 204800;
183 process_handle
->max_working_set
= 1413120;
185 _wapi_time_t_to_filetime (time (NULL
), &process_handle
->create_time
);
189 len16 (const gunichar2
*str
)
200 utf16_concat (const gunichar2
*first
, ...)
207 va_start (args
, first
);
208 total
+= len16 (first
);
209 for (s
= va_arg (args
, gunichar2
*); s
!= NULL
; s
= va_arg(args
, gunichar2
*)){
214 ret
= g_new (gunichar2
, total
+ 1);
220 for (s
= first
; *s
!= 0; s
++)
222 va_start (args
, first
);
223 for (s
= va_arg (args
, gunichar2
*); s
!= NULL
; s
= va_arg (args
, gunichar2
*)){
226 for (p
= s
; *p
!= 0; p
++)
234 #ifdef PLATFORM_MACOSX
236 /* 0 = no detection; -1 = not 10.5 or higher; 1 = 10.5 or higher */
237 static int osx_10_5_or_higher
;
240 detect_osx_10_5_or_higher (void)
246 if (uname (&u
) != 0){
247 osx_10_5_or_higher
= 1;
255 osx_10_5_or_higher
= -1;
257 osx_10_5_or_higher
= 1;
261 is_macos_10_5_or_higher (void)
263 if (osx_10_5_or_higher
== 0)
264 detect_osx_10_5_or_higher ();
266 return (osx_10_5_or_higher
== 1);
270 static const gunichar2 utf16_space_bytes
[2] = { 0x20, 0 };
271 static const gunichar2
*utf16_space
= utf16_space_bytes
;
272 static const gunichar2 utf16_quote_bytes
[2] = { 0x22, 0 };
273 static const gunichar2
*utf16_quote
= utf16_quote_bytes
;
278 print_utf16 (gunichar2
*str
)
282 res
= g_utf16_to_utf8 (str
, -1, NULL
, NULL
, NULL
);
283 g_print ("%s\n", res
);
288 /* Implemented as just a wrapper around CreateProcess () */
289 gboolean
ShellExecuteEx (WapiShellExecuteInfo
*sei
)
292 WapiProcessInformation process_info
;
296 /* w2k just segfaults here, but we can do better than
299 SetLastError (ERROR_INVALID_PARAMETER
);
303 if (sei
->lpFile
== NULL
) {
304 /* w2k returns TRUE for this, for some reason. */
308 /* Put both executable and parameters into the second argument
309 * to CreateProcess (), so it searches $PATH. The conversion
310 * into and back out of utf8 is because there is no
311 * g_strdup_printf () equivalent for gunichar2 :-(
313 args
= utf16_concat (utf16_quote
, sei
->lpFile
, utf16_quote
, sei
->lpParameters
== NULL
? NULL
: utf16_space
, sei
->lpParameters
, NULL
);
315 SetLastError (ERROR_INVALID_DATA
);
318 ret
= CreateProcess (NULL
, args
, NULL
, NULL
, TRUE
,
319 CREATE_UNICODE_ENVIRONMENT
, NULL
,
320 sei
->lpDirectory
, NULL
, &process_info
);
323 if (!ret
&& GetLastError () == ERROR_OUTOFMEMORY
)
327 static char *handler
;
328 static gunichar2
*handler_utf16
;
330 if (handler_utf16
== (gunichar2
*)-1)
333 #ifdef PLATFORM_MACOSX
334 handler
= g_strdup ("/usr/bin/open");
337 * On Linux, try: xdg-open, the FreeDesktop standard way of doing it,
338 * if that fails, try to use gnome-open, then kfmclient
340 handler
= g_find_program_in_path ("xdg-open");
341 if (handler
== NULL
){
342 handler
= g_find_program_in_path ("gnome-open");
343 if (handler
== NULL
){
344 handler
= g_find_program_in_path ("kfmclient");
345 if (handler
== NULL
){
346 handler_utf16
= (gunichar2
*) -1;
349 /* kfmclient needs exec argument */
351 handler
= g_strconcat (old
, " exec",
358 handler_utf16
= g_utf8_to_utf16 (handler
, -1, NULL
, NULL
, NULL
);
361 /* Put quotes around the filename, in case it's a url
362 * that contains #'s (CreateProcess() calls
363 * g_shell_parse_argv(), which deliberately throws
364 * away anything after an unquoted #). Fixes bug
367 args
= utf16_concat (handler_utf16
, utf16_space
, utf16_quote
,
368 sei
->lpFile
, utf16_quote
,
369 sei
->lpParameters
== NULL
? NULL
: utf16_space
,
370 sei
->lpParameters
, NULL
);
372 SetLastError (ERROR_INVALID_DATA
);
375 ret
= CreateProcess (NULL
, args
, NULL
, NULL
, TRUE
,
376 CREATE_UNICODE_ENVIRONMENT
, NULL
,
377 sei
->lpDirectory
, NULL
, &process_info
);
380 if (GetLastError () != ERROR_OUTOFMEMORY
)
381 SetLastError (ERROR_INVALID_DATA
);
384 /* Shell exec should not return a process handle when it spawned a GUI thing, like a browser. */
385 CloseHandle (process_info
.hProcess
);
386 process_info
.hProcess
= NULL
;
389 if (sei
->fMask
& SEE_MASK_NOCLOSEPROCESS
) {
390 sei
->hProcess
= process_info
.hProcess
;
392 CloseHandle (process_info
.hProcess
);
399 is_managed_binary (const gchar
*filename
)
401 int original_errno
= errno
;
402 #if defined(HAVE_LARGE_FILE_SUPPORT) && defined(O_LARGEFILE)
403 int file
= open (filename
, O_RDONLY
| O_LARGEFILE
);
405 int file
= open (filename
, O_RDONLY
);
408 unsigned char buffer
[8];
409 off_t file_size
, optional_header_offset
;
410 off_t pe_header_offset
;
411 gboolean managed
= FALSE
;
413 guint32 first_word
, second_word
;
415 /* If we are unable to open the file, then we definitely
416 * can't say that it is managed. The child mono process
417 * probably wouldn't be able to open it anyway.
420 errno
= original_errno
;
424 /* Retrieve the length of the file for future sanity checks. */
425 file_size
= lseek (file
, 0, SEEK_END
);
426 lseek (file
, 0, SEEK_SET
);
428 /* We know we need to read a header field at offset 60. */
432 num_read
= read (file
, buffer
, 2);
434 if ((num_read
!= 2) || (buffer
[0] != 'M') || (buffer
[1] != 'Z'))
437 new_offset
= lseek (file
, 60, SEEK_SET
);
439 if (new_offset
!= 60)
442 num_read
= read (file
, buffer
, 4);
446 pe_header_offset
= buffer
[0]
451 if (pe_header_offset
+ 24 > file_size
)
454 new_offset
= lseek (file
, pe_header_offset
, SEEK_SET
);
456 if (new_offset
!= pe_header_offset
)
459 num_read
= read (file
, buffer
, 4);
461 if ((num_read
!= 4) || (buffer
[0] != 'P') || (buffer
[1] != 'E') || (buffer
[2] != 0) || (buffer
[3] != 0))
465 * Verify that the header we want in the optional header data
466 * is present in this binary.
468 new_offset
= lseek (file
, pe_header_offset
+ 20, SEEK_SET
);
470 if (new_offset
!= pe_header_offset
+ 20)
473 num_read
= read (file
, buffer
, 2);
475 if ((num_read
!= 2) || ((buffer
[0] | (buffer
[1] << 8)) < 216))
478 /* Read the CLR header address and size fields. These will be
479 * zero if the binary is not managed.
481 optional_header_offset
= pe_header_offset
+ 24;
482 new_offset
= lseek (file
, optional_header_offset
+ 208, SEEK_SET
);
484 if (new_offset
!= optional_header_offset
+ 208)
487 num_read
= read (file
, buffer
, 8);
489 /* We are not concerned with endianness, only with
490 * whether it is zero or not.
492 first_word
= *(guint32
*)&buffer
[0];
493 second_word
= *(guint32
*)&buffer
[4];
495 if ((num_read
!= 8) || (first_word
== 0) || (second_word
== 0))
502 errno
= original_errno
;
506 gboolean
CreateProcessWithLogonW (const gunichar2
*username
,
507 const gunichar2
*domain
,
508 const gunichar2
*password
,
509 const guint32 logonFlags
,
510 const gunichar2
*appname
,
511 const gunichar2
*cmdline
,
512 guint32 create_flags
,
514 const gunichar2
*cwd
,
515 WapiStartupInfo
*startup
,
516 WapiProcessInformation
*process_info
)
518 /* FIXME: use user information */
519 return CreateProcess (appname
, cmdline
, NULL
, NULL
, FALSE
, create_flags
, env
, cwd
, startup
, process_info
);
523 is_executable (const char *prog
)
526 if (access (prog
, X_OK
) != 0)
528 if (stat (prog
, &buf
))
530 if (S_ISREG (buf
.st_mode
))
536 switchDirectorySeparators(gchar
*path
)
538 size_t i
, pathLength
= strlen(path
);
540 /* Turn all the slashes round the right way, except for \' */
541 /* There are probably other characters that need to be excluded as well. */
542 for (i
= 0; i
< pathLength
; i
++)
544 if (path
[i
] == '\\' && i
< pathLength
- 1 && path
[i
+1] != '\'' ) {
550 gboolean
CreateProcess (const gunichar2
*appname
, const gunichar2
*cmdline
,
551 WapiSecurityAttributes
*process_attrs G_GNUC_UNUSED
,
552 WapiSecurityAttributes
*thread_attrs G_GNUC_UNUSED
,
553 gboolean inherit_handles
, guint32 create_flags
,
554 gpointer new_environ
, const gunichar2
*cwd
,
555 WapiStartupInfo
*startup
,
556 WapiProcessInformation
*process_info
)
558 gchar
*cmd
=NULL
, *prog
= NULL
, *full_prog
= NULL
, *args
= NULL
, *args_after_prog
= NULL
, *dir
= NULL
, **env_strings
= NULL
, **argv
= NULL
;
559 guint32 i
, env_count
= 0;
560 gboolean ret
= FALSE
;
562 struct _WapiHandle_process process_handle
= {0}, *process_handle_data
;
564 int in_fd
, out_fd
, err_fd
;
567 int startup_pipe
[2] = {-1, -1};
569 struct MonoProcess
*mono_process
;
570 gboolean fork_failed
= FALSE
;
572 mono_once (&process_ops_once
, process_ops_init
);
573 mono_once (&process_sig_chld_once
, process_add_sigchld_handler
);
575 /* appname and cmdline specify the executable and its args:
577 * If appname is not NULL, it is the name of the executable.
578 * Otherwise the executable is the first token in cmdline.
580 * Executable searching:
582 * If appname is not NULL, it can specify the full path and
583 * file name, or else a partial name and the current directory
584 * will be used. There is no additional searching.
586 * If appname is NULL, the first whitespace-delimited token in
587 * cmdline is used. If the name does not contain a full
588 * directory path, the search sequence is:
590 * 1) The directory containing the current process
591 * 2) The current working directory
592 * 3) The windows system directory (Ignored)
593 * 4) The windows directory (Ignored)
596 * Just to make things more interesting, tokens can contain
597 * white space if they are surrounded by quotation marks. I'm
598 * beginning to understand just why windows apps are generally
599 * so crap, with an API like this :-(
601 if (appname
!= NULL
) {
602 cmd
= mono_unicode_to_external (appname
);
604 DEBUG ("%s: unicode conversion returned NULL",
607 SetLastError (ERROR_PATH_NOT_FOUND
);
611 switchDirectorySeparators(cmd
);
614 if (cmdline
!= NULL
) {
615 args
= mono_unicode_to_external (cmdline
);
617 DEBUG ("%s: unicode conversion returned NULL", __func__
);
619 SetLastError (ERROR_PATH_NOT_FOUND
);
625 dir
= mono_unicode_to_external (cwd
);
627 DEBUG ("%s: unicode conversion returned NULL", __func__
);
629 SetLastError (ERROR_PATH_NOT_FOUND
);
633 /* Turn all the slashes round the right way */
634 switchDirectorySeparators(dir
);
638 /* We can't put off locating the executable any longer :-( */
641 if (g_ascii_isalpha (cmd
[0]) && (cmd
[1] == ':')) {
642 /* Strip off the drive letter. I can't
643 * believe that CP/M holdover is still
646 g_memmove (cmd
, cmd
+2, strlen (cmd
)-2);
647 cmd
[strlen (cmd
)-2] = '\0';
650 unquoted
= g_shell_unquote (cmd
, NULL
);
651 if (unquoted
[0] == '/') {
652 /* Assume full path given */
653 prog
= g_strdup (unquoted
);
655 /* Executable existing ? */
656 if (!is_executable (prog
)) {
657 DEBUG ("%s: Couldn't find executable %s",
660 SetLastError (ERROR_FILE_NOT_FOUND
);
664 /* Search for file named by cmd in the current
667 char *curdir
= g_get_current_dir ();
669 prog
= g_strdup_printf ("%s/%s", curdir
, unquoted
);
672 /* And make sure it's executable */
673 if (!is_executable (prog
)) {
674 DEBUG ("%s: Couldn't find executable %s",
677 SetLastError (ERROR_FILE_NOT_FOUND
);
683 args_after_prog
= args
;
688 /* Dig out the first token from args, taking quotation
692 /* First, strip off all leading whitespace */
693 args
= g_strchug (args
);
695 /* args_after_prog points to the contents of args
696 * after token has been set (otherwise argv[0] is
699 args_after_prog
= args
;
701 /* Assume the opening quote will always be the first
704 if (args
[0] == '\"' || args
[0] == '\'') {
706 for (i
= 1; args
[i
] != '\0' && args
[i
] != quote
; i
++);
707 if (args
[i
+ 1] == '\0' || g_ascii_isspace (args
[i
+1])) {
708 /* We found the first token */
709 token
= g_strndup (args
+1, i
-1);
710 args_after_prog
= g_strchug (args
+ i
+ 1);
712 /* Quotation mark appeared in the
713 * middle of the token. Just give the
714 * whole first token, quotes and all,
721 /* No quote mark, or malformed */
722 for (i
= 0; args
[i
] != '\0'; i
++) {
723 if (g_ascii_isspace (args
[i
])) {
724 token
= g_strndup (args
, i
);
725 args_after_prog
= args
+ i
+ 1;
731 if (token
== NULL
&& args
[0] != '\0') {
732 /* Must be just one token in the string */
733 token
= g_strdup (args
);
734 args_after_prog
= NULL
;
739 DEBUG ("%s: Couldn't find what to exec", __func__
);
741 SetLastError (ERROR_PATH_NOT_FOUND
);
745 /* Turn all the slashes round the right way. Only for
748 switchDirectorySeparators(token
);
750 if (g_ascii_isalpha (token
[0]) && (token
[1] == ':')) {
751 /* Strip off the drive letter. I can't
752 * believe that CP/M holdover is still
755 g_memmove (token
, token
+2, strlen (token
)-2);
756 token
[strlen (token
)-2] = '\0';
759 if (token
[0] == '/') {
760 /* Assume full path given */
761 prog
= g_strdup (token
);
763 /* Executable existing ? */
764 if (!is_executable (prog
)) {
765 DEBUG ("%s: Couldn't find executable %s",
768 SetLastError (ERROR_FILE_NOT_FOUND
);
773 char *curdir
= g_get_current_dir ();
775 /* FIXME: Need to record the directory
776 * containing the current process, and check
777 * that for the new executable as the first
781 prog
= g_strdup_printf ("%s/%s", curdir
, token
);
784 /* I assume X_OK is the criterion to use,
787 if (!is_executable (prog
)) {
789 prog
= g_find_program_in_path (token
);
791 DEBUG ("%s: Couldn't find executable %s", __func__
, token
);
794 SetLastError (ERROR_FILE_NOT_FOUND
);
803 DEBUG ("%s: Exec prog [%s] args [%s]", __func__
, prog
,
806 /* Check for CLR binaries; if found, we will try to invoke
807 * them using the same mono binary that started us.
809 if (is_managed_binary (prog
)) {
810 gunichar2
*newapp
= NULL
, *newcmd
;
814 newapp
= mono_unicode_from_external (cli_launcher
, &bytes_ignored
);
816 newapp
= mono_unicode_from_external ("mono", &bytes_ignored
);
818 if (newapp
!= NULL
) {
819 if (appname
!= NULL
) {
820 newcmd
= utf16_concat (newapp
, utf16_space
,
821 appname
, utf16_space
,
824 newcmd
= utf16_concat (newapp
, utf16_space
,
828 g_free ((gunichar2
*)newapp
);
830 if (newcmd
!= NULL
) {
831 ret
= CreateProcess (NULL
, newcmd
,
835 create_flags
, new_environ
,
839 g_free ((gunichar2
*)newcmd
);
846 if (args_after_prog
!= NULL
&& *args_after_prog
) {
849 qprog
= g_shell_quote (prog
);
850 full_prog
= g_strconcat (qprog
, " ", args_after_prog
, NULL
);
853 full_prog
= g_shell_quote (prog
);
856 ret
= g_shell_parse_argv (full_prog
, NULL
, &argv
, &gerr
);
858 g_message ("CreateProcess: %s\n", gerr
->message
);
864 if (startup
!= NULL
&& startup
->dwFlags
& STARTF_USESTDHANDLES
) {
865 in_fd
= GPOINTER_TO_UINT (startup
->hStdInput
);
866 out_fd
= GPOINTER_TO_UINT (startup
->hStdOutput
);
867 err_fd
= GPOINTER_TO_UINT (startup
->hStdError
);
869 in_fd
= GPOINTER_TO_UINT (GetStdHandle (STD_INPUT_HANDLE
));
870 out_fd
= GPOINTER_TO_UINT (GetStdHandle (STD_OUTPUT_HANDLE
));
871 err_fd
= GPOINTER_TO_UINT (GetStdHandle (STD_ERROR_HANDLE
));
874 g_strlcpy (process_handle
.proc_name
, prog
,
875 _WAPI_PROC_NAME_MAX_LEN
- 1);
877 process_set_defaults (&process_handle
);
879 handle
= _wapi_handle_new (WAPI_HANDLE_PROCESS
, &process_handle
);
880 if (handle
== _WAPI_HANDLE_INVALID
) {
881 g_warning ("%s: error creating process handle", __func__
);
884 SetLastError (ERROR_OUTOFMEMORY
);
888 /* new_environ is a block of NULL-terminated strings, which
889 * is itself NULL-terminated. Of course, passing an array of
890 * string pointers would have made things too easy :-(
892 * If new_environ is not NULL it specifies the entire set of
893 * environment variables in the new process. Otherwise the
894 * new process inherits the same environment.
896 if (new_environ
!= NULL
) {
897 gunichar2
*new_environp
;
899 /* Count the number of strings */
900 for (new_environp
= (gunichar2
*)new_environ
; *new_environp
;
903 while (*new_environp
) {
908 /* +2: one for the process handle value, and the last
911 env_strings
= g_new0 (gchar
*, env_count
+ 2);
913 /* Copy each environ string into 'strings' turning it
914 * into utf8 (or the requested encoding) at the same
918 for (new_environp
= (gunichar2
*)new_environ
; *new_environp
;
920 env_strings
[env_count
] = mono_unicode_to_external (new_environp
);
922 while (*new_environp
) {
927 for (i
= 0; environ
[i
] != NULL
; i
++) {
931 /* +2: one for the process handle value, and the last
934 env_strings
= g_new0 (gchar
*, env_count
+ 2);
936 /* Copy each environ string into 'strings' turning it
937 * into utf8 (or the requested encoding) at the same
941 for (i
= 0; environ
[i
] != NULL
; i
++) {
942 env_strings
[env_count
] = g_strdup (environ
[i
]);
946 /* pass process handle info to the child, so it doesn't have
947 * to do an expensive search over the whole list
949 if (env_strings
!= NULL
) {
950 struct _WapiHandleUnshared
*handle_data
;
951 struct _WapiHandle_shared_ref
*ref
;
953 handle_data
= &_WAPI_PRIVATE_HANDLES(GPOINTER_TO_UINT(handle
));
954 ref
= &handle_data
->u
.shared
;
956 env_strings
[env_count
] = g_strdup_printf ("_WAPI_PROCESS_HANDLE_OFFSET=%d", ref
->offset
);
959 /* Create a pipe to make sure the child doesn't exit before
960 * we can add the process to the linked list of mono_processes */
961 if (pipe (startup_pipe
) == -1) {
962 /* Could not create the pipe to synchroniz process startup. We'll just not synchronize.
963 * This is just for a very hard to hit race condition in the first place */
964 startup_pipe
[0] = startup_pipe
[1] = -1;
965 DEBUG ("%s: new process startup not synchronized. We may not notice if the newly created process exits immediately.", __func__
);
968 thr_ret
= _wapi_handle_lock_shared_handles ();
969 g_assert (thr_ret
== 0);
974 SetLastError (ERROR_OUTOFMEMORY
);
978 } else if (pid
== 0) {
981 if (startup_pipe
[0] != -1) {
982 /* Wait until the parent has updated it's internal data */
983 ssize_t _i G_GNUC_UNUSED
= read (startup_pipe
[0], &dummy
, 1);
984 DEBUG ("%s: child: parent has completed its setup", __func__
);
985 close (startup_pipe
[0]);
986 close (startup_pipe
[1]);
989 /* should we detach from the process group? */
991 /* Connect stdin, stdout and stderr */
996 if (inherit_handles
!= TRUE
) {
997 /* FIXME: do something here */
1000 /* Close all file descriptors */
1001 for (i
= getdtablesize () - 1; i
> 2; i
--) {
1005 #ifdef DEBUG_ENABLED
1006 DEBUG ("%s: exec()ing [%s] in dir [%s]", __func__
, cmd
,
1008 for (i
= 0; argv
[i
] != NULL
; i
++) {
1009 g_message ("arg %d: [%s]", i
, argv
[i
]);
1012 for (i
= 0; env_strings
[i
] != NULL
; i
++) {
1013 g_message ("env %d: [%s]", i
, env_strings
[i
]);
1018 if (dir
!= NULL
&& chdir (dir
) == -1) {
1024 execve (argv
[0], argv
, env_strings
);
1031 ret
= _wapi_lookup_handle (handle
, WAPI_HANDLE_PROCESS
,
1032 (gpointer
*)&process_handle_data
);
1034 g_warning ("%s: error looking up process handle %p", __func__
,
1036 _wapi_handle_unref (handle
);
1040 process_handle_data
->id
= pid
;
1042 /* Add our mono_process into the linked list of mono_processes */
1043 mono_process
= (struct MonoProcess
*) g_malloc0 (sizeof (struct MonoProcess
));
1044 mono_process
->pid
= pid
;
1045 mono_process
->handle_count
= 1;
1046 if (MONO_SEM_INIT (&mono_process
->exit_sem
, 0) != 0) {
1047 /* If we can't create the exit semaphore, we just don't add anything
1048 * to our list of mono processes. Waiting on the process will return
1050 g_warning ("%s: could not create exit semaphore for process.", strerror (errno
));
1051 g_free (mono_process
);
1053 /* Keep the process handle artificially alive until the process
1054 * exits so that the information in the handle isn't lost. */
1055 _wapi_handle_ref (handle
);
1056 mono_process
->handle
= handle
;
1058 process_handle_data
->self
= _wapi_getpid ();
1059 process_handle_data
->mono_process
= mono_process
;
1061 mono_mutex_lock (&mono_processes_mutex
);
1062 mono_process
->next
= mono_processes
;
1063 mono_processes
= mono_process
;
1064 mono_mutex_unlock (&mono_processes_mutex
);
1067 if (process_info
!= NULL
) {
1068 process_info
->hProcess
= handle
;
1069 process_info
->dwProcessId
= pid
;
1071 /* FIXME: we might need to handle the thread info some
1074 process_info
->hThread
= INVALID_HANDLE_VALUE
;
1075 process_info
->dwThreadId
= 0;
1079 _wapi_handle_unlock_shared_handles ();
1082 _wapi_handle_unref (handle
);
1084 if (startup_pipe
[1] != -1) {
1085 /* Write 1 byte, doesn't matter what */
1086 ssize_t _i G_GNUC_UNUSED
= write (startup_pipe
[1], startup_pipe
, 1);
1087 close (startup_pipe
[0]);
1088 close (startup_pipe
[1]);
1095 if (full_prog
!= NULL
) {
1107 if(env_strings
!= NULL
) {
1108 g_strfreev (env_strings
);
1114 DEBUG ("%s: returning handle %p for pid %d", __func__
, handle
,
1117 /* Check if something needs to be cleaned up. */
1118 mono_processes_cleanup ();
1123 static void process_set_name (struct _WapiHandle_process
*process_handle
)
1125 gchar
*progname
, *utf8_progname
, *slash
;
1127 progname
=g_get_prgname ();
1128 utf8_progname
=mono_utf8_from_external (progname
);
1130 DEBUG ("%s: using [%s] as prog name", __func__
, progname
);
1132 if(utf8_progname
!=NULL
) {
1133 slash
=strrchr (utf8_progname
, '/');
1135 g_strlcpy (process_handle
->proc_name
, slash
+1,
1136 _WAPI_PROC_NAME_MAX_LEN
- 1);
1138 g_strlcpy (process_handle
->proc_name
, utf8_progname
,
1139 _WAPI_PROC_NAME_MAX_LEN
- 1);
1142 g_free (utf8_progname
);
1146 extern void _wapi_time_t_to_filetime (time_t timeval
, WapiFileTime
*filetime
);
1148 #if !GLIB_CHECK_VERSION (2,4,0)
1149 #define g_setenv(a,b,c) setenv(a,b,c)
1150 #define g_unsetenv(a) unsetenv(a)
1153 static void process_set_current (void)
1155 pid_t pid
= _wapi_getpid ();
1156 const char *handle_env
;
1157 struct _WapiHandle_process process_handle
= {0};
1159 mono_once (&process_ops_once
, process_ops_init
);
1161 handle_env
= g_getenv ("_WAPI_PROCESS_HANDLE_OFFSET");
1162 g_unsetenv ("_WAPI_PROCESS_HANDLE_OFFSET");
1164 if (handle_env
!= NULL
) {
1165 struct _WapiHandle_process
*process_handlep
;
1166 gchar
*procname
= NULL
;
1169 current_process
= _wapi_handle_new_from_offset (WAPI_HANDLE_PROCESS
, atoi (handle_env
), TRUE
);
1171 DEBUG ("%s: Found my process handle: %p (offset %d 0x%x)",
1172 __func__
, current_process
, atoi (handle_env
),
1175 ok
= _wapi_lookup_handle (current_process
, WAPI_HANDLE_PROCESS
,
1176 (gpointer
*)&process_handlep
);
1178 /* This test will probably break on linuxthreads, but
1179 * that should be ancient history on all distros we
1182 if (process_handlep
->id
== pid
) {
1183 procname
= process_handlep
->proc_name
;
1184 if (!strcmp (procname
, "mono")) {
1185 /* Set a better process name */
1186 DEBUG ("%s: Setting better process name", __func__
);
1188 process_set_name (process_handlep
);
1190 DEBUG ("%s: Leaving process name: %s", __func__
, procname
);
1196 /* Wrong pid, so drop this handle and fall through to
1199 _wapi_handle_unref (current_process
);
1203 /* We get here if the handle wasn't specified in the
1204 * environment, or if the process ID was wrong, or if the
1205 * handle lookup failed (eg if the parent process forked and
1206 * quit immediately, and deleted the shared data before the
1207 * child got a chance to attach it.)
1210 DEBUG ("%s: Need to create my own process handle", __func__
);
1212 process_handle
.id
= pid
;
1214 process_set_defaults (&process_handle
);
1215 process_set_name (&process_handle
);
1217 current_process
= _wapi_handle_new (WAPI_HANDLE_PROCESS
,
1219 if (current_process
== _WAPI_HANDLE_INVALID
) {
1220 g_warning ("%s: error creating process handle", __func__
);
1225 gpointer
_wapi_process_duplicate ()
1227 mono_once (&process_current_once
, process_set_current
);
1229 _wapi_handle_ref (current_process
);
1231 return(current_process
);
1234 /* Returns a pseudo handle that doesn't need to be closed afterwards */
1235 gpointer
GetCurrentProcess (void)
1237 mono_once (&process_current_once
, process_set_current
);
1239 return(_WAPI_PROCESS_CURRENT
);
1242 guint32
GetProcessId (gpointer handle
)
1244 struct _WapiHandle_process
*process_handle
;
1247 if ((GPOINTER_TO_UINT (handle
) & _WAPI_PROCESS_UNHANDLED
) == _WAPI_PROCESS_UNHANDLED
) {
1248 /* This is a pseudo handle */
1249 return(GPOINTER_TO_UINT (handle
) & _WAPI_PROCESS_UNHANDLED_PID_MASK
);
1252 ok
= _wapi_lookup_handle (handle
, WAPI_HANDLE_PROCESS
,
1253 (gpointer
*)&process_handle
);
1255 SetLastError (ERROR_INVALID_HANDLE
);
1259 return (process_handle
->id
);
1262 guint32
GetCurrentProcessId (void)
1264 mono_once (&process_current_once
, process_set_current
);
1266 return (GetProcessId (current_process
));
1269 /* Returns the process id as a convenience to the functions that call this */
1270 static pid_t
signal_process_if_gone (gpointer handle
)
1272 struct _WapiHandle_process
*process_handle
;
1275 g_assert ((GPOINTER_TO_UINT (handle
) & _WAPI_PROCESS_UNHANDLED
) != _WAPI_PROCESS_UNHANDLED
);
1277 /* Make sure the process is signalled if it has exited - if
1278 * the parent process didn't wait for it then it won't be
1280 ok
= _wapi_lookup_handle (handle
, WAPI_HANDLE_PROCESS
,
1281 (gpointer
*)&process_handle
);
1283 /* It's possible that the handle has vanished during
1284 * the _wapi_search_handle before it gets here, so
1285 * don't spam the console with warnings.
1287 /* g_warning ("%s: error looking up process handle %p",
1288 __func__, handle);*/
1293 DEBUG ("%s: looking at process %d", __func__
, process_handle
->id
);
1295 if (kill (process_handle
->id
, 0) == -1 &&
1298 /* The process is dead, (EPERM tells us a new process
1299 * has that ID, but as it's owned by someone else it
1300 * can't be the one listed in our shared memory file)
1302 _wapi_shared_handle_set_signal_state (handle
, TRUE
);
1305 return (process_handle
->id
);
1309 static gboolean
process_enum (gpointer handle
, gpointer user_data
)
1311 GArray
*processes
=user_data
;
1312 pid_t pid
= signal_process_if_gone (handle
);
1319 /* Ignore processes that have already exited (ie they are signalled) */
1320 if (_wapi_handle_issignalled (handle
) == FALSE
) {
1321 DEBUG ("%s: process %d added to array", __func__
, pid
);
1323 /* This ensures that duplicates aren't returned (see
1324 * the comment above _wapi_search_handle () for why
1327 for (i
= 0; i
< processes
->len
; i
++) {
1328 if (g_array_index (processes
, pid_t
, i
) == pid
) {
1329 /* We've already got this one, return
1330 * FALSE to keep searching
1336 g_array_append_val (processes
, pid
);
1339 /* Return false to keep searching */
1342 #endif /* UNUSED_CODE */
1344 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__)
1346 gboolean
EnumProcesses (guint32
*pids
, guint32 len
, guint32
*needed
)
1348 guint32 count
, fit
, i
, j
;
1351 size_t proclength
, size
;
1352 #if defined(__OpenBSD__)
1353 struct kinfo_proc2
*result
;
1356 name
[1] = KERN_PROC2
;
1357 name
[2] = KERN_PROC_ALL
;
1359 name
[4] = sizeof(struct kinfo_proc2
);
1362 struct kinfo_proc
*result
;
1363 static const int name
[] = { CTL_KERN
, KERN_PROC
, KERN_PROC_ALL
, 0 };
1366 mono_once (&process_current_once
, process_set_current
);
1373 #if defined(__OpenBSD__)
1374 size
= (sizeof(name
) / sizeof(*name
));
1376 size
= (sizeof(name
) / sizeof(*name
)) - 1;
1378 err
= sysctl ((int *)name
, size
, NULL
, &proclength
, NULL
, 0);
1381 result
= malloc (proclength
);
1386 #if defined(__OpenBSD__)
1387 name
[5] = (int)(proclength
/ sizeof(struct kinfo_proc2
));
1390 err
= sysctl ((int *) name
, size
, result
, &proclength
, NULL
, 0);
1399 } while (err
== 0 && !done
);
1402 if (result
!= NULL
) {
1409 #if defined(__OpenBSD__)
1410 count
= proclength
/ sizeof(struct kinfo_proc2
);
1412 count
= proclength
/ sizeof(struct kinfo_proc
);
1414 fit
= len
/ sizeof(guint32
);
1415 for (i
= 0, j
= 0; j
< fit
&& i
< count
; i
++) {
1416 #if defined(__OpenBSD__)
1417 pids
[j
++] = result
[i
].p_pid
;
1419 if (result
[i
].kp_proc
.p_pid
> 0) /* Pid 0 not supported */
1420 pids
[j
++] = result
[i
].kp_proc
.p_pid
;
1425 *needed
= j
* sizeof(guint32
);
1429 #elif defined(__HAIKU__)
1431 gboolean
EnumProcesses (guint32
*pids
, guint32 len
, guint32
*needed
)
1437 mono_once (&process_current_once
, process_set_current
);
1439 fit
= len
/ sizeof (guint32
);
1440 while (get_next_team_info (&cookie
, &teamInfo
) == B_OK
&& i
< fit
) {
1441 pids
[i
++] = teamInfo
.team
;
1443 *needed
= i
* sizeof (guint32
);
1448 gboolean
EnumProcesses (guint32
*pids
, guint32 len
, guint32
*needed
)
1452 struct dirent
*entry
;
1454 mono_once (&process_current_once
, process_set_current
);
1456 dir
= opendir ("/proc");
1462 fit
= len
/ sizeof (guint32
);
1463 while(i
< fit
&& (entry
= readdir (dir
)) != NULL
) {
1467 if (!isdigit (entry
->d_name
[0]))
1470 pid
= (pid_t
) strtol (entry
->d_name
, &endptr
, 10);
1471 if (*endptr
== '\0')
1472 pids
[i
++] = (guint32
) pid
;
1475 *needed
= i
* sizeof(guint32
);
1481 static gboolean
process_open_compare (gpointer handle
, gpointer user_data
)
1484 pid_t checking_pid
= signal_process_if_gone (handle
);
1486 if (checking_pid
== 0) {
1490 wanted_pid
= GPOINTER_TO_UINT (user_data
);
1492 /* It's possible to have more than one process handle with the
1493 * same pid, but only the one running process can be
1496 if (checking_pid
== wanted_pid
&&
1497 _wapi_handle_issignalled (handle
) == FALSE
) {
1498 /* If the handle is blown away in the window between
1499 * returning TRUE here and _wapi_search_handle pinging
1500 * the timestamp, the search will continue
1508 gboolean
CloseProcess(gpointer handle
)
1510 if ((GPOINTER_TO_UINT (handle
) & _WAPI_PROCESS_UNHANDLED
) == _WAPI_PROCESS_UNHANDLED
) {
1511 /* This is a pseudo handle */
1515 return CloseHandle (handle
);
1519 * The caller owns the returned handle and must call CloseProcess () on it to clean it up.
1521 gpointer
OpenProcess (guint32 req_access G_GNUC_UNUSED
, gboolean inherit G_GNUC_UNUSED
, guint32 pid
)
1523 /* Find the process handle that corresponds to pid */
1524 gpointer handle
= NULL
;
1526 mono_once (&process_current_once
, process_set_current
);
1528 DEBUG ("%s: looking for process %d", __func__
, pid
);
1530 handle
= _wapi_search_handle (WAPI_HANDLE_PROCESS
,
1531 process_open_compare
,
1532 GUINT_TO_POINTER (pid
), NULL
, TRUE
);
1534 if (is_pid_valid (pid
)) {
1535 /* Return a pseudo handle for processes we
1536 * don't have handles for
1538 return GINT_TO_POINTER (_WAPI_PROCESS_UNHANDLED
+ pid
);
1540 DEBUG ("%s: Can't find pid %d", __func__
, pid
);
1542 SetLastError (ERROR_PROC_NOT_FOUND
);
1548 /* _wapi_search_handle () already added a ref */
1552 gboolean
GetExitCodeProcess (gpointer process
, guint32
*code
)
1554 struct _WapiHandle_process
*process_handle
;
1558 mono_once (&process_current_once
, process_set_current
);
1564 pid
= GPOINTER_TO_UINT (process
) - _WAPI_PROCESS_UNHANDLED
;
1565 if ((GPOINTER_TO_UINT (process
) & _WAPI_PROCESS_UNHANDLED
) == _WAPI_PROCESS_UNHANDLED
) {
1566 /* This is a pseudo handle, so we don't know what the
1567 * exit code was, but we can check whether it's alive or not
1569 if (is_pid_valid (pid
)) {
1570 *code
= STILL_ACTIVE
;
1577 ok
=_wapi_lookup_handle (process
, WAPI_HANDLE_PROCESS
,
1578 (gpointer
*)&process_handle
);
1580 DEBUG ("%s: Can't find process %p", __func__
, process
);
1585 /* A process handle is only signalled if the process has exited
1586 * and has been waited for */
1588 /* Make sure any process exit has been noticed, before
1589 * checking if the process is signalled. Fixes bug 325463.
1591 process_wait (process
, 0, TRUE
);
1593 if (_wapi_handle_issignalled (process
) == TRUE
) {
1594 *code
= process_handle
->exitstatus
;
1596 *code
= STILL_ACTIVE
;
1602 gboolean
GetProcessTimes (gpointer process
, WapiFileTime
*create_time
,
1603 WapiFileTime
*exit_time
, WapiFileTime
*kernel_time
,
1604 WapiFileTime
*user_time
)
1606 struct _WapiHandle_process
*process_handle
;
1608 gboolean ku_times_set
= FALSE
;
1610 mono_once (&process_current_once
, process_set_current
);
1612 if(create_time
==NULL
|| exit_time
==NULL
|| kernel_time
==NULL
||
1614 /* Not sure if w32 allows NULLs here or not */
1618 if ((GPOINTER_TO_UINT (process
) & _WAPI_PROCESS_UNHANDLED
) == _WAPI_PROCESS_UNHANDLED
) {
1619 /* This is a pseudo handle, so just fail for now
1624 ok
=_wapi_lookup_handle (process
, WAPI_HANDLE_PROCESS
,
1625 (gpointer
*)&process_handle
);
1627 DEBUG ("%s: Can't find process %p", __func__
, process
);
1632 *create_time
=process_handle
->create_time
;
1634 /* A process handle is only signalled if the process has
1635 * exited. Otherwise exit_time isn't set
1637 if(_wapi_handle_issignalled (process
)==TRUE
) {
1638 *exit_time
=process_handle
->exit_time
;
1641 #ifdef HAVE_GETRUSAGE
1642 if (process_handle
->id
== getpid ()) {
1643 struct rusage time_data
;
1644 if (getrusage (RUSAGE_SELF
, &time_data
) == 0) {
1646 gint64
*tick_val_ptr
;
1647 ku_times_set
= TRUE
;
1648 tick_val
= time_data
.ru_utime
.tv_sec
* 10000000 + time_data
.ru_utime
.tv_usec
* 10;
1649 tick_val_ptr
= (gint64
*)user_time
;
1650 *tick_val_ptr
= tick_val
;
1651 tick_val
= time_data
.ru_stime
.tv_sec
* 10000000 + time_data
.ru_stime
.tv_usec
* 10;
1652 tick_val_ptr
= (gint64
*)kernel_time
;
1653 *tick_val_ptr
= tick_val
;
1657 if (!ku_times_set
) {
1658 memset (kernel_time
, 0, sizeof (WapiFileTime
));
1659 memset (user_time
, 0, sizeof (WapiFileTime
));
1667 gpointer address_start
;
1668 gpointer address_end
;
1670 gpointer address_offset
;
1676 static void free_procmodule (WapiProcModule
*mod
)
1678 if (mod
->perms
!= NULL
) {
1679 g_free (mod
->perms
);
1681 if (mod
->filename
!= NULL
) {
1682 g_free (mod
->filename
);
1687 static gint
find_procmodule (gconstpointer a
, gconstpointer b
)
1689 WapiProcModule
*want
= (WapiProcModule
*)a
;
1690 WapiProcModule
*compare
= (WapiProcModule
*)b
;
1692 if ((want
->device
== compare
->device
) &&
1693 (want
->inode
== compare
->inode
)) {
1700 #ifdef PLATFORM_MACOSX
1701 #include <mach-o/dyld.h>
1702 #include <mach-o/getsect.h>
1704 static GSList
*load_modules (void)
1707 WapiProcModule
*mod
;
1708 uint32_t count
= _dyld_image_count ();
1711 for (i
= 0; i
< count
; i
++) {
1712 #if SIZEOF_VOID_P == 8
1713 const struct mach_header_64
*hdr
;
1714 const struct section_64
*sec
;
1716 const struct mach_header
*hdr
;
1717 const struct section
*sec
;
1721 name
= _dyld_get_image_name (i
);
1722 #if SIZEOF_VOID_P == 8
1723 hdr
= (const struct mach_header_64
*)_dyld_get_image_header (i
);
1724 sec
= getsectbynamefromheader_64 (hdr
, SEG_DATA
, SECT_DATA
);
1726 hdr
= _dyld_get_image_header (i
);
1727 sec
= getsectbynamefromheader (hdr
, SEG_DATA
, SECT_DATA
);
1730 /* Some dynlibs do not have data sections on osx (#533893) */
1735 mod
= g_new0 (WapiProcModule
, 1);
1736 mod
->address_start
= GINT_TO_POINTER (sec
->addr
);
1737 mod
->address_end
= GINT_TO_POINTER (sec
->addr
+sec
->size
);
1738 mod
->perms
= g_strdup ("r--p");
1739 mod
->address_offset
= 0;
1740 mod
->device
= makedev (0, 0);
1741 mod
->inode
= (ino_t
) i
;
1742 mod
->filename
= g_strdup (name
);
1744 if (g_slist_find_custom (ret
, mod
, find_procmodule
) == NULL
) {
1745 ret
= g_slist_prepend (ret
, mod
);
1747 free_procmodule (mod
);
1751 ret
= g_slist_reverse (ret
);
1755 #elif defined(__OpenBSD__)
1757 static int load_modules_callback (struct dl_phdr_info
*info
, size_t size
, void *ptr
)
1759 if (size
< offsetof (struct dl_phdr_info
, dlpi_phnum
)
1760 + sizeof (info
->dlpi_phnum
))
1763 struct dl_phdr_info
*cpy
= calloc(1, sizeof(struct dl_phdr_info
));
1767 memcpy(cpy
, info
, sizeof(*info
));
1769 g_ptr_array_add ((GPtrArray
*)ptr
, cpy
);
1774 static GSList
*load_modules (void)
1777 WapiProcModule
*mod
;
1778 GPtrArray
*dlarray
= g_ptr_array_new();
1781 if (dl_iterate_phdr(load_modules_callback
, dlarray
) < 0)
1784 for (i
= 0; i
< dlarray
->len
; i
++) {
1785 struct dl_phdr_info
*info
= g_ptr_array_index (dlarray
, i
);
1787 mod
= g_new0 (WapiProcModule
, 1);
1788 mod
->address_start
= (gpointer
)(info
->dlpi_addr
+ info
->dlpi_phdr
[0].p_vaddr
);
1789 mod
->address_end
= (gpointer
)(info
->dlpi_addr
+
1790 info
->dlpi_phdr
[info
->dlpi_phnum
- 1].p_vaddr
);
1791 mod
->perms
= g_strdup ("r--p");
1792 mod
->address_offset
= 0;
1793 mod
->inode
= (ino_t
) i
;
1794 mod
->filename
= g_strdup (info
->dlpi_name
);
1796 DEBUG ("%s: inode=%d, filename=%s, address_start=%p, address_end=%p", __func__
,
1797 mod
->inode
, mod
->filename
, mod
->address_start
, mod
->address_end
);
1801 if (g_slist_find_custom (ret
, mod
, find_procmodule
) == NULL
) {
1802 ret
= g_slist_prepend (ret
, mod
);
1804 free_procmodule (mod
);
1808 g_ptr_array_free (dlarray
, TRUE
);
1810 ret
= g_slist_reverse (ret
);
1814 #elif defined(__HAIKU__)
1816 static GSList
*load_modules (void)
1819 WapiProcModule
*mod
;
1821 image_info imageInfo
;
1823 while (get_next_image_info (B_CURRENT_TEAM
, &cookie
, &imageInfo
) == B_OK
) {
1824 mod
= g_new0 (WapiProcModule
, 1);
1825 mod
->device
= imageInfo
.device
;
1826 mod
->inode
= imageInfo
.node
;
1827 mod
->filename
= g_strdup (imageInfo
.name
);
1828 mod
->address_start
= MIN (imageInfo
.text
, imageInfo
.data
);
1829 mod
->address_end
= MAX ((uint8_t*)imageInfo
.text
+ imageInfo
.text_size
,
1830 (uint8_t*)imageInfo
.data
+ imageInfo
.data_size
);
1831 mod
->perms
= g_strdup ("r--p");
1832 mod
->address_offset
= 0;
1834 if (g_slist_find_custom (ret
, mod
, find_procmodule
) == NULL
) {
1835 ret
= g_slist_prepend (ret
, mod
);
1837 free_procmodule (mod
);
1841 ret
= g_slist_reverse (ret
);
1846 static GSList
*load_modules (FILE *fp
)
1849 WapiProcModule
*mod
;
1850 gchar buf
[MAXPATHLEN
+ 1], *p
, *endp
;
1851 gchar
*start_start
, *end_start
, *prot_start
, *offset_start
;
1852 gchar
*maj_dev_start
, *min_dev_start
, *inode_start
, prot_buf
[5];
1853 gpointer address_start
, address_end
, address_offset
;
1854 guint32 maj_dev
, min_dev
;
1858 while (fgets (buf
, sizeof(buf
), fp
)) {
1860 while (g_ascii_isspace (*p
)) ++p
;
1862 if (!g_ascii_isxdigit (*start_start
)) {
1865 address_start
= (gpointer
)strtoul (start_start
, &endp
, 16);
1873 if (!g_ascii_isxdigit (*end_start
)) {
1876 address_end
= (gpointer
)strtoul (end_start
, &endp
, 16);
1878 if (!g_ascii_isspace (*p
)) {
1882 while (g_ascii_isspace (*p
)) ++p
;
1884 if (*prot_start
!= 'r' && *prot_start
!= '-') {
1887 memcpy (prot_buf
, prot_start
, 4);
1889 while (!g_ascii_isspace (*p
)) ++p
;
1891 while (g_ascii_isspace (*p
)) ++p
;
1893 if (!g_ascii_isxdigit (*offset_start
)) {
1896 address_offset
= (gpointer
)strtoul (offset_start
, &endp
, 16);
1898 if (!g_ascii_isspace (*p
)) {
1902 while(g_ascii_isspace (*p
)) ++p
;
1904 if (!g_ascii_isxdigit (*maj_dev_start
)) {
1907 maj_dev
= strtoul (maj_dev_start
, &endp
, 16);
1915 if (!g_ascii_isxdigit (*min_dev_start
)) {
1918 min_dev
= strtoul (min_dev_start
, &endp
, 16);
1920 if (!g_ascii_isspace (*p
)) {
1924 while (g_ascii_isspace (*p
)) ++p
;
1926 if (!g_ascii_isxdigit (*inode_start
)) {
1929 inode
= (ino_t
)strtol (inode_start
, &endp
, 10);
1931 if (!g_ascii_isspace (*p
)) {
1935 device
= makedev ((int)maj_dev
, (int)min_dev
);
1936 if ((device
== 0) &&
1941 while(g_ascii_isspace (*p
)) ++p
;
1942 /* p now points to the filename */
1944 mod
= g_new0 (WapiProcModule
, 1);
1945 mod
->address_start
= address_start
;
1946 mod
->address_end
= address_end
;
1947 mod
->perms
= g_strdup (prot_buf
);
1948 mod
->address_offset
= address_offset
;
1949 mod
->device
= device
;
1951 mod
->filename
= g_strdup (g_strstrip (p
));
1953 if (g_slist_find_custom (ret
, mod
, find_procmodule
) == NULL
) {
1954 ret
= g_slist_prepend (ret
, mod
);
1956 free_procmodule (mod
);
1960 ret
= g_slist_reverse (ret
);
1966 static gboolean
match_procname_to_modulename (gchar
*procname
, gchar
*modulename
)
1968 char* lastsep
= NULL
;
1969 char* lastsep2
= NULL
;
1972 gboolean result
= FALSE
;
1974 if (procname
== NULL
|| modulename
== NULL
)
1977 pname
= mono_path_resolve_symlinks (procname
);
1978 mname
= mono_path_resolve_symlinks (modulename
);
1980 if (!strcmp (pname
, mname
))
1984 lastsep
= strrchr (mname
, '/');
1986 if (!strcmp (lastsep
+1, pname
))
1989 lastsep2
= strrchr (pname
, '/');
1992 if (!strcmp (lastsep
+1, lastsep2
+1))
1995 if (!strcmp (mname
, lastsep2
+1))
2008 #if !defined(__OpenBSD__)
2010 open_process_map (int pid
, const char *mode
)
2013 const gchar
*proc_path
[] = {
2014 "/proc/%d/maps", /* GNU/Linux */
2015 "/proc/%d/map", /* FreeBSD */
2021 for (i
= 0; fp
== NULL
&& proc_path
[i
]; i
++) {
2022 filename
= g_strdup_printf (proc_path
[i
], pid
);
2023 fp
= fopen (filename
, mode
);
2031 gboolean
EnumProcessModules (gpointer process
, gpointer
*modules
,
2032 guint32 size
, guint32
*needed
)
2034 struct _WapiHandle_process
*process_handle
;
2036 #if !defined(__OpenBSD__) && !defined(PLATFORM_MACOSX)
2039 GSList
*mods
= NULL
;
2040 WapiProcModule
*module
;
2041 guint32 count
, avail
= size
/ sizeof(gpointer
);
2044 gchar
*proc_name
= NULL
;
2046 /* Store modules in an array of pointers (main module as
2047 * modules[0]), using the load address for each module as a
2048 * token. (Use 'NULL' as an alternative for the main module
2049 * so that the simple implementation can just return one item
2050 * for now.) Get the info from /proc/<pid>/maps on linux,
2051 * /proc/<pid>/map on FreeBSD, other systems will have to
2052 * implement /dev/kmem reading or whatever other horrid
2053 * technique is needed.
2055 if (size
< sizeof(gpointer
)) {
2059 if ((GPOINTER_TO_UINT (process
) & _WAPI_PROCESS_UNHANDLED
) == _WAPI_PROCESS_UNHANDLED
) {
2060 /* This is a pseudo handle */
2061 pid
= (pid_t
)(GPOINTER_TO_UINT (process
) & _WAPI_PROCESS_UNHANDLED_PID_MASK
);
2063 ok
= _wapi_lookup_handle (process
, WAPI_HANDLE_PROCESS
,
2064 (gpointer
*)&process_handle
);
2066 DEBUG ("%s: Can't find process %p", __func__
, process
);
2070 pid
= process_handle
->id
;
2071 proc_name
= process_handle
->proc_name
;
2074 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__) || defined(__HAIKU__)
2076 mods
= load_modules ();
2078 if ((fp
= open_process_map (pid
, "r")) == NULL
) {
2079 /* No /proc/<pid>/maps so just return the main module
2083 *needed
= sizeof(gpointer
);
2085 mods
= load_modules (fp
);
2088 count
= g_slist_length (mods
);
2090 /* count + 1 to leave slot 0 for the main module */
2091 *needed
= sizeof(gpointer
) * (count
+ 1);
2093 /* Use the NULL shortcut, as the first line in
2094 * /proc/<pid>/maps isn't the executable, and we need
2095 * that first in the returned list. Check the module name
2096 * to see if it ends with the proc name and substitute
2097 * the first entry with it. FIXME if this turns out to
2101 for (i
= 0; i
< (avail
- 1) && i
< count
; i
++) {
2102 module
= (WapiProcModule
*)g_slist_nth_data (mods
, i
);
2103 if (modules
[0] != NULL
)
2104 modules
[i
] = module
->address_start
;
2105 else if (match_procname_to_modulename (proc_name
, module
->filename
))
2106 modules
[0] = module
->address_start
;
2108 modules
[i
+ 1] = module
->address_start
;
2111 for (i
= 0; i
< count
; i
++) {
2112 free_procmodule (g_slist_nth_data (mods
, i
));
2114 g_slist_free (mods
);
2120 static gchar
*get_process_name_from_proc (pid_t pid
)
2122 #if defined(__OpenBSD__)
2125 struct kinfo_proc2
*pi
;
2126 #elif defined(PLATFORM_MACOSX)
2127 #if !(!defined (__mono_ppc__) && defined (TARGET_OSX))
2129 struct kinfo_proc
*pi
;
2130 int mib
[] = { CTL_KERN
, KERN_PROC
, KERN_PROC_PID
, pid
};
2134 gchar
*filename
= NULL
;
2139 #if defined(PLATFORM_SOLARIS)
2140 filename
= g_strdup_printf ("/proc/%d/psinfo", pid
);
2141 if ((fp
= fopen (filename
, "r")) != NULL
) {
2145 nread
= fread (&info
, sizeof (info
), 1, fp
);
2147 ret
= g_strdup (info
.pr_fname
);
2153 #elif defined(PLATFORM_MACOSX)
2154 #if !defined (__mono_ppc__) && defined (TARGET_OSX)
2155 /* No proc name on OSX < 10.5 nor ppc nor iOS */
2156 memset (buf
, '\0', sizeof(buf
));
2157 proc_name (pid
, buf
, sizeof(buf
));
2158 if (strlen (buf
) > 0)
2159 ret
= g_strdup (buf
);
2161 if (sysctl(mib
, 4, NULL
, &size
, NULL
, 0) < 0)
2164 if ((pi
= malloc(size
)) == NULL
)
2167 if (sysctl (mib
, 4, pi
, &size
, NULL
, 0) < 0) {
2168 if (errno
== ENOMEM
) {
2170 DEBUG ("%s: Didn't allocate enough memory for kproc info", __func__
);
2175 if (strlen (pi
->kp_proc
.p_comm
) > 0)
2176 ret
= g_strdup (pi
->kp_proc
.p_comm
);
2180 #elif defined(__OpenBSD__)
2182 mib
[1] = KERN_PROC2
;
2183 mib
[2] = KERN_PROC_PID
;
2185 mib
[4] = sizeof(struct kinfo_proc2
);
2189 if (sysctl(mib
, 6, NULL
, &size
, NULL
, 0) < 0)
2192 if ((pi
= malloc(size
)) == NULL
)
2195 mib
[5] = (int)(size
/ sizeof(struct kinfo_proc2
));
2197 if ((sysctl (mib
, 6, pi
, &size
, NULL
, 0) < 0) ||
2198 (size
!= sizeof (struct kinfo_proc2
))) {
2199 if (errno
== ENOMEM
) {
2206 if (strlen (pi
->p_comm
) > 0)
2207 ret
= g_strdup (pi
->p_comm
);
2210 #elif defined(__HAIKU__)
2211 image_info imageInfo
;
2214 if (get_next_image_info ((team_id
)pid
, &cookie
, &imageInfo
) == B_OK
) {
2215 ret
= g_strdup (imageInfo
.name
);
2218 memset (buf
, '\0', sizeof(buf
));
2219 filename
= g_strdup_printf ("/proc/%d/exe", pid
);
2220 if (readlink (filename
, buf
, 255) > 0) {
2221 ret
= g_strdup (buf
);
2229 filename
= g_strdup_printf ("/proc/%d/cmdline", pid
);
2230 if ((fp
= fopen (filename
, "r")) != NULL
) {
2231 if (fgets (buf
, 256, fp
) != NULL
) {
2232 ret
= g_strdup (buf
);
2243 filename
= g_strdup_printf ("/proc/%d/stat", pid
);
2244 if ((fp
= fopen (filename
, "r")) != NULL
) {
2245 if (fgets (buf
, 256, fp
) != NULL
) {
2248 start
= strchr (buf
, '(');
2249 if (start
!= NULL
) {
2250 end
= strchr (start
+ 1, ')');
2253 ret
= g_strndup (start
+ 1,
2268 * wapi_process_get_path:
2270 * Return the full path of the executable of the process PID, or NULL if it cannot be determined.
2271 * Returns malloc-ed memory.
2274 wapi_process_get_path (pid_t pid
)
2276 #if defined(PLATFORM_MACOSX) && !defined(__mono_ppc__) && defined(TARGET_OSX)
2277 gchar buf
[PROC_PIDPATHINFO_MAXSIZE
];
2280 res
= proc_pidpath (pid
, buf
, sizeof (buf
));
2283 if (buf
[0] == '\0')
2285 return g_strdup (buf
);
2287 return get_process_name_from_proc (pid
);
2292 * wapi_process_set_cli_launcher:
2294 * Set the full path of the runtime executable used to launch managed exe's.
2297 wapi_process_set_cli_launcher (char *path
)
2299 g_free (cli_launcher
);
2300 cli_launcher
= path
? g_strdup (path
) : NULL
;
2303 static guint32
get_module_name (gpointer process
, gpointer module
,
2304 gunichar2
*basename
, guint32 size
,
2307 struct _WapiHandle_process
*process_handle
;
2310 gunichar2
*procname
;
2311 gchar
*procname_ext
= NULL
;
2314 #if !defined(__OpenBSD__) && !defined(PLATFORM_MACOSX)
2317 GSList
*mods
= NULL
;
2318 WapiProcModule
*found_module
;
2321 gchar
*proc_name
= NULL
;
2323 mono_once (&process_current_once
, process_set_current
);
2325 DEBUG ("%s: Getting module base name, process handle %p module %p",
2326 __func__
, process
, module
);
2328 size
= size
*sizeof(gunichar2
); /* adjust for unicode characters */
2330 if (basename
== NULL
|| size
== 0) {
2334 if ((GPOINTER_TO_UINT (process
) & _WAPI_PROCESS_UNHANDLED
) == _WAPI_PROCESS_UNHANDLED
) {
2335 /* This is a pseudo handle */
2336 pid
= (pid_t
)(GPOINTER_TO_UINT (process
) & _WAPI_PROCESS_UNHANDLED_PID_MASK
);
2337 proc_name
= get_process_name_from_proc (pid
);
2339 ok
= _wapi_lookup_handle (process
, WAPI_HANDLE_PROCESS
,
2340 (gpointer
*)&process_handle
);
2342 DEBUG ("%s: Can't find process %p", __func__
,
2347 pid
= process_handle
->id
;
2348 proc_name
= g_strdup (process_handle
->proc_name
);
2351 /* Look up the address in /proc/<pid>/maps */
2352 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__) || defined(__HAIKU__)
2354 mods
= load_modules ();
2356 if ((fp
= open_process_map (pid
, "r")) == NULL
) {
2357 if (errno
== EACCES
&& module
== NULL
&& base
== TRUE
) {
2358 procname_ext
= get_process_name_from_proc (pid
);
2360 /* No /proc/<pid>/maps, so just return failure
2367 mods
= load_modules (fp
);
2370 count
= g_slist_length (mods
);
2372 /* If module != NULL compare the address.
2373 * If module == NULL we are looking for the main module.
2374 * The best we can do for now check it the module name end with the process name.
2376 for (i
= 0; i
< count
; i
++) {
2377 found_module
= (WapiProcModule
*)g_slist_nth_data (mods
, i
);
2378 if (procname_ext
== NULL
&&
2379 ((module
== NULL
&& match_procname_to_modulename (proc_name
, found_module
->filename
)) ||
2380 (module
!= NULL
&& found_module
->address_start
== module
))) {
2382 procname_ext
= g_path_get_basename (found_module
->filename
);
2384 procname_ext
= g_strdup (found_module
->filename
);
2388 free_procmodule (found_module
);
2391 if (procname_ext
== NULL
)
2393 /* If it's *still* null, we might have hit the
2394 * case where reading /proc/$pid/maps gives an
2395 * empty file for this user.
2397 procname_ext
= get_process_name_from_proc (pid
);
2400 g_slist_free (mods
);
2404 if (procname_ext
!= NULL
) {
2405 DEBUG ("%s: Process name is [%s]", __func__
,
2408 procname
= mono_unicode_from_external (procname_ext
, &bytes
);
2409 if (procname
== NULL
) {
2411 g_free (procname_ext
);
2417 /* Add the terminator */
2421 DEBUG ("%s: Size %d smaller than needed (%ld); truncating", __func__
, size
, bytes
);
2423 memcpy (basename
, procname
, size
);
2425 DEBUG ("%s: Size %d larger than needed (%ld)",
2426 __func__
, size
, bytes
);
2428 memcpy (basename
, procname
, bytes
);
2432 g_free (procname_ext
);
2440 guint32
GetModuleBaseName (gpointer process
, gpointer module
,
2441 gunichar2
*basename
, guint32 size
)
2443 return(get_module_name (process
, module
, basename
, size
, TRUE
));
2446 guint32
GetModuleFileNameEx (gpointer process
, gpointer module
,
2447 gunichar2
*filename
, guint32 size
)
2449 return(get_module_name (process
, module
, filename
, size
, FALSE
));
2452 gboolean
GetModuleInformation (gpointer process
, gpointer module
,
2453 WapiModuleInfo
*modinfo
, guint32 size
)
2455 struct _WapiHandle_process
*process_handle
;
2458 #if !defined(__OpenBSD__) && !defined(PLATFORM_MACOSX)
2461 GSList
*mods
= NULL
;
2462 WapiProcModule
*found_module
;
2465 gboolean ret
= FALSE
;
2466 gchar
*proc_name
= NULL
;
2468 mono_once (&process_current_once
, process_set_current
);
2470 DEBUG ("%s: Getting module info, process handle %p module %p",
2471 __func__
, process
, module
);
2473 if (modinfo
== NULL
|| size
< sizeof(WapiModuleInfo
)) {
2477 if ((GPOINTER_TO_UINT (process
) & _WAPI_PROCESS_UNHANDLED
) == _WAPI_PROCESS_UNHANDLED
) {
2478 /* This is a pseudo handle */
2479 pid
= (pid_t
)(GPOINTER_TO_UINT (process
) & _WAPI_PROCESS_UNHANDLED_PID_MASK
);
2480 proc_name
= get_process_name_from_proc (pid
);
2482 ok
= _wapi_lookup_handle (process
, WAPI_HANDLE_PROCESS
,
2483 (gpointer
*)&process_handle
);
2485 DEBUG ("%s: Can't find process %p", __func__
,
2490 pid
= process_handle
->id
;
2491 proc_name
= g_strdup (process_handle
->proc_name
);
2494 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__) || defined(__HAIKU__)
2496 mods
= load_modules ();
2498 /* Look up the address in /proc/<pid>/maps */
2499 if ((fp
= open_process_map (pid
, "r")) == NULL
) {
2500 /* No /proc/<pid>/maps, so just return failure
2506 mods
= load_modules (fp
);
2509 count
= g_slist_length (mods
);
2511 /* If module != NULL compare the address.
2512 * If module == NULL we are looking for the main module.
2513 * The best we can do for now check it the module name end with the process name.
2515 for (i
= 0; i
< count
; i
++) {
2516 found_module
= (WapiProcModule
*)g_slist_nth_data (mods
, i
);
2517 if ( ret
== FALSE
&&
2518 ((module
== NULL
&& match_procname_to_modulename (proc_name
, found_module
->filename
)) ||
2519 (module
!= NULL
&& found_module
->address_start
== module
))) {
2520 modinfo
->lpBaseOfDll
= found_module
->address_start
;
2521 modinfo
->SizeOfImage
= (gsize
)(found_module
->address_end
) - (gsize
)(found_module
->address_start
);
2522 modinfo
->EntryPoint
= found_module
->address_offset
;
2526 free_procmodule (found_module
);
2529 g_slist_free (mods
);
2536 gboolean
GetProcessWorkingSetSize (gpointer process
, size_t *min
, size_t *max
)
2538 struct _WapiHandle_process
*process_handle
;
2541 mono_once (&process_current_once
, process_set_current
);
2543 if(min
==NULL
|| max
==NULL
) {
2544 /* Not sure if w32 allows NULLs here or not */
2548 if ((GPOINTER_TO_UINT (process
) & _WAPI_PROCESS_UNHANDLED
) == _WAPI_PROCESS_UNHANDLED
) {
2549 /* This is a pseudo handle, so just fail for now
2554 ok
=_wapi_lookup_handle (process
, WAPI_HANDLE_PROCESS
,
2555 (gpointer
*)&process_handle
);
2557 DEBUG ("%s: Can't find process %p", __func__
, process
);
2562 *min
=process_handle
->min_working_set
;
2563 *max
=process_handle
->max_working_set
;
2568 gboolean
SetProcessWorkingSetSize (gpointer process
, size_t min
, size_t max
)
2570 struct _WapiHandle_process
*process_handle
;
2573 mono_once (&process_current_once
, process_set_current
);
2575 if ((GPOINTER_TO_UINT (process
) & _WAPI_PROCESS_UNHANDLED
) == _WAPI_PROCESS_UNHANDLED
) {
2576 /* This is a pseudo handle, so just fail for now
2581 ok
=_wapi_lookup_handle (process
, WAPI_HANDLE_PROCESS
,
2582 (gpointer
*)&process_handle
);
2584 DEBUG ("%s: Can't find process %p", __func__
, process
);
2589 process_handle
->min_working_set
=min
;
2590 process_handle
->max_working_set
=max
;
2597 TerminateProcess (gpointer process
, gint32 exitCode
)
2599 struct _WapiHandle_process
*process_handle
;
2605 if ((GPOINTER_TO_UINT (process
) & _WAPI_PROCESS_UNHANDLED
) == _WAPI_PROCESS_UNHANDLED
) {
2606 /* This is a pseudo handle */
2607 pid
= (pid_t
)(GPOINTER_TO_UINT (process
) & _WAPI_PROCESS_UNHANDLED_PID_MASK
);
2609 ok
= _wapi_lookup_handle (process
, WAPI_HANDLE_PROCESS
,
2610 (gpointer
*) &process_handle
);
2613 DEBUG ("%s: Can't find process %p", __func__
,
2615 SetLastError (ERROR_INVALID_HANDLE
);
2618 pid
= process_handle
->id
;
2621 signo
= (exitCode
== -1) ? SIGKILL
: SIGTERM
;
2622 ret
= kill (pid
, signo
);
2626 SetLastError (ERROR_INVALID_PARAMETER
);
2629 SetLastError (ERROR_ACCESS_DENIED
);
2632 SetLastError (ERROR_PROC_NOT_FOUND
);
2635 SetLastError (ERROR_GEN_FAILURE
);
2643 GetPriorityClass (gpointer process
)
2645 #ifdef HAVE_GETPRIORITY
2646 struct _WapiHandle_process
*process_handle
;
2651 if ((GPOINTER_TO_UINT (process
) & _WAPI_PROCESS_UNHANDLED
) == _WAPI_PROCESS_UNHANDLED
) {
2652 /* This is a pseudo handle */
2653 pid
= (pid_t
)(GPOINTER_TO_UINT (process
) & _WAPI_PROCESS_UNHANDLED_PID_MASK
);
2655 ok
= _wapi_lookup_handle (process
, WAPI_HANDLE_PROCESS
,
2656 (gpointer
*) &process_handle
);
2659 SetLastError (ERROR_INVALID_HANDLE
);
2662 pid
= process_handle
->id
;
2666 ret
= getpriority (PRIO_PROCESS
, pid
);
2667 if (ret
== -1 && errno
!= 0) {
2671 SetLastError (ERROR_ACCESS_DENIED
);
2674 SetLastError (ERROR_PROC_NOT_FOUND
);
2677 SetLastError (ERROR_GEN_FAILURE
);
2683 return NORMAL_PRIORITY_CLASS
;
2685 return REALTIME_PRIORITY_CLASS
;
2687 return HIGH_PRIORITY_CLASS
;
2689 return ABOVE_NORMAL_PRIORITY_CLASS
;
2691 return IDLE_PRIORITY_CLASS
;
2693 return BELOW_NORMAL_PRIORITY_CLASS
;
2695 return NORMAL_PRIORITY_CLASS
;
2697 SetLastError (ERROR_NOT_SUPPORTED
);
2703 SetPriorityClass (gpointer process
, guint32 priority_class
)
2705 #ifdef HAVE_SETPRIORITY
2706 struct _WapiHandle_process
*process_handle
;
2712 if ((GPOINTER_TO_UINT (process
) & _WAPI_PROCESS_UNHANDLED
) == _WAPI_PROCESS_UNHANDLED
) {
2713 /* This is a pseudo handle */
2714 pid
= (pid_t
)(GPOINTER_TO_UINT (process
) & _WAPI_PROCESS_UNHANDLED_PID_MASK
);
2716 ok
= _wapi_lookup_handle (process
, WAPI_HANDLE_PROCESS
,
2717 (gpointer
*) &process_handle
);
2720 SetLastError (ERROR_INVALID_HANDLE
);
2723 pid
= process_handle
->id
;
2726 switch (priority_class
) {
2727 case IDLE_PRIORITY_CLASS
:
2730 case BELOW_NORMAL_PRIORITY_CLASS
:
2733 case NORMAL_PRIORITY_CLASS
:
2736 case ABOVE_NORMAL_PRIORITY_CLASS
:
2739 case HIGH_PRIORITY_CLASS
:
2742 case REALTIME_PRIORITY_CLASS
:
2746 SetLastError (ERROR_INVALID_PARAMETER
);
2750 ret
= setpriority (PRIO_PROCESS
, pid
, prio
);
2755 SetLastError (ERROR_ACCESS_DENIED
);
2758 SetLastError (ERROR_PROC_NOT_FOUND
);
2761 SetLastError (ERROR_GEN_FAILURE
);
2767 SetLastError (ERROR_NOT_SUPPORTED
);
2773 mono_processes_cleanup (void)
2775 struct MonoProcess
*mp
;
2776 struct MonoProcess
*prev
= NULL
;
2777 struct MonoProcess
*candidate
= NULL
;
2778 gpointer unref_handle
;
2781 DEBUG ("%s", __func__
);
2783 /* Ensure we're not in here in multiple threads at once, nor recursive. */
2784 if (InterlockedCompareExchange (&mono_processes_cleaning_up
, 1, 0) != 0)
2787 mp
= mono_processes
;
2788 while (mp
!= NULL
) {
2789 if (mp
->pid
== 0 && mp
->handle
!= NULL
) {
2790 /* This process has exited and we need to remove the artifical ref
2792 mono_mutex_lock (&mono_processes_mutex
);
2793 unref_handle
= mp
->handle
;
2795 mono_mutex_unlock (&mono_processes_mutex
);
2797 _wapi_handle_unref (unref_handle
);
2803 mp
= mono_processes
;
2805 while (mp
!= NULL
) {
2806 if ((mp
->handle_count
== 0 && mp
->pid
== 0) || candidate
!= NULL
) {
2808 _wapi_handle_spin (spin
);
2812 /* We've found a candidate */
2813 mono_mutex_lock (&mono_processes_mutex
);
2814 if (candidate
== NULL
) {
2816 if (mp
== mono_processes
) {
2817 mono_processes
= mp
->next
;
2819 prev
->next
= mp
->next
;
2824 /* It's still safe to traverse the structure.*/
2825 mono_memory_barrier ();
2827 if (mono_processes_read_lock
!= 0) {
2828 /* The sigchld handler is watching us. Spin a bit and try again */
2831 } else if (spin
>= 8) {
2832 /* Just give up for now */
2833 mono_mutex_unlock (&mono_processes_mutex
);
2837 /* We've modified the list of processes, and we know the sigchld handler
2838 * isn't executing, so even if it executes at any moment, it'll see the
2839 * new version of the list. So now we can free the candidate. */
2840 DEBUG ("%s: freeing candidate %p", __func__
, candidate
);
2841 mp
= candidate
->next
;
2842 MONO_SEM_DESTROY (&candidate
->exit_sem
);
2847 mono_mutex_unlock (&mono_processes_mutex
);
2856 DEBUG ("%s done", __func__
);
2858 InterlockedDecrement (&mono_processes_cleaning_up
);
2862 process_close (gpointer handle
, gpointer data
)
2864 struct _WapiHandle_process
*process_handle
;
2866 DEBUG ("%s", __func__
);
2868 process_handle
= (struct _WapiHandle_process
*) data
;
2869 if (process_handle
->mono_process
&& process_handle
->self
== _wapi_getpid ())
2870 InterlockedDecrement (&process_handle
->mono_process
->handle_count
);
2871 mono_processes_cleanup ();
2875 MONO_SIGNAL_HANDLER_FUNC (static, mono_sigchld_signal_handler
, (int _dummy
, siginfo_t
*info
, void *context
))
2879 struct MonoProcess
*p
;
2882 fprintf (stdout
, "SIG CHILD handler for pid: %i\n", info
->si_pid
);
2885 InterlockedIncrement (&mono_processes_read_lock
);
2889 pid
= waitpid (-1, &status
, WNOHANG
);
2890 } while (pid
== -1 && errno
== EINTR
);
2896 fprintf (stdout
, "child ended: %i", pid
);
2900 if (p
->pid
== pid
) {
2901 p
->pid
= 0; /* this pid doesn't exist anymore, clear it */
2903 MONO_SEM_POST (&p
->exit_sem
);
2910 InterlockedDecrement (&mono_processes_read_lock
);
2913 fprintf (stdout
, "SIG CHILD handler: done looping.");
2919 static void process_add_sigchld_handler (void)
2922 struct sigaction sa
;
2924 sa
.sa_sigaction
= mono_sigchld_signal_handler
;
2925 sigemptyset (&sa
.sa_mask
);
2926 sa
.sa_flags
= SA_NOCLDSTOP
| SA_SIGINFO
;
2927 g_assert (sigaction (SIGCHLD
, &sa
, &previous_chld_sa
) != -1);
2928 DEBUG ("Added SIGCHLD handler");
2932 static guint32
process_wait (gpointer handle
, guint32 timeout
, gboolean alertable
)
2934 struct _WapiHandle_process
*process_handle
;
2940 struct MonoProcess
*mp
;
2942 gpointer current_thread
;
2944 current_thread
= wapi_get_current_thread_handle ();
2945 if (current_thread
== NULL
) {
2946 SetLastError (ERROR_INVALID_HANDLE
);
2950 /* FIXME: We can now easily wait on processes that aren't our own children,
2951 * but WaitFor*Object won't call us for pseudo handles. */
2952 g_assert ((GPOINTER_TO_UINT (handle
) & _WAPI_PROCESS_UNHANDLED
) != _WAPI_PROCESS_UNHANDLED
);
2954 DEBUG ("%s (%p, %u)", __func__
, handle
, timeout
);
2956 ok
= _wapi_lookup_handle (handle
, WAPI_HANDLE_PROCESS
, (gpointer
*)&process_handle
);
2958 g_warning ("%s: error looking up process handle %p", __func__
, handle
);
2962 if (process_handle
->exited
) {
2963 /* We've already done this one */
2964 DEBUG ("%s (%p, %u): Process already exited", __func__
, handle
, timeout
);
2965 return WAIT_OBJECT_0
;
2968 pid
= process_handle
->id
;
2970 DEBUG ("%s (%p, %u): PID: %d", __func__
, handle
, timeout
, pid
);
2972 /* We don't need to lock mono_processes here, the entry
2973 * has a handle_count > 0 which means it will not be freed. */
2974 mp
= process_handle
->mono_process
;
2975 if (mp
&& process_handle
->self
!= _wapi_getpid ()) {
2976 /* mono_process points to memory in another process' address space: we can't use it */
2980 start
= mono_msec_ticks ();
2986 /* We have a semaphore we can wait on */
2987 if (timeout
!= INFINITE
) {
2988 DEBUG ("%s (%p, %u): waiting on semaphore for %li ms...",
2989 __func__
, handle
, timeout
, (timeout
- (now
- start
)));
2991 ret
= MONO_SEM_TIMEDWAIT_ALERTABLE (&mp
->exit_sem
, (timeout
- (now
- start
)), alertable
);
2993 DEBUG ("%s (%p, %u): waiting on semaphore forever...",
2994 __func__
, handle
, timeout
);
2995 ret
= MONO_SEM_WAIT_ALERTABLE (&mp
->exit_sem
, alertable
);
2998 if (ret
== -1 && errno
!= EINTR
&& errno
!= ETIMEDOUT
) {
2999 DEBUG ("%s (%p, %u): sem_timedwait failure: %s",
3000 __func__
, handle
, timeout
, g_strerror (errno
));
3001 /* Should we return a failure here? */
3005 /* Success, process has exited */
3006 MONO_SEM_POST (&mp
->exit_sem
);
3010 /* We did not create this process, so we can't waidpid / sem_wait it.
3011 * We need to poll for the pid existence */
3012 DEBUG ("%s (%p, %u): polling on pid...", __func__
, handle
, timeout
);
3013 if (!is_pid_valid (pid
)) {
3014 /* Success, process has exited */
3020 DEBUG ("%s (%p, %u): WAIT_TIMEOUT (timeout = 0)", __func__
, handle
, timeout
);
3021 return WAIT_TIMEOUT
;
3024 now
= mono_msec_ticks ();
3025 if (now
- start
>= timeout
) {
3026 DEBUG ("%s (%p, %u): WAIT_TIMEOUT", __func__
, handle
, timeout
);
3027 return WAIT_TIMEOUT
;
3031 /* "timeout - (now - start)" will not underflow, since timeout is always >=0,
3032 * and we passed the check just above */
3033 _wapi_handle_spin (MIN (100, timeout
- (now
- start
)));
3036 if (alertable
&& _wapi_thread_apc_pending (current_thread
)) {
3037 DEBUG ("%s (%p, %u): WAIT_IO_COMPLETION", __func__
, handle
, timeout
);
3038 return WAIT_IO_COMPLETION
;
3042 /* Process must have exited */
3043 DEBUG ("%s (%p, %u): Waited successfully", __func__
, handle
, timeout
);
3045 ret
= _wapi_handle_lock_shared_handles ();
3046 g_assert (ret
== 0);
3048 status
= mp
? mp
->status
: 0;
3049 if (WIFSIGNALED (status
)) {
3050 process_handle
->exitstatus
= 128 + WTERMSIG (status
);
3052 process_handle
->exitstatus
= WEXITSTATUS (status
);
3054 _wapi_time_t_to_filetime (time (NULL
), &process_handle
->exit_time
);
3056 process_handle
->exited
= TRUE
;
3058 DEBUG ("%s (%p, %u): Setting pid %d signalled, exit status %d",
3059 __func__
, handle
, timeout
, process_handle
->id
, process_handle
->exitstatus
);
3061 _wapi_shared_handle_set_signal_state (handle
, TRUE
);
3063 _wapi_handle_unlock_shared_handles ();
3065 return WAIT_OBJECT_0
;
3069 wapi_processes_cleanup (void)
3071 g_free (cli_launcher
);