Merge pull request #4621 from alexanderkyte/strdup_env
[mono.git] / mono / metadata / console-unix.c
1 /**
2  * \file
3  * ConsoleDriver internal calls for Unix systems.
4  *
5  * Author:
6  *      Gonzalo Paniagua Javier (gonzalo@ximian.com)
7  *
8  * Copyright (C) 2005-2009 Novell, Inc. (http://www.novell.com)
9  * Licensed under the MIT license. See LICENSE file in the project root for full license information.
10  */
11 #if defined(__native_client__)
12 #include "console-null.c"
13 #else
14
15 #include <config.h>
16 #include <glib.h>
17 #include <stdio.h>
18 #include <string.h>
19 #include <fcntl.h>
20 #include <errno.h>
21 #include <signal.h>
22 #ifdef HAVE_SYS_SELECT_H
23 #    include <sys/select.h>
24 #endif
25 #ifdef HAVE_SYS_TIME_H
26 #    include <sys/time.h>
27 #endif
28 #include <sys/types.h>
29 #ifdef HAVE_UNISTD_H
30 #    include <unistd.h>
31 #endif
32 #include <mono/metadata/appdomain.h>
33 #include <mono/metadata/object-internals.h>
34 #include <mono/metadata/class-internals.h>
35 #include <mono/metadata/domain-internals.h>
36 #include <mono/metadata/gc-internals.h>
37 #include <mono/metadata/metadata.h>
38 #include <mono/metadata/threadpool.h>
39 #include <mono/utils/mono-signal-handler.h>
40 #include <mono/utils/mono-proclib.h>
41 #include <mono/utils/w32api.h>
42
43 /* On solaris, curses.h must come before both termios.h and term.h */
44 #ifdef HAVE_CURSES_H
45 #    include <curses.h>
46 #endif
47 #ifdef HAVE_TERMIOS_H
48 #    include <termios.h>
49 #endif
50 #ifdef HAVE_TERM_H
51 #    include <term.h>
52 #endif
53
54 /* Needed for FIONREAD under solaris */
55 #ifdef HAVE_SYS_FILIO_H
56 #    include <sys/filio.h>
57 #endif
58 #ifdef HAVE_SYS_IOCTL_H
59 #    include <sys/ioctl.h>
60 #endif
61
62 #include <mono/metadata/console-io.h>
63 #include <mono/metadata/exception.h>
64
65 static gboolean setup_finished;
66 static gboolean atexit_called;
67
68 /* The string used to return the terminal to its previous state */
69 static gchar *teardown_str;
70
71 /* The string used to set the terminal into keypad xmit mode after SIGCONT is received */
72 static gchar *keypad_xmit_str;
73
74 #ifdef HAVE_TERMIOS_H
75 /* This is the last state used by Mono, used after a CONT signal is received */
76 static struct termios mono_attr;
77 #endif
78
79 /* static void console_restore_signal_handlers (void); */
80 static void console_set_signal_handlers (void);
81
82 void
83 mono_console_init (void)
84 {
85         int fd;
86
87         /* Make sure the standard file descriptors are opened */
88         fd = open ("/dev/null", O_RDWR);
89         while (fd >= 0 && fd < 3) {
90                 fd = open ("/dev/null", O_RDWR);
91         }
92         close (fd);
93 }
94
95 static struct termios initial_attr;
96
97 MonoBoolean
98 ves_icall_System_ConsoleDriver_Isatty (HANDLE handle)
99 {
100         return isatty (GPOINTER_TO_INT (handle));
101 }
102
103 static MonoBoolean
104 set_property (gint property, gboolean value)
105 {
106         struct termios attr;
107         gboolean callset = FALSE;
108         gboolean check;
109         
110         if (tcgetattr (STDIN_FILENO, &attr) == -1)
111                 return FALSE;
112
113         check = (attr.c_lflag & property) != 0;
114         if ((value || check) && !(value && check)) {
115                 callset = TRUE;
116                 if (value)
117                         attr.c_lflag |= property;
118                 else
119                         attr.c_lflag &= ~property;
120         }
121
122         if (!callset)
123                 return TRUE;
124
125         if (tcsetattr (STDIN_FILENO, TCSANOW, &attr) == -1)
126                 return FALSE;
127
128         mono_attr = attr;
129         return TRUE;
130 }
131
132 MonoBoolean
133 ves_icall_System_ConsoleDriver_SetEcho (MonoBoolean want_echo)
134 {
135         
136         return set_property (ECHO, want_echo);
137 }
138
139 MonoBoolean
140 ves_icall_System_ConsoleDriver_SetBreak (MonoBoolean want_break)
141 {
142         return set_property (IGNBRK, !want_break);
143 }
144
145 gint32
146 ves_icall_System_ConsoleDriver_InternalKeyAvailable (gint32 timeout)
147 {
148         fd_set rfds;
149         struct timeval tv;
150         struct timeval *tvptr;
151         div_t divvy;
152         int ret, nbytes;
153
154         do {
155                 FD_ZERO (&rfds);
156                 FD_SET (STDIN_FILENO, &rfds);
157                 if (timeout >= 0) {
158                         divvy = div (timeout, 1000);
159                         tv.tv_sec = divvy.quot;
160                         tv.tv_usec = divvy.rem;
161                         tvptr = &tv;
162                 } else {
163                         tvptr = NULL;
164                 }
165                 ret = select (STDIN_FILENO + 1, &rfds, NULL, NULL, tvptr);
166         } while (ret == -1 && errno == EINTR);
167
168         if (ret > 0) {
169                 nbytes = 0;
170                 ret = ioctl (STDIN_FILENO, FIONREAD, &nbytes);
171                 if (ret >= 0)
172                         ret = nbytes;
173         }
174
175         return (ret > 0) ? ret : 0;
176 }
177
178 static gint32 cols_and_lines;
179
180 #ifdef TIOCGWINSZ
181 static int
182 terminal_get_dimensions (void)
183 {
184         struct winsize ws;
185         int ret;
186         int save_errno = errno;
187         
188         if (ioctl (STDIN_FILENO, TIOCGWINSZ, &ws) == 0){
189                 ret = (ws.ws_col << 16) | ws.ws_row;
190                 errno = save_errno;
191                 return ret;
192         } 
193         return -1;
194 }
195 #else
196 static int
197 terminal_get_dimensions (void)
198 {
199         return -1;
200 }
201 #endif
202
203 static void
204 tty_teardown (void)
205 {
206         int unused G_GNUC_UNUSED;
207
208         if (!setup_finished)
209                 return;
210
211         if (teardown_str != NULL) {
212                 unused = write (STDOUT_FILENO, teardown_str, strlen (teardown_str));
213                 g_free (teardown_str);
214                 teardown_str = NULL;
215         }
216
217         tcflush (STDIN_FILENO, TCIFLUSH);
218         tcsetattr (STDIN_FILENO, TCSANOW, &initial_attr);
219         set_property (ECHO, TRUE);
220         setup_finished = FALSE;
221 }
222
223 static void
224 do_console_cancel_event (void)
225 {
226         static MonoClassField *cancel_handler_field;
227         MonoError error;
228         MonoDomain *domain = mono_domain_get ();
229         MonoClass *klass;
230         MonoDelegate *load_value;
231         MonoMethod *method;
232         MonoVTable *vtable;
233
234         /* FIXME: this should likely iterate all the domains, instead */
235         if (!domain->domain)
236                 return;
237
238         klass = mono_class_try_load_from_name (mono_defaults.corlib, "System", "Console");
239         if (klass == NULL)
240                 return;
241
242         if (cancel_handler_field == NULL) {
243                 cancel_handler_field = mono_class_get_field_from_name (klass, "cancel_handler");
244                 g_assert (cancel_handler_field);
245         }
246
247         vtable = mono_class_vtable_full (domain, klass, &error);
248         if (vtable == NULL || !is_ok (&error)) {
249                 mono_error_cleanup (&error);
250                 return;
251         }
252         mono_field_static_get_value_checked (vtable, cancel_handler_field, &load_value, &error);
253         if (load_value == NULL || !is_ok (&error)) {
254                 mono_error_cleanup (&error);
255                 return;
256         }
257
258         klass = load_value->object.vtable->klass;
259         method = mono_class_get_method_from_name (klass, "BeginInvoke", -1);
260         g_assert (method != NULL);
261
262         mono_threadpool_begin_invoke (domain, (MonoObject*) load_value, method, NULL, &error);
263         if (!is_ok (&error)) {
264                 g_warning ("Couldn't invoke System.Console cancel handler due to %s", mono_error_get_message (&error));
265                 mono_error_cleanup (&error);
266         }
267 }
268
269 static int need_cancel = FALSE;
270 /* this is executed from the finalizer thread */
271 void
272 mono_console_handle_async_ops (void)
273 {
274         if (need_cancel) {
275                 need_cancel = FALSE;
276                 do_console_cancel_event ();
277         }
278 }
279
280 static gboolean in_sigint;
281
282 MONO_SIG_HANDLER_FUNC (static, sigint_handler)
283 {
284         int save_errno;
285
286         if (in_sigint)
287                 return;
288
289         in_sigint = TRUE;
290         save_errno = errno;
291         need_cancel = TRUE;
292         mono_gc_finalize_notify ();
293         errno = save_errno;
294         in_sigint = FALSE;
295 }
296
297 static struct sigaction save_sigcont, save_sigint, save_sigwinch;
298
299 MONO_SIG_HANDLER_FUNC (static, sigcont_handler)
300 {
301         int unused G_GNUC_UNUSED;
302         // Ignore error, there is not much we can do in the sigcont handler.
303         tcsetattr (STDIN_FILENO, TCSANOW, &mono_attr);
304
305         if (keypad_xmit_str != NULL)
306                 unused = write (STDOUT_FILENO, keypad_xmit_str, strlen (keypad_xmit_str));
307
308         // Call previous handler
309         if (save_sigcont.sa_sigaction != NULL &&
310             save_sigcont.sa_sigaction != (void *)SIG_DFL &&
311             save_sigcont.sa_sigaction != (void *)SIG_IGN)
312                 (*save_sigcont.sa_sigaction) (MONO_SIG_HANDLER_PARAMS);
313 }
314
315 MONO_SIG_HANDLER_FUNC (static, sigwinch_handler)
316 {
317         int dims = terminal_get_dimensions ();
318         if (dims != -1)
319                 cols_and_lines = dims;
320         
321         // Call previous handler
322         if (save_sigwinch.sa_sigaction != NULL &&
323             save_sigwinch.sa_sigaction != (void *)SIG_DFL &&
324             save_sigwinch.sa_sigaction != (void *)SIG_IGN)
325                 (*save_sigwinch.sa_sigaction) (MONO_SIG_HANDLER_PARAMS);
326 }
327
328 /*
329  * console_set_signal_handlers:
330  *
331  * Installs various signals handlers for the use of the console, as
332  * follows:
333  *
334  * SIGCONT: this is received after the application has resumed execution
335  * if it was suspended with Control-Z before.   This signal handler needs
336  * to resend the terminal sequence to send keyboard in keypad mode (this
337  * is the difference between getting a cuu1 code or a kcuu1 code for up-arrow
338  * for example
339  *
340  * SIGINT: invokes the System.Console.DoConsoleCancelEvent method using
341  * a thread from the thread pool which notifies all registered cancel_event
342  * listeners.
343  *
344  * SIGWINCH: is used to track changes to the console window when a GUI
345  * terminal is resized.    It sets an internal variable that is checked
346  * by System.Console when the Terminfo driver has been activated.
347  */
348 static void
349 console_set_signal_handlers ()
350 {
351 #if defined(HAVE_SIGACTION)
352         struct sigaction sigcont, sigint, sigwinch;
353
354         memset (&sigcont, 0, sizeof (struct sigaction));
355         memset (&sigint, 0, sizeof (struct sigaction));
356         memset (&sigwinch, 0, sizeof (struct sigaction));
357         
358         // Continuing
359         sigcont.sa_handler = (void (*)(int)) sigcont_handler;
360         sigcont.sa_flags = SA_RESTART;
361         sigemptyset (&sigcont.sa_mask);
362         sigaction (SIGCONT, &sigcont, &save_sigcont);
363         
364         // Interrupt handler
365         sigint.sa_handler = (void (*)(int)) sigint_handler;
366         sigint.sa_flags = SA_RESTART;
367         sigemptyset (&sigint.sa_mask);
368         sigaction (SIGINT, &sigint, &save_sigint);
369
370         // Window size changed
371         sigwinch.sa_handler = (void (*)(int)) sigwinch_handler;
372         sigwinch.sa_flags = SA_RESTART;
373         sigemptyset (&sigwinch.sa_mask);
374         sigaction (SIGWINCH, &sigwinch, &save_sigwinch);
375 #endif
376 }
377
378 #if currently_unuused
379 //
380 // Currently unused, should we ever call the restore handler?
381 // Perhaps before calling into Process.Start?
382 //
383 void
384 console_restore_signal_handlers ()
385 {
386         sigaction (SIGCONT, &save_sigcont, NULL);
387         sigaction (SIGINT, &save_sigint, NULL);
388         sigaction (SIGWINCH, &save_sigwinch, NULL);
389 }
390 #endif
391
392 static void
393 set_control_chars (MonoArray *control_chars, const guchar *cc)
394 {
395         /* The index into the array comes from corlib/System/ControlCharacters.cs */
396 #ifdef VINTR
397         mono_array_set (control_chars, gchar, 0, cc [VINTR]);
398 #endif
399 #ifdef VQUIT
400         mono_array_set (control_chars, gchar, 1, cc [VQUIT]);
401 #endif
402 #ifdef VERASE
403         mono_array_set (control_chars, gchar, 2, cc [VERASE]);
404 #endif
405 #ifdef VKILL
406         mono_array_set (control_chars, gchar, 3, cc [VKILL]);
407 #endif
408 #ifdef VEOF
409         mono_array_set (control_chars, gchar, 4, cc [VEOF]);
410 #endif
411 #ifdef VTIME
412         mono_array_set (control_chars, gchar, 5, cc [VTIME]);
413 #endif
414 #ifdef VMIN
415         mono_array_set (control_chars, gchar, 6, cc [VMIN]);
416 #endif
417 #ifdef VSWTC
418         mono_array_set (control_chars, gchar, 7, cc [VSWTC]);
419 #endif
420 #ifdef VSTART
421         mono_array_set (control_chars, gchar, 8, cc [VSTART]);
422 #endif
423 #ifdef VSTOP
424         mono_array_set (control_chars, gchar, 9, cc [VSTOP]);
425 #endif
426 #ifdef VSUSP
427         mono_array_set (control_chars, gchar, 10, cc [VSUSP]);
428 #endif
429 #ifdef VEOL
430         mono_array_set (control_chars, gchar, 11, cc [VEOL]);
431 #endif
432 #ifdef VREPRINT
433         mono_array_set (control_chars, gchar, 12, cc [VREPRINT]);
434 #endif
435 #ifdef VDISCARD
436         mono_array_set (control_chars, gchar, 13, cc [VDISCARD]);
437 #endif
438 #ifdef VWERASE
439         mono_array_set (control_chars, gchar, 14, cc [VWERASE]);
440 #endif
441 #ifdef VLNEXT
442         mono_array_set (control_chars, gchar, 15, cc [VLNEXT]);
443 #endif
444 #ifdef VEOL2
445         mono_array_set (control_chars, gchar, 16, cc [VEOL2]);
446 #endif
447 }
448
449 MonoBoolean
450 ves_icall_System_ConsoleDriver_TtySetup (MonoString *keypad, MonoString *teardown, MonoArray **control_chars, int **size)
451 {
452         MonoError error;
453
454         int dims;
455
456         dims = terminal_get_dimensions ();
457         if (dims == -1){
458                 int cols = 0, rows = 0;
459                                       
460                 char *str = g_getenv ("COLUMNS");
461                 if (str != NULL) {
462                         cols = atoi (str);
463                         g_free (str);
464                 }
465                 str = g_getenv ("LINES");
466                 if (str != NULL) {
467                         rows = atoi (str);
468                         g_free (str);
469                 }
470
471                 if (cols != 0 && rows != 0)
472                         cols_and_lines = (cols << 16) | rows;
473                 else
474                         cols_and_lines = -1;
475         } else {
476                 cols_and_lines = dims;
477         }
478         
479         *size = &cols_and_lines;
480
481         /* 17 is the number of entries set in set_control_chars() above.
482          * NCCS is the total size, but, by now, we only care about those 17 values*/
483         MonoArray *control_chars_arr = mono_array_new_checked (mono_domain_get (), mono_defaults.byte_class, 17, &error);
484         if (mono_error_set_pending_exception (&error))
485                 return FALSE;
486         mono_gc_wbarrier_generic_store (control_chars, (MonoObject*) control_chars_arr);
487         if (tcgetattr (STDIN_FILENO, &initial_attr) == -1)
488                 return FALSE;
489
490         mono_attr = initial_attr;
491         mono_attr.c_lflag &= ~(ICANON);
492         mono_attr.c_iflag &= ~(IXON|IXOFF);
493         mono_attr.c_cc [VMIN] = 1;
494         mono_attr.c_cc [VTIME] = 0;
495 #ifdef VDSUSP
496         /* Disable C-y being used as a suspend character on OSX */
497         mono_attr.c_cc [VDSUSP] = 255;
498 #endif
499         if (tcsetattr (STDIN_FILENO, TCSANOW, &mono_attr) == -1)
500                 return FALSE;
501
502         set_control_chars (*control_chars, mono_attr.c_cc);
503         /* If initialized from another appdomain... */
504         if (setup_finished)
505                 return TRUE;
506
507         keypad_xmit_str = NULL;
508         if (keypad != NULL) {
509                 keypad_xmit_str = mono_string_to_utf8_checked (keypad, &error);
510                 if (mono_error_set_pending_exception (&error))
511                         return FALSE;
512         }
513         
514         console_set_signal_handlers ();
515         setup_finished = TRUE;
516         if (!atexit_called) {
517                 if (teardown != NULL) {
518                         teardown_str = mono_string_to_utf8_checked (teardown, &error);
519                         if (mono_error_set_pending_exception (&error))
520                                 return FALSE;
521                 }
522
523                 mono_atexit (tty_teardown);
524         }
525
526         return TRUE;
527 }
528 #endif /* #if defined(__native_client__) */
529