Added/Updated .gitignore files
[mono.git] / mono / io-layer / processes.c
blob855f8f0f7d479c72b8ff5d3d1390e67c0bf39bd8
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 /* Implemented as just a wrapper around CreateProcess () */
460 gboolean ShellExecuteEx (WapiShellExecuteInfo *sei)
462 gboolean ret;
463 WapiProcessInformation process_info;
464 gunichar2 *args;
466 if (sei == NULL) {
467 /* w2k just segfaults here, but we can do better than
468 * that
470 SetLastError (ERROR_INVALID_PARAMETER);
471 return (FALSE);
474 if (sei->lpFile == NULL) {
475 /* w2k returns TRUE for this, for some reason. */
476 return (TRUE);
479 /* Put both executable and parameters into the second argument
480 * to CreateProcess (), so it searches $PATH. The conversion
481 * into and back out of utf8 is because there is no
482 * g_strdup_printf () equivalent for gunichar2 :-(
484 args = utf16_concat (sei->lpFile, sei->lpParameters == NULL ? NULL : utf16_space, sei->lpParameters, NULL);
485 if (args == NULL){
486 SetLastError (ERROR_INVALID_DATA);
487 return (FALSE);
489 ret = CreateProcess (NULL, args, NULL, NULL, TRUE,
490 CREATE_UNICODE_ENVIRONMENT, NULL,
491 sei->lpDirectory, NULL, &process_info);
492 g_free (args);
494 if (!ret && GetLastError () == ERROR_OUTOFMEMORY)
495 return ret;
497 if (!ret) {
498 static char *handler;
499 static gunichar2 *handler_utf16;
501 if (handler_utf16 == (gunichar2 *)-1)
502 return FALSE;
504 #ifdef PLATFORM_MACOSX
505 if (is_macos_10_5_or_higher ())
506 handler = g_strdup ("/usr/bin/open -W");
507 else
508 handler = g_strdup ("/usr/bin/open");
509 #else
511 * On Linux, try: xdg-open, the FreeDesktop standard way of doing it,
512 * if that fails, try to use gnome-open, then kfmclient
514 handler = g_find_program_in_path ("xdg-open");
515 if (handler == NULL){
516 handler = g_find_program_in_path ("gnome-open");
517 if (handler == NULL){
518 handler = g_find_program_in_path ("kfmclient");
519 if (handler == NULL){
520 handler_utf16 = (gunichar2 *) -1;
521 return (FALSE);
522 } else {
523 /* kfmclient needs exec argument */
524 char *old = handler;
525 handler = g_strconcat (old, " exec",
526 NULL);
527 g_free (old);
531 #endif
532 handler_utf16 = g_utf8_to_utf16 (handler, -1, NULL, NULL, NULL);
533 g_free (handler);
535 /* Put quotes around the filename, in case it's a url
536 * that contains #'s (CreateProcess() calls
537 * g_shell_parse_argv(), which deliberately throws
538 * away anything after an unquoted #). Fixes bug
539 * 371567.
541 args = utf16_concat (handler_utf16, utf16_space, utf16_quote,
542 sei->lpFile, utf16_quote,
543 sei->lpParameters == NULL ? NULL : utf16_space,
544 sei->lpParameters, NULL);
545 if (args == NULL){
546 SetLastError (ERROR_INVALID_DATA);
547 return FALSE;
549 ret = CreateProcess (NULL, args, NULL, NULL, TRUE,
550 CREATE_UNICODE_ENVIRONMENT, NULL,
551 sei->lpDirectory, NULL, &process_info);
552 g_free (args);
553 if (!ret){
554 SetLastError (ERROR_INVALID_DATA);
555 return FALSE;
559 if (sei->fMask & SEE_MASK_NOCLOSEPROCESS) {
560 sei->hProcess = process_info.hProcess;
561 } else {
562 CloseHandle (process_info.hProcess);
565 return (ret);
568 static gboolean
569 is_managed_binary (const gchar *filename)
571 int original_errno = errno;
572 #if defined(HAVE_LARGE_FILE_SUPPORT) && defined(O_LARGEFILE)
573 int file = open (filename, O_RDONLY | O_LARGEFILE);
574 #else
575 int file = open (filename, O_RDONLY);
576 #endif
577 off_t new_offset;
578 unsigned char buffer[8];
579 off_t file_size, optional_header_offset;
580 off_t pe_header_offset;
581 gboolean managed = FALSE;
582 int num_read;
583 guint32 first_word, second_word;
585 /* If we are unable to open the file, then we definitely
586 * can't say that it is managed. The child mono process
587 * probably wouldn't be able to open it anyway.
589 if (file < 0) {
590 errno = original_errno;
591 return FALSE;
594 /* Retrieve the length of the file for future sanity checks. */
595 file_size = lseek (file, 0, SEEK_END);
596 lseek (file, 0, SEEK_SET);
598 /* We know we need to read a header field at offset 60. */
599 if (file_size < 64)
600 goto leave;
602 num_read = read (file, buffer, 2);
604 if ((num_read != 2) || (buffer[0] != 'M') || (buffer[1] != 'Z'))
605 goto leave;
607 new_offset = lseek (file, 60, SEEK_SET);
609 if (new_offset != 60)
610 goto leave;
612 num_read = read (file, buffer, 4);
614 if (num_read != 4)
615 goto leave;
616 pe_header_offset = buffer[0]
617 | (buffer[1] << 8)
618 | (buffer[2] << 16)
619 | (buffer[3] << 24);
621 if (pe_header_offset + 24 > file_size)
622 goto leave;
624 new_offset = lseek (file, pe_header_offset, SEEK_SET);
626 if (new_offset != pe_header_offset)
627 goto leave;
629 num_read = read (file, buffer, 4);
631 if ((num_read != 4) || (buffer[0] != 'P') || (buffer[1] != 'E') || (buffer[2] != 0) || (buffer[3] != 0))
632 goto leave;
635 * Verify that the header we want in the optional header data
636 * is present in this binary.
638 new_offset = lseek (file, pe_header_offset + 20, SEEK_SET);
640 if (new_offset != pe_header_offset + 20)
641 goto leave;
643 num_read = read (file, buffer, 2);
645 if ((num_read != 2) || ((buffer[0] | (buffer[1] << 8)) < 216))
646 goto leave;
648 /* Read the CLR header address and size fields. These will be
649 * zero if the binary is not managed.
651 optional_header_offset = pe_header_offset + 24;
652 new_offset = lseek (file, optional_header_offset + 208, SEEK_SET);
654 if (new_offset != optional_header_offset + 208)
655 goto leave;
657 num_read = read (file, buffer, 8);
659 /* We are not concerned with endianness, only with
660 * whether it is zero or not.
662 first_word = *(guint32 *)&buffer[0];
663 second_word = *(guint32 *)&buffer[4];
665 if ((num_read != 8) || (first_word == 0) || (second_word == 0))
666 goto leave;
668 managed = TRUE;
670 leave:
671 close (file);
672 errno = original_errno;
673 return managed;
676 gboolean CreateProcessWithLogonW (const gunichar2 *username,
677 const gunichar2 *domain,
678 const gunichar2 *password,
679 const guint32 logonFlags,
680 const gunichar2 *appname,
681 const gunichar2 *cmdline,
682 guint32 create_flags,
683 gpointer env,
684 const gunichar2 *cwd,
685 WapiStartupInfo *startup,
686 WapiProcessInformation *process_info)
688 /* FIXME: use user information */
689 return CreateProcess (appname, cmdline, NULL, NULL, FALSE, create_flags, env, cwd, startup, process_info);
692 static gboolean
693 is_executable (const char *prog)
695 struct stat buf;
696 if (access (prog, X_OK) != 0)
697 return FALSE;
698 if (stat (prog, &buf))
699 return FALSE;
700 if (S_ISREG (buf.st_mode))
701 return TRUE;
702 return FALSE;
705 gboolean CreateProcess (const gunichar2 *appname, const gunichar2 *cmdline,
706 WapiSecurityAttributes *process_attrs G_GNUC_UNUSED,
707 WapiSecurityAttributes *thread_attrs G_GNUC_UNUSED,
708 gboolean inherit_handles, guint32 create_flags,
709 gpointer new_environ, const gunichar2 *cwd,
710 WapiStartupInfo *startup,
711 WapiProcessInformation *process_info)
713 gchar *cmd=NULL, *prog = NULL, *full_prog = NULL, *args = NULL, *args_after_prog = NULL, *dir = NULL, **env_strings = NULL, **argv = NULL;
714 guint32 i, env_count = 0;
715 gboolean ret = FALSE;
716 gpointer handle;
717 struct _WapiHandle_process process_handle = {0}, *process_handle_data;
718 GError *gerr = NULL;
719 int in_fd, out_fd, err_fd;
720 pid_t pid;
721 int thr_ret;
723 mono_once (&process_ops_once, process_ops_init);
725 /* appname and cmdline specify the executable and its args:
727 * If appname is not NULL, it is the name of the executable.
728 * Otherwise the executable is the first token in cmdline.
730 * Executable searching:
732 * If appname is not NULL, it can specify the full path and
733 * file name, or else a partial name and the current directory
734 * will be used. There is no additional searching.
736 * If appname is NULL, the first whitespace-delimited token in
737 * cmdline is used. If the name does not contain a full
738 * directory path, the search sequence is:
740 * 1) The directory containing the current process
741 * 2) The current working directory
742 * 3) The windows system directory (Ignored)
743 * 4) The windows directory (Ignored)
744 * 5) $PATH
746 * Just to make things more interesting, tokens can contain
747 * white space if they are surrounded by quotation marks. I'm
748 * beginning to understand just why windows apps are generally
749 * so crap, with an API like this :-(
751 if (appname != NULL) {
752 cmd = mono_unicode_to_external (appname);
753 if (cmd == NULL) {
754 #ifdef DEBUG
755 g_message ("%s: unicode conversion returned NULL",
756 __func__);
757 #endif
759 SetLastError (ERROR_PATH_NOT_FOUND);
760 goto free_strings;
763 /* Turn all the slashes round the right way */
764 for (i = 0; i < strlen (cmd); i++) {
765 if (cmd[i] == '\\') {
766 cmd[i] = '/';
771 if (cmdline != NULL) {
772 args = mono_unicode_to_external (cmdline);
773 if (args == NULL) {
774 #ifdef DEBUG
775 g_message ("%s: unicode conversion returned NULL", __func__);
776 #endif
778 SetLastError (ERROR_PATH_NOT_FOUND);
779 goto free_strings;
783 if (cwd != NULL) {
784 dir = mono_unicode_to_external (cwd);
785 if (dir == NULL) {
786 #ifdef DEBUG
787 g_message ("%s: unicode conversion returned NULL", __func__);
788 #endif
790 SetLastError (ERROR_PATH_NOT_FOUND);
791 goto free_strings;
794 /* Turn all the slashes round the right way */
795 for (i = 0; i < strlen (dir); i++) {
796 if (dir[i] == '\\') {
797 dir[i] = '/';
803 /* We can't put off locating the executable any longer :-( */
804 if (cmd != NULL) {
805 gchar *unquoted;
806 if (g_ascii_isalpha (cmd[0]) && (cmd[1] == ':')) {
807 /* Strip off the drive letter. I can't
808 * believe that CP/M holdover is still
809 * visible...
811 g_memmove (cmd, cmd+2, strlen (cmd)-2);
812 cmd[strlen (cmd)-2] = '\0';
815 unquoted = g_shell_unquote (cmd, NULL);
816 if (unquoted[0] == '/') {
817 /* Assume full path given */
818 prog = g_strdup (unquoted);
820 /* Executable existing ? */
821 if (!is_executable (prog)) {
822 #ifdef DEBUG
823 g_message ("%s: Couldn't find executable %s",
824 __func__, prog);
825 #endif
826 g_free (unquoted);
827 SetLastError (ERROR_FILE_NOT_FOUND);
828 goto free_strings;
830 } else {
831 /* Search for file named by cmd in the current
832 * directory
834 char *curdir = g_get_current_dir ();
836 prog = g_strdup_printf ("%s/%s", curdir, unquoted);
837 g_free (curdir);
839 /* And make sure it's executable */
840 if (!is_executable (prog)) {
841 #ifdef DEBUG
842 g_message ("%s: Couldn't find executable %s",
843 __func__, prog);
844 #endif
845 g_free (unquoted);
846 SetLastError (ERROR_FILE_NOT_FOUND);
847 goto free_strings;
850 g_free (unquoted);
852 args_after_prog = args;
853 } else {
854 gchar *token = NULL;
855 char quote;
857 /* Dig out the first token from args, taking quotation
858 * marks into account
861 /* First, strip off all leading whitespace */
862 args = g_strchug (args);
864 /* args_after_prog points to the contents of args
865 * after token has been set (otherwise argv[0] is
866 * duplicated)
868 args_after_prog = args;
870 /* Assume the opening quote will always be the first
871 * character
873 if (args[0] == '\"' || args [0] == '\'') {
874 quote = args [0];
875 for (i = 1; args[i] != '\0' && args[i] != quote; i++);
876 if (g_ascii_isspace (args[i+1])) {
877 /* We found the first token */
878 token = g_strndup (args+1, i-1);
879 args_after_prog = args + i;
880 } else {
881 /* Quotation mark appeared in the
882 * middle of the token. Just give the
883 * whole first token, quotes and all,
884 * to exec.
889 if (token == NULL) {
890 /* No quote mark, or malformed */
891 for (i = 0; args[i] != '\0'; i++) {
892 if (g_ascii_isspace (args[i])) {
893 token = g_strndup (args, i);
894 args_after_prog = args + i + 1;
895 break;
900 if (token == NULL && args[0] != '\0') {
901 /* Must be just one token in the string */
902 token = g_strdup (args);
903 args_after_prog = NULL;
906 if (token == NULL) {
907 /* Give up */
908 #ifdef DEBUG
909 g_message ("%s: Couldn't find what to exec", __func__);
910 #endif
912 SetLastError (ERROR_PATH_NOT_FOUND);
913 goto free_strings;
916 /* Turn all the slashes round the right way. Only for
917 * the prg. name
919 for (i = 0; i < strlen (token); i++) {
920 if (token[i] == '\\') {
921 token[i] = '/';
925 if (g_ascii_isalpha (token[0]) && (token[1] == ':')) {
926 /* Strip off the drive letter. I can't
927 * believe that CP/M holdover is still
928 * visible...
930 g_memmove (token, token+2, strlen (token)-2);
931 token[strlen (token)-2] = '\0';
934 if (token[0] == '/') {
935 /* Assume full path given */
936 prog = g_strdup (token);
938 /* Executable existing ? */
939 if (!is_executable (prog)) {
940 #ifdef DEBUG
941 g_message ("%s: Couldn't find executable %s",
942 __func__, token);
943 #endif
944 g_free (token);
945 SetLastError (ERROR_FILE_NOT_FOUND);
946 goto free_strings;
949 } else {
950 char *curdir = g_get_current_dir ();
952 /* FIXME: Need to record the directory
953 * containing the current process, and check
954 * that for the new executable as the first
955 * place to look
958 prog = g_strdup_printf ("%s/%s", curdir, token);
959 g_free (curdir);
961 /* I assume X_OK is the criterion to use,
962 * rather than F_OK
964 if (!is_executable (prog)) {
965 g_free (prog);
966 prog = g_find_program_in_path (token);
967 if (prog == NULL) {
968 #ifdef DEBUG
969 g_message ("%s: Couldn't find executable %s", __func__, token);
970 #endif
972 g_free (token);
973 SetLastError (ERROR_FILE_NOT_FOUND);
974 goto free_strings;
979 g_free (token);
982 #ifdef DEBUG
983 g_message ("%s: Exec prog [%s] args [%s]", __func__, prog,
984 args_after_prog);
985 #endif
987 /* Check for CLR binaries; if found, we will try to invoke
988 * them using the same mono binary that started us.
990 if (is_managed_binary (prog)) {
991 gunichar2 *newapp, *newcmd;
992 gsize bytes_ignored;
994 newapp = mono_unicode_from_external ("mono", &bytes_ignored);
996 if (newapp != NULL) {
997 if (appname != NULL) {
998 newcmd = utf16_concat (newapp, utf16_space,
999 appname, utf16_space,
1000 cmdline, NULL);
1001 } else {
1002 newcmd = utf16_concat (newapp, utf16_space,
1003 cmdline, NULL);
1006 g_free ((gunichar2 *)newapp);
1008 if (newcmd != NULL) {
1009 ret = CreateProcess (NULL, newcmd,
1010 process_attrs,
1011 thread_attrs,
1012 inherit_handles,
1013 create_flags, new_environ,
1014 cwd, startup,
1015 process_info);
1017 g_free ((gunichar2 *)newcmd);
1019 goto free_strings;
1024 if (args_after_prog != NULL && *args_after_prog) {
1025 gchar *qprog;
1027 qprog = g_shell_quote (prog);
1028 full_prog = g_strconcat (qprog, " ", args_after_prog, NULL);
1029 g_free (qprog);
1030 } else {
1031 full_prog = g_shell_quote (prog);
1034 ret = g_shell_parse_argv (full_prog, NULL, &argv, &gerr);
1035 if (ret == FALSE) {
1036 /* FIXME: Could do something with the GError here
1040 if (startup != NULL && startup->dwFlags & STARTF_USESTDHANDLES) {
1041 in_fd = GPOINTER_TO_UINT (startup->hStdInput);
1042 out_fd = GPOINTER_TO_UINT (startup->hStdOutput);
1043 err_fd = GPOINTER_TO_UINT (startup->hStdError);
1044 } else {
1045 in_fd = GPOINTER_TO_UINT (GetStdHandle (STD_INPUT_HANDLE));
1046 out_fd = GPOINTER_TO_UINT (GetStdHandle (STD_OUTPUT_HANDLE));
1047 err_fd = GPOINTER_TO_UINT (GetStdHandle (STD_ERROR_HANDLE));
1050 g_strlcpy (process_handle.proc_name, prog,
1051 _WAPI_PROC_NAME_MAX_LEN - 1);
1053 process_set_defaults (&process_handle);
1055 handle = _wapi_handle_new (WAPI_HANDLE_PROCESS, &process_handle);
1056 if (handle == _WAPI_HANDLE_INVALID) {
1057 g_warning ("%s: error creating process handle", __func__);
1059 ret = FALSE;
1060 SetLastError (ERROR_OUTOFMEMORY);
1061 goto free_strings;
1064 /* Hold another reference so the process has somewhere to
1065 * store its exit data even if we drop this handle
1067 _wapi_handle_ref (handle);
1069 /* new_environ is a block of NULL-terminated strings, which
1070 * is itself NULL-terminated. Of course, passing an array of
1071 * string pointers would have made things too easy :-(
1073 * If new_environ is not NULL it specifies the entire set of
1074 * environment variables in the new process. Otherwise the
1075 * new process inherits the same environment.
1077 if (new_environ != NULL) {
1078 gunichar2 *new_environp;
1080 /* Count the number of strings */
1081 for (new_environp = (gunichar2 *)new_environ; *new_environp;
1082 new_environp++) {
1083 env_count++;
1084 while (*new_environp) {
1085 new_environp++;
1089 /* +2: one for the process handle value, and the last
1090 * one is NULL
1092 env_strings = g_new0 (gchar *, env_count + 2);
1094 /* Copy each environ string into 'strings' turning it
1095 * into utf8 (or the requested encoding) at the same
1096 * time
1098 env_count = 0;
1099 for (new_environp = (gunichar2 *)new_environ; *new_environp;
1100 new_environp++) {
1101 env_strings[env_count] = mono_unicode_to_external (new_environp);
1102 env_count++;
1103 while (*new_environp) {
1104 new_environp++;
1107 } else {
1108 for (i = 0; environ[i] != NULL; i++) {
1109 env_count++;
1112 /* +2: one for the process handle value, and the last
1113 * one is NULL
1115 env_strings = g_new0 (gchar *, env_count + 2);
1117 /* Copy each environ string into 'strings' turning it
1118 * into utf8 (or the requested encoding) at the same
1119 * time
1121 env_count = 0;
1122 for (i = 0; environ[i] != NULL; i++) {
1123 env_strings[env_count] = g_strdup (environ[i]);
1124 env_count++;
1127 /* pass process handle info to the child, so it doesn't have
1128 * to do an expensive search over the whole list
1130 if (env_strings != NULL) {
1131 struct _WapiHandleUnshared *handle_data;
1132 struct _WapiHandle_shared_ref *ref;
1134 handle_data = &_WAPI_PRIVATE_HANDLES(GPOINTER_TO_UINT(handle));
1135 ref = &handle_data->u.shared;
1137 env_strings[env_count] = g_strdup_printf ("_WAPI_PROCESS_HANDLE_OFFSET=%d", ref->offset);
1140 thr_ret = _wapi_handle_lock_shared_handles ();
1141 g_assert (thr_ret == 0);
1143 pid = fork ();
1144 if (pid == -1) {
1145 /* Error */
1146 SetLastError (ERROR_OUTOFMEMORY);
1147 _wapi_handle_unref (handle);
1148 goto cleanup;
1149 } else if (pid == 0) {
1150 /* Child */
1152 if (_wapi_shm_disabled == FALSE) {
1153 /* Wait for the parent to finish setting up
1154 * the handle. The semaphore lock is safe
1155 * because the sem_undo structures of a
1156 * semaphore aren't inherited across a fork
1157 * (), but we can't do this if we're not using
1158 * the shared memory
1160 thr_ret = _wapi_handle_lock_shared_handles ();
1161 g_assert (thr_ret == 0);
1163 _wapi_handle_unlock_shared_handles ();
1166 /* should we detach from the process group? */
1168 /* Connect stdin, stdout and stderr */
1169 dup2 (in_fd, 0);
1170 dup2 (out_fd, 1);
1171 dup2 (err_fd, 2);
1173 if (inherit_handles != TRUE) {
1174 /* FIXME: do something here */
1177 /* Close all file descriptors */
1178 for (i = getdtablesize () - 1; i > 2; i--) {
1179 close (i);
1182 #ifdef DEBUG
1183 g_message ("%s: exec()ing [%s] in dir [%s]", __func__, cmd,
1184 dir==NULL?".":dir);
1185 for (i = 0; argv[i] != NULL; i++) {
1186 g_message ("arg %d: [%s]", i, argv[i]);
1189 for (i = 0; env_strings[i] != NULL; i++) {
1190 g_message ("env %d: [%s]", i, env_strings[i]);
1192 #endif
1194 /* set cwd */
1195 if (dir != NULL && chdir (dir) == -1) {
1196 /* set error */
1197 _exit (-1);
1200 /* exec */
1201 execve (argv[0], argv, env_strings);
1203 /* set error */
1204 _exit (-1);
1206 /* parent */
1208 ret = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
1209 (gpointer *)&process_handle_data);
1210 if (ret == FALSE) {
1211 g_warning ("%s: error looking up process handle %p", __func__,
1212 handle);
1213 _wapi_handle_unref (handle);
1214 goto cleanup;
1217 process_handle_data->id = pid;
1219 if (process_info != NULL) {
1220 process_info->hProcess = handle;
1221 process_info->dwProcessId = pid;
1223 /* FIXME: we might need to handle the thread info some
1224 * day
1226 process_info->hThread = INVALID_HANDLE_VALUE;
1227 process_info->dwThreadId = 0;
1230 cleanup:
1231 _wapi_handle_unlock_shared_handles ();
1233 free_strings:
1234 if (cmd != NULL) {
1235 g_free (cmd);
1237 if (full_prog != NULL) {
1238 g_free (full_prog);
1240 if (prog != NULL) {
1241 g_free (prog);
1243 if (args != NULL) {
1244 g_free (args);
1246 if (dir != NULL) {
1247 g_free (dir);
1249 if(env_strings != NULL) {
1250 g_strfreev (env_strings);
1252 if (argv != NULL) {
1253 g_strfreev (argv);
1256 #ifdef DEBUG
1257 g_message ("%s: returning handle %p for pid %d", __func__, handle,
1258 pid);
1259 #endif
1261 return(ret);
1264 static void process_set_name (struct _WapiHandle_process *process_handle)
1266 gchar *progname, *utf8_progname, *slash;
1268 progname=g_get_prgname ();
1269 utf8_progname=mono_utf8_from_external (progname);
1271 #ifdef DEBUG
1272 g_message ("%s: using [%s] as prog name", __func__, progname);
1273 #endif
1275 if(utf8_progname!=NULL) {
1276 slash=strrchr (utf8_progname, '/');
1277 if(slash!=NULL) {
1278 g_strlcpy (process_handle->proc_name, slash+1,
1279 _WAPI_PROC_NAME_MAX_LEN - 1);
1280 } else {
1281 g_strlcpy (process_handle->proc_name, utf8_progname,
1282 _WAPI_PROC_NAME_MAX_LEN - 1);
1285 g_free (utf8_progname);
1289 extern void _wapi_time_t_to_filetime (time_t timeval, WapiFileTime *filetime);
1291 #if !GLIB_CHECK_VERSION (2,4,0)
1292 #define g_setenv(a,b,c) setenv(a,b,c)
1293 #define g_unsetenv(a) unsetenv(a)
1294 #endif
1296 static void process_set_current (void)
1298 pid_t pid = _wapi_getpid ();
1299 const char *handle_env;
1300 struct _WapiHandle_process process_handle = {0};
1302 mono_once (&process_ops_once, process_ops_init);
1304 handle_env = g_getenv ("_WAPI_PROCESS_HANDLE_OFFSET");
1305 g_unsetenv ("_WAPI_PROCESS_HANDLE_OFFSET");
1307 if (handle_env != NULL) {
1308 struct _WapiHandle_process *process_handlep;
1309 gchar *procname = NULL;
1310 gboolean ok;
1312 current_process = _wapi_handle_new_from_offset (WAPI_HANDLE_PROCESS, atoi (handle_env), TRUE);
1314 #ifdef DEBUG
1315 g_message ("%s: Found my process handle: %p (offset %d 0x%x)",
1316 __func__, current_process, atoi (handle_env),
1317 atoi (handle_env));
1318 #endif
1320 ok = _wapi_lookup_handle (current_process, WAPI_HANDLE_PROCESS,
1321 (gpointer *)&process_handlep);
1322 if (ok) {
1323 /* This test will probably break on linuxthreads, but
1324 * that should be ancient history on all distros we
1325 * care about by now
1327 if (process_handlep->id == pid) {
1328 procname = process_handlep->proc_name;
1329 if (!strcmp (procname, "mono")) {
1330 /* Set a better process name */
1331 #ifdef DEBUG
1332 g_message ("%s: Setting better process name", __func__);
1333 #endif
1335 process_set_name (process_handlep);
1336 } else {
1337 #ifdef DEBUG
1338 g_message ("%s: Leaving process name: %s", __func__, procname);
1339 #endif
1342 return;
1345 /* Wrong pid, so drop this handle and fall through to
1346 * create a new one
1348 _wapi_handle_unref (current_process);
1352 /* We get here if the handle wasn't specified in the
1353 * environment, or if the process ID was wrong, or if the
1354 * handle lookup failed (eg if the parent process forked and
1355 * quit immediately, and deleted the shared data before the
1356 * child got a chance to attach it.)
1359 #ifdef DEBUG
1360 g_message ("%s: Need to create my own process handle", __func__);
1361 #endif
1363 process_handle.id = pid;
1365 process_set_defaults (&process_handle);
1366 process_set_name (&process_handle);
1368 current_process = _wapi_handle_new (WAPI_HANDLE_PROCESS,
1369 &process_handle);
1370 if (current_process == _WAPI_HANDLE_INVALID) {
1371 g_warning ("%s: error creating process handle", __func__);
1372 return;
1376 gpointer _wapi_process_duplicate ()
1378 mono_once (&process_current_once, process_set_current);
1380 _wapi_handle_ref (current_process);
1382 return(current_process);
1385 /* Returns a pseudo handle that doesn't need to be closed afterwards */
1386 gpointer GetCurrentProcess (void)
1388 mono_once (&process_current_once, process_set_current);
1390 return(_WAPI_PROCESS_CURRENT);
1393 guint32 GetProcessId (gpointer handle)
1395 struct _WapiHandle_process *process_handle;
1396 gboolean ok;
1398 if ((GPOINTER_TO_UINT (handle) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
1399 /* This is a pseudo handle */
1400 return(GPOINTER_TO_UINT (handle) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
1403 ok = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
1404 (gpointer *)&process_handle);
1405 if (ok == FALSE) {
1406 SetLastError (ERROR_INVALID_HANDLE);
1407 return (0);
1410 return (process_handle->id);
1413 guint32 GetCurrentProcessId (void)
1415 mono_once (&process_current_once, process_set_current);
1417 return (GetProcessId (current_process));
1420 /* Returns the process id as a convenience to the functions that call this */
1421 static pid_t signal_process_if_gone (gpointer handle)
1423 struct _WapiHandle_process *process_handle;
1424 gboolean ok;
1426 g_assert ((GPOINTER_TO_UINT (handle) & _WAPI_PROCESS_UNHANDLED) != _WAPI_PROCESS_UNHANDLED);
1428 /* Make sure the process is signalled if it has exited - if
1429 * the parent process didn't wait for it then it won't be
1431 ok = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
1432 (gpointer *)&process_handle);
1433 if (ok == FALSE) {
1434 /* It's possible that the handle has vanished during
1435 * the _wapi_search_handle before it gets here, so
1436 * don't spam the console with warnings.
1438 /* g_warning ("%s: error looking up process handle %p",
1439 __func__, handle);*/
1441 return (0);
1444 #ifdef DEBUG
1445 g_message ("%s: looking at process %d", __func__, process_handle->id);
1446 #endif
1448 if (kill (process_handle->id, 0) == -1 &&
1449 (errno == ESRCH ||
1450 errno == EPERM)) {
1451 /* The process is dead, (EPERM tells us a new process
1452 * has that ID, but as it's owned by someone else it
1453 * can't be the one listed in our shared memory file)
1455 _wapi_shared_handle_set_signal_state (handle, TRUE);
1458 return (process_handle->id);
1461 #ifdef UNUSED_CODE
1462 static gboolean process_enum (gpointer handle, gpointer user_data)
1464 GArray *processes=user_data;
1465 pid_t pid = signal_process_if_gone (handle);
1466 int i;
1468 if (pid == 0) {
1469 return (FALSE);
1472 /* Ignore processes that have already exited (ie they are signalled) */
1473 if (_wapi_handle_issignalled (handle) == FALSE) {
1474 #ifdef DEBUG
1475 g_message ("%s: process %d added to array", __func__, pid);
1476 #endif
1478 /* This ensures that duplicates aren't returned (see
1479 * the comment above _wapi_search_handle () for why
1480 * it's needed
1482 for (i = 0; i < processes->len; i++) {
1483 if (g_array_index (processes, pid_t, i) == pid) {
1484 /* We've already got this one, return
1485 * FALSE to keep searching
1487 return (FALSE);
1491 g_array_append_val (processes, pid);
1494 /* Return false to keep searching */
1495 return(FALSE);
1497 #endif /* UNUSED_CODE */
1499 #ifdef PLATFORM_MACOSX
1501 gboolean EnumProcesses (guint32 *pids, guint32 len, guint32 *needed)
1503 guint32 count, fit, i, j;
1504 gint32 err;
1505 gboolean done;
1506 struct kinfo_proc *result;
1507 size_t proclength;
1508 static const int name[] = { CTL_KERN, KERN_PROC, KERN_PROC_ALL, 0 };
1510 mono_once (&process_current_once, process_set_current);
1512 result = NULL;
1513 done = FALSE;
1515 do {
1516 proclength = 0;
1517 err = sysctl ((int *)name, (sizeof(name) / sizeof(*name)) - 1, NULL, &proclength, NULL, 0);
1519 if (err == 0) {
1520 result = malloc (proclength);
1521 if (result == NULL)
1522 return FALSE;
1524 err = sysctl ((int *) name, (sizeof(name) / sizeof(*name)) - 1, result, &proclength, NULL, 0);
1526 if (err == 0)
1527 done = TRUE;
1528 else
1529 free (result);
1531 } while (err == 0 && !done);
1533 if (err != 0) {
1534 if (result != NULL) {
1535 free (result);
1536 result = NULL;
1538 return(FALSE);
1541 count = proclength / sizeof(struct kinfo_proc);
1542 fit = len / sizeof(guint32);
1543 for (i = 0, j = 0; j< fit && i < count; i++) {
1544 pids [j++] = result [i].kp_proc.p_pid;
1546 free (result);
1547 result = NULL;
1548 *needed = j * sizeof(guint32);
1550 return(TRUE);
1552 #else
1553 gboolean EnumProcesses (guint32 *pids, guint32 len, guint32 *needed)
1555 GArray *processes = g_array_new (FALSE, FALSE, sizeof(pid_t));
1556 guint32 fit, i, j;
1557 DIR *dir;
1558 struct dirent *entry;
1560 mono_once (&process_current_once, process_set_current);
1562 dir = opendir ("/proc");
1563 if (dir == NULL) {
1564 return(FALSE);
1566 while((entry = readdir (dir)) != NULL) {
1567 if (isdigit (entry->d_name[0])) {
1568 char *endptr;
1569 pid_t pid = (pid_t)strtol (entry->d_name, &endptr, 10);
1571 if (*endptr == '\0') {
1572 /* Name was entirely numeric, so was a
1573 * process ID
1575 g_array_append_val (processes, pid);
1579 closedir (dir);
1581 fit=len/sizeof(guint32);
1582 for (i = 0, j = 0; j < fit && i < processes->len; i++) {
1583 pids[j++] = g_array_index (processes, pid_t, i);
1586 g_array_free (processes, TRUE);
1588 *needed = j * sizeof(guint32);
1590 return(TRUE);
1592 #endif
1594 static gboolean process_open_compare (gpointer handle, gpointer user_data)
1596 pid_t wanted_pid;
1597 pid_t checking_pid = signal_process_if_gone (handle);
1599 if (checking_pid == 0) {
1600 return(FALSE);
1603 wanted_pid = GPOINTER_TO_UINT (user_data);
1605 /* It's possible to have more than one process handle with the
1606 * same pid, but only the one running process can be
1607 * unsignalled
1609 if (checking_pid == wanted_pid &&
1610 _wapi_handle_issignalled (handle) == FALSE) {
1611 /* If the handle is blown away in the window between
1612 * returning TRUE here and _wapi_search_handle pinging
1613 * the timestamp, the search will continue
1615 return(TRUE);
1616 } else {
1617 return(FALSE);
1621 gpointer OpenProcess (guint32 req_access G_GNUC_UNUSED, gboolean inherit G_GNUC_UNUSED, guint32 pid)
1623 /* Find the process handle that corresponds to pid */
1624 gpointer handle;
1626 mono_once (&process_current_once, process_set_current);
1628 #ifdef DEBUG
1629 g_message ("%s: looking for process %d", __func__, pid);
1630 #endif
1632 handle = _wapi_search_handle (WAPI_HANDLE_PROCESS,
1633 process_open_compare,
1634 GUINT_TO_POINTER (pid), NULL, TRUE);
1635 if (handle == 0) {
1636 gchar *dir = g_strdup_printf ("/proc/%d", pid);
1637 if (!access (dir, F_OK)) {
1638 /* Return a pseudo handle for processes we
1639 * don't have handles for
1641 return GINT_TO_POINTER (_WAPI_PROCESS_UNHANDLED + pid);
1642 } else {
1643 #ifdef DEBUG
1644 g_message ("%s: Can't find pid %d", __func__, pid);
1645 #endif
1647 SetLastError (ERROR_PROC_NOT_FOUND);
1649 return(NULL);
1653 _wapi_handle_ref (handle);
1655 return(handle);
1658 gboolean GetExitCodeProcess (gpointer process, guint32 *code)
1660 struct _WapiHandle_process *process_handle;
1661 gboolean ok;
1663 mono_once (&process_current_once, process_set_current);
1665 if(code==NULL) {
1666 return(FALSE);
1669 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
1670 /* This is a pseudo handle, so we don't know what the
1671 * exit code was
1673 return(FALSE);
1676 ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
1677 (gpointer *)&process_handle);
1678 if(ok==FALSE) {
1679 #ifdef DEBUG
1680 g_message ("%s: Can't find process %p", __func__, process);
1681 #endif
1683 return(FALSE);
1686 /* A process handle is only signalled if the process has exited
1687 * and has been waited for */
1689 /* Make sure any process exit has been noticed, before
1690 * checking if the process is signalled. Fixes bug 325463.
1692 process_wait (process, 0);
1694 if (_wapi_handle_issignalled (process) == TRUE) {
1695 *code = process_handle->exitstatus;
1696 } else {
1697 *code = STILL_ACTIVE;
1700 return(TRUE);
1703 gboolean GetProcessTimes (gpointer process, WapiFileTime *create_time,
1704 WapiFileTime *exit_time, WapiFileTime *kernel_time,
1705 WapiFileTime *user_time)
1707 struct _WapiHandle_process *process_handle;
1708 gboolean ok;
1709 gboolean ku_times_set = FALSE;
1711 mono_once (&process_current_once, process_set_current);
1713 if(create_time==NULL || exit_time==NULL || kernel_time==NULL ||
1714 user_time==NULL) {
1715 /* Not sure if w32 allows NULLs here or not */
1716 return(FALSE);
1719 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
1720 /* This is a pseudo handle, so just fail for now
1722 return(FALSE);
1725 ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
1726 (gpointer *)&process_handle);
1727 if(ok==FALSE) {
1728 #ifdef DEBUG
1729 g_message ("%s: Can't find process %p", __func__, process);
1730 #endif
1732 return(FALSE);
1735 *create_time=process_handle->create_time;
1737 /* A process handle is only signalled if the process has
1738 * exited. Otherwise exit_time isn't set
1740 if(_wapi_handle_issignalled (process)==TRUE) {
1741 *exit_time=process_handle->exit_time;
1744 #ifdef HAVE_GETRUSAGE
1745 if (process_handle->id == getpid ()) {
1746 struct rusage time_data;
1747 if (getrusage (RUSAGE_SELF, &time_data) == 0) {
1748 gint64 tick_val;
1749 gint64 *tick_val_ptr;
1750 ku_times_set = TRUE;
1751 tick_val = time_data.ru_utime.tv_sec * 10000000 + time_data.ru_utime.tv_usec * 10;
1752 tick_val_ptr = (gint64*)user_time;
1753 *tick_val_ptr = tick_val;
1754 tick_val = time_data.ru_stime.tv_sec * 10000000 + time_data.ru_stime.tv_usec * 10;
1755 tick_val_ptr = (gint64*)kernel_time;
1756 *tick_val_ptr = tick_val;
1759 #endif
1760 if (!ku_times_set) {
1761 memset (kernel_time, 0, sizeof (WapiFileTime));
1762 memset (user_time, 0, sizeof (WapiFileTime));
1765 return(TRUE);
1768 typedef struct
1770 gpointer address_start;
1771 gpointer address_end;
1772 gchar *perms;
1773 gpointer address_offset;
1774 dev_t device;
1775 ino_t inode;
1776 gchar *filename;
1777 } WapiProcModule;
1779 static void free_procmodule (WapiProcModule *mod)
1781 if (mod->perms != NULL) {
1782 g_free (mod->perms);
1784 if (mod->filename != NULL) {
1785 g_free (mod->filename);
1787 g_free (mod);
1790 static gint find_procmodule (gconstpointer a, gconstpointer b)
1792 WapiProcModule *want = (WapiProcModule *)a;
1793 WapiProcModule *compare = (WapiProcModule *)b;
1795 if ((want->device == compare->device) &&
1796 (want->inode == compare->inode)) {
1797 return(0);
1798 } else {
1799 return(1);
1803 #ifdef PLATFORM_MACOSX
1804 #include <mach-o/dyld.h>
1805 #include <mach-o/getsect.h>
1807 static GSList *load_modules (void)
1809 GSList *ret = NULL;
1810 WapiProcModule *mod;
1811 uint32_t count = _dyld_image_count ();
1812 int i = 0;
1814 for (i = 0; i < count; i++) {
1815 const struct mach_header *hdr;
1816 const struct section *sec;
1817 const char *name;
1818 intptr_t slide;
1820 slide = _dyld_get_image_vmaddr_slide (i);
1821 name = _dyld_get_image_name (i);
1822 hdr = _dyld_get_image_header (i);
1823 sec = getsectbynamefromheader (hdr, SEG_DATA, SECT_DATA);
1825 /* Some dynlibs do not have data sections on osx (#533893) */
1826 if (sec == 0) {
1827 continue;
1830 mod = g_new0 (WapiProcModule, 1);
1831 mod->address_start = GINT_TO_POINTER (sec->addr);
1832 mod->address_end = GINT_TO_POINTER (sec->addr+sec->size);
1833 mod->perms = g_strdup ("r--p");
1834 mod->address_offset = 0;
1835 mod->device = makedev (0, 0);
1836 mod->inode = (ino_t) i;
1837 mod->filename = g_strdup (name);
1839 if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
1840 ret = g_slist_prepend (ret, mod);
1841 } else {
1842 free_procmodule (mod);
1846 ret = g_slist_reverse (ret);
1848 return(ret);
1850 #else
1851 static GSList *load_modules (FILE *fp)
1853 GSList *ret = NULL;
1854 WapiProcModule *mod;
1855 gchar buf[MAXPATHLEN + 1], *p, *endp;
1856 gchar *start_start, *end_start, *prot_start, *offset_start;
1857 gchar *maj_dev_start, *min_dev_start, *inode_start, prot_buf[5];
1858 gpointer address_start, address_end, address_offset;
1859 guint32 maj_dev, min_dev;
1860 ino_t inode;
1861 dev_t device;
1863 while (fgets (buf, sizeof(buf), fp)) {
1864 p = buf;
1865 while (g_ascii_isspace (*p)) ++p;
1866 start_start = p;
1867 if (!g_ascii_isxdigit (*start_start)) {
1868 continue;
1870 address_start = (gpointer)strtoul (start_start, &endp, 16);
1871 p = endp;
1872 if (*p != '-') {
1873 continue;
1876 ++p;
1877 end_start = p;
1878 if (!g_ascii_isxdigit (*end_start)) {
1879 continue;
1881 address_end = (gpointer)strtoul (end_start, &endp, 16);
1882 p = endp;
1883 if (!g_ascii_isspace (*p)) {
1884 continue;
1887 while (g_ascii_isspace (*p)) ++p;
1888 prot_start = p;
1889 if (*prot_start != 'r' && *prot_start != '-') {
1890 continue;
1892 memcpy (prot_buf, prot_start, 4);
1893 prot_buf[4] = '\0';
1894 while (!g_ascii_isspace (*p)) ++p;
1896 while (g_ascii_isspace (*p)) ++p;
1897 offset_start = p;
1898 if (!g_ascii_isxdigit (*offset_start)) {
1899 continue;
1901 address_offset = (gpointer)strtoul (offset_start, &endp, 16);
1902 p = endp;
1903 if (!g_ascii_isspace (*p)) {
1904 continue;
1907 while(g_ascii_isspace (*p)) ++p;
1908 maj_dev_start = p;
1909 if (!g_ascii_isxdigit (*maj_dev_start)) {
1910 continue;
1912 maj_dev = strtoul (maj_dev_start, &endp, 16);
1913 p = endp;
1914 if (*p != ':') {
1915 continue;
1918 ++p;
1919 min_dev_start = p;
1920 if (!g_ascii_isxdigit (*min_dev_start)) {
1921 continue;
1923 min_dev = strtoul (min_dev_start, &endp, 16);
1924 p = endp;
1925 if (!g_ascii_isspace (*p)) {
1926 continue;
1929 while (g_ascii_isspace (*p)) ++p;
1930 inode_start = p;
1931 if (!g_ascii_isxdigit (*inode_start)) {
1932 continue;
1934 inode = (ino_t)strtol (inode_start, &endp, 10);
1935 p = endp;
1936 if (!g_ascii_isspace (*p)) {
1937 continue;
1940 device = makedev ((int)maj_dev, (int)min_dev);
1941 if ((device == 0) &&
1942 (inode == 0)) {
1943 continue;
1946 while(g_ascii_isspace (*p)) ++p;
1947 /* p now points to the filename */
1949 mod = g_new0 (WapiProcModule, 1);
1950 mod->address_start = address_start;
1951 mod->address_end = address_end;
1952 mod->perms = g_strdup (prot_buf);
1953 mod->address_offset = address_offset;
1954 mod->device = device;
1955 mod->inode = inode;
1956 mod->filename = g_strdup (g_strstrip (p));
1958 if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
1959 ret = g_slist_prepend (ret, mod);
1960 } else {
1961 free_procmodule (mod);
1965 ret = g_slist_reverse (ret);
1967 return(ret);
1969 #endif
1971 static gboolean match_procname_to_modulename (gchar *procname, gchar *modulename)
1973 char* lastsep = NULL;
1974 char* pname = NULL;
1975 char* mname = NULL;
1976 gboolean result = FALSE;
1978 if (procname == NULL || modulename == NULL)
1979 return (FALSE);
1981 pname = mono_path_resolve_symlinks (procname);
1982 mname = mono_path_resolve_symlinks (modulename);
1984 if (!strcmp (pname, mname))
1985 result = TRUE;
1987 if (!result) {
1988 lastsep = strrchr (mname, '/');
1989 if (lastsep)
1990 if (!strcmp (lastsep+1, pname))
1991 result = TRUE;
1994 g_free (pname);
1995 g_free (mname);
1997 return result;
2000 static FILE *
2001 open_process_map (int pid, const char *mode)
2003 FILE *fp = NULL;
2004 const gchar *proc_path[] = {
2005 "/proc/%d/maps", /* GNU/Linux */
2006 "/proc/%d/map", /* FreeBSD */
2007 NULL
2009 int i;
2010 gchar *filename;
2012 for (i = 0; fp == NULL && proc_path [i]; i++) {
2013 filename = g_strdup_printf (proc_path[i], pid);
2014 fp = fopen (filename, mode);
2015 g_free (filename);
2018 return fp;
2021 gboolean EnumProcessModules (gpointer process, gpointer *modules,
2022 guint32 size, guint32 *needed)
2024 struct _WapiHandle_process *process_handle;
2025 gboolean ok;
2026 FILE *fp;
2027 GSList *mods = NULL;
2028 WapiProcModule *module;
2029 guint32 count, avail = size / sizeof(gpointer);
2030 int i;
2031 pid_t pid;
2032 gchar *proc_name = NULL;
2034 /* Store modules in an array of pointers (main module as
2035 * modules[0]), using the load address for each module as a
2036 * token. (Use 'NULL' as an alternative for the main module
2037 * so that the simple implementation can just return one item
2038 * for now.) Get the info from /proc/<pid>/maps on linux,
2039 * /proc/<pid>/map on FreeBSD, other systems will have to
2040 * implement /dev/kmem reading or whatever other horrid
2041 * technique is needed.
2043 if (size < sizeof(gpointer)) {
2044 return(FALSE);
2047 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2048 /* This is a pseudo handle */
2049 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2050 } else {
2051 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2052 (gpointer *)&process_handle);
2053 if (ok == FALSE) {
2054 #ifdef DEBUG
2055 g_message ("%s: Can't find process %p", __func__, process);
2056 #endif
2058 return(FALSE);
2060 pid = process_handle->id;
2061 proc_name = process_handle->proc_name;
2064 #ifdef PLATFORM_MACOSX
2066 mods = load_modules ();
2067 #else
2068 if ((fp = open_process_map (pid, "r")) == NULL) {
2069 /* No /proc/<pid>/maps so just return the main module
2070 * shortcut for now
2072 modules[0] = NULL;
2073 *needed = sizeof(gpointer);
2074 } else {
2075 mods = load_modules (fp);
2076 fclose (fp);
2077 #endif
2078 count = g_slist_length (mods);
2080 /* count + 1 to leave slot 0 for the main module */
2081 *needed = sizeof(gpointer) * (count + 1);
2083 /* Use the NULL shortcut, as the first line in
2084 * /proc/<pid>/maps isn't the executable, and we need
2085 * that first in the returned list. Check the module name
2086 * to see if it ends with the proc name and substitute
2087 * the first entry with it. FIXME if this turns out to
2088 * be a problem.
2090 modules[0] = NULL;
2091 for (i = 0; i < (avail - 1) && i < count; i++) {
2092 module = (WapiProcModule *)g_slist_nth_data (mods, i);
2093 if (modules[0] != NULL)
2094 modules[i] = module->address_start;
2095 else if (match_procname_to_modulename (proc_name, module->filename))
2096 modules[0] = module->address_start;
2097 else
2098 modules[i + 1] = module->address_start;
2101 for (i = 0; i < count; i++) {
2102 free_procmodule (g_slist_nth_data (mods, i));
2104 g_slist_free (mods);
2107 return(TRUE);
2110 static gchar *get_process_name_from_proc (pid_t pid)
2112 gchar *filename = NULL;
2113 gchar *ret = NULL;
2114 gchar buf[256];
2115 FILE *fp;
2117 #if defined(PLATFORM_SOLARIS)
2118 filename = g_strdup_printf ("/proc/%d/psinfo", pid);
2119 if ((fp = fopen (filename, "r")) != NULL) {
2120 struct psinfo info;
2121 int nread;
2123 nread = fread (&info, sizeof (info), 1, fp);
2124 if (nread == 1) {
2125 ret = g_strdup (info.pr_fname);
2128 fclose (fp);
2130 g_free (filename);
2131 #elif defined(PLATFORM_MACOSX)
2132 memset (buf, '\0', sizeof(buf));
2133 proc_name (pid, buf, sizeof(buf));
2134 if (strlen (buf) > 0)
2135 ret = g_strdup (buf);
2136 #else
2137 memset (buf, '\0', sizeof(buf));
2138 filename = g_strdup_printf ("/proc/%d/exe", pid);
2139 if (readlink (filename, buf, 255) > 0) {
2140 ret = g_strdup (buf);
2142 g_free (filename);
2144 if (ret != NULL) {
2145 return(ret);
2148 filename = g_strdup_printf ("/proc/%d/cmdline", pid);
2149 if ((fp = fopen (filename, "r")) != NULL) {
2150 if (fgets (buf, 256, fp) != NULL) {
2151 ret = g_strdup (buf);
2154 fclose (fp);
2156 g_free (filename);
2158 if (ret != NULL) {
2159 return(ret);
2162 filename = g_strdup_printf ("/proc/%d/stat", pid);
2163 if ((fp = fopen (filename, "r")) != NULL) {
2164 if (fgets (buf, 256, fp) != NULL) {
2165 gchar *start, *end;
2167 start = strchr (buf, '(');
2168 if (start != NULL) {
2169 end = strchr (start + 1, ')');
2171 if (end != NULL) {
2172 ret = g_strndup (start + 1,
2173 end - start - 1);
2178 fclose (fp);
2180 g_free (filename);
2181 #endif
2183 if (ret != NULL) {
2184 return(ret);
2187 return(NULL);
2190 static guint32 get_module_name (gpointer process, gpointer module,
2191 gunichar2 *basename, guint32 size,
2192 gboolean base)
2194 struct _WapiHandle_process *process_handle;
2195 gboolean ok;
2196 pid_t pid;
2197 gunichar2 *procname;
2198 gchar *procname_ext = NULL;
2199 glong len;
2200 gsize bytes;
2201 FILE *fp;
2202 GSList *mods = NULL;
2203 WapiProcModule *found_module;
2204 guint32 count;
2205 int i;
2206 gchar *proc_name = NULL;
2208 mono_once (&process_current_once, process_set_current);
2210 #ifdef DEBUG
2211 g_message ("%s: Getting module base name, process handle %p module %p",
2212 __func__, process, module);
2213 #endif
2215 size = size*sizeof(gunichar2); /* adjust for unicode characters */
2217 if (basename == NULL || size == 0) {
2218 return(0);
2221 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2222 /* This is a pseudo handle */
2223 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2224 proc_name = get_process_name_from_proc (pid);
2225 } else {
2226 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2227 (gpointer *)&process_handle);
2228 if (ok == FALSE) {
2229 #ifdef DEBUG
2230 g_message ("%s: Can't find process %p", __func__,
2231 process);
2232 #endif
2234 return(0);
2236 pid = process_handle->id;
2237 proc_name = g_strdup (process_handle->proc_name);
2240 /* Look up the address in /proc/<pid>/maps */
2241 #ifdef PLATFORM_MACOSX
2243 mods = load_modules ();
2244 #else
2245 if ((fp = open_process_map (pid, "r")) == NULL) {
2246 if (errno == EACCES && module == NULL && base == TRUE) {
2247 procname_ext = get_process_name_from_proc (pid);
2248 } else {
2249 /* No /proc/<pid>/maps, so just return failure
2250 * for now
2252 g_free (proc_name);
2253 return(0);
2255 } else {
2256 mods = load_modules (fp);
2257 fclose (fp);
2258 #endif
2259 count = g_slist_length (mods);
2261 /* If module != NULL compare the address.
2262 * If module == NULL we are looking for the main module.
2263 * The best we can do for now check it the module name end with the process name.
2265 for (i = 0; i < count; i++) {
2266 found_module = (WapiProcModule *)g_slist_nth_data (mods, i);
2267 if (procname_ext == NULL &&
2268 ((module == NULL && match_procname_to_modulename (proc_name, found_module->filename)) ||
2269 (module != NULL && found_module->address_start == module))) {
2270 if (base) {
2271 procname_ext = g_path_get_basename (found_module->filename);
2272 } else {
2273 procname_ext = g_strdup (found_module->filename);
2277 free_procmodule (found_module);
2280 if (procname_ext == NULL)
2282 /* If it's *still* null, we might have hit the
2283 * case where reading /proc/$pid/maps gives an
2284 * empty file for this user.
2286 procname_ext = get_process_name_from_proc (pid);
2289 g_slist_free (mods);
2290 g_free (proc_name);
2293 if (procname_ext != NULL) {
2294 #ifdef DEBUG
2295 g_message ("%s: Process name is [%s]", __func__,
2296 procname_ext);
2297 #endif
2299 procname = mono_unicode_from_external (procname_ext, &bytes);
2300 if (procname == NULL) {
2301 /* bugger */
2302 g_free (procname_ext);
2303 return(0);
2306 len = (bytes / 2);
2308 /* Add the terminator */
2309 bytes += 2;
2311 if (size < bytes) {
2312 #ifdef DEBUG
2313 g_message ("%s: Size %d smaller than needed (%ld); truncating", __func__, size, bytes);
2314 #endif
2316 memcpy (basename, procname, size);
2317 } else {
2318 #ifdef DEBUG
2319 g_message ("%s: Size %d larger than needed (%ld)",
2320 __func__, size, bytes);
2321 #endif
2323 memcpy (basename, procname, bytes);
2326 g_free (procname);
2327 g_free (procname_ext);
2329 return(len);
2332 return(0);
2335 guint32 GetModuleBaseName (gpointer process, gpointer module,
2336 gunichar2 *basename, guint32 size)
2338 return(get_module_name (process, module, basename, size, TRUE));
2341 guint32 GetModuleFileNameEx (gpointer process, gpointer module,
2342 gunichar2 *filename, guint32 size)
2344 return(get_module_name (process, module, filename, size, FALSE));
2347 gboolean GetModuleInformation (gpointer process, gpointer module,
2348 WapiModuleInfo *modinfo, guint32 size)
2350 struct _WapiHandle_process *process_handle;
2351 gboolean ok;
2352 pid_t pid;
2353 FILE *fp;
2354 GSList *mods = NULL;
2355 WapiProcModule *found_module;
2356 guint32 count;
2357 int i;
2358 gboolean ret = FALSE;
2359 gchar *proc_name = NULL;
2361 mono_once (&process_current_once, process_set_current);
2363 #ifdef DEBUG
2364 g_message ("%s: Getting module info, process handle %p module %p",
2365 __func__, process, module);
2366 #endif
2368 if (modinfo == NULL || size < sizeof(WapiModuleInfo)) {
2369 return(FALSE);
2372 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2373 /* This is a pseudo handle */
2374 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2375 proc_name = get_process_name_from_proc (pid);
2376 } else {
2377 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2378 (gpointer *)&process_handle);
2379 if (ok == FALSE) {
2380 #ifdef DEBUG
2381 g_message ("%s: Can't find process %p", __func__,
2382 process);
2383 #endif
2385 return(FALSE);
2387 pid = process_handle->id;
2388 proc_name = g_strdup (process_handle->proc_name);
2391 #ifdef PLATFORM_MACOSX
2393 mods = load_modules ();
2394 #else
2395 /* Look up the address in /proc/<pid>/maps */
2396 if ((fp = open_process_map (pid, "r")) == NULL) {
2397 /* No /proc/<pid>/maps, so just return failure
2398 * for now
2400 g_free (proc_name);
2401 return(FALSE);
2402 } else {
2403 mods = load_modules (fp);
2404 fclose (fp);
2405 #endif
2406 count = g_slist_length (mods);
2408 /* If module != NULL compare the address.
2409 * If module == NULL we are looking for the main module.
2410 * The best we can do for now check it the module name end with the process name.
2412 for (i = 0; i < count; i++) {
2413 found_module = (WapiProcModule *)g_slist_nth_data (mods, i);
2414 if ( ret == FALSE &&
2415 ((module == NULL && match_procname_to_modulename (proc_name, found_module->filename)) ||
2416 (module != NULL && found_module->address_start == module))) {
2417 modinfo->lpBaseOfDll = found_module->address_start;
2418 modinfo->SizeOfImage = (gsize)(found_module->address_end) - (gsize)(found_module->address_start);
2419 modinfo->EntryPoint = found_module->address_offset;
2420 ret = TRUE;
2423 free_procmodule (found_module);
2426 g_slist_free (mods);
2427 g_free (proc_name);
2430 return(ret);
2433 gboolean GetProcessWorkingSetSize (gpointer process, size_t *min, size_t *max)
2435 struct _WapiHandle_process *process_handle;
2436 gboolean ok;
2438 mono_once (&process_current_once, process_set_current);
2440 if(min==NULL || max==NULL) {
2441 /* Not sure if w32 allows NULLs here or not */
2442 return(FALSE);
2445 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2446 /* This is a pseudo handle, so just fail for now
2448 return(FALSE);
2451 ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2452 (gpointer *)&process_handle);
2453 if(ok==FALSE) {
2454 #ifdef DEBUG
2455 g_message ("%s: Can't find process %p", __func__, process);
2456 #endif
2458 return(FALSE);
2461 *min=process_handle->min_working_set;
2462 *max=process_handle->max_working_set;
2464 return(TRUE);
2467 gboolean SetProcessWorkingSetSize (gpointer process, size_t min, size_t max)
2469 struct _WapiHandle_process *process_handle;
2470 gboolean ok;
2472 mono_once (&process_current_once, process_set_current);
2474 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2475 /* This is a pseudo handle, so just fail for now
2477 return(FALSE);
2480 ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2481 (gpointer *)&process_handle);
2482 if(ok==FALSE) {
2483 #ifdef DEBUG
2484 g_message ("%s: Can't find process %p", __func__, process);
2485 #endif
2487 return(FALSE);
2490 process_handle->min_working_set=min;
2491 process_handle->max_working_set=max;
2493 return(TRUE);
2497 gboolean
2498 TerminateProcess (gpointer process, gint32 exitCode)
2500 struct _WapiHandle_process *process_handle;
2501 gboolean ok;
2502 int signo;
2503 int ret;
2504 pid_t pid;
2506 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2507 /* This is a pseudo handle */
2508 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2509 } else {
2510 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2511 (gpointer *) &process_handle);
2513 if (ok == FALSE) {
2514 #ifdef DEBUG
2515 g_message ("%s: Can't find process %p", __func__,
2516 process);
2517 #endif
2518 SetLastError (ERROR_INVALID_HANDLE);
2519 return FALSE;
2521 pid = process_handle->id;
2524 signo = (exitCode == -1) ? SIGKILL : SIGTERM;
2525 ret = kill (pid, signo);
2526 if (ret == -1) {
2527 switch (errno) {
2528 case EINVAL:
2529 SetLastError (ERROR_INVALID_PARAMETER);
2530 break;
2531 case EPERM:
2532 SetLastError (ERROR_ACCESS_DENIED);
2533 break;
2534 case ESRCH:
2535 SetLastError (ERROR_PROC_NOT_FOUND);
2536 break;
2537 default:
2538 SetLastError (ERROR_GEN_FAILURE);
2542 return (ret == 0);
2545 guint32
2546 GetPriorityClass (gpointer process)
2548 #ifdef HAVE_GETPRIORITY
2549 struct _WapiHandle_process *process_handle;
2550 gboolean ok;
2551 int ret;
2552 pid_t pid;
2554 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2555 /* This is a pseudo handle */
2556 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2557 } else {
2558 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2559 (gpointer *) &process_handle);
2561 if (!ok) {
2562 SetLastError (ERROR_INVALID_HANDLE);
2563 return FALSE;
2565 pid = process_handle->id;
2568 errno = 0;
2569 ret = getpriority (PRIO_PROCESS, pid);
2570 if (ret == -1 && errno != 0) {
2571 switch (errno) {
2572 case EPERM:
2573 case EACCES:
2574 SetLastError (ERROR_ACCESS_DENIED);
2575 break;
2576 case ESRCH:
2577 SetLastError (ERROR_PROC_NOT_FOUND);
2578 break;
2579 default:
2580 SetLastError (ERROR_GEN_FAILURE);
2582 return FALSE;
2585 if (ret == 0)
2586 return NORMAL_PRIORITY_CLASS;
2587 else if (ret < -15)
2588 return REALTIME_PRIORITY_CLASS;
2589 else if (ret < -10)
2590 return HIGH_PRIORITY_CLASS;
2591 else if (ret < 0)
2592 return ABOVE_NORMAL_PRIORITY_CLASS;
2593 else if (ret > 10)
2594 return IDLE_PRIORITY_CLASS;
2595 else if (ret > 0)
2596 return BELOW_NORMAL_PRIORITY_CLASS;
2598 return NORMAL_PRIORITY_CLASS;
2599 #else
2600 SetLastError (ERROR_NOT_SUPPORTED);
2601 return 0;
2602 #endif
2605 gboolean
2606 SetPriorityClass (gpointer process, guint32 priority_class)
2608 #ifdef HAVE_SETPRIORITY
2609 struct _WapiHandle_process *process_handle;
2610 gboolean ok;
2611 int ret;
2612 int prio;
2613 pid_t pid;
2615 if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2616 /* This is a pseudo handle */
2617 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2618 } else {
2619 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2620 (gpointer *) &process_handle);
2622 if (!ok) {
2623 SetLastError (ERROR_INVALID_HANDLE);
2624 return FALSE;
2626 pid = process_handle->id;
2629 switch (priority_class) {
2630 case IDLE_PRIORITY_CLASS:
2631 prio = 19;
2632 break;
2633 case BELOW_NORMAL_PRIORITY_CLASS:
2634 prio = 10;
2635 break;
2636 case NORMAL_PRIORITY_CLASS:
2637 prio = 0;
2638 break;
2639 case ABOVE_NORMAL_PRIORITY_CLASS:
2640 prio = -5;
2641 break;
2642 case HIGH_PRIORITY_CLASS:
2643 prio = -11;
2644 break;
2645 case REALTIME_PRIORITY_CLASS:
2646 prio = -20;
2647 break;
2648 default:
2649 SetLastError (ERROR_INVALID_PARAMETER);
2650 return FALSE;
2653 ret = setpriority (PRIO_PROCESS, pid, prio);
2654 if (ret == -1) {
2655 switch (errno) {
2656 case EPERM:
2657 case EACCES:
2658 SetLastError (ERROR_ACCESS_DENIED);
2659 break;
2660 case ESRCH:
2661 SetLastError (ERROR_PROC_NOT_FOUND);
2662 break;
2663 default:
2664 SetLastError (ERROR_GEN_FAILURE);
2668 return ret == 0;
2669 #else
2670 SetLastError (ERROR_NOT_SUPPORTED);
2671 return FALSE;
2672 #endif