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