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>
27 #ifdef HAVE_SYS_PARAM_H
28 #include <sys/param.h>
32 #ifdef HAVE_SYS_WAIT_H
35 #ifdef HAVE_SYS_RESOURCE_H
36 #include <sys/resource.h>
39 #ifdef HAVE_SYS_MKDEV_H
40 #include <sys/mkdev.h>
47 /* sys/resource.h (for rusage) is required when using osx 10.3 (but not 10.4) */
49 #include <TargetConditionals.h>
50 #include <sys/resource.h>
57 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__)
59 #include <sys/sysctl.h>
60 # if !defined(__OpenBSD__)
61 # include <sys/utsname.h>
65 #ifdef PLATFORM_SOLARIS
66 /* procfs.h cannot be included if this define is set, but it seems to work fine if it is undefined */
67 #if _FILE_OFFSET_BITS == 64
68 #undef _FILE_OFFSET_BITS
70 #define _FILE_OFFSET_BITS 64
77 #include <KernelKit.h>
80 #include <mono/io-layer/wapi.h>
81 #include <mono/io-layer/wapi-private.h>
82 #include <mono/io-layer/handles-private.h>
83 #include <mono/io-layer/misc-private.h>
84 #include <mono/io-layer/process-private.h>
85 #include <mono/io-layer/threads.h>
86 #include <mono/utils/strenc.h>
87 #include <mono/utils/mono-path.h>
88 #include <mono/io-layer/timefuncs-private.h>
89 #include <mono/utils/mono-time.h>
90 #include <mono/utils/mono-membar.h>
91 #include <mono/utils/mono-mutex.h>
92 #include <mono/utils/mono-signal-handler.h>
94 /* The process' environment strings */
95 #if defined(__APPLE__) && !defined (__arm__) && !defined (__aarch64__)
96 /* Apple defines this in crt_externs.h but doesn't provide that header for
97 * arm-apple-darwin9. We'll manually define the symbol on Apple as it does
98 * in fact exist on all implementations (so far)
100 char ***_NSGetEnviron(void);
101 #define environ (*_NSGetEnviron())
103 extern char **environ
;
107 #define DEBUG(...) g_message(__VA_ARGS__)
108 #define DEBUG_ENABLED 1
113 static guint32
process_wait (gpointer handle
, guint32 timeout
, gboolean alertable
);
114 static void process_close (gpointer handle
, gpointer data
);
115 static gboolean
is_pid_valid (pid_t pid
);
117 #if !defined(__OpenBSD__)
119 open_process_map (int pid
, const char *mode
);
122 struct _WapiHandleOps _wapi_process_ops
= {
123 process_close
, /* close_shared */
127 process_wait
, /* special_wait */
132 static struct sigaction previous_chld_sa
;
134 static mono_once_t process_sig_chld_once
= MONO_ONCE_INIT
;
135 static void process_add_sigchld_handler (void);
137 /* The signal-safe logic to use mono_processes goes like this:
138 * - The list must be safe to traverse for the signal handler at all times.
139 * It's safe to: prepend an entry (which is a single store to 'mono_processes'),
140 * unlink an entry (assuming the unlinked entry isn't freed and doesn't
141 * change its 'next' pointer so that it can still be traversed).
142 * When cleaning up we first unlink an entry, then we verify that
143 * the read lock isn't locked. Then we can free the entry, since
144 * we know that nobody is using the old version of the list (including
145 * the unlinked entry).
146 * We also need to lock when adding and cleaning up so that those two
147 * operations don't mess with eachother. (This lock is not used in the
150 static struct MonoProcess
*mono_processes
= NULL
;
151 static volatile gint32 mono_processes_cleaning_up
= 0;
152 static mono_mutex_t mono_processes_mutex
;
153 static void mono_processes_cleanup (void);
155 static gpointer current_process
;
156 static char *cli_launcher
;
158 static WapiHandle_process
*
159 lookup_process_handle (gpointer handle
)
161 WapiHandle_process
*process_data
;
164 ret
= _wapi_lookup_handle (handle
, WAPI_HANDLE_PROCESS
,
165 (gpointer
*)&process_data
);
171 /* Check if a pid is valid - i.e. if a process exists with this pid. */
173 is_pid_valid (pid_t pid
)
175 gboolean result
= FALSE
;
177 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__)
178 if (((kill(pid
, 0) == 0) || (errno
== EPERM
)) && pid
!= 0)
180 #elif defined(__HAIKU__)
182 if (get_team_info ((team_id
)pid
, &teamInfo
) == B_OK
)
185 char *dir
= g_strdup_printf ("/proc/%d", pid
);
186 if (!access (dir
, F_OK
))
195 process_set_defaults (WapiHandle_process
*process_handle
)
197 /* These seem to be the defaults on w2k */
198 process_handle
->min_working_set
= 204800;
199 process_handle
->max_working_set
= 1413120;
201 _wapi_time_t_to_filetime (time (NULL
), &process_handle
->create_time
);
205 len16 (const gunichar2
*str
)
216 utf16_concat (const gunichar2
*first
, ...)
223 va_start (args
, first
);
224 total
+= len16 (first
);
225 for (s
= va_arg (args
, gunichar2
*); s
!= NULL
; s
= va_arg(args
, gunichar2
*)){
230 ret
= g_new (gunichar2
, total
+ 1);
236 for (s
= first
; *s
!= 0; s
++)
238 va_start (args
, first
);
239 for (s
= va_arg (args
, gunichar2
*); s
!= NULL
; s
= va_arg (args
, gunichar2
*)){
242 for (p
= s
; *p
!= 0; p
++)
250 static const gunichar2 utf16_space_bytes
[2] = { 0x20, 0 };
251 static const gunichar2
*utf16_space
= utf16_space_bytes
;
252 static const gunichar2 utf16_quote_bytes
[2] = { 0x22, 0 };
253 static const gunichar2
*utf16_quote
= utf16_quote_bytes
;
258 print_utf16 (gunichar2
*str
)
262 res
= g_utf16_to_utf8 (str
, -1, NULL
, NULL
, NULL
);
263 g_print ("%s\n", res
);
268 /* Implemented as just a wrapper around CreateProcess () */
270 ShellExecuteEx (WapiShellExecuteInfo
*sei
)
273 WapiProcessInformation process_info
;
277 /* w2k just segfaults here, but we can do better than
280 SetLastError (ERROR_INVALID_PARAMETER
);
284 if (sei
->lpFile
== NULL
)
285 /* w2k returns TRUE for this, for some reason. */
288 /* Put both executable and parameters into the second argument
289 * to CreateProcess (), so it searches $PATH. The conversion
290 * into and back out of utf8 is because there is no
291 * g_strdup_printf () equivalent for gunichar2 :-(
293 args
= utf16_concat (utf16_quote
, sei
->lpFile
, utf16_quote
, sei
->lpParameters
== NULL
? NULL
: utf16_space
, sei
->lpParameters
, NULL
);
295 SetLastError (ERROR_INVALID_DATA
);
298 ret
= CreateProcess (NULL
, args
, NULL
, NULL
, TRUE
,
299 CREATE_UNICODE_ENVIRONMENT
, NULL
,
300 sei
->lpDirectory
, NULL
, &process_info
);
303 if (!ret
&& GetLastError () == ERROR_OUTOFMEMORY
)
307 static char *handler
;
308 static gunichar2
*handler_utf16
;
310 if (handler_utf16
== (gunichar2
*)-1)
313 #ifdef PLATFORM_MACOSX
314 handler
= g_strdup ("/usr/bin/open");
317 * On Linux, try: xdg-open, the FreeDesktop standard way of doing it,
318 * if that fails, try to use gnome-open, then kfmclient
320 handler
= g_find_program_in_path ("xdg-open");
321 if (handler
== NULL
){
322 handler
= g_find_program_in_path ("gnome-open");
323 if (handler
== NULL
){
324 handler
= g_find_program_in_path ("kfmclient");
325 if (handler
== NULL
){
326 handler_utf16
= (gunichar2
*) -1;
329 /* kfmclient needs exec argument */
331 handler
= g_strconcat (old
, " exec",
338 handler_utf16
= g_utf8_to_utf16 (handler
, -1, NULL
, NULL
, NULL
);
341 /* Put quotes around the filename, in case it's a url
342 * that contains #'s (CreateProcess() calls
343 * g_shell_parse_argv(), which deliberately throws
344 * away anything after an unquoted #). Fixes bug
347 args
= utf16_concat (handler_utf16
, utf16_space
, utf16_quote
,
348 sei
->lpFile
, utf16_quote
,
349 sei
->lpParameters
== NULL
? NULL
: utf16_space
,
350 sei
->lpParameters
, NULL
);
352 SetLastError (ERROR_INVALID_DATA
);
355 ret
= CreateProcess (NULL
, args
, NULL
, NULL
, TRUE
,
356 CREATE_UNICODE_ENVIRONMENT
, NULL
,
357 sei
->lpDirectory
, NULL
, &process_info
);
360 if (GetLastError () != ERROR_OUTOFMEMORY
)
361 SetLastError (ERROR_INVALID_DATA
);
364 /* Shell exec should not return a process handle when it spawned a GUI thing, like a browser. */
365 CloseHandle (process_info
.hProcess
);
366 process_info
.hProcess
= NULL
;
369 if (sei
->fMask
& SEE_MASK_NOCLOSEPROCESS
)
370 sei
->hProcess
= process_info
.hProcess
;
372 CloseHandle (process_info
.hProcess
);
378 is_managed_binary (const char *filename
)
380 int original_errno
= errno
;
381 #if defined(HAVE_LARGE_FILE_SUPPORT) && defined(O_LARGEFILE)
382 int file
= open (filename
, O_RDONLY
| O_LARGEFILE
);
384 int file
= open (filename
, O_RDONLY
);
387 unsigned char buffer
[8];
388 off_t file_size
, optional_header_offset
;
389 off_t pe_header_offset
;
390 gboolean managed
= FALSE
;
392 guint32 first_word
, second_word
;
394 /* If we are unable to open the file, then we definitely
395 * can't say that it is managed. The child mono process
396 * probably wouldn't be able to open it anyway.
399 errno
= original_errno
;
403 /* Retrieve the length of the file for future sanity checks. */
404 file_size
= lseek (file
, 0, SEEK_END
);
405 lseek (file
, 0, SEEK_SET
);
407 /* We know we need to read a header field at offset 60. */
411 num_read
= read (file
, buffer
, 2);
413 if ((num_read
!= 2) || (buffer
[0] != 'M') || (buffer
[1] != 'Z'))
416 new_offset
= lseek (file
, 60, SEEK_SET
);
418 if (new_offset
!= 60)
421 num_read
= read (file
, buffer
, 4);
425 pe_header_offset
= buffer
[0]
430 if (pe_header_offset
+ 24 > file_size
)
433 new_offset
= lseek (file
, pe_header_offset
, SEEK_SET
);
435 if (new_offset
!= pe_header_offset
)
438 num_read
= read (file
, buffer
, 4);
440 if ((num_read
!= 4) || (buffer
[0] != 'P') || (buffer
[1] != 'E') || (buffer
[2] != 0) || (buffer
[3] != 0))
444 * Verify that the header we want in the optional header data
445 * is present in this binary.
447 new_offset
= lseek (file
, pe_header_offset
+ 20, SEEK_SET
);
449 if (new_offset
!= pe_header_offset
+ 20)
452 num_read
= read (file
, buffer
, 2);
454 if ((num_read
!= 2) || ((buffer
[0] | (buffer
[1] << 8)) < 216))
457 /* Read the CLR header address and size fields. These will be
458 * zero if the binary is not managed.
460 optional_header_offset
= pe_header_offset
+ 24;
461 new_offset
= lseek (file
, optional_header_offset
+ 208, SEEK_SET
);
463 if (new_offset
!= optional_header_offset
+ 208)
466 num_read
= read (file
, buffer
, 8);
468 /* We are not concerned with endianness, only with
469 * whether it is zero or not.
471 first_word
= *(guint32
*)&buffer
[0];
472 second_word
= *(guint32
*)&buffer
[4];
474 if ((num_read
!= 8) || (first_word
== 0) || (second_word
== 0))
481 errno
= original_errno
;
486 CreateProcessWithLogonW (const gunichar2
*username
,
487 const gunichar2
*domain
,
488 const gunichar2
*password
,
489 const guint32 logonFlags
,
490 const gunichar2
*appname
,
491 const gunichar2
*cmdline
,
492 guint32 create_flags
,
494 const gunichar2
*cwd
,
495 WapiStartupInfo
*startup
,
496 WapiProcessInformation
*process_info
)
498 /* FIXME: use user information */
499 return CreateProcess (appname
, cmdline
, NULL
, NULL
, FALSE
, create_flags
, env
, cwd
, startup
, process_info
);
503 is_readable_or_executable (const char *prog
)
506 int a
= access (prog
, R_OK
);
507 int b
= access (prog
, X_OK
);
508 if (a
!= 0 && b
!= 0)
510 if (stat (prog
, &buf
))
512 if (S_ISREG (buf
.st_mode
))
518 is_executable (const char *prog
)
521 if (access (prog
, X_OK
) != 0)
523 if (stat (prog
, &buf
))
525 if (S_ISREG (buf
.st_mode
))
531 switch_dir_separators (char *path
)
533 size_t i
, pathLength
= strlen(path
);
535 /* Turn all the slashes round the right way, except for \' */
536 /* There are probably other characters that need to be excluded as well. */
537 for (i
= 0; i
< pathLength
; i
++) {
538 if (path
[i
] == '\\' && i
< pathLength
- 1 && path
[i
+1] != '\'' )
543 gboolean
CreateProcess (const gunichar2
*appname
, const gunichar2
*cmdline
,
544 WapiSecurityAttributes
*process_attrs G_GNUC_UNUSED
,
545 WapiSecurityAttributes
*thread_attrs G_GNUC_UNUSED
,
546 gboolean inherit_handles
, guint32 create_flags
,
547 gpointer new_environ
, const gunichar2
*cwd
,
548 WapiStartupInfo
*startup
,
549 WapiProcessInformation
*process_info
)
551 char *cmd
= NULL
, *prog
= NULL
, *full_prog
= NULL
, *args
= NULL
, *args_after_prog
= NULL
;
552 char *dir
= NULL
, **env_strings
= NULL
, **argv
= NULL
;
553 guint32 i
, env_count
= 0;
554 gboolean ret
= FALSE
;
556 WapiHandle_process process_handle
= {0}, *process_handle_data
;
558 int in_fd
, out_fd
, err_fd
;
561 int startup_pipe
[2] = {-1, -1};
563 struct MonoProcess
*mono_process
;
564 gboolean fork_failed
= FALSE
;
566 mono_once (&process_sig_chld_once
, process_add_sigchld_handler
);
568 /* appname and cmdline specify the executable and its args:
570 * If appname is not NULL, it is the name of the executable.
571 * Otherwise the executable is the first token in cmdline.
573 * Executable searching:
575 * If appname is not NULL, it can specify the full path and
576 * file name, or else a partial name and the current directory
577 * will be used. There is no additional searching.
579 * If appname is NULL, the first whitespace-delimited token in
580 * cmdline is used. If the name does not contain a full
581 * directory path, the search sequence is:
583 * 1) The directory containing the current process
584 * 2) The current working directory
585 * 3) The windows system directory (Ignored)
586 * 4) The windows directory (Ignored)
589 * Just to make things more interesting, tokens can contain
590 * white space if they are surrounded by quotation marks. I'm
591 * beginning to understand just why windows apps are generally
592 * so crap, with an API like this :-(
594 if (appname
!= NULL
) {
595 cmd
= mono_unicode_to_external (appname
);
597 DEBUG ("%s: unicode conversion returned NULL",
600 SetLastError (ERROR_PATH_NOT_FOUND
);
604 switch_dir_separators(cmd
);
607 if (cmdline
!= NULL
) {
608 args
= mono_unicode_to_external (cmdline
);
610 DEBUG ("%s: unicode conversion returned NULL", __func__
);
612 SetLastError (ERROR_PATH_NOT_FOUND
);
618 dir
= mono_unicode_to_external (cwd
);
620 DEBUG ("%s: unicode conversion returned NULL", __func__
);
622 SetLastError (ERROR_PATH_NOT_FOUND
);
626 /* Turn all the slashes round the right way */
627 switch_dir_separators(dir
);
631 /* We can't put off locating the executable any longer :-( */
634 if (g_ascii_isalpha (cmd
[0]) && (cmd
[1] == ':')) {
635 /* Strip off the drive letter. I can't
636 * believe that CP/M holdover is still
639 g_memmove (cmd
, cmd
+2, strlen (cmd
)-2);
640 cmd
[strlen (cmd
)-2] = '\0';
643 unquoted
= g_shell_unquote (cmd
, NULL
);
644 if (unquoted
[0] == '/') {
645 /* Assume full path given */
646 prog
= g_strdup (unquoted
);
648 /* Executable existing ? */
649 if (!is_readable_or_executable (prog
)) {
650 DEBUG ("%s: Couldn't find executable %s",
653 SetLastError (ERROR_FILE_NOT_FOUND
);
657 /* Search for file named by cmd in the current
660 char *curdir
= g_get_current_dir ();
662 prog
= g_strdup_printf ("%s/%s", curdir
, unquoted
);
665 /* And make sure it's readable */
666 if (!is_readable_or_executable (prog
)) {
667 DEBUG ("%s: Couldn't find executable %s",
670 SetLastError (ERROR_FILE_NOT_FOUND
);
676 args_after_prog
= args
;
681 /* Dig out the first token from args, taking quotation
685 /* First, strip off all leading whitespace */
686 args
= g_strchug (args
);
688 /* args_after_prog points to the contents of args
689 * after token has been set (otherwise argv[0] is
692 args_after_prog
= args
;
694 /* Assume the opening quote will always be the first
697 if (args
[0] == '\"' || args
[0] == '\'') {
699 for (i
= 1; args
[i
] != '\0' && args
[i
] != quote
; i
++);
700 if (args
[i
+ 1] == '\0' || g_ascii_isspace (args
[i
+1])) {
701 /* We found the first token */
702 token
= g_strndup (args
+1, i
-1);
703 args_after_prog
= g_strchug (args
+ i
+ 1);
705 /* Quotation mark appeared in the
706 * middle of the token. Just give the
707 * whole first token, quotes and all,
714 /* No quote mark, or malformed */
715 for (i
= 0; args
[i
] != '\0'; i
++) {
716 if (g_ascii_isspace (args
[i
])) {
717 token
= g_strndup (args
, i
);
718 args_after_prog
= args
+ i
+ 1;
724 if (token
== NULL
&& args
[0] != '\0') {
725 /* Must be just one token in the string */
726 token
= g_strdup (args
);
727 args_after_prog
= NULL
;
732 DEBUG ("%s: Couldn't find what to exec", __func__
);
734 SetLastError (ERROR_PATH_NOT_FOUND
);
738 /* Turn all the slashes round the right way. Only for
741 switch_dir_separators(token
);
743 if (g_ascii_isalpha (token
[0]) && (token
[1] == ':')) {
744 /* Strip off the drive letter. I can't
745 * believe that CP/M holdover is still
748 g_memmove (token
, token
+2, strlen (token
)-2);
749 token
[strlen (token
)-2] = '\0';
752 if (token
[0] == '/') {
753 /* Assume full path given */
754 prog
= g_strdup (token
);
756 /* Executable existing ? */
757 if (!is_readable_or_executable (prog
)) {
758 DEBUG ("%s: Couldn't find executable %s",
761 SetLastError (ERROR_FILE_NOT_FOUND
);
765 char *curdir
= g_get_current_dir ();
767 /* FIXME: Need to record the directory
768 * containing the current process, and check
769 * that for the new executable as the first
773 prog
= g_strdup_printf ("%s/%s", curdir
, token
);
776 /* I assume X_OK is the criterion to use,
779 * X_OK is too strict *if* the target is a CLR binary
781 if (!is_readable_or_executable (prog
)) {
783 prog
= g_find_program_in_path (token
);
785 DEBUG ("%s: Couldn't find executable %s", __func__
, token
);
788 SetLastError (ERROR_FILE_NOT_FOUND
);
797 DEBUG ("%s: Exec prog [%s] args [%s]", __func__
, prog
,
800 /* Check for CLR binaries; if found, we will try to invoke
801 * them using the same mono binary that started us.
803 if (is_managed_binary (prog
)) {
804 gunichar2
*newapp
= NULL
, *newcmd
;
808 newapp
= mono_unicode_from_external (cli_launcher
, &bytes_ignored
);
810 newapp
= mono_unicode_from_external ("mono", &bytes_ignored
);
812 if (newapp
!= NULL
) {
813 if (appname
!= NULL
) {
814 newcmd
= utf16_concat (newapp
, utf16_space
,
815 appname
, utf16_space
,
818 newcmd
= utf16_concat (newapp
, utf16_space
,
822 g_free ((gunichar2
*)newapp
);
824 if (newcmd
!= NULL
) {
825 ret
= CreateProcess (NULL
, newcmd
,
829 create_flags
, new_environ
,
833 g_free ((gunichar2
*)newcmd
);
839 if (!is_executable (prog
)) {
840 DEBUG ("%s: Executable permisson not set on %s", __func__
, prog
);
841 SetLastError (ERROR_ACCESS_DENIED
);
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 process_handle
.proc_name
= g_strdup (prog
);
876 process_set_defaults (&process_handle
);
878 handle
= _wapi_handle_new (WAPI_HANDLE_PROCESS
, &process_handle
);
879 if (handle
== _WAPI_HANDLE_INVALID
) {
880 g_warning ("%s: error creating process handle", __func__
);
883 SetLastError (ERROR_OUTOFMEMORY
);
887 /* new_environ is a block of NULL-terminated strings, which
888 * is itself NULL-terminated. Of course, passing an array of
889 * string pointers would have made things too easy :-(
891 * If new_environ is not NULL it specifies the entire set of
892 * environment variables in the new process. Otherwise the
893 * new process inherits the same environment.
896 gunichar2
*new_environp
;
898 /* Count the number of strings */
899 for (new_environp
= (gunichar2
*)new_environ
; *new_environp
;
902 while (*new_environp
) {
907 /* +2: one for the process handle value, and the last
910 env_strings
= g_new0 (char *, env_count
+ 2);
912 /* Copy each environ string into 'strings' turning it
913 * into utf8 (or the requested encoding) at the same
917 for (new_environp
= (gunichar2
*)new_environ
; *new_environp
;
919 env_strings
[env_count
] = mono_unicode_to_external (new_environp
);
921 while (*new_environp
) {
926 for (i
= 0; environ
[i
] != NULL
; i
++)
929 /* +2: one for the process handle value, and the last
932 env_strings
= g_new0 (char *, env_count
+ 2);
934 /* Copy each environ string into 'strings' turning it
935 * into utf8 (or the requested encoding) at the same
939 for (i
= 0; environ
[i
] != NULL
; i
++) {
940 env_strings
[env_count
] = g_strdup (environ
[i
]);
945 /* Create a pipe to make sure the child doesn't exit before
946 * we can add the process to the linked list of mono_processes */
947 if (pipe (startup_pipe
) == -1) {
948 /* Could not create the pipe to synchroniz process startup. We'll just not synchronize.
949 * This is just for a very hard to hit race condition in the first place */
950 startup_pipe
[0] = startup_pipe
[1] = -1;
951 DEBUG ("%s: new process startup not synchronized. We may not notice if the newly created process exits immediately.", __func__
);
954 thr_ret
= _wapi_handle_lock_shared_handles ();
955 g_assert (thr_ret
== 0);
960 SetLastError (ERROR_OUTOFMEMORY
);
964 } else if (pid
== 0) {
967 if (startup_pipe
[0] != -1) {
968 /* Wait until the parent has updated it's internal data */
969 ssize_t _i G_GNUC_UNUSED
= read (startup_pipe
[0], &dummy
, 1);
970 DEBUG ("%s: child: parent has completed its setup", __func__
);
971 close (startup_pipe
[0]);
972 close (startup_pipe
[1]);
975 /* should we detach from the process group? */
977 /* Connect stdin, stdout and stderr */
982 if (inherit_handles
!= TRUE
) {
983 /* FIXME: do something here */
986 /* Close all file descriptors */
987 for (i
= wapi_getdtablesize () - 1; i
> 2; i
--)
991 DEBUG ("%s: exec()ing [%s] in dir [%s]", __func__
, cmd
,
992 dir
== NULL
?".":dir
);
993 for (i
= 0; argv
[i
] != NULL
; i
++)
994 g_message ("arg %d: [%s]", i
, argv
[i
]);
996 for (i
= 0; env_strings
[i
] != NULL
; i
++)
997 g_message ("env %d: [%s]", i
, env_strings
[i
]);
1001 if (dir
!= NULL
&& chdir (dir
) == -1) {
1007 execve (argv
[0], argv
, env_strings
);
1014 process_handle_data
= lookup_process_handle (handle
);
1015 if (!process_handle_data
) {
1016 g_warning ("%s: error looking up process handle %p", __func__
,
1018 _wapi_handle_unref (handle
);
1022 process_handle_data
->id
= pid
;
1024 /* Add our mono_process into the linked list of mono_processes */
1025 mono_process
= (struct MonoProcess
*) g_malloc0 (sizeof (struct MonoProcess
));
1026 mono_process
->pid
= pid
;
1027 mono_process
->handle_count
= 1;
1028 if (MONO_SEM_INIT (&mono_process
->exit_sem
, 0) != 0) {
1029 /* If we can't create the exit semaphore, we just don't add anything
1030 * to our list of mono processes. Waiting on the process will return
1032 g_warning ("%s: could not create exit semaphore for process.", strerror (errno
));
1033 g_free (mono_process
);
1035 /* Keep the process handle artificially alive until the process
1036 * exits so that the information in the handle isn't lost. */
1037 _wapi_handle_ref (handle
);
1038 mono_process
->handle
= handle
;
1040 process_handle_data
->mono_process
= mono_process
;
1042 mono_mutex_lock (&mono_processes_mutex
);
1043 mono_process
->next
= mono_processes
;
1044 mono_processes
= mono_process
;
1045 mono_mutex_unlock (&mono_processes_mutex
);
1048 if (process_info
!= NULL
) {
1049 process_info
->hProcess
= handle
;
1050 process_info
->dwProcessId
= pid
;
1052 /* FIXME: we might need to handle the thread info some
1055 process_info
->hThread
= INVALID_HANDLE_VALUE
;
1056 process_info
->dwThreadId
= 0;
1060 _wapi_handle_unlock_shared_handles ();
1063 _wapi_handle_unref (handle
);
1065 if (startup_pipe
[1] != -1) {
1066 /* Write 1 byte, doesn't matter what */
1067 ssize_t _i G_GNUC_UNUSED
= write (startup_pipe
[1], startup_pipe
, 1);
1068 close (startup_pipe
[0]);
1069 close (startup_pipe
[1]);
1084 g_strfreev (env_strings
);
1088 DEBUG ("%s: returning handle %p for pid %d", __func__
, handle
,
1091 /* Check if something needs to be cleaned up. */
1092 mono_processes_cleanup ();
1098 process_set_name (WapiHandle_process
*process_handle
)
1100 char *progname
, *utf8_progname
, *slash
;
1102 progname
= g_get_prgname ();
1103 utf8_progname
= mono_utf8_from_external (progname
);
1105 DEBUG ("%s: using [%s] as prog name", __func__
, progname
);
1107 if (utf8_progname
) {
1108 slash
= strrchr (utf8_progname
, '/');
1110 process_handle
->proc_name
= g_strdup (slash
+1);
1112 process_handle
->proc_name
= g_strdup (utf8_progname
);
1113 g_free (utf8_progname
);
1118 wapi_processes_init (void)
1120 pid_t pid
= _wapi_getpid ();
1121 WapiHandle_process process_handle
= {0};
1123 _wapi_handle_register_capabilities (WAPI_HANDLE_PROCESS
,
1124 WAPI_HANDLE_CAP_WAIT
|
1125 WAPI_HANDLE_CAP_SPECIAL_WAIT
);
1127 process_handle
.id
= pid
;
1129 process_set_defaults (&process_handle
);
1130 process_set_name (&process_handle
);
1132 current_process
= _wapi_handle_new (WAPI_HANDLE_PROCESS
,
1134 g_assert (current_process
);
1138 _wapi_process_duplicate (void)
1140 _wapi_handle_ref (current_process
);
1142 return current_process
;
1145 /* Returns a pseudo handle that doesn't need to be closed afterwards */
1147 GetCurrentProcess (void)
1149 return _WAPI_PROCESS_CURRENT
;
1153 GetProcessId (gpointer handle
)
1155 WapiHandle_process
*process_handle
;
1157 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (handle
))
1158 /* This is a pseudo handle */
1159 return WAPI_HANDLE_TO_PID (handle
);
1161 process_handle
= lookup_process_handle (handle
);
1162 if (!process_handle
) {
1163 SetLastError (ERROR_INVALID_HANDLE
);
1167 return process_handle
->id
;
1171 process_open_compare (gpointer handle
, gpointer user_data
)
1174 WapiHandle_process
*process_handle
;
1177 g_assert (!WAPI_IS_PSEUDO_PROCESS_HANDLE (handle
));
1179 process_handle
= lookup_process_handle (handle
);
1180 g_assert (process_handle
);
1182 DEBUG ("%s: looking at process %d", __func__
, process_handle
->id
);
1184 checking_pid
= process_handle
->id
;
1186 if (checking_pid
== 0)
1189 wanted_pid
= GPOINTER_TO_UINT (user_data
);
1191 /* It's possible to have more than one process handle with the
1192 * same pid, but only the one running process can be
1195 if (checking_pid
== wanted_pid
&&
1196 !_wapi_handle_issignalled (handle
)) {
1197 /* If the handle is blown away in the window between
1198 * returning TRUE here and _wapi_search_handle pinging
1199 * the timestamp, the search will continue
1208 CloseProcess (gpointer handle
)
1210 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (handle
))
1212 return CloseHandle (handle
);
1216 * The caller owns the returned handle and must call CloseProcess () on it to clean it up.
1219 OpenProcess (guint32 req_access G_GNUC_UNUSED
, gboolean inherit G_GNUC_UNUSED
, guint32 pid
)
1221 /* Find the process handle that corresponds to pid */
1222 gpointer handle
= NULL
;
1224 DEBUG ("%s: looking for process %d", __func__
, pid
);
1226 handle
= _wapi_search_handle (WAPI_HANDLE_PROCESS
,
1227 process_open_compare
,
1228 GUINT_TO_POINTER (pid
), NULL
, TRUE
);
1230 if (is_pid_valid (pid
)) {
1231 /* Return a pseudo handle for processes we
1232 * don't have handles for
1234 return WAPI_PID_TO_HANDLE (pid
);
1236 DEBUG ("%s: Can't find pid %d", __func__
, pid
);
1238 SetLastError (ERROR_PROC_NOT_FOUND
);
1244 /* _wapi_search_handle () already added a ref */
1249 GetExitCodeProcess (gpointer process
, guint32
*code
)
1251 WapiHandle_process
*process_handle
;
1257 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process
)) {
1258 pid
= WAPI_HANDLE_TO_PID (process
);
1259 /* This is a pseudo handle, so we don't know what the
1260 * exit code was, but we can check whether it's alive or not
1262 if (is_pid_valid (pid
)) {
1263 *code
= STILL_ACTIVE
;
1270 process_handle
= lookup_process_handle (process
);
1271 if (!process_handle
) {
1272 DEBUG ("%s: Can't find process %p", __func__
, process
);
1277 if (process_handle
->id
== _wapi_getpid ()) {
1278 *code
= STILL_ACTIVE
;
1282 /* A process handle is only signalled if the process has exited
1283 * and has been waited for */
1285 /* Make sure any process exit has been noticed, before
1286 * checking if the process is signalled. Fixes bug 325463.
1288 process_wait (process
, 0, TRUE
);
1290 if (_wapi_handle_issignalled (process
))
1291 *code
= process_handle
->exitstatus
;
1293 *code
= STILL_ACTIVE
;
1299 GetProcessTimes (gpointer process
, WapiFileTime
*create_time
,
1300 WapiFileTime
*exit_time
, WapiFileTime
*kernel_time
,
1301 WapiFileTime
*user_time
)
1303 WapiHandle_process
*process_handle
;
1304 gboolean ku_times_set
= FALSE
;
1306 if (create_time
== NULL
|| exit_time
== NULL
|| kernel_time
== NULL
||
1308 /* Not sure if w32 allows NULLs here or not */
1311 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process
))
1312 /* This is a pseudo handle, so just fail for now
1316 process_handle
= lookup_process_handle (process
);
1317 if (!process_handle
) {
1318 DEBUG ("%s: Can't find process %p", __func__
, process
);
1323 *create_time
= process_handle
->create_time
;
1325 /* A process handle is only signalled if the process has
1326 * exited. Otherwise exit_time isn't set
1328 if (_wapi_handle_issignalled (process
))
1329 *exit_time
= process_handle
->exit_time
;
1331 #ifdef HAVE_GETRUSAGE
1332 if (process_handle
->id
== getpid ()) {
1333 struct rusage time_data
;
1334 if (getrusage (RUSAGE_SELF
, &time_data
) == 0) {
1336 ku_times_set
= TRUE
;
1337 tick_val
= (guint64
)time_data
.ru_utime
.tv_sec
* 10000000 + (guint64
)time_data
.ru_utime
.tv_usec
* 10;
1338 _wapi_guint64_to_filetime (tick_val
, user_time
);
1339 tick_val
= (guint64
)time_data
.ru_stime
.tv_sec
* 10000000 + (guint64
)time_data
.ru_stime
.tv_usec
* 10;
1340 _wapi_guint64_to_filetime (tick_val
, kernel_time
);
1344 if (!ku_times_set
) {
1345 memset (kernel_time
, 0, sizeof (WapiFileTime
));
1346 memset (user_time
, 0, sizeof (WapiFileTime
));
1354 gpointer address_start
;
1355 gpointer address_end
;
1357 gpointer address_offset
;
1363 static void free_procmodule (WapiProcModule
*mod
)
1365 if (mod
->perms
!= NULL
) {
1366 g_free (mod
->perms
);
1368 if (mod
->filename
!= NULL
) {
1369 g_free (mod
->filename
);
1374 static gint
find_procmodule (gconstpointer a
, gconstpointer b
)
1376 WapiProcModule
*want
= (WapiProcModule
*)a
;
1377 WapiProcModule
*compare
= (WapiProcModule
*)b
;
1379 if ((want
->device
== compare
->device
) &&
1380 (want
->inode
== compare
->inode
)) {
1387 #ifdef PLATFORM_MACOSX
1388 #include <mach-o/dyld.h>
1389 #include <mach-o/getsect.h>
1391 static GSList
*load_modules (void)
1394 WapiProcModule
*mod
;
1395 uint32_t count
= _dyld_image_count ();
1398 for (i
= 0; i
< count
; i
++) {
1399 #if SIZEOF_VOID_P == 8
1400 const struct mach_header_64
*hdr
;
1401 const struct section_64
*sec
;
1403 const struct mach_header
*hdr
;
1404 const struct section
*sec
;
1408 name
= _dyld_get_image_name (i
);
1409 #if SIZEOF_VOID_P == 8
1410 hdr
= (const struct mach_header_64
*)_dyld_get_image_header (i
);
1411 sec
= getsectbynamefromheader_64 (hdr
, SEG_DATA
, SECT_DATA
);
1413 hdr
= _dyld_get_image_header (i
);
1414 sec
= getsectbynamefromheader (hdr
, SEG_DATA
, SECT_DATA
);
1417 /* Some dynlibs do not have data sections on osx (#533893) */
1422 mod
= g_new0 (WapiProcModule
, 1);
1423 mod
->address_start
= GINT_TO_POINTER (sec
->addr
);
1424 mod
->address_end
= GINT_TO_POINTER (sec
->addr
+sec
->size
);
1425 mod
->perms
= g_strdup ("r--p");
1426 mod
->address_offset
= 0;
1427 mod
->device
= makedev (0, 0);
1429 mod
->filename
= g_strdup (name
);
1431 if (g_slist_find_custom (ret
, mod
, find_procmodule
) == NULL
) {
1432 ret
= g_slist_prepend (ret
, mod
);
1434 free_procmodule (mod
);
1438 ret
= g_slist_reverse (ret
);
1442 #elif defined(__OpenBSD__)
1444 static int load_modules_callback (struct dl_phdr_info
*info
, size_t size
, void *ptr
)
1446 if (size
< offsetof (struct dl_phdr_info
, dlpi_phnum
)
1447 + sizeof (info
->dlpi_phnum
))
1450 struct dl_phdr_info
*cpy
= calloc(1, sizeof(struct dl_phdr_info
));
1454 memcpy(cpy
, info
, sizeof(*info
));
1456 g_ptr_array_add ((GPtrArray
*)ptr
, cpy
);
1461 static GSList
*load_modules (void)
1464 WapiProcModule
*mod
;
1465 GPtrArray
*dlarray
= g_ptr_array_new();
1468 if (dl_iterate_phdr(load_modules_callback
, dlarray
) < 0)
1471 for (i
= 0; i
< dlarray
->len
; i
++) {
1472 struct dl_phdr_info
*info
= g_ptr_array_index (dlarray
, i
);
1474 mod
= g_new0 (WapiProcModule
, 1);
1475 mod
->address_start
= (gpointer
)(info
->dlpi_addr
+ info
->dlpi_phdr
[0].p_vaddr
);
1476 mod
->address_end
= (gpointer
)(info
->dlpi_addr
+
1477 info
->dlpi_phdr
[info
->dlpi_phnum
- 1].p_vaddr
);
1478 mod
->perms
= g_strdup ("r--p");
1479 mod
->address_offset
= 0;
1481 mod
->filename
= g_strdup (info
->dlpi_name
);
1483 DEBUG ("%s: inode=%d, filename=%s, address_start=%p, address_end=%p", __func__
,
1484 mod
->inode
, mod
->filename
, mod
->address_start
, mod
->address_end
);
1488 if (g_slist_find_custom (ret
, mod
, find_procmodule
) == NULL
) {
1489 ret
= g_slist_prepend (ret
, mod
);
1491 free_procmodule (mod
);
1495 g_ptr_array_free (dlarray
, TRUE
);
1497 ret
= g_slist_reverse (ret
);
1501 #elif defined(__HAIKU__)
1503 static GSList
*load_modules (void)
1506 WapiProcModule
*mod
;
1508 image_info imageInfo
;
1510 while (get_next_image_info (B_CURRENT_TEAM
, &cookie
, &imageInfo
) == B_OK
) {
1511 mod
= g_new0 (WapiProcModule
, 1);
1512 mod
->device
= imageInfo
.device
;
1513 mod
->inode
= imageInfo
.node
;
1514 mod
->filename
= g_strdup (imageInfo
.name
);
1515 mod
->address_start
= MIN (imageInfo
.text
, imageInfo
.data
);
1516 mod
->address_end
= MAX ((uint8_t*)imageInfo
.text
+ imageInfo
.text_size
,
1517 (uint8_t*)imageInfo
.data
+ imageInfo
.data_size
);
1518 mod
->perms
= g_strdup ("r--p");
1519 mod
->address_offset
= 0;
1521 if (g_slist_find_custom (ret
, mod
, find_procmodule
) == NULL
) {
1522 ret
= g_slist_prepend (ret
, mod
);
1524 free_procmodule (mod
);
1528 ret
= g_slist_reverse (ret
);
1533 static GSList
*load_modules (FILE *fp
)
1536 WapiProcModule
*mod
;
1537 char buf
[MAXPATHLEN
+ 1], *p
, *endp
;
1538 char *start_start
, *end_start
, *prot_start
, *offset_start
;
1539 char *maj_dev_start
, *min_dev_start
, *inode_start
, prot_buf
[5];
1540 gpointer address_start
, address_end
, address_offset
;
1541 guint32 maj_dev
, min_dev
;
1545 while (fgets (buf
, sizeof(buf
), fp
)) {
1547 while (g_ascii_isspace (*p
)) ++p
;
1549 if (!g_ascii_isxdigit (*start_start
)) {
1552 address_start
= (gpointer
)strtoul (start_start
, &endp
, 16);
1560 if (!g_ascii_isxdigit (*end_start
)) {
1563 address_end
= (gpointer
)strtoul (end_start
, &endp
, 16);
1565 if (!g_ascii_isspace (*p
)) {
1569 while (g_ascii_isspace (*p
)) ++p
;
1571 if (*prot_start
!= 'r' && *prot_start
!= '-') {
1574 memcpy (prot_buf
, prot_start
, 4);
1576 while (!g_ascii_isspace (*p
)) ++p
;
1578 while (g_ascii_isspace (*p
)) ++p
;
1580 if (!g_ascii_isxdigit (*offset_start
)) {
1583 address_offset
= (gpointer
)strtoul (offset_start
, &endp
, 16);
1585 if (!g_ascii_isspace (*p
)) {
1589 while(g_ascii_isspace (*p
)) ++p
;
1591 if (!g_ascii_isxdigit (*maj_dev_start
)) {
1594 maj_dev
= strtoul (maj_dev_start
, &endp
, 16);
1602 if (!g_ascii_isxdigit (*min_dev_start
)) {
1605 min_dev
= strtoul (min_dev_start
, &endp
, 16);
1607 if (!g_ascii_isspace (*p
)) {
1611 while (g_ascii_isspace (*p
)) ++p
;
1613 if (!g_ascii_isxdigit (*inode_start
)) {
1616 inode
= (guint64
)strtol (inode_start
, &endp
, 10);
1618 if (!g_ascii_isspace (*p
)) {
1622 device
= makedev ((int)maj_dev
, (int)min_dev
);
1623 if ((device
== 0) &&
1628 while(g_ascii_isspace (*p
)) ++p
;
1629 /* p now points to the filename */
1631 mod
= g_new0 (WapiProcModule
, 1);
1632 mod
->address_start
= address_start
;
1633 mod
->address_end
= address_end
;
1634 mod
->perms
= g_strdup (prot_buf
);
1635 mod
->address_offset
= address_offset
;
1636 mod
->device
= device
;
1638 mod
->filename
= g_strdup (g_strstrip (p
));
1640 if (g_slist_find_custom (ret
, mod
, find_procmodule
) == NULL
) {
1641 ret
= g_slist_prepend (ret
, mod
);
1643 free_procmodule (mod
);
1647 ret
= g_slist_reverse (ret
);
1653 static gboolean
match_procname_to_modulename (char *procname
, char *modulename
)
1655 char* lastsep
= NULL
;
1656 char* lastsep2
= NULL
;
1659 gboolean result
= FALSE
;
1661 if (procname
== NULL
|| modulename
== NULL
)
1664 pname
= mono_path_resolve_symlinks (procname
);
1665 mname
= mono_path_resolve_symlinks (modulename
);
1667 if (!strcmp (pname
, mname
))
1671 lastsep
= strrchr (mname
, '/');
1673 if (!strcmp (lastsep
+1, pname
))
1676 lastsep2
= strrchr (pname
, '/');
1679 if (!strcmp (lastsep
+1, lastsep2
+1))
1682 if (!strcmp (mname
, lastsep2
+1))
1695 #if !defined(__OpenBSD__)
1697 open_process_map (int pid
, const char *mode
)
1700 const char *proc_path
[] = {
1701 "/proc/%d/maps", /* GNU/Linux */
1702 "/proc/%d/map", /* FreeBSD */
1708 for (i
= 0; fp
== NULL
&& proc_path
[i
]; i
++) {
1709 filename
= g_strdup_printf (proc_path
[i
], pid
);
1710 fp
= fopen (filename
, mode
);
1718 gboolean
EnumProcessModules (gpointer process
, gpointer
*modules
,
1719 guint32 size
, guint32
*needed
)
1721 WapiHandle_process
*process_handle
;
1722 #if !defined(__OpenBSD__) && !defined(PLATFORM_MACOSX)
1725 GSList
*mods
= NULL
;
1726 WapiProcModule
*module
;
1727 guint32 count
, avail
= size
/ sizeof(gpointer
);
1730 char *proc_name
= NULL
;
1732 /* Store modules in an array of pointers (main module as
1733 * modules[0]), using the load address for each module as a
1734 * token. (Use 'NULL' as an alternative for the main module
1735 * so that the simple implementation can just return one item
1736 * for now.) Get the info from /proc/<pid>/maps on linux,
1737 * /proc/<pid>/map on FreeBSD, other systems will have to
1738 * implement /dev/kmem reading or whatever other horrid
1739 * technique is needed.
1741 if (size
< sizeof(gpointer
))
1744 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process
)) {
1745 pid
= WAPI_HANDLE_TO_PID (process
);
1747 process_handle
= lookup_process_handle (process
);
1748 if (!process_handle
) {
1749 DEBUG ("%s: Can't find process %p", __func__
, process
);
1753 pid
= process_handle
->id
;
1754 proc_name
= process_handle
->proc_name
;
1757 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__) || defined(__HAIKU__)
1758 mods
= load_modules ();
1761 *needed
= sizeof(gpointer
);
1765 fp
= open_process_map (pid
, "r");
1767 /* No /proc/<pid>/maps so just return the main module
1771 *needed
= sizeof(gpointer
);
1774 mods
= load_modules (fp
);
1777 count
= g_slist_length (mods
);
1779 /* count + 1 to leave slot 0 for the main module */
1780 *needed
= sizeof(gpointer
) * (count
+ 1);
1783 * Use the NULL shortcut, as the first line in
1784 * /proc/<pid>/maps isn't the executable, and we need
1785 * that first in the returned list. Check the module name
1786 * to see if it ends with the proc name and substitute
1787 * the first entry with it. FIXME if this turns out to
1791 for (i
= 0; i
< (avail
- 1) && i
< count
; i
++) {
1792 module
= (WapiProcModule
*)g_slist_nth_data (mods
, i
);
1793 if (modules
[0] != NULL
)
1794 modules
[i
] = module
->address_start
;
1795 else if (match_procname_to_modulename (proc_name
, module
->filename
))
1796 modules
[0] = module
->address_start
;
1798 modules
[i
+ 1] = module
->address_start
;
1801 for (i
= 0; i
< count
; i
++) {
1802 free_procmodule (g_slist_nth_data (mods
, i
));
1804 g_slist_free (mods
);
1810 get_process_name_from_proc (pid_t pid
)
1812 #if defined(__OpenBSD__)
1815 struct kinfo_proc
*pi
;
1816 #elif defined(PLATFORM_MACOSX)
1817 #if !(!defined (__mono_ppc__) && defined (TARGET_OSX))
1819 struct kinfo_proc
*pi
;
1820 int mib
[] = { CTL_KERN
, KERN_PROC
, KERN_PROC_PID
, pid
};
1824 char *filename
= NULL
;
1829 #if defined(PLATFORM_SOLARIS)
1830 filename
= g_strdup_printf ("/proc/%d/psinfo", pid
);
1831 if ((fp
= fopen (filename
, "r")) != NULL
) {
1835 nread
= fread (&info
, sizeof (info
), 1, fp
);
1837 ret
= g_strdup (info
.pr_fname
);
1843 #elif defined(PLATFORM_MACOSX)
1844 #if !defined (__mono_ppc__) && defined (TARGET_OSX)
1845 /* No proc name on OSX < 10.5 nor ppc nor iOS */
1846 memset (buf
, '\0', sizeof(buf
));
1847 proc_name (pid
, buf
, sizeof(buf
));
1848 if (strlen (buf
) > 0)
1849 ret
= g_strdup (buf
);
1851 if (sysctl(mib
, 4, NULL
, &size
, NULL
, 0) < 0)
1854 if ((pi
= malloc(size
)) == NULL
)
1857 if (sysctl (mib
, 4, pi
, &size
, NULL
, 0) < 0) {
1858 if (errno
== ENOMEM
) {
1860 DEBUG ("%s: Didn't allocate enough memory for kproc info", __func__
);
1865 if (strlen (pi
->kp_proc
.p_comm
) > 0)
1866 ret
= g_strdup (pi
->kp_proc
.p_comm
);
1870 #elif defined(__OpenBSD__)
1872 mib
[1] = KERN_PROC
;
1873 mib
[2] = KERN_PROC_PID
;
1875 mib
[4] = sizeof(struct kinfo_proc
);
1879 if (sysctl(mib
, 6, NULL
, &size
, NULL
, 0) < 0)
1882 if ((pi
= malloc(size
)) == NULL
)
1885 mib
[5] = (int)(size
/ sizeof(struct kinfo_proc
));
1887 if ((sysctl (mib
, 6, pi
, &size
, NULL
, 0) < 0) ||
1888 (size
!= sizeof (struct kinfo_proc
))) {
1889 if (errno
== ENOMEM
) {
1896 if (strlen (pi
->p_comm
) > 0)
1897 ret
= g_strdup (pi
->p_comm
);
1900 #elif defined(__HAIKU__)
1901 image_info imageInfo
;
1904 if (get_next_image_info ((team_id
)pid
, &cookie
, &imageInfo
) == B_OK
) {
1905 ret
= g_strdup (imageInfo
.name
);
1908 memset (buf
, '\0', sizeof(buf
));
1909 filename
= g_strdup_printf ("/proc/%d/exe", pid
);
1910 if (readlink (filename
, buf
, 255) > 0) {
1911 ret
= g_strdup (buf
);
1919 filename
= g_strdup_printf ("/proc/%d/cmdline", pid
);
1920 if ((fp
= fopen (filename
, "r")) != NULL
) {
1921 if (fgets (buf
, 256, fp
) != NULL
) {
1922 ret
= g_strdup (buf
);
1933 filename
= g_strdup_printf ("/proc/%d/stat", pid
);
1934 if ((fp
= fopen (filename
, "r")) != NULL
) {
1935 if (fgets (buf
, 256, fp
) != NULL
) {
1938 start
= strchr (buf
, '(');
1939 if (start
!= NULL
) {
1940 end
= strchr (start
+ 1, ')');
1943 ret
= g_strndup (start
+ 1,
1958 * wapi_process_get_path:
1960 * Return the full path of the executable of the process PID, or NULL if it cannot be determined.
1961 * Returns malloc-ed memory.
1964 wapi_process_get_path (pid_t pid
)
1966 #if defined(PLATFORM_MACOSX) && !defined(__mono_ppc__) && defined(TARGET_OSX)
1967 char buf
[PROC_PIDPATHINFO_MAXSIZE
];
1970 res
= proc_pidpath (pid
, buf
, sizeof (buf
));
1973 if (buf
[0] == '\0')
1975 return g_strdup (buf
);
1977 return get_process_name_from_proc (pid
);
1982 * wapi_process_set_cli_launcher:
1984 * Set the full path of the runtime executable used to launch managed exe's.
1987 wapi_process_set_cli_launcher (char *path
)
1989 g_free (cli_launcher
);
1990 cli_launcher
= path
? g_strdup (path
) : NULL
;
1994 get_module_name (gpointer process
, gpointer module
,
1995 gunichar2
*basename
, guint32 size
,
1998 WapiHandle_process
*process_handle
;
2000 gunichar2
*procname
;
2001 char *procname_ext
= NULL
;
2004 #if !defined(__OpenBSD__) && !defined(PLATFORM_MACOSX)
2007 GSList
*mods
= NULL
;
2008 WapiProcModule
*found_module
;
2011 char *proc_name
= NULL
;
2013 DEBUG ("%s: Getting module base name, process handle %p module %p",
2014 __func__
, process
, module
);
2016 size
= size
* sizeof (gunichar2
); /* adjust for unicode characters */
2018 if (basename
== NULL
|| size
== 0)
2021 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process
)) {
2022 /* This is a pseudo handle */
2023 pid
= (pid_t
)WAPI_HANDLE_TO_PID (process
);
2024 proc_name
= get_process_name_from_proc (pid
);
2026 process_handle
= lookup_process_handle (process
);
2027 if (!process_handle
) {
2028 DEBUG ("%s: Can't find process %p", __func__
,
2033 pid
= process_handle
->id
;
2034 proc_name
= g_strdup (process_handle
->proc_name
);
2037 /* Look up the address in /proc/<pid>/maps */
2038 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__) || defined(__HAIKU__)
2039 mods
= load_modules ();
2041 fp
= open_process_map (pid
, "r");
2043 if (errno
== EACCES
&& module
== NULL
&& base
== TRUE
) {
2044 procname_ext
= get_process_name_from_proc (pid
);
2046 /* No /proc/<pid>/maps, so just return failure
2053 mods
= load_modules (fp
);
2057 count
= g_slist_length (mods
);
2059 /* If module != NULL compare the address.
2060 * If module == NULL we are looking for the main module.
2061 * The best we can do for now check it the module name end with the process name.
2063 for (i
= 0; i
< count
; i
++) {
2064 found_module
= (WapiProcModule
*)g_slist_nth_data (mods
, i
);
2065 if (procname_ext
== NULL
&&
2066 ((module
== NULL
&& match_procname_to_modulename (proc_name
, found_module
->filename
)) ||
2067 (module
!= NULL
&& found_module
->address_start
== module
))) {
2069 procname_ext
= g_path_get_basename (found_module
->filename
);
2071 procname_ext
= g_strdup (found_module
->filename
);
2074 free_procmodule (found_module
);
2077 if (procname_ext
== NULL
) {
2078 /* If it's *still* null, we might have hit the
2079 * case where reading /proc/$pid/maps gives an
2080 * empty file for this user.
2082 procname_ext
= get_process_name_from_proc (pid
);
2085 g_slist_free (mods
);
2089 DEBUG ("%s: Process name is [%s]", __func__
,
2092 procname
= mono_unicode_from_external (procname_ext
, &bytes
);
2093 if (procname
== NULL
) {
2095 g_free (procname_ext
);
2101 /* Add the terminator */
2105 DEBUG ("%s: Size %d smaller than needed (%ld); truncating", __func__
, size
, bytes
);
2107 memcpy (basename
, procname
, size
);
2109 DEBUG ("%s: Size %d larger than needed (%ld)",
2110 __func__
, size
, bytes
);
2112 memcpy (basename
, procname
, bytes
);
2116 g_free (procname_ext
);
2125 GetModuleBaseName (gpointer process
, gpointer module
,
2126 gunichar2
*basename
, guint32 size
)
2128 return get_module_name (process
, module
, basename
, size
, TRUE
);
2132 GetModuleFileNameEx (gpointer process
, gpointer module
,
2133 gunichar2
*filename
, guint32 size
)
2135 return get_module_name (process
, module
, filename
, size
, FALSE
);
2139 GetModuleInformation (gpointer process
, gpointer module
,
2140 WapiModuleInfo
*modinfo
, guint32 size
)
2142 WapiHandle_process
*process_handle
;
2144 #if !defined(__OpenBSD__) && !defined(PLATFORM_MACOSX)
2147 GSList
*mods
= NULL
;
2148 WapiProcModule
*found_module
;
2151 gboolean ret
= FALSE
;
2152 char *proc_name
= NULL
;
2154 DEBUG ("%s: Getting module info, process handle %p module %p",
2155 __func__
, process
, module
);
2157 if (modinfo
== NULL
|| size
< sizeof (WapiModuleInfo
))
2160 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process
)) {
2161 pid
= (pid_t
)WAPI_HANDLE_TO_PID (process
);
2162 proc_name
= get_process_name_from_proc (pid
);
2164 process_handle
= lookup_process_handle (process
);
2165 if (!process_handle
) {
2166 DEBUG ("%s: Can't find process %p", __func__
,
2171 pid
= process_handle
->id
;
2172 proc_name
= g_strdup (process_handle
->proc_name
);
2175 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__) || defined(__HAIKU__)
2176 mods
= load_modules ();
2178 /* Look up the address in /proc/<pid>/maps */
2179 if ((fp
= open_process_map (pid
, "r")) == NULL
) {
2180 /* No /proc/<pid>/maps, so just return failure
2186 mods
= load_modules (fp
);
2189 count
= g_slist_length (mods
);
2191 /* If module != NULL compare the address.
2192 * If module == NULL we are looking for the main module.
2193 * The best we can do for now check it the module name end with the process name.
2195 for (i
= 0; i
< count
; i
++) {
2196 found_module
= (WapiProcModule
*)g_slist_nth_data (mods
, i
);
2198 ((module
== NULL
&& match_procname_to_modulename (proc_name
, found_module
->filename
)) ||
2199 (module
!= NULL
&& found_module
->address_start
== module
))) {
2200 modinfo
->lpBaseOfDll
= found_module
->address_start
;
2201 modinfo
->SizeOfImage
= (gsize
)(found_module
->address_end
) - (gsize
)(found_module
->address_start
);
2202 modinfo
->EntryPoint
= found_module
->address_offset
;
2206 free_procmodule (found_module
);
2209 g_slist_free (mods
);
2216 GetProcessWorkingSetSize (gpointer process
, size_t *min
, size_t *max
)
2218 WapiHandle_process
*process_handle
;
2220 if (min
== NULL
|| max
== NULL
)
2221 /* Not sure if w32 allows NULLs here or not */
2224 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process
))
2225 /* This is a pseudo handle, so just fail for now */
2228 process_handle
= lookup_process_handle (process
);
2229 if (!process_handle
) {
2230 DEBUG ("%s: Can't find process %p", __func__
, process
);
2235 *min
= process_handle
->min_working_set
;
2236 *max
= process_handle
->max_working_set
;
2242 SetProcessWorkingSetSize (gpointer process
, size_t min
, size_t max
)
2244 WapiHandle_process
*process_handle
;
2246 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process
))
2247 /* This is a pseudo handle, so just fail for now
2251 process_handle
= lookup_process_handle (process
);
2252 if (!process_handle
) {
2253 DEBUG ("%s: Can't find process %p", __func__
, process
);
2258 process_handle
->min_working_set
= min
;
2259 process_handle
->max_working_set
= max
;
2266 TerminateProcess (gpointer process
, gint32 exitCode
)
2268 WapiHandle_process
*process_handle
;
2273 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process
)) {
2274 /* This is a pseudo handle */
2275 pid
= (pid_t
)WAPI_HANDLE_TO_PID (process
);
2277 process_handle
= lookup_process_handle (process
);
2278 if (!process_handle
) {
2279 DEBUG ("%s: Can't find process %p", __func__
, process
);
2280 SetLastError (ERROR_INVALID_HANDLE
);
2283 pid
= process_handle
->id
;
2286 signo
= (exitCode
== -1) ? SIGKILL
: SIGTERM
;
2287 ret
= kill (pid
, signo
);
2291 SetLastError (ERROR_INVALID_PARAMETER
);
2294 SetLastError (ERROR_ACCESS_DENIED
);
2297 SetLastError (ERROR_PROC_NOT_FOUND
);
2300 SetLastError (ERROR_GEN_FAILURE
);
2308 GetPriorityClass (gpointer process
)
2310 #ifdef HAVE_GETPRIORITY
2311 WapiHandle_process
*process_handle
;
2315 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process
)) {
2316 /* This is a pseudo handle */
2317 pid
= (pid_t
)WAPI_HANDLE_TO_PID (process
);
2319 process_handle
= lookup_process_handle (process
);
2320 if (!process_handle
) {
2321 SetLastError (ERROR_INVALID_HANDLE
);
2324 pid
= process_handle
->id
;
2328 ret
= getpriority (PRIO_PROCESS
, pid
);
2329 if (ret
== -1 && errno
!= 0) {
2333 SetLastError (ERROR_ACCESS_DENIED
);
2336 SetLastError (ERROR_PROC_NOT_FOUND
);
2339 SetLastError (ERROR_GEN_FAILURE
);
2345 return NORMAL_PRIORITY_CLASS
;
2347 return REALTIME_PRIORITY_CLASS
;
2349 return HIGH_PRIORITY_CLASS
;
2351 return ABOVE_NORMAL_PRIORITY_CLASS
;
2353 return IDLE_PRIORITY_CLASS
;
2355 return BELOW_NORMAL_PRIORITY_CLASS
;
2357 return NORMAL_PRIORITY_CLASS
;
2359 SetLastError (ERROR_NOT_SUPPORTED
);
2365 SetPriorityClass (gpointer process
, guint32 priority_class
)
2367 #ifdef HAVE_SETPRIORITY
2368 WapiHandle_process
*process_handle
;
2373 if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process
)) {
2374 /* This is a pseudo handle */
2375 pid
= (pid_t
)WAPI_HANDLE_TO_PID (process
);
2377 process_handle
= lookup_process_handle (process
);
2378 if (!process_handle
) {
2379 SetLastError (ERROR_INVALID_HANDLE
);
2382 pid
= process_handle
->id
;
2385 switch (priority_class
) {
2386 case IDLE_PRIORITY_CLASS
:
2389 case BELOW_NORMAL_PRIORITY_CLASS
:
2392 case NORMAL_PRIORITY_CLASS
:
2395 case ABOVE_NORMAL_PRIORITY_CLASS
:
2398 case HIGH_PRIORITY_CLASS
:
2401 case REALTIME_PRIORITY_CLASS
:
2405 SetLastError (ERROR_INVALID_PARAMETER
);
2409 ret
= setpriority (PRIO_PROCESS
, pid
, prio
);
2414 SetLastError (ERROR_ACCESS_DENIED
);
2417 SetLastError (ERROR_PROC_NOT_FOUND
);
2420 SetLastError (ERROR_GEN_FAILURE
);
2426 SetLastError (ERROR_NOT_SUPPORTED
);
2432 mono_processes_cleanup (void)
2434 struct MonoProcess
*mp
;
2435 struct MonoProcess
*prev
= NULL
;
2436 GSList
*finished
= NULL
;
2438 gpointer unref_handle
;
2440 DEBUG ("%s", __func__
);
2442 /* Ensure we're not in here in multiple threads at once, nor recursive. */
2443 if (InterlockedCompareExchange (&mono_processes_cleaning_up
, 1, 0) != 0)
2446 for (mp
= mono_processes
; mp
; mp
= mp
->next
) {
2447 if (mp
->pid
== 0 && mp
->handle
) {
2448 /* This process has exited and we need to remove the artifical ref
2450 mono_mutex_lock (&mono_processes_mutex
);
2451 unref_handle
= mp
->handle
;
2453 mono_mutex_unlock (&mono_processes_mutex
);
2455 _wapi_handle_unref (unref_handle
);
2460 * Remove processes which exited from the mono_processes list.
2461 * We need to synchronize with the sigchld handler here, which runs
2462 * asynchronously. The handler requires that the mono_processes list
2465 mono_mutex_lock (&mono_processes_mutex
);
2467 mp
= mono_processes
;
2469 if (mp
->handle_count
== 0 && mp
->freeable
) {
2472 * This code can run parallel with the sigchld handler, but the
2473 * modifications it makes are safe.
2475 if (mp
== mono_processes
)
2476 mono_processes
= mp
->next
;
2478 prev
->next
= mp
->next
;
2479 finished
= g_slist_prepend (finished
, mp
);
2488 mono_memory_barrier ();
2490 for (l
= finished
; l
; l
= l
->next
) {
2492 * All the entries in the finished list are unlinked from mono_processes, and
2493 * they have the 'finished' flag set, which means the sigchld handler is done
2497 MONO_SEM_DESTROY (&mp
->exit_sem
);
2500 g_slist_free (finished
);
2502 mono_mutex_unlock (&mono_processes_mutex
);
2504 DEBUG ("%s done", __func__
);
2506 InterlockedDecrement (&mono_processes_cleaning_up
);
2510 process_close (gpointer handle
, gpointer data
)
2512 WapiHandle_process
*process_handle
;
2514 DEBUG ("%s", __func__
);
2516 process_handle
= (WapiHandle_process
*) data
;
2517 g_free (process_handle
->proc_name
);
2518 process_handle
->proc_name
= NULL
;
2519 if (process_handle
->mono_process
)
2520 InterlockedDecrement (&process_handle
->mono_process
->handle_count
);
2521 mono_processes_cleanup ();
2525 MONO_SIGNAL_HANDLER_FUNC (static, mono_sigchld_signal_handler
, (int _dummy
, siginfo_t
*info
, void *context
))
2529 struct MonoProcess
*p
;
2531 DEBUG ("SIG CHILD handler for pid: %i\n", info
->si_pid
);
2535 pid
= waitpid (-1, &status
, WNOHANG
);
2536 } while (pid
== -1 && errno
== EINTR
);
2541 DEBUG ("child ended: %i", pid
);
2544 * This can run concurrently with the code in the rest of this module.
2546 for (p
= mono_processes
; p
; p
= p
->next
) {
2547 if (p
->pid
== pid
) {
2552 p
->pid
= 0; /* this pid doesn't exist anymore, clear it */
2554 MONO_SEM_POST (&p
->exit_sem
);
2555 mono_memory_barrier ();
2556 /* Mark this as freeable, the pointer becomes invalid afterwards */
2561 DEBUG ("SIG CHILD handler: done looping.");
2567 process_add_sigchld_handler (void)
2570 struct sigaction sa
;
2572 sa
.sa_sigaction
= mono_sigchld_signal_handler
;
2573 sigemptyset (&sa
.sa_mask
);
2574 sa
.sa_flags
= SA_NOCLDSTOP
| SA_SIGINFO
;
2575 g_assert (sigaction (SIGCHLD
, &sa
, &previous_chld_sa
) != -1);
2576 DEBUG ("Added SIGCHLD handler");
2581 process_wait (gpointer handle
, guint32 timeout
, gboolean alertable
)
2583 WapiHandle_process
*process_handle
;
2588 struct MonoProcess
*mp
;
2590 /* FIXME: We can now easily wait on processes that aren't our own children,
2591 * but WaitFor*Object won't call us for pseudo handles. */
2592 g_assert ((GPOINTER_TO_UINT (handle
) & _WAPI_PROCESS_UNHANDLED
) != _WAPI_PROCESS_UNHANDLED
);
2594 DEBUG ("%s (%p, %u)", __func__
, handle
, timeout
);
2596 process_handle
= lookup_process_handle (handle
);
2597 if (!process_handle
) {
2598 g_warning ("%s: error looking up process handle %p", __func__
, handle
);
2602 if (process_handle
->exited
) {
2603 /* We've already done this one */
2604 DEBUG ("%s (%p, %u): Process already exited", __func__
, handle
, timeout
);
2605 return WAIT_OBJECT_0
;
2608 pid
= process_handle
->id
;
2610 DEBUG ("%s (%p, %u): PID: %d", __func__
, handle
, timeout
, pid
);
2612 /* We don't need to lock mono_processes here, the entry
2613 * has a handle_count > 0 which means it will not be freed. */
2614 mp
= process_handle
->mono_process
;
2617 start
= mono_msec_ticks ();
2621 if (timeout
!= INFINITE
) {
2622 DEBUG ("%s (%p, %u): waiting on semaphore for %li ms...",
2623 __func__
, handle
, timeout
, (timeout
- (now
- start
)));
2625 ret
= MONO_SEM_TIMEDWAIT_ALERTABLE (&mp
->exit_sem
, (timeout
- (now
- start
)), alertable
);
2627 DEBUG ("%s (%p, %u): waiting on semaphore forever...",
2628 __func__
, handle
, timeout
);
2629 ret
= MONO_SEM_WAIT_ALERTABLE (&mp
->exit_sem
, alertable
);
2632 if (ret
== -1 && errno
!= EINTR
&& errno
!= ETIMEDOUT
) {
2633 DEBUG ("%s (%p, %u): sem_timedwait failure: %s",
2634 __func__
, handle
, timeout
, g_strerror (errno
));
2635 /* Should we return a failure here? */
2639 /* Success, process has exited */
2640 MONO_SEM_POST (&mp
->exit_sem
);
2645 DEBUG ("%s (%p, %u): WAIT_TIMEOUT (timeout = 0)", __func__
, handle
, timeout
);
2646 return WAIT_TIMEOUT
;
2649 now
= mono_msec_ticks ();
2650 if (now
- start
>= timeout
) {
2651 DEBUG ("%s (%p, %u): WAIT_TIMEOUT", __func__
, handle
, timeout
);
2652 return WAIT_TIMEOUT
;
2655 if (alertable
&& _wapi_thread_cur_apc_pending ()) {
2656 DEBUG ("%s (%p, %u): WAIT_IO_COMPLETION", __func__
, handle
, timeout
);
2657 return WAIT_IO_COMPLETION
;
2661 /* Process must have exited */
2662 DEBUG ("%s (%p, %u): Waited successfully", __func__
, handle
, timeout
);
2664 ret
= _wapi_handle_lock_shared_handles ();
2665 g_assert (ret
== 0);
2667 status
= mp
? mp
->status
: 0;
2668 if (WIFSIGNALED (status
))
2669 process_handle
->exitstatus
= 128 + WTERMSIG (status
);
2671 process_handle
->exitstatus
= WEXITSTATUS (status
);
2672 _wapi_time_t_to_filetime (time (NULL
), &process_handle
->exit_time
);
2674 process_handle
->exited
= TRUE
;
2676 DEBUG ("%s (%p, %u): Setting pid %d signalled, exit status %d",
2677 __func__
, handle
, timeout
, process_handle
->id
, process_handle
->exitstatus
);
2679 _wapi_handle_set_signal_state (handle
, TRUE
, TRUE
);
2681 _wapi_handle_unlock_shared_handles ();
2683 return WAIT_OBJECT_0
;
2687 wapi_processes_cleanup (void)
2689 g_free (cli_launcher
);