Merge branch 'alexischr/nursery-canaries-managed-alloc'
[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  * Licensed under the MIT license. See LICENSE file in the project root for full license information.
9  */
10 #if defined(__native_client__)
11 #include "console-null.c"
12 #else
13
14 #include <config.h>
15 #include <glib.h>
16 #include <stdio.h>
17 #include <string.h>
18 #include <fcntl.h>
19 #include <errno.h>
20 #include <signal.h>
21 #ifdef HAVE_SYS_SELECT_H
22 #    include <sys/select.h>
23 #endif
24 #ifdef HAVE_SYS_TIME_H
25 #    include <sys/time.h>
26 #endif
27 #include <sys/types.h>
28 #ifdef HAVE_UNISTD_H
29 #    include <unistd.h>
30 #endif
31 #include <mono/metadata/appdomain.h>
32 #include <mono/metadata/object-internals.h>
33 #include <mono/metadata/class-internals.h>
34 #include <mono/metadata/domain-internals.h>
35 #include <mono/metadata/gc-internals.h>
36 #include <mono/metadata/metadata.h>
37 #include <mono/metadata/threadpool-ms.h>
38 #include <mono/utils/mono-signal-handler.h>
39 #include <mono/utils/mono-proclib.h>
40
41 /* On solaris, curses.h must come before both termios.h and term.h */
42 #ifdef HAVE_CURSES_H
43 #    include <curses.h>
44 #endif
45 #ifdef HAVE_TERMIOS_H
46 #    include <termios.h>
47 #endif
48 #ifdef HAVE_TERM_H
49 #    include <term.h>
50 #endif
51
52 /* Needed for FIONREAD under solaris */
53 #ifdef HAVE_SYS_FILIO_H
54 #    include <sys/filio.h>
55 #endif
56 #ifdef HAVE_SYS_IOCTL_H
57 #    include <sys/ioctl.h>
58 #endif
59
60 #include <mono/metadata/console-io.h>
61 #include <mono/metadata/exception.h>
62
63 static gboolean setup_finished;
64 static gboolean atexit_called;
65
66 /* The string used to return the terminal to its previous state */
67 static gchar *teardown_str;
68
69 /* The string used to set the terminal into keypad xmit mode after SIGCONT is received */
70 static gchar *keypad_xmit_str;
71
72 #ifdef HAVE_TERMIOS_H
73 /* This is the last state used by Mono, used after a CONT signal is received */
74 static struct termios mono_attr;
75 #endif
76
77 /* static void console_restore_signal_handlers (void); */
78 static void console_set_signal_handlers (void);
79
80 void
81 mono_console_init (void)
82 {
83         int fd;
84
85         /* Make sure the standard file descriptors are opened */
86         fd = open ("/dev/null", O_RDWR);
87         while (fd >= 0 && fd < 3) {
88                 fd = open ("/dev/null", O_RDWR);
89         }
90         close (fd);
91 }
92
93 static struct termios initial_attr;
94
95 MonoBoolean
96 ves_icall_System_ConsoleDriver_Isatty (HANDLE handle)
97 {
98         return isatty (GPOINTER_TO_INT (handle));
99 }
100
101 static MonoBoolean
102 set_property (gint property, gboolean value)
103 {
104         struct termios attr;
105         gboolean callset = FALSE;
106         gboolean check;
107         
108         if (tcgetattr (STDIN_FILENO, &attr) == -1)
109                 return FALSE;
110
111         check = (attr.c_lflag & property) != 0;
112         if ((value || check) && !(value && check)) {
113                 callset = TRUE;
114                 if (value)
115                         attr.c_lflag |= property;
116                 else
117                         attr.c_lflag &= ~property;
118         }
119
120         if (!callset)
121                 return TRUE;
122
123         if (tcsetattr (STDIN_FILENO, TCSANOW, &attr) == -1)
124                 return FALSE;
125
126         mono_attr = attr;
127         return TRUE;
128 }
129
130 MonoBoolean
131 ves_icall_System_ConsoleDriver_SetEcho (MonoBoolean want_echo)
132 {
133         
134         return set_property (ECHO, want_echo);
135 }
136
137 MonoBoolean
138 ves_icall_System_ConsoleDriver_SetBreak (MonoBoolean want_break)
139 {
140         return set_property (IGNBRK, !want_break);
141 }
142
143 gint32
144 ves_icall_System_ConsoleDriver_InternalKeyAvailable (gint32 timeout)
145 {
146         fd_set rfds;
147         struct timeval tv;
148         struct timeval *tvptr;
149         div_t divvy;
150         int ret, nbytes;
151
152         do {
153                 FD_ZERO (&rfds);
154                 FD_SET (STDIN_FILENO, &rfds);
155                 if (timeout >= 0) {
156                         divvy = div (timeout, 1000);
157                         tv.tv_sec = divvy.quot;
158                         tv.tv_usec = divvy.rem;
159                         tvptr = &tv;
160                 } else {
161                         tvptr = NULL;
162                 }
163                 ret = select (STDIN_FILENO + 1, &rfds, NULL, NULL, tvptr);
164         } while (ret == -1 && errno == EINTR);
165
166         if (ret > 0) {
167                 nbytes = 0;
168                 ret = ioctl (STDIN_FILENO, FIONREAD, &nbytes);
169                 if (ret >= 0)
170                         ret = nbytes;
171         }
172
173         return (ret > 0) ? ret : 0;
174 }
175
176 static gint32 cols_and_lines;
177
178 #ifdef TIOCGWINSZ
179 static int
180 terminal_get_dimensions (void)
181 {
182         struct winsize ws;
183         int ret;
184         int save_errno = errno;
185         
186         if (ioctl (STDIN_FILENO, TIOCGWINSZ, &ws) == 0){
187                 ret = (ws.ws_col << 16) | ws.ws_row;
188                 errno = save_errno;
189                 return ret;
190         } 
191         return -1;
192 }
193 #else
194 static int
195 terminal_get_dimensions (void)
196 {
197         return -1;
198 }
199 #endif
200
201 static void
202 tty_teardown (void)
203 {
204         int unused G_GNUC_UNUSED;
205
206         if (!setup_finished)
207                 return;
208
209         if (teardown_str != NULL) {
210                 unused = write (STDOUT_FILENO, teardown_str, strlen (teardown_str));
211                 g_free (teardown_str);
212                 teardown_str = NULL;
213         }
214
215         tcflush (STDIN_FILENO, TCIFLUSH);
216         tcsetattr (STDIN_FILENO, TCSANOW, &initial_attr);
217         set_property (ECHO, TRUE);
218         setup_finished = FALSE;
219 }
220
221 static void
222 do_console_cancel_event (void)
223 {
224         static MonoClassField *cancel_handler_field;
225         MonoError error;
226         MonoDomain *domain = mono_domain_get ();
227         MonoClass *klass;
228         MonoDelegate *load_value;
229         MonoMethod *method;
230         MonoVTable *vtable;
231
232         /* FIXME: this should likely iterate all the domains, instead */
233         if (!domain->domain)
234                 return;
235
236         klass = mono_class_try_load_from_name (mono_defaults.corlib, "System", "Console");
237         if (klass == NULL)
238                 return;
239
240         if (cancel_handler_field == NULL) {
241                 cancel_handler_field = mono_class_get_field_from_name (klass, "cancel_handler");
242                 g_assert (cancel_handler_field);
243         }
244
245         vtable = mono_class_vtable_full (domain, klass, &error);
246         if (vtable == NULL || !is_ok (&error)) {
247                 mono_error_cleanup (&error);
248                 return;
249         }
250         mono_field_static_get_value_checked (vtable, cancel_handler_field, &load_value, &error);
251         if (load_value == NULL || !is_ok (&error)) {
252                 mono_error_cleanup (&error);
253                 return;
254         }
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
260         mono_threadpool_ms_begin_invoke (domain, (MonoObject*) load_value, method, NULL, &error);
261         if (!is_ok (&error)) {
262                 g_warning ("Couldn't invoke System.Console cancel handler due to %s", mono_error_get_message (&error));
263                 mono_error_cleanup (&error);
264         }
265 }
266
267 static int need_cancel = FALSE;
268 /* this is executed from the finalizer thread */
269 void
270 mono_console_handle_async_ops (void)
271 {
272         if (need_cancel) {
273                 need_cancel = FALSE;
274                 do_console_cancel_event ();
275         }
276 }
277
278 static gboolean in_sigint;
279
280 MONO_SIG_HANDLER_FUNC (static, sigint_handler)
281 {
282         int save_errno;
283
284         if (in_sigint)
285                 return;
286
287         in_sigint = TRUE;
288         save_errno = errno;
289         need_cancel = TRUE;
290         mono_gc_finalize_notify ();
291         errno = save_errno;
292         in_sigint = FALSE;
293 }
294
295 static struct sigaction save_sigcont, save_sigint, save_sigwinch;
296
297 MONO_SIG_HANDLER_FUNC (static, sigcont_handler)
298 {
299         int unused G_GNUC_UNUSED;
300         // Ignore error, there is not much we can do in the sigcont handler.
301         tcsetattr (STDIN_FILENO, TCSANOW, &mono_attr);
302
303         if (keypad_xmit_str != NULL)
304                 unused = write (STDOUT_FILENO, keypad_xmit_str, strlen (keypad_xmit_str));
305
306         // Call previous handler
307         if (save_sigcont.sa_sigaction != NULL &&
308             save_sigcont.sa_sigaction != (void *)SIG_DFL &&
309             save_sigcont.sa_sigaction != (void *)SIG_IGN)
310                 (*save_sigcont.sa_sigaction) (MONO_SIG_HANDLER_PARAMS);
311 }
312
313 MONO_SIG_HANDLER_FUNC (static, sigwinch_handler)
314 {
315         int dims = terminal_get_dimensions ();
316         if (dims != -1)
317                 cols_and_lines = dims;
318         
319         // Call previous handler
320         if (save_sigwinch.sa_sigaction != NULL &&
321             save_sigwinch.sa_sigaction != (void *)SIG_DFL &&
322             save_sigwinch.sa_sigaction != (void *)SIG_IGN)
323                 (*save_sigwinch.sa_sigaction) (MONO_SIG_HANDLER_PARAMS);
324 }
325
326 /*
327  * console_set_signal_handlers:
328  *
329  * Installs various signals handlers for the use of the console, as
330  * follows:
331  *
332  * SIGCONT: this is received after the application has resumed execution
333  * if it was suspended with Control-Z before.   This signal handler needs
334  * to resend the terminal sequence to send keyboard in keypad mode (this
335  * is the difference between getting a cuu1 code or a kcuu1 code for up-arrow
336  * for example
337  *
338  * SIGINT: invokes the System.Console.DoConsoleCancelEvent method using
339  * a thread from the thread pool which notifies all registered cancel_event
340  * listeners.
341  *
342  * SIGWINCH: is used to track changes to the console window when a GUI
343  * terminal is resized.    It sets an internal variable that is checked
344  * by System.Console when the Terminfo driver has been activated.
345  */
346 static void
347 console_set_signal_handlers ()
348 {
349 #if defined(HAVE_SIGACTION)
350         struct sigaction sigcont, sigint, sigwinch;
351
352         memset (&sigcont, 0, sizeof (struct sigaction));
353         memset (&sigint, 0, sizeof (struct sigaction));
354         memset (&sigwinch, 0, sizeof (struct sigaction));
355         
356         // Continuing
357         sigcont.sa_handler = (void (*)(int)) sigcont_handler;
358         sigcont.sa_flags = SA_RESTART;
359         sigemptyset (&sigcont.sa_mask);
360         sigaction (SIGCONT, &sigcont, &save_sigcont);
361         
362         // Interrupt handler
363         sigint.sa_handler = (void (*)(int)) sigint_handler;
364         sigint.sa_flags = SA_RESTART;
365         sigemptyset (&sigint.sa_mask);
366         sigaction (SIGINT, &sigint, &save_sigint);
367
368         // Window size changed
369         sigwinch.sa_handler = (void (*)(int)) sigwinch_handler;
370         sigwinch.sa_flags = SA_RESTART;
371         sigemptyset (&sigwinch.sa_mask);
372         sigaction (SIGWINCH, &sigwinch, &save_sigwinch);
373 #endif
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         MonoError error;
451
452         int dims;
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         MonoArray *control_chars_arr = mono_array_new_checked (mono_domain_get (), mono_defaults.byte_class, 17, &error);
478         if (mono_error_set_pending_exception (&error))
479                 return FALSE;
480         mono_gc_wbarrier_generic_store (control_chars, (MonoObject*) control_chars_arr);
481         if (tcgetattr (STDIN_FILENO, &initial_attr) == -1)
482                 return FALSE;
483
484         mono_attr = initial_attr;
485         mono_attr.c_lflag &= ~(ICANON);
486         mono_attr.c_iflag &= ~(IXON|IXOFF);
487         mono_attr.c_cc [VMIN] = 1;
488         mono_attr.c_cc [VTIME] = 0;
489 #ifdef VDSUSP
490         /* Disable C-y being used as a suspend character on OSX */
491         mono_attr.c_cc [VDSUSP] = 255;
492 #endif
493         if (tcsetattr (STDIN_FILENO, TCSANOW, &mono_attr) == -1)
494                 return FALSE;
495
496         set_control_chars (*control_chars, mono_attr.c_cc);
497         /* If initialized from another appdomain... */
498         if (setup_finished)
499                 return TRUE;
500
501         keypad_xmit_str = NULL;
502         if (keypad != NULL) {
503                 keypad_xmit_str = mono_string_to_utf8_checked (keypad, &error);
504                 if (mono_error_set_pending_exception (&error))
505                         return FALSE;
506         }
507         
508         console_set_signal_handlers ();
509         setup_finished = TRUE;
510         if (!atexit_called) {
511                 if (teardown != NULL) {
512                         teardown_str = mono_string_to_utf8_checked (teardown, &error);
513                         if (mono_error_set_pending_exception (&error))
514                                 return FALSE;
515                 }
516
517                 mono_atexit (tty_teardown);
518         }
519
520         return TRUE;
521 }
522 #endif /* #if defined(__native_client__) */
523