2 * processes.c: Process handles
5 * Dick Porter (dick@ximian.com)
7 * (C) 2002 Ximian, Inc.
12 #include <mono/os/gc_wrapper.h>
13 #include "mono/utils/mono-hash.h"
21 #include <sys/types.h>
24 #include <mono/io-layer/wapi.h>
25 #include <mono/io-layer/unicode.h>
26 #include <mono/io-layer/wapi-private.h>
27 #include <mono/io-layer/handles-private.h>
28 #include <mono/io-layer/misc-private.h>
29 #include <mono/io-layer/mono-mutex.h>
30 #include <mono/io-layer/process-private.h>
31 #include <mono/io-layer/threads.h>
33 /* The process' environment strings */
34 extern char **environ;
38 static void process_close_shared (gpointer handle);
40 struct _WapiHandleOps _wapi_process_ops = {
41 process_close_shared, /* close_shared */
42 NULL, /* close_private */
48 static mono_once_t process_current_once=MONO_ONCE_INIT;
49 static gpointer current_process=NULL;
51 static mono_once_t process_ops_once=MONO_ONCE_INIT;
53 static void process_ops_init (void)
55 _wapi_handle_register_capabilities (WAPI_HANDLE_PROCESS,
56 WAPI_HANDLE_CAP_WAIT);
59 static void process_close_shared (gpointer handle G_GNUC_UNUSED)
61 struct _WapiHandle_process *process_handle;
64 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
65 (gpointer *)&process_handle, NULL);
67 g_warning (G_GNUC_PRETTY_FUNCTION
68 ": error looking up process handle %p", handle);
73 g_message (G_GNUC_PRETTY_FUNCTION
74 ": closing process handle %p with id %d", handle,
78 if(process_handle->proc_name!=0) {
79 _wapi_handle_scratch_delete (process_handle->proc_name);
80 process_handle->proc_name=0;
84 gboolean CreateProcess (const gunichar2 *appname, gunichar2 *cmdline,
85 WapiSecurityAttributes *process_attrs G_GNUC_UNUSED,
86 WapiSecurityAttributes *thread_attrs G_GNUC_UNUSED,
87 gboolean inherit_handles, guint32 create_flags,
88 gpointer new_environ, const gunichar2 *cwd,
89 WapiStartupInfo *startup,
90 WapiProcessInformation *process_info)
92 gchar *cmd=NULL, *prog = NULL, *full_prog = NULL, *args=NULL, *args_after_prog=NULL, *dir=NULL;
93 guint32 env=0, stored_dir=0, stored_prog=0, i;
95 gpointer stdin_handle, stdout_handle, stderr_handle;
97 gpointer process_handle, thread_handle;
99 mono_once (&process_ops_once, process_ops_init);
101 /* appname and cmdline specify the executable and its args:
103 * If appname is not NULL, it is the name of the executable.
104 * Otherwise the executable is the first token in cmdline.
106 * Executable searching:
108 * If appname is not NULL, it can specify the full path and
109 * file name, or else a partial name and the current directory
110 * will be used. There is no additional searching.
112 * If appname is NULL, the first whitespace-delimited token in
113 * cmdline is used. If the name does not contain a full
114 * directory path, the search sequence is:
116 * 1) The directory containing the current process
117 * 2) The current working directory
118 * 3) The windows system directory (Ignored)
119 * 4) The windows directory (Ignored)
122 * Just to make things more interesting, tokens can contain
123 * white space if they are surrounded by quotation marks. I'm
124 * beginning to understand just why windows apps are generally
125 * so crap, with an API like this :-(
128 cmd=_wapi_unicode_to_utf8 (appname);
131 g_message (G_GNUC_PRETTY_FUNCTION
132 ": unicode conversion returned NULL");
138 /* Turn all the slashes round the right way */
139 for(i=0; i<strlen (cmd); i++) {
147 args=_wapi_unicode_to_utf8 (cmdline);
150 g_message (G_GNUC_PRETTY_FUNCTION
151 ": unicode conversion returned NULL");
157 /* Turn all the slashes round the right way */
158 for(i=0; i<strlen (args); i++) {
166 dir=_wapi_unicode_to_utf8 (cwd);
169 g_message (G_GNUC_PRETTY_FUNCTION
170 ": unicode conversion returned NULL");
176 /* Turn all the slashes round the right way */
177 for(i=0; i<strlen (dir); i++) {
183 dir=g_get_current_dir ();
185 stored_dir=_wapi_handle_scratch_store (dir, strlen (dir));
188 /* new_environ is a block of NULL-terminated strings, which
189 * is itself NULL-terminated. Of course, passing an array of
190 * string pointers would have made things too easy :-(
192 * If new_environ is not NULL it specifies the entire set of
193 * environment variables in the new process. Otherwise the
194 * new process inherits the same environment.
196 if(new_environ!=NULL) {
199 gunichar2 *new_environp;
201 /* Count the number of strings */
202 for(new_environp=(gunichar2 *)new_environ; *new_environp;
205 while(*new_environp) {
209 strings=g_new0 (gchar *, count);
211 /* Copy each environ string into 'strings' turning it
212 * into utf8 at the same time
215 for(new_environp=(gunichar2 *)new_environ; *new_environp;
217 strings[count]=g_utf16_to_utf8 (new_environp, -1, NULL,
220 while(*new_environp) {
225 env=_wapi_handle_scratch_store_string_array (strings);
227 g_strfreev (strings);
229 /* Use the existing environment */
230 env=_wapi_handle_scratch_store_string_array (environ);
233 /* We can't put off locating the executable any longer :-( */
235 if(g_ascii_isalpha (cmd[0]) && (cmd[1]==':')) {
236 /* Strip off the drive letter. I can't
237 * believe that CP/M holdover is still
240 memmove (cmd, cmd+2, strlen (cmd)-2);
241 cmd[strlen (cmd)-2]='\0';
245 /* Assume full path given */
248 /* Executable existing ? */
249 if(access (prog, X_OK)!=0) {
252 g_message (G_GNUC_PRETTY_FUNCTION ": Couldn't find executable %s", token);
254 SetLastError (ERROR_FILE_NOT_FOUND);
258 /* Search for file named by cmd in the current
261 char *curdir=g_get_current_dir ();
263 prog=g_strdup_printf ("%s/%s", curdir, cmd);
267 args_after_prog=args;
271 /* Dig out the first token from args, taking quotation
275 /* First, strip off all leading whitespace */
276 args=g_strchug (args);
278 /* args_after_prog points to the contents of args
279 * after token has been set (otherwise argv[0] is
282 args_after_prog=args;
284 /* Assume the opening quote will always be the first
288 for(i=1; args[i]!='\0' && args[i]!='\"'; i++);
289 if(g_ascii_isspace (args[i+1])) {
290 /* We found the first token */
291 token=g_strndup (args+1, i-1);
292 args_after_prog=args+i;
294 /* Quotation mark appeared in the
295 * middle of the token. Just give the
296 * whole first token, quotes and all,
303 /* No quote mark, or malformed */
304 for(i=0; args[i]!='\0'; i++) {
305 if(g_ascii_isspace (args[i])) {
306 token=g_strndup (args, i);
307 args_after_prog=args+i;
313 if(token==NULL && args[0]!='\0') {
314 /* Must be just one token in the string */
315 token=g_strdup (args);
316 args_after_prog=NULL;
322 g_message (G_GNUC_PRETTY_FUNCTION
323 ": Couldn't find what to exec");
329 if(g_ascii_isalpha (token[0]) && (token[1]==':')) {
330 /* Strip off the drive letter. I can't
331 * believe that CP/M holdover is still
334 memmove (token, token+2, strlen (token)-2);
335 token[strlen (token)-2]='\0';
339 /* Assume full path given */
340 prog=g_strdup (token);
342 /* Executable existing ? */
343 if(access (prog, X_OK)!=0) {
346 g_message (G_GNUC_PRETTY_FUNCTION ": Couldn't find executable %s", token);
349 SetLastError (ERROR_FILE_NOT_FOUND);
354 char *curdir=g_get_current_dir ();
356 /* FIXME: Need to record the directory
357 * containing the current process, and check
358 * that for the new executable as the first
362 prog=g_strdup_printf ("%s/%s", curdir, token);
365 /* I assume X_OK is the criterion to use,
368 if(access (prog, X_OK)!=0) {
370 prog=g_find_program_in_path (token);
373 g_message (G_GNUC_PRETTY_FUNCTION ": Couldn't find executable %s", token);
377 SetLastError (ERROR_FILE_NOT_FOUND);
387 g_message (G_GNUC_PRETTY_FUNCTION ": Exec prog [%s] args [%s]", prog,
391 if(args_after_prog!=NULL) {
392 full_prog=g_strconcat (prog, " ", args_after_prog, NULL);
394 full_prog=g_strdup (prog);
397 stored_prog=_wapi_handle_scratch_store (full_prog, strlen (full_prog));
399 if(startup!=NULL && startup->dwFlags & STARTF_USESTDHANDLES) {
400 stdin_handle=startup->hStdInput;
401 stdout_handle=startup->hStdOutput;
402 stderr_handle=startup->hStdError;
404 stdin_handle=GetStdHandle (STD_INPUT_HANDLE);
405 stdout_handle=GetStdHandle (STD_OUTPUT_HANDLE);
406 stderr_handle=GetStdHandle (STD_ERROR_HANDLE);
409 ret=_wapi_handle_process_fork (stored_prog, env, stored_dir,
410 inherit_handles, create_flags,
411 stdin_handle, stdout_handle,
412 stderr_handle, &process_handle,
413 &thread_handle, &pid, &tid);
415 if(ret==TRUE && process_info!=NULL) {
416 process_info->hProcess=process_handle;
417 process_info->hThread=thread_handle;
418 process_info->dwProcessId=pid;
419 process_info->dwThreadId=tid;
426 if(full_prog!=NULL) {
430 _wapi_handle_scratch_delete (stored_prog);
439 _wapi_handle_scratch_delete (stored_dir);
442 _wapi_handle_scratch_delete_string_array (env);
448 static gboolean process_compare (gpointer handle, gpointer user_data)
450 struct _WapiHandle_process *process_handle;
454 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
455 (gpointer *)&process_handle, NULL);
457 g_warning (G_GNUC_PRETTY_FUNCTION
458 ": error looking up process handle %p", handle);
462 pid=GPOINTER_TO_UINT (user_data);
463 if(process_handle->id==pid) {
470 static void process_set_current (void)
472 struct _WapiHandle_process *process_handle;
476 current_process=_wapi_search_handle (WAPI_HANDLE_PROCESS,
478 GUINT_TO_POINTER (pid),
479 (gpointer *)&process_handle,
481 if(current_process==0) {
482 gchar *progname, *slash;
485 g_message (G_GNUC_PRETTY_FUNCTION
486 ": Need to create my own process handle");
489 current_process=_wapi_handle_new (WAPI_HANDLE_PROCESS);
490 if(current_process==_WAPI_HANDLE_INVALID) {
491 g_warning (G_GNUC_PRETTY_FUNCTION
492 ": error creating process handle");
496 ok=_wapi_lookup_handle (current_process, WAPI_HANDLE_PROCESS,
497 (gpointer *)&process_handle, NULL);
499 g_warning (G_GNUC_PRETTY_FUNCTION
500 ": error looking up process handle %p",
505 process_handle->id=pid;
507 /* These seem to be the defaults on w2k */
508 process_handle->min_working_set=204800;
509 process_handle->max_working_set=1413120;
511 progname=g_get_prgname ();
514 g_message (G_GNUC_PRETTY_FUNCTION ": using [%s] as prog name",
519 slash=strrchr (progname, '/');
521 process_handle->proc_name=_wapi_handle_scratch_store (slash+1, strlen (slash+1));
523 process_handle->proc_name=_wapi_handle_scratch_store (progname, strlen (progname));
527 /* Make sure the new handle has a reference so it wont go away
528 * until this process exits
530 _wapi_handle_ref (current_process);
533 g_message (G_GNUC_PRETTY_FUNCTION ": Found my process handle");
538 /* Returns a pseudo handle that doesn't need to be closed afterwards */
539 gpointer GetCurrentProcess (void)
541 mono_once (&process_current_once, process_set_current);
543 return((gpointer)-1);
546 guint32 GetCurrentProcessId (void)
548 struct _WapiHandle_process *current_process_handle;
551 mono_once (&process_current_once, process_set_current);
553 ok=_wapi_lookup_handle (current_process, WAPI_HANDLE_PROCESS,
554 (gpointer *)¤t_process_handle, NULL);
556 g_warning (G_GNUC_PRETTY_FUNCTION
557 ": error looking up current process handle %p",
559 /* No failure return is defined. PID 0 is invalid.
560 * This should only be reached when something else has
561 * gone badly wrong anyway.
566 return(current_process_handle->id);
569 static gboolean process_enum (gpointer handle, gpointer user_data)
571 GPtrArray *processes=user_data;
573 /* Ignore processes that have already exited (ie they are signalled) */
574 if(_wapi_handle_issignalled (handle)==FALSE) {
575 g_ptr_array_add (processes, handle);
578 /* Return false to keep searching */
582 gboolean EnumProcesses (guint32 *pids, guint32 len, guint32 *needed)
584 GPtrArray *processes=g_ptr_array_new ();
587 mono_once (&process_current_once, process_set_current);
589 _wapi_search_handle (WAPI_HANDLE_PROCESS, process_enum, processes,
592 fit=len/sizeof(guint32);
593 for(i=0; i<fit && i<processes->len; i++) {
594 struct _WapiHandle_process *process_handle;
597 ok=_wapi_lookup_handle (g_ptr_array_index (processes, i),
599 (gpointer *)&process_handle, NULL);
601 g_warning (G_GNUC_PRETTY_FUNCTION ": error looking up process handle %p", g_ptr_array_index (processes, i));
602 g_ptr_array_free (processes, FALSE);
606 pids[i]=process_handle->id;
609 g_ptr_array_free (processes, FALSE);
611 *needed=i*sizeof(guint32);
616 static gboolean process_open_compare (gpointer handle, gpointer user_data)
618 struct _WapiHandle_process *process_handle;
622 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
623 (gpointer *)&process_handle, NULL);
625 g_warning (G_GNUC_PRETTY_FUNCTION
626 ": error looking up process handle %p", handle);
630 pid=GPOINTER_TO_UINT (user_data);
632 /* It's possible to have more than one process handle with the
633 * same pid, but only the one running process can be
636 if(process_handle->id==pid &&
637 _wapi_handle_issignalled (handle)==FALSE) {
644 gpointer OpenProcess (guint32 access G_GNUC_UNUSED, gboolean inherit G_GNUC_UNUSED, guint32 pid)
646 /* Find the process handle that corresponds to pid */
649 mono_once (&process_current_once, process_set_current);
651 handle=_wapi_search_handle (WAPI_HANDLE_PROCESS, process_open_compare,
652 GUINT_TO_POINTER (pid), NULL, NULL);
655 g_message (G_GNUC_PRETTY_FUNCTION ": Can't find pid %d", pid);
658 /* Set an error code */
663 _wapi_handle_ref (handle);
668 gboolean GetExitCodeProcess (gpointer process, guint32 *code)
670 struct _WapiHandle_process *process_handle;
673 mono_once (&process_current_once, process_set_current);
679 ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
680 (gpointer *)&process_handle, NULL);
683 g_message (G_GNUC_PRETTY_FUNCTION ": Can't find process %p",
690 /* A process handle is only signalled if the process has exited */
691 if(_wapi_handle_issignalled (process)==TRUE) {
692 *code=process_handle->exitstatus;
700 gboolean GetProcessTimes (gpointer process, WapiFileTime *create_time,
701 WapiFileTime *exit_time, WapiFileTime *kernel_time,
702 WapiFileTime *user_time)
704 struct _WapiHandle_process *process_handle;
707 mono_once (&process_current_once, process_set_current);
709 if(create_time==NULL || exit_time==NULL || kernel_time==NULL ||
711 /* Not sure if w32 allows NULLs here or not */
715 ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
716 (gpointer *)&process_handle, NULL);
719 g_message (G_GNUC_PRETTY_FUNCTION ": Can't find process %p",
726 *create_time=process_handle->create_time;
728 /* A process handle is only signalled if the process has
729 * exited. Otherwise exit_time isn't set
731 if(_wapi_handle_issignalled (process)==TRUE) {
732 *exit_time=process_handle->exit_time;
738 gboolean EnumProcessModules (gpointer process, gpointer *modules,
739 guint32 size, guint32 *needed)
741 /* Store modules in an array of pointers (main module as
742 * modules[0]), using the load address for each module as a
743 * token. (Use 'NULL' as an alternative for the main module
744 * so that the simple implementation can just return one item
745 * for now.) Get the info from /proc/<pid>/maps on linux,
746 * other systems will have to implement /dev/kmem reading or
747 * whatever other horrid technique is needed.
749 if(size<sizeof(gpointer)) {
755 *needed=sizeof(gpointer);
758 *needed=sizeof(gpointer);
764 guint32 GetModuleBaseName (gpointer process, gpointer module,
765 gunichar2 *basename, guint32 size)
767 struct _WapiHandle_process *process_handle;
770 mono_once (&process_current_once, process_set_current);
773 g_message (G_GNUC_PRETTY_FUNCTION
774 ": Getting module base name, process handle %p module %p",
778 if(basename==NULL || size==0) {
782 ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
783 (gpointer *)&process_handle, NULL);
786 g_message (G_GNUC_PRETTY_FUNCTION ": Can't find process %p",
794 /* Shorthand for the main module, which has the
795 * process name recorded in the handle data
799 guchar *procname_utf8;
803 g_message (G_GNUC_PRETTY_FUNCTION
804 ": Returning main module name");
807 pid=process_handle->id;
808 procname_utf8=_wapi_handle_scratch_lookup_as_string (process_handle->proc_name);
811 g_message (G_GNUC_PRETTY_FUNCTION ": Process name is [%s]",
815 procname=g_utf8_to_utf16 (procname_utf8, -1, NULL, &len, NULL);
818 g_free (procname_utf8);
822 /* Add the terminator, and convert chars to bytes */
827 g_message (G_GNUC_PRETTY_FUNCTION ": Size %d smaller than needed (%ld); truncating", size, bytes);
830 memcpy (basename, procname, size);
833 g_message (G_GNUC_PRETTY_FUNCTION
834 ": Size %d larger than needed (%ld)",
838 memcpy (basename, procname, bytes);
841 g_free (procname_utf8);
846 /* Look up the address in /proc/<pid>/maps */
852 gboolean GetProcessWorkingSetSize (gpointer process, size_t *min, size_t *max)
854 struct _WapiHandle_process *process_handle;
857 mono_once (&process_current_once, process_set_current);
859 if(min==NULL || max==NULL) {
860 /* Not sure if w32 allows NULLs here or not */
864 ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
865 (gpointer *)&process_handle, NULL);
868 g_message (G_GNUC_PRETTY_FUNCTION ": Can't find process %p",
875 *min=process_handle->min_working_set;
876 *max=process_handle->max_working_set;
881 gboolean SetProcessWorkingSetSize (gpointer process, size_t min, size_t max)
883 struct _WapiHandle_process *process_handle;
886 mono_once (&process_current_once, process_set_current);
888 ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
889 (gpointer *)&process_handle, NULL);
892 g_message (G_GNUC_PRETTY_FUNCTION ": Can't find process %p",
899 process_handle->min_working_set=min;
900 process_handle->max_working_set=max;