2010-03-30 Zoltan Varga <vargaz@gmail.com>
[mono/afaerber.git] / mono / io-layer / processes.c
blobb5917161551c6e7bbdf384b2ff0c62bf11c6141e
1 /*
2 * processes.c: Process handles
4 * Author:
5 * Dick Porter (dick@ximian.com)
7 * (C) 2002-2006 Novell, Inc.
8 */
10 #include <config.h>
11 #include <glib.h>
12 #include <stdio.h>
13 #include <string.h>
14 #include <pthread.h>
15 #include <sched.h>
16 #include <sys/time.h>
17 #include <errno.h>
18 #include <sys/types.h>
19 #include <sys/stat.h>
20 #include <unistd.h>
21 #include <signal.h>
22 #include <sys/wait.h>
23 #include <sys/time.h>
24 #include <sys/resource.h>
25 #include <fcntl.h>
26 #include <sys/param.h>
27 #include <ctype.h>
29 #ifdef HAVE_SYS_MKDEV_H
30 #include <sys/mkdev.h>
31 #endif
33 /* sys/resource.h (for rusage) is required when using osx 10.3 (but not 10.4) */
34 #ifdef __APPLE__
35 #include <sys/resource.h>
36 #endif
38 #ifdef PLATFORM_MACOSX
39 #include <sys/proc.h>
40 #include <sys/sysctl.h>
41 #include <sys/utsname.h>
42 #endif
44 #ifdef PLATFORM_SOLARIS
45 /* procfs.h cannot be included if this define is set, but it seems to work fine if it is undefined */
46 #if _FILE_OFFSET_BITS == 64
47 #undef _FILE_OFFSET_BITS
48 #include <procfs.h>
49 #define _FILE_OFFSET_BITS 64
50 #else
51 #include <procfs.h>
52 #endif
53 #endif
55 #include <mono/io-layer/wapi.h>
56 #include <mono/io-layer/wapi-private.h>
57 #include <mono/io-layer/handles-private.h>
58 #include <mono/io-layer/misc-private.h>
59 #include <mono/io-layer/mono-mutex.h>
60 #include <mono/io-layer/process-private.h>
61 #include <mono/io-layer/threads.h>
62 #include <mono/utils/strenc.h>
63 #include <mono/utils/mono-path.h>
64 #include <mono/io-layer/timefuncs-private.h>
66 /* The process' environment strings */
67 #ifdef __APPLE__
68 /* Apple defines this in crt_externs.h but doesn't provide that header for
69 * arm-apple-darwin9. We'll manually define the symbol on Apple as it does
70 * in fact exist on all implementations (so far)
72 gchar ***_NSGetEnviron(void);
73 #define environ (*_NSGetEnviron())
74 #else
75 extern char **environ;
76 #endif
78 #undef DEBUG
80 static guint32 process_wait (gpointer handle, guint32 timeout);
82 static FILE *
83 open_process_map (int pid, const char *mode);
85 struct _WapiHandleOps _wapi_process_ops = {
86 NULL, /* close_shared */
87 NULL, /* signal */
88 NULL, /* own */
89 NULL, /* is_owned */
90 process_wait, /* special_wait */
91 NULL /* prewait */
94 static mono_once_t process_current_once=MONO_ONCE_INIT;
95 static gpointer current_process=NULL;
97 static mono_once_t process_ops_once=MONO_ONCE_INIT;
99 static void process_ops_init (void)
101 _wapi_handle_register_capabilities (WAPI_HANDLE_PROCESS,
102 WAPI_HANDLE_CAP_WAIT |
103 WAPI_HANDLE_CAP_SPECIAL_WAIT);
106 static gboolean process_set_termination_details (gpointer handle, int status)
108 struct _WapiHandle_process *process_handle;
109 gboolean ok;
110 int thr_ret;
112 g_assert ((GPOINTER_TO_UINT (handle) & _WAPI_PROCESS_UNHANDLED) != _WAPI_PROCESS_UNHANDLED);
114 ok = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
115 (gpointer *)&process_handle);
116 if (ok == FALSE) {
117 g_warning ("%s: error looking up process handle %p",
118 __func__, handle);
119 return(FALSE);
122 thr_ret = _wapi_handle_lock_shared_handles ();
123 g_assert (thr_ret == 0);
125 if (WIFSIGNALED(status)) {
126 process_handle->exitstatus = 128 + WTERMSIG(status);
127 } else {
128 process_handle->exitstatus = WEXITSTATUS(status);
130 _wapi_time_t_to_filetime (time(NULL), &process_handle->exit_time);
132 /* Don't set process_handle->waited here, it needs to only
133 * happen in the parent when wait() has been called.
136 #ifdef DEBUG
137 g_message ("%s: Setting handle %p pid %d signalled, exit status %d",
138 __func__, handle, process_handle->id,
139 process_handle->exitstatus);
140 #endif
142 _wapi_shared_handle_set_signal_state (handle, TRUE);
144 _wapi_handle_unlock_shared_handles ();
146 /* Drop the reference we hold so we have somewhere to store
147 * the exit details, now the process has in fact exited
149 _wapi_handle_unref (handle);
151 return (ok);
154 /* See if any child processes have terminated and wait() for them,
155 * updating process handle info. This function is called from the
156 * collection thread every few seconds.
158 static gboolean waitfor_pid (gpointer test, gpointer user_data)
160 struct _WapiHandle_process *process;
161 gboolean ok;
162 int status;
163 pid_t ret;
165 g_assert ((GPOINTER_TO_UINT (test) & _WAPI_PROCESS_UNHANDLED) != _WAPI_PROCESS_UNHANDLED);
167 ok = _wapi_lookup_handle (test, WAPI_HANDLE_PROCESS,
168 (gpointer *)&process);
169 if (ok == FALSE) {
170 /* The handle must have been too old and was reaped */
171 return (FALSE);
174 if (process->waited) {
175 /* We've already done this one */
176 return(FALSE);
179 do {
180 ret = waitpid (process->id, &status, WNOHANG);
181 } while (errno == EINTR);
183 if (ret <= 0) {
184 /* Process not ready for wait */
185 #ifdef DEBUG
186 g_message ("%s: Process %d not ready for waiting for: %s",
187 __func__, process->id, g_strerror (errno));
188 #endif
190 return (FALSE);
193 #ifdef DEBUG
194 g_message ("%s: Process %d finished", __func__, ret);
195 #endif
197 process->waited = TRUE;
199 *(int *)user_data = status;
201 return (TRUE);
204 void _wapi_process_reap (void)
206 gpointer proc;
207 int status;
209 #ifdef DEBUG
210 g_message ("%s: Reaping child processes", __func__);
211 #endif
213 do {
214 proc = _wapi_search_handle (WAPI_HANDLE_PROCESS, waitfor_pid,
215 &status, NULL, FALSE);
216 if (proc != NULL) {
217 #ifdef DEBUG
218 g_message ("%s: process handle %p exit code %d",
219 __func__, proc, status);
220 #endif
222 process_set_termination_details (proc, status);
224 /* _wapi_search_handle adds a reference, so
225 * drop it here
227 _wapi_handle_unref (proc);
229 } while (proc != NULL);
232 /* Limitations: This can only wait for processes that are our own
233 * children. Fixing this means resurrecting a daemon helper to manage
234 * processes.
236 static guint32 process_wait (gpointer handle, guint32 timeout)
238 struct _WapiHandle_process *process_handle;
239 gboolean ok;
240 pid_t pid, ret;
241 int status;
243 g_assert ((GPOINTER_TO_UINT (handle) & _WAPI_PROCESS_UNHANDLED) != _WAPI_PROCESS_UNHANDLED);
245 #ifdef DEBUG
246 g_message ("%s: Waiting for process %p", __func__, handle);
247 #endif
249 ok = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
250 (gpointer *)&process_handle);
251 if (ok == FALSE) {
252 g_warning ("%s: error looking up process handle %p", __func__,
253 handle);
254 return(WAIT_FAILED);
257 if (process_handle->waited) {
258 /* We've already done this one */
259 #ifdef DEBUG
260 g_message ("%s: Process %p already signalled", __func__,
261 handle);
262 #endif
264 return (WAIT_OBJECT_0);
267 pid = process_handle->id;
269 #ifdef DEBUG
270 g_message ("%s: PID is %d, timeout %d", __func__, pid, timeout);
271 #endif
273 if (timeout == INFINITE) {
274 if (pid == _wapi_getpid ()) {
275 do {
276 Sleep (10000);
277 } while(1);
278 } else {
279 while ((ret = waitpid (pid, &status, 0)) != pid) {
280 if (ret == (pid_t)-1 && errno != EINTR) {
281 return(WAIT_FAILED);
285 } else if (timeout == 0) {
286 /* Just poll */
287 ret = waitpid (pid, &status, WNOHANG);
288 if (ret != pid) {
289 return (WAIT_TIMEOUT);
291 } else {
292 /* Poll in a loop */
293 if (pid == _wapi_getpid ()) {
294 Sleep (timeout);
295 return(WAIT_TIMEOUT);
296 } else {
297 do {
298 ret = waitpid (pid, &status, WNOHANG);
299 #ifdef DEBUG
300 g_message ("%s: waitpid returns: %d, timeout is %d", __func__, ret, timeout);
301 #endif
303 if (ret == pid) {
304 break;
305 } else if (ret == (pid_t)-1 &&
306 errno != EINTR) {
307 #ifdef DEBUG
308 g_message ("%s: waitpid failure: %s",
309 __func__,
310 g_strerror (errno));
311 #endif
313 if (errno == ECHILD &&
314 process_handle->waited) {
315 /* The background
316 * process reaper must
317 * have got this one
319 #ifdef DEBUG
320 g_message ("%s: Process %p already reaped", __func__, handle);
321 #endif
323 return(WAIT_OBJECT_0);
324 } else {
325 return(WAIT_FAILED);
329 _wapi_handle_spin (100);
330 timeout -= 100;
331 } while (timeout > 0);
334 if (timeout <= 0) {
335 return(WAIT_TIMEOUT);
339 /* Process must have exited */
340 #ifdef DEBUG
341 g_message ("%s: Wait done, status %d", __func__, status);
342 #endif
344 ok = process_set_termination_details (handle, status);
345 if (ok == FALSE) {
346 SetLastError (ERROR_OUTOFMEMORY);
347 return (WAIT_FAILED);
349 process_handle->waited = TRUE;
351 return(WAIT_OBJECT_0);
354 void _wapi_process_signal_self ()
356 if (current_process != NULL) {
357 process_set_termination_details (current_process, 0);
361 static void process_set_defaults (struct _WapiHandle_process *process_handle)
363 /* These seem to be the defaults on w2k */
364 process_handle->min_working_set = 204800;
365 process_handle->max_working_set = 1413120;
367 process_handle->waited = FALSE;
369 _wapi_time_t_to_filetime (time (NULL), &process_handle->create_time);
372 static int
373 len16 (const gunichar2 *str)
375 int len = 0;
377 while (*str++ != 0)
378 len++;
380 return len;
383 static gunichar2 *
384 utf16_concat (const gunichar2 *first, ...)
386 va_list args;
387 int total = 0, i;
388 const gunichar2 *s;
389 gunichar2 *ret;
391 va_start (args, first);
392 total += len16 (first);
393 for (s = va_arg (args, gunichar2 *); s != NULL; s = va_arg(args, gunichar2 *)){
394 total += len16 (s);
396 va_end (args);
398 ret = g_new (gunichar2, total + 1);
399 if (ret == NULL)
400 return NULL;
402 ret [total] = 0;
403 i = 0;
404 for (s = first; *s != 0; s++)
405 ret [i++] = *s;
406 va_start (args, first);
407 for (s = va_arg (args, gunichar2 *); s != NULL; s = va_arg (args, gunichar2 *)){
408 const gunichar2 *p;
410 for (p = s; *p != 0; p++)
411 ret [i++] = *p;
413 va_end (args);
415 return ret;
418 #ifdef PLATFORM_MACOSX
420 /* 0 = no detection; -1 = not 10.5 or higher; 1 = 10.5 or higher */
421 static int osx_10_5_or_higher;
423 static void
424 detect_osx_10_5_or_higher (void)
426 struct utsname u;
427 char *p;
428 int v;
430 if (uname (&u) != 0){
431 osx_10_5_or_higher = 1;
432 return;
435 p = u.release;
436 v = atoi (p);
438 if (v < 9)
439 osx_10_5_or_higher = -1;
440 else
441 osx_10_5_or_higher = 1;
444 static gboolean
445 is_macos_10_5_or_higher (void)
447 if (osx_10_5_or_higher == 0)
448 detect_osx_10_5_or_higher ();
450 return (osx_10_5_or_higher == 1);
452 #endif
454 static const gunichar2 utf16_space_bytes [2] = { 0x20, 0 };
455 static const gunichar2 *utf16_space = utf16_space_bytes;
456 static const gunichar2 utf16_quote_bytes [2] = { 0x22, 0 };
457 static const gunichar2 *utf16_quote = utf16_quote_bytes;
459 #ifdef DEBUG
460 /* Useful in gdb */
461 void
462 print_utf16 (gunichar2 *str)
464 gchar *res;
466 res = g_utf16_to_utf8 (str, -1, NULL, NULL, NULL);
467 g_print ("%s\n", res);
468 g_free (res);
470 #endif
472 /* Implemented as just a wrapper around CreateProcess () */
473 gboolean ShellExecuteEx (WapiShellExecuteInfo *sei)
475 gboolean ret;
476 WapiProcessInformation process_info;
477 gunichar2 *args;
479 if (sei == NULL) {
480 /* w2k just segfaults here, but we can do better than
481 * that
483 SetLastError (ERROR_INVALID_PARAMETER);
484 return (FALSE);
487 if (sei->lpFile == NULL) {
488 /* w2k returns TRUE for this, for some reason. */
489 return (TRUE);
492 /* Put both executable and parameters into the second argument
493 * to CreateProcess (), so it searches $PATH. The conversion
494 * into and back out of utf8 is because there is no
495 * g_strdup_printf () equivalent for gunichar2 :-(
497 args = utf16_concat (utf16_quote, sei->lpFile, utf16_quote, sei->lpParameters == NULL ? NULL : utf16_space, sei->lpParameters, NULL);
498 if (args == NULL){
499 SetLastError (ERROR_INVALID_DATA);
500 return (FALSE);
502 ret = CreateProcess (NULL, args, NULL, NULL, TRUE,
503 CREATE_UNICODE_ENVIRONMENT, NULL,
504 sei->lpDirectory, NULL, &process_info);
505 g_free (args);
507 if (!ret && GetLastError () == ERROR_OUTOFMEMORY)
508 return ret;
510 if (!ret) {
511 static char *handler;
512 static gunichar2 *handler_utf16;
514 if (handler_utf16 == (gunichar2 *)-1)
515 return FALSE;
517 #ifdef PLATFORM_MACOSX
518 if (is_macos_10_5_or_higher ())
519 handler = g_strdup ("/usr/bin/open -W");
520 else
521 handler = g_strdup ("/usr/bin/open");
522 #else
524 * On Linux, try: xdg-open, the FreeDesktop standard way of doing it,
525 * if that fails, try to use gnome-open, then kfmclient
527 handler = g_find_program_in_path ("xdg-open");
528 if (handler == NULL){
529 handler = g_find_program_in_path ("gnome-open");
530 if (handler == NULL){
531 handler = g_find_program_in_path ("kfmclient");
532 if (handler == NULL){
533 handler_utf16 = (gunichar2 *) -1;
534 return (FALSE);
535 } else {
536 /* kfmclient needs exec argument */
537 char *old = handler;
538 handler = g_strconcat (old, " exec",
539 NULL);
540 g_free (old);
544 #endif
545 handler_utf16 = g_utf8_to_utf16 (handler, -1, NULL, NULL, NULL);
546 g_free (handler);
548 /* Put quotes around the filename, in case it's a url
549 * that contains #'s (CreateProcess() calls
550 * g_shell_parse_argv(), which deliberately throws
551 * away anything after an unquoted #). Fixes bug
552 * 371567.
554 args = utf16_concat (handler_utf16, utf16_space, utf16_quote,
555 sei->lpFile, utf16_quote,
556 sei->lpParameters == NULL ? NULL : utf16_space,
557 sei->lpParameters, NULL);
558 if (args == NULL){
559 SetLastError (ERROR_INVALID_DATA);
560 return FALSE;
562 ret = CreateProcess (NULL, args, NULL, NULL, TRUE,
563 CREATE_UNICODE_ENVIRONMENT, NULL,
564 sei->lpDirectory, NULL, &process_info);
565 g_free (args);
566 if (!ret){
567 SetLastError (ERROR_INVALID_DATA);
568 return FALSE;
572 if (sei->fMask & SEE_MASK_NOCLOSEPROCESS) {
573 sei->hProcess = process_info.hProcess;
574 } else {
575 CloseHandle (process_info.hProcess);
578 return (ret);
581 static gboolean
582 is_managed_binary (const gchar *filename)
584 int original_errno = errno;
585 #if defined(HAVE_LARGE_FILE_SUPPORT) && defined(O_LARGEFILE)
586 int file = open (filename, O_RDONLY | O_LARGEFILE);
587 #else
588 int file = open (filename, O_RDONLY);
589 #endif
590 off_t new_offset;
591 unsigned char buffer[8];
592 off_t file_size, optional_header_offset;
593 off_t pe_header_offset;
594 gboolean managed = FALSE;
595 int num_read;
596 guint32 first_word, second_word;
598 /* If we are unable to open the file, then we definitely
599 * can't say that it is managed. The child mono process
600 * probably wouldn't be able to open it anyway.
602 if (file < 0) {
603 errno = original_errno;
604 return FALSE;
607 /* Retrieve the length of the file for future sanity checks. */
608 file_size = lseek (file, 0, SEEK_END);
609 lseek (file, 0, SEEK_SET);
611 /* We know we need to read a header field at offset 60. */
612 if (file_size < 64)
613 goto leave;
615 num_read = read (file, buffer, 2);
617 if ((num_read != 2) || (buffer[0] != 'M') || (buffer[1] != 'Z'))
618 goto leave;
620 new_offset = lseek (file, 60, SEEK_SET);
622 if (new_offset != 60)
623 goto leave;
625 num_read = read (file, buffer, 4);
627 if (num_read != 4)
628 goto leave;
629 pe_header_offset = buffer[0]
630 | (buffer[1] << 8)
631 | (buffer[2] << 16)
632 | (buffer[3] << 24);
634 if (pe_header_offset + 24 > file_size)
635 goto leave;
637 new_offset = lseek (file, pe_header_offset, SEEK_SET);
639 if (new_offset != pe_header_offset)
640 goto leave;
642 num_read = read (file, buffer, 4);
644 if ((num_read != 4) || (buffer[0] != 'P') || (buffer[1] != 'E') || (buffer[2] != 0) || (buffer[3] != 0))
645 goto leave;
648 * Verify that the header we want in the optional header data
649 * is present in this binary.
651 new_offset = lseek (file, pe_header_offset + 20, SEEK_SET);
653 if (new_offset != pe_header_offset + 20)
654 goto leave;
656 num_read = read (file, buffer, 2);
658 if ((num_read != 2) || ((buffer[0] | (buffer[1] << 8)) < 216))
659 goto leave;
661 /* Read the CLR header address and size fields. These will be
662 * zero if the binary is not managed.
664 optional_header_offset = pe_header_offset + 24;
665 new_offset = lseek (file, optional_header_offset + 208, SEEK_SET);
667 if (new_offset != optional_header_offset + 208)
668 goto leave;
670 num_read = read (file, buffer, 8);
672 /* We are not concerned with endianness, only with
673 * whether it is zero or not.
675 first_word = *(guint32 *)&buffer[0];
676 second_word = *(guint32 *)&buffer[4];
678 if ((num_read != 8) || (first_word == 0) || (second_word == 0))
679 goto leave;
681 managed = TRUE;
683 leave:
684 close (file);
685 errno = original_errno;
686 return managed;
689 gboolean CreateProcessWithLogonW (const gunichar2 *username,
690 const gunichar2 *domain,
691 const gunichar2 *password,
692 const guint32 logonFlags,
693 const gunichar2 *appname,
694 const gunichar2 *cmdline,
695 guint32 create_flags,
696 gpointer env,
697 const gunichar2 *cwd,
698 WapiStartupInfo *startup,
699 WapiProcessInformation *process_info)
701 /* FIXME: use user information */
702 return CreateProcess (appname, cmdline, NULL, NULL, FALSE, create_flags, env, cwd, startup, process_info);
705 static gboolean
706 is_executable (const char *prog)
708 struct stat buf;
709 if (access (prog, X_OK) != 0)
710 return FALSE;
711 if (stat (prog, &buf))
712 return FALSE;
713 if (S_ISREG (buf.st_mode))
714 return TRUE;
715 return FALSE;
718 gboolean CreateProcess (const gunichar2 *appname, const gunichar2 *cmdline,
719 WapiSecurityAttributes *process_attrs G_GNUC_UNUSED,
720 WapiSecurityAttributes *thread_attrs G_GNUC_UNUSED,
721 gboolean inherit_handles, guint32 create_flags,
722 gpointer new_environ, const gunichar2 *cwd,
723 WapiStartupInfo *startup,
724 WapiProcessInformation *process_info)
726 gchar *cmd=NULL, *prog = NULL, *full_prog = NULL, *args = NULL, *args_after_prog = NULL, *dir = NULL, **env_strings = NULL, **argv = NULL;
727 guint32 i, env_count = 0;
728 gboolean ret = FALSE;
729 gpointer handle;
730 struct _WapiHandle_process process_handle = {0}, *process_handle_data;
731 GError *gerr = NULL;
732 int in_fd, out_fd, err_fd;
733 pid_t pid;
734 int thr_ret;
736 mono_once (&process_ops_once, process_ops_init);
738 /* appname and cmdline specify the executable and its args:
740 * If appname is not NULL, it is the name of the executable.
741 * Otherwise the executable is the first token in cmdline.
743 * Executable searching:
745 * If appname is not NULL, it can specify the full path and
746 * file name, or else a partial name and the current directory
747 * will be used. There is no additional searching.
749 * If appname is NULL, the first whitespace-delimited token in
750 * cmdline is used. If the name does not contain a full
751 * directory path, the search sequence is:
753 * 1) The directory containing the current process
754 * 2) The current working directory
755 * 3) The windows system directory (Ignored)
756 * 4) The windows directory (Ignored)
757 * 5) $PATH
759 * Just to make things more interesting, tokens can contain
760 * white space if they are surrounded by quotation marks. I'm
761 * beginning to understand just why windows apps are generally
762 * so crap, with an API like this :-(
764 if (appname != NULL) {
765 cmd = mono_unicode_to_external (appname);
766 if (cmd == NULL) {
767 #ifdef DEBUG
768 g_message ("%s: unicode conversion returned NULL",
769 __func__);
770 #endif
772 SetLastError (ERROR_PATH_NOT_FOUND);
773 goto free_strings;
776 /* Turn all the slashes round the right way */
777 for (i = 0; i < strlen (cmd); i++) {
778 if (cmd[i] == '\\') {
779 cmd[i] = '/';
784 if (cmdline != NULL) {
785 args = mono_unicode_to_external (cmdline);
786 if (args == NULL) {
787 #ifdef DEBUG
788 g_message ("%s: unicode conversion returned NULL", __func__);
789 #endif
791 SetLastError (ERROR_PATH_NOT_FOUND);
792 goto free_strings;
796 if (cwd != NULL) {
797 dir = mono_unicode_to_external (cwd);
798 if (dir == NULL) {
799 #ifdef DEBUG
800 g_message ("%s: unicode conversion returned NULL", __func__);
801 #endif
803 SetLastError (ERROR_PATH_NOT_FOUND);
804 goto free_strings;
807 /* Turn all the slashes round the right way */
808 for (i = 0; i < strlen (dir); i++) {
809 if (dir[i] == '\\') {
810 dir[i] = '/';
816 /* We can't put off locating the executable any longer :-( */
817 if (cmd != NULL) {
818 gchar *unquoted;
819 if (g_ascii_isalpha (cmd[0]) && (cmd[1] == ':')) {
820 /* Strip off the drive letter. I can't
821 * believe that CP/M holdover is still
822 * visible...
824 g_memmove (cmd, cmd+2, strlen (cmd)-2);
825 cmd[strlen (cmd)-2] = '\0';
828 unquoted = g_shell_unquote (cmd, NULL);
829 if (unquoted[0] == '/') {
830 /* Assume full path given */
831 prog = g_strdup (unquoted);
833 /* Executable existing ? */
834 if (!is_executable (prog)) {
835 #ifdef DEBUG
836 g_message ("%s: Couldn't find executable %s",
837 __func__, prog);
838 #endif
839 g_free (unquoted);
840 SetLastError (ERROR_FILE_NOT_FOUND);
841 goto free_strings;
843 } else {
844 /* Search for file named by cmd in the current
845 * directory
847 char *curdir = g_get_current_dir ();
849 prog = g_strdup_printf ("%s/%s", curdir, unquoted);
850 g_free (curdir);
852 /* And make sure it's executable */
853 if (!is_executable (prog)) {
854 #ifdef DEBUG
855 g_message ("%s: Couldn't find executable %s",
856 __func__, prog);
857 #endif
858 g_free (unquoted);
859 SetLastError (ERROR_FILE_NOT_FOUND);
860 goto free_strings;
863 g_free (unquoted);
865 args_after_prog = args;
866 } else {
867 gchar *token = NULL;
868 char quote;
869 gint token_len;
871 /* Dig out the first token from args, taking quotation
872 * marks into account
875 /* First, strip off all leading whitespace */
876 args = g_strchug (args);
878 /* args_after_prog points to the contents of args
879 * after token has been set (otherwise argv[0] is
880 * duplicated)
882 args_after_prog = args;
884 /* Assume the opening quote will always be the first
885 * character
887 if (args[0] == '\"' || args [0] == '\'') {
888 quote = args [0];
889 for (i = 1; args[i] != '\0' && args[i] != quote; i++);
890 if (args [i + 1] == '\0' || g_ascii_isspace (args[i+1])) {
891 /* We found the first token */
892 token = g_strndup (args+1, i-1);
893 args_after_prog = g_strchug (args + i + 1);
894 } else {
895 /* Quotation mark appeared in the
896 * middle of the token. Just give the
897 * whole first token, quotes and all,
898 * to exec.
903 if (token == NULL) {
904 /* No quote mark, or malformed */
905 for (i = 0; args[i] != '\0'; i++) {
906 if (g_ascii_isspace (args[i])) {
907 token = g_strndup (args, i);
908 args_after_prog = args + i + 1;
909 break;
914 if (token == NULL && args[0] != '\0') {
915 /* Must be just one token in the string */
916 token = g_strdup (args);
917 args_after_prog = NULL;
920 if (token == NULL) {
921 /* Give up */
922 #ifdef DEBUG
923 g_message ("%s: Couldn't find what to exec", __func__);
924 #endif
926 SetLastError (ERROR_PATH_NOT_FOUND);
927 goto free_strings;
930 /* Turn all the slashes round the right way. Only for
931 * the prg. name
933 token_len = strlen (token);
934 for (i = 0; i < token_len; i++) {
935 if (token[i] == '\\') {
936 token[i] = '/';
940 if (g_ascii_isalpha (token[0]) && (token[1] == ':')) {
941 /* Strip off the drive letter. I can't
942 * believe that CP/M holdover is still
943 * visible...
945 g_memmove (token, token+2, strlen (token)-2);
946 token[strlen (token)-2] = '\0';
949 if (token[0] == '/') {
950 /* Assume full path given */
951 prog = g_strdup (token);
953 /* Executable existing ? */
954 if (!is_executable (prog)) {
955 #ifdef DEBUG
956 g_message ("%s: Couldn't find executable %s",
957 __func__, token);
958 #endif
959 g_free (token);
960 SetLastError (ERROR_FILE_NOT_FOUND);
961 goto free_strings;
964 } else {
965 char *curdir = g_get_current_dir ();
967 /* FIXME: Need to record the directory
968 * containing the current process, and check
969 * that for the new executable as the first
970 * place to look
973 prog = g_strdup_printf ("%s/%s", curdir, token);
974 g_free (curdir);
976 /* I assume X_OK is the criterion to use,
977 * rather than F_OK
979 if (!is_executable (prog)) {
980 g_free (prog);
981 prog = g_find_program_in_path (token);
982 if (prog == NULL) {
983 #ifdef DEBUG
984 g_message ("%s: Couldn't find executable %s", __func__, token);
985 #endif
987 g_free (token);
988 SetLastError (ERROR_FILE_NOT_FOUND);
989 goto free_strings;
994 g_free (token);
997 #ifdef DEBUG
998 g_message ("%s: Exec prog [%s] args [%s]", __func__, prog,
999 args_after_prog);
1000 #endif
1002 /* Check for CLR binaries; if found, we will try to invoke
1003 * them using the same mono binary that started us.
1005 if (is_managed_binary (prog)) {
1006 gunichar2 *newapp, *newcmd;
1007 gsize bytes_ignored;
1009 newapp = mono_unicode_from_external ("mono", &bytes_ignored);
1011 if (newapp != NULL) {
1012 if (appname != NULL) {
1013 newcmd = utf16_concat (newapp, utf16_space,
1014 appname, utf16_space,
1015 cmdline, NULL);
1016 } else {
1017 newcmd = utf16_concat (newapp, utf16_space,
1018 cmdline, NULL);
1021 g_free ((gunichar2 *)newapp);
1023 if (newcmd != NULL) {
1024 ret = CreateProcess (NULL, newcmd,
1025 process_attrs,
1026 thread_attrs,
1027 inherit_handles,
1028 create_flags, new_environ,
1029 cwd, startup,
1030 process_info);
1032 g_free ((gunichar2 *)newcmd);
1034 goto free_strings;
1039 if (args_after_prog != NULL && *args_after_prog) {
1040 gchar *qprog;
1042 qprog = g_shell_quote (prog);
1043 full_prog = g_strconcat (qprog, " ", args_after_prog, NULL);
1044 g_free (qprog);
1045 } else {
1046 full_prog = g_shell_quote (prog);
1049 ret = g_shell_parse_argv (full_prog, NULL, &argv, &gerr);
1050 if (ret == FALSE) {
1051 g_message ("CreateProcess: %s\n", gerr->message);
1052 g_error_free (gerr);
1053 gerr = NULL;
1054 goto free_strings;
1057 if (startup != NULL && startup->dwFlags & STARTF_USESTDHANDLES) {
1058 in_fd = GPOINTER_TO_UINT (startup->hStdInput);
1059 out_fd = GPOINTER_TO_UINT (startup->hStdOutput);
1060 err_fd = GPOINTER_TO_UINT (startup->hStdError);
1061 } else {
1062 in_fd = GPOINTER_TO_UINT (GetStdHandle (STD_INPUT_HANDLE));
1063 out_fd = GPOINTER_TO_UINT (GetStdHandle (STD_OUTPUT_HANDLE));
1064 err_fd = GPOINTER_TO_UINT (GetStdHandle (STD_ERROR_HANDLE));
1067 g_strlcpy (process_handle.proc_name, prog,
1068 _WAPI_PROC_NAME_MAX_LEN - 1);
1070 process_set_defaults (&process_handle);
1072 handle = _wapi_handle_new (WAPI_HANDLE_PROCESS, &process_handle);
1073 if (handle == _WAPI_HANDLE_INVALID) {
1074 g_warning ("%s: error creating process handle", __func__);
1076 ret = FALSE;
1077 SetLastError (ERROR_OUTOFMEMORY);
1078 goto free_strings;
1081 /* Hold another reference so the process has somewhere to
1082 * store its exit data even if we drop this handle
1084 _wapi_handle_ref (handle);
1086 /* new_environ is a block of NULL-terminated strings, which
1087 * is itself NULL-terminated. Of course, passing an array of
1088 * string pointers would have made things too easy :-(
1090 * If new_environ is not NULL it specifies the entire set of
1091 * environment variables in the new process. Otherwise the
1092 * new process inherits the same environment.
1094 if (new_environ != NULL) {
1095 gunichar2 *new_environp;
1097 /* Count the number of strings */
1098 for (new_environp = (gunichar2 *)new_environ; *new_environp;
1099 new_environp++) {
1100 env_count++;
1101 while (*new_environp) {
1102 new_environp++;
1106 /* +2: one for the process handle value, and the last
1107 * one is NULL
1109 env_strings = g_new0 (gchar *, env_count + 2);
1111 /* Copy each environ string into 'strings' turning it
1112 * into utf8 (or the requested encoding) at the same
1113 * time
1115 env_count = 0;
1116 for (new_environp = (gunichar2 *)new_environ; *new_environp;
1117 new_environp++) {
1118 env_strings[env_count] = mono_unicode_to_external (new_environp);
1119 env_count++;
1120 while (*new_environp) {
1121 new_environp++;
1124 } else {
1125 for (i = 0; environ[i] != NULL; i++) {
1126 env_count++;
1129 /* +2: one for the process handle value, and the last
1130 * one is NULL
1132 env_strings = g_new0 (gchar *, env_count + 2);
1134 /* Copy each environ string into 'strings' turning it
1135 * into utf8 (or the requested encoding) at the same
1136 * time
1138 env_count = 0;
1139 for (i = 0; environ[i] != NULL; i++) {
1140 env_strings[env_count] = g_strdup (environ[i]);
1141 env_count++;
1144 /* pass process handle info to the child, so it doesn't have
1145 * to do an expensive search over the whole list
1147 if (env_strings != NULL) {
1148 struct _WapiHandleUnshared *handle_data;
1149 struct _WapiHandle_shared_ref *ref;
1151 handle_data = &_WAPI_PRIVATE_HANDLES(GPOINTER_TO_UINT(handle));
1152 ref = &handle_data->u.shared;
1154 env_strings[env_count] = g_strdup_printf ("_WAPI_PROCESS_HANDLE_OFFSET=%d", ref->offset);
1157 thr_ret = _wapi_handle_lock_shared_handles ();
1158 g_assert (thr_ret == 0);
1160 pid = fork ();
1161 if (pid == -1) {
1162 /* Error */
1163 SetLastError (ERROR_OUTOFMEMORY);
1164 _wapi_handle_unref (handle);
1165 goto cleanup;
1166 } else if (pid == 0) {
1167 /* Child */
1169 if (_wapi_shm_disabled == FALSE) {
1170 /* Wait for the parent to finish setting up
1171 * the handle. The semaphore lock is safe
1172 * because the sem_undo structures of a
1173 * semaphore aren't inherited across a fork
1174 * (), but we can't do this if we're not using
1175 * the shared memory
1177 thr_ret = _wapi_handle_lock_shared_handles ();
1178 g_assert (thr_ret == 0);
1180 _wapi_handle_unlock_shared_handles ();
1183 /* should we detach from the process group? */
1185 /* Connect stdin, stdout and stderr */
1186 dup2 (in_fd, 0);
1187 dup2 (out_fd, 1);
1188 dup2 (err_fd, 2);
1190 if (inherit_handles != TRUE) {
1191 /* FIXME: do something here */
1194 /* Close all file descriptors */
1195 for (i = getdtablesize () - 1; i > 2; i--) {
1196 close (i);
1199 #ifdef DEBUG
1200 g_message ("%s: exec()ing [%s] in dir [%s]", __func__, cmd,
1201 dir==NULL?".":dir);
1202 for (i = 0; argv[i] != NULL; i++) {
1203 g_message ("arg %d: [%s]", i, argv[i]);
1206 for (i = 0; env_strings[i] != NULL; i++) {
1207 g_message ("env %d: [%s]", i, env_strings[i]);
1209 #endif
1211 /* set cwd */
1212 if (dir != NULL && chdir (dir) == -1) {
1213 /* set error */
1214 _exit (-1);
1217 /* exec */
1218 execve (argv[0], argv, env_strings);
1220 /* set error */
1221 _exit (-1);
1223 /* parent */
1225 ret = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
1226 (gpointer *)&process_handle_data);
1227 if (ret == FALSE) {
1228 g_warning ("%s: error looking up process handle %p", __func__,
1229 handle);
1230 _wapi_handle_unref (handle);
1231 goto cleanup;
1234 process_handle_data->id = pid;
1236 if (process_info != NULL) {
1237 process_info->hProcess = handle;
1238 process_info->dwProcessId = pid;
1240 /* FIXME: we might need to handle the thread info some
1241 * day
1243 process_info->hThread = INVALID_HANDLE_VALUE;
1244 process_info->dwThreadId = 0;
1247 cleanup:
1248 _wapi_handle_unlock_shared_handles ();
1250 free_strings:
1251 if (cmd != NULL) {
1252 g_free (cmd);
1254 if (full_prog != NULL) {
1255 g_free (full_prog);
1257 if (prog != NULL) {
1258 g_free (prog);
1260 if (args != NULL) {
1261 g_free (args);
1263 if (dir != NULL) {
1264 g_free (dir);
1266 if(env_strings != NULL) {
1267 g_strfreev (env_strings);
1269 if (argv != NULL) {
1270 g_strfreev (argv);
1273 #ifdef DEBUG
1274 g_message ("%s: returning handle %p for pid %d", __func__, handle,
1275 pid);
1276 #endif
1278 return(ret);
1281 static void process_set_name (struct _WapiHandle_process *process_handle)
1283 gchar *progname, *utf8_progname, *slash;
1285 progname=g_get_prgname ();
1286 utf8_progname=mono_utf8_from_external (progname);
1288 #ifdef DEBUG
1289 g_message ("%s: using [%s] as prog name", __func__, progname);
1290 #endif
1292 if(utf8_progname!=NULL) {
1293 slash=strrchr (utf8_progname, '/');
1294 if(slash!=NULL) {
1295 g_strlcpy (process_handle->proc_name, slash+1,
1296 _WAPI_PROC_NAME_MAX_LEN - 1);
1297 } else {
1298 g_strlcpy (process_handle->proc_name, utf8_progname,
1299 _WAPI_PROC_NAME_MAX_LEN - 1);
1302 g_free (utf8_progname);
1306 extern void _wapi_time_t_to_filetime (time_t timeval, WapiFileTime *filetime);
1308 #if !GLIB_CHECK_VERSION (2,4,0)
1309 #define g_setenv(a,b,c) setenv(a,b,c)
1310 #define g_unsetenv(a) unsetenv(a)
1311 #endif
1313 static void process_set_current (void)
1315 pid_t pid = _wapi_getpid ();
1316 const char *handle_env;
1317 struct _WapiHandle_process process_handle = {0};
1319 mono_once (&process_ops_once, process_ops_init);
1321 handle_env = g_getenv ("_WAPI_PROCESS_HANDLE_OFFSET");
1322 g_unsetenv ("_WAPI_PROCESS_HANDLE_OFFSET");
1324 if (handle_env != NULL) {
1325 struct _WapiHandle_process *process_handlep;
1326 gchar *procname = NULL;
1327 gboolean ok;
1329 current_process = _wapi_handle_new_from_offset (WAPI_HANDLE_PROCESS, atoi (handle_env), TRUE);
1331 #ifdef DEBUG
1332 g_message ("%s: Found my process handle: %p (offset %d 0x%x)",
1333 __func__, current_process, atoi (handle_env),
1334 atoi (handle_env));
1335 #endif
1337 ok = _wapi_lookup_handle (current_process, WAPI_HANDLE_PROCESS,
1338 (gpointer *)&process_handlep);
1339 if (ok) {
1340 /* This test will probably break on linuxthreads, but
1341 * that should be ancient history on all distros we
1342 * care about by now
1344 if (process_handlep->id == pid) {
1345 procname = process_handlep->proc_name;
1346 if (!strcmp (procname, "mono")) {
1347 /* Set a better process name */
1348 #ifdef DEBUG
1349 g_message ("%s: Setting better process name", __func__);
1350 #endif
1352 process_set_name (process_handlep);
1353 } else {
1354 #ifdef DEBUG
1355 g_message ("%s: Leaving process name: %s", __func__, procname);
1356 #endif
1359 return;
1362 /* Wrong pid, so drop this handle and fall through to
1363 * create a new one
1365 _wapi_handle_unref (current_process);
1369 /* We get here if the handle wasn't specified in the
1370 * environment, or if the process ID was wrong, or if the
1371 * handle lookup failed (eg if the parent process forked and
1372 * quit immediately, and deleted the shared data before the
1373 * child got a chance to attach it.)
1376 #ifdef DEBUG
1377 g_message ("%s: Need to create my own process handle", __func__);
1378 #endif
1380 process_handle.id = pid;
1382 process_set_defaults (&process_handle);
1383 process_set_name (&process_handle);
1385 current_process = _wapi_handle_new (WAPI_HANDLE_PROCESS,
1386 &process_handle);
1387 if (current_process == _WAPI_HANDLE_INVALID) {
1388 g_warning ("%s: error creating process handle", __func__);
1389 return;
1393 gpointer _wapi_process_duplicate ()
1395 mono_once (&process_current_once, process_set_current);
1397 _wapi_handle_ref (current_process);
1399 return(current_process);
1402 /* Returns a pseudo handle that doesn't need to be closed afterwards */
1403 gpointer GetCurrentProcess (void)
1405 mono_once (&process_current_once, process_set_current);
1407 return(_WAPI_PROCESS_CURRENT);
1410 guint32 GetProcessId (gpointer handle)
1412 struct _WapiHandle_process *process_handle;
1413 gboolean ok;
1415 if ((GPOINTER_TO_UINT (handle) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
1416 /* This is a pseudo handle */
1417 return(GPOINTER_TO_UINT (handle) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
1420 ok = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
1421 (gpointer *)&process_handle);
1422 if (ok == FALSE) {
1423 SetLastError (ERROR_INVALID_HANDLE);
1424 return (0);
1427 return (process_handle->id);
1430 guint32 GetCurrentProcessId (void)
1432 mono_once (&process_current_once, process_set_current);
1434 return (GetProcessId (current_process));
1437 /* Returns the process id as a convenience to the functions that call this */
1438 static pid_t signal_process_if_gone (gpointer handle)
1440 struct _WapiHandle_process *process_handle;
1441 gboolean ok;
1443 g_assert ((GPOINTER_TO_UINT (handle) & _WAPI_PROCESS_UNHANDLED) != _WAPI_PROCESS_UNHANDLED);
1445 /* Make sure the process is signalled if it has exited - if
1446 * the parent process didn't wait for it then it won't be
1448 ok = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
1449 (gpointer *)&process_handle);
1450 if (ok == FALSE) {
1451 /* It's possible that the handle has vanished during
1452 * the _wapi_search_handle before it gets here, so
1453 * don't spam the console with warnings.
1455 /* g_warning ("%s: error looking up process handle %p",
1456 __func__, handle);*/
1458 return (0);
1461 #ifdef DEBUG
1462 g_message ("%s: looking at process %d", __func__, process_handle->id);
1463 #endif
1465 if (kill (process_handle->id, 0) == -1 &&
1466 (errno == ESRCH ||
1467 errno == EPERM)) {
1468 /* The process is dead, (EPERM tells us a new process
1469 * has that ID, but as it's owned by someone else it
1470 * can't be the one listed in our shared memory file)
1472 _wapi_shared_handle_set_signal_state (handle, TRUE);
1475 return (process_handle->id);
1478 #ifdef UNUSED_CODE
1479 static gboolean process_enum (gpointer handle, gpointer user_data)
1481 GArray *processes=user_data;
1482 pid_t pid = signal_process_if_gone (handle);
1483 int i;
1485 if (pid == 0) {
1486 return (FALSE);
1489 /* Ignore processes that have already exited (ie they are signalled) */
1490 if (_wapi_handle_issignalled (handle) == FALSE) {
1491 #ifdef DEBUG
1492 g_message ("%s: process %d added to array", __func__, pid);
1493 #endif
1495 /* This ensures that duplicates aren't returned (see
1496 * the comment above _wapi_search_handle () for why
1497 * it's needed
1499 for (i = 0; i < processes->len; i++) {
1500 if (g_array_index (processes, pid_t, i) == pid) {
1501 /* We've already got this one, return
1502 * FALSE to keep searching
1504 return (FALSE);
1508 g_array_append_val (processes, pid);
1511 /* Return false to keep searching */
1512 return(FALSE);
1514 #endif /* UNUSED_CODE */
1516 #ifdef PLATFORM_MACOSX
1518 gboolean EnumProcesses (guint32 *pids, guint32 len, guint32 *needed)
1520 guint32 count, fit, i, j;
1521 gint32 err;
1522 gboolean done;
1523 struct kinfo_proc *result;
1524 size_t proclength;
1525 static const int name[] = { CTL_KERN, KERN_PROC, KERN_PROC_ALL, 0 };
1527 mono_once (&process_current_once, process_set_current);
1529 result = NULL;
1530 done = FALSE;
1532 do {
1533 proclength = 0;
1534 err = sysctl ((int *)name, (sizeof(name) / sizeof(*name)) - 1, NULL, &proclength, NULL, 0);
1536 if (err == 0) {
1537 result = malloc (proclength);
1538 if (result == NULL)
1539 return FALSE;
1541 err = sysctl ((int *) name, (sizeof(name) / sizeof(*name)) - 1, result, &proclength, NULL, 0);
1543 if (err == 0)
1544 done = TRUE;
1545 else
1546 free (result);
1548 } while (err == 0 && !done);
1550 if (err != 0) {
1551 if (result != NULL) {
1552 free (result);
1553 result = NULL;
1555 return(FALSE);
1558 count = proclength / sizeof(struct kinfo_proc);
1559 fit = len / sizeof(guint32);
1560 for (i = 0, j = 0; j< fit && i < count; i++) {
1561 pids [j++] = result [i].kp_proc.p_pid;
1563 free (result);
1564 result = NULL;
1565 *needed = j * sizeof(guint32);
1567 return(TRUE);
1569 #else
1570 gboolean EnumProcesses (guint32 *pids, guint32 len, guint32 *needed)
1572 GArray *processes = g_array_new (FALSE, FALSE, sizeof(pid_t));
1573 guint32 fit, i, j;
1574 DIR *dir;
1575 struct dirent *entry;
1577 mono_once (&process_current_once, process_set_current);
1579 dir = opendir ("/proc");
1580 if (dir == NULL) {
1581 return(FALSE);
1583 while((entry = readdir (dir)) != NULL) {
1584 if (isdigit (entry->d_name[0])) {
1585 char *endptr;
1586 pid_t pid = (pid_t)strtol (entry->d_name, &endptr, 10);
1588 if (*endptr == '\0') {
1589 /* Name was entirely numeric, so was a
1590 * process ID
1592 g_array_append_val (processes, pid);
1596 closedir (dir);
1598 fit=len/sizeof(guint32);
1599 for (i = 0, j = 0; j < fit && i < processes->len; i++) {
1600 pids[j++] = g_array_index (processes, pid_t, i);
1603 g_array_free (processes, TRUE);
1605 *needed = j * sizeof(guint32);
1607 return(TRUE);
1609 #endif
1611 static gboolean process_open_compare (gpointer handle, gpointer user_data)
1613 pid_t wanted_pid;
1614 pid_t checking_pid = signal_process_if_gone (handle);
1616 if (checking_pid == 0) {
1617 return(FALSE);
1620 wanted_pid = GPOINTER_TO_UINT (user_data);
1622 /* It's possible to have more than one process handle with the
1623 * same pid, but only the one running process can be
1624 * unsignalled
1626 if (checking_pid == wanted_pid &&
1627 _wapi_handle_issignalled (handle) == FALSE) {
1628 /* If the handle is blown away in the window between
1629 * returning TRUE here and _wapi_search_handle pinging
1630 * the timestamp, the search will continue
1632 return(TRUE);
1633 } else {
1634 return(FALSE);
1638 gpointer OpenProcess (guint32 req_access G_GNUC_UNUSED, gboolean inherit G_GNUC_UNUSED, guint32 pid)
1640 /* Find the process handle that corresponds to pid */
1641 gpointer handle;
1643 mono_once (&process_current_once, process_set_current);
1645 #ifdef DEBUG
1646 g_message ("%s: looking for process %d", __func__, pid);
1647 #endif
1649 handle = _wapi_search_handle (WAPI_HANDLE_PROCESS,
1650 process_open_compare,
1651 GUINT_TO_POINTER (pid), NULL, TRUE);
1652 if (handle == 0) {
1653 gchar *dir = g_strdup_printf ("/proc/%d", pid);
1654 if (!access (dir, F_OK)) {
1655 /* Return a pseudo handle for processes we
1656 * don't have handles for
1658 return GINT_TO_POINTER (_WAPI_PROCESS_UNHANDLED + pid);
1659 } else {
1660 #ifdef DEBUG
1661 g_message ("%s: Can't find pid %d", __func__, pid);
1662 #endif
1664 SetLastError (ERROR_PROC_NOT_FOUND);
1666 return(NULL);
1670 _wapi_handle_ref (handle);
1672 return(handle);
1675 gboolean GetExitCodeProcess (gpointer process, guint32 *code)
1677 struct _WapiHandle_process *process_handle;
1678 gboolean ok;
1680 mono_once (&process_current_once, process_set_current);
1682 if(code==NULL) {
1683 return(FALSE);
1686 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
1687 /* This is a pseudo handle, so we don't know what the
1688 * exit code was
1690 return(FALSE);
1693 ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
1694 (gpointer *)&process_handle);
1695 if(ok==FALSE) {
1696 #ifdef DEBUG
1697 g_message ("%s: Can't find process %p", __func__, process);
1698 #endif
1700 return(FALSE);
1703 /* A process handle is only signalled if the process has exited
1704 * and has been waited for */
1706 /* Make sure any process exit has been noticed, before
1707 * checking if the process is signalled. Fixes bug 325463.
1709 process_wait (process, 0);
1711 if (_wapi_handle_issignalled (process) == TRUE) {
1712 *code = process_handle->exitstatus;
1713 } else {
1714 *code = STILL_ACTIVE;
1717 return(TRUE);
1720 gboolean GetProcessTimes (gpointer process, WapiFileTime *create_time,
1721 WapiFileTime *exit_time, WapiFileTime *kernel_time,
1722 WapiFileTime *user_time)
1724 struct _WapiHandle_process *process_handle;
1725 gboolean ok;
1726 gboolean ku_times_set = FALSE;
1728 mono_once (&process_current_once, process_set_current);
1730 if(create_time==NULL || exit_time==NULL || kernel_time==NULL ||
1731 user_time==NULL) {
1732 /* Not sure if w32 allows NULLs here or not */
1733 return(FALSE);
1736 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
1737 /* This is a pseudo handle, so just fail for now
1739 return(FALSE);
1742 ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
1743 (gpointer *)&process_handle);
1744 if(ok==FALSE) {
1745 #ifdef DEBUG
1746 g_message ("%s: Can't find process %p", __func__, process);
1747 #endif
1749 return(FALSE);
1752 *create_time=process_handle->create_time;
1754 /* A process handle is only signalled if the process has
1755 * exited. Otherwise exit_time isn't set
1757 if(_wapi_handle_issignalled (process)==TRUE) {
1758 *exit_time=process_handle->exit_time;
1761 #ifdef HAVE_GETRUSAGE
1762 if (process_handle->id == getpid ()) {
1763 struct rusage time_data;
1764 if (getrusage (RUSAGE_SELF, &time_data) == 0) {
1765 gint64 tick_val;
1766 gint64 *tick_val_ptr;
1767 ku_times_set = TRUE;
1768 tick_val = time_data.ru_utime.tv_sec * 10000000 + time_data.ru_utime.tv_usec * 10;
1769 tick_val_ptr = (gint64*)user_time;
1770 *tick_val_ptr = tick_val;
1771 tick_val = time_data.ru_stime.tv_sec * 10000000 + time_data.ru_stime.tv_usec * 10;
1772 tick_val_ptr = (gint64*)kernel_time;
1773 *tick_val_ptr = tick_val;
1776 #endif
1777 if (!ku_times_set) {
1778 memset (kernel_time, 0, sizeof (WapiFileTime));
1779 memset (user_time, 0, sizeof (WapiFileTime));
1782 return(TRUE);
1785 typedef struct
1787 gpointer address_start;
1788 gpointer address_end;
1789 gchar *perms;
1790 gpointer address_offset;
1791 dev_t device;
1792 ino_t inode;
1793 gchar *filename;
1794 } WapiProcModule;
1796 static void free_procmodule (WapiProcModule *mod)
1798 if (mod->perms != NULL) {
1799 g_free (mod->perms);
1801 if (mod->filename != NULL) {
1802 g_free (mod->filename);
1804 g_free (mod);
1807 static gint find_procmodule (gconstpointer a, gconstpointer b)
1809 WapiProcModule *want = (WapiProcModule *)a;
1810 WapiProcModule *compare = (WapiProcModule *)b;
1812 if ((want->device == compare->device) &&
1813 (want->inode == compare->inode)) {
1814 return(0);
1815 } else {
1816 return(1);
1820 #ifdef PLATFORM_MACOSX
1821 #include <mach-o/dyld.h>
1822 #include <mach-o/getsect.h>
1824 static GSList *load_modules (void)
1826 GSList *ret = NULL;
1827 WapiProcModule *mod;
1828 uint32_t count = _dyld_image_count ();
1829 int i = 0;
1831 for (i = 0; i < count; i++) {
1832 const struct mach_header *hdr;
1833 const struct section *sec;
1834 const char *name;
1835 intptr_t slide;
1837 slide = _dyld_get_image_vmaddr_slide (i);
1838 name = _dyld_get_image_name (i);
1839 hdr = _dyld_get_image_header (i);
1840 sec = getsectbynamefromheader (hdr, SEG_DATA, SECT_DATA);
1842 /* Some dynlibs do not have data sections on osx (#533893) */
1843 if (sec == 0) {
1844 continue;
1847 mod = g_new0 (WapiProcModule, 1);
1848 mod->address_start = GINT_TO_POINTER (sec->addr);
1849 mod->address_end = GINT_TO_POINTER (sec->addr+sec->size);
1850 mod->perms = g_strdup ("r--p");
1851 mod->address_offset = 0;
1852 mod->device = makedev (0, 0);
1853 mod->inode = (ino_t) i;
1854 mod->filename = g_strdup (name);
1856 if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
1857 ret = g_slist_prepend (ret, mod);
1858 } else {
1859 free_procmodule (mod);
1863 ret = g_slist_reverse (ret);
1865 return(ret);
1867 #else
1868 static GSList *load_modules (FILE *fp)
1870 GSList *ret = NULL;
1871 WapiProcModule *mod;
1872 gchar buf[MAXPATHLEN + 1], *p, *endp;
1873 gchar *start_start, *end_start, *prot_start, *offset_start;
1874 gchar *maj_dev_start, *min_dev_start, *inode_start, prot_buf[5];
1875 gpointer address_start, address_end, address_offset;
1876 guint32 maj_dev, min_dev;
1877 ino_t inode;
1878 dev_t device;
1880 while (fgets (buf, sizeof(buf), fp)) {
1881 p = buf;
1882 while (g_ascii_isspace (*p)) ++p;
1883 start_start = p;
1884 if (!g_ascii_isxdigit (*start_start)) {
1885 continue;
1887 address_start = (gpointer)strtoul (start_start, &endp, 16);
1888 p = endp;
1889 if (*p != '-') {
1890 continue;
1893 ++p;
1894 end_start = p;
1895 if (!g_ascii_isxdigit (*end_start)) {
1896 continue;
1898 address_end = (gpointer)strtoul (end_start, &endp, 16);
1899 p = endp;
1900 if (!g_ascii_isspace (*p)) {
1901 continue;
1904 while (g_ascii_isspace (*p)) ++p;
1905 prot_start = p;
1906 if (*prot_start != 'r' && *prot_start != '-') {
1907 continue;
1909 memcpy (prot_buf, prot_start, 4);
1910 prot_buf[4] = '\0';
1911 while (!g_ascii_isspace (*p)) ++p;
1913 while (g_ascii_isspace (*p)) ++p;
1914 offset_start = p;
1915 if (!g_ascii_isxdigit (*offset_start)) {
1916 continue;
1918 address_offset = (gpointer)strtoul (offset_start, &endp, 16);
1919 p = endp;
1920 if (!g_ascii_isspace (*p)) {
1921 continue;
1924 while(g_ascii_isspace (*p)) ++p;
1925 maj_dev_start = p;
1926 if (!g_ascii_isxdigit (*maj_dev_start)) {
1927 continue;
1929 maj_dev = strtoul (maj_dev_start, &endp, 16);
1930 p = endp;
1931 if (*p != ':') {
1932 continue;
1935 ++p;
1936 min_dev_start = p;
1937 if (!g_ascii_isxdigit (*min_dev_start)) {
1938 continue;
1940 min_dev = strtoul (min_dev_start, &endp, 16);
1941 p = endp;
1942 if (!g_ascii_isspace (*p)) {
1943 continue;
1946 while (g_ascii_isspace (*p)) ++p;
1947 inode_start = p;
1948 if (!g_ascii_isxdigit (*inode_start)) {
1949 continue;
1951 inode = (ino_t)strtol (inode_start, &endp, 10);
1952 p = endp;
1953 if (!g_ascii_isspace (*p)) {
1954 continue;
1957 device = makedev ((int)maj_dev, (int)min_dev);
1958 if ((device == 0) &&
1959 (inode == 0)) {
1960 continue;
1963 while(g_ascii_isspace (*p)) ++p;
1964 /* p now points to the filename */
1966 mod = g_new0 (WapiProcModule, 1);
1967 mod->address_start = address_start;
1968 mod->address_end = address_end;
1969 mod->perms = g_strdup (prot_buf);
1970 mod->address_offset = address_offset;
1971 mod->device = device;
1972 mod->inode = inode;
1973 mod->filename = g_strdup (g_strstrip (p));
1975 if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
1976 ret = g_slist_prepend (ret, mod);
1977 } else {
1978 free_procmodule (mod);
1982 ret = g_slist_reverse (ret);
1984 return(ret);
1986 #endif
1988 static gboolean match_procname_to_modulename (gchar *procname, gchar *modulename)
1990 char* lastsep = NULL;
1991 char* pname = NULL;
1992 char* mname = NULL;
1993 gboolean result = FALSE;
1995 if (procname == NULL || modulename == NULL)
1996 return (FALSE);
1998 pname = mono_path_resolve_symlinks (procname);
1999 mname = mono_path_resolve_symlinks (modulename);
2001 if (!strcmp (pname, mname))
2002 result = TRUE;
2004 if (!result) {
2005 lastsep = strrchr (mname, '/');
2006 if (lastsep)
2007 if (!strcmp (lastsep+1, pname))
2008 result = TRUE;
2011 g_free (pname);
2012 g_free (mname);
2014 return result;
2017 static FILE *
2018 open_process_map (int pid, const char *mode)
2020 FILE *fp = NULL;
2021 const gchar *proc_path[] = {
2022 "/proc/%d/maps", /* GNU/Linux */
2023 "/proc/%d/map", /* FreeBSD */
2024 NULL
2026 int i;
2027 gchar *filename;
2029 for (i = 0; fp == NULL && proc_path [i]; i++) {
2030 filename = g_strdup_printf (proc_path[i], pid);
2031 fp = fopen (filename, mode);
2032 g_free (filename);
2035 return fp;
2038 gboolean EnumProcessModules (gpointer process, gpointer *modules,
2039 guint32 size, guint32 *needed)
2041 struct _WapiHandle_process *process_handle;
2042 gboolean ok;
2043 FILE *fp;
2044 GSList *mods = NULL;
2045 WapiProcModule *module;
2046 guint32 count, avail = size / sizeof(gpointer);
2047 int i;
2048 pid_t pid;
2049 gchar *proc_name = NULL;
2051 /* Store modules in an array of pointers (main module as
2052 * modules[0]), using the load address for each module as a
2053 * token. (Use 'NULL' as an alternative for the main module
2054 * so that the simple implementation can just return one item
2055 * for now.) Get the info from /proc/<pid>/maps on linux,
2056 * /proc/<pid>/map on FreeBSD, other systems will have to
2057 * implement /dev/kmem reading or whatever other horrid
2058 * technique is needed.
2060 if (size < sizeof(gpointer)) {
2061 return(FALSE);
2064 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2065 /* This is a pseudo handle */
2066 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2067 } else {
2068 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2069 (gpointer *)&process_handle);
2070 if (ok == FALSE) {
2071 #ifdef DEBUG
2072 g_message ("%s: Can't find process %p", __func__, process);
2073 #endif
2075 return(FALSE);
2077 pid = process_handle->id;
2078 proc_name = process_handle->proc_name;
2081 #ifdef PLATFORM_MACOSX
2083 mods = load_modules ();
2084 #else
2085 if ((fp = open_process_map (pid, "r")) == NULL) {
2086 /* No /proc/<pid>/maps so just return the main module
2087 * shortcut for now
2089 modules[0] = NULL;
2090 *needed = sizeof(gpointer);
2091 } else {
2092 mods = load_modules (fp);
2093 fclose (fp);
2094 #endif
2095 count = g_slist_length (mods);
2097 /* count + 1 to leave slot 0 for the main module */
2098 *needed = sizeof(gpointer) * (count + 1);
2100 /* Use the NULL shortcut, as the first line in
2101 * /proc/<pid>/maps isn't the executable, and we need
2102 * that first in the returned list. Check the module name
2103 * to see if it ends with the proc name and substitute
2104 * the first entry with it. FIXME if this turns out to
2105 * be a problem.
2107 modules[0] = NULL;
2108 for (i = 0; i < (avail - 1) && i < count; i++) {
2109 module = (WapiProcModule *)g_slist_nth_data (mods, i);
2110 if (modules[0] != NULL)
2111 modules[i] = module->address_start;
2112 else if (match_procname_to_modulename (proc_name, module->filename))
2113 modules[0] = module->address_start;
2114 else
2115 modules[i + 1] = module->address_start;
2118 for (i = 0; i < count; i++) {
2119 free_procmodule (g_slist_nth_data (mods, i));
2121 g_slist_free (mods);
2124 return(TRUE);
2127 static gchar *get_process_name_from_proc (pid_t pid)
2129 gchar *filename = NULL;
2130 gchar *ret = NULL;
2131 gchar buf[256];
2132 FILE *fp;
2134 #if defined(PLATFORM_SOLARIS)
2135 filename = g_strdup_printf ("/proc/%d/psinfo", pid);
2136 if ((fp = fopen (filename, "r")) != NULL) {
2137 struct psinfo info;
2138 int nread;
2140 nread = fread (&info, sizeof (info), 1, fp);
2141 if (nread == 1) {
2142 ret = g_strdup (info.pr_fname);
2145 fclose (fp);
2147 g_free (filename);
2148 #elif defined(PLATFORM_MACOSX)
2149 memset (buf, '\0', sizeof(buf));
2150 proc_name (pid, buf, sizeof(buf));
2151 if (strlen (buf) > 0)
2152 ret = g_strdup (buf);
2153 #else
2154 memset (buf, '\0', sizeof(buf));
2155 filename = g_strdup_printf ("/proc/%d/exe", pid);
2156 if (readlink (filename, buf, 255) > 0) {
2157 ret = g_strdup (buf);
2159 g_free (filename);
2161 if (ret != NULL) {
2162 return(ret);
2165 filename = g_strdup_printf ("/proc/%d/cmdline", pid);
2166 if ((fp = fopen (filename, "r")) != NULL) {
2167 if (fgets (buf, 256, fp) != NULL) {
2168 ret = g_strdup (buf);
2171 fclose (fp);
2173 g_free (filename);
2175 if (ret != NULL) {
2176 return(ret);
2179 filename = g_strdup_printf ("/proc/%d/stat", pid);
2180 if ((fp = fopen (filename, "r")) != NULL) {
2181 if (fgets (buf, 256, fp) != NULL) {
2182 gchar *start, *end;
2184 start = strchr (buf, '(');
2185 if (start != NULL) {
2186 end = strchr (start + 1, ')');
2188 if (end != NULL) {
2189 ret = g_strndup (start + 1,
2190 end - start - 1);
2195 fclose (fp);
2197 g_free (filename);
2198 #endif
2200 if (ret != NULL) {
2201 return(ret);
2204 return(NULL);
2207 static guint32 get_module_name (gpointer process, gpointer module,
2208 gunichar2 *basename, guint32 size,
2209 gboolean base)
2211 struct _WapiHandle_process *process_handle;
2212 gboolean ok;
2213 pid_t pid;
2214 gunichar2 *procname;
2215 gchar *procname_ext = NULL;
2216 glong len;
2217 gsize bytes;
2218 FILE *fp;
2219 GSList *mods = NULL;
2220 WapiProcModule *found_module;
2221 guint32 count;
2222 int i;
2223 gchar *proc_name = NULL;
2225 mono_once (&process_current_once, process_set_current);
2227 #ifdef DEBUG
2228 g_message ("%s: Getting module base name, process handle %p module %p",
2229 __func__, process, module);
2230 #endif
2232 size = size*sizeof(gunichar2); /* adjust for unicode characters */
2234 if (basename == NULL || size == 0) {
2235 return(0);
2238 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2239 /* This is a pseudo handle */
2240 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2241 proc_name = get_process_name_from_proc (pid);
2242 } else {
2243 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2244 (gpointer *)&process_handle);
2245 if (ok == FALSE) {
2246 #ifdef DEBUG
2247 g_message ("%s: Can't find process %p", __func__,
2248 process);
2249 #endif
2251 return(0);
2253 pid = process_handle->id;
2254 proc_name = g_strdup (process_handle->proc_name);
2257 /* Look up the address in /proc/<pid>/maps */
2258 #ifdef PLATFORM_MACOSX
2260 mods = load_modules ();
2261 #else
2262 if ((fp = open_process_map (pid, "r")) == NULL) {
2263 if (errno == EACCES && module == NULL && base == TRUE) {
2264 procname_ext = get_process_name_from_proc (pid);
2265 } else {
2266 /* No /proc/<pid>/maps, so just return failure
2267 * for now
2269 g_free (proc_name);
2270 return(0);
2272 } else {
2273 mods = load_modules (fp);
2274 fclose (fp);
2275 #endif
2276 count = g_slist_length (mods);
2278 /* If module != NULL compare the address.
2279 * If module == NULL we are looking for the main module.
2280 * The best we can do for now check it the module name end with the process name.
2282 for (i = 0; i < count; i++) {
2283 found_module = (WapiProcModule *)g_slist_nth_data (mods, i);
2284 if (procname_ext == NULL &&
2285 ((module == NULL && match_procname_to_modulename (proc_name, found_module->filename)) ||
2286 (module != NULL && found_module->address_start == module))) {
2287 if (base) {
2288 procname_ext = g_path_get_basename (found_module->filename);
2289 } else {
2290 procname_ext = g_strdup (found_module->filename);
2294 free_procmodule (found_module);
2297 if (procname_ext == NULL)
2299 /* If it's *still* null, we might have hit the
2300 * case where reading /proc/$pid/maps gives an
2301 * empty file for this user.
2303 procname_ext = get_process_name_from_proc (pid);
2306 g_slist_free (mods);
2307 g_free (proc_name);
2310 if (procname_ext != NULL) {
2311 #ifdef DEBUG
2312 g_message ("%s: Process name is [%s]", __func__,
2313 procname_ext);
2314 #endif
2316 procname = mono_unicode_from_external (procname_ext, &bytes);
2317 if (procname == NULL) {
2318 /* bugger */
2319 g_free (procname_ext);
2320 return(0);
2323 len = (bytes / 2);
2325 /* Add the terminator */
2326 bytes += 2;
2328 if (size < bytes) {
2329 #ifdef DEBUG
2330 g_message ("%s: Size %d smaller than needed (%ld); truncating", __func__, size, bytes);
2331 #endif
2333 memcpy (basename, procname, size);
2334 } else {
2335 #ifdef DEBUG
2336 g_message ("%s: Size %d larger than needed (%ld)",
2337 __func__, size, bytes);
2338 #endif
2340 memcpy (basename, procname, bytes);
2343 g_free (procname);
2344 g_free (procname_ext);
2346 return(len);
2349 return(0);
2352 guint32 GetModuleBaseName (gpointer process, gpointer module,
2353 gunichar2 *basename, guint32 size)
2355 return(get_module_name (process, module, basename, size, TRUE));
2358 guint32 GetModuleFileNameEx (gpointer process, gpointer module,
2359 gunichar2 *filename, guint32 size)
2361 return(get_module_name (process, module, filename, size, FALSE));
2364 gboolean GetModuleInformation (gpointer process, gpointer module,
2365 WapiModuleInfo *modinfo, guint32 size)
2367 struct _WapiHandle_process *process_handle;
2368 gboolean ok;
2369 pid_t pid;
2370 FILE *fp;
2371 GSList *mods = NULL;
2372 WapiProcModule *found_module;
2373 guint32 count;
2374 int i;
2375 gboolean ret = FALSE;
2376 gchar *proc_name = NULL;
2378 mono_once (&process_current_once, process_set_current);
2380 #ifdef DEBUG
2381 g_message ("%s: Getting module info, process handle %p module %p",
2382 __func__, process, module);
2383 #endif
2385 if (modinfo == NULL || size < sizeof(WapiModuleInfo)) {
2386 return(FALSE);
2389 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2390 /* This is a pseudo handle */
2391 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2392 proc_name = get_process_name_from_proc (pid);
2393 } else {
2394 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2395 (gpointer *)&process_handle);
2396 if (ok == FALSE) {
2397 #ifdef DEBUG
2398 g_message ("%s: Can't find process %p", __func__,
2399 process);
2400 #endif
2402 return(FALSE);
2404 pid = process_handle->id;
2405 proc_name = g_strdup (process_handle->proc_name);
2408 #ifdef PLATFORM_MACOSX
2410 mods = load_modules ();
2411 #else
2412 /* Look up the address in /proc/<pid>/maps */
2413 if ((fp = open_process_map (pid, "r")) == NULL) {
2414 /* No /proc/<pid>/maps, so just return failure
2415 * for now
2417 g_free (proc_name);
2418 return(FALSE);
2419 } else {
2420 mods = load_modules (fp);
2421 fclose (fp);
2422 #endif
2423 count = g_slist_length (mods);
2425 /* If module != NULL compare the address.
2426 * If module == NULL we are looking for the main module.
2427 * The best we can do for now check it the module name end with the process name.
2429 for (i = 0; i < count; i++) {
2430 found_module = (WapiProcModule *)g_slist_nth_data (mods, i);
2431 if ( ret == FALSE &&
2432 ((module == NULL && match_procname_to_modulename (proc_name, found_module->filename)) ||
2433 (module != NULL && found_module->address_start == module))) {
2434 modinfo->lpBaseOfDll = found_module->address_start;
2435 modinfo->SizeOfImage = (gsize)(found_module->address_end) - (gsize)(found_module->address_start);
2436 modinfo->EntryPoint = found_module->address_offset;
2437 ret = TRUE;
2440 free_procmodule (found_module);
2443 g_slist_free (mods);
2444 g_free (proc_name);
2447 return(ret);
2450 gboolean GetProcessWorkingSetSize (gpointer process, size_t *min, size_t *max)
2452 struct _WapiHandle_process *process_handle;
2453 gboolean ok;
2455 mono_once (&process_current_once, process_set_current);
2457 if(min==NULL || max==NULL) {
2458 /* Not sure if w32 allows NULLs here or not */
2459 return(FALSE);
2462 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2463 /* This is a pseudo handle, so just fail for now
2465 return(FALSE);
2468 ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2469 (gpointer *)&process_handle);
2470 if(ok==FALSE) {
2471 #ifdef DEBUG
2472 g_message ("%s: Can't find process %p", __func__, process);
2473 #endif
2475 return(FALSE);
2478 *min=process_handle->min_working_set;
2479 *max=process_handle->max_working_set;
2481 return(TRUE);
2484 gboolean SetProcessWorkingSetSize (gpointer process, size_t min, size_t max)
2486 struct _WapiHandle_process *process_handle;
2487 gboolean ok;
2489 mono_once (&process_current_once, process_set_current);
2491 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2492 /* This is a pseudo handle, so just fail for now
2494 return(FALSE);
2497 ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2498 (gpointer *)&process_handle);
2499 if(ok==FALSE) {
2500 #ifdef DEBUG
2501 g_message ("%s: Can't find process %p", __func__, process);
2502 #endif
2504 return(FALSE);
2507 process_handle->min_working_set=min;
2508 process_handle->max_working_set=max;
2510 return(TRUE);
2514 gboolean
2515 TerminateProcess (gpointer process, gint32 exitCode)
2517 struct _WapiHandle_process *process_handle;
2518 gboolean ok;
2519 int signo;
2520 int ret;
2521 pid_t pid;
2523 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2524 /* This is a pseudo handle */
2525 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2526 } else {
2527 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2528 (gpointer *) &process_handle);
2530 if (ok == FALSE) {
2531 #ifdef DEBUG
2532 g_message ("%s: Can't find process %p", __func__,
2533 process);
2534 #endif
2535 SetLastError (ERROR_INVALID_HANDLE);
2536 return FALSE;
2538 pid = process_handle->id;
2541 signo = (exitCode == -1) ? SIGKILL : SIGTERM;
2542 ret = kill (pid, signo);
2543 if (ret == -1) {
2544 switch (errno) {
2545 case EINVAL:
2546 SetLastError (ERROR_INVALID_PARAMETER);
2547 break;
2548 case EPERM:
2549 SetLastError (ERROR_ACCESS_DENIED);
2550 break;
2551 case ESRCH:
2552 SetLastError (ERROR_PROC_NOT_FOUND);
2553 break;
2554 default:
2555 SetLastError (ERROR_GEN_FAILURE);
2559 return (ret == 0);
2562 guint32
2563 GetPriorityClass (gpointer process)
2565 #ifdef HAVE_GETPRIORITY
2566 struct _WapiHandle_process *process_handle;
2567 gboolean ok;
2568 int ret;
2569 pid_t pid;
2571 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2572 /* This is a pseudo handle */
2573 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2574 } else {
2575 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2576 (gpointer *) &process_handle);
2578 if (!ok) {
2579 SetLastError (ERROR_INVALID_HANDLE);
2580 return FALSE;
2582 pid = process_handle->id;
2585 errno = 0;
2586 ret = getpriority (PRIO_PROCESS, pid);
2587 if (ret == -1 && errno != 0) {
2588 switch (errno) {
2589 case EPERM:
2590 case EACCES:
2591 SetLastError (ERROR_ACCESS_DENIED);
2592 break;
2593 case ESRCH:
2594 SetLastError (ERROR_PROC_NOT_FOUND);
2595 break;
2596 default:
2597 SetLastError (ERROR_GEN_FAILURE);
2599 return FALSE;
2602 if (ret == 0)
2603 return NORMAL_PRIORITY_CLASS;
2604 else if (ret < -15)
2605 return REALTIME_PRIORITY_CLASS;
2606 else if (ret < -10)
2607 return HIGH_PRIORITY_CLASS;
2608 else if (ret < 0)
2609 return ABOVE_NORMAL_PRIORITY_CLASS;
2610 else if (ret > 10)
2611 return IDLE_PRIORITY_CLASS;
2612 else if (ret > 0)
2613 return BELOW_NORMAL_PRIORITY_CLASS;
2615 return NORMAL_PRIORITY_CLASS;
2616 #else
2617 SetLastError (ERROR_NOT_SUPPORTED);
2618 return 0;
2619 #endif
2622 gboolean
2623 SetPriorityClass (gpointer process, guint32 priority_class)
2625 #ifdef HAVE_SETPRIORITY
2626 struct _WapiHandle_process *process_handle;
2627 gboolean ok;
2628 int ret;
2629 int prio;
2630 pid_t pid;
2632 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2633 /* This is a pseudo handle */
2634 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2635 } else {
2636 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2637 (gpointer *) &process_handle);
2639 if (!ok) {
2640 SetLastError (ERROR_INVALID_HANDLE);
2641 return FALSE;
2643 pid = process_handle->id;
2646 switch (priority_class) {
2647 case IDLE_PRIORITY_CLASS:
2648 prio = 19;
2649 break;
2650 case BELOW_NORMAL_PRIORITY_CLASS:
2651 prio = 10;
2652 break;
2653 case NORMAL_PRIORITY_CLASS:
2654 prio = 0;
2655 break;
2656 case ABOVE_NORMAL_PRIORITY_CLASS:
2657 prio = -5;
2658 break;
2659 case HIGH_PRIORITY_CLASS:
2660 prio = -11;
2661 break;
2662 case REALTIME_PRIORITY_CLASS:
2663 prio = -20;
2664 break;
2665 default:
2666 SetLastError (ERROR_INVALID_PARAMETER);
2667 return FALSE;
2670 ret = setpriority (PRIO_PROCESS, pid, prio);
2671 if (ret == -1) {
2672 switch (errno) {
2673 case EPERM:
2674 case EACCES:
2675 SetLastError (ERROR_ACCESS_DENIED);
2676 break;
2677 case ESRCH:
2678 SetLastError (ERROR_PROC_NOT_FOUND);
2679 break;
2680 default:
2681 SetLastError (ERROR_GEN_FAILURE);
2685 return ret == 0;
2686 #else
2687 SetLastError (ERROR_NOT_SUPPORTED);
2688 return FALSE;
2689 #endif