robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

robinmerge: 1dc9728daa1d8a2702

master
121.4 KiB3945 linesraw
1// fileio.c: read from and write to a file
2
3#include <assert.h>
4#include <errno.h>
5#include <fcntl.h>
6#include <iconv.h>
7#include <inttypes.h>
8#include <limits.h>
9#include <stdbool.h>
10#include <stddef.h>
11#include <stdio.h>
12#include <string.h>
13#include <sys/stat.h>
14#include <sys/types.h>
15#include <time.h>
16#include <uv.h>
17
18#include "auto/config.h"
19#include "nvim/ascii_defs.h"
20#include "nvim/autocmd.h"
21#include "nvim/autocmd_defs.h"
22#include "nvim/buffer.h"
23#include "nvim/buffer_defs.h"
24#include "nvim/buffer_updates.h"
25#include "nvim/change.h"
26#include "nvim/context.h"
27#include "nvim/cursor.h"
28#include "nvim/dialog.h"
29#include "nvim/diff.h"
30#include "nvim/drawscreen.h"
31#include "nvim/errors.h"
32#include "nvim/eval.h"
33#include "nvim/eval/vars.h"
34#include "nvim/ex_cmds_defs.h"
35#include "nvim/ex_eval.h"
36#include "nvim/fileio.h"
37#include "nvim/fold.h"
38#include "nvim/garray.h"
39#include "nvim/garray_defs.h"
40#include "nvim/gettext_defs.h"
41#include "nvim/globals.h"
42#include "nvim/highlight_defs.h"
43#include "nvim/iconv_defs.h"
44#include "nvim/input.h"
45#include "nvim/insert.h"
46#include "nvim/log.h"
47#include "nvim/macros_defs.h"
48#include "nvim/mbyte.h"
49#include "nvim/mbyte_defs.h"
50#include "nvim/mcursor.h"
51#include "nvim/memfile.h"
52#include "nvim/memfile_defs.h"
53#include "nvim/memline.h"
54#include "nvim/memline_defs.h"
55#include "nvim/memory.h"
56#include "nvim/message.h"
57#include "nvim/move.h"
58#include "nvim/option.h"
59#include "nvim/option_defs.h"
60#include "nvim/option_vars.h"
61#include "nvim/os/fs.h"
62#include "nvim/os/fs_defs.h"
63#include "nvim/os/input.h"
64#include "nvim/os/os.h"
65#include "nvim/os/os_defs.h"
66#include "nvim/os/time.h"
67#include "nvim/path.h"
68#include "nvim/pos_defs.h"
69#include "nvim/regexp.h"
70#include "nvim/regexp_defs.h"
71#include "nvim/sha256.h"
72#include "nvim/shada.h"
73#include "nvim/state_defs.h"
74#include "nvim/strings.h"
75#include "nvim/types_defs.h"
76#include "nvim/ui.h"
77#include "nvim/undo.h"
78#include "nvim/undo_defs.h"
79#include "nvim/vim_defs.h"
80
81#ifdef BACKSLASH_IN_FILENAME
82# include "nvim/charset.h"
83#endif
84
85#ifdef HAVE_DIRFD_AND_FLOCK
86# include <dirent.h>
87# include <sys/file.h>
88#endif
89
90#ifdef MSWIN
91# include "nvim/os/os_win_console.h"
92#endif
93
94#ifdef OPEN_CHR_FILES
95# include "nvim/charset.h"
96#endif
97
98// For compatibility with libuv < 1.20.0 (tested on 1.18.0)
99#ifndef UV_FS_COPYFILE_FICLONE
100# define UV_FS_COPYFILE_FICLONE 0
101#endif
102
103#include "fileio.c.generated.h"
104
105static const char *e_auchangedbuf = N_("E812: Autocommands changed buffer or buffer name");
106
107// Bitmask with 0x80 set in each byte of a uint64_t word, used to detect
108// non-ASCII bytes (high bit set) in multiple bytes at once.
109#define NONASCII_MASK (((uint64_t)(-1) / 0xFF) * 0x80)
110
111/// Shows a message about file `name`, e.g. `"foo.txt" [New]`.
112///
113/// @param s Info appended to the filename, e.g. "[New]".
114/// @param msg_id Emit as a progress-message with this id, or NULL for a plain message.
115///               Caller must emit a non-"running" status for `msg_id`, later.
116static void filemess(buf_T *buf, char *name, char *s, const char *msg_id)
117{
118  int prev_msg_col = msg_col;
119
120  if (msg_silent != 0) {
121    return;
122  }
123
124  add_quoted_fname(IObuff, IOSIZE - 100, buf, name);
125
126  // Avoid an over-long translation to cause trouble.
127  xstrlcat(IObuff, s, IOSIZE);
128
129  // For the first message may have to start a new line.
130  // For further ones overwrite the previous one, reset msg_scroll before
131  // calling filemess().
132  int msg_scroll_save = msg_scroll;
133  if (shortmess(kShmOverall) && !msg_listdo_overwrite && !exiting && p_verbose == 0) {
134    msg_scroll = false;
135  }
136  if (!msg_scroll) {    // wait a bit when overwriting an error msg
137    msg_check_for_delay(false);
138  }
139  msg_start();
140  if (prev_msg_col != 0 && msg_col == 0) {
141    msg_putchar('\r');  // overwrite any previous message.
142  }
143  msg_scroll = msg_scroll_save;
144  msg_scrolled_ign = true;
145  // may truncate the message to avoid a hit-return prompt
146  if (msg_id != NULL) {
147    msg_progress(IObuff, (char *)msg_id, "running", 0, false, true, false);
148  } else {
149    msg_outtrans(msg_may_trunc(false, IObuff), 0, false);
150  }
151  msg_clr_eos();
152  msg_scrolled_ign = false;
153}
154
155/// Shows the "busy" message for writing file `name`, as a progress-message. #39280
156/// Caller must end the progress by emitting a non-"running" status to the same `msg_id`.
157void filemess_progress(buf_T *buf, char *name, const char *msg_id)
158{
159  filemess(buf, name, "", msg_id);
160}
161
162/// Read lines from file "fname" into the buffer after line "from".
163///
164/// 1. We allocate blocks with try_malloc, as big as possible.
165/// 2. Each block is filled with characters from the file with a single read().
166/// 3. The lines are inserted in the buffer with ml_append().
167///
168/// (caller must check that fname != NULL, unless READ_STDIN is used)
169///
170/// "lines_to_skip" is the number of lines that must be skipped
171/// "lines_to_read" is the number of lines that are appended
172/// When not recovering lines_to_skip is 0 and lines_to_read MAXLNUM.
173///
174/// flags:
175/// READ_NEW     starting to edit a new buffer
176/// READ_FILTER  reading filter output
177/// READ_STDIN   read from stdin instead of a file
178/// READ_BUFFER  read from curbuf instead of a file (converting after reading
179///              stdin)
180/// READ_NOFILE  do not read a file, only trigger BufReadCmd
181/// READ_DUMMY   read into a dummy buffer (to check if file contents changed)
182/// READ_KEEP_UNDO  don't clear undo info or read it from a file
183/// READ_FIFO    read from fifo/socket instead of a file
184///
185/// @param eap  can be NULL!
186///
187/// @return     FAIL for failure, NOTDONE for directory (failure), or OK
188int readfile(char *fname, char *sfname, linenr_T from, linenr_T lines_to_skip,
189             linenr_T lines_to_read, exarg_T *eap, int flags, bool silent)
190{
191  int retval = FAIL;  // jump to "theend" instead of returning
192  int fd = stdin_fd >= 0 ? stdin_fd : 0;
193  bool newfile = (flags & READ_NEW);
194  bool filtering = (flags & READ_FILTER);
195  bool read_stdin = (flags & READ_STDIN);
196  bool read_buffer = (flags & READ_BUFFER);
197  bool read_fifo = (flags & READ_FIFO);
198  bool set_options = newfile || read_buffer || (eap != NULL && eap->read_edit);
199  linenr_T read_buf_lnum = 1;           // next line to read from curbuf
200  colnr_T read_buf_col = 0;             // next char to read from this line
201  char c;
202  linenr_T lnum = from;
203  char *ptr = NULL;              // pointer into read buffer
204  char *buffer = NULL;           // read buffer
205  char *new_buffer = NULL;       // init to shut up gcc
206  char *line_start = NULL;       // init to shut up gcc
207  int wasempty;                         // buffer was empty before reading
208  colnr_T len;
209  ptrdiff_t size = 0;
210  uint8_t *p = NULL;
211  off_T filesize = 0;
212  bool skip_read = false;
213  context_sha256_T sha_ctx;
214  bool read_undo_file = false;
215  int split = 0;  // number of split lines
216  linenr_T linecnt;
217  bool error = false;                   // errors encountered
218  int ff_error = EOL_UNKNOWN;           // file format with errors
219  ptrdiff_t linerest = 0;               // remaining chars in line
220  int perm = 0;
221#ifdef UNIX
222  int swap_mode = -1;                   // protection bits for swap file
223#endif
224  int fileformat = 0;                   // end-of-line format
225  bool keep_fileformat = false;
226  FileInfo file_info;
227  linenr_T skip_count = 0;
228  linenr_T read_count = 0;
229  int msg_save = msg_scroll;
230  linenr_T read_no_eol_lnum = 0;        // non-zero lnum when last line of
231                                        // last read was missing the eol
232  bool file_rewind = false;
233  linenr_T conv_error = 0;              // line nr with conversion error
234  linenr_T illegal_byte = 0;            // line nr with illegal byte
235  bool keep_dest_enc = false;           // don't retry when char doesn't fit
236                                        // in destination encoding
237  int bad_char_behavior = BAD_REPLACE;
238  // BAD_KEEP, BAD_DROP or character to
239  // replace with
240  char *tmpname = NULL;          // name of 'charconvert' output file
241  int fio_flags = 0;
242  char *fenc;                    // fileencoding to use
243  bool fenc_alloced;                    // fenc_next is in allocated memory
244  char *fenc_next = NULL;        // next item in 'fencs' or NULL
245  bool advance_fenc = false;
246  int real_size = 0;
247  iconv_t iconv_fd = (iconv_t)-1;       // descriptor for iconv() or -1
248  bool did_iconv = false;               // true when iconv() failed and trying
249                                        // 'charconvert' next
250  bool converted = false;                // true if conversion done
251  bool notconverted = false;             // true if conversion wanted but it wasn't possible
252  char conv_rest[CONV_RESTLEN];
253  int conv_restlen = 0;                 // nr of bytes in conv_rest[]
254  pos_T orig_start;
255  buf_T *old_curbuf;
256  char *old_b_ffname;
257  char *old_b_fname;
258  int using_b_ffname;
259  int using_b_fname;
260  static char *msg_is_a_directory = N_("is a directory");
261
262  curbuf->b_au_did_filetype = false;  // reset before triggering any autocommands
263
264  curbuf->b_no_eol_lnum = 0;    // in case it was set by the previous read
265
266  // If there is no file name yet, use the one for the read file.
267  // BF_NOTEDITED is set to reflect this.
268  // Don't do this for a read from a filter.
269  // Only do this when 'cpoptions' contains the 'f' flag.
270  if (curbuf->b_ffname == NULL
271      && !filtering
272      && fname != NULL
273      && vim_strchr(p_cpo, kCpoFnamer) != NULL
274      && !(flags & READ_DUMMY)) {
275    if (set_rw_fname(fname, sfname) == FAIL) {
276      goto theend;
277    }
278  }
279
280  // Remember the initial values of curbuf, curbuf->b_ffname and
281  // curbuf->b_fname to detect whether they are altered as a result of
282  // executing nasty autocommands.  Also check if "fname" and "sfname"
283  // point to one of these values.
284  old_curbuf = curbuf;
285  old_b_ffname = curbuf->b_ffname;
286  old_b_fname = curbuf->b_fname;
287  using_b_ffname = (fname == curbuf->b_ffname) || (sfname == curbuf->b_ffname);
288  using_b_fname = (fname == curbuf->b_fname) || (sfname == curbuf->b_fname);
289
290  // don't display the file info for another buffer now
291  need_fileinfo = false;
292
293  // For Unix: Use the short file name whenever possible.
294  // Avoids problems with networks and when directory names are changed.
295  // Don't do this for Windows, a "cd" in a sub-shell may have moved us to
296  // another directory, which we don't detect.
297  if (sfname == NULL) {
298    sfname = fname;
299  }
300#ifdef UNIX
301  fname = sfname;
302#endif
303
304  // The BufReadCmd and FileReadCmd events intercept the reading process by
305  // executing the associated commands instead.
306  if (!filtering && !read_stdin && !read_buffer) {
307    orig_start = curbuf->b_op_start;
308
309    // Set '[ mark to the line above where the lines go (line 1 if zero).
310    curbuf->b_op_start.lnum = ((from == 0) ? 1 : from);
311    curbuf->b_op_start.col = 0;
312
313    if (newfile) {
314      if (apply_autocmds_exarg(EVENT_BUFREADCMD, NULL, sfname,
315                               false, curbuf, eap)) {
316        retval = OK;
317        if (aborting()) {
318          retval = FAIL;
319        }
320
321        // The BufReadCmd code usually uses ":read" to get the text and
322        // perhaps ":file" to change the buffer name. But we should
323        // consider this to work like ":edit", thus reset the
324        // BF_NOTEDITED flag.  Then ":write" will work to overwrite the
325        // same file.
326        if (retval == OK && !curbuf->b_au_did_filetype && *curbuf->b_p_ft != NUL) {
327          apply_autocmds(EVENT_FILETYPE, curbuf->b_p_ft, curbuf->b_fname, true, curbuf);
328          if (aborting()) {
329            retval = FAIL;
330          }
331        }
332        if (retval == OK) {
333          curbuf->b_flags &= ~BF_NOTEDITED;
334        }
335        goto theend;
336      }
337    } else if (apply_autocmds_exarg(EVENT_FILEREADCMD, sfname, sfname,
338                                    false, NULL, eap)) {
339      retval = aborting() ? FAIL : OK;
340      goto theend;
341    }
342
343    curbuf->b_op_start = orig_start;
344
345    if (flags & READ_NOFILE) {
346      // Return NOTDONE instead of FAIL so that BufEnter can be triggered
347      // and other operations don't fail.
348      retval = NOTDONE;
349      goto theend;
350    }
351  }
352
353  if (((shortmess(kShmOver) && !msg_listdo_overwrite) || curbuf->b_help) && p_verbose == 0) {
354    msg_scroll = false;         // overwrite previous file message
355  } else {
356    msg_scroll = true;          // don't overwrite previous file message
357  }
358  // If the name is too long we might crash further on, quit here.
359  if (fname != NULL && *fname != NUL) {
360    size_t fnamelen = strlen(fname);
361
362    // If the name is too long we might crash further on, quit here.
363    if (fnamelen >= MAXPATHL) {
364      filemess(curbuf, fname, _("Illegal file name"), NULL);
365      msg_end();
366      msg_scroll = msg_save;
367      goto theend;
368    }
369
370    // If the name ends in a path separator, we can't open it.  Check here,
371    // because reading the file may actually work, but then creating the
372    // swap file may destroy it!  Reported on MS-DOS and Win 95.
373    if (after_pathsep(fname, fname + fnamelen)) {
374      if (!silent) {
375        filemess(curbuf, fname, _(msg_is_a_directory), NULL);
376      }
377      msg_end();
378      msg_scroll = msg_save;
379      retval = NOTDONE;
380      goto theend;
381    }
382  }
383
384  if (!read_stdin && fname != NULL) {
385    perm = os_getperm(fname);
386  }
387
388#ifdef OPEN_CHR_FILES
389# define IS_CHR_DEV(perm, fname) S_ISCHR(perm) && is_dev_fd_file(fname)
390#else
391# define IS_CHR_DEV(perm, fname) false
392#endif
393
394  if (!read_stdin && !read_buffer && !read_fifo) {
395    if (perm >= 0 && !S_ISREG(perm)                 // not a regular file ...
396        && !S_ISFIFO(perm)                          // ... or fifo
397        && !S_ISSOCK(perm)                          // ... or socket
398        && !(IS_CHR_DEV(perm, fname))
399        // ... or a character special file named /dev/fd/<n>
400        ) {
401      // On Unix it is possible to read a directory, so we have to
402      // check for it before os_open().
403      if (S_ISDIR(perm)) {
404        if (!silent) {
405          filemess(curbuf, fname, _(msg_is_a_directory), NULL);
406        }
407        retval = NOTDONE;
408      } else {
409        filemess(curbuf, fname, _("is not a file"), NULL);
410      }
411      msg_end();
412      msg_scroll = msg_save;
413      goto theend;
414    }
415  }
416
417  // Set default or forced 'fileformat' and 'binary'.
418  set_file_options(set_options, eap);
419
420  // When opening a new file we take the readonly flag from the file.
421  // Default is r/w, can be set to r/o below.
422  // Don't reset it when in readonly mode
423  // Only set/reset b_p_ro when BF_CHECK_RO is set.
424  bool check_readonly = (newfile && (curbuf->b_flags & BF_CHECK_RO));
425  if (check_readonly && !readonlymode) {
426    curbuf->b_p_ro = false;
427  }
428
429  if (newfile && !read_stdin && !read_buffer && !read_fifo) {
430    // Remember time of file.
431    if (os_fileinfo(fname, &file_info)) {
432      buf_store_file_info(curbuf, &file_info);
433      curbuf->b_mtime_read = curbuf->b_mtime;
434      curbuf->b_mtime_read_ns = curbuf->b_mtime_ns;
435#ifdef UNIX
436      // Use the protection bits of the original file for the swap file.
437      // This makes it possible for others to read the name of the
438      // edited file from the swapfile, but only if they can read the
439      // edited file.
440      // Remove the "write" and "execute" bits for group and others
441      // (they must not write the swapfile).
442      // Add the "read" and "write" bits for the user, otherwise we may
443      // not be able to write to the file ourselves.
444      // Setting the bits is done below, after creating the swap file.
445      swap_mode = ((int)file_info.stat.st_mode & 0644) | 0600;
446#endif
447    } else {
448      curbuf->b_mtime = 0;
449      curbuf->b_mtime_ns = 0;
450      curbuf->b_mtime_read = 0;
451      curbuf->b_mtime_read_ns = 0;
452      curbuf->b_orig_size = 0;
453      curbuf->b_orig_mode = 0;
454    }
455
456    // Reset the "new file" flag.  It will be set again below when the
457    // file doesn't exist.
458    curbuf->b_flags &= ~(BF_NEW | BF_NEW_W);
459  }
460
461  // Check readonly.
462  bool file_readonly = false;
463  if (!read_buffer && !read_stdin) {
464    if (!newfile || readonlymode || !(perm & 0222)
465        || !os_file_is_writable(fname)) {
466      file_readonly = true;
467    }
468    fd = os_open(fname, O_RDONLY, 0);
469  }
470
471  if (fd < 0) {                     // cannot open at all
472    msg_scroll = msg_save;
473    if (!newfile) {
474      goto theend;
475    }
476    if (perm == UV_ENOENT) {  // check if the file exists
477      // Set the 'new-file' flag, so that when the file has
478      // been created by someone else, a ":w" will complain.
479      curbuf->b_flags |= BF_NEW;
480
481      // Create a swap file now, so that other Vims are warned
482      // that we are editing this file.  Don't do this for a
483      // "nofile" or "nowrite" buffer type.
484      if (!bt_dontwrite(curbuf)) {
485        check_need_swap(newfile);
486        // SwapExists autocommand may mess things up
487        if (curbuf != old_curbuf
488            || (using_b_ffname
489                && (old_b_ffname != curbuf->b_ffname))
490            || (using_b_fname
491                && (old_b_fname != curbuf->b_fname))) {
492          emsg(_(e_auchangedbuf));
493          goto theend;
494        }
495      }
496      if (!silent) {
497        if (dir_of_file_exists(fname)) {
498          filemess(curbuf, sfname, _("[New]"), NULL);
499        } else {
500          filemess(curbuf, sfname, _("[New DIRECTORY]"), NULL);
501        }
502      }
503      // Even though this is a new file, it might have been
504      // edited before and deleted.  Get the old marks.
505      check_marks_read();
506      // Set forced 'fileencoding'.
507      if (eap != NULL) {
508        set_forced_fenc(eap);
509      }
510      apply_autocmds_exarg(EVENT_BUFNEWFILE, sfname, sfname,
511                           false, curbuf, eap);
512      // remember the current fileformat
513      save_file_ff(curbuf);
514
515      if (!aborting()) {  // autocmds may abort script processing
516        retval = OK;      // a new file is not an error
517      }
518      goto theend;
519    }
520#if defined(UNIX) && defined(EOVERFLOW)
521    filemess(curbuf, sfname,
522             ((fd == UV_EFBIG)
523              ? _("[File too big]")
524              // libuv only returns -errno in Unix; Windows open() does not set EOVERFLOW.
525              : (fd == -EOVERFLOW) ? _("[File too big]") : _("[Permission Denied]")),
526             NULL);
527#else
528    filemess(curbuf, sfname, ((fd == UV_EFBIG) ? _("[File too big]") : _("[Permission Denied]")),
529             NULL);
530#endif
531    curbuf->b_p_ro = true;                  // must use "w!" now
532
533    goto theend;
534  }
535
536  // Only set the 'ro' flag for readonly files the first time they are
537  // loaded.    Help files always get readonly mode
538  if ((check_readonly && file_readonly) || curbuf->b_help) {
539    curbuf->b_p_ro = true;
540  }
541
542  if (set_options) {
543    // Don't change 'eol' if reading from buffer as it will already be
544    // correctly set when reading stdin.
545    if (!read_buffer) {
546      curbuf->b_p_eof = false;
547      curbuf->b_start_eof = false;
548      curbuf->b_p_eol = true;
549      curbuf->b_start_eol = true;
550    }
551    curbuf->b_p_bomb = false;
552    curbuf->b_start_bomb = false;
553  }
554
555  // Create a swap file now, so that other Vims are warned that we are
556  // editing this file.
557  // Don't do this for a "nofile" or "nowrite" buffer type.
558  if (!bt_dontwrite(curbuf)) {
559    check_need_swap(newfile);
560    if (!read_stdin
561        && (curbuf != old_curbuf
562            || (using_b_ffname && (old_b_ffname != curbuf->b_ffname))
563            || (using_b_fname && (old_b_fname != curbuf->b_fname)))) {
564      emsg(_(e_auchangedbuf));
565      if (!read_buffer) {
566        close(fd);
567      }
568      goto theend;
569    }
570#ifdef UNIX
571    // Set swap file protection bits after creating it.
572    if (swap_mode > 0 && curbuf->b_ml.ml_mfp != NULL
573        && curbuf->b_ml.ml_mfp->mf_fname != NULL) {
574      const char *swap_fname = curbuf->b_ml.ml_mfp->mf_fname;
575
576      // If the group-read bit is set but not the world-read bit, then
577      // the group must be equal to the group of the original file.  If
578      // we can't make that happen then reset the group-read bit.  This
579      // avoids making the swap file readable to more users when the
580      // primary group of the user is too permissive.
581      if ((swap_mode & 044) == 040) {
582        FileInfo swap_info;
583
584        if (os_fileinfo(swap_fname, &swap_info)
585            && file_info.stat.st_gid != swap_info.stat.st_gid
586            && os_fchown(curbuf->b_ml.ml_mfp->mf_fd, (uv_uid_t)(-1),
587                         (uv_gid_t)file_info.stat.st_gid)
588            == -1) {
589          swap_mode &= 0600;
590        }
591      }
592
593      os_setperm(swap_fname, swap_mode);
594    }
595#endif
596  }
597
598  // If "Quit" selected at ATTENTION dialog, don't load the file.
599  if (swap_exists_action == SEA_QUIT) {
600    if (!read_buffer && !read_stdin) {
601      close(fd);
602    }
603    goto theend;
604  }
605
606  no_wait_return++;         // don't wait for return yet
607
608  // Set '[ mark to the line above where the lines go (line 1 if zero).
609  orig_start = curbuf->b_op_start;
610  curbuf->b_op_start.lnum = ((from == 0) ? 1 : from);
611  curbuf->b_op_start.col = 0;
612
613  int try_mac = (vim_strchr(p_ffs, 'm') != NULL);
614  int try_dos = (vim_strchr(p_ffs, 'd') != NULL);
615  int try_unix = (vim_strchr(p_ffs, 'x') != NULL);
616
617  if (!read_buffer) {
618    int m = msg_scroll;
619    int n = msg_scrolled;
620
621    // The file must be closed again, the autocommands may want to change
622    // the file before reading it.
623    if (!read_stdin) {
624      close(fd);                // ignore errors
625    }
626
627    // The output from the autocommands should not overwrite anything and
628    // should not be overwritten: Set msg_scroll, restore its value if no
629    // output was done.
630    msg_scroll = true;
631    if (filtering) {
632      apply_autocmds_exarg(EVENT_FILTERREADPRE, NULL, sfname,
633                           false, curbuf, eap);
634    } else if (read_stdin) {
635      apply_autocmds_exarg(EVENT_STDINREADPRE, NULL, sfname,
636                           false, curbuf, eap);
637    } else if (newfile) {
638      apply_autocmds_exarg(EVENT_BUFREADPRE, NULL, sfname,
639                           false, curbuf, eap);
640    } else {
641      apply_autocmds_exarg(EVENT_FILEREADPRE, sfname, sfname,
642                           false, NULL, eap);
643    }
644
645    // autocommands may have changed it
646    try_mac = (vim_strchr(p_ffs, 'm') != NULL);
647    try_dos = (vim_strchr(p_ffs, 'd') != NULL);
648    try_unix = (vim_strchr(p_ffs, 'x') != NULL);
649    curbuf->b_op_start = orig_start;
650
651    if (msg_scrolled == n) {
652      msg_scroll = m;
653    }
654
655    if (aborting()) {       // autocmds may abort script processing
656      no_wait_return--;
657      msg_scroll = msg_save;
658      curbuf->b_p_ro = true;            // must use "w!" now
659      goto theend;
660    }
661    // Don't allow the autocommands to change the current buffer.
662    // Try to re-open the file.
663    //
664    // Don't allow the autocommands to change the buffer name either
665    // (cd for example) if it invalidates fname or sfname.
666    if (!read_stdin && (curbuf != old_curbuf
667                        || (using_b_ffname && (old_b_ffname != curbuf->b_ffname))
668                        || (using_b_fname && (old_b_fname != curbuf->b_fname))
669                        || (fd = os_open(fname, O_RDONLY, 0)) < 0)) {
670      no_wait_return--;
671      msg_scroll = msg_save;
672      if (fd < 0) {
673        emsg(_("E200: *ReadPre autocommands made the file unreadable"));
674      } else {
675        emsg(_("E201: *ReadPre autocommands must not change current buffer"));
676      }
677      curbuf->b_p_ro = true;            // must use "w!" now
678      goto theend;
679    }
680  }
681
682  // Autocommands may add lines to the file, need to check if it is empty
683  wasempty = (curbuf->b_ml.ml_flags & ML_EMPTY);
684
685  if (!recoverymode && !filtering && !(flags & READ_DUMMY) && !silent) {
686    if (!read_stdin && !read_buffer) {
687      filemess(curbuf, sfname, "", NULL);
688    }
689  }
690
691  msg_scroll = false;                   // overwrite the file message
692
693  // Set linecnt now, before the "retry" caused by a wrong guess for
694  // fileformat, and after the autocommands, which may change them.
695  linecnt = curbuf->b_ml.ml_line_count;
696
697  // "++bad=" argument.
698  if (eap != NULL && eap->bad_char != 0) {
699    bad_char_behavior = eap->bad_char;
700    if (set_options) {
701      curbuf->b_bad_char = eap->bad_char;
702    }
703  } else {
704    curbuf->b_bad_char = 0;
705  }
706
707  // Decide which 'encoding' to use or use first.
708  if (eap != NULL && eap->force_enc != 0) {
709    fenc = enc_canonize(eap->cmd + eap->force_enc);
710    fenc_alloced = true;
711    keep_dest_enc = true;
712  } else if (curbuf->b_p_bin) {
713    fenc = "";                // binary: don't convert
714    fenc_alloced = false;
715  } else if (curbuf->b_help) {
716    // Help files are either utf-8 or latin1.  Try utf-8 first, if this
717    // fails it must be latin1.
718    // It is needed when the first line contains non-ASCII characters.
719    // That is only in *.??x files.
720    fenc_next = "latin1";
721    fenc = "utf-8";
722
723    fenc_alloced = false;
724  } else if (*p_fencs == NUL) {
725    fenc = curbuf->b_p_fenc;            // use format from buffer
726    fenc_alloced = false;
727  } else {
728    fenc_next = p_fencs;                // try items in 'fileencodings'
729    fenc = next_fenc(&fenc_next, &fenc_alloced);
730  }
731
732  // Jump back here to retry reading the file in different ways.
733  // Reasons to retry:
734  // - encoding conversion failed: try another one from "fenc_next"
735  // - BOM detected and fenc was set, need to setup conversion
736  // - "fileformat" check failed: try another
737  //
738  // Variables set for special retry actions:
739  // "file_rewind"      Rewind the file to start reading it again.
740  // "advance_fenc"     Advance "fenc" using "fenc_next".
741  // "skip_read"        Re-use already read bytes (BOM detected).
742  // "did_iconv"        iconv() conversion failed, try 'charconvert'.
743  // "keep_fileformat" Don't reset "fileformat".
744  //
745  // Other status indicators:
746  // "tmpname"  When != NULL did conversion with 'charconvert'.
747  //                    Output file has to be deleted afterwards.
748  // "iconv_fd" When != -1 did conversion with iconv().
749retry:
750
751  if (file_rewind) {
752    if (read_buffer) {
753      read_buf_lnum = 1;
754      read_buf_col = 0;
755    } else if (read_stdin || vim_lseek(fd, 0, SEEK_SET) != 0) {
756      // Can't rewind the file, give up.
757      error = true;
758      goto failed;
759    }
760    // Delete the previously read lines.
761    while (lnum > from) {
762      ml_delete(lnum--);
763    }
764    file_rewind = false;
765    if (set_options) {
766      curbuf->b_p_bomb = false;
767      curbuf->b_start_bomb = false;
768    }
769    conv_error = 0;
770  }
771
772  // When retrying with another "fenc" and the first time "fileformat"
773  // will be reset.
774  if (keep_fileformat) {
775    keep_fileformat = false;
776  } else {
777    if (eap != NULL && eap->force_ff != 0) {
778      fileformat = get_fileformat_force(curbuf, eap);
779      try_unix = try_dos = try_mac = false;
780    } else if (curbuf->b_p_bin) {
781      fileformat = EOL_UNIX;                    // binary: use Unix format
782    } else if (*p_ffs ==
783               NUL) {
784      fileformat = get_fileformat(curbuf);      // use format from buffer
785    } else {
786      fileformat = EOL_UNKNOWN;                 // detect from file
787    }
788  }
789
790  if (iconv_fd != (iconv_t)-1) {
791    // aborted conversion with iconv(), close the descriptor
792    iconv_close(iconv_fd);
793    iconv_fd = (iconv_t)-1;
794  }
795
796  if (advance_fenc) {
797    // Try the next entry in 'fileencodings'.
798    advance_fenc = false;
799
800    if (eap != NULL && eap->force_enc != 0) {
801      // Conversion given with "++cc=" wasn't possible, read
802      // without conversion.
803      notconverted = true;
804      conv_error = 0;
805      if (fenc_alloced) {
806        xfree(fenc);
807      }
808      fenc = "";
809      fenc_alloced = false;
810    } else {
811      if (fenc_alloced) {
812        xfree(fenc);
813      }
814      if (fenc_next != NULL) {
815        fenc = next_fenc(&fenc_next, &fenc_alloced);
816      } else {
817        fenc = "";
818        fenc_alloced = false;
819      }
820    }
821    if (tmpname != NULL) {
822      os_remove(tmpname);  // delete converted file
823      XFREE_CLEAR(tmpname);
824    }
825  }
826
827  // Conversion may be required when the encoding of the file is different
828  // from 'encoding' or 'encoding' is UTF-16, UCS-2 or UCS-4.
829  fio_flags = 0;
830  converted = need_conversion(fenc);
831  if (converted) {
832    // "ucs-bom" means we need to check the first bytes of the file
833    // for a BOM.
834    if (strcmp(fenc, ENC_UCSBOM) == 0) {
835      fio_flags = FIO_UCSBOM;
836    } else {
837      // Check if UCS-2/4 or Latin1 to UTF-8 conversion needs to be
838      // done.  This is handled below after read().  Prepare the
839      // fio_flags to avoid having to parse the string each time.
840      // Also check for Unicode to Latin1 conversion, because iconv()
841      // appears not to handle this correctly.  This works just like
842      // conversion to UTF-8 except how the resulting character is put in
843      // the buffer.
844      fio_flags = get_fio_flags(fenc);
845    }
846
847    // Try using iconv() if we can't convert internally.
848    if (fio_flags == 0
849        && !did_iconv) {
850      iconv_fd = (iconv_t)my_iconv_open("utf-8", fenc);
851    }
852
853    // Use the 'charconvert' expression when conversion is required
854    // and we can't do it internally or with iconv().
855    if (fio_flags == 0 && !read_stdin && !read_buffer && p_ccv.type != kCallbackNone
856        && !read_fifo && iconv_fd == (iconv_t)-1) {
857      did_iconv = false;
858      // Skip conversion when it's already done (retry for wrong
859      // "fileformat").
860      if (tmpname == NULL) {
861        tmpname = readfile_charconvert(fname, fenc, &fd);
862        if (tmpname == NULL) {
863          // Conversion failed.  Try another one.
864          advance_fenc = true;
865          if (fd < 0) {
866            // Re-opening the original file failed!
867            emsg(_("E202: Conversion made file unreadable!"));
868            error = true;
869            goto failed;
870          }
871          goto retry;
872        }
873      }
874    } else {
875      if (fio_flags == 0 && iconv_fd == (iconv_t)-1) {
876        // Conversion wanted but we can't.
877        // Try the next conversion in 'fileencodings'
878        advance_fenc = true;
879        goto retry;
880      }
881    }
882  }
883
884  // Set "can_retry" when it's possible to rewind the file and try with
885  // another "fenc" value.  It's false when no other "fenc" to try, reading
886  // stdin or fixed at a specific encoding.
887  bool can_retry = (*fenc != NUL && !read_stdin && !keep_dest_enc && !read_fifo);
888
889  if (!skip_read) {
890    linerest = 0;
891    filesize = 0;
892    skip_count = lines_to_skip;
893    read_count = lines_to_read;
894    conv_restlen = 0;
895    read_undo_file = (newfile && (flags & READ_KEEP_UNDO) == 0
896                      && curbuf->b_ffname != NULL
897                      && curbuf->b_p_udf
898                      && !filtering
899                      && !read_fifo
900                      && !read_stdin
901                      && !read_buffer);
902    if (read_undo_file) {
903      sha256_start(&sha_ctx);
904    }
905  }
906
907  while (!error && !got_int) {
908    // We allocate as much space for the file as we can get, plus
909    // space for the old line plus room for one terminating NUL.
910    // The amount is limited by the fact that read() only can read
911    // up to max_unsigned characters (and other things).
912    {
913      if (!skip_read) {
914        // Use buffer >= 64K.  Add linerest to double the size if the
915        // line gets very long, to avoid a lot of copying. But don't
916        // read more than 1 Mbyte at a time, so we can be interrupted.
917        size = MIN(0x10000 + linerest, 0x100000);
918      }
919
920      // Protect against the argument of lalloc() going negative.
921      // Also split lines that are too long for colnr_T.  After this check
922      // passes, we read up to 'size' more bytes.  We must ensure that even
923      // after that read, the line length won't exceed MAXCOL - 1 (because
924      // we add 1 for the NUL when casting to colnr_T).  If this check fires,
925      // we insert a synthetic newline immediately, so linerest doesn't grow.
926      if (size < 0 || size + linerest + 1 < 0 || linerest >= MAXCOL - size) {
927        split++;
928        *ptr = NL;  // split line by inserting a NL
929        size = 1;
930      } else if (!skip_read) {
931        for (; size >= 10; size /= 2) {
932          new_buffer = verbose_try_malloc((size_t)size + (size_t)linerest + 1);
933          if (new_buffer) {
934            break;
935          }
936        }
937        if (new_buffer == NULL) {
938          error = true;
939          break;
940        }
941        if (linerest) {         // copy characters from the previous buffer
942          memmove(new_buffer, ptr - linerest, (size_t)linerest);
943        }
944        xfree(buffer);
945        buffer = new_buffer;
946        ptr = buffer + linerest;
947        line_start = buffer;
948
949        // May need room to translate into.
950        // For iconv() we don't really know the required space, use a
951        // factor ICONV_MULT.
952        // latin1 to utf-8: 1 byte becomes up to 2 bytes
953        // utf-16 to utf-8: 2 bytes become up to 3 bytes, 4 bytes
954        // become up to 4 bytes, size must be multiple of 2
955        // ucs-2 to utf-8: 2 bytes become up to 3 bytes, size must be
956        // multiple of 2
957        // ucs-4 to utf-8: 4 bytes become up to 6 bytes, size must be
958        // multiple of 4
959        real_size = (int)size;
960        if (iconv_fd != (iconv_t)-1) {
961          size = size / ICONV_MULT;
962        } else if (fio_flags & FIO_LATIN1) {
963          size = size / 2;
964        } else if (fio_flags & (FIO_UCS2 | FIO_UTF16)) {
965          size = (size * 2 / 3) & ~1;
966        } else if (fio_flags & FIO_UCS4) {
967          size = (size * 2 / 3) & ~3;
968        } else if (fio_flags == FIO_UCSBOM) {
969          size = size / ICONV_MULT;  // worst case
970        }
971
972        if (conv_restlen > 0) {
973          // Insert unconverted bytes from previous line.
974          memmove(ptr, conv_rest, (size_t)conv_restlen);
975          ptr += conv_restlen;
976          size -= conv_restlen;
977        }
978
979        if (read_buffer) {
980          // Read bytes from curbuf.  Used for converting text read
981          // from stdin.
982          if (read_buf_lnum > from) {
983            size = 0;
984          } else {
985            int ni;
986            int tlen = 0;
987            while (true) {
988              p = (uint8_t *)ml_get(read_buf_lnum) + read_buf_col;
989              int n = ml_get_len(read_buf_lnum) - read_buf_col;
990              if (tlen + n + 1 > size) {
991                // Filled up to "size", append partial line.
992                // Change NL to NUL to reverse the effect done
993                // below.
994                n = (int)(size - tlen);
995                for (ni = 0; ni < n; ni++) {
996                  if (p[ni] == NL) {
997                    ptr[tlen++] = NUL;
998                  } else {
999                    ptr[tlen++] = (char)p[ni];
1000                  }
1001                }
1002                read_buf_col += n;
1003                break;
1004              }
1005
1006              // Append whole line and new-line.  Change NL
1007              // to NUL to reverse the effect done below.
1008              for (ni = 0; ni < n; ni++) {
1009                if (p[ni] == NL) {
1010                  ptr[tlen++] = NUL;
1011                } else {
1012                  ptr[tlen++] = (char)p[ni];
1013                }
1014              }
1015              ptr[tlen++] = NL;
1016              read_buf_col = 0;
1017              if (++read_buf_lnum > from) {
1018                // When the last line didn't have an
1019                // end-of-line don't add it now either.
1020                if (!curbuf->b_p_eol) {
1021                  tlen--;
1022                }
1023                size = tlen;
1024                break;
1025              }
1026            }
1027          }
1028        } else {
1029          // Read bytes from the file.
1030          size_t read_size = (size_t)size;
1031          size = read_eintr(fd, ptr, read_size);
1032        }
1033
1034        if (size <= 0) {
1035          if (size < 0) {                           // read error
1036            error = true;
1037          } else if (conv_restlen > 0) {
1038            // Reached end-of-file but some trailing bytes could
1039            // not be converted.  Truncated file?
1040
1041            // When we did a conversion report an error.
1042            if (fio_flags != 0 || iconv_fd != (iconv_t)-1) {
1043              if (can_retry) {
1044                goto rewind_retry;
1045              }
1046              if (conv_error == 0) {
1047                conv_error = curbuf->b_ml.ml_line_count
1048                             - linecnt + 1;
1049              }
1050            } else if (illegal_byte == 0) {
1051              // Remember the first linenr with an illegal byte
1052              illegal_byte = curbuf->b_ml.ml_line_count
1053                             - linecnt + 1;
1054            }
1055            if (bad_char_behavior == BAD_DROP) {
1056              *(ptr - conv_restlen) = NUL;
1057              conv_restlen = 0;
1058            } else {
1059              // Replace the trailing bytes with the replacement
1060              // character if we were converting; if we weren't,
1061              // leave the UTF8 checking code to do it, as it
1062              // works slightly differently.
1063              if (bad_char_behavior != BAD_KEEP && (fio_flags != 0 || iconv_fd != (iconv_t)-1)) {
1064                while (conv_restlen > 0) {
1065                  *(--ptr) = (char)bad_char_behavior;
1066                  conv_restlen--;
1067                }
1068              }
1069              fio_flags = 0;  // don't convert this
1070              if (iconv_fd != (iconv_t)-1) {
1071                iconv_close(iconv_fd);
1072                iconv_fd = (iconv_t)-1;
1073              }
1074            }
1075          }
1076        }
1077      }
1078
1079      skip_read = false;
1080
1081      // At start of file: Check for BOM.
1082      // Also check for a BOM for other Unicode encodings, but not after
1083      // converting with 'charconvert' or when a BOM has already been
1084      // found.
1085      if ((filesize == 0)
1086          && (fio_flags == FIO_UCSBOM
1087              || (!curbuf->b_p_bomb
1088                  && tmpname == NULL
1089                  && (*fenc == 'u' || *fenc == NUL)))) {
1090        char *ccname;
1091        int blen = 0;
1092
1093        // no BOM detection in a short file or in binary mode
1094        if (size < 2 || curbuf->b_p_bin) {
1095          ccname = NULL;
1096        } else {
1097          ccname = check_for_bom(ptr, (int)size, &blen,
1098                                 fio_flags == FIO_UCSBOM ? FIO_ALL : get_fio_flags(fenc));
1099        }
1100        if (ccname != NULL) {
1101          // Remove BOM from the text
1102          filesize += blen;
1103          size -= blen;
1104          memmove(ptr, ptr + blen, (size_t)size);
1105          if (set_options) {
1106            curbuf->b_p_bomb = true;
1107            curbuf->b_start_bomb = true;
1108          }
1109        }
1110
1111        if (fio_flags == FIO_UCSBOM) {
1112          if (ccname == NULL) {
1113            // No BOM detected: retry with next encoding.
1114            advance_fenc = true;
1115          } else {
1116            // BOM detected: set "fenc" and jump back
1117            if (fenc_alloced) {
1118              xfree(fenc);
1119            }
1120            fenc = ccname;
1121            fenc_alloced = false;
1122          }
1123          // retry reading without getting new bytes or rewinding
1124          skip_read = true;
1125          goto retry;
1126        }
1127      }
1128
1129      // Include not converted bytes.
1130      ptr -= conv_restlen;
1131      size += conv_restlen;
1132      conv_restlen = 0;
1133      // Break here for a read error or end-of-file.
1134      if (size <= 0) {
1135        break;
1136      }
1137
1138      if (iconv_fd != (iconv_t)-1) {
1139        // Attempt conversion of the read bytes to 'encoding' using iconv().
1140        const char *fromp = ptr;
1141        size_t from_size = (size_t)size;
1142        ptr += size;
1143        char *top = ptr;
1144        size_t to_size = (size_t)(real_size - size);
1145
1146        // If there is conversion error or not enough room try using
1147        // another conversion.  Except for when there is no
1148        // alternative (help files).
1149        while ((iconv(iconv_fd, (void *)&fromp, &from_size,
1150                      &top, &to_size)
1151                == (size_t)-1 && ICONV_ERRNO != ICONV_EINVAL)
1152               || from_size > CONV_RESTLEN) {
1153          if (can_retry) {
1154            goto rewind_retry;
1155          }
1156          if (conv_error == 0) {
1157            conv_error = readfile_linenr(linecnt, ptr, top);
1158          }
1159
1160          // Deal with a bad byte and continue with the next.
1161          fromp++;
1162          from_size--;
1163          if (bad_char_behavior == BAD_KEEP) {
1164            *top++ = *(fromp - 1);
1165            to_size--;
1166          } else if (bad_char_behavior != BAD_DROP) {
1167            *top++ = (char)bad_char_behavior;
1168            to_size--;
1169          }
1170        }
1171
1172        if (from_size > 0) {
1173          // Some remaining characters, keep them for the next
1174          // round.
1175          memmove(conv_rest, fromp, from_size);
1176          conv_restlen = (int)from_size;
1177        }
1178
1179        // move the linerest to before the converted characters
1180        line_start = ptr - linerest;
1181        memmove(line_start, buffer, (size_t)linerest);
1182        size = (top - ptr);
1183      }
1184
1185      if (fio_flags != 0) {
1186        unsigned u8c;
1187        char *tail = NULL;
1188
1189        // Convert Unicode or Latin1 to UTF-8.
1190        // Go from end to start through the buffer, because the number
1191        // of bytes may increase.
1192        // "dest" points to after where the UTF-8 bytes go, "p" points
1193        // to after the next character to convert.
1194        char *dest = ptr + real_size;
1195        if (fio_flags == FIO_LATIN1 || fio_flags == FIO_UTF8) {
1196          p = (uint8_t *)ptr + size;
1197          if (fio_flags == FIO_UTF8) {
1198            // Check for a trailing incomplete UTF-8 sequence
1199            tail = ptr + size - 1;
1200            while (tail > ptr && (*tail & 0xc0) == 0x80) {
1201              tail--;
1202            }
1203            if (tail + utf_byte2len(*tail) <= ptr + size) {
1204              tail = NULL;
1205            } else {
1206              p = (uint8_t *)tail;
1207            }
1208          }
1209        } else if (fio_flags & (FIO_UCS2 | FIO_UTF16)) {
1210          // Check for a trailing byte
1211          p = (uint8_t *)ptr + (size & ~1);
1212          if (size & 1) {
1213            tail = (char *)p;
1214          }
1215          if ((fio_flags & FIO_UTF16) && p > (uint8_t *)ptr) {
1216            // Check for a trailing leading word
1217            if (fio_flags & FIO_ENDIAN_L) {
1218              u8c = (unsigned)(*--p) << 8;
1219              u8c += *--p;
1220            } else {
1221              u8c = *--p;
1222              u8c += (unsigned)(*--p) << 8;
1223            }
1224            if (u8c >= 0xd800 && u8c <= 0xdbff) {
1225              tail = (char *)p;
1226            } else {
1227              p += 2;
1228            }
1229          }
1230        } else {   //  FIO_UCS4
1231                   // Check for trailing 1, 2 or 3 bytes
1232          p = (uint8_t *)ptr + (size & ~3);
1233          if (size & 3) {
1234            tail = (char *)p;
1235          }
1236        }
1237
1238        // If there is a trailing incomplete sequence move it to
1239        // conv_rest[].
1240        if (tail != NULL) {
1241          conv_restlen = (int)((ptr + size) - tail);
1242          memmove(conv_rest, tail, (size_t)conv_restlen);
1243          size -= conv_restlen;
1244        }
1245
1246        while (p > (uint8_t *)ptr) {
1247          if (fio_flags & FIO_LATIN1) {
1248            u8c = *--p;
1249          } else if (fio_flags & (FIO_UCS2 | FIO_UTF16)) {
1250            if (fio_flags & FIO_ENDIAN_L) {
1251              u8c = (unsigned)(*--p) << 8;
1252              u8c += *--p;
1253            } else {
1254              u8c = *--p;
1255              u8c += (unsigned)(*--p) << 8;
1256            }
1257            if ((fio_flags & FIO_UTF16)
1258                && u8c >= 0xdc00 && u8c <= 0xdfff) {
1259              int u16c;
1260
1261              if (p == (uint8_t *)ptr) {
1262                // Missing leading word.
1263                if (can_retry) {
1264                  goto rewind_retry;
1265                }
1266                if (conv_error == 0) {
1267                  conv_error = readfile_linenr(linecnt, ptr, (char *)p);
1268                }
1269                if (bad_char_behavior == BAD_DROP) {
1270                  continue;
1271                }
1272                if (bad_char_behavior != BAD_KEEP) {
1273                  u8c = (unsigned)bad_char_behavior;
1274                }
1275              }
1276
1277              // found second word of double-word, get the first
1278              // word and compute the resulting character
1279              if (fio_flags & FIO_ENDIAN_L) {
1280                u16c = (*--p << 8);
1281                u16c += *--p;
1282              } else {
1283                u16c = *--p;
1284                u16c += (*--p << 8);
1285              }
1286              u8c = 0x10000 + (((unsigned)u16c & 0x3ff) << 10)
1287                    + (u8c & 0x3ff);
1288
1289              // Check if the word is indeed a leading word.
1290              if (u16c < 0xd800 || u16c > 0xdbff) {
1291                if (can_retry) {
1292                  goto rewind_retry;
1293                }
1294                if (conv_error == 0) {
1295                  conv_error = readfile_linenr(linecnt, ptr, (char *)p);
1296                }
1297                if (bad_char_behavior == BAD_DROP) {
1298                  continue;
1299                }
1300                if (bad_char_behavior != BAD_KEEP) {
1301                  u8c = (unsigned)bad_char_behavior;
1302                }
1303              }
1304            }
1305          } else if (fio_flags & FIO_UCS4) {
1306            if (fio_flags & FIO_ENDIAN_L) {
1307              u8c = (unsigned)(*--p) << 24;
1308              u8c += (unsigned)(*--p) << 16;
1309              u8c += (unsigned)(*--p) << 8;
1310              u8c += *--p;
1311            } else {          // big endian
1312              u8c = *--p;
1313              u8c += (unsigned)(*--p) << 8;
1314              u8c += (unsigned)(*--p) << 16;
1315              u8c += (unsigned)(*--p) << 24;
1316            }
1317            // Replace characters over INT_MAX with Unicode replacement character
1318            if (u8c > INT_MAX) {
1319              u8c = 0xfffd;
1320            }
1321          } else {        // UTF-8
1322            if (*--p < 0x80) {
1323              u8c = *p;
1324            } else {
1325              len = utf_head_off(ptr, (char *)p);
1326              p -= len;
1327              u8c = (unsigned)utf_ptr2char((char *)p);
1328              if (len == 0) {
1329                // Not a valid UTF-8 character, retry with
1330                // another fenc when possible, otherwise just
1331                // report the error.
1332                if (can_retry) {
1333                  goto rewind_retry;
1334                }
1335                if (conv_error == 0) {
1336                  conv_error = readfile_linenr(linecnt, ptr, (char *)p);
1337                }
1338                if (bad_char_behavior == BAD_DROP) {
1339                  continue;
1340                }
1341                if (bad_char_behavior != BAD_KEEP) {
1342                  u8c = (unsigned)bad_char_behavior;
1343                }
1344              }
1345            }
1346          }
1347          assert(u8c <= INT_MAX);
1348          // produce UTF-8
1349          dest -= utf_char2len((int)u8c);
1350          utf_char2bytes((int)u8c, dest);
1351        }
1352
1353        // move the linerest to before the converted characters
1354        line_start = dest - linerest;
1355        memmove(line_start, buffer, (size_t)linerest);
1356        size = ((ptr + real_size) - dest);
1357        ptr = dest;
1358      } else if (!curbuf->b_p_bin) {
1359        bool incomplete_tail = false;
1360
1361        // Reading UTF-8: Check if the bytes are valid UTF-8.
1362        for (p = (uint8_t *)ptr;;) {
1363          // Skip ASCII bytes quickly using word-at-a-time check.
1364          {
1365            uint8_t *ascii_end = (uint8_t *)ptr + size;
1366            while (ascii_end - p >= (ptrdiff_t)sizeof(uint64_t)) {
1367              uint64_t word;
1368              memcpy(&word, p, sizeof(uint64_t));
1369              if (word & NONASCII_MASK) {
1370                break;
1371              }
1372              p += sizeof(uint64_t);
1373            }
1374            while (p < ascii_end && *p < 0x80) {
1375              p++;
1376            }
1377          }
1378
1379          int todo = (int)(((uint8_t *)ptr + size) - p);
1380          if (todo <= 0) {
1381            break;
1382          }
1383          if (*p >= 0x80) {
1384            // A length of 1 means it's an illegal byte.  Accept
1385            // an incomplete character at the end though, the next
1386            // read() will get the next bytes, we'll check it
1387            // then.
1388            int l = utf_ptr2len_len((char *)p, todo);
1389            if (l > todo && !incomplete_tail) {
1390              // Avoid retrying with a different encoding when
1391              // a truncated file is more likely, or attempting
1392              // to read the rest of an incomplete sequence when
1393              // we have already done so.
1394              if (p > (uint8_t *)ptr || filesize > 0) {
1395                incomplete_tail = true;
1396              }
1397              // Incomplete byte sequence, move it to conv_rest[]
1398              // and try to read the rest of it, unless we've
1399              // already done so.
1400              if (p > (uint8_t *)ptr) {
1401                conv_restlen = todo;
1402                memmove(conv_rest, p, (size_t)conv_restlen);
1403                size -= conv_restlen;
1404                break;
1405              }
1406            }
1407            if (l == 1 || l > todo) {
1408              // Illegal byte.  If we can try another encoding
1409              // do that, unless at EOF where a truncated
1410              // file is more likely than a conversion error.
1411              if (can_retry && !incomplete_tail) {
1412                break;
1413              }
1414
1415              // When we did a conversion report an error.
1416              if (iconv_fd != (iconv_t)-1 && conv_error == 0) {
1417                conv_error = readfile_linenr(linecnt, ptr, (char *)p);
1418              }
1419
1420              // Remember the first linenr with an illegal byte
1421              if (conv_error == 0 && illegal_byte == 0) {
1422                illegal_byte = readfile_linenr(linecnt, ptr, (char *)p);
1423              }
1424
1425              // Drop, keep or replace the bad byte.
1426              if (bad_char_behavior == BAD_DROP) {
1427                memmove(p, p + 1, (size_t)(todo - 1));
1428                size--;
1429              } else {
1430                if (bad_char_behavior != BAD_KEEP) {
1431                  *p = (uint8_t)bad_char_behavior;
1432                }
1433                p++;
1434              }
1435            } else {
1436              p += l;
1437            }
1438          }
1439        }
1440        if (p < (uint8_t *)ptr + size && !incomplete_tail) {
1441          // Detected a UTF-8 error.
1442rewind_retry:
1443          // Retry reading with another conversion.
1444          if (p_ccv.type != kCallbackNone && iconv_fd != (iconv_t)-1) {
1445            // iconv() failed, try 'charconvert'
1446            did_iconv = true;
1447          } else {
1448            // use next item from 'fileencodings'
1449            advance_fenc = true;
1450          }
1451          file_rewind = true;
1452          goto retry;
1453        }
1454      }
1455
1456      // count the number of characters (after conversion!)
1457      filesize += size;
1458
1459      // when reading the first part of a file: guess EOL type
1460      if (fileformat == EOL_UNKNOWN) {
1461        // First try finding a NL, for Dos and Unix
1462        if (try_dos || try_unix) {
1463          // Reset the carriage return counter.
1464          if (try_mac) {
1465            try_mac = 1;
1466          }
1467
1468          for (p = (uint8_t *)ptr; p < (uint8_t *)ptr + size; p++) {
1469            if (*p == NL) {
1470              if (!try_unix
1471                  || (try_dos && p > (uint8_t *)ptr && p[-1] == CAR)) {
1472                fileformat = EOL_DOS;
1473              } else {
1474                fileformat = EOL_UNIX;
1475              }
1476              break;
1477            } else if (*p == CAR && try_mac) {
1478              try_mac++;
1479            }
1480          }
1481
1482          // Don't give in to EOL_UNIX if EOL_MAC is more likely
1483          if (fileformat == EOL_UNIX && try_mac) {
1484            // Need to reset the counters when retrying fenc.
1485            try_mac = 1;
1486            try_unix = 1;
1487            for (; p >= (uint8_t *)ptr && *p != CAR; p--) {}
1488            if (p >= (uint8_t *)ptr) {
1489              for (p = (uint8_t *)ptr; p < (uint8_t *)ptr + size; p++) {
1490                if (*p == NL) {
1491                  try_unix++;
1492                } else if (*p == CAR) {
1493                  try_mac++;
1494                }
1495              }
1496              if (try_mac > try_unix) {
1497                fileformat = EOL_MAC;
1498              }
1499            }
1500          } else if (fileformat == EOL_UNKNOWN && try_mac == 1) {
1501            // Looking for CR but found no end-of-line markers at all:
1502            // use the default format.
1503            fileformat = default_fileformat();
1504          }
1505        }
1506
1507        // No NL found: may use Mac format
1508        if (fileformat == EOL_UNKNOWN && try_mac) {
1509          fileformat = EOL_MAC;
1510        }
1511
1512        // Still nothing found?  Use first format in 'ffs'
1513        if (fileformat == EOL_UNKNOWN) {
1514          fileformat = default_fileformat();
1515        }
1516
1517        // May set 'p_ff' if editing a new file.
1518        if (set_options) {
1519          set_fileformat(fileformat, OPT_LOCAL);
1520        }
1521      }
1522    }
1523
1524    // This loop is executed once for every character read.
1525    // Keep it fast!
1526    if (fileformat == EOL_MAC) {
1527      ptr--;
1528      while (++ptr, --size >= 0) {
1529        // catch most common case first
1530        if ((c = *ptr) != NUL && c != CAR && c != NL) {
1531          continue;
1532        }
1533        if (c == NUL) {
1534          *ptr = NL;            // NULs are replaced by newlines!
1535        } else if (c == NL) {
1536          *ptr = CAR;           // NLs are replaced by CRs!
1537        } else {
1538          if (skip_count == 0) {
1539            *ptr = NUL;                     // end of line
1540            len = (colnr_T)(ptr - line_start + 1);
1541            if (ml_append(lnum, line_start, len, newfile) == FAIL) {
1542              error = true;
1543              break;
1544            }
1545            if (read_undo_file) {
1546              sha256_update(&sha_ctx, (uint8_t *)line_start, (size_t)len);
1547            }
1548            lnum++;
1549            if (--read_count == 0) {
1550              error = true;                     // break loop
1551              line_start = ptr;                 // nothing left to write
1552              break;
1553            }
1554          } else {
1555            skip_count--;
1556          }
1557          line_start = ptr + 1;
1558        }
1559      }
1560    } else {
1561      // Use memchr() for SIMD-optimized newline scanning instead
1562      // of scanning each byte individually.
1563      char *end = ptr + size;
1564
1565      while (ptr < end) {
1566        char *nl = memchr(ptr, NL, (size_t)(end - ptr));
1567        char *nul_scan;
1568
1569        if (nl == NULL) {
1570          // No more newlines in buffer.
1571          // Replace any NUL bytes with NL in remaining data.
1572          while ((nul_scan = memchr(ptr, NUL, (size_t)(end - ptr))) != NULL) {
1573            *nul_scan = NL;
1574            ptr = nul_scan + 1;
1575          }
1576          ptr = end;
1577          break;
1578        }
1579
1580        // Replace NUL bytes with NL before the newline.
1581        {
1582          char *scan = ptr;
1583          while ((nul_scan = memchr(scan, NUL, (size_t)(nl - scan))) != NULL) {
1584            *nul_scan = NL;
1585            scan = nul_scan + 1;
1586          }
1587        }
1588
1589        // Process the newline.
1590        ptr = nl;
1591        if (skip_count == 0) {
1592          *ptr = NUL;                         // end of line
1593          len = (colnr_T)(ptr - line_start + 1);
1594          if (fileformat == EOL_DOS) {
1595            if (ptr > line_start && ptr[-1] == CAR) {
1596              // remove CR before NL
1597              ptr[-1] = NUL;
1598              len--;
1599            } else if (ff_error != EOL_DOS) {
1600              // Reading in Dos format, but no CR-LF found!
1601              // When 'fileformats' includes "unix", delete all
1602              // the lines read so far and start all over again.
1603              // Otherwise give an error message later.
1604              if (try_unix
1605                  && !read_stdin
1606                  && (read_buffer || vim_lseek(fd, 0, SEEK_SET) == 0)) {
1607                fileformat = EOL_UNIX;
1608                if (set_options) {
1609                  set_fileformat(EOL_UNIX, OPT_LOCAL);
1610                }
1611                file_rewind = true;
1612                keep_fileformat = true;
1613                goto retry;
1614              }
1615              ff_error = EOL_DOS;
1616            }
1617          }
1618          if (ml_append(lnum, line_start, len, newfile) == FAIL) {
1619            error = true;
1620            break;
1621          }
1622          if (read_undo_file) {
1623            sha256_update(&sha_ctx, (uint8_t *)line_start, (size_t)len);
1624          }
1625          lnum++;
1626          if (--read_count == 0) {
1627            error = true;                         // break loop
1628            line_start = ptr;                 // nothing left to write
1629            break;
1630          }
1631        } else {
1632          skip_count--;
1633        }
1634        line_start = ptr + 1;
1635        ptr++;
1636      }
1637      size = -1;
1638    }
1639    linerest = (ptr - line_start);
1640    os_breakcheck();
1641  }
1642
1643failed:
1644  // not an error, max. number of lines reached
1645  if (error && read_count == 0) {
1646    error = false;
1647  }
1648
1649  // In Dos format ignore a trailing CTRL-Z, unless 'binary' is set.
1650  // In old days the file length was in sector count and the CTRL-Z the
1651  // marker where the file really ended.  Assuming we write it to a file
1652  // system that keeps file length properly the CTRL-Z should be dropped.
1653  // Set the 'endoffile' option so the user can decide what to write later.
1654  // In Unix format the CTRL-Z is just another character.
1655  if (linerest != 0
1656      && !curbuf->b_p_bin
1657      && fileformat == EOL_DOS
1658      && ptr[-1] == Ctrl_Z) {
1659    ptr--;
1660    linerest--;
1661    if (set_options) {
1662      curbuf->b_p_eof = true;
1663    }
1664  }
1665
1666  // If we get EOF in the middle of a line, note the fact and
1667  // complete the line ourselves.
1668  if (!error
1669      && !got_int
1670      && linerest != 0) {
1671    // remember for when writing
1672    if (set_options) {
1673      curbuf->b_p_eol = false;
1674    }
1675    *ptr = NUL;
1676    len = (colnr_T)(ptr - line_start + 1);
1677    if (ml_append(lnum, line_start, len, newfile) == FAIL) {
1678      error = true;
1679    } else {
1680      if (read_undo_file) {
1681        sha256_update(&sha_ctx, (uint8_t *)line_start, (size_t)len);
1682      }
1683      read_no_eol_lnum = ++lnum;
1684    }
1685  }
1686
1687  if (set_options) {
1688    // Remember the current file format.
1689    save_file_ff(curbuf);
1690    // If editing a new file: set 'fenc' for the current buffer.
1691    // Also for ":read ++edit file".
1692    set_option_direct(kOptFileencoding, CSTR_AS_OBJ(fenc), OPT_LOCAL, 0);
1693  }
1694  if (fenc_alloced) {
1695    xfree(fenc);
1696  }
1697  if (iconv_fd != (iconv_t)-1) {
1698    iconv_close(iconv_fd);
1699  }
1700
1701  if (!read_buffer && !read_stdin) {
1702    close(fd);  // errors are ignored
1703  } else {
1704    os_set_cloexec(fd);
1705  }
1706  xfree(buffer);
1707
1708  if (read_stdin) {
1709    close(fd);
1710    if (stdin_fd < 0) {
1711#ifndef MSWIN
1712      // On Unix, use stderr for stdin, makes shell commands work.
1713      vim_ignored = dup(2);
1714#else
1715      // On Windows, use the console input handle (CONIN$) for stdin.
1716      vim_ignored = os_open_conin_fd();
1717#endif
1718    }
1719  }
1720
1721  if (tmpname != NULL) {
1722    os_remove(tmpname);  // delete converted file
1723    xfree(tmpname);
1724  }
1725  no_wait_return--;                     // may wait for return now
1726
1727  // In recovery mode everything but autocommands is skipped.
1728  if (!recoverymode) {
1729    // need to delete the last line, which comes from the empty buffer
1730    if (newfile && wasempty && !(curbuf->b_ml.ml_flags & ML_EMPTY)) {
1731      ml_delete(curbuf->b_ml.ml_line_count);
1732      linecnt--;
1733    }
1734    curbuf->deleted_bytes = 0;
1735    curbuf->deleted_bytes2 = 0;
1736    curbuf->deleted_codepoints = 0;
1737    curbuf->deleted_codeunits = 0;
1738    linecnt = curbuf->b_ml.ml_line_count - linecnt;
1739    if (filesize == 0) {
1740      linecnt = 0;
1741    }
1742    if (newfile || read_buffer) {
1743      redraw_curbuf_later(UPD_NOT_VALID);
1744      // After reading the text into the buffer the diff info needs to
1745      // be updated.
1746      diff_invalidate(curbuf);
1747      // All folds in the window are invalid now.  Mark them for update
1748      // before triggering autocommands.
1749      foldUpdateAll(curwin);
1750    } else if (linecnt) {               // appended at least one line
1751      appended_lines_mark(from, linecnt);
1752    }
1753
1754    if (got_int) {
1755      if (!(flags & READ_DUMMY)) {
1756        filemess(curbuf, sfname, _(e_interr), NULL);
1757        if (newfile) {
1758          curbuf->b_p_ro = true;                // must use "w!" now
1759        }
1760      }
1761      msg_scroll = msg_save;
1762      check_marks_read();
1763      retval = OK;        // an interrupt isn't really an error
1764      goto theend;
1765    }
1766
1767    if (!filtering && !(flags & READ_DUMMY) && !silent) {
1768      add_quoted_fname(IObuff, IOSIZE, curbuf, sfname);
1769      c = false;
1770
1771      int buflen = (int)strlen(IObuff);
1772#ifdef UNIX
1773      if (S_ISFIFO(perm)) {             // fifo
1774        buflen += snprintf(IObuff + buflen, (size_t)(IOSIZE - buflen), _("[fifo]"));
1775        c = true;
1776      }
1777      if (S_ISSOCK(perm)) {            // or socket
1778        buflen += snprintf(IObuff + buflen, (size_t)(IOSIZE - buflen), _("[socket]"));
1779        c = true;
1780      }
1781# ifdef OPEN_CHR_FILES
1782      if (S_ISCHR(perm)) {                          // or character special
1783        buflen += snprintf(IObuff + buflen, (size_t)(IOSIZE - buflen), _("[character special]"));
1784        c = true;
1785      }
1786# endif
1787#endif
1788      if (curbuf->b_p_ro) {
1789        buflen += snprintf(IObuff + buflen, (size_t)(IOSIZE - buflen), "%s",
1790                           shortmess(kShmRo) ? _("[RO]") : _("[readonly]"));
1791        c = true;
1792      }
1793      if (read_no_eol_lnum) {
1794        buflen += snprintf(IObuff + buflen, (size_t)(IOSIZE - buflen), _("[noeol]"));
1795        c = true;
1796      }
1797      if (ff_error == EOL_DOS) {
1798        buflen += snprintf(IObuff + buflen, (size_t)(IOSIZE - buflen), _("[CR missing]"));
1799        c = true;
1800      }
1801      if (split) {
1802        buflen += snprintf(IObuff + buflen, (size_t)(IOSIZE - buflen), _("[long lines split]"));
1803        c = true;
1804      }
1805      if (notconverted) {
1806        buflen += snprintf(IObuff + buflen, (size_t)(IOSIZE - buflen), _("[NOT converted]"));
1807        c = true;
1808      } else if (converted) {
1809        buflen += snprintf(IObuff + buflen, (size_t)(IOSIZE - buflen), _("[converted]"));
1810        c = true;
1811      }
1812      if (conv_error != 0) {
1813        snprintf(IObuff + buflen, (size_t)(IOSIZE - buflen),
1814                 _("[CONVERSION ERROR in line %" PRId64 "]"), (int64_t)conv_error);
1815        c = true;
1816      } else if (illegal_byte > 0) {
1817        snprintf(IObuff + buflen, (size_t)(IOSIZE - buflen),
1818                 _("[ILLEGAL BYTE in line %" PRId64 "]"), (int64_t)illegal_byte);
1819        c = true;
1820      } else if (error) {
1821        snprintf(IObuff + buflen, (size_t)(IOSIZE - buflen), _("[READ ERRORS]"));
1822        c = true;
1823      }
1824      if (msg_add_fileformat(fileformat)) {
1825        c = true;
1826      }
1827
1828      msg_add_lines(c, linecnt, filesize);
1829
1830      XFREE_CLEAR(keep_msg);
1831      p = NULL;
1832      msg_scrolled_ign = true;
1833
1834      if (!read_stdin && !read_buffer) {
1835        if (msg_col > 0) {
1836          msg_putchar('\r');  // overwrite previous message
1837        }
1838        p = (uint8_t *)msg_trunc(IObuff, false, 0);
1839      }
1840
1841      if (read_stdin || read_buffer || restart_edit != 0
1842          || (msg_scrolled != 0 && !need_wait_return)) {
1843        // Need to repeat the message after redrawing when:
1844        // - When reading from stdin (the screen will be cleared next).
1845        // - When restart_edit is set (otherwise there will be a delay before
1846        //   redrawing).
1847        // - When the screen was scrolled but there is no wait-return prompt.
1848        set_keep_msg((char *)p, 0);
1849      }
1850      msg_scrolled_ign = false;
1851    }
1852
1853    // with errors writing the file requires ":w!"
1854    if (newfile && (error
1855                    || conv_error != 0
1856                    || (illegal_byte > 0 && bad_char_behavior != BAD_KEEP))) {
1857      curbuf->b_p_ro = true;
1858    }
1859
1860    u_clearline(curbuf);   // cannot use "U" command after adding lines
1861
1862    // Cursor at first new line.
1863    curwin->w_cursor.lnum = from + 1;
1864    check_cursor_lnum(curwin);
1865    beginline(BL_WHITE | BL_FIX);           // on first non-blank
1866
1867    if ((cmdmod.cmod_flags & CMOD_LOCKMARKS) == 0) {
1868      // Set '[ and '] marks to the newly read lines.
1869      curbuf->b_op_start.lnum = from + 1;
1870      curbuf->b_op_start.col = 0;
1871      curbuf->b_op_end.lnum = from + linecnt;
1872      curbuf->b_op_end.col = 0;
1873    }
1874  }
1875  msg_scroll = msg_save;
1876
1877  // Get the marks before executing autocommands, so they can be used there.
1878  check_marks_read();
1879
1880  // We remember if the last line of the read didn't have
1881  // an eol even when 'binary' is off, to support turning 'fixeol' off,
1882  // or writing the read again with 'binary' on.  The latter is required
1883  // for ":autocmd FileReadPost *.gz set bin|'[,']!gunzip" to work.
1884  curbuf->b_no_eol_lnum = read_no_eol_lnum;
1885
1886  // When reloading a buffer put the cursor at the first line that is
1887  // different.
1888  if (flags & READ_KEEP_UNDO) {
1889    u_find_first_changed();
1890  }
1891
1892  // When opening a new file locate undo info and read it.
1893  if (read_undo_file) {
1894    uint8_t hash[UNDO_HASH_SIZE];
1895
1896    sha256_finish(&sha_ctx, hash);
1897    u_read_undo(NULL, hash, fname);
1898  }
1899
1900  if (!read_stdin && !read_fifo && (!read_buffer || sfname != NULL)) {
1901    int m = msg_scroll;
1902    int n = msg_scrolled;
1903
1904    // Save the fileformat now, otherwise the buffer will be considered
1905    // modified if the format/encoding was automatically detected.
1906    if (set_options) {
1907      save_file_ff(curbuf);
1908    }
1909
1910    // The output from the autocommands should not overwrite anything and
1911    // should not be overwritten: Set msg_scroll, restore its value if no
1912    // output was done.
1913    msg_scroll = true;
1914    if (filtering) {
1915      apply_autocmds_exarg(EVENT_FILTERREADPOST, NULL, sfname,
1916                           false, curbuf, eap);
1917    } else if (newfile || (read_buffer && sfname != NULL)) {
1918      // 'filetype' detection is triggered by BufReadPost.
1919      bool did_bufrp = apply_autocmds_exarg(EVENT_BUFREADPOST, NULL, sfname, false, curbuf, eap);
1920
1921      if (!curbuf->b_au_did_filetype && *curbuf->b_p_ft != NUL) {
1922        // EVENT_FILETYPE was not triggered but the buffer already has a
1923        // filetype.  Trigger EVENT_FILETYPE using the existing filetype.
1924        apply_autocmds(EVENT_FILETYPE, curbuf->b_p_ft, curbuf->b_fname, true, curbuf);
1925      }
1926
1927      if (!did_bufrp && *curbuf->b_p_ft == NUL && augroup_exists("filetypedetect")) {
1928        // BufReadPost was skipped, and 'filetype' is empty. Retry filetype-detection now.
1929        apply_autocmds_group(EVENT_BUFREADPOST, sfname, NULL, true, augroup_find("filetypedetect"),
1930                             curbuf, curwin, NULL, NULL, false);
1931      }
1932    } else {
1933      apply_autocmds_exarg(EVENT_FILEREADPOST, sfname, sfname,
1934                           false, NULL, eap);
1935    }
1936    if (msg_scrolled == n) {
1937      msg_scroll = m;
1938    }
1939    if (aborting()) {       // autocmds may abort script processing
1940      return FAIL;
1941    }
1942  }
1943
1944  if (!(recoverymode && error)) {
1945    retval = OK;
1946  }
1947
1948theend:
1949  if (curbuf->b_ml.ml_mfp != NULL
1950      && curbuf->b_ml.ml_mfp->mf_dirty == MF_DIRTY_YES_NOSYNC) {
1951    // OK to sync the swap file now
1952    curbuf->b_ml.ml_mfp->mf_dirty = MF_DIRTY_YES;
1953  }
1954
1955  return retval;
1956}
1957
1958#ifdef OPEN_CHR_FILES
1959/// Returns true if the file name argument is of the form "/dev/fd/\d\+",
1960/// which is the name of files used for process substitution output by
1961/// some shells on some operating systems, e.g., bash on SunOS.
1962/// Do not accept "/dev/fd/[012]", opening these may hang Vim.
1963///
1964/// @param fname file name to check
1965bool is_dev_fd_file(char *fname)
1966  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT
1967{
1968  return strncmp(fname, "/dev/fd/", 8) == 0
1969         && ascii_isdigit((uint8_t)fname[8])
1970         && *skipdigits(fname + 9) == NUL
1971         && (fname[9] != NUL
1972             || (fname[8] != '0' && fname[8] != '1' && fname[8] != '2'));
1973}
1974#endif
1975
1976/// From the current line count and characters read after that, estimate the
1977/// line number where we are now.
1978/// Used for error messages that include a line number.
1979///
1980/// @param linecnt  line count before reading more bytes
1981/// @param p        start of more bytes read
1982/// @param endp     end of more bytes read
1983static linenr_T readfile_linenr(linenr_T linecnt, char *p, const char *endp)
1984{
1985  linenr_T lnum = curbuf->b_ml.ml_line_count - linecnt + 1;
1986  for (char *s = p; s < endp; s++) {
1987    if (*s == '\n') {
1988      lnum++;
1989    }
1990  }
1991  return lnum;
1992}
1993
1994/// Fill "*eap" to force the 'fileencoding', 'fileformat' and 'binary' to be
1995/// equal to the buffer "buf".  Used for calling readfile().
1996void prep_exarg(exarg_T *eap, const buf_T *buf)
1997  FUNC_ATTR_NONNULL_ALL
1998{
1999  const size_t cmd_len = 15 + strlen(buf->b_p_fenc);
2000  eap->cmd = xmalloc(cmd_len);
2001
2002  snprintf(eap->cmd, cmd_len, "e ++enc=%s", buf->b_p_fenc);
2003  eap->force_enc = 8;
2004  eap->bad_char = buf->b_bad_char;
2005  eap->force_ff = (unsigned char)(*buf->b_p_ff);
2006
2007  eap->force_bin = buf->b_p_bin ? FORCE_BIN : FORCE_NOBIN;
2008  eap->read_edit = false;
2009  eap->forceit = false;
2010}
2011
2012/// Set default or forced 'fileformat' and 'binary'.
2013void set_file_options(bool set_options, exarg_T *eap)
2014{
2015  // set default 'fileformat'
2016  if (set_options) {
2017    if (eap != NULL && eap->force_ff != 0) {
2018      set_fileformat(get_fileformat_force(curbuf, eap), OPT_LOCAL);
2019    } else if (*p_ffs != NUL) {
2020      set_fileformat(default_fileformat(), OPT_LOCAL);
2021    }
2022  }
2023
2024  // set or reset 'binary'
2025  if (eap != NULL && eap->force_bin != 0) {
2026    int oldval = curbuf->b_p_bin;
2027
2028    curbuf->b_p_bin = (eap->force_bin == FORCE_BIN);
2029    set_options_bin(oldval, curbuf->b_p_bin, OPT_LOCAL);
2030  }
2031}
2032
2033/// Set forced 'fileencoding'.
2034void set_forced_fenc(exarg_T *eap)
2035{
2036  if (eap->force_enc == 0) {
2037    return;
2038  }
2039
2040  char *fenc = enc_canonize(eap->cmd + eap->force_enc);
2041  set_option_direct(kOptFileencoding, CSTR_AS_OBJ(fenc), OPT_LOCAL, 0);
2042  xfree(fenc);
2043}
2044
2045/// Find next fileencoding to use from 'fileencodings'.
2046/// "pp" points to fenc_next.  It's advanced to the next item.
2047/// When there are no more items, an empty string is returned and *pp is set to
2048/// NULL.
2049/// When *pp is not set to NULL, the result is in allocated memory and "alloced"
2050/// is set to true.
2051static char *next_fenc(char **pp, bool *alloced)
2052  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_NONNULL_RET
2053{
2054  char *r;
2055
2056  *alloced = false;
2057  if (**pp == NUL) {
2058    *pp = NULL;
2059    return "";
2060  }
2061  char *p = vim_strchr(*pp, ',');
2062  if (p == NULL) {
2063    r = enc_canonize(*pp);
2064    *pp += strlen(*pp);
2065  } else {
2066    r = xmemdupz(*pp, (size_t)(p - *pp));
2067    *pp = p + 1;
2068    p = enc_canonize(r);
2069    xfree(r);
2070    r = p;
2071  }
2072  *alloced = true;
2073  return r;
2074}
2075
2076/// Convert a file with the 'charconvert' expression.
2077/// This closes the file which is to be read, converts it and opens the
2078/// resulting file for reading.
2079///
2080/// @param fname  name of input file
2081/// @param fenc   converted from
2082/// @param fdp    in/out: file descriptor of file
2083///
2084/// @return       name of the resulting converted file (the caller should delete it after reading it).
2085///               Returns NULL if the conversion failed ("*fdp" is not set) .
2086static char *readfile_charconvert(char *fname, char *fenc, int *fdp)
2087{
2088  char *errmsg = NULL;
2089
2090  char *tmpname = vim_tempname();
2091  if (tmpname == NULL) {
2092    errmsg = _("Can't find temp file for conversion");
2093  } else {
2094    close(*fdp);                // close the input file, ignore errors
2095    *fdp = -1;
2096    if (eval_charconvert(fenc, "utf-8",
2097                         fname, tmpname) == FAIL) {
2098      errmsg = _("Conversion with 'charconvert' failed");
2099    }
2100    if (errmsg == NULL && (*fdp = os_open(tmpname, O_RDONLY, 0)) < 0) {
2101      errmsg = _("can't read output of 'charconvert'");
2102    }
2103  }
2104
2105  if (errmsg != NULL) {
2106    // Don't use emsg(), it breaks mappings, the retry with
2107    // another type of conversion might still work.
2108    msg(errmsg, 0);
2109    if (tmpname != NULL) {
2110      os_remove(tmpname);  // delete converted file
2111      XFREE_CLEAR(tmpname);
2112    }
2113  }
2114
2115  // If the input file is closed, open it (caller should check for error).
2116  if (*fdp < 0) {
2117    *fdp = os_open(fname, O_RDONLY, 0);
2118  }
2119
2120  return tmpname;
2121}
2122
2123/// Set the name of the current buffer.  Use when the buffer doesn't have a
2124/// name and a ":r" or ":w" command with a file name is used.
2125int set_rw_fname(char *fname, char *sfname)
2126{
2127  buf_T *buf = curbuf;
2128
2129  // It's like the unnamed buffer is deleted....
2130  if (curbuf->b_p_bl) {
2131    apply_autocmds(EVENT_BUFDELETE, NULL, NULL, false, curbuf);
2132  }
2133  apply_autocmds(EVENT_BUFWIPEOUT, NULL, NULL, false, curbuf);
2134  if (aborting()) {         // autocmds may abort script processing
2135    return FAIL;
2136  }
2137  if (curbuf != buf) {
2138    // We are in another buffer now, don't do the renaming.
2139    emsg(_(e_auchangedbuf));
2140    return FAIL;
2141  }
2142
2143  if (setfname(curbuf, fname, sfname, false) == OK) {
2144    curbuf->b_flags |= BF_NOTEDITED;
2145  }
2146
2147  // ....and a new named one is created
2148  apply_autocmds(EVENT_BUFNEW, NULL, NULL, false, curbuf);
2149  if (curbuf->b_p_bl) {
2150    apply_autocmds(EVENT_BUFADD, NULL, NULL, false, curbuf);
2151  }
2152  if (aborting()) {         // autocmds may abort script processing
2153    return FAIL;
2154  }
2155
2156  // Do filetype detection now if 'filetype' is empty.
2157  if (*curbuf->b_p_ft == NUL) {
2158    if (augroup_exists("filetypedetect")) {
2159      do_doautocmd("filetypedetect BufRead", false, NULL);
2160    }
2161    do_modelines(0);
2162  }
2163
2164  return OK;
2165}
2166
2167/// Put file name into the specified buffer with quotes
2168///
2169/// Replaces home directory at the start with `~`.
2170///
2171/// @param[out]  ret_buf  Buffer to save results to.
2172/// @param[in]  bufsize  ret_buf size.
2173/// @param[in]  buf  buf_T file name is coming from.
2174/// @param[in]  fname  File name to write.
2175void add_quoted_fname(char *const ret_buf, const size_t bufsize, const buf_T *const buf,
2176                      const char *fname)
2177  FUNC_ATTR_NONNULL_ARG(1)
2178{
2179  if (fname == NULL) {
2180    fname = "-stdin-";
2181  }
2182  size_t len = 0;
2183  ret_buf[len++] = '"';
2184  len += home_replace(buf, fname, ret_buf + len, bufsize - 4, true);
2185  xstrlcpy(ret_buf + len, "\" ", bufsize - len);
2186}
2187
2188/// Append message for text mode to IObuff.
2189///
2190/// @param eol_type line ending type
2191///
2192/// @return true if something was appended.
2193bool msg_add_fileformat(int eol_type)
2194{
2195#ifndef USE_CRNL
2196  if (eol_type == EOL_DOS) {
2197    xstrlcat(IObuff, _("[dos]"), IOSIZE);
2198    return true;
2199  }
2200#endif
2201  if (eol_type == EOL_MAC) {
2202    xstrlcat(IObuff, _("[mac]"), IOSIZE);
2203    return true;
2204  }
2205#ifdef USE_CRNL
2206  if (eol_type == EOL_UNIX) {
2207    xstrlcat(IObuff, _("[unix]"), IOSIZE);
2208    return true;
2209  }
2210#endif
2211  return false;
2212}
2213
2214/// Append line and character count to IObuff.
2215void msg_add_lines(int insert_space, linenr_T lnum, off_T nchars)
2216{
2217  size_t len = strlen(IObuff);
2218
2219  if (shortmess(kShmLines)) {
2220    snprintf(IObuff + len, IOSIZE - len,
2221             _("%s%" PRId64 "L, %" PRId64 "B"),  // l10n: L as in line, B as in byte
2222             insert_space ? " " : "", (int64_t)lnum, (int64_t)nchars);
2223  } else {
2224    len += (size_t)snprintf(IObuff + len, IOSIZE - len,
2225                            NGETTEXT("%s%" PRId64 " line, ", "%s%" PRId64 " lines, ", lnum),
2226                            insert_space ? " " : "", (int64_t)lnum);
2227    snprintf(IObuff + len, IOSIZE - len,
2228             NGETTEXT("%" PRId64 " byte", "%" PRId64 " bytes", nchars),
2229             (int64_t)nchars);
2230  }
2231}
2232
2233bool time_differs(const FileInfo *file_info, int64_t mtime, int64_t mtime_ns)
2234  FUNC_ATTR_CONST
2235{
2236#if defined(__linux__) || defined(MSWIN)
2237  return file_info->stat.st_mtim.tv_nsec != mtime_ns
2238         // On a FAT filesystem, esp. under Linux, there are only 5 bits to store
2239         // the seconds.  Since the roundoff is done when flushing the inode, the
2240         // time may change unexpectedly by one second!!!
2241         || file_info->stat.st_mtim.tv_sec - mtime > 1
2242         || mtime - file_info->stat.st_mtim.tv_sec > 1;
2243#else
2244  return file_info->stat.st_mtim.tv_nsec != mtime_ns
2245         || file_info->stat.st_mtim.tv_sec != mtime;
2246#endif
2247}
2248
2249/// Return true if file encoding "fenc" requires conversion from or to
2250/// 'encoding'.
2251///
2252/// @param fenc file encoding to check
2253///
2254/// @return true if conversion is required
2255bool need_conversion(const char *fenc)
2256  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT
2257{
2258  bool same_encoding;
2259  int fenc_flags;
2260
2261  if (*fenc == NUL || strcmp(p_enc, fenc) == 0) {
2262    same_encoding = true;
2263    fenc_flags = 0;
2264  } else {
2265    // Ignore difference between "ansi" and "latin1", "ucs-4" and
2266    // "ucs-4be", etc.
2267    int enc_flags = get_fio_flags(p_enc);
2268    fenc_flags = get_fio_flags(fenc);
2269    same_encoding = (enc_flags != 0 && fenc_flags == enc_flags);
2270  }
2271  if (same_encoding) {
2272    // Specified file encoding matches UTF-8.
2273    return false;
2274  }
2275
2276  // Encodings differ.  However, conversion is not needed when 'enc' is any
2277  // Unicode encoding and the file is UTF-8.
2278  return !(fenc_flags == FIO_UTF8);
2279}
2280
2281/// Return the FIO_ flags needed for the internal conversion if 'name' was
2282/// unicode or latin1, otherwise 0. If "name" is an empty string,
2283/// use 'encoding'.
2284///
2285/// @param name string to check for encoding
2286int get_fio_flags(const char *name)
2287{
2288  if (*name == NUL) {
2289    name = p_enc;
2290  }
2291  int prop = enc_canon_props(name);
2292  if (prop & ENC_UNICODE) {
2293    if (prop & ENC_2BYTE) {
2294      if (prop & ENC_ENDIAN_L) {
2295        return FIO_UCS2 | FIO_ENDIAN_L;
2296      }
2297      return FIO_UCS2;
2298    }
2299    if (prop & ENC_4BYTE) {
2300      if (prop & ENC_ENDIAN_L) {
2301        return FIO_UCS4 | FIO_ENDIAN_L;
2302      }
2303      return FIO_UCS4;
2304    }
2305    if (prop & ENC_2WORD) {
2306      if (prop & ENC_ENDIAN_L) {
2307        return FIO_UTF16 | FIO_ENDIAN_L;
2308      }
2309      return FIO_UTF16;
2310    }
2311    return FIO_UTF8;
2312  }
2313  if (prop & ENC_LATIN1) {
2314    return FIO_LATIN1;
2315  }
2316  // must be ENC_DBCS, requires iconv()
2317  return 0;
2318}
2319
2320/// Check for a Unicode BOM (Byte Order Mark) at the start of p[size].
2321/// "size" must be at least 2.
2322///
2323/// @return  the name of the encoding and set "*lenp" to the length or,
2324///          NULL when no BOM found.
2325static char *check_for_bom(const char *p_in, int size, int *lenp, int flags)
2326{
2327  const uint8_t *p = (const uint8_t *)p_in;
2328  char *name = NULL;
2329  int len = 2;
2330
2331  if (p[0] == 0xef && p[1] == 0xbb && size >= 3 && p[2] == 0xbf
2332      && (flags == FIO_ALL || flags == FIO_UTF8 || flags == 0)) {
2333    name = "utf-8";             // EF BB BF
2334    len = 3;
2335  } else if (p[0] == 0xff && p[1] == 0xfe) {
2336    if (size >= 4 && p[2] == 0 && p[3] == 0
2337        && (flags == FIO_ALL || flags == (FIO_UCS4 | FIO_ENDIAN_L))) {
2338      name = "ucs-4le";         // FF FE 00 00
2339      len = 4;
2340    } else if (flags == (FIO_UCS2 | FIO_ENDIAN_L)) {
2341      name = "ucs-2le";         // FF FE
2342    } else if (flags == FIO_ALL
2343               || flags == (FIO_UTF16 | FIO_ENDIAN_L)) {
2344      // utf-16le is preferred, it also works for ucs-2le text
2345      name = "utf-16le";        // FF FE
2346    }
2347  } else if (p[0] == 0xfe && p[1] == 0xff
2348             && (flags == FIO_ALL || flags == FIO_UCS2 || flags ==
2349                 FIO_UTF16)) {
2350    // Default to utf-16, it works also for ucs-2 text.
2351    if (flags == FIO_UCS2) {
2352      name = "ucs-2";           // FE FF
2353    } else {
2354      name = "utf-16";          // FE FF
2355    }
2356  } else if (size >= 4 && p[0] == 0 && p[1] == 0 && p[2] == 0xfe
2357             && p[3] == 0xff && (flags == FIO_ALL || flags == FIO_UCS4)) {
2358    name = "ucs-4";             // 00 00 FE FF
2359    len = 4;
2360  }
2361
2362  *lenp = len;
2363  return name;
2364}
2365
2366/// Shorten filename of a buffer.
2367///
2368/// @param force  when true: Use full path from now on for files currently being
2369///               edited, both for file name and swap file name.  Try to shorten the file
2370///               names a bit, if safe to do so.
2371///               when false: Only try to shorten absolute file names.
2372///
2373/// For buffers that have buftype "nofile" or "scratch": never change the file
2374/// name.
2375///
2376/// @return  True if `b_fname` changed.
2377bool shorten_buf_fname(buf_T *buf, char *dirname, int force)
2378{
2379  if (buf->b_fname == NULL
2380      || bt_nofilename(buf)
2381      || path_with_url(buf->b_fname)
2382      || !(force || buf->b_sfname == NULL || path_is_absolute(buf->b_sfname))) {
2383    return false;
2384  }
2385
2386  char *p = path_shorten_fname(buf->b_ffname, dirname);
2387  bool shorten = p != NULL && *p != NUL;
2388  if (shorten && buf->b_sfname != NULL && strcmp(p, buf->b_sfname) == 0) {
2389    // Same name: keep the allocation. Callers (readfile()) alias `b_fname` across autocommands and
2390    // check the pointer to detect a rename. Very cool... #41454
2391    return false;
2392  }
2393
2394  // Decide now, the old name may be freed below.
2395  char *new_fname = shorten ? p : buf->b_ffname;
2396  bool changed = new_fname == NULL || strcmp(new_fname, buf->b_fname) != 0;
2397
2398  if (buf->b_sfname != buf->b_ffname) {
2399    XFREE_CLEAR(buf->b_sfname);
2400  }
2401  if (shorten) {
2402    buf->b_sfname = xstrdup(p);
2403    buf->b_fname = buf->b_sfname;
2404  } else {
2405    buf->b_fname = buf->b_ffname;
2406  }
2407  return changed;
2408}
2409
2410/// Shortens filenames for all buffers. Schedules a statusline redraw if any name changed.
2411void shorten_fnames(int force)
2412{
2413  char dirname[MAXPATHL];
2414  bool changed = false;
2415
2416  os_dirname(dirname, MAXPATHL);
2417  FOR_ALL_BUFFERS(buf) {
2418    changed |= shorten_buf_fname(buf, dirname, force);
2419
2420    // Always make the swap file name a full path, a "nofile" buffer may
2421    // also have a swap file.
2422    mf_fullname(buf->b_ml.ml_mfp);
2423  }
2424  if (changed) {
2425    status_redraw_all();
2426    redraw_tabline = true;
2427  }
2428}
2429
2430/// Get new filename ended by given extension.
2431///
2432/// @param fname        The original filename.
2433///                     If NULL, use current directory name and ext to
2434///                     compute new filename.
2435/// @param ext          The extension to add to the filename.
2436///                     4 chars max if prefixed with a dot, 3 otherwise.
2437/// @param prepend_dot  If true, prefix ext with a dot.
2438///                     Does nothing if ext already starts with a dot, or
2439///                     if fname is NULL.
2440///
2441/// @return [allocated] - A new filename, made up from:
2442///                       * fname + ext, if fname not NULL.
2443///                       * current dir + ext, if fname is NULL.
2444///                       Result is guaranteed to:
2445///                       * be ended by <ext>.
2446///                       * have a basename with at most BASENAMELEN chars:
2447///                         original basename is truncated if necessary.
2448///                       * be different than original: basename chars are
2449///                         replaced by "_" if necessary. If that can't be done
2450///                         because truncated value of original filename was
2451///                         made of all underscores, replace first "_" by "v".
2452///                     - NULL, if fname is NULL and there was a problem trying
2453///                       to get current directory.
2454char *modname(const char *fname, const char *ext, bool prepend_dot)
2455  FUNC_ATTR_NONNULL_ARG(2)
2456{
2457  char *retval;
2458  size_t fnamelen;
2459  size_t extlen = strlen(ext);
2460
2461  // If there is no file name we must get the name of the current directory
2462  // (we need the full path in case :cd is used).
2463  if (fname == NULL || *fname == NUL) {
2464    retval = xmalloc(MAXPATHL + extlen + 3);  // +3 for PATHSEP, "_" (Win), NUL
2465    if (os_dirname(retval, MAXPATHL) == FAIL
2466        || strlen(retval) == 0) {
2467      xfree(retval);
2468      return NULL;
2469    }
2470    add_pathsep(retval);
2471    fnamelen = strlen(retval);
2472    prepend_dot = false;  // nothing to prepend a dot to
2473  } else {
2474    fnamelen = strlen(fname);
2475    retval = xmalloc(fnamelen + extlen + 3);
2476    strcpy(retval, fname);  // NOLINT(runtime/printf)
2477  }
2478
2479  // Search backwards until we hit a '/', '\' or ':'.
2480  // Then truncate what is after the '/', '\' or ':' to BASENAMELEN characters.
2481  char *ptr = NULL;
2482  for (ptr = retval + fnamelen; ptr > retval; MB_PTR_BACK(retval, ptr)) {
2483    if (vim_ispathsep(*ptr)) {
2484      ptr++;
2485      break;
2486    }
2487  }
2488
2489  // the file name has at most BASENAMELEN characters.
2490  size_t ptrlen = fnamelen - (size_t)(ptr - retval);
2491  if (ptrlen > (unsigned)BASENAMELEN) {
2492    ptrlen = BASENAMELEN;
2493    ptr[ptrlen] = NUL;
2494  }
2495
2496  char *s = ptr + ptrlen;
2497
2498  // Append the extension.
2499  // ext can start with '.' and cannot exceed 3 more characters.
2500  strcpy(s, ext);  // NOLINT(runtime/printf)
2501
2502  char *e;
2503  // Prepend the dot if needed.
2504  if (prepend_dot && *(e = path_tail(retval)) != '.') {
2505    memmove(e + 1, e, ((fnamelen + extlen) - (size_t)(e - retval)) + 1);  // +1 for NUL
2506    *e = '.';
2507  }
2508
2509  // Check that, after appending the extension, the file name is really
2510  // different.
2511  if (fname != NULL && strcmp(fname, retval) == 0) {
2512    // we search for a character that can be replaced by '_'
2513    while (--s >= ptr) {
2514      if (*s != '_') {
2515        *s = '_';
2516        break;
2517      }
2518    }
2519    if (s < ptr) {  // fname was "________.<ext>", how tricky!
2520      *ptr = 'v';
2521    }
2522  }
2523  return retval;
2524}
2525
2526/// Like fgets(), but if the file line is too long, it is truncated and the
2527/// rest of the line is thrown away.
2528///
2529/// @param[out] buf buffer to fill
2530/// @param size size of the buffer
2531/// @param fp file to read from
2532///
2533/// @return true for EOF or error
2534bool vim_fgets(char *buf, int size, FILE *fp)
2535  FUNC_ATTR_NONNULL_ALL
2536{
2537  char *retval;
2538
2539  // safety check
2540  if (size < 2) {
2541    if (size == 1) {
2542      buf[0] = NUL;
2543    }
2544    return true;
2545  }
2546
2547  buf[size - 2] = NUL;
2548
2549  do {
2550    errno = 0;
2551    retval = fgets(buf, size, fp);
2552  } while (retval == NULL && errno == EINTR && ferror(fp));
2553
2554  if (buf[size - 2] != NUL && buf[size - 2] != '\n') {
2555    char tbuf[200];
2556
2557    buf[size - 1] = NUL;  // Truncate the line.
2558
2559    // Now throw away the rest of the line:
2560    do {
2561      tbuf[sizeof(tbuf) - 2] = NUL;
2562      errno = 0;
2563      retval = fgets(tbuf, sizeof(tbuf), fp);
2564      if (retval == NULL && (feof(fp) || errno != EINTR)) {
2565        break;
2566      }
2567    } while (tbuf[sizeof(tbuf) - 2] != NUL && tbuf[sizeof(tbuf) - 2] != '\n');
2568  }
2569  return retval == NULL;
2570}
2571
2572/// Read 2 bytes from "fd" and turn them into an int, MSB first.
2573///
2574/// @return  -1 when encountering EOF.
2575int get2c(FILE *fd)
2576{
2577  const int n = getc(fd);
2578  if (n == EOF) {
2579    return -1;
2580  }
2581  const int c = getc(fd);
2582  if (c == EOF) {
2583    return -1;
2584  }
2585  return (n << 8) + c;
2586}
2587
2588/// Read 3 bytes from "fd" and turn them into an int, MSB first.
2589///
2590/// @return  -1 when encountering EOF.
2591int get3c(FILE *fd)
2592{
2593  int n = getc(fd);
2594  if (n == EOF) {
2595    return -1;
2596  }
2597  int c = getc(fd);
2598  if (c == EOF) {
2599    return -1;
2600  }
2601  n = (n << 8) + c;
2602  c = getc(fd);
2603  if (c == EOF) {
2604    return -1;
2605  }
2606  return (n << 8) + c;
2607}
2608
2609/// Read 4 bytes from "fd" and turn them into an int, MSB first.
2610///
2611/// @return  -1 when encountering EOF.
2612int get4c(FILE *fd)
2613{
2614  // Use unsigned rather than int otherwise result is undefined
2615  // when left-shift sets the MSB.
2616  unsigned n;
2617
2618  int c = getc(fd);
2619  if (c == EOF) {
2620    return -1;
2621  }
2622  n = (unsigned)c;
2623  c = getc(fd);
2624  if (c == EOF) {
2625    return -1;
2626  }
2627  n = (n << 8) + (unsigned)c;
2628  c = getc(fd);
2629  if (c == EOF) {
2630    return -1;
2631  }
2632  n = (n << 8) + (unsigned)c;
2633  c = getc(fd);
2634  if (c == EOF) {
2635    return -1;
2636  }
2637  n = (n << 8) + (unsigned)c;
2638  return (int)n;
2639}
2640
2641/// Read 8 bytes from `fd` and turn them into a time_t, MSB first.
2642///
2643/// @return  -1 when encountering EOF.
2644time_t get8ctime(FILE *fd)
2645{
2646  time_t n = 0;
2647
2648  for (int i = 0; i < 8; i++) {
2649    const int c = getc(fd);
2650    if (c == EOF) {
2651      return -1;
2652    }
2653    n = (n << 8) + c;
2654  }
2655  return n;
2656}
2657
2658/// Reads a string of length "cnt" from "fd" into allocated memory.
2659///
2660/// @return  pointer to the string or NULL when unable to read that many bytes.
2661char *read_string(FILE *fd, size_t cnt)
2662{
2663  char *str = xmallocz(cnt);
2664  for (size_t i = 0; i < cnt; i++) {
2665    int c = getc(fd);
2666    if (c == EOF) {
2667      xfree(str);
2668      return NULL;
2669    }
2670    str[i] = (char)c;
2671  }
2672  return str;
2673}
2674
2675/// Writes a number to file "fd", most significant bit first, in "len" bytes.
2676///
2677/// @return  false in case of an error.
2678bool put_bytes(FILE *fd, uintmax_t number, size_t len)
2679{
2680  assert(len > 0);
2681  for (size_t i = len - 1; i < len; i--) {
2682    if (putc((int)(number >> (i * 8)), fd) == EOF) {
2683      return false;
2684    }
2685  }
2686  return true;
2687}
2688
2689/// Writes time_t to file "fd" in 8 bytes.
2690///
2691/// @return  FAIL when the write failed.
2692int put_time(FILE *fd, time_t time_)
2693{
2694  uint8_t buf[8];
2695  time_to_bytes(time_, buf);
2696  return fwrite(buf, sizeof(uint8_t), ARRAY_SIZE(buf), fd) == 1 ? OK : FAIL;
2697}
2698
2699static int rename_with_tmp(const char *const from, const char *const to)
2700{
2701  // Find a name that doesn't exist and is in the same directory.
2702  // Rename "from" to "tempname" and then rename "tempname" to "to".
2703  if (strlen(from) >= MAXPATHL - 5) {
2704    return -1;
2705  }
2706
2707  char tempname[MAXPATHL + 1];
2708  STRCPY(tempname, from);
2709  for (int n = 123; n < 99999; n++) {
2710    char *tail = path_tail(tempname);
2711    snprintf(tail, (size_t)((MAXPATHL + 1) - (tail - tempname)), "%d", n);
2712
2713    if (!os_path_exists(tempname)) {
2714      if (os_rename(from, tempname) == OK) {
2715        if (os_rename(tempname, to) == OK) {
2716          return 0;
2717        }
2718        // Strange, the second step failed.  Try moving the
2719        // file back and return failure.
2720        os_rename(tempname, from);
2721        return -1;
2722      }
2723      // If it fails for one temp name it will most likely fail
2724      // for any temp name, give up.
2725      return -1;
2726    }
2727  }
2728  return -1;
2729}
2730
2731/// os_rename() only works if both files are on the same file system, this
2732/// function will (attempts to?) copy the file across if rename fails -- webb
2733///
2734/// @return  -1 for failure, 0 for success
2735int vim_rename(const char *from, const char *to)
2736  FUNC_ATTR_NONNULL_ALL
2737{
2738  bool use_tmp_file = false;
2739
2740  // When the names are identical, there is nothing to do.  When they refer
2741  // to the same file (ignoring case and slash/backslash differences) but
2742  // the file name differs we need to go through a temp file.
2743  if (path_equal(from, to, kPathCmpLiteral)) {
2744    if (p_fic && (strcmp(path_tail(from), path_tail(to)) != 0)) {
2745      use_tmp_file = true;
2746    } else {
2747      return 0;
2748    }
2749  }
2750
2751  // Fail if the "from" file doesn't exist. Avoids that "to" is deleted.
2752  FileInfo from_info;
2753  if (!os_fileinfo(from, &from_info)) {
2754    return -1;
2755  }
2756
2757  // It's possible for the source and destination to be the same file.
2758  // This happens when "from" and "to" differ in case and are on a FAT32
2759  // filesystem. In that case go through a temp file name.
2760  FileInfo to_info;
2761  if (os_fileinfo(to, &to_info) && os_fileinfo_id_equal(&from_info,  &to_info)) {
2762    use_tmp_file = true;
2763  }
2764
2765  if (use_tmp_file) {
2766    return rename_with_tmp(from, to);
2767  }
2768
2769  // First try a normal rename without removing "to".
2770  if (os_rename(from, to) == OK) {
2771    return 0;
2772  }
2773
2774  // Retry after removing "to", e.g. when renaming a directory over a file.
2775  if (os_remove(to) == 0 && os_rename(from, to) == OK) {
2776    return 0;
2777  }
2778
2779  // Rename() failed, try copying the file.
2780  int ret = vim_copyfile(from, to);
2781  if (ret != OK) {
2782    return -1;
2783  }
2784
2785  if (os_fileinfo(from, &from_info)) {
2786    os_remove(from);
2787  }
2788
2789  return 0;
2790}
2791
2792/// Create the new file with same permissions as the original.
2793/// Return FAIL for failure, OK for success.
2794int vim_copyfile(const char *from, const char *to)
2795{
2796  char *errmsg = NULL;
2797
2798#ifdef HAVE_READLINK
2799  FileInfo from_info;
2800  if (os_fileinfo_link(from, &from_info) && S_ISLNK(from_info.stat.st_mode)) {
2801    int ret = -1;
2802
2803    char linkbuf[MAXPATHL + 1];
2804    ssize_t len = readlink(from, linkbuf, MAXPATHL);
2805    if (len > 0) {
2806      linkbuf[len] = NUL;
2807
2808      // Create link
2809      ret = symlink(linkbuf, to);
2810    }
2811
2812    return ret == 0 ? OK : FAIL;
2813  }
2814#endif
2815
2816  // For systems that support ACL: get the ACL from the original file.
2817  vim_acl_T acl = os_get_acl(from);
2818
2819  if (os_copy(from, to, UV_FS_COPYFILE_EXCL) != 0) {
2820    os_free_acl(acl);
2821    return FAIL;
2822  }
2823
2824  os_set_acl(to, acl);
2825  os_free_acl(acl);
2826  if (errmsg != NULL) {
2827    semsg(errmsg, to);
2828    return FAIL;
2829  }
2830  return OK;
2831}
2832
2833static bool already_warned = false;
2834
2835/// Check if any not hidden buffer has been changed.
2836/// Postpone the check if there are characters in the stuff buffer, a global
2837/// command is being executed, a mapping is being executed or an autocommand is
2838/// busy.
2839///
2840/// @param focus  called for GUI focus event
2841///
2842/// @return       true if some message was written (screen should be redrawn and cursor positioned).
2843int check_timestamps(int focus)
2844{
2845  // Don't check timestamps while system() or another low-level function may
2846  // cause us to lose and gain focus.
2847  if (no_check_timestamps > 0) {
2848    return false;
2849  }
2850
2851  // Avoid doing a check twice.  The OK/Reload dialog can cause a focus
2852  // event and we would keep on checking if the file is steadily growing.
2853  // Do check again after typing something.
2854  if (focus && did_check_timestamps) {
2855    need_check_timestamps = true;
2856    return false;
2857  }
2858
2859  int didit = 0;
2860
2861  if (!stuff_empty() || global_busy || !typebuf_typed()
2862      || autocmd_busy || curbuf->b_ro_locked > 0
2863      || allbuf_lock > 0) {
2864    need_check_timestamps = true;               // check later
2865  } else {
2866    no_wait_return++;
2867    did_check_timestamps = true;
2868    already_warned = false;
2869    FOR_ALL_BUFFERS(buf) {
2870      // Only check buffers in a window.
2871      if (buf->b_nwindows > 0) {
2872        bufref_T bufref;
2873        set_bufref(&bufref, buf);
2874        const int n = buf_check_timestamp(buf);
2875        didit = MAX(didit, n);
2876        if (n > 0 && !bufref_valid(&bufref)) {
2877          // Autocommands have removed the buffer, start at the first one again.
2878          buf = firstbuf;
2879          continue;
2880        }
2881      }
2882    }
2883    no_wait_return--;
2884    need_check_timestamps = false;
2885    if (need_wait_return && didit == 2) {
2886      // make sure msg isn't overwritten
2887      msg_puts("\n");
2888      ui_flush();
2889    }
2890  }
2891  return didit;
2892}
2893
2894/// Move all the lines from buffer "frombuf" to buffer "tobuf".
2895///
2896/// @return  OK or FAIL.
2897///          When FAIL "tobuf" is incomplete and/or "frombuf" is not empty.
2898static int move_lines(buf_T *frombuf, buf_T *tobuf)
2899{
2900  buf_T *tbuf = curbuf;
2901  int retval = OK;
2902
2903  // Copy the lines in "frombuf" to "tobuf".
2904  curbuf = tobuf;
2905  for (linenr_T lnum = 1; lnum <= frombuf->b_ml.ml_line_count; lnum++) {
2906    char *p = xmemdupz(ml_get_buf(frombuf, lnum), (size_t)ml_get_buf_len(frombuf, lnum));
2907    if (ml_append(lnum - 1, p, 0, false) == FAIL) {
2908      xfree(p);
2909      retval = FAIL;
2910      break;
2911    }
2912    xfree(p);
2913  }
2914
2915  // Delete all the lines in "frombuf".
2916  if (retval != FAIL) {
2917    curbuf = frombuf;
2918    for (linenr_T lnum = curbuf->b_ml.ml_line_count; lnum > 0; lnum--) {
2919      if (ml_delete(lnum) == FAIL) {
2920        // Oops!  We could try putting back the saved lines, but that
2921        // might fail again...
2922        retval = FAIL;
2923        break;
2924      }
2925    }
2926  }
2927
2928  curbuf = tbuf;
2929  return retval;
2930}
2931
2932/// Check if buffer "buf" has been changed.
2933/// Also check if the file for a new buffer unexpectedly appeared.
2934///
2935/// @return  1 if a changed buffer was found or,
2936///          2 if a message has been displayed or,
2937///          0 otherwise.
2938int buf_check_timestamp(buf_T *buf)
2939  FUNC_ATTR_NONNULL_ALL
2940{
2941  int retval = 0;
2942  char *mesg = NULL;
2943  char *mesg2 = "";
2944  bool helpmesg = false;
2945
2946  enum {
2947    RELOAD_NONE,
2948    RELOAD_NORMAL,
2949    RELOAD_DETECT,
2950  } reload = RELOAD_NONE;
2951
2952  bool can_reload = false;
2953  uint64_t orig_size = buf->b_orig_size;
2954  int orig_mode = buf->b_orig_mode;
2955  static bool busy = false;
2956
2957  bufref_T bufref;
2958  set_bufref(&bufref, buf);
2959
2960  // If its a terminal, there is no file name, the buffer is not loaded,
2961  // 'buftype' is set, we are in the middle of a save or being called
2962  // recursively: ignore this buffer.
2963  if (buf->terminal
2964      || buf->b_ffname == NULL
2965      || buf->b_ml.ml_mfp == NULL
2966      || !bt_normal(buf)
2967      || buf->b_saving
2968      || busy) {
2969    return 0;
2970  }
2971
2972  FileInfo file_info;
2973  bool file_info_ok;
2974  if (!(buf->b_flags & BF_NOTEDITED)
2975      && buf->b_mtime != 0
2976      && (!(file_info_ok = os_fileinfo(buf->b_ffname, &file_info))
2977          || time_differs(&file_info, buf->b_mtime, buf->b_mtime_ns)
2978          || (int)file_info.stat.st_mode != buf->b_orig_mode)) {
2979    const int64_t prev_b_mtime = buf->b_mtime;
2980
2981    retval = 1;
2982
2983    // set b_mtime to stop further warnings (e.g., when executing
2984    // FileChangedShell autocmd)
2985    if (!file_info_ok) {
2986      // Check the file again later to see if it re-appears.
2987      buf->b_mtime = -1;
2988      buf->b_orig_size = 0;
2989      buf->b_orig_mode = 0;
2990    } else {
2991      buf_store_file_info(buf, &file_info);
2992    }
2993
2994    if (os_isdir(buf->b_fname)) {
2995      // Don't do anything for a directory.  Might contain the file explorer.
2996    } else if ((buf->b_p_ar >= 0 ? buf->b_p_ar : p_ar)
2997               && !bufIsChanged(buf) && file_info_ok) {
2998      // If 'autoread' is set, the buffer has no changes and the file still
2999      // exists, reload the buffer.  Use the buffer-local option value if it
3000      // was set, the global option value otherwise.
3001      reload = RELOAD_NORMAL;
3002    } else {
3003      char *reason;
3004      size_t reasonlen;
3005
3006      if (!file_info_ok) {
3007        reason = "deleted";
3008        reasonlen = STRLEN_LITERAL("deleted");
3009      } else if (bufIsChanged(buf)) {
3010        reason = "conflict";
3011        reasonlen = STRLEN_LITERAL("conflict");
3012      } else if (orig_size != buf->b_orig_size || buf_contents_changed(buf)) {
3013        reason = "changed";
3014        reasonlen = STRLEN_LITERAL("changed");
3015      } else if (orig_mode != buf->b_orig_mode) {
3016        reason = "mode";
3017        reasonlen = STRLEN_LITERAL("mode");
3018      } else {
3019        reason = "time";
3020        reasonlen = STRLEN_LITERAL("time");
3021      }
3022
3023      // Only give the warning if there are no FileChangedShell
3024      // autocommands.
3025      // Avoid being called recursively by setting "busy".
3026      busy = true;
3027      set_vim_var_string(VV_FCS_REASON, reason, (int)reasonlen);
3028      set_vim_var_string(VV_FCS_CHOICE, "", 0);
3029      allbuf_lock++;
3030      bool n = apply_autocmds(EVENT_FILECHANGEDSHELL, buf->b_fname, buf->b_fname, false, buf);
3031      allbuf_lock--;
3032      busy = false;
3033      if (n) {
3034        if (!bufref_valid(&bufref)) {
3035          emsg(_("E246: FileChangedShell autocommand deleted buffer"));
3036        }
3037        char *s = get_vim_var_str(VV_FCS_CHOICE);
3038        if (strcmp(s, "reload") == 0 && *reason != 'd') {
3039          reload = RELOAD_NORMAL;
3040        } else if (strcmp(s, "edit") == 0) {
3041          reload = RELOAD_DETECT;
3042        } else if (strcmp(s, "ask") == 0) {
3043          n = false;
3044        } else {
3045          return 2;
3046        }
3047      }
3048      if (!n) {
3049        if (*reason == 'd') {
3050          // Only give the message once.
3051          if (prev_b_mtime != -1) {
3052            mesg = _("E211: File \"%s\" no longer available");
3053          }
3054        } else {
3055          helpmesg = true;
3056          can_reload = true;
3057
3058          // Check if the file contents really changed to avoid
3059          // giving a warning when only the timestamp was set (e.g.,
3060          // checked out of CVS).  Always warn when the buffer was
3061          // changed.
3062          if (reason[2] == 'n') {
3063            mesg =
3064              _("W12: Warning: File \"%s\" has changed and the buffer was changed in Vim as well");
3065            mesg2 = _("See \":help W12\" for more info.");
3066          } else if (reason[1] == 'h') {
3067            mesg = _("W11: Warning: File \"%s\" has changed since editing started");
3068            mesg2 = _("See \":help W11\" for more info.");
3069          } else if (*reason == 'm') {
3070            mesg = _("W16: Warning: Mode of file \"%s\" has changed since editing started");
3071            mesg2 = _("See \":help W16\" for more info.");
3072          } else {
3073            // Only timestamp changed, store it to avoid a warning
3074            // in check_mtime() later.
3075            buf->b_mtime_read = buf->b_mtime;
3076            buf->b_mtime_read_ns = buf->b_mtime_ns;
3077          }
3078        }
3079      }
3080    }
3081  } else if ((buf->b_flags & BF_NEW) && !(buf->b_flags & BF_NEW_W)
3082             && os_path_exists(buf->b_ffname)) {
3083    retval = 1;
3084    mesg = _("W13: Warning: File \"%s\" has been created after editing started");
3085    buf->b_flags |= BF_NEW_W;
3086    can_reload = true;
3087  }
3088
3089  if (mesg != NULL) {
3090    char *path = home_replace_save(buf, buf->b_fname);
3091    if (!helpmesg) {
3092      mesg2 = "";
3093    }
3094    // +2 for either '\n' or "; " and +1 for NUL
3095    const size_t tbufsize = strlen(path) + strlen(mesg) + strlen(mesg2) + 3;
3096    char *const tbuf = xmalloc(tbufsize);
3097    int tbuflen = snprintf(tbuf, tbufsize, mesg, path);
3098    // Set warningmsg here, before the unimportant and output-specific
3099    // mesg2 has been appended.
3100    set_vim_var_string(VV_WARNINGMSG, tbuf, tbuflen);
3101    if (can_reload) {
3102      if (*mesg2 != NUL) {
3103        snprintf(tbuf + tbuflen, tbufsize - (size_t)tbuflen, "\n%s", mesg2);
3104      }
3105      switch (do_dialog(VIM_WARNING, _("Warning"), tbuf,
3106                        _("&OK\n&Load File\nLoad File &and Options"),
3107                        1, NULL, true)) {
3108      case 2:
3109        reload = RELOAD_NORMAL;
3110        break;
3111      case 3:
3112        reload = RELOAD_DETECT;
3113        break;
3114      }
3115    } else if (State > MODE_NORMAL_BUSY || (State & MODE_CMDLINE) || already_warned) {
3116      if (*mesg2 != NUL) {
3117        snprintf(tbuf + tbuflen, tbufsize - (size_t)tbuflen, "; %s", mesg2);
3118      }
3119      emsg(tbuf);
3120      retval = 2;
3121    } else {
3122      if (!autocmd_busy) {
3123        msg_start();
3124        msg_puts_hl(tbuf, HLF_E, true);
3125        if (*mesg2 != NUL) {
3126          msg_puts_hl(mesg2, HLF_W, true);
3127        }
3128        msg_clr_eos();
3129        msg_end();
3130        if (emsg_silent == 0 && !in_assert_fails && !ui_has(kUIMessages)) {
3131          msg_delay(1004, true);  // give the user some time to think about it
3132          redraw_cmdline = false;  // don't redraw and erase the message
3133        }
3134      }
3135      already_warned = true;
3136    }
3137
3138    xfree(tbuf);
3139    xfree(path);
3140  }
3141
3142  if (reload != RELOAD_NONE) {
3143    // Reload the buffer.
3144    buf_reload(buf, orig_mode, reload == RELOAD_DETECT);
3145    if (bufref_valid(&bufref) && buf->b_p_udf && buf->b_ffname != NULL) {
3146      uint8_t hash[UNDO_HASH_SIZE];
3147
3148      // Any existing undo file is unusable, write it now.
3149      u_compute_hash(buf, hash);
3150      u_write_undo(NULL, false, buf, hash);
3151    }
3152  }
3153
3154  // Trigger FileChangedShell when the file was changed in any way.
3155  if (bufref_valid(&bufref) && retval != 0) {
3156    apply_autocmds(EVENT_FILECHANGEDSHELLPOST, buf->b_fname, buf->b_fname, false, buf);
3157  }
3158  return retval;
3159}
3160
3161/// Reload a buffer that is already loaded.
3162/// Used when the file was changed outside of Vim.
3163/// "orig_mode" is buf->b_orig_mode before the need for reloading was detected.
3164/// buf->b_orig_mode may have been reset already.
3165void buf_reload(buf_T *buf, int orig_mode, bool reload_options)
3166{
3167  exarg_T ea;
3168  int old_ro = buf->b_p_ro;
3169  buf_T *savebuf;
3170  bufref_T bufref;
3171  int saved = OK;
3172  CtxSwitch aco = { 0 };
3173  int flags = READ_NEW;
3174
3175  // Set curwin/curbuf for "buf" and save some things.
3176  ctx_switch(&aco, NULL, NULL, buf, 0);
3177
3178  mc_buf_clear(buf);  // Multicursor: file-reload invalidates the extmarks.
3179
3180  // Unless reload_options is set, we only want to read the text from the
3181  // file, not reset the syntax highlighting, clear marks, diff status, etc.
3182  // Force the fileformat and encoding to be the same.
3183  if (reload_options) {
3184    CLEAR_FIELD(ea);
3185  } else {
3186    prep_exarg(&ea, buf);
3187  }
3188
3189  pos_T old_cursor = curwin->w_cursor;
3190  linenr_T old_topline = curwin->w_topline;
3191
3192  if (p_ur < 0 || curbuf->b_ml.ml_line_count <= p_ur) {
3193    // Save all the text, so that the reload can be undone.
3194    // Sync first so that this is a separate undo-able action.
3195    u_sync(false);
3196    saved = u_savecommon(curbuf, 0, curbuf->b_ml.ml_line_count + 1, 0, true);
3197    flags |= READ_KEEP_UNDO;
3198  }
3199
3200  // To behave like when a new file is edited (matters for
3201  // BufReadPost autocommands) we first need to delete the current
3202  // buffer contents.  But if reading the file fails we should keep
3203  // the old contents.  Can't use memory only, the file might be
3204  // too big.  Use a hidden buffer to move the buffer contents to.
3205  if (buf_is_empty(curbuf) || saved == FAIL) {
3206    savebuf = NULL;
3207  } else {
3208    // Allocate a buffer without putting it in the buffer list.
3209    savebuf = buflist_new(NULL, NULL, 1, BLN_DUMMY);
3210    set_bufref(&bufref, savebuf);
3211    if (savebuf != NULL && buf == curbuf) {
3212      // Open the memline.
3213      curbuf = savebuf;
3214      curwin->w_buffer = savebuf;
3215      saved = ml_open(curbuf);
3216      curbuf = buf;
3217      curwin->w_buffer = buf;
3218    }
3219    if (savebuf == NULL || saved == FAIL || buf != curbuf
3220        || move_lines(buf, savebuf) == FAIL) {
3221      semsg(_("E462: Could not prepare for reloading \"%s\""),
3222            buf->b_fname);
3223      saved = FAIL;
3224    }
3225  }
3226
3227  if (saved == OK) {
3228    curbuf->b_flags |= BF_CHECK_RO;           // check for RO again
3229    curbuf->b_keep_filetype = true;           // don't detect 'filetype'
3230    if (readfile(buf->b_ffname, buf->b_fname, 0, 0,
3231                 (linenr_T)MAXLNUM, &ea, flags, shortmess(kShmFileinfo)) != OK) {
3232      if (!aborting()) {
3233        semsg(_("E321: Could not reload \"%s\""), buf->b_fname);
3234      }
3235      if (savebuf != NULL && bufref_valid(&bufref) && buf == curbuf) {
3236        // Put the text back from the save buffer.  First
3237        // delete any lines that readfile() added.
3238        while (!buf_is_empty(curbuf)) {
3239          if (ml_delete(buf->b_ml.ml_line_count) == FAIL) {
3240            break;
3241          }
3242        }
3243        move_lines(savebuf, buf);
3244      }
3245    } else if (buf == curbuf) {  // "buf" still valid.
3246      // Mark the buffer as unmodified and free undo info.
3247      unchanged(buf, true, true);
3248      if ((flags & READ_KEEP_UNDO) == 0) {
3249        u_clearallandblockfree(buf);
3250      } else {
3251        // Mark all undo states as changed.
3252        u_unchanged(curbuf);
3253      }
3254      buf_updates_unload(curbuf, true);
3255      curbuf->b_mod_set = true;
3256    }
3257  }
3258  xfree(ea.cmd);
3259
3260  if (savebuf != NULL && bufref_valid(&bufref)) {
3261    wipe_buffer(savebuf, false);
3262  }
3263
3264  // Invalidate diff info if necessary.
3265  diff_invalidate(curbuf);
3266
3267  // Restore the topline and cursor position and check it (lines may
3268  // have been removed).
3269  curwin->w_topline = MIN(old_topline, curbuf->b_ml.ml_line_count);
3270  curwin->w_cursor = old_cursor;
3271  check_cursor(curwin);
3272  update_topline(curwin);
3273  curbuf->b_keep_filetype = false;
3274
3275  // Update folds unless they are defined manually.
3276  FOR_ALL_TAB_WINDOWS(tp, wp) {
3277    if (wp->w_buffer == curwin->w_buffer
3278        && !foldmethodIsManual(wp)) {
3279      foldUpdateAll(wp);
3280    }
3281  }
3282
3283  // If the mode didn't change and 'readonly' was set, keep the old
3284  // value; the user probably used the ":view" command.  But don't
3285  // reset it, might have had a read error.
3286  if (orig_mode == curbuf->b_orig_mode) {
3287    curbuf->b_p_ro |= old_ro;
3288  }
3289
3290  // Modelines must override settings done by autocommands.
3291  do_modelines(0);
3292
3293  // restore curwin/curbuf and a few other things
3294  ctx_restore(&aco);
3295  // Careful: autocommands may have made "buf" invalid!
3296}
3297
3298void buf_store_file_info(buf_T *buf, FileInfo *file_info)
3299  FUNC_ATTR_NONNULL_ALL
3300{
3301  buf->b_mtime = file_info->stat.st_mtim.tv_sec;
3302  buf->b_mtime_ns = file_info->stat.st_mtim.tv_nsec;
3303  buf->b_orig_size = os_fileinfo_size(file_info);
3304  buf->b_orig_mode = (int)file_info->stat.st_mode;
3305}
3306
3307/// Adjust the line with missing eol, used for the next write.
3308/// Used for do_filter(), when the input lines for the filter are deleted.
3309void write_lnum_adjust(linenr_T offset)
3310{
3311  if (curbuf->b_no_eol_lnum != 0) {     // only if there is a missing eol
3312    curbuf->b_no_eol_lnum += offset;
3313  }
3314}
3315
3316/// Path to Nvim's own temp dir. Ends in a slash.
3317static char *vim_tempdir = NULL;
3318#ifdef HAVE_DIRFD_AND_FLOCK
3319static DIR *vim_tempdir_dp = NULL;  ///< File descriptor of temp dir
3320#endif
3321
3322/// Creates a directory for private use by this instance of Nvim, trying each of
3323/// `TEMP_DIR_NAMES` until one succeeds.
3324///
3325/// Only done once, the same directory is used for all temp files.
3326/// This method avoids security problems because of symlink attacks et al.
3327/// It's also a bit faster, because we only need to check for an existing
3328/// file when creating the directory and not for each temp file.
3329static void vim_mktempdir(void)
3330{
3331  static const char *temp_dirs[] = TEMP_DIR_NAMES;  // Try each of these until one succeeds.
3332  char tmp[TEMP_FILE_PATH_MAXLEN];
3333  char path[TEMP_FILE_PATH_MAXLEN];
3334  char user[40] = { 0 };
3335
3336  os_get_username(user, sizeof(user));
3337  // Usernames may contain slashes! #19240
3338  memchrsub(user, '/', '_', sizeof(user));
3339  memchrsub(user, '\\', '_', sizeof(user));
3340
3341  // Make sure the umask doesn't remove the executable bit.
3342  // "repl" has been reported to use "0177".
3343  mode_t umask_save = umask(0077);
3344  for (size_t i = 0; i < ARRAY_SIZE(temp_dirs); i++) {
3345    // Expand environment variables, leave room for "/tmp/nvim.<user>/XXXXXX/999999999".
3346    size_t tmplen = expand_env((char *)temp_dirs[i], tmp, TEMP_FILE_PATH_MAXLEN - 64);
3347    if (!os_isdir(tmp)) {
3348      if (strequal("$TMPDIR", temp_dirs[i])) {
3349        if (!os_env_exists("TMPDIR", true)) {
3350          DLOG("$TMPDIR is unset");
3351        } else {
3352          WLOG("$TMPDIR tempdir not a directory (or does not exist): \"%s\"", tmp);
3353        }
3354      }
3355      continue;
3356    }
3357
3358    // "/tmp/" exists, now try to create "/tmp/nvim.<user>/".
3359    if (!after_pathsep(tmp, tmp + tmplen)) {
3360      tmplen += (size_t)vim_snprintf(tmp + tmplen, sizeof(tmp) - tmplen, PATHSEPSTR);
3361      assert(tmplen < sizeof(tmp));
3362    }
3363    tmplen += (size_t)vim_snprintf(tmp + tmplen, sizeof(tmp) - tmplen,
3364                                   "nvim.%s", user);
3365    assert(tmplen < sizeof(tmp));
3366    os_mkdir(tmp, 0700);  // Always create, to avoid a race.
3367    bool owned = os_file_owned(tmp);
3368    bool isdir = os_isdir(tmp);
3369#ifdef UNIX
3370    int perm = os_getperm(tmp);  // XDG_RUNTIME_DIR must be owned by the user, mode 0700.
3371    bool valid = isdir && owned && 0700 == (perm & 0777);
3372#else
3373    bool valid = isdir && owned;  // TODO(justinmk): Windows ACL?
3374#endif
3375    if (valid) {
3376      if (!after_pathsep(tmp, tmp + tmplen)) {
3377        tmplen += (size_t)vim_snprintf(tmp + tmplen, sizeof(tmp) - tmplen, PATHSEPSTR);
3378        assert(tmplen < sizeof(tmp));
3379      }
3380    } else {
3381      if (!owned) {
3382        ELOG("tempdir root not owned by current user (%s): %s", user, tmp);
3383      } else if (!isdir) {
3384        ELOG("tempdir root not a directory: %s", tmp);
3385      }
3386#ifdef UNIX
3387      if (0700 != (perm & 0777)) {
3388        ELOG("tempdir root has invalid permissions (%o): %s", perm, tmp);
3389      }
3390#endif
3391      // If our "root" tempdir is invalid or fails, proceed without "<user>/".
3392      // Else user1 could break user2 by creating "/tmp/nvim.user2/".
3393      tmplen -= strlen(user);
3394      tmp[tmplen] = NUL;
3395    }
3396
3397    // Now try to create "/tmp/nvim.<user>/XXXXXX".
3398    // "XXXXXX" is mkdtemp "template", will be replaced with random alphanumeric chars.
3399    tmplen += (size_t)vim_snprintf(tmp + tmplen, sizeof(tmp) - tmplen, "XXXXXX");
3400    assert(tmplen < sizeof(tmp));
3401    (void)tmplen;
3402    int r = os_mkdtemp(tmp, path);
3403    if (r != 0) {
3404      WLOG("tempdir create failed: %s: %s", os_strerror(r), tmp);
3405      continue;
3406    }
3407
3408    if (vim_settempdir(path)) {
3409      // Successfully created and set temporary directory so stop trying.
3410      break;
3411    }
3412    // Couldn't set `vim_tempdir` to `path` so remove created directory.
3413    os_rmdir(path);
3414  }
3415  umask(umask_save);
3416}
3417
3418/// Core part of "readdir()" function.
3419/// Retrieve the list of files/directories of "path" into "gap".
3420///
3421/// @return  OK for success, FAIL for failure.
3422int readdir_core(garray_T *gap, const char *path, void *context, CheckItem checkitem)
3423  FUNC_ATTR_NONNULL_ARG(1, 2)
3424{
3425  ga_init(gap, (int)sizeof(char *), 20);
3426
3427  Directory dir;
3428  if (!os_scandir(&dir, path)) {
3429    smsg(0, _(e_notopen), path);
3430    return FAIL;
3431  }
3432
3433  while (true) {
3434    const char *p = os_scandir_next(&dir);
3435    if (p == NULL) {
3436      break;
3437    }
3438
3439    bool ignore = (p[0] == '.' && (p[1] == NUL || (p[1] == '.' && p[2] == NUL)));
3440    if (!ignore && checkitem != NULL) {
3441      varnumber_T r = checkitem(context, p);
3442      if (r < 0) {
3443        break;
3444      }
3445      if (r == 0) {
3446        ignore = true;
3447      }
3448    }
3449
3450    if (!ignore) {
3451      ga_grow(gap, 1);
3452      ((char **)gap->ga_data)[gap->ga_len++] = xstrdup(p);
3453    }
3454  }
3455
3456  os_closedir(&dir);
3457
3458  if (gap->ga_len > 0) {
3459    sort_strings(gap->ga_data, gap->ga_len);
3460  }
3461
3462  return OK;
3463}
3464
3465/// Delete "name" and everything in it, recursively.
3466///
3467/// @param name  The path which should be deleted.
3468///
3469/// @return  0 for success, -1 if some file was not deleted.
3470int delete_recursive(const char *name)
3471  FUNC_ATTR_NONNULL_ALL
3472{
3473  int result = 0;
3474
3475  if (os_isrealdir(name)) {
3476    char *exp = xstrdup(name);
3477    garray_T ga;
3478    if (readdir_core(&ga, exp, NULL, NULL) == OK) {
3479      int len = snprintf(NameBuff, MAXPATHL, "%s/", exp);
3480
3481      for (int i = 0; i < ga.ga_len; i++) {
3482        snprintf(NameBuff + len, MAXPATHL - (size_t)len, "%s", ((char **)ga.ga_data)[i]);
3483        if (delete_recursive(NameBuff) != 0) {
3484          // Remember the failure but continue deleting any further
3485          // entries.
3486          result = -1;
3487        }
3488      }
3489      ga_clear_strings(&ga);
3490      if (os_rmdir(exp) != 0) {
3491        result = -1;
3492      }
3493    } else {
3494      result = -1;
3495    }
3496    xfree(exp);
3497  } else {
3498    // Delete symlink only.
3499    result = os_remove(name) == 0 ? 0 : -1;
3500  }
3501
3502  return result;
3503}
3504
3505#ifdef HAVE_DIRFD_AND_FLOCK
3506/// Open temporary directory and take file lock to prevent
3507/// to be auto-cleaned.
3508static void vim_opentempdir(void)
3509{
3510  if (vim_tempdir_dp != NULL) {
3511    return;
3512  }
3513
3514  DIR *dp = opendir(vim_tempdir);
3515  if (dp == NULL) {
3516    return;
3517  }
3518
3519  vim_tempdir_dp = dp;
3520  flock(dirfd(vim_tempdir_dp), LOCK_SH);
3521}
3522
3523/// Close temporary directory - it automatically release file lock.
3524static void vim_closetempdir(void)
3525{
3526  if (vim_tempdir_dp == NULL) {
3527    return;
3528  }
3529
3530  closedir(vim_tempdir_dp);
3531  vim_tempdir_dp = NULL;
3532}
3533#endif
3534
3535/// Delete the temp directory and all files it contains.
3536void vim_deltempdir(void)
3537{
3538  if (vim_tempdir == NULL) {
3539    return;
3540  }
3541
3542#ifdef HAVE_DIRFD_AND_FLOCK
3543  vim_closetempdir();
3544#endif
3545  // remove the trailing path separator
3546  path_tail(vim_tempdir)[-1] = NUL;
3547  delete_recursive(vim_tempdir);
3548  XFREE_CLEAR(vim_tempdir);
3549}
3550
3551/// Gets path to Nvim's own temp dir (ending with slash).
3552///
3553/// Creates the directory on the first call.
3554char *vim_gettempdir(void)
3555{
3556  static int notfound = 0;
3557  if (vim_tempdir == NULL || !os_isdir(vim_tempdir)) {
3558    if (vim_tempdir != NULL) {
3559      notfound++;
3560      if (notfound == 1) {
3561        ELOG("tempdir disappeared (antivirus or broken cleanup job?): %s", vim_tempdir);
3562      }
3563      if (notfound > 1) {
3564        msg_schedule_semsg("E5431: tempdir disappeared (%d times)", notfound);
3565      }
3566      XFREE_CLEAR(vim_tempdir);
3567    }
3568    vim_mktempdir();
3569  }
3570  return vim_tempdir;
3571}
3572
3573/// Sets Nvim's own temporary directory name to `tempdir`. This directory must
3574/// already exist. Expands the name to a full path and put it in `vim_tempdir`.
3575/// This avoids that using `:cd` would confuse us.
3576///
3577/// @param tempdir must be no longer than MAXPATHL.
3578///
3579/// @return false if we run out of memory.
3580static bool vim_settempdir(char *tempdir)
3581{
3582  char *buf = verbose_try_malloc(MAXPATHL + 2);
3583  if (buf == NULL) {
3584    return false;
3585  }
3586
3587  vim_FullName(tempdir, buf, MAXPATHL,
3588#ifdef MSWIN
3589               true
3590#else
3591               false
3592#endif
3593               );
3594
3595  size_t buflen = strlen(buf);
3596  if (!after_pathsep(buf, buf + buflen)) {
3597    strcpy(buf + buflen, PATHSEPSTR);  // NOLINT(runtime/printf)
3598    buflen += STRLEN_LITERAL(PATHSEPSTR);
3599  }
3600  vim_tempdir = xmemdupz(buf, buflen);
3601#ifdef HAVE_DIRFD_AND_FLOCK
3602  vim_opentempdir();
3603#endif
3604  xfree(buf);
3605  return true;
3606}
3607
3608/// Return a unique name that can be used for a temp file.
3609///
3610/// @note The temp file is NOT created.
3611///
3612/// @return  pointer to the temp file name or NULL if Nvim can't create
3613///          temporary directory for its own temporary files.
3614char *vim_tempname(void)
3615{
3616  // Temp filename counter.
3617  static uint64_t temp_count;
3618
3619  char *tempdir = vim_gettempdir();
3620  if (!tempdir) {
3621    return NULL;
3622  }
3623
3624  // There is no need to check if the file exists, because we own the directory
3625  // and nobody else creates a file in it.
3626  char templ[TEMP_FILE_PATH_MAXLEN];
3627  int itmplen = snprintf(templ, TEMP_FILE_PATH_MAXLEN, "%s%" PRIu64, tempdir, temp_count++);
3628  return xmemdupz(templ, (size_t)itmplen);
3629}
3630
3631/// Tries matching a filename with a "pattern" ("prog" is NULL), or use the
3632/// precompiled regprog "prog" ("pattern" is NULL).  That avoids calling
3633/// vim_regcomp() often.
3634///
3635/// Used for autocommands and 'wildignore'.
3636///
3637/// @param pattern pattern to match with
3638/// @param prog pre-compiled regprog or NULL
3639/// @param fname full path of the file name
3640/// @param sfname short file name or NULL
3641/// @param tail tail of the path
3642/// @param allow_dirs Allow matching with dir
3643///
3644/// @return true if there is a match, false otherwise
3645bool match_file_pat(char *pattern, regprog_T **prog, char *fname, char *sfname, char *tail,
3646                    int allow_dirs)
3647{
3648  regmatch_T regmatch;
3649  bool result = false;
3650
3651  regmatch.rm_ic = p_fic;   // ignore case if 'fileignorecase' is set
3652  regmatch.regprog = prog != NULL ? *prog : vim_regcomp(pattern, RE_MAGIC);
3653
3654  // Try for a match with the pattern with:
3655  // 1. the full file name, when the pattern has a '/'.
3656  // 2. the short file name, when the pattern has a '/'.
3657  // 3. the tail of the file name, when the pattern has no '/'.
3658  if (regmatch.regprog != NULL
3659      && ((allow_dirs
3660           && (vim_regexec(&regmatch, fname, 0)
3661               || (sfname != NULL
3662                   && vim_regexec(&regmatch, sfname, 0))))
3663          || (!allow_dirs && vim_regexec(&regmatch, tail, 0)))) {
3664    result = true;
3665  }
3666
3667  if (prog != NULL) {
3668    *prog = regmatch.regprog;
3669  } else {
3670    vim_regfree(regmatch.regprog);
3671  }
3672  return result;
3673}
3674
3675/// Check if a file matches with a pattern in "list".
3676/// "list" is a comma-separated list of patterns, like 'wildignore'.
3677/// "sfname" is the short file name or NULL, "ffname" the long file name.
3678///
3679/// @param list list of patterns to match
3680/// @param sfname short file name
3681/// @param ffname full file name
3682///
3683/// @return true if there was a match
3684bool match_file_list(char *list, char *sfname, char *ffname)
3685  FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ARG(1, 3)
3686{
3687  char *tail = path_tail(sfname);
3688
3689  // try all patterns in 'wildignore'
3690  char *p = list;
3691  while (*p) {
3692    char buf[MAXPATHL];
3693    copy_option_part(&p, buf, ARRAY_SIZE(buf), ",");
3694    char allow_dirs;
3695    char *regpat = file_pat_to_reg_pat(buf, NULL, &allow_dirs, false);
3696    if (regpat == NULL) {
3697      break;
3698    }
3699    bool match = match_file_pat(regpat, NULL, ffname, sfname, tail, (int)allow_dirs);
3700    xfree(regpat);
3701    if (match) {
3702      return true;
3703    }
3704  }
3705  return false;
3706}
3707
3708/// Convert the given pattern "pat" which has shell style wildcards in it, into
3709/// a regular expression, and return the result in allocated memory.  If there
3710/// is a directory path separator to be matched, then true is put in
3711/// allow_dirs, otherwise false is put there -- webb.
3712/// Handle backslashes before special characters, like "\*" and "\ ".
3713///
3714/// @param pat_end     first char after pattern or NULL
3715/// @param allow_dirs  Result passed back out in here
3716/// @param no_bslash   Don't use a backward slash as pathsep
3717///                    (only makes a difference when BACKSLASH_IN_FILENAME in defined)
3718///
3719/// @return            NULL on failure.
3720char *file_pat_to_reg_pat(const char *pat, const char *pat_end, char *allow_dirs, int no_bslash)
3721  FUNC_ATTR_NONNULL_ARG(1)
3722{
3723  if (allow_dirs != NULL) {
3724    *allow_dirs = false;
3725  }
3726
3727  if (pat_end == NULL) {
3728    pat_end = pat + strlen(pat);
3729  }
3730
3731  if (pat_end == pat) {
3732    return xstrdup("^$");
3733  }
3734
3735  size_t size = 2;  // '^' at start, '$' at end.
3736
3737  for (const char *p = pat; p < pat_end; p++) {
3738    switch (*p) {
3739    case '*':
3740    case '.':
3741    case ',':
3742    case '{':
3743    case '}':
3744    case '~':
3745      size += 2;                // extra backslash
3746      break;
3747#ifdef BACKSLASH_IN_FILENAME
3748    case '\\':
3749    case '/':
3750      size += 4;                // could become "[\/]"
3751      break;
3752#endif
3753    default:
3754      size++;
3755      break;
3756    }
3757  }
3758  char *reg_pat = xmalloc(size + 1);
3759
3760  size_t i = 0;
3761
3762  if (pat[0] == '*') {
3763    while (pat[0] == '*' && pat < pat_end - 1) {
3764      pat++;
3765    }
3766  } else {
3767    reg_pat[i++] = '^';
3768  }
3769  const char *endp = pat_end - 1;
3770  bool add_dollar = true;
3771  if (endp >= pat && *endp == '*') {
3772    while (endp - pat > 0 && *endp == '*') {
3773      endp--;
3774    }
3775    add_dollar = false;
3776  }
3777  int nested = 0;
3778  for (const char *p = pat; *p && nested >= 0 && p <= endp; p++) {
3779    switch (*p) {
3780    case '*':
3781      reg_pat[i++] = '.';
3782      reg_pat[i++] = '*';
3783      while (p[1] == '*') {  // "**" matches like "*"
3784        p++;
3785      }
3786      break;
3787    case '.':
3788    case '~':
3789      reg_pat[i++] = '\\';
3790      reg_pat[i++] = *p;
3791      break;
3792    case '?':
3793      reg_pat[i++] = '.';
3794      break;
3795    case '\\':
3796      if (p[1] == NUL) {
3797        break;
3798      }
3799#ifdef BACKSLASH_IN_FILENAME
3800      if (!no_bslash) {
3801        // translate:
3802        // "\x" to "\\x"  e.g., "dir\file"
3803        // "\*" to "\\.*" e.g., "dir\*.c"
3804        // "\?" to "\\."  e.g., "dir\??.c"
3805        // "\+" to "\+"   e.g., "fileX\+.c"
3806        if ((vim_isfilec((uint8_t)p[1]) || p[1] == '*' || p[1] == '?')
3807            && p[1] != '+') {
3808          reg_pat[i++] = '[';
3809          reg_pat[i++] = '\\';
3810          reg_pat[i++] = '/';
3811          reg_pat[i++] = ']';
3812          if (allow_dirs != NULL) {
3813            *allow_dirs = true;
3814          }
3815          break;
3816        }
3817      }
3818#endif
3819      // Undo escaping from ExpandEscape():
3820      // foo\?bar -> foo?bar
3821      // foo\%bar -> foo%bar
3822      // foo\,bar -> foo,bar
3823      // foo\ bar -> foo bar
3824      // Don't unescape \, * and others that are also special in a
3825      // regexp.
3826      // An escaped { must be unescaped since we use magic not
3827      // verymagic.  Use "\\\{n,m\}"" to get "\{n,m}".
3828      if (*++p == '?' && (!BACKSLASH_IN_FILENAME_BOOL || no_bslash)) {
3829        reg_pat[i++] = '?';
3830      } else if (*p == ',' || *p == '%' || *p == '#'
3831                 || ascii_isspace(*p) || *p == '{' || *p == '}') {
3832        reg_pat[i++] = *p;
3833      } else if (*p == '\\' && p[1] == '\\' && p[2] == '{') {
3834        reg_pat[i++] = '\\';
3835        reg_pat[i++] = '{';
3836        p += 2;
3837      } else {
3838        if (allow_dirs != NULL && vim_ispathsep(*p)
3839            && (!BACKSLASH_IN_FILENAME_BOOL || (!no_bslash || *p != '\\'))) {
3840          *allow_dirs = true;
3841        }
3842        reg_pat[i++] = '\\';
3843        reg_pat[i++] = *p;
3844      }
3845      break;
3846#ifdef BACKSLASH_IN_FILENAME
3847    case '/':
3848      reg_pat[i++] = '[';
3849      reg_pat[i++] = '\\';
3850      reg_pat[i++] = '/';
3851      reg_pat[i++] = ']';
3852      if (allow_dirs != NULL) {
3853        *allow_dirs = true;
3854      }
3855      break;
3856#endif
3857    case '{':
3858      reg_pat[i++] = '\\';
3859      reg_pat[i++] = '(';
3860      nested++;
3861      break;
3862    case '}':
3863      reg_pat[i++] = '\\';
3864      reg_pat[i++] = ')';
3865      nested--;
3866      break;
3867    case ',':
3868      if (nested) {
3869        reg_pat[i++] = '\\';
3870        reg_pat[i++] = '|';
3871      } else {
3872        reg_pat[i++] = ',';
3873      }
3874      break;
3875    default:
3876      if (allow_dirs != NULL && vim_ispathsep(*p)) {
3877        *allow_dirs = true;
3878      }
3879      reg_pat[i++] = *p;
3880      break;
3881    }
3882  }
3883  if (add_dollar) {
3884    reg_pat[i++] = '$';
3885  }
3886  reg_pat[i] = NUL;
3887  if (nested != 0) {
3888    if (nested < 0) {
3889      emsg(_("E219: Missing {."));
3890    } else {
3891      emsg(_("E220: Missing }."));
3892    }
3893    XFREE_CLEAR(reg_pat);
3894  }
3895  return reg_pat;
3896}
3897
3898#ifdef EINTR
3899
3900// Type of buffer size argument of read() and write() is platform-dependent.
3901# ifdef MSWIN
3902#  define BUFSIZE(x) (unsigned)(x)
3903# else
3904#  define BUFSIZE(x) (x)
3905# endif
3906
3907/// Version of read() that retries when interrupted by EINTR (possibly
3908/// by a SIGWINCH).
3909ssize_t read_eintr(int fd, void *buf, size_t bufsize)
3910{
3911  ssize_t ret;
3912
3913  while (true) {
3914    ret = read(fd, buf, BUFSIZE(bufsize));
3915    if (ret >= 0 || errno != EINTR) {
3916      break;
3917    }
3918  }
3919  return ret;
3920}
3921
3922/// Version of write() that retries when interrupted by EINTR (possibly
3923/// by a SIGWINCH).
3924ssize_t write_eintr(int fd, void *buf, size_t bufsize)
3925{
3926  ssize_t ret = 0;
3927
3928  // Repeat the write() so long it didn't fail, other than being interrupted
3929  // by a signal.
3930  while ((size_t)ret < bufsize) {
3931    ssize_t wlen = write(fd, (char *)buf + ret, BUFSIZE(bufsize - (size_t)ret));
3932    if (wlen < 0) {
3933      if (errno != EINTR) {
3934        break;
3935      }
3936    } else {
3937      ret += wlen;
3938    }
3939  }
3940  return ret;
3941}
3942
3943# undef BUFSIZE
3944
3945#endif