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