Update PointConverter.cs
[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 #if defined(__native_client__)
10 #include "console-null.c"
11 #else
12
13 #include <config.h>
14 #include <glib.h>
15 #include <stdio.h>
16 #include <string.h>
17 #include <fcntl.h>
18 #include <errno.h>
19 #include <signal.h>
20 #ifdef HAVE_SYS_TIME_H
21 #    include <sys/time.h>
22 #endif
23 #include <sys/types.h>
24 #ifdef HAVE_UNISTD_H
25 #    include <unistd.h>
26 #endif
27 #include <mono/metadata/appdomain.h>
28 #include <mono/metadata/object-internals.h>
29 #include <mono/metadata/class-internals.h>
30 #include <mono/metadata/domain-internals.h>
31 #include <mono/metadata/gc-internal.h>
32 #include <mono/metadata/metadata.h>
33 #include <mono/metadata/threadpool.h>
34
35 /* On solaris, curses.h must come before both termios.h and term.h */
36 #ifdef HAVE_CURSES_H
37 #    include <curses.h>
38 #endif
39 #ifdef HAVE_TERMIOS_H
40 #    include <termios.h>
41 #endif
42 #ifdef HAVE_TERM_H
43 #    include <term.h>
44 #endif
45
46 /* Needed for FIONREAD under solaris */
47 #ifdef HAVE_SYS_FILIO_H
48 #    include <sys/filio.h>
49 #endif
50 #ifdef HAVE_SYS_IOCTL_H
51 #    include <sys/ioctl.h>
52 #endif
53
54 #include <mono/metadata/console-io.h>
55 #include <mono/metadata/exception.h>
56
57 static gboolean setup_finished;
58 static gboolean atexit_called;
59
60 /* The string used to return the terminal to its previous state */
61 static gchar *teardown_str;
62
63 /* The string used to set the terminal into keypad xmit mode after SIGCONT is received */
64 static gchar *keypad_xmit_str;
65
66 #ifdef HAVE_TERMIOS_H
67 /* This is the last state used by Mono, used after a CONT signal is received */
68 static struct termios mono_attr;
69 #endif
70
71 /* static void console_restore_signal_handlers (void); */
72 static void console_set_signal_handlers (void);
73
74 void
75 mono_console_init (void)
76 {
77         int fd;
78
79         /* Make sure the standard file descriptors are opened */
80         fd = open ("/dev/null", O_RDWR);
81         while (fd >= 0 && fd < 3) {
82                 fd = open ("/dev/null", O_RDWR);
83         }
84         close (fd);
85 }
86
87 static struct termios initial_attr;
88
89 MonoBoolean
90 ves_icall_System_ConsoleDriver_Isatty (HANDLE handle)
91 {
92         MONO_ARCH_SAVE_REGS;
93
94         return isatty (GPOINTER_TO_INT (handle));
95 }
96
97 static MonoBoolean
98 set_property (gint property, gboolean value)
99 {
100         struct termios attr;
101         gboolean callset = FALSE;
102         gboolean check;
103         
104         MONO_ARCH_SAVE_REGS;
105
106         if (tcgetattr (STDIN_FILENO, &attr) == -1)
107                 return FALSE;
108
109         check = (attr.c_lflag & property) != 0;
110         if ((value || check) && !(value && check)) {
111                 callset = TRUE;
112                 if (value)
113                         attr.c_lflag |= property;
114                 else
115                         attr.c_lflag &= ~property;
116         }
117
118         if (!callset)
119                 return TRUE;
120
121         if (tcsetattr (STDIN_FILENO, TCSANOW, &attr) == -1)
122                 return FALSE;
123
124         mono_attr = attr;
125         return TRUE;
126 }
127
128 MonoBoolean
129 ves_icall_System_ConsoleDriver_SetEcho (MonoBoolean want_echo)
130 {
131         
132         return set_property (ECHO, want_echo);
133 }
134
135 MonoBoolean
136 ves_icall_System_ConsoleDriver_SetBreak (MonoBoolean want_break)
137 {
138         return set_property (IGNBRK, !want_break);
139 }
140
141 gint32
142 ves_icall_System_ConsoleDriver_InternalKeyAvailable (gint32 timeout)
143 {
144         fd_set rfds;
145         struct timeval tv;
146         struct timeval *tvptr;
147         div_t divvy;
148         int ret, nbytes;
149
150         MONO_ARCH_SAVE_REGS;
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;
205
206         MONO_ARCH_SAVE_REGS;
207
208         if (!setup_finished)
209                 return;
210
211         if (teardown_str != NULL) {
212                 unused = write (STDOUT_FILENO, teardown_str, strlen (teardown_str));
213                 g_free (teardown_str);
214                 teardown_str = NULL;
215         }
216
217         tcflush (STDIN_FILENO, TCIFLUSH);
218         tcsetattr (STDIN_FILENO, TCSANOW, &initial_attr);
219         set_property (ECHO, TRUE);
220         setup_finished = FALSE;
221 }
222
223 static void
224 do_console_cancel_event (void)
225 {
226         static MonoClassField *cancel_handler_field;
227         MonoDomain *domain = mono_domain_get ();
228         MonoClass *klass;
229         MonoDelegate *load_value;
230         MonoMethod *method;
231         MonoMethodMessage *msg;
232         MonoMethod *im;
233         MonoVTable *vtable;
234
235         /* FIXME: this should likely iterate all the domains, instead */
236         if (!domain->domain)
237                 return;
238
239         klass = mono_class_from_name (mono_defaults.corlib, "System", "Console");
240         if (klass == NULL)
241                 return;
242
243         if (cancel_handler_field == NULL) {
244                 cancel_handler_field = mono_class_get_field_from_name (klass, "cancel_handler");
245                 g_assert (cancel_handler_field);
246         }
247
248         vtable = mono_class_vtable_full (domain, klass, FALSE);
249         if (vtable == NULL)
250                 return;
251         mono_field_static_get_value (vtable, cancel_handler_field, &load_value);
252         if (load_value == NULL)
253                 return;
254
255         klass = load_value->object.vtable->klass;
256         method = mono_class_get_method_from_name (klass, "BeginInvoke", -1);
257         g_assert (method != NULL);
258         im = mono_get_delegate_invoke (method->klass);
259         msg = mono_method_call_message_new (method, NULL, im, NULL, NULL);
260         mono_thread_pool_add ((MonoObject *) load_value, msg, NULL, NULL);
261 }
262
263 static int need_cancel = FALSE;
264 /* this is executed from the finalizer thread */
265 void
266 mono_console_handle_async_ops (void)
267 {
268         if (need_cancel) {
269                 need_cancel = FALSE;
270                 do_console_cancel_event ();
271         }
272 }
273
274 static gboolean in_sigint;
275 static void
276 sigint_handler (int signo)
277 {
278         int save_errno;
279         MONO_ARCH_SAVE_REGS;
280
281         if (in_sigint)
282                 return;
283
284         in_sigint = TRUE;
285         save_errno = errno;
286         need_cancel = TRUE;
287         mono_gc_finalize_notify ();
288         errno = save_errno;
289         in_sigint = FALSE;
290 }
291
292 static struct sigaction save_sigcont, save_sigint, save_sigwinch;
293
294 static void
295 sigcont_handler (int signo, void *the_siginfo, void *data)
296 {
297         int unused;
298         // Ignore error, there is not much we can do in the sigcont handler.
299         tcsetattr (STDIN_FILENO, TCSANOW, &mono_attr);
300
301         if (keypad_xmit_str != NULL)
302                 unused = write (STDOUT_FILENO, keypad_xmit_str, strlen (keypad_xmit_str));
303
304         // Call previous handler
305         if (save_sigcont.sa_sigaction != NULL &&
306             save_sigcont.sa_sigaction != (void *)SIG_DFL &&
307             save_sigcont.sa_sigaction != (void *)SIG_IGN)
308                 (*save_sigcont.sa_sigaction) (signo, the_siginfo, data);
309 }
310
311 static void
312 sigwinch_handler (int signo, void *the_siginfo, void *data)
313 {
314         int dims = terminal_get_dimensions ();
315         if (dims != -1)
316                 cols_and_lines = dims;
317         
318         // Call previous handler
319         if (save_sigwinch.sa_sigaction != NULL &&
320             save_sigwinch.sa_sigaction != (void *)SIG_DFL &&
321             save_sigwinch.sa_sigaction != (void *)SIG_IGN)
322                 (*save_sigwinch.sa_sigaction) (signo, the_siginfo, data);
323 }
324
325 /*
326  * console_set_signal_handlers:
327  *
328  * Installs various signals handlers for the use of the console, as
329  * follows:
330  *
331  * SIGCONT: this is received after the application has resumed execution
332  * if it was suspended with Control-Z before.   This signal handler needs
333  * to resend the terminal sequence to send keyboard in keypad mode (this
334  * is the difference between getting a cuu1 code or a kcuu1 code for up-arrow
335  * for example
336  *
337  * SIGINT: invokes the System.Console.DoConsoleCancelEvent method using
338  * a thread from the thread pool which notifies all registered cancel_event
339  * listeners.
340  *
341  * SIGWINCH: is used to track changes to the console window when a GUI
342  * terminal is resized.    It sets an internal variable that is checked
343  * by System.Console when the Terminfo driver has been activated.
344  */
345 static void
346 console_set_signal_handlers ()
347 {
348         struct sigaction sigcont, sigint, sigwinch;
349
350         memset (&sigcont, 0, sizeof (struct sigaction));
351         memset (&sigint, 0, sizeof (struct sigaction));
352         memset (&sigwinch, 0, sizeof (struct sigaction));
353         
354         // Continuing
355         sigcont.sa_handler = (void *) sigcont_handler;
356         sigcont.sa_flags = 0;
357         sigemptyset (&sigcont.sa_mask);
358         sigaction (SIGCONT, &sigcont, &save_sigcont);
359         
360         // Interrupt handler
361         sigint.sa_handler = sigint_handler;
362         sigint.sa_flags = 0;
363         sigemptyset (&sigint.sa_mask);
364         sigaction (SIGINT, &sigint, &save_sigint);
365
366         // Window size changed
367         sigwinch.sa_handler = (void *) sigwinch_handler;
368         sigwinch.sa_flags = 0;
369         sigemptyset (&sigwinch.sa_mask);
370         sigaction (SIGWINCH, &sigwinch, &save_sigwinch);
371 }
372
373 #if currently_unuused
374 //
375 // Currently unused, should we ever call the restore handler?
376 // Perhaps before calling into Process.Start?
377 //
378 void
379 console_restore_signal_handlers ()
380 {
381         sigaction (SIGCONT, &save_sigcont, NULL);
382         sigaction (SIGINT, &save_sigint, NULL);
383         sigaction (SIGWINCH, &save_sigwinch, NULL);
384 }
385 #endif
386
387 static void
388 set_control_chars (MonoArray *control_chars, const guchar *cc)
389 {
390         /* The index into the array comes from corlib/System/ControlCharacters.cs */
391 #ifdef VINTR
392         mono_array_set (control_chars, gchar, 0, cc [VINTR]);
393 #endif
394 #ifdef VQUIT
395         mono_array_set (control_chars, gchar, 1, cc [VQUIT]);
396 #endif
397 #ifdef VERASE
398         mono_array_set (control_chars, gchar, 2, cc [VERASE]);
399 #endif
400 #ifdef VKILL
401         mono_array_set (control_chars, gchar, 3, cc [VKILL]);
402 #endif
403 #ifdef VEOF
404         mono_array_set (control_chars, gchar, 4, cc [VEOF]);
405 #endif
406 #ifdef VTIME
407         mono_array_set (control_chars, gchar, 5, cc [VTIME]);
408 #endif
409 #ifdef VMIN
410         mono_array_set (control_chars, gchar, 6, cc [VMIN]);
411 #endif
412 #ifdef VSWTC
413         mono_array_set (control_chars, gchar, 7, cc [VSWTC]);
414 #endif
415 #ifdef VSTART
416         mono_array_set (control_chars, gchar, 8, cc [VSTART]);
417 #endif
418 #ifdef VSTOP
419         mono_array_set (control_chars, gchar, 9, cc [VSTOP]);
420 #endif
421 #ifdef VSUSP
422         mono_array_set (control_chars, gchar, 10, cc [VSUSP]);
423 #endif
424 #ifdef VEOL
425         mono_array_set (control_chars, gchar, 11, cc [VEOL]);
426 #endif
427 #ifdef VREPRINT
428         mono_array_set (control_chars, gchar, 12, cc [VREPRINT]);
429 #endif
430 #ifdef VDISCARD
431         mono_array_set (control_chars, gchar, 13, cc [VDISCARD]);
432 #endif
433 #ifdef VWERASE
434         mono_array_set (control_chars, gchar, 14, cc [VWERASE]);
435 #endif
436 #ifdef VLNEXT
437         mono_array_set (control_chars, gchar, 15, cc [VLNEXT]);
438 #endif
439 #ifdef VEOL2
440         mono_array_set (control_chars, gchar, 16, cc [VEOL2]);
441 #endif
442 }
443
444 MonoBoolean
445 ves_icall_System_ConsoleDriver_TtySetup (MonoString *keypad, MonoString *teardown, MonoArray **control_chars, int **size)
446 {
447         int dims;
448
449         MONO_ARCH_SAVE_REGS;
450
451         dims = terminal_get_dimensions ();
452         if (dims == -1){
453                 int cols = 0, rows = 0;
454                                       
455                 char *str = getenv ("COLUMNS");
456                 if (str != NULL)
457                         cols = atoi (str);
458                 str = getenv ("LINES");
459                 if (str != NULL)
460                         rows = atoi (str);
461
462                 if (cols != 0 && rows != 0)
463                         cols_and_lines = (cols << 16) | rows;
464                 else
465                         cols_and_lines = -1;
466         } else {
467                 cols_and_lines = dims;
468         }
469         
470         *size = &cols_and_lines;
471
472         /* 17 is the number of entries set in set_control_chars() above.
473          * NCCS is the total size, but, by now, we only care about those 17 values*/
474         mono_gc_wbarrier_generic_store (control_chars, (MonoObject*) mono_array_new (mono_domain_get (), mono_defaults.byte_class, 17));
475         if (tcgetattr (STDIN_FILENO, &initial_attr) == -1)
476                 return FALSE;
477
478         mono_attr = initial_attr;
479         mono_attr.c_lflag &= ~(ICANON);
480         mono_attr.c_iflag &= ~(IXON|IXOFF);
481         mono_attr.c_cc [VMIN] = 1;
482         mono_attr.c_cc [VTIME] = 0;
483 #ifdef VDSUSP
484         /* Disable C-y being used as a suspend character on OSX */
485         mono_attr.c_cc [VDSUSP] = 255;
486 #endif
487         if (tcsetattr (STDIN_FILENO, TCSANOW, &mono_attr) == -1)
488                 return FALSE;
489
490         set_control_chars (*control_chars, mono_attr.c_cc);
491         /* If initialized from another appdomain... */
492         if (setup_finished)
493                 return TRUE;
494
495         keypad_xmit_str = keypad != NULL ? mono_string_to_utf8 (keypad) : NULL;
496         
497         console_set_signal_handlers ();
498         setup_finished = TRUE;
499         if (!atexit_called) {
500                 if (teardown != NULL)
501                         teardown_str = mono_string_to_utf8 (teardown);
502
503                 atexit (tty_teardown);
504         }
505
506         return TRUE;
507 }
508 #endif /* #if defined(__native_client__) */
509