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