blob: aee3a35ff7b1b7030559e2fe7f3b030653474af0 [file] [log] [blame]
Bram Moolenaaredf3f972016-08-29 22:49:24 +02001/* vi:set ts=8 sts=4 sw=4 noet:
Bram Moolenaar071d4272004-06-13 20:20:40 +00002 *
3 * VIM - Vi IMproved by Bram Moolenaar
4 * OS/2 port by Paul Slootman
5 * VMS merge by Zoltan Arpadffy
6 *
7 * Do ":help uganda" in Vim to read copying and usage conditions.
8 * Do ":help credits" in Vim to see a list of people who contributed.
9 * See README.txt for an overview of the Vim source code.
10 */
11
12/*
13 * os_unix.c -- code for all flavors of Unix (BSD, SYSV, SVR4, POSIX, ...)
14 * Also for OS/2, using the excellent EMX package!!!
15 * Also for BeOS and Atari MiNT.
16 *
17 * A lot of this file was originally written by Juergen Weigert and later
18 * changed beyond recognition.
19 */
20
Bram Moolenaar071d4272004-06-13 20:20:40 +000021#include "vim.h"
22
Bram Moolenaar325b7a22004-07-05 15:58:32 +000023#ifdef FEAT_MZSCHEME
24# include "if_mzsch.h"
25#endif
26
Bram Moolenaar071d4272004-06-13 20:20:40 +000027#include "os_unixx.h" /* unix includes for os_unix.c only */
28
29#ifdef USE_XSMP
30# include <X11/SM/SMlib.h>
31#endif
32
Bram Moolenaar588ebeb2008-05-07 17:09:24 +000033#ifdef HAVE_SELINUX
34# include <selinux/selinux.h>
35static int selinux_enabled = -1;
36#endif
37
Bram Moolenaar5bd32f42014-04-02 14:05:38 +020038#ifdef HAVE_SMACK
39# include <attr/xattr.h>
40# include <linux/xattr.h>
41# ifndef SMACK_LABEL_LEN
42# define SMACK_LABEL_LEN 1024
43# endif
44#endif
45
Bram Moolenaar643b6142018-09-12 20:29:09 +020046#ifdef __BEOS__
Bram Moolenaar311d9822007-02-27 15:48:28 +000047# undef select
Bram Moolenaar643b6142018-09-12 20:29:09 +020048# define select beos_select
Bram Moolenaar071d4272004-06-13 20:20:40 +000049#endif
50
Bram Moolenaara2442432007-04-26 14:26:37 +000051#ifdef __CYGWIN__
52# ifndef WIN32
Bram Moolenaar0d1498e2008-06-29 12:00:49 +000053# include <cygwin/version.h>
54# include <sys/cygwin.h> /* for cygwin_conv_to_posix_path() and/or
55 * for cygwin_conv_path() */
Bram Moolenaar693e40c2013-02-26 14:56:42 +010056# ifdef FEAT_CYGWIN_WIN32_CLIPBOARD
57# define WIN32_LEAN_AND_MEAN
58# include <windows.h>
59# include "winclip.pro"
60# endif
Bram Moolenaara2442432007-04-26 14:26:37 +000061# endif
62#endif
63
Bram Moolenaar071d4272004-06-13 20:20:40 +000064#ifdef FEAT_MOUSE_GPM
65# include <gpm.h>
66/* <linux/keyboard.h> contains defines conflicting with "keymap.h",
67 * I just copied relevant defines here. A cleaner solution would be to put gpm
68 * code into separate file and include there linux/keyboard.h
69 */
70/* #include <linux/keyboard.h> */
71# define KG_SHIFT 0
72# define KG_CTRL 2
73# define KG_ALT 3
74# define KG_ALTGR 1
75# define KG_SHIFTL 4
76# define KG_SHIFTR 5
77# define KG_CTRLL 6
78# define KG_CTRLR 7
79# define KG_CAPSSHIFT 8
80
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +010081static void gpm_close(void);
82static int gpm_open(void);
83static int mch_gpm_process(void);
Bram Moolenaar071d4272004-06-13 20:20:40 +000084#endif
85
Bram Moolenaar3577c6f2008-06-24 21:16:56 +000086#ifdef FEAT_SYSMOUSE
87# include <sys/consio.h>
88# include <sys/fbio.h>
89
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +010090static int sysmouse_open(void);
91static void sysmouse_close(void);
Bram Moolenaard99df422016-01-29 23:20:40 +010092static RETSIGTYPE sig_sysmouse SIGPROTOARG;
Bram Moolenaar3577c6f2008-06-24 21:16:56 +000093#endif
94
Bram Moolenaar071d4272004-06-13 20:20:40 +000095/*
96 * end of autoconf section. To be extended...
97 */
98
99/* Are the following #ifdefs still required? And why? Is that for X11? */
100
101#if defined(ESIX) || defined(M_UNIX) && !defined(SCO)
102# ifdef SIGWINCH
103# undef SIGWINCH
104# endif
105# ifdef TIOCGWINSZ
106# undef TIOCGWINSZ
107# endif
108#endif
109
110#if defined(SIGWINDOW) && !defined(SIGWINCH) /* hpux 9.01 has it */
111# define SIGWINCH SIGWINDOW
112#endif
113
114#ifdef FEAT_X11
115# include <X11/Xlib.h>
116# include <X11/Xutil.h>
117# include <X11/Xatom.h>
118# ifdef FEAT_XCLIPBOARD
119# include <X11/Intrinsic.h>
120# include <X11/Shell.h>
121# include <X11/StringDefs.h>
122static Widget xterm_Shell = (Widget)0;
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +0100123static void clip_update(void);
124static void xterm_update(void);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000125# endif
126
127# if defined(FEAT_XCLIPBOARD) || defined(FEAT_TITLE)
128Window x11_window = 0;
129# endif
130Display *x11_display = NULL;
131
132# ifdef FEAT_TITLE
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +0100133static int get_x11_windis(void);
134static void set_x11_title(char_u *);
135static void set_x11_icon(char_u *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000136# endif
137#endif
138
139#ifdef FEAT_TITLE
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +0100140static int get_x11_title(int);
141static int get_x11_icon(int);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000142
143static char_u *oldtitle = NULL;
Bram Moolenaar8e82c052018-08-21 19:47:48 +0200144static volatile sig_atomic_t oldtitle_outdated = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000145static int did_set_title = FALSE;
146static char_u *oldicon = NULL;
147static int did_set_icon = FALSE;
148#endif
149
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +0100150static void may_core_dump(void);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000151
Bram Moolenaar205b8862011-09-07 15:04:31 +0200152#ifdef HAVE_UNION_WAIT
153typedef union wait waitstatus;
154#else
155typedef int waitstatus;
156#endif
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +0100157static pid_t wait4pid(pid_t, waitstatus *);
Bram Moolenaar205b8862011-09-07 15:04:31 +0200158
Bram Moolenaare9c21ae2017-08-03 20:44:48 +0200159static int WaitForChar(long msec, int *interrupted, int ignore_input);
160static int WaitForCharOrMouse(long msec, int *interrupted, int ignore_input);
Bram Moolenaar4ffa0702013-12-11 17:12:37 +0100161#if defined(__BEOS__) || defined(VMS)
Bram Moolenaarcda77642016-06-04 13:32:35 +0200162int RealWaitForChar(int, long, int *, int *interrupted);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000163#else
Bram Moolenaarcda77642016-06-04 13:32:35 +0200164static int RealWaitForChar(int, long, int *, int *interrupted);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000165#endif
166
167#ifdef FEAT_XCLIPBOARD
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +0100168static int do_xterm_trace(void);
Bram Moolenaarcf851ce2005-06-16 21:52:47 +0000169# define XT_TRACE_DELAY 50 /* delay for xterm tracing */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000170#endif
171
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +0100172static void handle_resize(void);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000173
174#if defined(SIGWINCH)
Bram Moolenaard99df422016-01-29 23:20:40 +0100175static RETSIGTYPE sig_winch SIGPROTOARG;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000176#endif
177#if defined(SIGINT)
Bram Moolenaard99df422016-01-29 23:20:40 +0100178static RETSIGTYPE catch_sigint SIGPROTOARG;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000179#endif
180#if defined(SIGPWR)
Bram Moolenaard99df422016-01-29 23:20:40 +0100181static RETSIGTYPE catch_sigpwr SIGPROTOARG;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000182#endif
183#if defined(SIGALRM) && defined(FEAT_X11) \
184 && defined(FEAT_TITLE) && !defined(FEAT_GUI_GTK)
185# define SET_SIG_ALARM
Bram Moolenaard99df422016-01-29 23:20:40 +0100186static RETSIGTYPE sig_alarm SIGPROTOARG;
Bram Moolenaar76243bd2009-03-02 01:47:02 +0000187/* volatile because it is used in signal handler sig_alarm(). */
Bram Moolenaar8e82c052018-08-21 19:47:48 +0200188static volatile sig_atomic_t sig_alarm_called;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000189#endif
Bram Moolenaard99df422016-01-29 23:20:40 +0100190static RETSIGTYPE deathtrap SIGPROTOARG;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000191
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +0100192static void catch_int_signal(void);
193static void set_signals(void);
194static void catch_signals(RETSIGTYPE (*func_deadly)(), RETSIGTYPE (*func_other)());
Bram Moolenaarbb09ceb2016-10-18 16:27:23 +0200195#ifdef HAVE_SIGPROCMASK
196# define SIGSET_DECL(set) sigset_t set;
197# define BLOCK_SIGNALS(set) block_signals(set)
198# define UNBLOCK_SIGNALS(set) unblock_signals(set)
199#else
200# define SIGSET_DECL(set)
201# define BLOCK_SIGNALS(set) do { /**/ } while (0)
202# define UNBLOCK_SIGNALS(set) do { /**/ } while (0)
203#endif
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +0100204static int have_wildcard(int, char_u **);
205static int have_dollars(int, char_u **);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000206
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +0100207static int save_patterns(int num_pat, char_u **pat, int *num_file, char_u ***file);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000208
209#ifndef SIG_ERR
Bram Moolenaar8f0b2d42009-05-16 14:41:10 +0000210# define SIG_ERR ((RETSIGTYPE (*)())-1)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000211#endif
212
Bram Moolenaar76243bd2009-03-02 01:47:02 +0000213/* volatile because it is used in signal handler sig_winch(). */
Bram Moolenaar8e82c052018-08-21 19:47:48 +0200214static volatile sig_atomic_t do_resize = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000215static char_u *extra_shell_arg = NULL;
216static int show_shell_mess = TRUE;
Bram Moolenaar76243bd2009-03-02 01:47:02 +0000217/* volatile because it is used in signal handler deathtrap(). */
Bram Moolenaar8e82c052018-08-21 19:47:48 +0200218static volatile sig_atomic_t deadly_signal = 0; /* The signal we caught */
Bram Moolenaar76243bd2009-03-02 01:47:02 +0000219/* volatile because it is used in signal handler deathtrap(). */
Bram Moolenaar8e82c052018-08-21 19:47:48 +0200220static volatile sig_atomic_t in_mch_delay = FALSE; /* sleeping in mch_delay() */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000221
Bram Moolenaarc4d4ac22016-11-07 22:42:57 +0100222#if defined(FEAT_JOB_CHANNEL) && !defined(USE_SYSTEM)
223static int dont_check_job_ended = 0;
224#endif
225
Bram Moolenaar071d4272004-06-13 20:20:40 +0000226static int curr_tmode = TMODE_COOK; /* contains current terminal mode */
227
228#ifdef USE_XSMP
229typedef struct
230{
231 SmcConn smcconn; /* The SM connection ID */
232 IceConn iceconn; /* The ICE connection ID */
Bram Moolenaar67c53842010-05-22 18:28:27 +0200233 char *clientid; /* The client ID for the current smc session */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000234 Bool save_yourself; /* If we're in the middle of a save_yourself */
235 Bool shutdown; /* If we're in shutdown mode */
236} xsmp_config_T;
237
238static xsmp_config_T xsmp;
239#endif
240
241#ifdef SYS_SIGLIST_DECLARED
242/*
243 * I have seen
244 * extern char *_sys_siglist[NSIG];
245 * on Irix, Linux, NetBSD and Solaris. It contains a nice list of strings
246 * that describe the signals. That is nearly what we want here. But
247 * autoconf does only check for sys_siglist (without the underscore), I
248 * do not want to change everything today.... jw.
Bram Moolenaar3f7d0902016-11-12 21:13:42 +0100249 * This is why AC_DECL_SYS_SIGLIST is commented out in configure.ac.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000250 */
251#endif
252
253static struct signalinfo
254{
255 int sig; /* Signal number, eg. SIGSEGV etc */
256 char *name; /* Signal name (not char_u!). */
257 char deadly; /* Catch as a deadly signal? */
258} signal_info[] =
259{
260#ifdef SIGHUP
261 {SIGHUP, "HUP", TRUE},
262#endif
263#ifdef SIGQUIT
264 {SIGQUIT, "QUIT", TRUE},
265#endif
266#ifdef SIGILL
267 {SIGILL, "ILL", TRUE},
268#endif
269#ifdef SIGTRAP
270 {SIGTRAP, "TRAP", TRUE},
271#endif
272#ifdef SIGABRT
273 {SIGABRT, "ABRT", TRUE},
274#endif
275#ifdef SIGEMT
276 {SIGEMT, "EMT", TRUE},
277#endif
278#ifdef SIGFPE
279 {SIGFPE, "FPE", TRUE},
280#endif
281#ifdef SIGBUS
282 {SIGBUS, "BUS", TRUE},
283#endif
Bram Moolenaar75676462013-01-30 14:55:42 +0100284#if defined(SIGSEGV) && !defined(FEAT_MZSCHEME)
285 /* MzScheme uses SEGV in its garbage collector */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000286 {SIGSEGV, "SEGV", TRUE},
287#endif
288#ifdef SIGSYS
289 {SIGSYS, "SYS", TRUE},
290#endif
291#ifdef SIGALRM
292 {SIGALRM, "ALRM", FALSE}, /* Perl's alarm() can trigger it */
293#endif
294#ifdef SIGTERM
295 {SIGTERM, "TERM", TRUE},
296#endif
Bram Moolenaarb292a2a2011-02-09 18:47:40 +0100297#if defined(SIGVTALRM) && !defined(FEAT_RUBY)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000298 {SIGVTALRM, "VTALRM", TRUE},
299#endif
Bram Moolenaar02f07e02008-03-12 12:17:28 +0000300#if defined(SIGPROF) && !defined(FEAT_MZSCHEME) && !defined(WE_ARE_PROFILING)
301 /* MzScheme uses SIGPROF for its own needs; On Linux with profiling
302 * this makes Vim exit. WE_ARE_PROFILING is defined in Makefile. */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000303 {SIGPROF, "PROF", TRUE},
304#endif
305#ifdef SIGXCPU
306 {SIGXCPU, "XCPU", TRUE},
307#endif
308#ifdef SIGXFSZ
309 {SIGXFSZ, "XFSZ", TRUE},
310#endif
311#ifdef SIGUSR1
312 {SIGUSR1, "USR1", TRUE},
313#endif
Bram Moolenaar3577c6f2008-06-24 21:16:56 +0000314#if defined(SIGUSR2) && !defined(FEAT_SYSMOUSE)
315 /* Used for sysmouse handling */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000316 {SIGUSR2, "USR2", TRUE},
317#endif
318#ifdef SIGINT
319 {SIGINT, "INT", FALSE},
320#endif
321#ifdef SIGWINCH
322 {SIGWINCH, "WINCH", FALSE},
323#endif
324#ifdef SIGTSTP
325 {SIGTSTP, "TSTP", FALSE},
326#endif
327#ifdef SIGPIPE
328 {SIGPIPE, "PIPE", FALSE},
329#endif
330 {-1, "Unknown!", FALSE}
331};
332
Bram Moolenaar25724922009-07-14 15:38:41 +0000333 int
Bram Moolenaar05540972016-01-30 20:31:25 +0100334mch_chdir(char *path)
Bram Moolenaar25724922009-07-14 15:38:41 +0000335{
336 if (p_verbose >= 5)
337 {
338 verbose_enter();
339 smsg((char_u *)"chdir(%s)", path);
340 verbose_leave();
341 }
342# ifdef VMS
343 return chdir(vms_fixfilename(path));
344# else
345 return chdir(path);
346# endif
347}
348
Bram Moolenaar4f44b882017-08-13 20:06:18 +0200349/* Why is NeXT excluded here (and not in os_unixx.h)? */
350#if defined(ECHOE) && defined(ICANON) && (defined(HAVE_TERMIO_H) || defined(HAVE_TERMIOS_H)) && !defined(__NeXT__)
351# define NEW_TTY_SYSTEM
352#endif
353
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +0000354/*
Bram Moolenaard23a8232018-02-10 18:45:26 +0100355 * Write s[len] to the screen (stdout).
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +0000356 */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000357 void
Bram Moolenaar05540972016-01-30 20:31:25 +0100358mch_write(char_u *s, int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000359{
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +0000360 ignored = (int)write(1, (char *)s, len);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000361 if (p_wd) /* Unix is too fast, slow down a bit more */
Bram Moolenaar8fdd7212016-03-26 19:41:48 +0100362 RealWaitForChar(read_cmd_fd, p_wd, NULL, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000363}
364
365/*
Bram Moolenaarc2a27c32007-12-01 16:19:33 +0000366 * mch_inchar(): low level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000367 * Get a characters from the keyboard.
368 * Return the number of characters that are available.
369 * If wtime == 0 do not wait for characters.
370 * If wtime == n wait a short time for characters.
371 * If wtime == -1 wait forever for characters.
372 */
373 int
Bram Moolenaar05540972016-01-30 20:31:25 +0100374mch_inchar(
375 char_u *buf,
376 int maxlen,
377 long wtime, /* don't use "time", MIPS cannot handle it */
378 int tb_change_cnt)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000379{
380 int len;
Bram Moolenaarcda77642016-06-04 13:32:35 +0200381 int interrupted = FALSE;
Bram Moolenaar01688ad2016-10-27 20:00:07 +0200382 int did_start_blocking = FALSE;
Bram Moolenaare30a3d02016-06-04 14:11:20 +0200383 long wait_time;
Bram Moolenaar01688ad2016-10-27 20:00:07 +0200384 long elapsed_time = 0;
Bram Moolenaar833eb1d2016-11-24 17:22:50 +0100385#ifdef ELAPSED_FUNC
386 ELAPSED_TYPE start_tv;
Bram Moolenaare30a3d02016-06-04 14:11:20 +0200387
Bram Moolenaar833eb1d2016-11-24 17:22:50 +0100388 ELAPSED_INIT(start_tv);
Bram Moolenaare30a3d02016-06-04 14:11:20 +0200389#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000390
Bram Moolenaar01688ad2016-10-27 20:00:07 +0200391 /* repeat until we got a character or waited long enough */
Bram Moolenaare30a3d02016-06-04 14:11:20 +0200392 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000393 {
Bram Moolenaar01688ad2016-10-27 20:00:07 +0200394 /* Check if window changed size while we were busy, perhaps the ":set
395 * columns=99" command was used. */
396 while (do_resize)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000397 handle_resize();
Bram Moolenaar67c53842010-05-22 18:28:27 +0200398
Bram Moolenaar93c88e02015-09-15 14:12:05 +0200399#ifdef MESSAGE_QUEUE
Bram Moolenaared5a9d62018-09-06 13:14:43 +0200400 // Only process messages when waiting.
401 if (wtime != 0)
402 {
403 parse_queued_messages();
404 // If input was put directly in typeahead buffer bail out here.
405 if (typebuf_changed(tb_change_cnt))
406 return 0;
407 }
Bram Moolenaar67c53842010-05-22 18:28:27 +0200408#endif
Bram Moolenaar01688ad2016-10-27 20:00:07 +0200409 if (wtime < 0 && did_start_blocking)
410 /* blocking and already waited for p_ut */
411 wait_time = -1;
412 else
413 {
414 if (wtime >= 0)
415 wait_time = wtime;
416 else
417 /* going to block after p_ut */
418 wait_time = p_ut;
Bram Moolenaar833eb1d2016-11-24 17:22:50 +0100419#ifdef ELAPSED_FUNC
420 elapsed_time = ELAPSED_FUNC(start_tv);
Bram Moolenaar01688ad2016-10-27 20:00:07 +0200421#endif
422 wait_time -= elapsed_time;
423 if (wait_time < 0)
424 {
425 if (wtime >= 0)
426 /* no character available within "wtime" */
427 return 0;
428
Bram Moolenaar1c17ffa2018-04-24 15:19:04 +0200429 else
Bram Moolenaar01688ad2016-10-27 20:00:07 +0200430 {
431 /* no character available within 'updatetime' */
432 did_start_blocking = TRUE;
Bram Moolenaar01688ad2016-10-27 20:00:07 +0200433 if (trigger_cursorhold() && maxlen >= 3
434 && !typebuf_changed(tb_change_cnt))
435 {
436 buf[0] = K_SPECIAL;
437 buf[1] = KS_EXTRA;
438 buf[2] = (int)KE_CURSORHOLD;
439 return 3;
440 }
Bram Moolenaar01688ad2016-10-27 20:00:07 +0200441 /*
442 * If there is no character available within 'updatetime'
443 * seconds flush all the swap files to disk.
444 * Also done when interrupted by SIGWINCH.
445 */
446 before_blocking();
447 continue;
448 }
449 }
450 }
451
452#ifdef FEAT_JOB_CHANNEL
453 /* Checking if a job ended requires polling. Do this every 100 msec. */
454 if (has_pending_job() && (wait_time < 0 || wait_time > 100L))
455 wait_time = 100L;
Bram Moolenaar8a8199e2016-11-26 15:13:33 +0100456 /* If there is readahead then parse_queued_messages() timed out and we
457 * should call it again soon. */
458 if ((wait_time < 0 || wait_time > 100L) && channel_any_readahead())
459 wait_time = 10L;
Bram Moolenaar01688ad2016-10-27 20:00:07 +0200460#endif
Bram Moolenaarc3719bd2017-11-18 22:13:31 +0100461#ifdef FEAT_BEVAL_GUI
Bram Moolenaar59716a22017-03-01 20:32:44 +0100462 if (p_beval && wait_time > 100L)
463 /* The 'balloonexpr' may indirectly invoke a callback while waiting
464 * for a character, need to check often. */
465 wait_time = 100L;
466#endif
Bram Moolenaar01688ad2016-10-27 20:00:07 +0200467
Bram Moolenaar071d4272004-06-13 20:20:40 +0000468 /*
Bram Moolenaar48bae372010-07-29 23:12:15 +0200469 * We want to be interrupted by the winch signal
470 * or by an event on the monitored file descriptors.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000471 */
Bram Moolenaare9c21ae2017-08-03 20:44:48 +0200472 if (WaitForChar(wait_time, &interrupted, FALSE))
Bram Moolenaar67c53842010-05-22 18:28:27 +0200473 {
Bram Moolenaar01688ad2016-10-27 20:00:07 +0200474 /* If input was put directly in typeahead buffer bail out here. */
475 if (typebuf_changed(tb_change_cnt))
476 return 0;
477
478 /*
479 * For some terminals we only get one character at a time.
480 * We want the get all available characters, so we could keep on
481 * trying until none is available
482 * For some other terminals this is quite slow, that's why we don't
483 * do it.
484 */
485 len = read_from_input_buf(buf, (long)maxlen);
486 if (len > 0)
487 return len;
488 continue;
Bram Moolenaar67c53842010-05-22 18:28:27 +0200489 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000490
Bram Moolenaar01688ad2016-10-27 20:00:07 +0200491 /* no character available */
492#if !(defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H))
493 /* estimate the elapsed time */
Bram Moolenaarde5e2c22016-11-04 20:35:31 +0100494 elapsed_time += wait_time;
Bram Moolenaar01688ad2016-10-27 20:00:07 +0200495#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000496
Bram Moolenaar01688ad2016-10-27 20:00:07 +0200497 if (do_resize /* interrupted by SIGWINCH signal */
498#ifdef FEAT_CLIENTSERVER
499 || server_waiting()
500#endif
501#ifdef MESSAGE_QUEUE
502 || interrupted
503#endif
504 || wait_time > 0
Bram Moolenaar1572e302017-03-25 20:16:28 +0100505 || (wtime < 0 && !did_start_blocking))
Bram Moolenaar01688ad2016-10-27 20:00:07 +0200506 continue;
507
508 /* no character available or interrupted */
509 break;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000510 }
Bram Moolenaar01688ad2016-10-27 20:00:07 +0200511 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000512}
513
514 static void
Bram Moolenaar05540972016-01-30 20:31:25 +0100515handle_resize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000516{
517 do_resize = FALSE;
518 shell_resized();
519}
520
521/*
Bram Moolenaar40b1b542016-04-20 20:18:23 +0200522 * Return non-zero if a character is available.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000523 */
524 int
Bram Moolenaar05540972016-01-30 20:31:25 +0100525mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000526{
Bram Moolenaare9c21ae2017-08-03 20:44:48 +0200527 return WaitForChar(0L, NULL, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000528}
529
Bram Moolenaare9c21ae2017-08-03 20:44:48 +0200530#if defined(FEAT_TERMINAL) || defined(PROTO)
531/*
532 * Check for any pending input or messages.
533 */
534 int
535mch_check_messages(void)
536{
537 return WaitForChar(0L, NULL, TRUE);
538}
539#endif
540
Bram Moolenaar071d4272004-06-13 20:20:40 +0000541#if defined(HAVE_TOTAL_MEM) || defined(PROTO)
542# ifdef HAVE_SYS_RESOURCE_H
Bram Moolenaar8f0b2d42009-05-16 14:41:10 +0000543# include <sys/resource.h>
Bram Moolenaar071d4272004-06-13 20:20:40 +0000544# endif
545# if defined(HAVE_SYS_SYSCTL_H) && defined(HAVE_SYSCTL)
546# include <sys/sysctl.h>
547# endif
548# if defined(HAVE_SYS_SYSINFO_H) && defined(HAVE_SYSINFO)
549# include <sys/sysinfo.h>
550# endif
Bram Moolenaar362dc332018-03-05 21:59:37 +0100551# ifdef MACOS_X
Bram Moolenaar988615f2018-02-27 17:58:20 +0100552# include <mach/mach_host.h>
553# include <mach/mach_port.h>
Bram Moolenaar988615f2018-02-27 17:58:20 +0100554# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000555
556/*
Bram Moolenaar914572a2007-05-01 11:37:47 +0000557 * Return total amount of memory available in Kbyte.
558 * Doesn't change when memory has been allocated.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000559 */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000560 long_u
Bram Moolenaar05540972016-01-30 20:31:25 +0100561mch_total_mem(int special UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000562{
Bram Moolenaar071d4272004-06-13 20:20:40 +0000563 long_u mem = 0;
Bram Moolenaar914572a2007-05-01 11:37:47 +0000564 long_u shiftright = 10; /* how much to shift "mem" right for Kbyte */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000565
Bram Moolenaar362dc332018-03-05 21:59:37 +0100566# ifdef MACOS_X
Bram Moolenaar988615f2018-02-27 17:58:20 +0100567 {
568 /* Mac (Darwin) way of getting the amount of RAM available */
569 mach_port_t host = mach_host_self();
570 kern_return_t kret;
571# ifdef HOST_VM_INFO64
572 struct vm_statistics64 vm_stat;
573 natural_t count = HOST_VM_INFO64_COUNT;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000574
Bram Moolenaar988615f2018-02-27 17:58:20 +0100575 kret = host_statistics64(host, HOST_VM_INFO64,
576 (host_info64_t)&vm_stat, &count);
577# else
578 struct vm_statistics vm_stat;
579 natural_t count = HOST_VM_INFO_COUNT;
580
581 kret = host_statistics(host, HOST_VM_INFO,
582 (host_info_t)&vm_stat, &count);
583# endif
584 if (kret == KERN_SUCCESS)
585 /* get the amount of user memory by summing each usage */
586 mem = (long_u)(vm_stat.free_count + vm_stat.active_count
587 + vm_stat.inactive_count
588# ifdef MAC_OS_X_VERSION_10_9
589 + vm_stat.compressor_page_count
590# endif
Bram Moolenaar62b7f6a2018-03-22 21:44:07 +0100591 ) * sysconf(_SC_PAGESIZE);
Bram Moolenaar988615f2018-02-27 17:58:20 +0100592 mach_port_deallocate(mach_task_self(), host);
593 }
594# endif
595
596# ifdef HAVE_SYSCTL
597 if (mem == 0)
598 {
599 /* BSD way of getting the amount of RAM available. */
600 int mib[2];
601 size_t len = sizeof(long_u);
602# ifdef HW_USERMEM64
603 long_u physmem;
604# else
605 /* sysctl() may return 32 bit or 64 bit, accept both */
606 union {
607 int_u u32;
608 long_u u64;
609 } physmem;
610# endif
611
612 mib[0] = CTL_HW;
613# ifdef HW_USERMEM64
614 mib[1] = HW_USERMEM64;
615# else
616 mib[1] = HW_USERMEM;
617# endif
618 if (sysctl(mib, 2, &physmem, &len, NULL, 0) == 0)
619 {
620# ifdef HW_USERMEM64
621 mem = (long_u)physmem;
622# else
623 if (len == sizeof(physmem.u64))
624 mem = (long_u)physmem.u64;
625 else
626 mem = (long_u)physmem.u32;
627# endif
628 }
629 }
Bram Moolenaara06ecab2016-07-16 14:47:36 +0200630# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000631
Bram Moolenaara06ecab2016-07-16 14:47:36 +0200632# if defined(HAVE_SYS_SYSINFO_H) && defined(HAVE_SYSINFO)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000633 if (mem == 0)
634 {
635 struct sysinfo sinfo;
636
637 /* Linux way of getting amount of RAM available */
638 if (sysinfo(&sinfo) == 0)
Bram Moolenaar914572a2007-05-01 11:37:47 +0000639 {
Bram Moolenaara06ecab2016-07-16 14:47:36 +0200640# ifdef HAVE_SYSINFO_MEM_UNIT
Bram Moolenaar914572a2007-05-01 11:37:47 +0000641 /* avoid overflow as much as possible */
642 while (shiftright > 0 && (sinfo.mem_unit & 1) == 0)
643 {
644 sinfo.mem_unit = sinfo.mem_unit >> 1;
645 --shiftright;
646 }
647 mem = sinfo.totalram * sinfo.mem_unit;
Bram Moolenaara06ecab2016-07-16 14:47:36 +0200648# else
Bram Moolenaar071d4272004-06-13 20:20:40 +0000649 mem = sinfo.totalram;
Bram Moolenaara06ecab2016-07-16 14:47:36 +0200650# endif
Bram Moolenaar914572a2007-05-01 11:37:47 +0000651 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000652 }
Bram Moolenaara06ecab2016-07-16 14:47:36 +0200653# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000654
Bram Moolenaara06ecab2016-07-16 14:47:36 +0200655# ifdef HAVE_SYSCONF
Bram Moolenaar071d4272004-06-13 20:20:40 +0000656 if (mem == 0)
657 {
658 long pagesize, pagecount;
659
660 /* Solaris way of getting amount of RAM available */
661 pagesize = sysconf(_SC_PAGESIZE);
662 pagecount = sysconf(_SC_PHYS_PAGES);
663 if (pagesize > 0 && pagecount > 0)
Bram Moolenaar914572a2007-05-01 11:37:47 +0000664 {
665 /* avoid overflow as much as possible */
666 while (shiftright > 0 && (pagesize & 1) == 0)
667 {
Bram Moolenaar3d27a452007-05-10 17:44:18 +0000668 pagesize = (long_u)pagesize >> 1;
Bram Moolenaar914572a2007-05-01 11:37:47 +0000669 --shiftright;
670 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000671 mem = (long_u)pagesize * pagecount;
Bram Moolenaar914572a2007-05-01 11:37:47 +0000672 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000673 }
Bram Moolenaara06ecab2016-07-16 14:47:36 +0200674# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000675
676 /* Return the minimum of the physical memory and the user limit, because
677 * using more than the user limit may cause Vim to be terminated. */
Bram Moolenaara06ecab2016-07-16 14:47:36 +0200678# if defined(HAVE_SYS_RESOURCE_H) && defined(HAVE_GETRLIMIT)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000679 {
680 struct rlimit rlp;
681
682 if (getrlimit(RLIMIT_DATA, &rlp) == 0
683 && rlp.rlim_cur < ((rlim_t)1 << (sizeof(long_u) * 8 - 1))
Bram Moolenaara06ecab2016-07-16 14:47:36 +0200684# ifdef RLIM_INFINITY
Bram Moolenaar071d4272004-06-13 20:20:40 +0000685 && rlp.rlim_cur != RLIM_INFINITY
Bram Moolenaara06ecab2016-07-16 14:47:36 +0200686# endif
Bram Moolenaar914572a2007-05-01 11:37:47 +0000687 && ((long_u)rlp.rlim_cur >> 10) < (mem >> shiftright)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000688 )
Bram Moolenaar914572a2007-05-01 11:37:47 +0000689 {
690 mem = (long_u)rlp.rlim_cur;
691 shiftright = 10;
692 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000693 }
Bram Moolenaara06ecab2016-07-16 14:47:36 +0200694# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000695
696 if (mem > 0)
Bram Moolenaar914572a2007-05-01 11:37:47 +0000697 return mem >> shiftright;
698 return (long_u)0x1fffff;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000699}
700#endif
701
702 void
Bram Moolenaar05540972016-01-30 20:31:25 +0100703mch_delay(long msec, int ignoreinput)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000704{
705 int old_tmode;
Bram Moolenaar325b7a22004-07-05 15:58:32 +0000706#ifdef FEAT_MZSCHEME
707 long total = msec; /* remember original value */
708#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000709
710 if (ignoreinput)
711 {
712 /* Go to cooked mode without echo, to allow SIGINT interrupting us
Bram Moolenaarae0f2ca2008-02-10 21:25:55 +0000713 * here. But we don't want QUIT to kill us (CTRL-\ used in a
714 * shell may produce SIGQUIT). */
715 in_mch_delay = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000716 old_tmode = curr_tmode;
717 if (curr_tmode == TMODE_RAW)
718 settmode(TMODE_SLEEP);
719
720 /*
721 * Everybody sleeps in a different way...
722 * Prefer nanosleep(), some versions of usleep() can only sleep up to
723 * one second.
724 */
Bram Moolenaar325b7a22004-07-05 15:58:32 +0000725#ifdef FEAT_MZSCHEME
726 do
727 {
728 /* if total is large enough, wait by portions in p_mzq */
729 if (total > p_mzq)
730 msec = p_mzq;
731 else
732 msec = total;
733 total -= msec;
734#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000735#ifdef HAVE_NANOSLEEP
736 {
737 struct timespec ts;
738
739 ts.tv_sec = msec / 1000;
740 ts.tv_nsec = (msec % 1000) * 1000000;
741 (void)nanosleep(&ts, NULL);
742 }
743#else
744# ifdef HAVE_USLEEP
745 while (msec >= 1000)
746 {
747 usleep((unsigned int)(999 * 1000));
748 msec -= 999;
749 }
750 usleep((unsigned int)(msec * 1000));
751# else
752# ifndef HAVE_SELECT
753 poll(NULL, 0, (int)msec);
754# else
Bram Moolenaar071d4272004-06-13 20:20:40 +0000755 {
756 struct timeval tv;
757
758 tv.tv_sec = msec / 1000;
759 tv.tv_usec = (msec % 1000) * 1000;
760 /*
761 * NOTE: Solaris 2.6 has a bug that makes select() hang here. Get
762 * a patch from Sun to fix this. Reported by Gunnar Pedersen.
763 */
764 select(0, NULL, NULL, NULL, &tv);
765 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000766# endif /* HAVE_SELECT */
767# endif /* HAVE_NANOSLEEP */
768#endif /* HAVE_USLEEP */
Bram Moolenaar325b7a22004-07-05 15:58:32 +0000769#ifdef FEAT_MZSCHEME
770 }
771 while (total > 0);
772#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000773
774 settmode(old_tmode);
Bram Moolenaarae0f2ca2008-02-10 21:25:55 +0000775 in_mch_delay = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000776 }
777 else
Bram Moolenaare9c21ae2017-08-03 20:44:48 +0200778 WaitForChar(msec, NULL, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000779}
780
Bram Moolenaarbc7aa852005-03-06 23:38:09 +0000781#if defined(HAVE_STACK_LIMIT) \
Bram Moolenaar071d4272004-06-13 20:20:40 +0000782 || (!defined(HAVE_SIGALTSTACK) && defined(HAVE_SIGSTACK))
783# define HAVE_CHECK_STACK_GROWTH
784/*
785 * Support for checking for an almost-out-of-stack-space situation.
786 */
787
788/*
789 * Return a pointer to an item on the stack. Used to find out if the stack
790 * grows up or down.
791 */
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +0100792static void check_stack_growth(char *p);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000793static int stack_grows_downwards;
794
795/*
796 * Find out if the stack grows upwards or downwards.
797 * "p" points to a variable on the stack of the caller.
798 */
799 static void
Bram Moolenaar05540972016-01-30 20:31:25 +0100800check_stack_growth(char *p)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000801{
802 int i;
803
804 stack_grows_downwards = (p > (char *)&i);
805}
806#endif
807
Bram Moolenaarbc7aa852005-03-06 23:38:09 +0000808#if defined(HAVE_STACK_LIMIT) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000809static char *stack_limit = NULL;
810
811#if defined(_THREAD_SAFE) && defined(HAVE_PTHREAD_NP_H)
812# include <pthread.h>
813# include <pthread_np.h>
814#endif
815
816/*
817 * Find out until how var the stack can grow without getting into trouble.
818 * Called when starting up and when switching to the signal stack in
819 * deathtrap().
820 */
821 static void
Bram Moolenaar05540972016-01-30 20:31:25 +0100822get_stack_limit(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000823{
824 struct rlimit rlp;
825 int i;
826 long lim;
827
828 /* Set the stack limit to 15/16 of the allowable size. Skip this when the
829 * limit doesn't fit in a long (rlim_cur might be "long long"). */
830 if (getrlimit(RLIMIT_STACK, &rlp) == 0
831 && rlp.rlim_cur < ((rlim_t)1 << (sizeof(long_u) * 8 - 1))
832# ifdef RLIM_INFINITY
833 && rlp.rlim_cur != RLIM_INFINITY
834# endif
835 )
836 {
837 lim = (long)rlp.rlim_cur;
838#if defined(_THREAD_SAFE) && defined(HAVE_PTHREAD_NP_H)
839 {
840 pthread_attr_t attr;
841 size_t size;
842
843 /* On FreeBSD the initial thread always has a fixed stack size, no
844 * matter what the limits are set to. Normally it's 1 Mbyte. */
845 pthread_attr_init(&attr);
846 if (pthread_attr_get_np(pthread_self(), &attr) == 0)
847 {
848 pthread_attr_getstacksize(&attr, &size);
849 if (lim > (long)size)
850 lim = (long)size;
851 }
852 pthread_attr_destroy(&attr);
853 }
854#endif
855 if (stack_grows_downwards)
856 {
857 stack_limit = (char *)((long)&i - (lim / 16L * 15L));
858 if (stack_limit >= (char *)&i)
859 /* overflow, set to 1/16 of current stack position */
860 stack_limit = (char *)((long)&i / 16L);
861 }
862 else
863 {
864 stack_limit = (char *)((long)&i + (lim / 16L * 15L));
865 if (stack_limit <= (char *)&i)
866 stack_limit = NULL; /* overflow */
867 }
868 }
869}
870
871/*
872 * Return FAIL when running out of stack space.
873 * "p" must point to any variable local to the caller that's on the stack.
874 */
875 int
Bram Moolenaar05540972016-01-30 20:31:25 +0100876mch_stackcheck(char *p)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000877{
878 if (stack_limit != NULL)
879 {
880 if (stack_grows_downwards)
881 {
882 if (p < stack_limit)
883 return FAIL;
884 }
885 else if (p > stack_limit)
886 return FAIL;
887 }
888 return OK;
889}
890#endif
891
892#if defined(HAVE_SIGALTSTACK) || defined(HAVE_SIGSTACK)
893/*
894 * Support for using the signal stack.
895 * This helps when we run out of stack space, which causes a SIGSEGV. The
896 * signal handler then must run on another stack, since the normal stack is
897 * completely full.
898 */
899
900#ifndef SIGSTKSZ
901# define SIGSTKSZ 8000 /* just a guess of how much stack is needed... */
902#endif
903
904# ifdef HAVE_SIGALTSTACK
905static stack_t sigstk; /* for sigaltstack() */
906# else
907static struct sigstack sigstk; /* for sigstack() */
908# endif
909
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +0100910static void init_signal_stack(void);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000911static char *signal_stack;
912
913 static void
Bram Moolenaar05540972016-01-30 20:31:25 +0100914init_signal_stack(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000915{
916 if (signal_stack != NULL)
917 {
918# ifdef HAVE_SIGALTSTACK
Bram Moolenaar071d4272004-06-13 20:20:40 +0000919# ifdef HAVE_SS_BASE
920 sigstk.ss_base = signal_stack;
921# else
922 sigstk.ss_sp = signal_stack;
923# endif
924 sigstk.ss_size = SIGSTKSZ;
925 sigstk.ss_flags = 0;
926 (void)sigaltstack(&sigstk, NULL);
927# else
928 sigstk.ss_sp = signal_stack;
929 if (stack_grows_downwards)
930 sigstk.ss_sp += SIGSTKSZ - 1;
931 sigstk.ss_onstack = 0;
932 (void)sigstack(&sigstk, NULL);
933# endif
934 }
935}
936#endif
937
938/*
Bram Moolenaar76243bd2009-03-02 01:47:02 +0000939 * We need correct prototypes for a signal function, otherwise mean compilers
Bram Moolenaar071d4272004-06-13 20:20:40 +0000940 * will barf when the second argument to signal() is ``wrong''.
941 * Let me try it with a few tricky defines from my own osdef.h (jw).
942 */
943#if defined(SIGWINCH)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000944 static RETSIGTYPE
945sig_winch SIGDEFARG(sigarg)
946{
947 /* this is not required on all systems, but it doesn't hurt anybody */
948 signal(SIGWINCH, (RETSIGTYPE (*)())sig_winch);
949 do_resize = TRUE;
950 SIGRETURN;
951}
952#endif
953
954#if defined(SIGINT)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000955 static RETSIGTYPE
956catch_sigint SIGDEFARG(sigarg)
957{
958 /* this is not required on all systems, but it doesn't hurt anybody */
959 signal(SIGINT, (RETSIGTYPE (*)())catch_sigint);
960 got_int = TRUE;
961 SIGRETURN;
962}
963#endif
964
965#if defined(SIGPWR)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000966 static RETSIGTYPE
967catch_sigpwr SIGDEFARG(sigarg)
968{
Bram Moolenaard8b0cf12004-12-12 11:33:30 +0000969 /* this is not required on all systems, but it doesn't hurt anybody */
970 signal(SIGPWR, (RETSIGTYPE (*)())catch_sigpwr);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000971 /*
972 * I'm not sure we get the SIGPWR signal when the system is really going
973 * down or when the batteries are almost empty. Just preserve the swap
974 * files and don't exit, that can't do any harm.
975 */
976 ml_sync_all(FALSE, FALSE);
977 SIGRETURN;
978}
979#endif
980
981#ifdef SET_SIG_ALARM
982/*
983 * signal function for alarm().
984 */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000985 static RETSIGTYPE
986sig_alarm SIGDEFARG(sigarg)
987{
988 /* doesn't do anything, just to break a system call */
989 sig_alarm_called = TRUE;
990 SIGRETURN;
991}
992#endif
993
Bram Moolenaar44ecf652005-03-07 23:09:59 +0000994#if (defined(HAVE_SETJMP_H) \
995 && ((defined(FEAT_X11) && defined(FEAT_XCLIPBOARD)) \
996 || defined(FEAT_LIBCALL))) \
997 || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000998/*
999 * A simplistic version of setjmp() that only allows one level of using.
1000 * Don't call twice before calling mch_endjmp()!.
1001 * Usage:
1002 * mch_startjmp();
1003 * if (SETJMP(lc_jump_env) != 0)
1004 * {
1005 * mch_didjmp();
1006 * EMSG("crash!");
1007 * }
1008 * else
1009 * {
1010 * do_the_work;
1011 * mch_endjmp();
1012 * }
1013 * Note: Can't move SETJMP() here, because a function calling setjmp() must
1014 * not return before the saved environment is used.
1015 * Returns OK for normal return, FAIL when the protected code caused a
1016 * problem and LONGJMP() was used.
1017 */
1018 void
Bram Moolenaar05540972016-01-30 20:31:25 +01001019mch_startjmp(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001020{
1021#ifdef SIGHASARG
1022 lc_signal = 0;
1023#endif
1024 lc_active = TRUE;
1025}
1026
1027 void
Bram Moolenaar05540972016-01-30 20:31:25 +01001028mch_endjmp(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001029{
1030 lc_active = FALSE;
1031}
1032
1033 void
Bram Moolenaar05540972016-01-30 20:31:25 +01001034mch_didjmp(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001035{
1036# if defined(HAVE_SIGALTSTACK) || defined(HAVE_SIGSTACK)
1037 /* On FreeBSD the signal stack has to be reset after using siglongjmp(),
1038 * otherwise catching the signal only works once. */
1039 init_signal_stack();
1040# endif
1041}
1042#endif
1043
1044/*
1045 * This function handles deadly signals.
Bram Moolenaarbec9c202013-09-05 21:41:39 +02001046 * It tries to preserve any swap files and exit properly.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001047 * (partly from Elvis).
Bram Moolenaarbec9c202013-09-05 21:41:39 +02001048 * NOTE: Avoid unsafe functions, such as allocating memory, they can result in
1049 * a deadlock.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001050 */
1051 static RETSIGTYPE
1052deathtrap SIGDEFARG(sigarg)
1053{
1054 static int entered = 0; /* count the number of times we got here.
1055 Note: when memory has been corrupted
1056 this may get an arbitrary value! */
1057#ifdef SIGHASARG
1058 int i;
1059#endif
1060
1061#if defined(HAVE_SETJMP_H)
1062 /*
1063 * Catch a crash in protected code.
1064 * Restores the environment saved in lc_jump_env, which looks like
1065 * SETJMP() returns 1.
1066 */
1067 if (lc_active)
1068 {
1069# if defined(SIGHASARG)
1070 lc_signal = sigarg;
1071# endif
1072 lc_active = FALSE; /* don't jump again */
1073 LONGJMP(lc_jump_env, 1);
1074 /* NOTREACHED */
1075 }
1076#endif
1077
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001078#ifdef SIGHASARG
Bram Moolenaarae0f2ca2008-02-10 21:25:55 +00001079# ifdef SIGQUIT
1080 /* While in mch_delay() we go to cooked mode to allow a CTRL-C to
1081 * interrupt us. But in cooked mode we may also get SIGQUIT, e.g., when
1082 * pressing CTRL-\, but we don't want Vim to exit then. */
1083 if (in_mch_delay && sigarg == SIGQUIT)
1084 SIGRETURN;
1085# endif
1086
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001087 /* When SIGHUP, SIGQUIT, etc. are blocked: postpone the effect and return
1088 * here. This avoids that a non-reentrant function is interrupted, e.g.,
1089 * free(). Calling free() again may then cause a crash. */
1090 if (entered == 0
1091 && (0
1092# ifdef SIGHUP
1093 || sigarg == SIGHUP
1094# endif
1095# ifdef SIGQUIT
1096 || sigarg == SIGQUIT
1097# endif
1098# ifdef SIGTERM
1099 || sigarg == SIGTERM
1100# endif
1101# ifdef SIGPWR
1102 || sigarg == SIGPWR
1103# endif
1104# ifdef SIGUSR1
1105 || sigarg == SIGUSR1
1106# endif
1107# ifdef SIGUSR2
1108 || sigarg == SIGUSR2
1109# endif
1110 )
Bram Moolenaar1f28b072005-07-12 22:42:41 +00001111 && !vim_handle_signal(sigarg))
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001112 SIGRETURN;
1113#endif
1114
Bram Moolenaar071d4272004-06-13 20:20:40 +00001115 /* Remember how often we have been called. */
1116 ++entered;
1117
Bram Moolenaare429e702016-06-10 19:49:14 +02001118 /* Executing autocommands is likely to use more stack space than we have
1119 * available in the signal stack. */
1120 block_autocmds();
Bram Moolenaare429e702016-06-10 19:49:14 +02001121
Bram Moolenaar071d4272004-06-13 20:20:40 +00001122#ifdef FEAT_EVAL
1123 /* Set the v:dying variable. */
1124 set_vim_var_nr(VV_DYING, (long)entered);
1125#endif
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01001126 v_dying = entered;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001127
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00001128#ifdef HAVE_STACK_LIMIT
Bram Moolenaar071d4272004-06-13 20:20:40 +00001129 /* Since we are now using the signal stack, need to reset the stack
1130 * limit. Otherwise using a regexp will fail. */
1131 get_stack_limit();
1132#endif
1133
Bram Moolenaar1f4d4de2006-03-14 23:00:46 +00001134#if 0
1135 /* This is for opening gdb the moment Vim crashes.
1136 * You need to manually adjust the file name and Vim executable name.
1137 * Suggested by SungHyun Nam. */
1138 {
1139# define VI_GDB_FILE "/tmp/vimgdb"
1140# define VIM_NAME "/usr/bin/vim"
1141 FILE *fp = fopen(VI_GDB_FILE, "w");
1142 if (fp)
1143 {
1144 fprintf(fp,
1145 "file %s\n"
1146 "attach %d\n"
1147 "set height 1000\n"
1148 "bt full\n"
1149 , VIM_NAME, getpid());
1150 fclose(fp);
1151 system("xterm -e gdb -x "VI_GDB_FILE);
1152 unlink(VI_GDB_FILE);
1153 }
1154 }
1155#endif
1156
Bram Moolenaar071d4272004-06-13 20:20:40 +00001157#ifdef SIGHASARG
1158 /* try to find the name of this signal */
1159 for (i = 0; signal_info[i].sig != -1; i++)
1160 if (sigarg == signal_info[i].sig)
1161 break;
1162 deadly_signal = sigarg;
1163#endif
1164
1165 full_screen = FALSE; /* don't write message to the GUI, it might be
1166 * part of the problem... */
1167 /*
1168 * If something goes wrong after entering here, we may get here again.
1169 * When this happens, give a message and try to exit nicely (resetting the
1170 * terminal mode, etc.)
1171 * When this happens twice, just exit, don't even try to give a message,
1172 * stack may be corrupt or something weird.
1173 * When this still happens again (or memory was corrupted in such a way
1174 * that "entered" was clobbered) use _exit(), don't try freeing resources.
1175 */
1176 if (entered >= 3)
1177 {
1178 reset_signals(); /* don't catch any signals anymore */
1179 may_core_dump();
1180 if (entered >= 4)
1181 _exit(8);
1182 exit(7);
1183 }
1184 if (entered == 2)
1185 {
Bram Moolenaarbec9c202013-09-05 21:41:39 +02001186 /* No translation, it may call malloc(). */
1187 OUT_STR("Vim: Double signal, exiting\n");
Bram Moolenaar071d4272004-06-13 20:20:40 +00001188 out_flush();
1189 getout(1);
1190 }
1191
Bram Moolenaarbec9c202013-09-05 21:41:39 +02001192 /* No translation, it may call malloc(). */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001193#ifdef SIGHASARG
Bram Moolenaarbec9c202013-09-05 21:41:39 +02001194 sprintf((char *)IObuff, "Vim: Caught deadly signal %s\n",
Bram Moolenaar071d4272004-06-13 20:20:40 +00001195 signal_info[i].name);
1196#else
Bram Moolenaarbec9c202013-09-05 21:41:39 +02001197 sprintf((char *)IObuff, "Vim: Caught deadly signal\n");
Bram Moolenaar071d4272004-06-13 20:20:40 +00001198#endif
Bram Moolenaarbec9c202013-09-05 21:41:39 +02001199
1200 /* Preserve files and exit. This sets the really_exiting flag to prevent
1201 * calling free(). */
1202 preserve_exit();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001203
Bram Moolenaare429e702016-06-10 19:49:14 +02001204 /* NOTREACHED */
1205
Bram Moolenaar009b2592004-10-24 19:18:58 +00001206#ifdef NBDEBUG
1207 reset_signals();
1208 may_core_dump();
1209 abort();
1210#endif
1211
Bram Moolenaar071d4272004-06-13 20:20:40 +00001212 SIGRETURN;
1213}
1214
Bram Moolenaar071d4272004-06-13 20:20:40 +00001215/*
Bram Moolenaar2e310482018-08-21 13:09:10 +02001216 * Invoked after receiving SIGCONT. We don't know what happened while
1217 * sleeping, deal with part of that.
1218 */
1219 static void
1220after_sigcont(void)
1221{
1222# ifdef FEAT_TITLE
1223 // Don't change "oldtitle" in a signal handler, set a flag to obtain it
1224 // again later.
1225 oldtitle_outdated = TRUE;
1226# endif
1227 settmode(TMODE_RAW);
1228 need_check_timestamps = TRUE;
1229 did_check_timestamps = FALSE;
1230}
1231
1232#if defined(SIGCONT)
1233static RETSIGTYPE sigcont_handler SIGPROTOARG;
Bram Moolenaar8e82c052018-08-21 19:47:48 +02001234static volatile sig_atomic_t in_mch_suspend = FALSE;
Bram Moolenaar2e310482018-08-21 13:09:10 +02001235
1236/*
1237 * With multi-threading, suspending might not work immediately. Catch the
1238 * SIGCONT signal, which will be used as an indication whether the suspending
1239 * has been done or not.
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001240 *
1241 * On Linux, signal is not always handled immediately either.
1242 * See https://bugs.launchpad.net/bugs/291373
Bram Moolenaar2e310482018-08-21 13:09:10 +02001243 * Probably because the signal is handled in another thread.
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001244 *
Bram Moolenaarb292a2a2011-02-09 18:47:40 +01001245 * volatile because it is used in signal handler sigcont_handler().
Bram Moolenaar071d4272004-06-13 20:20:40 +00001246 */
Bram Moolenaar8e82c052018-08-21 19:47:48 +02001247static volatile sig_atomic_t sigcont_received;
Bram Moolenaarf1883472018-08-20 21:58:57 +02001248static RETSIGTYPE sigcont_handler SIGPROTOARG;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001249
1250/*
1251 * signal handler for SIGCONT
1252 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001253 static RETSIGTYPE
1254sigcont_handler SIGDEFARG(sigarg)
1255{
Bram Moolenaar2e310482018-08-21 13:09:10 +02001256 if (in_mch_suspend)
1257 {
1258 sigcont_received = TRUE;
1259 }
1260 else
1261 {
1262 // We didn't suspend ourselves, assume we were stopped by a SIGSTOP
1263 // signal (which can't be intercepted) and get a SIGCONT. Need to get
1264 // back to a sane mode. We should redraw, but we can't really do that
1265 // in a signal handler, do a redraw later.
1266 after_sigcont();
1267 redraw_later(CLEAR);
1268 cursor_on_force();
1269 out_flush();
1270 }
1271
Bram Moolenaar071d4272004-06-13 20:20:40 +00001272 SIGRETURN;
1273}
1274#endif
1275
Bram Moolenaar62b42182010-09-21 22:09:37 +02001276# if defined(FEAT_CLIPBOARD) && defined(FEAT_X11)
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +01001277static void loose_clipboard(void);
Bram Moolenaar090cfc12013-03-19 12:35:42 +01001278# ifdef USE_SYSTEM
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +01001279static void save_clipboard(void);
1280static void restore_clipboard(void);
Bram Moolenaar1a0316c2013-03-13 17:50:25 +01001281
1282static void *clip_star_save = NULL;
1283static void *clip_plus_save = NULL;
Bram Moolenaar090cfc12013-03-19 12:35:42 +01001284# endif
Bram Moolenaar62b42182010-09-21 22:09:37 +02001285
1286/*
1287 * Called when Vim is going to sleep or execute a shell command.
1288 * We can't respond to requests for the X selections. Lose them, otherwise
1289 * other applications will hang. But first copy the text to cut buffer 0.
1290 */
1291 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01001292loose_clipboard(void)
Bram Moolenaar62b42182010-09-21 22:09:37 +02001293{
1294 if (clip_star.owned || clip_plus.owned)
1295 {
1296 x11_export_final_selection();
1297 if (clip_star.owned)
1298 clip_lose_selection(&clip_star);
1299 if (clip_plus.owned)
1300 clip_lose_selection(&clip_plus);
1301 if (x11_display != NULL)
1302 XFlush(x11_display);
1303 }
1304}
Bram Moolenaar1a0316c2013-03-13 17:50:25 +01001305
Bram Moolenaar090cfc12013-03-19 12:35:42 +01001306# ifdef USE_SYSTEM
Bram Moolenaar1a0316c2013-03-13 17:50:25 +01001307/*
1308 * Save clipboard text to restore later.
1309 */
1310 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01001311save_clipboard(void)
Bram Moolenaar1a0316c2013-03-13 17:50:25 +01001312{
1313 if (clip_star.owned)
1314 clip_star_save = get_register('*', TRUE);
1315 if (clip_plus.owned)
1316 clip_plus_save = get_register('+', TRUE);
1317}
1318
1319/*
1320 * Restore clipboard text if no one own the X selection.
1321 */
1322 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01001323restore_clipboard(void)
Bram Moolenaar1a0316c2013-03-13 17:50:25 +01001324{
1325 if (clip_star_save != NULL)
1326 {
1327 if (!clip_gen_owner_exists(&clip_star))
1328 put_register('*', clip_star_save);
1329 else
1330 free_register(clip_star_save);
1331 clip_star_save = NULL;
1332 }
1333 if (clip_plus_save != NULL)
1334 {
1335 if (!clip_gen_owner_exists(&clip_plus))
1336 put_register('+', clip_plus_save);
1337 else
1338 free_register(clip_plus_save);
1339 clip_plus_save = NULL;
1340 }
1341}
Bram Moolenaar090cfc12013-03-19 12:35:42 +01001342# endif
Bram Moolenaar62b42182010-09-21 22:09:37 +02001343#endif
1344
Bram Moolenaar071d4272004-06-13 20:20:40 +00001345/*
1346 * If the machine has job control, use it to suspend the program,
1347 * otherwise fake it by starting a new shell.
1348 */
1349 void
Bram Moolenaar05540972016-01-30 20:31:25 +01001350mch_suspend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001351{
1352 /* BeOS does have SIGTSTP, but it doesn't work. */
1353#if defined(SIGTSTP) && !defined(__BEOS__)
Bram Moolenaar2e310482018-08-21 13:09:10 +02001354 in_mch_suspend = TRUE;
1355
Bram Moolenaar071d4272004-06-13 20:20:40 +00001356 out_flush(); /* needed to make cursor visible on some systems */
1357 settmode(TMODE_COOK);
1358 out_flush(); /* needed to disable mouse on some systems */
1359
1360# if defined(FEAT_CLIPBOARD) && defined(FEAT_X11)
Bram Moolenaar62b42182010-09-21 22:09:37 +02001361 loose_clipboard();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001362# endif
Bram Moolenaar2e310482018-08-21 13:09:10 +02001363# if defined(SIGCONT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001364 sigcont_received = FALSE;
1365# endif
Bram Moolenaar2e310482018-08-21 13:09:10 +02001366
Bram Moolenaar071d4272004-06-13 20:20:40 +00001367 kill(0, SIGTSTP); /* send ourselves a STOP signal */
Bram Moolenaar2e310482018-08-21 13:09:10 +02001368
1369# if defined(SIGCONT)
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001370 /*
1371 * Wait for the SIGCONT signal to be handled. It generally happens
Bram Moolenaar2e310482018-08-21 13:09:10 +02001372 * immediately, but somehow not all the time, probably because it's handled
1373 * in another thread. Do not call pause() because there would be race
1374 * condition which would hang Vim if signal happened in between the test of
1375 * sigcont_received and the call to pause(). If signal is not yet received,
1376 * sleep 0, 1, 2, 3 ms. Don't bother waiting further if signal is not
1377 * received after 1+2+3 ms (not expected to happen).
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001378 */
1379 {
Bram Moolenaar262735e2009-07-14 10:20:22 +00001380 long wait_time;
Bram Moolenaar2e310482018-08-21 13:09:10 +02001381
Bram Moolenaar262735e2009-07-14 10:20:22 +00001382 for (wait_time = 0; !sigcont_received && wait_time <= 3L; wait_time++)
Bram Moolenaar262735e2009-07-14 10:20:22 +00001383 mch_delay(wait_time, FALSE);
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001384 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001385# endif
Bram Moolenaar2e310482018-08-21 13:09:10 +02001386 in_mch_suspend = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001387
Bram Moolenaar2e310482018-08-21 13:09:10 +02001388 after_sigcont();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001389#else
1390 suspend_shell();
1391#endif
1392}
1393
1394 void
Bram Moolenaar05540972016-01-30 20:31:25 +01001395mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001396{
1397 Columns = 80;
1398 Rows = 24;
1399
1400 out_flush();
1401 set_signals();
Bram Moolenaardf177f62005-02-22 08:39:57 +00001402
Bram Moolenaar56718732006-03-15 22:53:57 +00001403#ifdef MACOS_CONVERT
Bram Moolenaardf177f62005-02-22 08:39:57 +00001404 mac_conv_init();
1405#endif
Bram Moolenaar693e40c2013-02-26 14:56:42 +01001406#ifdef FEAT_CYGWIN_WIN32_CLIPBOARD
1407 win_clip_init();
1408#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001409}
1410
1411 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01001412set_signals(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001413{
1414#if defined(SIGWINCH)
1415 /*
1416 * WINDOW CHANGE signal is handled with sig_winch().
1417 */
1418 signal(SIGWINCH, (RETSIGTYPE (*)())sig_winch);
1419#endif
1420
1421 /*
1422 * We want the STOP signal to work, to make mch_suspend() work.
1423 * For "rvim" the STOP signal is ignored.
1424 */
1425#ifdef SIGTSTP
1426 signal(SIGTSTP, restricted ? SIG_IGN : SIG_DFL);
1427#endif
Bram Moolenaar2e310482018-08-21 13:09:10 +02001428#if defined(SIGCONT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001429 signal(SIGCONT, sigcont_handler);
1430#endif
1431
1432 /*
1433 * We want to ignore breaking of PIPEs.
1434 */
1435#ifdef SIGPIPE
1436 signal(SIGPIPE, SIG_IGN);
1437#endif
1438
Bram Moolenaar071d4272004-06-13 20:20:40 +00001439#ifdef SIGINT
Bram Moolenaardf177f62005-02-22 08:39:57 +00001440 catch_int_signal();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001441#endif
1442
1443 /*
1444 * Ignore alarm signals (Perl's alarm() generates it).
1445 */
1446#ifdef SIGALRM
1447 signal(SIGALRM, SIG_IGN);
1448#endif
1449
1450 /*
1451 * Catch SIGPWR (power failure?) to preserve the swap files, so that no
1452 * work will be lost.
1453 */
1454#ifdef SIGPWR
1455 signal(SIGPWR, (RETSIGTYPE (*)())catch_sigpwr);
1456#endif
1457
1458 /*
1459 * Arrange for other signals to gracefully shutdown Vim.
1460 */
1461 catch_signals(deathtrap, SIG_ERR);
1462
1463#if defined(FEAT_GUI) && defined(SIGHUP)
1464 /*
1465 * When the GUI is running, ignore the hangup signal.
1466 */
1467 if (gui.in_use)
1468 signal(SIGHUP, SIG_IGN);
1469#endif
1470}
1471
Bram Moolenaardf177f62005-02-22 08:39:57 +00001472#if defined(SIGINT) || defined(PROTO)
1473/*
1474 * Catch CTRL-C (only works while in Cooked mode).
1475 */
1476 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01001477catch_int_signal(void)
Bram Moolenaardf177f62005-02-22 08:39:57 +00001478{
1479 signal(SIGINT, (RETSIGTYPE (*)())catch_sigint);
1480}
1481#endif
1482
Bram Moolenaar071d4272004-06-13 20:20:40 +00001483 void
Bram Moolenaar05540972016-01-30 20:31:25 +01001484reset_signals(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001485{
1486 catch_signals(SIG_DFL, SIG_DFL);
Bram Moolenaar2e310482018-08-21 13:09:10 +02001487#if defined(SIGCONT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001488 /* SIGCONT isn't in the list, because its default action is ignore */
1489 signal(SIGCONT, SIG_DFL);
1490#endif
1491}
1492
1493 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01001494catch_signals(
1495 RETSIGTYPE (*func_deadly)(),
1496 RETSIGTYPE (*func_other)())
Bram Moolenaar071d4272004-06-13 20:20:40 +00001497{
1498 int i;
1499
1500 for (i = 0; signal_info[i].sig != -1; i++)
1501 if (signal_info[i].deadly)
1502 {
1503#if defined(HAVE_SIGALTSTACK) && defined(HAVE_SIGACTION)
1504 struct sigaction sa;
1505
1506 /* Setup to use the alternate stack for the signal function. */
1507 sa.sa_handler = func_deadly;
1508 sigemptyset(&sa.sa_mask);
1509# if defined(__linux__) && defined(_REENTRANT)
1510 /* On Linux, with glibc compiled for kernel 2.2, there is a bug in
1511 * thread handling in combination with using the alternate stack:
1512 * pthread library functions try to use the stack pointer to
1513 * identify the current thread, causing a SEGV signal, which
1514 * recursively calls deathtrap() and hangs. */
1515 sa.sa_flags = 0;
1516# else
1517 sa.sa_flags = SA_ONSTACK;
1518# endif
1519 sigaction(signal_info[i].sig, &sa, NULL);
1520#else
1521# if defined(HAVE_SIGALTSTACK) && defined(HAVE_SIGVEC)
1522 struct sigvec sv;
1523
1524 /* Setup to use the alternate stack for the signal function. */
1525 sv.sv_handler = func_deadly;
1526 sv.sv_mask = 0;
1527 sv.sv_flags = SV_ONSTACK;
1528 sigvec(signal_info[i].sig, &sv, NULL);
1529# else
1530 signal(signal_info[i].sig, func_deadly);
1531# endif
1532#endif
1533 }
1534 else if (func_other != SIG_ERR)
1535 signal(signal_info[i].sig, func_other);
1536}
1537
Bram Moolenaarbb09ceb2016-10-18 16:27:23 +02001538#ifdef HAVE_SIGPROCMASK
1539 static void
1540block_signals(sigset_t *set)
1541{
1542 sigset_t newset;
1543 int i;
1544
1545 sigemptyset(&newset);
1546
1547 for (i = 0; signal_info[i].sig != -1; i++)
1548 sigaddset(&newset, signal_info[i].sig);
1549
Bram Moolenaar2e310482018-08-21 13:09:10 +02001550# if defined(SIGCONT)
Bram Moolenaarbb09ceb2016-10-18 16:27:23 +02001551 /* SIGCONT isn't in the list, because its default action is ignore */
1552 sigaddset(&newset, SIGCONT);
1553# endif
1554
1555 sigprocmask(SIG_BLOCK, &newset, set);
1556}
1557
1558 static void
1559unblock_signals(sigset_t *set)
1560{
1561 sigprocmask(SIG_SETMASK, set, NULL);
1562}
1563#endif
1564
Bram Moolenaar071d4272004-06-13 20:20:40 +00001565/*
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001566 * Handling of SIGHUP, SIGQUIT and SIGTERM:
Bram Moolenaar9e1d2832007-05-06 12:51:41 +00001567 * "when" == a signal: when busy, postpone and return FALSE, otherwise
1568 * return TRUE
1569 * "when" == SIGNAL_BLOCK: Going to be busy, block signals
1570 * "when" == SIGNAL_UNBLOCK: Going to wait, unblock signals, use postponed
Bram Moolenaar67c53842010-05-22 18:28:27 +02001571 * signal
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001572 * Returns TRUE when Vim should exit.
1573 */
1574 int
Bram Moolenaar05540972016-01-30 20:31:25 +01001575vim_handle_signal(int sig)
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001576{
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001577 static int got_signal = 0;
1578 static int blocked = TRUE;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001579
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001580 switch (sig)
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001581 {
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001582 case SIGNAL_BLOCK: blocked = TRUE;
1583 break;
1584
1585 case SIGNAL_UNBLOCK: blocked = FALSE;
1586 if (got_signal != 0)
1587 {
1588 kill(getpid(), got_signal);
1589 got_signal = 0;
1590 }
1591 break;
1592
1593 default: if (!blocked)
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001594 return TRUE; /* exit! */
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001595 got_signal = sig;
1596#ifdef SIGPWR
1597 if (sig != SIGPWR)
1598#endif
1599 got_int = TRUE; /* break any loops */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001600 break;
1601 }
1602 return FALSE;
1603}
1604
1605/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00001606 * Check_win checks whether we have an interactive stdout.
1607 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001608 int
Bram Moolenaar05540972016-01-30 20:31:25 +01001609mch_check_win(int argc UNUSED, char **argv UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001610{
Bram Moolenaar071d4272004-06-13 20:20:40 +00001611 if (isatty(1))
1612 return OK;
1613 return FAIL;
1614}
1615
1616/*
1617 * Return TRUE if the input comes from a terminal, FALSE otherwise.
1618 */
1619 int
Bram Moolenaar05540972016-01-30 20:31:25 +01001620mch_input_isatty(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001621{
1622 if (isatty(read_cmd_fd))
1623 return TRUE;
1624 return FALSE;
1625}
1626
1627#ifdef FEAT_X11
1628
Bram Moolenaar833eb1d2016-11-24 17:22:50 +01001629# if defined(ELAPSED_TIMEVAL) \
Bram Moolenaar071d4272004-06-13 20:20:40 +00001630 && (defined(FEAT_XCLIPBOARD) || defined(FEAT_TITLE))
1631
Bram Moolenaar071d4272004-06-13 20:20:40 +00001632/*
1633 * Give a message about the elapsed time for opening the X window.
1634 */
1635 static void
Bram Moolenaar833eb1d2016-11-24 17:22:50 +01001636xopen_message(long elapsed_msec)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001637{
Bram Moolenaar833eb1d2016-11-24 17:22:50 +01001638 smsg((char_u *)_("Opening the X display took %ld msec"), elapsed_msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001639}
1640# endif
1641#endif
1642
1643#if defined(FEAT_X11) && (defined(FEAT_TITLE) || defined(FEAT_XCLIPBOARD))
1644/*
1645 * A few functions shared by X11 title and clipboard code.
1646 */
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +01001647static int x_error_handler(Display *dpy, XErrorEvent *error_event);
1648static int x_error_check(Display *dpy, XErrorEvent *error_event);
1649static int x_connect_to_server(void);
1650static int test_x11_window(Display *dpy);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001651
1652static int got_x_error = FALSE;
1653
1654/*
1655 * X Error handler, otherwise X just exits! (very rude) -- webb
1656 */
1657 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01001658x_error_handler(Display *dpy, XErrorEvent *error_event)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001659{
Bram Moolenaar843ee412004-06-30 16:16:41 +00001660 XGetErrorText(dpy, error_event->error_code, (char *)IObuff, IOSIZE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001661 STRCAT(IObuff, _("\nVim: Got X error\n"));
1662
1663 /* We cannot print a message and continue, because no X calls are allowed
1664 * here (causes my system to hang). Silently continuing might be an
1665 * alternative... */
1666 preserve_exit(); /* preserve files and exit */
1667
1668 return 0; /* NOTREACHED */
1669}
1670
1671/*
1672 * Another X Error handler, just used to check for errors.
1673 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001674 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01001675x_error_check(Display *dpy UNUSED, XErrorEvent *error_event UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001676{
1677 got_x_error = TRUE;
1678 return 0;
1679}
1680
1681#if defined(FEAT_X11) && defined(FEAT_XCLIPBOARD)
1682# if defined(HAVE_SETJMP_H)
1683/*
1684 * An X IO Error handler, used to catch error while opening the display.
1685 */
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +01001686static int x_IOerror_check(Display *dpy);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001687
Bram Moolenaar071d4272004-06-13 20:20:40 +00001688 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01001689x_IOerror_check(Display *dpy UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001690{
1691 /* This function should not return, it causes exit(). Longjump instead. */
1692 LONGJMP(lc_jump_env, 1);
Bram Moolenaarfe17e762013-06-29 14:17:02 +02001693# if defined(VMS) || defined(__CYGWIN__) || defined(__CYGWIN32__)
Bram Moolenaarb4990bf2010-02-11 18:19:38 +01001694 return 0; /* avoid the compiler complains about missing return value */
1695# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001696}
1697# endif
1698
1699/*
1700 * An X IO Error handler, used to catch terminal errors.
1701 */
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +01001702static int x_IOerror_handler(Display *dpy);
1703static void may_restore_clipboard(void);
Bram Moolenaarb1e26502014-11-19 18:48:46 +01001704static int xterm_dpy_was_reset = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001705
Bram Moolenaar071d4272004-06-13 20:20:40 +00001706 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01001707x_IOerror_handler(Display *dpy UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001708{
1709 xterm_dpy = NULL;
Bram Moolenaarb1e26502014-11-19 18:48:46 +01001710 xterm_dpy_was_reset = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001711 x11_window = 0;
1712 x11_display = NULL;
1713 xterm_Shell = (Widget)0;
1714
1715 /* This function should not return, it causes exit(). Longjump instead. */
1716 LONGJMP(x_jump_env, 1);
Bram Moolenaarfe17e762013-06-29 14:17:02 +02001717# if defined(VMS) || defined(__CYGWIN__) || defined(__CYGWIN32__)
Bram Moolenaarb4990bf2010-02-11 18:19:38 +01001718 return 0; /* avoid the compiler complains about missing return value */
1719# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001720}
Bram Moolenaarb1e26502014-11-19 18:48:46 +01001721
1722/*
1723 * If the X11 connection was lost try to restore it.
1724 * Helps when the X11 server was stopped and restarted while Vim was inactive
Bram Moolenaarcaad4f02014-12-17 14:36:14 +01001725 * (e.g. through tmux).
Bram Moolenaarb1e26502014-11-19 18:48:46 +01001726 */
1727 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01001728may_restore_clipboard(void)
Bram Moolenaarb1e26502014-11-19 18:48:46 +01001729{
1730 if (xterm_dpy_was_reset)
1731 {
1732 xterm_dpy_was_reset = FALSE;
Bram Moolenaar527a6782014-12-17 17:59:31 +01001733
1734# ifndef LESSTIF_VERSION
1735 /* This has been reported to avoid Vim getting stuck. */
1736 if (app_context != (XtAppContext)NULL)
1737 {
1738 XtDestroyApplicationContext(app_context);
1739 app_context = (XtAppContext)NULL;
1740 x11_display = NULL; /* freed by XtDestroyApplicationContext() */
1741 }
1742# endif
1743
Bram Moolenaarb1e26502014-11-19 18:48:46 +01001744 setup_term_clip();
1745 get_x11_title(FALSE);
1746 }
1747}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001748#endif
1749
1750/*
1751 * Return TRUE when connection to the X server is desired.
1752 */
1753 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01001754x_connect_to_server(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001755{
Bram Moolenaar071d4272004-06-13 20:20:40 +00001756#if defined(FEAT_CLIENTSERVER)
1757 if (x_force_connect)
1758 return TRUE;
1759#endif
1760 if (x_no_connect)
1761 return FALSE;
1762
1763 /* Check for a match with "exclude:" from 'clipboard'. */
1764 if (clip_exclude_prog != NULL)
1765 {
Bram Moolenaardffa5b82014-11-19 16:38:07 +01001766 if (vim_regexec_prog(&clip_exclude_prog, FALSE, T_NAME, (colnr_T)0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001767 return FALSE;
1768 }
1769 return TRUE;
1770}
1771
1772/*
1773 * Test if "dpy" and x11_window are valid by getting the window title.
1774 * I don't actually want it yet, so there may be a simpler call to use, but
1775 * this will cause the error handler x_error_check() to be called if anything
1776 * is wrong, such as the window pointer being invalid (as can happen when the
1777 * user changes his DISPLAY, but not his WINDOWID) -- webb
1778 */
1779 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01001780test_x11_window(Display *dpy)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001781{
1782 int (*old_handler)();
1783 XTextProperty text_prop;
1784
1785 old_handler = XSetErrorHandler(x_error_check);
1786 got_x_error = FALSE;
1787 if (XGetWMName(dpy, x11_window, &text_prop))
1788 XFree((void *)text_prop.value);
1789 XSync(dpy, False);
1790 (void)XSetErrorHandler(old_handler);
1791
1792 if (p_verbose > 0 && got_x_error)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00001793 verb_msg((char_u *)_("Testing the X display failed"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00001794
1795 return (got_x_error ? FAIL : OK);
1796}
1797#endif
1798
1799#ifdef FEAT_TITLE
1800
1801#ifdef FEAT_X11
1802
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +01001803static int get_x11_thing(int get_title, int test_only);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001804
1805/*
1806 * try to get x11 window and display
1807 *
1808 * return FAIL for failure, OK otherwise
1809 */
1810 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01001811get_x11_windis(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001812{
1813 char *winid;
1814 static int result = -1;
1815#define XD_NONE 0 /* x11_display not set here */
1816#define XD_HERE 1 /* x11_display opened here */
1817#define XD_GUI 2 /* x11_display used from gui.dpy */
1818#define XD_XTERM 3 /* x11_display used from xterm_dpy */
1819 static int x11_display_from = XD_NONE;
1820 static int did_set_error_handler = FALSE;
1821
1822 if (!did_set_error_handler)
1823 {
1824 /* X just exits if it finds an error otherwise! */
1825 (void)XSetErrorHandler(x_error_handler);
1826 did_set_error_handler = TRUE;
1827 }
1828
Bram Moolenaar9372a112005-12-06 19:59:18 +00001829#if defined(FEAT_GUI_X11) || defined(FEAT_GUI_GTK)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001830 if (gui.in_use)
1831 {
1832 /*
1833 * If the X11 display was opened here before, for the window where Vim
1834 * was started, close that one now to avoid a memory leak.
1835 */
1836 if (x11_display_from == XD_HERE && x11_display != NULL)
1837 {
1838 XCloseDisplay(x11_display);
1839 x11_display_from = XD_NONE;
1840 }
1841 if (gui_get_x11_windis(&x11_window, &x11_display) == OK)
1842 {
1843 x11_display_from = XD_GUI;
1844 return OK;
1845 }
1846 x11_display = NULL;
1847 return FAIL;
1848 }
1849 else if (x11_display_from == XD_GUI)
1850 {
1851 /* GUI must have stopped somehow, clear x11_display */
1852 x11_window = 0;
1853 x11_display = NULL;
1854 x11_display_from = XD_NONE;
1855 }
1856#endif
1857
1858 /* When started with the "-X" argument, don't try connecting. */
1859 if (!x_connect_to_server())
1860 return FAIL;
1861
1862 /*
1863 * If WINDOWID not set, should try another method to find out
1864 * what the current window number is. The only code I know for
1865 * this is very complicated.
1866 * We assume that zero is invalid for WINDOWID.
1867 */
1868 if (x11_window == 0 && (winid = getenv("WINDOWID")) != NULL)
1869 x11_window = (Window)atol(winid);
1870
1871#ifdef FEAT_XCLIPBOARD
1872 if (xterm_dpy != NULL && x11_window != 0)
1873 {
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00001874 /* We may have checked it already, but Gnome terminal can move us to
1875 * another window, so we need to check every time. */
1876 if (x11_display_from != XD_XTERM)
1877 {
1878 /*
1879 * If the X11 display was opened here before, for the window where
1880 * Vim was started, close that one now to avoid a memory leak.
1881 */
1882 if (x11_display_from == XD_HERE && x11_display != NULL)
1883 XCloseDisplay(x11_display);
1884 x11_display = xterm_dpy;
1885 x11_display_from = XD_XTERM;
1886 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001887 if (test_x11_window(x11_display) == FAIL)
1888 {
1889 /* probably bad $WINDOWID */
1890 x11_window = 0;
1891 x11_display = NULL;
1892 x11_display_from = XD_NONE;
1893 return FAIL;
1894 }
1895 return OK;
1896 }
1897#endif
1898
1899 if (x11_window == 0 || x11_display == NULL)
1900 result = -1;
1901
1902 if (result != -1) /* Have already been here and set this */
1903 return result; /* Don't do all these X calls again */
1904
1905 if (x11_window != 0 && x11_display == NULL)
1906 {
1907#ifdef SET_SIG_ALARM
1908 RETSIGTYPE (*sig_save)();
1909#endif
1910#if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
1911 struct timeval start_tv;
1912
1913 if (p_verbose > 0)
1914 gettimeofday(&start_tv, NULL);
1915#endif
1916
1917#ifdef SET_SIG_ALARM
1918 /*
1919 * Opening the Display may hang if the DISPLAY setting is wrong, or
1920 * the network connection is bad. Set an alarm timer to get out.
1921 */
1922 sig_alarm_called = FALSE;
1923 sig_save = (RETSIGTYPE (*)())signal(SIGALRM,
1924 (RETSIGTYPE (*)())sig_alarm);
1925 alarm(2);
1926#endif
1927 x11_display = XOpenDisplay(NULL);
1928
1929#ifdef SET_SIG_ALARM
1930 alarm(0);
1931 signal(SIGALRM, (RETSIGTYPE (*)())sig_save);
1932 if (p_verbose > 0 && sig_alarm_called)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00001933 verb_msg((char_u *)_("Opening the X display timed out"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00001934#endif
1935 if (x11_display != NULL)
1936 {
Bram Moolenaar833eb1d2016-11-24 17:22:50 +01001937# ifdef ELAPSED_FUNC
Bram Moolenaar071d4272004-06-13 20:20:40 +00001938 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00001939 {
1940 verbose_enter();
Bram Moolenaar833eb1d2016-11-24 17:22:50 +01001941 xopen_message(ELAPSED_FUNC(start_tv));
Bram Moolenaara04f10b2005-05-31 22:09:46 +00001942 verbose_leave();
1943 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001944# endif
1945 if (test_x11_window(x11_display) == FAIL)
1946 {
1947 /* Maybe window id is bad */
1948 x11_window = 0;
1949 XCloseDisplay(x11_display);
1950 x11_display = NULL;
1951 }
1952 else
1953 x11_display_from = XD_HERE;
1954 }
1955 }
1956 if (x11_window == 0 || x11_display == NULL)
1957 return (result = FAIL);
Bram Moolenaar727c8762010-10-20 19:17:48 +02001958
1959# ifdef FEAT_EVAL
1960 set_vim_var_nr(VV_WINDOWID, (long)x11_window);
1961# endif
1962
Bram Moolenaar071d4272004-06-13 20:20:40 +00001963 return (result = OK);
1964}
1965
1966/*
1967 * Determine original x11 Window Title
1968 */
1969 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01001970get_x11_title(int test_only)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001971{
Bram Moolenaar47136d72004-10-12 20:02:24 +00001972 return get_x11_thing(TRUE, test_only);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001973}
1974
1975/*
1976 * Determine original x11 Window icon
1977 */
1978 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01001979get_x11_icon(int test_only)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001980{
1981 int retval = FALSE;
1982
1983 retval = get_x11_thing(FALSE, test_only);
1984
1985 /* could not get old icon, use terminal name */
1986 if (oldicon == NULL && !test_only)
1987 {
1988 if (STRNCMP(T_NAME, "builtin_", 8) == 0)
Bram Moolenaar20de1c22009-07-22 11:28:11 +00001989 oldicon = vim_strsave(T_NAME + 8);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001990 else
Bram Moolenaar20de1c22009-07-22 11:28:11 +00001991 oldicon = vim_strsave(T_NAME);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001992 }
1993
1994 return retval;
1995}
1996
1997 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01001998get_x11_thing(
1999 int get_title, /* get title string */
2000 int test_only)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002001{
2002 XTextProperty text_prop;
2003 int retval = FALSE;
2004 Status status;
2005
2006 if (get_x11_windis() == OK)
2007 {
2008 /* Get window/icon name if any */
2009 if (get_title)
2010 status = XGetWMName(x11_display, x11_window, &text_prop);
2011 else
2012 status = XGetWMIconName(x11_display, x11_window, &text_prop);
2013
2014 /*
2015 * If terminal is xterm, then x11_window may be a child window of the
2016 * outer xterm window that actually contains the window/icon name, so
2017 * keep traversing up the tree until a window with a title/icon is
2018 * found.
2019 */
2020 /* Previously this was only done for xterm and alikes. I don't see a
2021 * reason why it would fail for other terminal emulators.
2022 * if (term_is_xterm) */
2023 {
2024 Window root;
2025 Window parent;
2026 Window win = x11_window;
2027 Window *children;
2028 unsigned int num_children;
2029
2030 while (!status || text_prop.value == NULL)
2031 {
2032 if (!XQueryTree(x11_display, win, &root, &parent, &children,
2033 &num_children))
2034 break;
2035 if (children)
2036 XFree((void *)children);
2037 if (parent == root || parent == 0)
2038 break;
2039
2040 win = parent;
2041 if (get_title)
2042 status = XGetWMName(x11_display, win, &text_prop);
2043 else
2044 status = XGetWMIconName(x11_display, win, &text_prop);
2045 }
2046 }
2047 if (status && text_prop.value != NULL)
2048 {
2049 retval = TRUE;
2050 if (!test_only)
2051 {
Bram Moolenaarf82bac32010-07-25 22:30:20 +02002052#if defined(FEAT_XFONTSET) || defined(FEAT_MBYTE)
2053 if (text_prop.encoding == XA_STRING
2054# ifdef FEAT_MBYTE
2055 && !has_mbyte
2056# endif
2057 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00002058 {
2059#endif
2060 if (get_title)
2061 oldtitle = vim_strsave((char_u *)text_prop.value);
2062 else
2063 oldicon = vim_strsave((char_u *)text_prop.value);
Bram Moolenaarf82bac32010-07-25 22:30:20 +02002064#if defined(FEAT_XFONTSET) || defined(FEAT_MBYTE)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002065 }
2066 else
2067 {
2068 char **cl;
2069 Status transform_status;
2070 int n = 0;
2071
2072 transform_status = XmbTextPropertyToTextList(x11_display,
2073 &text_prop,
2074 &cl, &n);
2075 if (transform_status >= Success && n > 0 && cl[0])
2076 {
2077 if (get_title)
2078 oldtitle = vim_strsave((char_u *) cl[0]);
2079 else
2080 oldicon = vim_strsave((char_u *) cl[0]);
2081 XFreeStringList(cl);
2082 }
2083 else
2084 {
2085 if (get_title)
2086 oldtitle = vim_strsave((char_u *)text_prop.value);
2087 else
2088 oldicon = vim_strsave((char_u *)text_prop.value);
2089 }
2090 }
2091#endif
2092 }
2093 XFree((void *)text_prop.value);
2094 }
2095 }
2096 return retval;
2097}
2098
Bram Moolenaarcbc246a2014-10-11 14:47:26 +02002099/* Xutf8 functions are not avaialble on older systems. Note that on some
2100 * systems X_HAVE_UTF8_STRING may be defined in a header file but
2101 * Xutf8SetWMProperties() is not in the X11 library. Configure checks for
2102 * that and defines HAVE_XUTF8SETWMPROPERTIES. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002103#if defined(X_HAVE_UTF8_STRING) && defined(FEAT_MBYTE)
Bram Moolenaarcbc246a2014-10-11 14:47:26 +02002104# if X_HAVE_UTF8_STRING && HAVE_XUTF8SETWMPROPERTIES
Bram Moolenaar071d4272004-06-13 20:20:40 +00002105# define USE_UTF8_STRING
2106# endif
2107#endif
2108
2109/*
2110 * Set x11 Window Title
2111 *
2112 * get_x11_windis() must be called before this and have returned OK
2113 */
2114 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01002115set_x11_title(char_u *title)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002116{
2117 /* XmbSetWMProperties() and Xutf8SetWMProperties() should use a STRING
2118 * when possible, COMPOUND_TEXT otherwise. COMPOUND_TEXT isn't
2119 * supported everywhere and STRING doesn't work for multi-byte titles.
2120 */
2121#ifdef USE_UTF8_STRING
2122 if (enc_utf8)
2123 Xutf8SetWMProperties(x11_display, x11_window, (const char *)title,
2124 NULL, NULL, 0, NULL, NULL, NULL);
2125 else
2126#endif
2127 {
2128#if XtSpecificationRelease >= 4
2129# ifdef FEAT_XFONTSET
2130 XmbSetWMProperties(x11_display, x11_window, (const char *)title,
2131 NULL, NULL, 0, NULL, NULL, NULL);
2132# else
2133 XTextProperty text_prop;
Bram Moolenaar9d75c832005-01-25 21:57:23 +00002134 char *c_title = (char *)title;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002135
2136 /* directly from example 3-18 "basicwin" of Xlib Programming Manual */
Bram Moolenaar9d75c832005-01-25 21:57:23 +00002137 (void)XStringListToTextProperty(&c_title, 1, &text_prop);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002138 XSetWMProperties(x11_display, x11_window, &text_prop,
2139 NULL, NULL, 0, NULL, NULL, NULL);
2140# endif
2141#else
2142 XStoreName(x11_display, x11_window, (char *)title);
2143#endif
2144 }
2145 XFlush(x11_display);
2146}
2147
2148/*
2149 * Set x11 Window icon
2150 *
2151 * get_x11_windis() must be called before this and have returned OK
2152 */
2153 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01002154set_x11_icon(char_u *icon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002155{
2156 /* See above for comments about using X*SetWMProperties(). */
2157#ifdef USE_UTF8_STRING
2158 if (enc_utf8)
2159 Xutf8SetWMProperties(x11_display, x11_window, NULL, (const char *)icon,
2160 NULL, 0, NULL, NULL, NULL);
2161 else
2162#endif
2163 {
2164#if XtSpecificationRelease >= 4
2165# ifdef FEAT_XFONTSET
2166 XmbSetWMProperties(x11_display, x11_window, NULL, (const char *)icon,
2167 NULL, 0, NULL, NULL, NULL);
2168# else
2169 XTextProperty text_prop;
Bram Moolenaar9d75c832005-01-25 21:57:23 +00002170 char *c_icon = (char *)icon;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002171
Bram Moolenaar9d75c832005-01-25 21:57:23 +00002172 (void)XStringListToTextProperty(&c_icon, 1, &text_prop);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002173 XSetWMProperties(x11_display, x11_window, NULL, &text_prop,
2174 NULL, 0, NULL, NULL, NULL);
2175# endif
2176#else
2177 XSetIconName(x11_display, x11_window, (char *)icon);
2178#endif
2179 }
2180 XFlush(x11_display);
2181}
2182
2183#else /* FEAT_X11 */
2184
Bram Moolenaar071d4272004-06-13 20:20:40 +00002185 static int
Bram Moolenaard14e00e2016-01-31 17:30:51 +01002186get_x11_title(int test_only UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002187{
2188 return FALSE;
2189}
2190
2191 static int
Bram Moolenaard14e00e2016-01-31 17:30:51 +01002192get_x11_icon(int test_only)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002193{
2194 if (!test_only)
2195 {
2196 if (STRNCMP(T_NAME, "builtin_", 8) == 0)
Bram Moolenaar20de1c22009-07-22 11:28:11 +00002197 oldicon = vim_strsave(T_NAME + 8);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002198 else
Bram Moolenaar20de1c22009-07-22 11:28:11 +00002199 oldicon = vim_strsave(T_NAME);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002200 }
2201 return FALSE;
2202}
2203
2204#endif /* FEAT_X11 */
2205
2206 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002207mch_can_restore_title(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002208{
2209 return get_x11_title(TRUE);
2210}
2211
2212 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002213mch_can_restore_icon(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002214{
2215 return get_x11_icon(TRUE);
2216}
2217
2218/*
2219 * Set the window title and icon.
2220 */
2221 void
Bram Moolenaar05540972016-01-30 20:31:25 +01002222mch_settitle(char_u *title, char_u *icon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002223{
2224 int type = 0;
2225 static int recursive = 0;
2226
2227 if (T_NAME == NULL) /* no terminal name (yet) */
2228 return;
2229 if (title == NULL && icon == NULL) /* nothing to do */
2230 return;
2231
2232 /* When one of the X11 functions causes a deadly signal, we get here again
2233 * recursively. Avoid hanging then (something is probably locked). */
2234 if (recursive)
2235 return;
2236 ++recursive;
2237
2238 /*
2239 * if the window ID and the display is known, we may use X11 calls
2240 */
2241#ifdef FEAT_X11
2242 if (get_x11_windis() == OK)
2243 type = 1;
2244#else
2245# if defined(FEAT_GUI_PHOTON) || defined(FEAT_GUI_MAC) || defined(FEAT_GUI_GTK)
2246 if (gui.in_use)
2247 type = 1;
2248# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002249#endif
2250
2251 /*
Bram Moolenaarf82bac32010-07-25 22:30:20 +02002252 * Note: if "t_ts" is set, title is set with escape sequence rather
Bram Moolenaar071d4272004-06-13 20:20:40 +00002253 * than x11 calls, because the x11 calls don't always work
2254 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002255 if ((type || *T_TS != NUL) && title != NULL)
2256 {
Bram Moolenaard8f0cef2018-08-19 22:20:16 +02002257 if (oldtitle_outdated)
2258 {
2259 oldtitle_outdated = FALSE;
2260 VIM_CLEAR(oldtitle);
2261 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002262 if (oldtitle == NULL
2263#ifdef FEAT_GUI
2264 && !gui.in_use
2265#endif
2266 ) /* first call but not in GUI, save title */
2267 (void)get_x11_title(FALSE);
2268
2269 if (*T_TS != NUL) /* it's OK if t_fs is empty */
2270 term_settitle(title);
2271#ifdef FEAT_X11
2272 else
2273# ifdef FEAT_GUI_GTK
2274 if (!gui.in_use) /* don't do this if GTK+ is running */
2275# endif
2276 set_x11_title(title); /* x11 */
2277#endif
Bram Moolenaar2fa15e62005-01-04 21:23:48 +00002278#if defined(FEAT_GUI_GTK) \
Bram Moolenaar071d4272004-06-13 20:20:40 +00002279 || defined(FEAT_GUI_PHOTON) || defined(FEAT_GUI_MAC)
2280 else
2281 gui_mch_settitle(title, icon);
2282#endif
2283 did_set_title = TRUE;
2284 }
2285
2286 if ((type || *T_CIS != NUL) && icon != NULL)
2287 {
2288 if (oldicon == NULL
2289#ifdef FEAT_GUI
2290 && !gui.in_use
2291#endif
2292 ) /* first call, save icon */
2293 get_x11_icon(FALSE);
2294
2295 if (*T_CIS != NUL)
2296 {
2297 out_str(T_CIS); /* set icon start */
2298 out_str_nf(icon);
2299 out_str(T_CIE); /* set icon end */
2300 out_flush();
2301 }
2302#ifdef FEAT_X11
2303 else
2304# ifdef FEAT_GUI_GTK
2305 if (!gui.in_use) /* don't do this if GTK+ is running */
2306# endif
2307 set_x11_icon(icon); /* x11 */
2308#endif
2309 did_set_icon = TRUE;
2310 }
2311 --recursive;
2312}
2313
2314/*
2315 * Restore the window/icon title.
2316 * "which" is one of:
Bram Moolenaar40385db2018-08-07 22:31:44 +02002317 * SAVE_RESTORE_TITLE only restore title
2318 * SAVE_RESTORE_ICON only restore icon
2319 * SAVE_RESTORE_BOTH restore title and icon
Bram Moolenaar071d4272004-06-13 20:20:40 +00002320 */
2321 void
Bram Moolenaar05540972016-01-30 20:31:25 +01002322mch_restore_title(int which)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002323{
2324 /* only restore the title or icon when it has been set */
Bram Moolenaar40385db2018-08-07 22:31:44 +02002325 mch_settitle(((which & SAVE_RESTORE_TITLE) && did_set_title) ?
Bram Moolenaar071d4272004-06-13 20:20:40 +00002326 (oldtitle ? oldtitle : p_titleold) : NULL,
Bram Moolenaar40385db2018-08-07 22:31:44 +02002327 ((which & SAVE_RESTORE_ICON) && did_set_icon) ? oldicon : NULL);
2328
2329 // pop and push from/to the stack
2330 term_pop_title(which);
2331 term_push_title(which);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002332}
2333
2334#endif /* FEAT_TITLE */
2335
2336/*
2337 * Return TRUE if "name" looks like some xterm name.
Bram Moolenaar3a7c85b2005-02-05 21:39:53 +00002338 * Seiichi Sato mentioned that "mlterm" works like xterm.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002339 */
2340 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002341vim_is_xterm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002342{
2343 if (name == NULL)
2344 return FALSE;
2345 return (STRNICMP(name, "xterm", 5) == 0
2346 || STRNICMP(name, "nxterm", 6) == 0
2347 || STRNICMP(name, "kterm", 5) == 0
Bram Moolenaar3a7c85b2005-02-05 21:39:53 +00002348 || STRNICMP(name, "mlterm", 6) == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00002349 || STRNICMP(name, "rxvt", 4) == 0
Bram Moolenaar995e4af2017-09-01 20:24:03 +02002350 || STRNICMP(name, "screen.xterm", 12) == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00002351 || STRCMP(name, "builtin_xterm") == 0);
2352}
2353
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00002354#if defined(FEAT_MOUSE_XTERM) || defined(PROTO)
2355/*
2356 * Return TRUE if "name" appears to be that of a terminal
2357 * known to support the xterm-style mouse protocol.
2358 * Relies on term_is_xterm having been set to its correct value.
2359 */
2360 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002361use_xterm_like_mouse(char_u *name)
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00002362{
2363 return (name != NULL
Bram Moolenaare56132b2016-08-14 18:23:21 +02002364 && (term_is_xterm
2365 || STRNICMP(name, "screen", 6) == 0
Bram Moolenaar0ba40702016-10-12 14:50:54 +02002366 || STRNICMP(name, "tmux", 4) == 0
Bram Moolenaare56132b2016-08-14 18:23:21 +02002367 || STRICMP(name, "st") == 0
2368 || STRNICMP(name, "st-", 3) == 0
2369 || STRNICMP(name, "stterm", 6) == 0));
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00002370}
2371#endif
2372
Bram Moolenaar071d4272004-06-13 20:20:40 +00002373#if defined(FEAT_MOUSE_TTY) || defined(PROTO)
2374/*
2375 * Return non-zero when using an xterm mouse, according to 'ttymouse'.
2376 * Return 1 for "xterm".
2377 * Return 2 for "xterm2".
Bram Moolenaarc8427482011-10-20 21:09:35 +02002378 * Return 3 for "urxvt".
Bram Moolenaar2b9578f2012-08-15 16:21:32 +02002379 * Return 4 for "sgr".
Bram Moolenaar071d4272004-06-13 20:20:40 +00002380 */
2381 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002382use_xterm_mouse(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002383{
Bram Moolenaar2b9578f2012-08-15 16:21:32 +02002384 if (ttym_flags == TTYM_SGR)
2385 return 4;
Bram Moolenaarc8427482011-10-20 21:09:35 +02002386 if (ttym_flags == TTYM_URXVT)
2387 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002388 if (ttym_flags == TTYM_XTERM2)
2389 return 2;
2390 if (ttym_flags == TTYM_XTERM)
2391 return 1;
2392 return 0;
2393}
2394#endif
2395
2396 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002397vim_is_iris(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002398{
2399 if (name == NULL)
2400 return FALSE;
2401 return (STRNICMP(name, "iris-ansi", 9) == 0
2402 || STRCMP(name, "builtin_iris-ansi") == 0);
2403}
2404
2405 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002406vim_is_vt300(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002407{
2408 if (name == NULL)
2409 return FALSE; /* actually all ANSI comp. terminals should be here */
Bram Moolenaard4755bb2004-09-02 19:12:26 +00002410 /* catch VT100 - VT5xx */
2411 return ((STRNICMP(name, "vt", 2) == 0
2412 && vim_strchr((char_u *)"12345", name[2]) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002413 || STRCMP(name, "builtin_vt320") == 0);
2414}
2415
2416/*
2417 * Return TRUE if "name" is a terminal for which 'ttyfast' should be set.
2418 * This should include all windowed terminal emulators.
2419 */
2420 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002421vim_is_fastterm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002422{
2423 if (name == NULL)
2424 return FALSE;
2425 if (vim_is_xterm(name) || vim_is_vt300(name) || vim_is_iris(name))
2426 return TRUE;
2427 return ( STRNICMP(name, "hpterm", 6) == 0
2428 || STRNICMP(name, "sun-cmd", 7) == 0
2429 || STRNICMP(name, "screen", 6) == 0
Bram Moolenaar0ba40702016-10-12 14:50:54 +02002430 || STRNICMP(name, "tmux", 4) == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00002431 || STRNICMP(name, "dtterm", 6) == 0);
2432}
2433
2434/*
2435 * Insert user name in s[len].
2436 * Return OK if a name found.
2437 */
2438 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002439mch_get_user_name(char_u *s, int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002440{
2441#ifdef VMS
Bram Moolenaarffb8ab02005-09-07 21:15:32 +00002442 vim_strncpy(s, (char_u *)cuserid(NULL), len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002443 return OK;
2444#else
2445 return mch_get_uname(getuid(), s, len);
2446#endif
2447}
2448
2449/*
2450 * Insert user name for "uid" in s[len].
2451 * Return OK if a name found.
2452 */
2453 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002454mch_get_uname(uid_t uid, char_u *s, int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002455{
2456#if defined(HAVE_PWD_H) && defined(HAVE_GETPWUID)
2457 struct passwd *pw;
2458
2459 if ((pw = getpwuid(uid)) != NULL
2460 && pw->pw_name != NULL && *(pw->pw_name) != NUL)
2461 {
Bram Moolenaarbbebc852005-07-18 21:47:53 +00002462 vim_strncpy(s, (char_u *)pw->pw_name, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002463 return OK;
2464 }
2465#endif
2466 sprintf((char *)s, "%d", (int)uid); /* assumes s is long enough */
2467 return FAIL; /* a number is not a name */
2468}
2469
2470/*
2471 * Insert host name is s[len].
2472 */
2473
2474#ifdef HAVE_SYS_UTSNAME_H
2475 void
Bram Moolenaar05540972016-01-30 20:31:25 +01002476mch_get_host_name(char_u *s, int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002477{
2478 struct utsname vutsname;
2479
2480 if (uname(&vutsname) < 0)
2481 *s = NUL;
2482 else
Bram Moolenaarbbebc852005-07-18 21:47:53 +00002483 vim_strncpy(s, (char_u *)vutsname.nodename, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002484}
2485#else /* HAVE_SYS_UTSNAME_H */
2486
2487# ifdef HAVE_SYS_SYSTEMINFO_H
2488# define gethostname(nam, len) sysinfo(SI_HOSTNAME, nam, len)
2489# endif
2490
2491 void
Bram Moolenaard14e00e2016-01-31 17:30:51 +01002492mch_get_host_name(char_u *s, int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002493{
2494# ifdef VAXC
2495 vaxc$gethostname((char *)s, len);
2496# else
2497 gethostname((char *)s, len);
2498# endif
2499 s[len - 1] = NUL; /* make sure it's terminated */
2500}
2501#endif /* HAVE_SYS_UTSNAME_H */
2502
2503/*
2504 * return process ID
2505 */
2506 long
Bram Moolenaar05540972016-01-30 20:31:25 +01002507mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002508{
2509 return (long)getpid();
2510}
2511
2512#if !defined(HAVE_STRERROR) && defined(USE_GETCWD)
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +01002513static char *strerror(int);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002514
2515 static char *
Bram Moolenaar05540972016-01-30 20:31:25 +01002516strerror(int err)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002517{
2518 extern int sys_nerr;
2519 extern char *sys_errlist[];
2520 static char er[20];
2521
2522 if (err > 0 && err < sys_nerr)
2523 return (sys_errlist[err]);
2524 sprintf(er, "Error %d", err);
2525 return er;
2526}
2527#endif
2528
2529/*
2530 * Get name of current directory into buffer 'buf' of length 'len' bytes.
2531 * Return OK for success, FAIL for failure.
2532 */
2533 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002534mch_dirname(char_u *buf, int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002535{
2536#if defined(USE_GETCWD)
2537 if (getcwd((char *)buf, len) == NULL)
2538 {
2539 STRCPY(buf, strerror(errno));
2540 return FAIL;
2541 }
2542 return OK;
2543#else
2544 return (getwd((char *)buf) != NULL ? OK : FAIL);
2545#endif
2546}
2547
Bram Moolenaar071d4272004-06-13 20:20:40 +00002548/*
Bram Moolenaar3d20ca12006-11-28 16:43:58 +00002549 * Get absolute file name into "buf[len]".
Bram Moolenaar071d4272004-06-13 20:20:40 +00002550 *
2551 * return FAIL for failure, OK for success
2552 */
2553 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002554mch_FullName(
2555 char_u *fname,
2556 char_u *buf,
2557 int len,
2558 int force) /* also expand when already absolute path */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002559{
2560 int l;
Bram Moolenaar38323e42007-03-06 19:22:53 +00002561#ifdef HAVE_FCHDIR
Bram Moolenaar071d4272004-06-13 20:20:40 +00002562 int fd = -1;
2563 static int dont_fchdir = FALSE; /* TRUE when fchdir() doesn't work */
Bram Moolenaar38323e42007-03-06 19:22:53 +00002564#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002565 char_u olddir[MAXPATHL];
2566 char_u *p;
2567 int retval = OK;
Bram Moolenaarbf820722008-06-21 11:12:49 +00002568#ifdef __CYGWIN__
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00002569 char_u posix_fname[MAXPATHL]; /* Cygwin docs mention MAX_PATH, but
2570 it's not always defined */
Bram Moolenaarbf820722008-06-21 11:12:49 +00002571#endif
2572
Bram Moolenaar38323e42007-03-06 19:22:53 +00002573#ifdef VMS
2574 fname = vms_fixfilename(fname);
2575#endif
2576
Bram Moolenaara2442432007-04-26 14:26:37 +00002577#ifdef __CYGWIN__
2578 /*
2579 * This helps for when "/etc/hosts" is a symlink to "c:/something/hosts".
2580 */
Bram Moolenaar0d1498e2008-06-29 12:00:49 +00002581# if CYGWIN_VERSION_DLL_MAJOR >= 1007
Bram Moolenaar06b07342015-12-31 22:26:28 +01002582 /* Use CCP_RELATIVE to avoid that it sometimes returns a path that ends in
2583 * a forward slash. */
2584 cygwin_conv_path(CCP_WIN_A_TO_POSIX | CCP_RELATIVE,
2585 fname, posix_fname, MAXPATHL);
Bram Moolenaar0d1498e2008-06-29 12:00:49 +00002586# else
Bram Moolenaarbf820722008-06-21 11:12:49 +00002587 cygwin_conv_to_posix_path(fname, posix_fname);
Bram Moolenaar0d1498e2008-06-29 12:00:49 +00002588# endif
Bram Moolenaarbf820722008-06-21 11:12:49 +00002589 fname = posix_fname;
Bram Moolenaara2442432007-04-26 14:26:37 +00002590#endif
2591
Bram Moolenaare3303cb2015-12-31 18:29:46 +01002592 /* Expand it if forced or not an absolute path.
2593 * Do not do it for "/file", the result is always "/". */
2594 if ((force || !mch_isFullName(fname))
2595 && ((p = vim_strrchr(fname, '/')) == NULL || p != fname))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002596 {
2597 /*
2598 * If the file name has a path, change to that directory for a moment,
2599 * and then do the getwd() (and get back to where we were).
2600 * This will get the correct path name with "../" things.
2601 */
Bram Moolenaare3303cb2015-12-31 18:29:46 +01002602 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002603 {
Bram Moolenaar38323e42007-03-06 19:22:53 +00002604#ifdef HAVE_FCHDIR
Bram Moolenaar071d4272004-06-13 20:20:40 +00002605 /*
2606 * Use fchdir() if possible, it's said to be faster and more
2607 * reliable. But on SunOS 4 it might not work. Check this by
2608 * doing a fchdir() right now.
2609 */
2610 if (!dont_fchdir)
2611 {
2612 fd = open(".", O_RDONLY | O_EXTRA, 0);
2613 if (fd >= 0 && fchdir(fd) < 0)
2614 {
2615 close(fd);
2616 fd = -1;
2617 dont_fchdir = TRUE; /* don't try again */
2618 }
2619 }
Bram Moolenaar38323e42007-03-06 19:22:53 +00002620#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002621
2622 /* Only change directory when we are sure we can return to where
2623 * we are now. After doing "su" chdir(".") might not work. */
2624 if (
Bram Moolenaar38323e42007-03-06 19:22:53 +00002625#ifdef HAVE_FCHDIR
Bram Moolenaar071d4272004-06-13 20:20:40 +00002626 fd < 0 &&
Bram Moolenaar38323e42007-03-06 19:22:53 +00002627#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002628 (mch_dirname(olddir, MAXPATHL) == FAIL
2629 || mch_chdir((char *)olddir) != 0))
2630 {
2631 p = NULL; /* can't get current dir: don't chdir */
2632 retval = FAIL;
2633 }
2634 else
2635 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00002636 /* The directory is copied into buf[], to be able to remove
2637 * the file name without changing it (could be a string in
2638 * read-only memory) */
2639 if (p - fname >= len)
2640 retval = FAIL;
2641 else
2642 {
Bram Moolenaarbbebc852005-07-18 21:47:53 +00002643 vim_strncpy(buf, fname, p - fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002644 if (mch_chdir((char *)buf))
2645 retval = FAIL;
2646 else
2647 fname = p + 1;
2648 *buf = NUL;
2649 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002650 }
2651 }
2652 if (mch_dirname(buf, len) == FAIL)
2653 {
2654 retval = FAIL;
2655 *buf = NUL;
2656 }
2657 if (p != NULL)
2658 {
Bram Moolenaar38323e42007-03-06 19:22:53 +00002659#ifdef HAVE_FCHDIR
Bram Moolenaar071d4272004-06-13 20:20:40 +00002660 if (fd >= 0)
2661 {
Bram Moolenaar25724922009-07-14 15:38:41 +00002662 if (p_verbose >= 5)
2663 {
2664 verbose_enter();
2665 MSG("fchdir() to previous dir");
2666 verbose_leave();
2667 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002668 l = fchdir(fd);
2669 close(fd);
2670 }
2671 else
Bram Moolenaar38323e42007-03-06 19:22:53 +00002672#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002673 l = mch_chdir((char *)olddir);
2674 if (l != 0)
2675 EMSG(_(e_prev_dir));
2676 }
2677
2678 l = STRLEN(buf);
Bram Moolenaardac75692012-10-14 04:35:45 +02002679 if (l >= len - 1)
2680 retval = FAIL; /* no space for trailing "/" */
Bram Moolenaar38323e42007-03-06 19:22:53 +00002681#ifndef VMS
Bram Moolenaardac75692012-10-14 04:35:45 +02002682 else if (l > 0 && buf[l - 1] != '/' && *fname != NUL
Bram Moolenaar071d4272004-06-13 20:20:40 +00002683 && STRCMP(fname, ".") != 0)
Bram Moolenaardac75692012-10-14 04:35:45 +02002684 STRCAT(buf, "/");
Bram Moolenaar38323e42007-03-06 19:22:53 +00002685#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002686 }
Bram Moolenaar3d20ca12006-11-28 16:43:58 +00002687
Bram Moolenaar071d4272004-06-13 20:20:40 +00002688 /* Catch file names which are too long. */
Bram Moolenaar78a15312009-05-15 19:33:18 +00002689 if (retval == FAIL || (int)(STRLEN(buf) + STRLEN(fname)) >= len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002690 return FAIL;
2691
2692 /* Do not append ".", "/dir/." is equal to "/dir". */
2693 if (STRCMP(fname, ".") != 0)
2694 STRCAT(buf, fname);
2695
2696 return OK;
2697}
2698
2699/*
2700 * Return TRUE if "fname" does not depend on the current directory.
2701 */
2702 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002703mch_isFullName(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002704{
Bram Moolenaara06ecab2016-07-16 14:47:36 +02002705#ifdef VMS
Bram Moolenaar071d4272004-06-13 20:20:40 +00002706 return ( fname[0] == '/' || fname[0] == '.' ||
2707 strchr((char *)fname,':') || strchr((char *)fname,'"') ||
2708 (strchr((char *)fname,'[') && strchr((char *)fname,']'))||
2709 (strchr((char *)fname,'<') && strchr((char *)fname,'>')) );
Bram Moolenaara06ecab2016-07-16 14:47:36 +02002710#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002711 return (*fname == '/' || *fname == '~');
Bram Moolenaar071d4272004-06-13 20:20:40 +00002712#endif
2713}
2714
Bram Moolenaar24552be2005-12-10 20:17:30 +00002715#if defined(USE_FNAME_CASE) || defined(PROTO)
2716/*
2717 * Set the case of the file name, if it already exists. This will cause the
2718 * file name to remain exactly the same.
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00002719 * Only required for file systems where case is ignored and preserved.
Bram Moolenaar24552be2005-12-10 20:17:30 +00002720 */
Bram Moolenaar24552be2005-12-10 20:17:30 +00002721 void
Bram Moolenaar05540972016-01-30 20:31:25 +01002722fname_case(
2723 char_u *name,
2724 int len UNUSED) /* buffer size, only used when name gets longer */
Bram Moolenaar24552be2005-12-10 20:17:30 +00002725{
2726 struct stat st;
2727 char_u *slash, *tail;
2728 DIR *dirp;
2729 struct dirent *dp;
2730
Bram Moolenaarde5e2c22016-11-04 20:35:31 +01002731 if (mch_lstat((char *)name, &st) >= 0)
Bram Moolenaar24552be2005-12-10 20:17:30 +00002732 {
2733 /* Open the directory where the file is located. */
2734 slash = vim_strrchr(name, '/');
2735 if (slash == NULL)
2736 {
2737 dirp = opendir(".");
2738 tail = name;
2739 }
2740 else
2741 {
2742 *slash = NUL;
2743 dirp = opendir((char *)name);
2744 *slash = '/';
2745 tail = slash + 1;
2746 }
2747
2748 if (dirp != NULL)
2749 {
2750 while ((dp = readdir(dirp)) != NULL)
2751 {
2752 /* Only accept names that differ in case and are the same byte
2753 * length. TODO: accept different length name. */
2754 if (STRICMP(tail, dp->d_name) == 0
2755 && STRLEN(tail) == STRLEN(dp->d_name))
2756 {
2757 char_u newname[MAXPATHL + 1];
2758 struct stat st2;
2759
2760 /* Verify the inode is equal. */
2761 vim_strncpy(newname, name, MAXPATHL);
2762 vim_strncpy(newname + (tail - name), (char_u *)dp->d_name,
2763 MAXPATHL - (tail - name));
Bram Moolenaarde5e2c22016-11-04 20:35:31 +01002764 if (mch_lstat((char *)newname, &st2) >= 0
Bram Moolenaar24552be2005-12-10 20:17:30 +00002765 && st.st_ino == st2.st_ino
2766 && st.st_dev == st2.st_dev)
2767 {
2768 STRCPY(tail, dp->d_name);
2769 break;
2770 }
2771 }
2772 }
2773
2774 closedir(dirp);
2775 }
2776 }
2777}
2778#endif
2779
Bram Moolenaar071d4272004-06-13 20:20:40 +00002780/*
2781 * Get file permissions for 'name'.
2782 * Returns -1 when it doesn't exist.
2783 */
2784 long
Bram Moolenaar05540972016-01-30 20:31:25 +01002785mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002786{
2787 struct stat statb;
2788
2789 /* Keep the #ifdef outside of stat(), it may be a macro. */
2790#ifdef VMS
2791 if (stat((char *)vms_fixfilename(name), &statb))
2792#else
2793 if (stat((char *)name, &statb))
2794#endif
2795 return -1;
Bram Moolenaar708f62c2007-08-11 20:24:10 +00002796#ifdef __INTERIX
2797 /* The top bit makes the value negative, which means the file doesn't
2798 * exist. Remove the bit, we don't use it. */
2799 return statb.st_mode & ~S_ADDACE;
2800#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002801 return statb.st_mode;
Bram Moolenaar708f62c2007-08-11 20:24:10 +00002802#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002803}
2804
2805/*
Bram Moolenaarcd142e32017-11-16 17:03:45 +01002806 * Set file permission for "name" to "perm".
2807 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002808 */
2809 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002810mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002811{
2812 return (chmod((char *)
2813#ifdef VMS
2814 vms_fixfilename(name),
2815#else
2816 name,
2817#endif
2818 (mode_t)perm) == 0 ? OK : FAIL);
2819}
2820
Bram Moolenaarcd142e32017-11-16 17:03:45 +01002821#if defined(HAVE_FCHMOD) || defined(PROTO)
2822/*
2823 * Set file permission for open file "fd" to "perm".
2824 * Return FAIL for failure, OK otherwise.
2825 */
2826 int
2827mch_fsetperm(int fd, long perm)
2828{
2829 return (fchmod(fd, (mode_t)perm) == 0 ? OK : FAIL);
2830}
2831#endif
2832
Bram Moolenaar071d4272004-06-13 20:20:40 +00002833#if defined(HAVE_ACL) || defined(PROTO)
2834# ifdef HAVE_SYS_ACL_H
2835# include <sys/acl.h>
2836# endif
2837# ifdef HAVE_SYS_ACCESS_H
2838# include <sys/access.h>
2839# endif
2840
2841# ifdef HAVE_SOLARIS_ACL
2842typedef struct vim_acl_solaris_T {
2843 int acl_cnt;
2844 aclent_t *acl_entry;
2845} vim_acl_solaris_T;
2846# endif
2847
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00002848#if defined(HAVE_SELINUX) || defined(PROTO)
2849/*
2850 * Copy security info from "from_file" to "to_file".
2851 */
2852 void
Bram Moolenaar05540972016-01-30 20:31:25 +01002853mch_copy_sec(char_u *from_file, char_u *to_file)
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00002854{
2855 if (from_file == NULL)
2856 return;
2857
2858 if (selinux_enabled == -1)
2859 selinux_enabled = is_selinux_enabled();
2860
2861 if (selinux_enabled > 0)
2862 {
2863 security_context_t from_context = NULL;
2864 security_context_t to_context = NULL;
2865
2866 if (getfilecon((char *)from_file, &from_context) < 0)
2867 {
2868 /* If the filesystem doesn't support extended attributes,
2869 the original had no special security context and the
2870 target cannot have one either. */
2871 if (errno == EOPNOTSUPP)
2872 return;
2873
2874 MSG_PUTS(_("\nCould not get security context for "));
2875 msg_outtrans(from_file);
2876 msg_putchar('\n');
2877 return;
2878 }
2879 if (getfilecon((char *)to_file, &to_context) < 0)
2880 {
2881 MSG_PUTS(_("\nCould not get security context for "));
2882 msg_outtrans(to_file);
2883 msg_putchar('\n');
2884 freecon (from_context);
2885 return ;
2886 }
2887 if (strcmp(from_context, to_context) != 0)
2888 {
2889 if (setfilecon((char *)to_file, from_context) < 0)
2890 {
2891 MSG_PUTS(_("\nCould not set security context for "));
2892 msg_outtrans(to_file);
2893 msg_putchar('\n');
2894 }
2895 }
2896 freecon(to_context);
2897 freecon(from_context);
2898 }
2899}
2900#endif /* HAVE_SELINUX */
2901
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02002902#if defined(HAVE_SMACK) && !defined(PROTO)
2903/*
2904 * Copy security info from "from_file" to "to_file".
2905 */
2906 void
Bram Moolenaard14e00e2016-01-31 17:30:51 +01002907mch_copy_sec(char_u *from_file, char_u *to_file)
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02002908{
Bram Moolenaar62f167f2014-04-23 12:52:40 +02002909 static const char * const smack_copied_attributes[] =
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02002910 {
2911 XATTR_NAME_SMACK,
2912 XATTR_NAME_SMACKEXEC,
2913 XATTR_NAME_SMACKMMAP
2914 };
2915
2916 char buffer[SMACK_LABEL_LEN];
2917 const char *name;
2918 int index;
2919 int ret;
2920 ssize_t size;
2921
2922 if (from_file == NULL)
2923 return;
2924
2925 for (index = 0 ; index < (int)(sizeof(smack_copied_attributes)
2926 / sizeof(smack_copied_attributes)[0]) ; index++)
2927 {
2928 /* get the name of the attribute to copy */
2929 name = smack_copied_attributes[index];
2930
2931 /* get the value of the attribute in buffer */
2932 size = getxattr((char*)from_file, name, buffer, sizeof(buffer));
2933 if (size >= 0)
2934 {
2935 /* copy the attribute value of buffer */
2936 ret = setxattr((char*)to_file, name, buffer, (size_t)size, 0);
2937 if (ret < 0)
2938 {
Bram Moolenaar4a1314c2016-01-27 20:47:18 +01002939 vim_snprintf((char *)IObuff, IOSIZE,
2940 _("Could not set security context %s for %s"),
2941 name, to_file);
2942 msg_outtrans(IObuff);
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02002943 msg_putchar('\n');
2944 }
2945 }
2946 else
2947 {
2948 /* what reason of not having the attribute value? */
2949 switch (errno)
2950 {
2951 case ENOTSUP:
2952 /* extended attributes aren't supported or enabled */
2953 /* should a message be echoed? not sure... */
2954 return; /* leave because it isn't usefull to continue */
2955
2956 case ERANGE:
2957 default:
2958 /* no enough size OR unexpected error */
Bram Moolenaar4a1314c2016-01-27 20:47:18 +01002959 vim_snprintf((char *)IObuff, IOSIZE,
2960 _("Could not get security context %s for %s. Removing it!"),
2961 name, from_file);
2962 msg_puts(IObuff);
2963 msg_putchar('\n');
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02002964 /* FALLTHROUGH to remove the attribute */
2965
2966 case ENODATA:
2967 /* no attribute of this name */
2968 ret = removexattr((char*)to_file, name);
Bram Moolenaar57a728d2014-04-02 23:09:26 +02002969 /* Silently ignore errors, apparently this happens when
2970 * smack is not actually being used. */
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02002971 break;
2972 }
2973 }
2974 }
2975}
2976#endif /* HAVE_SMACK */
2977
Bram Moolenaar071d4272004-06-13 20:20:40 +00002978/*
2979 * Return a pointer to the ACL of file "fname" in allocated memory.
2980 * Return NULL if the ACL is not available for whatever reason.
2981 */
2982 vim_acl_T
Bram Moolenaar05540972016-01-30 20:31:25 +01002983mch_get_acl(char_u *fname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002984{
2985 vim_acl_T ret = NULL;
2986#ifdef HAVE_POSIX_ACL
2987 ret = (vim_acl_T)acl_get_file((char *)fname, ACL_TYPE_ACCESS);
2988#else
Bram Moolenaar8d462f92012-02-05 22:51:33 +01002989#ifdef HAVE_SOLARIS_ZFS_ACL
2990 acl_t *aclent;
2991
2992 if (acl_get((char *)fname, 0, &aclent) < 0)
2993 return NULL;
2994 ret = (vim_acl_T)aclent;
2995#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002996#ifdef HAVE_SOLARIS_ACL
2997 vim_acl_solaris_T *aclent;
2998
2999 aclent = malloc(sizeof(vim_acl_solaris_T));
3000 if ((aclent->acl_cnt = acl((char *)fname, GETACLCNT, 0, NULL)) < 0)
3001 {
3002 free(aclent);
3003 return NULL;
3004 }
3005 aclent->acl_entry = malloc(aclent->acl_cnt * sizeof(aclent_t));
3006 if (acl((char *)fname, GETACL, aclent->acl_cnt, aclent->acl_entry) < 0)
3007 {
3008 free(aclent->acl_entry);
3009 free(aclent);
3010 return NULL;
3011 }
3012 ret = (vim_acl_T)aclent;
3013#else
3014#if defined(HAVE_AIX_ACL)
3015 int aclsize;
3016 struct acl *aclent;
3017
3018 aclsize = sizeof(struct acl);
3019 aclent = malloc(aclsize);
3020 if (statacl((char *)fname, STX_NORMAL, aclent, aclsize) < 0)
3021 {
3022 if (errno == ENOSPC)
3023 {
3024 aclsize = aclent->acl_len;
3025 aclent = realloc(aclent, aclsize);
3026 if (statacl((char *)fname, STX_NORMAL, aclent, aclsize) < 0)
3027 {
3028 free(aclent);
3029 return NULL;
3030 }
3031 }
3032 else
3033 {
3034 free(aclent);
3035 return NULL;
3036 }
3037 }
3038 ret = (vim_acl_T)aclent;
3039#endif /* HAVE_AIX_ACL */
3040#endif /* HAVE_SOLARIS_ACL */
Bram Moolenaar8d462f92012-02-05 22:51:33 +01003041#endif /* HAVE_SOLARIS_ZFS_ACL */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003042#endif /* HAVE_POSIX_ACL */
3043 return ret;
3044}
3045
3046/*
3047 * Set the ACL of file "fname" to "acl" (unless it's NULL).
3048 */
3049 void
Bram Moolenaar05540972016-01-30 20:31:25 +01003050mch_set_acl(char_u *fname UNUSED, vim_acl_T aclent)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003051{
3052 if (aclent == NULL)
3053 return;
3054#ifdef HAVE_POSIX_ACL
3055 acl_set_file((char *)fname, ACL_TYPE_ACCESS, (acl_t)aclent);
3056#else
Bram Moolenaar8d462f92012-02-05 22:51:33 +01003057#ifdef HAVE_SOLARIS_ZFS_ACL
3058 acl_set((char *)fname, (acl_t *)aclent);
3059#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00003060#ifdef HAVE_SOLARIS_ACL
3061 acl((char *)fname, SETACL, ((vim_acl_solaris_T *)aclent)->acl_cnt,
3062 ((vim_acl_solaris_T *)aclent)->acl_entry);
3063#else
3064#ifdef HAVE_AIX_ACL
3065 chacl((char *)fname, aclent, ((struct acl *)aclent)->acl_len);
3066#endif /* HAVE_AIX_ACL */
3067#endif /* HAVE_SOLARIS_ACL */
Bram Moolenaar8d462f92012-02-05 22:51:33 +01003068#endif /* HAVE_SOLARIS_ZFS_ACL */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003069#endif /* HAVE_POSIX_ACL */
3070}
3071
3072 void
Bram Moolenaar05540972016-01-30 20:31:25 +01003073mch_free_acl(vim_acl_T aclent)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003074{
3075 if (aclent == NULL)
3076 return;
3077#ifdef HAVE_POSIX_ACL
3078 acl_free((acl_t)aclent);
3079#else
Bram Moolenaar8d462f92012-02-05 22:51:33 +01003080#ifdef HAVE_SOLARIS_ZFS_ACL
3081 acl_free((acl_t *)aclent);
3082#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00003083#ifdef HAVE_SOLARIS_ACL
3084 free(((vim_acl_solaris_T *)aclent)->acl_entry);
3085 free(aclent);
3086#else
3087#ifdef HAVE_AIX_ACL
3088 free(aclent);
3089#endif /* HAVE_AIX_ACL */
3090#endif /* HAVE_SOLARIS_ACL */
Bram Moolenaar8d462f92012-02-05 22:51:33 +01003091#endif /* HAVE_SOLARIS_ZFS_ACL */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003092#endif /* HAVE_POSIX_ACL */
3093}
3094#endif
3095
3096/*
3097 * Set hidden flag for "name".
3098 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003099 void
Bram Moolenaar05540972016-01-30 20:31:25 +01003100mch_hide(char_u *name UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003101{
3102 /* can't hide a file */
3103}
3104
3105/*
Bram Moolenaar43a34f92016-01-17 15:56:34 +01003106 * return TRUE if "name" is a directory or a symlink to a directory
Bram Moolenaar071d4272004-06-13 20:20:40 +00003107 * return FALSE if "name" is not a directory
3108 * return FALSE for error
3109 */
3110 int
Bram Moolenaar05540972016-01-30 20:31:25 +01003111mch_isdir(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003112{
3113 struct stat statb;
3114
3115 if (*name == NUL) /* Some stat()s don't flag "" as an error. */
3116 return FALSE;
3117 if (stat((char *)name, &statb))
3118 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003119 return (S_ISDIR(statb.st_mode) ? TRUE : FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003120}
3121
Bram Moolenaar43a34f92016-01-17 15:56:34 +01003122/*
3123 * return TRUE if "name" is a directory, NOT a symlink to a directory
3124 * return FALSE if "name" is not a directory
3125 * return FALSE for error
3126 */
3127 int
Bram Moolenaar05540972016-01-30 20:31:25 +01003128mch_isrealdir(char_u *name)
Bram Moolenaar43a34f92016-01-17 15:56:34 +01003129{
3130 struct stat statb;
3131
3132 if (*name == NUL) /* Some stat()s don't flag "" as an error. */
3133 return FALSE;
Bram Moolenaarde5e2c22016-11-04 20:35:31 +01003134 if (mch_lstat((char *)name, &statb))
Bram Moolenaar43a34f92016-01-17 15:56:34 +01003135 return FALSE;
Bram Moolenaar43a34f92016-01-17 15:56:34 +01003136 return (S_ISDIR(statb.st_mode) ? TRUE : FALSE);
Bram Moolenaar43a34f92016-01-17 15:56:34 +01003137}
3138
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +01003139static int executable_file(char_u *name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003140
3141/*
3142 * Return 1 if "name" is an executable file, 0 if not or it doesn't exist.
3143 */
3144 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01003145executable_file(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003146{
3147 struct stat st;
3148
3149 if (stat((char *)name, &st))
3150 return 0;
Bram Moolenaar206f0112014-03-12 16:51:55 +01003151#ifdef VMS
3152 /* Like on Unix system file can have executable rights but not necessarily
3153 * be an executable, but on Unix is not a default for an ordianry file to
3154 * have an executable flag - on VMS it is in most cases.
3155 * Therefore, this check does not have any sense - let keep us to the
3156 * conventions instead:
3157 * *.COM and *.EXE files are the executables - the rest are not. This is
3158 * not ideal but better then it was.
3159 */
3160 int vms_executable = 0;
3161 if (S_ISREG(st.st_mode) && mch_access((char *)name, X_OK) == 0)
3162 {
3163 if (strstr(vms_tolower((char*)name),".exe") != NULL
3164 || strstr(vms_tolower((char*)name),".com")!= NULL)
3165 vms_executable = 1;
3166 }
3167 return vms_executable;
3168#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00003169 return S_ISREG(st.st_mode) && mch_access((char *)name, X_OK) == 0;
Bram Moolenaar206f0112014-03-12 16:51:55 +01003170#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003171}
3172
3173/*
Bram Moolenaar2fcf6682017-03-11 20:03:42 +01003174 * Return TRUE if "name" can be found in $PATH and executed, FALSE if not.
Bram Moolenaarb5971142015-03-21 17:32:19 +01003175 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003176 * Return -1 if unknown.
3177 */
3178 int
Bram Moolenaar05540972016-01-30 20:31:25 +01003179mch_can_exe(char_u *name, char_u **path, int use_path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003180{
3181 char_u *buf;
3182 char_u *p, *e;
3183 int retval;
3184
Bram Moolenaarb5971142015-03-21 17:32:19 +01003185 /* When "use_path" is false and if it's an absolute or relative path don't
3186 * need to use $PATH. */
3187 if (!use_path || mch_isFullName(name) || (name[0] == '.'
3188 && (name[1] == '/' || (name[1] == '.' && name[2] == '/'))))
Bram Moolenaar206f0112014-03-12 16:51:55 +01003189 {
Bram Moolenaarb5971142015-03-21 17:32:19 +01003190 /* There must be a path separator, files in the current directory
3191 * can't be executed. */
3192 if (gettail(name) != name && executable_file(name))
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003193 {
3194 if (path != NULL)
3195 {
Bram Moolenaar43663192017-03-05 14:29:12 +01003196 if (name[0] != '/')
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003197 *path = FullName_save(name, TRUE);
3198 else
3199 *path = vim_strsave(name);
3200 }
3201 return TRUE;
3202 }
3203 return FALSE;
Bram Moolenaar206f0112014-03-12 16:51:55 +01003204 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003205
3206 p = (char_u *)getenv("PATH");
3207 if (p == NULL || *p == NUL)
3208 return -1;
3209 buf = alloc((unsigned)(STRLEN(name) + STRLEN(p) + 2));
3210 if (buf == NULL)
3211 return -1;
3212
3213 /*
3214 * Walk through all entries in $PATH to check if "name" exists there and
3215 * is an executable file.
3216 */
3217 for (;;)
3218 {
3219 e = (char_u *)strchr((char *)p, ':');
3220 if (e == NULL)
3221 e = p + STRLEN(p);
3222 if (e - p <= 1) /* empty entry means current dir */
3223 STRCPY(buf, "./");
3224 else
3225 {
Bram Moolenaarbbebc852005-07-18 21:47:53 +00003226 vim_strncpy(buf, p, e - p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003227 add_pathsep(buf);
3228 }
3229 STRCAT(buf, name);
3230 retval = executable_file(buf);
3231 if (retval == 1)
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003232 {
3233 if (path != NULL)
3234 {
Bram Moolenaar43663192017-03-05 14:29:12 +01003235 if (buf[0] != '/')
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003236 *path = FullName_save(buf, TRUE);
3237 else
3238 *path = vim_strsave(buf);
3239 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003240 break;
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003241 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003242
3243 if (*e != ':')
3244 break;
3245 p = e + 1;
3246 }
3247
3248 vim_free(buf);
3249 return retval;
3250}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003251
3252/*
3253 * Check what "name" is:
3254 * NODE_NORMAL: file or directory (or doesn't exist)
3255 * NODE_WRITABLE: writable device, socket, fifo, etc.
3256 * NODE_OTHER: non-writable things
3257 */
3258 int
Bram Moolenaar05540972016-01-30 20:31:25 +01003259mch_nodetype(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003260{
3261 struct stat st;
3262
3263 if (stat((char *)name, &st))
3264 return NODE_NORMAL;
3265 if (S_ISREG(st.st_mode) || S_ISDIR(st.st_mode))
3266 return NODE_NORMAL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003267 if (S_ISBLK(st.st_mode)) /* block device isn't writable */
3268 return NODE_OTHER;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003269 /* Everything else is writable? */
3270 return NODE_WRITABLE;
3271}
3272
3273 void
Bram Moolenaar05540972016-01-30 20:31:25 +01003274mch_early_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003275{
3276#ifdef HAVE_CHECK_STACK_GROWTH
3277 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003278
Bram Moolenaar071d4272004-06-13 20:20:40 +00003279 check_stack_growth((char *)&i);
3280
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00003281# ifdef HAVE_STACK_LIMIT
Bram Moolenaar071d4272004-06-13 20:20:40 +00003282 get_stack_limit();
3283# endif
3284
3285#endif
3286
3287 /*
3288 * Setup an alternative stack for signals. Helps to catch signals when
3289 * running out of stack space.
3290 * Use of sigaltstack() is preferred, it's more portable.
3291 * Ignore any errors.
3292 */
3293#if defined(HAVE_SIGALTSTACK) || defined(HAVE_SIGSTACK)
Bram Moolenaar5a221812008-11-12 12:08:45 +00003294 signal_stack = (char *)alloc(SIGSTKSZ);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003295 init_signal_stack();
3296#endif
3297}
3298
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003299#if defined(EXITFREE) || defined(PROTO)
3300 void
Bram Moolenaar05540972016-01-30 20:31:25 +01003301mch_free_mem(void)
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003302{
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00003303# if defined(FEAT_CLIPBOARD) && defined(FEAT_X11)
3304 if (clip_star.owned)
3305 clip_lose_selection(&clip_star);
3306 if (clip_plus.owned)
3307 clip_lose_selection(&clip_plus);
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003308# endif
Bram Moolenaare8208012008-06-20 09:59:25 +00003309# if defined(FEAT_X11) && defined(FEAT_XCLIPBOARD)
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003310 if (xterm_Shell != (Widget)0)
3311 XtDestroyWidget(xterm_Shell);
Bram Moolenaare8208012008-06-20 09:59:25 +00003312# ifndef LESSTIF_VERSION
3313 /* Lesstif crashes here, lose some memory */
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003314 if (xterm_dpy != NULL)
3315 XtCloseDisplay(xterm_dpy);
3316 if (app_context != (XtAppContext)NULL)
Bram Moolenaare8208012008-06-20 09:59:25 +00003317 {
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003318 XtDestroyApplicationContext(app_context);
Bram Moolenaare8208012008-06-20 09:59:25 +00003319# ifdef FEAT_X11
3320 x11_display = NULL; /* freed by XtDestroyApplicationContext() */
3321# endif
3322 }
3323# endif
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003324# endif
Bram Moolenaar0eda7ac2010-06-26 05:38:18 +02003325# if defined(FEAT_X11)
Bram Moolenaare8208012008-06-20 09:59:25 +00003326 if (x11_display != NULL
3327# ifdef FEAT_XCLIPBOARD
3328 && x11_display != xterm_dpy
3329# endif
3330 )
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00003331 XCloseDisplay(x11_display);
3332# endif
3333# if defined(HAVE_SIGALTSTACK) || defined(HAVE_SIGSTACK)
Bram Moolenaard23a8232018-02-10 18:45:26 +01003334 VIM_CLEAR(signal_stack);
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00003335# endif
3336# ifdef FEAT_TITLE
3337 vim_free(oldtitle);
3338 vim_free(oldicon);
3339# endif
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003340}
3341#endif
3342
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +01003343static void exit_scroll(void);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003344
3345/*
3346 * Output a newline when exiting.
3347 * Make sure the newline goes to the same stream as the text.
3348 */
3349 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01003350exit_scroll(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003351{
Bram Moolenaardf177f62005-02-22 08:39:57 +00003352 if (silent_mode)
3353 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003354 if (newline_on_exit || msg_didout)
3355 {
3356 if (msg_use_printf())
3357 {
3358 if (info_message)
3359 mch_msg("\n");
3360 else
3361 mch_errmsg("\r\n");
3362 }
3363 else
3364 out_char('\n');
3365 }
3366 else
3367 {
3368 restore_cterm_colors(); /* get original colors back */
3369 msg_clr_eos_force(); /* clear the rest of the display */
3370 windgoto((int)Rows - 1, 0); /* may have moved the cursor */
3371 }
3372}
3373
3374 void
Bram Moolenaar05540972016-01-30 20:31:25 +01003375mch_exit(int r)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003376{
3377 exiting = TRUE;
3378
3379#if defined(FEAT_X11) && defined(FEAT_CLIPBOARD)
3380 x11_export_final_selection();
3381#endif
3382
3383#ifdef FEAT_GUI
3384 if (!gui.in_use)
3385#endif
3386 {
3387 settmode(TMODE_COOK);
3388#ifdef FEAT_TITLE
Bram Moolenaar40385db2018-08-07 22:31:44 +02003389 // restore xterm title and icon name
3390 mch_restore_title(SAVE_RESTORE_BOTH);
3391 term_pop_title(SAVE_RESTORE_BOTH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003392#endif
3393 /*
3394 * When t_ti is not empty but it doesn't cause swapping terminal
3395 * pages, need to output a newline when msg_didout is set. But when
3396 * t_ti does swap pages it should not go to the shell page. Do this
3397 * before stoptermcap().
3398 */
3399 if (swapping_screen() && !newline_on_exit)
3400 exit_scroll();
3401
3402 /* Stop termcap: May need to check for T_CRV response, which
3403 * requires RAW mode. */
3404 stoptermcap();
3405
3406 /*
3407 * A newline is only required after a message in the alternate screen.
3408 * This is set to TRUE by wait_return().
3409 */
3410 if (!swapping_screen() || newline_on_exit)
3411 exit_scroll();
3412
3413 /* Cursor may have been switched off without calling starttermcap()
3414 * when doing "vim -u vimrc" and vimrc contains ":q". */
3415 if (full_screen)
3416 cursor_on();
3417 }
3418 out_flush();
3419 ml_close_all(TRUE); /* remove all memfiles */
3420 may_core_dump();
3421#ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00003422 if (gui.in_use)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003423 gui_exit(r);
3424#endif
Bram Moolenaardf177f62005-02-22 08:39:57 +00003425
Bram Moolenaar56718732006-03-15 22:53:57 +00003426#ifdef MACOS_CONVERT
Bram Moolenaardf177f62005-02-22 08:39:57 +00003427 mac_conv_cleanup();
3428#endif
3429
Bram Moolenaar071d4272004-06-13 20:20:40 +00003430#ifdef __QNX__
3431 /* A core dump won't be created if the signal handler
3432 * doesn't return, so we can't call exit() */
3433 if (deadly_signal != 0)
3434 return;
3435#endif
3436
Bram Moolenaar009b2592004-10-24 19:18:58 +00003437#ifdef FEAT_NETBEANS_INTG
Bram Moolenaarb26e6322010-05-22 21:34:09 +02003438 netbeans_send_disconnect();
Bram Moolenaar009b2592004-10-24 19:18:58 +00003439#endif
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003440
3441#ifdef EXITFREE
3442 free_all_mem();
3443#endif
3444
Bram Moolenaar071d4272004-06-13 20:20:40 +00003445 exit(r);
3446}
3447
3448 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01003449may_core_dump(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003450{
3451 if (deadly_signal != 0)
3452 {
3453 signal(deadly_signal, SIG_DFL);
3454 kill(getpid(), deadly_signal); /* Die using the signal we caught */
3455 }
3456}
3457
3458#ifndef VMS
3459
3460 void
Bram Moolenaar05540972016-01-30 20:31:25 +01003461mch_settmode(int tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003462{
3463 static int first = TRUE;
3464
Bram Moolenaar4f44b882017-08-13 20:06:18 +02003465#ifdef NEW_TTY_SYSTEM
Bram Moolenaar071d4272004-06-13 20:20:40 +00003466# ifdef HAVE_TERMIOS_H
3467 static struct termios told;
3468 struct termios tnew;
3469# else
3470 static struct termio told;
3471 struct termio tnew;
3472# endif
3473
3474 if (first)
3475 {
3476 first = FALSE;
3477# if defined(HAVE_TERMIOS_H)
3478 tcgetattr(read_cmd_fd, &told);
3479# else
3480 ioctl(read_cmd_fd, TCGETA, &told);
3481# endif
3482 }
3483
3484 tnew = told;
3485 if (tmode == TMODE_RAW)
3486 {
3487 /*
3488 * ~ICRNL enables typing ^V^M
3489 */
3490 tnew.c_iflag &= ~ICRNL;
3491 tnew.c_lflag &= ~(ICANON | ECHO | ISIG | ECHOE
3492# if defined(IEXTEN) && !defined(__MINT__)
3493 | IEXTEN /* IEXTEN enables typing ^V on SOLARIS */
3494 /* but it breaks function keys on MINT */
3495# endif
3496 );
3497# ifdef ONLCR /* don't map NL -> CR NL, we do it ourselves */
3498 tnew.c_oflag &= ~ONLCR;
3499# endif
3500 tnew.c_cc[VMIN] = 1; /* return after 1 char */
3501 tnew.c_cc[VTIME] = 0; /* don't wait */
3502 }
3503 else if (tmode == TMODE_SLEEP)
Bram Moolenaar40de4562016-07-01 15:03:46 +02003504 {
3505 /* Also reset ICANON here, otherwise on Solaris select() won't see
3506 * typeahead characters. */
3507 tnew.c_lflag &= ~(ICANON | ECHO);
3508 tnew.c_cc[VMIN] = 1; /* return after 1 char */
3509 tnew.c_cc[VTIME] = 0; /* don't wait */
3510 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003511
3512# if defined(HAVE_TERMIOS_H)
3513 {
3514 int n = 10;
3515
3516 /* A signal may cause tcsetattr() to fail (e.g., SIGCONT). Retry a
3517 * few times. */
3518 while (tcsetattr(read_cmd_fd, TCSANOW, &tnew) == -1
3519 && errno == EINTR && n > 0)
3520 --n;
3521 }
3522# else
3523 ioctl(read_cmd_fd, TCSETA, &tnew);
3524# endif
3525
3526#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00003527 /*
3528 * for "old" tty systems
3529 */
3530# ifndef TIOCSETN
3531# define TIOCSETN TIOCSETP /* for hpux 9.0 */
3532# endif
3533 static struct sgttyb ttybold;
3534 struct sgttyb ttybnew;
3535
3536 if (first)
3537 {
3538 first = FALSE;
3539 ioctl(read_cmd_fd, TIOCGETP, &ttybold);
3540 }
3541
3542 ttybnew = ttybold;
3543 if (tmode == TMODE_RAW)
3544 {
3545 ttybnew.sg_flags &= ~(CRMOD | ECHO);
3546 ttybnew.sg_flags |= RAW;
3547 }
3548 else if (tmode == TMODE_SLEEP)
3549 ttybnew.sg_flags &= ~(ECHO);
3550 ioctl(read_cmd_fd, TIOCSETN, &ttybnew);
3551#endif
3552 curr_tmode = tmode;
3553}
3554
3555/*
3556 * Try to get the code for "t_kb" from the stty setting
3557 *
3558 * Even if termcap claims a backspace key, the user's setting *should*
3559 * prevail. stty knows more about reality than termcap does, and if
3560 * somebody's usual erase key is DEL (which, for most BSD users, it will
3561 * be), they're going to get really annoyed if their erase key starts
3562 * doing forward deletes for no reason. (Eric Fischer)
3563 */
3564 void
Bram Moolenaar05540972016-01-30 20:31:25 +01003565get_stty(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003566{
Bram Moolenaar4f44b882017-08-13 20:06:18 +02003567 ttyinfo_T info;
3568 char_u buf[2];
3569 char_u *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003570
Bram Moolenaar4f44b882017-08-13 20:06:18 +02003571 if (get_tty_info(read_cmd_fd, &info) == OK)
3572 {
3573 intr_char = info.interrupt;
3574 buf[0] = info.backspace;
3575 buf[1] = NUL;
3576 add_termcode((char_u *)"kb", buf, FALSE);
3577
3578 /* If <BS> and <DEL> are now the same, redefine <DEL>. */
3579 p = find_termcode((char_u *)"kD");
3580 if (p != NULL && p[0] == buf[0] && p[1] == buf[1])
3581 do_fixdel(NULL);
3582 }
3583}
3584
3585/*
3586 * Obtain the characters that Backspace and Enter produce on "fd".
3587 * Returns OK or FAIL.
3588 */
3589 int
3590get_tty_info(int fd, ttyinfo_T *info)
3591{
3592#ifdef NEW_TTY_SYSTEM
Bram Moolenaar071d4272004-06-13 20:20:40 +00003593# ifdef HAVE_TERMIOS_H
3594 struct termios keys;
3595# else
3596 struct termio keys;
3597# endif
3598
Bram Moolenaar4f44b882017-08-13 20:06:18 +02003599 if (
Bram Moolenaar071d4272004-06-13 20:20:40 +00003600# if defined(HAVE_TERMIOS_H)
Bram Moolenaar4f44b882017-08-13 20:06:18 +02003601 tcgetattr(fd, &keys) != -1
Bram Moolenaar071d4272004-06-13 20:20:40 +00003602# else
Bram Moolenaar4f44b882017-08-13 20:06:18 +02003603 ioctl(fd, TCGETA, &keys) != -1
Bram Moolenaar071d4272004-06-13 20:20:40 +00003604# endif
Bram Moolenaar4f44b882017-08-13 20:06:18 +02003605 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003606 {
Bram Moolenaar4f44b882017-08-13 20:06:18 +02003607 info->backspace = keys.c_cc[VERASE];
3608 info->interrupt = keys.c_cc[VINTR];
3609 if (keys.c_iflag & ICRNL)
3610 info->enter = NL;
3611 else
3612 info->enter = CAR;
3613 if (keys.c_oflag & ONLCR)
3614 info->nl_does_cr = TRUE;
3615 else
3616 info->nl_does_cr = FALSE;
3617 return OK;
3618 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003619#else
3620 /* for "old" tty systems */
3621 struct sgttyb keys;
3622
Bram Moolenaar4f44b882017-08-13 20:06:18 +02003623 if (ioctl(fd, TIOCGETP, &keys) != -1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003624 {
Bram Moolenaar4f44b882017-08-13 20:06:18 +02003625 info->backspace = keys.sg_erase;
3626 info->interrupt = keys.sg_kill;
3627 info->enter = CAR;
3628 info->nl_does_cr = TRUE;
3629 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003630 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003631#endif
Bram Moolenaar4f44b882017-08-13 20:06:18 +02003632 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003633}
3634
3635#endif /* VMS */
3636
3637#if defined(FEAT_MOUSE_TTY) || defined(PROTO)
Bram Moolenaar51b0f372017-11-18 18:52:04 +01003638static int mouse_ison = FALSE;
3639
Bram Moolenaar071d4272004-06-13 20:20:40 +00003640/*
3641 * Set mouse clicks on or off.
3642 */
3643 void
Bram Moolenaar05540972016-01-30 20:31:25 +01003644mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003645{
Bram Moolenaarc3719bd2017-11-18 22:13:31 +01003646# ifdef FEAT_BEVAL_TERM
Bram Moolenaar51b0f372017-11-18 18:52:04 +01003647 static int bevalterm_ison = FALSE;
3648# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003649 int xterm_mouse_vers;
3650
Bram Moolenaara06afc72018-08-27 23:24:16 +02003651# if defined(FEAT_X11) && defined(FEAT_XCLIPBOARD)
3652 if (!on)
3653 // Make sure not tracing mouse movements. Important when a button-down
3654 // was received but no release yet.
3655 stop_xterm_trace();
3656# endif
3657
Bram Moolenaar51b0f372017-11-18 18:52:04 +01003658 if (on == mouse_ison
Bram Moolenaarc3719bd2017-11-18 22:13:31 +01003659# ifdef FEAT_BEVAL_TERM
Bram Moolenaar51b0f372017-11-18 18:52:04 +01003660 && p_bevalterm == bevalterm_ison
3661# endif
3662 )
3663 /* return quickly if nothing to do */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003664 return;
3665
3666 xterm_mouse_vers = use_xterm_mouse();
Bram Moolenaarc8427482011-10-20 21:09:35 +02003667
3668# ifdef FEAT_MOUSE_URXVT
Bram Moolenaar2b9578f2012-08-15 16:21:32 +02003669 if (ttym_flags == TTYM_URXVT)
3670 {
Bram Moolenaarc8427482011-10-20 21:09:35 +02003671 out_str_nf((char_u *)
3672 (on
3673 ? IF_EB("\033[?1015h", ESC_STR "[?1015h")
3674 : IF_EB("\033[?1015l", ESC_STR "[?1015l")));
Bram Moolenaar51b0f372017-11-18 18:52:04 +01003675 mouse_ison = on;
Bram Moolenaarc8427482011-10-20 21:09:35 +02003676 }
3677# endif
3678
Bram Moolenaar2b9578f2012-08-15 16:21:32 +02003679# ifdef FEAT_MOUSE_SGR
3680 if (ttym_flags == TTYM_SGR)
3681 {
Bram Moolenaar51b0f372017-11-18 18:52:04 +01003682 /* SGR mode supports columns above 223 */
Bram Moolenaar2b9578f2012-08-15 16:21:32 +02003683 out_str_nf((char_u *)
3684 (on
3685 ? IF_EB("\033[?1006h", ESC_STR "[?1006h")
3686 : IF_EB("\033[?1006l", ESC_STR "[?1006l")));
Bram Moolenaar51b0f372017-11-18 18:52:04 +01003687 mouse_ison = on;
3688 }
3689# endif
3690
Bram Moolenaarc3719bd2017-11-18 22:13:31 +01003691# ifdef FEAT_BEVAL_TERM
Bram Moolenaar51b0f372017-11-18 18:52:04 +01003692 if (bevalterm_ison != (p_bevalterm && on))
3693 {
3694 bevalterm_ison = (p_bevalterm && on);
3695 if (xterm_mouse_vers > 1 && !bevalterm_ison)
3696 /* disable mouse movement events, enabling is below */
3697 out_str_nf((char_u *)
3698 (IF_EB("\033[?1003l", ESC_STR "[?1003l")));
Bram Moolenaar2b9578f2012-08-15 16:21:32 +02003699 }
3700# endif
3701
Bram Moolenaar071d4272004-06-13 20:20:40 +00003702 if (xterm_mouse_vers > 0)
3703 {
3704 if (on) /* enable mouse events, use mouse tracking if available */
3705 out_str_nf((char_u *)
3706 (xterm_mouse_vers > 1
Bram Moolenaar51b0f372017-11-18 18:52:04 +01003707 ? (
Bram Moolenaarc3719bd2017-11-18 22:13:31 +01003708# ifdef FEAT_BEVAL_TERM
Bram Moolenaar51b0f372017-11-18 18:52:04 +01003709 bevalterm_ison
3710 ? IF_EB("\033[?1003h", ESC_STR "[?1003h") :
3711# endif
3712 IF_EB("\033[?1002h", ESC_STR "[?1002h"))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003713 : IF_EB("\033[?1000h", ESC_STR "[?1000h")));
3714 else /* disable mouse events, could probably always send the same */
3715 out_str_nf((char_u *)
3716 (xterm_mouse_vers > 1
3717 ? IF_EB("\033[?1002l", ESC_STR "[?1002l")
3718 : IF_EB("\033[?1000l", ESC_STR "[?1000l")));
Bram Moolenaar51b0f372017-11-18 18:52:04 +01003719 mouse_ison = on;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003720 }
3721
3722# ifdef FEAT_MOUSE_DEC
3723 else if (ttym_flags == TTYM_DEC)
3724 {
3725 if (on) /* enable mouse events */
3726 out_str_nf((char_u *)"\033[1;2'z\033[1;3'{");
3727 else /* disable mouse events */
3728 out_str_nf((char_u *)"\033['z");
Bram Moolenaar51b0f372017-11-18 18:52:04 +01003729 mouse_ison = on;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003730 }
3731# endif
3732
3733# ifdef FEAT_MOUSE_GPM
3734 else
3735 {
3736 if (on)
3737 {
3738 if (gpm_open())
Bram Moolenaar51b0f372017-11-18 18:52:04 +01003739 mouse_ison = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003740 }
3741 else
3742 {
3743 gpm_close();
Bram Moolenaar51b0f372017-11-18 18:52:04 +01003744 mouse_ison = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003745 }
3746 }
3747# endif
3748
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00003749# ifdef FEAT_SYSMOUSE
3750 else
3751 {
3752 if (on)
3753 {
3754 if (sysmouse_open() == OK)
Bram Moolenaar51b0f372017-11-18 18:52:04 +01003755 mouse_ison = TRUE;
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00003756 }
3757 else
3758 {
3759 sysmouse_close();
Bram Moolenaar51b0f372017-11-18 18:52:04 +01003760 mouse_ison = FALSE;
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00003761 }
3762 }
3763# endif
3764
Bram Moolenaar071d4272004-06-13 20:20:40 +00003765# ifdef FEAT_MOUSE_JSB
3766 else
3767 {
3768 if (on)
3769 {
3770 /* D - Enable Mouse up/down messages
3771 * L - Enable Left Button Reporting
3772 * M - Enable Middle Button Reporting
3773 * R - Enable Right Button Reporting
3774 * K - Enable SHIFT and CTRL key Reporting
3775 * + - Enable Advanced messaging of mouse moves and up/down messages
3776 * Q - Quiet No Ack
3777 * # - Numeric value of mouse pointer required
3778 * 0 = Multiview 2000 cursor, used as standard
3779 * 1 = Windows Arrow
3780 * 2 = Windows I Beam
3781 * 3 = Windows Hour Glass
3782 * 4 = Windows Cross Hair
3783 * 5 = Windows UP Arrow
3784 */
Bram Moolenaarf8de1612013-04-15 15:32:25 +02003785# ifdef JSBTERM_MOUSE_NONADVANCED
3786 /* Disables full feedback of pointer movements */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003787 out_str_nf((char_u *)IF_EB("\033[0~ZwLMRK1Q\033\\",
3788 ESC_STR "[0~ZwLMRK1Q" ESC_STR "\\"));
Bram Moolenaarf8de1612013-04-15 15:32:25 +02003789# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00003790 out_str_nf((char_u *)IF_EB("\033[0~ZwLMRK+1Q\033\\",
3791 ESC_STR "[0~ZwLMRK+1Q" ESC_STR "\\"));
Bram Moolenaarf8de1612013-04-15 15:32:25 +02003792# endif
Bram Moolenaar51b0f372017-11-18 18:52:04 +01003793 mouse_ison = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003794 }
3795 else
3796 {
3797 out_str_nf((char_u *)IF_EB("\033[0~ZwQ\033\\",
3798 ESC_STR "[0~ZwQ" ESC_STR "\\"));
Bram Moolenaar51b0f372017-11-18 18:52:04 +01003799 mouse_ison = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003800 }
3801 }
3802# endif
3803# ifdef FEAT_MOUSE_PTERM
3804 else
3805 {
3806 /* 1 = button press, 6 = release, 7 = drag, 1h...9l = right button */
3807 if (on)
3808 out_str_nf("\033[>1h\033[>6h\033[>7h\033[>1h\033[>9l");
3809 else
3810 out_str_nf("\033[>1l\033[>6l\033[>7l\033[>1l\033[>9h");
Bram Moolenaar51b0f372017-11-18 18:52:04 +01003811 mouse_ison = on;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003812 }
3813# endif
3814}
3815
Bram Moolenaarc3719bd2017-11-18 22:13:31 +01003816#if defined(FEAT_BEVAL_TERM) || defined(PROTO)
Bram Moolenaar51b0f372017-11-18 18:52:04 +01003817/*
3818 * Called when 'balloonevalterm' changed.
3819 */
3820 void
3821mch_bevalterm_changed(void)
3822{
3823 mch_setmouse(mouse_ison);
3824}
3825#endif
3826
Bram Moolenaar071d4272004-06-13 20:20:40 +00003827/*
3828 * Set the mouse termcode, depending on the 'term' and 'ttymouse' options.
3829 */
3830 void
Bram Moolenaar05540972016-01-30 20:31:25 +01003831check_mouse_termcode(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003832{
3833# ifdef FEAT_MOUSE_XTERM
3834 if (use_xterm_mouse()
Bram Moolenaarc8427482011-10-20 21:09:35 +02003835# ifdef FEAT_MOUSE_URXVT
3836 && use_xterm_mouse() != 3
3837# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003838# ifdef FEAT_GUI
3839 && !gui.in_use
3840# endif
3841 )
3842 {
3843 set_mouse_termcode(KS_MOUSE, (char_u *)(term_is_8bit(T_NAME)
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00003844 ? IF_EB("\233M", CSI_STR "M")
3845 : IF_EB("\033[M", ESC_STR "[M")));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003846 if (*p_mouse != NUL)
3847 {
3848 /* force mouse off and maybe on to send possibly new mouse
3849 * activation sequence to the xterm, with(out) drag tracing. */
3850 mch_setmouse(FALSE);
3851 setmouse();
3852 }
3853 }
3854 else
3855 del_mouse_termcode(KS_MOUSE);
3856# endif
3857
3858# ifdef FEAT_MOUSE_GPM
3859 if (!use_xterm_mouse()
3860# ifdef FEAT_GUI
3861 && !gui.in_use
3862# endif
3863 )
3864 set_mouse_termcode(KS_MOUSE, (char_u *)IF_EB("\033MG", ESC_STR "MG"));
3865# endif
3866
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00003867# ifdef FEAT_SYSMOUSE
3868 if (!use_xterm_mouse()
3869# ifdef FEAT_GUI
3870 && !gui.in_use
3871# endif
3872 )
3873 set_mouse_termcode(KS_MOUSE, (char_u *)IF_EB("\033MS", ESC_STR "MS"));
3874# endif
3875
Bram Moolenaar071d4272004-06-13 20:20:40 +00003876# ifdef FEAT_MOUSE_JSB
Bram Moolenaar4e067c82014-07-30 17:21:58 +02003877 /* Conflicts with xterm mouse: "\033[" and "\033[M" ??? */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003878 if (!use_xterm_mouse()
3879# ifdef FEAT_GUI
3880 && !gui.in_use
3881# endif
3882 )
3883 set_mouse_termcode(KS_JSBTERM_MOUSE,
3884 (char_u *)IF_EB("\033[0~zw", ESC_STR "[0~zw"));
3885 else
3886 del_mouse_termcode(KS_JSBTERM_MOUSE);
3887# endif
3888
3889# ifdef FEAT_MOUSE_NET
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00003890 /* There is no conflict, but one may type "ESC }" from Insert mode. Don't
Bram Moolenaar071d4272004-06-13 20:20:40 +00003891 * define it in the GUI or when using an xterm. */
3892 if (!use_xterm_mouse()
3893# ifdef FEAT_GUI
3894 && !gui.in_use
3895# endif
3896 )
3897 set_mouse_termcode(KS_NETTERM_MOUSE,
3898 (char_u *)IF_EB("\033}", ESC_STR "}"));
3899 else
3900 del_mouse_termcode(KS_NETTERM_MOUSE);
3901# endif
3902
3903# ifdef FEAT_MOUSE_DEC
Bram Moolenaar4e067c82014-07-30 17:21:58 +02003904 /* Conflicts with xterm mouse: "\033[" and "\033[M" */
Bram Moolenaarcbc17d62014-05-22 21:22:19 +02003905 if (!use_xterm_mouse()
Bram Moolenaar071d4272004-06-13 20:20:40 +00003906# ifdef FEAT_GUI
3907 && !gui.in_use
3908# endif
3909 )
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00003910 set_mouse_termcode(KS_DEC_MOUSE, (char_u *)(term_is_8bit(T_NAME)
3911 ? IF_EB("\233", CSI_STR) : IF_EB("\033[", ESC_STR "[")));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003912 else
3913 del_mouse_termcode(KS_DEC_MOUSE);
3914# endif
3915# ifdef FEAT_MOUSE_PTERM
Bram Moolenaar4e067c82014-07-30 17:21:58 +02003916 /* same conflict as the dec mouse */
Bram Moolenaarcbc17d62014-05-22 21:22:19 +02003917 if (!use_xterm_mouse()
Bram Moolenaar071d4272004-06-13 20:20:40 +00003918# ifdef FEAT_GUI
3919 && !gui.in_use
3920# endif
3921 )
3922 set_mouse_termcode(KS_PTERM_MOUSE,
3923 (char_u *) IF_EB("\033[", ESC_STR "["));
3924 else
3925 del_mouse_termcode(KS_PTERM_MOUSE);
3926# endif
Bram Moolenaarc8427482011-10-20 21:09:35 +02003927# ifdef FEAT_MOUSE_URXVT
Bram Moolenaarcbc17d62014-05-22 21:22:19 +02003928 if (use_xterm_mouse() == 3
Bram Moolenaarc8427482011-10-20 21:09:35 +02003929# ifdef FEAT_GUI
3930 && !gui.in_use
3931# endif
3932 )
3933 {
3934 set_mouse_termcode(KS_URXVT_MOUSE, (char_u *)(term_is_8bit(T_NAME)
Bram Moolenaara529ce02017-06-22 22:37:57 +02003935 ? IF_EB("\233*M", CSI_STR "*M")
3936 : IF_EB("\033[*M", ESC_STR "[*M")));
Bram Moolenaarc8427482011-10-20 21:09:35 +02003937
3938 if (*p_mouse != NUL)
3939 {
3940 mch_setmouse(FALSE);
3941 setmouse();
3942 }
3943 }
3944 else
3945 del_mouse_termcode(KS_URXVT_MOUSE);
3946# endif
Bram Moolenaar2b9578f2012-08-15 16:21:32 +02003947# ifdef FEAT_MOUSE_SGR
Bram Moolenaar2b9578f2012-08-15 16:21:32 +02003948 if (use_xterm_mouse() == 4
3949# ifdef FEAT_GUI
3950 && !gui.in_use
3951# endif
3952 )
3953 {
3954 set_mouse_termcode(KS_SGR_MOUSE, (char_u *)(term_is_8bit(T_NAME)
Bram Moolenaara529ce02017-06-22 22:37:57 +02003955 ? IF_EB("\233<*M", CSI_STR "<*M")
3956 : IF_EB("\033[<*M", ESC_STR "[<*M")));
3957
3958 set_mouse_termcode(KS_SGR_MOUSE_RELEASE, (char_u *)(term_is_8bit(T_NAME)
3959 ? IF_EB("\233<*m", CSI_STR "<*m")
3960 : IF_EB("\033[<*m", ESC_STR "[<*m")));
Bram Moolenaar2b9578f2012-08-15 16:21:32 +02003961
3962 if (*p_mouse != NUL)
3963 {
3964 mch_setmouse(FALSE);
3965 setmouse();
3966 }
3967 }
3968 else
Bram Moolenaara529ce02017-06-22 22:37:57 +02003969 {
Bram Moolenaar2b9578f2012-08-15 16:21:32 +02003970 del_mouse_termcode(KS_SGR_MOUSE);
Bram Moolenaara529ce02017-06-22 22:37:57 +02003971 del_mouse_termcode(KS_SGR_MOUSE_RELEASE);
3972 }
Bram Moolenaar2b9578f2012-08-15 16:21:32 +02003973# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003974}
3975#endif
3976
3977/*
3978 * set screen mode, always fails.
3979 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003980 int
Bram Moolenaar05540972016-01-30 20:31:25 +01003981mch_screenmode(char_u *arg UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003982{
3983 EMSG(_(e_screenmode));
3984 return FAIL;
3985}
3986
3987#ifndef VMS
3988
3989/*
3990 * Try to get the current window size:
3991 * 1. with an ioctl(), most accurate method
3992 * 2. from the environment variables LINES and COLUMNS
3993 * 3. from the termcap
3994 * 4. keep using the old values
3995 * Return OK when size could be determined, FAIL otherwise.
3996 */
3997 int
Bram Moolenaar05540972016-01-30 20:31:25 +01003998mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003999{
4000 long rows = 0;
4001 long columns = 0;
4002 char_u *p;
4003
4004 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004005 * 1. try using an ioctl. It is the most accurate method.
4006 *
4007 * Try using TIOCGWINSZ first, some systems that have it also define
4008 * TIOCGSIZE but don't have a struct ttysize.
4009 */
4010# ifdef TIOCGWINSZ
4011 {
4012 struct winsize ws;
4013 int fd = 1;
4014
4015 /* When stdout is not a tty, use stdin for the ioctl(). */
4016 if (!isatty(fd) && isatty(read_cmd_fd))
4017 fd = read_cmd_fd;
4018 if (ioctl(fd, TIOCGWINSZ, &ws) == 0)
4019 {
4020 columns = ws.ws_col;
4021 rows = ws.ws_row;
4022 }
4023 }
4024# else /* TIOCGWINSZ */
4025# ifdef TIOCGSIZE
4026 {
4027 struct ttysize ts;
4028 int fd = 1;
4029
4030 /* When stdout is not a tty, use stdin for the ioctl(). */
4031 if (!isatty(fd) && isatty(read_cmd_fd))
4032 fd = read_cmd_fd;
4033 if (ioctl(fd, TIOCGSIZE, &ts) == 0)
4034 {
4035 columns = ts.ts_cols;
4036 rows = ts.ts_lines;
4037 }
4038 }
4039# endif /* TIOCGSIZE */
4040# endif /* TIOCGWINSZ */
4041
4042 /*
4043 * 2. get size from environment
Bram Moolenaar4399ef42005-02-12 14:29:27 +00004044 * When being POSIX compliant ('|' flag in 'cpoptions') this overrules
4045 * the ioctl() values!
Bram Moolenaar071d4272004-06-13 20:20:40 +00004046 */
Bram Moolenaar4399ef42005-02-12 14:29:27 +00004047 if (columns == 0 || rows == 0 || vim_strchr(p_cpo, CPO_TSIZE) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004048 {
4049 if ((p = (char_u *)getenv("LINES")))
4050 rows = atoi((char *)p);
4051 if ((p = (char_u *)getenv("COLUMNS")))
4052 columns = atoi((char *)p);
4053 }
4054
4055#ifdef HAVE_TGETENT
4056 /*
4057 * 3. try reading "co" and "li" entries from termcap
4058 */
4059 if (columns == 0 || rows == 0)
4060 getlinecol(&columns, &rows);
4061#endif
4062
4063 /*
4064 * 4. If everything fails, use the old values
4065 */
4066 if (columns <= 0 || rows <= 0)
4067 return FAIL;
4068
4069 Rows = rows;
4070 Columns = columns;
Bram Moolenaare057d402013-06-30 17:51:51 +02004071 limit_screen_size();
Bram Moolenaar071d4272004-06-13 20:20:40 +00004072 return OK;
4073}
4074
Bram Moolenaarb13501f2017-07-22 22:32:56 +02004075#if defined(FEAT_TERMINAL) || defined(PROTO)
4076/*
4077 * Report the windows size "rows" and "cols" to tty "fd".
4078 */
4079 int
4080mch_report_winsize(int fd, int rows, int cols)
4081{
4082# ifdef TIOCSWINSZ
4083 struct winsize ws;
4084
4085 ws.ws_col = cols;
4086 ws.ws_row = rows;
4087 ws.ws_xpixel = cols * 5;
4088 ws.ws_ypixel = rows * 10;
4089 if (ioctl(fd, TIOCSWINSZ, &ws) == 0)
4090 {
4091 ch_log(NULL, "ioctl(TIOCSWINSZ) success");
4092 return OK;
4093 }
4094 ch_log(NULL, "ioctl(TIOCSWINSZ) failed");
4095# else
4096# ifdef TIOCSSIZE
4097 struct ttysize ts;
4098
4099 ts.ts_cols = cols;
4100 ts.ts_lines = rows;
4101 if (ioctl(fd, TIOCSSIZE, &ws) == 0)
4102 {
4103 ch_log(NULL, "ioctl(TIOCSSIZE) success");
4104 return OK;
4105 }
4106 ch_log(NULL, "ioctl(TIOCSSIZE) failed");
4107# endif
4108# endif
4109 return FAIL;
4110}
4111#endif
4112
Bram Moolenaar071d4272004-06-13 20:20:40 +00004113/*
4114 * Try to set the window size to Rows and Columns.
4115 */
4116 void
Bram Moolenaar05540972016-01-30 20:31:25 +01004117mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004118{
4119 if (*T_CWS)
4120 {
4121 /*
4122 * NOTE: if you get an error here that term_set_winsize() is
4123 * undefined, check the output of configure. It could probably not
4124 * find a ncurses, termcap or termlib library.
4125 */
4126 term_set_winsize((int)Rows, (int)Columns);
4127 out_flush();
4128 screen_start(); /* don't know where cursor is now */
4129 }
4130}
4131
4132#endif /* VMS */
4133
4134/*
4135 * Rows and/or Columns has changed.
4136 */
4137 void
Bram Moolenaar05540972016-01-30 20:31:25 +01004138mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004139{
4140 /* Nothing to do. */
4141}
4142
Bram Moolenaar205b8862011-09-07 15:04:31 +02004143/*
4144 * Wait for process "child" to end.
4145 * Return "child" if it exited properly, <= 0 on error.
4146 */
4147 static pid_t
Bram Moolenaar05540972016-01-30 20:31:25 +01004148wait4pid(pid_t child, waitstatus *status)
Bram Moolenaar205b8862011-09-07 15:04:31 +02004149{
4150 pid_t wait_pid = 0;
Bram Moolenaar0abe0522016-08-28 16:53:12 +02004151 long delay_msec = 1;
Bram Moolenaar205b8862011-09-07 15:04:31 +02004152
4153 while (wait_pid != child)
4154 {
Bram Moolenaar6be120e2012-04-20 15:55:16 +02004155 /* When compiled with Python threads are probably used, in which case
4156 * wait() sometimes hangs for no obvious reason. Use waitpid()
4157 * instead and loop (like the GUI). Also needed for other interfaces,
4158 * they might call system(). */
4159# ifdef __NeXT__
Bram Moolenaar205b8862011-09-07 15:04:31 +02004160 wait_pid = wait4(child, status, WNOHANG, (struct rusage *)0);
Bram Moolenaar6be120e2012-04-20 15:55:16 +02004161# else
Bram Moolenaar205b8862011-09-07 15:04:31 +02004162 wait_pid = waitpid(child, status, WNOHANG);
Bram Moolenaar6be120e2012-04-20 15:55:16 +02004163# endif
Bram Moolenaar205b8862011-09-07 15:04:31 +02004164 if (wait_pid == 0)
4165 {
Bram Moolenaar0abe0522016-08-28 16:53:12 +02004166 /* Wait for 1 to 10 msec before trying again. */
4167 mch_delay(delay_msec, TRUE);
4168 if (++delay_msec > 10)
4169 delay_msec = 10;
Bram Moolenaar205b8862011-09-07 15:04:31 +02004170 continue;
4171 }
Bram Moolenaar205b8862011-09-07 15:04:31 +02004172 if (wait_pid <= 0
4173# ifdef ECHILD
4174 && errno == ECHILD
4175# endif
4176 )
4177 break;
4178 }
4179 return wait_pid;
4180}
4181
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01004182#if !defined(USE_SYSTEM) || defined(FEAT_JOB_CHANNEL)
Bram Moolenaar7da34602017-08-01 17:14:21 +02004183/*
4184 * Set the environment for a child process.
4185 */
Bram Moolenaar6463ca22016-02-13 17:04:46 +01004186 static void
Bram Moolenaar493359e2018-06-12 20:25:52 +02004187set_child_environment(
4188 long rows,
4189 long columns,
4190 char *term,
4191 int is_terminal UNUSED)
Bram Moolenaar6463ca22016-02-13 17:04:46 +01004192{
4193# ifdef HAVE_SETENV
4194 char envbuf[50];
4195# else
Bram Moolenaar5f7e7bd2017-07-22 14:08:43 +02004196 static char envbuf_Term[30];
Bram Moolenaar6463ca22016-02-13 17:04:46 +01004197 static char envbuf_Rows[20];
Bram Moolenaar58556cd2017-07-20 23:04:46 +02004198 static char envbuf_Lines[20];
Bram Moolenaar6463ca22016-02-13 17:04:46 +01004199 static char envbuf_Columns[20];
Bram Moolenaarb7a8dfe2017-07-22 20:33:05 +02004200 static char envbuf_Colors[20];
Bram Moolenaar493359e2018-06-12 20:25:52 +02004201# ifdef FEAT_TERMINAL
Bram Moolenaard7a137f2018-06-12 18:05:24 +02004202 static char envbuf_Version[20];
Bram Moolenaar493359e2018-06-12 20:25:52 +02004203# endif
Bram Moolenaar2a4f06f2017-08-01 18:44:29 +02004204# ifdef FEAT_CLIENTSERVER
Bram Moolenaar7da34602017-08-01 17:14:21 +02004205 static char envbuf_Servername[60];
Bram Moolenaar2a4f06f2017-08-01 18:44:29 +02004206# endif
Bram Moolenaar6463ca22016-02-13 17:04:46 +01004207# endif
Bram Moolenaarb7a8dfe2017-07-22 20:33:05 +02004208 long colors =
4209# ifdef FEAT_GUI
4210 gui.in_use ? 256*256*256 :
4211# endif
4212 t_colors;
Bram Moolenaar6463ca22016-02-13 17:04:46 +01004213
Bram Moolenaar6463ca22016-02-13 17:04:46 +01004214# ifdef HAVE_SETENV
Bram Moolenaar58556cd2017-07-20 23:04:46 +02004215 setenv("TERM", term, 1);
4216 sprintf((char *)envbuf, "%ld", rows);
Bram Moolenaar6463ca22016-02-13 17:04:46 +01004217 setenv("ROWS", (char *)envbuf, 1);
Bram Moolenaar58556cd2017-07-20 23:04:46 +02004218 sprintf((char *)envbuf, "%ld", rows);
Bram Moolenaar6463ca22016-02-13 17:04:46 +01004219 setenv("LINES", (char *)envbuf, 1);
Bram Moolenaar58556cd2017-07-20 23:04:46 +02004220 sprintf((char *)envbuf, "%ld", columns);
Bram Moolenaar6463ca22016-02-13 17:04:46 +01004221 setenv("COLUMNS", (char *)envbuf, 1);
Bram Moolenaarb7a8dfe2017-07-22 20:33:05 +02004222 sprintf((char *)envbuf, "%ld", colors);
4223 setenv("COLORS", (char *)envbuf, 1);
Bram Moolenaar493359e2018-06-12 20:25:52 +02004224# ifdef FEAT_TERMINAL
4225 if (is_terminal)
4226 {
Bram Moolenaar5ecdf962018-06-13 20:49:50 +02004227 sprintf((char *)envbuf, "%ld", (long)get_vim_var_nr(VV_VERSION));
Bram Moolenaar493359e2018-06-12 20:25:52 +02004228 setenv("VIM_TERMINAL", (char *)envbuf, 1);
4229 }
4230# endif
Bram Moolenaar2a4f06f2017-08-01 18:44:29 +02004231# ifdef FEAT_CLIENTSERVER
Bram Moolenaar7da34602017-08-01 17:14:21 +02004232 setenv("VIM_SERVERNAME", serverName == NULL ? "" : (char *)serverName, 1);
Bram Moolenaar2a4f06f2017-08-01 18:44:29 +02004233# endif
Bram Moolenaar6463ca22016-02-13 17:04:46 +01004234# else
4235 /*
4236 * Putenv does not copy the string, it has to remain valid.
4237 * Use a static array to avoid losing allocated memory.
Bram Moolenaar7da34602017-08-01 17:14:21 +02004238 * This won't work well when running multiple children...
Bram Moolenaar6463ca22016-02-13 17:04:46 +01004239 */
Bram Moolenaar58556cd2017-07-20 23:04:46 +02004240 vim_snprintf(envbuf_Term, sizeof(envbuf_Term), "TERM=%s", term);
4241 putenv(envbuf_Term);
4242 vim_snprintf(envbuf_Rows, sizeof(envbuf_Rows), "ROWS=%ld", rows);
Bram Moolenaar6463ca22016-02-13 17:04:46 +01004243 putenv(envbuf_Rows);
Bram Moolenaar58556cd2017-07-20 23:04:46 +02004244 vim_snprintf(envbuf_Lines, sizeof(envbuf_Lines), "LINES=%ld", rows);
4245 putenv(envbuf_Lines);
4246 vim_snprintf(envbuf_Columns, sizeof(envbuf_Columns),
4247 "COLUMNS=%ld", columns);
Bram Moolenaar6463ca22016-02-13 17:04:46 +01004248 putenv(envbuf_Columns);
Bram Moolenaarb7a8dfe2017-07-22 20:33:05 +02004249 vim_snprintf(envbuf_Colors, sizeof(envbuf_Colors), "COLORS=%ld", colors);
4250 putenv(envbuf_Colors);
Bram Moolenaar493359e2018-06-12 20:25:52 +02004251# ifdef FEAT_TERMINAL
4252 if (is_terminal)
4253 {
4254 vim_snprintf(envbuf_Version, sizeof(envbuf_Version),
Bram Moolenaar5ecdf962018-06-13 20:49:50 +02004255 "VIM_TERMINAL=%ld", (long)get_vim_var_nr(VV_VERSION));
Bram Moolenaar493359e2018-06-12 20:25:52 +02004256 putenv(envbuf_Version);
4257 }
4258# endif
Bram Moolenaar2a4f06f2017-08-01 18:44:29 +02004259# ifdef FEAT_CLIENTSERVER
Bram Moolenaar7da34602017-08-01 17:14:21 +02004260 vim_snprintf(envbuf_Servername, sizeof(envbuf_Servername),
4261 "VIM_SERVERNAME=%s", serverName == NULL ? "" : (char *)serverName);
4262 putenv(envbuf_Servername);
Bram Moolenaar2a4f06f2017-08-01 18:44:29 +02004263# endif
Bram Moolenaar6463ca22016-02-13 17:04:46 +01004264# endif
4265}
Bram Moolenaar58556cd2017-07-20 23:04:46 +02004266
4267 static void
Bram Moolenaar493359e2018-06-12 20:25:52 +02004268set_default_child_environment(int is_terminal)
Bram Moolenaar58556cd2017-07-20 23:04:46 +02004269{
Bram Moolenaar493359e2018-06-12 20:25:52 +02004270 set_child_environment(Rows, Columns, "dumb", is_terminal);
Bram Moolenaar58556cd2017-07-20 23:04:46 +02004271}
Bram Moolenaar6463ca22016-02-13 17:04:46 +01004272#endif
4273
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02004274#if defined(FEAT_GUI) || defined(FEAT_JOB_CHANNEL)
Bram Moolenaar979e8c52017-08-01 15:08:07 +02004275/*
4276 * Open a PTY, with FD for the master and slave side.
4277 * When failing "pty_master_fd" and "pty_slave_fd" are -1.
4278 * When successful both file descriptors are stored.
4279 */
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02004280 static void
Bram Moolenaar7c9aec42017-08-03 13:51:25 +02004281open_pty(int *pty_master_fd, int *pty_slave_fd, char_u **namep)
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02004282{
4283 char *tty_name;
4284
4285 *pty_master_fd = OpenPTY(&tty_name); /* open pty */
4286 if (*pty_master_fd >= 0)
4287 {
4288 /* Leaving out O_NOCTTY may lead to waitpid() always returning
4289 * 0 on Mac OS X 10.7 thereby causing freezes. Let's assume
4290 * adding O_NOCTTY always works when defined. */
4291#ifdef O_NOCTTY
4292 *pty_slave_fd = open(tty_name, O_RDWR | O_NOCTTY | O_EXTRA, 0);
4293#else
4294 *pty_slave_fd = open(tty_name, O_RDWR | O_EXTRA, 0);
4295#endif
4296 if (*pty_slave_fd < 0)
4297 {
4298 close(*pty_master_fd);
4299 *pty_master_fd = -1;
4300 }
Bram Moolenaar7c9aec42017-08-03 13:51:25 +02004301 else if (namep != NULL)
4302 *namep = vim_strsave((char_u *)tty_name);
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02004303 }
4304}
4305#endif
4306
Bram Moolenaarfae42832017-08-01 22:24:26 +02004307/*
4308 * Send SIGINT to a child process if "c" is an interrupt character.
4309 */
4310 void
4311may_send_sigint(int c UNUSED, pid_t pid UNUSED, pid_t wpid UNUSED)
4312{
4313# ifdef SIGINT
4314 if (c == Ctrl_C || c == intr_char)
4315 {
4316# ifdef HAVE_SETSID
4317 kill(-pid, SIGINT);
4318# else
4319 kill(0, SIGINT);
4320# endif
4321 if (wpid > 0)
4322 kill(wpid, SIGINT);
4323 }
4324# endif
4325}
4326
Bram Moolenaar13568252018-03-16 20:46:58 +01004327#if !defined(USE_SYSTEM) || (defined(FEAT_GUI) && defined(FEAT_TERMINAL))
4328
4329 static int
4330build_argv(
4331 char_u *cmd,
4332 char ***argvp,
4333 char_u **sh_tofree,
4334 char_u **shcf_tofree)
4335{
4336 char **argv = NULL;
4337 int argc;
4338
4339 *sh_tofree = vim_strsave(p_sh);
4340 if (*sh_tofree == NULL) /* out of memory */
4341 return FAIL;
4342
4343 if (mch_parse_cmd(*sh_tofree, TRUE, &argv, &argc) == FAIL)
4344 return FAIL;
4345 *argvp = argv;
4346
4347 if (cmd != NULL)
4348 {
4349 char_u *s;
4350 char_u *p;
4351
4352 if (extra_shell_arg != NULL)
4353 argv[argc++] = (char *)extra_shell_arg;
4354
4355 /* Break 'shellcmdflag' into white separated parts. This doesn't
4356 * handle quoted strings, they are very unlikely to appear. */
4357 *shcf_tofree = alloc((unsigned)STRLEN(p_shcf) + 1);
4358 if (*shcf_tofree == NULL) /* out of memory */
4359 return FAIL;
4360 s = *shcf_tofree;
4361 p = p_shcf;
4362 while (*p != NUL)
4363 {
4364 argv[argc++] = (char *)s;
4365 while (*p && *p != ' ' && *p != TAB)
4366 *s++ = *p++;
4367 *s++ = NUL;
4368 p = skipwhite(p);
4369 }
4370
4371 argv[argc++] = (char *)cmd;
4372 }
4373 argv[argc] = NULL;
4374 return OK;
4375}
4376#endif
4377
4378#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
4379/*
4380 * Use a terminal window to run a shell command in.
4381 */
4382 static int
4383mch_call_shell_terminal(
4384 char_u *cmd,
4385 int options UNUSED) /* SHELL_*, see vim.h */
4386{
4387 jobopt_T opt;
4388 char **argv = NULL;
4389 char_u *tofree1 = NULL;
4390 char_u *tofree2 = NULL;
4391 int retval = -1;
4392 buf_T *buf;
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004393 job_T *job;
Bram Moolenaar13568252018-03-16 20:46:58 +01004394 aco_save_T aco;
4395 oparg_T oa; /* operator arguments */
4396
4397 if (build_argv(cmd, &argv, &tofree1, &tofree2) == FAIL)
4398 goto theend;
4399
4400 init_job_options(&opt);
4401 ch_log(NULL, "starting terminal for system command '%s'", cmd);
4402 buf = term_start(NULL, argv, &opt, TERM_START_SYSTEM);
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004403 if (buf == NULL)
4404 goto theend;
4405
4406 job = term_getjob(buf->b_term);
4407 ++job->jv_refcount;
Bram Moolenaar13568252018-03-16 20:46:58 +01004408
4409 /* Find a window to make "buf" curbuf. */
4410 aucmd_prepbuf(&aco, buf);
4411
4412 clear_oparg(&oa);
4413 while (term_use_loop())
4414 {
4415 if (oa.op_type == OP_NOP && oa.regname == NUL && !VIsual_active)
4416 {
4417 /* If terminal_loop() returns OK we got a key that is handled
4418 * in Normal model. We don't do redrawing anyway. */
4419 if (terminal_loop(TRUE) == OK)
4420 normal_cmd(&oa, TRUE);
4421 }
4422 else
4423 normal_cmd(&oa, TRUE);
4424 }
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004425 retval = job->jv_exitval;
Bram Moolenaar13568252018-03-16 20:46:58 +01004426 ch_log(NULL, "system command finished");
4427
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004428 job_unref(job);
4429
Bram Moolenaar13568252018-03-16 20:46:58 +01004430 /* restore curwin/curbuf and a few other things */
4431 aucmd_restbuf(&aco);
4432
4433 wait_return(TRUE);
4434 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
4435
4436theend:
4437 vim_free(argv);
4438 vim_free(tofree1);
4439 vim_free(tofree2);
4440 return retval;
4441}
4442#endif
4443
4444#ifdef USE_SYSTEM
4445/*
4446 * Use system() to start the shell: simple but slow.
4447 */
4448 static int
4449mch_call_shell_system(
Bram Moolenaar05540972016-01-30 20:31:25 +01004450 char_u *cmd,
4451 int options) /* SHELL_*, see vim.h */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004452{
4453#ifdef VMS
4454 char *ifn = NULL;
4455 char *ofn = NULL;
4456#endif
4457 int tmode = cur_tmode;
Bram Moolenaarb2b050a2016-07-16 21:52:46 +02004458 char_u *newcmd; /* only needed for unix */
Bram Moolenaarde5e2c22016-11-04 20:35:31 +01004459 int x;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004460
4461 out_flush();
4462
4463 if (options & SHELL_COOKED)
4464 settmode(TMODE_COOK); /* set to normal mode */
4465
Bram Moolenaar62b42182010-09-21 22:09:37 +02004466# if defined(FEAT_CLIPBOARD) && defined(FEAT_X11)
Bram Moolenaar1a0316c2013-03-13 17:50:25 +01004467 save_clipboard();
Bram Moolenaar62b42182010-09-21 22:09:37 +02004468 loose_clipboard();
4469# endif
4470
Bram Moolenaar071d4272004-06-13 20:20:40 +00004471 if (cmd == NULL)
4472 x = system((char *)p_sh);
4473 else
4474 {
Bram Moolenaara06ecab2016-07-16 14:47:36 +02004475# ifdef VMS
Bram Moolenaar071d4272004-06-13 20:20:40 +00004476 if (ofn = strchr((char *)cmd, '>'))
4477 *ofn++ = '\0';
4478 if (ifn = strchr((char *)cmd, '<'))
4479 {
4480 char *p;
4481
4482 *ifn++ = '\0';
4483 p = strchr(ifn,' '); /* chop off any trailing spaces */
4484 if (p)
4485 *p = '\0';
4486 }
4487 if (ofn)
4488 x = vms_sys((char *)cmd, ofn, ifn);
4489 else
4490 x = system((char *)cmd);
Bram Moolenaara06ecab2016-07-16 14:47:36 +02004491# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004492 newcmd = lalloc(STRLEN(p_sh)
4493 + (extra_shell_arg == NULL ? 0 : STRLEN(extra_shell_arg))
4494 + STRLEN(p_shcf) + STRLEN(cmd) + 4, TRUE);
4495 if (newcmd == NULL)
4496 x = 0;
4497 else
4498 {
4499 sprintf((char *)newcmd, "%s %s %s %s", p_sh,
4500 extra_shell_arg == NULL ? "" : (char *)extra_shell_arg,
4501 (char *)p_shcf,
4502 (char *)cmd);
4503 x = system((char *)newcmd);
4504 vim_free(newcmd);
4505 }
Bram Moolenaara06ecab2016-07-16 14:47:36 +02004506# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004507 }
4508# ifdef VMS
4509 x = vms_sys_status(x);
4510# endif
4511 if (emsg_silent)
4512 ;
4513 else if (x == 127)
4514 MSG_PUTS(_("\nCannot execute shell sh\n"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004515 else if (x && !(options & SHELL_SILENT))
4516 {
4517 MSG_PUTS(_("\nshell returned "));
4518 msg_outnum((long)x);
4519 msg_putchar('\n');
4520 }
4521
4522 if (tmode == TMODE_RAW)
4523 settmode(TMODE_RAW); /* set to raw mode */
4524# ifdef FEAT_TITLE
4525 resettitle();
4526# endif
Bram Moolenaar1a0316c2013-03-13 17:50:25 +01004527# if defined(FEAT_CLIPBOARD) && defined(FEAT_X11)
4528 restore_clipboard();
4529# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004530 return x;
Bram Moolenaar13568252018-03-16 20:46:58 +01004531}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004532
Bram Moolenaar13568252018-03-16 20:46:58 +01004533#else /* USE_SYSTEM */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004534
Bram Moolenaardf177f62005-02-22 08:39:57 +00004535# define EXEC_FAILED 122 /* Exit code when shell didn't execute. Don't use
4536 127, some shells use that already */
Bram Moolenaarb109bb42017-08-21 21:07:29 +02004537# define OPEN_NULL_FAILED 123 /* Exit code if /dev/null can't be opened */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004538
Bram Moolenaar13568252018-03-16 20:46:58 +01004539/*
4540 * Don't use system(), use fork()/exec().
4541 */
4542 static int
4543mch_call_shell_fork(
4544 char_u *cmd,
4545 int options) /* SHELL_*, see vim.h */
4546{
4547 int tmode = cur_tmode;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004548 pid_t pid;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004549 pid_t wpid = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004550 pid_t wait_pid = 0;
4551# ifdef HAVE_UNION_WAIT
4552 union wait status;
4553# else
4554 int status = -1;
4555# endif
4556 int retval = -1;
4557 char **argv = NULL;
Bram Moolenaar13568252018-03-16 20:46:58 +01004558 char_u *tofree1 = NULL;
4559 char_u *tofree2 = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004560 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004561 int pty_master_fd = -1; /* for pty's */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004562# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004563 int pty_slave_fd = -1;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004564# endif
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004565 int fd_toshell[2]; /* for pipes */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004566 int fd_fromshell[2];
4567 int pipe_error = FALSE;
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004568 int did_settmode = FALSE; /* settmode(TMODE_RAW) called */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004569
4570 out_flush();
4571 if (options & SHELL_COOKED)
4572 settmode(TMODE_COOK); /* set to normal mode */
4573
Bram Moolenaar13568252018-03-16 20:46:58 +01004574 if (build_argv(cmd, &argv, &tofree1, &tofree2) == FAIL)
Bram Moolenaar835dc632016-02-07 14:27:38 +01004575 goto error;
Bram Moolenaarea35ef62011-08-04 22:59:28 +02004576
Bram Moolenaar071d4272004-06-13 20:20:40 +00004577 /*
Bram Moolenaardf177f62005-02-22 08:39:57 +00004578 * For the GUI, when writing the output into the buffer and when reading
4579 * input from the buffer: Try using a pseudo-tty to get the stdin/stdout
4580 * of the executed command into the Vim window. Or use a pipe.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004581 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004582 if ((options & (SHELL_READ|SHELL_WRITE))
4583# ifdef FEAT_GUI
4584 || (gui.in_use && show_shell_mess)
4585# endif
4586 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00004587 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00004588# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004589 /*
4590 * Try to open a master pty.
4591 * If this works, open the slave pty.
4592 * If the slave can't be opened, close the master pty.
4593 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004594 if (p_guipty && !(options & (SHELL_READ|SHELL_WRITE)))
Bram Moolenaar7c9aec42017-08-03 13:51:25 +02004595 open_pty(&pty_master_fd, &pty_slave_fd, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004596 /*
4597 * If not opening a pty or it didn't work, try using pipes.
4598 */
4599 if (pty_master_fd < 0)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004600# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004601 {
4602 pipe_error = (pipe(fd_toshell) < 0);
4603 if (!pipe_error) /* pipe create OK */
4604 {
4605 pipe_error = (pipe(fd_fromshell) < 0);
4606 if (pipe_error) /* pipe create failed */
4607 {
4608 close(fd_toshell[0]);
4609 close(fd_toshell[1]);
4610 }
4611 }
4612 if (pipe_error)
4613 {
4614 MSG_PUTS(_("\nCannot create pipes\n"));
4615 out_flush();
4616 }
4617 }
4618 }
4619
4620 if (!pipe_error) /* pty or pipe opened or not used */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004621 {
Bram Moolenaarbb09ceb2016-10-18 16:27:23 +02004622 SIGSET_DECL(curset)
4623
Bram Moolenaar071d4272004-06-13 20:20:40 +00004624# ifdef __BEOS__
4625 beos_cleanup_read_thread();
4626# endif
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004627
Bram Moolenaarbb09ceb2016-10-18 16:27:23 +02004628 BLOCK_SIGNALS(&curset);
4629 pid = fork(); /* maybe we should use vfork() */
4630 if (pid == -1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004631 {
Bram Moolenaarbb09ceb2016-10-18 16:27:23 +02004632 UNBLOCK_SIGNALS(&curset);
4633
Bram Moolenaar071d4272004-06-13 20:20:40 +00004634 MSG_PUTS(_("\nCannot fork\n"));
Bram Moolenaardf177f62005-02-22 08:39:57 +00004635 if ((options & (SHELL_READ|SHELL_WRITE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004636# ifdef FEAT_GUI
Bram Moolenaardf177f62005-02-22 08:39:57 +00004637 || (gui.in_use && show_shell_mess)
4638# endif
4639 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00004640 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00004641# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004642 if (pty_master_fd >= 0) /* close the pseudo tty */
4643 {
4644 close(pty_master_fd);
4645 close(pty_slave_fd);
4646 }
4647 else /* close the pipes */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004648# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004649 {
4650 close(fd_toshell[0]);
4651 close(fd_toshell[1]);
4652 close(fd_fromshell[0]);
4653 close(fd_fromshell[1]);
4654 }
4655 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004656 }
4657 else if (pid == 0) /* child */
4658 {
4659 reset_signals(); /* handle signals normally */
Bram Moolenaarbb09ceb2016-10-18 16:27:23 +02004660 UNBLOCK_SIGNALS(&curset);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004661
Bram Moolenaar819524702018-02-27 19:10:00 +01004662# ifdef FEAT_JOB_CHANNEL
4663 if (ch_log_active())
4664 /* close the log file in the child */
4665 ch_logfile((char_u *)"", (char_u *)"");
4666# endif
4667
Bram Moolenaar071d4272004-06-13 20:20:40 +00004668 if (!show_shell_mess || (options & SHELL_EXPAND))
4669 {
4670 int fd;
4671
4672 /*
4673 * Don't want to show any message from the shell. Can't just
4674 * close stdout and stderr though, because some systems will
4675 * break if you try to write to them after that, so we must
4676 * use dup() to replace them with something else -- webb
4677 * Connect stdin to /dev/null too, so ":n `cat`" doesn't hang,
4678 * waiting for input.
4679 */
4680 fd = open("/dev/null", O_RDWR | O_EXTRA, 0);
4681 fclose(stdin);
4682 fclose(stdout);
4683 fclose(stderr);
4684
4685 /*
4686 * If any of these open()'s and dup()'s fail, we just continue
4687 * anyway. It's not fatal, and on most systems it will make
4688 * no difference at all. On a few it will cause the execvp()
4689 * to exit with a non-zero status even when the completion
4690 * could be done, which is nothing too serious. If the open()
4691 * or dup() failed we'd just do the same thing ourselves
4692 * anyway -- webb
4693 */
4694 if (fd >= 0)
4695 {
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004696 ignored = dup(fd); /* To replace stdin (fd 0) */
4697 ignored = dup(fd); /* To replace stdout (fd 1) */
4698 ignored = dup(fd); /* To replace stderr (fd 2) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004699
4700 /* Don't need this now that we've duplicated it */
4701 close(fd);
4702 }
4703 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004704 else if ((options & (SHELL_READ|SHELL_WRITE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004705# ifdef FEAT_GUI
Bram Moolenaardf177f62005-02-22 08:39:57 +00004706 || gui.in_use
4707# endif
4708 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00004709 {
4710
Bram Moolenaardf177f62005-02-22 08:39:57 +00004711# ifdef HAVE_SETSID
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004712 /* Create our own process group, so that the child and all its
4713 * children can be kill()ed. Don't do this when using pipes,
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004714 * because stdin is not a tty, we would lose /dev/tty. */
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004715 if (p_stmp)
Bram Moolenaar07256082009-02-04 13:19:42 +00004716 {
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004717 (void)setsid();
Bram Moolenaar07256082009-02-04 13:19:42 +00004718# if defined(SIGHUP)
4719 /* When doing "!xterm&" and 'shell' is bash: the shell
4720 * will exit and send SIGHUP to all processes in its
4721 * group, killing the just started process. Ignore SIGHUP
4722 * to avoid that. (suggested by Simon Schubert)
4723 */
4724 signal(SIGHUP, SIG_IGN);
4725# endif
4726 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004727# endif
4728# ifdef FEAT_GUI
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004729 if (pty_slave_fd >= 0)
4730 {
4731 /* push stream discipline modules */
4732 if (options & SHELL_COOKED)
4733 SetupSlavePTY(pty_slave_fd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004734# ifdef TIOCSCTTY
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004735 /* Try to become controlling tty (probably doesn't work,
4736 * unless run by root) */
4737 ioctl(pty_slave_fd, TIOCSCTTY, (char *)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004738# endif
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004739 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004740# endif
Bram Moolenaar493359e2018-06-12 20:25:52 +02004741 set_default_child_environment(FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004742
Bram Moolenaara5792f52005-11-23 21:25:05 +00004743 /*
4744 * stderr is only redirected when using the GUI, so that a
4745 * program like gpg can still access the terminal to get a
4746 * passphrase using stderr.
4747 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004748# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004749 if (pty_master_fd >= 0)
4750 {
4751 close(pty_master_fd); /* close master side of pty */
4752
4753 /* set up stdin/stdout/stderr for the child */
4754 close(0);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004755 ignored = dup(pty_slave_fd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004756 close(1);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004757 ignored = dup(pty_slave_fd);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004758 if (gui.in_use)
4759 {
4760 close(2);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004761 ignored = dup(pty_slave_fd);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004762 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004763
4764 close(pty_slave_fd); /* has been dupped, close it now */
4765 }
4766 else
Bram Moolenaardf177f62005-02-22 08:39:57 +00004767# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004768 {
4769 /* set up stdin for the child */
4770 close(fd_toshell[1]);
4771 close(0);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004772 ignored = dup(fd_toshell[0]);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004773 close(fd_toshell[0]);
4774
4775 /* set up stdout for the child */
4776 close(fd_fromshell[0]);
4777 close(1);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004778 ignored = dup(fd_fromshell[1]);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004779 close(fd_fromshell[1]);
4780
Bram Moolenaara5792f52005-11-23 21:25:05 +00004781# ifdef FEAT_GUI
4782 if (gui.in_use)
4783 {
4784 /* set up stderr for the child */
4785 close(2);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004786 ignored = dup(1);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004787 }
4788# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004789 }
4790 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00004791
Bram Moolenaar071d4272004-06-13 20:20:40 +00004792 /*
4793 * There is no type cast for the argv, because the type may be
4794 * different on different machines. This may cause a warning
4795 * message with strict compilers, don't worry about it.
4796 * Call _exit() instead of exit() to avoid closing the connection
4797 * to the X server (esp. with GTK, which uses atexit()).
4798 */
4799 execvp(argv[0], argv);
4800 _exit(EXEC_FAILED); /* exec failed, return failure code */
4801 }
4802 else /* parent */
4803 {
4804 /*
4805 * While child is running, ignore terminating signals.
Bram Moolenaardf177f62005-02-22 08:39:57 +00004806 * Do catch CTRL-C, so that "got_int" is set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004807 */
4808 catch_signals(SIG_IGN, SIG_ERR);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004809 catch_int_signal();
Bram Moolenaarbb09ceb2016-10-18 16:27:23 +02004810 UNBLOCK_SIGNALS(&curset);
Bram Moolenaarc4d4ac22016-11-07 22:42:57 +01004811# ifdef FEAT_JOB_CHANNEL
4812 ++dont_check_job_ended;
4813# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004814 /*
4815 * For the GUI we redirect stdin, stdout and stderr to our window.
Bram Moolenaardf177f62005-02-22 08:39:57 +00004816 * This is also used to pipe stdin/stdout to/from the external
4817 * command.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004818 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004819 if ((options & (SHELL_READ|SHELL_WRITE))
4820# ifdef FEAT_GUI
4821 || (gui.in_use && show_shell_mess)
4822# endif
4823 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00004824 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00004825# define BUFLEN 100 /* length for buffer, pseudo tty limit is 128 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004826 char_u buffer[BUFLEN + 1];
Bram Moolenaardf177f62005-02-22 08:39:57 +00004827# ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00004828 int buffer_off = 0; /* valid bytes in buffer[] */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004829# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004830 char_u ta_buf[BUFLEN + 1]; /* TypeAHead */
4831 int ta_len = 0; /* valid bytes in ta_buf[] */
4832 int len;
4833 int p_more_save;
4834 int old_State;
4835 int c;
4836 int toshell_fd;
4837 int fromshell_fd;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004838 garray_T ga;
4839 int noread_cnt;
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004840# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4841 struct timeval start_tv;
4842# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004843
Bram Moolenaardf177f62005-02-22 08:39:57 +00004844# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004845 if (pty_master_fd >= 0)
4846 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004847 fromshell_fd = pty_master_fd;
4848 toshell_fd = dup(pty_master_fd);
4849 }
4850 else
Bram Moolenaardf177f62005-02-22 08:39:57 +00004851# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004852 {
4853 close(fd_toshell[0]);
4854 close(fd_fromshell[1]);
4855 toshell_fd = fd_toshell[1];
4856 fromshell_fd = fd_fromshell[0];
4857 }
4858
4859 /*
4860 * Write to the child if there are typed characters.
4861 * Read from the child if there are characters available.
4862 * Repeat the reading a few times if more characters are
4863 * available. Need to check for typed keys now and then, but
4864 * not too often (delays when no chars are available).
4865 * This loop is quit if no characters can be read from the pty
4866 * (WaitForChar detected special condition), or there are no
4867 * characters available and the child has exited.
4868 * Only check if the child has exited when there is no more
4869 * output. The child may exit before all the output has
4870 * been printed.
4871 *
4872 * Currently this busy loops!
4873 * This can probably dead-lock when the write blocks!
4874 */
4875 p_more_save = p_more;
4876 p_more = FALSE;
4877 old_State = State;
4878 State = EXTERNCMD; /* don't redraw at window resize */
4879
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004880 if ((options & SHELL_WRITE) && toshell_fd >= 0)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004881 {
4882 /* Fork a process that will write the lines to the
4883 * external program. */
4884 if ((wpid = fork()) == -1)
4885 {
4886 MSG_PUTS(_("\nCannot fork\n"));
4887 }
Bram Moolenaar205b8862011-09-07 15:04:31 +02004888 else if (wpid == 0) /* child */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004889 {
4890 linenr_T lnum = curbuf->b_op_start.lnum;
4891 int written = 0;
Bram Moolenaar89d40322006-08-29 15:30:07 +00004892 char_u *lp = ml_get(lnum);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004893 size_t l;
4894
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00004895 close(fromshell_fd);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004896 for (;;)
4897 {
Bram Moolenaar89d40322006-08-29 15:30:07 +00004898 l = STRLEN(lp + written);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004899 if (l == 0)
4900 len = 0;
Bram Moolenaar89d40322006-08-29 15:30:07 +00004901 else if (lp[written] == NL)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004902 /* NL -> NUL translation */
4903 len = write(toshell_fd, "", (size_t)1);
4904 else
4905 {
Bram Moolenaar70b2a562012-01-10 22:26:17 +01004906 char_u *s = vim_strchr(lp + written, NL);
4907
Bram Moolenaar89d40322006-08-29 15:30:07 +00004908 len = write(toshell_fd, (char *)lp + written,
Bram Moolenaar78a15312009-05-15 19:33:18 +00004909 s == NULL ? l
4910 : (size_t)(s - (lp + written)));
Bram Moolenaardf177f62005-02-22 08:39:57 +00004911 }
Bram Moolenaar78a15312009-05-15 19:33:18 +00004912 if (len == (int)l)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004913 {
4914 /* Finished a line, add a NL, unless this line
4915 * should not have one. */
4916 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004917 || (!curbuf->b_p_bin
4918 && curbuf->b_p_fixeol)
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01004919 || (lnum != curbuf->b_no_eol_lnum
Bram Moolenaardf177f62005-02-22 08:39:57 +00004920 && (lnum !=
4921 curbuf->b_ml.ml_line_count
4922 || curbuf->b_p_eol)))
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004923 ignored = write(toshell_fd, "\n",
4924 (size_t)1);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004925 ++lnum;
4926 if (lnum > curbuf->b_op_end.lnum)
4927 {
4928 /* finished all the lines, close pipe */
4929 close(toshell_fd);
4930 toshell_fd = -1;
4931 break;
4932 }
Bram Moolenaar89d40322006-08-29 15:30:07 +00004933 lp = ml_get(lnum);
Bram Moolenaardf177f62005-02-22 08:39:57 +00004934 written = 0;
4935 }
4936 else if (len > 0)
4937 written += len;
4938 }
4939 _exit(0);
4940 }
Bram Moolenaar205b8862011-09-07 15:04:31 +02004941 else /* parent */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004942 {
4943 close(toshell_fd);
4944 toshell_fd = -1;
4945 }
4946 }
4947
4948 if (options & SHELL_READ)
4949 ga_init2(&ga, 1, BUFLEN);
4950
4951 noread_cnt = 0;
Bram Moolenaar833eb1d2016-11-24 17:22:50 +01004952# ifdef ELAPSED_FUNC
4953 ELAPSED_INIT(start_tv);
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004954# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004955 for (;;)
4956 {
4957 /*
4958 * Check if keys have been typed, write them to the child
Bram Moolenaar5b962cf2005-12-12 21:58:40 +00004959 * if there are any.
4960 * Don't do this if we are expanding wild cards (would eat
4961 * typeahead).
4962 * Don't do this when filtering and terminal is in cooked
4963 * mode, the shell command will handle the I/O. Avoids
4964 * that a typed password is echoed for ssh or gpg command.
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004965 * Don't get characters when the child has already
4966 * finished (wait_pid == 0).
Bram Moolenaardf177f62005-02-22 08:39:57 +00004967 * Don't read characters unless we didn't get output for a
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004968 * while (noread_cnt > 4), avoids that ":r !ls" eats
4969 * typeahead.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004970 */
4971 len = 0;
4972 if (!(options & SHELL_EXPAND)
Bram Moolenaar5b962cf2005-12-12 21:58:40 +00004973 && ((options &
4974 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4975 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004976# ifdef FEAT_GUI
Bram Moolenaar5b962cf2005-12-12 21:58:40 +00004977 || gui.in_use
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004978# endif
Bram Moolenaar5b962cf2005-12-12 21:58:40 +00004979 )
Bram Moolenaar12033fb2005-12-16 21:49:31 +00004980 && wait_pid == 0
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004981 && (ta_len > 0 || noread_cnt > 4))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004982 {
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004983 if (ta_len == 0)
4984 {
4985 /* Get extra characters when we don't have any.
4986 * Reset the counter and timer. */
4987 noread_cnt = 0;
Bram Moolenaar833eb1d2016-11-24 17:22:50 +01004988# ifdef ELAPSED_FUNC
4989 ELAPSED_INIT(start_tv);
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00004990# endif
4991 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4992 }
4993 if (ta_len > 0 || len > 0)
4994 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004995 /*
4996 * For pipes:
4997 * Check for CTRL-C: send interrupt signal to child.
4998 * Check for CTRL-D: EOF, close pipe to child.
4999 */
5000 if (len == 1 && (pty_master_fd < 0 || cmd != NULL))
5001 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00005002 /*
5003 * Send SIGINT to the child's group or all
5004 * processes in our group.
5005 */
Bram Moolenaarfae42832017-08-01 22:24:26 +02005006 may_send_sigint(ta_buf[ta_len], pid, wpid);
5007
Bram Moolenaar071d4272004-06-13 20:20:40 +00005008 if (pty_master_fd < 0 && toshell_fd >= 0
5009 && ta_buf[ta_len] == Ctrl_D)
5010 {
5011 close(toshell_fd);
5012 toshell_fd = -1;
5013 }
5014 }
5015
5016 /* replace K_BS by <BS> and K_DEL by <DEL> */
5017 for (i = ta_len; i < ta_len + len; ++i)
5018 {
5019 if (ta_buf[i] == CSI && len - i > 2)
5020 {
5021 c = TERMCAP2KEY(ta_buf[i + 1], ta_buf[i + 2]);
5022 if (c == K_DEL || c == K_KDEL || c == K_BS)
5023 {
5024 mch_memmove(ta_buf + i + 1, ta_buf + i + 3,
5025 (size_t)(len - i - 2));
5026 if (c == K_DEL || c == K_KDEL)
5027 ta_buf[i] = DEL;
5028 else
5029 ta_buf[i] = Ctrl_H;
5030 len -= 2;
5031 }
5032 }
5033 else if (ta_buf[i] == '\r')
5034 ta_buf[i] = '\n';
Bram Moolenaardf177f62005-02-22 08:39:57 +00005035# ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00005036 if (has_mbyte)
Bram Moolenaarfeba08b2009-06-16 13:12:07 +00005037 i += (*mb_ptr2len_len)(ta_buf + i,
5038 ta_len + len - i) - 1;
Bram Moolenaardf177f62005-02-22 08:39:57 +00005039# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005040 }
5041
5042 /*
5043 * For pipes: echo the typed characters.
5044 * For a pty this does not seem to work.
5045 */
5046 if (pty_master_fd < 0)
5047 {
5048 for (i = ta_len; i < ta_len + len; ++i)
5049 {
5050 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
5051 msg_putchar(ta_buf[i]);
Bram Moolenaardf177f62005-02-22 08:39:57 +00005052# ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00005053 else if (has_mbyte)
5054 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00005055 int l = (*mb_ptr2len)(ta_buf + i);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005056
5057 msg_outtrans_len(ta_buf + i, l);
5058 i += l - 1;
5059 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00005060# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005061 else
5062 msg_outtrans_len(ta_buf + i, 1);
5063 }
5064 windgoto(msg_row, msg_col);
5065 out_flush();
5066 }
5067
5068 ta_len += len;
5069
5070 /*
5071 * Write the characters to the child, unless EOF has
5072 * been typed for pipes. Write one character at a
Bram Moolenaare37d50a2008-08-06 17:06:04 +00005073 * time, to avoid losing too much typeahead.
Bram Moolenaardf177f62005-02-22 08:39:57 +00005074 * When writing buffer lines, drop the typed
5075 * characters (only check for CTRL-C).
Bram Moolenaar071d4272004-06-13 20:20:40 +00005076 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00005077 if (options & SHELL_WRITE)
5078 ta_len = 0;
5079 else if (toshell_fd >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005080 {
5081 len = write(toshell_fd, (char *)ta_buf, (size_t)1);
5082 if (len > 0)
5083 {
5084 ta_len -= len;
5085 mch_memmove(ta_buf, ta_buf + len, ta_len);
5086 }
5087 }
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00005088 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005089 }
5090
Bram Moolenaardf177f62005-02-22 08:39:57 +00005091 if (got_int)
5092 {
5093 /* CTRL-C sends a signal to the child, we ignore it
5094 * ourselves */
5095# ifdef HAVE_SETSID
5096 kill(-pid, SIGINT);
5097# else
5098 kill(0, SIGINT);
5099# endif
5100 if (wpid > 0)
5101 kill(wpid, SIGINT);
5102 got_int = FALSE;
5103 }
5104
Bram Moolenaar071d4272004-06-13 20:20:40 +00005105 /*
5106 * Check if the child has any characters to be printed.
5107 * Read them and write them to our window. Repeat this as
5108 * long as there is something to do, avoid the 10ms wait
5109 * for mch_inchar(), or sending typeahead characters to
5110 * the external process.
5111 * TODO: This should handle escape sequences, compatible
5112 * to some terminal (vt52?).
5113 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00005114 ++noread_cnt;
Bram Moolenaar8fdd7212016-03-26 19:41:48 +01005115 while (RealWaitForChar(fromshell_fd, 10L, NULL, NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005116 {
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01005117 len = read_eintr(fromshell_fd, buffer
Bram Moolenaardf177f62005-02-22 08:39:57 +00005118# ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00005119 + buffer_off, (size_t)(BUFLEN - buffer_off)
Bram Moolenaardf177f62005-02-22 08:39:57 +00005120# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005121 , (size_t)BUFLEN
Bram Moolenaardf177f62005-02-22 08:39:57 +00005122# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005123 );
5124 if (len <= 0) /* end of file or error */
5125 goto finished;
Bram Moolenaardf177f62005-02-22 08:39:57 +00005126
5127 noread_cnt = 0;
5128 if (options & SHELL_READ)
5129 {
5130 /* Do NUL -> NL translation, append NL separated
5131 * lines to the current buffer. */
5132 for (i = 0; i < len; ++i)
5133 {
5134 if (buffer[i] == NL)
5135 append_ga_line(&ga);
5136 else if (buffer[i] == NUL)
5137 ga_append(&ga, NL);
5138 else
5139 ga_append(&ga, buffer[i]);
5140 }
5141 }
5142# ifdef FEAT_MBYTE
5143 else if (has_mbyte)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005144 {
5145 int l;
Bram Moolenaara2150ac2018-03-17 13:15:17 +01005146 char_u *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005147
Bram Moolenaardf177f62005-02-22 08:39:57 +00005148 len += buffer_off;
5149 buffer[len] = NUL;
5150
Bram Moolenaar071d4272004-06-13 20:20:40 +00005151 /* Check if the last character in buffer[] is
5152 * incomplete, keep these bytes for the next
5153 * round. */
5154 for (p = buffer; p < buffer + len; p += l)
5155 {
Bram Moolenaard3c907b2016-08-17 21:32:09 +02005156 l = MB_CPTR2LEN(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005157 if (l == 0)
5158 l = 1; /* NUL byte? */
5159 else if (MB_BYTE2LEN(*p) != l)
5160 break;
5161 }
5162 if (p == buffer) /* no complete character */
5163 {
5164 /* avoid getting stuck at an illegal byte */
5165 if (len >= 12)
5166 ++p;
5167 else
5168 {
5169 buffer_off = len;
5170 continue;
5171 }
5172 }
5173 c = *p;
5174 *p = NUL;
5175 msg_puts(buffer);
5176 if (p < buffer + len)
5177 {
5178 *p = c;
5179 buffer_off = (buffer + len) - p;
5180 mch_memmove(buffer, p, buffer_off);
5181 continue;
5182 }
5183 buffer_off = 0;
5184 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00005185# endif /* FEAT_MBYTE */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005186 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005187 {
5188 buffer[len] = NUL;
5189 msg_puts(buffer);
5190 }
5191
5192 windgoto(msg_row, msg_col);
5193 cursor_on();
5194 out_flush();
5195 if (got_int)
5196 break;
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00005197
Bram Moolenaar833eb1d2016-11-24 17:22:50 +01005198# ifdef ELAPSED_FUNC
Bram Moolenaar17fe5e12016-04-04 22:03:08 +02005199 if (wait_pid == 0)
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00005200 {
Bram Moolenaar833eb1d2016-11-24 17:22:50 +01005201 long msec = ELAPSED_FUNC(start_tv);
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00005202
5203 /* Avoid that we keep looping here without
5204 * checking for a CTRL-C for a long time. Don't
5205 * break out too often to avoid losing typeahead. */
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00005206 if (msec > 2000)
5207 {
5208 noread_cnt = 5;
5209 break;
5210 }
5211 }
5212# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005213 }
5214
Bram Moolenaar17fe5e12016-04-04 22:03:08 +02005215 /* If we already detected the child has finished, continue
5216 * reading output for a short while. Some text may be
5217 * buffered. */
Bram Moolenaar12033fb2005-12-16 21:49:31 +00005218 if (wait_pid == pid)
Bram Moolenaar17fe5e12016-04-04 22:03:08 +02005219 {
5220 if (noread_cnt < 5)
5221 continue;
Bram Moolenaar12033fb2005-12-16 21:49:31 +00005222 break;
Bram Moolenaar17fe5e12016-04-04 22:03:08 +02005223 }
Bram Moolenaar12033fb2005-12-16 21:49:31 +00005224
Bram Moolenaar071d4272004-06-13 20:20:40 +00005225 /*
5226 * Check if the child still exists, before checking for
Bram Moolenaare37d50a2008-08-06 17:06:04 +00005227 * typed characters (otherwise we would lose typeahead).
Bram Moolenaar071d4272004-06-13 20:20:40 +00005228 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00005229# ifdef __NeXT__
Bram Moolenaar205b8862011-09-07 15:04:31 +02005230 wait_pid = wait4(pid, &status, WNOHANG, (struct rusage *)0);
Bram Moolenaardf177f62005-02-22 08:39:57 +00005231# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005232 wait_pid = waitpid(pid, &status, WNOHANG);
Bram Moolenaardf177f62005-02-22 08:39:57 +00005233# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005234 if ((wait_pid == (pid_t)-1 && errno == ECHILD)
5235 || (wait_pid == pid && WIFEXITED(status)))
5236 {
Bram Moolenaar12033fb2005-12-16 21:49:31 +00005237 /* Don't break the loop yet, try reading more
5238 * characters from "fromshell_fd" first. When using
5239 * pipes there might still be something to read and
5240 * then we'll break the loop at the "break" above. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005241 wait_pid = pid;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005242 }
Bram Moolenaar12033fb2005-12-16 21:49:31 +00005243 else
5244 wait_pid = 0;
Bram Moolenaar090cfc12013-03-19 12:35:42 +01005245
Bram Moolenaar95a51352013-03-21 22:53:50 +01005246# if defined(FEAT_XCLIPBOARD) && defined(FEAT_X11)
Bram Moolenaar090cfc12013-03-19 12:35:42 +01005247 /* Handle any X events, e.g. serving the clipboard. */
5248 clip_update();
5249# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005250 }
5251finished:
5252 p_more = p_more_save;
Bram Moolenaardf177f62005-02-22 08:39:57 +00005253 if (options & SHELL_READ)
5254 {
5255 if (ga.ga_len > 0)
5256 {
5257 append_ga_line(&ga);
5258 /* remember that the NL was missing */
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01005259 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
Bram Moolenaardf177f62005-02-22 08:39:57 +00005260 }
5261 else
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01005262 curbuf->b_no_eol_lnum = 0;
Bram Moolenaardf177f62005-02-22 08:39:57 +00005263 ga_clear(&ga);
5264 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005265
Bram Moolenaar071d4272004-06-13 20:20:40 +00005266 /*
5267 * Give all typeahead that wasn't used back to ui_inchar().
5268 */
5269 if (ta_len)
5270 ui_inchar_undo(ta_buf, ta_len);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005271 State = old_State;
5272 if (toshell_fd >= 0)
5273 close(toshell_fd);
5274 close(fromshell_fd);
5275 }
Bram Moolenaar95a51352013-03-21 22:53:50 +01005276# if defined(FEAT_XCLIPBOARD) && defined(FEAT_X11)
Bram Moolenaar090cfc12013-03-19 12:35:42 +01005277 else
5278 {
Bram Moolenaar0abe0522016-08-28 16:53:12 +02005279 long delay_msec = 1;
5280
Bram Moolenaar090cfc12013-03-19 12:35:42 +01005281 /*
5282 * Similar to the loop above, but only handle X events, no
5283 * I/O.
5284 */
5285 for (;;)
5286 {
5287 if (got_int)
5288 {
5289 /* CTRL-C sends a signal to the child, we ignore it
5290 * ourselves */
5291# ifdef HAVE_SETSID
5292 kill(-pid, SIGINT);
5293# else
5294 kill(0, SIGINT);
5295# endif
5296 got_int = FALSE;
5297 }
5298# ifdef __NeXT__
5299 wait_pid = wait4(pid, &status, WNOHANG, (struct rusage *)0);
5300# else
5301 wait_pid = waitpid(pid, &status, WNOHANG);
5302# endif
5303 if ((wait_pid == (pid_t)-1 && errno == ECHILD)
5304 || (wait_pid == pid && WIFEXITED(status)))
5305 {
5306 wait_pid = pid;
5307 break;
5308 }
5309
5310 /* Handle any X events, e.g. serving the clipboard. */
5311 clip_update();
5312
Bram Moolenaar0abe0522016-08-28 16:53:12 +02005313 /* Wait for 1 to 10 msec. 1 is faster but gives the child
5314 * less time. */
5315 mch_delay(delay_msec, TRUE);
5316 if (++delay_msec > 10)
5317 delay_msec = 10;
Bram Moolenaar090cfc12013-03-19 12:35:42 +01005318 }
5319 }
5320# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005321
5322 /*
5323 * Wait until our child has exited.
5324 * Ignore wait() returning pids of other children and returning
5325 * because of some signal like SIGWINCH.
5326 * Don't wait if wait_pid was already set above, indicating the
5327 * child already exited.
5328 */
Bram Moolenaar205b8862011-09-07 15:04:31 +02005329 if (wait_pid != pid)
5330 wait_pid = wait4pid(pid, &status);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005331
Bram Moolenaar624891f2010-10-13 16:22:09 +02005332# ifdef FEAT_GUI
5333 /* Close slave side of pty. Only do this after the child has
5334 * exited, otherwise the child may hang when it tries to write on
5335 * the pty. */
5336 if (pty_master_fd >= 0)
5337 close(pty_slave_fd);
5338# endif
5339
Bram Moolenaardf177f62005-02-22 08:39:57 +00005340 /* Make sure the child that writes to the external program is
5341 * dead. */
5342 if (wpid > 0)
Bram Moolenaar205b8862011-09-07 15:04:31 +02005343 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00005344 kill(wpid, SIGKILL);
Bram Moolenaar205b8862011-09-07 15:04:31 +02005345 wait4pid(wpid, NULL);
5346 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00005347
Bram Moolenaarc4d4ac22016-11-07 22:42:57 +01005348# ifdef FEAT_JOB_CHANNEL
5349 --dont_check_job_ended;
5350# endif
5351
Bram Moolenaar071d4272004-06-13 20:20:40 +00005352 /*
5353 * Set to raw mode right now, otherwise a CTRL-C after
5354 * catch_signals() will kill Vim.
5355 */
5356 if (tmode == TMODE_RAW)
5357 settmode(TMODE_RAW);
5358 did_settmode = TRUE;
5359 set_signals();
5360
5361 if (WIFEXITED(status))
5362 {
Bram Moolenaar9d75c832005-01-25 21:57:23 +00005363 /* LINTED avoid "bitwise operation on signed value" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005364 retval = WEXITSTATUS(status);
Bram Moolenaar75676462013-01-30 14:55:42 +01005365 if (retval != 0 && !emsg_silent)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005366 {
5367 if (retval == EXEC_FAILED)
5368 {
5369 MSG_PUTS(_("\nCannot execute shell "));
5370 msg_outtrans(p_sh);
5371 msg_putchar('\n');
5372 }
5373 else if (!(options & SHELL_SILENT))
5374 {
5375 MSG_PUTS(_("\nshell returned "));
5376 msg_outnum((long)retval);
5377 msg_putchar('\n');
5378 }
5379 }
5380 }
5381 else
5382 MSG_PUTS(_("\nCommand terminated\n"));
5383 }
5384 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005385
5386error:
5387 if (!did_settmode)
5388 if (tmode == TMODE_RAW)
5389 settmode(TMODE_RAW); /* set to raw mode */
5390# ifdef FEAT_TITLE
5391 resettitle();
5392# endif
Bram Moolenaar13568252018-03-16 20:46:58 +01005393 vim_free(argv);
5394 vim_free(tofree1);
5395 vim_free(tofree2);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005396
5397 return retval;
Bram Moolenaar13568252018-03-16 20:46:58 +01005398}
Bram Moolenaar071d4272004-06-13 20:20:40 +00005399#endif /* USE_SYSTEM */
Bram Moolenaar13568252018-03-16 20:46:58 +01005400
5401 int
5402mch_call_shell(
5403 char_u *cmd,
5404 int options) /* SHELL_*, see vim.h */
5405{
5406#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
5407 if (gui.in_use && vim_strchr(p_go, GO_TERMINAL) != NULL)
5408 return mch_call_shell_terminal(cmd, options);
5409#endif
5410#ifdef USE_SYSTEM
5411 return mch_call_shell_system(cmd, options);
5412#else
5413 return mch_call_shell_fork(cmd, options);
5414#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005415}
5416
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005417#if defined(FEAT_JOB_CHANNEL) || defined(PROTO)
Bram Moolenaar835dc632016-02-07 14:27:38 +01005418 void
Bram Moolenaar493359e2018-06-12 20:25:52 +02005419mch_job_start(char **argv, job_T *job, jobopt_T *options, int is_terminal)
Bram Moolenaar835dc632016-02-07 14:27:38 +01005420{
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005421 pid_t pid;
Bram Moolenaar7c9aec42017-08-03 13:51:25 +02005422 int fd_in[2] = {-1, -1}; /* for stdin */
5423 int fd_out[2] = {-1, -1}; /* for stdout */
5424 int fd_err[2] = {-1, -1}; /* for stderr */
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02005425 int pty_master_fd = -1;
5426 int pty_slave_fd = -1;
Bram Moolenaar16eb4f82016-02-14 23:02:34 +01005427 channel_T *channel = NULL;
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005428 int use_null_for_in = options->jo_io[PART_IN] == JIO_NULL;
5429 int use_null_for_out = options->jo_io[PART_OUT] == JIO_NULL;
5430 int use_null_for_err = options->jo_io[PART_ERR] == JIO_NULL;
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005431 int use_file_for_in = options->jo_io[PART_IN] == JIO_FILE;
Bram Moolenaare98d1212016-03-08 15:37:41 +01005432 int use_file_for_out = options->jo_io[PART_OUT] == JIO_FILE;
5433 int use_file_for_err = options->jo_io[PART_ERR] == JIO_FILE;
Bram Moolenaarb2412082017-08-20 18:09:14 +02005434 int use_buffer_for_in = options->jo_io[PART_IN] == JIO_BUFFER;
Bram Moolenaarc25558b2016-03-03 21:02:23 +01005435 int use_out_for_err = options->jo_io[PART_ERR] == JIO_OUT;
Bram Moolenaarbb09ceb2016-10-18 16:27:23 +02005436 SIGSET_DECL(curset)
Bram Moolenaar835dc632016-02-07 14:27:38 +01005437
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005438 if (use_out_for_err && use_null_for_out)
5439 use_null_for_err = TRUE;
5440
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005441 /* default is to fail */
5442 job->jv_status = JOB_FAILED;
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005443
Bram Moolenaarb2412082017-08-20 18:09:14 +02005444 if (options->jo_pty
5445 && (!(use_file_for_in || use_null_for_in)
5446 || !(use_file_for_in || use_null_for_out)
5447 || !(use_out_for_err || use_file_for_err || use_null_for_err)))
Bram Moolenaar2dc9d262017-09-08 14:39:30 +02005448 {
5449 open_pty(&pty_master_fd, &pty_slave_fd, &job->jv_tty_out);
5450 if (job->jv_tty_out != NULL)
5451 job->jv_tty_in = vim_strsave(job->jv_tty_out);
5452 }
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02005453
Bram Moolenaar12dcf022016-02-15 23:09:04 +01005454 /* TODO: without the channel feature connect the child to /dev/null? */
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005455 /* Open pipes for stdin, stdout, stderr. */
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005456 if (use_file_for_in)
5457 {
5458 char_u *fname = options->jo_io_name[PART_IN];
5459
5460 fd_in[0] = mch_open((char *)fname, O_RDONLY, 0);
5461 if (fd_in[0] < 0)
5462 {
5463 EMSG2(_(e_notopen), fname);
5464 goto failed;
5465 }
5466 }
Bram Moolenaarb2412082017-08-20 18:09:14 +02005467 else
5468 /* When writing buffer lines to the input don't use the pty, so that
5469 * the pipe can be closed when all lines were written. */
5470 if (!use_null_for_in && (pty_master_fd < 0 || use_buffer_for_in)
5471 && pipe(fd_in) < 0)
5472 goto failed;
Bram Moolenaare98d1212016-03-08 15:37:41 +01005473
5474 if (use_file_for_out)
5475 {
5476 char_u *fname = options->jo_io_name[PART_OUT];
5477
5478 fd_out[1] = mch_open((char *)fname, O_WRONLY | O_CREAT | O_TRUNC, 0644);
5479 if (fd_out[1] < 0)
5480 {
5481 EMSG2(_(e_notopen), fname);
5482 goto failed;
5483 }
5484 }
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02005485 else if (!use_null_for_out && pty_master_fd < 0 && pipe(fd_out) < 0)
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005486 goto failed;
Bram Moolenaare98d1212016-03-08 15:37:41 +01005487
5488 if (use_file_for_err)
5489 {
5490 char_u *fname = options->jo_io_name[PART_ERR];
5491
5492 fd_err[1] = mch_open((char *)fname, O_WRONLY | O_CREAT | O_TRUNC, 0600);
5493 if (fd_err[1] < 0)
5494 {
5495 EMSG2(_(e_notopen), fname);
5496 goto failed;
5497 }
5498 }
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02005499 else if (!use_out_for_err && !use_null_for_err
5500 && pty_master_fd < 0 && pipe(fd_err) < 0)
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005501 goto failed;
5502
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005503 if (!use_null_for_in || !use_null_for_out || !use_null_for_err)
5504 {
Bram Moolenaarde279892016-03-11 22:19:44 +01005505 if (options->jo_set & JO_CHANNEL)
5506 {
5507 channel = options->jo_channel;
5508 if (channel != NULL)
5509 ++channel->ch_refcount;
5510 }
5511 else
5512 channel = add_channel();
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005513 if (channel == NULL)
5514 goto failed;
Bram Moolenaarf3360612017-10-01 16:21:31 +02005515 if (job->jv_tty_out != NULL)
5516 ch_log(channel, "using pty %s on fd %d",
5517 job->jv_tty_out, pty_master_fd);
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005518 }
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005519
Bram Moolenaarbb09ceb2016-10-18 16:27:23 +02005520 BLOCK_SIGNALS(&curset);
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005521 pid = fork(); /* maybe we should use vfork() */
Bram Moolenaarbb09ceb2016-10-18 16:27:23 +02005522 if (pid == -1)
Bram Moolenaar835dc632016-02-07 14:27:38 +01005523 {
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005524 /* failed to fork */
Bram Moolenaarbb09ceb2016-10-18 16:27:23 +02005525 UNBLOCK_SIGNALS(&curset);
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005526 goto failed;
Bram Moolenaar835dc632016-02-07 14:27:38 +01005527 }
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005528 if (pid == 0)
Bram Moolenaar835dc632016-02-07 14:27:38 +01005529 {
Bram Moolenaar4694a172016-04-21 14:05:23 +02005530 int null_fd = -1;
5531 int stderr_works = TRUE;
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005532
Bram Moolenaar835dc632016-02-07 14:27:38 +01005533 /* child */
5534 reset_signals(); /* handle signals normally */
Bram Moolenaarbb09ceb2016-10-18 16:27:23 +02005535 UNBLOCK_SIGNALS(&curset);
Bram Moolenaar835dc632016-02-07 14:27:38 +01005536
Bram Moolenaar819524702018-02-27 19:10:00 +01005537# ifdef FEAT_JOB_CHANNEL
5538 if (ch_log_active())
5539 /* close the log file in the child */
5540 ch_logfile((char_u *)"", (char_u *)"");
5541# endif
5542
Bram Moolenaar835dc632016-02-07 14:27:38 +01005543# ifdef HAVE_SETSID
5544 /* Create our own process group, so that the child and all its
5545 * children can be kill()ed. Don't do this when using pipes,
5546 * because stdin is not a tty, we would lose /dev/tty. */
5547 (void)setsid();
5548# endif
5549
Bram Moolenaar58556cd2017-07-20 23:04:46 +02005550# ifdef FEAT_TERMINAL
5551 if (options->jo_term_rows > 0)
Bram Moolenaar9a993e32018-04-05 22:15:22 +02005552 {
5553 char *term = (char *)T_NAME;
5554
5555#ifdef FEAT_GUI
5556 if (term_is_gui(T_NAME))
5557 /* In the GUI 'term' is not what we want, use $TERM. */
5558 term = getenv("TERM");
5559#endif
5560 /* Use 'term' or $TERM if it starts with "xterm", otherwise fall
5561 * back to "xterm". */
5562 if (term == NULL || *term == NUL || STRNCMP(term, "xterm", 5) != 0)
5563 term = "xterm";
Bram Moolenaar58556cd2017-07-20 23:04:46 +02005564 set_child_environment(
5565 (long)options->jo_term_rows,
5566 (long)options->jo_term_cols,
Bram Moolenaar493359e2018-06-12 20:25:52 +02005567 term,
5568 is_terminal);
Bram Moolenaar9a993e32018-04-05 22:15:22 +02005569 }
Bram Moolenaar58556cd2017-07-20 23:04:46 +02005570 else
5571# endif
Bram Moolenaar493359e2018-06-12 20:25:52 +02005572 set_default_child_environment(is_terminal);
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005573
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005574 if (options->jo_env != NULL)
5575 {
5576 dict_T *dict = options->jo_env;
5577 hashitem_T *hi;
5578 int todo = (int)dict->dv_hashtab.ht_used;
5579
5580 for (hi = dict->dv_hashtab.ht_array; todo > 0; ++hi)
5581 if (!HASHITEM_EMPTY(hi))
5582 {
5583 typval_T *item = &dict_lookup(hi)->di_tv;
5584
5585 vim_setenv((char_u*)hi->hi_key, get_tv_string(item));
5586 --todo;
5587 }
5588 }
5589
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005590 if (use_null_for_in || use_null_for_out || use_null_for_err)
Bram Moolenaarb109bb42017-08-21 21:07:29 +02005591 {
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005592 null_fd = open("/dev/null", O_RDWR | O_EXTRA, 0);
Bram Moolenaarb109bb42017-08-21 21:07:29 +02005593 if (null_fd < 0)
5594 {
5595 perror("opening /dev/null failed");
5596 _exit(OPEN_NULL_FAILED);
5597 }
5598 }
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005599
Bram Moolenaar223896d2017-08-02 22:33:28 +02005600 if (pty_slave_fd >= 0)
5601 {
5602 /* push stream discipline modules */
5603 SetupSlavePTY(pty_slave_fd);
5604# ifdef TIOCSCTTY
5605 /* Try to become controlling tty (probably doesn't work,
5606 * unless run by root) */
5607 ioctl(pty_slave_fd, TIOCSCTTY, (char *)NULL);
5608# endif
5609 }
5610
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005611 /* set up stdin for the child */
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02005612 close(0);
Bram Moolenaarc0a1d7f2016-03-19 14:12:50 +01005613 if (use_null_for_in && null_fd >= 0)
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005614 ignored = dup(null_fd);
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02005615 else if (fd_in[0] < 0)
5616 ignored = dup(pty_slave_fd);
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005617 else
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005618 ignored = dup(fd_in[0]);
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005619
Bram Moolenaarc25558b2016-03-03 21:02:23 +01005620 /* set up stderr for the child */
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02005621 close(2);
Bram Moolenaarc0a1d7f2016-03-19 14:12:50 +01005622 if (use_null_for_err && null_fd >= 0)
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005623 {
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005624 ignored = dup(null_fd);
Bram Moolenaar4694a172016-04-21 14:05:23 +02005625 stderr_works = FALSE;
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005626 }
5627 else if (use_out_for_err)
Bram Moolenaarc25558b2016-03-03 21:02:23 +01005628 ignored = dup(fd_out[1]);
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02005629 else if (fd_err[1] < 0)
5630 ignored = dup(pty_slave_fd);
Bram Moolenaarc25558b2016-03-03 21:02:23 +01005631 else
Bram Moolenaarc25558b2016-03-03 21:02:23 +01005632 ignored = dup(fd_err[1]);
Bram Moolenaarc25558b2016-03-03 21:02:23 +01005633
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005634 /* set up stdout for the child */
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02005635 close(1);
Bram Moolenaarc0a1d7f2016-03-19 14:12:50 +01005636 if (use_null_for_out && null_fd >= 0)
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005637 ignored = dup(null_fd);
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02005638 else if (fd_out[1] < 0)
5639 ignored = dup(pty_slave_fd);
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005640 else
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005641 ignored = dup(fd_out[1]);
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02005642
5643 if (fd_in[0] >= 0)
5644 close(fd_in[0]);
5645 if (fd_in[1] >= 0)
5646 close(fd_in[1]);
5647 if (fd_out[0] >= 0)
5648 close(fd_out[0]);
5649 if (fd_out[1] >= 0)
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005650 close(fd_out[1]);
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02005651 if (fd_err[0] >= 0)
5652 close(fd_err[0]);
5653 if (fd_err[1] >= 0)
5654 close(fd_err[1]);
5655 if (pty_master_fd >= 0)
5656 {
Bram Moolenaar223896d2017-08-02 22:33:28 +02005657 close(pty_master_fd); /* not used in the child */
5658 close(pty_slave_fd); /* was duped above */
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005659 }
Bram Moolenaarea83bf02016-05-08 09:40:51 +02005660
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005661 if (null_fd >= 0)
5662 close(null_fd);
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005663
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005664 if (options->jo_cwd != NULL && mch_chdir((char *)options->jo_cwd) != 0)
5665 _exit(EXEC_FAILED);
5666
Bram Moolenaar835dc632016-02-07 14:27:38 +01005667 /* See above for type of argv. */
5668 execvp(argv[0], argv);
5669
Bram Moolenaar4694a172016-04-21 14:05:23 +02005670 if (stderr_works)
5671 perror("executing job failed");
Bram Moolenaarfae42832017-08-01 22:24:26 +02005672# ifdef EXITFREE
Bram Moolenaarcda77642016-06-04 13:32:35 +02005673 /* calling free_all_mem() here causes problems. Ignore valgrind
5674 * reporting possibly leaked memory. */
Bram Moolenaarfae42832017-08-01 22:24:26 +02005675# endif
Bram Moolenaar835dc632016-02-07 14:27:38 +01005676 _exit(EXEC_FAILED); /* exec failed, return failure code */
5677 }
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005678
5679 /* parent */
Bram Moolenaarbb09ceb2016-10-18 16:27:23 +02005680 UNBLOCK_SIGNALS(&curset);
5681
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005682 job->jv_pid = pid;
5683 job->jv_status = JOB_STARTED;
Bram Moolenaarde279892016-03-11 22:19:44 +01005684 job->jv_channel = channel; /* ch_refcount was set above */
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005685
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02005686 if (pty_master_fd >= 0)
Bram Moolenaar13ebb032017-08-26 22:02:51 +02005687 close(pty_slave_fd); /* not used in the parent */
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02005688 /* close child stdin, stdout and stderr */
Bram Moolenaar819524702018-02-27 19:10:00 +01005689 if (fd_in[0] >= 0)
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005690 close(fd_in[0]);
Bram Moolenaar819524702018-02-27 19:10:00 +01005691 if (fd_out[1] >= 0)
Bram Moolenaare98d1212016-03-08 15:37:41 +01005692 close(fd_out[1]);
Bram Moolenaar819524702018-02-27 19:10:00 +01005693 if (fd_err[1] >= 0)
Bram Moolenaarc25558b2016-03-03 21:02:23 +01005694 close(fd_err[1]);
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005695 if (channel != NULL)
5696 {
Bram Moolenaar4e9d4432018-04-24 20:54:07 +02005697 int in_fd = use_file_for_in || use_null_for_in
5698 ? INVALID_FD : fd_in[1] < 0 ? pty_master_fd : fd_in[1];
5699 int out_fd = use_file_for_out || use_null_for_out
5700 ? INVALID_FD : fd_out[0] < 0 ? pty_master_fd : fd_out[0];
Bram Moolenaarb0b98d52018-05-05 21:01:00 +02005701 /* When using pty_master_fd only set it for stdout, do not duplicate it
5702 * for stderr, it only needs to be read once. */
Bram Moolenaar4e9d4432018-04-24 20:54:07 +02005703 int err_fd = use_out_for_err || use_file_for_err || use_null_for_err
Bram Moolenaarcd8fb442018-05-12 17:42:42 +02005704 ? INVALID_FD
5705 : fd_err[0] >= 0
5706 ? fd_err[0]
5707 : (out_fd == pty_master_fd
5708 ? INVALID_FD
5709 : pty_master_fd);
Bram Moolenaar4e9d4432018-04-24 20:54:07 +02005710
5711 channel_set_pipes(channel, in_fd, out_fd, err_fd);
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005712 channel_set_job(channel, job, options);
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005713 }
Bram Moolenaar979e8c52017-08-01 15:08:07 +02005714 else
5715 {
5716 if (fd_in[1] >= 0)
5717 close(fd_in[1]);
5718 if (fd_out[0] >= 0)
5719 close(fd_out[0]);
5720 if (fd_err[0] >= 0)
5721 close(fd_err[0]);
5722 if (pty_master_fd >= 0)
5723 close(pty_master_fd);
5724 }
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005725
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005726 /* success! */
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005727 return;
5728
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005729failed:
Bram Moolenaarde279892016-03-11 22:19:44 +01005730 channel_unref(channel);
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005731 if (fd_in[0] >= 0)
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005732 close(fd_in[0]);
Bram Moolenaare98d1212016-03-08 15:37:41 +01005733 if (fd_in[1] >= 0)
5734 close(fd_in[1]);
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005735 if (fd_out[0] >= 0)
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005736 close(fd_out[0]);
Bram Moolenaare98d1212016-03-08 15:37:41 +01005737 if (fd_out[1] >= 0)
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005738 close(fd_out[1]);
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005739 if (fd_err[0] >= 0)
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005740 close(fd_err[0]);
Bram Moolenaare98d1212016-03-08 15:37:41 +01005741 if (fd_err[1] >= 0)
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005742 close(fd_err[1]);
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02005743 if (pty_master_fd >= 0)
5744 close(pty_master_fd);
5745 if (pty_slave_fd >= 0)
5746 close(pty_slave_fd);
Bram Moolenaar835dc632016-02-07 14:27:38 +01005747}
5748
5749 char *
5750mch_job_status(job_T *job)
5751{
5752# ifdef HAVE_UNION_WAIT
5753 union wait status;
5754# else
5755 int status = -1;
5756# endif
5757 pid_t wait_pid = 0;
5758
5759# ifdef __NeXT__
5760 wait_pid = wait4(job->jv_pid, &status, WNOHANG, (struct rusage *)0);
5761# else
5762 wait_pid = waitpid(job->jv_pid, &status, WNOHANG);
5763# endif
5764 if (wait_pid == -1)
5765 {
5766 /* process must have exited */
Bram Moolenaarb0b98d52018-05-05 21:01:00 +02005767 if (job->jv_status < JOB_ENDED)
5768 ch_log(job->jv_channel, "Job no longer exists: %s",
5769 strerror(errno));
Bram Moolenaar97792de2016-10-15 18:36:49 +02005770 goto return_dead;
Bram Moolenaar835dc632016-02-07 14:27:38 +01005771 }
5772 if (wait_pid == 0)
5773 return "run";
5774 if (WIFEXITED(status))
5775 {
5776 /* LINTED avoid "bitwise operation on signed value" */
5777 job->jv_exitval = WEXITSTATUS(status);
Bram Moolenaarb0b98d52018-05-05 21:01:00 +02005778 if (job->jv_status < JOB_ENDED)
5779 ch_log(job->jv_channel, "Job exited with %d", job->jv_exitval);
Bram Moolenaar97792de2016-10-15 18:36:49 +02005780 goto return_dead;
Bram Moolenaar835dc632016-02-07 14:27:38 +01005781 }
Bram Moolenaar76467df2016-02-12 19:30:26 +01005782 if (WIFSIGNALED(status))
5783 {
5784 job->jv_exitval = -1;
Bram Moolenaarb0b98d52018-05-05 21:01:00 +02005785 if (job->jv_status < JOB_ENDED)
5786 ch_log(job->jv_channel, "Job terminated by a signal");
Bram Moolenaar97792de2016-10-15 18:36:49 +02005787 goto return_dead;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005788 }
Bram Moolenaar835dc632016-02-07 14:27:38 +01005789 return "run";
Bram Moolenaar97792de2016-10-15 18:36:49 +02005790
5791return_dead:
Bram Moolenaar7df915d2016-11-17 17:25:32 +01005792 if (job->jv_status < JOB_ENDED)
Bram Moolenaar97792de2016-10-15 18:36:49 +02005793 job->jv_status = JOB_ENDED;
Bram Moolenaar97792de2016-10-15 18:36:49 +02005794 return "dead";
5795}
5796
5797 job_T *
5798mch_detect_ended_job(job_T *job_list)
5799{
5800# ifdef HAVE_UNION_WAIT
5801 union wait status;
5802# else
5803 int status = -1;
5804# endif
5805 pid_t wait_pid = 0;
5806 job_T *job;
5807
Bram Moolenaarc4d4ac22016-11-07 22:42:57 +01005808# ifndef USE_SYSTEM
5809 /* Do not do this when waiting for a shell command to finish, we would get
5810 * the exit value here (and discard it), the exit value obtained there
5811 * would then be wrong. */
5812 if (dont_check_job_ended > 0)
5813 return NULL;
5814# endif
5815
Bram Moolenaar97792de2016-10-15 18:36:49 +02005816# ifdef __NeXT__
5817 wait_pid = wait4(-1, &status, WNOHANG, (struct rusage *)0);
5818# else
5819 wait_pid = waitpid(-1, &status, WNOHANG);
5820# endif
5821 if (wait_pid <= 0)
5822 /* no process ended */
5823 return NULL;
5824 for (job = job_list; job != NULL; job = job->jv_next)
5825 {
5826 if (job->jv_pid == wait_pid)
5827 {
5828 if (WIFEXITED(status))
5829 /* LINTED avoid "bitwise operation on signed value" */
5830 job->jv_exitval = WEXITSTATUS(status);
5831 else if (WIFSIGNALED(status))
5832 job->jv_exitval = -1;
Bram Moolenaar7df915d2016-11-17 17:25:32 +01005833 if (job->jv_status < JOB_ENDED)
Bram Moolenaar97792de2016-10-15 18:36:49 +02005834 {
5835 ch_log(job->jv_channel, "Job ended");
5836 job->jv_status = JOB_ENDED;
5837 }
5838 return job;
5839 }
5840 }
5841 return NULL;
Bram Moolenaar835dc632016-02-07 14:27:38 +01005842}
5843
Bram Moolenaar3a117e12016-10-30 21:57:52 +01005844/*
5845 * Send a (deadly) signal to "job".
5846 * Return FAIL if "how" is not a valid name.
5847 */
Bram Moolenaar835dc632016-02-07 14:27:38 +01005848 int
Bram Moolenaar2d33e902017-08-11 16:31:54 +02005849mch_signal_job(job_T *job, char_u *how)
Bram Moolenaar835dc632016-02-07 14:27:38 +01005850{
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005851 int sig = -1;
5852 pid_t job_pid;
Bram Moolenaar835dc632016-02-07 14:27:38 +01005853
Bram Moolenaar923d9262016-02-25 20:56:01 +01005854 if (*how == NUL || STRCMP(how, "term") == 0)
Bram Moolenaar835dc632016-02-07 14:27:38 +01005855 sig = SIGTERM;
Bram Moolenaar923d9262016-02-25 20:56:01 +01005856 else if (STRCMP(how, "hup") == 0)
5857 sig = SIGHUP;
Bram Moolenaar835dc632016-02-07 14:27:38 +01005858 else if (STRCMP(how, "quit") == 0)
5859 sig = SIGQUIT;
Bram Moolenaar923d9262016-02-25 20:56:01 +01005860 else if (STRCMP(how, "int") == 0)
5861 sig = SIGINT;
Bram Moolenaar835dc632016-02-07 14:27:38 +01005862 else if (STRCMP(how, "kill") == 0)
5863 sig = SIGKILL;
Bram Moolenaarb13501f2017-07-22 22:32:56 +02005864#ifdef SIGWINCH
5865 else if (STRCMP(how, "winch") == 0)
5866 sig = SIGWINCH;
5867#endif
Bram Moolenaar835dc632016-02-07 14:27:38 +01005868 else if (isdigit(*how))
5869 sig = atoi((char *)how);
5870 else
5871 return FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005872
Bram Moolenaar72801402016-02-09 11:37:50 +01005873 /* TODO: have an option to only kill the process, not the group? */
Bram Moolenaar76467df2016-02-12 19:30:26 +01005874 job_pid = job->jv_pid;
Bram Moolenaar2fcf6682017-03-11 20:03:42 +01005875#ifdef HAVE_GETPGID
Bram Moolenaar76467df2016-02-12 19:30:26 +01005876 if (job_pid == getpgid(job_pid))
5877 job_pid = -job_pid;
Bram Moolenaar2fcf6682017-03-11 20:03:42 +01005878#endif
Bram Moolenaar76467df2016-02-12 19:30:26 +01005879
Bram Moolenaar61a66052017-07-22 18:39:00 +02005880 /* Never kill ourselves! */
5881 if (job_pid != 0)
5882 kill(job_pid, sig);
Bram Moolenaar76467df2016-02-12 19:30:26 +01005883
Bram Moolenaar835dc632016-02-07 14:27:38 +01005884 return OK;
5885}
Bram Moolenaar76467df2016-02-12 19:30:26 +01005886
5887/*
5888 * Clear the data related to "job".
5889 */
5890 void
5891mch_clear_job(job_T *job)
5892{
5893 /* call waitpid because child process may become zombie */
5894# ifdef __NeXT__
Bram Moolenaar4ca812b2016-03-02 21:51:16 +01005895 (void)wait4(job->jv_pid, NULL, WNOHANG, (struct rusage *)0);
Bram Moolenaar76467df2016-02-12 19:30:26 +01005896# else
Bram Moolenaar4ca812b2016-03-02 21:51:16 +01005897 (void)waitpid(job->jv_pid, NULL, WNOHANG);
Bram Moolenaar76467df2016-02-12 19:30:26 +01005898# endif
5899}
Bram Moolenaar835dc632016-02-07 14:27:38 +01005900#endif
5901
Bram Moolenaar13ebb032017-08-26 22:02:51 +02005902#if defined(FEAT_TERMINAL) || defined(PROTO)
5903 int
5904mch_create_pty_channel(job_T *job, jobopt_T *options)
5905{
5906 int pty_master_fd = -1;
5907 int pty_slave_fd = -1;
5908 channel_T *channel;
5909
Bram Moolenaar2dc9d262017-09-08 14:39:30 +02005910 open_pty(&pty_master_fd, &pty_slave_fd, &job->jv_tty_out);
5911 if (job->jv_tty_out != NULL)
5912 job->jv_tty_in = vim_strsave(job->jv_tty_out);
Bram Moolenaar13ebb032017-08-26 22:02:51 +02005913 close(pty_slave_fd);
5914
5915 channel = add_channel();
5916 if (channel == NULL)
Bram Moolenaar1b9f9d32017-09-05 23:32:38 +02005917 {
5918 close(pty_master_fd);
Bram Moolenaar13ebb032017-08-26 22:02:51 +02005919 return FAIL;
Bram Moolenaar1b9f9d32017-09-05 23:32:38 +02005920 }
Bram Moolenaarf3360612017-10-01 16:21:31 +02005921 if (job->jv_tty_out != NULL)
5922 ch_log(channel, "using pty %s on fd %d",
5923 job->jv_tty_out, pty_master_fd);
Bram Moolenaar13ebb032017-08-26 22:02:51 +02005924 job->jv_channel = channel; /* ch_refcount was set by add_channel() */
5925 channel->ch_keep_open = TRUE;
5926
Bram Moolenaarb0b98d52018-05-05 21:01:00 +02005927 /* Only set the pty_master_fd for stdout, do not duplicate it for stderr,
5928 * it only needs to be read once. */
5929 channel_set_pipes(channel, pty_master_fd, pty_master_fd, INVALID_FD);
Bram Moolenaar13ebb032017-08-26 22:02:51 +02005930 channel_set_job(channel, job, options);
5931 return OK;
5932}
5933#endif
5934
Bram Moolenaar071d4272004-06-13 20:20:40 +00005935/*
5936 * Check for CTRL-C typed by reading all available characters.
5937 * In cooked mode we should get SIGINT, no need to check.
5938 */
5939 void
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02005940mch_breakcheck(int force)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005941{
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02005942 if ((curr_tmode == TMODE_RAW || force)
5943 && RealWaitForChar(read_cmd_fd, 0L, NULL, NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005944 fill_input_buf(FALSE);
5945}
5946
5947/*
Bram Moolenaar943bb2b2016-03-19 14:11:18 +01005948 * Wait "msec" msec until a character is available from the mouse, keyboard,
5949 * from inbuf[].
5950 * "msec" == -1 will block forever.
5951 * Invokes timer callbacks when needed.
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02005952 * When "ignore_input" is TRUE even check for pending input when input is
5953 * already available.
Bram Moolenaarcda77642016-06-04 13:32:35 +02005954 * "interrupted" (if not NULL) is set to TRUE when no character is available
5955 * but something else needs to be done.
Bram Moolenaar40b1b542016-04-20 20:18:23 +02005956 * Returns TRUE when a character is available.
Bram Moolenaarcda77642016-06-04 13:32:35 +02005957 * When a GUI is being used, this will never get called -- webb
Bram Moolenaar071d4272004-06-13 20:20:40 +00005958 */
5959 static int
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02005960WaitForChar(long msec, int *interrupted, int ignore_input)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005961{
Bram Moolenaar943bb2b2016-03-19 14:11:18 +01005962#ifdef FEAT_TIMERS
Bram Moolenaarc9e649a2017-12-18 18:14:47 +01005963 return ui_wait_for_chars_or_timer(
5964 msec, WaitForCharOrMouse, interrupted, ignore_input) == OK;
Bram Moolenaar943bb2b2016-03-19 14:11:18 +01005965#else
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02005966 return WaitForCharOrMouse(msec, interrupted, ignore_input);
Bram Moolenaar943bb2b2016-03-19 14:11:18 +01005967#endif
5968}
5969
5970/*
5971 * Wait "msec" msec until a character is available from the mouse or keyboard
5972 * or from inbuf[].
5973 * "msec" == -1 will block forever.
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02005974 * for "ignore_input" see WaitForCharOr().
Bram Moolenaarcda77642016-06-04 13:32:35 +02005975 * "interrupted" (if not NULL) is set to TRUE when no character is available
5976 * but something else needs to be done.
Bram Moolenaar943bb2b2016-03-19 14:11:18 +01005977 * When a GUI is being used, this will never get called -- webb
5978 */
5979 static int
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02005980WaitForCharOrMouse(long msec, int *interrupted, int ignore_input)
Bram Moolenaar943bb2b2016-03-19 14:11:18 +01005981{
Bram Moolenaar071d4272004-06-13 20:20:40 +00005982#ifdef FEAT_MOUSE_GPM
5983 int gpm_process_wanted;
5984#endif
5985#ifdef FEAT_XCLIPBOARD
5986 int rest;
5987#endif
5988 int avail;
5989
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02005990 if (!ignore_input && input_available()) /* something in inbuf[] */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005991 return 1;
5992
5993#if defined(FEAT_MOUSE_DEC)
5994 /* May need to query the mouse position. */
5995 if (WantQueryMouse)
5996 {
Bram Moolenaar6bb68362005-03-22 23:03:44 +00005997 WantQueryMouse = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005998 mch_write((char_u *)IF_EB("\033[1'|", ESC_STR "[1'|"), 5);
5999 }
6000#endif
6001
6002 /*
6003 * For FEAT_MOUSE_GPM and FEAT_XCLIPBOARD we loop here to process mouse
6004 * events. This is a bit complicated, because they might both be defined.
6005 */
6006#if defined(FEAT_MOUSE_GPM) || defined(FEAT_XCLIPBOARD)
6007# ifdef FEAT_XCLIPBOARD
6008 rest = 0;
6009 if (do_xterm_trace())
6010 rest = msec;
6011# endif
6012 do
6013 {
6014# ifdef FEAT_XCLIPBOARD
6015 if (rest != 0)
6016 {
6017 msec = XT_TRACE_DELAY;
6018 if (rest >= 0 && rest < XT_TRACE_DELAY)
6019 msec = rest;
6020 if (rest >= 0)
6021 rest -= msec;
6022 }
6023# endif
6024# ifdef FEAT_MOUSE_GPM
6025 gpm_process_wanted = 0;
Bram Moolenaar8fdd7212016-03-26 19:41:48 +01006026 avail = RealWaitForChar(read_cmd_fd, msec,
Bram Moolenaarcda77642016-06-04 13:32:35 +02006027 &gpm_process_wanted, interrupted);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006028# else
Bram Moolenaarcda77642016-06-04 13:32:35 +02006029 avail = RealWaitForChar(read_cmd_fd, msec, NULL, interrupted);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006030# endif
6031 if (!avail)
6032 {
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006033 if (!ignore_input && input_available())
Bram Moolenaar071d4272004-06-13 20:20:40 +00006034 return 1;
6035# ifdef FEAT_XCLIPBOARD
6036 if (rest == 0 || !do_xterm_trace())
6037# endif
6038 break;
6039 }
6040 }
6041 while (FALSE
6042# ifdef FEAT_MOUSE_GPM
6043 || (gpm_process_wanted && mch_gpm_process() == 0)
6044# endif
6045# ifdef FEAT_XCLIPBOARD
6046 || (!avail && rest != 0)
6047# endif
Bram Moolenaar8fdd7212016-03-26 19:41:48 +01006048 )
6049 ;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006050
6051#else
Bram Moolenaarcda77642016-06-04 13:32:35 +02006052 avail = RealWaitForChar(read_cmd_fd, msec, NULL, interrupted);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006053#endif
6054 return avail;
6055}
6056
Bram Moolenaar4ffa0702013-12-11 17:12:37 +01006057#ifndef VMS
Bram Moolenaar071d4272004-06-13 20:20:40 +00006058/*
6059 * Wait "msec" msec until a character is available from file descriptor "fd".
Bram Moolenaar493c7a82011-09-07 14:06:47 +02006060 * "msec" == 0 will check for characters once.
6061 * "msec" == -1 will block until a character is available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006062 * When a GUI is being used, this will not be used for input -- webb
Bram Moolenaar071d4272004-06-13 20:20:40 +00006063 * Or when a Linux GPM mouse event is waiting.
Bram Moolenaar93c88e02015-09-15 14:12:05 +02006064 * Or when a clientserver message is on the queue.
Bram Moolenaarcda77642016-06-04 13:32:35 +02006065 * "interrupted" (if not NULL) is set to TRUE when no character is available
6066 * but something else needs to be done.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006067 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006068#if defined(__BEOS__)
6069 int
6070#else
Bram Moolenaarec70bdd2016-02-18 22:17:42 +01006071 static int
Bram Moolenaar071d4272004-06-13 20:20:40 +00006072#endif
Bram Moolenaarcda77642016-06-04 13:32:35 +02006073RealWaitForChar(int fd, long msec, int *check_for_gpm UNUSED, int *interrupted)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006074{
6075 int ret;
Bram Moolenaarec70bdd2016-02-18 22:17:42 +01006076 int result;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006077#if defined(FEAT_XCLIPBOARD) || defined(USE_XSMP) || defined(FEAT_MZSCHEME)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006078 static int busy = FALSE;
6079
6080 /* May retry getting characters after an event was handled. */
6081# define MAY_LOOP
6082
Bram Moolenaar833eb1d2016-11-24 17:22:50 +01006083# ifdef ELAPSED_FUNC
Bram Moolenaar071d4272004-06-13 20:20:40 +00006084 /* Remember at what time we started, so that we know how much longer we
6085 * should wait after being interrupted. */
Bram Moolenaar76b6dfe2016-06-04 14:37:22 +02006086 long start_msec = msec;
Bram Moolenaar833eb1d2016-11-24 17:22:50 +01006087 ELAPSED_TYPE start_tv;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006088
Bram Moolenaar76b6dfe2016-06-04 14:37:22 +02006089 if (msec > 0)
Bram Moolenaar833eb1d2016-11-24 17:22:50 +01006090 ELAPSED_INIT(start_tv);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006091# endif
6092
6093 /* Handle being called recursively. This may happen for the session
6094 * manager stuff, it may save the file, which does a breakcheck. */
6095 if (busy)
6096 return 0;
6097#endif
6098
6099#ifdef MAY_LOOP
Bram Moolenaar35fdbb52005-07-09 21:08:57 +00006100 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006101#endif
6102 {
6103#ifdef MAY_LOOP
6104 int finished = TRUE; /* default is to 'loop' just once */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006105# ifdef FEAT_MZSCHEME
6106 int mzquantum_used = FALSE;
6107# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006108#endif
6109#ifndef HAVE_SELECT
Bram Moolenaar8b877ac2016-03-28 19:16:20 +02006110 /* each channel may use in, out and err */
6111 struct pollfd fds[6 + 3 * MAX_OPEN_CHANNELS];
Bram Moolenaar071d4272004-06-13 20:20:40 +00006112 int nfd;
6113# ifdef FEAT_XCLIPBOARD
6114 int xterm_idx = -1;
6115# endif
6116# ifdef FEAT_MOUSE_GPM
6117 int gpm_idx = -1;
6118# endif
6119# ifdef USE_XSMP
6120 int xsmp_idx = -1;
6121# endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006122 int towait = (int)msec;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006123
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006124# ifdef FEAT_MZSCHEME
6125 mzvim_check_threads();
6126 if (mzthreads_allowed() && p_mzq > 0 && (msec < 0 || msec > p_mzq))
6127 {
6128 towait = (int)p_mzq; /* don't wait longer than 'mzquantum' */
6129 mzquantum_used = TRUE;
6130 }
6131# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006132 fds[0].fd = fd;
6133 fds[0].events = POLLIN;
6134 nfd = 1;
6135
Bram Moolenaar071d4272004-06-13 20:20:40 +00006136# ifdef FEAT_XCLIPBOARD
Bram Moolenaarb1e26502014-11-19 18:48:46 +01006137 may_restore_clipboard();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006138 if (xterm_Shell != (Widget)0)
6139 {
6140 xterm_idx = nfd;
6141 fds[nfd].fd = ConnectionNumber(xterm_dpy);
6142 fds[nfd].events = POLLIN;
6143 nfd++;
6144 }
6145# endif
6146# ifdef FEAT_MOUSE_GPM
6147 if (check_for_gpm != NULL && gpm_flag && gpm_fd >= 0)
6148 {
6149 gpm_idx = nfd;
6150 fds[nfd].fd = gpm_fd;
6151 fds[nfd].events = POLLIN;
6152 nfd++;
6153 }
6154# endif
6155# ifdef USE_XSMP
6156 if (xsmp_icefd != -1)
6157 {
6158 xsmp_idx = nfd;
6159 fds[nfd].fd = xsmp_icefd;
6160 fds[nfd].events = POLLIN;
6161 nfd++;
6162 }
6163# endif
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01006164#ifdef FEAT_JOB_CHANNEL
Bram Moolenaarf3360612017-10-01 16:21:31 +02006165 nfd = channel_poll_setup(nfd, &fds, &towait);
Bram Moolenaar67c53842010-05-22 18:28:27 +02006166#endif
Bram Moolenaarcda77642016-06-04 13:32:35 +02006167 if (interrupted != NULL)
6168 *interrupted = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006169
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006170 ret = poll(fds, nfd, towait);
Bram Moolenaarec70bdd2016-02-18 22:17:42 +01006171
6172 result = ret > 0 && (fds[0].revents & POLLIN);
Bram Moolenaarcda77642016-06-04 13:32:35 +02006173 if (result == 0 && interrupted != NULL && ret > 0)
6174 *interrupted = TRUE;
Bram Moolenaarec70bdd2016-02-18 22:17:42 +01006175
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006176# ifdef FEAT_MZSCHEME
6177 if (ret == 0 && mzquantum_used)
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00006178 /* MzThreads scheduling is required and timeout occurred */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006179 finished = FALSE;
6180# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006181
Bram Moolenaar071d4272004-06-13 20:20:40 +00006182# ifdef FEAT_XCLIPBOARD
6183 if (xterm_Shell != (Widget)0 && (fds[xterm_idx].revents & POLLIN))
6184 {
6185 xterm_update(); /* Maybe we should hand out clipboard */
6186 if (--ret == 0 && !input_available())
6187 /* Try again */
6188 finished = FALSE;
6189 }
6190# endif
6191# ifdef FEAT_MOUSE_GPM
6192 if (gpm_idx >= 0 && (fds[gpm_idx].revents & POLLIN))
6193 {
6194 *check_for_gpm = 1;
6195 }
6196# endif
6197# ifdef USE_XSMP
6198 if (xsmp_idx >= 0 && (fds[xsmp_idx].revents & (POLLIN | POLLHUP)))
6199 {
6200 if (fds[xsmp_idx].revents & POLLIN)
6201 {
6202 busy = TRUE;
6203 xsmp_handle_requests();
6204 busy = FALSE;
6205 }
6206 else if (fds[xsmp_idx].revents & POLLHUP)
6207 {
6208 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00006209 verb_msg((char_u *)_("XSMP lost ICE connection"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00006210 xsmp_close();
6211 }
6212 if (--ret == 0)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006213 finished = FALSE; /* Try again */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006214 }
6215# endif
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01006216#ifdef FEAT_JOB_CHANNEL
Bram Moolenaarf3360612017-10-01 16:21:31 +02006217 /* also call when ret == 0, we may be polling a keep-open channel */
6218 if (ret >= 0)
Bram Moolenaare0874f82016-01-24 20:36:41 +01006219 ret = channel_poll_check(ret, &fds);
Bram Moolenaar67c53842010-05-22 18:28:27 +02006220#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006221
Bram Moolenaar071d4272004-06-13 20:20:40 +00006222#else /* HAVE_SELECT */
6223
6224 struct timeval tv;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006225 struct timeval *tvp;
Bram Moolenaar8b877ac2016-03-28 19:16:20 +02006226 fd_set rfds, wfds, efds;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006227 int maxfd;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006228 long towait = msec;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006229
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006230# ifdef FEAT_MZSCHEME
6231 mzvim_check_threads();
6232 if (mzthreads_allowed() && p_mzq > 0 && (msec < 0 || msec > p_mzq))
6233 {
6234 towait = p_mzq; /* don't wait longer than 'mzquantum' */
6235 mzquantum_used = TRUE;
6236 }
6237# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006238
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006239 if (towait >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006240 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006241 tv.tv_sec = towait / 1000;
6242 tv.tv_usec = (towait % 1000) * (1000000/1000);
6243 tvp = &tv;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006244 }
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006245 else
6246 tvp = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006247
6248 /*
6249 * Select on ready for reading and exceptional condition (end of file).
6250 */
Bram Moolenaar493c7a82011-09-07 14:06:47 +02006251select_eintr:
6252 FD_ZERO(&rfds);
Bram Moolenaar8b877ac2016-03-28 19:16:20 +02006253 FD_ZERO(&wfds);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006254 FD_ZERO(&efds);
6255 FD_SET(fd, &rfds);
6256# if !defined(__QNX__) && !defined(__CYGWIN32__)
6257 /* For QNX select() always returns 1 if this is set. Why? */
6258 FD_SET(fd, &efds);
6259# endif
6260 maxfd = fd;
6261
Bram Moolenaar071d4272004-06-13 20:20:40 +00006262# ifdef FEAT_XCLIPBOARD
Bram Moolenaarb1e26502014-11-19 18:48:46 +01006263 may_restore_clipboard();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006264 if (xterm_Shell != (Widget)0)
6265 {
6266 FD_SET(ConnectionNumber(xterm_dpy), &rfds);
6267 if (maxfd < ConnectionNumber(xterm_dpy))
6268 maxfd = ConnectionNumber(xterm_dpy);
Bram Moolenaardd82d692012-08-15 17:26:57 +02006269
6270 /* An event may have already been read but not handled. In
6271 * particulary, XFlush may cause this. */
6272 xterm_update();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006273 }
6274# endif
6275# ifdef FEAT_MOUSE_GPM
6276 if (check_for_gpm != NULL && gpm_flag && gpm_fd >= 0)
6277 {
6278 FD_SET(gpm_fd, &rfds);
6279 FD_SET(gpm_fd, &efds);
6280 if (maxfd < gpm_fd)
6281 maxfd = gpm_fd;
6282 }
6283# endif
6284# ifdef USE_XSMP
6285 if (xsmp_icefd != -1)
6286 {
6287 FD_SET(xsmp_icefd, &rfds);
6288 FD_SET(xsmp_icefd, &efds);
6289 if (maxfd < xsmp_icefd)
6290 maxfd = xsmp_icefd;
6291 }
6292# endif
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01006293# ifdef FEAT_JOB_CHANNEL
Bram Moolenaarf3360612017-10-01 16:21:31 +02006294 maxfd = channel_select_setup(maxfd, &rfds, &wfds, &tv, &tvp);
Bram Moolenaardd82d692012-08-15 17:26:57 +02006295# endif
Bram Moolenaarcda77642016-06-04 13:32:35 +02006296 if (interrupted != NULL)
6297 *interrupted = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006298
Bram Moolenaar643b6142018-09-12 20:29:09 +02006299 ret = select(maxfd + 1, SELECT_TYPE_ARG234 &rfds,
6300 SELECT_TYPE_ARG234 &wfds, SELECT_TYPE_ARG234 &efds, tvp);
Bram Moolenaarec70bdd2016-02-18 22:17:42 +01006301 result = ret > 0 && FD_ISSET(fd, &rfds);
6302 if (result)
6303 --ret;
Bram Moolenaarcda77642016-06-04 13:32:35 +02006304 else if (interrupted != NULL && ret > 0)
6305 *interrupted = TRUE;
Bram Moolenaarec70bdd2016-02-18 22:17:42 +01006306
Bram Moolenaar493c7a82011-09-07 14:06:47 +02006307# ifdef EINTR
6308 if (ret == -1 && errno == EINTR)
Bram Moolenaar2e7b1df2011-10-12 21:04:20 +02006309 {
6310 /* Check whether window has been resized, EINTR may be caused by
6311 * SIGWINCH. */
6312 if (do_resize)
6313 handle_resize();
6314
Bram Moolenaar493c7a82011-09-07 14:06:47 +02006315 /* Interrupted by a signal, need to try again. We ignore msec
6316 * here, because we do want to check even after a timeout if
6317 * characters are available. Needed for reading output of an
6318 * external command after the process has finished. */
6319 goto select_eintr;
Bram Moolenaar2e7b1df2011-10-12 21:04:20 +02006320 }
Bram Moolenaar493c7a82011-09-07 14:06:47 +02006321# endif
Bram Moolenaar311d9822007-02-27 15:48:28 +00006322# ifdef __TANDEM
6323 if (ret == -1 && errno == ENOTSUP)
6324 {
6325 FD_ZERO(&rfds);
6326 FD_ZERO(&efds);
6327 ret = 0;
6328 }
Bram Moolenaar493c7a82011-09-07 14:06:47 +02006329# endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006330# ifdef FEAT_MZSCHEME
6331 if (ret == 0 && mzquantum_used)
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00006332 /* loop if MzThreads must be scheduled and timeout occurred */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006333 finished = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006334# endif
6335
Bram Moolenaar071d4272004-06-13 20:20:40 +00006336# ifdef FEAT_XCLIPBOARD
6337 if (ret > 0 && xterm_Shell != (Widget)0
6338 && FD_ISSET(ConnectionNumber(xterm_dpy), &rfds))
6339 {
6340 xterm_update(); /* Maybe we should hand out clipboard */
6341 /* continue looping when we only got the X event and the input
6342 * buffer is empty */
6343 if (--ret == 0 && !input_available())
6344 {
6345 /* Try again */
6346 finished = FALSE;
6347 }
6348 }
6349# endif
6350# ifdef FEAT_MOUSE_GPM
6351 if (ret > 0 && gpm_flag && check_for_gpm != NULL && gpm_fd >= 0)
6352 {
6353 if (FD_ISSET(gpm_fd, &efds))
6354 gpm_close();
6355 else if (FD_ISSET(gpm_fd, &rfds))
6356 *check_for_gpm = 1;
6357 }
6358# endif
6359# ifdef USE_XSMP
6360 if (ret > 0 && xsmp_icefd != -1)
6361 {
6362 if (FD_ISSET(xsmp_icefd, &efds))
6363 {
6364 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00006365 verb_msg((char_u *)_("XSMP lost ICE connection"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00006366 xsmp_close();
6367 if (--ret == 0)
6368 finished = FALSE; /* keep going if event was only one */
6369 }
6370 else if (FD_ISSET(xsmp_icefd, &rfds))
6371 {
6372 busy = TRUE;
6373 xsmp_handle_requests();
6374 busy = FALSE;
6375 if (--ret == 0)
6376 finished = FALSE; /* keep going if event was only one */
6377 }
6378 }
6379# endif
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01006380#ifdef FEAT_JOB_CHANNEL
Bram Moolenaarf3360612017-10-01 16:21:31 +02006381 /* also call when ret == 0, we may be polling a keep-open channel */
6382 if (ret >= 0)
Bram Moolenaar8b877ac2016-03-28 19:16:20 +02006383 ret = channel_select_check(ret, &rfds, &wfds);
Bram Moolenaar67c53842010-05-22 18:28:27 +02006384#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006385
6386#endif /* HAVE_SELECT */
6387
6388#ifdef MAY_LOOP
6389 if (finished || msec == 0)
6390 break;
6391
Bram Moolenaar93c88e02015-09-15 14:12:05 +02006392# ifdef FEAT_CLIENTSERVER
6393 if (server_waiting())
6394 break;
6395# endif
6396
Bram Moolenaar071d4272004-06-13 20:20:40 +00006397 /* We're going to loop around again, find out for how long */
6398 if (msec > 0)
6399 {
Bram Moolenaar833eb1d2016-11-24 17:22:50 +01006400# ifdef ELAPSED_FUNC
Bram Moolenaar071d4272004-06-13 20:20:40 +00006401 /* Compute remaining wait time. */
Bram Moolenaar833eb1d2016-11-24 17:22:50 +01006402 msec = start_msec - ELAPSED_FUNC(start_tv);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006403# else
6404 /* Guess we got interrupted halfway. */
6405 msec = msec / 2;
6406# endif
6407 if (msec <= 0)
6408 break; /* waited long enough */
6409 }
6410#endif
6411 }
6412
Bram Moolenaarec70bdd2016-02-18 22:17:42 +01006413 return result;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006414}
6415
Bram Moolenaar071d4272004-06-13 20:20:40 +00006416#ifndef NO_EXPANDPATH
Bram Moolenaar071d4272004-06-13 20:20:40 +00006417/*
Bram Moolenaar02743632005-07-25 20:42:36 +00006418 * Expand a path into all matching files and/or directories. Handles "*",
6419 * "?", "[a-z]", "**", etc.
6420 * "path" has backslashes before chars that are not to be expanded.
6421 * Returns the number of matches found.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006422 */
6423 int
Bram Moolenaar05540972016-01-30 20:31:25 +01006424mch_expandpath(
6425 garray_T *gap,
6426 char_u *path,
6427 int flags) /* EW_* flags */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006428{
Bram Moolenaar02743632005-07-25 20:42:36 +00006429 return unix_expandpath(gap, path, 0, flags, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006430}
6431#endif
6432
6433/*
6434 * mch_expand_wildcards() - this code does wild-card pattern matching using
6435 * the shell
6436 *
6437 * return OK for success, FAIL for error (you may lose some memory) and put
6438 * an error message in *file.
6439 *
6440 * num_pat is number of input patterns
6441 * pat is array of pointers to input patterns
6442 * num_file is pointer to number of matched file names
6443 * file is pointer to array of pointers to matched file names
6444 */
6445
6446#ifndef SEEK_SET
6447# define SEEK_SET 0
6448#endif
6449#ifndef SEEK_END
6450# define SEEK_END 2
6451#endif
6452
Bram Moolenaar5555acc2006-04-07 21:33:12 +00006453#define SHELL_SPECIAL (char_u *)"\t \"&'$;<>()\\|"
Bram Moolenaar316059c2006-01-14 21:18:42 +00006454
Bram Moolenaar071d4272004-06-13 20:20:40 +00006455 int
Bram Moolenaar05540972016-01-30 20:31:25 +01006456mch_expand_wildcards(
6457 int num_pat,
6458 char_u **pat,
6459 int *num_file,
6460 char_u ***file,
6461 int flags) /* EW_* flags */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006462{
6463 int i;
6464 size_t len;
Bram Moolenaar85325f82017-03-30 21:18:45 +02006465 long llen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006466 char_u *p;
6467 int dir;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006468
Bram Moolenaarc7247912008-01-13 12:54:11 +00006469 /*
6470 * This is the non-OS/2 implementation (really Unix).
6471 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006472 int j;
6473 char_u *tempname;
6474 char_u *command;
6475 FILE *fd;
6476 char_u *buffer;
Bram Moolenaarc7247912008-01-13 12:54:11 +00006477#define STYLE_ECHO 0 /* use "echo", the default */
6478#define STYLE_GLOB 1 /* use "glob", for csh */
6479#define STYLE_VIMGLOB 2 /* use "vimglob", for Posix sh */
6480#define STYLE_PRINT 3 /* use "print -N", for zsh */
6481#define STYLE_BT 4 /* `cmd` expansion, execute the pattern
6482 * directly */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006483 int shell_style = STYLE_ECHO;
6484 int check_spaces;
6485 static int did_find_nul = FALSE;
6486 int ampersent = FALSE;
Bram Moolenaarc7247912008-01-13 12:54:11 +00006487 /* vimglob() function to define for Posix shell */
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00006488 static char *sh_vimglob_func = "vimglob() { while [ $# -ge 1 ]; do echo \"$1\"; shift; done }; vimglob >";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006489
6490 *num_file = 0; /* default: no files found */
6491 *file = NULL;
6492
6493 /*
6494 * If there are no wildcards, just copy the names to allocated memory.
6495 * Saves a lot of time, because we don't have to start a new shell.
6496 */
6497 if (!have_wildcard(num_pat, pat))
6498 return save_patterns(num_pat, pat, num_file, file);
6499
Bram Moolenaar0e634da2005-07-20 21:57:28 +00006500# ifdef HAVE_SANDBOX
6501 /* Don't allow any shell command in the sandbox. */
6502 if (sandbox != 0 && check_secure())
6503 return FAIL;
6504# endif
6505
Bram Moolenaar071d4272004-06-13 20:20:40 +00006506 /*
6507 * Don't allow the use of backticks in secure and restricted mode.
6508 */
Bram Moolenaar0e634da2005-07-20 21:57:28 +00006509 if (secure || restricted)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006510 for (i = 0; i < num_pat; ++i)
6511 if (vim_strchr(pat[i], '`') != NULL
6512 && (check_restricted() || check_secure()))
6513 return FAIL;
6514
6515 /*
6516 * get a name for the temp file
6517 */
Bram Moolenaare5c421c2015-03-31 13:33:08 +02006518 if ((tempname = vim_tempname('o', FALSE)) == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006519 {
6520 EMSG(_(e_notmp));
6521 return FAIL;
6522 }
6523
6524 /*
6525 * Let the shell expand the patterns and write the result into the temp
Bram Moolenaarc7247912008-01-13 12:54:11 +00006526 * file.
6527 * STYLE_BT: NL separated
6528 * If expanding `cmd` execute it directly.
6529 * STYLE_GLOB: NUL separated
6530 * If we use *csh, "glob" will work better than "echo".
6531 * STYLE_PRINT: NL or NUL separated
6532 * If we use *zsh, "print -N" will work better than "glob".
6533 * STYLE_VIMGLOB: NL separated
6534 * If we use *sh*, we define "vimglob()".
6535 * STYLE_ECHO: space separated.
6536 * A shell we don't know, stay safe and use "echo".
Bram Moolenaar071d4272004-06-13 20:20:40 +00006537 */
6538 if (num_pat == 1 && *pat[0] == '`'
6539 && (len = STRLEN(pat[0])) > 2
6540 && *(pat[0] + len - 1) == '`')
6541 shell_style = STYLE_BT;
6542 else if ((len = STRLEN(p_sh)) >= 3)
6543 {
6544 if (STRCMP(p_sh + len - 3, "csh") == 0)
6545 shell_style = STYLE_GLOB;
6546 else if (STRCMP(p_sh + len - 3, "zsh") == 0)
6547 shell_style = STYLE_PRINT;
6548 }
Bram Moolenaarc7247912008-01-13 12:54:11 +00006549 if (shell_style == STYLE_ECHO && strstr((char *)gettail(p_sh),
6550 "sh") != NULL)
6551 shell_style = STYLE_VIMGLOB;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006552
Bram Moolenaarc7247912008-01-13 12:54:11 +00006553 /* Compute the length of the command. We need 2 extra bytes: for the
6554 * optional '&' and for the NUL.
6555 * Worst case: "unset nonomatch; print -N >" plus two is 29 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006556 len = STRLEN(tempname) + 29;
Bram Moolenaarc7247912008-01-13 12:54:11 +00006557 if (shell_style == STYLE_VIMGLOB)
6558 len += STRLEN(sh_vimglob_func);
6559
Bram Moolenaarb23c3382005-01-31 19:09:12 +00006560 for (i = 0; i < num_pat; ++i)
6561 {
6562 /* Count the length of the patterns in the same way as they are put in
6563 * "command" below. */
6564#ifdef USE_SYSTEM
Bram Moolenaar071d4272004-06-13 20:20:40 +00006565 len += STRLEN(pat[i]) + 3; /* add space and two quotes */
Bram Moolenaarb23c3382005-01-31 19:09:12 +00006566#else
6567 ++len; /* add space */
Bram Moolenaar316059c2006-01-14 21:18:42 +00006568 for (j = 0; pat[i][j] != NUL; ++j)
6569 {
6570 if (vim_strchr(SHELL_SPECIAL, pat[i][j]) != NULL)
6571 ++len; /* may add a backslash */
6572 ++len;
6573 }
Bram Moolenaarb23c3382005-01-31 19:09:12 +00006574#endif
6575 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006576 command = alloc(len);
6577 if (command == NULL)
6578 {
6579 /* out of memory */
6580 vim_free(tempname);
6581 return FAIL;
6582 }
6583
6584 /*
6585 * Build the shell command:
6586 * - Set $nonomatch depending on EW_NOTFOUND (hopefully the shell
6587 * recognizes this).
6588 * - Add the shell command to print the expanded names.
6589 * - Add the temp file name.
6590 * - Add the file name patterns.
6591 */
6592 if (shell_style == STYLE_BT)
6593 {
Bram Moolenaar316059c2006-01-14 21:18:42 +00006594 /* change `command; command& ` to (command; command ) */
6595 STRCPY(command, "(");
6596 STRCAT(command, pat[0] + 1); /* exclude first backtick */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006597 p = command + STRLEN(command) - 1;
Bram Moolenaar316059c2006-01-14 21:18:42 +00006598 *p-- = ')'; /* remove last backtick */
Bram Moolenaar1c465442017-03-12 20:10:05 +01006599 while (p > command && VIM_ISWHITE(*p))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006600 --p;
6601 if (*p == '&') /* remove trailing '&' */
6602 {
6603 ampersent = TRUE;
6604 *p = ' ';
6605 }
6606 STRCAT(command, ">");
6607 }
6608 else
6609 {
6610 if (flags & EW_NOTFOUND)
6611 STRCPY(command, "set nonomatch; ");
6612 else
6613 STRCPY(command, "unset nonomatch; ");
6614 if (shell_style == STYLE_GLOB)
6615 STRCAT(command, "glob >");
6616 else if (shell_style == STYLE_PRINT)
6617 STRCAT(command, "print -N >");
Bram Moolenaarc7247912008-01-13 12:54:11 +00006618 else if (shell_style == STYLE_VIMGLOB)
6619 STRCAT(command, sh_vimglob_func);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006620 else
6621 STRCAT(command, "echo >");
6622 }
Bram Moolenaarc7247912008-01-13 12:54:11 +00006623
Bram Moolenaar071d4272004-06-13 20:20:40 +00006624 STRCAT(command, tempname);
Bram Moolenaarc7247912008-01-13 12:54:11 +00006625
Bram Moolenaar071d4272004-06-13 20:20:40 +00006626 if (shell_style != STYLE_BT)
6627 for (i = 0; i < num_pat; ++i)
6628 {
6629 /* When using system() always add extra quotes, because the shell
Bram Moolenaar316059c2006-01-14 21:18:42 +00006630 * is started twice. Otherwise put a backslash before special
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00006631 * characters, except inside ``. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006632#ifdef USE_SYSTEM
6633 STRCAT(command, " \"");
6634 STRCAT(command, pat[i]);
6635 STRCAT(command, "\"");
6636#else
Bram Moolenaar582fd852005-03-28 20:58:01 +00006637 int intick = FALSE;
6638
Bram Moolenaar071d4272004-06-13 20:20:40 +00006639 p = command + STRLEN(command);
6640 *p++ = ' ';
Bram Moolenaar316059c2006-01-14 21:18:42 +00006641 for (j = 0; pat[i][j] != NUL; ++j)
Bram Moolenaar582fd852005-03-28 20:58:01 +00006642 {
6643 if (pat[i][j] == '`')
Bram Moolenaar582fd852005-03-28 20:58:01 +00006644 intick = !intick;
Bram Moolenaar316059c2006-01-14 21:18:42 +00006645 else if (pat[i][j] == '\\' && pat[i][j + 1] != NUL)
6646 {
Bram Moolenaard12f5c12006-01-25 22:10:52 +00006647 /* Remove a backslash, take char literally. But keep
Bram Moolenaar49315f62006-02-04 00:54:59 +00006648 * backslash inside backticks, before a special character
6649 * and before a backtick. */
Bram Moolenaard12f5c12006-01-25 22:10:52 +00006650 if (intick
Bram Moolenaar49315f62006-02-04 00:54:59 +00006651 || vim_strchr(SHELL_SPECIAL, pat[i][j + 1]) != NULL
6652 || pat[i][j + 1] == '`')
Bram Moolenaard12f5c12006-01-25 22:10:52 +00006653 *p++ = '\\';
Bram Moolenaar280f1262006-01-30 00:14:18 +00006654 ++j;
Bram Moolenaar316059c2006-01-14 21:18:42 +00006655 }
Bram Moolenaare4df1642014-08-29 12:58:44 +02006656 else if (!intick
6657 && ((flags & EW_KEEPDOLLAR) == 0 || pat[i][j] != '$')
6658 && vim_strchr(SHELL_SPECIAL, pat[i][j]) != NULL)
Bram Moolenaar316059c2006-01-14 21:18:42 +00006659 /* Put a backslash before a special character, but not
Bram Moolenaare4df1642014-08-29 12:58:44 +02006660 * when inside ``. And not for $var when EW_KEEPDOLLAR is
6661 * set. */
Bram Moolenaar316059c2006-01-14 21:18:42 +00006662 *p++ = '\\';
Bram Moolenaar280f1262006-01-30 00:14:18 +00006663
6664 /* Copy one character. */
6665 *p++ = pat[i][j];
Bram Moolenaar582fd852005-03-28 20:58:01 +00006666 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006667 *p = NUL;
6668#endif
6669 }
6670 if (flags & EW_SILENT)
6671 show_shell_mess = FALSE;
6672 if (ampersent)
Bram Moolenaarc7247912008-01-13 12:54:11 +00006673 STRCAT(command, "&"); /* put the '&' after the redirection */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006674
6675 /*
6676 * Using zsh -G: If a pattern has no matches, it is just deleted from
6677 * the argument list, otherwise zsh gives an error message and doesn't
6678 * expand any other pattern.
6679 */
6680 if (shell_style == STYLE_PRINT)
6681 extra_shell_arg = (char_u *)"-G"; /* Use zsh NULL_GLOB option */
6682
6683 /*
6684 * If we use -f then shell variables set in .cshrc won't get expanded.
6685 * vi can do it, so we will too, but it is only necessary if there is a "$"
6686 * in one of the patterns, otherwise we can still use the fast option.
6687 */
6688 else if (shell_style == STYLE_GLOB && !have_dollars(num_pat, pat))
6689 extra_shell_arg = (char_u *)"-f"; /* Use csh fast option */
6690
6691 /*
6692 * execute the shell command
6693 */
6694 i = call_shell(command, SHELL_EXPAND | SHELL_SILENT);
6695
6696 /* When running in the background, give it some time to create the temp
6697 * file, but don't wait for it to finish. */
6698 if (ampersent)
6699 mch_delay(10L, TRUE);
6700
6701 extra_shell_arg = NULL; /* cleanup */
6702 show_shell_mess = TRUE;
6703 vim_free(command);
6704
Bram Moolenaarc7247912008-01-13 12:54:11 +00006705 if (i != 0) /* mch_call_shell() failed */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006706 {
6707 mch_remove(tempname);
6708 vim_free(tempname);
6709 /*
6710 * With interactive completion, the error message is not printed.
6711 * However with USE_SYSTEM, I don't know how to turn off error messages
6712 * from the shell, so screen may still get messed up -- webb.
6713 */
6714#ifndef USE_SYSTEM
6715 if (!(flags & EW_SILENT))
6716#endif
6717 {
6718 redraw_later_clear(); /* probably messed up screen */
6719 msg_putchar('\n'); /* clear bottom line quickly */
6720 cmdline_row = Rows - 1; /* continue on last line */
6721#ifdef USE_SYSTEM
6722 if (!(flags & EW_SILENT))
6723#endif
6724 {
6725 MSG(_(e_wildexpand));
6726 msg_start(); /* don't overwrite this message */
6727 }
6728 }
6729 /* If a `cmd` expansion failed, don't list `cmd` as a match, even when
6730 * EW_NOTFOUND is given */
6731 if (shell_style == STYLE_BT)
6732 return FAIL;
6733 goto notfound;
6734 }
6735
6736 /*
6737 * read the names from the file into memory
6738 */
6739 fd = fopen((char *)tempname, READBIN);
6740 if (fd == NULL)
6741 {
6742 /* Something went wrong, perhaps a file name with a special char. */
6743 if (!(flags & EW_SILENT))
6744 {
6745 MSG(_(e_wildexpand));
6746 msg_start(); /* don't overwrite this message */
6747 }
6748 vim_free(tempname);
6749 goto notfound;
6750 }
6751 fseek(fd, 0L, SEEK_END);
Bram Moolenaar85325f82017-03-30 21:18:45 +02006752 llen = ftell(fd); /* get size of temp file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006753 fseek(fd, 0L, SEEK_SET);
Bram Moolenaar85325f82017-03-30 21:18:45 +02006754 if (llen < 0)
6755 /* just in case ftell() would fail */
6756 buffer = NULL;
6757 else
6758 buffer = alloc(llen + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006759 if (buffer == NULL)
6760 {
6761 /* out of memory */
6762 mch_remove(tempname);
6763 vim_free(tempname);
6764 fclose(fd);
6765 return FAIL;
6766 }
Bram Moolenaar85325f82017-03-30 21:18:45 +02006767 len = llen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006768 i = fread((char *)buffer, 1, len, fd);
6769 fclose(fd);
6770 mch_remove(tempname);
Bram Moolenaar78a15312009-05-15 19:33:18 +00006771 if (i != (int)len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006772 {
6773 /* unexpected read error */
6774 EMSG2(_(e_notread), tempname);
6775 vim_free(tempname);
6776 vim_free(buffer);
6777 return FAIL;
6778 }
6779 vim_free(tempname);
6780
Bram Moolenaarc7247912008-01-13 12:54:11 +00006781# if defined(__CYGWIN__) || defined(__CYGWIN32__)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006782 /* Translate <CR><NL> into <NL>. Caution, buffer may contain NUL. */
6783 p = buffer;
Bram Moolenaarfe17e762013-06-29 14:17:02 +02006784 for (i = 0; i < (int)len; ++i)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006785 if (!(buffer[i] == CAR && buffer[i + 1] == NL))
6786 *p++ = buffer[i];
6787 len = p - buffer;
6788# endif
6789
6790
6791 /* file names are separated with Space */
6792 if (shell_style == STYLE_ECHO)
6793 {
6794 buffer[len] = '\n'; /* make sure the buffer ends in NL */
6795 p = buffer;
6796 for (i = 0; *p != '\n'; ++i) /* count number of entries */
6797 {
6798 while (*p != ' ' && *p != '\n')
6799 ++p;
6800 p = skipwhite(p); /* skip to next entry */
6801 }
6802 }
6803 /* file names are separated with NL */
Bram Moolenaarc7247912008-01-13 12:54:11 +00006804 else if (shell_style == STYLE_BT || shell_style == STYLE_VIMGLOB)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006805 {
6806 buffer[len] = NUL; /* make sure the buffer ends in NUL */
6807 p = buffer;
6808 for (i = 0; *p != NUL; ++i) /* count number of entries */
6809 {
6810 while (*p != '\n' && *p != NUL)
6811 ++p;
6812 if (*p != NUL)
6813 ++p;
6814 p = skipwhite(p); /* skip leading white space */
6815 }
6816 }
6817 /* file names are separated with NUL */
6818 else
6819 {
6820 /*
6821 * Some versions of zsh use spaces instead of NULs to separate
6822 * results. Only do this when there is no NUL before the end of the
6823 * buffer, otherwise we would never be able to use file names with
6824 * embedded spaces when zsh does use NULs.
6825 * When we found a NUL once, we know zsh is OK, set did_find_nul and
6826 * don't check for spaces again.
6827 */
6828 check_spaces = FALSE;
6829 if (shell_style == STYLE_PRINT && !did_find_nul)
6830 {
6831 /* If there is a NUL, set did_find_nul, else set check_spaces */
Bram Moolenaaref9d6aa2011-04-11 16:56:35 +02006832 buffer[len] = NUL;
Bram Moolenaarb011af92013-12-11 13:21:51 +01006833 if (len && (int)STRLEN(buffer) < (int)len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006834 did_find_nul = TRUE;
6835 else
6836 check_spaces = TRUE;
6837 }
6838
6839 /*
6840 * Make sure the buffer ends with a NUL. For STYLE_PRINT there
6841 * already is one, for STYLE_GLOB it needs to be added.
6842 */
6843 if (len && buffer[len - 1] == NUL)
6844 --len;
6845 else
6846 buffer[len] = NUL;
6847 i = 0;
6848 for (p = buffer; p < buffer + len; ++p)
6849 if (*p == NUL || (*p == ' ' && check_spaces)) /* count entry */
6850 {
6851 ++i;
6852 *p = NUL;
6853 }
6854 if (len)
6855 ++i; /* count last entry */
6856 }
6857 if (i == 0)
6858 {
6859 /*
6860 * Can happen when using /bin/sh and typing ":e $NO_SUCH_VAR^I".
6861 * /bin/sh will happily expand it to nothing rather than returning an
6862 * error; and hey, it's good to check anyway -- webb.
6863 */
6864 vim_free(buffer);
6865 goto notfound;
6866 }
6867 *num_file = i;
6868 *file = (char_u **)alloc(sizeof(char_u *) * i);
6869 if (*file == NULL)
6870 {
6871 /* out of memory */
6872 vim_free(buffer);
6873 return FAIL;
6874 }
6875
6876 /*
6877 * Isolate the individual file names.
6878 */
6879 p = buffer;
6880 for (i = 0; i < *num_file; ++i)
6881 {
6882 (*file)[i] = p;
6883 /* Space or NL separates */
Bram Moolenaarc7247912008-01-13 12:54:11 +00006884 if (shell_style == STYLE_ECHO || shell_style == STYLE_BT
6885 || shell_style == STYLE_VIMGLOB)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006886 {
Bram Moolenaar49315f62006-02-04 00:54:59 +00006887 while (!(shell_style == STYLE_ECHO && *p == ' ')
6888 && *p != '\n' && *p != NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006889 ++p;
6890 if (p == buffer + len) /* last entry */
6891 *p = NUL;
6892 else
6893 {
6894 *p++ = NUL;
6895 p = skipwhite(p); /* skip to next entry */
6896 }
6897 }
6898 else /* NUL separates */
6899 {
6900 while (*p && p < buffer + len) /* skip entry */
6901 ++p;
6902 ++p; /* skip NUL */
6903 }
6904 }
6905
6906 /*
6907 * Move the file names to allocated memory.
6908 */
6909 for (j = 0, i = 0; i < *num_file; ++i)
6910 {
6911 /* Require the files to exist. Helps when using /bin/sh */
6912 if (!(flags & EW_NOTFOUND) && mch_getperm((*file)[i]) < 0)
6913 continue;
6914
6915 /* check if this entry should be included */
6916 dir = (mch_isdir((*file)[i]));
6917 if ((dir && !(flags & EW_DIR)) || (!dir && !(flags & EW_FILE)))
6918 continue;
6919
Bram Moolenaara2031822006-03-07 22:29:51 +00006920 /* Skip files that are not executable if we check for that. */
Bram Moolenaarb5971142015-03-21 17:32:19 +01006921 if (!dir && (flags & EW_EXEC)
6922 && !mch_can_exe((*file)[i], NULL, !(flags & EW_SHELLCMD)))
Bram Moolenaara2031822006-03-07 22:29:51 +00006923 continue;
6924
Bram Moolenaar071d4272004-06-13 20:20:40 +00006925 p = alloc((unsigned)(STRLEN((*file)[i]) + 1 + dir));
6926 if (p)
6927 {
6928 STRCPY(p, (*file)[i]);
6929 if (dir)
Bram Moolenaarb2389092008-01-03 17:56:04 +00006930 add_pathsep(p); /* add '/' to a directory name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006931 (*file)[j++] = p;
6932 }
6933 }
6934 vim_free(buffer);
6935 *num_file = j;
6936
6937 if (*num_file == 0) /* rejected all entries */
6938 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01006939 VIM_CLEAR(*file);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006940 goto notfound;
6941 }
6942
6943 return OK;
6944
6945notfound:
6946 if (flags & EW_NOTFOUND)
6947 return save_patterns(num_pat, pat, num_file, file);
6948 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006949}
6950
6951#endif /* VMS */
6952
Bram Moolenaar071d4272004-06-13 20:20:40 +00006953 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01006954save_patterns(
6955 int num_pat,
6956 char_u **pat,
6957 int *num_file,
6958 char_u ***file)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006959{
6960 int i;
Bram Moolenaard8b02732005-01-14 21:48:43 +00006961 char_u *s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006962
6963 *file = (char_u **)alloc(num_pat * sizeof(char_u *));
6964 if (*file == NULL)
6965 return FAIL;
6966 for (i = 0; i < num_pat; i++)
Bram Moolenaard8b02732005-01-14 21:48:43 +00006967 {
6968 s = vim_strsave(pat[i]);
6969 if (s != NULL)
6970 /* Be compatible with expand_filename(): halve the number of
6971 * backslashes. */
6972 backslash_halve(s);
6973 (*file)[i] = s;
6974 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006975 *num_file = num_pat;
6976 return OK;
6977}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006978
Bram Moolenaar071d4272004-06-13 20:20:40 +00006979/*
6980 * Return TRUE if the string "p" contains a wildcard that mch_expandpath() can
6981 * expand.
6982 */
6983 int
Bram Moolenaar05540972016-01-30 20:31:25 +01006984mch_has_exp_wildcard(char_u *p)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006985{
Bram Moolenaar91acfff2017-03-12 19:22:36 +01006986 for ( ; *p; MB_PTR_ADV(p))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006987 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006988 if (*p == '\\' && p[1] != NUL)
6989 ++p;
6990 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006991 if (vim_strchr((char_u *)
6992#ifdef VMS
6993 "*?%"
6994#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006995 "*?[{'"
Bram Moolenaar071d4272004-06-13 20:20:40 +00006996#endif
6997 , *p) != NULL)
6998 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006999 }
7000 return FALSE;
7001}
7002
7003/*
7004 * Return TRUE if the string "p" contains a wildcard.
7005 * Don't recognize '~' at the end as a wildcard.
7006 */
7007 int
Bram Moolenaar05540972016-01-30 20:31:25 +01007008mch_has_wildcard(char_u *p)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007009{
Bram Moolenaar91acfff2017-03-12 19:22:36 +01007010 for ( ; *p; MB_PTR_ADV(p))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007011 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007012 if (*p == '\\' && p[1] != NUL)
7013 ++p;
7014 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007015 if (vim_strchr((char_u *)
7016#ifdef VMS
7017 "*?%$"
7018#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007019 "*?[{`'$"
Bram Moolenaar071d4272004-06-13 20:20:40 +00007020#endif
7021 , *p) != NULL
7022 || (*p == '~' && p[1] != NUL))
7023 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007024 }
7025 return FALSE;
7026}
7027
Bram Moolenaar071d4272004-06-13 20:20:40 +00007028 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01007029have_wildcard(int num, char_u **file)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007030{
7031 int i;
7032
7033 for (i = 0; i < num; i++)
7034 if (mch_has_wildcard(file[i]))
7035 return 1;
7036 return 0;
7037}
7038
7039 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01007040have_dollars(int num, char_u **file)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007041{
7042 int i;
7043
7044 for (i = 0; i < num; i++)
7045 if (vim_strchr(file[i], '$') != NULL)
7046 return TRUE;
7047 return FALSE;
7048}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007049
Bram Moolenaarfdcc9af2016-02-29 12:52:39 +01007050#if !defined(HAVE_RENAME) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007051/*
7052 * Scaled-down version of rename(), which is missing in Xenix.
7053 * This version can only move regular files and will fail if the
7054 * destination exists.
7055 */
7056 int
Bram Moolenaarfdcc9af2016-02-29 12:52:39 +01007057mch_rename(const char *src, const char *dest)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007058{
7059 struct stat st;
7060
7061 if (stat(dest, &st) >= 0) /* fail if destination exists */
7062 return -1;
7063 if (link(src, dest) != 0) /* link file to new name */
7064 return -1;
7065 if (mch_remove(src) == 0) /* delete link to old name */
7066 return 0;
7067 return -1;
7068}
7069#endif /* !HAVE_RENAME */
7070
7071#ifdef FEAT_MOUSE_GPM
7072/*
7073 * Initializes connection with gpm (if it isn't already opened)
7074 * Return 1 if succeeded (or connection already opened), 0 if failed
7075 */
7076 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01007077gpm_open(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007078{
7079 static Gpm_Connect gpm_connect; /* Must it be kept till closing ? */
7080
7081 if (!gpm_flag)
7082 {
7083 gpm_connect.eventMask = (GPM_UP | GPM_DRAG | GPM_DOWN);
7084 gpm_connect.defaultMask = ~GPM_HARD;
7085 /* Default handling for mouse move*/
7086 gpm_connect.minMod = 0; /* Handle any modifier keys */
7087 gpm_connect.maxMod = 0xffff;
7088 if (Gpm_Open(&gpm_connect, 0) > 0)
7089 {
7090 /* gpm library tries to handling TSTP causes
7091 * problems. Anyways, we close connection to Gpm whenever
7092 * we are going to suspend or starting an external process
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00007093 * so we shouldn't have problem with this
Bram Moolenaar071d4272004-06-13 20:20:40 +00007094 */
Bram Moolenaar76243bd2009-03-02 01:47:02 +00007095# ifdef SIGTSTP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007096 signal(SIGTSTP, restricted ? SIG_IGN : SIG_DFL);
Bram Moolenaar76243bd2009-03-02 01:47:02 +00007097# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007098 return 1; /* succeed */
7099 }
7100 if (gpm_fd == -2)
7101 Gpm_Close(); /* We don't want to talk to xterm via gpm */
7102 return 0;
7103 }
7104 return 1; /* already open */
7105}
7106
7107/*
7108 * Closes connection to gpm
Bram Moolenaar071d4272004-06-13 20:20:40 +00007109 */
7110 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01007111gpm_close(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007112{
7113 if (gpm_flag && gpm_fd >= 0) /* if Open */
7114 Gpm_Close();
7115}
7116
7117/* Reads gpm event and adds special keys to input buf. Returns length of
7118 * generated key sequence.
Bram Moolenaarc7f02552014-04-01 21:00:59 +02007119 * This function is styled after gui_send_mouse_event().
Bram Moolenaar071d4272004-06-13 20:20:40 +00007120 */
7121 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01007122mch_gpm_process(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007123{
7124 int button;
7125 static Gpm_Event gpm_event;
7126 char_u string[6];
7127 int_u vim_modifiers;
7128 int row,col;
7129 unsigned char buttons_mask;
7130 unsigned char gpm_modifiers;
7131 static unsigned char old_buttons = 0;
7132
7133 Gpm_GetEvent(&gpm_event);
7134
7135#ifdef FEAT_GUI
7136 /* Don't put events in the input queue now. */
7137 if (hold_gui_events)
7138 return 0;
7139#endif
7140
7141 row = gpm_event.y - 1;
7142 col = gpm_event.x - 1;
7143
7144 string[0] = ESC; /* Our termcode */
7145 string[1] = 'M';
7146 string[2] = 'G';
7147 switch (GPM_BARE_EVENTS(gpm_event.type))
7148 {
7149 case GPM_DRAG:
7150 string[3] = MOUSE_DRAG;
7151 break;
7152 case GPM_DOWN:
7153 buttons_mask = gpm_event.buttons & ~old_buttons;
7154 old_buttons = gpm_event.buttons;
7155 switch (buttons_mask)
7156 {
7157 case GPM_B_LEFT:
7158 button = MOUSE_LEFT;
7159 break;
7160 case GPM_B_MIDDLE:
7161 button = MOUSE_MIDDLE;
7162 break;
7163 case GPM_B_RIGHT:
7164 button = MOUSE_RIGHT;
7165 break;
7166 default:
7167 return 0;
7168 /*Don't know what to do. Can more than one button be
7169 * reported in one event? */
7170 }
7171 string[3] = (char_u)(button | 0x20);
7172 SET_NUM_MOUSE_CLICKS(string[3], gpm_event.clicks + 1);
7173 break;
7174 case GPM_UP:
7175 string[3] = MOUSE_RELEASE;
7176 old_buttons &= ~gpm_event.buttons;
7177 break;
7178 default:
7179 return 0;
7180 }
7181 /*This code is based on gui_x11_mouse_cb in gui_x11.c */
7182 gpm_modifiers = gpm_event.modifiers;
7183 vim_modifiers = 0x0;
7184 /* I ignore capslock stats. Aren't we all just hate capslock mixing with
7185 * Vim commands ? Besides, gpm_event.modifiers is unsigned char, and
7186 * K_CAPSSHIFT is defined 8, so it probably isn't even reported
7187 */
7188 if (gpm_modifiers & ((1 << KG_SHIFT) | (1 << KG_SHIFTR) | (1 << KG_SHIFTL)))
7189 vim_modifiers |= MOUSE_SHIFT;
7190
7191 if (gpm_modifiers & ((1 << KG_CTRL) | (1 << KG_CTRLR) | (1 << KG_CTRLL)))
7192 vim_modifiers |= MOUSE_CTRL;
7193 if (gpm_modifiers & ((1 << KG_ALT) | (1 << KG_ALTGR)))
7194 vim_modifiers |= MOUSE_ALT;
7195 string[3] |= vim_modifiers;
7196 string[4] = (char_u)(col + ' ' + 1);
7197 string[5] = (char_u)(row + ' ' + 1);
7198 add_to_input_buf(string, 6);
7199 return 6;
7200}
7201#endif /* FEAT_MOUSE_GPM */
7202
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00007203#ifdef FEAT_SYSMOUSE
7204/*
7205 * Initialize connection with sysmouse.
7206 * Let virtual console inform us with SIGUSR2 for pending sysmouse
7207 * output, any sysmouse output than will be processed via sig_sysmouse().
7208 * Return OK if succeeded, FAIL if failed.
7209 */
7210 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01007211sysmouse_open(void)
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00007212{
7213 struct mouse_info mouse;
7214
7215 mouse.operation = MOUSE_MODE;
7216 mouse.u.mode.mode = 0;
7217 mouse.u.mode.signal = SIGUSR2;
7218 if (ioctl(1, CONS_MOUSECTL, &mouse) != -1)
7219 {
7220 signal(SIGUSR2, (RETSIGTYPE (*)())sig_sysmouse);
7221 mouse.operation = MOUSE_SHOW;
7222 ioctl(1, CONS_MOUSECTL, &mouse);
7223 return OK;
7224 }
7225 return FAIL;
7226}
7227
7228/*
7229 * Stop processing SIGUSR2 signals, and also make sure that
7230 * virtual console do not send us any sysmouse related signal.
7231 */
7232 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01007233sysmouse_close(void)
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00007234{
7235 struct mouse_info mouse;
7236
7237 signal(SIGUSR2, restricted ? SIG_IGN : SIG_DFL);
7238 mouse.operation = MOUSE_MODE;
7239 mouse.u.mode.mode = 0;
7240 mouse.u.mode.signal = 0;
7241 ioctl(1, CONS_MOUSECTL, &mouse);
7242}
7243
7244/*
7245 * Gets info from sysmouse and adds special keys to input buf.
7246 */
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00007247 static RETSIGTYPE
7248sig_sysmouse SIGDEFARG(sigarg)
7249{
7250 struct mouse_info mouse;
7251 struct video_info video;
7252 char_u string[6];
7253 int row, col;
7254 int button;
7255 int buttons;
7256 static int oldbuttons = 0;
7257
7258#ifdef FEAT_GUI
7259 /* Don't put events in the input queue now. */
7260 if (hold_gui_events)
7261 return;
7262#endif
7263
7264 mouse.operation = MOUSE_GETINFO;
7265 if (ioctl(1, FBIO_GETMODE, &video.vi_mode) != -1
7266 && ioctl(1, FBIO_MODEINFO, &video) != -1
7267 && ioctl(1, CONS_MOUSECTL, &mouse) != -1
7268 && video.vi_cheight > 0 && video.vi_cwidth > 0)
7269 {
7270 row = mouse.u.data.y / video.vi_cheight;
7271 col = mouse.u.data.x / video.vi_cwidth;
7272 buttons = mouse.u.data.buttons;
7273 string[0] = ESC; /* Our termcode */
7274 string[1] = 'M';
7275 string[2] = 'S';
7276 if (oldbuttons == buttons && buttons != 0)
7277 {
7278 button = MOUSE_DRAG;
7279 }
7280 else
7281 {
7282 switch (buttons)
7283 {
7284 case 0:
7285 button = MOUSE_RELEASE;
7286 break;
7287 case 1:
7288 button = MOUSE_LEFT;
7289 break;
7290 case 2:
7291 button = MOUSE_MIDDLE;
7292 break;
7293 case 4:
7294 button = MOUSE_RIGHT;
7295 break;
7296 default:
7297 return;
7298 }
7299 oldbuttons = buttons;
7300 }
7301 string[3] = (char_u)(button);
7302 string[4] = (char_u)(col + ' ' + 1);
7303 string[5] = (char_u)(row + ' ' + 1);
7304 add_to_input_buf(string, 6);
7305 }
7306 return;
7307}
7308#endif /* FEAT_SYSMOUSE */
7309
Bram Moolenaar071d4272004-06-13 20:20:40 +00007310#if defined(FEAT_LIBCALL) || defined(PROTO)
Bram Moolenaard99df422016-01-29 23:20:40 +01007311typedef char_u * (*STRPROCSTR)(char_u *);
7312typedef char_u * (*INTPROCSTR)(int);
7313typedef int (*STRPROCINT)(char_u *);
7314typedef int (*INTPROCINT)(int);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007315
7316/*
7317 * Call a DLL routine which takes either a string or int param
7318 * and returns an allocated string.
7319 */
7320 int
Bram Moolenaar05540972016-01-30 20:31:25 +01007321mch_libcall(
7322 char_u *libname,
7323 char_u *funcname,
7324 char_u *argstring, /* NULL when using a argint */
7325 int argint,
7326 char_u **string_result,/* NULL when using number_result */
7327 int *number_result)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007328{
7329# if defined(USE_DLOPEN)
7330 void *hinstLib;
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00007331 char *dlerr = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007332# else
7333 shl_t hinstLib;
7334# endif
7335 STRPROCSTR ProcAdd;
7336 INTPROCSTR ProcAddI;
7337 char_u *retval_str = NULL;
7338 int retval_int = 0;
7339 int success = FALSE;
7340
Bram Moolenaarb39ef122006-06-22 16:19:31 +00007341 /*
7342 * Get a handle to the DLL module.
7343 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007344# if defined(USE_DLOPEN)
Bram Moolenaarb39ef122006-06-22 16:19:31 +00007345 /* First clear any error, it's not cleared by the dlopen() call. */
7346 (void)dlerror();
7347
Bram Moolenaar071d4272004-06-13 20:20:40 +00007348 hinstLib = dlopen((char *)libname, RTLD_LAZY
7349# ifdef RTLD_LOCAL
7350 | RTLD_LOCAL
7351# endif
7352 );
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00007353 if (hinstLib == NULL)
7354 {
7355 /* "dlerr" must be used before dlclose() */
7356 dlerr = (char *)dlerror();
7357 if (dlerr != NULL)
7358 EMSG2(_("dlerror = \"%s\""), dlerr);
7359 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007360# else
7361 hinstLib = shl_load((const char*)libname, BIND_IMMEDIATE|BIND_VERBOSE, 0L);
7362# endif
7363
7364 /* If the handle is valid, try to get the function address. */
7365 if (hinstLib != NULL)
7366 {
7367# ifdef HAVE_SETJMP_H
7368 /*
7369 * Catch a crash when calling the library function. For example when
7370 * using a number where a string pointer is expected.
7371 */
7372 mch_startjmp();
7373 if (SETJMP(lc_jump_env) != 0)
7374 {
7375 success = FALSE;
Bram Moolenaard68071d2006-05-02 22:08:30 +00007376# if defined(USE_DLOPEN)
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00007377 dlerr = NULL;
Bram Moolenaard68071d2006-05-02 22:08:30 +00007378# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007379 mch_didjmp();
7380 }
7381 else
7382# endif
7383 {
7384 retval_str = NULL;
7385 retval_int = 0;
7386
7387 if (argstring != NULL)
7388 {
7389# if defined(USE_DLOPEN)
Bram Moolenaar6d721c72017-01-17 16:56:28 +01007390 *(void **)(&ProcAdd) = dlsym(hinstLib, (const char *)funcname);
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00007391 dlerr = (char *)dlerror();
Bram Moolenaar071d4272004-06-13 20:20:40 +00007392# else
7393 if (shl_findsym(&hinstLib, (const char *)funcname,
7394 TYPE_PROCEDURE, (void *)&ProcAdd) < 0)
7395 ProcAdd = NULL;
7396# endif
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00007397 if ((success = (ProcAdd != NULL
7398# if defined(USE_DLOPEN)
7399 && dlerr == NULL
7400# endif
7401 )))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007402 {
7403 if (string_result == NULL)
7404 retval_int = ((STRPROCINT)ProcAdd)(argstring);
7405 else
7406 retval_str = (ProcAdd)(argstring);
7407 }
7408 }
7409 else
7410 {
7411# if defined(USE_DLOPEN)
Bram Moolenaar6d721c72017-01-17 16:56:28 +01007412 *(void **)(&ProcAddI) = dlsym(hinstLib, (const char *)funcname);
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00007413 dlerr = (char *)dlerror();
Bram Moolenaar071d4272004-06-13 20:20:40 +00007414# else
7415 if (shl_findsym(&hinstLib, (const char *)funcname,
7416 TYPE_PROCEDURE, (void *)&ProcAddI) < 0)
7417 ProcAddI = NULL;
7418# endif
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00007419 if ((success = (ProcAddI != NULL
7420# if defined(USE_DLOPEN)
7421 && dlerr == NULL
7422# endif
7423 )))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007424 {
7425 if (string_result == NULL)
7426 retval_int = ((INTPROCINT)ProcAddI)(argint);
7427 else
7428 retval_str = (ProcAddI)(argint);
7429 }
7430 }
7431
7432 /* Save the string before we free the library. */
7433 /* Assume that a "1" or "-1" result is an illegal pointer. */
7434 if (string_result == NULL)
7435 *number_result = retval_int;
7436 else if (retval_str != NULL
7437 && retval_str != (char_u *)1
7438 && retval_str != (char_u *)-1)
7439 *string_result = vim_strsave(retval_str);
7440 }
7441
7442# ifdef HAVE_SETJMP_H
7443 mch_endjmp();
7444# ifdef SIGHASARG
7445 if (lc_signal != 0)
7446 {
7447 int i;
7448
7449 /* try to find the name of this signal */
7450 for (i = 0; signal_info[i].sig != -1; i++)
7451 if (lc_signal == signal_info[i].sig)
7452 break;
7453 EMSG2("E368: got SIG%s in libcall()", signal_info[i].name);
7454 }
7455# endif
7456# endif
7457
Bram Moolenaar071d4272004-06-13 20:20:40 +00007458# if defined(USE_DLOPEN)
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00007459 /* "dlerr" must be used before dlclose() */
7460 if (dlerr != NULL)
7461 EMSG2(_("dlerror = \"%s\""), dlerr);
7462
7463 /* Free the DLL module. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007464 (void)dlclose(hinstLib);
7465# else
7466 (void)shl_unload(hinstLib);
7467# endif
7468 }
7469
7470 if (!success)
7471 {
7472 EMSG2(_(e_libcall), funcname);
7473 return FAIL;
7474 }
7475
7476 return OK;
7477}
7478#endif
7479
7480#if (defined(FEAT_X11) && defined(FEAT_XCLIPBOARD)) || defined(PROTO)
7481static int xterm_trace = -1; /* default: disabled */
7482static int xterm_button;
7483
7484/*
7485 * Setup a dummy window for X selections in a terminal.
7486 */
7487 void
Bram Moolenaar05540972016-01-30 20:31:25 +01007488setup_term_clip(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007489{
7490 int z = 0;
7491 char *strp = "";
7492 Widget AppShell;
7493
7494 if (!x_connect_to_server())
7495 return;
7496
7497 open_app_context();
7498 if (app_context != NULL && xterm_Shell == (Widget)0)
7499 {
7500 int (*oldhandler)();
7501#if defined(HAVE_SETJMP_H)
7502 int (*oldIOhandler)();
7503#endif
Bram Moolenaar833eb1d2016-11-24 17:22:50 +01007504# ifdef ELAPSED_FUNC
7505 ELAPSED_TYPE start_tv;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007506
7507 if (p_verbose > 0)
Bram Moolenaar833eb1d2016-11-24 17:22:50 +01007508 ELAPSED_INIT(start_tv);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007509# endif
7510
7511 /* Ignore X errors while opening the display */
7512 oldhandler = XSetErrorHandler(x_error_check);
7513
7514#if defined(HAVE_SETJMP_H)
7515 /* Ignore X IO errors while opening the display */
7516 oldIOhandler = XSetIOErrorHandler(x_IOerror_check);
7517 mch_startjmp();
7518 if (SETJMP(lc_jump_env) != 0)
7519 {
7520 mch_didjmp();
7521 xterm_dpy = NULL;
7522 }
7523 else
7524#endif
7525 {
7526 xterm_dpy = XtOpenDisplay(app_context, xterm_display,
7527 "vim_xterm", "Vim_xterm", NULL, 0, &z, &strp);
7528#if defined(HAVE_SETJMP_H)
7529 mch_endjmp();
7530#endif
7531 }
7532
7533#if defined(HAVE_SETJMP_H)
7534 /* Now handle X IO errors normally. */
7535 (void)XSetIOErrorHandler(oldIOhandler);
7536#endif
7537 /* Now handle X errors normally. */
7538 (void)XSetErrorHandler(oldhandler);
7539
7540 if (xterm_dpy == NULL)
7541 {
7542 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007543 verb_msg((char_u *)_("Opening the X display failed"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007544 return;
7545 }
7546
7547 /* Catch terminating error of the X server connection. */
7548 (void)XSetIOErrorHandler(x_IOerror_handler);
7549
Bram Moolenaar833eb1d2016-11-24 17:22:50 +01007550# ifdef ELAPSED_FUNC
Bram Moolenaar071d4272004-06-13 20:20:40 +00007551 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007552 {
7553 verbose_enter();
Bram Moolenaar833eb1d2016-11-24 17:22:50 +01007554 xopen_message(ELAPSED_FUNC(start_tv));
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007555 verbose_leave();
7556 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007557# endif
7558
7559 /* Create a Shell to make converters work. */
7560 AppShell = XtVaAppCreateShell("vim_xterm", "Vim_xterm",
7561 applicationShellWidgetClass, xterm_dpy,
7562 NULL);
7563 if (AppShell == (Widget)0)
7564 return;
7565 xterm_Shell = XtVaCreatePopupShell("VIM",
7566 topLevelShellWidgetClass, AppShell,
7567 XtNmappedWhenManaged, 0,
7568 XtNwidth, 1,
7569 XtNheight, 1,
7570 NULL);
7571 if (xterm_Shell == (Widget)0)
7572 return;
7573
7574 x11_setup_atoms(xterm_dpy);
Bram Moolenaar7cfea752010-06-22 06:07:12 +02007575 x11_setup_selection(xterm_Shell);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007576 if (x11_display == NULL)
7577 x11_display = xterm_dpy;
7578
7579 XtRealizeWidget(xterm_Shell);
7580 XSync(xterm_dpy, False);
7581 xterm_update();
7582 }
7583 if (xterm_Shell != (Widget)0)
7584 {
7585 clip_init(TRUE);
7586 if (x11_window == 0 && (strp = getenv("WINDOWID")) != NULL)
7587 x11_window = (Window)atol(strp);
7588 /* Check if $WINDOWID is valid. */
7589 if (test_x11_window(xterm_dpy) == FAIL)
7590 x11_window = 0;
7591 if (x11_window != 0)
7592 xterm_trace = 0;
7593 }
7594}
7595
7596 void
Bram Moolenaar05540972016-01-30 20:31:25 +01007597start_xterm_trace(int button)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007598{
7599 if (x11_window == 0 || xterm_trace < 0 || xterm_Shell == (Widget)0)
7600 return;
7601 xterm_trace = 1;
7602 xterm_button = button;
7603 do_xterm_trace();
7604}
7605
7606
7607 void
Bram Moolenaar05540972016-01-30 20:31:25 +01007608stop_xterm_trace(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007609{
7610 if (xterm_trace < 0)
7611 return;
7612 xterm_trace = 0;
7613}
7614
7615/*
7616 * Query the xterm pointer and generate mouse termcodes if necessary
7617 * return TRUE if dragging is active, else FALSE
7618 */
7619 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01007620do_xterm_trace(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007621{
7622 Window root, child;
7623 int root_x, root_y;
7624 int win_x, win_y;
7625 int row, col;
7626 int_u mask_return;
7627 char_u buf[50];
7628 char_u *strp;
7629 long got_hints;
7630 static char_u *mouse_code;
7631 static char_u mouse_name[2] = {KS_MOUSE, KE_FILLER};
7632 static int prev_row = 0, prev_col = 0;
7633 static XSizeHints xterm_hints;
7634
7635 if (xterm_trace <= 0)
7636 return FALSE;
7637
7638 if (xterm_trace == 1)
7639 {
7640 /* Get the hints just before tracking starts. The font size might
Bram Moolenaara6c2c912008-01-13 15:31:00 +00007641 * have changed recently. */
7642 if (!XGetWMNormalHints(xterm_dpy, x11_window, &xterm_hints, &got_hints)
7643 || !(got_hints & PResizeInc)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007644 || xterm_hints.width_inc <= 1
7645 || xterm_hints.height_inc <= 1)
7646 {
7647 xterm_trace = -1; /* Not enough data -- disable tracing */
7648 return FALSE;
7649 }
7650
7651 /* Rely on the same mouse code for the duration of this */
7652 mouse_code = find_termcode(mouse_name);
7653 prev_row = mouse_row;
Bram Moolenaarcde88542015-08-11 19:14:00 +02007654 prev_col = mouse_col;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007655 xterm_trace = 2;
7656
7657 /* Find the offset of the chars, there might be a scrollbar on the
7658 * left of the window and/or a menu on the top (eterm etc.) */
7659 XQueryPointer(xterm_dpy, x11_window, &root, &child, &root_x, &root_y,
7660 &win_x, &win_y, &mask_return);
7661 xterm_hints.y = win_y - (xterm_hints.height_inc * mouse_row)
7662 - (xterm_hints.height_inc / 2);
7663 if (xterm_hints.y <= xterm_hints.height_inc / 2)
7664 xterm_hints.y = 2;
7665 xterm_hints.x = win_x - (xterm_hints.width_inc * mouse_col)
7666 - (xterm_hints.width_inc / 2);
7667 if (xterm_hints.x <= xterm_hints.width_inc / 2)
7668 xterm_hints.x = 2;
7669 return TRUE;
7670 }
Bram Moolenaaref9d6aa2011-04-11 16:56:35 +02007671 if (mouse_code == NULL || STRLEN(mouse_code) > 45)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007672 {
7673 xterm_trace = 0;
7674 return FALSE;
7675 }
7676
7677 XQueryPointer(xterm_dpy, x11_window, &root, &child, &root_x, &root_y,
7678 &win_x, &win_y, &mask_return);
7679
7680 row = check_row((win_y - xterm_hints.y) / xterm_hints.height_inc);
7681 col = check_col((win_x - xterm_hints.x) / xterm_hints.width_inc);
7682 if (row == prev_row && col == prev_col)
7683 return TRUE;
7684
7685 STRCPY(buf, mouse_code);
7686 strp = buf + STRLEN(buf);
7687 *strp++ = (xterm_button | MOUSE_DRAG) & ~0x20;
7688 *strp++ = (char_u)(col + ' ' + 1);
7689 *strp++ = (char_u)(row + ' ' + 1);
7690 *strp = 0;
7691 add_to_input_buf(buf, STRLEN(buf));
7692
7693 prev_row = row;
7694 prev_col = col;
7695 return TRUE;
7696}
7697
7698# if defined(FEAT_GUI) || defined(PROTO)
7699/*
7700 * Destroy the display, window and app_context. Required for GTK.
7701 */
7702 void
Bram Moolenaar05540972016-01-30 20:31:25 +01007703clear_xterm_clip(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007704{
7705 if (xterm_Shell != (Widget)0)
7706 {
7707 XtDestroyWidget(xterm_Shell);
7708 xterm_Shell = (Widget)0;
7709 }
7710 if (xterm_dpy != NULL)
7711 {
Bram Moolenaare8208012008-06-20 09:59:25 +00007712# if 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00007713 /* Lesstif and Solaris crash here, lose some memory */
7714 XtCloseDisplay(xterm_dpy);
Bram Moolenaare8208012008-06-20 09:59:25 +00007715# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007716 if (x11_display == xterm_dpy)
7717 x11_display = NULL;
7718 xterm_dpy = NULL;
7719 }
Bram Moolenaare8208012008-06-20 09:59:25 +00007720# if 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00007721 if (app_context != (XtAppContext)NULL)
7722 {
7723 /* Lesstif and Solaris crash here, lose some memory */
7724 XtDestroyApplicationContext(app_context);
7725 app_context = (XtAppContext)NULL;
7726 }
Bram Moolenaare8208012008-06-20 09:59:25 +00007727# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007728}
7729# endif
7730
7731/*
Bram Moolenaar090cfc12013-03-19 12:35:42 +01007732 * Catch up with GUI or X events.
7733 */
7734 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01007735clip_update(void)
Bram Moolenaar090cfc12013-03-19 12:35:42 +01007736{
7737# ifdef FEAT_GUI
7738 if (gui.in_use)
7739 gui_mch_update();
7740 else
7741# endif
7742 if (xterm_Shell != (Widget)0)
7743 xterm_update();
7744}
7745
7746/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007747 * Catch up with any queued X events. This may put keyboard input into the
7748 * input buffer, call resize call-backs, trigger timers etc. If there is
7749 * nothing in the X event queue (& no timers pending), then we return
7750 * immediately.
7751 */
7752 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01007753xterm_update(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007754{
7755 XEvent event;
7756
Bram Moolenaarb1fc2bf2015-03-20 16:26:54 +01007757 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007758 {
Bram Moolenaar93c88e02015-09-15 14:12:05 +02007759 XtInputMask mask = XtAppPending(app_context);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007760
Bram Moolenaar93c88e02015-09-15 14:12:05 +02007761 if (mask == 0 || vim_is_input_buf_full())
Bram Moolenaarb1fc2bf2015-03-20 16:26:54 +01007762 break;
7763
Bram Moolenaar93c88e02015-09-15 14:12:05 +02007764 if (mask & XtIMXEvent)
Bram Moolenaarb1fc2bf2015-03-20 16:26:54 +01007765 {
7766 /* There is an event to process. */
Bram Moolenaar93c88e02015-09-15 14:12:05 +02007767 XtAppNextEvent(app_context, &event);
Bram Moolenaarb1fc2bf2015-03-20 16:26:54 +01007768#ifdef FEAT_CLIENTSERVER
7769 {
7770 XPropertyEvent *e = (XPropertyEvent *)&event;
7771
7772 if (e->type == PropertyNotify && e->window == commWindow
Bram Moolenaar071d4272004-06-13 20:20:40 +00007773 && e->atom == commProperty && e->state == PropertyNewValue)
Bram Moolenaar93c88e02015-09-15 14:12:05 +02007774 serverEventProc(xterm_dpy, &event, 0);
Bram Moolenaarb1fc2bf2015-03-20 16:26:54 +01007775 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007776#endif
Bram Moolenaar93c88e02015-09-15 14:12:05 +02007777 XtDispatchEvent(&event);
7778 }
Bram Moolenaarb1fc2bf2015-03-20 16:26:54 +01007779 else
7780 {
7781 /* There is something else than an event to process. */
Bram Moolenaar93c88e02015-09-15 14:12:05 +02007782 XtAppProcessEvent(app_context, mask);
7783 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007784 }
7785}
7786
7787 int
Bram Moolenaar05540972016-01-30 20:31:25 +01007788clip_xterm_own_selection(VimClipboard *cbd)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007789{
7790 if (xterm_Shell != (Widget)0)
7791 return clip_x11_own_selection(xterm_Shell, cbd);
7792 return FAIL;
7793}
7794
7795 void
Bram Moolenaar05540972016-01-30 20:31:25 +01007796clip_xterm_lose_selection(VimClipboard *cbd)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007797{
7798 if (xterm_Shell != (Widget)0)
7799 clip_x11_lose_selection(xterm_Shell, cbd);
7800}
7801
7802 void
Bram Moolenaar05540972016-01-30 20:31:25 +01007803clip_xterm_request_selection(VimClipboard *cbd)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007804{
7805 if (xterm_Shell != (Widget)0)
7806 clip_x11_request_selection(xterm_Shell, xterm_dpy, cbd);
7807}
7808
7809 void
Bram Moolenaar05540972016-01-30 20:31:25 +01007810clip_xterm_set_selection(VimClipboard *cbd)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007811{
7812 clip_x11_set_selection(cbd);
7813}
7814#endif
7815
7816
7817#if defined(USE_XSMP) || defined(PROTO)
7818/*
7819 * Code for X Session Management Protocol.
7820 */
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +01007821static void xsmp_handle_save_yourself(SmcConn smc_conn, SmPointer client_data, int save_type, Bool shutdown, int interact_style, Bool fast);
7822static void xsmp_die(SmcConn smc_conn, SmPointer client_data);
7823static void xsmp_save_complete(SmcConn smc_conn, SmPointer client_data);
7824static void xsmp_shutdown_cancelled(SmcConn smc_conn, SmPointer client_data);
7825static void xsmp_ice_connection(IceConn iceConn, IcePointer clientData, Bool opening, IcePointer *watchData);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007826
7827
7828# if defined(FEAT_GUI) && defined(USE_XSMP_INTERACT)
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +01007829static void xsmp_handle_interaction(SmcConn smc_conn, SmPointer client_data);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007830
7831/*
7832 * This is our chance to ask the user if they want to save,
7833 * or abort the logout
7834 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007835 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01007836xsmp_handle_interaction(SmcConn smc_conn, SmPointer client_data UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007837{
7838 cmdmod_T save_cmdmod;
7839 int cancel_shutdown = False;
7840
7841 save_cmdmod = cmdmod;
7842 cmdmod.confirm = TRUE;
Bram Moolenaar027387f2016-01-02 22:25:52 +01007843 if (check_changed_any(FALSE, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007844 /* Mustn't logout */
7845 cancel_shutdown = True;
7846 cmdmod = save_cmdmod;
7847 setcursor(); /* position cursor */
7848 out_flush();
7849
7850 /* Done interaction */
7851 SmcInteractDone(smc_conn, cancel_shutdown);
7852
7853 /* Finish off
7854 * Only end save-yourself here if we're not cancelling shutdown;
7855 * we'll get a cancelled callback later in which we'll end it.
7856 * Hopefully get around glitchy SMs (like GNOME-1)
7857 */
7858 if (!cancel_shutdown)
7859 {
7860 xsmp.save_yourself = False;
7861 SmcSaveYourselfDone(smc_conn, True);
7862 }
7863}
7864# endif
7865
7866/*
7867 * Callback that starts save-yourself.
7868 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007869 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01007870xsmp_handle_save_yourself(
7871 SmcConn smc_conn,
7872 SmPointer client_data UNUSED,
7873 int save_type UNUSED,
7874 Bool shutdown,
7875 int interact_style UNUSED,
7876 Bool fast UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007877{
7878 /* Handle already being in saveyourself */
7879 if (xsmp.save_yourself)
7880 SmcSaveYourselfDone(smc_conn, True);
7881 xsmp.save_yourself = True;
7882 xsmp.shutdown = shutdown;
7883
7884 /* First up, preserve all files */
7885 out_flush();
7886 ml_sync_all(FALSE, FALSE); /* preserve all swap files */
7887
7888 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007889 verb_msg((char_u *)_("XSMP handling save-yourself request"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007890
7891# if defined(FEAT_GUI) && defined(USE_XSMP_INTERACT)
7892 /* Now see if we can ask about unsaved files */
7893 if (shutdown && !fast && gui.in_use)
7894 /* Need to interact with user, but need SM's permission */
7895 SmcInteractRequest(smc_conn, SmDialogError,
7896 xsmp_handle_interaction, client_data);
7897 else
7898# endif
7899 {
7900 /* Can stop the cycle here */
7901 SmcSaveYourselfDone(smc_conn, True);
7902 xsmp.save_yourself = False;
7903 }
7904}
7905
7906
7907/*
7908 * Callback to warn us of imminent death.
7909 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007910 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01007911xsmp_die(SmcConn smc_conn UNUSED, SmPointer client_data UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007912{
7913 xsmp_close();
7914
7915 /* quit quickly leaving swapfiles for modified buffers behind */
7916 getout_preserve_modified(0);
7917}
7918
7919
7920/*
7921 * Callback to tell us that save-yourself has completed.
7922 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007923 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01007924xsmp_save_complete(
7925 SmcConn smc_conn UNUSED,
7926 SmPointer client_data UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007927{
7928 xsmp.save_yourself = False;
7929}
7930
7931
7932/*
7933 * Callback to tell us that an instigated shutdown was cancelled
7934 * (maybe even by us)
7935 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007936 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01007937xsmp_shutdown_cancelled(
7938 SmcConn smc_conn,
7939 SmPointer client_data UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007940{
7941 if (xsmp.save_yourself)
7942 SmcSaveYourselfDone(smc_conn, True);
7943 xsmp.save_yourself = False;
7944 xsmp.shutdown = False;
7945}
7946
7947
7948/*
7949 * Callback to tell us that a new ICE connection has been established.
7950 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007951 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01007952xsmp_ice_connection(
7953 IceConn iceConn,
7954 IcePointer clientData UNUSED,
7955 Bool opening,
7956 IcePointer *watchData UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007957{
7958 /* Intercept creation of ICE connection fd */
7959 if (opening)
7960 {
7961 xsmp_icefd = IceConnectionNumber(iceConn);
7962 IceRemoveConnectionWatch(xsmp_ice_connection, NULL);
7963 }
7964}
7965
7966
7967/* Handle any ICE processing that's required; return FAIL if SM lost */
7968 int
Bram Moolenaar05540972016-01-30 20:31:25 +01007969xsmp_handle_requests(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007970{
7971 Bool rep;
7972
7973 if (IceProcessMessages(xsmp.iceconn, NULL, &rep)
7974 == IceProcessMessagesIOError)
7975 {
7976 /* Lost ICE */
7977 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007978 verb_msg((char_u *)_("XSMP lost ICE connection"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007979 xsmp_close();
7980 return FAIL;
7981 }
7982 else
7983 return OK;
7984}
7985
7986static int dummy;
7987
7988/* Set up X Session Management Protocol */
7989 void
7990xsmp_init(void)
7991{
7992 char errorstring[80];
Bram Moolenaar071d4272004-06-13 20:20:40 +00007993 SmcCallbacks smcallbacks;
7994#if 0
7995 SmPropValue smname;
7996 SmProp smnameprop;
7997 SmProp *smprops[1];
7998#endif
7999
8000 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00008001 verb_msg((char_u *)_("XSMP opening connection"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00008002
8003 xsmp.save_yourself = xsmp.shutdown = False;
8004
8005 /* Set up SM callbacks - must have all, even if they're not used */
8006 smcallbacks.save_yourself.callback = xsmp_handle_save_yourself;
8007 smcallbacks.save_yourself.client_data = NULL;
8008 smcallbacks.die.callback = xsmp_die;
8009 smcallbacks.die.client_data = NULL;
8010 smcallbacks.save_complete.callback = xsmp_save_complete;
8011 smcallbacks.save_complete.client_data = NULL;
8012 smcallbacks.shutdown_cancelled.callback = xsmp_shutdown_cancelled;
8013 smcallbacks.shutdown_cancelled.client_data = NULL;
8014
8015 /* Set up a watch on ICE connection creations. The "dummy" argument is
8016 * apparently required for FreeBSD (we get a BUS error when using NULL). */
8017 if (IceAddConnectionWatch(xsmp_ice_connection, &dummy) == 0)
8018 {
8019 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00008020 verb_msg((char_u *)_("XSMP ICE connection watch failed"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00008021 return;
8022 }
8023
8024 /* Create an SM connection */
8025 xsmp.smcconn = SmcOpenConnection(
8026 NULL,
8027 NULL,
8028 SmProtoMajor,
8029 SmProtoMinor,
8030 SmcSaveYourselfProcMask | SmcDieProcMask
8031 | SmcSaveCompleteProcMask | SmcShutdownCancelledProcMask,
8032 &smcallbacks,
8033 NULL,
Bram Moolenaare8208012008-06-20 09:59:25 +00008034 &xsmp.clientid,
Bram Moolenaar071d4272004-06-13 20:20:40 +00008035 sizeof(errorstring),
8036 errorstring);
8037 if (xsmp.smcconn == NULL)
8038 {
8039 char errorreport[132];
Bram Moolenaar051b7822005-05-19 21:00:46 +00008040
Bram Moolenaar071d4272004-06-13 20:20:40 +00008041 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00008042 {
8043 vim_snprintf(errorreport, sizeof(errorreport),
8044 _("XSMP SmcOpenConnection failed: %s"), errorstring);
8045 verb_msg((char_u *)errorreport);
8046 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008047 return;
8048 }
8049 xsmp.iceconn = SmcGetIceConnection(xsmp.smcconn);
8050
8051#if 0
8052 /* ID ourselves */
8053 smname.value = "vim";
8054 smname.length = 3;
8055 smnameprop.name = "SmProgram";
8056 smnameprop.type = "SmARRAY8";
8057 smnameprop.num_vals = 1;
8058 smnameprop.vals = &smname;
8059
8060 smprops[0] = &smnameprop;
8061 SmcSetProperties(xsmp.smcconn, 1, smprops);
8062#endif
8063}
8064
8065
8066/* Shut down XSMP comms. */
8067 void
Bram Moolenaar05540972016-01-30 20:31:25 +01008068xsmp_close(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008069{
8070 if (xsmp_icefd != -1)
8071 {
8072 SmcCloseConnection(xsmp.smcconn, 0, NULL);
Bram Moolenaar5a221812008-11-12 12:08:45 +00008073 if (xsmp.clientid != NULL)
8074 free(xsmp.clientid);
Bram Moolenaare8208012008-06-20 09:59:25 +00008075 xsmp.clientid = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008076 xsmp_icefd = -1;
8077 }
8078}
8079#endif /* USE_XSMP */
8080
8081
8082#ifdef EBCDIC
8083/* Translate character to its CTRL- value */
8084char CtrlTable[] =
8085{
8086/* 00 - 5E */
8087 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
8088 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
8089 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
8090 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
8091 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
8092 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
8093/* ^ */ 0x1E,
8094/* - */ 0x1F,
8095/* 61 - 6C */
8096 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
8097/* _ */ 0x1F,
8098/* 6E - 80 */
8099 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
8100/* a */ 0x01,
8101/* b */ 0x02,
8102/* c */ 0x03,
8103/* d */ 0x37,
8104/* e */ 0x2D,
8105/* f */ 0x2E,
8106/* g */ 0x2F,
8107/* h */ 0x16,
8108/* i */ 0x05,
8109/* 8A - 90 */
8110 0, 0, 0, 0, 0, 0, 0,
8111/* j */ 0x15,
8112/* k */ 0x0B,
8113/* l */ 0x0C,
8114/* m */ 0x0D,
8115/* n */ 0x0E,
8116/* o */ 0x0F,
8117/* p */ 0x10,
8118/* q */ 0x11,
8119/* r */ 0x12,
8120/* 9A - A1 */
8121 0, 0, 0, 0, 0, 0, 0, 0,
8122/* s */ 0x13,
8123/* t */ 0x3C,
8124/* u */ 0x3D,
8125/* v */ 0x32,
8126/* w */ 0x26,
8127/* x */ 0x18,
8128/* y */ 0x19,
8129/* z */ 0x3F,
8130/* AA - AC */
8131 0, 0, 0,
8132/* [ */ 0x27,
8133/* AE - BC */
8134 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
8135/* ] */ 0x1D,
8136/* BE - C0 */ 0, 0, 0,
8137/* A */ 0x01,
8138/* B */ 0x02,
8139/* C */ 0x03,
8140/* D */ 0x37,
8141/* E */ 0x2D,
8142/* F */ 0x2E,
8143/* G */ 0x2F,
8144/* H */ 0x16,
8145/* I */ 0x05,
8146/* CA - D0 */ 0, 0, 0, 0, 0, 0, 0,
8147/* J */ 0x15,
8148/* K */ 0x0B,
8149/* L */ 0x0C,
8150/* M */ 0x0D,
8151/* N */ 0x0E,
8152/* O */ 0x0F,
8153/* P */ 0x10,
8154/* Q */ 0x11,
8155/* R */ 0x12,
8156/* DA - DF */ 0, 0, 0, 0, 0, 0,
8157/* \ */ 0x1C,
8158/* E1 */ 0,
8159/* S */ 0x13,
8160/* T */ 0x3C,
8161/* U */ 0x3D,
8162/* V */ 0x32,
8163/* W */ 0x26,
8164/* X */ 0x18,
8165/* Y */ 0x19,
8166/* Z */ 0x3F,
8167/* EA - FF*/ 0, 0, 0, 0, 0, 0,
8168 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
8169};
8170
8171char MetaCharTable[]=
8172{/* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
8173 0, 0, 0, 0,'\\', 0,'F', 0,'W','M','N', 0, 0, 0, 0, 0,
8174 0, 0, 0, 0,']', 0, 0,'G', 0, 0,'R','O', 0, 0, 0, 0,
8175 '@','A','B','C','D','E', 0, 0,'H','I','J','K','L', 0, 0, 0,
8176 'P','Q', 0,'S','T','U','V', 0,'X','Y','Z','[', 0, 0,'^', 0
8177};
8178
8179
8180/* TODO: Use characters NOT numbers!!! */
8181char CtrlCharTable[]=
8182{/* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
8183 124,193,194,195, 0,201, 0, 0, 0, 0, 0,210,211,212,213,214,
8184 215,216,217,226, 0,209,200, 0,231,232, 0, 0,224,189, 95,109,
8185 0, 0, 0, 0, 0, 0,230,173, 0, 0, 0, 0, 0,197,198,199,
8186 0, 0,229, 0, 0, 0, 0,196, 0, 0, 0, 0,227,228, 0,233,
8187};
8188
8189
8190#endif