Merge pull request #980 from StephenMcConnel/bug-18638
[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-internal.h>
35 #include <mono/metadata/metadata.h>
36 #include <mono/metadata/threadpool.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         MONO_ARCH_SAVE_REGS;
98
99         return isatty (GPOINTER_TO_INT (handle));
100 }
101
102 static MonoBoolean
103 set_property (gint property, gboolean value)
104 {
105         struct termios attr;
106         gboolean callset = FALSE;
107         gboolean check;
108         
109         MONO_ARCH_SAVE_REGS;
110
111         if (tcgetattr (STDIN_FILENO, &attr) == -1)
112                 return FALSE;
113
114         check = (attr.c_lflag & property) != 0;
115         if ((value || check) && !(value && check)) {
116                 callset = TRUE;
117                 if (value)
118                         attr.c_lflag |= property;
119                 else
120                         attr.c_lflag &= ~property;
121         }
122
123         if (!callset)
124                 return TRUE;
125
126         if (tcsetattr (STDIN_FILENO, TCSANOW, &attr) == -1)
127                 return FALSE;
128
129         mono_attr = attr;
130         return TRUE;
131 }
132
133 MonoBoolean
134 ves_icall_System_ConsoleDriver_SetEcho (MonoBoolean want_echo)
135 {
136         
137         return set_property (ECHO, want_echo);
138 }
139
140 MonoBoolean
141 ves_icall_System_ConsoleDriver_SetBreak (MonoBoolean want_break)
142 {
143         return set_property (IGNBRK, !want_break);
144 }
145
146 gint32
147 ves_icall_System_ConsoleDriver_InternalKeyAvailable (gint32 timeout)
148 {
149         fd_set rfds;
150         struct timeval tv;
151         struct timeval *tvptr;
152         div_t divvy;
153         int ret, nbytes;
154
155         MONO_ARCH_SAVE_REGS;
156
157         do {
158                 FD_ZERO (&rfds);
159                 FD_SET (STDIN_FILENO, &rfds);
160                 if (timeout >= 0) {
161                         divvy = div (timeout, 1000);
162                         tv.tv_sec = divvy.quot;
163                         tv.tv_usec = divvy.rem;
164                         tvptr = &tv;
165                 } else {
166                         tvptr = NULL;
167                 }
168                 ret = select (STDIN_FILENO + 1, &rfds, NULL, NULL, tvptr);
169         } while (ret == -1 && errno == EINTR);
170
171         if (ret > 0) {
172                 nbytes = 0;
173                 ret = ioctl (STDIN_FILENO, FIONREAD, &nbytes);
174                 if (ret >= 0)
175                         ret = nbytes;
176         }
177
178         return (ret > 0) ? ret : 0;
179 }
180
181 static gint32 cols_and_lines;
182
183 #ifdef TIOCGWINSZ
184 static int
185 terminal_get_dimensions (void)
186 {
187         struct winsize ws;
188         int ret;
189         int save_errno = errno;
190         
191         if (ioctl (STDIN_FILENO, TIOCGWINSZ, &ws) == 0){
192                 ret = (ws.ws_col << 16) | ws.ws_row;
193                 errno = save_errno;
194                 return ret;
195         } 
196         return -1;
197 }
198 #else
199 static int
200 terminal_get_dimensions (void)
201 {
202         return -1;
203 }
204 #endif
205
206 static void
207 tty_teardown (void)
208 {
209         int unused;
210
211         MONO_ARCH_SAVE_REGS;
212
213         if (!setup_finished)
214                 return;
215
216         if (teardown_str != NULL) {
217                 unused = write (STDOUT_FILENO, teardown_str, strlen (teardown_str));
218                 g_free (teardown_str);
219                 teardown_str = NULL;
220         }
221
222         tcflush (STDIN_FILENO, TCIFLUSH);
223         tcsetattr (STDIN_FILENO, TCSANOW, &initial_attr);
224         set_property (ECHO, TRUE);
225         setup_finished = FALSE;
226 }
227
228 static void
229 do_console_cancel_event (void)
230 {
231         static MonoClassField *cancel_handler_field;
232         MonoDomain *domain = mono_domain_get ();
233         MonoClass *klass;
234         MonoDelegate *load_value;
235         MonoMethod *method;
236         MonoMethodMessage *msg;
237         MonoMethod *im;
238         MonoVTable *vtable;
239
240         /* FIXME: this should likely iterate all the domains, instead */
241         if (!domain->domain)
242                 return;
243
244         klass = mono_class_from_name (mono_defaults.corlib, "System", "Console");
245         if (klass == NULL)
246                 return;
247
248         if (cancel_handler_field == NULL) {
249                 cancel_handler_field = mono_class_get_field_from_name (klass, "cancel_handler");
250                 g_assert (cancel_handler_field);
251         }
252
253         vtable = mono_class_vtable_full (domain, klass, FALSE);
254         if (vtable == NULL)
255                 return;
256         mono_field_static_get_value (vtable, cancel_handler_field, &load_value);
257         if (load_value == NULL)
258                 return;
259
260         klass = load_value->object.vtable->klass;
261         method = mono_class_get_method_from_name (klass, "BeginInvoke", -1);
262         g_assert (method != NULL);
263         im = mono_get_delegate_invoke (method->klass);
264         msg = mono_method_call_message_new (method, NULL, im, NULL, NULL);
265         mono_thread_pool_add ((MonoObject *) load_value, msg, NULL, NULL);
266 }
267
268 static int need_cancel = FALSE;
269 /* this is executed from the finalizer thread */
270 void
271 mono_console_handle_async_ops (void)
272 {
273         if (need_cancel) {
274                 need_cancel = FALSE;
275                 do_console_cancel_event ();
276         }
277 }
278
279 static gboolean in_sigint;
280
281 MONO_SIG_HANDLER_FUNC (static, sigint_handler)
282 {
283         int save_errno;
284         MONO_ARCH_SAVE_REGS;
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;
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         struct sigaction sigcont, sigint, sigwinch;
352
353         memset (&sigcont, 0, sizeof (struct sigaction));
354         memset (&sigint, 0, sizeof (struct sigaction));
355         memset (&sigwinch, 0, sizeof (struct sigaction));
356         
357         // Continuing
358         sigcont.sa_handler = (void *) sigcont_handler;
359         sigcont.sa_flags = 0;
360         sigemptyset (&sigcont.sa_mask);
361         sigaction (SIGCONT, &sigcont, &save_sigcont);
362         
363         // Interrupt handler
364         sigint.sa_handler = (void *) sigint_handler;
365         sigint.sa_flags = 0;
366         sigemptyset (&sigint.sa_mask);
367         sigaction (SIGINT, &sigint, &save_sigint);
368
369         // Window size changed
370         sigwinch.sa_handler = (void *) sigwinch_handler;
371         sigwinch.sa_flags = 0;
372         sigemptyset (&sigwinch.sa_mask);
373         sigaction (SIGWINCH, &sigwinch, &save_sigwinch);
374 }
375
376 #if currently_unuused
377 //
378 // Currently unused, should we ever call the restore handler?
379 // Perhaps before calling into Process.Start?
380 //
381 void
382 console_restore_signal_handlers ()
383 {
384         sigaction (SIGCONT, &save_sigcont, NULL);
385         sigaction (SIGINT, &save_sigint, NULL);
386         sigaction (SIGWINCH, &save_sigwinch, NULL);
387 }
388 #endif
389
390 static void
391 set_control_chars (MonoArray *control_chars, const guchar *cc)
392 {
393         /* The index into the array comes from corlib/System/ControlCharacters.cs */
394 #ifdef VINTR
395         mono_array_set (control_chars, gchar, 0, cc [VINTR]);
396 #endif
397 #ifdef VQUIT
398         mono_array_set (control_chars, gchar, 1, cc [VQUIT]);
399 #endif
400 #ifdef VERASE
401         mono_array_set (control_chars, gchar, 2, cc [VERASE]);
402 #endif
403 #ifdef VKILL
404         mono_array_set (control_chars, gchar, 3, cc [VKILL]);
405 #endif
406 #ifdef VEOF
407         mono_array_set (control_chars, gchar, 4, cc [VEOF]);
408 #endif
409 #ifdef VTIME
410         mono_array_set (control_chars, gchar, 5, cc [VTIME]);
411 #endif
412 #ifdef VMIN
413         mono_array_set (control_chars, gchar, 6, cc [VMIN]);
414 #endif
415 #ifdef VSWTC
416         mono_array_set (control_chars, gchar, 7, cc [VSWTC]);
417 #endif
418 #ifdef VSTART
419         mono_array_set (control_chars, gchar, 8, cc [VSTART]);
420 #endif
421 #ifdef VSTOP
422         mono_array_set (control_chars, gchar, 9, cc [VSTOP]);
423 #endif
424 #ifdef VSUSP
425         mono_array_set (control_chars, gchar, 10, cc [VSUSP]);
426 #endif
427 #ifdef VEOL
428         mono_array_set (control_chars, gchar, 11, cc [VEOL]);
429 #endif
430 #ifdef VREPRINT
431         mono_array_set (control_chars, gchar, 12, cc [VREPRINT]);
432 #endif
433 #ifdef VDISCARD
434         mono_array_set (control_chars, gchar, 13, cc [VDISCARD]);
435 #endif
436 #ifdef VWERASE
437         mono_array_set (control_chars, gchar, 14, cc [VWERASE]);
438 #endif
439 #ifdef VLNEXT
440         mono_array_set (control_chars, gchar, 15, cc [VLNEXT]);
441 #endif
442 #ifdef VEOL2
443         mono_array_set (control_chars, gchar, 16, cc [VEOL2]);
444 #endif
445 }
446
447 MonoBoolean
448 ves_icall_System_ConsoleDriver_TtySetup (MonoString *keypad, MonoString *teardown, MonoArray **control_chars, int **size)
449 {
450         int dims;
451
452         MONO_ARCH_SAVE_REGS;
453
454         dims = terminal_get_dimensions ();
455         if (dims == -1){
456                 int cols = 0, rows = 0;
457                                       
458                 const char *str = g_getenv ("COLUMNS");
459                 if (str != NULL)
460                         cols = atoi (str);
461                 str = g_getenv ("LINES");
462                 if (str != NULL)
463                         rows = atoi (str);
464
465                 if (cols != 0 && rows != 0)
466                         cols_and_lines = (cols << 16) | rows;
467                 else
468                         cols_and_lines = -1;
469         } else {
470                 cols_and_lines = dims;
471         }
472         
473         *size = &cols_and_lines;
474
475         /* 17 is the number of entries set in set_control_chars() above.
476          * NCCS is the total size, but, by now, we only care about those 17 values*/
477         mono_gc_wbarrier_generic_store (control_chars, (MonoObject*) mono_array_new (mono_domain_get (), mono_defaults.byte_class, 17));
478         if (tcgetattr (STDIN_FILENO, &initial_attr) == -1)
479                 return FALSE;
480
481         mono_attr = initial_attr;
482         mono_attr.c_lflag &= ~(ICANON);
483         mono_attr.c_iflag &= ~(IXON|IXOFF);
484         mono_attr.c_cc [VMIN] = 1;
485         mono_attr.c_cc [VTIME] = 0;
486 #ifdef VDSUSP
487         /* Disable C-y being used as a suspend character on OSX */
488         mono_attr.c_cc [VDSUSP] = 255;
489 #endif
490         if (tcsetattr (STDIN_FILENO, TCSANOW, &mono_attr) == -1)
491                 return FALSE;
492
493         set_control_chars (*control_chars, mono_attr.c_cc);
494         /* If initialized from another appdomain... */
495         if (setup_finished)
496                 return TRUE;
497
498         keypad_xmit_str = keypad != NULL ? mono_string_to_utf8 (keypad) : NULL;
499         
500         console_set_signal_handlers ();
501         setup_finished = TRUE;
502         if (!atexit_called) {
503                 if (teardown != NULL)
504                         teardown_str = mono_string_to_utf8 (teardown);
505
506                 mono_atexit (tty_teardown);
507         }
508
509         return TRUE;
510 }
511 #endif /* #if defined(__native_client__) */
512