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