blob: 9fd6436e6ff66f6bd06ad513501c62f22622e9ff [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!!!
Bram Moolenaar041c7102020-05-30 18:14:57 +020015 * Also for Atari MiNT.
Bram Moolenaar071d4272004-06-13 20:20:40 +000016 *
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 Moolenaar0f873732019-12-05 20:28:46 +010027#include "os_unixx.h" // unix includes for os_unix.c only
Bram Moolenaar071d4272004-06-13 20:20:40 +000028
Foxe Chenb90c2392025-06-27 21:10:35 +020029#ifdef HAVE_SHM_OPEN
30# include <sys/mman.h>
31# include <sys/stat.h>
32# include <fcntl.h>
33#endif
34
Bram Moolenaar071d4272004-06-13 20:20:40 +000035#ifdef USE_XSMP
36# include <X11/SM/SMlib.h>
37#endif
38
Bram Moolenaar588ebeb2008-05-07 17:09:24 +000039#ifdef HAVE_SELINUX
40# include <selinux/selinux.h>
41static int selinux_enabled = -1;
42#endif
43
Christian Brabandte085dfd2023-09-30 12:49:18 +020044#ifdef FEAT_XATTR
zeertzjq6de4e582023-09-30 14:19:14 +020045# include <sys/xattr.h>
Christian Brabandte085dfd2023-09-30 12:49:18 +020046#endif
47
Bram Moolenaar5bd32f42014-04-02 14:05:38 +020048#ifdef HAVE_SMACK
zeertzjq6de4e582023-09-30 14:19:14 +020049# include <sys/xattr.h>
Bram Moolenaar5bd32f42014-04-02 14:05:38 +020050# include <linux/xattr.h>
51# ifndef SMACK_LABEL_LEN
52# define SMACK_LABEL_LEN 1024
53# endif
54#endif
55
Bram Moolenaara2442432007-04-26 14:26:37 +000056#ifdef __CYGWIN__
K.Takata972db232022-02-04 10:45:38 +000057# include <cygwin/version.h>
58# include <sys/cygwin.h> // for cygwin_conv_to_posix_path() and/or
Bram Moolenaar0f873732019-12-05 20:28:46 +010059 // for cygwin_conv_path()
K.Takata972db232022-02-04 10:45:38 +000060# ifdef FEAT_CYGWIN_WIN32_CLIPBOARD
61# define WIN32_LEAN_AND_MEAN
62# include <windows.h>
63# include "winclip.pro"
Bram Moolenaara2442432007-04-26 14:26:37 +000064# endif
65#endif
66
Bram Moolenaar071d4272004-06-13 20:20:40 +000067#ifdef FEAT_MOUSE_GPM
Bram Moolenaar33fc4a62022-02-23 18:07:38 +000068
Bram Moolenaar071d4272004-06-13 20:20:40 +000069# include <gpm.h>
Bram Moolenaar33fc4a62022-02-23 18:07:38 +000070
71# ifdef DYNAMIC_GPM
72# define Gpm_Open (*dll_Gpm_Open)
73# define Gpm_Close (*dll_Gpm_Close)
74# define Gpm_GetEvent (*dll_Gpm_GetEvent)
75# define gpm_flag (dll_gpm_flag != NULL ? *dll_gpm_flag : 0)
76# define gpm_fd (dll_gpm_fd != NULL ? *dll_gpm_fd : -1)
77
78static int (*dll_Gpm_Open) (Gpm_Connect *, int);
79static int (*dll_Gpm_Close) (void);
80static int (*dll_Gpm_GetEvent) (Gpm_Event *);
81static int *dll_gpm_flag;
82static int *dll_gpm_fd;
83
84static void *libgpm_hinst;
85# endif
86
Bram Moolenaar0f873732019-12-05 20:28:46 +010087// <linux/keyboard.h> contains defines conflicting with "keymap.h",
88// I just copied relevant defines here. A cleaner solution would be to put gpm
89// code into separate file and include there linux/keyboard.h
90// #include <linux/keyboard.h>
Bram Moolenaar071d4272004-06-13 20:20:40 +000091# define KG_SHIFT 0
92# define KG_CTRL 2
93# define KG_ALT 3
94# define KG_ALTGR 1
95# define KG_SHIFTL 4
96# define KG_SHIFTR 5
97# define KG_CTRLL 6
98# define KG_CTRLR 7
99# define KG_CAPSSHIFT 8
100
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +0100101static void gpm_close(void);
102static int gpm_open(void);
103static int mch_gpm_process(void);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000104#endif
105
Bram Moolenaar3577c6f2008-06-24 21:16:56 +0000106#ifdef FEAT_SYSMOUSE
107# include <sys/consio.h>
108# include <sys/fbio.h>
109
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +0100110static int sysmouse_open(void);
111static void sysmouse_close(void);
Bram Moolenaar99c48fe2022-06-05 22:05:19 +0100112static void sig_sysmouse SIGPROTOARG;
Bram Moolenaar3577c6f2008-06-24 21:16:56 +0000113#endif
114
Bram Moolenaar071d4272004-06-13 20:20:40 +0000115/*
116 * end of autoconf section. To be extended...
117 */
118
Bram Moolenaar0f873732019-12-05 20:28:46 +0100119// Are the following #ifdefs still required? And why? Is that for X11?
Bram Moolenaar071d4272004-06-13 20:20:40 +0000120
121#if defined(ESIX) || defined(M_UNIX) && !defined(SCO)
122# ifdef SIGWINCH
123# undef SIGWINCH
124# endif
125# ifdef TIOCGWINSZ
126# undef TIOCGWINSZ
127# endif
128#endif
129
Bram Moolenaar0f873732019-12-05 20:28:46 +0100130#if defined(SIGWINDOW) && !defined(SIGWINCH) // hpux 9.01 has it
Bram Moolenaar071d4272004-06-13 20:20:40 +0000131# define SIGWINCH SIGWINDOW
132#endif
133
134#ifdef FEAT_X11
135# include <X11/Xlib.h>
136# include <X11/Xutil.h>
137# include <X11/Xatom.h>
138# ifdef FEAT_XCLIPBOARD
139# include <X11/Intrinsic.h>
140# include <X11/Shell.h>
141# include <X11/StringDefs.h>
142static Widget xterm_Shell = (Widget)0;
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +0100143static void clip_update(void);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000144# endif
145
Bram Moolenaar071d4272004-06-13 20:20:40 +0000146Window x11_window = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000147Display *x11_display = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000148#endif
149
Bram Moolenaar5c3128e2020-05-11 20:54:42 +0200150static int ignore_sigtstp = FALSE;
151
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +0100152static int get_x11_title(int);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000153
154static char_u *oldtitle = NULL;
Bram Moolenaar8e82c052018-08-21 19:47:48 +0200155static volatile sig_atomic_t oldtitle_outdated = FALSE;
Bram Moolenaardac13472019-09-16 21:06:21 +0200156static int unix_did_set_title = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000157static char_u *oldicon = NULL;
158static int did_set_icon = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000159
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +0100160static void may_core_dump(void);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000161
Bram Moolenaar205b8862011-09-07 15:04:31 +0200162#ifdef HAVE_UNION_WAIT
163typedef union wait waitstatus;
164#else
165typedef int waitstatus;
166#endif
Bram Moolenaare9c21ae2017-08-03 20:44:48 +0200167static int WaitForChar(long msec, int *interrupted, int ignore_input);
168static int WaitForCharOrMouse(long msec, int *interrupted, int ignore_input);
Bram Moolenaar041c7102020-05-30 18:14:57 +0200169#ifdef VMS
Bram Moolenaarcda77642016-06-04 13:32:35 +0200170int RealWaitForChar(int, long, int *, int *interrupted);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000171#else
Bram Moolenaarcda77642016-06-04 13:32:35 +0200172static int RealWaitForChar(int, long, int *, int *interrupted);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000173#endif
174
175#ifdef FEAT_XCLIPBOARD
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +0100176static int do_xterm_trace(void);
Bram Moolenaar0f873732019-12-05 20:28:46 +0100177# define XT_TRACE_DELAY 50 // delay for xterm tracing
Bram Moolenaar071d4272004-06-13 20:20:40 +0000178#endif
179
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +0100180static void handle_resize(void);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000181
182#if defined(SIGWINCH)
Bram Moolenaar99c48fe2022-06-05 22:05:19 +0100183static void sig_winch SIGPROTOARG;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000184#endif
dbivolaruab16ad32021-12-29 19:41:47 +0000185#if defined(SIGTSTP)
Bram Moolenaar99c48fe2022-06-05 22:05:19 +0100186static void sig_tstp SIGPROTOARG;
Bram Moolenaarabd56da2022-06-23 20:46:27 +0100187// volatile because it is used in signal handler sig_tstp() and
188// sigcont_handler().
dbivolaruab16ad32021-12-29 19:41:47 +0000189static volatile sig_atomic_t in_mch_suspend = FALSE;
190#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000191#if defined(SIGINT)
Bram Moolenaar99c48fe2022-06-05 22:05:19 +0100192static void catch_sigint SIGPROTOARG;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000193#endif
Bram Moolenaarbe5ee862020-06-10 20:56:58 +0200194#if defined(SIGUSR1)
Bram Moolenaar99c48fe2022-06-05 22:05:19 +0100195static void catch_sigusr1 SIGPROTOARG;
Bram Moolenaarbe5ee862020-06-10 20:56:58 +0200196#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000197#if defined(SIGPWR)
Bram Moolenaar99c48fe2022-06-05 22:05:19 +0100198static void catch_sigpwr SIGPROTOARG;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000199#endif
Bram Moolenaar651fca82021-11-29 20:39:38 +0000200#if defined(SIGALRM) && defined(FEAT_X11) && !defined(FEAT_GUI_GTK)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000201# define SET_SIG_ALARM
Bram Moolenaar99c48fe2022-06-05 22:05:19 +0100202static void sig_alarm SIGPROTOARG;
Bram Moolenaar0f873732019-12-05 20:28:46 +0100203// volatile because it is used in signal handler sig_alarm().
Bram Moolenaar8e82c052018-08-21 19:47:48 +0200204static volatile sig_atomic_t sig_alarm_called;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000205#endif
Bram Moolenaar99c48fe2022-06-05 22:05:19 +0100206static void deathtrap SIGPROTOARG;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000207
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +0100208static void catch_int_signal(void);
209static void set_signals(void);
Michael Jarvisbe9624e2023-04-19 20:28:48 +0100210static void catch_signals(void (*func_deadly)(int), void (*func_other)(int));
Bram Moolenaarbb09ceb2016-10-18 16:27:23 +0200211#ifdef HAVE_SIGPROCMASK
212# define SIGSET_DECL(set) sigset_t set;
213# define BLOCK_SIGNALS(set) block_signals(set)
214# define UNBLOCK_SIGNALS(set) unblock_signals(set)
215#else
216# define SIGSET_DECL(set)
217# define BLOCK_SIGNALS(set) do { /**/ } while (0)
218# define UNBLOCK_SIGNALS(set) do { /**/ } while (0)
219#endif
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +0100220static int have_wildcard(int, char_u **);
221static int have_dollars(int, char_u **);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000222
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +0100223static int save_patterns(int num_pat, char_u **pat, int *num_file, char_u ***file);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000224
225#ifndef SIG_ERR
ichizok378447f2023-05-11 22:25:42 +0100226# define SIG_ERR ((sighandler_T)-1)
227#endif
228#ifndef SIG_HOLD
229# define SIG_HOLD ((sighandler_T)-2)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000230#endif
231
Bram Moolenaar0f873732019-12-05 20:28:46 +0100232// volatile because it is used in signal handler sig_winch().
Bram Moolenaar8e82c052018-08-21 19:47:48 +0200233static volatile sig_atomic_t do_resize = FALSE;
dbivolaruab16ad32021-12-29 19:41:47 +0000234// volatile because it is used in signal handler sig_tstp().
235static volatile sig_atomic_t got_tstp = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000236static char_u *extra_shell_arg = NULL;
237static int show_shell_mess = TRUE;
Bram Moolenaar0f873732019-12-05 20:28:46 +0100238// volatile because it is used in signal handler deathtrap().
239static volatile sig_atomic_t deadly_signal = 0; // The signal we caught
240// volatile because it is used in signal handler deathtrap().
241static volatile sig_atomic_t in_mch_delay = FALSE; // sleeping in mch_delay()
Bram Moolenaar071d4272004-06-13 20:20:40 +0000242
Bram Moolenaarc4d4ac22016-11-07 22:42:57 +0100243#if defined(FEAT_JOB_CHANNEL) && !defined(USE_SYSTEM)
244static int dont_check_job_ended = 0;
245#endif
246
Bram Moolenaar26e86442020-05-17 14:06:16 +0200247// Current terminal mode from mch_settmode(). Can differ from cur_tmode.
248static tmode_T mch_cur_tmode = TMODE_COOK;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000249
250#ifdef USE_XSMP
251typedef struct
252{
Bram Moolenaar0f873732019-12-05 20:28:46 +0100253 SmcConn smcconn; // The SM connection ID
254 IceConn iceconn; // The ICE connection ID
255 char *clientid; // The client ID for the current smc session
256 Bool save_yourself; // If we're in the middle of a save_yourself
257 Bool shutdown; // If we're in shutdown mode
Bram Moolenaar071d4272004-06-13 20:20:40 +0000258} xsmp_config_T;
259
260static xsmp_config_T xsmp;
261#endif
262
263#ifdef SYS_SIGLIST_DECLARED
264/*
265 * I have seen
266 * extern char *_sys_siglist[NSIG];
Yegappan Lakshmananaebc6ef2022-08-27 21:24:26 +0100267 * on Linux, NetBSD and Solaris. It contains a nice list of strings
Bram Moolenaar071d4272004-06-13 20:20:40 +0000268 * that describe the signals. That is nearly what we want here. But
269 * autoconf does only check for sys_siglist (without the underscore), I
270 * do not want to change everything today.... jw.
Bram Moolenaar3f7d0902016-11-12 21:13:42 +0100271 * This is why AC_DECL_SYS_SIGLIST is commented out in configure.ac.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000272 */
273#endif
274
275static struct signalinfo
276{
Bram Moolenaar0f873732019-12-05 20:28:46 +0100277 int sig; // Signal number, eg. SIGSEGV etc
278 char *name; // Signal name (not char_u!).
279 char deadly; // Catch as a deadly signal?
Bram Moolenaar071d4272004-06-13 20:20:40 +0000280} signal_info[] =
281{
282#ifdef SIGHUP
283 {SIGHUP, "HUP", TRUE},
284#endif
285#ifdef SIGQUIT
286 {SIGQUIT, "QUIT", TRUE},
287#endif
288#ifdef SIGILL
289 {SIGILL, "ILL", TRUE},
290#endif
291#ifdef SIGTRAP
292 {SIGTRAP, "TRAP", TRUE},
293#endif
294#ifdef SIGABRT
295 {SIGABRT, "ABRT", TRUE},
296#endif
297#ifdef SIGEMT
298 {SIGEMT, "EMT", TRUE},
299#endif
300#ifdef SIGFPE
301 {SIGFPE, "FPE", TRUE},
302#endif
303#ifdef SIGBUS
304 {SIGBUS, "BUS", TRUE},
305#endif
Bram Moolenaar75676462013-01-30 14:55:42 +0100306#if defined(SIGSEGV) && !defined(FEAT_MZSCHEME)
Bram Moolenaar0f873732019-12-05 20:28:46 +0100307 // MzScheme uses SEGV in its garbage collector
Bram Moolenaar071d4272004-06-13 20:20:40 +0000308 {SIGSEGV, "SEGV", TRUE},
309#endif
310#ifdef SIGSYS
311 {SIGSYS, "SYS", TRUE},
312#endif
313#ifdef SIGALRM
Bram Moolenaar0f873732019-12-05 20:28:46 +0100314 {SIGALRM, "ALRM", FALSE}, // Perl's alarm() can trigger it
Bram Moolenaar071d4272004-06-13 20:20:40 +0000315#endif
316#ifdef SIGTERM
317 {SIGTERM, "TERM", TRUE},
318#endif
Bram Moolenaarb292a2a2011-02-09 18:47:40 +0100319#if defined(SIGVTALRM) && !defined(FEAT_RUBY)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000320 {SIGVTALRM, "VTALRM", TRUE},
321#endif
Bram Moolenaar02f07e02008-03-12 12:17:28 +0000322#if defined(SIGPROF) && !defined(FEAT_MZSCHEME) && !defined(WE_ARE_PROFILING)
Bram Moolenaar0f873732019-12-05 20:28:46 +0100323 // MzScheme uses SIGPROF for its own needs; On Linux with profiling
324 // this makes Vim exit. WE_ARE_PROFILING is defined in Makefile.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000325 {SIGPROF, "PROF", TRUE},
326#endif
327#ifdef SIGXCPU
328 {SIGXCPU, "XCPU", TRUE},
329#endif
330#ifdef SIGXFSZ
331 {SIGXFSZ, "XFSZ", TRUE},
332#endif
333#ifdef SIGUSR1
Bram Moolenaarbe5ee862020-06-10 20:56:58 +0200334 {SIGUSR1, "USR1", FALSE},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000335#endif
Bram Moolenaar3577c6f2008-06-24 21:16:56 +0000336#if defined(SIGUSR2) && !defined(FEAT_SYSMOUSE)
Bram Moolenaar0f873732019-12-05 20:28:46 +0100337 // Used for sysmouse handling
Bram Moolenaar071d4272004-06-13 20:20:40 +0000338 {SIGUSR2, "USR2", TRUE},
339#endif
340#ifdef SIGINT
341 {SIGINT, "INT", FALSE},
342#endif
343#ifdef SIGWINCH
344 {SIGWINCH, "WINCH", FALSE},
345#endif
346#ifdef SIGTSTP
347 {SIGTSTP, "TSTP", FALSE},
348#endif
349#ifdef SIGPIPE
350 {SIGPIPE, "PIPE", FALSE},
351#endif
352 {-1, "Unknown!", FALSE}
353};
354
ichizok378447f2023-05-11 22:25:42 +0100355 sighandler_T
356mch_signal(int sig, sighandler_T func)
357{
358#if defined(HAVE_SIGACTION) && defined(HAVE_SIGPROCMASK)
359 // Modern implementation: use sigaction().
360 struct sigaction sa, old;
361 sigset_t curset;
362 int blocked;
363
364 if (sigprocmask(SIG_BLOCK, NULL, &curset) == -1)
365 return SIG_ERR;
366
367 blocked = sigismember(&curset, sig);
368
369 if (func == SIG_HOLD)
370 {
371 if (blocked)
372 return SIG_HOLD;
373
374 sigemptyset(&curset);
375 sigaddset(&curset, sig);
376
377 if (sigaction(sig, NULL, &old) == -1
378 || sigprocmask(SIG_BLOCK, &curset, NULL) == -1)
379 return SIG_ERR;
380 return old.sa_handler;
381 }
382
383 if (blocked)
384 {
385 sigemptyset(&curset);
386 sigaddset(&curset, sig);
387
388 if (sigprocmask(SIG_UNBLOCK, &curset, NULL) == -1)
389 return SIG_ERR;
390 }
391
392 sa.sa_handler = func;
393 sigemptyset(&sa.sa_mask);
394# ifdef SA_RESTART
395 sa.sa_flags = SA_RESTART;
396# else
397 sa.sa_flags = 0;
398# endif
399 if (sigaction(sig, &sa, &old) == -1)
400 return SIG_ERR;
401 return blocked ? SIG_HOLD: old.sa_handler;
402#elif defined(HAVE_SIGSET)
403 // Using sigset() is preferred above signal().
404 return sigset(sig, func);
405#else
406 // Oldest and most compatible solution.
407 return signal(sig, func);
408#endif
409}
410
Bram Moolenaar25724922009-07-14 15:38:41 +0000411 int
Bram Moolenaar05540972016-01-30 20:31:25 +0100412mch_chdir(char *path)
Bram Moolenaar25724922009-07-14 15:38:41 +0000413{
414 if (p_verbose >= 5)
415 {
416 verbose_enter();
Bram Moolenaarf9e3e092019-01-13 23:38:42 +0100417 smsg("chdir(%s)", path);
Bram Moolenaar25724922009-07-14 15:38:41 +0000418 verbose_leave();
419 }
ichizok378447f2023-05-11 22:25:42 +0100420#ifdef VMS
Bram Moolenaar25724922009-07-14 15:38:41 +0000421 return chdir(vms_fixfilename(path));
ichizok378447f2023-05-11 22:25:42 +0100422#else
Bram Moolenaar25724922009-07-14 15:38:41 +0000423 return chdir(path);
ichizok378447f2023-05-11 22:25:42 +0100424#endif
Bram Moolenaar25724922009-07-14 15:38:41 +0000425}
426
Bram Moolenaar0f873732019-12-05 20:28:46 +0100427// Why is NeXT excluded here (and not in os_unixx.h)?
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +0100428#if defined(ECHOE) && defined(ICANON) \
429 && (defined(HAVE_TERMIO_H) || defined(HAVE_TERMIOS_H)) \
430 && !defined(__NeXT__)
Bram Moolenaar4f44b882017-08-13 20:06:18 +0200431# define NEW_TTY_SYSTEM
432#endif
433
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +0000434/*
Bram Moolenaard23a8232018-02-10 18:45:26 +0100435 * Write s[len] to the screen (stdout).
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +0000436 */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000437 void
Bram Moolenaar05540972016-01-30 20:31:25 +0100438mch_write(char_u *s, int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000439{
Bram Moolenaar42335f52018-09-13 15:33:43 +0200440 vim_ignored = (int)write(1, (char *)s, len);
Bram Moolenaar0f873732019-12-05 20:28:46 +0100441 if (p_wd) // Unix is too fast, slow down a bit more
Bram Moolenaar8fdd7212016-03-26 19:41:48 +0100442 RealWaitForChar(read_cmd_fd, p_wd, NULL, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000443}
444
445/*
Bram Moolenaare40b9d42019-01-27 16:55:47 +0100446 * Function passed to inchar_loop() to handle window resizing.
447 * If "check_only" is TRUE: Return whether there was a resize.
448 * If "check_only" is FALSE: Deal with the window resized.
449 */
450 static int
451resize_func(int check_only)
452{
453 if (check_only)
454 return do_resize;
455 while (do_resize)
Bram Moolenaar55f1b822023-06-21 13:42:48 +0100456 {
Bram Moolenaar545c8a52023-06-21 15:51:47 +0100457#ifdef FEAT_EVAL
Bram Moolenaar55f1b822023-06-21 13:42:48 +0100458 ch_log(NULL, "calling handle_resize() in resize_func()");
Bram Moolenaar545c8a52023-06-21 15:51:47 +0100459#endif
Bram Moolenaare40b9d42019-01-27 16:55:47 +0100460 handle_resize();
Bram Moolenaar55f1b822023-06-21 13:42:48 +0100461 }
Bram Moolenaare40b9d42019-01-27 16:55:47 +0100462 return FALSE;
463}
464
465/*
Bram Moolenaarc2a27c32007-12-01 16:19:33 +0000466 * mch_inchar(): low level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000467 * Get a characters from the keyboard.
468 * Return the number of characters that are available.
469 * If wtime == 0 do not wait for characters.
470 * If wtime == n wait a short time for characters.
471 * If wtime == -1 wait forever for characters.
472 */
473 int
Bram Moolenaar05540972016-01-30 20:31:25 +0100474mch_inchar(
475 char_u *buf,
476 int maxlen,
Bram Moolenaar0f873732019-12-05 20:28:46 +0100477 long wtime, // don't use "time", MIPS cannot handle it
Bram Moolenaar05540972016-01-30 20:31:25 +0100478 int tb_change_cnt)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000479{
Bram Moolenaare40b9d42019-01-27 16:55:47 +0100480 return inchar_loop(buf, maxlen, wtime, tb_change_cnt,
481 WaitForChar, resize_func);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000482}
483
484 static void
Bram Moolenaar05540972016-01-30 20:31:25 +0100485handle_resize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000486{
487 do_resize = FALSE;
488 shell_resized();
489}
490
491/*
Bram Moolenaar40b1b542016-04-20 20:18:23 +0200492 * Return non-zero if a character is available.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000493 */
494 int
Bram Moolenaar05540972016-01-30 20:31:25 +0100495mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000496{
Bram Moolenaare9c21ae2017-08-03 20:44:48 +0200497 return WaitForChar(0L, NULL, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000498}
499
Bram Moolenaare9c21ae2017-08-03 20:44:48 +0200500#if defined(FEAT_TERMINAL) || defined(PROTO)
501/*
502 * Check for any pending input or messages.
503 */
504 int
505mch_check_messages(void)
506{
507 return WaitForChar(0L, NULL, TRUE);
508}
509#endif
510
Bram Moolenaar071d4272004-06-13 20:20:40 +0000511#if defined(HAVE_TOTAL_MEM) || defined(PROTO)
512# ifdef HAVE_SYS_RESOURCE_H
Bram Moolenaar8f0b2d42009-05-16 14:41:10 +0000513# include <sys/resource.h>
Bram Moolenaar071d4272004-06-13 20:20:40 +0000514# endif
515# if defined(HAVE_SYS_SYSCTL_H) && defined(HAVE_SYSCTL)
516# include <sys/sysctl.h>
517# endif
518# if defined(HAVE_SYS_SYSINFO_H) && defined(HAVE_SYSINFO)
519# include <sys/sysinfo.h>
520# endif
Bram Moolenaar362dc332018-03-05 21:59:37 +0100521# ifdef MACOS_X
Bram Moolenaar988615f2018-02-27 17:58:20 +0100522# include <mach/mach_host.h>
523# include <mach/mach_port.h>
Bram Moolenaar988615f2018-02-27 17:58:20 +0100524# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000525
526/*
Bram Moolenaar914572a2007-05-01 11:37:47 +0000527 * Return total amount of memory available in Kbyte.
528 * Doesn't change when memory has been allocated.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000529 */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000530 long_u
Bram Moolenaar05540972016-01-30 20:31:25 +0100531mch_total_mem(int special UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000532{
Bram Moolenaar071d4272004-06-13 20:20:40 +0000533 long_u mem = 0;
Bram Moolenaar0f873732019-12-05 20:28:46 +0100534 long_u shiftright = 10; // how much to shift "mem" right for Kbyte
Bram Moolenaar071d4272004-06-13 20:20:40 +0000535
Bram Moolenaar362dc332018-03-05 21:59:37 +0100536# ifdef MACOS_X
Bram Moolenaar988615f2018-02-27 17:58:20 +0100537 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100538 // Mac (Darwin) way of getting the amount of RAM available
Bram Moolenaar988615f2018-02-27 17:58:20 +0100539 mach_port_t host = mach_host_self();
540 kern_return_t kret;
541# ifdef HOST_VM_INFO64
542 struct vm_statistics64 vm_stat;
543 natural_t count = HOST_VM_INFO64_COUNT;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000544
Bram Moolenaar988615f2018-02-27 17:58:20 +0100545 kret = host_statistics64(host, HOST_VM_INFO64,
546 (host_info64_t)&vm_stat, &count);
547# else
548 struct vm_statistics vm_stat;
549 natural_t count = HOST_VM_INFO_COUNT;
550
551 kret = host_statistics(host, HOST_VM_INFO,
552 (host_info_t)&vm_stat, &count);
553# endif
554 if (kret == KERN_SUCCESS)
Bram Moolenaar0f873732019-12-05 20:28:46 +0100555 // get the amount of user memory by summing each usage
Bram Moolenaar988615f2018-02-27 17:58:20 +0100556 mem = (long_u)(vm_stat.free_count + vm_stat.active_count
557 + vm_stat.inactive_count
558# ifdef MAC_OS_X_VERSION_10_9
559 + vm_stat.compressor_page_count
560# endif
Bram Moolenaar62b7f6a2018-03-22 21:44:07 +0100561 ) * sysconf(_SC_PAGESIZE);
Bram Moolenaar988615f2018-02-27 17:58:20 +0100562 mach_port_deallocate(mach_task_self(), host);
563 }
564# endif
565
566# ifdef HAVE_SYSCTL
567 if (mem == 0)
568 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100569 // BSD way of getting the amount of RAM available.
Bram Moolenaar988615f2018-02-27 17:58:20 +0100570 int mib[2];
571 size_t len = sizeof(long_u);
572# ifdef HW_USERMEM64
573 long_u physmem;
574# else
Bram Moolenaar0f873732019-12-05 20:28:46 +0100575 // sysctl() may return 32 bit or 64 bit, accept both
Bram Moolenaar988615f2018-02-27 17:58:20 +0100576 union {
577 int_u u32;
578 long_u u64;
579 } physmem;
580# endif
581
582 mib[0] = CTL_HW;
583# ifdef HW_USERMEM64
584 mib[1] = HW_USERMEM64;
585# else
586 mib[1] = HW_USERMEM;
587# endif
588 if (sysctl(mib, 2, &physmem, &len, NULL, 0) == 0)
589 {
590# ifdef HW_USERMEM64
591 mem = (long_u)physmem;
592# else
593 if (len == sizeof(physmem.u64))
594 mem = (long_u)physmem.u64;
595 else
596 mem = (long_u)physmem.u32;
597# endif
598 }
599 }
Bram Moolenaara06ecab2016-07-16 14:47:36 +0200600# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000601
Bram Moolenaara06ecab2016-07-16 14:47:36 +0200602# if defined(HAVE_SYS_SYSINFO_H) && defined(HAVE_SYSINFO)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000603 if (mem == 0)
604 {
605 struct sysinfo sinfo;
606
Bram Moolenaar0f873732019-12-05 20:28:46 +0100607 // Linux way of getting amount of RAM available
Bram Moolenaar071d4272004-06-13 20:20:40 +0000608 if (sysinfo(&sinfo) == 0)
Bram Moolenaar914572a2007-05-01 11:37:47 +0000609 {
Bram Moolenaara06ecab2016-07-16 14:47:36 +0200610# ifdef HAVE_SYSINFO_MEM_UNIT
Bram Moolenaar0f873732019-12-05 20:28:46 +0100611 // avoid overflow as much as possible
Bram Moolenaar914572a2007-05-01 11:37:47 +0000612 while (shiftright > 0 && (sinfo.mem_unit & 1) == 0)
613 {
614 sinfo.mem_unit = sinfo.mem_unit >> 1;
615 --shiftright;
616 }
617 mem = sinfo.totalram * sinfo.mem_unit;
Bram Moolenaara06ecab2016-07-16 14:47:36 +0200618# else
Bram Moolenaar071d4272004-06-13 20:20:40 +0000619 mem = sinfo.totalram;
Bram Moolenaara06ecab2016-07-16 14:47:36 +0200620# endif
Bram Moolenaar914572a2007-05-01 11:37:47 +0000621 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000622 }
Bram Moolenaara06ecab2016-07-16 14:47:36 +0200623# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000624
Bram Moolenaara06ecab2016-07-16 14:47:36 +0200625# ifdef HAVE_SYSCONF
Bram Moolenaar071d4272004-06-13 20:20:40 +0000626 if (mem == 0)
627 {
628 long pagesize, pagecount;
629
Bram Moolenaar0f873732019-12-05 20:28:46 +0100630 // Solaris way of getting amount of RAM available
Bram Moolenaar071d4272004-06-13 20:20:40 +0000631 pagesize = sysconf(_SC_PAGESIZE);
632 pagecount = sysconf(_SC_PHYS_PAGES);
633 if (pagesize > 0 && pagecount > 0)
Bram Moolenaar914572a2007-05-01 11:37:47 +0000634 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100635 // avoid overflow as much as possible
Bram Moolenaar914572a2007-05-01 11:37:47 +0000636 while (shiftright > 0 && (pagesize & 1) == 0)
637 {
Bram Moolenaar3d27a452007-05-10 17:44:18 +0000638 pagesize = (long_u)pagesize >> 1;
Bram Moolenaar914572a2007-05-01 11:37:47 +0000639 --shiftright;
640 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000641 mem = (long_u)pagesize * pagecount;
Bram Moolenaar914572a2007-05-01 11:37:47 +0000642 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000643 }
Bram Moolenaara06ecab2016-07-16 14:47:36 +0200644# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000645
Bram Moolenaar0f873732019-12-05 20:28:46 +0100646 // Return the minimum of the physical memory and the user limit, because
647 // using more than the user limit may cause Vim to be terminated.
Bram Moolenaara06ecab2016-07-16 14:47:36 +0200648# if defined(HAVE_SYS_RESOURCE_H) && defined(HAVE_GETRLIMIT)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000649 {
650 struct rlimit rlp;
651
652 if (getrlimit(RLIMIT_DATA, &rlp) == 0
653 && rlp.rlim_cur < ((rlim_t)1 << (sizeof(long_u) * 8 - 1))
Bram Moolenaara06ecab2016-07-16 14:47:36 +0200654# ifdef RLIM_INFINITY
Bram Moolenaar071d4272004-06-13 20:20:40 +0000655 && rlp.rlim_cur != RLIM_INFINITY
Bram Moolenaara06ecab2016-07-16 14:47:36 +0200656# endif
Bram Moolenaar914572a2007-05-01 11:37:47 +0000657 && ((long_u)rlp.rlim_cur >> 10) < (mem >> shiftright)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000658 )
Bram Moolenaar914572a2007-05-01 11:37:47 +0000659 {
660 mem = (long_u)rlp.rlim_cur;
661 shiftright = 10;
662 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000663 }
Bram Moolenaara06ecab2016-07-16 14:47:36 +0200664# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000665
666 if (mem > 0)
Bram Moolenaar914572a2007-05-01 11:37:47 +0000667 return mem >> shiftright;
668 return (long_u)0x1fffff;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000669}
670#endif
671
Bram Moolenaar0981c872020-08-23 14:28:37 +0200672/*
673 * "flags": MCH_DELAY_IGNOREINPUT - don't read input
674 * MCH_DELAY_SETTMODE - use settmode() even for short delays
675 */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000676 void
Bram Moolenaar0981c872020-08-23 14:28:37 +0200677mch_delay(long msec, int flags)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000678{
Bram Moolenaar26e86442020-05-17 14:06:16 +0200679 tmode_T old_tmode;
Bram Moolenaar80361a52020-10-05 21:39:25 +0200680 int call_settmode;
Bram Moolenaar325b7a22004-07-05 15:58:32 +0000681#ifdef FEAT_MZSCHEME
Bram Moolenaar0f873732019-12-05 20:28:46 +0100682 long total = msec; // remember original value
Bram Moolenaar325b7a22004-07-05 15:58:32 +0000683#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000684
Bram Moolenaar0981c872020-08-23 14:28:37 +0200685 if (flags & MCH_DELAY_IGNOREINPUT)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000686 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100687 // Go to cooked mode without echo, to allow SIGINT interrupting us
688 // here. But we don't want QUIT to kill us (CTRL-\ used in a
689 // shell may produce SIGQUIT).
Bram Moolenaar26e86442020-05-17 14:06:16 +0200690 // Only do this if sleeping for more than half a second.
Bram Moolenaarae0f2ca2008-02-10 21:25:55 +0000691 in_mch_delay = TRUE;
Bram Moolenaar80361a52020-10-05 21:39:25 +0200692 call_settmode = mch_cur_tmode == TMODE_RAW
693 && (msec > 500 || (flags & MCH_DELAY_SETTMODE));
694 if (call_settmode)
695 {
696 old_tmode = mch_cur_tmode;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000697 settmode(TMODE_SLEEP);
Bram Moolenaar80361a52020-10-05 21:39:25 +0200698 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000699
700 /*
701 * Everybody sleeps in a different way...
702 * Prefer nanosleep(), some versions of usleep() can only sleep up to
703 * one second.
704 */
Bram Moolenaar325b7a22004-07-05 15:58:32 +0000705#ifdef FEAT_MZSCHEME
706 do
707 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100708 // if total is large enough, wait by portions in p_mzq
Bram Moolenaar325b7a22004-07-05 15:58:32 +0000709 if (total > p_mzq)
710 msec = p_mzq;
711 else
712 msec = total;
713 total -= msec;
714#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000715#ifdef HAVE_NANOSLEEP
716 {
717 struct timespec ts;
718
719 ts.tv_sec = msec / 1000;
720 ts.tv_nsec = (msec % 1000) * 1000000;
721 (void)nanosleep(&ts, NULL);
722 }
723#else
724# ifdef HAVE_USLEEP
725 while (msec >= 1000)
726 {
727 usleep((unsigned int)(999 * 1000));
728 msec -= 999;
729 }
730 usleep((unsigned int)(msec * 1000));
731# else
732# ifndef HAVE_SELECT
733 poll(NULL, 0, (int)msec);
734# else
Bram Moolenaar071d4272004-06-13 20:20:40 +0000735 {
736 struct timeval tv;
737
738 tv.tv_sec = msec / 1000;
739 tv.tv_usec = (msec % 1000) * 1000;
Bram Moolenaar0981c872020-08-23 14:28:37 +0200740 // NOTE: Solaris 2.6 has a bug that makes select() hang here. Get
741 // a patch from Sun to fix this. Reported by Gunnar Pedersen.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000742 select(0, NULL, NULL, NULL, &tv);
743 }
Michael Jarvisbe9624e2023-04-19 20:28:48 +0100744# endif
745# endif
746#endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +0000747#ifdef FEAT_MZSCHEME
748 }
749 while (total > 0);
750#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000751
Bram Moolenaar80361a52020-10-05 21:39:25 +0200752 if (call_settmode)
Bram Moolenaar26e86442020-05-17 14:06:16 +0200753 settmode(old_tmode);
Bram Moolenaarae0f2ca2008-02-10 21:25:55 +0000754 in_mch_delay = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000755 }
756 else
Bram Moolenaare9c21ae2017-08-03 20:44:48 +0200757 WaitForChar(msec, NULL, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000758}
759
Bram Moolenaarbc7aa852005-03-06 23:38:09 +0000760#if defined(HAVE_STACK_LIMIT) \
Bram Moolenaar071d4272004-06-13 20:20:40 +0000761 || (!defined(HAVE_SIGALTSTACK) && defined(HAVE_SIGSTACK))
762# define HAVE_CHECK_STACK_GROWTH
763/*
764 * Support for checking for an almost-out-of-stack-space situation.
765 */
766
767/*
768 * Return a pointer to an item on the stack. Used to find out if the stack
769 * grows up or down.
770 */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000771static int stack_grows_downwards;
772
773/*
774 * Find out if the stack grows upwards or downwards.
775 * "p" points to a variable on the stack of the caller.
776 */
777 static void
Bram Moolenaar05540972016-01-30 20:31:25 +0100778check_stack_growth(char *p)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000779{
780 int i;
781
782 stack_grows_downwards = (p > (char *)&i);
783}
784#endif
785
Bram Moolenaarbc7aa852005-03-06 23:38:09 +0000786#if defined(HAVE_STACK_LIMIT) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000787static char *stack_limit = NULL;
788
789#if defined(_THREAD_SAFE) && defined(HAVE_PTHREAD_NP_H)
790# include <pthread.h>
791# include <pthread_np.h>
792#endif
793
794/*
795 * Find out until how var the stack can grow without getting into trouble.
796 * Called when starting up and when switching to the signal stack in
797 * deathtrap().
798 */
799 static void
Bram Moolenaar05540972016-01-30 20:31:25 +0100800get_stack_limit(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000801{
802 struct rlimit rlp;
803 int i;
804 long lim;
805
Bram Moolenaar0f873732019-12-05 20:28:46 +0100806 // Set the stack limit to 15/16 of the allowable size. Skip this when the
807 // limit doesn't fit in a long (rlim_cur might be "long long").
Bram Moolenaar071d4272004-06-13 20:20:40 +0000808 if (getrlimit(RLIMIT_STACK, &rlp) == 0
809 && rlp.rlim_cur < ((rlim_t)1 << (sizeof(long_u) * 8 - 1))
810# ifdef RLIM_INFINITY
811 && rlp.rlim_cur != RLIM_INFINITY
812# endif
813 )
814 {
815 lim = (long)rlp.rlim_cur;
816#if defined(_THREAD_SAFE) && defined(HAVE_PTHREAD_NP_H)
817 {
818 pthread_attr_t attr;
819 size_t size;
820
Bram Moolenaar0f873732019-12-05 20:28:46 +0100821 // On FreeBSD the initial thread always has a fixed stack size, no
822 // matter what the limits are set to. Normally it's 1 Mbyte.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000823 pthread_attr_init(&attr);
824 if (pthread_attr_get_np(pthread_self(), &attr) == 0)
825 {
826 pthread_attr_getstacksize(&attr, &size);
827 if (lim > (long)size)
828 lim = (long)size;
829 }
830 pthread_attr_destroy(&attr);
831 }
832#endif
833 if (stack_grows_downwards)
834 {
835 stack_limit = (char *)((long)&i - (lim / 16L * 15L));
836 if (stack_limit >= (char *)&i)
Bram Moolenaar0f873732019-12-05 20:28:46 +0100837 // overflow, set to 1/16 of current stack position
Bram Moolenaar071d4272004-06-13 20:20:40 +0000838 stack_limit = (char *)((long)&i / 16L);
839 }
840 else
841 {
842 stack_limit = (char *)((long)&i + (lim / 16L * 15L));
843 if (stack_limit <= (char *)&i)
Bram Moolenaar0f873732019-12-05 20:28:46 +0100844 stack_limit = NULL; // overflow
Bram Moolenaar071d4272004-06-13 20:20:40 +0000845 }
846 }
847}
848
849/*
850 * Return FAIL when running out of stack space.
851 * "p" must point to any variable local to the caller that's on the stack.
852 */
853 int
Bram Moolenaar05540972016-01-30 20:31:25 +0100854mch_stackcheck(char *p)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000855{
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000856 if (stack_limit == NULL)
857 return OK;
858
859 if (stack_grows_downwards)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000860 {
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000861 if (p < stack_limit)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000862 return FAIL;
863 }
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000864 else if (p > stack_limit)
865 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000866 return OK;
867}
868#endif
869
870#if defined(HAVE_SIGALTSTACK) || defined(HAVE_SIGSTACK)
871/*
872 * Support for using the signal stack.
873 * This helps when we run out of stack space, which causes a SIGSEGV. The
874 * signal handler then must run on another stack, since the normal stack is
875 * completely full.
876 */
877
Bram Moolenaar071d4272004-06-13 20:20:40 +0000878# ifdef HAVE_SIGALTSTACK
Bram Moolenaar0f873732019-12-05 20:28:46 +0100879static stack_t sigstk; // for sigaltstack()
Bram Moolenaar071d4272004-06-13 20:20:40 +0000880# else
Bram Moolenaar0f873732019-12-05 20:28:46 +0100881static struct sigstack sigstk; // for sigstack()
Bram Moolenaar071d4272004-06-13 20:20:40 +0000882# endif
883
Zdenek Dohnalba9c23e2021-08-11 14:20:05 +0200884/*
885 * Get a size of signal stack.
886 * Preference (if available): sysconf > SIGSTKSZ > guessed size
887 */
Michael Jarvisbe9624e2023-04-19 20:28:48 +0100888static long int get_signal_stack_size(void)
Zdenek Dohnalba9c23e2021-08-11 14:20:05 +0200889{
890# ifdef HAVE_SYSCONF_SIGSTKSZ
891 long int size = -1;
892
893 // return size only if sysconf doesn't return an error
894 if ((size = sysconf(_SC_SIGSTKSZ)) > -1)
895 return size;
896# endif
897
898# ifdef SIGSTKSZ
899 // if sysconf() isn't available or gives error, return SIGSTKSZ
900 // if defined
901 return SIGSTKSZ;
902# endif
903
904 // otherwise guess the size
905 return 8000;
906}
907
Bram Moolenaar071d4272004-06-13 20:20:40 +0000908static char *signal_stack;
909
910 static void
Bram Moolenaar05540972016-01-30 20:31:25 +0100911init_signal_stack(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000912{
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000913 if (signal_stack == NULL)
914 return;
915
Bram Moolenaar071d4272004-06-13 20:20:40 +0000916# ifdef HAVE_SIGALTSTACK
Bram Moolenaar071d4272004-06-13 20:20:40 +0000917# ifdef HAVE_SS_BASE
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000918 sigstk.ss_base = signal_stack;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000919# else
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000920 sigstk.ss_sp = signal_stack;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000921# endif
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000922 sigstk.ss_size = get_signal_stack_size();
923 sigstk.ss_flags = 0;
924 (void)sigaltstack(&sigstk, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000925# else
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +0000926 sigstk.ss_sp = signal_stack;
927 if (stack_grows_downwards)
928 sigstk.ss_sp += get_signal_stack_size() - 1;
929 sigstk.ss_onstack = 0;
930 (void)sigstack(&sigstk, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000931# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000932}
933#endif
934
935/*
Bram Moolenaar76243bd2009-03-02 01:47:02 +0000936 * We need correct prototypes for a signal function, otherwise mean compilers
Bram Moolenaar071d4272004-06-13 20:20:40 +0000937 * will barf when the second argument to signal() is ``wrong''.
938 * Let me try it with a few tricky defines from my own osdef.h (jw).
939 */
940#if defined(SIGWINCH)
Bram Moolenaar99c48fe2022-06-05 22:05:19 +0100941 static void
Bram Moolenaar071d4272004-06-13 20:20:40 +0000942sig_winch SIGDEFARG(sigarg)
943{
Bram Moolenaar0f873732019-12-05 20:28:46 +0100944 // this is not required on all systems, but it doesn't hurt anybody
ichizok378447f2023-05-11 22:25:42 +0100945 mch_signal(SIGWINCH, sig_winch);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000946 do_resize = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000947}
948#endif
949
dbivolaruab16ad32021-12-29 19:41:47 +0000950#if defined(SIGTSTP)
Bram Moolenaar99c48fe2022-06-05 22:05:19 +0100951 static void
dbivolaruab16ad32021-12-29 19:41:47 +0000952sig_tstp SIGDEFARG(sigarg)
953{
954 // Second time we get called we actually need to suspend
955 if (in_mch_suspend)
956 {
ichizok378447f2023-05-11 22:25:42 +0100957 mch_signal(SIGTSTP, ignore_sigtstp ? SIG_IGN : SIG_DFL);
dbivolaruab16ad32021-12-29 19:41:47 +0000958 raise(sigarg);
959 }
dbivolaru79a6e252022-01-23 16:41:14 +0000960 else
961 got_tstp = TRUE;
dbivolaruab16ad32021-12-29 19:41:47 +0000962
ichizok5f823d12022-03-13 17:27:38 +0000963#if !defined(__ANDROID__) && !defined(__OpenBSD__) && !defined(__DragonFly__)
964 // This is not required on all systems. On some systems (at least Android,
965 // OpenBSD, and DragonFlyBSD) this breaks suspending with CTRL-Z.
ichizok378447f2023-05-11 22:25:42 +0100966 mch_signal(SIGTSTP, sig_tstp);
xtkobacbef12e2022-02-27 12:31:52 +0000967#endif
dbivolaruab16ad32021-12-29 19:41:47 +0000968}
969#endif
970
Bram Moolenaar071d4272004-06-13 20:20:40 +0000971#if defined(SIGINT)
Bram Moolenaar99c48fe2022-06-05 22:05:19 +0100972 static void
Bram Moolenaar071d4272004-06-13 20:20:40 +0000973catch_sigint SIGDEFARG(sigarg)
974{
Bram Moolenaar0f873732019-12-05 20:28:46 +0100975 // this is not required on all systems, but it doesn't hurt anybody
ichizok378447f2023-05-11 22:25:42 +0100976 mch_signal(SIGINT, catch_sigint);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000977 got_int = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000978}
979#endif
980
Bram Moolenaarbe5ee862020-06-10 20:56:58 +0200981#if defined(SIGUSR1)
Bram Moolenaar99c48fe2022-06-05 22:05:19 +0100982 static void
Bram Moolenaarbe5ee862020-06-10 20:56:58 +0200983catch_sigusr1 SIGDEFARG(sigarg)
984{
985 // this is not required on all systems, but it doesn't hurt anybody
ichizok378447f2023-05-11 22:25:42 +0100986 mch_signal(SIGUSR1, catch_sigusr1);
Bram Moolenaarbe5ee862020-06-10 20:56:58 +0200987 got_sigusr1 = TRUE;
Bram Moolenaarbe5ee862020-06-10 20:56:58 +0200988}
989#endif
990
Bram Moolenaar071d4272004-06-13 20:20:40 +0000991#if defined(SIGPWR)
Bram Moolenaar99c48fe2022-06-05 22:05:19 +0100992 static void
Bram Moolenaar071d4272004-06-13 20:20:40 +0000993catch_sigpwr SIGDEFARG(sigarg)
994{
Bram Moolenaar0f873732019-12-05 20:28:46 +0100995 // this is not required on all systems, but it doesn't hurt anybody
ichizok378447f2023-05-11 22:25:42 +0100996 mch_signal(SIGPWR, catch_sigpwr);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000997 /*
998 * I'm not sure we get the SIGPWR signal when the system is really going
999 * down or when the batteries are almost empty. Just preserve the swap
1000 * files and don't exit, that can't do any harm.
1001 */
1002 ml_sync_all(FALSE, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001003}
1004#endif
1005
1006#ifdef SET_SIG_ALARM
1007/*
1008 * signal function for alarm().
1009 */
Bram Moolenaar99c48fe2022-06-05 22:05:19 +01001010 static void
Bram Moolenaar071d4272004-06-13 20:20:40 +00001011sig_alarm SIGDEFARG(sigarg)
1012{
Bram Moolenaar0f873732019-12-05 20:28:46 +01001013 // doesn't do anything, just to break a system call
Bram Moolenaar071d4272004-06-13 20:20:40 +00001014 sig_alarm_called = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001015}
1016#endif
1017
Bram Moolenaaredce7422019-01-20 18:39:30 +01001018#if (defined(HAVE_SETJMP_H) \
1019 && ((defined(FEAT_X11) && defined(FEAT_XCLIPBOARD)) \
1020 || defined(FEAT_LIBCALL))) \
1021 || defined(PROTO)
Bram Moolenaarb2148f52019-01-20 23:43:57 +01001022# define USING_SETJMP 1
Bram Moolenaaredce7422019-01-20 18:39:30 +01001023
Bram Moolenaarb7a7e032018-12-28 17:01:59 +01001024// argument to SETJMP()
1025static JMP_BUF lc_jump_env;
1026
1027# ifdef SIGHASARG
Bram Moolenaar32aa1022019-11-02 22:54:41 +01001028// Caught signal number, 0 when no signal was caught; used for mch_libcall().
Bram Moolenaarb7a7e032018-12-28 17:01:59 +01001029// Volatile because it is used in signal handlers.
1030static volatile sig_atomic_t lc_signal;
1031# endif
1032
1033// TRUE when lc_jump_env is valid.
1034// Volatile because it is used in signal handler deathtrap().
zeertzjq9b7d2a92022-08-26 10:33:54 +01001035static volatile sig_atomic_t lc_active = FALSE;
Bram Moolenaarb7a7e032018-12-28 17:01:59 +01001036
Bram Moolenaar071d4272004-06-13 20:20:40 +00001037/*
1038 * A simplistic version of setjmp() that only allows one level of using.
Bram Moolenaarb7a7e032018-12-28 17:01:59 +01001039 * Used to protect areas where we could crash.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001040 * Don't call twice before calling mch_endjmp()!.
Bram Moolenaarb7a7e032018-12-28 17:01:59 +01001041 *
Bram Moolenaar071d4272004-06-13 20:20:40 +00001042 * Usage:
1043 * mch_startjmp();
1044 * if (SETJMP(lc_jump_env) != 0)
1045 * {
1046 * mch_didjmp();
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01001047 * emsg("crash!");
Bram Moolenaar071d4272004-06-13 20:20:40 +00001048 * }
1049 * else
1050 * {
1051 * do_the_work;
1052 * mch_endjmp();
1053 * }
1054 * Note: Can't move SETJMP() here, because a function calling setjmp() must
1055 * not return before the saved environment is used.
1056 * Returns OK for normal return, FAIL when the protected code caused a
1057 * problem and LONGJMP() was used.
1058 */
Bram Moolenaar113e1072019-01-20 15:30:40 +01001059 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01001060mch_startjmp(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001061{
Bram Moolenaarb2148f52019-01-20 23:43:57 +01001062# ifdef SIGHASARG
Bram Moolenaar071d4272004-06-13 20:20:40 +00001063 lc_signal = 0;
Bram Moolenaarb2148f52019-01-20 23:43:57 +01001064# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001065 lc_active = TRUE;
1066}
1067
Bram Moolenaar113e1072019-01-20 15:30:40 +01001068 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01001069mch_endjmp(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001070{
1071 lc_active = FALSE;
1072}
1073
Bram Moolenaar113e1072019-01-20 15:30:40 +01001074 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01001075mch_didjmp(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001076{
1077# if defined(HAVE_SIGALTSTACK) || defined(HAVE_SIGSTACK)
Bram Moolenaarb7a7e032018-12-28 17:01:59 +01001078 // On FreeBSD the signal stack has to be reset after using siglongjmp(),
1079 // otherwise catching the signal only works once.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001080 init_signal_stack();
1081# endif
1082}
1083#endif
1084
1085/*
1086 * This function handles deadly signals.
Bram Moolenaarbec9c202013-09-05 21:41:39 +02001087 * It tries to preserve any swap files and exit properly.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001088 * (partly from Elvis).
Bram Moolenaarbec9c202013-09-05 21:41:39 +02001089 * NOTE: Avoid unsafe functions, such as allocating memory, they can result in
1090 * a deadlock.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001091 */
Bram Moolenaar99c48fe2022-06-05 22:05:19 +01001092 static void
Bram Moolenaar071d4272004-06-13 20:20:40 +00001093deathtrap SIGDEFARG(sigarg)
1094{
Bram Moolenaar0f873732019-12-05 20:28:46 +01001095 static int entered = 0; // count the number of times we got here.
1096 // Note: when memory has been corrupted
1097 // this may get an arbitrary value!
Bram Moolenaar071d4272004-06-13 20:20:40 +00001098#ifdef SIGHASARG
1099 int i;
1100#endif
1101
Bram Moolenaarb2148f52019-01-20 23:43:57 +01001102#if defined(USING_SETJMP)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001103 /*
1104 * Catch a crash in protected code.
1105 * Restores the environment saved in lc_jump_env, which looks like
1106 * SETJMP() returns 1.
1107 */
1108 if (lc_active)
1109 {
1110# if defined(SIGHASARG)
1111 lc_signal = sigarg;
1112# endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01001113 lc_active = FALSE; // don't jump again
Bram Moolenaar071d4272004-06-13 20:20:40 +00001114 LONGJMP(lc_jump_env, 1);
Bram Moolenaar0f873732019-12-05 20:28:46 +01001115 // NOTREACHED
Bram Moolenaar071d4272004-06-13 20:20:40 +00001116 }
1117#endif
1118
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001119#ifdef SIGHASARG
Bram Moolenaarae0f2ca2008-02-10 21:25:55 +00001120# ifdef SIGQUIT
Bram Moolenaar0f873732019-12-05 20:28:46 +01001121 // While in mch_delay() we go to cooked mode to allow a CTRL-C to
1122 // interrupt us. But in cooked mode we may also get SIGQUIT, e.g., when
1123 // pressing CTRL-\, but we don't want Vim to exit then.
Bram Moolenaarae0f2ca2008-02-10 21:25:55 +00001124 if (in_mch_delay && sigarg == SIGQUIT)
Bram Moolenaar99c48fe2022-06-05 22:05:19 +01001125 return;
Bram Moolenaarae0f2ca2008-02-10 21:25:55 +00001126# endif
1127
Bram Moolenaar0f873732019-12-05 20:28:46 +01001128 // When SIGHUP, SIGQUIT, etc. are blocked: postpone the effect and return
1129 // here. This avoids that a non-reentrant function is interrupted, e.g.,
1130 // free(). Calling free() again may then cause a crash.
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001131 if (entered == 0
1132 && (0
1133# ifdef SIGHUP
1134 || sigarg == SIGHUP
1135# endif
1136# ifdef SIGQUIT
1137 || sigarg == SIGQUIT
1138# endif
1139# ifdef SIGTERM
1140 || sigarg == SIGTERM
1141# endif
1142# ifdef SIGPWR
1143 || sigarg == SIGPWR
1144# endif
1145# ifdef SIGUSR1
1146 || sigarg == SIGUSR1
1147# endif
1148# ifdef SIGUSR2
1149 || sigarg == SIGUSR2
1150# endif
1151 )
Bram Moolenaar1f28b072005-07-12 22:42:41 +00001152 && !vim_handle_signal(sigarg))
Bram Moolenaar99c48fe2022-06-05 22:05:19 +01001153 return;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001154#endif
1155
Bram Moolenaar0f873732019-12-05 20:28:46 +01001156 // Remember how often we have been called.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001157 ++entered;
1158
Bram Moolenaar0f873732019-12-05 20:28:46 +01001159 // Executing autocommands is likely to use more stack space than we have
1160 // available in the signal stack.
Bram Moolenaare429e702016-06-10 19:49:14 +02001161 block_autocmds();
Bram Moolenaare429e702016-06-10 19:49:14 +02001162
Bram Moolenaar071d4272004-06-13 20:20:40 +00001163#ifdef FEAT_EVAL
Bram Moolenaar0f873732019-12-05 20:28:46 +01001164 // Set the v:dying variable.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001165 set_vim_var_nr(VV_DYING, (long)entered);
1166#endif
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01001167 v_dying = entered;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001168
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00001169#ifdef HAVE_STACK_LIMIT
Bram Moolenaar0f873732019-12-05 20:28:46 +01001170 // Since we are now using the signal stack, need to reset the stack
1171 // limit. Otherwise using a regexp will fail.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001172 get_stack_limit();
1173#endif
1174
Bram Moolenaar1f4d4de2006-03-14 23:00:46 +00001175#if 0
Bram Moolenaar0f873732019-12-05 20:28:46 +01001176 // This is for opening gdb the moment Vim crashes.
1177 // You need to manually adjust the file name and Vim executable name.
1178 // Suggested by SungHyun Nam.
Bram Moolenaar1f4d4de2006-03-14 23:00:46 +00001179 {
1180# define VI_GDB_FILE "/tmp/vimgdb"
1181# define VIM_NAME "/usr/bin/vim"
1182 FILE *fp = fopen(VI_GDB_FILE, "w");
1183 if (fp)
1184 {
1185 fprintf(fp,
1186 "file %s\n"
1187 "attach %d\n"
1188 "set height 1000\n"
1189 "bt full\n"
1190 , VIM_NAME, getpid());
1191 fclose(fp);
1192 system("xterm -e gdb -x "VI_GDB_FILE);
1193 unlink(VI_GDB_FILE);
1194 }
1195 }
1196#endif
1197
Bram Moolenaar071d4272004-06-13 20:20:40 +00001198#ifdef SIGHASARG
Bram Moolenaar0f873732019-12-05 20:28:46 +01001199 // try to find the name of this signal
Bram Moolenaar071d4272004-06-13 20:20:40 +00001200 for (i = 0; signal_info[i].sig != -1; i++)
1201 if (sigarg == signal_info[i].sig)
1202 break;
1203 deadly_signal = sigarg;
1204#endif
1205
Bram Moolenaar0f873732019-12-05 20:28:46 +01001206 full_screen = FALSE; // don't write message to the GUI, it might be
1207 // part of the problem...
Bram Moolenaar071d4272004-06-13 20:20:40 +00001208 /*
1209 * If something goes wrong after entering here, we may get here again.
1210 * When this happens, give a message and try to exit nicely (resetting the
1211 * terminal mode, etc.)
1212 * When this happens twice, just exit, don't even try to give a message,
1213 * stack may be corrupt or something weird.
1214 * When this still happens again (or memory was corrupted in such a way
1215 * that "entered" was clobbered) use _exit(), don't try freeing resources.
1216 */
1217 if (entered >= 3)
1218 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001219 reset_signals(); // don't catch any signals anymore
Bram Moolenaar071d4272004-06-13 20:20:40 +00001220 may_core_dump();
1221 if (entered >= 4)
1222 _exit(8);
1223 exit(7);
1224 }
1225 if (entered == 2)
1226 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001227 // No translation, it may call malloc().
Bram Moolenaarbec9c202013-09-05 21:41:39 +02001228 OUT_STR("Vim: Double signal, exiting\n");
Bram Moolenaar071d4272004-06-13 20:20:40 +00001229 out_flush();
1230 getout(1);
1231 }
1232
Bram Moolenaar0f873732019-12-05 20:28:46 +01001233 // No translation, it may call malloc().
Bram Moolenaar071d4272004-06-13 20:20:40 +00001234#ifdef SIGHASARG
Bram Moolenaar69212b12020-05-10 14:14:03 +02001235 sprintf((char *)IObuff, "Vim: Caught deadly signal %s\r\n",
Bram Moolenaar071d4272004-06-13 20:20:40 +00001236 signal_info[i].name);
1237#else
Bram Moolenaar69212b12020-05-10 14:14:03 +02001238 sprintf((char *)IObuff, "Vim: Caught deadly signal\r\n");
Bram Moolenaar071d4272004-06-13 20:20:40 +00001239#endif
Bram Moolenaarbec9c202013-09-05 21:41:39 +02001240
Bram Moolenaar0f873732019-12-05 20:28:46 +01001241 // Preserve files and exit. This sets the really_exiting flag to prevent
1242 // calling free().
Bram Moolenaarbec9c202013-09-05 21:41:39 +02001243 preserve_exit();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001244
Bram Moolenaar0f873732019-12-05 20:28:46 +01001245 // NOTREACHED
Bram Moolenaare429e702016-06-10 19:49:14 +02001246
Bram Moolenaar009b2592004-10-24 19:18:58 +00001247#ifdef NBDEBUG
1248 reset_signals();
1249 may_core_dump();
1250 abort();
1251#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001252}
1253
Bram Moolenaar071d4272004-06-13 20:20:40 +00001254/*
Bram Moolenaar2e310482018-08-21 13:09:10 +02001255 * Invoked after receiving SIGCONT. We don't know what happened while
1256 * sleeping, deal with part of that.
1257 */
1258 static void
1259after_sigcont(void)
1260{
Bram Moolenaar2e310482018-08-21 13:09:10 +02001261 // Don't change "oldtitle" in a signal handler, set a flag to obtain it
1262 // again later.
1263 oldtitle_outdated = TRUE;
Bram Moolenaar651fca82021-11-29 20:39:38 +00001264
Bram Moolenaar2e310482018-08-21 13:09:10 +02001265 settmode(TMODE_RAW);
1266 need_check_timestamps = TRUE;
1267 did_check_timestamps = FALSE;
1268}
1269
1270#if defined(SIGCONT)
Bram Moolenaar99c48fe2022-06-05 22:05:19 +01001271static void sigcont_handler SIGPROTOARG;
Bram Moolenaar2e310482018-08-21 13:09:10 +02001272
1273/*
1274 * With multi-threading, suspending might not work immediately. Catch the
1275 * SIGCONT signal, which will be used as an indication whether the suspending
1276 * has been done or not.
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001277 *
1278 * On Linux, signal is not always handled immediately either.
1279 * See https://bugs.launchpad.net/bugs/291373
Bram Moolenaar2e310482018-08-21 13:09:10 +02001280 * Probably because the signal is handled in another thread.
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001281 *
Bram Moolenaarb292a2a2011-02-09 18:47:40 +01001282 * volatile because it is used in signal handler sigcont_handler().
Bram Moolenaar071d4272004-06-13 20:20:40 +00001283 */
Bram Moolenaar8e82c052018-08-21 19:47:48 +02001284static volatile sig_atomic_t sigcont_received;
Bram Moolenaar99c48fe2022-06-05 22:05:19 +01001285static void sigcont_handler SIGPROTOARG;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001286
1287/*
1288 * signal handler for SIGCONT
1289 */
Bram Moolenaar99c48fe2022-06-05 22:05:19 +01001290 static void
Bram Moolenaar071d4272004-06-13 20:20:40 +00001291sigcont_handler SIGDEFARG(sigarg)
1292{
Bram Moolenaar2e310482018-08-21 13:09:10 +02001293 if (in_mch_suspend)
1294 {
1295 sigcont_received = TRUE;
1296 }
1297 else
1298 {
1299 // We didn't suspend ourselves, assume we were stopped by a SIGSTOP
1300 // signal (which can't be intercepted) and get a SIGCONT. Need to get
1301 // back to a sane mode. We should redraw, but we can't really do that
1302 // in a signal handler, do a redraw later.
1303 after_sigcont();
Bram Moolenaara4d158b2022-08-14 14:17:45 +01001304 redraw_later(UPD_CLEAR);
Bram Moolenaar2e310482018-08-21 13:09:10 +02001305 cursor_on_force();
1306 out_flush();
1307 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001308}
1309#endif
1310
Foxe Chenb90c2392025-06-27 21:10:35 +02001311#if defined(FEAT_CLIPBOARD)
1312# if defined(USE_SYSTEM) && (defined(FEAT_X11) \
1313 || defined(FEAT_WAYLAND_CLIPBOARD))
Bram Moolenaar1a0316c2013-03-13 17:50:25 +01001314static void *clip_star_save = NULL;
1315static void *clip_plus_save = NULL;
Bram Moolenaar090cfc12013-03-19 12:35:42 +01001316# endif
Bram Moolenaar62b42182010-09-21 22:09:37 +02001317
Foxe Chenb90c2392025-06-27 21:10:35 +02001318# if defined(FEAT_CLIPBOARD) && (defined(FEAT_X11) \
1319 || defined(FEAT_WAYLAND_CLIPBOARD))
Bram Moolenaar62b42182010-09-21 22:09:37 +02001320/*
1321 * Called when Vim is going to sleep or execute a shell command.
Hirohito Higashi73b96502025-06-28 18:18:21 +02001322 * We can't respond to requests for the X or Wayland selections.
Foxe Chenb90c2392025-06-27 21:10:35 +02001323 * Lose them, otherwise other applications will hang. But first
1324 * copy the text to cut buffer 0 (for X11). Wayland users must have
1325 * a clipboard manager to replicate such behaviour.
Bram Moolenaar62b42182010-09-21 22:09:37 +02001326 */
1327 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01001328loose_clipboard(void)
Bram Moolenaar62b42182010-09-21 22:09:37 +02001329{
1330 if (clip_star.owned || clip_plus.owned)
1331 {
Foxe Chenb90c2392025-06-27 21:10:35 +02001332#ifdef FEAT_X11
Bram Moolenaar62b42182010-09-21 22:09:37 +02001333 x11_export_final_selection();
Foxe Chenb90c2392025-06-27 21:10:35 +02001334#endif
Bram Moolenaar62b42182010-09-21 22:09:37 +02001335 if (clip_star.owned)
1336 clip_lose_selection(&clip_star);
1337 if (clip_plus.owned)
1338 clip_lose_selection(&clip_plus);
Foxe Chenb90c2392025-06-27 21:10:35 +02001339#ifdef FEAT_X11
Bram Moolenaar62b42182010-09-21 22:09:37 +02001340 if (x11_display != NULL)
1341 XFlush(x11_display);
Foxe Chenb90c2392025-06-27 21:10:35 +02001342#endif
Bram Moolenaar62b42182010-09-21 22:09:37 +02001343 }
1344}
Foxe Chenb90c2392025-06-27 21:10:35 +02001345#endif
Bram Moolenaar1a0316c2013-03-13 17:50:25 +01001346
Foxe Chenb90c2392025-06-27 21:10:35 +02001347# if defined(USE_SYSTEM) && (defined(FEAT_X11) || defined(FEAT_WAYLAND_CLIPBOARD))
Bram Moolenaar1a0316c2013-03-13 17:50:25 +01001348/*
1349 * Save clipboard text to restore later.
1350 */
1351 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01001352save_clipboard(void)
Bram Moolenaar1a0316c2013-03-13 17:50:25 +01001353{
1354 if (clip_star.owned)
1355 clip_star_save = get_register('*', TRUE);
1356 if (clip_plus.owned)
1357 clip_plus_save = get_register('+', TRUE);
1358}
1359
1360/*
Foxe Chenb90c2392025-06-27 21:10:35 +02001361 * Restore clipboard text if no one own the X/Wayland selection.
Bram Moolenaar1a0316c2013-03-13 17:50:25 +01001362 */
1363 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01001364restore_clipboard(void)
Bram Moolenaar1a0316c2013-03-13 17:50:25 +01001365{
1366 if (clip_star_save != NULL)
1367 {
1368 if (!clip_gen_owner_exists(&clip_star))
1369 put_register('*', clip_star_save);
1370 else
1371 free_register(clip_star_save);
1372 clip_star_save = NULL;
1373 }
1374 if (clip_plus_save != NULL)
1375 {
1376 if (!clip_gen_owner_exists(&clip_plus))
1377 put_register('+', clip_plus_save);
1378 else
1379 free_register(clip_plus_save);
1380 clip_plus_save = NULL;
1381 }
1382}
Bram Moolenaar090cfc12013-03-19 12:35:42 +01001383# endif
Bram Moolenaar62b42182010-09-21 22:09:37 +02001384#endif
1385
Bram Moolenaar071d4272004-06-13 20:20:40 +00001386/*
1387 * If the machine has job control, use it to suspend the program,
1388 * otherwise fake it by starting a new shell.
1389 */
1390 void
Bram Moolenaar05540972016-01-30 20:31:25 +01001391mch_suspend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001392{
Bram Moolenaar5c3128e2020-05-11 20:54:42 +02001393 if (ignore_sigtstp)
1394 return;
1395
Bram Moolenaar041c7102020-05-30 18:14:57 +02001396#if defined(SIGTSTP)
Bram Moolenaar2e310482018-08-21 13:09:10 +02001397 in_mch_suspend = TRUE;
1398
Bram Moolenaar0f873732019-12-05 20:28:46 +01001399 out_flush(); // needed to make cursor visible on some systems
Bram Moolenaar071d4272004-06-13 20:20:40 +00001400 settmode(TMODE_COOK);
Bram Moolenaar0f873732019-12-05 20:28:46 +01001401 out_flush(); // needed to disable mouse on some systems
Bram Moolenaar071d4272004-06-13 20:20:40 +00001402
Foxe Chenb90c2392025-06-27 21:10:35 +02001403# if defined(FEAT_CLIPBOARD) && (defined(FEAT_X11) \
1404 || defined(FEAT_WAYLAND_CLIPBOARD))
Bram Moolenaar62b42182010-09-21 22:09:37 +02001405 loose_clipboard();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001406# endif
Bram Moolenaar2e310482018-08-21 13:09:10 +02001407# if defined(SIGCONT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001408 sigcont_received = FALSE;
1409# endif
Bram Moolenaar2e310482018-08-21 13:09:10 +02001410
Bram Moolenaar0f873732019-12-05 20:28:46 +01001411 kill(0, SIGTSTP); // send ourselves a STOP signal
Bram Moolenaar2e310482018-08-21 13:09:10 +02001412
1413# if defined(SIGCONT)
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001414 /*
1415 * Wait for the SIGCONT signal to be handled. It generally happens
Bram Moolenaar2e310482018-08-21 13:09:10 +02001416 * immediately, but somehow not all the time, probably because it's handled
1417 * in another thread. Do not call pause() because there would be race
1418 * condition which would hang Vim if signal happened in between the test of
1419 * sigcont_received and the call to pause(). If signal is not yet received,
1420 * sleep 0, 1, 2, 3 ms. Don't bother waiting further if signal is not
1421 * received after 1+2+3 ms (not expected to happen).
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001422 */
1423 {
Bram Moolenaar262735e2009-07-14 10:20:22 +00001424 long wait_time;
Bram Moolenaar2e310482018-08-21 13:09:10 +02001425
Bram Moolenaar262735e2009-07-14 10:20:22 +00001426 for (wait_time = 0; !sigcont_received && wait_time <= 3L; wait_time++)
Bram Moolenaar0981c872020-08-23 14:28:37 +02001427 mch_delay(wait_time, 0);
Bram Moolenaar76243bd2009-03-02 01:47:02 +00001428 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001429# endif
Bram Moolenaar2e310482018-08-21 13:09:10 +02001430 in_mch_suspend = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001431
Bram Moolenaar2e310482018-08-21 13:09:10 +02001432 after_sigcont();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001433#else
1434 suspend_shell();
1435#endif
1436}
1437
1438 void
Bram Moolenaar05540972016-01-30 20:31:25 +01001439mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001440{
1441 Columns = 80;
1442 Rows = 24;
1443
1444 out_flush();
Bram Moolenaar5c3128e2020-05-11 20:54:42 +02001445
1446#ifdef SIGTSTP
1447 // Check whether we were invoked with SIGTSTP set to be ignored. If it is
1448 // that indicates the shell (or program) that launched us does not support
1449 // tty job control and thus we should ignore that signal. If invoked as a
1450 // restricted editor (e.g., as "rvim") SIGTSTP is always ignored.
ichizok378447f2023-05-11 22:25:42 +01001451 ignore_sigtstp = restricted || SIG_IGN == mch_signal(SIGTSTP, SIG_ERR);
Bram Moolenaar5c3128e2020-05-11 20:54:42 +02001452#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001453 set_signals();
Bram Moolenaardf177f62005-02-22 08:39:57 +00001454
Bram Moolenaar56718732006-03-15 22:53:57 +00001455#ifdef MACOS_CONVERT
Bram Moolenaardf177f62005-02-22 08:39:57 +00001456 mac_conv_init();
1457#endif
Bram Moolenaar693e40c2013-02-26 14:56:42 +01001458#ifdef FEAT_CYGWIN_WIN32_CLIPBOARD
1459 win_clip_init();
1460#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001461}
1462
1463 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01001464set_signals(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001465{
1466#if defined(SIGWINCH)
1467 /*
1468 * WINDOW CHANGE signal is handled with sig_winch().
1469 */
ichizok378447f2023-05-11 22:25:42 +01001470 mch_signal(SIGWINCH, sig_winch);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001471#endif
1472
Bram Moolenaar071d4272004-06-13 20:20:40 +00001473#ifdef SIGTSTP
Bram Moolenaar5c3128e2020-05-11 20:54:42 +02001474 // See mch_init() for the conditions under which we ignore SIGTSTP.
Bram Moolenaar8e4af852022-01-24 12:20:45 +00001475 // In the GUI default TSTP processing is OK.
1476 // Checking both gui.in_use and gui.starting because gui.in_use is not set
1477 // at this point (set after menus are displayed), but gui.starting is set.
ichizok378447f2023-05-11 22:25:42 +01001478 mch_signal(SIGTSTP, ignore_sigtstp ? SIG_IGN
Bram Moolenaar8e4af852022-01-24 12:20:45 +00001479# ifdef FEAT_GUI
1480 : gui.in_use || gui.starting ? SIG_DFL
1481# endif
ichizok378447f2023-05-11 22:25:42 +01001482 : sig_tstp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001483#endif
Bram Moolenaar2e310482018-08-21 13:09:10 +02001484#if defined(SIGCONT)
ichizok378447f2023-05-11 22:25:42 +01001485 mch_signal(SIGCONT, sigcont_handler);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001486#endif
Bram Moolenaarbe5ee862020-06-10 20:56:58 +02001487#ifdef SIGPIPE
Bram Moolenaar071d4272004-06-13 20:20:40 +00001488 /*
1489 * We want to ignore breaking of PIPEs.
1490 */
ichizok378447f2023-05-11 22:25:42 +01001491 mch_signal(SIGPIPE, SIG_IGN);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001492#endif
1493
Bram Moolenaar071d4272004-06-13 20:20:40 +00001494#ifdef SIGINT
Bram Moolenaardf177f62005-02-22 08:39:57 +00001495 catch_int_signal();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001496#endif
1497
Bram Moolenaarbe5ee862020-06-10 20:56:58 +02001498#ifdef SIGUSR1
1499 /*
1500 * Call user's handler on SIGUSR1
1501 */
ichizok378447f2023-05-11 22:25:42 +01001502 mch_signal(SIGUSR1, catch_sigusr1);
Bram Moolenaarbe5ee862020-06-10 20:56:58 +02001503#endif
1504
Bram Moolenaar071d4272004-06-13 20:20:40 +00001505 /*
1506 * Ignore alarm signals (Perl's alarm() generates it).
1507 */
1508#ifdef SIGALRM
ichizok378447f2023-05-11 22:25:42 +01001509 mch_signal(SIGALRM, SIG_IGN);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001510#endif
1511
Bram Moolenaarbe5ee862020-06-10 20:56:58 +02001512#ifdef SIGPWR
Bram Moolenaar071d4272004-06-13 20:20:40 +00001513 /*
1514 * Catch SIGPWR (power failure?) to preserve the swap files, so that no
1515 * work will be lost.
1516 */
ichizok378447f2023-05-11 22:25:42 +01001517 mch_signal(SIGPWR, catch_sigpwr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001518#endif
1519
1520 /*
1521 * Arrange for other signals to gracefully shutdown Vim.
1522 */
1523 catch_signals(deathtrap, SIG_ERR);
1524
1525#if defined(FEAT_GUI) && defined(SIGHUP)
1526 /*
1527 * When the GUI is running, ignore the hangup signal.
1528 */
1529 if (gui.in_use)
ichizok378447f2023-05-11 22:25:42 +01001530 mch_signal(SIGHUP, SIG_IGN);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001531#endif
1532}
1533
Bram Moolenaardf177f62005-02-22 08:39:57 +00001534#if defined(SIGINT) || defined(PROTO)
1535/*
1536 * Catch CTRL-C (only works while in Cooked mode).
1537 */
1538 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01001539catch_int_signal(void)
Bram Moolenaardf177f62005-02-22 08:39:57 +00001540{
ichizok378447f2023-05-11 22:25:42 +01001541 mch_signal(SIGINT, catch_sigint);
Bram Moolenaardf177f62005-02-22 08:39:57 +00001542}
1543#endif
1544
Bram Moolenaar071d4272004-06-13 20:20:40 +00001545 void
Bram Moolenaar05540972016-01-30 20:31:25 +01001546reset_signals(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001547{
1548 catch_signals(SIG_DFL, SIG_DFL);
Bram Moolenaar2e310482018-08-21 13:09:10 +02001549#if defined(SIGCONT)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001550 // SIGCONT isn't in the list, because its default action is ignore
ichizok378447f2023-05-11 22:25:42 +01001551 mch_signal(SIGCONT, SIG_DFL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001552#endif
1553}
1554
1555 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01001556catch_signals(
Michael Jarvisbe9624e2023-04-19 20:28:48 +01001557 void (*func_deadly)(int),
1558 void (*func_other)(int))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001559{
1560 int i;
1561
1562 for (i = 0; signal_info[i].sig != -1; i++)
Bram Moolenaar5c3128e2020-05-11 20:54:42 +02001563 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001564 if (signal_info[i].deadly)
1565 {
1566#if defined(HAVE_SIGALTSTACK) && defined(HAVE_SIGACTION)
1567 struct sigaction sa;
1568
Bram Moolenaar0f873732019-12-05 20:28:46 +01001569 // Setup to use the alternate stack for the signal function.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001570 sa.sa_handler = func_deadly;
1571 sigemptyset(&sa.sa_mask);
1572# if defined(__linux__) && defined(_REENTRANT)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001573 // On Linux, with glibc compiled for kernel 2.2, there is a bug in
1574 // thread handling in combination with using the alternate stack:
1575 // pthread library functions try to use the stack pointer to
1576 // identify the current thread, causing a SEGV signal, which
1577 // recursively calls deathtrap() and hangs.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001578 sa.sa_flags = 0;
1579# else
1580 sa.sa_flags = SA_ONSTACK;
1581# endif
1582 sigaction(signal_info[i].sig, &sa, NULL);
1583#else
1584# if defined(HAVE_SIGALTSTACK) && defined(HAVE_SIGVEC)
1585 struct sigvec sv;
1586
Bram Moolenaar0f873732019-12-05 20:28:46 +01001587 // Setup to use the alternate stack for the signal function.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001588 sv.sv_handler = func_deadly;
1589 sv.sv_mask = 0;
1590 sv.sv_flags = SV_ONSTACK;
1591 sigvec(signal_info[i].sig, &sv, NULL);
1592# else
ichizok378447f2023-05-11 22:25:42 +01001593 mch_signal(signal_info[i].sig, func_deadly);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001594# endif
1595#endif
1596 }
1597 else if (func_other != SIG_ERR)
Bram Moolenaar5c3128e2020-05-11 20:54:42 +02001598 {
1599 // Deal with non-deadly signals.
1600#ifdef SIGTSTP
ichizok378447f2023-05-11 22:25:42 +01001601 mch_signal(signal_info[i].sig,
Bram Moolenaar5c3128e2020-05-11 20:54:42 +02001602 signal_info[i].sig == SIGTSTP && ignore_sigtstp
1603 ? SIG_IGN : func_other);
1604#else
ichizok378447f2023-05-11 22:25:42 +01001605 mch_signal(signal_info[i].sig, func_other);
Bram Moolenaar5c3128e2020-05-11 20:54:42 +02001606#endif
1607 }
1608 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001609}
1610
Bram Moolenaarbb09ceb2016-10-18 16:27:23 +02001611#ifdef HAVE_SIGPROCMASK
1612 static void
1613block_signals(sigset_t *set)
1614{
1615 sigset_t newset;
1616 int i;
1617
1618 sigemptyset(&newset);
1619
1620 for (i = 0; signal_info[i].sig != -1; i++)
1621 sigaddset(&newset, signal_info[i].sig);
1622
Bram Moolenaar2e310482018-08-21 13:09:10 +02001623# if defined(SIGCONT)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001624 // SIGCONT isn't in the list, because its default action is ignore
Bram Moolenaarbb09ceb2016-10-18 16:27:23 +02001625 sigaddset(&newset, SIGCONT);
1626# endif
1627
1628 sigprocmask(SIG_BLOCK, &newset, set);
1629}
1630
1631 static void
1632unblock_signals(sigset_t *set)
1633{
1634 sigprocmask(SIG_SETMASK, set, NULL);
1635}
1636#endif
1637
Bram Moolenaar071d4272004-06-13 20:20:40 +00001638/*
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001639 * Handling of SIGHUP, SIGQUIT and SIGTERM:
Bram Moolenaar9e1d2832007-05-06 12:51:41 +00001640 * "when" == a signal: when busy, postpone and return FALSE, otherwise
1641 * return TRUE
1642 * "when" == SIGNAL_BLOCK: Going to be busy, block signals
1643 * "when" == SIGNAL_UNBLOCK: Going to wait, unblock signals, use postponed
Bram Moolenaar67c53842010-05-22 18:28:27 +02001644 * signal
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001645 * Returns TRUE when Vim should exit.
1646 */
1647 int
Bram Moolenaar05540972016-01-30 20:31:25 +01001648vim_handle_signal(int sig)
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001649{
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001650 static int got_signal = 0;
1651 static int blocked = TRUE;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001652
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001653 switch (sig)
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001654 {
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001655 case SIGNAL_BLOCK: blocked = TRUE;
1656 break;
1657
1658 case SIGNAL_UNBLOCK: blocked = FALSE;
1659 if (got_signal != 0)
1660 {
1661 kill(getpid(), got_signal);
1662 got_signal = 0;
1663 }
1664 break;
1665
1666 default: if (!blocked)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001667 return TRUE; // exit!
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001668 got_signal = sig;
1669#ifdef SIGPWR
1670 if (sig != SIGPWR)
1671#endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01001672 got_int = TRUE; // break any loops
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00001673 break;
1674 }
1675 return FALSE;
1676}
1677
1678/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00001679 * Check_win checks whether we have an interactive stdout.
1680 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001681 int
Bram Moolenaar05540972016-01-30 20:31:25 +01001682mch_check_win(int argc UNUSED, char **argv UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001683{
Bram Moolenaar071d4272004-06-13 20:20:40 +00001684 if (isatty(1))
1685 return OK;
1686 return FAIL;
1687}
1688
1689/*
1690 * Return TRUE if the input comes from a terminal, FALSE otherwise.
1691 */
1692 int
Bram Moolenaar05540972016-01-30 20:31:25 +01001693mch_input_isatty(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001694{
1695 if (isatty(read_cmd_fd))
1696 return TRUE;
1697 return FALSE;
1698}
1699
1700#ifdef FEAT_X11
1701
Bram Moolenaar651fca82021-11-29 20:39:38 +00001702# if defined(ELAPSED_TIMEVAL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001703
Bram Moolenaar071d4272004-06-13 20:20:40 +00001704/*
1705 * Give a message about the elapsed time for opening the X window.
1706 */
1707 static void
Bram Moolenaar833eb1d2016-11-24 17:22:50 +01001708xopen_message(long elapsed_msec)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001709{
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01001710 smsg(_("Opening the X display took %ld msec"), elapsed_msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001711}
1712# endif
1713#endif
1714
Bram Moolenaar651fca82021-11-29 20:39:38 +00001715#if defined(FEAT_X11)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001716/*
1717 * A few functions shared by X11 title and clipboard code.
1718 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001719
1720static int got_x_error = FALSE;
1721
1722/*
1723 * X Error handler, otherwise X just exits! (very rude) -- webb
1724 */
1725 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01001726x_error_handler(Display *dpy, XErrorEvent *error_event)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001727{
Bram Moolenaar843ee412004-06-30 16:16:41 +00001728 XGetErrorText(dpy, error_event->error_code, (char *)IObuff, IOSIZE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001729 STRCAT(IObuff, _("\nVim: Got X error\n"));
1730
Bram Moolenaarb1062eb2020-05-09 16:11:33 +02001731 // In the GUI we cannot print a message and continue, because no X calls
1732 // are allowed here (causes my system to hang). Silently continuing seems
1733 // like the best alternative. Do preserve files, in case we crash.
1734 ml_sync_all(FALSE, FALSE);
1735
1736#ifdef FEAT_GUI
1737 if (!gui.in_use)
1738#endif
1739 msg((char *)IObuff);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001740
Bram Moolenaar0f873732019-12-05 20:28:46 +01001741 return 0; // NOTREACHED
Bram Moolenaar071d4272004-06-13 20:20:40 +00001742}
1743
1744/*
1745 * Another X Error handler, just used to check for errors.
1746 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001747 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01001748x_error_check(Display *dpy UNUSED, XErrorEvent *error_event UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001749{
1750 got_x_error = TRUE;
1751 return 0;
1752}
1753
Bram Moolenaarc0c75492018-12-29 11:03:23 +01001754/*
1755 * Return TRUE when connection to the X server is desired.
1756 */
1757 static int
1758x_connect_to_server(void)
1759{
1760 // No point in connecting if we are exiting or dying.
1761 if (exiting || v_dying)
1762 return FALSE;
1763
1764#if defined(FEAT_CLIENTSERVER)
1765 if (x_force_connect)
1766 return TRUE;
1767#endif
1768 if (x_no_connect)
1769 return FALSE;
1770
Bram Moolenaara8bfa172018-12-29 22:28:46 +01001771 // Check for a match with "exclude:" from 'clipboard'.
Bram Moolenaarc0c75492018-12-29 11:03:23 +01001772 if (clip_exclude_prog != NULL)
1773 {
Bram Moolenaara8bfa172018-12-29 22:28:46 +01001774 // Just in case we get called recursively, return FALSE. This could
1775 // happen if vpeekc() is used while executing the prog and it causes a
1776 // related callback to be invoked.
1777 if (regprog_in_use(clip_exclude_prog))
1778 return FALSE;
1779
Bram Moolenaarc0c75492018-12-29 11:03:23 +01001780 if (vim_regexec_prog(&clip_exclude_prog, FALSE, T_NAME, (colnr_T)0))
1781 return FALSE;
1782 }
1783 return TRUE;
1784}
1785
Bram Moolenaar071d4272004-06-13 20:20:40 +00001786#if defined(FEAT_X11) && defined(FEAT_XCLIPBOARD)
Bram Moolenaarb2148f52019-01-20 23:43:57 +01001787# if defined(USING_SETJMP)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001788/*
1789 * An X IO Error handler, used to catch error while opening the display.
1790 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001791 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01001792x_IOerror_check(Display *dpy UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001793{
Bram Moolenaar0f873732019-12-05 20:28:46 +01001794 // This function should not return, it causes exit(). Longjump instead.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001795 LONGJMP(lc_jump_env, 1);
Bram Moolenaar1eed5322019-02-26 17:03:54 +01001796# if defined(VMS) || defined(__CYGWIN__)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001797 return 0; // avoid the compiler complains about missing return value
Bram Moolenaarb4990bf2010-02-11 18:19:38 +01001798# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001799}
1800# endif
1801
1802/*
1803 * An X IO Error handler, used to catch terminal errors.
1804 */
Bram Moolenaard155d7a2018-12-21 16:04:21 +01001805static int xterm_dpy_retry_count = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001806
Bram Moolenaar071d4272004-06-13 20:20:40 +00001807 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01001808x_IOerror_handler(Display *dpy UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001809{
1810 xterm_dpy = NULL;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01001811 xterm_dpy_retry_count = 5; // Try reconnecting five times
Bram Moolenaar071d4272004-06-13 20:20:40 +00001812 x11_window = 0;
1813 x11_display = NULL;
1814 xterm_Shell = (Widget)0;
1815
Bram Moolenaar0f873732019-12-05 20:28:46 +01001816 // This function should not return, it causes exit(). Longjump instead.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001817 LONGJMP(x_jump_env, 1);
Bram Moolenaar1eed5322019-02-26 17:03:54 +01001818# if defined(VMS) || defined(__CYGWIN__)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001819 return 0; // avoid the compiler complains about missing return value
Bram Moolenaarb4990bf2010-02-11 18:19:38 +01001820# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001821}
Bram Moolenaarb1e26502014-11-19 18:48:46 +01001822
1823/*
1824 * If the X11 connection was lost try to restore it.
1825 * Helps when the X11 server was stopped and restarted while Vim was inactive
Bram Moolenaarcaad4f02014-12-17 14:36:14 +01001826 * (e.g. through tmux).
Bram Moolenaarb1e26502014-11-19 18:48:46 +01001827 */
1828 static void
Foxe Chenb90c2392025-06-27 21:10:35 +02001829may_restore_x11_clipboard(void)
Bram Moolenaarb1e26502014-11-19 18:48:46 +01001830{
Bram Moolenaar01e51e52018-12-29 13:09:46 +01001831 // No point in restoring the connecting if we are exiting or dying.
1832 if (!exiting && !v_dying && xterm_dpy_retry_count > 0)
Bram Moolenaarb1e26502014-11-19 18:48:46 +01001833 {
Bram Moolenaard155d7a2018-12-21 16:04:21 +01001834 --xterm_dpy_retry_count;
Bram Moolenaar527a6782014-12-17 17:59:31 +01001835
1836# ifndef LESSTIF_VERSION
Bram Moolenaar0f873732019-12-05 20:28:46 +01001837 // This has been reported to avoid Vim getting stuck.
Bram Moolenaar527a6782014-12-17 17:59:31 +01001838 if (app_context != (XtAppContext)NULL)
1839 {
1840 XtDestroyApplicationContext(app_context);
1841 app_context = (XtAppContext)NULL;
Bram Moolenaar0f873732019-12-05 20:28:46 +01001842 x11_display = NULL; // freed by XtDestroyApplicationContext()
Bram Moolenaar527a6782014-12-17 17:59:31 +01001843 }
1844# endif
1845
Bram Moolenaarb1e26502014-11-19 18:48:46 +01001846 setup_term_clip();
1847 get_x11_title(FALSE);
1848 }
1849}
Bram Moolenaard4aa83a2019-05-09 18:59:31 +02001850
1851 void
1852ex_xrestore(exarg_T *eap)
1853{
John Marriottefc41a52025-01-23 20:05:29 +01001854 size_t arglen;
1855
1856 if (eap->arg != NULL && (arglen = STRLEN(eap->arg)) > 0)
Bram Moolenaard4aa83a2019-05-09 18:59:31 +02001857 {
Bram Moolenaar6ed545e2022-05-09 20:09:23 +01001858 if (xterm_display_allocated)
1859 vim_free(xterm_display);
John Marriottefc41a52025-01-23 20:05:29 +01001860 xterm_display = (char *)vim_strnsave(eap->arg, arglen);
Bram Moolenaar6ed545e2022-05-09 20:09:23 +01001861 xterm_display_allocated = TRUE;
Bram Moolenaard4aa83a2019-05-09 18:59:31 +02001862 }
Foxe Chenb90c2392025-06-27 21:10:35 +02001863 smsg(_("restoring X11 display %s"), xterm_display == NULL
Bram Moolenaar0c5c3fa2019-11-30 22:38:16 +01001864 ? (char *)mch_getenv((char_u *)"DISPLAY") : xterm_display);
Bram Moolenaard4aa83a2019-05-09 18:59:31 +02001865
1866 clear_xterm_clip();
1867 x11_window = 0;
1868 xterm_dpy_retry_count = 5; // Try reconnecting five times
Foxe Chenb90c2392025-06-27 21:10:35 +02001869 may_restore_x11_clipboard();
1870 choose_clipmethod();
Bram Moolenaard4aa83a2019-05-09 18:59:31 +02001871}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001872#endif
1873
1874/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00001875 * Test if "dpy" and x11_window are valid by getting the window title.
1876 * I don't actually want it yet, so there may be a simpler call to use, but
1877 * this will cause the error handler x_error_check() to be called if anything
1878 * is wrong, such as the window pointer being invalid (as can happen when the
1879 * user changes his DISPLAY, but not his WINDOWID) -- webb
1880 */
1881 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01001882test_x11_window(Display *dpy)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001883{
Dominique Pellé4927bc72023-09-24 16:12:07 +02001884 int (*old_handler)(Display*, XErrorEvent*);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001885 XTextProperty text_prop;
1886
1887 old_handler = XSetErrorHandler(x_error_check);
1888 got_x_error = FALSE;
1889 if (XGetWMName(dpy, x11_window, &text_prop))
1890 XFree((void *)text_prop.value);
1891 XSync(dpy, False);
1892 (void)XSetErrorHandler(old_handler);
1893
1894 if (p_verbose > 0 && got_x_error)
Bram Moolenaar32526b32019-01-19 17:43:09 +01001895 verb_msg(_("Testing the X display failed"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00001896
1897 return (got_x_error ? FAIL : OK);
1898}
1899#endif
1900
Bram Moolenaar071d4272004-06-13 20:20:40 +00001901
1902#ifdef FEAT_X11
1903
Bram Moolenaarbaaa7e92016-01-29 22:47:03 +01001904static int get_x11_thing(int get_title, int test_only);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001905
1906/*
1907 * try to get x11 window and display
1908 *
1909 * return FAIL for failure, OK otherwise
1910 */
1911 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01001912get_x11_windis(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001913{
1914 char *winid;
1915 static int result = -1;
Bram Moolenaar0f873732019-12-05 20:28:46 +01001916#define XD_NONE 0 // x11_display not set here
1917#define XD_HERE 1 // x11_display opened here
1918#define XD_GUI 2 // x11_display used from gui.dpy
1919#define XD_XTERM 3 // x11_display used from xterm_dpy
Bram Moolenaar071d4272004-06-13 20:20:40 +00001920 static int x11_display_from = XD_NONE;
1921 static int did_set_error_handler = FALSE;
1922
1923 if (!did_set_error_handler)
1924 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001925 // X just exits if it finds an error otherwise!
Bram Moolenaar071d4272004-06-13 20:20:40 +00001926 (void)XSetErrorHandler(x_error_handler);
1927 did_set_error_handler = TRUE;
1928 }
1929
Bram Moolenaar9372a112005-12-06 19:59:18 +00001930#if defined(FEAT_GUI_X11) || defined(FEAT_GUI_GTK)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001931 if (gui.in_use)
1932 {
1933 /*
1934 * If the X11 display was opened here before, for the window where Vim
1935 * was started, close that one now to avoid a memory leak.
1936 */
1937 if (x11_display_from == XD_HERE && x11_display != NULL)
1938 {
1939 XCloseDisplay(x11_display);
1940 x11_display_from = XD_NONE;
1941 }
1942 if (gui_get_x11_windis(&x11_window, &x11_display) == OK)
1943 {
1944 x11_display_from = XD_GUI;
1945 return OK;
1946 }
1947 x11_display = NULL;
1948 return FAIL;
1949 }
1950 else if (x11_display_from == XD_GUI)
1951 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001952 // GUI must have stopped somehow, clear x11_display
Bram Moolenaar071d4272004-06-13 20:20:40 +00001953 x11_window = 0;
1954 x11_display = NULL;
1955 x11_display_from = XD_NONE;
1956 }
1957#endif
1958
Bram Moolenaar0f873732019-12-05 20:28:46 +01001959 // When started with the "-X" argument, don't try connecting.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001960 if (!x_connect_to_server())
1961 return FAIL;
1962
1963 /*
1964 * If WINDOWID not set, should try another method to find out
1965 * what the current window number is. The only code I know for
1966 * this is very complicated.
1967 * We assume that zero is invalid for WINDOWID.
1968 */
1969 if (x11_window == 0 && (winid = getenv("WINDOWID")) != NULL)
1970 x11_window = (Window)atol(winid);
1971
1972#ifdef FEAT_XCLIPBOARD
Bram Moolenaard4aa83a2019-05-09 18:59:31 +02001973 if (xterm_dpy == x11_display)
1974 // x11_display may have been set to xterm_dpy elsewhere
1975 x11_display_from = XD_XTERM;
1976
Bram Moolenaar071d4272004-06-13 20:20:40 +00001977 if (xterm_dpy != NULL && x11_window != 0)
1978 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001979 // We may have checked it already, but Gnome terminal can move us to
1980 // another window, so we need to check every time.
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00001981 if (x11_display_from != XD_XTERM)
1982 {
1983 /*
1984 * If the X11 display was opened here before, for the window where
1985 * Vim was started, close that one now to avoid a memory leak.
1986 */
1987 if (x11_display_from == XD_HERE && x11_display != NULL)
1988 XCloseDisplay(x11_display);
1989 x11_display = xterm_dpy;
1990 x11_display_from = XD_XTERM;
1991 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001992 if (test_x11_window(x11_display) == FAIL)
1993 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001994 // probably bad $WINDOWID
Bram Moolenaar071d4272004-06-13 20:20:40 +00001995 x11_window = 0;
1996 x11_display = NULL;
1997 x11_display_from = XD_NONE;
1998 return FAIL;
1999 }
2000 return OK;
2001 }
2002#endif
2003
2004 if (x11_window == 0 || x11_display == NULL)
2005 result = -1;
2006
Bram Moolenaar0f873732019-12-05 20:28:46 +01002007 if (result != -1) // Have already been here and set this
2008 return result; // Don't do all these X calls again
Bram Moolenaar071d4272004-06-13 20:20:40 +00002009
2010 if (x11_window != 0 && x11_display == NULL)
2011 {
2012#ifdef SET_SIG_ALARM
ichizok378447f2023-05-11 22:25:42 +01002013 sighandler_T sig_save;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002014#endif
Bram Moolenaar1ac56c22019-01-17 22:28:22 +01002015#ifdef ELAPSED_FUNC
2016 elapsed_T start_tv;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002017
2018 if (p_verbose > 0)
Bram Moolenaar1ac56c22019-01-17 22:28:22 +01002019 ELAPSED_INIT(start_tv);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002020#endif
2021
2022#ifdef SET_SIG_ALARM
2023 /*
2024 * Opening the Display may hang if the DISPLAY setting is wrong, or
2025 * the network connection is bad. Set an alarm timer to get out.
2026 */
2027 sig_alarm_called = FALSE;
ichizok378447f2023-05-11 22:25:42 +01002028 sig_save = mch_signal(SIGALRM, sig_alarm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002029 alarm(2);
2030#endif
2031 x11_display = XOpenDisplay(NULL);
2032
2033#ifdef SET_SIG_ALARM
2034 alarm(0);
ichizok378447f2023-05-11 22:25:42 +01002035 mch_signal(SIGALRM, sig_save);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002036 if (p_verbose > 0 && sig_alarm_called)
Bram Moolenaar563bbea2019-01-22 21:45:40 +01002037 verb_msg(_("Opening the X display timed out"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00002038#endif
2039 if (x11_display != NULL)
2040 {
Bram Moolenaar833eb1d2016-11-24 17:22:50 +01002041# ifdef ELAPSED_FUNC
Bram Moolenaar071d4272004-06-13 20:20:40 +00002042 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00002043 {
2044 verbose_enter();
Bram Moolenaar833eb1d2016-11-24 17:22:50 +01002045 xopen_message(ELAPSED_FUNC(start_tv));
Bram Moolenaara04f10b2005-05-31 22:09:46 +00002046 verbose_leave();
2047 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002048# endif
2049 if (test_x11_window(x11_display) == FAIL)
2050 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002051 // Maybe window id is bad
Bram Moolenaar071d4272004-06-13 20:20:40 +00002052 x11_window = 0;
2053 XCloseDisplay(x11_display);
2054 x11_display = NULL;
2055 }
2056 else
2057 x11_display_from = XD_HERE;
2058 }
2059 }
2060 if (x11_window == 0 || x11_display == NULL)
2061 return (result = FAIL);
Bram Moolenaar727c8762010-10-20 19:17:48 +02002062
2063# ifdef FEAT_EVAL
2064 set_vim_var_nr(VV_WINDOWID, (long)x11_window);
2065# endif
2066
Bram Moolenaar071d4272004-06-13 20:20:40 +00002067 return (result = OK);
2068}
2069
2070/*
2071 * Determine original x11 Window Title
2072 */
2073 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01002074get_x11_title(int test_only)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002075{
Bram Moolenaar47136d72004-10-12 20:02:24 +00002076 return get_x11_thing(TRUE, test_only);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002077}
2078
2079/*
2080 * Determine original x11 Window icon
2081 */
2082 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01002083get_x11_icon(int test_only)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002084{
2085 int retval = FALSE;
2086
2087 retval = get_x11_thing(FALSE, test_only);
2088
Bram Moolenaar0f873732019-12-05 20:28:46 +01002089 // could not get old icon, use terminal name
Bram Moolenaar071d4272004-06-13 20:20:40 +00002090 if (oldicon == NULL && !test_only)
2091 {
2092 if (STRNCMP(T_NAME, "builtin_", 8) == 0)
Bram Moolenaar20de1c22009-07-22 11:28:11 +00002093 oldicon = vim_strsave(T_NAME + 8);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002094 else
Bram Moolenaar20de1c22009-07-22 11:28:11 +00002095 oldicon = vim_strsave(T_NAME);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002096 }
2097
2098 return retval;
2099}
2100
2101 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01002102get_x11_thing(
Bram Moolenaar0f873732019-12-05 20:28:46 +01002103 int get_title, // get title string
Bram Moolenaar05540972016-01-30 20:31:25 +01002104 int test_only)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002105{
2106 XTextProperty text_prop;
2107 int retval = FALSE;
2108 Status status;
2109
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00002110 if (get_x11_windis() != OK)
2111 return FALSE;
2112
2113 // Get window/icon name if any
2114 if (get_title)
2115 status = XGetWMName(x11_display, x11_window, &text_prop);
2116 else
2117 status = XGetWMIconName(x11_display, x11_window, &text_prop);
2118
2119 /*
2120 * If terminal is xterm, then x11_window may be a child window of the
2121 * outer xterm window that actually contains the window/icon name, so
2122 * keep traversing up the tree until a window with a title/icon is
2123 * found.
2124 */
2125 // Previously this was only done for xterm and alike. I don't see a
2126 // reason why it would fail for other terminal emulators.
2127 // if (term_is_xterm)
2128 Window root;
2129 Window parent;
2130 Window win = x11_window;
2131 Window *children;
2132 unsigned int num_children;
2133
2134 while (!status || text_prop.value == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002135 {
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00002136 if (!XQueryTree(x11_display, win, &root, &parent, &children,
2137 &num_children))
2138 break;
2139 if (children)
2140 XFree((void *)children);
2141 if (parent == root || parent == 0)
2142 break;
2143
2144 win = parent;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002145 if (get_title)
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00002146 status = XGetWMName(x11_display, win, &text_prop);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002147 else
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00002148 status = XGetWMIconName(x11_display, win, &text_prop);
2149 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002150
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00002151 if (status && text_prop.value != NULL)
2152 {
2153 retval = TRUE;
2154 if (!test_only)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002155 {
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00002156 if (get_title)
2157 vim_free(oldtitle);
2158 else
2159 vim_free(oldicon);
2160 if (text_prop.encoding == XA_STRING && !has_mbyte)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002161 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00002162 if (get_title)
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00002163 oldtitle = vim_strsave((char_u *)text_prop.value);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002164 else
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00002165 oldicon = vim_strsave((char_u *)text_prop.value);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002166 }
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00002167 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002168 {
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00002169 char **cl;
2170 Status transform_status;
2171 int n = 0;
2172
2173 transform_status = XmbTextPropertyToTextList(x11_display,
2174 &text_prop,
2175 &cl, &n);
2176 if (transform_status >= Success && n > 0 && cl[0])
2177 {
2178 if (get_title)
2179 oldtitle = vim_strsave((char_u *) cl[0]);
2180 else
2181 oldicon = vim_strsave((char_u *) cl[0]);
2182 XFreeStringList(cl);
2183 }
Bram Moolenaar6b649ac2019-12-07 17:47:22 +01002184 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002185 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00002186 if (get_title)
2187 oldtitle = vim_strsave((char_u *)text_prop.value);
2188 else
2189 oldicon = vim_strsave((char_u *)text_prop.value);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002190 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002191 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002192 }
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00002193 XFree((void *)text_prop.value);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002194 }
2195 return retval;
2196}
2197
Bram Moolenaar0f873732019-12-05 20:28:46 +01002198// Xutf8 functions are not available on older systems. Note that on some
2199// systems X_HAVE_UTF8_STRING may be defined in a header file but
2200// Xutf8SetWMProperties() is not in the X11 library. Configure checks for
2201// that and defines HAVE_XUTF8SETWMPROPERTIES.
Bram Moolenaara12a1612019-01-24 16:39:02 +01002202#if defined(X_HAVE_UTF8_STRING)
Bram Moolenaarcbc246a2014-10-11 14:47:26 +02002203# if X_HAVE_UTF8_STRING && HAVE_XUTF8SETWMPROPERTIES
Bram Moolenaar071d4272004-06-13 20:20:40 +00002204# define USE_UTF8_STRING
2205# endif
2206#endif
2207
2208/*
2209 * Set x11 Window Title
2210 *
2211 * get_x11_windis() must be called before this and have returned OK
2212 */
2213 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01002214set_x11_title(char_u *title)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002215{
Bram Moolenaar0f873732019-12-05 20:28:46 +01002216 // XmbSetWMProperties() and Xutf8SetWMProperties() should use a STRING
2217 // when possible, COMPOUND_TEXT otherwise. COMPOUND_TEXT isn't
2218 // supported everywhere and STRING doesn't work for multi-byte titles.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002219#ifdef USE_UTF8_STRING
2220 if (enc_utf8)
2221 Xutf8SetWMProperties(x11_display, x11_window, (const char *)title,
2222 NULL, NULL, 0, NULL, NULL, NULL);
2223 else
2224#endif
2225 {
2226#if XtSpecificationRelease >= 4
2227# ifdef FEAT_XFONTSET
2228 XmbSetWMProperties(x11_display, x11_window, (const char *)title,
2229 NULL, NULL, 0, NULL, NULL, NULL);
2230# else
2231 XTextProperty text_prop;
Bram Moolenaar9d75c832005-01-25 21:57:23 +00002232 char *c_title = (char *)title;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002233
Bram Moolenaar0f873732019-12-05 20:28:46 +01002234 // directly from example 3-18 "basicwin" of Xlib Programming Manual
Bram Moolenaar9d75c832005-01-25 21:57:23 +00002235 (void)XStringListToTextProperty(&c_title, 1, &text_prop);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002236 XSetWMProperties(x11_display, x11_window, &text_prop,
2237 NULL, NULL, 0, NULL, NULL, NULL);
2238# endif
2239#else
2240 XStoreName(x11_display, x11_window, (char *)title);
2241#endif
2242 }
2243 XFlush(x11_display);
2244}
2245
2246/*
2247 * Set x11 Window icon
2248 *
2249 * get_x11_windis() must be called before this and have returned OK
2250 */
2251 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01002252set_x11_icon(char_u *icon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002253{
Bram Moolenaar0f873732019-12-05 20:28:46 +01002254 // See above for comments about using X*SetWMProperties().
Bram Moolenaar071d4272004-06-13 20:20:40 +00002255#ifdef USE_UTF8_STRING
2256 if (enc_utf8)
2257 Xutf8SetWMProperties(x11_display, x11_window, NULL, (const char *)icon,
2258 NULL, 0, NULL, NULL, NULL);
2259 else
2260#endif
2261 {
2262#if XtSpecificationRelease >= 4
2263# ifdef FEAT_XFONTSET
2264 XmbSetWMProperties(x11_display, x11_window, NULL, (const char *)icon,
2265 NULL, 0, NULL, NULL, NULL);
2266# else
2267 XTextProperty text_prop;
Bram Moolenaar9d75c832005-01-25 21:57:23 +00002268 char *c_icon = (char *)icon;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002269
Bram Moolenaar9d75c832005-01-25 21:57:23 +00002270 (void)XStringListToTextProperty(&c_icon, 1, &text_prop);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002271 XSetWMProperties(x11_display, x11_window, NULL, &text_prop,
2272 NULL, 0, NULL, NULL, NULL);
2273# endif
2274#else
2275 XSetIconName(x11_display, x11_window, (char *)icon);
2276#endif
2277 }
2278 XFlush(x11_display);
2279}
2280
Bram Moolenaar0f873732019-12-05 20:28:46 +01002281#else // FEAT_X11
Bram Moolenaar071d4272004-06-13 20:20:40 +00002282
Bram Moolenaar071d4272004-06-13 20:20:40 +00002283 static int
Bram Moolenaard14e00e2016-01-31 17:30:51 +01002284get_x11_title(int test_only UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002285{
2286 return FALSE;
2287}
2288
2289 static int
Bram Moolenaard14e00e2016-01-31 17:30:51 +01002290get_x11_icon(int test_only)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002291{
2292 if (!test_only)
2293 {
2294 if (STRNCMP(T_NAME, "builtin_", 8) == 0)
Bram Moolenaar20de1c22009-07-22 11:28:11 +00002295 oldicon = vim_strsave(T_NAME + 8);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002296 else
Bram Moolenaar20de1c22009-07-22 11:28:11 +00002297 oldicon = vim_strsave(T_NAME);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002298 }
2299 return FALSE;
2300}
2301
Bram Moolenaar0f873732019-12-05 20:28:46 +01002302#endif // FEAT_X11
Bram Moolenaar071d4272004-06-13 20:20:40 +00002303
2304 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002305mch_can_restore_title(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002306{
2307 return get_x11_title(TRUE);
2308}
2309
2310 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002311mch_can_restore_icon(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002312{
2313 return get_x11_icon(TRUE);
2314}
2315
2316/*
2317 * Set the window title and icon.
2318 */
2319 void
Bram Moolenaar05540972016-01-30 20:31:25 +01002320mch_settitle(char_u *title, char_u *icon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002321{
2322 int type = 0;
2323 static int recursive = 0;
2324
Bram Moolenaar0f873732019-12-05 20:28:46 +01002325 if (T_NAME == NULL) // no terminal name (yet)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002326 return;
Bram Moolenaar0f873732019-12-05 20:28:46 +01002327 if (title == NULL && icon == NULL) // nothing to do
Bram Moolenaar071d4272004-06-13 20:20:40 +00002328 return;
2329
Bram Moolenaar0f873732019-12-05 20:28:46 +01002330 // When one of the X11 functions causes a deadly signal, we get here again
2331 // recursively. Avoid hanging then (something is probably locked).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002332 if (recursive)
2333 return;
2334 ++recursive;
2335
2336 /*
2337 * if the window ID and the display is known, we may use X11 calls
2338 */
2339#ifdef FEAT_X11
2340 if (get_x11_windis() == OK)
2341 type = 1;
lilydjwg6e0a18f2024-01-29 20:54:28 +01002342#endif
2343#if defined(FEAT_GUI_PHOTON) \
Bram Moolenaarb3f74062020-02-26 16:16:53 +01002344 || defined(FEAT_GUI_GTK) || defined(FEAT_GUI_HAIKU)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002345 if (gui.in_use)
2346 type = 1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002347#endif
2348
2349 /*
Bram Moolenaarf82bac32010-07-25 22:30:20 +02002350 * Note: if "t_ts" is set, title is set with escape sequence rather
Bram Moolenaar071d4272004-06-13 20:20:40 +00002351 * than x11 calls, because the x11 calls don't always work
2352 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002353 if ((type || *T_TS != NUL) && title != NULL)
2354 {
Bram Moolenaard8f0cef2018-08-19 22:20:16 +02002355 if (oldtitle_outdated)
2356 {
2357 oldtitle_outdated = FALSE;
2358 VIM_CLEAR(oldtitle);
2359 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002360 if (oldtitle == NULL
2361#ifdef FEAT_GUI
2362 && !gui.in_use
2363#endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01002364 ) // first call but not in GUI, save title
Bram Moolenaar071d4272004-06-13 20:20:40 +00002365 (void)get_x11_title(FALSE);
2366
Bram Moolenaar0f873732019-12-05 20:28:46 +01002367 if (*T_TS != NUL) // it's OK if t_fs is empty
Bram Moolenaar071d4272004-06-13 20:20:40 +00002368 term_settitle(title);
2369#ifdef FEAT_X11
2370 else
2371# ifdef FEAT_GUI_GTK
Bram Moolenaar0f873732019-12-05 20:28:46 +01002372 if (!gui.in_use) // don't do this if GTK+ is running
Bram Moolenaar071d4272004-06-13 20:20:40 +00002373# endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01002374 set_x11_title(title); // x11
Bram Moolenaar071d4272004-06-13 20:20:40 +00002375#endif
Bram Moolenaarb3f74062020-02-26 16:16:53 +01002376#if defined(FEAT_GUI_GTK) || defined(FEAT_GUI_HAIKU) \
Bram Moolenaar097148e2020-08-11 21:58:20 +02002377 || defined(FEAT_GUI_PHOTON)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002378 else
2379 gui_mch_settitle(title, icon);
2380#endif
Bram Moolenaardac13472019-09-16 21:06:21 +02002381 unix_did_set_title = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002382 }
2383
2384 if ((type || *T_CIS != NUL) && icon != NULL)
2385 {
2386 if (oldicon == NULL
2387#ifdef FEAT_GUI
2388 && !gui.in_use
2389#endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01002390 ) // first call, save icon
Bram Moolenaar071d4272004-06-13 20:20:40 +00002391 get_x11_icon(FALSE);
2392
2393 if (*T_CIS != NUL)
2394 {
Bram Moolenaarfaf626e2019-10-24 17:43:25 +02002395 out_str(T_CIS); // set icon start
Bram Moolenaar071d4272004-06-13 20:20:40 +00002396 out_str_nf(icon);
Bram Moolenaarfaf626e2019-10-24 17:43:25 +02002397 out_str(T_CIE); // set icon end
Bram Moolenaar071d4272004-06-13 20:20:40 +00002398 out_flush();
2399 }
2400#ifdef FEAT_X11
2401 else
2402# ifdef FEAT_GUI_GTK
Bram Moolenaar0f873732019-12-05 20:28:46 +01002403 if (!gui.in_use) // don't do this if GTK+ is running
Bram Moolenaar071d4272004-06-13 20:20:40 +00002404# endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01002405 set_x11_icon(icon); // x11
Bram Moolenaar071d4272004-06-13 20:20:40 +00002406#endif
2407 did_set_icon = TRUE;
2408 }
2409 --recursive;
2410}
2411
2412/*
2413 * Restore the window/icon title.
2414 * "which" is one of:
Bram Moolenaar40385db2018-08-07 22:31:44 +02002415 * SAVE_RESTORE_TITLE only restore title
2416 * SAVE_RESTORE_ICON only restore icon
2417 * SAVE_RESTORE_BOTH restore title and icon
Bram Moolenaar071d4272004-06-13 20:20:40 +00002418 */
2419 void
Bram Moolenaar05540972016-01-30 20:31:25 +01002420mch_restore_title(int which)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002421{
Bram Moolenaardac13472019-09-16 21:06:21 +02002422 int do_push_pop = unix_did_set_title || did_set_icon;
Bram Moolenaare5c83282019-05-03 23:15:37 +02002423
Yegappan Lakshmanan14113fd2023-03-07 17:13:51 +00002424 // Only restore the title or icon when it has been set.
2425 // When using "oldtitle" make a copy, it might be freed halfway.
2426 char_u *title = ((which & SAVE_RESTORE_TITLE) && unix_did_set_title)
2427 ? (oldtitle ? oldtitle : p_titleold) : NULL;
2428 char_u *tofree = NULL;
2429 if (title == oldtitle && oldtitle != NULL)
2430 {
2431 tofree = vim_strsave(title);
2432 if (tofree != NULL)
2433 title = tofree;
2434 }
2435 mch_settitle(title,
Bram Moolenaar40385db2018-08-07 22:31:44 +02002436 ((which & SAVE_RESTORE_ICON) && did_set_icon) ? oldicon : NULL);
Yegappan Lakshmanan14113fd2023-03-07 17:13:51 +00002437 vim_free(tofree);
Bram Moolenaar40385db2018-08-07 22:31:44 +02002438
Bram Moolenaare5c83282019-05-03 23:15:37 +02002439 if (do_push_pop)
2440 {
2441 // pop and push from/to the stack
2442 term_pop_title(which);
2443 term_push_title(which);
2444 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002445}
2446
Bram Moolenaar071d4272004-06-13 20:20:40 +00002447
2448/*
2449 * Return TRUE if "name" looks like some xterm name.
Bram Moolenaar88456cd2022-11-18 22:14:09 +00002450 * This matches "xterm.*", thus "xterm-256color", "xterm-kitty", etc.
Bram Moolenaarafa3f1c2022-12-19 18:56:48 +00002451 * Do not consider "xterm-kitty" an xterm, it is not fully xterm compatible,
2452 * using the "xterm-kitty" terminfo entry should work better.
Bram Moolenaar3a7c85b2005-02-05 21:39:53 +00002453 * Seiichi Sato mentioned that "mlterm" works like xterm.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002454 */
2455 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002456vim_is_xterm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002457{
2458 if (name == NULL)
2459 return FALSE;
Bram Moolenaarafa3f1c2022-12-19 18:56:48 +00002460 return ((STRNICMP(name, "xterm", 5) == 0
2461 && STRNICMP(name, "xterm-kitty", 11) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002462 || STRNICMP(name, "nxterm", 6) == 0
2463 || STRNICMP(name, "kterm", 5) == 0
Bram Moolenaar3a7c85b2005-02-05 21:39:53 +00002464 || STRNICMP(name, "mlterm", 6) == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00002465 || STRNICMP(name, "rxvt", 4) == 0
Bram Moolenaar995e4af2017-09-01 20:24:03 +02002466 || STRNICMP(name, "screen.xterm", 12) == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00002467 || STRCMP(name, "builtin_xterm") == 0);
2468}
2469
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00002470#if defined(FEAT_MOUSE_XTERM) || defined(PROTO)
2471/*
2472 * Return TRUE if "name" appears to be that of a terminal
2473 * known to support the xterm-style mouse protocol.
2474 * Relies on term_is_xterm having been set to its correct value.
2475 */
2476 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002477use_xterm_like_mouse(char_u *name)
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00002478{
2479 return (name != NULL
Bram Moolenaare56132b2016-08-14 18:23:21 +02002480 && (term_is_xterm
2481 || STRNICMP(name, "screen", 6) == 0
Bram Moolenaar0ba40702016-10-12 14:50:54 +02002482 || STRNICMP(name, "tmux", 4) == 0
Bram Moolenaar48873ae2021-12-08 21:00:24 +00002483 || STRNICMP(name, "gnome", 5) == 0
Bram Moolenaare56132b2016-08-14 18:23:21 +02002484 || STRICMP(name, "st") == 0
2485 || STRNICMP(name, "st-", 3) == 0
2486 || STRNICMP(name, "stterm", 6) == 0));
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00002487}
2488#endif
2489
Bram Moolenaar071d4272004-06-13 20:20:40 +00002490/*
2491 * Return non-zero when using an xterm mouse, according to 'ttymouse'.
2492 * Return 1 for "xterm".
2493 * Return 2 for "xterm2".
Bram Moolenaarc8427482011-10-20 21:09:35 +02002494 * Return 3 for "urxvt".
Bram Moolenaar2b9578f2012-08-15 16:21:32 +02002495 * Return 4 for "sgr".
Bram Moolenaar071d4272004-06-13 20:20:40 +00002496 */
2497 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002498use_xterm_mouse(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002499{
Bram Moolenaar2b9578f2012-08-15 16:21:32 +02002500 if (ttym_flags == TTYM_SGR)
2501 return 4;
Bram Moolenaarc8427482011-10-20 21:09:35 +02002502 if (ttym_flags == TTYM_URXVT)
2503 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002504 if (ttym_flags == TTYM_XTERM2)
2505 return 2;
2506 if (ttym_flags == TTYM_XTERM)
2507 return 1;
2508 return 0;
2509}
Bram Moolenaar071d4272004-06-13 20:20:40 +00002510
Bram Moolenaar88456cd2022-11-18 22:14:09 +00002511/*
2512 * Return TRUE if "name" is an iris-ansi terminal name.
2513 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002514 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002515vim_is_iris(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002516{
2517 if (name == NULL)
2518 return FALSE;
2519 return (STRNICMP(name, "iris-ansi", 9) == 0
2520 || STRCMP(name, "builtin_iris-ansi") == 0);
2521}
2522
Dominique Pellee764d1b2023-03-12 21:20:59 +00002523#if defined(VMS) || defined(PROTO)
Bram Moolenaar88456cd2022-11-18 22:14:09 +00002524/*
2525 * Return TRUE if "name" is a vt300-like terminal name.
2526 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002527 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002528vim_is_vt300(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002529{
2530 if (name == NULL)
Bram Moolenaar88456cd2022-11-18 22:14:09 +00002531 return FALSE;
2532 // Actually all ANSI compatible terminals should be here.
2533 // Catch at least VT1xx - VT5xx
Bram Moolenaard4755bb2004-09-02 19:12:26 +00002534 return ((STRNICMP(name, "vt", 2) == 0
Bram Moolenaar88456cd2022-11-18 22:14:09 +00002535 && vim_strchr((char_u *)"12345", name[2]) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002536 || STRCMP(name, "builtin_vt320") == 0);
2537}
Dominique Pellee764d1b2023-03-12 21:20:59 +00002538#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002539
2540/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00002541 * Insert user name in s[len].
2542 * Return OK if a name found.
2543 */
2544 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002545mch_get_user_name(char_u *s, int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002546{
2547#ifdef VMS
Bram Moolenaarffb8ab02005-09-07 21:15:32 +00002548 vim_strncpy(s, (char_u *)cuserid(NULL), len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002549 return OK;
2550#else
2551 return mch_get_uname(getuid(), s, len);
2552#endif
2553}
2554
2555/*
2556 * Insert user name for "uid" in s[len].
2557 * Return OK if a name found.
2558 */
2559 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002560mch_get_uname(uid_t uid, char_u *s, int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002561{
2562#if defined(HAVE_PWD_H) && defined(HAVE_GETPWUID)
2563 struct passwd *pw;
2564
2565 if ((pw = getpwuid(uid)) != NULL
2566 && pw->pw_name != NULL && *(pw->pw_name) != NUL)
2567 {
Bram Moolenaarbbebc852005-07-18 21:47:53 +00002568 vim_strncpy(s, (char_u *)pw->pw_name, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002569 return OK;
2570 }
2571#endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01002572 sprintf((char *)s, "%d", (int)uid); // assumes s is long enough
2573 return FAIL; // a number is not a name
Bram Moolenaar071d4272004-06-13 20:20:40 +00002574}
2575
2576/*
2577 * Insert host name is s[len].
2578 */
2579
2580#ifdef HAVE_SYS_UTSNAME_H
2581 void
Bram Moolenaar05540972016-01-30 20:31:25 +01002582mch_get_host_name(char_u *s, int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002583{
2584 struct utsname vutsname;
2585
2586 if (uname(&vutsname) < 0)
2587 *s = NUL;
2588 else
Bram Moolenaarbbebc852005-07-18 21:47:53 +00002589 vim_strncpy(s, (char_u *)vutsname.nodename, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002590}
Bram Moolenaar0f873732019-12-05 20:28:46 +01002591#else // HAVE_SYS_UTSNAME_H
Bram Moolenaar071d4272004-06-13 20:20:40 +00002592
2593# ifdef HAVE_SYS_SYSTEMINFO_H
2594# define gethostname(nam, len) sysinfo(SI_HOSTNAME, nam, len)
2595# endif
2596
2597 void
Bram Moolenaard14e00e2016-01-31 17:30:51 +01002598mch_get_host_name(char_u *s, int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002599{
2600# ifdef VAXC
2601 vaxc$gethostname((char *)s, len);
2602# else
2603 gethostname((char *)s, len);
2604# endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01002605 s[len - 1] = NUL; // make sure it's terminated
Bram Moolenaar071d4272004-06-13 20:20:40 +00002606}
Bram Moolenaar0f873732019-12-05 20:28:46 +01002607#endif // HAVE_SYS_UTSNAME_H
Bram Moolenaar071d4272004-06-13 20:20:40 +00002608
2609/*
2610 * return process ID
2611 */
2612 long
Bram Moolenaar05540972016-01-30 20:31:25 +01002613mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002614{
2615 return (long)getpid();
2616}
2617
Bram Moolenaar67cf86b2019-04-28 22:25:38 +02002618/*
2619 * return TRUE if process "pid" is still running
2620 */
2621 int
Bram Moolenaar1b243ea2019-04-28 22:50:40 +02002622mch_process_running(long pid)
Bram Moolenaar67cf86b2019-04-28 22:25:38 +02002623{
Bram Moolenaar44dea9d2021-06-23 21:13:20 +02002624 // If there is no error the process must be running.
2625 if (kill(pid, 0) == 0)
2626 return TRUE;
2627#ifdef ESRCH
2628 // If the error is ESRCH then the process is not running.
2629 if (errno == ESRCH)
2630 return FALSE;
2631#endif
2632 // If the process is running and owned by another user we get EPERM. With
2633 // other errors the process might be running, assuming it is then.
2634 return TRUE;
Bram Moolenaar67cf86b2019-04-28 22:25:38 +02002635}
2636
Bram Moolenaar071d4272004-06-13 20:20:40 +00002637#if !defined(HAVE_STRERROR) && defined(USE_GETCWD)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002638 static char *
Bram Moolenaar05540972016-01-30 20:31:25 +01002639strerror(int err)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002640{
2641 extern int sys_nerr;
2642 extern char *sys_errlist[];
2643 static char er[20];
2644
2645 if (err > 0 && err < sys_nerr)
2646 return (sys_errlist[err]);
John Marriottefc41a52025-01-23 20:05:29 +01002647 snprintf(er, sizeof(er), "Error %d", err);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002648 return er;
2649}
2650#endif
2651
2652/*
Bram Moolenaar964b3742019-05-24 18:54:09 +02002653 * Get name of current directory into buffer "buf" of length "len" bytes.
2654 * "len" must be at least PATH_MAX.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002655 * Return OK for success, FAIL for failure.
2656 */
2657 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002658mch_dirname(char_u *buf, int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002659{
2660#if defined(USE_GETCWD)
2661 if (getcwd((char *)buf, len) == NULL)
2662 {
2663 STRCPY(buf, strerror(errno));
2664 return FAIL;
2665 }
2666 return OK;
2667#else
2668 return (getwd((char *)buf) != NULL ? OK : FAIL);
2669#endif
2670}
2671
Bram Moolenaar071d4272004-06-13 20:20:40 +00002672/*
Bram Moolenaar3d20ca12006-11-28 16:43:58 +00002673 * Get absolute file name into "buf[len]".
Bram Moolenaar071d4272004-06-13 20:20:40 +00002674 *
2675 * return FAIL for failure, OK for success
2676 */
2677 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002678mch_FullName(
2679 char_u *fname,
2680 char_u *buf,
2681 int len,
Bram Moolenaar0f873732019-12-05 20:28:46 +01002682 int force) // also expand when already absolute path
Bram Moolenaar071d4272004-06-13 20:20:40 +00002683{
John Marriottefc41a52025-01-23 20:05:29 +01002684 int buflen = 0;
Bram Moolenaar38323e42007-03-06 19:22:53 +00002685#ifdef HAVE_FCHDIR
Bram Moolenaar071d4272004-06-13 20:20:40 +00002686 int fd = -1;
Bram Moolenaar0f873732019-12-05 20:28:46 +01002687 static int dont_fchdir = FALSE; // TRUE when fchdir() doesn't work
Bram Moolenaar38323e42007-03-06 19:22:53 +00002688#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002689 char_u olddir[MAXPATHL];
2690 char_u *p;
2691 int retval = OK;
Bram Moolenaarbf820722008-06-21 11:12:49 +00002692#ifdef __CYGWIN__
Bram Moolenaar0f873732019-12-05 20:28:46 +01002693 char_u posix_fname[MAXPATHL]; // Cygwin docs mention MAX_PATH, but
2694 // it's not always defined
Bram Moolenaarbf820722008-06-21 11:12:49 +00002695#endif
2696
Bram Moolenaar38323e42007-03-06 19:22:53 +00002697#ifdef VMS
2698 fname = vms_fixfilename(fname);
2699#endif
2700
Bram Moolenaara2442432007-04-26 14:26:37 +00002701#ifdef __CYGWIN__
2702 /*
2703 * This helps for when "/etc/hosts" is a symlink to "c:/something/hosts".
2704 */
Bram Moolenaar0d1498e2008-06-29 12:00:49 +00002705# if CYGWIN_VERSION_DLL_MAJOR >= 1007
Bram Moolenaar0f873732019-12-05 20:28:46 +01002706 // Use CCP_RELATIVE to avoid that it sometimes returns a path that ends in
2707 // a forward slash.
Bram Moolenaar06b07342015-12-31 22:26:28 +01002708 cygwin_conv_path(CCP_WIN_A_TO_POSIX | CCP_RELATIVE,
2709 fname, posix_fname, MAXPATHL);
Bram Moolenaar0d1498e2008-06-29 12:00:49 +00002710# else
Bram Moolenaarbf820722008-06-21 11:12:49 +00002711 cygwin_conv_to_posix_path(fname, posix_fname);
Bram Moolenaar0d1498e2008-06-29 12:00:49 +00002712# endif
Bram Moolenaarbf820722008-06-21 11:12:49 +00002713 fname = posix_fname;
Bram Moolenaara2442432007-04-26 14:26:37 +00002714#endif
2715
Bram Moolenaar0f873732019-12-05 20:28:46 +01002716 // Expand it if forced or not an absolute path.
2717 // Do not do it for "/file", the result is always "/".
Bram Moolenaare3303cb2015-12-31 18:29:46 +01002718 if ((force || !mch_isFullName(fname))
2719 && ((p = vim_strrchr(fname, '/')) == NULL || p != fname))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002720 {
zeertzjq1ee74202024-07-12 07:29:14 +02002721 if (p == NULL && STRCMP(fname, "..") == 0)
2722 // Handle ".." without path separators.
2723 p = fname + 2;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002724 /*
2725 * If the file name has a path, change to that directory for a moment,
Bram Moolenaar964b3742019-05-24 18:54:09 +02002726 * and then get the directory (and get back to where we were).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002727 * This will get the correct path name with "../" things.
2728 */
Bram Moolenaare3303cb2015-12-31 18:29:46 +01002729 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002730 {
Bram Moolenaar4eaef992021-08-30 21:26:16 +02002731 if (STRCMP(p, "/..") == 0)
zeertzjq1ee74202024-07-12 07:29:14 +02002732 // For "/path/dir/.." include the "/..".
Bram Moolenaar4eaef992021-08-30 21:26:16 +02002733 p += 3;
2734
Bram Moolenaar38323e42007-03-06 19:22:53 +00002735#ifdef HAVE_FCHDIR
Bram Moolenaar071d4272004-06-13 20:20:40 +00002736 /*
2737 * Use fchdir() if possible, it's said to be faster and more
2738 * reliable. But on SunOS 4 it might not work. Check this by
2739 * doing a fchdir() right now.
2740 */
2741 if (!dont_fchdir)
2742 {
2743 fd = open(".", O_RDONLY | O_EXTRA, 0);
2744 if (fd >= 0 && fchdir(fd) < 0)
2745 {
2746 close(fd);
2747 fd = -1;
Bram Moolenaar0f873732019-12-05 20:28:46 +01002748 dont_fchdir = TRUE; // don't try again
Bram Moolenaar071d4272004-06-13 20:20:40 +00002749 }
2750 }
Bram Moolenaar38323e42007-03-06 19:22:53 +00002751#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002752
Bram Moolenaar0f873732019-12-05 20:28:46 +01002753 // Only change directory when we are sure we can return to where
2754 // we are now. After doing "su" chdir(".") might not work.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002755 if (
Bram Moolenaar38323e42007-03-06 19:22:53 +00002756#ifdef HAVE_FCHDIR
Bram Moolenaar071d4272004-06-13 20:20:40 +00002757 fd < 0 &&
Bram Moolenaar38323e42007-03-06 19:22:53 +00002758#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002759 (mch_dirname(olddir, MAXPATHL) == FAIL
2760 || mch_chdir((char *)olddir) != 0))
2761 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002762 p = NULL; // can't get current dir: don't chdir
Bram Moolenaar071d4272004-06-13 20:20:40 +00002763 retval = FAIL;
2764 }
2765 else
2766 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002767 // The directory is copied into buf[], to be able to remove
2768 // the file name without changing it (could be a string in
2769 // read-only memory)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002770 if (p - fname >= len)
2771 retval = FAIL;
2772 else
2773 {
Bram Moolenaarbbebc852005-07-18 21:47:53 +00002774 vim_strncpy(buf, fname, p - fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002775 if (mch_chdir((char *)buf))
Bram Moolenaarc6376c72021-10-03 19:29:48 +01002776 {
2777 // Path does not exist (yet). For a full path fail,
2778 // will use the path as-is. For a relative path use
2779 // the current directory and append the file name.
2780 if (mch_isFullName(fname))
2781 retval = FAIL;
2782 else
2783 p = NULL;
2784 }
Bram Moolenaar4eaef992021-08-30 21:26:16 +02002785 else if (*p == '/')
Bram Moolenaar071d4272004-06-13 20:20:40 +00002786 fname = p + 1;
Bram Moolenaar4eaef992021-08-30 21:26:16 +02002787 else
2788 fname = p;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002789 *buf = NUL;
2790 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002791 }
2792 }
2793 if (mch_dirname(buf, len) == FAIL)
2794 {
2795 retval = FAIL;
2796 *buf = NUL;
2797 }
2798 if (p != NULL)
2799 {
John Marriottefc41a52025-01-23 20:05:29 +01002800 int l;
2801
Bram Moolenaar38323e42007-03-06 19:22:53 +00002802#ifdef HAVE_FCHDIR
Bram Moolenaar071d4272004-06-13 20:20:40 +00002803 if (fd >= 0)
2804 {
Bram Moolenaar25724922009-07-14 15:38:41 +00002805 if (p_verbose >= 5)
2806 {
2807 verbose_enter();
Bram Moolenaar32526b32019-01-19 17:43:09 +01002808 msg("fchdir() to previous dir");
Bram Moolenaar25724922009-07-14 15:38:41 +00002809 verbose_leave();
2810 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002811 l = fchdir(fd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002812 }
2813 else
Bram Moolenaar38323e42007-03-06 19:22:53 +00002814#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002815 l = mch_chdir((char *)olddir);
2816 if (l != 0)
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00002817 emsg(_(e_cannot_go_back_to_previous_directory));
Bram Moolenaar071d4272004-06-13 20:20:40 +00002818 }
itchyny051a40c2021-10-20 10:00:05 +01002819#ifdef HAVE_FCHDIR
2820 if (fd >= 0)
2821 close(fd);
2822#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002823
John Marriottefc41a52025-01-23 20:05:29 +01002824 buflen = (int)STRLEN(buf);
2825 if (buflen >= len - 1)
Bram Moolenaar0f873732019-12-05 20:28:46 +01002826 retval = FAIL; // no space for trailing "/"
Bram Moolenaar38323e42007-03-06 19:22:53 +00002827#ifndef VMS
John Marriottefc41a52025-01-23 20:05:29 +01002828 else if (buflen > 0 && buf[buflen - 1] != PATHSEP && *fname != NUL
Bram Moolenaar071d4272004-06-13 20:20:40 +00002829 && STRCMP(fname, ".") != 0)
John Marriottefc41a52025-01-23 20:05:29 +01002830 {
2831 STRCPY(buf + buflen, PATHSEPSTR);
2832 buflen += STRLEN_LITERAL(PATHSEPSTR);
2833 }
Bram Moolenaar38323e42007-03-06 19:22:53 +00002834#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002835 }
Bram Moolenaar3d20ca12006-11-28 16:43:58 +00002836
John Marriottefc41a52025-01-23 20:05:29 +01002837 if (buflen == 0)
2838 buflen = (int)STRLEN(buf);
2839
Bram Moolenaar0f873732019-12-05 20:28:46 +01002840 // Catch file names which are too long.
John Marriottefc41a52025-01-23 20:05:29 +01002841 if (retval == FAIL || (int)(buflen + STRLEN(fname)) >= len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002842 return FAIL;
2843
Bram Moolenaar0f873732019-12-05 20:28:46 +01002844 // Do not append ".", "/dir/." is equal to "/dir".
Bram Moolenaar071d4272004-06-13 20:20:40 +00002845 if (STRCMP(fname, ".") != 0)
John Marriottefc41a52025-01-23 20:05:29 +01002846 STRCPY(buf + buflen, fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002847
2848 return OK;
2849}
2850
2851/*
2852 * Return TRUE if "fname" does not depend on the current directory.
2853 */
2854 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002855mch_isFullName(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002856{
Bram Moolenaara06ecab2016-07-16 14:47:36 +02002857#ifdef VMS
Bram Moolenaar071d4272004-06-13 20:20:40 +00002858 return ( fname[0] == '/' || fname[0] == '.' ||
2859 strchr((char *)fname,':') || strchr((char *)fname,'"') ||
2860 (strchr((char *)fname,'[') && strchr((char *)fname,']'))||
2861 (strchr((char *)fname,'<') && strchr((char *)fname,'>')) );
Bram Moolenaara06ecab2016-07-16 14:47:36 +02002862#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002863 return (*fname == '/' || *fname == '~');
Bram Moolenaar071d4272004-06-13 20:20:40 +00002864#endif
2865}
2866
Bram Moolenaar24552be2005-12-10 20:17:30 +00002867#if defined(USE_FNAME_CASE) || defined(PROTO)
2868/*
2869 * Set the case of the file name, if it already exists. This will cause the
2870 * file name to remain exactly the same.
Bram Moolenaarc2a27c32007-12-01 16:19:33 +00002871 * Only required for file systems where case is ignored and preserved.
Bram Moolenaar24552be2005-12-10 20:17:30 +00002872 */
Bram Moolenaar24552be2005-12-10 20:17:30 +00002873 void
Bram Moolenaar05540972016-01-30 20:31:25 +01002874fname_case(
2875 char_u *name,
Bram Moolenaar0f873732019-12-05 20:28:46 +01002876 int len UNUSED) // buffer size, only used when name gets longer
Bram Moolenaar24552be2005-12-10 20:17:30 +00002877{
2878 struct stat st;
2879 char_u *slash, *tail;
John Marriottefc41a52025-01-23 20:05:29 +01002880 size_t taillen;
Bram Moolenaar24552be2005-12-10 20:17:30 +00002881 DIR *dirp;
2882 struct dirent *dp;
2883
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00002884 if (mch_lstat((char *)name, &st) < 0)
2885 return;
2886
2887 // Open the directory where the file is located.
2888 slash = vim_strrchr(name, '/');
2889 if (slash == NULL)
Bram Moolenaar24552be2005-12-10 20:17:30 +00002890 {
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00002891 dirp = opendir(".");
2892 tail = name;
2893 }
2894 else
2895 {
2896 *slash = NUL;
2897 dirp = opendir((char *)name);
2898 *slash = '/';
2899 tail = slash + 1;
2900 }
Bram Moolenaar24552be2005-12-10 20:17:30 +00002901
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00002902 if (dirp == NULL)
2903 return;
2904
John Marriottefc41a52025-01-23 20:05:29 +01002905 taillen = STRLEN(tail);
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00002906 while ((dp = readdir(dirp)) != NULL)
2907 {
2908 // Only accept names that differ in case and are the same byte
2909 // length. TODO: accept different length name.
2910 if (STRICMP(tail, dp->d_name) == 0
John Marriottefc41a52025-01-23 20:05:29 +01002911 && taillen == STRLEN(dp->d_name))
Bram Moolenaar24552be2005-12-10 20:17:30 +00002912 {
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00002913 char_u newname[MAXPATHL + 1];
2914 struct stat st2;
2915
2916 // Verify the inode is equal.
2917 vim_strncpy(newname, name, MAXPATHL);
2918 vim_strncpy(newname + (tail - name), (char_u *)dp->d_name,
2919 MAXPATHL - (tail - name));
2920 if (mch_lstat((char *)newname, &st2) >= 0
2921 && st.st_ino == st2.st_ino
2922 && st.st_dev == st2.st_dev)
Bram Moolenaar24552be2005-12-10 20:17:30 +00002923 {
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00002924 STRCPY(tail, dp->d_name);
2925 break;
Bram Moolenaar24552be2005-12-10 20:17:30 +00002926 }
Bram Moolenaar24552be2005-12-10 20:17:30 +00002927 }
2928 }
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00002929
2930 closedir(dirp);
Bram Moolenaar24552be2005-12-10 20:17:30 +00002931}
2932#endif
2933
Bram Moolenaar071d4272004-06-13 20:20:40 +00002934/*
2935 * Get file permissions for 'name'.
2936 * Returns -1 when it doesn't exist.
2937 */
2938 long
Bram Moolenaar05540972016-01-30 20:31:25 +01002939mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002940{
2941 struct stat statb;
2942
Bram Moolenaar0f873732019-12-05 20:28:46 +01002943 // Keep the #ifdef outside of stat(), it may be a macro.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002944#ifdef VMS
2945 if (stat((char *)vms_fixfilename(name), &statb))
2946#else
2947 if (stat((char *)name, &statb))
2948#endif
2949 return -1;
Bram Moolenaar708f62c2007-08-11 20:24:10 +00002950#ifdef __INTERIX
Bram Moolenaar0f873732019-12-05 20:28:46 +01002951 // The top bit makes the value negative, which means the file doesn't
2952 // exist. Remove the bit, we don't use it.
Bram Moolenaar708f62c2007-08-11 20:24:10 +00002953 return statb.st_mode & ~S_ADDACE;
2954#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002955 return statb.st_mode;
Bram Moolenaar708f62c2007-08-11 20:24:10 +00002956#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002957}
2958
2959/*
Bram Moolenaarcd142e32017-11-16 17:03:45 +01002960 * Set file permission for "name" to "perm".
2961 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002962 */
2963 int
Bram Moolenaar05540972016-01-30 20:31:25 +01002964mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002965{
2966 return (chmod((char *)
2967#ifdef VMS
2968 vms_fixfilename(name),
2969#else
2970 name,
2971#endif
2972 (mode_t)perm) == 0 ? OK : FAIL);
2973}
2974
Bram Moolenaarcd142e32017-11-16 17:03:45 +01002975#if defined(HAVE_FCHMOD) || defined(PROTO)
2976/*
2977 * Set file permission for open file "fd" to "perm".
2978 * Return FAIL for failure, OK otherwise.
2979 */
2980 int
2981mch_fsetperm(int fd, long perm)
2982{
2983 return (fchmod(fd, (mode_t)perm) == 0 ? OK : FAIL);
2984}
2985#endif
2986
Bram Moolenaar071d4272004-06-13 20:20:40 +00002987#if defined(HAVE_ACL) || defined(PROTO)
2988# ifdef HAVE_SYS_ACL_H
2989# include <sys/acl.h>
2990# endif
2991# ifdef HAVE_SYS_ACCESS_H
2992# include <sys/access.h>
2993# endif
2994
2995# ifdef HAVE_SOLARIS_ACL
2996typedef struct vim_acl_solaris_T {
2997 int acl_cnt;
2998 aclent_t *acl_entry;
2999} vim_acl_solaris_T;
3000# endif
3001
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00003002#if defined(HAVE_SELINUX) || defined(PROTO)
3003/*
3004 * Copy security info from "from_file" to "to_file".
3005 */
3006 void
Bram Moolenaar05540972016-01-30 20:31:25 +01003007mch_copy_sec(char_u *from_file, char_u *to_file)
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00003008{
3009 if (from_file == NULL)
3010 return;
3011
3012 if (selinux_enabled == -1)
3013 selinux_enabled = is_selinux_enabled();
3014
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003015 if (selinux_enabled <= 0)
3016 return;
3017
3018 // Use "char *" instead of "security_context_t" to avoid a deprecation
3019 // warning.
3020 char *from_context = NULL;
3021 char *to_context = NULL;
3022
3023 if (getfilecon((char *)from_file, &from_context) < 0)
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00003024 {
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003025 // If the filesystem doesn't support extended attributes,
3026 // the original had no special security context and the
3027 // target cannot have one either.
3028 if (errno == EOPNOTSUPP)
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00003029 return;
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003030
3031 msg_puts(_("\nCould not get security context for "));
3032 msg_outtrans(from_file);
3033 msg_putchar('\n');
3034 return;
3035 }
3036 if (getfilecon((char *)to_file, &to_context) < 0)
3037 {
3038 msg_puts(_("\nCould not get security context for "));
3039 msg_outtrans(to_file);
3040 msg_putchar('\n');
3041 freecon (from_context);
3042 return ;
3043 }
3044 if (strcmp(from_context, to_context) != 0)
3045 {
3046 if (setfilecon((char *)to_file, from_context) < 0)
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00003047 {
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003048 msg_puts(_("\nCould not set security context for "));
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00003049 msg_outtrans(to_file);
3050 msg_putchar('\n');
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00003051 }
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00003052 }
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003053 freecon(to_context);
3054 freecon(from_context);
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00003055}
Bram Moolenaar0f873732019-12-05 20:28:46 +01003056#endif // HAVE_SELINUX
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00003057
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02003058#if defined(HAVE_SMACK) && !defined(PROTO)
3059/*
3060 * Copy security info from "from_file" to "to_file".
3061 */
3062 void
Bram Moolenaard14e00e2016-01-31 17:30:51 +01003063mch_copy_sec(char_u *from_file, char_u *to_file)
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02003064{
Bram Moolenaar62f167f2014-04-23 12:52:40 +02003065 static const char * const smack_copied_attributes[] =
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02003066 {
3067 XATTR_NAME_SMACK,
3068 XATTR_NAME_SMACKEXEC,
3069 XATTR_NAME_SMACKMMAP
3070 };
3071
3072 char buffer[SMACK_LABEL_LEN];
3073 const char *name;
3074 int index;
3075 int ret;
3076 ssize_t size;
3077
3078 if (from_file == NULL)
3079 return;
3080
Christian Brabandt5a679b22023-10-16 10:17:13 +02003081 size = listxattr((char *)from_file, NULL, 0);
3082 // not supported or no attributes to copy
Paul R. Tagliamonte14759de2024-03-10 08:35:10 +01003083 if (size <= 0)
Christian Brabandt5a679b22023-10-16 10:17:13 +02003084 return;
3085
John Marriottefc41a52025-01-23 20:05:29 +01003086 for (index = 0 ; index < (int)ARRAY_LENGTH(smack_copied_attributes); index++)
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02003087 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01003088 // get the name of the attribute to copy
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02003089 name = smack_copied_attributes[index];
3090
Bram Moolenaar0f873732019-12-05 20:28:46 +01003091 // get the value of the attribute in buffer
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02003092 size = getxattr((char*)from_file, name, buffer, sizeof(buffer));
3093 if (size >= 0)
3094 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01003095 // copy the attribute value of buffer
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02003096 ret = setxattr((char*)to_file, name, buffer, (size_t)size, 0);
3097 if (ret < 0)
3098 {
Bram Moolenaar4a1314c2016-01-27 20:47:18 +01003099 vim_snprintf((char *)IObuff, IOSIZE,
3100 _("Could not set security context %s for %s"),
3101 name, to_file);
3102 msg_outtrans(IObuff);
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02003103 msg_putchar('\n');
3104 }
3105 }
3106 else
3107 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01003108 // what reason of not having the attribute value?
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02003109 switch (errno)
3110 {
3111 case ENOTSUP:
Bram Moolenaar0f873732019-12-05 20:28:46 +01003112 // extended attributes aren't supported or enabled
3113 // should a message be echoed? not sure...
3114 return; // leave because it isn't useful to continue
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02003115
3116 case ERANGE:
3117 default:
Bram Moolenaar0f873732019-12-05 20:28:46 +01003118 // no enough size OR unexpected error
Bram Moolenaar4a1314c2016-01-27 20:47:18 +01003119 vim_snprintf((char *)IObuff, IOSIZE,
3120 _("Could not get security context %s for %s. Removing it!"),
3121 name, from_file);
Bram Moolenaar32526b32019-01-19 17:43:09 +01003122 msg_puts((char *)IObuff);
Bram Moolenaar4a1314c2016-01-27 20:47:18 +01003123 msg_putchar('\n');
Bram Moolenaar0f873732019-12-05 20:28:46 +01003124 // FALLTHROUGH to remove the attribute
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02003125
3126 case ENODATA:
Bram Moolenaar0f873732019-12-05 20:28:46 +01003127 // no attribute of this name
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02003128 ret = removexattr((char*)to_file, name);
Bram Moolenaar0f873732019-12-05 20:28:46 +01003129 // Silently ignore errors, apparently this happens when
3130 // smack is not actually being used.
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02003131 break;
3132 }
3133 }
3134 }
3135}
Bram Moolenaar0f873732019-12-05 20:28:46 +01003136#endif // HAVE_SMACK
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02003137
Christian Brabandte085dfd2023-09-30 12:49:18 +02003138#ifdef FEAT_XATTR
3139/*
3140 * Copy extended attributes from_file to to_file
3141 */
3142 void
3143mch_copy_xattr(char_u *from_file, char_u *to_file)
3144{
3145 char *xattr_buf;
Paul R. Tagliamonte14759de2024-03-10 08:35:10 +01003146 ssize_t size;
3147 ssize_t tsize;
Christian Brabandte085dfd2023-09-30 12:49:18 +02003148 ssize_t keylen, vallen, max_vallen = 0;
3149 char *key;
3150 char *val = NULL;
3151 char *errmsg = NULL;
3152
3153 if (from_file == NULL)
3154 return;
3155
3156 // get the length of the extended attributes
3157 size = listxattr((char *)from_file, NULL, 0);
3158 // not supported or no attributes to copy
Paul R. Tagliamonte14759de2024-03-10 08:35:10 +01003159 if (size <= 0)
Christian Brabandte085dfd2023-09-30 12:49:18 +02003160 return;
3161 xattr_buf = (char*)alloc(size);
3162 if (xattr_buf == NULL)
3163 return;
3164 size = listxattr((char *)from_file, xattr_buf, size);
3165 tsize = size;
3166
3167 errno = 0;
3168
3169 for (int round = 0; round < 2; round++)
3170 {
3171
3172 key = xattr_buf;
3173 if (round == 1)
3174 size = tsize;
3175
3176 while (size > 0)
3177 {
3178 vallen = getxattr((char *)from_file, key,
3179 val, round ? max_vallen : 0);
3180 // only set the attribute in the second round
3181 if (vallen >= 0 && round &&
3182 setxattr((char *)to_file, key, val, vallen, 0) == 0)
3183 ;
3184 else if (errno)
3185 {
3186 switch (errno)
3187 {
3188 case E2BIG:
3189 errmsg = e_xattr_e2big;
3190 goto error_exit;
3191 case ENOTSUP:
Gene C993b1752023-10-02 22:42:26 +02003192 case EACCES:
3193 case EPERM:
3194 break;
Christian Brabandte085dfd2023-09-30 12:49:18 +02003195 case ERANGE:
3196 errmsg = e_xattr_erange;
3197 goto error_exit;
3198 default:
3199 errmsg = e_xattr_other;
3200 goto error_exit;
3201 }
3202 }
3203
3204 if (round == 0 && vallen > max_vallen)
3205 max_vallen = vallen;
3206
3207 // add one for terminating null
3208 keylen = STRLEN(key) + 1;
3209 size -= keylen;
3210 key += keylen;
3211 }
3212 if (round)
3213 break;
3214
3215 val = (char*)alloc(max_vallen + 1);
3216 if (val == NULL)
3217 goto error_exit;
3218
3219 }
3220error_exit:
3221 vim_free(xattr_buf);
3222 vim_free(val);
3223
3224 if (errmsg != NULL)
zeertzjq7ece0362023-10-01 09:07:14 +02003225 emsg(_(errmsg));
Christian Brabandte085dfd2023-09-30 12:49:18 +02003226}
3227#endif
3228
Bram Moolenaar071d4272004-06-13 20:20:40 +00003229/*
3230 * Return a pointer to the ACL of file "fname" in allocated memory.
3231 * Return NULL if the ACL is not available for whatever reason.
3232 */
3233 vim_acl_T
Bram Moolenaar05540972016-01-30 20:31:25 +01003234mch_get_acl(char_u *fname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003235{
3236 vim_acl_T ret = NULL;
3237#ifdef HAVE_POSIX_ACL
3238 ret = (vim_acl_T)acl_get_file((char *)fname, ACL_TYPE_ACCESS);
3239#else
Bram Moolenaar8d462f92012-02-05 22:51:33 +01003240#ifdef HAVE_SOLARIS_ZFS_ACL
3241 acl_t *aclent;
3242
3243 if (acl_get((char *)fname, 0, &aclent) < 0)
3244 return NULL;
3245 ret = (vim_acl_T)aclent;
3246#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00003247#ifdef HAVE_SOLARIS_ACL
3248 vim_acl_solaris_T *aclent;
3249
3250 aclent = malloc(sizeof(vim_acl_solaris_T));
John Marriottefc41a52025-01-23 20:05:29 +01003251 if (aclent == NULL)
3252 return NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003253 if ((aclent->acl_cnt = acl((char *)fname, GETACLCNT, 0, NULL)) < 0)
3254 {
3255 free(aclent);
3256 return NULL;
3257 }
3258 aclent->acl_entry = malloc(aclent->acl_cnt * sizeof(aclent_t));
John Marriottefc41a52025-01-23 20:05:29 +01003259 if (aclent->acl_entry == NULL)
3260 {
3261 free(aclent);
3262 return NULL;
3263 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003264 if (acl((char *)fname, GETACL, aclent->acl_cnt, aclent->acl_entry) < 0)
3265 {
3266 free(aclent->acl_entry);
3267 free(aclent);
3268 return NULL;
3269 }
3270 ret = (vim_acl_T)aclent;
3271#else
3272#if defined(HAVE_AIX_ACL)
3273 int aclsize;
3274 struct acl *aclent;
3275
3276 aclsize = sizeof(struct acl);
3277 aclent = malloc(aclsize);
John Marriottefc41a52025-01-23 20:05:29 +01003278 if (aclent == NULL)
3279 return NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003280 if (statacl((char *)fname, STX_NORMAL, aclent, aclsize) < 0)
3281 {
3282 if (errno == ENOSPC)
3283 {
3284 aclsize = aclent->acl_len;
3285 aclent = realloc(aclent, aclsize);
John Marriottefc41a52025-01-23 20:05:29 +01003286 if (aclent == NULL || statacl((char *)fname, STX_NORMAL, aclent, aclsize) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003287 {
3288 free(aclent);
3289 return NULL;
3290 }
3291 }
3292 else
3293 {
3294 free(aclent);
3295 return NULL;
3296 }
3297 }
3298 ret = (vim_acl_T)aclent;
Bram Moolenaar0f873732019-12-05 20:28:46 +01003299#endif // HAVE_AIX_ACL
3300#endif // HAVE_SOLARIS_ACL
3301#endif // HAVE_SOLARIS_ZFS_ACL
3302#endif // HAVE_POSIX_ACL
Bram Moolenaar071d4272004-06-13 20:20:40 +00003303 return ret;
3304}
3305
3306/*
3307 * Set the ACL of file "fname" to "acl" (unless it's NULL).
3308 */
3309 void
Bram Moolenaar05540972016-01-30 20:31:25 +01003310mch_set_acl(char_u *fname UNUSED, vim_acl_T aclent)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003311{
3312 if (aclent == NULL)
3313 return;
3314#ifdef HAVE_POSIX_ACL
3315 acl_set_file((char *)fname, ACL_TYPE_ACCESS, (acl_t)aclent);
3316#else
Bram Moolenaar8d462f92012-02-05 22:51:33 +01003317#ifdef HAVE_SOLARIS_ZFS_ACL
3318 acl_set((char *)fname, (acl_t *)aclent);
3319#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00003320#ifdef HAVE_SOLARIS_ACL
3321 acl((char *)fname, SETACL, ((vim_acl_solaris_T *)aclent)->acl_cnt,
3322 ((vim_acl_solaris_T *)aclent)->acl_entry);
3323#else
3324#ifdef HAVE_AIX_ACL
3325 chacl((char *)fname, aclent, ((struct acl *)aclent)->acl_len);
Bram Moolenaar0f873732019-12-05 20:28:46 +01003326#endif // HAVE_AIX_ACL
3327#endif // HAVE_SOLARIS_ACL
3328#endif // HAVE_SOLARIS_ZFS_ACL
3329#endif // HAVE_POSIX_ACL
Bram Moolenaar071d4272004-06-13 20:20:40 +00003330}
3331
3332 void
Bram Moolenaar05540972016-01-30 20:31:25 +01003333mch_free_acl(vim_acl_T aclent)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003334{
3335 if (aclent == NULL)
3336 return;
3337#ifdef HAVE_POSIX_ACL
3338 acl_free((acl_t)aclent);
3339#else
Bram Moolenaar8d462f92012-02-05 22:51:33 +01003340#ifdef HAVE_SOLARIS_ZFS_ACL
3341 acl_free((acl_t *)aclent);
3342#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00003343#ifdef HAVE_SOLARIS_ACL
3344 free(((vim_acl_solaris_T *)aclent)->acl_entry);
3345 free(aclent);
3346#else
3347#ifdef HAVE_AIX_ACL
3348 free(aclent);
Bram Moolenaar0f873732019-12-05 20:28:46 +01003349#endif // HAVE_AIX_ACL
3350#endif // HAVE_SOLARIS_ACL
3351#endif // HAVE_SOLARIS_ZFS_ACL
3352#endif // HAVE_POSIX_ACL
Bram Moolenaar071d4272004-06-13 20:20:40 +00003353}
3354#endif
3355
3356/*
3357 * Set hidden flag for "name".
3358 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003359 void
Bram Moolenaar05540972016-01-30 20:31:25 +01003360mch_hide(char_u *name UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003361{
Bram Moolenaar0f873732019-12-05 20:28:46 +01003362 // can't hide a file
Bram Moolenaar071d4272004-06-13 20:20:40 +00003363}
3364
3365/*
Bram Moolenaar43a34f92016-01-17 15:56:34 +01003366 * return TRUE if "name" is a directory or a symlink to a directory
Bram Moolenaar071d4272004-06-13 20:20:40 +00003367 * return FALSE if "name" is not a directory
3368 * return FALSE for error
3369 */
3370 int
Bram Moolenaar05540972016-01-30 20:31:25 +01003371mch_isdir(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003372{
3373 struct stat statb;
3374
Bram Moolenaar0f873732019-12-05 20:28:46 +01003375 if (*name == NUL) // Some stat()s don't flag "" as an error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003376 return FALSE;
3377 if (stat((char *)name, &statb))
3378 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003379 return (S_ISDIR(statb.st_mode) ? TRUE : FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003380}
3381
Bram Moolenaar43a34f92016-01-17 15:56:34 +01003382/*
3383 * return TRUE if "name" is a directory, NOT a symlink to a directory
3384 * return FALSE if "name" is not a directory
3385 * return FALSE for error
3386 */
3387 int
Bram Moolenaar05540972016-01-30 20:31:25 +01003388mch_isrealdir(char_u *name)
Bram Moolenaar43a34f92016-01-17 15:56:34 +01003389{
3390 struct stat statb;
3391
Bram Moolenaar0f873732019-12-05 20:28:46 +01003392 if (*name == NUL) // Some stat()s don't flag "" as an error.
Bram Moolenaar43a34f92016-01-17 15:56:34 +01003393 return FALSE;
Bram Moolenaarde5e2c22016-11-04 20:35:31 +01003394 if (mch_lstat((char *)name, &statb))
Bram Moolenaar43a34f92016-01-17 15:56:34 +01003395 return FALSE;
Bram Moolenaar43a34f92016-01-17 15:56:34 +01003396 return (S_ISDIR(statb.st_mode) ? TRUE : FALSE);
Bram Moolenaar43a34f92016-01-17 15:56:34 +01003397}
3398
Bram Moolenaar071d4272004-06-13 20:20:40 +00003399/*
3400 * Return 1 if "name" is an executable file, 0 if not or it doesn't exist.
3401 */
3402 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01003403executable_file(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003404{
3405 struct stat st;
3406
3407 if (stat((char *)name, &st))
3408 return 0;
Bram Moolenaar206f0112014-03-12 16:51:55 +01003409#ifdef VMS
Bram Moolenaar0f873732019-12-05 20:28:46 +01003410 // Like on Unix system file can have executable rights but not necessarily
3411 // be an executable, but on Unix is not a default for an ordinary file to
3412 // have an executable flag - on VMS it is in most cases.
3413 // Therefore, this check does not have any sense - let keep us to the
3414 // conventions instead:
3415 // *.COM and *.EXE files are the executables - the rest are not. This is
Dominique Pelleaf4a61a2021-12-27 17:21:41 +00003416 // not ideal but better than it was.
Bram Moolenaar206f0112014-03-12 16:51:55 +01003417 int vms_executable = 0;
3418 if (S_ISREG(st.st_mode) && mch_access((char *)name, X_OK) == 0)
3419 {
3420 if (strstr(vms_tolower((char*)name),".exe") != NULL
3421 || strstr(vms_tolower((char*)name),".com")!= NULL)
3422 vms_executable = 1;
3423 }
3424 return vms_executable;
3425#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00003426 return S_ISREG(st.st_mode) && mch_access((char *)name, X_OK) == 0;
Bram Moolenaar206f0112014-03-12 16:51:55 +01003427#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003428}
3429
3430/*
Bram Moolenaar2fcf6682017-03-11 20:03:42 +01003431 * Return TRUE if "name" can be found in $PATH and executed, FALSE if not.
Bram Moolenaarb5971142015-03-21 17:32:19 +01003432 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003433 * Return -1 if unknown.
3434 */
3435 int
Bram Moolenaar05540972016-01-30 20:31:25 +01003436mch_can_exe(char_u *name, char_u **path, int use_path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003437{
3438 char_u *buf;
John Marriottefc41a52025-01-23 20:05:29 +01003439 size_t bufsize;
3440 size_t buflen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003441 char_u *p, *e;
John Marriottefc41a52025-01-23 20:05:29 +01003442 char_u *p_end;
3443 size_t elen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003444 int retval;
3445
Bram Moolenaar0f873732019-12-05 20:28:46 +01003446 // When "use_path" is false and if it's an absolute or relative path don't
3447 // need to use $PATH.
Bram Moolenaard08b8c42019-07-24 14:59:45 +02003448 if (!use_path || gettail(name) != name)
Bram Moolenaar206f0112014-03-12 16:51:55 +01003449 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01003450 // There must be a path separator, files in the current directory
3451 // can't be executed.
Bram Moolenaard08b8c42019-07-24 14:59:45 +02003452 if ((use_path || gettail(name) != name) && executable_file(name))
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003453 {
3454 if (path != NULL)
3455 {
Bram Moolenaar43663192017-03-05 14:29:12 +01003456 if (name[0] != '/')
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003457 *path = FullName_save(name, TRUE);
3458 else
3459 *path = vim_strsave(name);
3460 }
3461 return TRUE;
3462 }
3463 return FALSE;
Bram Moolenaar206f0112014-03-12 16:51:55 +01003464 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003465
3466 p = (char_u *)getenv("PATH");
3467 if (p == NULL || *p == NUL)
3468 return -1;
John Marriottefc41a52025-01-23 20:05:29 +01003469 p_end = p + STRLEN(p);
3470 bufsize = STRLEN(name) + (size_t)(p_end - p) + 2;
3471 buf = alloc(bufsize);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003472 if (buf == NULL)
3473 return -1;
3474
3475 /*
3476 * Walk through all entries in $PATH to check if "name" exists there and
3477 * is an executable file.
3478 */
3479 for (;;)
3480 {
3481 e = (char_u *)strchr((char *)p, ':');
3482 if (e == NULL)
John Marriottefc41a52025-01-23 20:05:29 +01003483 e = p_end;
3484 elen = (size_t)(e - p);
3485 if (elen <= 1) // empty entry means current dir
Bram Moolenaar071d4272004-06-13 20:20:40 +00003486 {
John Marriottefc41a52025-01-23 20:05:29 +01003487 p = (char_u *)"./";
3488 elen = STRLEN_LITERAL("./");
Bram Moolenaar071d4272004-06-13 20:20:40 +00003489 }
John Marriottefc41a52025-01-23 20:05:29 +01003490 buflen = vim_snprintf((char *)buf, bufsize, "%.*s%s%s",
3491 (int)elen,
3492 p,
3493 (after_pathsep(p, p + elen)) ? "" : PATHSEPSTR,
3494 name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003495 retval = executable_file(buf);
3496 if (retval == 1)
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003497 {
3498 if (path != NULL)
3499 {
Bram Moolenaar43663192017-03-05 14:29:12 +01003500 if (buf[0] != '/')
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003501 *path = FullName_save(buf, TRUE);
3502 else
John Marriottefc41a52025-01-23 20:05:29 +01003503 *path = vim_strnsave(buf, buflen);
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003504 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003505 break;
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003506 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003507
3508 if (*e != ':')
3509 break;
3510 p = e + 1;
3511 }
3512
3513 vim_free(buf);
3514 return retval;
3515}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003516
3517/*
3518 * Check what "name" is:
3519 * NODE_NORMAL: file or directory (or doesn't exist)
3520 * NODE_WRITABLE: writable device, socket, fifo, etc.
3521 * NODE_OTHER: non-writable things
3522 */
3523 int
Bram Moolenaar05540972016-01-30 20:31:25 +01003524mch_nodetype(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003525{
3526 struct stat st;
3527
3528 if (stat((char *)name, &st))
3529 return NODE_NORMAL;
3530 if (S_ISREG(st.st_mode) || S_ISDIR(st.st_mode))
3531 return NODE_NORMAL;
Bram Moolenaar0f873732019-12-05 20:28:46 +01003532 if (S_ISBLK(st.st_mode)) // block device isn't writable
Bram Moolenaar071d4272004-06-13 20:20:40 +00003533 return NODE_OTHER;
Bram Moolenaar0f873732019-12-05 20:28:46 +01003534 // Everything else is writable?
Bram Moolenaar071d4272004-06-13 20:20:40 +00003535 return NODE_WRITABLE;
3536}
3537
3538 void
Bram Moolenaar05540972016-01-30 20:31:25 +01003539mch_early_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003540{
3541#ifdef HAVE_CHECK_STACK_GROWTH
3542 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003543
Bram Moolenaar071d4272004-06-13 20:20:40 +00003544 check_stack_growth((char *)&i);
3545
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00003546# ifdef HAVE_STACK_LIMIT
Bram Moolenaar071d4272004-06-13 20:20:40 +00003547 get_stack_limit();
3548# endif
3549
3550#endif
3551
3552 /*
3553 * Setup an alternative stack for signals. Helps to catch signals when
3554 * running out of stack space.
3555 * Use of sigaltstack() is preferred, it's more portable.
3556 * Ignore any errors.
3557 */
3558#if defined(HAVE_SIGALTSTACK) || defined(HAVE_SIGSTACK)
Zdenek Dohnalba9c23e2021-08-11 14:20:05 +02003559 signal_stack = alloc(get_signal_stack_size());
Bram Moolenaar071d4272004-06-13 20:20:40 +00003560 init_signal_stack();
3561#endif
3562}
3563
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003564#if defined(EXITFREE) || defined(PROTO)
3565 void
Bram Moolenaar05540972016-01-30 20:31:25 +01003566mch_free_mem(void)
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003567{
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00003568# if defined(FEAT_CLIPBOARD) && defined(FEAT_X11)
3569 if (clip_star.owned)
3570 clip_lose_selection(&clip_star);
3571 if (clip_plus.owned)
3572 clip_lose_selection(&clip_plus);
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003573# endif
Bram Moolenaare8208012008-06-20 09:59:25 +00003574# if defined(FEAT_X11) && defined(FEAT_XCLIPBOARD)
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003575 if (xterm_Shell != (Widget)0)
3576 XtDestroyWidget(xterm_Shell);
Bram Moolenaare8208012008-06-20 09:59:25 +00003577# ifndef LESSTIF_VERSION
Bram Moolenaar0f873732019-12-05 20:28:46 +01003578 // Lesstif crashes here, lose some memory
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003579 if (xterm_dpy != NULL)
3580 XtCloseDisplay(xterm_dpy);
3581 if (app_context != (XtAppContext)NULL)
Bram Moolenaare8208012008-06-20 09:59:25 +00003582 {
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003583 XtDestroyApplicationContext(app_context);
Bram Moolenaare8208012008-06-20 09:59:25 +00003584# ifdef FEAT_X11
Bram Moolenaar0f873732019-12-05 20:28:46 +01003585 x11_display = NULL; // freed by XtDestroyApplicationContext()
Bram Moolenaare8208012008-06-20 09:59:25 +00003586# endif
3587 }
3588# endif
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003589# endif
Bram Moolenaar0eda7ac2010-06-26 05:38:18 +02003590# if defined(FEAT_X11)
Bram Moolenaare8208012008-06-20 09:59:25 +00003591 if (x11_display != NULL
3592# ifdef FEAT_XCLIPBOARD
3593 && x11_display != xterm_dpy
3594# endif
3595 )
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00003596 XCloseDisplay(x11_display);
3597# endif
3598# if defined(HAVE_SIGALTSTACK) || defined(HAVE_SIGSTACK)
Bram Moolenaard23a8232018-02-10 18:45:26 +01003599 VIM_CLEAR(signal_stack);
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00003600# endif
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00003601 vim_free(oldtitle);
3602 vim_free(oldicon);
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003603}
3604#endif
3605
Bram Moolenaar071d4272004-06-13 20:20:40 +00003606/*
3607 * Output a newline when exiting.
3608 * Make sure the newline goes to the same stream as the text.
3609 */
3610 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01003611exit_scroll(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003612{
Bram Moolenaardf177f62005-02-22 08:39:57 +00003613 if (silent_mode)
3614 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003615 if (newline_on_exit || msg_didout)
3616 {
3617 if (msg_use_printf())
3618 {
3619 if (info_message)
3620 mch_msg("\n");
3621 else
3622 mch_errmsg("\r\n");
3623 }
3624 else
3625 out_char('\n');
3626 }
Bram Moolenaar7007e312021-03-27 12:11:33 +01003627 else if (!is_not_a_term())
Bram Moolenaar071d4272004-06-13 20:20:40 +00003628 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01003629 restore_cterm_colors(); // get original colors back
3630 msg_clr_eos_force(); // clear the rest of the display
3631 windgoto((int)Rows - 1, 0); // may have moved the cursor
Bram Moolenaar071d4272004-06-13 20:20:40 +00003632 }
3633}
3634
Bram Moolenaarb4151682020-05-11 22:13:28 +02003635#ifdef USE_GCOV_FLUSH
ichizokdee78e12021-12-09 21:08:01 +00003636# if (defined(__GNUC__) \
3637 && ((__GNUC__ == 11 && __GNUC_MINOR__ >= 1) || (__GNUC__ >= 12))) \
3638 || (defined(__clang__) && (__clang_major__ >= 12))
3639extern void __gcov_dump(void);
3640extern void __gcov_reset(void);
3641# define __gcov_flush() do { __gcov_dump(); __gcov_reset(); } while (0)
3642# else
3643extern void __gcov_flush(void);
3644# endif
Bram Moolenaarb4151682020-05-11 22:13:28 +02003645#endif
3646
Bram Moolenaar071d4272004-06-13 20:20:40 +00003647 void
Bram Moolenaar05540972016-01-30 20:31:25 +01003648mch_exit(int r)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003649{
3650 exiting = TRUE;
3651
3652#if defined(FEAT_X11) && defined(FEAT_CLIPBOARD)
3653 x11_export_final_selection();
3654#endif
3655
3656#ifdef FEAT_GUI
3657 if (!gui.in_use)
3658#endif
3659 {
3660 settmode(TMODE_COOK);
Bram Moolenaar7007e312021-03-27 12:11:33 +01003661 if (!is_not_a_term())
3662 {
3663 // restore xterm title and icon name
3664 mch_restore_title(SAVE_RESTORE_BOTH);
3665 term_pop_title(SAVE_RESTORE_BOTH);
3666 }
Bram Moolenaar651fca82021-11-29 20:39:38 +00003667
Bram Moolenaar071d4272004-06-13 20:20:40 +00003668 /*
3669 * When t_ti is not empty but it doesn't cause swapping terminal
3670 * pages, need to output a newline when msg_didout is set. But when
3671 * t_ti does swap pages it should not go to the shell page. Do this
3672 * before stoptermcap().
3673 */
3674 if (swapping_screen() && !newline_on_exit)
3675 exit_scroll();
3676
Bram Moolenaar0f873732019-12-05 20:28:46 +01003677 // Stop termcap: May need to check for T_CRV response, which
3678 // requires RAW mode.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003679 stoptermcap();
3680
3681 /*
3682 * A newline is only required after a message in the alternate screen.
3683 * This is set to TRUE by wait_return().
3684 */
3685 if (!swapping_screen() || newline_on_exit)
3686 exit_scroll();
3687
Bram Moolenaar0f873732019-12-05 20:28:46 +01003688 // Cursor may have been switched off without calling starttermcap()
3689 // when doing "vim -u vimrc" and vimrc contains ":q".
Bram Moolenaar071d4272004-06-13 20:20:40 +00003690 if (full_screen)
3691 cursor_on();
3692 }
3693 out_flush();
Bram Moolenaar0f873732019-12-05 20:28:46 +01003694 ml_close_all(TRUE); // remove all memfiles
Bram Moolenaarb4151682020-05-11 22:13:28 +02003695
3696#ifdef USE_GCOV_FLUSH
3697 // Flush coverage info before possibly being killed by a deadly signal.
3698 __gcov_flush();
3699#endif
3700
Bram Moolenaar071d4272004-06-13 20:20:40 +00003701 may_core_dump();
3702#ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00003703 if (gui.in_use)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003704 gui_exit(r);
3705#endif
Bram Moolenaardf177f62005-02-22 08:39:57 +00003706
Bram Moolenaar56718732006-03-15 22:53:57 +00003707#ifdef MACOS_CONVERT
Bram Moolenaardf177f62005-02-22 08:39:57 +00003708 mac_conv_cleanup();
3709#endif
3710
Bram Moolenaar071d4272004-06-13 20:20:40 +00003711#ifdef __QNX__
Bram Moolenaar0f873732019-12-05 20:28:46 +01003712 // A core dump won't be created if the signal handler
3713 // doesn't return, so we can't call exit()
Bram Moolenaar071d4272004-06-13 20:20:40 +00003714 if (deadly_signal != 0)
3715 return;
3716#endif
3717
Bram Moolenaar009b2592004-10-24 19:18:58 +00003718#ifdef FEAT_NETBEANS_INTG
Bram Moolenaarb26e6322010-05-22 21:34:09 +02003719 netbeans_send_disconnect();
Bram Moolenaar009b2592004-10-24 19:18:58 +00003720#endif
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00003721
3722#ifdef EXITFREE
3723 free_all_mem();
3724#endif
3725
Bram Moolenaar071d4272004-06-13 20:20:40 +00003726 exit(r);
3727}
3728
3729 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01003730may_core_dump(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003731{
3732 if (deadly_signal != 0)
3733 {
ichizok378447f2023-05-11 22:25:42 +01003734 mch_signal(deadly_signal, SIG_DFL);
Bram Moolenaar0f873732019-12-05 20:28:46 +01003735 kill(getpid(), deadly_signal); // Die using the signal we caught
Bram Moolenaar071d4272004-06-13 20:20:40 +00003736 }
3737}
3738
3739#ifndef VMS
3740
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01003741/*
3742 * Get the file descriptor to use for tty operations.
3743 */
3744 static int
3745get_tty_fd(int fd)
3746{
3747 int tty_fd = fd;
3748
3749#if defined(HAVE_SVR4_PTYS) && defined(SUN_SYSTEM)
3750 // On SunOS: Get the terminal parameters from "fd", or the slave device of
3751 // "fd" when it is a master device.
3752 if (mch_isatty(fd) > 1)
3753 {
3754 char *name;
3755
3756 name = ptsname(fd);
3757 if (name == NULL)
3758 return -1;
3759
3760 tty_fd = open(name, O_RDONLY | O_NOCTTY | O_EXTRA, 0);
3761 if (tty_fd < 0)
3762 return -1;
3763 }
3764#endif
3765 return tty_fd;
3766}
3767
3768 static int
3769mch_tcgetattr(int fd, void *term)
3770{
3771 int tty_fd;
3772 int retval = -1;
3773
3774 tty_fd = get_tty_fd(fd);
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003775 if (tty_fd < 0)
3776 return -1;
3777
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01003778#ifdef NEW_TTY_SYSTEM
3779# ifdef HAVE_TERMIOS_H
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003780 retval = tcgetattr(tty_fd, (struct termios *)term);
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01003781# else
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003782 retval = ioctl(tty_fd, TCGETA, (struct termio *)term);
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01003783# endif
3784#else
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003785 // for "old" tty systems
3786 retval = ioctl(tty_fd, TIOCGETP, (struct sgttyb *)term);
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01003787#endif
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003788 if (tty_fd != fd)
3789 close(tty_fd);
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01003790 return retval;
3791}
3792
Bram Moolenaar071d4272004-06-13 20:20:40 +00003793 void
Bram Moolenaar26e86442020-05-17 14:06:16 +02003794mch_settmode(tmode_T tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003795{
3796 static int first = TRUE;
3797
Bram Moolenaar4f44b882017-08-13 20:06:18 +02003798#ifdef NEW_TTY_SYSTEM
Bram Moolenaar071d4272004-06-13 20:20:40 +00003799# ifdef HAVE_TERMIOS_H
3800 static struct termios told;
3801 struct termios tnew;
3802# else
3803 static struct termio told;
3804 struct termio tnew;
3805# endif
3806
3807 if (first)
3808 {
3809 first = FALSE;
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01003810 mch_tcgetattr(read_cmd_fd, &told);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003811 }
3812
3813 tnew = told;
3814 if (tmode == TMODE_RAW)
3815 {
Bram Moolenaar041c7102020-05-30 18:14:57 +02003816 // ~ICRNL enables typing ^V^M
Bram Moolenaar928eec62020-05-31 13:09:47 +02003817 // ~IXON disables CTRL-S stopping output, so that it can be mapped.
Anton Sharonov49528da2024-04-14 20:02:24 +02003818 tnew.c_iflag &= ~(ICRNL |
3819 (T_XON == NULL || *T_XON == NUL ? IXON : 0));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003820 tnew.c_lflag &= ~(ICANON | ECHO | ISIG | ECHOE
Bram Moolenaare3f915d2020-07-14 23:02:44 +02003821# if defined(IEXTEN)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003822 | IEXTEN // IEXTEN enables typing ^V on SOLARIS
Bram Moolenaar071d4272004-06-13 20:20:40 +00003823# endif
3824 );
Bram Moolenaarfaf626e2019-10-24 17:43:25 +02003825# ifdef ONLCR
3826 // Don't map NL -> CR NL, we do it ourselves.
3827 // Also disable expanding tabs if possible.
3828# ifdef XTABS
3829 tnew.c_oflag &= ~(ONLCR | XTABS);
3830# else
3831# ifdef TAB3
3832 tnew.c_oflag &= ~(ONLCR | TAB3);
3833# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00003834 tnew.c_oflag &= ~ONLCR;
Bram Moolenaarfaf626e2019-10-24 17:43:25 +02003835# endif
3836# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003837# endif
Bram Moolenaarfaf626e2019-10-24 17:43:25 +02003838 tnew.c_cc[VMIN] = 1; // return after 1 char
3839 tnew.c_cc[VTIME] = 0; // don't wait
Bram Moolenaar071d4272004-06-13 20:20:40 +00003840 }
3841 else if (tmode == TMODE_SLEEP)
Bram Moolenaar40de4562016-07-01 15:03:46 +02003842 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01003843 // Also reset ICANON here, otherwise on Solaris select() won't see
3844 // typeahead characters.
Bram Moolenaar40de4562016-07-01 15:03:46 +02003845 tnew.c_lflag &= ~(ICANON | ECHO);
Bram Moolenaar0f873732019-12-05 20:28:46 +01003846 tnew.c_cc[VMIN] = 1; // return after 1 char
3847 tnew.c_cc[VTIME] = 0; // don't wait
Bram Moolenaar40de4562016-07-01 15:03:46 +02003848 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003849
3850# if defined(HAVE_TERMIOS_H)
3851 {
3852 int n = 10;
3853
Bram Moolenaar0f873732019-12-05 20:28:46 +01003854 // A signal may cause tcsetattr() to fail (e.g., SIGCONT). Retry a
3855 // few times.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003856 while (tcsetattr(read_cmd_fd, TCSANOW, &tnew) == -1
3857 && errno == EINTR && n > 0)
3858 --n;
3859 }
3860# else
3861 ioctl(read_cmd_fd, TCSETA, &tnew);
3862# endif
3863
3864#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00003865 /*
3866 * for "old" tty systems
3867 */
3868# ifndef TIOCSETN
Bram Moolenaar0f873732019-12-05 20:28:46 +01003869# define TIOCSETN TIOCSETP // for hpux 9.0
Bram Moolenaar071d4272004-06-13 20:20:40 +00003870# endif
3871 static struct sgttyb ttybold;
3872 struct sgttyb ttybnew;
3873
3874 if (first)
3875 {
3876 first = FALSE;
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01003877 mch_tcgetattr(read_cmd_fd, &ttybold);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003878 }
3879
3880 ttybnew = ttybold;
3881 if (tmode == TMODE_RAW)
3882 {
3883 ttybnew.sg_flags &= ~(CRMOD | ECHO);
3884 ttybnew.sg_flags |= RAW;
3885 }
3886 else if (tmode == TMODE_SLEEP)
3887 ttybnew.sg_flags &= ~(ECHO);
3888 ioctl(read_cmd_fd, TIOCSETN, &ttybnew);
3889#endif
Bram Moolenaar26e86442020-05-17 14:06:16 +02003890 mch_cur_tmode = tmode;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003891}
3892
3893/*
3894 * Try to get the code for "t_kb" from the stty setting
3895 *
3896 * Even if termcap claims a backspace key, the user's setting *should*
3897 * prevail. stty knows more about reality than termcap does, and if
3898 * somebody's usual erase key is DEL (which, for most BSD users, it will
3899 * be), they're going to get really annoyed if their erase key starts
3900 * doing forward deletes for no reason. (Eric Fischer)
3901 */
3902 void
Bram Moolenaar05540972016-01-30 20:31:25 +01003903get_stty(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003904{
Bram Moolenaar4f44b882017-08-13 20:06:18 +02003905 ttyinfo_T info;
3906 char_u buf[2];
3907 char_u *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003908
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003909 if (get_tty_info(read_cmd_fd, &info) != OK)
3910 return;
Bram Moolenaar4f44b882017-08-13 20:06:18 +02003911
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00003912 intr_char = info.interrupt;
3913 buf[0] = info.backspace;
3914 buf[1] = NUL;
3915 add_termcode((char_u *)"kb", buf, FALSE);
3916
3917 // If <BS> and <DEL> are now the same, redefine <DEL>.
3918 p = find_termcode((char_u *)"kD");
3919 if (p != NULL && p[0] == buf[0] && p[1] == buf[1])
3920 do_fixdel(NULL);
Bram Moolenaar4f44b882017-08-13 20:06:18 +02003921}
3922
3923/*
3924 * Obtain the characters that Backspace and Enter produce on "fd".
3925 * Returns OK or FAIL.
3926 */
3927 int
3928get_tty_info(int fd, ttyinfo_T *info)
3929{
3930#ifdef NEW_TTY_SYSTEM
Bram Moolenaar071d4272004-06-13 20:20:40 +00003931# ifdef HAVE_TERMIOS_H
3932 struct termios keys;
3933# else
3934 struct termio keys;
3935# endif
3936
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01003937 if (mch_tcgetattr(fd, &keys) != -1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003938 {
Bram Moolenaar4f44b882017-08-13 20:06:18 +02003939 info->backspace = keys.c_cc[VERASE];
3940 info->interrupt = keys.c_cc[VINTR];
3941 if (keys.c_iflag & ICRNL)
3942 info->enter = NL;
3943 else
3944 info->enter = CAR;
3945 if (keys.c_oflag & ONLCR)
3946 info->nl_does_cr = TRUE;
3947 else
3948 info->nl_does_cr = FALSE;
3949 return OK;
3950 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003951#else
Bram Moolenaar0f873732019-12-05 20:28:46 +01003952 // for "old" tty systems
Bram Moolenaar071d4272004-06-13 20:20:40 +00003953 struct sgttyb keys;
3954
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01003955 if (mch_tcgetattr(fd, &keys) != -1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003956 {
Bram Moolenaar4f44b882017-08-13 20:06:18 +02003957 info->backspace = keys.sg_erase;
3958 info->interrupt = keys.sg_kill;
3959 info->enter = CAR;
3960 info->nl_does_cr = TRUE;
3961 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003962 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003963#endif
Bram Moolenaar4f44b882017-08-13 20:06:18 +02003964 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003965}
3966
Bram Moolenaar0f873732019-12-05 20:28:46 +01003967#endif // VMS
Bram Moolenaar071d4272004-06-13 20:20:40 +00003968
Bram Moolenaar51b0f372017-11-18 18:52:04 +01003969static int mouse_ison = FALSE;
3970
Bram Moolenaar071d4272004-06-13 20:20:40 +00003971/*
Bram Moolenaarb4ad3b02022-03-30 10:57:45 +01003972 * Set mouse clicks on or off and possible enable mouse movement events.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003973 */
3974 void
Bram Moolenaar05540972016-01-30 20:31:25 +01003975mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003976{
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02003977#ifdef FEAT_BEVAL_TERM
Bram Moolenaar51b0f372017-11-18 18:52:04 +01003978 static int bevalterm_ison = FALSE;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02003979#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003980 int xterm_mouse_vers;
3981
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02003982#if defined(FEAT_X11) && defined(FEAT_XCLIPBOARD)
Bram Moolenaara06afc72018-08-27 23:24:16 +02003983 if (!on)
3984 // Make sure not tracing mouse movements. Important when a button-down
3985 // was received but no release yet.
3986 stop_xterm_trace();
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02003987#endif
Bram Moolenaara06afc72018-08-27 23:24:16 +02003988
Bram Moolenaar51b0f372017-11-18 18:52:04 +01003989 if (on == mouse_ison
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02003990#ifdef FEAT_BEVAL_TERM
Bram Moolenaar51b0f372017-11-18 18:52:04 +01003991 && p_bevalterm == bevalterm_ison
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02003992#endif
Bram Moolenaar51b0f372017-11-18 18:52:04 +01003993 )
Bram Moolenaar0f873732019-12-05 20:28:46 +01003994 // return quickly if nothing to do
Bram Moolenaar071d4272004-06-13 20:20:40 +00003995 return;
3996
3997 xterm_mouse_vers = use_xterm_mouse();
Bram Moolenaarc8427482011-10-20 21:09:35 +02003998
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02003999#ifdef FEAT_MOUSE_URXVT
Bram Moolenaar2b9578f2012-08-15 16:21:32 +02004000 if (ttym_flags == TTYM_URXVT)
4001 {
Bram Moolenaar424bcae2022-01-31 14:59:41 +00004002 out_str_nf((char_u *)(on ? "\033[?1015h" : "\033[?1015l"));
Bram Moolenaar51b0f372017-11-18 18:52:04 +01004003 mouse_ison = on;
Bram Moolenaarc8427482011-10-20 21:09:35 +02004004 }
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02004005#endif
Bram Moolenaarc8427482011-10-20 21:09:35 +02004006
Bram Moolenaar06cd14d2023-01-10 12:37:38 +00004007 if (T_CXM != NULL && *T_CXM != NUL)
4008 {
4009 term_enable_mouse(on);
4010 }
4011 else if (ttym_flags == TTYM_SGR)
Bram Moolenaar2b9578f2012-08-15 16:21:32 +02004012 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004013 // SGR mode supports columns above 223
Bram Moolenaar424bcae2022-01-31 14:59:41 +00004014 out_str_nf((char_u *)(on ? "\033[?1006h" : "\033[?1006l"));
Bram Moolenaar51b0f372017-11-18 18:52:04 +01004015 mouse_ison = on;
4016 }
Bram Moolenaar51b0f372017-11-18 18:52:04 +01004017
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02004018#ifdef FEAT_BEVAL_TERM
Bram Moolenaar51b0f372017-11-18 18:52:04 +01004019 if (bevalterm_ison != (p_bevalterm && on))
4020 {
4021 bevalterm_ison = (p_bevalterm && on);
4022 if (xterm_mouse_vers > 1 && !bevalterm_ison)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004023 // disable mouse movement events, enabling is below
Bram Moolenaar424bcae2022-01-31 14:59:41 +00004024 out_str_nf((char_u *)("\033[?1003l"));
Bram Moolenaar2b9578f2012-08-15 16:21:32 +02004025 }
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02004026#endif
Bram Moolenaar2b9578f2012-08-15 16:21:32 +02004027
Bram Moolenaar071d4272004-06-13 20:20:40 +00004028 if (xterm_mouse_vers > 0)
4029 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004030 if (on) // enable mouse events, use mouse tracking if available
Bram Moolenaar071d4272004-06-13 20:20:40 +00004031 out_str_nf((char_u *)
4032 (xterm_mouse_vers > 1
Bram Moolenaar51b0f372017-11-18 18:52:04 +01004033 ? (
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02004034#ifdef FEAT_BEVAL_TERM
Bram Moolenaar424bcae2022-01-31 14:59:41 +00004035 bevalterm_ison ? "\033[?1003h" :
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02004036#endif
Bram Moolenaar424bcae2022-01-31 14:59:41 +00004037 "\033[?1002h")
4038 : "\033[?1000h"));
Bram Moolenaar0f873732019-12-05 20:28:46 +01004039 else // disable mouse events, could probably always send the same
Bram Moolenaar071d4272004-06-13 20:20:40 +00004040 out_str_nf((char_u *)
Bram Moolenaar424bcae2022-01-31 14:59:41 +00004041 (xterm_mouse_vers > 1 ? "\033[?1002l" : "\033[?1000l"));
Bram Moolenaar51b0f372017-11-18 18:52:04 +01004042 mouse_ison = on;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004043 }
4044
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02004045#ifdef FEAT_MOUSE_DEC
Bram Moolenaar071d4272004-06-13 20:20:40 +00004046 else if (ttym_flags == TTYM_DEC)
4047 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004048 if (on) // enable mouse events
Bram Moolenaar071d4272004-06-13 20:20:40 +00004049 out_str_nf((char_u *)"\033[1;2'z\033[1;3'{");
Bram Moolenaar0f873732019-12-05 20:28:46 +01004050 else // disable mouse events
Bram Moolenaar071d4272004-06-13 20:20:40 +00004051 out_str_nf((char_u *)"\033['z");
Bram Moolenaar51b0f372017-11-18 18:52:04 +01004052 mouse_ison = on;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004053 }
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02004054#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004055
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02004056#ifdef FEAT_MOUSE_GPM
Bram Moolenaar071d4272004-06-13 20:20:40 +00004057 else
4058 {
4059 if (on)
4060 {
4061 if (gpm_open())
Bram Moolenaar51b0f372017-11-18 18:52:04 +01004062 mouse_ison = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004063 }
4064 else
4065 {
4066 gpm_close();
Bram Moolenaar51b0f372017-11-18 18:52:04 +01004067 mouse_ison = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004068 }
4069 }
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02004070#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004071
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02004072#ifdef FEAT_SYSMOUSE
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00004073 else
4074 {
4075 if (on)
4076 {
4077 if (sysmouse_open() == OK)
Bram Moolenaar51b0f372017-11-18 18:52:04 +01004078 mouse_ison = TRUE;
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00004079 }
4080 else
4081 {
4082 sysmouse_close();
Bram Moolenaar51b0f372017-11-18 18:52:04 +01004083 mouse_ison = FALSE;
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00004084 }
4085 }
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02004086#endif
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00004087
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02004088#ifdef FEAT_MOUSE_JSB
Bram Moolenaar071d4272004-06-13 20:20:40 +00004089 else
4090 {
4091 if (on)
4092 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004093 // D - Enable Mouse up/down messages
4094 // L - Enable Left Button Reporting
4095 // M - Enable Middle Button Reporting
4096 // R - Enable Right Button Reporting
4097 // K - Enable SHIFT and CTRL key Reporting
4098 // + - Enable Advanced messaging of mouse moves and up/down messages
4099 // Q - Quiet No Ack
4100 // # - Numeric value of mouse pointer required
4101 // 0 = Multiview 2000 cursor, used as standard
4102 // 1 = Windows Arrow
4103 // 2 = Windows I Beam
4104 // 3 = Windows Hour Glass
4105 // 4 = Windows Cross Hair
4106 // 5 = Windows UP Arrow
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02004107# ifdef JSBTERM_MOUSE_NONADVANCED
Bram Moolenaar0f873732019-12-05 20:28:46 +01004108 // Disables full feedback of pointer movements
Bram Moolenaar424bcae2022-01-31 14:59:41 +00004109 out_str_nf((char_u *)"\033[0~ZwLMRK1Q\033\\");
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02004110# else
Bram Moolenaar424bcae2022-01-31 14:59:41 +00004111 out_str_nf((char_u *)"\033[0~ZwLMRK+1Q\033\\");
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02004112# endif
Bram Moolenaar51b0f372017-11-18 18:52:04 +01004113 mouse_ison = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004114 }
4115 else
4116 {
Bram Moolenaar424bcae2022-01-31 14:59:41 +00004117 out_str_nf((char_u *)"\033[0~ZwQ\033\\");
Bram Moolenaar51b0f372017-11-18 18:52:04 +01004118 mouse_ison = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004119 }
4120 }
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02004121#endif
4122#ifdef FEAT_MOUSE_PTERM
Bram Moolenaar071d4272004-06-13 20:20:40 +00004123 else
4124 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004125 // 1 = button press, 6 = release, 7 = drag, 1h...9l = right button
Bram Moolenaar071d4272004-06-13 20:20:40 +00004126 if (on)
4127 out_str_nf("\033[>1h\033[>6h\033[>7h\033[>1h\033[>9l");
4128 else
4129 out_str_nf("\033[>1l\033[>6l\033[>7l\033[>1l\033[>9h");
Bram Moolenaar51b0f372017-11-18 18:52:04 +01004130 mouse_ison = on;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004131 }
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02004132#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004133}
4134
Bram Moolenaarc3719bd2017-11-18 22:13:31 +01004135#if defined(FEAT_BEVAL_TERM) || defined(PROTO)
Bram Moolenaar51b0f372017-11-18 18:52:04 +01004136/*
4137 * Called when 'balloonevalterm' changed.
4138 */
4139 void
4140mch_bevalterm_changed(void)
4141{
4142 mch_setmouse(mouse_ison);
4143}
4144#endif
4145
Bram Moolenaar071d4272004-06-13 20:20:40 +00004146/*
4147 * Set the mouse termcode, depending on the 'term' and 'ttymouse' options.
4148 */
4149 void
Bram Moolenaar05540972016-01-30 20:31:25 +01004150check_mouse_termcode(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004151{
4152# ifdef FEAT_MOUSE_XTERM
4153 if (use_xterm_mouse()
Bram Moolenaarc8427482011-10-20 21:09:35 +02004154# ifdef FEAT_MOUSE_URXVT
4155 && use_xterm_mouse() != 3
4156# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004157# ifdef FEAT_GUI
4158 && !gui.in_use
4159# endif
4160 )
4161 {
4162 set_mouse_termcode(KS_MOUSE, (char_u *)(term_is_8bit(T_NAME)
Bram Moolenaar424bcae2022-01-31 14:59:41 +00004163 ? "\233M" : "\033[M"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004164 if (*p_mouse != NUL)
4165 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004166 // force mouse off and maybe on to send possibly new mouse
4167 // activation sequence to the xterm, with(out) drag tracing.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004168 mch_setmouse(FALSE);
4169 setmouse();
4170 }
4171 }
4172 else
4173 del_mouse_termcode(KS_MOUSE);
4174# endif
4175
4176# ifdef FEAT_MOUSE_GPM
4177 if (!use_xterm_mouse()
4178# ifdef FEAT_GUI
4179 && !gui.in_use
4180# endif
4181 )
Bram Moolenaar424bcae2022-01-31 14:59:41 +00004182 set_mouse_termcode(KS_GPM_MOUSE, (char_u *)"\033MG");
Bram Moolenaarbedf0912019-05-04 16:58:45 +02004183 else
4184 del_mouse_termcode(KS_GPM_MOUSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004185# endif
4186
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00004187# ifdef FEAT_SYSMOUSE
4188 if (!use_xterm_mouse()
4189# ifdef FEAT_GUI
4190 && !gui.in_use
4191# endif
4192 )
Bram Moolenaar424bcae2022-01-31 14:59:41 +00004193 set_mouse_termcode(KS_MOUSE, (char_u *)"\033MS");
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00004194# endif
4195
Bram Moolenaar071d4272004-06-13 20:20:40 +00004196# ifdef FEAT_MOUSE_JSB
Bram Moolenaar0f873732019-12-05 20:28:46 +01004197 // Conflicts with xterm mouse: "\033[" and "\033[M" ???
Bram Moolenaar071d4272004-06-13 20:20:40 +00004198 if (!use_xterm_mouse()
4199# ifdef FEAT_GUI
4200 && !gui.in_use
4201# endif
4202 )
Bram Moolenaar424bcae2022-01-31 14:59:41 +00004203 set_mouse_termcode(KS_JSBTERM_MOUSE, (char_u *)"\033[0~zw");
Bram Moolenaar071d4272004-06-13 20:20:40 +00004204 else
4205 del_mouse_termcode(KS_JSBTERM_MOUSE);
4206# endif
4207
4208# ifdef FEAT_MOUSE_NET
Bram Moolenaar0f873732019-12-05 20:28:46 +01004209 // There is no conflict, but one may type "ESC }" from Insert mode. Don't
4210 // define it in the GUI or when using an xterm.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004211 if (!use_xterm_mouse()
4212# ifdef FEAT_GUI
4213 && !gui.in_use
4214# endif
4215 )
Bram Moolenaar424bcae2022-01-31 14:59:41 +00004216 set_mouse_termcode(KS_NETTERM_MOUSE, (char_u *)"\033}");
Bram Moolenaar071d4272004-06-13 20:20:40 +00004217 else
4218 del_mouse_termcode(KS_NETTERM_MOUSE);
4219# endif
4220
4221# ifdef FEAT_MOUSE_DEC
Bram Moolenaar0f873732019-12-05 20:28:46 +01004222 // Conflicts with xterm mouse: "\033[" and "\033[M"
Bram Moolenaarcbc17d62014-05-22 21:22:19 +02004223 if (!use_xterm_mouse()
Bram Moolenaar071d4272004-06-13 20:20:40 +00004224# ifdef FEAT_GUI
4225 && !gui.in_use
4226# endif
4227 )
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00004228 set_mouse_termcode(KS_DEC_MOUSE, (char_u *)(term_is_8bit(T_NAME)
Bram Moolenaar424bcae2022-01-31 14:59:41 +00004229 ? "\233" : "\033["));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004230 else
4231 del_mouse_termcode(KS_DEC_MOUSE);
4232# endif
4233# ifdef FEAT_MOUSE_PTERM
Bram Moolenaar0f873732019-12-05 20:28:46 +01004234 // same conflict as the dec mouse
Bram Moolenaarcbc17d62014-05-22 21:22:19 +02004235 if (!use_xterm_mouse()
Bram Moolenaar071d4272004-06-13 20:20:40 +00004236# ifdef FEAT_GUI
4237 && !gui.in_use
4238# endif
4239 )
Bram Moolenaar424bcae2022-01-31 14:59:41 +00004240 set_mouse_termcode(KS_PTERM_MOUSE, (char_u *)"\033[");
Bram Moolenaar071d4272004-06-13 20:20:40 +00004241 else
4242 del_mouse_termcode(KS_PTERM_MOUSE);
4243# endif
Bram Moolenaarc8427482011-10-20 21:09:35 +02004244# ifdef FEAT_MOUSE_URXVT
Bram Moolenaarcbc17d62014-05-22 21:22:19 +02004245 if (use_xterm_mouse() == 3
Bram Moolenaarc8427482011-10-20 21:09:35 +02004246# ifdef FEAT_GUI
4247 && !gui.in_use
4248# endif
4249 )
4250 {
4251 set_mouse_termcode(KS_URXVT_MOUSE, (char_u *)(term_is_8bit(T_NAME)
Bram Moolenaar424bcae2022-01-31 14:59:41 +00004252 ? "\233*M" : "\033[*M"));
Bram Moolenaarc8427482011-10-20 21:09:35 +02004253
4254 if (*p_mouse != NUL)
4255 {
4256 mch_setmouse(FALSE);
4257 setmouse();
4258 }
4259 }
4260 else
4261 del_mouse_termcode(KS_URXVT_MOUSE);
4262# endif
Bram Moolenaar2b9578f2012-08-15 16:21:32 +02004263 if (use_xterm_mouse() == 4
Bram Moolenaar2ace1bd2019-03-22 12:03:30 +01004264# ifdef FEAT_GUI
Bram Moolenaar2b9578f2012-08-15 16:21:32 +02004265 && !gui.in_use
Bram Moolenaar2ace1bd2019-03-22 12:03:30 +01004266# endif
Bram Moolenaar2b9578f2012-08-15 16:21:32 +02004267 )
4268 {
4269 set_mouse_termcode(KS_SGR_MOUSE, (char_u *)(term_is_8bit(T_NAME)
Bram Moolenaar424bcae2022-01-31 14:59:41 +00004270 ? "\233<*M" : "\033[<*M"));
Bram Moolenaara529ce02017-06-22 22:37:57 +02004271
4272 set_mouse_termcode(KS_SGR_MOUSE_RELEASE, (char_u *)(term_is_8bit(T_NAME)
Bram Moolenaar424bcae2022-01-31 14:59:41 +00004273 ? "\233<*m" : "\033[<*m"));
Bram Moolenaar2b9578f2012-08-15 16:21:32 +02004274
4275 if (*p_mouse != NUL)
4276 {
4277 mch_setmouse(FALSE);
4278 setmouse();
4279 }
4280 }
4281 else
Bram Moolenaara529ce02017-06-22 22:37:57 +02004282 {
Bram Moolenaar2b9578f2012-08-15 16:21:32 +02004283 del_mouse_termcode(KS_SGR_MOUSE);
Bram Moolenaara529ce02017-06-22 22:37:57 +02004284 del_mouse_termcode(KS_SGR_MOUSE_RELEASE);
4285 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004286}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004287
Bram Moolenaar071d4272004-06-13 20:20:40 +00004288#ifndef VMS
4289
4290/*
4291 * Try to get the current window size:
4292 * 1. with an ioctl(), most accurate method
4293 * 2. from the environment variables LINES and COLUMNS
4294 * 3. from the termcap
4295 * 4. keep using the old values
4296 * Return OK when size could be determined, FAIL otherwise.
4297 */
4298 int
Bram Moolenaar05540972016-01-30 20:31:25 +01004299mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004300{
4301 long rows = 0;
4302 long columns = 0;
4303 char_u *p;
4304
4305 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004306 * 1. try using an ioctl. It is the most accurate method.
4307 *
4308 * Try using TIOCGWINSZ first, some systems that have it also define
4309 * TIOCGSIZE but don't have a struct ttysize.
4310 */
4311# ifdef TIOCGWINSZ
4312 {
4313 struct winsize ws;
4314 int fd = 1;
4315
Bram Moolenaar0f873732019-12-05 20:28:46 +01004316 // When stdout is not a tty, use stdin for the ioctl().
Bram Moolenaar071d4272004-06-13 20:20:40 +00004317 if (!isatty(fd) && isatty(read_cmd_fd))
4318 fd = read_cmd_fd;
4319 if (ioctl(fd, TIOCGWINSZ, &ws) == 0)
4320 {
4321 columns = ws.ws_col;
4322 rows = ws.ws_row;
Bram Moolenaar545c8a52023-06-21 15:51:47 +01004323# ifdef FEAT_EVAL
Bram Moolenaar55f1b822023-06-21 13:42:48 +01004324 ch_log(NULL, "Got size with TIOCGWINSZ: %ld x %ld", columns, rows);
Bram Moolenaar545c8a52023-06-21 15:51:47 +01004325# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004326 }
4327 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01004328# else // TIOCGWINSZ
Bram Moolenaar071d4272004-06-13 20:20:40 +00004329# ifdef TIOCGSIZE
4330 {
4331 struct ttysize ts;
4332 int fd = 1;
4333
Bram Moolenaar0f873732019-12-05 20:28:46 +01004334 // When stdout is not a tty, use stdin for the ioctl().
Bram Moolenaar071d4272004-06-13 20:20:40 +00004335 if (!isatty(fd) && isatty(read_cmd_fd))
4336 fd = read_cmd_fd;
4337 if (ioctl(fd, TIOCGSIZE, &ts) == 0)
4338 {
4339 columns = ts.ts_cols;
4340 rows = ts.ts_lines;
Bram Moolenaar545c8a52023-06-21 15:51:47 +01004341# ifdef FEAT_EVAL
Bram Moolenaar55f1b822023-06-21 13:42:48 +01004342 ch_log(NULL, "Got size with TIOCGSIZE: %ld x %ld", columns, rows);
Bram Moolenaar545c8a52023-06-21 15:51:47 +01004343# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004344 }
4345 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01004346# endif // TIOCGSIZE
4347# endif // TIOCGWINSZ
Bram Moolenaar071d4272004-06-13 20:20:40 +00004348
4349 /*
4350 * 2. get size from environment
Bram Moolenaar4399ef42005-02-12 14:29:27 +00004351 * When being POSIX compliant ('|' flag in 'cpoptions') this overrules
4352 * the ioctl() values!
Bram Moolenaar071d4272004-06-13 20:20:40 +00004353 */
Bram Moolenaar4399ef42005-02-12 14:29:27 +00004354 if (columns == 0 || rows == 0 || vim_strchr(p_cpo, CPO_TSIZE) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004355 {
4356 if ((p = (char_u *)getenv("LINES")))
Bram Moolenaar55f1b822023-06-21 13:42:48 +01004357 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004358 rows = atoi((char *)p);
Bram Moolenaar545c8a52023-06-21 15:51:47 +01004359# ifdef FEAT_EVAL
Bram Moolenaar55f1b822023-06-21 13:42:48 +01004360 ch_log(NULL, "Got 'lines' from $LINES: %ld", rows);
Bram Moolenaar545c8a52023-06-21 15:51:47 +01004361# endif
Bram Moolenaar55f1b822023-06-21 13:42:48 +01004362 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004363 if ((p = (char_u *)getenv("COLUMNS")))
Bram Moolenaar55f1b822023-06-21 13:42:48 +01004364 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004365 columns = atoi((char *)p);
Bram Moolenaar545c8a52023-06-21 15:51:47 +01004366# ifdef FEAT_EVAL
Bram Moolenaar55f1b822023-06-21 13:42:48 +01004367 ch_log(NULL, "Got 'columns' from $COLUMNS: %ld", columns);
Bram Moolenaar545c8a52023-06-21 15:51:47 +01004368# endif
Bram Moolenaar55f1b822023-06-21 13:42:48 +01004369 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004370 }
4371
4372#ifdef HAVE_TGETENT
4373 /*
4374 * 3. try reading "co" and "li" entries from termcap
4375 */
4376 if (columns == 0 || rows == 0)
Bram Moolenaar55f1b822023-06-21 13:42:48 +01004377 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004378 getlinecol(&columns, &rows);
Bram Moolenaar545c8a52023-06-21 15:51:47 +01004379# ifdef FEAT_EVAL
Bram Moolenaar55f1b822023-06-21 13:42:48 +01004380 ch_log(NULL, "Got size from termcap: %ld x %ld", columns, rows);
Bram Moolenaar545c8a52023-06-21 15:51:47 +01004381# endif
Bram Moolenaar55f1b822023-06-21 13:42:48 +01004382 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004383#endif
4384
4385 /*
4386 * 4. If everything fails, use the old values
4387 */
4388 if (columns <= 0 || rows <= 0)
4389 return FAIL;
4390
4391 Rows = rows;
4392 Columns = columns;
Bram Moolenaare057d402013-06-30 17:51:51 +02004393 limit_screen_size();
Bram Moolenaar071d4272004-06-13 20:20:40 +00004394 return OK;
4395}
4396
mikoto20001083cae2024-11-11 21:24:14 +01004397/*
4398 * Try to get the current terminal cell size.
mikoto2000de094dc2024-11-14 22:13:48 +01004399 * On failure, returns -1x-1
mikoto20001083cae2024-11-11 21:24:14 +01004400 */
4401 void
4402mch_calc_cell_size(struct cellsize *cs_out)
4403{
mikoto2000de094dc2024-11-14 22:13:48 +01004404 // get current tty size.
4405 struct winsize ws;
4406 int fd = 1;
4407 int retval = -1;
4408 retval = ioctl(fd, TIOCGWINSZ, &ws);
4409
4410#ifdef FEAT_EVAL
4411 ch_log(NULL, "ioctl(TIOCGWINSZ) %s", retval == 0 ? "success" : "failed");
mikoto20001083cae2024-11-11 21:24:14 +01004412#endif
mikoto20001083cae2024-11-11 21:24:14 +01004413
mikoto2000a73dfc22024-11-18 21:12:21 +01004414 if (retval == -1 || ws.ws_col == 0 || ws.ws_row == 0)
mikoto2000de094dc2024-11-14 22:13:48 +01004415 {
Yegappan Lakshmanane89aef32025-05-14 20:31:55 +02004416 cs_out->cs_xpixel = -1;
4417 cs_out->cs_ypixel = -1;
4418 return;
mikoto2000de094dc2024-11-14 22:13:48 +01004419 }
mikoto20001083cae2024-11-11 21:24:14 +01004420
mikoto2000de094dc2024-11-14 22:13:48 +01004421 // calculate parent tty's pixel per cell.
4422 int x_cell_size = ws.ws_xpixel / ws.ws_col;
4423 int y_cell_size = ws.ws_ypixel / ws.ws_row;
mikoto20001083cae2024-11-11 21:24:14 +01004424
mikoto2000de094dc2024-11-14 22:13:48 +01004425 // calculate current tty's pixel
4426 cs_out->cs_xpixel = x_cell_size;
4427 cs_out->cs_ypixel = y_cell_size;
4428
4429#ifdef FEAT_EVAL
4430 ch_log(NULL, "Got cell pixel size with TIOCGWINSZ: %d x %d", x_cell_size, y_cell_size);
mikoto20001083cae2024-11-11 21:24:14 +01004431#endif
4432}
4433
Bram Moolenaarb13501f2017-07-22 22:32:56 +02004434#if defined(FEAT_TERMINAL) || defined(PROTO)
4435/*
4436 * Report the windows size "rows" and "cols" to tty "fd".
4437 */
4438 int
4439mch_report_winsize(int fd, int rows, int cols)
4440{
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01004441 int tty_fd;
4442 int retval = -1;
Bram Moolenaarb13501f2017-07-22 22:32:56 +02004443
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01004444 tty_fd = get_tty_fd(fd);
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00004445 if (tty_fd < 0)
4446 return FAIL;
4447
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01004448# if defined(TIOCSWINSZ)
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00004449 struct winsize ws;
Bram Moolenaarb13501f2017-07-22 22:32:56 +02004450
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00004451 ws.ws_col = cols;
4452 ws.ws_row = rows;
mikoto20001083cae2024-11-11 21:24:14 +01004453
zeertzjq98800972025-04-18 10:57:33 +02004454 // calculate and set tty pixel size
mikoto20001083cae2024-11-11 21:24:14 +01004455 struct cellsize cs;
4456 mch_calc_cell_size(&cs);
mikoto2000de094dc2024-11-14 22:13:48 +01004457
4458 if (cs.cs_xpixel == -1)
4459 {
Naruhiko Nishinoc2a90002025-05-04 20:05:47 +02004460 // failed get pixel size.
4461 ws.ws_xpixel = 0;
4462 ws.ws_ypixel = 0;
mikoto2000de094dc2024-11-14 22:13:48 +01004463 }
4464 else
4465 {
Naruhiko Nishinoc2a90002025-05-04 20:05:47 +02004466 ws.ws_xpixel = cols * cs.cs_xpixel;
4467 ws.ws_ypixel = rows * cs.cs_ypixel;
mikoto2000de094dc2024-11-14 22:13:48 +01004468 }
mikoto20001083cae2024-11-11 21:24:14 +01004469
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00004470 retval = ioctl(tty_fd, TIOCSWINSZ, &ws);
Bram Moolenaar55f1b822023-06-21 13:42:48 +01004471 ch_log(NULL, "ioctl(TIOCSWINSZ) %s", retval == 0 ? "success" : "failed");
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01004472# elif defined(TIOCSSIZE)
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00004473 struct ttysize ts;
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01004474
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00004475 ts.ts_cols = cols;
4476 ts.ts_lines = rows;
4477 retval = ioctl(tty_fd, TIOCSSIZE, &ts);
Bram Moolenaar55f1b822023-06-21 13:42:48 +01004478 ch_log(NULL, "ioctl(TIOCSSIZE) %s", retval == 0 ? "success" : "failed");
Bram Moolenaarb13501f2017-07-22 22:32:56 +02004479# endif
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00004480 if (tty_fd != fd)
4481 close(tty_fd);
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01004482 return retval == 0 ? OK : FAIL;
Bram Moolenaarb13501f2017-07-22 22:32:56 +02004483}
4484#endif
4485
Bram Moolenaar071d4272004-06-13 20:20:40 +00004486/*
4487 * Try to set the window size to Rows and Columns.
4488 */
4489 void
Bram Moolenaar05540972016-01-30 20:31:25 +01004490mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004491{
4492 if (*T_CWS)
4493 {
4494 /*
4495 * NOTE: if you get an error here that term_set_winsize() is
4496 * undefined, check the output of configure. It could probably not
4497 * find a ncurses, termcap or termlib library.
4498 */
4499 term_set_winsize((int)Rows, (int)Columns);
4500 out_flush();
Bram Moolenaar0f873732019-12-05 20:28:46 +01004501 screen_start(); // don't know where cursor is now
Bram Moolenaar071d4272004-06-13 20:20:40 +00004502 }
4503}
4504
Bram Moolenaar0f873732019-12-05 20:28:46 +01004505#endif // VMS
Bram Moolenaar071d4272004-06-13 20:20:40 +00004506
4507/*
4508 * Rows and/or Columns has changed.
4509 */
4510 void
Bram Moolenaar05540972016-01-30 20:31:25 +01004511mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004512{
Bram Moolenaar0f873732019-12-05 20:28:46 +01004513 // Nothing to do.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004514}
4515
Bram Moolenaar205b8862011-09-07 15:04:31 +02004516/*
4517 * Wait for process "child" to end.
4518 * Return "child" if it exited properly, <= 0 on error.
4519 */
4520 static pid_t
Bram Moolenaar05540972016-01-30 20:31:25 +01004521wait4pid(pid_t child, waitstatus *status)
Bram Moolenaar205b8862011-09-07 15:04:31 +02004522{
4523 pid_t wait_pid = 0;
Bram Moolenaar0abe0522016-08-28 16:53:12 +02004524 long delay_msec = 1;
Bram Moolenaar205b8862011-09-07 15:04:31 +02004525
4526 while (wait_pid != child)
4527 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004528 // When compiled with Python threads are probably used, in which case
4529 // wait() sometimes hangs for no obvious reason. Use waitpid()
4530 // instead and loop (like the GUI). Also needed for other interfaces,
4531 // they might call system().
Bram Moolenaar6be120e2012-04-20 15:55:16 +02004532# ifdef __NeXT__
Bram Moolenaar205b8862011-09-07 15:04:31 +02004533 wait_pid = wait4(child, status, WNOHANG, (struct rusage *)0);
Bram Moolenaar6be120e2012-04-20 15:55:16 +02004534# else
Bram Moolenaar205b8862011-09-07 15:04:31 +02004535 wait_pid = waitpid(child, status, WNOHANG);
Bram Moolenaar6be120e2012-04-20 15:55:16 +02004536# endif
Bram Moolenaar205b8862011-09-07 15:04:31 +02004537 if (wait_pid == 0)
4538 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004539 // Wait for 1 to 10 msec before trying again.
Bram Moolenaar0981c872020-08-23 14:28:37 +02004540 mch_delay(delay_msec, MCH_DELAY_IGNOREINPUT | MCH_DELAY_SETTMODE);
Bram Moolenaar0abe0522016-08-28 16:53:12 +02004541 if (++delay_msec > 10)
4542 delay_msec = 10;
Bram Moolenaar205b8862011-09-07 15:04:31 +02004543 continue;
4544 }
Bram Moolenaar205b8862011-09-07 15:04:31 +02004545 if (wait_pid <= 0
4546# ifdef ECHILD
4547 && errno == ECHILD
4548# endif
4549 )
4550 break;
4551 }
4552 return wait_pid;
4553}
4554
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01004555#if !defined(USE_SYSTEM) || defined(FEAT_JOB_CHANNEL)
Bram Moolenaar7da34602017-08-01 17:14:21 +02004556/*
4557 * Set the environment for a child process.
4558 */
Bram Moolenaar6463ca22016-02-13 17:04:46 +01004559 static void
Bram Moolenaar493359e2018-06-12 20:25:52 +02004560set_child_environment(
4561 long rows,
4562 long columns,
4563 char *term,
4564 int is_terminal UNUSED)
Bram Moolenaar6463ca22016-02-13 17:04:46 +01004565{
4566# ifdef HAVE_SETENV
4567 char envbuf[50];
4568# else
Bram Moolenaar5f7e7bd2017-07-22 14:08:43 +02004569 static char envbuf_Term[30];
Bram Moolenaar6463ca22016-02-13 17:04:46 +01004570 static char envbuf_Rows[20];
Bram Moolenaar58556cd2017-07-20 23:04:46 +02004571 static char envbuf_Lines[20];
Bram Moolenaar6463ca22016-02-13 17:04:46 +01004572 static char envbuf_Columns[20];
Bram Moolenaarb7a8dfe2017-07-22 20:33:05 +02004573 static char envbuf_Colors[20];
Bram Moolenaar493359e2018-06-12 20:25:52 +02004574# ifdef FEAT_TERMINAL
Bram Moolenaard7a137f2018-06-12 18:05:24 +02004575 static char envbuf_Version[20];
Bram Moolenaar493359e2018-06-12 20:25:52 +02004576# endif
Bram Moolenaar2a4f06f2017-08-01 18:44:29 +02004577# ifdef FEAT_CLIENTSERVER
Bram Moolenaar7da34602017-08-01 17:14:21 +02004578 static char envbuf_Servername[60];
Bram Moolenaar2a4f06f2017-08-01 18:44:29 +02004579# endif
Bram Moolenaar6463ca22016-02-13 17:04:46 +01004580# endif
4581
Bram Moolenaar6463ca22016-02-13 17:04:46 +01004582# ifdef HAVE_SETENV
Bram Moolenaar58556cd2017-07-20 23:04:46 +02004583 setenv("TERM", term, 1);
4584 sprintf((char *)envbuf, "%ld", rows);
Bram Moolenaar6463ca22016-02-13 17:04:46 +01004585 setenv("ROWS", (char *)envbuf, 1);
Bram Moolenaar58556cd2017-07-20 23:04:46 +02004586 sprintf((char *)envbuf, "%ld", rows);
Bram Moolenaar6463ca22016-02-13 17:04:46 +01004587 setenv("LINES", (char *)envbuf, 1);
Bram Moolenaar58556cd2017-07-20 23:04:46 +02004588 sprintf((char *)envbuf, "%ld", columns);
Bram Moolenaar6463ca22016-02-13 17:04:46 +01004589 setenv("COLUMNS", (char *)envbuf, 1);
Bram Moolenaar759d8152020-04-26 16:52:49 +02004590 sprintf((char *)envbuf, "%d", t_colors);
Bram Moolenaarb7a8dfe2017-07-22 20:33:05 +02004591 setenv("COLORS", (char *)envbuf, 1);
Bram Moolenaar493359e2018-06-12 20:25:52 +02004592# ifdef FEAT_TERMINAL
4593 if (is_terminal)
4594 {
Bram Moolenaar5ecdf962018-06-13 20:49:50 +02004595 sprintf((char *)envbuf, "%ld", (long)get_vim_var_nr(VV_VERSION));
Bram Moolenaar493359e2018-06-12 20:25:52 +02004596 setenv("VIM_TERMINAL", (char *)envbuf, 1);
4597 }
4598# endif
Bram Moolenaar2a4f06f2017-08-01 18:44:29 +02004599# ifdef FEAT_CLIENTSERVER
Bram Moolenaar7da34602017-08-01 17:14:21 +02004600 setenv("VIM_SERVERNAME", serverName == NULL ? "" : (char *)serverName, 1);
Bram Moolenaar2a4f06f2017-08-01 18:44:29 +02004601# endif
Bram Moolenaar6463ca22016-02-13 17:04:46 +01004602# else
4603 /*
4604 * Putenv does not copy the string, it has to remain valid.
4605 * Use a static array to avoid losing allocated memory.
Bram Moolenaar7da34602017-08-01 17:14:21 +02004606 * This won't work well when running multiple children...
Bram Moolenaar6463ca22016-02-13 17:04:46 +01004607 */
Bram Moolenaar58556cd2017-07-20 23:04:46 +02004608 vim_snprintf(envbuf_Term, sizeof(envbuf_Term), "TERM=%s", term);
4609 putenv(envbuf_Term);
4610 vim_snprintf(envbuf_Rows, sizeof(envbuf_Rows), "ROWS=%ld", rows);
Bram Moolenaar6463ca22016-02-13 17:04:46 +01004611 putenv(envbuf_Rows);
Bram Moolenaar58556cd2017-07-20 23:04:46 +02004612 vim_snprintf(envbuf_Lines, sizeof(envbuf_Lines), "LINES=%ld", rows);
4613 putenv(envbuf_Lines);
4614 vim_snprintf(envbuf_Columns, sizeof(envbuf_Columns),
4615 "COLUMNS=%ld", columns);
Bram Moolenaar6463ca22016-02-13 17:04:46 +01004616 putenv(envbuf_Columns);
Bram Moolenaaraffc8fd2020-04-28 21:58:29 +02004617 vim_snprintf(envbuf_Colors, sizeof(envbuf_Colors), "COLORS=%ld", t_colors);
Bram Moolenaarb7a8dfe2017-07-22 20:33:05 +02004618 putenv(envbuf_Colors);
Bram Moolenaar493359e2018-06-12 20:25:52 +02004619# ifdef FEAT_TERMINAL
4620 if (is_terminal)
4621 {
4622 vim_snprintf(envbuf_Version, sizeof(envbuf_Version),
Bram Moolenaar5ecdf962018-06-13 20:49:50 +02004623 "VIM_TERMINAL=%ld", (long)get_vim_var_nr(VV_VERSION));
Bram Moolenaar493359e2018-06-12 20:25:52 +02004624 putenv(envbuf_Version);
4625 }
4626# endif
Bram Moolenaar2a4f06f2017-08-01 18:44:29 +02004627# ifdef FEAT_CLIENTSERVER
Bram Moolenaar7da34602017-08-01 17:14:21 +02004628 vim_snprintf(envbuf_Servername, sizeof(envbuf_Servername),
4629 "VIM_SERVERNAME=%s", serverName == NULL ? "" : (char *)serverName);
4630 putenv(envbuf_Servername);
Bram Moolenaar2a4f06f2017-08-01 18:44:29 +02004631# endif
Bram Moolenaar6463ca22016-02-13 17:04:46 +01004632# endif
4633}
Bram Moolenaar58556cd2017-07-20 23:04:46 +02004634
4635 static void
Bram Moolenaar493359e2018-06-12 20:25:52 +02004636set_default_child_environment(int is_terminal)
Bram Moolenaar58556cd2017-07-20 23:04:46 +02004637{
Bram Moolenaar493359e2018-06-12 20:25:52 +02004638 set_child_environment(Rows, Columns, "dumb", is_terminal);
Bram Moolenaar58556cd2017-07-20 23:04:46 +02004639}
Bram Moolenaar6463ca22016-02-13 17:04:46 +01004640#endif
4641
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02004642#if defined(FEAT_GUI) || defined(FEAT_JOB_CHANNEL)
Bram Moolenaar979e8c52017-08-01 15:08:07 +02004643/*
4644 * Open a PTY, with FD for the master and slave side.
4645 * When failing "pty_master_fd" and "pty_slave_fd" are -1.
Bram Moolenaar59386482019-02-10 22:43:46 +01004646 * When successful both file descriptors are stored and the allocated pty name
4647 * is stored in both "*name1" and "*name2".
Bram Moolenaar979e8c52017-08-01 15:08:07 +02004648 */
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02004649 static void
Bram Moolenaar59386482019-02-10 22:43:46 +01004650open_pty(int *pty_master_fd, int *pty_slave_fd, char_u **name1, char_u **name2)
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02004651{
4652 char *tty_name;
4653
Bram Moolenaar59386482019-02-10 22:43:46 +01004654 if (name1 != NULL)
4655 *name1 = NULL;
4656 if (name2 != NULL)
4657 *name2 = NULL;
4658
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01004659 *pty_master_fd = mch_openpty(&tty_name); // open pty
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00004660 if (*pty_master_fd < 0)
4661 return;
4662
4663 // Leaving out O_NOCTTY may lead to waitpid() always returning
4664 // 0 on Mac OS X 10.7 thereby causing freezes. Let's assume
4665 // adding O_NOCTTY always works when defined.
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02004666#ifdef O_NOCTTY
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00004667 *pty_slave_fd = open(tty_name, O_RDWR | O_NOCTTY | O_EXTRA, 0);
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02004668#else
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00004669 *pty_slave_fd = open(tty_name, O_RDWR | O_EXTRA, 0);
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02004670#endif
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00004671 if (*pty_slave_fd < 0)
4672 {
4673 close(*pty_master_fd);
4674 *pty_master_fd = -1;
4675 }
4676 else
4677 {
4678 if (name1 != NULL)
4679 *name1 = vim_strsave((char_u *)tty_name);
4680 if (name2 != NULL)
4681 *name2 = vim_strsave((char_u *)tty_name);
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02004682 }
4683}
4684#endif
4685
Bram Moolenaarfae42832017-08-01 22:24:26 +02004686/*
4687 * Send SIGINT to a child process if "c" is an interrupt character.
4688 */
Bram Moolenaar840d16f2019-09-10 21:27:18 +02004689 static void
Bram Moolenaarfae42832017-08-01 22:24:26 +02004690may_send_sigint(int c UNUSED, pid_t pid UNUSED, pid_t wpid UNUSED)
4691{
4692# ifdef SIGINT
4693 if (c == Ctrl_C || c == intr_char)
4694 {
4695# ifdef HAVE_SETSID
4696 kill(-pid, SIGINT);
4697# else
4698 kill(0, SIGINT);
4699# endif
4700 if (wpid > 0)
4701 kill(wpid, SIGINT);
4702 }
4703# endif
4704}
4705
Bram Moolenaar197c6b72019-11-03 23:37:12 +01004706#if !defined(USE_SYSTEM) || defined(FEAT_TERMINAL) || defined(PROTO)
Bram Moolenaar13568252018-03-16 20:46:58 +01004707
Bram Moolenaar0f873732019-12-05 20:28:46 +01004708/*
4709 * Parse "cmd" and return the result in "argvp" which is an allocated array of
4710 * pointers, the last one is NULL.
4711 * The "sh_tofree" and "shcf_tofree" must be later freed by the caller.
4712 */
Bram Moolenaar197c6b72019-11-03 23:37:12 +01004713 int
4714unix_build_argv(
Bram Moolenaar13568252018-03-16 20:46:58 +01004715 char_u *cmd,
4716 char ***argvp,
4717 char_u **sh_tofree,
4718 char_u **shcf_tofree)
4719{
4720 char **argv = NULL;
4721 int argc;
4722
4723 *sh_tofree = vim_strsave(p_sh);
Bram Moolenaar0f873732019-12-05 20:28:46 +01004724 if (*sh_tofree == NULL) // out of memory
Bram Moolenaar13568252018-03-16 20:46:58 +01004725 return FAIL;
4726
4727 if (mch_parse_cmd(*sh_tofree, TRUE, &argv, &argc) == FAIL)
4728 return FAIL;
4729 *argvp = argv;
4730
4731 if (cmd != NULL)
4732 {
4733 char_u *s;
4734 char_u *p;
4735
4736 if (extra_shell_arg != NULL)
4737 argv[argc++] = (char *)extra_shell_arg;
4738
Bram Moolenaar0f873732019-12-05 20:28:46 +01004739 // Break 'shellcmdflag' into white separated parts. This doesn't
4740 // handle quoted strings, they are very unlikely to appear.
Bram Moolenaar964b3742019-05-24 18:54:09 +02004741 *shcf_tofree = alloc(STRLEN(p_shcf) + 1);
Bram Moolenaar0f873732019-12-05 20:28:46 +01004742 if (*shcf_tofree == NULL) // out of memory
Bram Moolenaar13568252018-03-16 20:46:58 +01004743 return FAIL;
4744 s = *shcf_tofree;
4745 p = p_shcf;
4746 while (*p != NUL)
4747 {
4748 argv[argc++] = (char *)s;
4749 while (*p && *p != ' ' && *p != TAB)
4750 *s++ = *p++;
4751 *s++ = NUL;
4752 p = skipwhite(p);
4753 }
4754
4755 argv[argc++] = (char *)cmd;
4756 }
4757 argv[argc] = NULL;
4758 return OK;
4759}
4760#endif
4761
4762#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
4763/*
4764 * Use a terminal window to run a shell command in.
4765 */
4766 static int
4767mch_call_shell_terminal(
4768 char_u *cmd,
Bram Moolenaar0f873732019-12-05 20:28:46 +01004769 int options UNUSED) // SHELL_*, see vim.h
Bram Moolenaar13568252018-03-16 20:46:58 +01004770{
4771 jobopt_T opt;
4772 char **argv = NULL;
4773 char_u *tofree1 = NULL;
4774 char_u *tofree2 = NULL;
4775 int retval = -1;
4776 buf_T *buf;
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004777 job_T *job;
Bram Moolenaar13568252018-03-16 20:46:58 +01004778 aco_save_T aco;
Bram Moolenaar0f873732019-12-05 20:28:46 +01004779 oparg_T oa; // operator arguments
Bram Moolenaar13568252018-03-16 20:46:58 +01004780
Bram Moolenaar197c6b72019-11-03 23:37:12 +01004781 if (unix_build_argv(cmd, &argv, &tofree1, &tofree2) == FAIL)
Bram Moolenaar13568252018-03-16 20:46:58 +01004782 goto theend;
4783
4784 init_job_options(&opt);
4785 ch_log(NULL, "starting terminal for system command '%s'", cmd);
4786 buf = term_start(NULL, argv, &opt, TERM_START_SYSTEM);
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004787 if (buf == NULL)
4788 goto theend;
4789
4790 job = term_getjob(buf->b_term);
4791 ++job->jv_refcount;
Bram Moolenaar13568252018-03-16 20:46:58 +01004792
Bram Moolenaar0f873732019-12-05 20:28:46 +01004793 // Find a window to make "buf" curbuf.
Bram Moolenaar13568252018-03-16 20:46:58 +01004794 aucmd_prepbuf(&aco, buf);
Bram Moolenaare76062c2022-11-28 18:51:43 +00004795 if (curbuf == buf)
Bram Moolenaar13568252018-03-16 20:46:58 +01004796 {
Bram Moolenaare76062c2022-11-28 18:51:43 +00004797 // Only when managed to find a window for "buf",
4798 clear_oparg(&oa);
4799 while (term_use_loop())
Bram Moolenaar13568252018-03-16 20:46:58 +01004800 {
Bram Moolenaare76062c2022-11-28 18:51:43 +00004801 if (oa.op_type == OP_NOP && oa.regname == NUL && !VIsual_active)
4802 {
4803 // If terminal_loop() returns OK we got a key that is handled
4804 // in Normal model. We don't do redrawing anyway.
4805 if (terminal_loop(TRUE) == OK)
4806 normal_cmd(&oa, TRUE);
4807 }
4808 else
Bram Moolenaar13568252018-03-16 20:46:58 +01004809 normal_cmd(&oa, TRUE);
4810 }
Bram Moolenaare76062c2022-11-28 18:51:43 +00004811 retval = job->jv_exitval;
4812 ch_log(NULL, "system command finished");
4813
4814 job_unref(job);
4815
4816 // restore curwin/curbuf and a few other things
4817 aucmd_restbuf(&aco);
Bram Moolenaar13568252018-03-16 20:46:58 +01004818 }
Bram Moolenaar13568252018-03-16 20:46:58 +01004819
Yegappan Lakshmanan6b085b92022-09-04 12:47:21 +01004820 // Only require pressing Enter when redrawing, to avoid that system() gets
Bram Moolenaarcb5ed4d2022-07-28 12:54:08 +01004821 // the hit-enter prompt even though it didn't output anything.
Bram Moolenaar79cdf022023-05-20 14:07:00 +01004822 if (RedrawingDisabled == 0)
Bram Moolenaarcb5ed4d2022-07-28 12:54:08 +01004823 wait_return(TRUE);
Bram Moolenaar13568252018-03-16 20:46:58 +01004824 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
4825
4826theend:
4827 vim_free(argv);
4828 vim_free(tofree1);
4829 vim_free(tofree2);
4830 return retval;
4831}
4832#endif
4833
4834#ifdef USE_SYSTEM
4835/*
4836 * Use system() to start the shell: simple but slow.
4837 */
4838 static int
4839mch_call_shell_system(
Bram Moolenaar05540972016-01-30 20:31:25 +01004840 char_u *cmd,
Bram Moolenaar0f873732019-12-05 20:28:46 +01004841 int options) // SHELL_*, see vim.h
Bram Moolenaar071d4272004-06-13 20:20:40 +00004842{
4843#ifdef VMS
4844 char *ifn = NULL;
4845 char *ofn = NULL;
4846#endif
Bram Moolenaar26e86442020-05-17 14:06:16 +02004847 tmode_T tmode = cur_tmode;
Bram Moolenaar0f873732019-12-05 20:28:46 +01004848 char_u *newcmd; // only needed for unix
Bram Moolenaarde5e2c22016-11-04 20:35:31 +01004849 int x;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004850
4851 out_flush();
4852
4853 if (options & SHELL_COOKED)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004854 settmode(TMODE_COOK); // set to normal mode
Bram Moolenaar071d4272004-06-13 20:20:40 +00004855
Foxe Chenb90c2392025-06-27 21:10:35 +02004856# if defined(FEAT_CLIPBOARD) && (defined(FEAT_X11) \
4857 || defined(FEAT_WAYLAND_CLIPBOARD))
4858# if defined(FEAT_X11) || defined(FEAT_WAYLAND_CLIPBOARD)
Bram Moolenaar1a0316c2013-03-13 17:50:25 +01004859 save_clipboard();
Foxe Chenb90c2392025-06-27 21:10:35 +02004860#endif
Bram Moolenaar62b42182010-09-21 22:09:37 +02004861 loose_clipboard();
4862# endif
4863
Bram Moolenaar071d4272004-06-13 20:20:40 +00004864 if (cmd == NULL)
4865 x = system((char *)p_sh);
4866 else
4867 {
Bram Moolenaara06ecab2016-07-16 14:47:36 +02004868# ifdef VMS
Bram Moolenaar071d4272004-06-13 20:20:40 +00004869 if (ofn = strchr((char *)cmd, '>'))
4870 *ofn++ = '\0';
4871 if (ifn = strchr((char *)cmd, '<'))
4872 {
4873 char *p;
4874
4875 *ifn++ = '\0';
Bram Moolenaar0f873732019-12-05 20:28:46 +01004876 p = strchr(ifn,' '); // chop off any trailing spaces
Bram Moolenaar071d4272004-06-13 20:20:40 +00004877 if (p)
4878 *p = '\0';
4879 }
4880 if (ofn)
4881 x = vms_sys((char *)cmd, ofn, ifn);
4882 else
4883 x = system((char *)cmd);
Bram Moolenaara06ecab2016-07-16 14:47:36 +02004884# else
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02004885 newcmd = alloc(STRLEN(p_sh)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004886 + (extra_shell_arg == NULL ? 0 : STRLEN(extra_shell_arg))
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02004887 + STRLEN(p_shcf) + STRLEN(cmd) + 4);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004888 if (newcmd == NULL)
4889 x = 0;
4890 else
4891 {
4892 sprintf((char *)newcmd, "%s %s %s %s", p_sh,
4893 extra_shell_arg == NULL ? "" : (char *)extra_shell_arg,
4894 (char *)p_shcf,
4895 (char *)cmd);
4896 x = system((char *)newcmd);
4897 vim_free(newcmd);
4898 }
Bram Moolenaara06ecab2016-07-16 14:47:36 +02004899# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004900 }
4901# ifdef VMS
4902 x = vms_sys_status(x);
4903# endif
4904 if (emsg_silent)
4905 ;
4906 else if (x == 127)
Bram Moolenaar32526b32019-01-19 17:43:09 +01004907 msg_puts(_("\nCannot execute shell sh\n"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004908 else if (x && !(options & SHELL_SILENT))
4909 {
Bram Moolenaar32526b32019-01-19 17:43:09 +01004910 msg_puts(_("\nshell returned "));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004911 msg_outnum((long)x);
4912 msg_putchar('\n');
4913 }
4914
4915 if (tmode == TMODE_RAW)
Bram Moolenaar3b1f18f2020-05-16 23:15:08 +02004916 {
4917 // The shell may have messed with the mode, always set it.
4918 cur_tmode = TMODE_UNKNOWN;
Bram Moolenaar0f873732019-12-05 20:28:46 +01004919 settmode(TMODE_RAW); // set to raw mode
Bram Moolenaar3b1f18f2020-05-16 23:15:08 +02004920 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004921 resettitle();
Foxe Chenb90c2392025-06-27 21:10:35 +02004922# if defined(FEAT_CLIPBOARD) && (defined(FEAT_X11) \
4923 || defined(FEAT_WAYLAND_CLIPBOARD))
Bram Moolenaar1a0316c2013-03-13 17:50:25 +01004924 restore_clipboard();
4925# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004926 return x;
Bram Moolenaar13568252018-03-16 20:46:58 +01004927}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004928
Bram Moolenaar0f873732019-12-05 20:28:46 +01004929#else // USE_SYSTEM
Bram Moolenaar071d4272004-06-13 20:20:40 +00004930
Bram Moolenaar0f873732019-12-05 20:28:46 +01004931# define EXEC_FAILED 122 // Exit code when shell didn't execute. Don't use
4932 // 127, some shells use that already
4933# define OPEN_NULL_FAILED 123 // Exit code if /dev/null can't be opened
Bram Moolenaar071d4272004-06-13 20:20:40 +00004934
Bram Moolenaar13568252018-03-16 20:46:58 +01004935/*
4936 * Don't use system(), use fork()/exec().
4937 */
4938 static int
4939mch_call_shell_fork(
4940 char_u *cmd,
Bram Moolenaar0f873732019-12-05 20:28:46 +01004941 int options) // SHELL_*, see vim.h
Bram Moolenaar13568252018-03-16 20:46:58 +01004942{
Bram Moolenaar26e86442020-05-17 14:06:16 +02004943 tmode_T tmode = cur_tmode;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004944 pid_t pid;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004945 pid_t wpid = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004946 pid_t wait_pid = 0;
4947# ifdef HAVE_UNION_WAIT
4948 union wait status;
4949# else
4950 int status = -1;
4951# endif
4952 int retval = -1;
4953 char **argv = NULL;
Bram Moolenaar13568252018-03-16 20:46:58 +01004954 char_u *tofree1 = NULL;
4955 char_u *tofree2 = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004956 int i;
Bram Moolenaar0f873732019-12-05 20:28:46 +01004957 int pty_master_fd = -1; // for pty's
Bram Moolenaardf177f62005-02-22 08:39:57 +00004958# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004959 int pty_slave_fd = -1;
Bram Moolenaardf177f62005-02-22 08:39:57 +00004960# endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01004961 int fd_toshell[2]; // for pipes
Bram Moolenaar071d4272004-06-13 20:20:40 +00004962 int fd_fromshell[2];
4963 int pipe_error = FALSE;
Bram Moolenaar0f873732019-12-05 20:28:46 +01004964 int did_settmode = FALSE; // settmode(TMODE_RAW) called
Bram Moolenaar071d4272004-06-13 20:20:40 +00004965
4966 out_flush();
4967 if (options & SHELL_COOKED)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004968 settmode(TMODE_COOK); // set to normal mode
Bram Moolenaar3b1f18f2020-05-16 23:15:08 +02004969 if (tmode == TMODE_RAW)
4970 // The shell may have messed with the mode, always set it later.
4971 cur_tmode = TMODE_UNKNOWN;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004972
Bram Moolenaar197c6b72019-11-03 23:37:12 +01004973 if (unix_build_argv(cmd, &argv, &tofree1, &tofree2) == FAIL)
Bram Moolenaar835dc632016-02-07 14:27:38 +01004974 goto error;
Bram Moolenaarea35ef62011-08-04 22:59:28 +02004975
Bram Moolenaar071d4272004-06-13 20:20:40 +00004976 /*
Bram Moolenaardf177f62005-02-22 08:39:57 +00004977 * For the GUI, when writing the output into the buffer and when reading
4978 * input from the buffer: Try using a pseudo-tty to get the stdin/stdout
4979 * of the executed command into the Vim window. Or use a pipe.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004980 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004981 if ((options & (SHELL_READ|SHELL_WRITE))
4982# ifdef FEAT_GUI
4983 || (gui.in_use && show_shell_mess)
4984# endif
4985 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00004986 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00004987# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004988 /*
4989 * Try to open a master pty.
4990 * If this works, open the slave pty.
4991 * If the slave can't be opened, close the master pty.
4992 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00004993 if (p_guipty && !(options & (SHELL_READ|SHELL_WRITE)))
Bram Moolenaar59386482019-02-10 22:43:46 +01004994 open_pty(&pty_master_fd, &pty_slave_fd, NULL, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004995 /*
4996 * If not opening a pty or it didn't work, try using pipes.
4997 */
4998 if (pty_master_fd < 0)
Bram Moolenaardf177f62005-02-22 08:39:57 +00004999# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005000 {
5001 pipe_error = (pipe(fd_toshell) < 0);
Bram Moolenaar0f873732019-12-05 20:28:46 +01005002 if (!pipe_error) // pipe create OK
Bram Moolenaar071d4272004-06-13 20:20:40 +00005003 {
5004 pipe_error = (pipe(fd_fromshell) < 0);
Bram Moolenaar0f873732019-12-05 20:28:46 +01005005 if (pipe_error) // pipe create failed
Bram Moolenaar071d4272004-06-13 20:20:40 +00005006 {
5007 close(fd_toshell[0]);
5008 close(fd_toshell[1]);
5009 }
5010 }
5011 if (pipe_error)
5012 {
Bram Moolenaar32526b32019-01-19 17:43:09 +01005013 msg_puts(_("\nCannot create pipes\n"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005014 out_flush();
5015 }
5016 }
5017 }
5018
Bram Moolenaar0f873732019-12-05 20:28:46 +01005019 if (!pipe_error) // pty or pipe opened or not used
Bram Moolenaar071d4272004-06-13 20:20:40 +00005020 {
Bram Moolenaarbb09ceb2016-10-18 16:27:23 +02005021 SIGSET_DECL(curset)
Bram Moolenaarbb09ceb2016-10-18 16:27:23 +02005022 BLOCK_SIGNALS(&curset);
Bram Moolenaar0f873732019-12-05 20:28:46 +01005023 pid = fork(); // maybe we should use vfork()
Bram Moolenaarbb09ceb2016-10-18 16:27:23 +02005024 if (pid == -1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005025 {
Bram Moolenaarbb09ceb2016-10-18 16:27:23 +02005026 UNBLOCK_SIGNALS(&curset);
5027
Bram Moolenaar32526b32019-01-19 17:43:09 +01005028 msg_puts(_("\nCannot fork\n"));
Bram Moolenaardf177f62005-02-22 08:39:57 +00005029 if ((options & (SHELL_READ|SHELL_WRITE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005030# ifdef FEAT_GUI
Bram Moolenaardf177f62005-02-22 08:39:57 +00005031 || (gui.in_use && show_shell_mess)
5032# endif
5033 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00005034 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00005035# ifdef FEAT_GUI
Bram Moolenaar0f873732019-12-05 20:28:46 +01005036 if (pty_master_fd >= 0) // close the pseudo tty
Bram Moolenaar071d4272004-06-13 20:20:40 +00005037 {
5038 close(pty_master_fd);
5039 close(pty_slave_fd);
5040 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01005041 else // close the pipes
Bram Moolenaardf177f62005-02-22 08:39:57 +00005042# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005043 {
5044 close(fd_toshell[0]);
5045 close(fd_toshell[1]);
5046 close(fd_fromshell[0]);
5047 close(fd_fromshell[1]);
5048 }
5049 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005050 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01005051 else if (pid == 0) // child
Bram Moolenaar071d4272004-06-13 20:20:40 +00005052 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005053 reset_signals(); // handle signals normally
Bram Moolenaarbb09ceb2016-10-18 16:27:23 +02005054 UNBLOCK_SIGNALS(&curset);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005055
Bram Moolenaar4c5678f2022-11-30 18:12:19 +00005056# ifdef FEAT_EVAL
Bram Moolenaar819524702018-02-27 19:10:00 +01005057 if (ch_log_active())
Bram Moolenaar76603ba2020-08-30 17:24:37 +02005058 {
5059 ch_log(NULL, "closing channel log in the child process");
Bram Moolenaar819524702018-02-27 19:10:00 +01005060 ch_logfile((char_u *)"", (char_u *)"");
Bram Moolenaar76603ba2020-08-30 17:24:37 +02005061 }
Bram Moolenaar819524702018-02-27 19:10:00 +01005062# endif
5063
Bram Moolenaar071d4272004-06-13 20:20:40 +00005064 if (!show_shell_mess || (options & SHELL_EXPAND))
5065 {
5066 int fd;
5067
5068 /*
5069 * Don't want to show any message from the shell. Can't just
5070 * close stdout and stderr though, because some systems will
5071 * break if you try to write to them after that, so we must
5072 * use dup() to replace them with something else -- webb
5073 * Connect stdin to /dev/null too, so ":n `cat`" doesn't hang,
5074 * waiting for input.
5075 */
5076 fd = open("/dev/null", O_RDWR | O_EXTRA, 0);
5077 fclose(stdin);
5078 fclose(stdout);
5079 fclose(stderr);
5080
5081 /*
5082 * If any of these open()'s and dup()'s fail, we just continue
5083 * anyway. It's not fatal, and on most systems it will make
5084 * no difference at all. On a few it will cause the execvp()
5085 * to exit with a non-zero status even when the completion
5086 * could be done, which is nothing too serious. If the open()
5087 * or dup() failed we'd just do the same thing ourselves
5088 * anyway -- webb
5089 */
5090 if (fd >= 0)
5091 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005092 vim_ignored = dup(fd); // To replace stdin (fd 0)
5093 vim_ignored = dup(fd); // To replace stdout (fd 1)
5094 vim_ignored = dup(fd); // To replace stderr (fd 2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005095
Bram Moolenaar0f873732019-12-05 20:28:46 +01005096 // Don't need this now that we've duplicated it
Bram Moolenaar071d4272004-06-13 20:20:40 +00005097 close(fd);
5098 }
5099 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00005100 else if ((options & (SHELL_READ|SHELL_WRITE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005101# ifdef FEAT_GUI
Bram Moolenaardf177f62005-02-22 08:39:57 +00005102 || gui.in_use
5103# endif
5104 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00005105 {
5106
Bram Moolenaardf177f62005-02-22 08:39:57 +00005107# ifdef HAVE_SETSID
Bram Moolenaar0f873732019-12-05 20:28:46 +01005108 // Create our own process group, so that the child and all its
5109 // children can be kill()ed. Don't do this when using pipes,
5110 // because stdin is not a tty, we would lose /dev/tty.
Bram Moolenaar12033fb2005-12-16 21:49:31 +00005111 if (p_stmp)
Bram Moolenaar07256082009-02-04 13:19:42 +00005112 {
Bram Moolenaar12033fb2005-12-16 21:49:31 +00005113 (void)setsid();
Bram Moolenaar07256082009-02-04 13:19:42 +00005114# if defined(SIGHUP)
Bram Moolenaar0f873732019-12-05 20:28:46 +01005115 // When doing "!xterm&" and 'shell' is bash: the shell
5116 // will exit and send SIGHUP to all processes in its
5117 // group, killing the just started process. Ignore SIGHUP
5118 // to avoid that. (suggested by Simon Schubert)
ichizok378447f2023-05-11 22:25:42 +01005119 mch_signal(SIGHUP, SIG_IGN);
Bram Moolenaar07256082009-02-04 13:19:42 +00005120# endif
5121 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00005122# endif
5123# ifdef FEAT_GUI
Bram Moolenaar12033fb2005-12-16 21:49:31 +00005124 if (pty_slave_fd >= 0)
5125 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005126 // push stream discipline modules
Bram Moolenaar12033fb2005-12-16 21:49:31 +00005127 if (options & SHELL_COOKED)
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01005128 setup_slavepty(pty_slave_fd);
Bram Moolenaarfff10d92021-10-13 10:05:30 +01005129# ifdef TIOCSCTTY
5130 // Try to become controlling tty (probably doesn't work,
5131 // unless run by root)
5132 ioctl(pty_slave_fd, TIOCSCTTY, (char *)NULL);
5133# endif
Bram Moolenaar12033fb2005-12-16 21:49:31 +00005134 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00005135# endif
Bram Moolenaar493359e2018-06-12 20:25:52 +02005136 set_default_child_environment(FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005137
Bram Moolenaara5792f52005-11-23 21:25:05 +00005138 /*
5139 * stderr is only redirected when using the GUI, so that a
5140 * program like gpg can still access the terminal to get a
5141 * passphrase using stderr.
5142 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00005143# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00005144 if (pty_master_fd >= 0)
5145 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005146 close(pty_master_fd); // close master side of pty
Bram Moolenaar071d4272004-06-13 20:20:40 +00005147
Bram Moolenaar0f873732019-12-05 20:28:46 +01005148 // set up stdin/stdout/stderr for the child
Bram Moolenaar071d4272004-06-13 20:20:40 +00005149 close(0);
Bram Moolenaar42335f52018-09-13 15:33:43 +02005150 vim_ignored = dup(pty_slave_fd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005151 close(1);
Bram Moolenaar42335f52018-09-13 15:33:43 +02005152 vim_ignored = dup(pty_slave_fd);
Bram Moolenaara5792f52005-11-23 21:25:05 +00005153 if (gui.in_use)
5154 {
5155 close(2);
Bram Moolenaar42335f52018-09-13 15:33:43 +02005156 vim_ignored = dup(pty_slave_fd);
Bram Moolenaara5792f52005-11-23 21:25:05 +00005157 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005158
Bram Moolenaar0f873732019-12-05 20:28:46 +01005159 close(pty_slave_fd); // has been dupped, close it now
Bram Moolenaar071d4272004-06-13 20:20:40 +00005160 }
5161 else
Bram Moolenaardf177f62005-02-22 08:39:57 +00005162# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005163 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005164 // set up stdin for the child
Bram Moolenaar071d4272004-06-13 20:20:40 +00005165 close(fd_toshell[1]);
5166 close(0);
Bram Moolenaar42335f52018-09-13 15:33:43 +02005167 vim_ignored = dup(fd_toshell[0]);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005168 close(fd_toshell[0]);
5169
Bram Moolenaar0f873732019-12-05 20:28:46 +01005170 // set up stdout for the child
Bram Moolenaar071d4272004-06-13 20:20:40 +00005171 close(fd_fromshell[0]);
5172 close(1);
Bram Moolenaar42335f52018-09-13 15:33:43 +02005173 vim_ignored = dup(fd_fromshell[1]);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005174 close(fd_fromshell[1]);
5175
Bram Moolenaara5792f52005-11-23 21:25:05 +00005176# ifdef FEAT_GUI
5177 if (gui.in_use)
5178 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005179 // set up stderr for the child
Bram Moolenaara5792f52005-11-23 21:25:05 +00005180 close(2);
Bram Moolenaar42335f52018-09-13 15:33:43 +02005181 vim_ignored = dup(1);
Bram Moolenaara5792f52005-11-23 21:25:05 +00005182 }
5183# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005184 }
5185 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00005186
Bram Moolenaar071d4272004-06-13 20:20:40 +00005187 /*
5188 * There is no type cast for the argv, because the type may be
5189 * different on different machines. This may cause a warning
5190 * message with strict compilers, don't worry about it.
5191 * Call _exit() instead of exit() to avoid closing the connection
Foxe Chenb90c2392025-06-27 21:10:35 +02005192 * to the X/Wayland server (esp. with GTK, which uses atexit()).
Bram Moolenaar071d4272004-06-13 20:20:40 +00005193 */
5194 execvp(argv[0], argv);
Bram Moolenaar0f873732019-12-05 20:28:46 +01005195 _exit(EXEC_FAILED); // exec failed, return failure code
Bram Moolenaar071d4272004-06-13 20:20:40 +00005196 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01005197 else // parent
Bram Moolenaar071d4272004-06-13 20:20:40 +00005198 {
5199 /*
5200 * While child is running, ignore terminating signals.
Bram Moolenaardf177f62005-02-22 08:39:57 +00005201 * Do catch CTRL-C, so that "got_int" is set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005202 */
5203 catch_signals(SIG_IGN, SIG_ERR);
Bram Moolenaardf177f62005-02-22 08:39:57 +00005204 catch_int_signal();
Bram Moolenaarbb09ceb2016-10-18 16:27:23 +02005205 UNBLOCK_SIGNALS(&curset);
Bram Moolenaarc4d4ac22016-11-07 22:42:57 +01005206# ifdef FEAT_JOB_CHANNEL
5207 ++dont_check_job_ended;
5208# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005209 /*
5210 * For the GUI we redirect stdin, stdout and stderr to our window.
Bram Moolenaardf177f62005-02-22 08:39:57 +00005211 * This is also used to pipe stdin/stdout to/from the external
5212 * command.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005213 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00005214 if ((options & (SHELL_READ|SHELL_WRITE))
5215# ifdef FEAT_GUI
5216 || (gui.in_use && show_shell_mess)
5217# endif
5218 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00005219 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005220# define BUFLEN 100 // length for buffer, pseudo tty limit is 128
Bram Moolenaar071d4272004-06-13 20:20:40 +00005221 char_u buffer[BUFLEN + 1];
Bram Moolenaar0f873732019-12-05 20:28:46 +01005222 int buffer_off = 0; // valid bytes in buffer[]
5223 char_u ta_buf[BUFLEN + 1]; // TypeAHead
5224 int ta_len = 0; // valid bytes in ta_buf[]
Bram Moolenaar071d4272004-06-13 20:20:40 +00005225 int len;
5226 int p_more_save;
5227 int old_State;
5228 int c;
5229 int toshell_fd;
5230 int fromshell_fd;
Bram Moolenaardf177f62005-02-22 08:39:57 +00005231 garray_T ga;
5232 int noread_cnt;
Bram Moolenaar1ac56c22019-01-17 22:28:22 +01005233# ifdef ELAPSED_FUNC
5234 elapsed_T start_tv;
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00005235# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005236
Bram Moolenaardf177f62005-02-22 08:39:57 +00005237# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00005238 if (pty_master_fd >= 0)
5239 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00005240 fromshell_fd = pty_master_fd;
5241 toshell_fd = dup(pty_master_fd);
5242 }
5243 else
Bram Moolenaardf177f62005-02-22 08:39:57 +00005244# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005245 {
5246 close(fd_toshell[0]);
5247 close(fd_fromshell[1]);
5248 toshell_fd = fd_toshell[1];
5249 fromshell_fd = fd_fromshell[0];
5250 }
5251
5252 /*
5253 * Write to the child if there are typed characters.
5254 * Read from the child if there are characters available.
5255 * Repeat the reading a few times if more characters are
5256 * available. Need to check for typed keys now and then, but
5257 * not too often (delays when no chars are available).
5258 * This loop is quit if no characters can be read from the pty
5259 * (WaitForChar detected special condition), or there are no
5260 * characters available and the child has exited.
5261 * Only check if the child has exited when there is no more
5262 * output. The child may exit before all the output has
5263 * been printed.
5264 *
5265 * Currently this busy loops!
5266 * This can probably dead-lock when the write blocks!
5267 */
5268 p_more_save = p_more;
5269 p_more = FALSE;
5270 old_State = State;
Bram Moolenaar24959102022-05-07 20:01:16 +01005271 State = MODE_EXTERNCMD; // don't redraw at window resize
Bram Moolenaar071d4272004-06-13 20:20:40 +00005272
Bram Moolenaar12033fb2005-12-16 21:49:31 +00005273 if ((options & SHELL_WRITE) && toshell_fd >= 0)
Bram Moolenaardf177f62005-02-22 08:39:57 +00005274 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005275 // Fork a process that will write the lines to the
5276 // external program.
Bram Moolenaardf177f62005-02-22 08:39:57 +00005277 if ((wpid = fork()) == -1)
5278 {
Bram Moolenaar32526b32019-01-19 17:43:09 +01005279 msg_puts(_("\nCannot fork\n"));
Bram Moolenaardf177f62005-02-22 08:39:57 +00005280 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01005281 else if (wpid == 0) // child
Bram Moolenaardf177f62005-02-22 08:39:57 +00005282 {
5283 linenr_T lnum = curbuf->b_op_start.lnum;
zeertzjq53fed232025-03-30 15:01:56 +02005284 size_t written = 0;
Bram Moolenaar89d40322006-08-29 15:30:07 +00005285 char_u *lp = ml_get(lnum);
John Marriottefc41a52025-01-23 20:05:29 +01005286 size_t lplen = (size_t)ml_get_len(lnum);
Bram Moolenaardf177f62005-02-22 08:39:57 +00005287
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00005288 close(fromshell_fd);
Bram Moolenaardf177f62005-02-22 08:39:57 +00005289 for (;;)
5290 {
John Marriottefc41a52025-01-23 20:05:29 +01005291 if (lplen == 0)
Bram Moolenaardf177f62005-02-22 08:39:57 +00005292 len = 0;
Bram Moolenaar89d40322006-08-29 15:30:07 +00005293 else if (lp[written] == NL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01005294 // NL -> NUL translation
Bram Moolenaardf177f62005-02-22 08:39:57 +00005295 len = write(toshell_fd, "", (size_t)1);
5296 else
5297 {
Bram Moolenaar70b2a562012-01-10 22:26:17 +01005298 char_u *s = vim_strchr(lp + written, NL);
5299
Bram Moolenaar89d40322006-08-29 15:30:07 +00005300 len = write(toshell_fd, (char *)lp + written,
zeertzjq53fed232025-03-30 15:01:56 +02005301 s == NULL ? lplen - written
Bram Moolenaar78a15312009-05-15 19:33:18 +00005302 : (size_t)(s - (lp + written)));
Bram Moolenaardf177f62005-02-22 08:39:57 +00005303 }
zeertzjq53fed232025-03-30 15:01:56 +02005304 if (len == (int)(lplen - written))
Bram Moolenaardf177f62005-02-22 08:39:57 +00005305 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005306 // Finished a line, add a NL, unless this line
5307 // should not have one.
Bram Moolenaardf177f62005-02-22 08:39:57 +00005308 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02005309 || (!curbuf->b_p_bin
5310 && curbuf->b_p_fixeol)
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01005311 || (lnum != curbuf->b_no_eol_lnum
Bram Moolenaar88456cd2022-11-18 22:14:09 +00005312 && (lnum != curbuf->b_ml.ml_line_count
Bram Moolenaardf177f62005-02-22 08:39:57 +00005313 || curbuf->b_p_eol)))
Bram Moolenaar42335f52018-09-13 15:33:43 +02005314 vim_ignored = write(toshell_fd, "\n",
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00005315 (size_t)1);
Bram Moolenaardf177f62005-02-22 08:39:57 +00005316 ++lnum;
5317 if (lnum > curbuf->b_op_end.lnum)
5318 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005319 // finished all the lines, close pipe
Bram Moolenaardf177f62005-02-22 08:39:57 +00005320 close(toshell_fd);
Bram Moolenaardf177f62005-02-22 08:39:57 +00005321 break;
5322 }
Bram Moolenaar89d40322006-08-29 15:30:07 +00005323 lp = ml_get(lnum);
John Marriottefc41a52025-01-23 20:05:29 +01005324 lplen = ml_get_len(lnum);
Bram Moolenaardf177f62005-02-22 08:39:57 +00005325 written = 0;
5326 }
5327 else if (len > 0)
zeertzjq53fed232025-03-30 15:01:56 +02005328 written += (size_t)len;
Bram Moolenaardf177f62005-02-22 08:39:57 +00005329 }
5330 _exit(0);
5331 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01005332 else // parent
Bram Moolenaardf177f62005-02-22 08:39:57 +00005333 {
5334 close(toshell_fd);
5335 toshell_fd = -1;
5336 }
5337 }
5338
5339 if (options & SHELL_READ)
5340 ga_init2(&ga, 1, BUFLEN);
5341
5342 noread_cnt = 0;
Bram Moolenaar833eb1d2016-11-24 17:22:50 +01005343# ifdef ELAPSED_FUNC
5344 ELAPSED_INIT(start_tv);
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00005345# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005346 for (;;)
5347 {
5348 /*
5349 * Check if keys have been typed, write them to the child
Bram Moolenaar5b962cf2005-12-12 21:58:40 +00005350 * if there are any.
5351 * Don't do this if we are expanding wild cards (would eat
5352 * typeahead).
5353 * Don't do this when filtering and terminal is in cooked
5354 * mode, the shell command will handle the I/O. Avoids
5355 * that a typed password is echoed for ssh or gpg command.
Bram Moolenaar12033fb2005-12-16 21:49:31 +00005356 * Don't get characters when the child has already
5357 * finished (wait_pid == 0).
Bram Moolenaardf177f62005-02-22 08:39:57 +00005358 * Don't read characters unless we didn't get output for a
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00005359 * while (noread_cnt > 4), avoids that ":r !ls" eats
5360 * typeahead.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005361 */
5362 len = 0;
5363 if (!(options & SHELL_EXPAND)
Bram Moolenaar5b962cf2005-12-12 21:58:40 +00005364 && ((options &
5365 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
5366 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00005367# ifdef FEAT_GUI
Bram Moolenaar5b962cf2005-12-12 21:58:40 +00005368 || gui.in_use
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00005369# endif
Bram Moolenaar5b962cf2005-12-12 21:58:40 +00005370 )
Bram Moolenaar12033fb2005-12-16 21:49:31 +00005371 && wait_pid == 0
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00005372 && (ta_len > 0 || noread_cnt > 4))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005373 {
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00005374 if (ta_len == 0)
5375 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005376 // Get extra characters when we don't have any.
5377 // Reset the counter and timer.
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00005378 noread_cnt = 0;
Bram Moolenaar833eb1d2016-11-24 17:22:50 +01005379# ifdef ELAPSED_FUNC
5380 ELAPSED_INIT(start_tv);
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00005381# endif
5382 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
5383 }
5384 if (ta_len > 0 || len > 0)
5385 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00005386 /*
5387 * For pipes:
5388 * Check for CTRL-C: send interrupt signal to child.
5389 * Check for CTRL-D: EOF, close pipe to child.
5390 */
5391 if (len == 1 && (pty_master_fd < 0 || cmd != NULL))
5392 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00005393 /*
5394 * Send SIGINT to the child's group or all
5395 * processes in our group.
5396 */
Bram Moolenaarfae42832017-08-01 22:24:26 +02005397 may_send_sigint(ta_buf[ta_len], pid, wpid);
5398
Bram Moolenaar071d4272004-06-13 20:20:40 +00005399 if (pty_master_fd < 0 && toshell_fd >= 0
5400 && ta_buf[ta_len] == Ctrl_D)
5401 {
5402 close(toshell_fd);
5403 toshell_fd = -1;
5404 }
5405 }
5406
Bram Moolenaar2f7e1b82022-10-04 13:17:31 +01005407 // Remove Vim-specific codes from the input.
5408 len = term_replace_keycodes(ta_buf, ta_len, len);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005409
5410 /*
5411 * For pipes: echo the typed characters.
5412 * For a pty this does not seem to work.
5413 */
5414 if (pty_master_fd < 0)
5415 {
5416 for (i = ta_len; i < ta_len + len; ++i)
5417 {
5418 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
5419 msg_putchar(ta_buf[i]);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005420 else if (has_mbyte)
5421 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00005422 int l = (*mb_ptr2len)(ta_buf + i);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005423
5424 msg_outtrans_len(ta_buf + i, l);
5425 i += l - 1;
5426 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005427 else
5428 msg_outtrans_len(ta_buf + i, 1);
5429 }
5430 windgoto(msg_row, msg_col);
5431 out_flush();
5432 }
5433
5434 ta_len += len;
5435
5436 /*
5437 * Write the characters to the child, unless EOF has
5438 * been typed for pipes. Write one character at a
Bram Moolenaare37d50a2008-08-06 17:06:04 +00005439 * time, to avoid losing too much typeahead.
Bram Moolenaardf177f62005-02-22 08:39:57 +00005440 * When writing buffer lines, drop the typed
5441 * characters (only check for CTRL-C).
Bram Moolenaar071d4272004-06-13 20:20:40 +00005442 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00005443 if (options & SHELL_WRITE)
5444 ta_len = 0;
5445 else if (toshell_fd >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005446 {
5447 len = write(toshell_fd, (char *)ta_buf, (size_t)1);
5448 if (len > 0)
5449 {
5450 ta_len -= len;
5451 mch_memmove(ta_buf, ta_buf + len, ta_len);
5452 }
5453 }
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00005454 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005455 }
5456
Bram Moolenaardf177f62005-02-22 08:39:57 +00005457 if (got_int)
5458 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005459 // CTRL-C sends a signal to the child, we ignore it
5460 // ourselves
Bram Moolenaardf177f62005-02-22 08:39:57 +00005461# ifdef HAVE_SETSID
5462 kill(-pid, SIGINT);
5463# else
5464 kill(0, SIGINT);
5465# endif
5466 if (wpid > 0)
5467 kill(wpid, SIGINT);
5468 got_int = FALSE;
5469 }
5470
Bram Moolenaar071d4272004-06-13 20:20:40 +00005471 /*
5472 * Check if the child has any characters to be printed.
5473 * Read them and write them to our window. Repeat this as
5474 * long as there is something to do, avoid the 10ms wait
5475 * for mch_inchar(), or sending typeahead characters to
5476 * the external process.
5477 * TODO: This should handle escape sequences, compatible
5478 * to some terminal (vt52?).
5479 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00005480 ++noread_cnt;
Bram Moolenaar8fdd7212016-03-26 19:41:48 +01005481 while (RealWaitForChar(fromshell_fd, 10L, NULL, NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005482 {
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01005483 len = read_eintr(fromshell_fd, buffer
Bram Moolenaar071d4272004-06-13 20:20:40 +00005484 + buffer_off, (size_t)(BUFLEN - buffer_off)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005485 );
Bram Moolenaar0f873732019-12-05 20:28:46 +01005486 if (len <= 0) // end of file or error
Bram Moolenaar071d4272004-06-13 20:20:40 +00005487 goto finished;
Bram Moolenaardf177f62005-02-22 08:39:57 +00005488
5489 noread_cnt = 0;
5490 if (options & SHELL_READ)
5491 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005492 // Do NUL -> NL translation, append NL separated
5493 // lines to the current buffer.
Bram Moolenaardf177f62005-02-22 08:39:57 +00005494 for (i = 0; i < len; ++i)
5495 {
5496 if (buffer[i] == NL)
5497 append_ga_line(&ga);
5498 else if (buffer[i] == NUL)
5499 ga_append(&ga, NL);
5500 else
5501 ga_append(&ga, buffer[i]);
5502 }
5503 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00005504 else if (has_mbyte)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005505 {
5506 int l;
Bram Moolenaara2150ac2018-03-17 13:15:17 +01005507 char_u *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005508
Bram Moolenaardf177f62005-02-22 08:39:57 +00005509 len += buffer_off;
5510 buffer[len] = NUL;
5511
Bram Moolenaar0f873732019-12-05 20:28:46 +01005512 // Check if the last character in buffer[] is
5513 // incomplete, keep these bytes for the next
5514 // round.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005515 for (p = buffer; p < buffer + len; p += l)
5516 {
Bram Moolenaard3c907b2016-08-17 21:32:09 +02005517 l = MB_CPTR2LEN(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005518 if (l == 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01005519 l = 1; // NUL byte?
Bram Moolenaar071d4272004-06-13 20:20:40 +00005520 else if (MB_BYTE2LEN(*p) != l)
5521 break;
5522 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01005523 if (p == buffer) // no complete character
Bram Moolenaar071d4272004-06-13 20:20:40 +00005524 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005525 // avoid getting stuck at an illegal byte
Bram Moolenaar071d4272004-06-13 20:20:40 +00005526 if (len >= 12)
5527 ++p;
5528 else
5529 {
5530 buffer_off = len;
5531 continue;
5532 }
5533 }
5534 c = *p;
5535 *p = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01005536 msg_puts((char *)buffer);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005537 if (p < buffer + len)
5538 {
5539 *p = c;
5540 buffer_off = (buffer + len) - p;
5541 mch_memmove(buffer, p, buffer_off);
5542 continue;
5543 }
5544 buffer_off = 0;
5545 }
5546 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005547 {
5548 buffer[len] = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01005549 msg_puts((char *)buffer);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005550 }
5551
5552 windgoto(msg_row, msg_col);
5553 cursor_on();
5554 out_flush();
5555 if (got_int)
5556 break;
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00005557
Bram Moolenaar833eb1d2016-11-24 17:22:50 +01005558# ifdef ELAPSED_FUNC
Bram Moolenaar17fe5e12016-04-04 22:03:08 +02005559 if (wait_pid == 0)
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00005560 {
Bram Moolenaar833eb1d2016-11-24 17:22:50 +01005561 long msec = ELAPSED_FUNC(start_tv);
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00005562
Bram Moolenaar0f873732019-12-05 20:28:46 +01005563 // Avoid that we keep looping here without
5564 // checking for a CTRL-C for a long time. Don't
5565 // break out too often to avoid losing typeahead.
Bram Moolenaarb3dc8fd2009-02-22 01:52:59 +00005566 if (msec > 2000)
5567 {
5568 noread_cnt = 5;
5569 break;
5570 }
5571 }
5572# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005573 }
5574
Bram Moolenaar0f873732019-12-05 20:28:46 +01005575 // If we already detected the child has finished, continue
5576 // reading output for a short while. Some text may be
5577 // buffered.
Bram Moolenaar12033fb2005-12-16 21:49:31 +00005578 if (wait_pid == pid)
Bram Moolenaar17fe5e12016-04-04 22:03:08 +02005579 {
5580 if (noread_cnt < 5)
5581 continue;
Bram Moolenaar12033fb2005-12-16 21:49:31 +00005582 break;
Bram Moolenaar17fe5e12016-04-04 22:03:08 +02005583 }
Bram Moolenaar12033fb2005-12-16 21:49:31 +00005584
Bram Moolenaar071d4272004-06-13 20:20:40 +00005585 /*
5586 * Check if the child still exists, before checking for
Bram Moolenaare37d50a2008-08-06 17:06:04 +00005587 * typed characters (otherwise we would lose typeahead).
Bram Moolenaar071d4272004-06-13 20:20:40 +00005588 */
Bram Moolenaardf177f62005-02-22 08:39:57 +00005589# ifdef __NeXT__
Bram Moolenaar205b8862011-09-07 15:04:31 +02005590 wait_pid = wait4(pid, &status, WNOHANG, (struct rusage *)0);
Bram Moolenaardf177f62005-02-22 08:39:57 +00005591# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005592 wait_pid = waitpid(pid, &status, WNOHANG);
Bram Moolenaardf177f62005-02-22 08:39:57 +00005593# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005594 if ((wait_pid == (pid_t)-1 && errno == ECHILD)
5595 || (wait_pid == pid && WIFEXITED(status)))
5596 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005597 // Don't break the loop yet, try reading more
5598 // characters from "fromshell_fd" first. When using
5599 // pipes there might still be something to read and
5600 // then we'll break the loop at the "break" above.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005601 wait_pid = pid;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005602 }
Bram Moolenaar12033fb2005-12-16 21:49:31 +00005603 else
5604 wait_pid = 0;
Bram Moolenaar090cfc12013-03-19 12:35:42 +01005605
Bram Moolenaar95a51352013-03-21 22:53:50 +01005606# if defined(FEAT_XCLIPBOARD) && defined(FEAT_X11)
Bram Moolenaar0f873732019-12-05 20:28:46 +01005607 // Handle any X events, e.g. serving the clipboard.
Bram Moolenaar090cfc12013-03-19 12:35:42 +01005608 clip_update();
5609# endif
Foxe Chenb90c2392025-06-27 21:10:35 +02005610#ifdef FEAT_WAYLAND
Hirohito Higashi73b96502025-06-28 18:18:21 +02005611 // Handle Wayland events such as sending data as the source
Foxe Chenb90c2392025-06-27 21:10:35 +02005612 // client.
5613 wayland_client_update();
5614#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005615 }
5616finished:
5617 p_more = p_more_save;
Bram Moolenaardf177f62005-02-22 08:39:57 +00005618 if (options & SHELL_READ)
5619 {
5620 if (ga.ga_len > 0)
5621 {
5622 append_ga_line(&ga);
Bram Moolenaar0f873732019-12-05 20:28:46 +01005623 // remember that the NL was missing
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01005624 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
Bram Moolenaardf177f62005-02-22 08:39:57 +00005625 }
5626 else
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01005627 curbuf->b_no_eol_lnum = 0;
Bram Moolenaardf177f62005-02-22 08:39:57 +00005628 ga_clear(&ga);
5629 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005630
Bram Moolenaar071d4272004-06-13 20:20:40 +00005631 /*
5632 * Give all typeahead that wasn't used back to ui_inchar().
5633 */
5634 if (ta_len)
5635 ui_inchar_undo(ta_buf, ta_len);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005636 State = old_State;
5637 if (toshell_fd >= 0)
5638 close(toshell_fd);
5639 close(fromshell_fd);
5640 }
Foxe Chenb90c2392025-06-27 21:10:35 +02005641# if (defined(FEAT_XCLIPBOARD) && defined(FEAT_X11)) || defined(FEAT_WAYLAND)
Bram Moolenaar090cfc12013-03-19 12:35:42 +01005642 else
5643 {
Bram Moolenaar0abe0522016-08-28 16:53:12 +02005644 long delay_msec = 1;
5645
Bram Moolenaar8a3da6a2020-12-08 19:18:37 +01005646 if (tmode == TMODE_RAW)
Bram Moolenaar63a2e362022-11-23 20:20:18 +00005647 // Possibly disables modifyOtherKeys, so that the system
5648 // can recognize CTRL-C.
5649 out_str_t_TE();
Bram Moolenaar0981c872020-08-23 14:28:37 +02005650
Bram Moolenaar090cfc12013-03-19 12:35:42 +01005651 /*
Foxe Chenb90c2392025-06-27 21:10:35 +02005652 * Similar to the loop above, but only handle X and Wayland
5653 * events, no I/O.
Bram Moolenaar090cfc12013-03-19 12:35:42 +01005654 */
5655 for (;;)
5656 {
5657 if (got_int)
5658 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005659 // CTRL-C sends a signal to the child, we ignore it
5660 // ourselves
Bram Moolenaar090cfc12013-03-19 12:35:42 +01005661# ifdef HAVE_SETSID
5662 kill(-pid, SIGINT);
5663# else
5664 kill(0, SIGINT);
5665# endif
5666 got_int = FALSE;
5667 }
5668# ifdef __NeXT__
5669 wait_pid = wait4(pid, &status, WNOHANG, (struct rusage *)0);
5670# else
5671 wait_pid = waitpid(pid, &status, WNOHANG);
5672# endif
5673 if ((wait_pid == (pid_t)-1 && errno == ECHILD)
5674 || (wait_pid == pid && WIFEXITED(status)))
5675 {
5676 wait_pid = pid;
5677 break;
5678 }
5679
Foxe Chenb90c2392025-06-27 21:10:35 +02005680#if defined(FEAT_XCLIPBOARD) && defined(FEAT_X11)
Bram Moolenaar0f873732019-12-05 20:28:46 +01005681 // Handle any X events, e.g. serving the clipboard.
Bram Moolenaar090cfc12013-03-19 12:35:42 +01005682 clip_update();
Foxe Chenb90c2392025-06-27 21:10:35 +02005683#endif
5684#ifdef FEAT_WAYLAND
Hirohito Higashi73b96502025-06-28 18:18:21 +02005685 // Handle Wayland events such as sending data as the source
Foxe Chenb90c2392025-06-27 21:10:35 +02005686 // client.
5687 wayland_client_update();
5688#endif
Bram Moolenaar090cfc12013-03-19 12:35:42 +01005689
Bram Moolenaar0f873732019-12-05 20:28:46 +01005690 // Wait for 1 to 10 msec. 1 is faster but gives the child
Bram Moolenaar0981c872020-08-23 14:28:37 +02005691 // less time, gradually wait longer.
5692 mch_delay(delay_msec,
5693 MCH_DELAY_IGNOREINPUT | MCH_DELAY_SETTMODE);
Bram Moolenaar0abe0522016-08-28 16:53:12 +02005694 if (++delay_msec > 10)
5695 delay_msec = 10;
Bram Moolenaar090cfc12013-03-19 12:35:42 +01005696 }
Bram Moolenaar0981c872020-08-23 14:28:37 +02005697
Bram Moolenaar8a3da6a2020-12-08 19:18:37 +01005698 if (tmode == TMODE_RAW)
5699 // possibly enables modifyOtherKeys again
Bram Moolenaar733a69b2022-12-01 12:03:47 +00005700 out_str_t_TI();
Bram Moolenaar090cfc12013-03-19 12:35:42 +01005701 }
5702# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005703
5704 /*
5705 * Wait until our child has exited.
5706 * Ignore wait() returning pids of other children and returning
5707 * because of some signal like SIGWINCH.
5708 * Don't wait if wait_pid was already set above, indicating the
5709 * child already exited.
5710 */
Bram Moolenaar205b8862011-09-07 15:04:31 +02005711 if (wait_pid != pid)
Yegappan Lakshmanan6b085b92022-09-04 12:47:21 +01005712 (void)wait4pid(pid, &status);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005713
Bram Moolenaar624891f2010-10-13 16:22:09 +02005714# ifdef FEAT_GUI
Bram Moolenaar0f873732019-12-05 20:28:46 +01005715 // Close slave side of pty. Only do this after the child has
5716 // exited, otherwise the child may hang when it tries to write on
5717 // the pty.
Bram Moolenaar624891f2010-10-13 16:22:09 +02005718 if (pty_master_fd >= 0)
5719 close(pty_slave_fd);
5720# endif
5721
Bram Moolenaar0f873732019-12-05 20:28:46 +01005722 // Make sure the child that writes to the external program is
5723 // dead.
Bram Moolenaardf177f62005-02-22 08:39:57 +00005724 if (wpid > 0)
Bram Moolenaar205b8862011-09-07 15:04:31 +02005725 {
Bram Moolenaardf177f62005-02-22 08:39:57 +00005726 kill(wpid, SIGKILL);
Bram Moolenaar205b8862011-09-07 15:04:31 +02005727 wait4pid(wpid, NULL);
5728 }
Bram Moolenaardf177f62005-02-22 08:39:57 +00005729
Bram Moolenaarc4d4ac22016-11-07 22:42:57 +01005730# ifdef FEAT_JOB_CHANNEL
5731 --dont_check_job_ended;
5732# endif
5733
Bram Moolenaar071d4272004-06-13 20:20:40 +00005734 /*
5735 * Set to raw mode right now, otherwise a CTRL-C after
5736 * catch_signals() will kill Vim.
5737 */
5738 if (tmode == TMODE_RAW)
5739 settmode(TMODE_RAW);
5740 did_settmode = TRUE;
5741 set_signals();
5742
5743 if (WIFEXITED(status))
5744 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005745 // LINTED avoid "bitwise operation on signed value"
Bram Moolenaar071d4272004-06-13 20:20:40 +00005746 retval = WEXITSTATUS(status);
Bram Moolenaar75676462013-01-30 14:55:42 +01005747 if (retval != 0 && !emsg_silent)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005748 {
5749 if (retval == EXEC_FAILED)
5750 {
Bram Moolenaar32526b32019-01-19 17:43:09 +01005751 msg_puts(_("\nCannot execute shell "));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005752 msg_outtrans(p_sh);
5753 msg_putchar('\n');
5754 }
5755 else if (!(options & SHELL_SILENT))
5756 {
Bram Moolenaar32526b32019-01-19 17:43:09 +01005757 msg_puts(_("\nshell returned "));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005758 msg_outnum((long)retval);
5759 msg_putchar('\n');
5760 }
5761 }
5762 }
5763 else
Bram Moolenaar32526b32019-01-19 17:43:09 +01005764 msg_puts(_("\nCommand terminated\n"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005765 }
5766 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005767
5768error:
5769 if (!did_settmode)
5770 if (tmode == TMODE_RAW)
Bram Moolenaar0f873732019-12-05 20:28:46 +01005771 settmode(TMODE_RAW); // set to raw mode
Bram Moolenaar071d4272004-06-13 20:20:40 +00005772 resettitle();
Bram Moolenaar13568252018-03-16 20:46:58 +01005773 vim_free(argv);
5774 vim_free(tofree1);
5775 vim_free(tofree2);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005776
5777 return retval;
Bram Moolenaar13568252018-03-16 20:46:58 +01005778}
Bram Moolenaar0f873732019-12-05 20:28:46 +01005779#endif // USE_SYSTEM
Bram Moolenaar13568252018-03-16 20:46:58 +01005780
5781 int
5782mch_call_shell(
5783 char_u *cmd,
Bram Moolenaar0f873732019-12-05 20:28:46 +01005784 int options) // SHELL_*, see vim.h
Bram Moolenaar13568252018-03-16 20:46:58 +01005785{
Bram Moolenaar4c5678f2022-11-30 18:12:19 +00005786#ifdef FEAT_EVAL
Bram Moolenaarc9a9a0a2022-04-12 15:09:23 +01005787 ch_log(NULL, "executing shell command: %s", cmd);
5788#endif
Bram Moolenaar13568252018-03-16 20:46:58 +01005789#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
Bram Moolenaar524c8532022-09-27 15:48:20 +01005790 if (gui.in_use && vim_strchr(p_go, GO_TERMINAL) != NULL
5791 && (options & SHELL_SILENT) == 0)
Bram Moolenaar13568252018-03-16 20:46:58 +01005792 return mch_call_shell_terminal(cmd, options);
5793#endif
5794#ifdef USE_SYSTEM
5795 return mch_call_shell_system(cmd, options);
5796#else
5797 return mch_call_shell_fork(cmd, options);
5798#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005799}
5800
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005801#if defined(FEAT_JOB_CHANNEL) || defined(PROTO)
Bram Moolenaar835dc632016-02-07 14:27:38 +01005802 void
Bram Moolenaar493359e2018-06-12 20:25:52 +02005803mch_job_start(char **argv, job_T *job, jobopt_T *options, int is_terminal)
Bram Moolenaar835dc632016-02-07 14:27:38 +01005804{
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005805 pid_t pid;
Bram Moolenaar0f873732019-12-05 20:28:46 +01005806 int fd_in[2] = {-1, -1}; // for stdin
5807 int fd_out[2] = {-1, -1}; // for stdout
5808 int fd_err[2] = {-1, -1}; // for stderr
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02005809 int pty_master_fd = -1;
5810 int pty_slave_fd = -1;
Bram Moolenaar16eb4f82016-02-14 23:02:34 +01005811 channel_T *channel = NULL;
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005812 int use_null_for_in = options->jo_io[PART_IN] == JIO_NULL;
5813 int use_null_for_out = options->jo_io[PART_OUT] == JIO_NULL;
5814 int use_null_for_err = options->jo_io[PART_ERR] == JIO_NULL;
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005815 int use_file_for_in = options->jo_io[PART_IN] == JIO_FILE;
Bram Moolenaare98d1212016-03-08 15:37:41 +01005816 int use_file_for_out = options->jo_io[PART_OUT] == JIO_FILE;
5817 int use_file_for_err = options->jo_io[PART_ERR] == JIO_FILE;
Bram Moolenaarb2412082017-08-20 18:09:14 +02005818 int use_buffer_for_in = options->jo_io[PART_IN] == JIO_BUFFER;
Bram Moolenaarc25558b2016-03-03 21:02:23 +01005819 int use_out_for_err = options->jo_io[PART_ERR] == JIO_OUT;
Bram Moolenaarbb09ceb2016-10-18 16:27:23 +02005820 SIGSET_DECL(curset)
Bram Moolenaar835dc632016-02-07 14:27:38 +01005821
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005822 if (use_out_for_err && use_null_for_out)
5823 use_null_for_err = TRUE;
5824
Bram Moolenaar0f873732019-12-05 20:28:46 +01005825 // default is to fail
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005826 job->jv_status = JOB_FAILED;
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005827
Bram Moolenaarb2412082017-08-20 18:09:14 +02005828 if (options->jo_pty
5829 && (!(use_file_for_in || use_null_for_in)
Bram Moolenaar59386482019-02-10 22:43:46 +01005830 || !(use_file_for_out || use_null_for_out)
Bram Moolenaarb2412082017-08-20 18:09:14 +02005831 || !(use_out_for_err || use_file_for_err || use_null_for_err)))
Bram Moolenaar59386482019-02-10 22:43:46 +01005832 open_pty(&pty_master_fd, &pty_slave_fd,
5833 &job->jv_tty_out, &job->jv_tty_in);
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02005834
Bram Moolenaar0f873732019-12-05 20:28:46 +01005835 // TODO: without the channel feature connect the child to /dev/null?
5836 // Open pipes for stdin, stdout, stderr.
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005837 if (use_file_for_in)
5838 {
5839 char_u *fname = options->jo_io_name[PART_IN];
5840
5841 fd_in[0] = mch_open((char *)fname, O_RDONLY, 0);
5842 if (fd_in[0] < 0)
5843 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005844 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005845 goto failed;
5846 }
5847 }
Bram Moolenaarb2412082017-08-20 18:09:14 +02005848 else
Bram Moolenaar0f873732019-12-05 20:28:46 +01005849 // When writing buffer lines to the input don't use the pty, so that
5850 // the pipe can be closed when all lines were written.
Bram Moolenaarb2412082017-08-20 18:09:14 +02005851 if (!use_null_for_in && (pty_master_fd < 0 || use_buffer_for_in)
5852 && pipe(fd_in) < 0)
5853 goto failed;
Bram Moolenaare98d1212016-03-08 15:37:41 +01005854
5855 if (use_file_for_out)
5856 {
5857 char_u *fname = options->jo_io_name[PART_OUT];
5858
5859 fd_out[1] = mch_open((char *)fname, O_WRONLY | O_CREAT | O_TRUNC, 0644);
5860 if (fd_out[1] < 0)
5861 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005862 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaare98d1212016-03-08 15:37:41 +01005863 goto failed;
5864 }
5865 }
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02005866 else if (!use_null_for_out && pty_master_fd < 0 && pipe(fd_out) < 0)
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005867 goto failed;
Bram Moolenaare98d1212016-03-08 15:37:41 +01005868
5869 if (use_file_for_err)
5870 {
5871 char_u *fname = options->jo_io_name[PART_ERR];
5872
5873 fd_err[1] = mch_open((char *)fname, O_WRONLY | O_CREAT | O_TRUNC, 0600);
5874 if (fd_err[1] < 0)
5875 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005876 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaare98d1212016-03-08 15:37:41 +01005877 goto failed;
5878 }
5879 }
Christian Brabandtb50bc9a2024-09-30 21:29:43 +02005880 // only create a pipe for the error fd, when either a callback has been setup
5881 // or pty is not used (e.g. terminal uses pty by default)
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02005882 else if (!use_out_for_err && !use_null_for_err
Christian Brabandtb50bc9a2024-09-30 21:29:43 +02005883 && (pty_master_fd < 0 || (options->jo_set & JO_ERR_CALLBACK))
5884 && pipe(fd_err) < 0)
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005885 goto failed;
5886
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005887 if (!use_null_for_in || !use_null_for_out || !use_null_for_err)
5888 {
Bram Moolenaarde279892016-03-11 22:19:44 +01005889 if (options->jo_set & JO_CHANNEL)
5890 {
5891 channel = options->jo_channel;
5892 if (channel != NULL)
5893 ++channel->ch_refcount;
5894 }
5895 else
5896 channel = add_channel();
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005897 if (channel == NULL)
5898 goto failed;
Bram Moolenaarf3360612017-10-01 16:21:31 +02005899 if (job->jv_tty_out != NULL)
5900 ch_log(channel, "using pty %s on fd %d",
5901 job->jv_tty_out, pty_master_fd);
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005902 }
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005903
Bram Moolenaarbb09ceb2016-10-18 16:27:23 +02005904 BLOCK_SIGNALS(&curset);
Bram Moolenaar0f873732019-12-05 20:28:46 +01005905 pid = fork(); // maybe we should use vfork()
Bram Moolenaarbb09ceb2016-10-18 16:27:23 +02005906 if (pid == -1)
Bram Moolenaar835dc632016-02-07 14:27:38 +01005907 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005908 // failed to fork
Bram Moolenaarbb09ceb2016-10-18 16:27:23 +02005909 UNBLOCK_SIGNALS(&curset);
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005910 goto failed;
Bram Moolenaar835dc632016-02-07 14:27:38 +01005911 }
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005912 if (pid == 0)
Bram Moolenaar835dc632016-02-07 14:27:38 +01005913 {
Bram Moolenaar4694a172016-04-21 14:05:23 +02005914 int null_fd = -1;
5915 int stderr_works = TRUE;
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005916
Bram Moolenaar0f873732019-12-05 20:28:46 +01005917 // child
5918 reset_signals(); // handle signals normally
Bram Moolenaarbb09ceb2016-10-18 16:27:23 +02005919 UNBLOCK_SIGNALS(&curset);
Bram Moolenaar835dc632016-02-07 14:27:38 +01005920
Bram Moolenaar4c5678f2022-11-30 18:12:19 +00005921# ifdef FEAT_EVAL
Bram Moolenaar819524702018-02-27 19:10:00 +01005922 if (ch_log_active())
Bram Moolenaar0f873732019-12-05 20:28:46 +01005923 // close the log file in the child
Bram Moolenaar819524702018-02-27 19:10:00 +01005924 ch_logfile((char_u *)"", (char_u *)"");
5925# endif
5926
Bram Moolenaar835dc632016-02-07 14:27:38 +01005927# ifdef HAVE_SETSID
Bram Moolenaar0f873732019-12-05 20:28:46 +01005928 // Create our own process group, so that the child and all its
5929 // children can be kill()ed. Don't do this when using pipes,
5930 // because stdin is not a tty, we would lose /dev/tty.
Bram Moolenaar835dc632016-02-07 14:27:38 +01005931 (void)setsid();
5932# endif
5933
Bram Moolenaar58556cd2017-07-20 23:04:46 +02005934# ifdef FEAT_TERMINAL
5935 if (options->jo_term_rows > 0)
Bram Moolenaar9a993e32018-04-05 22:15:22 +02005936 {
5937 char *term = (char *)T_NAME;
5938
5939#ifdef FEAT_GUI
5940 if (term_is_gui(T_NAME))
Bram Moolenaar0f873732019-12-05 20:28:46 +01005941 // In the GUI 'term' is not what we want, use $TERM.
Bram Moolenaar9a993e32018-04-05 22:15:22 +02005942 term = getenv("TERM");
5943#endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01005944 // Use 'term' or $TERM if it starts with "xterm", otherwise fall
Bram Moolenaar4d5d0df2020-04-14 20:56:31 +02005945 // back to "xterm" or "xterm-color".
Bram Moolenaar9a993e32018-04-05 22:15:22 +02005946 if (term == NULL || *term == NUL || STRNCMP(term, "xterm", 5) != 0)
Bram Moolenaar5ba8d352020-04-05 21:42:12 +02005947 {
Bram Moolenaar5ba8d352020-04-05 21:42:12 +02005948 if (t_colors >= 256)
Bram Moolenaar4d5d0df2020-04-14 20:56:31 +02005949 // TODO: should we check this name is supported?
Bram Moolenaar5ba8d352020-04-05 21:42:12 +02005950 term = "xterm-256color";
Bram Moolenaar4d5d0df2020-04-14 20:56:31 +02005951 else if (t_colors > 16)
5952 term = "xterm-color";
Bram Moolenaar5ba8d352020-04-05 21:42:12 +02005953 else
5954 term = "xterm";
5955 }
Bram Moolenaar58556cd2017-07-20 23:04:46 +02005956 set_child_environment(
5957 (long)options->jo_term_rows,
5958 (long)options->jo_term_cols,
Bram Moolenaar493359e2018-06-12 20:25:52 +02005959 term,
5960 is_terminal);
Bram Moolenaar9a993e32018-04-05 22:15:22 +02005961 }
Bram Moolenaar58556cd2017-07-20 23:04:46 +02005962 else
5963# endif
Bram Moolenaar493359e2018-06-12 20:25:52 +02005964 set_default_child_environment(is_terminal);
Bram Moolenaar6463ca22016-02-13 17:04:46 +01005965
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005966 if (options->jo_env != NULL)
5967 {
5968 dict_T *dict = options->jo_env;
5969 hashitem_T *hi;
5970 int todo = (int)dict->dv_hashtab.ht_used;
5971
Yegappan Lakshmanan14113fd2023-03-07 17:13:51 +00005972 FOR_ALL_HASHTAB_ITEMS(&dict->dv_hashtab, hi, todo)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005973 if (!HASHITEM_EMPTY(hi))
5974 {
5975 typval_T *item = &dict_lookup(hi)->di_tv;
5976
=?UTF-8?q?Dundar=20G=C3=B6c?=420fabc2022-01-28 15:28:04 +00005977 vim_setenv(hi->hi_key, tv_get_string(item));
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005978 --todo;
5979 }
5980 }
5981
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005982 if (use_null_for_in || use_null_for_out || use_null_for_err)
Bram Moolenaarb109bb42017-08-21 21:07:29 +02005983 {
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005984 null_fd = open("/dev/null", O_RDWR | O_EXTRA, 0);
Bram Moolenaarb109bb42017-08-21 21:07:29 +02005985 if (null_fd < 0)
5986 {
5987 perror("opening /dev/null failed");
5988 _exit(OPEN_NULL_FAILED);
5989 }
5990 }
Bram Moolenaarf65333c2016-03-08 18:27:21 +01005991
Bram Moolenaar223896d2017-08-02 22:33:28 +02005992 if (pty_slave_fd >= 0)
5993 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005994 // push stream discipline modules
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01005995 setup_slavepty(pty_slave_fd);
Bram Moolenaar223896d2017-08-02 22:33:28 +02005996# ifdef TIOCSCTTY
Bram Moolenaar0f873732019-12-05 20:28:46 +01005997 // Try to become controlling tty (probably doesn't work,
5998 // unless run by root)
Bram Moolenaar223896d2017-08-02 22:33:28 +02005999 ioctl(pty_slave_fd, TIOCSCTTY, (char *)NULL);
6000# endif
6001 }
6002
Bram Moolenaar0f873732019-12-05 20:28:46 +01006003 // set up stdin for the child
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02006004 close(0);
Bram Moolenaarc0a1d7f2016-03-19 14:12:50 +01006005 if (use_null_for_in && null_fd >= 0)
Bram Moolenaar42335f52018-09-13 15:33:43 +02006006 vim_ignored = dup(null_fd);
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02006007 else if (fd_in[0] < 0)
Bram Moolenaar42335f52018-09-13 15:33:43 +02006008 vim_ignored = dup(pty_slave_fd);
Bram Moolenaarf65333c2016-03-08 18:27:21 +01006009 else
Bram Moolenaar42335f52018-09-13 15:33:43 +02006010 vim_ignored = dup(fd_in[0]);
Bram Moolenaar6463ca22016-02-13 17:04:46 +01006011
Bram Moolenaar0f873732019-12-05 20:28:46 +01006012 // set up stderr for the child
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02006013 close(2);
Bram Moolenaarc0a1d7f2016-03-19 14:12:50 +01006014 if (use_null_for_err && null_fd >= 0)
Bram Moolenaarf65333c2016-03-08 18:27:21 +01006015 {
Bram Moolenaar42335f52018-09-13 15:33:43 +02006016 vim_ignored = dup(null_fd);
Bram Moolenaar4694a172016-04-21 14:05:23 +02006017 stderr_works = FALSE;
Bram Moolenaarf65333c2016-03-08 18:27:21 +01006018 }
6019 else if (use_out_for_err)
Bram Moolenaar42335f52018-09-13 15:33:43 +02006020 vim_ignored = dup(fd_out[1]);
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02006021 else if (fd_err[1] < 0)
Bram Moolenaar42335f52018-09-13 15:33:43 +02006022 vim_ignored = dup(pty_slave_fd);
Bram Moolenaarc25558b2016-03-03 21:02:23 +01006023 else
Bram Moolenaar42335f52018-09-13 15:33:43 +02006024 vim_ignored = dup(fd_err[1]);
Bram Moolenaarc25558b2016-03-03 21:02:23 +01006025
Bram Moolenaar0f873732019-12-05 20:28:46 +01006026 // set up stdout for the child
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02006027 close(1);
Bram Moolenaarc0a1d7f2016-03-19 14:12:50 +01006028 if (use_null_for_out && null_fd >= 0)
Bram Moolenaar42335f52018-09-13 15:33:43 +02006029 vim_ignored = dup(null_fd);
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02006030 else if (fd_out[1] < 0)
Bram Moolenaar42335f52018-09-13 15:33:43 +02006031 vim_ignored = dup(pty_slave_fd);
Bram Moolenaarf65333c2016-03-08 18:27:21 +01006032 else
Bram Moolenaar42335f52018-09-13 15:33:43 +02006033 vim_ignored = dup(fd_out[1]);
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02006034
6035 if (fd_in[0] >= 0)
6036 close(fd_in[0]);
6037 if (fd_in[1] >= 0)
6038 close(fd_in[1]);
6039 if (fd_out[0] >= 0)
6040 close(fd_out[0]);
6041 if (fd_out[1] >= 0)
Bram Moolenaarf65333c2016-03-08 18:27:21 +01006042 close(fd_out[1]);
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02006043 if (fd_err[0] >= 0)
6044 close(fd_err[0]);
6045 if (fd_err[1] >= 0)
6046 close(fd_err[1]);
6047 if (pty_master_fd >= 0)
6048 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006049 close(pty_master_fd); // not used in the child
6050 close(pty_slave_fd); // was duped above
Bram Moolenaarf65333c2016-03-08 18:27:21 +01006051 }
Bram Moolenaarea83bf02016-05-08 09:40:51 +02006052
Bram Moolenaarf65333c2016-03-08 18:27:21 +01006053 if (null_fd >= 0)
6054 close(null_fd);
Bram Moolenaar6463ca22016-02-13 17:04:46 +01006055
Bram Moolenaar05aafed2017-08-11 19:12:11 +02006056 if (options->jo_cwd != NULL && mch_chdir((char *)options->jo_cwd) != 0)
6057 _exit(EXEC_FAILED);
6058
Bram Moolenaar0f873732019-12-05 20:28:46 +01006059 // See above for type of argv.
Bram Moolenaar835dc632016-02-07 14:27:38 +01006060 execvp(argv[0], argv);
6061
Bram Moolenaar4694a172016-04-21 14:05:23 +02006062 if (stderr_works)
6063 perror("executing job failed");
Bram Moolenaarfae42832017-08-01 22:24:26 +02006064# ifdef EXITFREE
Bram Moolenaar0f873732019-12-05 20:28:46 +01006065 // calling free_all_mem() here causes problems. Ignore valgrind
6066 // reporting possibly leaked memory.
Bram Moolenaarfae42832017-08-01 22:24:26 +02006067# endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01006068 _exit(EXEC_FAILED); // exec failed, return failure code
Bram Moolenaar835dc632016-02-07 14:27:38 +01006069 }
Bram Moolenaar6463ca22016-02-13 17:04:46 +01006070
Bram Moolenaar0f873732019-12-05 20:28:46 +01006071 // parent
Bram Moolenaarbb09ceb2016-10-18 16:27:23 +02006072 UNBLOCK_SIGNALS(&curset);
6073
Bram Moolenaar6463ca22016-02-13 17:04:46 +01006074 job->jv_pid = pid;
6075 job->jv_status = JOB_STARTED;
Bram Moolenaar0f873732019-12-05 20:28:46 +01006076 job->jv_channel = channel; // ch_refcount was set above
Bram Moolenaar6463ca22016-02-13 17:04:46 +01006077
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02006078 if (pty_master_fd >= 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01006079 close(pty_slave_fd); // not used in the parent
6080 // close child stdin, stdout and stderr
Bram Moolenaar819524702018-02-27 19:10:00 +01006081 if (fd_in[0] >= 0)
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01006082 close(fd_in[0]);
Bram Moolenaar819524702018-02-27 19:10:00 +01006083 if (fd_out[1] >= 0)
Bram Moolenaare98d1212016-03-08 15:37:41 +01006084 close(fd_out[1]);
Bram Moolenaar819524702018-02-27 19:10:00 +01006085 if (fd_err[1] >= 0)
Bram Moolenaarc25558b2016-03-03 21:02:23 +01006086 close(fd_err[1]);
Bram Moolenaarf65333c2016-03-08 18:27:21 +01006087 if (channel != NULL)
6088 {
Bram Moolenaar652de232019-04-04 20:13:09 +02006089 int in_fd = INVALID_FD;
6090 int out_fd = INVALID_FD;
6091 int err_fd = INVALID_FD;
6092
6093 if (!(use_file_for_in || use_null_for_in))
6094 in_fd = fd_in[1] >= 0 ? fd_in[1] : pty_master_fd;
6095
6096 if (!(use_file_for_out || use_null_for_out))
6097 out_fd = fd_out[0] >= 0 ? fd_out[0] : pty_master_fd;
6098
6099 // When using pty_master_fd only set it for stdout, do not duplicate
6100 // it for stderr, it only needs to be read once.
6101 if (!(use_out_for_err || use_file_for_err || use_null_for_err))
6102 {
6103 if (fd_err[0] >= 0)
6104 err_fd = fd_err[0];
6105 else if (out_fd != pty_master_fd)
6106 err_fd = pty_master_fd;
6107 }
Bram Moolenaar4e9d4432018-04-24 20:54:07 +02006108
6109 channel_set_pipes(channel, in_fd, out_fd, err_fd);
Bram Moolenaarf65333c2016-03-08 18:27:21 +01006110 channel_set_job(channel, job, options);
Bram Moolenaarf65333c2016-03-08 18:27:21 +01006111 }
Bram Moolenaar979e8c52017-08-01 15:08:07 +02006112 else
6113 {
6114 if (fd_in[1] >= 0)
6115 close(fd_in[1]);
6116 if (fd_out[0] >= 0)
6117 close(fd_out[0]);
6118 if (fd_err[0] >= 0)
6119 close(fd_err[0]);
6120 if (pty_master_fd >= 0)
6121 close(pty_master_fd);
6122 }
Bram Moolenaar6463ca22016-02-13 17:04:46 +01006123
Bram Moolenaar0f873732019-12-05 20:28:46 +01006124 // success!
Bram Moolenaar6463ca22016-02-13 17:04:46 +01006125 return;
6126
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01006127failed:
Bram Moolenaarde279892016-03-11 22:19:44 +01006128 channel_unref(channel);
Bram Moolenaar6463ca22016-02-13 17:04:46 +01006129 if (fd_in[0] >= 0)
Bram Moolenaar6463ca22016-02-13 17:04:46 +01006130 close(fd_in[0]);
Bram Moolenaare98d1212016-03-08 15:37:41 +01006131 if (fd_in[1] >= 0)
6132 close(fd_in[1]);
Bram Moolenaar6463ca22016-02-13 17:04:46 +01006133 if (fd_out[0] >= 0)
Bram Moolenaar6463ca22016-02-13 17:04:46 +01006134 close(fd_out[0]);
Bram Moolenaare98d1212016-03-08 15:37:41 +01006135 if (fd_out[1] >= 0)
Bram Moolenaar6463ca22016-02-13 17:04:46 +01006136 close(fd_out[1]);
Bram Moolenaar6463ca22016-02-13 17:04:46 +01006137 if (fd_err[0] >= 0)
Bram Moolenaar6463ca22016-02-13 17:04:46 +01006138 close(fd_err[0]);
Bram Moolenaare98d1212016-03-08 15:37:41 +01006139 if (fd_err[1] >= 0)
Bram Moolenaar6463ca22016-02-13 17:04:46 +01006140 close(fd_err[1]);
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02006141 if (pty_master_fd >= 0)
6142 close(pty_master_fd);
6143 if (pty_slave_fd >= 0)
6144 close(pty_slave_fd);
Bram Moolenaar835dc632016-02-07 14:27:38 +01006145}
6146
Bram Moolenaarb3051ce2019-01-31 15:52:11 +01006147 static char_u *
6148get_signal_name(int sig)
6149{
6150 int i;
6151 char_u numbuf[NUMBUFLEN];
6152
6153 if (sig == SIGKILL)
John Marriottefc41a52025-01-23 20:05:29 +01006154 return vim_strnsave((char_u *)"kill", STRLEN_LITERAL("kill"));
Bram Moolenaarb3051ce2019-01-31 15:52:11 +01006155
6156 for (i = 0; signal_info[i].sig != -1; i++)
6157 if (sig == signal_info[i].sig)
6158 return strlow_save((char_u *)signal_info[i].name);
6159
John Marriottefc41a52025-01-23 20:05:29 +01006160 i = vim_snprintf((char *)numbuf, NUMBUFLEN, "%d", sig);
6161 return vim_strnsave(numbuf, i);
Bram Moolenaarb3051ce2019-01-31 15:52:11 +01006162}
6163
Bram Moolenaar835dc632016-02-07 14:27:38 +01006164 char *
6165mch_job_status(job_T *job)
6166{
6167# ifdef HAVE_UNION_WAIT
6168 union wait status;
6169# else
6170 int status = -1;
6171# endif
6172 pid_t wait_pid = 0;
6173
6174# ifdef __NeXT__
6175 wait_pid = wait4(job->jv_pid, &status, WNOHANG, (struct rusage *)0);
6176# else
6177 wait_pid = waitpid(job->jv_pid, &status, WNOHANG);
6178# endif
6179 if (wait_pid == -1)
6180 {
Bram Moolenaar5c6a3c92023-03-04 13:23:26 +00006181 int waitpid_errno = errno;
6182 if (waitpid_errno == ECHILD && mch_process_running(job->jv_pid))
6183 // The process is alive, but it was probably reparented (for
6184 // example by ptrace called by a debugger like lldb or gdb).
6185 // Note: This assumes that process IDs are not reused.
6186 return "run";
6187
Bram Moolenaar0f873732019-12-05 20:28:46 +01006188 // process must have exited
Bram Moolenaarb0b98d52018-05-05 21:01:00 +02006189 if (job->jv_status < JOB_ENDED)
6190 ch_log(job->jv_channel, "Job no longer exists: %s",
Bram Moolenaar5c6a3c92023-03-04 13:23:26 +00006191 strerror(waitpid_errno));
Bram Moolenaar97792de2016-10-15 18:36:49 +02006192 goto return_dead;
Bram Moolenaar835dc632016-02-07 14:27:38 +01006193 }
6194 if (wait_pid == 0)
6195 return "run";
6196 if (WIFEXITED(status))
6197 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006198 // LINTED avoid "bitwise operation on signed value"
Bram Moolenaar835dc632016-02-07 14:27:38 +01006199 job->jv_exitval = WEXITSTATUS(status);
Bram Moolenaarb0b98d52018-05-05 21:01:00 +02006200 if (job->jv_status < JOB_ENDED)
6201 ch_log(job->jv_channel, "Job exited with %d", job->jv_exitval);
Bram Moolenaar97792de2016-10-15 18:36:49 +02006202 goto return_dead;
Bram Moolenaar835dc632016-02-07 14:27:38 +01006203 }
Bram Moolenaar76467df2016-02-12 19:30:26 +01006204 if (WIFSIGNALED(status))
6205 {
6206 job->jv_exitval = -1;
Bram Moolenaarb3051ce2019-01-31 15:52:11 +01006207 job->jv_termsig = get_signal_name(WTERMSIG(status));
6208 if (job->jv_status < JOB_ENDED && job->jv_termsig != NULL)
6209 ch_log(job->jv_channel, "Job terminated by signal \"%s\"",
6210 job->jv_termsig);
Bram Moolenaar97792de2016-10-15 18:36:49 +02006211 goto return_dead;
Bram Moolenaar76467df2016-02-12 19:30:26 +01006212 }
Bram Moolenaar835dc632016-02-07 14:27:38 +01006213 return "run";
Bram Moolenaar97792de2016-10-15 18:36:49 +02006214
6215return_dead:
Bram Moolenaar7df915d2016-11-17 17:25:32 +01006216 if (job->jv_status < JOB_ENDED)
Bram Moolenaar97792de2016-10-15 18:36:49 +02006217 job->jv_status = JOB_ENDED;
Bram Moolenaar97792de2016-10-15 18:36:49 +02006218 return "dead";
6219}
6220
6221 job_T *
6222mch_detect_ended_job(job_T *job_list)
6223{
6224# ifdef HAVE_UNION_WAIT
6225 union wait status;
6226# else
6227 int status = -1;
6228# endif
6229 pid_t wait_pid = 0;
6230 job_T *job;
6231
Bram Moolenaarc4d4ac22016-11-07 22:42:57 +01006232# ifndef USE_SYSTEM
Bram Moolenaar0f873732019-12-05 20:28:46 +01006233 // Do not do this when waiting for a shell command to finish, we would get
6234 // the exit value here (and discard it), the exit value obtained there
6235 // would then be wrong.
Bram Moolenaarc4d4ac22016-11-07 22:42:57 +01006236 if (dont_check_job_ended > 0)
6237 return NULL;
6238# endif
6239
Bram Moolenaar97792de2016-10-15 18:36:49 +02006240# ifdef __NeXT__
6241 wait_pid = wait4(-1, &status, WNOHANG, (struct rusage *)0);
6242# else
6243 wait_pid = waitpid(-1, &status, WNOHANG);
6244# endif
6245 if (wait_pid <= 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01006246 // no process ended
Bram Moolenaar97792de2016-10-15 18:36:49 +02006247 return NULL;
6248 for (job = job_list; job != NULL; job = job->jv_next)
6249 {
6250 if (job->jv_pid == wait_pid)
6251 {
6252 if (WIFEXITED(status))
Bram Moolenaar0f873732019-12-05 20:28:46 +01006253 // LINTED avoid "bitwise operation on signed value"
Bram Moolenaar97792de2016-10-15 18:36:49 +02006254 job->jv_exitval = WEXITSTATUS(status);
6255 else if (WIFSIGNALED(status))
Bram Moolenaarb3051ce2019-01-31 15:52:11 +01006256 {
Bram Moolenaar97792de2016-10-15 18:36:49 +02006257 job->jv_exitval = -1;
Bram Moolenaarb3051ce2019-01-31 15:52:11 +01006258 job->jv_termsig = get_signal_name(WTERMSIG(status));
6259 }
Bram Moolenaar7df915d2016-11-17 17:25:32 +01006260 if (job->jv_status < JOB_ENDED)
Bram Moolenaar97792de2016-10-15 18:36:49 +02006261 {
6262 ch_log(job->jv_channel, "Job ended");
6263 job->jv_status = JOB_ENDED;
6264 }
6265 return job;
6266 }
6267 }
6268 return NULL;
Bram Moolenaar835dc632016-02-07 14:27:38 +01006269}
6270
Bram Moolenaar3a117e12016-10-30 21:57:52 +01006271/*
6272 * Send a (deadly) signal to "job".
6273 * Return FAIL if "how" is not a valid name.
6274 */
Bram Moolenaar835dc632016-02-07 14:27:38 +01006275 int
Bram Moolenaar2d33e902017-08-11 16:31:54 +02006276mch_signal_job(job_T *job, char_u *how)
Bram Moolenaar835dc632016-02-07 14:27:38 +01006277{
Bram Moolenaar6463ca22016-02-13 17:04:46 +01006278 int sig = -1;
Bram Moolenaar835dc632016-02-07 14:27:38 +01006279
Bram Moolenaar923d9262016-02-25 20:56:01 +01006280 if (*how == NUL || STRCMP(how, "term") == 0)
Bram Moolenaar835dc632016-02-07 14:27:38 +01006281 sig = SIGTERM;
Bram Moolenaar923d9262016-02-25 20:56:01 +01006282 else if (STRCMP(how, "hup") == 0)
6283 sig = SIGHUP;
Bram Moolenaar835dc632016-02-07 14:27:38 +01006284 else if (STRCMP(how, "quit") == 0)
6285 sig = SIGQUIT;
Bram Moolenaar923d9262016-02-25 20:56:01 +01006286 else if (STRCMP(how, "int") == 0)
6287 sig = SIGINT;
Bram Moolenaar835dc632016-02-07 14:27:38 +01006288 else if (STRCMP(how, "kill") == 0)
6289 sig = SIGKILL;
Bram Moolenaarb13501f2017-07-22 22:32:56 +02006290#ifdef SIGWINCH
6291 else if (STRCMP(how, "winch") == 0)
6292 sig = SIGWINCH;
6293#endif
Keith Thompson184f71c2024-01-04 21:19:04 +01006294 else if (SAFE_isdigit(*how))
Bram Moolenaar835dc632016-02-07 14:27:38 +01006295 sig = atoi((char *)how);
6296 else
6297 return FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01006298
Bram Moolenaar76ab4fd2018-12-08 14:39:05 +01006299 // Never kill ourselves!
6300 if (job->jv_pid != 0)
6301 {
6302 // TODO: have an option to only kill the process, not the group?
6303 kill(-job->jv_pid, sig);
6304 kill(job->jv_pid, sig);
6305 }
Bram Moolenaar76467df2016-02-12 19:30:26 +01006306
Bram Moolenaar835dc632016-02-07 14:27:38 +01006307 return OK;
6308}
Bram Moolenaar76467df2016-02-12 19:30:26 +01006309
6310/*
6311 * Clear the data related to "job".
6312 */
6313 void
6314mch_clear_job(job_T *job)
6315{
Bram Moolenaar0f873732019-12-05 20:28:46 +01006316 // call waitpid because child process may become zombie
Bram Moolenaar76467df2016-02-12 19:30:26 +01006317# ifdef __NeXT__
Bram Moolenaar4ca812b2016-03-02 21:51:16 +01006318 (void)wait4(job->jv_pid, NULL, WNOHANG, (struct rusage *)0);
Bram Moolenaar76467df2016-02-12 19:30:26 +01006319# else
Bram Moolenaar4ca812b2016-03-02 21:51:16 +01006320 (void)waitpid(job->jv_pid, NULL, WNOHANG);
Bram Moolenaar76467df2016-02-12 19:30:26 +01006321# endif
6322}
Bram Moolenaar835dc632016-02-07 14:27:38 +01006323#endif
6324
Bram Moolenaar13ebb032017-08-26 22:02:51 +02006325#if defined(FEAT_TERMINAL) || defined(PROTO)
6326 int
6327mch_create_pty_channel(job_T *job, jobopt_T *options)
6328{
6329 int pty_master_fd = -1;
6330 int pty_slave_fd = -1;
6331 channel_T *channel;
6332
Bram Moolenaar59386482019-02-10 22:43:46 +01006333 open_pty(&pty_master_fd, &pty_slave_fd, &job->jv_tty_out, &job->jv_tty_in);
Bram Moolenaard0342202020-06-29 22:40:42 +02006334 if (pty_master_fd < 0 || pty_slave_fd < 0)
6335 return FAIL;
Bram Moolenaar13ebb032017-08-26 22:02:51 +02006336 close(pty_slave_fd);
6337
6338 channel = add_channel();
6339 if (channel == NULL)
Bram Moolenaar1b9f9d32017-09-05 23:32:38 +02006340 {
6341 close(pty_master_fd);
Bram Moolenaar13ebb032017-08-26 22:02:51 +02006342 return FAIL;
Bram Moolenaar1b9f9d32017-09-05 23:32:38 +02006343 }
Bram Moolenaarf3360612017-10-01 16:21:31 +02006344 if (job->jv_tty_out != NULL)
6345 ch_log(channel, "using pty %s on fd %d",
6346 job->jv_tty_out, pty_master_fd);
Bram Moolenaar0f873732019-12-05 20:28:46 +01006347 job->jv_channel = channel; // ch_refcount was set by add_channel()
Bram Moolenaar13ebb032017-08-26 22:02:51 +02006348 channel->ch_keep_open = TRUE;
6349
Bram Moolenaar0f873732019-12-05 20:28:46 +01006350 // Only set the pty_master_fd for stdout, do not duplicate it for stderr,
6351 // it only needs to be read once.
Bram Moolenaarb0b98d52018-05-05 21:01:00 +02006352 channel_set_pipes(channel, pty_master_fd, pty_master_fd, INVALID_FD);
Bram Moolenaar13ebb032017-08-26 22:02:51 +02006353 channel_set_job(channel, job, options);
6354 return OK;
6355}
6356#endif
6357
Bram Moolenaar071d4272004-06-13 20:20:40 +00006358/*
6359 * Check for CTRL-C typed by reading all available characters.
6360 * In cooked mode we should get SIGINT, no need to check.
6361 */
6362 void
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02006363mch_breakcheck(int force)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006364{
Bram Moolenaar26e86442020-05-17 14:06:16 +02006365 if ((mch_cur_tmode == TMODE_RAW || force)
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02006366 && RealWaitForChar(read_cmd_fd, 0L, NULL, NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006367 fill_input_buf(FALSE);
6368}
6369
6370/*
Bram Moolenaar943bb2b2016-03-19 14:11:18 +01006371 * Wait "msec" msec until a character is available from the mouse, keyboard,
6372 * from inbuf[].
6373 * "msec" == -1 will block forever.
6374 * Invokes timer callbacks when needed.
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006375 * When "ignore_input" is TRUE even check for pending input when input is
6376 * already available.
Bram Moolenaarcda77642016-06-04 13:32:35 +02006377 * "interrupted" (if not NULL) is set to TRUE when no character is available
6378 * but something else needs to be done.
Bram Moolenaar40b1b542016-04-20 20:18:23 +02006379 * Returns TRUE when a character is available.
Bram Moolenaarcda77642016-06-04 13:32:35 +02006380 * When a GUI is being used, this will never get called -- webb
Bram Moolenaar071d4272004-06-13 20:20:40 +00006381 */
6382 static int
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006383WaitForChar(long msec, int *interrupted, int ignore_input)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006384{
Bram Moolenaar943bb2b2016-03-19 14:11:18 +01006385#ifdef FEAT_TIMERS
Bram Moolenaarc9e649a2017-12-18 18:14:47 +01006386 return ui_wait_for_chars_or_timer(
6387 msec, WaitForCharOrMouse, interrupted, ignore_input) == OK;
Bram Moolenaar943bb2b2016-03-19 14:11:18 +01006388#else
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006389 return WaitForCharOrMouse(msec, interrupted, ignore_input);
Bram Moolenaar943bb2b2016-03-19 14:11:18 +01006390#endif
6391}
6392
6393/*
6394 * Wait "msec" msec until a character is available from the mouse or keyboard
6395 * or from inbuf[].
6396 * "msec" == -1 will block forever.
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006397 * for "ignore_input" see WaitForCharOr().
Bram Moolenaarcda77642016-06-04 13:32:35 +02006398 * "interrupted" (if not NULL) is set to TRUE when no character is available
6399 * but something else needs to be done.
Bram Moolenaar943bb2b2016-03-19 14:11:18 +01006400 * When a GUI is being used, this will never get called -- webb
6401 */
6402 static int
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006403WaitForCharOrMouse(long msec, int *interrupted, int ignore_input)
Bram Moolenaar943bb2b2016-03-19 14:11:18 +01006404{
Bram Moolenaar071d4272004-06-13 20:20:40 +00006405#ifdef FEAT_MOUSE_GPM
6406 int gpm_process_wanted;
6407#endif
6408#ifdef FEAT_XCLIPBOARD
6409 int rest;
6410#endif
6411 int avail;
6412
Bram Moolenaar0f873732019-12-05 20:28:46 +01006413 if (!ignore_input && input_available()) // something in inbuf[]
Bram Moolenaar071d4272004-06-13 20:20:40 +00006414 return 1;
6415
6416#if defined(FEAT_MOUSE_DEC)
Bram Moolenaar0f873732019-12-05 20:28:46 +01006417 // May need to query the mouse position.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006418 if (WantQueryMouse)
6419 {
Bram Moolenaar6bb68362005-03-22 23:03:44 +00006420 WantQueryMouse = FALSE;
Bram Moolenaar92fd5992019-05-02 23:00:22 +02006421 if (!no_query_mouse_for_testing)
Bram Moolenaar424bcae2022-01-31 14:59:41 +00006422 mch_write((char_u *)"\033[1'|", 5);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006423 }
6424#endif
6425
6426 /*
6427 * For FEAT_MOUSE_GPM and FEAT_XCLIPBOARD we loop here to process mouse
6428 * events. This is a bit complicated, because they might both be defined.
6429 */
6430#if defined(FEAT_MOUSE_GPM) || defined(FEAT_XCLIPBOARD)
6431# ifdef FEAT_XCLIPBOARD
6432 rest = 0;
6433 if (do_xterm_trace())
6434 rest = msec;
6435# endif
6436 do
6437 {
6438# ifdef FEAT_XCLIPBOARD
6439 if (rest != 0)
6440 {
6441 msec = XT_TRACE_DELAY;
6442 if (rest >= 0 && rest < XT_TRACE_DELAY)
6443 msec = rest;
6444 if (rest >= 0)
6445 rest -= msec;
6446 }
6447# endif
Yee Cheng Chin4314e4f2022-10-08 13:50:05 +01006448# ifdef FEAT_SOUND_MACOSX
6449 // Invoke any pending sound callbacks.
6450 process_cfrunloop();
6451# endif
Bram Moolenaar28e67e02019-08-15 23:05:49 +02006452# ifdef FEAT_SOUND_CANBERRA
6453 // Invoke any pending sound callbacks.
6454 if (has_sound_callback_in_queue())
6455 invoke_sound_callback();
6456# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006457# ifdef FEAT_MOUSE_GPM
6458 gpm_process_wanted = 0;
Bram Moolenaar8fdd7212016-03-26 19:41:48 +01006459 avail = RealWaitForChar(read_cmd_fd, msec,
Bram Moolenaarcda77642016-06-04 13:32:35 +02006460 &gpm_process_wanted, interrupted);
Bram Moolenaarb5432d82019-08-30 19:28:25 +02006461 if (!avail && !gpm_process_wanted)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006462# else
Bram Moolenaarcda77642016-06-04 13:32:35 +02006463 avail = RealWaitForChar(read_cmd_fd, msec, NULL, interrupted);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006464 if (!avail)
Bram Moolenaarb5432d82019-08-30 19:28:25 +02006465# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006466 {
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006467 if (!ignore_input && input_available())
Bram Moolenaar071d4272004-06-13 20:20:40 +00006468 return 1;
6469# ifdef FEAT_XCLIPBOARD
6470 if (rest == 0 || !do_xterm_trace())
6471# endif
6472 break;
6473 }
6474 }
6475 while (FALSE
6476# ifdef FEAT_MOUSE_GPM
6477 || (gpm_process_wanted && mch_gpm_process() == 0)
6478# endif
6479# ifdef FEAT_XCLIPBOARD
6480 || (!avail && rest != 0)
6481# endif
Bram Moolenaar8fdd7212016-03-26 19:41:48 +01006482 )
6483 ;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006484
6485#else
Bram Moolenaarcda77642016-06-04 13:32:35 +02006486 avail = RealWaitForChar(read_cmd_fd, msec, NULL, interrupted);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006487#endif
6488 return avail;
6489}
6490
Bram Moolenaar4ffa0702013-12-11 17:12:37 +01006491#ifndef VMS
Bram Moolenaar071d4272004-06-13 20:20:40 +00006492/*
6493 * Wait "msec" msec until a character is available from file descriptor "fd".
Bram Moolenaar493c7a82011-09-07 14:06:47 +02006494 * "msec" == 0 will check for characters once.
6495 * "msec" == -1 will block until a character is available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006496 * When a GUI is being used, this will not be used for input -- webb
Bram Moolenaar071d4272004-06-13 20:20:40 +00006497 * Or when a Linux GPM mouse event is waiting.
Bram Moolenaar93c88e02015-09-15 14:12:05 +02006498 * Or when a clientserver message is on the queue.
Bram Moolenaarcda77642016-06-04 13:32:35 +02006499 * "interrupted" (if not NULL) is set to TRUE when no character is available
6500 * but something else needs to be done.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006501 */
Bram Moolenaarec70bdd2016-02-18 22:17:42 +01006502 static int
Bram Moolenaarcda77642016-06-04 13:32:35 +02006503RealWaitForChar(int fd, long msec, int *check_for_gpm UNUSED, int *interrupted)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006504{
6505 int ret;
Bram Moolenaarec70bdd2016-02-18 22:17:42 +01006506 int result;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006507#if defined(FEAT_XCLIPBOARD) || defined(USE_XSMP) || defined(FEAT_MZSCHEME)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006508 static int busy = FALSE;
6509
Bram Moolenaar0f873732019-12-05 20:28:46 +01006510 // May retry getting characters after an event was handled.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006511# define MAY_LOOP
6512
Bram Moolenaar833eb1d2016-11-24 17:22:50 +01006513# ifdef ELAPSED_FUNC
Bram Moolenaar0f873732019-12-05 20:28:46 +01006514 // Remember at what time we started, so that we know how much longer we
6515 // should wait after being interrupted.
Bram Moolenaar1ac56c22019-01-17 22:28:22 +01006516 long start_msec = msec;
6517 elapsed_T start_tv;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006518
Bram Moolenaar76b6dfe2016-06-04 14:37:22 +02006519 if (msec > 0)
Bram Moolenaar833eb1d2016-11-24 17:22:50 +01006520 ELAPSED_INIT(start_tv);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006521# endif
6522
Bram Moolenaar0f873732019-12-05 20:28:46 +01006523 // Handle being called recursively. This may happen for the session
6524 // manager stuff, it may save the file, which does a breakcheck.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006525 if (busy)
6526 return 0;
6527#endif
6528
6529#ifdef MAY_LOOP
Bram Moolenaar35fdbb52005-07-09 21:08:57 +00006530 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006531#endif
6532 {
6533#ifdef MAY_LOOP
Bram Moolenaar0f873732019-12-05 20:28:46 +01006534 int finished = TRUE; // default is to 'loop' just once
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006535# ifdef FEAT_MZSCHEME
6536 int mzquantum_used = FALSE;
6537# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006538#endif
6539#ifndef HAVE_SELECT
Bram Moolenaar0f873732019-12-05 20:28:46 +01006540 // each channel may use in, out and err
Foxe Chenb90c2392025-06-27 21:10:35 +02006541 struct pollfd fds[7 + 3 * MAX_OPEN_CHANNELS];
Bram Moolenaar071d4272004-06-13 20:20:40 +00006542 int nfd;
Foxe Chenb90c2392025-06-27 21:10:35 +02006543# ifdef FEAT_WAYLAND_CLIPBOARD
6544 int wayland_idx = -1;
6545# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006546# ifdef FEAT_XCLIPBOARD
6547 int xterm_idx = -1;
6548# endif
6549# ifdef FEAT_MOUSE_GPM
6550 int gpm_idx = -1;
6551# endif
6552# ifdef USE_XSMP
6553 int xsmp_idx = -1;
6554# endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006555 int towait = (int)msec;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006556
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006557# ifdef FEAT_MZSCHEME
6558 mzvim_check_threads();
6559 if (mzthreads_allowed() && p_mzq > 0 && (msec < 0 || msec > p_mzq))
6560 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006561 towait = (int)p_mzq; // don't wait longer than 'mzquantum'
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006562 mzquantum_used = TRUE;
6563 }
6564# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006565 fds[0].fd = fd;
6566 fds[0].events = POLLIN;
6567 nfd = 1;
6568
Foxe Chenb90c2392025-06-27 21:10:35 +02006569# ifdef FEAT_WAYLAND_CLIPBOARD
6570 if (wayland_may_restore_connection())
6571 {
6572 wayland_idx = nfd;
6573 fds[nfd].fd = vwl_display_fd;
6574 fds[nfd].events = POLLIN;
6575 nfd++;
6576 }
6577# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006578# ifdef FEAT_XCLIPBOARD
Bram Moolenaarb1e26502014-11-19 18:48:46 +01006579 may_restore_clipboard();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006580 if (xterm_Shell != (Widget)0)
6581 {
6582 xterm_idx = nfd;
6583 fds[nfd].fd = ConnectionNumber(xterm_dpy);
6584 fds[nfd].events = POLLIN;
6585 nfd++;
6586 }
6587# endif
6588# ifdef FEAT_MOUSE_GPM
6589 if (check_for_gpm != NULL && gpm_flag && gpm_fd >= 0)
6590 {
6591 gpm_idx = nfd;
6592 fds[nfd].fd = gpm_fd;
6593 fds[nfd].events = POLLIN;
6594 nfd++;
6595 }
6596# endif
6597# ifdef USE_XSMP
6598 if (xsmp_icefd != -1)
6599 {
6600 xsmp_idx = nfd;
6601 fds[nfd].fd = xsmp_icefd;
6602 fds[nfd].events = POLLIN;
6603 nfd++;
6604 }
6605# endif
Foxe Chenb90c2392025-06-27 21:10:35 +02006606# ifdef FEAT_JOB_CHANNEL
Bram Moolenaarf3360612017-10-01 16:21:31 +02006607 nfd = channel_poll_setup(nfd, &fds, &towait);
Foxe Chenb90c2392025-06-27 21:10:35 +02006608# endif
Bram Moolenaarcda77642016-06-04 13:32:35 +02006609 if (interrupted != NULL)
6610 *interrupted = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006611
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006612 ret = poll(fds, nfd, towait);
Bram Moolenaarec70bdd2016-02-18 22:17:42 +01006613
6614 result = ret > 0 && (fds[0].revents & POLLIN);
Bram Moolenaarcda77642016-06-04 13:32:35 +02006615 if (result == 0 && interrupted != NULL && ret > 0)
6616 *interrupted = TRUE;
Bram Moolenaarec70bdd2016-02-18 22:17:42 +01006617
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006618# ifdef FEAT_MZSCHEME
6619 if (ret == 0 && mzquantum_used)
Bram Moolenaar0f873732019-12-05 20:28:46 +01006620 // MzThreads scheduling is required and timeout occurred
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006621 finished = FALSE;
6622# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006623
Foxe Chenb90c2392025-06-27 21:10:35 +02006624# ifdef FEAT_WAYLAND_CLIPBOARD
6625 // Technically we should first call wl_display_prepare_read() before
6626 // polling the fd, then read and dispatch after we poll. However that is
6627 // only needed for multi threaded environments to prevent deadlocks so
6628 // we are fine.
6629 if (fds[wayland_idx].revents & POLLIN)
6630 wayland_client_update();
6631# endif
6632
Bram Moolenaar071d4272004-06-13 20:20:40 +00006633# ifdef FEAT_XCLIPBOARD
6634 if (xterm_Shell != (Widget)0 && (fds[xterm_idx].revents & POLLIN))
6635 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006636 xterm_update(); // Maybe we should hand out clipboard
Bram Moolenaar071d4272004-06-13 20:20:40 +00006637 if (--ret == 0 && !input_available())
Bram Moolenaar0f873732019-12-05 20:28:46 +01006638 // Try again
Bram Moolenaar071d4272004-06-13 20:20:40 +00006639 finished = FALSE;
6640 }
6641# endif
6642# ifdef FEAT_MOUSE_GPM
6643 if (gpm_idx >= 0 && (fds[gpm_idx].revents & POLLIN))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006644 *check_for_gpm = 1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006645# endif
6646# ifdef USE_XSMP
6647 if (xsmp_idx >= 0 && (fds[xsmp_idx].revents & (POLLIN | POLLHUP)))
6648 {
6649 if (fds[xsmp_idx].revents & POLLIN)
6650 {
6651 busy = TRUE;
6652 xsmp_handle_requests();
6653 busy = FALSE;
6654 }
6655 else if (fds[xsmp_idx].revents & POLLHUP)
6656 {
6657 if (p_verbose > 0)
Bram Moolenaar32526b32019-01-19 17:43:09 +01006658 verb_msg(_("XSMP lost ICE connection"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00006659 xsmp_close();
6660 }
6661 if (--ret == 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01006662 finished = FALSE; // Try again
Bram Moolenaar071d4272004-06-13 20:20:40 +00006663 }
6664# endif
Foxe Chenb90c2392025-06-27 21:10:35 +02006665# ifdef FEAT_JOB_CHANNEL
Bram Moolenaar2c519cf2019-03-21 21:45:34 +01006666 // also call when ret == 0, we may be polling a keep-open channel
Bram Moolenaarf3360612017-10-01 16:21:31 +02006667 if (ret >= 0)
Bram Moolenaar2c519cf2019-03-21 21:45:34 +01006668 channel_poll_check(ret, &fds);
Foxe Chenb90c2392025-06-27 21:10:35 +02006669# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006670
Bram Moolenaar0f873732019-12-05 20:28:46 +01006671#else // HAVE_SELECT
Bram Moolenaar071d4272004-06-13 20:20:40 +00006672
6673 struct timeval tv;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006674 struct timeval *tvp;
Bram Moolenaar61fb8d82018-11-12 21:45:08 +01006675 // These are static because they can take 8 Kbyte each and cause the
6676 // signal stack to run out with -O3.
6677 static fd_set rfds, wfds, efds;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006678 int maxfd;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006679 long towait = msec;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006680
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006681# ifdef FEAT_MZSCHEME
6682 mzvim_check_threads();
6683 if (mzthreads_allowed() && p_mzq > 0 && (msec < 0 || msec > p_mzq))
6684 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006685 towait = p_mzq; // don't wait longer than 'mzquantum'
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006686 mzquantum_used = TRUE;
6687 }
6688# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006689
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006690 if (towait >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006691 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006692 tv.tv_sec = towait / 1000;
6693 tv.tv_usec = (towait % 1000) * (1000000/1000);
6694 tvp = &tv;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006695 }
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006696 else
6697 tvp = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006698
6699 /*
6700 * Select on ready for reading and exceptional condition (end of file).
6701 */
Bram Moolenaar493c7a82011-09-07 14:06:47 +02006702select_eintr:
6703 FD_ZERO(&rfds);
Bram Moolenaar8b877ac2016-03-28 19:16:20 +02006704 FD_ZERO(&wfds);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006705 FD_ZERO(&efds);
6706 FD_SET(fd, &rfds);
K.Takatab247e062022-02-07 10:45:23 +00006707# ifndef __QNX__
Bram Moolenaar0f873732019-12-05 20:28:46 +01006708 // For QNX select() always returns 1 if this is set. Why?
Bram Moolenaar071d4272004-06-13 20:20:40 +00006709 FD_SET(fd, &efds);
6710# endif
6711 maxfd = fd;
6712
Foxe Chenb90c2392025-06-27 21:10:35 +02006713# ifdef FEAT_WAYLAND_CLIPBOARD
6714
6715 if (wayland_may_restore_connection())
6716 {
6717 FD_SET(wayland_display_fd, &rfds);
6718
6719 if (maxfd < wayland_display_fd)
6720 maxfd = wayland_display_fd;
6721 }
6722# endif
6723
Bram Moolenaar071d4272004-06-13 20:20:40 +00006724# ifdef FEAT_XCLIPBOARD
Foxe Chenb90c2392025-06-27 21:10:35 +02006725 may_restore_x11_clipboard();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006726 if (xterm_Shell != (Widget)0)
6727 {
6728 FD_SET(ConnectionNumber(xterm_dpy), &rfds);
6729 if (maxfd < ConnectionNumber(xterm_dpy))
6730 maxfd = ConnectionNumber(xterm_dpy);
Bram Moolenaardd82d692012-08-15 17:26:57 +02006731
Bram Moolenaar0f873732019-12-05 20:28:46 +01006732 // An event may have already been read but not handled. In
6733 // particularly, XFlush may cause this.
Bram Moolenaardd82d692012-08-15 17:26:57 +02006734 xterm_update();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006735 }
6736# endif
6737# ifdef FEAT_MOUSE_GPM
6738 if (check_for_gpm != NULL && gpm_flag && gpm_fd >= 0)
6739 {
6740 FD_SET(gpm_fd, &rfds);
6741 FD_SET(gpm_fd, &efds);
6742 if (maxfd < gpm_fd)
6743 maxfd = gpm_fd;
6744 }
6745# endif
6746# ifdef USE_XSMP
6747 if (xsmp_icefd != -1)
6748 {
6749 FD_SET(xsmp_icefd, &rfds);
6750 FD_SET(xsmp_icefd, &efds);
6751 if (maxfd < xsmp_icefd)
6752 maxfd = xsmp_icefd;
6753 }
6754# endif
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01006755# ifdef FEAT_JOB_CHANNEL
Bram Moolenaarf3360612017-10-01 16:21:31 +02006756 maxfd = channel_select_setup(maxfd, &rfds, &wfds, &tv, &tvp);
Bram Moolenaardd82d692012-08-15 17:26:57 +02006757# endif
Bram Moolenaarcda77642016-06-04 13:32:35 +02006758 if (interrupted != NULL)
6759 *interrupted = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006760
Bram Moolenaar643b6142018-09-12 20:29:09 +02006761 ret = select(maxfd + 1, SELECT_TYPE_ARG234 &rfds,
6762 SELECT_TYPE_ARG234 &wfds, SELECT_TYPE_ARG234 &efds, tvp);
Bram Moolenaarec70bdd2016-02-18 22:17:42 +01006763 result = ret > 0 && FD_ISSET(fd, &rfds);
6764 if (result)
6765 --ret;
Bram Moolenaarcda77642016-06-04 13:32:35 +02006766 else if (interrupted != NULL && ret > 0)
6767 *interrupted = TRUE;
Bram Moolenaarec70bdd2016-02-18 22:17:42 +01006768
Bram Moolenaar493c7a82011-09-07 14:06:47 +02006769# ifdef EINTR
6770 if (ret == -1 && errno == EINTR)
Bram Moolenaar2e7b1df2011-10-12 21:04:20 +02006771 {
dbivolaruab16ad32021-12-29 19:41:47 +00006772 // Check whether the EINTR is caused by SIGTSTP
6773 if (got_tstp && !in_mch_suspend)
6774 {
6775 exarg_T ea;
dbivolaru79a6e252022-01-23 16:41:14 +00006776
dbivolaruab16ad32021-12-29 19:41:47 +00006777 ea.forceit = TRUE;
6778 ex_stop(&ea);
6779 got_tstp = FALSE;
6780 }
6781
Bram Moolenaar0f873732019-12-05 20:28:46 +01006782 // Check whether window has been resized, EINTR may be caused by
6783 // SIGWINCH.
Bram Moolenaar2e7b1df2011-10-12 21:04:20 +02006784 if (do_resize)
Bram Moolenaar55f1b822023-06-21 13:42:48 +01006785 {
Bram Moolenaar545c8a52023-06-21 15:51:47 +01006786# ifdef FEAT_EVAL
Bram Moolenaar55f1b822023-06-21 13:42:48 +01006787 ch_log(NULL, "calling handle_resize() in RealWaitForChar()");
Bram Moolenaar545c8a52023-06-21 15:51:47 +01006788# endif
Bram Moolenaar2e7b1df2011-10-12 21:04:20 +02006789 handle_resize();
Bram Moolenaar55f1b822023-06-21 13:42:48 +01006790 }
Bram Moolenaar2e7b1df2011-10-12 21:04:20 +02006791
Bram Moolenaar0f873732019-12-05 20:28:46 +01006792 // Interrupted by a signal, need to try again. We ignore msec
6793 // here, because we do want to check even after a timeout if
6794 // characters are available. Needed for reading output of an
6795 // external command after the process has finished.
Bram Moolenaar493c7a82011-09-07 14:06:47 +02006796 goto select_eintr;
Bram Moolenaar2e7b1df2011-10-12 21:04:20 +02006797 }
Bram Moolenaar493c7a82011-09-07 14:06:47 +02006798# endif
Bram Moolenaar311d9822007-02-27 15:48:28 +00006799# ifdef __TANDEM
6800 if (ret == -1 && errno == ENOTSUP)
6801 {
6802 FD_ZERO(&rfds);
6803 FD_ZERO(&efds);
6804 ret = 0;
6805 }
Bram Moolenaar493c7a82011-09-07 14:06:47 +02006806# endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006807# ifdef FEAT_MZSCHEME
6808 if (ret == 0 && mzquantum_used)
Bram Moolenaar0f873732019-12-05 20:28:46 +01006809 // loop if MzThreads must be scheduled and timeout occurred
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006810 finished = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006811# endif
6812
Foxe Chenb90c2392025-06-27 21:10:35 +02006813# ifdef FEAT_WAYLAND_CLIPBOARD
6814 // Technically we should first call wl_display_prepare_read() before
6815 // polling the fd, then read and dispatch after we poll. However that is
6816 // only needed for multi threaded environments to prevent deadlocks so
6817 // we are fine.
6818 if (ret > 0 && FD_ISSET(wayland_display_fd, &rfds))
6819 wayland_client_update();
6820# endif
6821
Bram Moolenaar071d4272004-06-13 20:20:40 +00006822# ifdef FEAT_XCLIPBOARD
6823 if (ret > 0 && xterm_Shell != (Widget)0
6824 && FD_ISSET(ConnectionNumber(xterm_dpy), &rfds))
6825 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006826 xterm_update(); // Maybe we should hand out clipboard
6827 // continue looping when we only got the X event and the input
6828 // buffer is empty
Bram Moolenaar071d4272004-06-13 20:20:40 +00006829 if (--ret == 0 && !input_available())
6830 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006831 // Try again
Bram Moolenaar071d4272004-06-13 20:20:40 +00006832 finished = FALSE;
6833 }
6834 }
6835# endif
6836# ifdef FEAT_MOUSE_GPM
Bram Moolenaar33fc4a62022-02-23 18:07:38 +00006837 if (ret > 0 && check_for_gpm != NULL && gpm_flag && gpm_fd >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006838 {
6839 if (FD_ISSET(gpm_fd, &efds))
6840 gpm_close();
6841 else if (FD_ISSET(gpm_fd, &rfds))
6842 *check_for_gpm = 1;
6843 }
6844# endif
6845# ifdef USE_XSMP
6846 if (ret > 0 && xsmp_icefd != -1)
6847 {
6848 if (FD_ISSET(xsmp_icefd, &efds))
6849 {
6850 if (p_verbose > 0)
Bram Moolenaar32526b32019-01-19 17:43:09 +01006851 verb_msg(_("XSMP lost ICE connection"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00006852 xsmp_close();
6853 if (--ret == 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01006854 finished = FALSE; // keep going if event was only one
Bram Moolenaar071d4272004-06-13 20:20:40 +00006855 }
6856 else if (FD_ISSET(xsmp_icefd, &rfds))
6857 {
6858 busy = TRUE;
6859 xsmp_handle_requests();
6860 busy = FALSE;
6861 if (--ret == 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01006862 finished = FALSE; // keep going if event was only one
Bram Moolenaar071d4272004-06-13 20:20:40 +00006863 }
6864 }
6865# endif
Foxe Chenb90c2392025-06-27 21:10:35 +02006866# ifdef FEAT_JOB_CHANNEL
Bram Moolenaar0f873732019-12-05 20:28:46 +01006867 // also call when ret == 0, we may be polling a keep-open channel
Bram Moolenaarf3360612017-10-01 16:21:31 +02006868 if (ret >= 0)
Yegappan Lakshmanan6b085b92022-09-04 12:47:21 +01006869 (void)channel_select_check(ret, &rfds, &wfds);
Foxe Chenb90c2392025-06-27 21:10:35 +02006870# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006871
Bram Moolenaar0f873732019-12-05 20:28:46 +01006872#endif // HAVE_SELECT
Bram Moolenaar071d4272004-06-13 20:20:40 +00006873
6874#ifdef MAY_LOOP
6875 if (finished || msec == 0)
6876 break;
6877
Bram Moolenaar93c88e02015-09-15 14:12:05 +02006878# ifdef FEAT_CLIENTSERVER
6879 if (server_waiting())
6880 break;
6881# endif
6882
Bram Moolenaar0f873732019-12-05 20:28:46 +01006883 // We're going to loop around again, find out for how long
Bram Moolenaar071d4272004-06-13 20:20:40 +00006884 if (msec > 0)
6885 {
Bram Moolenaar833eb1d2016-11-24 17:22:50 +01006886# ifdef ELAPSED_FUNC
Bram Moolenaar0f873732019-12-05 20:28:46 +01006887 // Compute remaining wait time.
Bram Moolenaar833eb1d2016-11-24 17:22:50 +01006888 msec = start_msec - ELAPSED_FUNC(start_tv);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006889# else
Bram Moolenaar0f873732019-12-05 20:28:46 +01006890 // Guess we got interrupted halfway.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006891 msec = msec / 2;
6892# endif
6893 if (msec <= 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01006894 break; // waited long enough
Bram Moolenaar071d4272004-06-13 20:20:40 +00006895 }
6896#endif
6897 }
6898
Bram Moolenaarec70bdd2016-02-18 22:17:42 +01006899 return result;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006900}
6901
Bram Moolenaar071d4272004-06-13 20:20:40 +00006902/*
Christian Brabandt6cc30272024-12-13 17:54:33 +01006903 * Expand a path into all matching files and/or directories. Handles "*",
6904 * "?", "[a-z]", "**", etc.
6905 * "path" has backslashes before chars that are not to be expanded.
6906 * Returns the number of matches found.
6907 */
6908 int
6909mch_expandpath(
6910 garray_T *gap,
6911 char_u *path,
6912 int flags) // EW_* flags
6913{
6914 return unix_expandpath(gap, path, 0, flags, FALSE);
6915}
6916
6917/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00006918 * mch_expand_wildcards() - this code does wild-card pattern matching using
6919 * the shell
6920 *
6921 * return OK for success, FAIL for error (you may lose some memory) and put
6922 * an error message in *file.
6923 *
6924 * num_pat is number of input patterns
6925 * pat is array of pointers to input patterns
6926 * num_file is pointer to number of matched file names
6927 * file is pointer to array of pointers to matched file names
6928 */
6929
6930#ifndef SEEK_SET
6931# define SEEK_SET 0
6932#endif
6933#ifndef SEEK_END
6934# define SEEK_END 2
6935#endif
6936
Bram Moolenaar5555acc2006-04-07 21:33:12 +00006937#define SHELL_SPECIAL (char_u *)"\t \"&'$;<>()\\|"
Bram Moolenaar316059c2006-01-14 21:18:42 +00006938
Bram Moolenaar071d4272004-06-13 20:20:40 +00006939 int
Bram Moolenaar05540972016-01-30 20:31:25 +01006940mch_expand_wildcards(
6941 int num_pat,
6942 char_u **pat,
6943 int *num_file,
6944 char_u ***file,
Bram Moolenaar0f873732019-12-05 20:28:46 +01006945 int flags) // EW_* flags
Bram Moolenaar071d4272004-06-13 20:20:40 +00006946{
6947 int i;
6948 size_t len;
Bram Moolenaar85325f82017-03-30 21:18:45 +02006949 long llen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006950 char_u *p;
6951 int dir;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006952
Bram Moolenaarc7247912008-01-13 12:54:11 +00006953 /*
6954 * This is the non-OS/2 implementation (really Unix).
6955 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006956 int j;
6957 char_u *tempname;
John Marriottefc41a52025-01-23 20:05:29 +01006958 size_t tempnamelen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006959 char_u *command;
John Marriottefc41a52025-01-23 20:05:29 +01006960 size_t commandlen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006961 FILE *fd;
6962 char_u *buffer;
Bram Moolenaar0f873732019-12-05 20:28:46 +01006963#define STYLE_ECHO 0 // use "echo", the default
6964#define STYLE_GLOB 1 // use "glob", for csh
6965#define STYLE_VIMGLOB 2 // use "vimglob", for Posix sh
6966#define STYLE_PRINT 3 // use "print -N", for zsh
Christian Brabandt9eb1ce52023-09-27 19:08:25 +02006967#define STYLE_BT 4 // `cmd` expansion, execute the pattern directly
6968#define STYLE_GLOBSTAR 5 // use extended shell glob for bash (this uses extended
6969 // globbing functionality using globstar, needs bash > 4)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006970 int shell_style = STYLE_ECHO;
6971 int check_spaces;
6972 static int did_find_nul = FALSE;
Bram Moolenaarbdace832019-03-02 10:13:42 +01006973 int ampersand = FALSE;
John Marriottefc41a52025-01-23 20:05:29 +01006974#define STRING_INIT(s) \
6975 {(char_u *)(s), STRLEN_LITERAL(s)}
6976 // vimglob() function to define for Posix shell
6977 static string_T sh_vimglob_func = STRING_INIT("vimglob() { while [ $# -ge 1 ]; do echo \"$1\"; shift; done }; vimglob >");
6978 // vimglob() function with globstar setting enabled, only for bash >= 4.X
6979 static string_T sh_globstar_opt = STRING_INIT("[[ ${BASH_VERSINFO[0]} -ge 4 ]] && shopt -s globstar; ");
6980#undef STRING_INIT
6981
Bram Moolenaar071d4272004-06-13 20:20:40 +00006982
Bram Moolenaar0f873732019-12-05 20:28:46 +01006983 *num_file = 0; // default: no files found
Bram Moolenaar071d4272004-06-13 20:20:40 +00006984 *file = NULL;
6985
6986 /*
6987 * If there are no wildcards, just copy the names to allocated memory.
6988 * Saves a lot of time, because we don't have to start a new shell.
6989 */
6990 if (!have_wildcard(num_pat, pat))
6991 return save_patterns(num_pat, pat, num_file, file);
6992
Bram Moolenaar0e634da2005-07-20 21:57:28 +00006993# ifdef HAVE_SANDBOX
Bram Moolenaar0f873732019-12-05 20:28:46 +01006994 // Don't allow any shell command in the sandbox.
Bram Moolenaar0e634da2005-07-20 21:57:28 +00006995 if (sandbox != 0 && check_secure())
6996 return FAIL;
6997# endif
6998
Bram Moolenaar071d4272004-06-13 20:20:40 +00006999 /*
7000 * Don't allow the use of backticks in secure and restricted mode.
7001 */
Bram Moolenaar0e634da2005-07-20 21:57:28 +00007002 if (secure || restricted)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007003 for (i = 0; i < num_pat; ++i)
7004 if (vim_strchr(pat[i], '`') != NULL
7005 && (check_restricted() || check_secure()))
7006 return FAIL;
7007
7008 /*
7009 * get a name for the temp file
7010 */
Bram Moolenaare5c421c2015-03-31 13:33:08 +02007011 if ((tempname = vim_tempname('o', FALSE)) == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007012 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00007013 emsg(_(e_cant_get_temp_file_name));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007014 return FAIL;
7015 }
7016
7017 /*
7018 * Let the shell expand the patterns and write the result into the temp
Bram Moolenaarc7247912008-01-13 12:54:11 +00007019 * file.
7020 * STYLE_BT: NL separated
7021 * If expanding `cmd` execute it directly.
7022 * STYLE_GLOB: NUL separated
7023 * If we use *csh, "glob" will work better than "echo".
7024 * STYLE_PRINT: NL or NUL separated
7025 * If we use *zsh, "print -N" will work better than "glob".
7026 * STYLE_VIMGLOB: NL separated
7027 * If we use *sh*, we define "vimglob()".
Christian Brabandt9eb1ce52023-09-27 19:08:25 +02007028 * STYLE_GLOBSTAR: NL separated
7029 * If we use *bash*, we define "vimglob() and enable globstar option".
Bram Moolenaarc7247912008-01-13 12:54:11 +00007030 * STYLE_ECHO: space separated.
7031 * A shell we don't know, stay safe and use "echo".
Bram Moolenaar071d4272004-06-13 20:20:40 +00007032 */
7033 if (num_pat == 1 && *pat[0] == '`'
7034 && (len = STRLEN(pat[0])) > 2
7035 && *(pat[0] + len - 1) == '`')
7036 shell_style = STYLE_BT;
7037 else if ((len = STRLEN(p_sh)) >= 3)
7038 {
7039 if (STRCMP(p_sh + len - 3, "csh") == 0)
7040 shell_style = STYLE_GLOB;
7041 else if (STRCMP(p_sh + len - 3, "zsh") == 0)
7042 shell_style = STYLE_PRINT;
7043 }
Christian Brabandt9eb1ce52023-09-27 19:08:25 +02007044 if (shell_style == STYLE_ECHO)
7045 {
Yegappan Lakshmanane89aef32025-05-14 20:31:55 +02007046 if (strstr((char *)gettail(p_sh), "bash") != NULL)
Christian Brabandt9eb1ce52023-09-27 19:08:25 +02007047 shell_style = STYLE_GLOBSTAR;
Yegappan Lakshmanane89aef32025-05-14 20:31:55 +02007048 else if (strstr((char *)gettail(p_sh), "sh") != NULL)
Christian Brabandt9eb1ce52023-09-27 19:08:25 +02007049 shell_style = STYLE_VIMGLOB;
7050 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007051
Bram Moolenaar0f873732019-12-05 20:28:46 +01007052 // Compute the length of the command. We need 2 extra bytes: for the
7053 // optional '&' and for the NUL.
7054 // Worst case: "unset nonomatch; print -N >" plus two is 29
John Marriottefc41a52025-01-23 20:05:29 +01007055 tempnamelen = STRLEN(tempname);
7056 len = tempnamelen + 29;
Bram Moolenaarc7247912008-01-13 12:54:11 +00007057 if (shell_style == STYLE_VIMGLOB)
John Marriottefc41a52025-01-23 20:05:29 +01007058 len += sh_vimglob_func.length;
Christian Brabandt9eb1ce52023-09-27 19:08:25 +02007059 else if (shell_style == STYLE_GLOBSTAR)
John Marriottefc41a52025-01-23 20:05:29 +01007060 len += sh_vimglob_func.length + sh_globstar_opt.length;
Bram Moolenaarc7247912008-01-13 12:54:11 +00007061
Bram Moolenaarb23c3382005-01-31 19:09:12 +00007062 for (i = 0; i < num_pat; ++i)
7063 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007064 // Count the length of the patterns in the same way as they are put in
7065 // "command" below.
Bram Moolenaarb23c3382005-01-31 19:09:12 +00007066#ifdef USE_SYSTEM
Bram Moolenaar0f873732019-12-05 20:28:46 +01007067 len += STRLEN(pat[i]) + 3; // add space and two quotes
Bram Moolenaarb23c3382005-01-31 19:09:12 +00007068#else
Bram Moolenaar0f873732019-12-05 20:28:46 +01007069 ++len; // add space
Bram Moolenaar316059c2006-01-14 21:18:42 +00007070 for (j = 0; pat[i][j] != NUL; ++j)
7071 {
7072 if (vim_strchr(SHELL_SPECIAL, pat[i][j]) != NULL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01007073 ++len; // may add a backslash
Bram Moolenaar316059c2006-01-14 21:18:42 +00007074 ++len;
7075 }
Bram Moolenaarb23c3382005-01-31 19:09:12 +00007076#endif
7077 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007078 command = alloc(len);
7079 if (command == NULL)
7080 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007081 // out of memory
Bram Moolenaar071d4272004-06-13 20:20:40 +00007082 vim_free(tempname);
7083 return FAIL;
7084 }
7085
7086 /*
7087 * Build the shell command:
7088 * - Set $nonomatch depending on EW_NOTFOUND (hopefully the shell
7089 * recognizes this).
7090 * - Add the shell command to print the expanded names.
7091 * - Add the temp file name.
7092 * - Add the file name patterns.
7093 */
7094 if (shell_style == STYLE_BT)
7095 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007096 // change `command; command& ` to (command; command )
John Marriottefc41a52025-01-23 20:05:29 +01007097 commandlen = vim_snprintf((char *)command, len, "(%s)>%s", pat[0] + 1, tempname); // +1 to exclude first backtick
7098
7099 p = (char_u *)strstr((char *)command, ")>");
7100 if (p == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007101 {
John Marriottefc41a52025-01-23 20:05:29 +01007102 ; // can't happen ;-)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007103 }
John Marriottefc41a52025-01-23 20:05:29 +01007104 else
7105 {
7106 --p;
7107 while (p > command && VIM_ISWHITE(*p))
7108 --p;
7109 if (*p == '`') // remove backtick
7110 *p = ' ';
7111
7112 --p;
7113 while (p > command && VIM_ISWHITE(*p))
7114 --p;
7115 if (*p == '&') // remove ampersand
7116 {
7117 ampersand = TRUE;
7118 *p = ' ';
7119 }
7120 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007121 }
7122 else
7123 {
Christian Brabandt8b8d8292021-11-19 12:37:36 +00007124 if (shell_style == STYLE_GLOB)
7125 {
7126 // Assume the nonomatch option is valid only for csh like shells,
7127 // otherwise, this may set the positional parameters for the shell,
7128 // e.g. "$*".
John Marriottefc41a52025-01-23 20:05:29 +01007129 commandlen = vim_snprintf((char *)command, len, "%sset nonomatch; glob >%s",
7130 (flags & EW_NOTFOUND) ? "" : "un", tempname);
Christian Brabandt8b8d8292021-11-19 12:37:36 +00007131 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007132 else if (shell_style == STYLE_PRINT)
John Marriottefc41a52025-01-23 20:05:29 +01007133 commandlen = vim_snprintf((char *)command, len, "print -N >%s", tempname);
Bram Moolenaarc7247912008-01-13 12:54:11 +00007134 else if (shell_style == STYLE_VIMGLOB)
John Marriottefc41a52025-01-23 20:05:29 +01007135 commandlen = vim_snprintf((char *)command, len, "%s%s", sh_vimglob_func.string, tempname);
Christian Brabandt9eb1ce52023-09-27 19:08:25 +02007136 else if (shell_style == STYLE_GLOBSTAR)
John Marriottefc41a52025-01-23 20:05:29 +01007137 commandlen = vim_snprintf((char *)command, len, "%s%s%s", sh_globstar_opt.string,
7138 sh_vimglob_func.string, tempname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007139 else
John Marriottefc41a52025-01-23 20:05:29 +01007140 commandlen = vim_snprintf((char *)command, len, "echo >%s", tempname);
Bram Moolenaarc7247912008-01-13 12:54:11 +00007141
Bram Moolenaar071d4272004-06-13 20:20:40 +00007142 for (i = 0; i < num_pat; ++i)
7143 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007144 // When using system() always add extra quotes, because the shell
7145 // is started twice. Otherwise put a backslash before special
7146 // characters, except inside ``.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007147#ifdef USE_SYSTEM
John Marriottefc41a52025-01-23 20:05:29 +01007148 commandlen += vim_snprintf((char *)command + commandlen, len, " \"%s\"", pat[i]);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007149#else
Bram Moolenaar582fd852005-03-28 20:58:01 +00007150 int intick = FALSE;
7151
John Marriottefc41a52025-01-23 20:05:29 +01007152 p = command + commandlen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007153 *p++ = ' ';
Bram Moolenaar316059c2006-01-14 21:18:42 +00007154 for (j = 0; pat[i][j] != NUL; ++j)
Bram Moolenaar582fd852005-03-28 20:58:01 +00007155 {
7156 if (pat[i][j] == '`')
Bram Moolenaar582fd852005-03-28 20:58:01 +00007157 intick = !intick;
Bram Moolenaar316059c2006-01-14 21:18:42 +00007158 else if (pat[i][j] == '\\' && pat[i][j + 1] != NUL)
7159 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007160 // Remove a backslash, take char literally. But keep
7161 // backslash inside backticks, before a special character
7162 // and before a backtick.
Bram Moolenaard12f5c12006-01-25 22:10:52 +00007163 if (intick
Bram Moolenaar49315f62006-02-04 00:54:59 +00007164 || vim_strchr(SHELL_SPECIAL, pat[i][j + 1]) != NULL
7165 || pat[i][j + 1] == '`')
Bram Moolenaard12f5c12006-01-25 22:10:52 +00007166 *p++ = '\\';
Bram Moolenaar280f1262006-01-30 00:14:18 +00007167 ++j;
Bram Moolenaar316059c2006-01-14 21:18:42 +00007168 }
Bram Moolenaare4df1642014-08-29 12:58:44 +02007169 else if (!intick
7170 && ((flags & EW_KEEPDOLLAR) == 0 || pat[i][j] != '$')
7171 && vim_strchr(SHELL_SPECIAL, pat[i][j]) != NULL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01007172 // Put a backslash before a special character, but not
7173 // when inside ``. And not for $var when EW_KEEPDOLLAR is
7174 // set.
Bram Moolenaar316059c2006-01-14 21:18:42 +00007175 *p++ = '\\';
Bram Moolenaar280f1262006-01-30 00:14:18 +00007176
Bram Moolenaar0f873732019-12-05 20:28:46 +01007177 // Copy one character.
Bram Moolenaar280f1262006-01-30 00:14:18 +00007178 *p++ = pat[i][j];
Bram Moolenaar582fd852005-03-28 20:58:01 +00007179 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007180 *p = NUL;
John Marriottefc41a52025-01-23 20:05:29 +01007181 commandlen = (size_t)(p - command);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007182#endif
7183 }
John Marriottefc41a52025-01-23 20:05:29 +01007184 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007185 if (flags & EW_SILENT)
7186 show_shell_mess = FALSE;
Bram Moolenaarbdace832019-03-02 10:13:42 +01007187 if (ampersand)
John Marriottefc41a52025-01-23 20:05:29 +01007188 STRCPY(command + commandlen, "&"); // put the '&' after the redirection
Bram Moolenaar071d4272004-06-13 20:20:40 +00007189
7190 /*
7191 * Using zsh -G: If a pattern has no matches, it is just deleted from
7192 * the argument list, otherwise zsh gives an error message and doesn't
7193 * expand any other pattern.
7194 */
7195 if (shell_style == STYLE_PRINT)
Bram Moolenaar0f873732019-12-05 20:28:46 +01007196 extra_shell_arg = (char_u *)"-G"; // Use zsh NULL_GLOB option
Bram Moolenaar071d4272004-06-13 20:20:40 +00007197
7198 /*
7199 * If we use -f then shell variables set in .cshrc won't get expanded.
7200 * vi can do it, so we will too, but it is only necessary if there is a "$"
7201 * in one of the patterns, otherwise we can still use the fast option.
7202 */
7203 else if (shell_style == STYLE_GLOB && !have_dollars(num_pat, pat))
Bram Moolenaar0f873732019-12-05 20:28:46 +01007204 extra_shell_arg = (char_u *)"-f"; // Use csh fast option
Bram Moolenaar071d4272004-06-13 20:20:40 +00007205
7206 /*
7207 * execute the shell command
7208 */
7209 i = call_shell(command, SHELL_EXPAND | SHELL_SILENT);
7210
Bram Moolenaar0f873732019-12-05 20:28:46 +01007211 // When running in the background, give it some time to create the temp
7212 // file, but don't wait for it to finish.
Bram Moolenaarbdace832019-03-02 10:13:42 +01007213 if (ampersand)
Bram Moolenaar0981c872020-08-23 14:28:37 +02007214 mch_delay(10L, MCH_DELAY_IGNOREINPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007215
Bram Moolenaar0f873732019-12-05 20:28:46 +01007216 extra_shell_arg = NULL; // cleanup
Bram Moolenaar071d4272004-06-13 20:20:40 +00007217 show_shell_mess = TRUE;
7218 vim_free(command);
7219
Bram Moolenaar0f873732019-12-05 20:28:46 +01007220 if (i != 0) // mch_call_shell() failed
Bram Moolenaar071d4272004-06-13 20:20:40 +00007221 {
7222 mch_remove(tempname);
7223 vim_free(tempname);
7224 /*
7225 * With interactive completion, the error message is not printed.
7226 * However with USE_SYSTEM, I don't know how to turn off error messages
7227 * from the shell, so screen may still get messed up -- webb.
7228 */
7229#ifndef USE_SYSTEM
7230 if (!(flags & EW_SILENT))
7231#endif
7232 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007233 redraw_later_clear(); // probably messed up screen
7234 msg_putchar('\n'); // clear bottom line quickly
7235 cmdline_row = Rows - 1; // continue on last line
Bram Moolenaar071d4272004-06-13 20:20:40 +00007236#ifdef USE_SYSTEM
7237 if (!(flags & EW_SILENT))
7238#endif
7239 {
Bram Moolenaar40bcec12021-12-05 22:19:27 +00007240 msg(_(e_cannot_expand_wildcards));
Bram Moolenaar0f873732019-12-05 20:28:46 +01007241 msg_start(); // don't overwrite this message
Bram Moolenaar071d4272004-06-13 20:20:40 +00007242 }
7243 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01007244 // If a `cmd` expansion failed, don't list `cmd` as a match, even when
7245 // EW_NOTFOUND is given
Bram Moolenaar071d4272004-06-13 20:20:40 +00007246 if (shell_style == STYLE_BT)
7247 return FAIL;
7248 goto notfound;
7249 }
7250
7251 /*
7252 * read the names from the file into memory
7253 */
7254 fd = fopen((char *)tempname, READBIN);
7255 if (fd == NULL)
7256 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007257 // Something went wrong, perhaps a file name with a special char.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007258 if (!(flags & EW_SILENT))
7259 {
Bram Moolenaar40bcec12021-12-05 22:19:27 +00007260 msg(_(e_cannot_expand_wildcards));
Bram Moolenaar0f873732019-12-05 20:28:46 +01007261 msg_start(); // don't overwrite this message
Bram Moolenaar071d4272004-06-13 20:20:40 +00007262 }
7263 vim_free(tempname);
7264 goto notfound;
7265 }
7266 fseek(fd, 0L, SEEK_END);
Bram Moolenaar0f873732019-12-05 20:28:46 +01007267 llen = ftell(fd); // get size of temp file
Bram Moolenaar071d4272004-06-13 20:20:40 +00007268 fseek(fd, 0L, SEEK_SET);
Bram Moolenaar85325f82017-03-30 21:18:45 +02007269 if (llen < 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01007270 // just in case ftell() would fail
Bram Moolenaar85325f82017-03-30 21:18:45 +02007271 buffer = NULL;
7272 else
7273 buffer = alloc(llen + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007274 if (buffer == NULL)
7275 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007276 // out of memory
Bram Moolenaar071d4272004-06-13 20:20:40 +00007277 mch_remove(tempname);
7278 vim_free(tempname);
7279 fclose(fd);
7280 return FAIL;
7281 }
Bram Moolenaar85325f82017-03-30 21:18:45 +02007282 len = llen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007283 i = fread((char *)buffer, 1, len, fd);
7284 fclose(fd);
7285 mch_remove(tempname);
Bram Moolenaar78a15312009-05-15 19:33:18 +00007286 if (i != (int)len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007287 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007288 // unexpected read error
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00007289 semsg(_(e_cant_read_file_str), tempname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007290 vim_free(tempname);
7291 vim_free(buffer);
7292 return FAIL;
7293 }
7294 vim_free(tempname);
7295
Bram Moolenaar1eed5322019-02-26 17:03:54 +01007296# ifdef __CYGWIN__
Bram Moolenaar0f873732019-12-05 20:28:46 +01007297 // Translate <CR><NL> into <NL>. Caution, buffer may contain NUL.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007298 p = buffer;
Bram Moolenaarfe17e762013-06-29 14:17:02 +02007299 for (i = 0; i < (int)len; ++i)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007300 if (!(buffer[i] == CAR && buffer[i + 1] == NL))
7301 *p++ = buffer[i];
7302 len = p - buffer;
7303# endif
7304
7305
Bram Moolenaar0f873732019-12-05 20:28:46 +01007306 // file names are separated with Space
Bram Moolenaar071d4272004-06-13 20:20:40 +00007307 if (shell_style == STYLE_ECHO)
7308 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007309 buffer[len] = '\n'; // make sure the buffer ends in NL
Bram Moolenaar071d4272004-06-13 20:20:40 +00007310 p = buffer;
Bram Moolenaar0f873732019-12-05 20:28:46 +01007311 for (i = 0; *p != '\n'; ++i) // count number of entries
Bram Moolenaar071d4272004-06-13 20:20:40 +00007312 {
7313 while (*p != ' ' && *p != '\n')
7314 ++p;
Bram Moolenaar0f873732019-12-05 20:28:46 +01007315 p = skipwhite(p); // skip to next entry
Bram Moolenaar071d4272004-06-13 20:20:40 +00007316 }
7317 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01007318 // file names are separated with NL
Christian Brabandt9eb1ce52023-09-27 19:08:25 +02007319 else if (shell_style == STYLE_BT ||
7320 shell_style == STYLE_VIMGLOB ||
7321 shell_style == STYLE_GLOBSTAR)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007322 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007323 buffer[len] = NUL; // make sure the buffer ends in NUL
Bram Moolenaar071d4272004-06-13 20:20:40 +00007324 p = buffer;
Bram Moolenaar0f873732019-12-05 20:28:46 +01007325 for (i = 0; *p != NUL; ++i) // count number of entries
Bram Moolenaar071d4272004-06-13 20:20:40 +00007326 {
7327 while (*p != '\n' && *p != NUL)
7328 ++p;
7329 if (*p != NUL)
7330 ++p;
Bram Moolenaar0f873732019-12-05 20:28:46 +01007331 p = skipwhite(p); // skip leading white space
Bram Moolenaar071d4272004-06-13 20:20:40 +00007332 }
7333 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01007334 // file names are separated with NUL
Bram Moolenaar071d4272004-06-13 20:20:40 +00007335 else
7336 {
7337 /*
7338 * Some versions of zsh use spaces instead of NULs to separate
7339 * results. Only do this when there is no NUL before the end of the
7340 * buffer, otherwise we would never be able to use file names with
7341 * embedded spaces when zsh does use NULs.
7342 * When we found a NUL once, we know zsh is OK, set did_find_nul and
7343 * don't check for spaces again.
7344 */
7345 check_spaces = FALSE;
7346 if (shell_style == STYLE_PRINT && !did_find_nul)
7347 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007348 // If there is a NUL, set did_find_nul, else set check_spaces
Bram Moolenaaref9d6aa2011-04-11 16:56:35 +02007349 buffer[len] = NUL;
Bram Moolenaarb011af92013-12-11 13:21:51 +01007350 if (len && (int)STRLEN(buffer) < (int)len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007351 did_find_nul = TRUE;
7352 else
7353 check_spaces = TRUE;
7354 }
7355
7356 /*
7357 * Make sure the buffer ends with a NUL. For STYLE_PRINT there
7358 * already is one, for STYLE_GLOB it needs to be added.
7359 */
7360 if (len && buffer[len - 1] == NUL)
7361 --len;
7362 else
7363 buffer[len] = NUL;
7364 i = 0;
7365 for (p = buffer; p < buffer + len; ++p)
Bram Moolenaar0f873732019-12-05 20:28:46 +01007366 if (*p == NUL || (*p == ' ' && check_spaces)) // count entry
Bram Moolenaar071d4272004-06-13 20:20:40 +00007367 {
7368 ++i;
7369 *p = NUL;
7370 }
7371 if (len)
Bram Moolenaar0f873732019-12-05 20:28:46 +01007372 ++i; // count last entry
Bram Moolenaar071d4272004-06-13 20:20:40 +00007373 }
7374 if (i == 0)
7375 {
7376 /*
7377 * Can happen when using /bin/sh and typing ":e $NO_SUCH_VAR^I".
7378 * /bin/sh will happily expand it to nothing rather than returning an
7379 * error; and hey, it's good to check anyway -- webb.
7380 */
7381 vim_free(buffer);
7382 goto notfound;
7383 }
7384 *num_file = i;
Bram Moolenaarc799fe22019-05-28 23:08:19 +02007385 *file = ALLOC_MULT(char_u *, i);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007386 if (*file == NULL)
7387 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007388 // out of memory
Bram Moolenaar071d4272004-06-13 20:20:40 +00007389 vim_free(buffer);
7390 return FAIL;
7391 }
7392
7393 /*
7394 * Isolate the individual file names.
7395 */
7396 p = buffer;
7397 for (i = 0; i < *num_file; ++i)
7398 {
7399 (*file)[i] = p;
Bram Moolenaar0f873732019-12-05 20:28:46 +01007400 // Space or NL separates
Bram Moolenaarc7247912008-01-13 12:54:11 +00007401 if (shell_style == STYLE_ECHO || shell_style == STYLE_BT
Christian Brabandt9eb1ce52023-09-27 19:08:25 +02007402 || shell_style == STYLE_VIMGLOB || shell_style == STYLE_GLOBSTAR)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007403 {
Bram Moolenaar49315f62006-02-04 00:54:59 +00007404 while (!(shell_style == STYLE_ECHO && *p == ' ')
7405 && *p != '\n' && *p != NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007406 ++p;
Bram Moolenaar0f873732019-12-05 20:28:46 +01007407 if (p == buffer + len) // last entry
Bram Moolenaar071d4272004-06-13 20:20:40 +00007408 *p = NUL;
7409 else
7410 {
7411 *p++ = NUL;
Bram Moolenaar0f873732019-12-05 20:28:46 +01007412 p = skipwhite(p); // skip to next entry
Bram Moolenaar071d4272004-06-13 20:20:40 +00007413 }
7414 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01007415 else // NUL separates
Bram Moolenaar071d4272004-06-13 20:20:40 +00007416 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007417 while (*p && p < buffer + len) // skip entry
Bram Moolenaar071d4272004-06-13 20:20:40 +00007418 ++p;
Bram Moolenaar0f873732019-12-05 20:28:46 +01007419 ++p; // skip NUL
Bram Moolenaar071d4272004-06-13 20:20:40 +00007420 }
7421 }
7422
7423 /*
7424 * Move the file names to allocated memory.
7425 */
7426 for (j = 0, i = 0; i < *num_file; ++i)
7427 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007428 // Require the files to exist. Helps when using /bin/sh
Bram Moolenaar071d4272004-06-13 20:20:40 +00007429 if (!(flags & EW_NOTFOUND) && mch_getperm((*file)[i]) < 0)
7430 continue;
7431
Bram Moolenaar0f873732019-12-05 20:28:46 +01007432 // check if this entry should be included
Bram Moolenaar071d4272004-06-13 20:20:40 +00007433 dir = (mch_isdir((*file)[i]));
7434 if ((dir && !(flags & EW_DIR)) || (!dir && !(flags & EW_FILE)))
7435 continue;
7436
Bram Moolenaar0f873732019-12-05 20:28:46 +01007437 // Skip files that are not executable if we check for that.
Bram Moolenaarb5971142015-03-21 17:32:19 +01007438 if (!dir && (flags & EW_EXEC)
7439 && !mch_can_exe((*file)[i], NULL, !(flags & EW_SHELLCMD)))
Bram Moolenaara2031822006-03-07 22:29:51 +00007440 continue;
7441
Bram Moolenaar964b3742019-05-24 18:54:09 +02007442 p = alloc(STRLEN((*file)[i]) + 1 + dir);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007443 if (p)
7444 {
7445 STRCPY(p, (*file)[i]);
7446 if (dir)
Bram Moolenaar0f873732019-12-05 20:28:46 +01007447 add_pathsep(p); // add '/' to a directory name
Bram Moolenaar071d4272004-06-13 20:20:40 +00007448 (*file)[j++] = p;
7449 }
7450 }
7451 vim_free(buffer);
7452 *num_file = j;
7453
Bram Moolenaar0f873732019-12-05 20:28:46 +01007454 if (*num_file == 0) // rejected all entries
Bram Moolenaar071d4272004-06-13 20:20:40 +00007455 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01007456 VIM_CLEAR(*file);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007457 goto notfound;
7458 }
7459
7460 return OK;
7461
7462notfound:
7463 if (flags & EW_NOTFOUND)
7464 return save_patterns(num_pat, pat, num_file, file);
7465 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007466}
7467
Bram Moolenaar0f873732019-12-05 20:28:46 +01007468#endif // VMS
Bram Moolenaar071d4272004-06-13 20:20:40 +00007469
Bram Moolenaar071d4272004-06-13 20:20:40 +00007470 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01007471save_patterns(
7472 int num_pat,
7473 char_u **pat,
7474 int *num_file,
7475 char_u ***file)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007476{
7477 int i;
Bram Moolenaard8b02732005-01-14 21:48:43 +00007478 char_u *s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007479
Bram Moolenaarc799fe22019-05-28 23:08:19 +02007480 *file = ALLOC_MULT(char_u *, num_pat);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007481 if (*file == NULL)
7482 return FAIL;
7483 for (i = 0; i < num_pat; i++)
Bram Moolenaard8b02732005-01-14 21:48:43 +00007484 {
7485 s = vim_strsave(pat[i]);
7486 if (s != NULL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01007487 // Be compatible with expand_filename(): halve the number of
7488 // backslashes.
Bram Moolenaard8b02732005-01-14 21:48:43 +00007489 backslash_halve(s);
7490 (*file)[i] = s;
7491 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007492 *num_file = num_pat;
7493 return OK;
7494}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007495
Bram Moolenaar071d4272004-06-13 20:20:40 +00007496/*
7497 * Return TRUE if the string "p" contains a wildcard that mch_expandpath() can
7498 * expand.
7499 */
7500 int
Bram Moolenaar05540972016-01-30 20:31:25 +01007501mch_has_exp_wildcard(char_u *p)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007502{
Bram Moolenaar91acfff2017-03-12 19:22:36 +01007503 for ( ; *p; MB_PTR_ADV(p))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007504 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007505 if (*p == '\\' && p[1] != NUL)
7506 ++p;
7507 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007508 if (vim_strchr((char_u *)
7509#ifdef VMS
7510 "*?%"
7511#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007512 "*?[{'"
Bram Moolenaar071d4272004-06-13 20:20:40 +00007513#endif
7514 , *p) != NULL)
7515 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007516 }
7517 return FALSE;
7518}
7519
7520/*
7521 * Return TRUE if the string "p" contains a wildcard.
7522 * Don't recognize '~' at the end as a wildcard.
7523 */
7524 int
Bram Moolenaar05540972016-01-30 20:31:25 +01007525mch_has_wildcard(char_u *p)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007526{
Bram Moolenaar91acfff2017-03-12 19:22:36 +01007527 for ( ; *p; MB_PTR_ADV(p))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007528 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007529 if (*p == '\\' && p[1] != NUL)
7530 ++p;
7531 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007532 if (vim_strchr((char_u *)
7533#ifdef VMS
7534 "*?%$"
7535#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007536 "*?[{`'$"
Bram Moolenaar071d4272004-06-13 20:20:40 +00007537#endif
7538 , *p) != NULL
7539 || (*p == '~' && p[1] != NUL))
7540 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007541 }
7542 return FALSE;
7543}
7544
Bram Moolenaar071d4272004-06-13 20:20:40 +00007545 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01007546have_wildcard(int num, char_u **file)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007547{
7548 int i;
7549
7550 for (i = 0; i < num; i++)
7551 if (mch_has_wildcard(file[i]))
7552 return 1;
7553 return 0;
7554}
7555
7556 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01007557have_dollars(int num, char_u **file)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007558{
7559 int i;
7560
7561 for (i = 0; i < num; i++)
7562 if (vim_strchr(file[i], '$') != NULL)
7563 return TRUE;
7564 return FALSE;
7565}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007566
Bram Moolenaarfdcc9af2016-02-29 12:52:39 +01007567#if !defined(HAVE_RENAME) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007568/*
7569 * Scaled-down version of rename(), which is missing in Xenix.
7570 * This version can only move regular files and will fail if the
7571 * destination exists.
7572 */
7573 int
Bram Moolenaarfdcc9af2016-02-29 12:52:39 +01007574mch_rename(const char *src, const char *dest)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007575{
7576 struct stat st;
7577
Bram Moolenaar0f873732019-12-05 20:28:46 +01007578 if (stat(dest, &st) >= 0) // fail if destination exists
Bram Moolenaar071d4272004-06-13 20:20:40 +00007579 return -1;
Bram Moolenaar0f873732019-12-05 20:28:46 +01007580 if (link(src, dest) != 0) // link file to new name
Bram Moolenaar071d4272004-06-13 20:20:40 +00007581 return -1;
Bram Moolenaar0f873732019-12-05 20:28:46 +01007582 if (mch_remove(src) == 0) // delete link to old name
Bram Moolenaar071d4272004-06-13 20:20:40 +00007583 return 0;
7584 return -1;
7585}
Bram Moolenaar0f873732019-12-05 20:28:46 +01007586#endif // !HAVE_RENAME
Bram Moolenaar071d4272004-06-13 20:20:40 +00007587
Bram Moolenaar4b8366b2019-05-04 17:34:34 +02007588#if defined(FEAT_MOUSE_GPM) || defined(PROTO)
Bram Moolenaar33fc4a62022-02-23 18:07:38 +00007589# if defined(DYNAMIC_GPM) || defined(PROTO)
7590/*
7591 * Initialize Gpm's symbols for dynamic linking.
7592 * Must be called only if libgpm_hinst is NULL.
7593 */
7594 static int
7595load_libgpm(void)
7596{
7597 libgpm_hinst = dlopen("libgpm.so", RTLD_LAZY|RTLD_GLOBAL);
7598
7599 if (libgpm_hinst == NULL)
7600 {
7601 if (p_verbose > 0)
7602 smsg_attr(HL_ATTR(HLF_W),
Bram Moolenaar6ed545e2022-05-09 20:09:23 +01007603 _("Could not load gpm library: %s"), dlerror());
Bram Moolenaar33fc4a62022-02-23 18:07:38 +00007604 return FAIL;
7605 }
7606
7607 if (
7608 (dll_Gpm_Open = dlsym(libgpm_hinst, "Gpm_Open")) == NULL
7609 || (dll_Gpm_Close = dlsym(libgpm_hinst, "Gpm_Close")) == NULL
7610 || (dll_Gpm_GetEvent = dlsym(libgpm_hinst, "Gpm_GetEvent")) == NULL
7611 || (dll_gpm_flag = dlsym(libgpm_hinst, "gpm_flag")) == NULL
7612 || (dll_gpm_fd = dlsym(libgpm_hinst, "gpm_fd")) == NULL
7613 )
7614 {
7615 semsg(_(e_could_not_load_library_str_str), "gpm", dlerror());
7616 dlclose(libgpm_hinst);
7617 libgpm_hinst = NULL;
7618 dll_gpm_flag = NULL;
7619 dll_gpm_fd = NULL;
7620 return FAIL;
7621 }
7622 return OK;
7623}
7624
7625 int
7626gpm_available(void)
7627{
7628 return libgpm_hinst != NULL || load_libgpm() == OK;
7629}
7630# endif // DYNAMIC_GPM
7631
Bram Moolenaar071d4272004-06-13 20:20:40 +00007632/*
7633 * Initializes connection with gpm (if it isn't already opened)
7634 * Return 1 if succeeded (or connection already opened), 0 if failed
7635 */
7636 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01007637gpm_open(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007638{
Bram Moolenaar0f873732019-12-05 20:28:46 +01007639 static Gpm_Connect gpm_connect; // Must it be kept till closing ?
Bram Moolenaar071d4272004-06-13 20:20:40 +00007640
Bram Moolenaar33fc4a62022-02-23 18:07:38 +00007641#ifdef DYNAMIC_GPM
7642 if (!gpm_available())
7643 return 0;
7644#endif
7645
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00007646 if (gpm_flag)
7647 return 1; // already open
7648
7649 gpm_connect.eventMask = (GPM_UP | GPM_DRAG | GPM_DOWN);
7650 gpm_connect.defaultMask = ~GPM_HARD;
7651 // Default handling for mouse move
7652 gpm_connect.minMod = 0; // Handle any modifier keys
7653 gpm_connect.maxMod = 0xffff;
7654 if (Gpm_Open(&gpm_connect, 0) > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007655 {
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00007656 // gpm library tries to handling TSTP causes
7657 // problems. Anyways, we close connection to Gpm whenever
7658 // we are going to suspend or starting an external process
7659 // so we shouldn't have problem with this
Bram Moolenaar76243bd2009-03-02 01:47:02 +00007660# ifdef SIGTSTP
ichizok378447f2023-05-11 22:25:42 +01007661 mch_signal(SIGTSTP, restricted ? SIG_IGN : sig_tstp);
Bram Moolenaar76243bd2009-03-02 01:47:02 +00007662# endif
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00007663 return 1; // succeed
Bram Moolenaar071d4272004-06-13 20:20:40 +00007664 }
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00007665 if (gpm_fd == -2)
Julio Bcc59d622024-04-04 21:55:10 +02007666 {
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00007667 Gpm_Close(); // We don't want to talk to xterm via gpm
Julio Bcc59d622024-04-04 21:55:10 +02007668
zeertzjqd9be94c2024-07-14 10:20:20 +02007669 // Gpm_Close fails to properly restore the WINCH and TSTP handlers,
7670 // leading to Vim ignoring resize signals. We have to re-initialize
7671 // these handlers again here.
Julio Bcc59d622024-04-04 21:55:10 +02007672# ifdef SIGWINCH
7673 mch_signal(SIGWINCH, sig_winch);
7674# endif
7675# ifdef SIGTSTP
7676 mch_signal(SIGTSTP, restricted ? SIG_IGN : sig_tstp);
7677# endif
7678 }
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00007679 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007680}
7681
7682/*
Bram Moolenaar4b8366b2019-05-04 17:34:34 +02007683 * Returns TRUE if the GPM mouse is enabled.
7684 */
7685 int
7686gpm_enabled(void)
7687{
7688 return gpm_flag && gpm_fd >= 0;
7689}
7690
7691/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007692 * Closes connection to gpm
Bram Moolenaar071d4272004-06-13 20:20:40 +00007693 */
7694 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01007695gpm_close(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007696{
Bram Moolenaar4b8366b2019-05-04 17:34:34 +02007697 if (gpm_enabled())
Bram Moolenaar071d4272004-06-13 20:20:40 +00007698 Gpm_Close();
7699}
7700
Bram Moolenaarbedf0912019-05-04 16:58:45 +02007701/*
7702 * Reads gpm event and adds special keys to input buf. Returns length of
Bram Moolenaar071d4272004-06-13 20:20:40 +00007703 * generated key sequence.
Bram Moolenaarc7f02552014-04-01 21:00:59 +02007704 * This function is styled after gui_send_mouse_event().
Bram Moolenaar071d4272004-06-13 20:20:40 +00007705 */
7706 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01007707mch_gpm_process(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007708{
7709 int button;
7710 static Gpm_Event gpm_event;
7711 char_u string[6];
7712 int_u vim_modifiers;
7713 int row,col;
7714 unsigned char buttons_mask;
7715 unsigned char gpm_modifiers;
7716 static unsigned char old_buttons = 0;
7717
7718 Gpm_GetEvent(&gpm_event);
7719
7720#ifdef FEAT_GUI
Bram Moolenaar0f873732019-12-05 20:28:46 +01007721 // Don't put events in the input queue now.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007722 if (hold_gui_events)
7723 return 0;
7724#endif
7725
7726 row = gpm_event.y - 1;
7727 col = gpm_event.x - 1;
7728
Bram Moolenaar0f873732019-12-05 20:28:46 +01007729 string[0] = ESC; // Our termcode
Bram Moolenaar071d4272004-06-13 20:20:40 +00007730 string[1] = 'M';
7731 string[2] = 'G';
7732 switch (GPM_BARE_EVENTS(gpm_event.type))
7733 {
7734 case GPM_DRAG:
7735 string[3] = MOUSE_DRAG;
7736 break;
7737 case GPM_DOWN:
7738 buttons_mask = gpm_event.buttons & ~old_buttons;
7739 old_buttons = gpm_event.buttons;
7740 switch (buttons_mask)
7741 {
7742 case GPM_B_LEFT:
7743 button = MOUSE_LEFT;
7744 break;
7745 case GPM_B_MIDDLE:
7746 button = MOUSE_MIDDLE;
7747 break;
7748 case GPM_B_RIGHT:
7749 button = MOUSE_RIGHT;
7750 break;
7751 default:
7752 return 0;
Bram Moolenaar0f873732019-12-05 20:28:46 +01007753 // Don't know what to do. Can more than one button be
7754 // reported in one event?
Bram Moolenaar071d4272004-06-13 20:20:40 +00007755 }
7756 string[3] = (char_u)(button | 0x20);
7757 SET_NUM_MOUSE_CLICKS(string[3], gpm_event.clicks + 1);
7758 break;
7759 case GPM_UP:
7760 string[3] = MOUSE_RELEASE;
7761 old_buttons &= ~gpm_event.buttons;
7762 break;
7763 default:
7764 return 0;
7765 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01007766 // This code is based on gui_x11_mouse_cb in gui_x11.c
Bram Moolenaar071d4272004-06-13 20:20:40 +00007767 gpm_modifiers = gpm_event.modifiers;
7768 vim_modifiers = 0x0;
Bram Moolenaar0f873732019-12-05 20:28:46 +01007769 // I ignore capslock stats. Aren't we all just hate capslock mixing with
7770 // Vim commands ? Besides, gpm_event.modifiers is unsigned char, and
7771 // K_CAPSSHIFT is defined 8, so it probably isn't even reported
Bram Moolenaar071d4272004-06-13 20:20:40 +00007772 if (gpm_modifiers & ((1 << KG_SHIFT) | (1 << KG_SHIFTR) | (1 << KG_SHIFTL)))
7773 vim_modifiers |= MOUSE_SHIFT;
7774
7775 if (gpm_modifiers & ((1 << KG_CTRL) | (1 << KG_CTRLR) | (1 << KG_CTRLL)))
7776 vim_modifiers |= MOUSE_CTRL;
7777 if (gpm_modifiers & ((1 << KG_ALT) | (1 << KG_ALTGR)))
7778 vim_modifiers |= MOUSE_ALT;
7779 string[3] |= vim_modifiers;
7780 string[4] = (char_u)(col + ' ' + 1);
7781 string[5] = (char_u)(row + ' ' + 1);
7782 add_to_input_buf(string, 6);
7783 return 6;
7784}
Bram Moolenaar0f873732019-12-05 20:28:46 +01007785#endif // FEAT_MOUSE_GPM
Bram Moolenaar071d4272004-06-13 20:20:40 +00007786
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00007787#ifdef FEAT_SYSMOUSE
7788/*
7789 * Initialize connection with sysmouse.
7790 * Let virtual console inform us with SIGUSR2 for pending sysmouse
7791 * output, any sysmouse output than will be processed via sig_sysmouse().
7792 * Return OK if succeeded, FAIL if failed.
7793 */
7794 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01007795sysmouse_open(void)
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00007796{
7797 struct mouse_info mouse;
7798
7799 mouse.operation = MOUSE_MODE;
7800 mouse.u.mode.mode = 0;
7801 mouse.u.mode.signal = SIGUSR2;
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00007802 if (ioctl(1, CONS_MOUSECTL, &mouse) == -1)
7803 return FAIL;
7804
ichizok378447f2023-05-11 22:25:42 +01007805 mch_signal(SIGUSR2, sig_sysmouse);
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00007806 mouse.operation = MOUSE_SHOW;
7807 ioctl(1, CONS_MOUSECTL, &mouse);
7808 return OK;
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00007809}
7810
7811/*
7812 * Stop processing SIGUSR2 signals, and also make sure that
7813 * virtual console do not send us any sysmouse related signal.
7814 */
7815 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01007816sysmouse_close(void)
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00007817{
7818 struct mouse_info mouse;
7819
ichizok378447f2023-05-11 22:25:42 +01007820 mch_signal(SIGUSR2, restricted ? SIG_IGN : SIG_DFL);
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00007821 mouse.operation = MOUSE_MODE;
7822 mouse.u.mode.mode = 0;
7823 mouse.u.mode.signal = 0;
7824 ioctl(1, CONS_MOUSECTL, &mouse);
7825}
7826
7827/*
7828 * Gets info from sysmouse and adds special keys to input buf.
7829 */
Bram Moolenaar99c48fe2022-06-05 22:05:19 +01007830 static void
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00007831sig_sysmouse SIGDEFARG(sigarg)
7832{
7833 struct mouse_info mouse;
7834 struct video_info video;
7835 char_u string[6];
7836 int row, col;
7837 int button;
7838 int buttons;
7839 static int oldbuttons = 0;
7840
7841#ifdef FEAT_GUI
Bram Moolenaar0f873732019-12-05 20:28:46 +01007842 // Don't put events in the input queue now.
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00007843 if (hold_gui_events)
7844 return;
7845#endif
7846
7847 mouse.operation = MOUSE_GETINFO;
7848 if (ioctl(1, FBIO_GETMODE, &video.vi_mode) != -1
7849 && ioctl(1, FBIO_MODEINFO, &video) != -1
7850 && ioctl(1, CONS_MOUSECTL, &mouse) != -1
7851 && video.vi_cheight > 0 && video.vi_cwidth > 0)
7852 {
7853 row = mouse.u.data.y / video.vi_cheight;
7854 col = mouse.u.data.x / video.vi_cwidth;
7855 buttons = mouse.u.data.buttons;
Bram Moolenaar0f873732019-12-05 20:28:46 +01007856 string[0] = ESC; // Our termcode
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00007857 string[1] = 'M';
7858 string[2] = 'S';
7859 if (oldbuttons == buttons && buttons != 0)
7860 {
7861 button = MOUSE_DRAG;
7862 }
7863 else
7864 {
7865 switch (buttons)
7866 {
7867 case 0:
7868 button = MOUSE_RELEASE;
7869 break;
7870 case 1:
7871 button = MOUSE_LEFT;
7872 break;
7873 case 2:
7874 button = MOUSE_MIDDLE;
7875 break;
7876 case 4:
7877 button = MOUSE_RIGHT;
7878 break;
7879 default:
7880 return;
7881 }
7882 oldbuttons = buttons;
7883 }
7884 string[3] = (char_u)(button);
7885 string[4] = (char_u)(col + ' ' + 1);
7886 string[5] = (char_u)(row + ' ' + 1);
7887 add_to_input_buf(string, 6);
7888 }
7889 return;
7890}
Bram Moolenaar0f873732019-12-05 20:28:46 +01007891#endif // FEAT_SYSMOUSE
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00007892
LemonBoy9987fe82024-07-04 13:20:49 +02007893/*
7894 * Fill the buffer 'buf' with 'len' random bytes.
7895 * Returns FAIL if the OS PRNG is not available or something went wrong.
7896 */
7897 int
7898mch_get_random(char_u *buf, int len)
7899{
7900 static int dev_urandom_state = NOTDONE;
7901
7902 if (dev_urandom_state == FAIL)
7903 return FAIL;
7904
7905 int fd = open("/dev/urandom", O_RDONLY);
7906
7907 // Attempt reading /dev/urandom.
7908 if (fd == -1)
7909 dev_urandom_state = FAIL;
7910 else if (read(fd, buf, len) == len)
Christian Brabandt93a3d2b2024-07-05 09:54:30 +02007911 {
LemonBoy9987fe82024-07-04 13:20:49 +02007912 dev_urandom_state = OK;
Christian Brabandt93a3d2b2024-07-05 09:54:30 +02007913 close(fd);
7914 }
LemonBoy9987fe82024-07-04 13:20:49 +02007915 else
7916 {
7917 dev_urandom_state = FAIL;
7918 close(fd);
7919 }
7920
7921 return dev_urandom_state;
7922}
7923
Bram Moolenaar071d4272004-06-13 20:20:40 +00007924#if defined(FEAT_LIBCALL) || defined(PROTO)
Bram Moolenaard99df422016-01-29 23:20:40 +01007925typedef char_u * (*STRPROCSTR)(char_u *);
7926typedef char_u * (*INTPROCSTR)(int);
7927typedef int (*STRPROCINT)(char_u *);
7928typedef int (*INTPROCINT)(int);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007929
7930/*
7931 * Call a DLL routine which takes either a string or int param
7932 * and returns an allocated string.
7933 */
7934 int
Bram Moolenaar05540972016-01-30 20:31:25 +01007935mch_libcall(
7936 char_u *libname,
7937 char_u *funcname,
Bram Moolenaar0f873732019-12-05 20:28:46 +01007938 char_u *argstring, // NULL when using a argint
Bram Moolenaar05540972016-01-30 20:31:25 +01007939 int argint,
Bram Moolenaar0f873732019-12-05 20:28:46 +01007940 char_u **string_result, // NULL when using number_result
Bram Moolenaar05540972016-01-30 20:31:25 +01007941 int *number_result)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007942{
7943# if defined(USE_DLOPEN)
7944 void *hinstLib;
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00007945 char *dlerr = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007946# else
7947 shl_t hinstLib;
7948# endif
7949 STRPROCSTR ProcAdd;
7950 INTPROCSTR ProcAddI;
7951 char_u *retval_str = NULL;
7952 int retval_int = 0;
7953 int success = FALSE;
7954
Bram Moolenaarb39ef122006-06-22 16:19:31 +00007955 /*
7956 * Get a handle to the DLL module.
7957 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007958# if defined(USE_DLOPEN)
Bram Moolenaar0f873732019-12-05 20:28:46 +01007959 // First clear any error, it's not cleared by the dlopen() call.
Bram Moolenaarb39ef122006-06-22 16:19:31 +00007960 (void)dlerror();
7961
Bram Moolenaar071d4272004-06-13 20:20:40 +00007962 hinstLib = dlopen((char *)libname, RTLD_LAZY
7963# ifdef RTLD_LOCAL
7964 | RTLD_LOCAL
7965# endif
7966 );
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00007967 if (hinstLib == NULL)
7968 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007969 // "dlerr" must be used before dlclose()
=?UTF-8?q?Dundar=20G=C3=B6c?=420fabc2022-01-28 15:28:04 +00007970 dlerr = dlerror();
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00007971 if (dlerr != NULL)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01007972 semsg(_("dlerror = \"%s\""), dlerr);
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00007973 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007974# else
7975 hinstLib = shl_load((const char*)libname, BIND_IMMEDIATE|BIND_VERBOSE, 0L);
7976# endif
7977
Bram Moolenaar0f873732019-12-05 20:28:46 +01007978 // If the handle is valid, try to get the function address.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007979 if (hinstLib != NULL)
7980 {
Bram Moolenaarb2148f52019-01-20 23:43:57 +01007981# ifdef USING_SETJMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00007982 /*
7983 * Catch a crash when calling the library function. For example when
7984 * using a number where a string pointer is expected.
7985 */
7986 mch_startjmp();
7987 if (SETJMP(lc_jump_env) != 0)
7988 {
7989 success = FALSE;
Bram Moolenaard68071d2006-05-02 22:08:30 +00007990# if defined(USE_DLOPEN)
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00007991 dlerr = NULL;
Bram Moolenaard68071d2006-05-02 22:08:30 +00007992# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007993 mch_didjmp();
7994 }
7995 else
7996# endif
7997 {
7998 retval_str = NULL;
7999 retval_int = 0;
8000
8001 if (argstring != NULL)
8002 {
8003# if defined(USE_DLOPEN)
Bram Moolenaar6d721c72017-01-17 16:56:28 +01008004 *(void **)(&ProcAdd) = dlsym(hinstLib, (const char *)funcname);
=?UTF-8?q?Dundar=20G=C3=B6c?=420fabc2022-01-28 15:28:04 +00008005 dlerr = dlerror();
Bram Moolenaar071d4272004-06-13 20:20:40 +00008006# else
8007 if (shl_findsym(&hinstLib, (const char *)funcname,
8008 TYPE_PROCEDURE, (void *)&ProcAdd) < 0)
8009 ProcAdd = NULL;
8010# endif
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00008011 if ((success = (ProcAdd != NULL
8012# if defined(USE_DLOPEN)
8013 && dlerr == NULL
8014# endif
8015 )))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008016 {
8017 if (string_result == NULL)
Bram Moolenaara4224862020-09-13 22:00:12 +02008018 retval_int = ((STRPROCINT)(void *)ProcAdd)(argstring);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008019 else
8020 retval_str = (ProcAdd)(argstring);
8021 }
8022 }
8023 else
8024 {
8025# if defined(USE_DLOPEN)
Bram Moolenaar6d721c72017-01-17 16:56:28 +01008026 *(void **)(&ProcAddI) = dlsym(hinstLib, (const char *)funcname);
=?UTF-8?q?Dundar=20G=C3=B6c?=420fabc2022-01-28 15:28:04 +00008027 dlerr = dlerror();
Bram Moolenaar071d4272004-06-13 20:20:40 +00008028# else
8029 if (shl_findsym(&hinstLib, (const char *)funcname,
8030 TYPE_PROCEDURE, (void *)&ProcAddI) < 0)
8031 ProcAddI = NULL;
8032# endif
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00008033 if ((success = (ProcAddI != NULL
8034# if defined(USE_DLOPEN)
8035 && dlerr == NULL
8036# endif
8037 )))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008038 {
8039 if (string_result == NULL)
Bram Moolenaara4224862020-09-13 22:00:12 +02008040 retval_int = ((INTPROCINT)(void *)ProcAddI)(argint);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008041 else
8042 retval_str = (ProcAddI)(argint);
8043 }
8044 }
8045
Bram Moolenaar0f873732019-12-05 20:28:46 +01008046 // Save the string before we free the library.
8047 // Assume that a "1" or "-1" result is an illegal pointer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008048 if (string_result == NULL)
8049 *number_result = retval_int;
8050 else if (retval_str != NULL
8051 && retval_str != (char_u *)1
8052 && retval_str != (char_u *)-1)
8053 *string_result = vim_strsave(retval_str);
8054 }
8055
Bram Moolenaarb2148f52019-01-20 23:43:57 +01008056# ifdef USING_SETJMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00008057 mch_endjmp();
8058# ifdef SIGHASARG
8059 if (lc_signal != 0)
8060 {
8061 int i;
8062
Bram Moolenaar0f873732019-12-05 20:28:46 +01008063 // try to find the name of this signal
Bram Moolenaar071d4272004-06-13 20:20:40 +00008064 for (i = 0; signal_info[i].sig != -1; i++)
8065 if (lc_signal == signal_info[i].sig)
8066 break;
Bram Moolenaar50809a42023-05-20 16:39:07 +01008067 semsg(_(e_got_sig_str_in_libcall), signal_info[i].name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008068 }
8069# endif
8070# endif
8071
Bram Moolenaar071d4272004-06-13 20:20:40 +00008072# if defined(USE_DLOPEN)
Bram Moolenaar0f873732019-12-05 20:28:46 +01008073 // "dlerr" must be used before dlclose()
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00008074 if (dlerr != NULL)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01008075 semsg(_("dlerror = \"%s\""), dlerr);
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00008076
Bram Moolenaar0f873732019-12-05 20:28:46 +01008077 // Free the DLL module.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008078 (void)dlclose(hinstLib);
8079# else
8080 (void)shl_unload(hinstLib);
8081# endif
8082 }
8083
8084 if (!success)
8085 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00008086 semsg(_(e_library_call_failed_for_str), funcname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008087 return FAIL;
8088 }
8089
8090 return OK;
8091}
8092#endif
8093
8094#if (defined(FEAT_X11) && defined(FEAT_XCLIPBOARD)) || defined(PROTO)
Bram Moolenaar0f873732019-12-05 20:28:46 +01008095static int xterm_trace = -1; // default: disabled
Bram Moolenaar071d4272004-06-13 20:20:40 +00008096static int xterm_button;
8097
8098/*
8099 * Setup a dummy window for X selections in a terminal.
8100 */
8101 void
Bram Moolenaar05540972016-01-30 20:31:25 +01008102setup_term_clip(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008103{
8104 int z = 0;
8105 char *strp = "";
8106 Widget AppShell;
8107
8108 if (!x_connect_to_server())
8109 return;
8110
8111 open_app_context();
8112 if (app_context != NULL && xterm_Shell == (Widget)0)
8113 {
Dominique Pellé4927bc72023-09-24 16:12:07 +02008114 int (*oldhandler)(Display*, XErrorEvent*);
Bram Moolenaarb2148f52019-01-20 23:43:57 +01008115# if defined(USING_SETJMP)
Dominique Pellé4927bc72023-09-24 16:12:07 +02008116 int (*oldIOhandler)(Display*);
Bram Moolenaaredce7422019-01-20 18:39:30 +01008117# endif
Bram Moolenaar833eb1d2016-11-24 17:22:50 +01008118# ifdef ELAPSED_FUNC
Bram Moolenaar1ac56c22019-01-17 22:28:22 +01008119 elapsed_T start_tv;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008120
8121 if (p_verbose > 0)
Bram Moolenaar833eb1d2016-11-24 17:22:50 +01008122 ELAPSED_INIT(start_tv);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008123# endif
8124
Bram Moolenaar0f873732019-12-05 20:28:46 +01008125 // Ignore X errors while opening the display
Bram Moolenaar071d4272004-06-13 20:20:40 +00008126 oldhandler = XSetErrorHandler(x_error_check);
8127
Bram Moolenaarb2148f52019-01-20 23:43:57 +01008128# if defined(USING_SETJMP)
Bram Moolenaar0f873732019-12-05 20:28:46 +01008129 // Ignore X IO errors while opening the display
Bram Moolenaar071d4272004-06-13 20:20:40 +00008130 oldIOhandler = XSetIOErrorHandler(x_IOerror_check);
8131 mch_startjmp();
8132 if (SETJMP(lc_jump_env) != 0)
8133 {
8134 mch_didjmp();
8135 xterm_dpy = NULL;
8136 }
8137 else
Bram Moolenaaredce7422019-01-20 18:39:30 +01008138# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00008139 {
8140 xterm_dpy = XtOpenDisplay(app_context, xterm_display,
8141 "vim_xterm", "Vim_xterm", NULL, 0, &z, &strp);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01008142 if (xterm_dpy != NULL)
8143 xterm_dpy_retry_count = 0;
Bram Moolenaarb2148f52019-01-20 23:43:57 +01008144# if defined(USING_SETJMP)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008145 mch_endjmp();
Bram Moolenaaredce7422019-01-20 18:39:30 +01008146# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00008147 }
8148
Bram Moolenaarb2148f52019-01-20 23:43:57 +01008149# if defined(USING_SETJMP)
Bram Moolenaar0f873732019-12-05 20:28:46 +01008150 // Now handle X IO errors normally.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008151 (void)XSetIOErrorHandler(oldIOhandler);
Bram Moolenaaredce7422019-01-20 18:39:30 +01008152# endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01008153 // Now handle X errors normally.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008154 (void)XSetErrorHandler(oldhandler);
8155
8156 if (xterm_dpy == NULL)
8157 {
8158 if (p_verbose > 0)
Bram Moolenaar32526b32019-01-19 17:43:09 +01008159 verb_msg(_("Opening the X display failed"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00008160 return;
8161 }
8162
Bram Moolenaar0f873732019-12-05 20:28:46 +01008163 // Catch terminating error of the X server connection.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008164 (void)XSetIOErrorHandler(x_IOerror_handler);
8165
Bram Moolenaar833eb1d2016-11-24 17:22:50 +01008166# ifdef ELAPSED_FUNC
Bram Moolenaar071d4272004-06-13 20:20:40 +00008167 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00008168 {
8169 verbose_enter();
Bram Moolenaar833eb1d2016-11-24 17:22:50 +01008170 xopen_message(ELAPSED_FUNC(start_tv));
Bram Moolenaara04f10b2005-05-31 22:09:46 +00008171 verbose_leave();
8172 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008173# endif
8174
Bram Moolenaar0f873732019-12-05 20:28:46 +01008175 // Create a Shell to make converters work.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008176 AppShell = XtVaAppCreateShell("vim_xterm", "Vim_xterm",
8177 applicationShellWidgetClass, xterm_dpy,
8178 NULL);
8179 if (AppShell == (Widget)0)
8180 return;
8181 xterm_Shell = XtVaCreatePopupShell("VIM",
8182 topLevelShellWidgetClass, AppShell,
8183 XtNmappedWhenManaged, 0,
8184 XtNwidth, 1,
8185 XtNheight, 1,
8186 NULL);
8187 if (xterm_Shell == (Widget)0)
8188 return;
8189
8190 x11_setup_atoms(xterm_dpy);
Bram Moolenaar7cfea752010-06-22 06:07:12 +02008191 x11_setup_selection(xterm_Shell);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008192 if (x11_display == NULL)
8193 x11_display = xterm_dpy;
8194
8195 XtRealizeWidget(xterm_Shell);
8196 XSync(xterm_dpy, False);
8197 xterm_update();
8198 }
8199 if (xterm_Shell != (Widget)0)
8200 {
8201 clip_init(TRUE);
8202 if (x11_window == 0 && (strp = getenv("WINDOWID")) != NULL)
8203 x11_window = (Window)atol(strp);
Bram Moolenaar0f873732019-12-05 20:28:46 +01008204 // Check if $WINDOWID is valid.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008205 if (test_x11_window(xterm_dpy) == FAIL)
8206 x11_window = 0;
8207 if (x11_window != 0)
8208 xterm_trace = 0;
8209 }
8210}
8211
8212 void
Bram Moolenaar05540972016-01-30 20:31:25 +01008213start_xterm_trace(int button)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008214{
8215 if (x11_window == 0 || xterm_trace < 0 || xterm_Shell == (Widget)0)
8216 return;
8217 xterm_trace = 1;
8218 xterm_button = button;
8219 do_xterm_trace();
8220}
8221
8222
8223 void
Bram Moolenaar05540972016-01-30 20:31:25 +01008224stop_xterm_trace(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008225{
8226 if (xterm_trace < 0)
8227 return;
8228 xterm_trace = 0;
8229}
8230
8231/*
8232 * Query the xterm pointer and generate mouse termcodes if necessary
8233 * return TRUE if dragging is active, else FALSE
8234 */
8235 static int
Bram Moolenaar05540972016-01-30 20:31:25 +01008236do_xterm_trace(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008237{
8238 Window root, child;
8239 int root_x, root_y;
8240 int win_x, win_y;
8241 int row, col;
8242 int_u mask_return;
8243 char_u buf[50];
8244 char_u *strp;
8245 long got_hints;
John Marriottefc41a52025-01-23 20:05:29 +01008246 static char_u *mouse_code = NULL;
8247 static size_t mouse_codelen = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008248 static char_u mouse_name[2] = {KS_MOUSE, KE_FILLER};
8249 static int prev_row = 0, prev_col = 0;
8250 static XSizeHints xterm_hints;
8251
8252 if (xterm_trace <= 0)
8253 return FALSE;
8254
8255 if (xterm_trace == 1)
8256 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01008257 // Get the hints just before tracking starts. The font size might
8258 // have changed recently.
Bram Moolenaara6c2c912008-01-13 15:31:00 +00008259 if (!XGetWMNormalHints(xterm_dpy, x11_window, &xterm_hints, &got_hints)
8260 || !(got_hints & PResizeInc)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008261 || xterm_hints.width_inc <= 1
8262 || xterm_hints.height_inc <= 1)
8263 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01008264 xterm_trace = -1; // Not enough data -- disable tracing
Bram Moolenaar071d4272004-06-13 20:20:40 +00008265 return FALSE;
8266 }
8267
Bram Moolenaar0f873732019-12-05 20:28:46 +01008268 // Rely on the same mouse code for the duration of this
Bram Moolenaar071d4272004-06-13 20:20:40 +00008269 mouse_code = find_termcode(mouse_name);
John Marriottefc41a52025-01-23 20:05:29 +01008270 if (mouse_code != NULL)
8271 mouse_codelen = STRLEN(mouse_code);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008272 prev_row = mouse_row;
Bram Moolenaarcde88542015-08-11 19:14:00 +02008273 prev_col = mouse_col;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008274 xterm_trace = 2;
8275
Bram Moolenaar0f873732019-12-05 20:28:46 +01008276 // Find the offset of the chars, there might be a scrollbar on the
8277 // left of the window and/or a menu on the top (eterm etc.)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008278 XQueryPointer(xterm_dpy, x11_window, &root, &child, &root_x, &root_y,
8279 &win_x, &win_y, &mask_return);
8280 xterm_hints.y = win_y - (xterm_hints.height_inc * mouse_row)
8281 - (xterm_hints.height_inc / 2);
8282 if (xterm_hints.y <= xterm_hints.height_inc / 2)
8283 xterm_hints.y = 2;
8284 xterm_hints.x = win_x - (xterm_hints.width_inc * mouse_col)
8285 - (xterm_hints.width_inc / 2);
8286 if (xterm_hints.x <= xterm_hints.width_inc / 2)
8287 xterm_hints.x = 2;
8288 return TRUE;
8289 }
John Marriottefc41a52025-01-23 20:05:29 +01008290
8291 if (mouse_code == NULL || mouse_codelen > 45)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008292 {
8293 xterm_trace = 0;
8294 return FALSE;
8295 }
8296
8297 XQueryPointer(xterm_dpy, x11_window, &root, &child, &root_x, &root_y,
8298 &win_x, &win_y, &mask_return);
8299
8300 row = check_row((win_y - xterm_hints.y) / xterm_hints.height_inc);
8301 col = check_col((win_x - xterm_hints.x) / xterm_hints.width_inc);
8302 if (row == prev_row && col == prev_col)
8303 return TRUE;
8304
8305 STRCPY(buf, mouse_code);
John Marriottefc41a52025-01-23 20:05:29 +01008306 strp = buf + mouse_codelen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008307 *strp++ = (xterm_button | MOUSE_DRAG) & ~0x20;
8308 *strp++ = (char_u)(col + ' ' + 1);
8309 *strp++ = (char_u)(row + ' ' + 1);
John Marriottefc41a52025-01-23 20:05:29 +01008310 *strp = NUL;
8311 add_to_input_buf(buf, strp - buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008312
8313 prev_row = row;
8314 prev_col = col;
8315 return TRUE;
8316}
8317
Bram Moolenaard4aa83a2019-05-09 18:59:31 +02008318# if defined(FEAT_GUI) || defined(FEAT_XCLIPBOARD) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008319/*
8320 * Destroy the display, window and app_context. Required for GTK.
8321 */
8322 void
Bram Moolenaar05540972016-01-30 20:31:25 +01008323clear_xterm_clip(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008324{
8325 if (xterm_Shell != (Widget)0)
8326 {
8327 XtDestroyWidget(xterm_Shell);
8328 xterm_Shell = (Widget)0;
8329 }
8330 if (xterm_dpy != NULL)
8331 {
Bram Moolenaare8208012008-06-20 09:59:25 +00008332# if 0
Bram Moolenaar0f873732019-12-05 20:28:46 +01008333 // Lesstif and Solaris crash here, lose some memory
Bram Moolenaar071d4272004-06-13 20:20:40 +00008334 XtCloseDisplay(xterm_dpy);
Bram Moolenaare8208012008-06-20 09:59:25 +00008335# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00008336 if (x11_display == xterm_dpy)
8337 x11_display = NULL;
8338 xterm_dpy = NULL;
8339 }
Bram Moolenaare8208012008-06-20 09:59:25 +00008340# if 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00008341 if (app_context != (XtAppContext)NULL)
8342 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01008343 // Lesstif and Solaris crash here, lose some memory
Bram Moolenaar071d4272004-06-13 20:20:40 +00008344 XtDestroyApplicationContext(app_context);
8345 app_context = (XtAppContext)NULL;
8346 }
Bram Moolenaare8208012008-06-20 09:59:25 +00008347# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00008348}
8349# endif
8350
8351/*
Bram Moolenaar090cfc12013-03-19 12:35:42 +01008352 * Catch up with GUI or X events.
8353 */
8354 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01008355clip_update(void)
Bram Moolenaar090cfc12013-03-19 12:35:42 +01008356{
8357# ifdef FEAT_GUI
8358 if (gui.in_use)
8359 gui_mch_update();
8360 else
8361# endif
8362 if (xterm_Shell != (Widget)0)
8363 xterm_update();
8364}
8365
8366/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008367 * Catch up with any queued X events. This may put keyboard input into the
8368 * input buffer, call resize call-backs, trigger timers etc. If there is
8369 * nothing in the X event queue (& no timers pending), then we return
8370 * immediately.
8371 */
Foxe Chenb90c2392025-06-27 21:10:35 +02008372 void
Bram Moolenaar05540972016-01-30 20:31:25 +01008373xterm_update(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008374{
8375 XEvent event;
8376
Bram Moolenaarb1fc2bf2015-03-20 16:26:54 +01008377 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008378 {
Bram Moolenaar93c88e02015-09-15 14:12:05 +02008379 XtInputMask mask = XtAppPending(app_context);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008380
Bram Moolenaar93c88e02015-09-15 14:12:05 +02008381 if (mask == 0 || vim_is_input_buf_full())
Bram Moolenaarb1fc2bf2015-03-20 16:26:54 +01008382 break;
8383
Bram Moolenaar93c88e02015-09-15 14:12:05 +02008384 if (mask & XtIMXEvent)
Bram Moolenaarb1fc2bf2015-03-20 16:26:54 +01008385 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01008386 // There is an event to process.
Bram Moolenaar93c88e02015-09-15 14:12:05 +02008387 XtAppNextEvent(app_context, &event);
Bram Moolenaarb1fc2bf2015-03-20 16:26:54 +01008388#ifdef FEAT_CLIENTSERVER
8389 {
8390 XPropertyEvent *e = (XPropertyEvent *)&event;
8391
8392 if (e->type == PropertyNotify && e->window == commWindow
Bram Moolenaar071d4272004-06-13 20:20:40 +00008393 && e->atom == commProperty && e->state == PropertyNewValue)
Bram Moolenaar93c88e02015-09-15 14:12:05 +02008394 serverEventProc(xterm_dpy, &event, 0);
Bram Moolenaarb1fc2bf2015-03-20 16:26:54 +01008395 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008396#endif
Bram Moolenaar93c88e02015-09-15 14:12:05 +02008397 XtDispatchEvent(&event);
8398 }
Bram Moolenaarb1fc2bf2015-03-20 16:26:54 +01008399 else
8400 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01008401 // There is something else than an event to process.
Bram Moolenaar93c88e02015-09-15 14:12:05 +02008402 XtAppProcessEvent(app_context, mask);
8403 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008404 }
8405}
8406
8407 int
Bram Moolenaar0554fa42019-06-14 21:36:54 +02008408clip_xterm_own_selection(Clipboard_T *cbd)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008409{
8410 if (xterm_Shell != (Widget)0)
8411 return clip_x11_own_selection(xterm_Shell, cbd);
8412 return FAIL;
8413}
8414
8415 void
Bram Moolenaar0554fa42019-06-14 21:36:54 +02008416clip_xterm_lose_selection(Clipboard_T *cbd)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008417{
8418 if (xterm_Shell != (Widget)0)
8419 clip_x11_lose_selection(xterm_Shell, cbd);
8420}
8421
8422 void
Bram Moolenaar0554fa42019-06-14 21:36:54 +02008423clip_xterm_request_selection(Clipboard_T *cbd)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008424{
8425 if (xterm_Shell != (Widget)0)
8426 clip_x11_request_selection(xterm_Shell, xterm_dpy, cbd);
8427}
8428
8429 void
Bram Moolenaar0554fa42019-06-14 21:36:54 +02008430clip_xterm_set_selection(Clipboard_T *cbd)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008431{
8432 clip_x11_set_selection(cbd);
8433}
8434#endif
8435
8436
8437#if defined(USE_XSMP) || defined(PROTO)
8438/*
8439 * Code for X Session Management Protocol.
8440 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008441
8442# if defined(FEAT_GUI) && defined(USE_XSMP_INTERACT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008443/*
8444 * This is our chance to ask the user if they want to save,
8445 * or abort the logout
8446 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008447 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01008448xsmp_handle_interaction(SmcConn smc_conn, SmPointer client_data UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008449{
Bram Moolenaare1004402020-10-24 20:49:43 +02008450 int save_cmod_flags;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008451 int cancel_shutdown = False;
8452
Bram Moolenaare1004402020-10-24 20:49:43 +02008453 save_cmod_flags = cmdmod.cmod_flags;
8454 cmdmod.cmod_flags |= CMOD_CONFIRM;
Bram Moolenaar027387f2016-01-02 22:25:52 +01008455 if (check_changed_any(FALSE, FALSE))
Bram Moolenaar0f873732019-12-05 20:28:46 +01008456 // Mustn't logout
Bram Moolenaar071d4272004-06-13 20:20:40 +00008457 cancel_shutdown = True;
Bram Moolenaare1004402020-10-24 20:49:43 +02008458 cmdmod.cmod_flags = save_cmod_flags;
Bram Moolenaar0f873732019-12-05 20:28:46 +01008459 setcursor(); // position cursor
Bram Moolenaar071d4272004-06-13 20:20:40 +00008460 out_flush();
8461
Bram Moolenaar0f873732019-12-05 20:28:46 +01008462 // Done interaction
Bram Moolenaar071d4272004-06-13 20:20:40 +00008463 SmcInteractDone(smc_conn, cancel_shutdown);
8464
Bram Moolenaar0f873732019-12-05 20:28:46 +01008465 // Finish off
8466 // Only end save-yourself here if we're not cancelling shutdown;
8467 // we'll get a cancelled callback later in which we'll end it.
8468 // Hopefully get around glitchy SMs (like GNOME-1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008469 if (!cancel_shutdown)
8470 {
8471 xsmp.save_yourself = False;
8472 SmcSaveYourselfDone(smc_conn, True);
8473 }
8474}
8475# endif
8476
8477/*
8478 * Callback that starts save-yourself.
8479 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008480 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01008481xsmp_handle_save_yourself(
8482 SmcConn smc_conn,
8483 SmPointer client_data UNUSED,
8484 int save_type UNUSED,
8485 Bool shutdown,
8486 int interact_style UNUSED,
8487 Bool fast UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008488{
Bram Moolenaar0f873732019-12-05 20:28:46 +01008489 // Handle already being in saveyourself
Bram Moolenaar071d4272004-06-13 20:20:40 +00008490 if (xsmp.save_yourself)
8491 SmcSaveYourselfDone(smc_conn, True);
8492 xsmp.save_yourself = True;
8493 xsmp.shutdown = shutdown;
8494
Bram Moolenaar0f873732019-12-05 20:28:46 +01008495 // First up, preserve all files
Bram Moolenaar071d4272004-06-13 20:20:40 +00008496 out_flush();
Bram Moolenaar0f873732019-12-05 20:28:46 +01008497 ml_sync_all(FALSE, FALSE); // preserve all swap files
Bram Moolenaar071d4272004-06-13 20:20:40 +00008498
8499 if (p_verbose > 0)
Bram Moolenaar32526b32019-01-19 17:43:09 +01008500 verb_msg(_("XSMP handling save-yourself request"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00008501
8502# if defined(FEAT_GUI) && defined(USE_XSMP_INTERACT)
Bram Moolenaar0f873732019-12-05 20:28:46 +01008503 // Now see if we can ask about unsaved files
Bram Moolenaar071d4272004-06-13 20:20:40 +00008504 if (shutdown && !fast && gui.in_use)
Bram Moolenaar0f873732019-12-05 20:28:46 +01008505 // Need to interact with user, but need SM's permission
Bram Moolenaar071d4272004-06-13 20:20:40 +00008506 SmcInteractRequest(smc_conn, SmDialogError,
8507 xsmp_handle_interaction, client_data);
8508 else
8509# endif
8510 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01008511 // Can stop the cycle here
Bram Moolenaar071d4272004-06-13 20:20:40 +00008512 SmcSaveYourselfDone(smc_conn, True);
8513 xsmp.save_yourself = False;
8514 }
8515}
8516
8517
8518/*
8519 * Callback to warn us of imminent death.
8520 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008521 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01008522xsmp_die(SmcConn smc_conn UNUSED, SmPointer client_data UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008523{
8524 xsmp_close();
8525
Bram Moolenaar0f873732019-12-05 20:28:46 +01008526 // quit quickly leaving swapfiles for modified buffers behind
Bram Moolenaar071d4272004-06-13 20:20:40 +00008527 getout_preserve_modified(0);
8528}
8529
8530
8531/*
8532 * Callback to tell us that save-yourself has completed.
8533 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008534 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01008535xsmp_save_complete(
8536 SmcConn smc_conn UNUSED,
8537 SmPointer client_data UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008538{
8539 xsmp.save_yourself = False;
8540}
8541
8542
8543/*
8544 * Callback to tell us that an instigated shutdown was cancelled
8545 * (maybe even by us)
8546 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008547 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01008548xsmp_shutdown_cancelled(
8549 SmcConn smc_conn,
8550 SmPointer client_data UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008551{
8552 if (xsmp.save_yourself)
8553 SmcSaveYourselfDone(smc_conn, True);
8554 xsmp.save_yourself = False;
8555 xsmp.shutdown = False;
8556}
8557
8558
8559/*
8560 * Callback to tell us that a new ICE connection has been established.
8561 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008562 static void
Bram Moolenaar05540972016-01-30 20:31:25 +01008563xsmp_ice_connection(
8564 IceConn iceConn,
8565 IcePointer clientData UNUSED,
8566 Bool opening,
8567 IcePointer *watchData UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008568{
Bram Moolenaar0f873732019-12-05 20:28:46 +01008569 // Intercept creation of ICE connection fd
Bram Moolenaar071d4272004-06-13 20:20:40 +00008570 if (opening)
8571 {
8572 xsmp_icefd = IceConnectionNumber(iceConn);
8573 IceRemoveConnectionWatch(xsmp_ice_connection, NULL);
8574 }
8575}
8576
8577
Bram Moolenaar0f873732019-12-05 20:28:46 +01008578// Handle any ICE processing that's required; return FAIL if SM lost
Bram Moolenaar071d4272004-06-13 20:20:40 +00008579 int
Bram Moolenaar05540972016-01-30 20:31:25 +01008580xsmp_handle_requests(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008581{
8582 Bool rep;
8583
8584 if (IceProcessMessages(xsmp.iceconn, NULL, &rep)
8585 == IceProcessMessagesIOError)
8586 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01008587 // Lost ICE
Bram Moolenaar071d4272004-06-13 20:20:40 +00008588 if (p_verbose > 0)
Bram Moolenaar32526b32019-01-19 17:43:09 +01008589 verb_msg(_("XSMP lost ICE connection"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00008590 xsmp_close();
8591 return FAIL;
8592 }
8593 else
8594 return OK;
8595}
8596
8597static int dummy;
8598
Bram Moolenaar0f873732019-12-05 20:28:46 +01008599// Set up X Session Management Protocol
Bram Moolenaar071d4272004-06-13 20:20:40 +00008600 void
8601xsmp_init(void)
8602{
8603 char errorstring[80];
Bram Moolenaar071d4272004-06-13 20:20:40 +00008604 SmcCallbacks smcallbacks;
8605#if 0
8606 SmPropValue smname;
8607 SmProp smnameprop;
8608 SmProp *smprops[1];
8609#endif
8610
8611 if (p_verbose > 0)
Bram Moolenaar32526b32019-01-19 17:43:09 +01008612 verb_msg(_("XSMP opening connection"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00008613
8614 xsmp.save_yourself = xsmp.shutdown = False;
8615
Bram Moolenaar0f873732019-12-05 20:28:46 +01008616 // Set up SM callbacks - must have all, even if they're not used
Bram Moolenaar071d4272004-06-13 20:20:40 +00008617 smcallbacks.save_yourself.callback = xsmp_handle_save_yourself;
8618 smcallbacks.save_yourself.client_data = NULL;
8619 smcallbacks.die.callback = xsmp_die;
8620 smcallbacks.die.client_data = NULL;
8621 smcallbacks.save_complete.callback = xsmp_save_complete;
8622 smcallbacks.save_complete.client_data = NULL;
8623 smcallbacks.shutdown_cancelled.callback = xsmp_shutdown_cancelled;
8624 smcallbacks.shutdown_cancelled.client_data = NULL;
8625
Bram Moolenaar0f873732019-12-05 20:28:46 +01008626 // Set up a watch on ICE connection creations. The "dummy" argument is
8627 // apparently required for FreeBSD (we get a BUS error when using NULL).
Bram Moolenaar071d4272004-06-13 20:20:40 +00008628 if (IceAddConnectionWatch(xsmp_ice_connection, &dummy) == 0)
8629 {
8630 if (p_verbose > 0)
Bram Moolenaar32526b32019-01-19 17:43:09 +01008631 verb_msg(_("XSMP ICE connection watch failed"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00008632 return;
8633 }
8634
Bram Moolenaar0f873732019-12-05 20:28:46 +01008635 // Create an SM connection
Bram Moolenaar071d4272004-06-13 20:20:40 +00008636 xsmp.smcconn = SmcOpenConnection(
8637 NULL,
8638 NULL,
8639 SmProtoMajor,
8640 SmProtoMinor,
8641 SmcSaveYourselfProcMask | SmcDieProcMask
8642 | SmcSaveCompleteProcMask | SmcShutdownCancelledProcMask,
8643 &smcallbacks,
8644 NULL,
Bram Moolenaare8208012008-06-20 09:59:25 +00008645 &xsmp.clientid,
Bram Moolenaar4841a7c2018-09-22 14:08:49 +02008646 sizeof(errorstring) - 1,
Bram Moolenaar071d4272004-06-13 20:20:40 +00008647 errorstring);
8648 if (xsmp.smcconn == NULL)
8649 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00008650 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00008651 {
Bram Moolenaare1be1182020-10-24 13:30:51 +02008652 char errorreport[132];
8653
8654 // If the message is too long it might not be NUL terminated. Add
8655 // a NUL at the end to make sure we don't go over the end.
8656 errorstring[sizeof(errorstring) - 1] = NUL;
Bram Moolenaara04f10b2005-05-31 22:09:46 +00008657 vim_snprintf(errorreport, sizeof(errorreport),
8658 _("XSMP SmcOpenConnection failed: %s"), errorstring);
Bram Moolenaar32526b32019-01-19 17:43:09 +01008659 verb_msg(errorreport);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00008660 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008661 return;
8662 }
8663 xsmp.iceconn = SmcGetIceConnection(xsmp.smcconn);
8664
8665#if 0
Bram Moolenaar0f873732019-12-05 20:28:46 +01008666 // ID ourselves
Bram Moolenaar071d4272004-06-13 20:20:40 +00008667 smname.value = "vim";
8668 smname.length = 3;
8669 smnameprop.name = "SmProgram";
8670 smnameprop.type = "SmARRAY8";
8671 smnameprop.num_vals = 1;
8672 smnameprop.vals = &smname;
8673
8674 smprops[0] = &smnameprop;
8675 SmcSetProperties(xsmp.smcconn, 1, smprops);
8676#endif
8677}
8678
8679
Bram Moolenaar0f873732019-12-05 20:28:46 +01008680// Shut down XSMP comms.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008681 void
Bram Moolenaar05540972016-01-30 20:31:25 +01008682xsmp_close(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008683{
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008684 if (xsmp_icefd == -1)
8685 return;
8686
8687 SmcCloseConnection(xsmp.smcconn, 0, NULL);
8688 if (xsmp.clientid != NULL)
8689 free(xsmp.clientid);
8690 xsmp.clientid = NULL;
8691 xsmp_icefd = -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008692}
Bram Moolenaar0f873732019-12-05 20:28:46 +01008693#endif // USE_XSMP
Paul Ollis65745772022-06-05 16:55:54 +01008694
8695#if defined(FEAT_RELTIME) || defined(PROTO)
Bram Moolenaar08210f82023-04-13 19:15:54 +01008696# if defined(PROF_NSEC) || defined(PROTO)
Paul Ollis65745772022-06-05 16:55:54 +01008697/*
8698 * Implement timeout with timer_create() and timer_settime().
8699 */
Bram Moolenaar155f2d12022-06-20 13:38:33 +01008700static volatile sig_atomic_t timeout_flag = FALSE;
8701static timer_t timer_id;
8702static int timer_created = FALSE;
Paul Ollis65745772022-06-05 16:55:54 +01008703
8704/*
8705 * Callback for when the timer expires.
8706 */
8707 static void
8708set_flag(union sigval _unused UNUSED)
8709{
8710 timeout_flag = TRUE;
8711}
8712
8713/*
8714 * Stop any active timeout.
8715 */
8716 void
8717stop_timeout(void)
8718{
8719 static struct itimerspec disarm = {{0, 0}, {0, 0}};
8720
8721 if (timer_created)
8722 {
8723 int ret = timer_settime(timer_id, 0, &disarm, NULL);
8724
8725 if (ret < 0)
8726 semsg(_(e_could_not_clear_timeout_str), strerror(errno));
8727 }
8728
8729 // Clear the current timeout flag; any previous timeout should be
8730 // considered _not_ triggered.
8731 timeout_flag = FALSE;
8732}
8733
8734/*
8735 * Start the timeout timer.
8736 *
8737 * The return value is a pointer to a flag that is initialised to FALSE. If the
8738 * timeout expires, the flag is set to TRUE. This will only return pointers to
8739 * static memory; i.e. any pointer returned by this function may always be
8740 * safely dereferenced.
8741 *
8742 * This function is not expected to fail, but if it does it will still return a
8743 * valid flag pointer; the flag will remain stuck as FALSE .
8744 */
Bram Moolenaar155f2d12022-06-20 13:38:33 +01008745 volatile sig_atomic_t *
Paul Ollis65745772022-06-05 16:55:54 +01008746start_timeout(long msec)
8747{
8748 struct itimerspec interval = {
Bram Moolenaar88456cd2022-11-18 22:14:09 +00008749 {0, 0}, // Do not repeat.
8750 {msec / 1000, (msec % 1000) * 1000000}}; // Timeout interval
Paul Ollis65745772022-06-05 16:55:54 +01008751 int ret;
8752
8753 // This is really the caller's responsibility, but let's make sure the
8754 // previous timer has been stopped.
8755 stop_timeout();
Paul Ollis65745772022-06-05 16:55:54 +01008756
8757 if (!timer_created)
8758 {
8759 struct sigevent action = {0};
8760
8761 action.sigev_notify = SIGEV_THREAD;
8762 action.sigev_notify_function = set_flag;
Bram Moolenaar88456cd2022-11-18 22:14:09 +00008763 ret = timer_create(CLOCK_MONOTONIC, &action, &timer_id);
8764 if (ret < 0)
Paul Ollis65745772022-06-05 16:55:54 +01008765 {
8766 semsg(_(e_could_not_set_timeout_str), strerror(errno));
8767 return &timeout_flag;
8768 }
8769 timer_created = TRUE;
8770 }
8771
Bram Moolenaar4c5678f2022-11-30 18:12:19 +00008772# ifdef FEAT_EVAL
Bram Moolenaar616592e2022-06-17 15:17:10 +01008773 ch_log(NULL, "setting timeout timer to %d sec %ld nsec",
8774 (int)interval.it_value.tv_sec, (long)interval.it_value.tv_nsec);
Bram Moolenaar509ce032022-06-20 11:23:01 +01008775# endif
Paul Ollis65745772022-06-05 16:55:54 +01008776 ret = timer_settime(timer_id, 0, &interval, NULL);
8777 if (ret < 0)
8778 semsg(_(e_could_not_set_timeout_str), strerror(errno));
8779
8780 return &timeout_flag;
8781}
8782
Bram Moolenaarc72e31d2022-06-16 18:47:20 +01008783/*
8784 * To be used before fork/exec: delete any created timer.
8785 */
8786 void
8787delete_timer(void)
8788{
Yegappan Lakshmanana41e2212023-01-16 18:19:05 +00008789 if (!timer_created)
8790 return;
8791
8792 timer_delete(timer_id);
8793 timer_created = FALSE;
Bram Moolenaarc72e31d2022-06-16 18:47:20 +01008794}
8795
Bram Moolenaar08210f82023-04-13 19:15:54 +01008796# else // PROF_NSEC
Paul Ollis65745772022-06-05 16:55:54 +01008797
8798/*
8799 * Implement timeout with setitimer()
8800 */
Bram Moolenaar155f2d12022-06-20 13:38:33 +01008801static struct sigaction prev_sigaction;
Bram Moolenaar88456cd2022-11-18 22:14:09 +00008802static volatile sig_atomic_t timeout_flag = FALSE;
8803static int timer_active = FALSE;
Bram Moolenaar155f2d12022-06-20 13:38:33 +01008804static int timer_handler_active = FALSE;
Bram Moolenaar88456cd2022-11-18 22:14:09 +00008805static volatile sig_atomic_t alarm_pending = FALSE;
Paul Ollis65745772022-06-05 16:55:54 +01008806
8807/*
8808 * Handle SIGALRM for a timeout.
8809 */
Bram Moolenaar99c48fe2022-06-05 22:05:19 +01008810 static void
Paul Ollis65745772022-06-05 16:55:54 +01008811set_flag SIGDEFARG(sigarg)
8812{
8813 if (alarm_pending)
8814 alarm_pending = FALSE;
8815 else
8816 timeout_flag = TRUE;
8817}
8818
8819/*
8820 * Stop any active timeout.
8821 */
8822 void
8823stop_timeout(void)
8824{
8825 static struct itimerval disarm = {{0, 0}, {0, 0}};
8826 int ret;
8827
8828 if (timer_active)
8829 {
8830 timer_active = FALSE;
Bram Moolenaar155f2d12022-06-20 13:38:33 +01008831 ret = setitimer(ITIMER_REAL, &disarm, NULL);
Paul Ollis65745772022-06-05 16:55:54 +01008832 if (ret < 0)
8833 // Should only get here as a result of coding errors.
8834 semsg(_(e_could_not_clear_timeout_str), strerror(errno));
8835 }
8836
8837 if (timer_handler_active)
8838 {
8839 timer_handler_active = FALSE;
8840 ret = sigaction(SIGALRM, &prev_sigaction, NULL);
8841 if (ret < 0)
8842 // Should only get here as a result of coding errors.
8843 semsg(_(e_could_not_reset_handler_for_timeout_str),
8844 strerror(errno));
8845 }
Bram Moolenaar155f2d12022-06-20 13:38:33 +01008846 timeout_flag = FALSE;
Paul Ollis65745772022-06-05 16:55:54 +01008847}
8848
8849/*
8850 * Start the timeout timer.
8851 *
8852 * The return value is a pointer to a flag that is initialised to FALSE. If the
8853 * timeout expires, the flag is set to TRUE. This will only return pointers to
8854 * static memory; i.e. any pointer returned by this function may always be
8855 * safely dereferenced.
8856 *
8857 * This function is not expected to fail, but if it does it will still return a
8858 * valid flag pointer; the flag will remain stuck as FALSE .
8859 */
Bram Moolenaar155f2d12022-06-20 13:38:33 +01008860 volatile sig_atomic_t *
Paul Ollis65745772022-06-05 16:55:54 +01008861start_timeout(long msec)
8862{
8863 struct itimerval interval = {
Bram Moolenaar88456cd2022-11-18 22:14:09 +00008864 {0, 0}, // Do not repeat.
8865 {msec / 1000, (msec % 1000) * 1000}}; // Timeout interval
Paul Ollis65745772022-06-05 16:55:54 +01008866 struct sigaction handle_alarm;
8867 int ret;
8868 sigset_t sigs;
8869 sigset_t saved_sigs;
8870
8871 // This is really the caller's responsibility, but let's make sure the
8872 // previous timer has been stopped.
8873 stop_timeout();
8874
8875 // There is a small chance that SIGALRM is pending and so the handler must
8876 // ignore it on the first call.
8877 alarm_pending = FALSE;
8878 ret = sigemptyset(&sigs);
8879 ret = ret == 0 ? sigaddset(&sigs, SIGALRM) : ret;
8880 ret = ret == 0 ? sigprocmask(SIG_BLOCK, &sigs, &saved_sigs) : ret;
8881 timeout_flag = FALSE;
8882 ret = ret == 0 ? sigpending(&sigs) : ret;
8883 if (ret == 0)
8884 {
8885 alarm_pending = sigismember(&sigs, SIGALRM);
Bram Moolenaar1f89abf2022-06-06 10:07:01 +01008886 ret = sigprocmask(SIG_SETMASK, &saved_sigs, NULL);
Paul Ollis65745772022-06-05 16:55:54 +01008887 }
8888 if (unlikely(ret != 0 || alarm_pending < 0))
8889 {
8890 // Just catching coding errors. Write an error message, but carry on.
8891 semsg(_(e_could_not_check_for_pending_sigalrm_str), strerror(errno));
8892 alarm_pending = FALSE;
8893 }
8894
8895 // Set up the alarm handler first.
8896 ret = sigemptyset(&handle_alarm.sa_mask);
8897 handle_alarm.sa_handler = set_flag;
8898 handle_alarm.sa_flags = 0;
8899 ret = ret == 0 ? sigaction(SIGALRM, &handle_alarm, &prev_sigaction) : ret;
8900 if (ret < 0)
8901 {
8902 // Should only get here as a result of coding errors.
8903 semsg(_(e_could_not_set_handler_for_timeout_str), strerror(errno));
8904 return &timeout_flag;
8905 }
8906 timer_handler_active = TRUE;
8907
8908 // Set up the interval timer once the alarm handler is in place.
Bram Moolenaar155f2d12022-06-20 13:38:33 +01008909 ret = setitimer(ITIMER_REAL, &interval, NULL);
Paul Ollis65745772022-06-05 16:55:54 +01008910 if (ret < 0)
8911 {
8912 // Should only get here as a result of coding errors.
8913 semsg(_(e_could_not_set_timeout_str), strerror(errno));
8914 stop_timeout();
8915 return &timeout_flag;
8916 }
8917
8918 timer_active = TRUE;
8919 return &timeout_flag;
8920}
Bram Moolenaar08210f82023-04-13 19:15:54 +01008921# endif // PROF_NSEC
Paul Ollis65745772022-06-05 16:55:54 +01008922#endif // FEAT_RELTIME
Foxe Chenb90c2392025-06-27 21:10:35 +02008923
8924/*
8925 * Create an anonymous/temporary file/object and return its file descriptor.
8926 * Returns -1 on error.
8927 */
8928 int
8929mch_create_anon_file(void)
8930{
8931 int fd = -1;
8932#ifdef HAVE_SHM_OPEN
8933 const char template[] = "/vimXXXXXX";
8934
8935 for (int i = 0; i < 100; i++)
8936 {
8937 mch_get_random((char_u*)template + 4, 6);
8938
8939 errno = 0;
8940 fd = shm_open(template, O_CREAT | O_RDWR | O_EXCL, 0600);
8941
8942 if (fd >= 0 || errno != EEXIST)
8943 break; }
8944 // Remove object name from namespace
8945 shm_unlink(template);
8946#endif
8947 if (fd == -1)
8948 // Last resort
8949 fd = fileno(tmpfile());
8950
8951 return fd;
8952}