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");
135 SetLastError(ERROR_PATH_NOT_FOUND);
139 /* Turn all the slashes round the right way */
140 for(i=0; i<strlen (cmd); i++) {
148 args=_wapi_unicode_to_utf8 (cmdline);
151 g_message (G_GNUC_PRETTY_FUNCTION
152 ": unicode conversion returned NULL");
155 SetLastError(ERROR_PATH_NOT_FOUND);
159 /* Turn all the slashes round the right way */
160 for(i=0; i<strlen (args); i++) {
168 dir=_wapi_unicode_to_utf8 (cwd);
171 g_message (G_GNUC_PRETTY_FUNCTION
172 ": unicode conversion returned NULL");
175 SetLastError(ERROR_PATH_NOT_FOUND);
179 /* Turn all the slashes round the right way */
180 for(i=0; i<strlen (dir); i++) {
186 dir=g_get_current_dir ();
188 stored_dir=_wapi_handle_scratch_store (dir, strlen (dir));
191 /* new_environ is a block of NULL-terminated strings, which
192 * is itself NULL-terminated. Of course, passing an array of
193 * string pointers would have made things too easy :-(
195 * If new_environ is not NULL it specifies the entire set of
196 * environment variables in the new process. Otherwise the
197 * new process inherits the same environment.
199 if(new_environ!=NULL) {
202 gunichar2 *new_environp;
204 /* Count the number of strings */
205 for(new_environp=(gunichar2 *)new_environ; *new_environp;
208 while(*new_environp) {
212 strings=g_new0 (gchar *, count);
214 /* Copy each environ string into 'strings' turning it
215 * into utf8 at the same time
218 for(new_environp=(gunichar2 *)new_environ; *new_environp;
220 strings[count]=g_utf16_to_utf8 (new_environp, -1, NULL,
223 while(*new_environp) {
228 env=_wapi_handle_scratch_store_string_array (strings);
230 g_strfreev (strings);
232 /* Use the existing environment */
233 env=_wapi_handle_scratch_store_string_array (environ);
236 /* We can't put off locating the executable any longer :-( */
238 if(g_ascii_isalpha (cmd[0]) && (cmd[1]==':')) {
239 /* Strip off the drive letter. I can't
240 * believe that CP/M holdover is still
243 memmove (cmd, cmd+2, strlen (cmd)-2);
244 cmd[strlen (cmd)-2]='\0';
248 /* Assume full path given */
251 /* Executable existing ? */
252 if(access (prog, X_OK)!=0) {
254 g_message (G_GNUC_PRETTY_FUNCTION ": Couldn't find executable %s", prog);
257 SetLastError (ERROR_FILE_NOT_FOUND);
261 /* Search for file named by cmd in the current
264 char *curdir=g_get_current_dir ();
266 prog=g_strdup_printf ("%s/%s", curdir, cmd);
270 args_after_prog=args;
274 /* Dig out the first token from args, taking quotation
278 /* First, strip off all leading whitespace */
279 args=g_strchug (args);
281 /* args_after_prog points to the contents of args
282 * after token has been set (otherwise argv[0] is
285 args_after_prog=args;
287 /* Assume the opening quote will always be the first
291 for(i=1; args[i]!='\0' && args[i]!='\"'; i++);
292 if(g_ascii_isspace (args[i+1])) {
293 /* We found the first token */
294 token=g_strndup (args+1, i-1);
295 args_after_prog=args+i;
297 /* Quotation mark appeared in the
298 * middle of the token. Just give the
299 * whole first token, quotes and all,
306 /* No quote mark, or malformed */
307 for(i=0; args[i]!='\0'; i++) {
308 if(g_ascii_isspace (args[i])) {
309 token=g_strndup (args, i);
310 args_after_prog=args+i;
316 if(token==NULL && args[0]!='\0') {
317 /* Must be just one token in the string */
318 token=g_strdup (args);
319 args_after_prog=NULL;
325 g_message (G_GNUC_PRETTY_FUNCTION
326 ": Couldn't find what to exec");
329 SetLastError(ERROR_PATH_NOT_FOUND);
333 if(g_ascii_isalpha (token[0]) && (token[1]==':')) {
334 /* Strip off the drive letter. I can't
335 * believe that CP/M holdover is still
338 memmove (token, token+2, strlen (token)-2);
339 token[strlen (token)-2]='\0';
343 /* Assume full path given */
344 prog=g_strdup (token);
346 /* Executable existing ? */
347 if(access (prog, X_OK)!=0) {
350 g_message (G_GNUC_PRETTY_FUNCTION ": Couldn't find executable %s", token);
353 SetLastError (ERROR_FILE_NOT_FOUND);
358 char *curdir=g_get_current_dir ();
360 /* FIXME: Need to record the directory
361 * containing the current process, and check
362 * that for the new executable as the first
366 prog=g_strdup_printf ("%s/%s", curdir, token);
369 /* I assume X_OK is the criterion to use,
372 if(access (prog, X_OK)!=0) {
374 prog=g_find_program_in_path (token);
377 g_message (G_GNUC_PRETTY_FUNCTION ": Couldn't find executable %s", token);
381 SetLastError (ERROR_FILE_NOT_FOUND);
391 g_message (G_GNUC_PRETTY_FUNCTION ": Exec prog [%s] args [%s]", prog,
395 if(args_after_prog!=NULL) {
396 full_prog=g_strconcat (prog, " ", args_after_prog, NULL);
398 full_prog=g_strdup (prog);
401 stored_prog=_wapi_handle_scratch_store (full_prog, strlen (full_prog));
403 if(startup!=NULL && startup->dwFlags & STARTF_USESTDHANDLES) {
404 stdin_handle=startup->hStdInput;
405 stdout_handle=startup->hStdOutput;
406 stderr_handle=startup->hStdError;
408 stdin_handle=GetStdHandle (STD_INPUT_HANDLE);
409 stdout_handle=GetStdHandle (STD_OUTPUT_HANDLE);
410 stderr_handle=GetStdHandle (STD_ERROR_HANDLE);
413 ret=_wapi_handle_process_fork (stored_prog, env, stored_dir,
414 inherit_handles, create_flags,
415 stdin_handle, stdout_handle,
416 stderr_handle, &process_handle,
417 &thread_handle, &pid, &tid);
419 if(ret==TRUE && process_info!=NULL) {
420 process_info->hProcess=process_handle;
421 process_info->hThread=thread_handle;
422 process_info->dwProcessId=pid;
423 process_info->dwThreadId=tid;
424 } else if(ret==FALSE) {
425 /* FIXME: work out a better error code
427 SetLastError(ERROR_PATH_NOT_FOUND);
434 if(full_prog!=NULL) {
438 _wapi_handle_scratch_delete (stored_prog);
447 _wapi_handle_scratch_delete (stored_dir);
450 _wapi_handle_scratch_delete_string_array (env);
456 static void process_set_name (struct _WapiHandle_process *process_handle)
458 gchar *progname, *slash;
460 progname=g_get_prgname ();
463 g_message (G_GNUC_PRETTY_FUNCTION ": using [%s] as prog name",
468 slash=strrchr (progname, '/');
470 process_handle->proc_name=_wapi_handle_scratch_store (slash+1, strlen (slash+1));
472 process_handle->proc_name=_wapi_handle_scratch_store (progname, strlen (progname));
477 static void process_set_current (void)
479 struct _WapiHandle_process *process_handle;
484 handle_env=getenv ("_WAPI_PROCESS_HANDLE");
485 if(handle_env==NULL) {
487 g_message (G_GNUC_PRETTY_FUNCTION
488 ": Need to create my own process handle");
491 current_process=_wapi_handle_new (WAPI_HANDLE_PROCESS);
492 if(current_process==_WAPI_HANDLE_INVALID) {
493 g_warning (G_GNUC_PRETTY_FUNCTION
494 ": error creating process handle");
498 ok=_wapi_lookup_handle (current_process, WAPI_HANDLE_PROCESS,
499 (gpointer *)&process_handle, NULL);
501 g_warning (G_GNUC_PRETTY_FUNCTION
502 ": error looking up process handle %p",
507 process_handle->id=pid;
509 /* These seem to be the defaults on w2k */
510 process_handle->min_working_set=204800;
511 process_handle->max_working_set=1413120;
513 process_set_name (process_handle);
515 /* Make sure the new handle has a reference so it wont go away
516 * until this process exits
518 _wapi_handle_ref (current_process);
522 current_process=GUINT_TO_POINTER (atoi (handle_env));
525 g_message (G_GNUC_PRETTY_FUNCTION
526 ": Found my process handle: %p", current_process);
529 ok=_wapi_lookup_handle (current_process, WAPI_HANDLE_PROCESS,
530 (gpointer *)&process_handle, NULL);
532 g_warning (G_GNUC_PRETTY_FUNCTION
533 ": error looking up process handle %p",
538 procname=_wapi_handle_scratch_lookup (process_handle->proc_name);
540 if(!strcmp (procname, "mono")) {
541 /* Set a better process name */
543 g_message (G_GNUC_PRETTY_FUNCTION ": Setting better process name");
546 _wapi_handle_scratch_delete (process_handle->proc_name);
547 process_set_name (process_handle);
550 g_message (G_GNUC_PRETTY_FUNCTION
551 ": Leaving process name: %s",
561 /* Returns a pseudo handle that doesn't need to be closed afterwards */
562 gpointer GetCurrentProcess (void)
564 mono_once (&process_current_once, process_set_current);
566 return((gpointer)-1);
569 guint32 GetCurrentProcessId (void)
571 struct _WapiHandle_process *current_process_handle;
574 mono_once (&process_current_once, process_set_current);
576 ok=_wapi_lookup_handle (current_process, WAPI_HANDLE_PROCESS,
577 (gpointer *)¤t_process_handle, NULL);
579 g_warning (G_GNUC_PRETTY_FUNCTION
580 ": error looking up current process handle %p",
582 /* No failure return is defined. PID 0 is invalid.
583 * This should only be reached when something else has
584 * gone badly wrong anyway.
589 return(current_process_handle->id);
592 static gboolean process_enum (gpointer handle, gpointer user_data)
594 GPtrArray *processes=user_data;
596 /* Ignore processes that have already exited (ie they are signalled) */
597 if(_wapi_handle_issignalled (handle)==FALSE) {
598 g_ptr_array_add (processes, handle);
601 /* Return false to keep searching */
605 gboolean EnumProcesses (guint32 *pids, guint32 len, guint32 *needed)
607 GPtrArray *processes=g_ptr_array_new ();
610 mono_once (&process_current_once, process_set_current);
612 _wapi_search_handle (WAPI_HANDLE_PROCESS, process_enum, processes,
615 fit=len/sizeof(guint32);
616 for(i=0; i<fit && i<processes->len; i++) {
617 struct _WapiHandle_process *process_handle;
620 ok=_wapi_lookup_handle (g_ptr_array_index (processes, i),
622 (gpointer *)&process_handle, NULL);
624 g_warning (G_GNUC_PRETTY_FUNCTION ": error looking up process handle %p", g_ptr_array_index (processes, i));
625 g_ptr_array_free (processes, FALSE);
629 pids[i]=process_handle->id;
632 g_ptr_array_free (processes, FALSE);
634 *needed=i*sizeof(guint32);
639 static gboolean process_open_compare (gpointer handle, gpointer user_data)
641 struct _WapiHandle_process *process_handle;
645 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
646 (gpointer *)&process_handle, NULL);
648 g_warning (G_GNUC_PRETTY_FUNCTION
649 ": error looking up process handle %p", handle);
653 pid=GPOINTER_TO_UINT (user_data);
655 /* It's possible to have more than one process handle with the
656 * same pid, but only the one running process can be
659 if(process_handle->id==pid &&
660 _wapi_handle_issignalled (handle)==FALSE) {
667 gpointer OpenProcess (guint32 access G_GNUC_UNUSED, gboolean inherit G_GNUC_UNUSED, guint32 pid)
669 /* Find the process handle that corresponds to pid */
672 mono_once (&process_current_once, process_set_current);
674 handle=_wapi_search_handle (WAPI_HANDLE_PROCESS, process_open_compare,
675 GUINT_TO_POINTER (pid), NULL, NULL);
678 g_message (G_GNUC_PRETTY_FUNCTION ": Can't find pid %d", pid);
681 /* Set an error code */
686 _wapi_handle_ref (handle);
691 gboolean GetExitCodeProcess (gpointer process, guint32 *code)
693 struct _WapiHandle_process *process_handle;
696 mono_once (&process_current_once, process_set_current);
702 ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
703 (gpointer *)&process_handle, NULL);
706 g_message (G_GNUC_PRETTY_FUNCTION ": Can't find process %p",
713 /* A process handle is only signalled if the process has exited */
714 if(_wapi_handle_issignalled (process)==TRUE) {
715 *code=process_handle->exitstatus;
723 gboolean GetProcessTimes (gpointer process, WapiFileTime *create_time,
724 WapiFileTime *exit_time, WapiFileTime *kernel_time,
725 WapiFileTime *user_time)
727 struct _WapiHandle_process *process_handle;
730 mono_once (&process_current_once, process_set_current);
732 if(create_time==NULL || exit_time==NULL || kernel_time==NULL ||
734 /* Not sure if w32 allows NULLs here or not */
738 ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
739 (gpointer *)&process_handle, NULL);
742 g_message (G_GNUC_PRETTY_FUNCTION ": Can't find process %p",
749 *create_time=process_handle->create_time;
751 /* A process handle is only signalled if the process has
752 * exited. Otherwise exit_time isn't set
754 if(_wapi_handle_issignalled (process)==TRUE) {
755 *exit_time=process_handle->exit_time;
761 gboolean EnumProcessModules (gpointer process, gpointer *modules,
762 guint32 size, guint32 *needed)
764 /* Store modules in an array of pointers (main module as
765 * modules[0]), using the load address for each module as a
766 * token. (Use 'NULL' as an alternative for the main module
767 * so that the simple implementation can just return one item
768 * for now.) Get the info from /proc/<pid>/maps on linux,
769 * other systems will have to implement /dev/kmem reading or
770 * whatever other horrid technique is needed.
772 if(size<sizeof(gpointer)) {
778 *needed=sizeof(gpointer);
781 *needed=sizeof(gpointer);
787 guint32 GetModuleBaseName (gpointer process, gpointer module,
788 gunichar2 *basename, guint32 size)
790 struct _WapiHandle_process *process_handle;
793 mono_once (&process_current_once, process_set_current);
796 g_message (G_GNUC_PRETTY_FUNCTION
797 ": Getting module base name, process handle %p module %p",
801 if(basename==NULL || size==0) {
805 ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
806 (gpointer *)&process_handle, NULL);
809 g_message (G_GNUC_PRETTY_FUNCTION ": Can't find process %p",
817 /* Shorthand for the main module, which has the
818 * process name recorded in the handle data
822 guchar *procname_utf8;
826 g_message (G_GNUC_PRETTY_FUNCTION
827 ": Returning main module name");
830 pid=process_handle->id;
831 procname_utf8=_wapi_handle_scratch_lookup (process_handle->proc_name);
834 g_message (G_GNUC_PRETTY_FUNCTION ": Process name is [%s]",
838 procname=g_utf8_to_utf16 (procname_utf8, -1, NULL, &len, NULL);
841 g_free (procname_utf8);
845 /* Add the terminator, and convert chars to bytes */
850 g_message (G_GNUC_PRETTY_FUNCTION ": Size %d smaller than needed (%ld); truncating", size, bytes);
853 memcpy (basename, procname, size);
856 g_message (G_GNUC_PRETTY_FUNCTION
857 ": Size %d larger than needed (%ld)",
861 memcpy (basename, procname, bytes);
864 g_free (procname_utf8);
869 /* Look up the address in /proc/<pid>/maps */
875 gboolean GetProcessWorkingSetSize (gpointer process, size_t *min, size_t *max)
877 struct _WapiHandle_process *process_handle;
880 mono_once (&process_current_once, process_set_current);
882 if(min==NULL || max==NULL) {
883 /* Not sure if w32 allows NULLs here or not */
887 ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
888 (gpointer *)&process_handle, NULL);
891 g_message (G_GNUC_PRETTY_FUNCTION ": Can't find process %p",
898 *min=process_handle->min_working_set;
899 *max=process_handle->max_working_set;
904 gboolean SetProcessWorkingSetSize (gpointer process, size_t min, size_t max)
906 struct _WapiHandle_process *process_handle;
909 mono_once (&process_current_once, process_set_current);
911 ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
912 (gpointer *)&process_handle, NULL);
915 g_message (G_GNUC_PRETTY_FUNCTION ": Can't find process %p",
922 process_handle->min_working_set=min;
923 process_handle->max_working_set=max;