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