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__)
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_read_lock = 0;
152 static volatile gint32 mono_processes_cleaning_up = 0;
153 static mono_mutex_t mono_processes_mutex;
154 static void mono_processes_cleanup (void);
156 static gpointer current_process;
157 static char *cli_launcher;
159 static WapiHandle_process *
160 lookup_process_handle (gpointer handle)
162 WapiHandle_process *process_data;
165 ret = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
166 (gpointer *)&process_data);
172 /* Check if a pid is valid - i.e. if a process exists with this pid. */
174 is_pid_valid (pid_t pid)
176 gboolean result = FALSE;
178 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__)
179 if (((kill(pid, 0) == 0) || (errno == EPERM)) && pid != 0)
181 #elif defined(__HAIKU__)
183 if (get_team_info ((team_id)pid, &teamInfo) == B_OK)
186 char *dir = g_strdup_printf ("/proc/%d", pid);
187 if (!access (dir, F_OK))
196 process_set_defaults (WapiHandle_process *process_handle)
198 /* These seem to be the defaults on w2k */
199 process_handle->min_working_set = 204800;
200 process_handle->max_working_set = 1413120;
202 _wapi_time_t_to_filetime (time (NULL), &process_handle->create_time);
206 len16 (const gunichar2 *str)
217 utf16_concat (const gunichar2 *first, ...)
224 va_start (args, first);
225 total += len16 (first);
226 for (s = va_arg (args, gunichar2 *); s != NULL; s = va_arg(args, gunichar2 *)){
231 ret = g_new (gunichar2, total + 1);
237 for (s = first; *s != 0; s++)
239 va_start (args, first);
240 for (s = va_arg (args, gunichar2 *); s != NULL; s = va_arg (args, gunichar2 *)){
243 for (p = s; *p != 0; p++)
251 static const gunichar2 utf16_space_bytes [2] = { 0x20, 0 };
252 static const gunichar2 *utf16_space = utf16_space_bytes;
253 static const gunichar2 utf16_quote_bytes [2] = { 0x22, 0 };
254 static const gunichar2 *utf16_quote = utf16_quote_bytes;
259 print_utf16 (gunichar2 *str)
263 res = g_utf16_to_utf8 (str, -1, NULL, NULL, NULL);
264 g_print ("%s\n", res);
269 /* Implemented as just a wrapper around CreateProcess () */
271 ShellExecuteEx (WapiShellExecuteInfo *sei)
274 WapiProcessInformation process_info;
278 /* w2k just segfaults here, but we can do better than
281 SetLastError (ERROR_INVALID_PARAMETER);
285 if (sei->lpFile == NULL)
286 /* w2k returns TRUE for this, for some reason. */
289 /* Put both executable and parameters into the second argument
290 * to CreateProcess (), so it searches $PATH. The conversion
291 * into and back out of utf8 is because there is no
292 * g_strdup_printf () equivalent for gunichar2 :-(
294 args = utf16_concat (utf16_quote, sei->lpFile, utf16_quote, sei->lpParameters == NULL ? NULL : utf16_space, sei->lpParameters, NULL);
296 SetLastError (ERROR_INVALID_DATA);
299 ret = CreateProcess (NULL, args, NULL, NULL, TRUE,
300 CREATE_UNICODE_ENVIRONMENT, NULL,
301 sei->lpDirectory, NULL, &process_info);
304 if (!ret && GetLastError () == ERROR_OUTOFMEMORY)
308 static char *handler;
309 static gunichar2 *handler_utf16;
311 if (handler_utf16 == (gunichar2 *)-1)
314 #ifdef PLATFORM_MACOSX
315 handler = g_strdup ("/usr/bin/open");
318 * On Linux, try: xdg-open, the FreeDesktop standard way of doing it,
319 * if that fails, try to use gnome-open, then kfmclient
321 handler = g_find_program_in_path ("xdg-open");
322 if (handler == NULL){
323 handler = g_find_program_in_path ("gnome-open");
324 if (handler == NULL){
325 handler = g_find_program_in_path ("kfmclient");
326 if (handler == NULL){
327 handler_utf16 = (gunichar2 *) -1;
330 /* kfmclient needs exec argument */
332 handler = g_strconcat (old, " exec",
339 handler_utf16 = g_utf8_to_utf16 (handler, -1, NULL, NULL, NULL);
342 /* Put quotes around the filename, in case it's a url
343 * that contains #'s (CreateProcess() calls
344 * g_shell_parse_argv(), which deliberately throws
345 * away anything after an unquoted #). Fixes bug
348 args = utf16_concat (handler_utf16, utf16_space, utf16_quote,
349 sei->lpFile, utf16_quote,
350 sei->lpParameters == NULL ? NULL : utf16_space,
351 sei->lpParameters, NULL);
353 SetLastError (ERROR_INVALID_DATA);
356 ret = CreateProcess (NULL, args, NULL, NULL, TRUE,
357 CREATE_UNICODE_ENVIRONMENT, NULL,
358 sei->lpDirectory, NULL, &process_info);
361 if (GetLastError () != ERROR_OUTOFMEMORY)
362 SetLastError (ERROR_INVALID_DATA);
365 /* Shell exec should not return a process handle when it spawned a GUI thing, like a browser. */
366 CloseHandle (process_info.hProcess);
367 process_info.hProcess = NULL;
370 if (sei->fMask & SEE_MASK_NOCLOSEPROCESS)
371 sei->hProcess = process_info.hProcess;
373 CloseHandle (process_info.hProcess);
379 is_managed_binary (const char *filename)
381 int original_errno = errno;
382 #if defined(HAVE_LARGE_FILE_SUPPORT) && defined(O_LARGEFILE)
383 int file = open (filename, O_RDONLY | O_LARGEFILE);
385 int file = open (filename, O_RDONLY);
388 unsigned char buffer[8];
389 off_t file_size, optional_header_offset;
390 off_t pe_header_offset;
391 gboolean managed = FALSE;
393 guint32 first_word, second_word;
395 /* If we are unable to open the file, then we definitely
396 * can't say that it is managed. The child mono process
397 * probably wouldn't be able to open it anyway.
400 errno = original_errno;
404 /* Retrieve the length of the file for future sanity checks. */
405 file_size = lseek (file, 0, SEEK_END);
406 lseek (file, 0, SEEK_SET);
408 /* We know we need to read a header field at offset 60. */
412 num_read = read (file, buffer, 2);
414 if ((num_read != 2) || (buffer[0] != 'M') || (buffer[1] != 'Z'))
417 new_offset = lseek (file, 60, SEEK_SET);
419 if (new_offset != 60)
422 num_read = read (file, buffer, 4);
426 pe_header_offset = buffer[0]
431 if (pe_header_offset + 24 > file_size)
434 new_offset = lseek (file, pe_header_offset, SEEK_SET);
436 if (new_offset != pe_header_offset)
439 num_read = read (file, buffer, 4);
441 if ((num_read != 4) || (buffer[0] != 'P') || (buffer[1] != 'E') || (buffer[2] != 0) || (buffer[3] != 0))
445 * Verify that the header we want in the optional header data
446 * is present in this binary.
448 new_offset = lseek (file, pe_header_offset + 20, SEEK_SET);
450 if (new_offset != pe_header_offset + 20)
453 num_read = read (file, buffer, 2);
455 if ((num_read != 2) || ((buffer[0] | (buffer[1] << 8)) < 216))
458 /* Read the CLR header address and size fields. These will be
459 * zero if the binary is not managed.
461 optional_header_offset = pe_header_offset + 24;
462 new_offset = lseek (file, optional_header_offset + 208, SEEK_SET);
464 if (new_offset != optional_header_offset + 208)
467 num_read = read (file, buffer, 8);
469 /* We are not concerned with endianness, only with
470 * whether it is zero or not.
472 first_word = *(guint32 *)&buffer[0];
473 second_word = *(guint32 *)&buffer[4];
475 if ((num_read != 8) || (first_word == 0) || (second_word == 0))
482 errno = original_errno;
487 CreateProcessWithLogonW (const gunichar2 *username,
488 const gunichar2 *domain,
489 const gunichar2 *password,
490 const guint32 logonFlags,
491 const gunichar2 *appname,
492 const gunichar2 *cmdline,
493 guint32 create_flags,
495 const gunichar2 *cwd,
496 WapiStartupInfo *startup,
497 WapiProcessInformation *process_info)
499 /* FIXME: use user information */
500 return CreateProcess (appname, cmdline, NULL, NULL, FALSE, create_flags, env, cwd, startup, process_info);
504 is_readable (const char *prog)
507 if (access (prog, R_OK) != 0)
509 if (stat (prog, &buf))
511 if (S_ISREG (buf.st_mode))
517 is_executable (const char *prog)
520 if (access (prog, X_OK) != 0)
522 if (stat (prog, &buf))
524 if (S_ISREG (buf.st_mode))
530 switch_dir_separators (char *path)
532 size_t i, pathLength = strlen(path);
534 /* Turn all the slashes round the right way, except for \' */
535 /* There are probably other characters that need to be excluded as well. */
536 for (i = 0; i < pathLength; i++) {
537 if (path[i] == '\\' && i < pathLength - 1 && path[i+1] != '\'' )
542 gboolean CreateProcess (const gunichar2 *appname, const gunichar2 *cmdline,
543 WapiSecurityAttributes *process_attrs G_GNUC_UNUSED,
544 WapiSecurityAttributes *thread_attrs G_GNUC_UNUSED,
545 gboolean inherit_handles, guint32 create_flags,
546 gpointer new_environ, const gunichar2 *cwd,
547 WapiStartupInfo *startup,
548 WapiProcessInformation *process_info)
550 char *cmd = NULL, *prog = NULL, *full_prog = NULL, *args = NULL, *args_after_prog = NULL;
551 char *dir = NULL, **env_strings = NULL, **argv = NULL;
552 guint32 i, env_count = 0;
553 gboolean ret = FALSE;
555 WapiHandle_process process_handle = {0}, *process_handle_data;
557 int in_fd, out_fd, err_fd;
560 int startup_pipe [2] = {-1, -1};
562 struct MonoProcess *mono_process;
563 gboolean fork_failed = FALSE;
565 mono_once (&process_sig_chld_once, process_add_sigchld_handler);
567 /* appname and cmdline specify the executable and its args:
569 * If appname is not NULL, it is the name of the executable.
570 * Otherwise the executable is the first token in cmdline.
572 * Executable searching:
574 * If appname is not NULL, it can specify the full path and
575 * file name, or else a partial name and the current directory
576 * will be used. There is no additional searching.
578 * If appname is NULL, the first whitespace-delimited token in
579 * cmdline is used. If the name does not contain a full
580 * directory path, the search sequence is:
582 * 1) The directory containing the current process
583 * 2) The current working directory
584 * 3) The windows system directory (Ignored)
585 * 4) The windows directory (Ignored)
588 * Just to make things more interesting, tokens can contain
589 * white space if they are surrounded by quotation marks. I'm
590 * beginning to understand just why windows apps are generally
591 * so crap, with an API like this :-(
593 if (appname != NULL) {
594 cmd = mono_unicode_to_external (appname);
596 DEBUG ("%s: unicode conversion returned NULL",
599 SetLastError (ERROR_PATH_NOT_FOUND);
603 switch_dir_separators(cmd);
606 if (cmdline != NULL) {
607 args = mono_unicode_to_external (cmdline);
609 DEBUG ("%s: unicode conversion returned NULL", __func__);
611 SetLastError (ERROR_PATH_NOT_FOUND);
617 dir = mono_unicode_to_external (cwd);
619 DEBUG ("%s: unicode conversion returned NULL", __func__);
621 SetLastError (ERROR_PATH_NOT_FOUND);
625 /* Turn all the slashes round the right way */
626 switch_dir_separators(dir);
630 /* We can't put off locating the executable any longer :-( */
633 if (g_ascii_isalpha (cmd[0]) && (cmd[1] == ':')) {
634 /* Strip off the drive letter. I can't
635 * believe that CP/M holdover is still
638 g_memmove (cmd, cmd+2, strlen (cmd)-2);
639 cmd[strlen (cmd)-2] = '\0';
642 unquoted = g_shell_unquote (cmd, NULL);
643 if (unquoted[0] == '/') {
644 /* Assume full path given */
645 prog = g_strdup (unquoted);
647 /* Executable existing ? */
648 if (!is_readable (prog)) {
649 DEBUG ("%s: Couldn't find executable %s",
652 SetLastError (ERROR_FILE_NOT_FOUND);
656 /* Search for file named by cmd in the current
659 char *curdir = g_get_current_dir ();
661 prog = g_strdup_printf ("%s/%s", curdir, unquoted);
664 /* And make sure it's readable */
665 if (!is_readable (prog)) {
666 DEBUG ("%s: Couldn't find executable %s",
669 SetLastError (ERROR_FILE_NOT_FOUND);
675 args_after_prog = args;
680 /* Dig out the first token from args, taking quotation
684 /* First, strip off all leading whitespace */
685 args = g_strchug (args);
687 /* args_after_prog points to the contents of args
688 * after token has been set (otherwise argv[0] is
691 args_after_prog = args;
693 /* Assume the opening quote will always be the first
696 if (args[0] == '\"' || args [0] == '\'') {
698 for (i = 1; args[i] != '\0' && args[i] != quote; i++);
699 if (args [i + 1] == '\0' || g_ascii_isspace (args[i+1])) {
700 /* We found the first token */
701 token = g_strndup (args+1, i-1);
702 args_after_prog = g_strchug (args + i + 1);
704 /* Quotation mark appeared in the
705 * middle of the token. Just give the
706 * whole first token, quotes and all,
713 /* No quote mark, or malformed */
714 for (i = 0; args[i] != '\0'; i++) {
715 if (g_ascii_isspace (args[i])) {
716 token = g_strndup (args, i);
717 args_after_prog = args + i + 1;
723 if (token == NULL && args[0] != '\0') {
724 /* Must be just one token in the string */
725 token = g_strdup (args);
726 args_after_prog = NULL;
731 DEBUG ("%s: Couldn't find what to exec", __func__);
733 SetLastError (ERROR_PATH_NOT_FOUND);
737 /* Turn all the slashes round the right way. Only for
740 switch_dir_separators(token);
742 if (g_ascii_isalpha (token[0]) && (token[1] == ':')) {
743 /* Strip off the drive letter. I can't
744 * believe that CP/M holdover is still
747 g_memmove (token, token+2, strlen (token)-2);
748 token[strlen (token)-2] = '\0';
751 if (token[0] == '/') {
752 /* Assume full path given */
753 prog = g_strdup (token);
755 /* Executable existing ? */
756 if (!is_readable (prog)) {
757 DEBUG ("%s: Couldn't find executable %s",
760 SetLastError (ERROR_FILE_NOT_FOUND);
764 char *curdir = g_get_current_dir ();
766 /* FIXME: Need to record the directory
767 * containing the current process, and check
768 * that for the new executable as the first
772 prog = g_strdup_printf ("%s/%s", curdir, token);
775 /* I assume X_OK is the criterion to use,
778 * X_OK is too strict *if* the target is a CLR binary
780 if (!is_readable (prog)) {
782 prog = g_find_program_in_path (token);
784 DEBUG ("%s: Couldn't find executable %s", __func__, token);
787 SetLastError (ERROR_FILE_NOT_FOUND);
796 DEBUG ("%s: Exec prog [%s] args [%s]", __func__, prog,
799 /* Check for CLR binaries; if found, we will try to invoke
800 * them using the same mono binary that started us.
802 if (is_managed_binary (prog)) {
803 gunichar2 *newapp = NULL, *newcmd;
807 newapp = mono_unicode_from_external (cli_launcher, &bytes_ignored);
809 newapp = mono_unicode_from_external ("mono", &bytes_ignored);
811 if (newapp != NULL) {
812 if (appname != NULL) {
813 newcmd = utf16_concat (newapp, utf16_space,
814 appname, utf16_space,
817 newcmd = utf16_concat (newapp, utf16_space,
821 g_free ((gunichar2 *)newapp);
823 if (newcmd != NULL) {
824 ret = CreateProcess (NULL, newcmd,
828 create_flags, new_environ,
832 g_free ((gunichar2 *)newcmd);
838 if (!is_executable (prog)) {
839 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 struct MonoProcess *candidate = NULL;
2437 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 mp = mono_processes;
2447 while (mp != NULL) {
2448 if (mp->pid == 0 && mp->handle != NULL) {
2449 /* This process has exited and we need to remove the artifical ref
2451 mono_mutex_lock (&mono_processes_mutex);
2452 unref_handle = mp->handle;
2454 mono_mutex_unlock (&mono_processes_mutex);
2456 _wapi_handle_unref (unref_handle);
2463 * Remove processes which exited from the mono_processes list.
2464 * We need to synchronize with the sigchld handler here, which runs
2465 * asynchronously. The handler requires that the mono_processes list
2468 mp = mono_processes;
2470 while (mp != NULL) {
2471 if ((mp->handle_count == 0 && mp->pid == 0) || candidate != NULL) {
2473 _wapi_handle_spin (spin);
2477 /* We've found a candidate */
2478 mono_mutex_lock (&mono_processes_mutex);
2480 * This code can run parallel with the sigchld handler, but the
2481 * modifications it makes are safe.
2483 if (candidate == NULL) {
2485 if (mp == mono_processes) {
2486 mono_processes = mp->next;
2488 prev->next = mp->next;
2493 /* It's still safe to traverse the structure.*/
2494 mono_memory_barrier ();
2496 if (mono_processes_read_lock != 0) {
2497 /* The sigchld handler is watching us. Spin a bit and try again */
2500 } else if (spin >= 8) {
2501 /* Just give up for now */
2502 mono_mutex_unlock (&mono_processes_mutex);
2506 /* We've modified the list of processes, and we know the sigchld handler
2507 * isn't executing, so even if it executes at any moment, it'll see the
2508 * new version of the list. So now we can free the candidate. */
2509 DEBUG ("%s: freeing candidate %p", __func__, candidate);
2510 mp = candidate->next;
2511 MONO_SEM_DESTROY (&candidate->exit_sem);
2516 mono_mutex_unlock (&mono_processes_mutex);
2525 DEBUG ("%s done", __func__);
2527 InterlockedDecrement (&mono_processes_cleaning_up);
2531 process_close (gpointer handle, gpointer data)
2533 WapiHandle_process *process_handle;
2535 DEBUG ("%s", __func__);
2537 process_handle = (WapiHandle_process *) data;
2538 g_free (process_handle->proc_name);
2539 process_handle->proc_name = NULL;
2540 if (process_handle->mono_process)
2541 InterlockedDecrement (&process_handle->mono_process->handle_count);
2542 mono_processes_cleanup ();
2546 MONO_SIGNAL_HANDLER_FUNC (static, mono_sigchld_signal_handler, (int _dummy, siginfo_t *info, void *context))
2550 struct MonoProcess *p;
2552 DEBUG ("SIG CHILD handler for pid: %i\n", info->si_pid);
2554 InterlockedIncrement (&mono_processes_read_lock);
2558 pid = waitpid (-1, &status, WNOHANG);
2559 } while (pid == -1 && errno == EINTR);
2564 DEBUG ("child ended: %i", pid);
2567 if (p->pid == pid) {
2568 p->pid = 0; /* this pid doesn't exist anymore, clear it */
2570 MONO_SEM_POST (&p->exit_sem);
2577 InterlockedDecrement (&mono_processes_read_lock);
2579 DEBUG ("SIG CHILD handler: done looping.");
2585 process_add_sigchld_handler (void)
2588 struct sigaction sa;
2590 sa.sa_sigaction = mono_sigchld_signal_handler;
2591 sigemptyset (&sa.sa_mask);
2592 sa.sa_flags = SA_NOCLDSTOP | SA_SIGINFO;
2593 g_assert (sigaction (SIGCHLD, &sa, &previous_chld_sa) != -1);
2594 DEBUG ("Added SIGCHLD handler");
2599 process_wait (gpointer handle, guint32 timeout, gboolean alertable)
2601 WapiHandle_process *process_handle;
2606 struct MonoProcess *mp;
2608 /* FIXME: We can now easily wait on processes that aren't our own children,
2609 * but WaitFor*Object won't call us for pseudo handles. */
2610 g_assert ((GPOINTER_TO_UINT (handle) & _WAPI_PROCESS_UNHANDLED) != _WAPI_PROCESS_UNHANDLED);
2612 DEBUG ("%s (%p, %u)", __func__, handle, timeout);
2614 process_handle = lookup_process_handle (handle);
2615 if (!process_handle) {
2616 g_warning ("%s: error looking up process handle %p", __func__, handle);
2620 if (process_handle->exited) {
2621 /* We've already done this one */
2622 DEBUG ("%s (%p, %u): Process already exited", __func__, handle, timeout);
2623 return WAIT_OBJECT_0;
2626 pid = process_handle->id;
2628 DEBUG ("%s (%p, %u): PID: %d", __func__, handle, timeout, pid);
2630 /* We don't need to lock mono_processes here, the entry
2631 * has a handle_count > 0 which means it will not be freed. */
2632 mp = process_handle->mono_process;
2635 start = mono_msec_ticks ();
2639 if (timeout != INFINITE) {
2640 DEBUG ("%s (%p, %u): waiting on semaphore for %li ms...",
2641 __func__, handle, timeout, (timeout - (now - start)));
2643 ret = MONO_SEM_TIMEDWAIT_ALERTABLE (&mp->exit_sem, (timeout - (now - start)), alertable);
2645 DEBUG ("%s (%p, %u): waiting on semaphore forever...",
2646 __func__, handle, timeout);
2647 ret = MONO_SEM_WAIT_ALERTABLE (&mp->exit_sem, alertable);
2650 if (ret == -1 && errno != EINTR && errno != ETIMEDOUT) {
2651 DEBUG ("%s (%p, %u): sem_timedwait failure: %s",
2652 __func__, handle, timeout, g_strerror (errno));
2653 /* Should we return a failure here? */
2657 /* Success, process has exited */
2658 MONO_SEM_POST (&mp->exit_sem);
2663 DEBUG ("%s (%p, %u): WAIT_TIMEOUT (timeout = 0)", __func__, handle, timeout);
2664 return WAIT_TIMEOUT;
2667 now = mono_msec_ticks ();
2668 if (now - start >= timeout) {
2669 DEBUG ("%s (%p, %u): WAIT_TIMEOUT", __func__, handle, timeout);
2670 return WAIT_TIMEOUT;
2673 if (alertable && _wapi_thread_cur_apc_pending ()) {
2674 DEBUG ("%s (%p, %u): WAIT_IO_COMPLETION", __func__, handle, timeout);
2675 return WAIT_IO_COMPLETION;
2679 /* Process must have exited */
2680 DEBUG ("%s (%p, %u): Waited successfully", __func__, handle, timeout);
2682 ret = _wapi_handle_lock_shared_handles ();
2683 g_assert (ret == 0);
2685 status = mp ? mp->status : 0;
2686 if (WIFSIGNALED (status))
2687 process_handle->exitstatus = 128 + WTERMSIG (status);
2689 process_handle->exitstatus = WEXITSTATUS (status);
2690 _wapi_time_t_to_filetime (time (NULL), &process_handle->exit_time);
2692 process_handle->exited = TRUE;
2694 DEBUG ("%s (%p, %u): Setting pid %d signalled, exit status %d",
2695 __func__, handle, timeout, process_handle->id, process_handle->exitstatus);
2697 _wapi_handle_set_signal_state (handle, TRUE, TRUE);
2699 _wapi_handle_unlock_shared_handles ();
2701 return WAIT_OBJECT_0;
2705 wapi_processes_cleanup (void)
2707 g_free (cli_launcher);