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