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