fix macro syntax
[mono.git] / mono / io-layer / processes.c
1 /*
2  * processes.c:  Process handles
3  *
4  * Author:
5  *      Dick Porter (dick@ximian.com)
6  *
7  * (C) 2002-2006 Novell, Inc.
8  */
9
10 #include <config.h>
11 #include <glib.h>
12 #include <string.h>
13 #include <pthread.h>
14 #include <sched.h>
15 #include <sys/time.h>
16 #include <errno.h>
17 #include <sys/types.h>
18 #include <unistd.h>
19 #include <signal.h>
20 #include <sys/wait.h>
21
22 #include <mono/io-layer/wapi.h>
23 #include <mono/io-layer/wapi-private.h>
24 #include <mono/io-layer/handles-private.h>
25 #include <mono/io-layer/misc-private.h>
26 #include <mono/io-layer/mono-mutex.h>
27 #include <mono/io-layer/process-private.h>
28 #include <mono/io-layer/threads.h>
29 #include <mono/utils/strenc.h>
30 #include <mono/io-layer/timefuncs-private.h>
31
32 /* The process' environment strings */
33 extern char **environ;
34
35 #undef DEBUG
36
37 static guint32 process_wait (gpointer handle, guint32 timeout);
38
39 struct _WapiHandleOps _wapi_process_ops = {
40         NULL,                           /* close_shared */
41         NULL,                           /* signal */
42         NULL,                           /* own */
43         NULL,                           /* is_owned */
44         process_wait,                   /* special_wait */
45         NULL                            /* prewait */   
46 };
47
48 static mono_once_t process_current_once=MONO_ONCE_INIT;
49 static gpointer current_process=NULL;
50
51 static mono_once_t process_ops_once=MONO_ONCE_INIT;
52
53 static void process_ops_init (void)
54 {
55         _wapi_handle_register_capabilities (WAPI_HANDLE_PROCESS,
56                                             WAPI_HANDLE_CAP_WAIT |
57                                             WAPI_HANDLE_CAP_SPECIAL_WAIT);
58 }
59
60 static gboolean process_set_termination_details (gpointer handle, int status)
61 {
62         struct _WapiHandle_process *process_handle;
63         gboolean ok;
64         int thr_ret;
65         
66         ok = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
67                                   (gpointer *)&process_handle);
68         if (ok == FALSE) {
69                 g_warning ("%s: error looking up process handle %p",
70                            __func__, handle);
71                 return(FALSE);
72         }
73         
74         thr_ret = _wapi_handle_lock_shared_handles ();
75         g_assert (thr_ret == 0);
76
77         if (WIFSIGNALED(status)) {
78                 process_handle->exitstatus = 128 + WTERMSIG(status);
79         } else {
80                 process_handle->exitstatus = WEXITSTATUS(status);
81         }
82         _wapi_time_t_to_filetime (time(NULL), &process_handle->exit_time);
83         
84         _wapi_shared_handle_set_signal_state (handle, TRUE);
85
86         _wapi_handle_unlock_shared_handles ();
87
88         return (ok);
89 }
90
91 /* See if any child processes have terminated and wait() for them,
92  * updating process handle info.  This function is called from the
93  * collection thread every few seconds.
94  */
95 static gboolean waitfor_pid (gpointer test, gpointer user_data G_GNUC_UNUSED)
96 {
97         struct _WapiHandle_process *process;
98         gboolean ok;
99         int status;
100         pid_t ret;
101         
102         if (_wapi_handle_issignalled (test)) {
103                 /* We've already done this one */
104                 return (FALSE);
105         }
106         
107         ok = _wapi_lookup_handle (test, WAPI_HANDLE_PROCESS,
108                                   (gpointer *)&process);
109         if (ok == FALSE) {
110                 /* The handle must have been too old and was reaped */
111                 return (FALSE);
112         }
113         
114         do {
115                 ret = waitpid (process->id, &status, WNOHANG);
116         } while (errno == EINTR);
117         
118         if (ret <= 0) {
119                 /* Process not ready for wait */
120 #ifdef DEBUG
121                 g_message ("%s: Process %d not ready for waiting for: %s",
122                            __func__, process->id, g_strerror (errno));
123 #endif
124
125                 return (FALSE);
126         }
127         
128 #ifdef DEBUG
129         g_message ("%s: Process %d finished", __func__, ret);
130 #endif
131
132         process_set_termination_details (test, status);
133         
134         /* return FALSE to keep searching */
135         return (FALSE);
136 }
137
138 void _wapi_process_reap (void)
139 {
140 #ifdef DEBUG
141         g_message ("%s: Reaping child processes", __func__);
142 #endif
143
144         _wapi_search_handle (WAPI_HANDLE_PROCESS, waitfor_pid, NULL, NULL,
145                              FALSE);
146 }
147
148 /* Limitations: This can only wait for processes that are our own
149  * children.  Fixing this means resurrecting a daemon helper to manage
150  * processes.
151  */
152 static guint32 process_wait (gpointer handle, guint32 timeout)
153 {
154         struct _WapiHandle_process *process_handle;
155         gboolean ok;
156         pid_t pid, ret;
157         int status;
158         
159 #ifdef DEBUG
160         g_message ("%s: Waiting for process %p", __func__, handle);
161 #endif
162
163         ok = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
164                                   (gpointer *)&process_handle);
165         if (ok == FALSE) {
166                 g_warning ("%s: error looking up process handle %p", __func__,
167                            handle);
168                 return(WAIT_FAILED);
169         }
170         
171         pid = process_handle->id;
172         
173 #ifdef DEBUG
174         g_message ("%s: PID is %d", __func__, pid);
175 #endif
176
177         if (timeout == INFINITE) {
178                 while ((ret = waitpid (pid, &status, 0)) != pid) {
179                         if (ret == (pid_t)-1 && errno != EINTR) {
180                                 return(WAIT_FAILED);
181                         }
182                 }
183         } else if (timeout == 0) {
184                 /* Just poll */
185                 ret = waitpid (pid, &status, WNOHANG);
186                 if (ret != pid) {
187                         return (WAIT_TIMEOUT);
188                 }
189         } else {
190                 /* Poll in a loop */
191                 do {
192                         ret = waitpid (pid, &status, WNOHANG);
193                         if (ret == pid) {
194                                 break;
195                         } else if (ret == (pid_t)-1 && errno != EINTR) {
196                                 return(WAIT_FAILED);
197                         }
198
199                         _wapi_handle_spin (100);
200                         timeout -= 100;
201                 } while (timeout > 0);
202
203                 if (timeout <= 0) {
204                         return(WAIT_TIMEOUT);
205                 }
206         }
207
208         /* Process must have exited */
209 #ifdef DEBUG
210         g_message ("%s: Wait done", __func__);
211 #endif
212
213         ok = process_set_termination_details (handle, status);
214         if (ok == FALSE) {
215                 SetLastError (ERROR_OUTOFMEMORY);
216                 return (WAIT_FAILED);
217         }
218
219         return(WAIT_OBJECT_0);
220 }
221
222 void _wapi_process_signal_self ()
223 {
224         if (current_process != NULL) {
225                 process_set_termination_details (current_process, 0);
226         }
227 }
228
229         
230 static void process_set_defaults (struct _WapiHandle_process *process_handle)
231 {
232         /* These seem to be the defaults on w2k */
233         process_handle->min_working_set = 204800;
234         process_handle->max_working_set = 1413120;
235
236         _wapi_time_t_to_filetime (time (NULL), &process_handle->create_time);
237 }
238
239 /* Implemented as just a wrapper around CreateProcess () */
240 gboolean ShellExecuteEx (WapiShellExecuteInfo *sei)
241 {
242         gboolean ret;
243         WapiProcessInformation process_info;
244         gunichar2 *args;
245         gchar *u8file, *u8params, *u8args;
246         
247         if (sei == NULL) {
248                 /* w2k just segfaults here, but we can do better than
249                  * that
250                  */
251                 SetLastError (ERROR_INVALID_PARAMETER);
252                 return (FALSE);
253         }
254
255         if (sei->lpFile == NULL) {
256                 /* w2k returns TRUE for this, for some reason. */
257                 return (TRUE);
258         }
259         
260         /* Put both executable and parameters into the second argument
261          * to CreateProcess (), so it searches $PATH.  The conversion
262          * into and back out of utf8 is because there is no
263          * g_strdup_printf () equivalent for gunichar2 :-(
264          */
265         u8file = g_utf16_to_utf8 (sei->lpFile, -1, NULL, NULL, NULL);
266         if (u8file == NULL) {
267                 SetLastError (ERROR_INVALID_DATA);
268                 return (FALSE);
269         }
270         
271         if (sei->lpParameters != NULL) {
272                 u8params = g_utf16_to_utf8 (sei->lpParameters, -1, NULL, NULL, NULL);
273                 if (u8params == NULL) {
274                         SetLastError (ERROR_INVALID_DATA);
275                         g_free (u8file);
276                         return (FALSE);
277                 }
278         
279                 u8args = g_strdup_printf ("%s %s", u8file, u8params);
280                 if (u8args == NULL) {
281                         SetLastError (ERROR_INVALID_DATA);
282                         g_free (u8params);
283                         g_free (u8file);
284                         return (FALSE);
285                 }
286         
287                 args = g_utf8_to_utf16 (u8args, -1, NULL, NULL, NULL);
288         
289                 g_free (u8file);
290                 g_free (u8params);
291                 g_free (u8args);
292         } else {
293                 args = g_utf8_to_utf16 (u8file, -1, NULL, NULL, NULL);
294         }
295                 
296         if (args == NULL) {
297                 SetLastError (ERROR_INVALID_DATA);
298                 return (FALSE);
299         }
300         
301         ret = CreateProcess (NULL, args, NULL, NULL, TRUE,
302                              CREATE_UNICODE_ENVIRONMENT, NULL,
303                              sei->lpDirectory, NULL, &process_info);
304         g_free (args);
305         
306         if (!ret) {
307                 return (FALSE);
308         }
309         
310         if (sei->fMask & SEE_MASK_NOCLOSEPROCESS) {
311                 sei->hProcess = process_info.hProcess;
312         } else {
313                 CloseHandle (process_info.hProcess);
314         }
315         
316         return (ret);
317 }
318
319 gboolean CreateProcess (const gunichar2 *appname, const gunichar2 *cmdline,
320                         WapiSecurityAttributes *process_attrs G_GNUC_UNUSED,
321                         WapiSecurityAttributes *thread_attrs G_GNUC_UNUSED,
322                         gboolean inherit_handles, guint32 create_flags,
323                         gpointer new_environ, const gunichar2 *cwd,
324                         WapiStartupInfo *startup,
325                         WapiProcessInformation *process_info)
326 {
327         gchar *cmd=NULL, *prog = NULL, *full_prog = NULL, *args = NULL, *args_after_prog = NULL, *dir = NULL, **env_strings = NULL, **argv;
328         guint32 i, env_count = 0;
329         gboolean ret = FALSE;
330         gpointer handle;
331         struct _WapiHandle_process process_handle = {0}, *process_handle_data;
332         GError *gerr = NULL;
333         int in_fd, out_fd, err_fd;
334         pid_t pid;
335         int thr_ret;
336         
337         mono_once (&process_ops_once, process_ops_init);
338         
339         /* appname and cmdline specify the executable and its args:
340          *
341          * If appname is not NULL, it is the name of the executable.
342          * Otherwise the executable is the first token in cmdline.
343          *
344          * Executable searching:
345          *
346          * If appname is not NULL, it can specify the full path and
347          * file name, or else a partial name and the current directory
348          * will be used.  There is no additional searching.
349          *
350          * If appname is NULL, the first whitespace-delimited token in
351          * cmdline is used.  If the name does not contain a full
352          * directory path, the search sequence is:
353          *
354          * 1) The directory containing the current process
355          * 2) The current working directory
356          * 3) The windows system directory  (Ignored)
357          * 4) The windows directory (Ignored)
358          * 5) $PATH
359          *
360          * Just to make things more interesting, tokens can contain
361          * white space if they are surrounded by quotation marks.  I'm
362          * beginning to understand just why windows apps are generally
363          * so crap, with an API like this :-(
364          */
365         if (appname != NULL) {
366                 cmd = mono_unicode_to_external (appname);
367                 if (cmd == NULL) {
368 #ifdef DEBUG
369                         g_message ("%s: unicode conversion returned NULL",
370                                    __func__);
371 #endif
372
373                         SetLastError (ERROR_PATH_NOT_FOUND);
374                         goto cleanup;
375                 }
376
377                 /* Turn all the slashes round the right way */
378                 for (i = 0; i < strlen (cmd); i++) {
379                         if (cmd[i] == '\\') {
380                                 cmd[i] = '/';
381                         }
382                 }
383         }
384         
385         if (cmdline != NULL) {
386                 args = mono_unicode_to_external (cmdline);
387                 if (args == NULL) {
388 #ifdef DEBUG
389                         g_message ("%s: unicode conversion returned NULL", __func__);
390 #endif
391
392                         SetLastError (ERROR_PATH_NOT_FOUND);
393                         goto cleanup;
394                 }
395         }
396
397         if (cwd != NULL) {
398                 dir = mono_unicode_to_external (cwd);
399                 if (dir == NULL) {
400 #ifdef DEBUG
401                         g_message ("%s: unicode conversion returned NULL", __func__);
402 #endif
403
404                         SetLastError (ERROR_PATH_NOT_FOUND);
405                         goto cleanup;
406                 }
407
408                 /* Turn all the slashes round the right way */
409                 for (i = 0; i < strlen (dir); i++) {
410                         if (dir[i] == '\\') {
411                                 dir[i] = '/';
412                         }
413                 }
414         } else {
415                 dir = g_get_current_dir ();
416         }
417         
418
419         /* We can't put off locating the executable any longer :-( */
420         if (cmd != NULL) {
421                 gchar *unquoted;
422                 if (g_ascii_isalpha (cmd[0]) && (cmd[1] == ':')) {
423                         /* Strip off the drive letter.  I can't
424                          * believe that CP/M holdover is still
425                          * visible...
426                          */
427                         g_memmove (cmd, cmd+2, strlen (cmd)-2);
428                         cmd[strlen (cmd)-2] = '\0';
429                 }
430
431                 unquoted = g_shell_unquote (cmd, NULL);
432                 if (unquoted[0] == '/') {
433                         /* Assume full path given */
434                         prog = g_strdup (unquoted);
435
436                         /* Executable existing ? */
437                         if (access (prog, X_OK) != 0) {
438 #ifdef DEBUG
439                                 g_message ("%s: Couldn't find executable %s",
440                                            __func__, prog);
441 #endif
442                                 g_free (prog);
443                                 g_free (unquoted);
444                                 SetLastError (ERROR_FILE_NOT_FOUND);
445                                 goto cleanup;
446                         }
447                 } else {
448                         /* Search for file named by cmd in the current
449                          * directory
450                          */
451                         char *curdir = g_get_current_dir ();
452
453                         prog = g_strdup_printf ("%s/%s", curdir, unquoted);
454                         g_free (unquoted);
455                         g_free (curdir);
456
457                         /* And make sure it's executable */
458                         if (access (prog, X_OK) != 0) {
459 #ifdef DEBUG
460                                 g_message ("%s: Couldn't find executable %s",
461                                            __func__, prog);
462 #endif
463                                 g_free (prog);
464                                 SetLastError (ERROR_FILE_NOT_FOUND);
465                                 goto cleanup;
466                         }
467                 }
468
469                 args_after_prog = args;
470         } else {
471                 gchar *token = NULL;
472                 char quote;
473                 
474                 /* Dig out the first token from args, taking quotation
475                  * marks into account
476                  */
477
478                 /* First, strip off all leading whitespace */
479                 args = g_strchug (args);
480                 
481                 /* args_after_prog points to the contents of args
482                  * after token has been set (otherwise argv[0] is
483                  * duplicated)
484                  */
485                 args_after_prog = args;
486
487                 /* Assume the opening quote will always be the first
488                  * character
489                  */
490                 if (args[0] == '\"' || args [0] == '\'') {
491                         quote = args [0];
492                         for (i = 1; args[i] != '\0' && args[i] != quote; i++);
493                         if (g_ascii_isspace (args[i+1])) {
494                                 /* We found the first token */
495                                 token = g_strndup (args+1, i-1);
496                                 args_after_prog = args + i;
497                         } else {
498                                 /* Quotation mark appeared in the
499                                  * middle of the token.  Just give the
500                                  * whole first token, quotes and all,
501                                  * to exec.
502                                  */
503                         }
504                 }
505                 
506                 if (token == NULL) {
507                         /* No quote mark, or malformed */
508                         for (i = 0; args[i] != '\0'; i++) {
509                                 if (g_ascii_isspace (args[i])) {
510                                         token = g_strndup (args, i);
511                                         args_after_prog = args + i + 1;
512                                         break;
513                                 }
514                         }
515                 }
516
517                 if (token == NULL && args[0] != '\0') {
518                         /* Must be just one token in the string */
519                         token = g_strdup (args);
520                         args_after_prog = NULL;
521                 }
522                 
523                 if (token == NULL) {
524                         /* Give up */
525 #ifdef DEBUG
526                         g_message ("%s: Couldn't find what to exec", __func__);
527 #endif
528
529                         SetLastError (ERROR_PATH_NOT_FOUND);
530                         goto cleanup;
531                 }
532                 
533                 /* Turn all the slashes round the right way. Only for
534                  * the prg. name
535                  */
536                 for (i = 0; i < strlen (token); i++) {
537                         if (token[i] == '\\') {
538                                 token[i] = '/';
539                         }
540                 }
541
542                 if (g_ascii_isalpha (token[0]) && (token[1] == ':')) {
543                         /* Strip off the drive letter.  I can't
544                          * believe that CP/M holdover is still
545                          * visible...
546                          */
547                         g_memmove (token, token+2, strlen (token)-2);
548                         token[strlen (token)-2] = '\0';
549                 }
550
551                 if (token[0] == '/') {
552                         /* Assume full path given */
553                         prog = g_strdup (token);
554                         
555                         /* Executable existing ? */
556                         if (access (prog, X_OK) != 0) {
557                                 g_free (prog);
558 #ifdef DEBUG
559                                 g_message ("%s: Couldn't find executable %s",
560                                            __func__, token);
561 #endif
562                                 g_free (token);
563                                 SetLastError (ERROR_FILE_NOT_FOUND);
564                                 goto cleanup;
565                         }
566
567                 } else {
568                         char *curdir = g_get_current_dir ();
569
570                         /* FIXME: Need to record the directory
571                          * containing the current process, and check
572                          * that for the new executable as the first
573                          * place to look
574                          */
575
576                         prog = g_strdup_printf ("%s/%s", curdir, token);
577                         g_free (curdir);
578
579                         /* I assume X_OK is the criterion to use,
580                          * rather than F_OK
581                          */
582                         if (access (prog, X_OK) != 0) {
583                                 g_free (prog);
584                                 prog = g_find_program_in_path (token);
585                                 if (prog == NULL) {
586 #ifdef DEBUG
587                                         g_message ("%s: Couldn't find executable %s", __func__, token);
588 #endif
589
590                                         g_free (token);
591                                         SetLastError (ERROR_FILE_NOT_FOUND);
592                                         goto cleanup;
593                                 }
594                         }
595                 }
596
597                 g_free (token);
598         }
599
600 #ifdef DEBUG
601         g_message ("%s: Exec prog [%s] args [%s]", __func__, prog,
602                    args_after_prog);
603 #endif
604         
605         if (args_after_prog != NULL && *args_after_prog) {
606                 gchar *qprog;
607
608                 qprog = g_shell_quote (prog);
609                 full_prog = g_strconcat (qprog, " ", args_after_prog, NULL);
610                 g_free (qprog);
611         } else {
612                 full_prog = g_shell_quote (prog);
613         }
614
615         ret = g_shell_parse_argv (full_prog, NULL, &argv, &gerr);
616         if (ret == FALSE) {
617                 /* FIXME: Could do something with the GError here
618                  */
619         }
620
621         if (startup != NULL && startup->dwFlags & STARTF_USESTDHANDLES) {
622                 in_fd = GPOINTER_TO_UINT (startup->hStdInput);
623                 out_fd = GPOINTER_TO_UINT (startup->hStdOutput);
624                 err_fd = GPOINTER_TO_UINT (startup->hStdError);
625         } else {
626                 in_fd = GPOINTER_TO_UINT (GetStdHandle (STD_INPUT_HANDLE));
627                 out_fd = GPOINTER_TO_UINT (GetStdHandle (STD_OUTPUT_HANDLE));
628                 err_fd = GPOINTER_TO_UINT (GetStdHandle (STD_ERROR_HANDLE));
629         }
630         
631         g_strlcpy (process_handle.proc_name, prog,
632                    _WAPI_PROC_NAME_MAX_LEN - 1);
633
634         process_set_defaults (&process_handle);
635         
636         handle = _wapi_handle_new (WAPI_HANDLE_PROCESS, &process_handle);
637         if (handle == _WAPI_HANDLE_INVALID) {
638                 g_warning ("%s: error creating process handle", __func__);
639
640                 SetLastError (ERROR_PATH_NOT_FOUND);
641                 goto cleanup;
642         }
643
644         /* Hold another reference so the process has somewhere to
645          * store its exit data even if we drop this handle
646          */
647         _wapi_handle_ref (handle);
648         
649         /* new_environ is a block of NULL-terminated strings, which
650          * is itself NULL-terminated. Of course, passing an array of
651          * string pointers would have made things too easy :-(
652          *
653          * If new_environ is not NULL it specifies the entire set of
654          * environment variables in the new process.  Otherwise the
655          * new process inherits the same environment.
656          */
657         if (new_environ != NULL) {
658                 gunichar2 *new_environp;
659
660                 /* Count the number of strings */
661                 for (new_environp = (gunichar2 *)new_environ; *new_environp;
662                      new_environp++) {
663                         env_count++;
664                         while (*new_environp) {
665                                 new_environp++;
666                         }
667                 }
668
669                 /* +2: one for the process handle value, and the last
670                  * one is NULL
671                  */
672                 env_strings = g_new0 (gchar *, env_count + 2);
673                 
674                 /* Copy each environ string into 'strings' turning it
675                  * into utf8 (or the requested encoding) at the same
676                  * time
677                  */
678                 env_count = 0;
679                 for (new_environp = (gunichar2 *)new_environ; *new_environp;
680                      new_environp++) {
681                         env_strings[env_count] = mono_unicode_to_external (new_environp);
682                         env_count++;
683                         while (*new_environp) {
684                                 new_environp++;
685                         }
686                 }
687         } else {
688                 for (i = 0; environ[i] != NULL; i++) {
689                         env_count++;
690                 }
691
692                 /* +2: one for the process handle value, and the last
693                  * one is NULL
694                  */
695                 env_strings = g_new0 (gchar *, env_count + 2);
696                 
697                 /* Copy each environ string into 'strings' turning it
698                  * into utf8 (or the requested encoding) at the same
699                  * time
700                  */
701                 env_count = 0;
702                 for (i = 0; environ[i] != NULL; i++) {
703                         env_strings[env_count] = g_strdup (environ[i]);
704                         env_count++;
705                 }
706         }
707         /* pass process handle info to the child, so it doesn't have
708          * to do an expensive search over the whole list
709          */
710         if (env_strings != NULL) {
711                 struct _WapiHandleUnshared *handle_data;
712                 struct _WapiHandle_shared_ref *ref;
713                 
714                 handle_data = &_WAPI_PRIVATE_HANDLES(GPOINTER_TO_UINT(handle));
715                 ref = &handle_data->u.shared;
716                 
717                 env_strings[env_count] = g_strdup_printf ("_WAPI_PROCESS_HANDLE_OFFSET=%d", ref->offset);
718         }
719
720         thr_ret = _wapi_handle_lock_shared_handles ();
721         g_assert (thr_ret == 0);
722         
723         pid = fork ();
724         if (pid == -1) {
725                 /* Error */
726                 SetLastError (ERROR_OUTOFMEMORY);
727                 _wapi_handle_unref (handle);
728                 goto cleanup;
729         } else if (pid == 0) {
730                 /* Child */
731                 
732                 /* Wait for the parent to finish setting up the
733                  * handle.  The semaphore lock is safe because the
734                  * sem_undo structures of a semaphore aren't inherited
735                  * across a fork ()
736                  */
737                 thr_ret = _wapi_handle_lock_shared_handles ();
738                 g_assert (thr_ret == 0);
739         
740                 _wapi_handle_unlock_shared_handles ();
741                 
742                 /* should we detach from the process group? */
743
744                 /* Connect stdin, stdout and stderr */
745                 dup2 (in_fd, 0);
746                 dup2 (out_fd, 1);
747                 dup2 (err_fd, 2);
748
749                 if (inherit_handles != TRUE) {
750                         /* FIXME: do something here */
751                 }
752                 
753                 /* Close all file descriptors */
754                 for (i = getdtablesize () - 1; i > 2; i--) {
755                         close (i);
756                 }
757
758 #ifdef DEBUG
759                 g_message ("%s: exec()ing [%s] in dir [%s]", __func__, cmd,
760                            dir);
761                 for (i = 0; argv[i] != NULL; i++) {
762                         g_message ("arg %d: [%s]", i, argv[i]);
763                 }
764                 
765                 for (i = 0; env_strings[i] != NULL; i++) {
766                         g_message ("env %d: [%s]", i, env_strings[i]);
767                 }
768 #endif
769
770                 /* set cwd */
771                 if (chdir (dir) == -1) {
772                         /* set error */
773                         exit (-1);
774                 }
775                 
776                 /* exec */
777                 execve (argv[0], argv, env_strings);
778                 
779                 /* set error */
780                 exit (-1);
781         }
782         /* parent */
783         
784         ret = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
785                                    (gpointer *)&process_handle_data);
786         if (ret == FALSE) {
787                 g_warning ("%s: error looking up process handle %p", __func__,
788                            handle);
789                 _wapi_handle_unref (handle);
790                 goto cleanup;
791         }
792         
793         process_handle_data->id = pid;
794         
795         if (process_info != NULL) {
796                 process_info->hProcess = handle;
797                 process_info->dwProcessId = pid;
798
799                 /* FIXME: we might need to handle the thread info some
800                  * day
801                  */
802                 process_info->hThread = NULL;
803                 process_info->dwThreadId = 0;
804         }
805
806 cleanup:
807         _wapi_handle_unlock_shared_handles ();
808
809         if (cmd != NULL) {
810                 g_free (cmd);
811         }
812         if (full_prog != NULL) {
813                 g_free (prog);
814         }
815         if (args != NULL) {
816                 g_free (args);
817         }
818         if (dir != NULL) {
819                 g_free (dir);
820         }
821         if(env_strings != NULL) {
822                 g_strfreev (env_strings);
823         }
824         
825         return(ret);
826 }
827                 
828 static void process_set_name (struct _WapiHandle_process *process_handle)
829 {
830         gchar *progname, *utf8_progname, *slash;
831         
832         progname=g_get_prgname ();
833         utf8_progname=mono_utf8_from_external (progname);
834
835 #ifdef DEBUG
836         g_message ("%s: using [%s] as prog name", __func__, progname);
837 #endif
838
839         if(utf8_progname!=NULL) {
840                 slash=strrchr (utf8_progname, '/');
841                 if(slash!=NULL) {
842                         g_strlcpy (process_handle->proc_name, slash+1,
843                                    _WAPI_PROC_NAME_MAX_LEN - 1);
844                 } else {
845                         g_strlcpy (process_handle->proc_name, utf8_progname,
846                                    _WAPI_PROC_NAME_MAX_LEN - 1);
847                 }
848
849                 g_free (utf8_progname);
850         }
851 }
852
853 extern void _wapi_time_t_to_filetime (time_t timeval, WapiFileTime *filetime);
854
855 #if !GLIB_CHECK_VERSION (2,4,0)
856 #define g_setenv(a,b,c) setenv(a,b,c)
857 #define g_unsetenv(a) unsetenv(a)
858 #endif
859
860 static void process_set_current (void)
861 {
862         pid_t pid = _wapi_getpid ();
863         const char *handle_env;
864         struct _WapiHandle_process process_handle = {0};
865         
866         handle_env = g_getenv ("_WAPI_PROCESS_HANDLE_OFFSET");
867         g_unsetenv ("_WAPI_PROCESS_HANDLE_OFFSET");
868         
869         if (handle_env != NULL) {
870                 struct _WapiHandle_process *process_handlep;
871                 guchar *procname = NULL;
872                 gboolean ok;
873                 
874                 current_process = _wapi_handle_new_from_offset (WAPI_HANDLE_PROCESS, atoi (handle_env), TRUE);
875                 
876 #ifdef DEBUG
877                 g_message ("%s: Found my process handle: %p (offset %d 0x%x)",
878                            __func__, current_process, atoi (handle_env),
879                            atoi (handle_env));
880 #endif
881
882                 ok = _wapi_lookup_handle (current_process, WAPI_HANDLE_PROCESS,
883                                           (gpointer *)&process_handlep);
884                 if (ok) {
885                         /* This test will probably break on linuxthreads, but
886                          * that should be ancient history on all distros we
887                          * care about by now
888                          */
889                         if (process_handlep->id == pid) {
890                                 procname = process_handlep->proc_name;
891                                 if (!strcmp (procname, "mono")) {
892                                         /* Set a better process name */
893 #ifdef DEBUG
894                                         g_message ("%s: Setting better process name", __func__);
895 #endif
896                                         
897                                         process_set_name (process_handlep);
898                                 } else {
899 #ifdef DEBUG
900                                         g_message ("%s: Leaving process name: %s", __func__, procname);
901 #endif
902                                 }
903
904                                 return;
905                         }
906
907                         /* Wrong pid, so drop this handle and fall through to
908                          * create a new one
909                          */
910                         _wapi_handle_unref (current_process);
911                 }
912         }
913
914         /* We get here if the handle wasn't specified in the
915          * environment, or if the process ID was wrong, or if the
916          * handle lookup failed (eg if the parent process forked and
917          * quit immediately, and deleted the shared data before the
918          * child got a chance to attach it.)
919          */
920
921 #ifdef DEBUG
922         g_message ("%s: Need to create my own process handle", __func__);
923 #endif
924
925         process_handle.id = pid;
926
927         process_set_defaults (&process_handle);
928         process_set_name (&process_handle);
929
930         current_process = _wapi_handle_new (WAPI_HANDLE_PROCESS,
931                                             &process_handle);
932         if (current_process == _WAPI_HANDLE_INVALID) {
933                 g_warning ("%s: error creating process handle", __func__);
934                 return;
935         }
936                 
937         /* Make sure the new handle has a reference so it wont go away
938          * until this process exits
939          */
940         _wapi_handle_ref (current_process);
941 }
942
943 /* Returns a pseudo handle that doesn't need to be closed afterwards */
944 gpointer GetCurrentProcess (void)
945 {
946         mono_once (&process_current_once, process_set_current);
947                 
948         return((gpointer)-1);
949 }
950
951 guint32 GetProcessId (gpointer handle)
952 {
953         struct _WapiHandle_process *process_handle;
954         gboolean ok;
955         
956         ok = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
957                                   (gpointer *)&process_handle);
958         if (ok == FALSE) {
959                 SetLastError (ERROR_INVALID_HANDLE);
960                 return (0);
961         }
962         
963         return (process_handle->id);
964 }
965
966 guint32 GetCurrentProcessId (void)
967 {
968         mono_once (&process_current_once, process_set_current);
969                 
970         return (GetProcessId (current_process));
971 }
972
973 /* Returns the process id as a convenience to the functions that call this */
974 static pid_t signal_process_if_gone (gpointer handle)
975 {
976         struct _WapiHandle_process *process_handle;
977         gboolean ok;
978         
979         /* Make sure the process is signalled if it has exited - if
980          * the parent process didn't wait for it then it won't be
981          */
982         ok = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
983                                   (gpointer *)&process_handle);
984         if (ok == FALSE) {
985                 /* It's possible that the handle has vanished during
986                  * the _wapi_search_handle before it gets here, so
987                  * don't spam the console with warnings.
988                  */
989 /*              g_warning ("%s: error looking up process handle %p",
990   __func__, handle);*/
991                 
992                 return (0);
993         }
994         
995 #ifdef DEBUG
996         g_message ("%s: looking at process %d", __func__, process_handle->id);
997 #endif
998
999         if (kill (process_handle->id, 0) == -1 &&
1000             (errno == ESRCH ||
1001              errno == EPERM)) {
1002                 /* The process is dead, (EPERM tells us a new process
1003                  * has that ID, but as it's owned by someone else it
1004                  * can't be the one listed in our shared memory file)
1005                  */
1006                 _wapi_shared_handle_set_signal_state (handle, TRUE);
1007         }
1008
1009         return (process_handle->id);
1010 }
1011
1012 static gboolean process_enum (gpointer handle, gpointer user_data)
1013 {
1014         GArray *processes=user_data;
1015         pid_t pid = signal_process_if_gone (handle);
1016         int i;
1017         
1018         if (pid == 0) {
1019                 return (FALSE);
1020         }
1021         
1022         /* Ignore processes that have already exited (ie they are signalled) */
1023         if (_wapi_handle_issignalled (handle) == FALSE) {
1024 #ifdef DEBUG
1025                 g_message ("%s: process %d added to array", __func__, pid);
1026 #endif
1027
1028                 /* This ensures that duplicates aren't returned (see
1029                  * the comment above _wapi_search_handle () for why
1030                  * it's needed
1031                  */
1032                 for (i = 0; i < processes->len; i++) {
1033                         if (g_array_index (processes, pid_t, i) == pid) {
1034                                 /* We've already got this one, return
1035                                  * FALSE to keep searching
1036                                  */
1037                                 return (FALSE);
1038                         }
1039                 }
1040                 
1041                 g_array_append_val (processes, pid);
1042         }
1043         
1044         /* Return false to keep searching */
1045         return(FALSE);
1046 }
1047
1048 gboolean EnumProcesses (guint32 *pids, guint32 len, guint32 *needed)
1049 {
1050         GArray *processes = g_array_new (FALSE, FALSE, sizeof(pid_t));
1051         guint32 fit, i, j;
1052         
1053         mono_once (&process_current_once, process_set_current);
1054         
1055         _wapi_search_handle (WAPI_HANDLE_PROCESS, process_enum, processes,
1056                              NULL, TRUE);
1057         
1058         fit=len/sizeof(guint32);
1059         for (i = 0, j = 0; j < fit && i < processes->len; i++) {
1060                 pids[j++] = g_array_index (processes, pid_t, i);
1061         }
1062
1063         g_array_free (processes, TRUE);
1064         
1065         *needed = j * sizeof(guint32);
1066         
1067         return(TRUE);
1068 }
1069
1070 static gboolean process_open_compare (gpointer handle, gpointer user_data)
1071 {
1072         pid_t wanted_pid;
1073         pid_t checking_pid = signal_process_if_gone (handle);
1074
1075         if (checking_pid == 0) {
1076                 return(FALSE);
1077         }
1078         
1079         wanted_pid = GPOINTER_TO_UINT (user_data);
1080
1081         /* It's possible to have more than one process handle with the
1082          * same pid, but only the one running process can be
1083          * unsignalled
1084          */
1085         if (checking_pid == wanted_pid &&
1086             _wapi_handle_issignalled (handle) == FALSE) {
1087                 /* If the handle is blown away in the window between
1088                  * returning TRUE here and _wapi_search_handle pinging
1089                  * the timestamp, the search will continue
1090                  */
1091                 return(TRUE);
1092         } else {
1093                 return(FALSE);
1094         }
1095 }
1096
1097 gpointer OpenProcess (guint32 access G_GNUC_UNUSED, gboolean inherit G_GNUC_UNUSED, guint32 pid)
1098 {
1099         /* Find the process handle that corresponds to pid */
1100         gpointer handle;
1101         
1102         mono_once (&process_current_once, process_set_current);
1103
1104 #ifdef DEBUG
1105         g_message ("%s: looking for process %d", __func__, pid);
1106 #endif
1107
1108         handle = _wapi_search_handle (WAPI_HANDLE_PROCESS,
1109                                       process_open_compare,
1110                                       GUINT_TO_POINTER (pid), NULL, TRUE);
1111         if (handle == 0) {
1112 #ifdef DEBUG
1113                 g_message ("%s: Can't find pid %d", __func__, pid);
1114 #endif
1115
1116                 SetLastError (ERROR_PROC_NOT_FOUND);
1117         
1118                 return(NULL);
1119         }
1120
1121         _wapi_handle_ref (handle);
1122         
1123         return(handle);
1124 }
1125
1126 gboolean GetExitCodeProcess (gpointer process, guint32 *code)
1127 {
1128         struct _WapiHandle_process *process_handle;
1129         gboolean ok;
1130         
1131         mono_once (&process_current_once, process_set_current);
1132
1133         if(code==NULL) {
1134                 return(FALSE);
1135         }
1136         
1137         ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
1138                                 (gpointer *)&process_handle);
1139         if(ok==FALSE) {
1140 #ifdef DEBUG
1141                 g_message ("%s: Can't find process %p", __func__, process);
1142 #endif
1143                 
1144                 return(FALSE);
1145         }
1146         
1147         /* A process handle is only signalled if the process has exited
1148          * and has been waited for */
1149         if (_wapi_handle_issignalled (process) == TRUE ||
1150             process_wait (process, 0) == WAIT_OBJECT_0) {
1151                 *code = process_handle->exitstatus;
1152         } else {
1153                 *code = STILL_ACTIVE;
1154         }
1155         
1156         return(TRUE);
1157 }
1158
1159 gboolean GetProcessTimes (gpointer process, WapiFileTime *create_time,
1160                           WapiFileTime *exit_time, WapiFileTime *kernel_time,
1161                           WapiFileTime *user_time)
1162 {
1163         struct _WapiHandle_process *process_handle;
1164         gboolean ok;
1165         
1166         mono_once (&process_current_once, process_set_current);
1167
1168         if(create_time==NULL || exit_time==NULL || kernel_time==NULL ||
1169            user_time==NULL) {
1170                 /* Not sure if w32 allows NULLs here or not */
1171                 return(FALSE);
1172         }
1173         
1174         ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
1175                                 (gpointer *)&process_handle);
1176         if(ok==FALSE) {
1177 #ifdef DEBUG
1178                 g_message ("%s: Can't find process %p", __func__, process);
1179 #endif
1180                 
1181                 return(FALSE);
1182         }
1183         
1184         *create_time=process_handle->create_time;
1185
1186         /* A process handle is only signalled if the process has
1187          * exited.  Otherwise exit_time isn't set
1188          */
1189         if(_wapi_handle_issignalled (process)==TRUE) {
1190                 *exit_time=process_handle->exit_time;
1191         }
1192         
1193         return(TRUE);
1194 }
1195
1196 gboolean EnumProcessModules (gpointer process, gpointer *modules,
1197                              guint32 size, guint32 *needed)
1198 {
1199         /* Store modules in an array of pointers (main module as
1200          * modules[0]), using the load address for each module as a
1201          * token.  (Use 'NULL' as an alternative for the main module
1202          * so that the simple implementation can just return one item
1203          * for now.)  Get the info from /proc/<pid>/maps on linux,
1204          * other systems will have to implement /dev/kmem reading or
1205          * whatever other horrid technique is needed.
1206          */
1207         if(size<sizeof(gpointer)) {
1208                 return(FALSE);
1209         }
1210         
1211 #ifdef linux
1212         modules[0]=NULL;
1213         *needed=sizeof(gpointer);
1214 #else
1215         modules[0]=NULL;
1216         *needed=sizeof(gpointer);
1217 #endif
1218         
1219         return(TRUE);
1220 }
1221
1222 guint32 GetModuleBaseName (gpointer process, gpointer module,
1223                            gunichar2 *basename, guint32 size)
1224 {
1225         struct _WapiHandle_process *process_handle;
1226         gboolean ok;
1227         
1228         mono_once (&process_current_once, process_set_current);
1229
1230 #ifdef DEBUG
1231         g_message ("%s: Getting module base name, process handle %p module %p",
1232                    __func__, process, module);
1233 #endif
1234
1235         if(basename==NULL || size==0) {
1236                 return(FALSE);
1237         }
1238         
1239         ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
1240                                 (gpointer *)&process_handle);
1241         if(ok==FALSE) {
1242 #ifdef DEBUG
1243                 g_message ("%s: Can't find process %p", __func__, process);
1244 #endif
1245                 
1246                 return(FALSE);
1247         }
1248
1249         if(module==NULL) {
1250                 /* Shorthand for the main module, which has the
1251                  * process name recorded in the handle data
1252                  */
1253                 pid_t pid;
1254                 gunichar2 *procname;
1255                 guchar *procname_utf8 = NULL;
1256                 glong len, bytes;
1257                 
1258 #ifdef DEBUG
1259                 g_message ("%s: Returning main module name", __func__);
1260 #endif
1261
1262                 pid=process_handle->id;
1263                 procname_utf8 = process_handle->proc_name;
1264         
1265 #ifdef DEBUG
1266                 g_message ("%s: Process name is [%s]", __func__,
1267                            procname_utf8);
1268 #endif
1269
1270                 procname = g_utf8_to_utf16 (procname_utf8, -1, NULL, &len,
1271                                             NULL);
1272                 if (procname == NULL) {
1273                         /* bugger */
1274                         return(0);
1275                 }
1276
1277                 /* Add the terminator, and convert chars to bytes */
1278                 bytes = (len + 1) * 2;
1279                 
1280                 if (size < bytes) {
1281 #ifdef DEBUG
1282                         g_message ("%s: Size %d smaller than needed (%ld); truncating", __func__, size, bytes);
1283 #endif
1284
1285                         memcpy (basename, procname, size);
1286                 } else {
1287 #ifdef DEBUG
1288                         g_message ("%s: Size %d larger than needed (%ld)",
1289                                    __func__, size, bytes);
1290 #endif
1291
1292                         memcpy (basename, procname, bytes);
1293                 }
1294                 
1295                 g_free (procname);
1296
1297                 return(len);
1298         } else {
1299                 /* Look up the address in /proc/<pid>/maps */
1300         }
1301         
1302         return(0);
1303 }
1304
1305 gboolean GetProcessWorkingSetSize (gpointer process, size_t *min, size_t *max)
1306 {
1307         struct _WapiHandle_process *process_handle;
1308         gboolean ok;
1309         
1310         mono_once (&process_current_once, process_set_current);
1311
1312         if(min==NULL || max==NULL) {
1313                 /* Not sure if w32 allows NULLs here or not */
1314                 return(FALSE);
1315         }
1316         
1317         ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
1318                                 (gpointer *)&process_handle);
1319         if(ok==FALSE) {
1320 #ifdef DEBUG
1321                 g_message ("%s: Can't find process %p", __func__, process);
1322 #endif
1323                 
1324                 return(FALSE);
1325         }
1326
1327         *min=process_handle->min_working_set;
1328         *max=process_handle->max_working_set;
1329         
1330         return(TRUE);
1331 }
1332
1333 gboolean SetProcessWorkingSetSize (gpointer process, size_t min, size_t max)
1334 {
1335         struct _WapiHandle_process *process_handle;
1336         gboolean ok;
1337
1338         mono_once (&process_current_once, process_set_current);
1339
1340         ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
1341                                 (gpointer *)&process_handle);
1342         if(ok==FALSE) {
1343 #ifdef DEBUG
1344                 g_message ("%s: Can't find process %p", __func__, process);
1345 #endif
1346                 
1347                 return(FALSE);
1348         }
1349
1350         process_handle->min_working_set=min;
1351         process_handle->max_working_set=max;
1352         
1353         return(TRUE);
1354 }
1355
1356
1357 gboolean
1358 TerminateProcess (gpointer process, gint32 exitCode)
1359 {
1360         struct _WapiHandle_process *process_handle;
1361         gboolean ok;
1362         int signo;
1363         int ret;
1364
1365         ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
1366                                   (gpointer *) &process_handle);
1367
1368         if (ok == FALSE) {
1369 #ifdef DEBUG
1370                 g_message ("%s: Can't find process %p", __func__, process);
1371 #endif
1372                 SetLastError (ERROR_INVALID_HANDLE);
1373                 return FALSE;
1374         }
1375
1376         signo = (exitCode == -1) ? SIGKILL : SIGTERM;
1377         ret = kill (process_handle->id, signo);
1378         if (ret == -1) {
1379                 switch (errno) {
1380                 case EINVAL:
1381                         SetLastError (ERROR_INVALID_PARAMETER);
1382                         break;
1383                 case EPERM:
1384                         SetLastError (ERROR_ACCESS_DENIED);
1385                         break;
1386                 case ESRCH:
1387                         SetLastError (ERROR_PROC_NOT_FOUND);
1388                         break;
1389                 default:
1390                         SetLastError (ERROR_GEN_FAILURE);
1391                 }
1392         }
1393         
1394         return (ret == 0);
1395 }
1396