robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
60.6 KiB1877 linesraw
1// bufwrite.c: functions for writing a buffer
2
3#include <fcntl.h>
4#include <iconv.h>
5#include <inttypes.h>
6#include <stdbool.h>
7#include <stdio.h>
8#include <string.h>
9#include <sys/stat.h>
10#include <uv.h>
11
12#include "auto/config.h"
13#include "nvim/ascii_defs.h"
14#include "nvim/autocmd.h"
15#include "nvim/autocmd_defs.h"
16#include "nvim/buffer.h"
17#include "nvim/buffer_defs.h"
18#include "nvim/bufwrite.h"
19#include "nvim/change.h"
20#include "nvim/context.h"
21#include "nvim/dialog.h"
22#include "nvim/drawscreen.h"
23#include "nvim/errors.h"
24#include "nvim/eval/typval_defs.h"
25#include "nvim/eval/vars.h"
26#include "nvim/ex_cmds.h"
27#include "nvim/ex_cmds_defs.h"
28#include "nvim/ex_eval.h"
29#include "nvim/fileio.h"
30#include "nvim/gettext_defs.h"
31#include "nvim/globals.h"
32#include "nvim/highlight_defs.h"
33#include "nvim/iconv_defs.h"
34#include "nvim/macros_defs.h"
35#include "nvim/mbyte.h"
36#include "nvim/memline.h"
37#include "nvim/memline_defs.h"
38#include "nvim/memory.h"
39#include "nvim/message.h"
40#include "nvim/option.h"
41#include "nvim/option_vars.h"
42#include "nvim/os/fs.h"
43#include "nvim/os/fs_defs.h"
44#include "nvim/os/input.h"
45#include "nvim/os/os_defs.h"
46#include "nvim/path.h"
47#include "nvim/pos_defs.h"
48#include "nvim/sha256.h"
49#include "nvim/strings.h"
50#include "nvim/types_defs.h"
51#include "nvim/ui.h"
52#include "nvim/undo.h"
53#include "nvim/undo_defs.h"
54#include "nvim/vim_defs.h"
55
56static const char *err_readonly = "is read-only (cannot override: \"W\" in 'cpoptions')";
57static const char e_patchmode_cant_touch_empty_original_file[]
58  = N_("E206: Patchmode: can't touch empty original file");
59static const char e_write_error_conversion_failed_make_fenc_empty_to_override[]
60  = N_("E513: Write error, conversion failed (make 'fenc' empty to override)");
61static const char e_write_error_conversion_failed_in_line_nr_make_fenc_empty_to_override[]
62  = N_("E513: Write error, conversion failed in line %" PRIdLINENR
63       " (make 'fenc' empty to override)");
64static const char e_write_error_file_system_full[]
65  = N_("E514: Write error (file system full?)");
66static const char e_no_matching_autocommands_for_buftype_str_buffer[]
67  = N_("E676: No matching autocommands for buftype=%s buffer");
68
69typedef struct {
70  const char *num;
71  char *msg;
72  int arg;
73  bool alloc;
74} Error_T;
75
76#define SMALLBUFSIZE 256     // size of emergency write buffer
77
78// Structure to pass arguments from buf_write() to buf_write_bytes().
79struct bw_info {
80  int bw_fd;                      // file descriptor
81  char *bw_buf;                   // buffer with data to be written
82  int bw_len;                     // length of data
83  int bw_flags;                   // FIO_ flags
84  int bw_first;                   // first write call
85  char *bw_conv_buf;              // buffer for writing converted chars
86  size_t bw_conv_buflen;          // size of bw_conv_buf
87  int bw_conv_error;              // set for conversion error
88  linenr_T bw_conv_error_lnum;    // first line with error or zero
89  linenr_T bw_start_lnum;         // line number at start of buffer
90  iconv_t bw_iconv_fd;            // descriptor for iconv() or -1
91};
92
93#include "bufwrite.c.generated.h"
94
95/// Convert a Unicode character to bytes.
96///
97/// @param c character to convert
98/// @param[in,out] pp pointer to store the result at
99/// @param flags FIO_ flags that specify which encoding to use
100///
101/// @return true for an error, false when it's OK.
102static bool ucs2bytes(unsigned c, char **pp, int flags)
103  FUNC_ATTR_NONNULL_ALL
104{
105  uint8_t *p = (uint8_t *)(*pp);
106  bool error = false;
107
108  if (flags & FIO_UCS4) {
109    if (flags & FIO_ENDIAN_L) {
110      *p++ = (uint8_t)c;
111      *p++ = (uint8_t)(c >> 8);
112      *p++ = (uint8_t)(c >> 16);
113      *p++ = (uint8_t)(c >> 24);
114    } else {
115      *p++ = (uint8_t)(c >> 24);
116      *p++ = (uint8_t)(c >> 16);
117      *p++ = (uint8_t)(c >> 8);
118      *p++ = (uint8_t)c;
119    }
120  } else if (flags & (FIO_UCS2 | FIO_UTF16)) {
121    if (c >= 0x10000) {
122      if (flags & FIO_UTF16) {
123        // Make two words, ten bits of the character in each.  First
124        // word is 0xd800 - 0xdbff, second one 0xdc00 - 0xdfff
125        c -= 0x10000;
126        if (c >= 0x100000) {
127          error = true;
128        }
129        int cc = (int)(((c >> 10) & 0x3ff) + 0xd800);
130        if (flags & FIO_ENDIAN_L) {
131          *p++ = (uint8_t)cc;
132          *p++ = (uint8_t)(cc >> 8);
133        } else {
134          *p++ = (uint8_t)(cc >> 8);
135          *p++ = (uint8_t)cc;
136        }
137        c = (c & 0x3ff) + 0xdc00;
138      } else {
139        error = true;
140      }
141    }
142    if (flags & FIO_ENDIAN_L) {
143      *p++ = (uint8_t)c;
144      *p++ = (uint8_t)(c >> 8);
145    } else {
146      *p++ = (uint8_t)(c >> 8);
147      *p++ = (uint8_t)c;
148    }
149  } else {  // Latin1
150    if (c >= 0x100) {
151      error = true;
152      *p++ = 0xBF;
153    } else {
154      *p++ = (uint8_t)c;
155    }
156  }
157
158  *pp = (char *)p;
159  return error;
160}
161
162/// Converts a buffer encoding based on values in ip using iconv.
163///
164/// See buf_write_convert for parameters and return value details.
165static int buf_write_convert_with_iconv(struct bw_info *ip, char **bufp, int *lenp)
166{
167  int len = *lenp;
168
169  // Convert with iconv().
170  const char *from = *bufp;
171  size_t fromlen = (size_t)len;
172  size_t tolen = ip->bw_conv_buflen;
173  char *to = ip->bw_conv_buf;
174
175  if (ip->bw_first) {
176    size_t save_len = tolen;
177
178    // output the initial shift state sequence
179    iconv(ip->bw_iconv_fd, NULL, NULL, &to, &tolen);
180
181    // There is a bug in iconv() on Linux (which appears to be
182    // wide-spread) which sets "to" to NULL and messes up "tolen".
183    if (to == NULL) {
184      to = ip->bw_conv_buf;
185      tolen = save_len;
186    }
187    ip->bw_first = false;
188  }
189
190  // If iconv() has an error, fail.
191  if (iconv(ip->bw_iconv_fd, (void *)&from, &fromlen, &to, &tolen)
192      == (size_t)-1 && ICONV_ERRNO != ICONV_EINVAL) {
193    ip->bw_conv_error = true;
194    return -1;
195  }
196
197  *bufp = ip->bw_conv_buf;
198  *lenp = (int)(to - ip->bw_conv_buf);
199
200  return len - (int)fromlen;
201}
202
203/// Converts a buffer encoding based on values in ip.
204///
205/// @param ip buf_write_bytes context
206/// @param[in,out] bufp Pointer to the input buffer. On return, pointer to the output buffer.
207/// @param[in,out] lenp Pointer to the input buffer length. On return the referenced value is set to
208///                     the length of the output buffer.
209///
210/// @return The number of input buffer bytes consumed for the conversion, which may be less than the
211///         initial input buffer size when the buffer ends with an incomplete character sequence.
212static int buf_write_convert(struct bw_info *ip, char **bufp, int *lenp)
213{
214  int flags = ip->bw_flags;  // extra flags
215
216  int wlen = *lenp;
217  if (flags & (FIO_UCS4 | FIO_UTF16 | FIO_UCS2 | FIO_LATIN1)) {
218    unsigned c;
219    int n = 0;
220    // Convert UTF-8 bytes in the buffer to UCS-2, UCS-4, UTF-16 or
221    // Latin1 chars in the file.
222    // translate in-place (can only get shorter) or to buffer
223    char *p = flags & FIO_LATIN1 ? *bufp : ip->bw_conv_buf;
224    for (wlen = 0; wlen < *lenp; wlen += n) {
225      n = utf_ptr2len_len(*bufp + wlen, *lenp - wlen);
226      if (n > *lenp - wlen) {
227        // We have an incomplete byte sequence at the end to
228        // be written.  We can't convert it without the
229        // remaining bytes.  Keep them for the next call.
230        break;
231      }
232      c = n > 1 ? (unsigned)utf_ptr2char(*bufp + wlen)
233                : (uint8_t)(*bufp)[wlen];
234      // Check that there is enough space
235      if (!(flags & FIO_LATIN1)) {
236        size_t need = (flags & FIO_UCS4) ? 4 : 2;
237        if ((flags & FIO_UTF16) && c >= 0x10000) {
238          need = 4;
239        }
240
241        if ((size_t)(p - ip->bw_conv_buf) + need > ip->bw_conv_buflen) {
242          return FAIL;
243        }
244      }
245
246      if (ucs2bytes(c, &p, flags) && !ip->bw_conv_error) {
247        ip->bw_conv_error = true;
248        ip->bw_conv_error_lnum = ip->bw_start_lnum;
249      }
250      if (c == NL) {
251        ip->bw_start_lnum++;
252      }
253    }
254    if (flags & FIO_LATIN1) {
255      *lenp = (int)(p - *bufp);
256    } else {
257      *bufp = ip->bw_conv_buf;
258      *lenp = (int)(p - ip->bw_conv_buf);
259    }
260  }
261
262  if (ip->bw_iconv_fd != (iconv_t)-1) {
263    return buf_write_convert_with_iconv(ip, bufp, lenp);
264  }
265
266  return wlen;
267}
268
269/// Call write() to write a number of bytes to the file.
270/// Handles 'encoding' conversion.
271///
272/// @return  FAIL for failure, OK otherwise.
273static int buf_write_bytes(struct bw_info *ip)
274{
275  char *buf = ip->bw_buf;    // data to write
276  int len = ip->bw_len;      // length of data
277  int flags = ip->bw_flags;  // extra flags
278
279  int converted = len;
280  int remaining = 0;
281
282  // Skip conversion when writing the BOM.
283  if (!(flags & FIO_NOCONVERT)) {
284    if ((converted = buf_write_convert(ip, &buf, &len)) < 0) {
285      return FAIL;
286    }
287
288    remaining = ip->bw_len - converted;
289  }
290
291  ip->bw_len = remaining;
292
293  // Skip writing while checking conversion
294  if (ip->bw_fd >= 0) {
295    int wlen = (int)write_eintr(ip->bw_fd, buf, (size_t)len);
296    if (wlen < len) {
297      return FAIL;
298    }
299  }
300
301  if (remaining > 0) {
302    memmove(ip->bw_buf, ip->bw_buf + converted, (size_t)remaining);
303  }
304
305  return OK;
306}
307
308/// Check modification time of file, before writing to it.
309/// The size isn't checked, because using a tool like "gzip" takes care of
310/// using the same timestamp but can't set the size.
311static int check_mtime(buf_T *buf, FileInfo *file_info)
312{
313  if (buf->b_mtime_read != 0
314      && time_differs(file_info, buf->b_mtime_read, buf->b_mtime_read_ns)) {
315    msg_scroll = true;  // Don't overwrite messages here.
316    msg_silent = 0;     // Must give this prompt.
317    // Don't use emsg() here, don't want to flush the buffers.
318    msg(_("WARNING: The file has been changed since reading it!!!"), HLF_E);
319    if (ask_yesno(_("Do you really want to write to it")) == 'n') {
320      return FAIL;
321    }
322    msg_scroll = false;  // Always overwrite the file message now.
323  }
324  return OK;
325}
326
327/// Generate a BOM in "buf[4]" for encoding "name".
328///
329/// @return  the length of the BOM (zero when no BOM).
330static int make_bom(char *buf_in, char *name)
331{
332  uint8_t *buf = (uint8_t *)buf_in;
333  int flags = get_fio_flags(name);
334
335  // Can't put a BOM in a non-Unicode file.
336  if (flags == FIO_LATIN1 || flags == 0) {
337    return 0;
338  }
339
340  if (flags == FIO_UTF8) {      // UTF-8
341    buf[0] = 0xef;
342    buf[1] = 0xbb;
343    buf[2] = 0xbf;
344    return 3;
345  }
346  char *p = (char *)buf;
347  ucs2bytes(0xfeff, &p, flags);
348  return (int)((uint8_t *)p - buf);
349}
350
351static int buf_write_do_autocmds(buf_T *buf, char **fnamep, char **sfnamep, char **ffnamep,
352                                 linenr_T start, linenr_T *endp, exarg_T *eap, bool append,
353                                 bool filtering, bool reset_changed, bool overwriting, bool whole,
354                                 const pos_T orig_start, const pos_T orig_end)
355{
356  linenr_T old_line_count = buf->b_ml.ml_line_count;
357  int msg_save = msg_scroll;
358
359  CtxSwitch aco = { 0 };
360  bool did_cmd = false;
361  bool nofile_err = false;
362  bool empty_memline = buf->b_ml.ml_mfp == NULL;
363  bufref_T bufref;
364
365  char *sfname = *sfnamep;
366
367  // Apply PRE autocommands.
368  // Set curbuf to the buffer to be written.
369  // Careful: The autocommands may call buf_write() recursively!
370  bool buf_ffname = *ffnamep == buf->b_ffname;
371  bool buf_sfname = sfname == buf->b_sfname;
372  bool buf_fname_f = *fnamep == buf->b_ffname;
373  bool buf_fname_s = *fnamep == buf->b_sfname;
374
375  // Set curwin/curbuf to buf and save a few things.
376  ctx_switch(&aco, NULL, NULL, buf, 0);
377  set_bufref(&bufref, buf);
378
379  if (append) {
380    did_cmd = apply_autocmds_exarg(EVENT_FILEAPPENDCMD, sfname, sfname, false, curbuf, eap);
381    if (!did_cmd) {
382      if (overwriting && bt_nofilename(curbuf)) {
383        nofile_err = true;
384      } else {
385        apply_autocmds_exarg(EVENT_FILEAPPENDPRE,
386                             sfname, sfname, false, curbuf, eap);
387      }
388    }
389  } else if (filtering) {
390    apply_autocmds_exarg(EVENT_FILTERWRITEPRE,
391                         NULL, sfname, false, curbuf, eap);
392  } else if (reset_changed && whole) {
393    bool was_changed = curbufIsChanged();
394
395    did_cmd = apply_autocmds_exarg(EVENT_BUFWRITECMD, sfname, sfname, false, curbuf, eap);
396    if (did_cmd) {
397      if (was_changed && !curbufIsChanged()) {
398        // Written everything correctly and BufWriteCmd has reset
399        // 'modified': Correct the undo information so that an
400        // undo now sets 'modified'.
401        u_unchanged(curbuf);
402        u_update_save_nr(curbuf);
403      }
404    } else {
405      if (overwriting && bt_nofilename(curbuf)) {
406        nofile_err = true;
407      } else {
408        apply_autocmds_exarg(EVENT_BUFWRITEPRE,
409                             sfname, sfname, false, curbuf, eap);
410      }
411    }
412  } else {
413    did_cmd = apply_autocmds_exarg(EVENT_FILEWRITECMD, sfname, sfname, false, curbuf, eap);
414    if (!did_cmd) {
415      if (overwriting && bt_nofilename(curbuf)) {
416        nofile_err = true;
417      } else {
418        apply_autocmds_exarg(EVENT_FILEWRITEPRE,
419                             sfname, sfname, false, curbuf, eap);
420      }
421    }
422  }
423
424  // restore curwin/curbuf and a few other things
425  ctx_restore(&aco);
426
427  // In three situations we return here and don't write the file:
428  // 1. the autocommands deleted or unloaded the buffer.
429  // 2. The autocommands abort script processing.
430  // 3. If one of the "Cmd" autocommands was executed.
431  if (!bufref_valid(&bufref)) {
432    buf = NULL;
433  }
434  if (buf == NULL || (buf->b_ml.ml_mfp == NULL && !empty_memline)
435      || did_cmd || nofile_err
436      || aborting()) {
437    if (buf != NULL && (cmdmod.cmod_flags & CMOD_LOCKMARKS)) {
438      // restore the original '[ and '] positions
439      buf->b_op_start = orig_start;
440      buf->b_op_end = orig_end;
441    }
442
443    no_wait_return--;
444    msg_scroll = msg_save;
445    if (nofile_err) {
446      semsg(_(e_no_matching_autocommands_for_buftype_str_buffer), curbuf->b_p_bt);
447    }
448
449    if (nofile_err || aborting()) {
450      // An aborting error, interrupt or exception in the
451      // autocommands.
452      return FAIL;
453    }
454    if (did_cmd) {
455      if (buf == NULL) {
456        // The buffer was deleted.  We assume it was written
457        // (can't retry anyway).
458        return OK;
459      }
460      if (overwriting) {
461        // Assume the buffer was written, update the timestamp.
462        ml_timestamp(buf);
463        if (append) {
464          buf->b_flags &= ~BF_NEW;
465        } else {
466          buf->b_flags &= ~BF_WRITE_MASK;
467        }
468      }
469      if (reset_changed && buf->b_changed && !append
470          && (overwriting || vim_strchr(p_cpo, kCpoPlus) != NULL)) {
471        // Buffer still changed, the autocommands didn't work properly.
472        return FAIL;
473      }
474      return OK;
475    }
476    if (!aborting()) {
477      emsg(_("E203: Autocommands deleted or unloaded buffer to be written"));
478    }
479    return FAIL;
480  }
481
482  // The autocommands may have changed the number of lines in the file.
483  // When writing the whole file, adjust the end.
484  // When writing part of the file, assume that the autocommands only
485  // changed the number of lines that are to be written (tricky!).
486  if (buf->b_ml.ml_line_count != old_line_count) {
487    if (whole) {                                              // write all
488      *endp = buf->b_ml.ml_line_count;
489    } else if (buf->b_ml.ml_line_count > old_line_count) {           // more lines
490      *endp += buf->b_ml.ml_line_count - old_line_count;
491    } else {                                                    // less lines
492      *endp -= old_line_count - buf->b_ml.ml_line_count;
493      if (*endp < start) {
494        no_wait_return--;
495        msg_scroll = msg_save;
496        emsg(_("E204: Autocommand changed number of lines in unexpected way"));
497        return FAIL;
498      }
499    }
500  }
501
502  // The autocommands may have changed the name of the buffer, which may
503  // be kept in fname, ffname and sfname. A CWD change may also clear b_sfname;
504  // use b_fname, which falls back to the full name when there is no short name.
505  if (buf_ffname) {
506    *ffnamep = buf->b_ffname;
507  }
508  if (buf_sfname) {
509    *sfnamep = buf->b_fname;
510  }
511  if (buf_fname_f) {
512    *fnamep = buf->b_ffname;
513  }
514  if (buf_fname_s) {
515    *fnamep = buf->b_fname;
516  }
517  return NOTDONE;
518}
519
520static void buf_write_do_post_autocmds(buf_T *buf, char *fname, exarg_T *eap, bool append,
521                                       bool filtering, bool reset_changed, bool whole)
522{
523  CtxSwitch aco = { 0 };
524
525  curbuf->b_no_eol_lnum = 0;      // in case it was set by the previous read
526
527  // Apply POST autocommands.
528  // Careful: The autocommands may call buf_write() recursively!
529  ctx_switch(&aco, NULL, NULL, buf, 0);
530
531  if (append) {
532    apply_autocmds_exarg(EVENT_FILEAPPENDPOST, fname, fname,
533                         false, curbuf, eap);
534  } else if (filtering) {
535    apply_autocmds_exarg(EVENT_FILTERWRITEPOST, NULL, fname,
536                         false, curbuf, eap);
537  } else if (reset_changed && whole) {
538    apply_autocmds_exarg(EVENT_BUFWRITEPOST, fname, fname,
539                         false, curbuf, eap);
540  } else {
541    apply_autocmds_exarg(EVENT_FILEWRITEPOST, fname, fname,
542                         false, curbuf, eap);
543  }
544
545  // restore curwin/curbuf and a few other things
546  ctx_restore(&aco);
547}
548
549static inline Error_T set_err_num(const char *num, const char *msg)
550{
551  return (Error_T){ .num = num, .msg = (char *)msg, .arg = 0 };
552}
553
554static inline Error_T set_err(const char *msg)
555{
556  return (Error_T){ .num = NULL, .msg = (char *)msg, .arg = 0 };
557}
558
559static inline Error_T set_err_arg(const char *msg, int arg)
560{
561  return (Error_T){ .num = NULL, .msg = (char *)msg, .arg = arg };
562}
563
564/// Shows a write error msg.  IObuff must hold the quoted file name.
565///
566/// @param msg_id  Ends the progress-message with "failed" status. NULL to show a plain error msg.
567static void emit_err(Error_T *e, char *msg_id)
568{
569  char errmsg[IOSIZE];
570  if (e->num != NULL && e->arg != 0) {
571    vim_snprintf(errmsg, IOSIZE, "%s: %s%s: %s", e->num, IObuff, e->msg, os_strerror(e->arg));
572  } else if (e->num != NULL) {
573    vim_snprintf(errmsg, IOSIZE, "%s: %s%s", e->num, IObuff, e->msg);
574  } else if (e->arg != 0) {
575    vim_snprintf(errmsg, IOSIZE, e->msg, os_strerror(e->arg));
576  } else {
577    xstrlcpy(errmsg, e->msg, IOSIZE);
578  }
579  if (msg_id != NULL) {
580    msg_progress(errmsg, msg_id, "failed", HLF_E, false, false, true);
581  } else {
582    emsg(errmsg);
583  }
584  if (e->alloc) {
585    xfree(e->msg);
586  }
587}
588
589#ifdef UNIX
590
591static int get_fileinfo_os(char *fname, FileInfo *file_info_old, bool overwriting, int *perm,
592                           bool *device, bool *newfile, Error_T *err)
593{
594  *perm = -1;
595  if (!os_fileinfo(fname, file_info_old)) {
596    *newfile = true;
597  } else {
598    *perm = (int)file_info_old->stat.st_mode;
599    if (!S_ISREG(file_info_old->stat.st_mode)) {             // not a file
600      if (S_ISDIR(file_info_old->stat.st_mode)) {
601        *err = set_err_num("E502", _("is a directory"));
602        return FAIL;
603      }
604      if (os_nodetype(fname) != NODE_WRITABLE) {
605        *err = set_err_num("E503", _("is not a file or writable device"));
606        return FAIL;
607      }
608      // It's a device of some kind (or a fifo) which we can write to
609      // but for which we can't make a backup.
610      *device = true;
611      *newfile = true;
612      *perm = -1;
613    }
614  }
615  return OK;
616}
617
618#else
619
620static int get_fileinfo_os(char *fname, FileInfo *file_info_old, bool overwriting, int *perm,
621                           bool *device, bool *newfile, Error_T *err)
622{
623  // Check for a writable device name.
624  char nodetype = fname == NULL ? NODE_OTHER : (char)os_nodetype(fname);
625  if (nodetype == NODE_OTHER) {
626    *err = set_err_num("E503", _("is not a file or writable device"));
627    return FAIL;
628  }
629  if (nodetype == NODE_WRITABLE) {
630    *device = true;
631    *newfile = true;
632    *perm = -1;
633  } else {
634    *perm = os_getperm(fname);
635    if (*perm < 0) {
636      *newfile = true;
637    } else if (os_isdir(fname)) {
638      *err = set_err_num("E502", _("is a directory"));
639      return FAIL;
640    }
641    if (overwriting) {
642      os_fileinfo(fname, file_info_old);
643    }
644  }
645  return OK;
646}
647
648#endif
649
650/// @param buf
651/// @param fname          File name
652/// @param overwriting
653/// @param forceit
654/// @param[out] file_info_old
655/// @param[out] perm
656/// @param[out] device
657/// @param[out] newfile
658/// @param[out] readonly
659static int get_fileinfo(buf_T *buf, char *fname, bool overwriting, bool forceit,
660                        FileInfo *file_info_old, int *perm, bool *device, bool *newfile,
661                        bool *readonly, Error_T *err)
662{
663  if (get_fileinfo_os(fname, file_info_old, overwriting, perm, device, newfile, err) == FAIL) {
664    return FAIL;
665  }
666
667  *readonly = false;  // overwritten file is read-only
668
669  if (!*device && !*newfile) {
670    // Check if the file is really writable (when renaming the file to
671    // make a backup we won't discover it later).
672    *readonly = !os_file_is_writable(fname);
673
674    if (!forceit && *readonly) {
675      if (vim_strchr(p_cpo, kCpoFwrite) != NULL) {
676        *err = set_err_num("E504", _(err_readonly));
677      } else {
678        *err = set_err_num("E505", _("is read-only (add ! to override)"));
679      }
680      return FAIL;
681    }
682
683    // If 'forceit' is false, check if the timestamp hasn't changed since reading the file.
684    if (overwriting && !forceit) {
685      int retval = check_mtime(buf, file_info_old);
686      if (retval == FAIL) {
687        return FAIL;
688      }
689    }
690  }
691  return OK;
692}
693
694/// @return The backup file name
695char *buf_get_backup_name(char *fname, char **dirp, bool no_prepend_dot, char *backup_ext)
696{
697  char *backup = NULL;
698  // Isolate one directory name, using an entry in 'bdir'.
699  size_t dir_len = copy_option_part(dirp, IObuff, IOSIZE, ",");
700  char *p = IObuff + dir_len;
701  if (**dirp == NUL && !os_isdir(IObuff)) {
702    int ret;
703    char *failed_dir;
704    if ((ret = os_mkdir_recurse(IObuff, 0755, &failed_dir, NULL)) != 0) {
705      semsg(_("E303: Unable to create directory \"%s\" for backup file: %s"),
706            failed_dir, os_strerror(ret));
707      xfree(failed_dir);
708    }
709  }
710  if (dir_len > 1 && after_pathsep(IObuff, p) && p[-1] == p[-2]) {
711    // path ends with '//', use full path
712    if ((p = make_percent_swname(IObuff, p, fname))
713        != NULL) {
714      backup = modname(p, backup_ext, no_prepend_dot);
715      xfree(p);
716    }
717  }
718  if (backup == NULL) {
719    char *rootname = get_file_in_dir(fname, IObuff);
720    if (rootname != NULL) {
721      backup = modname(rootname, backup_ext, no_prepend_dot);
722      xfree(rootname);
723    }
724  }
725  return backup;
726}
727
728static int buf_write_make_backup(char *fname, bool append, FileInfo *file_info_old, vim_acl_T acl,
729                                 int perm, unsigned bkc, bool file_readonly, bool forceit,
730                                 bool *backup_copyp, char **backupp, Error_T *err)
731{
732  FileInfo file_info;
733  const bool no_prepend_dot = false;
734
735  if ((bkc & kOptBkcFlagYes) || append) {       // "yes"
736    *backup_copyp = true;
737  } else if ((bkc & kOptBkcFlagAuto)) {          // "auto"
738    // Don't rename the file when:
739    // - it's a hard link
740    // - it's a symbolic link
741    // - we don't have write permission in the directory
742    if (os_fileinfo_hardlinks(file_info_old) > 1
743        || !os_fileinfo_link(fname, &file_info)
744        || !os_fileinfo_id_equal(&file_info, file_info_old)) {
745      *backup_copyp = true;
746    } else {
747      // Check if we can create a file and set the owner/group/mode to
748      // the ones from the original file.
749      // First find a file name that doesn't exist yet (use some
750      // arbitrary numbers).
751      size_t dirlen = (size_t)(path_tail(fname) - fname);
752      assert(dirlen < MAXPATHL);
753      char tmp_fname[MAXPATHL];
754      xmemcpyz(tmp_fname, fname, dirlen);
755      for (int i = 4913;; i += 123) {
756        snprintf(tmp_fname + dirlen, sizeof(tmp_fname) - dirlen, "%d", i);
757        if (!os_fileinfo_link(tmp_fname, &file_info)) {
758          break;
759        }
760      }
761      int fd = os_open(tmp_fname,
762                       O_CREAT|O_WRONLY|O_EXCL|O_NOFOLLOW, perm);
763      if (fd < 0) {           // can't write in directory
764        *backup_copyp = true;
765      } else {
766#ifdef UNIX
767        os_fchown(fd, (uv_uid_t)file_info_old->stat.st_uid, (uv_gid_t)file_info_old->stat.st_gid);
768        os_fsetperm(fd, perm);
769        if (!os_fileinfo(tmp_fname, &file_info)
770            || file_info.stat.st_uid != file_info_old->stat.st_uid
771            || file_info.stat.st_gid != file_info_old->stat.st_gid
772            || (int)file_info.stat.st_mode != perm) {
773          *backup_copyp = true;
774        }
775#endif
776        // Close the file before removing it, on MS-Windows we
777        // can't delete an open file.
778        close(fd);
779        os_remove(tmp_fname);
780      }
781    }
782  }
783
784  // Break symlinks and/or hardlinks if we've been asked to.
785  if ((bkc & kOptBkcFlagBreaksymlink) || (bkc & kOptBkcFlagBreakhardlink)) {
786#ifdef UNIX
787    bool file_info_link_ok = os_fileinfo_link(fname, &file_info);
788
789    // Symlinks.
790    if ((bkc & kOptBkcFlagBreaksymlink)
791        && file_info_link_ok
792        && !os_fileinfo_id_equal(&file_info, file_info_old)) {
793      *backup_copyp = false;
794    }
795
796    // Hardlinks.
797    if ((bkc & kOptBkcFlagBreakhardlink)
798        && os_fileinfo_hardlinks(file_info_old) > 1
799        && (!file_info_link_ok
800            || os_fileinfo_id_equal(&file_info, file_info_old))) {
801      *backup_copyp = false;
802    }
803#endif
804  }
805
806  // make sure we have a valid backup extension to use
807  char *backup_ext = *p_bex == NUL ? ".bak" : p_bex;
808
809  if (*backup_copyp) {
810    bool some_error = false;
811
812    // Try to make the backup in each directory in the 'bdir' option.
813    //
814    // Unix semantics has it, that we may have a writable file,
815    // that cannot be recreated with a simple open(..., O_CREAT, ) e.g:
816    //  - the directory is not writable,
817    //  - the file may be a symbolic link,
818    //  - the file may belong to another user/group, etc.
819    //
820    // For these reasons, the existing writable file must be truncated
821    // and reused. Creation of a backup COPY will be attempted.
822    char *dirp = p_bdir;
823    while (*dirp) {
824      *backupp = buf_get_backup_name(fname, &dirp, no_prepend_dot, backup_ext);
825      if (*backupp == NULL) {
826        some_error = true;                // out of memory
827        goto nobackup;
828      }
829
830      FileInfo file_info_new;
831      {
832        // Check if backup file already exists.
833        if (os_fileinfo(*backupp, &file_info_new)) {
834          if (os_fileinfo_id_equal(&file_info_new, file_info_old)) {
835            //
836            // Backup file is same as original file.
837            // May happen when modname() gave the same file back (e.g. silly
838            // link). If we don't check here, we either ruin the file when
839            // copying or erase it after writing.
840            //
841            XFREE_CLEAR(*backupp);              // no backup file to delete
842          } else if (!p_bk) {
843            // We are not going to keep the backup file, so don't
844            // delete an existing one, and try to use another name instead.
845            // Change one character, just before the extension.
846            //
847            char *wp = *backupp + strlen(*backupp) - 1 - strlen(backup_ext);
848            wp = MAX(wp, *backupp);  // empty file name ???
849            *wp = 'z';
850            while (*wp > 'a' && os_fileinfo(*backupp, &file_info_new)) {
851              (*wp)--;
852            }
853            // They all exist??? Must be something wrong.
854            if (*wp == 'a') {
855              XFREE_CLEAR(*backupp);
856            }
857          }
858        }
859      }
860
861      // Try to create the backup file
862      if (*backupp != NULL) {
863        // remove old backup, if present
864        os_remove(*backupp);
865
866        // copy the file
867        if (os_copy(fname, *backupp, UV_FS_COPYFILE_FICLONE) != 0) {
868          *err = set_err(_("E509: Cannot create backup file (add ! to override)"));
869          XFREE_CLEAR(*backupp);
870          *backupp = NULL;
871          continue;
872        }
873
874        // set file protection same as original file, but
875        // strip s-bit.
876        os_setperm(*backupp, perm & 0777);
877
878#ifdef UNIX
879        // Try to set the group of the backup same as the original file. If
880        // this fails, set the protection bits for the group same as the
881        // protection bits for others.
882        if (file_info_new.stat.st_gid != file_info_old->stat.st_gid
883            && os_chown(*backupp, (uv_uid_t)-1, (uv_gid_t)file_info_old->stat.st_gid) != 0) {
884          os_setperm(*backupp, (perm & 0707) | ((perm & 07) << 3));
885        }
886        os_file_settime(*backupp,
887                        (double)file_info_old->stat.st_atim.tv_sec,
888                        (double)file_info_old->stat.st_mtim.tv_sec);
889#endif
890
891        os_set_acl(*backupp, acl);
892#ifdef HAVE_XATTR
893        os_copy_xattr(fname, *backupp);
894#endif
895        *err = set_err(NULL);
896        break;
897      }
898    }
899
900nobackup:
901    if (*backupp == NULL && err->msg == NULL) {
902      *err = set_err(_("E509: Cannot create backup file (add ! to override)"));
903    }
904    // Ignore errors when forceit is true.
905    if ((some_error || err->msg != NULL) && !forceit) {
906      return FAIL;
907    }
908    *err = set_err(NULL);
909  } else {
910    // Make a backup by renaming the original file.
911
912    // If 'cpoptions' includes the "W" flag, we don't want to
913    // overwrite a read-only file.  But rename may be possible
914    // anyway, thus we need an extra check here.
915    if (file_readonly && vim_strchr(p_cpo, kCpoFwrite) != NULL) {
916      *err = set_err_num("E504", _(err_readonly));
917      return FAIL;
918    }
919
920    // Form the backup file name - change path/fo.o.h to
921    // path/fo.o.h.bak Try all directories in 'backupdir', first one
922    // that works is used.
923    char *dirp = p_bdir;
924    while (*dirp) {
925      *backupp = buf_get_backup_name(fname, &dirp, no_prepend_dot, backup_ext);
926      if (*backupp != NULL) {
927        // If we are not going to keep the backup file, don't
928        // delete an existing one, try to use another name.
929        // Change one character, just before the extension.
930        if (!p_bk && os_path_exists(*backupp)) {
931          char *p = *backupp + strlen(*backupp) - 1 - strlen(backup_ext);
932          p = MAX(p, *backupp);  // empty file name ???
933          *p = 'z';
934          while (*p > 'a' && os_path_exists(*backupp)) {
935            (*p)--;
936          }
937          // They all exist??? Must be something wrong!
938          if (*p == 'a') {
939            XFREE_CLEAR(*backupp);
940          }
941        }
942      }
943      if (*backupp != NULL) {
944        // Delete any existing backup and move the current version
945        // to the backup. For safety, we don't remove the backup
946        // until the write has finished successfully. And if the
947        // 'backup' option is set, leave it around.
948
949        // If the renaming of the original file to the backup file
950        // works, quit here.
951        ///
952        if (vim_rename(fname, *backupp) == 0) {
953          break;
954        }
955
956        XFREE_CLEAR(*backupp);             // don't do the rename below
957      }
958    }
959    if (*backupp == NULL && !forceit) {
960      *err = set_err(_("E510: Can't make backup file (add ! to override)"));
961      return FAIL;
962    }
963  }
964  return OK;
965}
966
967/// buf_write() - write to file "fname" lines "start" through "end"
968///
969/// We do our own buffering here because fwrite() is so slow.
970///
971/// If "forceit" is true, we don't care for errors when attempting backups.
972/// In case of an error everything possible is done to restore the original
973/// file.  But when "forceit" is true, we risk losing it.
974///
975/// When "reset_changed" is true and "append" == false and "start" == 1 and
976/// "end" == curbuf->b_ml.ml_line_count, reset curbuf->b_changed.
977///
978/// This function must NOT use NameBuff (because it's called by autowrite()).
979///
980///
981/// @param eap     for forced 'ff' and 'fenc', can be NULL!
982/// @param append  append to the file
983///
984/// @return        FAIL for failure, OK otherwise
985int buf_write(buf_T *buf, char *fname, char *sfname, linenr_T start, linenr_T end, exarg_T *eap,
986              bool append, bool forceit, bool reset_changed, bool filtering)
987{
988  int retval = OK;
989  int msg_save = msg_scroll;
990  bool prev_got_int = got_int;
991  // writing everything
992  bool whole = (start == 1 && end == buf->b_ml.ml_line_count);
993  bool write_undo_file = false;
994  context_sha256_T sha_ctx;
995  unsigned bkc = get_bkc_flags(buf);
996
997  if (fname == NULL || *fname == NUL) {  // safety check
998    return FAIL;
999  }
1000  if (buf->b_ml.ml_mfp == NULL) {
1001    // This can happen during startup when there is a stray "w" in the
1002    // vimrc file.
1003    emsg(_(e_empty_buffer));
1004    return FAIL;
1005  }
1006
1007  // Disallow writing in secure mode.
1008  if (check_secure()) {
1009    return FAIL;
1010  }
1011
1012  // Avoid a crash for a long name.
1013  if (strlen(fname) >= MAXPATHL) {
1014    emsg(_(e_longname));
1015    return FAIL;
1016  }
1017
1018  // Ensure all fields are initialized (zeroed, or else specified here).
1019  struct bw_info write_info = {          // info for buf_write_bytes()
1020    .bw_iconv_fd = (iconv_t)-1,
1021  };
1022
1023  // If there is no file name yet, use the one for the written file.
1024  // BF_NOTEDITED is set to reflect this (in case the write fails).
1025  // Don't do this when the write is for a filter command.
1026  // Don't do this when appending.
1027  // Only do this when 'cpoptions' contains the 'F' flag.
1028  if (buf->b_ffname == NULL
1029      && reset_changed
1030      && whole
1031      && buf == curbuf
1032      && !bt_nofilename(buf)
1033      && !filtering
1034      && (!append || vim_strchr(p_cpo, kCpoFnameapp) != NULL)
1035      && vim_strchr(p_cpo, kCpoFnamew) != NULL) {
1036    if (set_rw_fname(fname, sfname) == FAIL) {
1037      return FAIL;
1038    }
1039    buf = curbuf;           // just in case autocmds made "buf" invalid
1040  }
1041
1042  if (sfname == NULL) {
1043    sfname = fname;
1044  }
1045
1046  // For Unix: Use the short file name whenever possible.
1047  // Avoids problems with networks and when directory names are changed.
1048  // Don't do this for Windows, a "cd" in a sub-shell may have moved us to
1049  // another directory, which we don't detect.
1050  char *ffname = fname;                           // remember full fname
1051#ifdef UNIX
1052  fname = sfname;
1053#endif
1054
1055  // true if writing over original
1056  bool overwriting = buf->b_ffname != NULL && path_equal(ffname, buf->b_ffname, kPathCmpLiteral);
1057
1058  no_wait_return++;                 // don't wait for return yet
1059
1060  const pos_T orig_start = buf->b_op_start;
1061  const pos_T orig_end = buf->b_op_end;
1062
1063  // Set '[ and '] marks to the lines to be written.
1064  buf->b_op_start.lnum = start;
1065  buf->b_op_start.col = 0;
1066  buf->b_op_end.lnum = end;
1067  buf->b_op_end.col = 0;
1068
1069  int res = buf_write_do_autocmds(buf, &fname, &sfname, &ffname, start, &end, eap, append,
1070                                  filtering, reset_changed, overwriting, whole, orig_start,
1071                                  orig_end);
1072  if (res != NOTDONE) {
1073    return res;
1074  }
1075
1076  // Emitting a msg below can run user code (ui2 `msg_show` handler), which may change CWD and thus
1077  // reallocate the buffer names. #41417
1078  char *const fname_copy = xstrdup(fname);
1079  char *const sfname_copy = xstrdup(sfname);
1080  char *const ffname_copy = xstrdup(ffname);
1081  fname = fname_copy;
1082  sfname = sfname_copy;
1083  ffname = ffname_copy;
1084
1085  if (cmdmod.cmod_flags & CMOD_LOCKMARKS) {
1086    // restore the original '[ and '] positions
1087    buf->b_op_start = orig_start;
1088    buf->b_op_end = orig_end;
1089  }
1090
1091  if (shortmess(kShmOver) && !exiting) {
1092    msg_scroll = false;             // overwrite previous file message
1093  } else {
1094    msg_scroll = true;              // don't overwrite previous file message
1095  }
1096  // Progress-msg id, e.g. `nvim.bufwrite "foo.txt"`.
1097  char msg_id[MAXPATHL + 32];
1098#ifndef UNIX
1099  char *msgname = sfname;
1100#else
1101  char *msgname = fname;
1102#endif
1103  size_t id_len = xstrlcpy(msg_id, "nvim.bufwrite ", sizeof(msg_id));
1104  add_quoted_fname(msg_id + id_len, sizeof(msg_id) - id_len, buf, msgname);
1105  msg_id[strlen(msg_id) - 1] = NUL;  // add_quoted_fname() appends a space, for display only.
1106
1107  if (!filtering) {
1108    // show that we are busy
1109    filemess_progress(buf, msgname, msg_id);
1110  }
1111  msg_scroll = false;               // always overwrite the file message now
1112
1113  char *buffer = verbose_try_malloc(WRITEBUFSIZE);
1114  int bufsize;
1115  char smallbuf[SMALLBUFSIZE];
1116  // can't allocate big buffer, use small one (to be able to write when out of
1117  // memory)
1118  if (buffer == NULL) {
1119    buffer = smallbuf;
1120    bufsize = SMALLBUFSIZE;
1121  } else {
1122    bufsize = WRITEBUFSIZE;
1123  }
1124
1125  Error_T err = { 0 };
1126  int perm;              // file permissions
1127  bool newfile = false;  // true if file doesn't exist yet
1128  bool device = false;   // writing to a device
1129  bool file_readonly = false;  // overwritten file is read-only
1130  char *backup = NULL;
1131  char *fenc_tofree = NULL;   // allocated "fenc"
1132
1133  // Get information about original file (if there is one).
1134  FileInfo file_info_old;
1135
1136  vim_acl_T acl = NULL;                 // ACL copied from original file to
1137                                        // backup or new file
1138
1139  if (get_fileinfo(buf, fname, overwriting, forceit, &file_info_old, &perm, &device, &newfile,
1140                   &file_readonly, &err) == FAIL) {
1141    goto fail;
1142  }
1143
1144  // For systems that support ACL: get the ACL from the original file.
1145  if (!newfile) {
1146    acl = os_get_acl(fname);
1147  }
1148
1149  // If 'backupskip' is not empty, don't make a backup for some files.
1150  bool dobackup = (p_wb || p_bk || *p_pm != NUL);
1151  if (dobackup && *p_bsk != NUL && match_file_list(p_bsk, sfname, ffname)) {
1152    dobackup = false;
1153  }
1154
1155  bool backup_copy = false;  // copy the original file?
1156
1157  // Save the value of got_int and reset it.  We don't want a previous
1158  // interruption cancel writing, only hitting CTRL-C while writing should
1159  // abort it.
1160  prev_got_int = got_int;
1161  got_int = false;
1162
1163  // Mark the buffer as 'being saved' to prevent changed buffer warnings
1164  buf->b_saving = true;
1165
1166  // If we are not appending or filtering, the file exists, and the
1167  // 'writebackup', 'backup' or 'patchmode' option is set, need a backup.
1168  // When 'patchmode' is set also make a backup when appending.
1169  //
1170  // Do not make any backup, if 'writebackup' and 'backup' are both switched
1171  // off.  This helps when editing large files on almost-full disks.
1172  if (!(append && *p_pm == NUL) && !filtering && perm >= 0 && dobackup) {
1173    if (buf_write_make_backup(fname, append, &file_info_old, acl, perm, bkc, file_readonly, forceit,
1174                              &backup_copy, &backup, &err) == FAIL) {
1175      retval = FAIL;
1176      goto fail;
1177    }
1178  }
1179
1180#ifdef UNIX
1181  bool made_writable = false;  // 'w' bit has been set
1182
1183  // When using ":w!" and the file was read-only: make it writable
1184  if (forceit && perm >= 0 && !(perm & 0200)
1185      && file_info_old.stat.st_uid == getuid()
1186      && vim_strchr(p_cpo, kCpoFwrite) == NULL) {
1187    perm |= 0200;
1188    os_setperm(fname, perm);
1189    made_writable = true;
1190  }
1191#endif
1192
1193  // When using ":w!" and writing to the current file, 'readonly' makes no
1194  // sense, reset it, unless 'Z' appears in 'cpoptions'.
1195  if (forceit && overwriting && vim_strchr(p_cpo, kCpoKeepro) == NULL) {
1196    buf->b_p_ro = false;
1197    need_maketitle = true;          // set window title later
1198    status_redraw_all();            // redraw status lines later
1199  }
1200
1201  end = MIN(end, buf->b_ml.ml_line_count);
1202  if (buf->b_ml.ml_flags & ML_EMPTY) {
1203    start = end + 1;
1204  }
1205
1206  char *wfname = NULL;       // name of file to write to
1207
1208  // If the original file is being overwritten, there is a small chance that
1209  // we crash in the middle of writing. Therefore the file is preserved now.
1210  // This makes all block numbers positive so that recovery does not need
1211  // the original file.
1212  // Don't do this if there is a backup file and we are exiting.
1213  if (reset_changed && !newfile && overwriting && !(exiting && backup != NULL)) {
1214    ml_preserve(buf, false, !!(buf->b_p_fs >= 0 ? buf->b_p_fs : p_fs));
1215    if (got_int) {
1216      err = set_err(_(e_interr));
1217      goto restore_backup;
1218    }
1219  }
1220
1221  // Default: write the file directly.  May write to a temp file for
1222  // multi-byte conversion.
1223  wfname = fname;
1224
1225  char *fenc;  // effective 'fileencoding'
1226
1227  // Check for forced 'fileencoding' from "++opt=val" argument.
1228  if (eap != NULL && eap->force_enc != 0) {
1229    fenc = eap->cmd + eap->force_enc;
1230    fenc = enc_canonize(fenc);
1231    fenc_tofree = fenc;
1232  } else {
1233    fenc = buf->b_p_fenc;
1234  }
1235
1236  // Check if the file needs to be converted.
1237  bool converted = need_conversion(fenc);
1238  int wb_flags = 0;
1239
1240  // Check if UTF-8 to UCS-2/4 or Latin1 conversion needs to be done.  Or
1241  // Latin1 to Unicode conversion.  This is handled in buf_write_bytes().
1242  // Prepare the flags for it and allocate bw_conv_buf when needed.
1243  if (converted) {
1244    wb_flags = get_fio_flags(fenc);
1245    if (wb_flags & (FIO_UCS2 | FIO_UCS4 | FIO_UTF16 | FIO_UTF8)) {
1246      // Need to allocate a buffer to translate into.
1247      if (wb_flags & (FIO_UCS2 | FIO_UTF16 | FIO_UTF8)) {
1248        write_info.bw_conv_buflen = (size_t)bufsize * 2;
1249      } else {       // FIO_UCS4
1250        write_info.bw_conv_buflen = (size_t)bufsize * 4;
1251      }
1252      write_info.bw_conv_buf = verbose_try_malloc(write_info.bw_conv_buflen);
1253      if (!write_info.bw_conv_buf) {
1254        end = 0;
1255      }
1256    }
1257  }
1258
1259  if (converted && wb_flags == 0) {
1260    // Use iconv() conversion when conversion is needed and it's not done
1261    // internally.
1262    write_info.bw_iconv_fd = (iconv_t)my_iconv_open(fenc, "utf-8");
1263    if (write_info.bw_iconv_fd != (iconv_t)-1) {
1264      // We're going to use iconv(), allocate a buffer to convert in.
1265      write_info.bw_conv_buflen = (size_t)bufsize * ICONV_MULT;
1266      write_info.bw_conv_buf = verbose_try_malloc(write_info.bw_conv_buflen);
1267      if (!write_info.bw_conv_buf) {
1268        end = 0;
1269      }
1270      write_info.bw_first = true;
1271    } else {
1272      // When the file needs to be converted with 'charconvert' after
1273      // writing, write to a temp file instead and let the conversion
1274      // overwrite the original file.
1275      if (p_ccv.type != kCallbackNone) {
1276        wfname = vim_tempname();
1277        if (wfname == NULL) {  // Can't write without a tempfile!
1278          err = set_err(_("E214: Can't find temp file for writing"));
1279          goto restore_backup;
1280        }
1281      }
1282    }
1283  }
1284
1285  bool notconverted = false;
1286
1287  if (converted && wb_flags == 0
1288      && write_info.bw_iconv_fd == (iconv_t)-1
1289      && wfname == fname) {
1290    if (!forceit) {
1291      err = set_err(_("E213: Cannot convert (add ! to write without conversion)"));
1292      goto restore_backup;
1293    }
1294    notconverted = true;
1295  }
1296
1297  bool no_eol = false;  // no end-of-line written
1298  int nchars;
1299  linenr_T lnum;
1300  int fileformat;
1301  bool checking_conversion;
1302
1303  int fd;
1304
1305  // If conversion is taking place, we may first pretend to write and check
1306  // for conversion errors.  Then loop again to write for real.
1307  // When not doing conversion this writes for real right away.
1308  for (checking_conversion = true;; checking_conversion = false) {
1309    // There is no need to check conversion when:
1310    // - there is no conversion
1311    // - we make a backup file, that can be restored in case of conversion
1312    // failure.
1313    if (!converted || dobackup) {
1314      checking_conversion = false;
1315    }
1316
1317    if (checking_conversion) {
1318      // Make sure we don't write anything.
1319      fd = -1;
1320      write_info.bw_fd = fd;
1321    } else {
1322      // Open the file "wfname" for writing.
1323      // We may try to open the file twice: If we can't write to the file
1324      // and forceit is true we delete the existing file and try to
1325      // create a new one. If this still fails we may have lost the
1326      // original file!  (this may happen when the user reached his
1327      // quotum for number of files).
1328      // Appending will fail if the file does not exist and forceit is
1329      // false.
1330      const int fflags = O_WRONLY | (append
1331                                     ? (forceit ? (O_APPEND | O_CREAT) : O_APPEND)
1332                                     : (O_CREAT | O_TRUNC));
1333      const int mode = perm < 0 ? 0666 : (perm & 0777);
1334
1335      while ((fd = os_open(wfname, fflags, mode)) < 0) {
1336        // A forced write will try to create a new file if the old one
1337        // is still readonly. This may also happen when the directory
1338        // is read-only. In that case the os_remove() will fail.
1339        if (err.msg == NULL) {
1340#ifdef UNIX
1341          FileInfo file_info;
1342
1343          // Don't delete the file when it's a hard or symbolic link.
1344          if ((!newfile && os_fileinfo_hardlinks(&file_info_old) > 1)
1345              || (os_fileinfo_link(fname, &file_info)
1346                  && !os_fileinfo_id_equal(&file_info, &file_info_old))) {
1347            err = set_err(_("E166: Can't open linked file for writing"));
1348          } else {
1349            err = set_err_arg(_("E212: Can't open file for writing: %s"), fd);
1350            if (forceit && vim_strchr(p_cpo, kCpoFwrite) == NULL && perm >= 0) {
1351              // we write to the file, thus it should be marked
1352              // writable after all
1353              if (!(perm & 0200)) {
1354                made_writable = true;
1355              }
1356              perm |= 0200;
1357              if (file_info_old.stat.st_uid != getuid()
1358                  || file_info_old.stat.st_gid != getgid()) {
1359                perm &= 0777;
1360              }
1361              if (!append) {                    // don't remove when appending
1362                os_remove(wfname);
1363              }
1364              continue;
1365            }
1366          }
1367#else
1368          err = set_err_arg(_("E212: Can't open file for writing: %s"), fd);
1369          if (forceit && vim_strchr(p_cpo, kCpoFwrite) == NULL && perm >= 0) {
1370            if (!append) {                    // don't remove when appending
1371              os_remove(wfname);
1372            }
1373            continue;
1374          }
1375#endif
1376        }
1377
1378restore_backup:
1379        {
1380          // If we failed to open the file, we don't need a backup. Throw it
1381          // away.  If we moved or removed the original file try to put the
1382          // backup in its place.
1383          if (backup != NULL && wfname == fname) {
1384            if (backup_copy) {
1385              // There is a small chance that we removed the original,
1386              // try to move the copy in its place.
1387              // This may not work if the vim_rename() fails.
1388              // In that case we leave the copy around.
1389              // If file does not exist, put the copy in its place
1390              if (!os_path_exists(fname)) {
1391                vim_rename(backup, fname);
1392              }
1393              // if original file does exist throw away the copy
1394              if (os_path_exists(fname)) {
1395                os_remove(backup);
1396              }
1397            } else {
1398              // try to put the original file back
1399              vim_rename(backup, fname);
1400            }
1401          }
1402
1403          // if original file no longer exists give an extra warning
1404          if (!newfile && !os_path_exists(fname)) {
1405            end = 0;
1406          }
1407        }
1408
1409        if (wfname != fname) {
1410          xfree(wfname);
1411        }
1412        goto fail;
1413      }
1414      write_info.bw_fd = fd;
1415    }
1416    err = set_err(NULL);
1417
1418    write_info.bw_buf = buffer;
1419    nchars = 0;
1420
1421    // use "++bin", "++nobin" or 'binary'
1422    int write_bin;
1423    if (eap != NULL && eap->force_bin != 0) {
1424      write_bin = (eap->force_bin == FORCE_BIN);
1425    } else {
1426      write_bin = buf->b_p_bin;
1427    }
1428
1429    // Skip the BOM when appending and the file already existed, the BOM
1430    // only makes sense at the start of the file.
1431    if (buf->b_p_bomb && !write_bin && (!append || perm < 0)) {
1432      write_info.bw_len = make_bom(buffer, fenc);
1433      if (write_info.bw_len > 0) {
1434        // don't convert
1435        write_info.bw_flags = FIO_NOCONVERT | wb_flags;
1436        if (buf_write_bytes(&write_info) == FAIL) {
1437          end = 0;
1438        } else {
1439          nchars += write_info.bw_len;
1440        }
1441      }
1442    }
1443    write_info.bw_start_lnum = start;
1444
1445    write_undo_file = (buf->b_p_udf && overwriting && !append
1446                       && !filtering && reset_changed && !checking_conversion);
1447    if (write_undo_file) {
1448      // Prepare for computing the hash value of the text.
1449      sha256_start(&sha_ctx);
1450    }
1451
1452    write_info.bw_len = 0;
1453    write_info.bw_flags = wb_flags;
1454    fileformat = get_fileformat_force(buf, eap);
1455    char *s = buffer;
1456    for (lnum = start; lnum <= end; lnum++) {
1457      // The next while loop is done once for each character written.
1458      // Keep it fast!
1459      char *ptr = ml_get_buf(buf, lnum) - 1;
1460      if (write_undo_file) {
1461        sha256_update(&sha_ctx, (uint8_t *)ptr + 1, (uint32_t)(strlen(ptr + 1) + 1));
1462      }
1463      char c;
1464      while ((c = *++ptr) != NUL) {
1465        if (c == NL) {
1466          *s = NUL;                       // replace newlines with NULs
1467        } else if (c == CAR && fileformat == EOL_MAC) {
1468          *s = NL;                        // Mac: replace CRs with NLs
1469        } else {
1470          *s = c;
1471        }
1472        s++;
1473        if (++write_info.bw_len != bufsize) {
1474          continue;
1475        }
1476        if (buf_write_bytes(&write_info) == FAIL) {
1477          end = 0;                        // write error: break loop
1478          break;
1479        }
1480        nchars += bufsize - write_info.bw_len;
1481        s = buffer + write_info.bw_len;
1482        write_info.bw_start_lnum = lnum;
1483      }
1484      // write failed or last line has no EOL: stop here
1485      if (end == 0
1486          || (lnum == end
1487              && (write_bin || !buf->b_p_fixeol)
1488              && ((write_bin && lnum == buf->b_no_eol_lnum)
1489                  || (lnum == buf->b_ml.ml_line_count && !buf->b_p_eol)))) {
1490        lnum++;                           // written the line, count it
1491        no_eol = true;
1492        break;
1493      }
1494      if (fileformat == EOL_UNIX) {
1495        *s++ = NL;
1496      } else {
1497        *s++ = CAR;                       // EOL_MAC or EOL_DOS: write CR
1498        if (fileformat == EOL_DOS) {      // write CR-NL
1499          if (++write_info.bw_len == bufsize) {
1500            if (buf_write_bytes(&write_info) == FAIL) {
1501              end = 0;                    // write error: break loop
1502              break;
1503            }
1504            nchars += bufsize - write_info.bw_len;
1505            s = buffer + write_info.bw_len;
1506          }
1507          *s++ = NL;
1508        }
1509      }
1510      if (++write_info.bw_len == bufsize) {
1511        if (buf_write_bytes(&write_info) == FAIL) {
1512          end = 0;  // Write error: break loop.
1513          break;
1514        }
1515        nchars += bufsize - write_info.bw_len;
1516        s = buffer + write_info.bw_len;
1517
1518        os_breakcheck();
1519        if (got_int) {
1520          end = 0;  // Interrupted, break loop.
1521          break;
1522        }
1523      }
1524    }
1525    if (write_info.bw_len > 0 && end > 0) {
1526      int remaining = write_info.bw_len;
1527      if (buf_write_bytes(&write_info) == FAIL) {
1528        end = 0;                      // write error
1529      }
1530      nchars += remaining - write_info.bw_len;
1531    }
1532
1533    // Did we convert & write everything?
1534    if (end != 0 && write_info.bw_len > 0) {
1535      write_info.bw_conv_error = true;
1536      write_info.bw_conv_error_lnum = end;
1537      end = 0;
1538    }
1539
1540    if (!buf->b_p_fixeol && buf->b_p_eof) {
1541      // write trailing CTRL-Z
1542      write_eintr(write_info.bw_fd, "\x1a", 1);
1543    }
1544
1545    // Stop when writing done or an error was encountered.
1546    if (!checking_conversion || end == 0) {
1547      break;
1548    }
1549
1550    // If no error happened until now, writing should be ok, so loop to
1551    // really write the buffer.
1552  }
1553
1554  // If we started writing, finish writing. Also when an error was
1555  // encountered.
1556  if (!checking_conversion) {
1557    // On many journalling file systems there is a bug that causes both the
1558    // original and the backup file to be lost when halting the system right
1559    // after writing the file.  That's because only the meta-data is
1560    // journalled.  Syncing the file slows down the system, but assures it has
1561    // been written to disk and we don't lose it.
1562    // For a device do try the fsync() but don't complain if it does not work
1563    // (could be a pipe).
1564    // If the 'fsync' option is false, don't fsync().  Useful for laptops.
1565    int error;
1566    if ((buf->b_p_fs >= 0 ? buf->b_p_fs : p_fs) && (error = os_fsync(fd)) != 0
1567        // fsync not supported on this storage.
1568        && error != UV_ENOTSUP && !device) {
1569      err = set_err_arg(e_fsync, error);
1570      end = 0;
1571    }
1572
1573    if (!backup_copy) {
1574#ifdef HAVE_XATTR
1575      os_copy_xattr(backup, wfname);
1576#endif
1577    }
1578
1579#ifdef UNIX
1580    // When creating a new file, set its owner/group to that of the original
1581    // file.  Get the new device and inode number.
1582    if (backup != NULL && !backup_copy) {
1583      // don't change the owner when it's already OK, some systems remove
1584      // permission or ACL stuff
1585      FileInfo file_info;
1586      if (!os_fileinfo(wfname, &file_info)
1587          || file_info.stat.st_uid != file_info_old.stat.st_uid
1588          || file_info.stat.st_gid != file_info_old.stat.st_gid) {
1589        os_fchown(fd, (uv_uid_t)file_info_old.stat.st_uid, (uv_gid_t)file_info_old.stat.st_gid);
1590        if (perm >= 0) {  // Set permission again, may have changed.
1591          os_setperm(wfname, perm);
1592        }
1593      }
1594      buf_set_file_id(buf);
1595    } else if (!buf->file_id_valid) {
1596      // Set the file_id when creating a new file.
1597      buf_set_file_id(buf);
1598    }
1599#endif
1600
1601    if ((error = os_close(fd)) != 0) {
1602      err = set_err_arg(_("E512: Close failed: %s"), error);
1603      end = 0;
1604    }
1605
1606#ifdef UNIX
1607    if (made_writable) {
1608      perm &= ~0200;              // reset 'w' bit for security reasons
1609    }
1610#endif
1611    if (perm >= 0) {  // Set perm. of new file same as old file.
1612      os_setperm(wfname, perm);
1613    }
1614    // Probably need to set the ACL before changing the user (can't set the
1615    // ACL on a file the user doesn't own).
1616    if (!backup_copy) {
1617      os_set_acl(wfname, acl);
1618    }
1619
1620    if (wfname != fname) {
1621      // The file was written to a temp file, now it needs to be converted
1622      // with 'charconvert' to (overwrite) the output file.
1623      if (end != 0) {
1624        if (eval_charconvert("utf-8", fenc, wfname, fname) == FAIL) {
1625          write_info.bw_conv_error = true;
1626          end = 0;
1627        }
1628      }
1629      os_remove(wfname);
1630      xfree(wfname);
1631    }
1632  }
1633
1634  if (end == 0) {
1635    // Error encountered.
1636    if (err.msg == NULL) {
1637      if (write_info.bw_conv_error) {
1638        if (write_info.bw_conv_error_lnum == 0) {
1639          err = set_err(_(e_write_error_conversion_failed_make_fenc_empty_to_override));
1640        } else {
1641          err = set_err(xmalloc(300));
1642          err.alloc = true;
1643          vim_snprintf(err.msg, 300,  // NOLINT(runtime/printf)
1644                       _(e_write_error_conversion_failed_in_line_nr_make_fenc_empty_to_override),
1645                       write_info.bw_conv_error_lnum);
1646        }
1647      } else if (got_int) {
1648        err = set_err(_(e_interr));
1649      } else {
1650        err = set_err(_(e_write_error_file_system_full));
1651      }
1652    }
1653
1654    // If we have a backup file, try to put it in place of the new file,
1655    // because the new file is probably corrupt.  This avoids losing the
1656    // original file when trying to make a backup when writing the file a
1657    // second time.
1658    // When "backup_copy" is set we need to copy the backup over the new
1659    // file.  Otherwise rename the backup file.
1660    // If this is OK, don't give the extra warning message.
1661    if (backup != NULL) {
1662      if (backup_copy) {
1663        // This may take a while, if we were interrupted let the user
1664        // know we got the message.
1665        if (got_int) {
1666          msg(_(e_interr), 0);
1667          ui_flush();
1668        }
1669
1670        // copy the file.
1671        if (os_copy(backup, fname, UV_FS_COPYFILE_FICLONE)
1672            == 0) {
1673          end = 1;  // success
1674        }
1675      } else {
1676        if (vim_rename(backup, fname) == 0) {
1677          end = 1;
1678        }
1679      }
1680    }
1681    goto fail;
1682  }
1683
1684  lnum -= start;            // compute number of written lines
1685  no_wait_return--;         // may wait for return now
1686
1687#ifndef UNIX
1688  fname = sfname;           // use shortname now, for the messages
1689#endif
1690  if (!filtering) {
1691    add_quoted_fname(IObuff, IOSIZE, buf, fname);
1692    bool insert_space = false;
1693    if (write_info.bw_conv_error) {
1694      xstrlcat(IObuff, _(" CONVERSION ERROR"), IOSIZE);
1695      insert_space = true;
1696      if (write_info.bw_conv_error_lnum != 0) {
1697        vim_snprintf_add(IObuff, IOSIZE, _(" in line %" PRId64 ";"),
1698                         (int64_t)write_info.bw_conv_error_lnum);
1699      }
1700    } else if (notconverted) {
1701      xstrlcat(IObuff, _("[NOT converted]"), IOSIZE);
1702      insert_space = true;
1703    } else if (converted) {
1704      xstrlcat(IObuff, _("[converted]"), IOSIZE);
1705      insert_space = true;
1706    }
1707    if (device) {
1708      xstrlcat(IObuff, _("[Device]"), IOSIZE);
1709      insert_space = true;
1710    } else if (newfile) {
1711      xstrlcat(IObuff, _("[New]"), IOSIZE);
1712      insert_space = true;
1713    }
1714    if (no_eol) {
1715      xstrlcat(IObuff, _("[noeol]"), IOSIZE);
1716      insert_space = true;
1717    }
1718    // may add [unix/dos/mac]
1719    if (msg_add_fileformat(fileformat)) {
1720      insert_space = true;
1721    }
1722    msg_add_lines(insert_space, lnum, nchars);       // add line/char count
1723    if (!shortmess(kShmWrite)) {
1724      if (append) {
1725        xstrlcat(IObuff, shortmess(kShmWri) ? _(" [a]") : _(" appended"), IOSIZE);
1726      } else {
1727        xstrlcat(IObuff, shortmess(kShmWri) ? _(" [w]") : _(" written"), IOSIZE);
1728      }
1729    }
1730    // Hide cursor while emitting "written" message, so cursor doesn't flicker in cmdline. #25974
1731    ui_busy_start();
1732    set_keep_msg(msg_progress(IObuff, msg_id, "success", 0, true, true, false), 0);
1733    ui_busy_stop();
1734  }
1735
1736  // When written everything correctly: reset 'modified'.  Unless not
1737  // writing to the original file and '+' is not in 'cpoptions'.
1738  if (reset_changed && whole && !append
1739      && !write_info.bw_conv_error
1740      && (overwriting || vim_strchr(p_cpo, kCpoPlus) != NULL)) {
1741    unchanged(buf, true, false);
1742    const varnumber_T changedtick = buf_get_changedtick(buf);
1743    if (buf->b_last_changedtick + 1 == changedtick) {
1744      // b:changedtick may be incremented in unchanged() but that should not
1745      // trigger a TextChanged event.
1746      buf->b_last_changedtick = changedtick;
1747    }
1748    u_unchanged(buf);
1749    u_update_save_nr(buf);
1750  }
1751
1752  // If written to the current file, update the timestamp of the swap file
1753  // and reset the BF_WRITE_MASK flags. Also sets buf->b_mtime.
1754  if (overwriting) {
1755    ml_timestamp(buf);
1756    if (append) {
1757      buf->b_flags &= ~BF_NEW;
1758    } else {
1759      buf->b_flags &= ~BF_WRITE_MASK;
1760    }
1761  }
1762
1763  // If we kept a backup until now, and we are in patch mode, then we make
1764  // the backup file our 'original' file.
1765  if (*p_pm && dobackup) {
1766    char *const org = modname(fname, p_pm, false);
1767
1768    if (backup != NULL) {
1769      // If the original file does not exist yet
1770      // the current backup file becomes the original file
1771      if (org == NULL) {
1772        emsg(_("E205: Patchmode: can't save original file"));
1773      } else if (!os_path_exists(org)) {
1774        vim_rename(backup, org);
1775        XFREE_CLEAR(backup);                   // don't delete the file
1776#ifdef UNIX
1777        os_file_settime(org,
1778                        (double)file_info_old.stat.st_atim.tv_sec,
1779                        (double)file_info_old.stat.st_mtim.tv_sec);
1780#endif
1781      }
1782    } else {
1783      // If there is no backup file, remember that a (new) file was
1784      // created.
1785      int empty_fd;
1786
1787      if (org == NULL
1788          || (empty_fd = os_open(org,
1789                                 O_CREAT | O_EXCL | O_NOFOLLOW,
1790                                 perm < 0 ? 0666 : (perm & 0777))) < 0) {
1791        emsg(_(e_patchmode_cant_touch_empty_original_file));
1792      } else {
1793        close(empty_fd);
1794      }
1795    }
1796    if (org != NULL) {
1797      os_setperm(org, os_getperm(fname) & 0777);
1798      xfree(org);
1799    }
1800  }
1801
1802  // Remove the backup unless 'backup' option is set
1803  if (!p_bk && backup != NULL
1804      && !write_info.bw_conv_error
1805      && os_remove(backup) != 0) {
1806    emsg(_("E207: Can't delete backup file"));
1807  }
1808
1809  goto nofail;
1810
1811  // Finish up.  We get here either after failure or success.
1812fail:
1813  no_wait_return--;             // may wait for return now
1814nofail:
1815
1816  // Done saving, we accept changed buffer warnings again
1817  buf->b_saving = false;
1818
1819  xfree(backup);
1820  if (buffer != smallbuf) {
1821    xfree(buffer);
1822  }
1823  xfree(fenc_tofree);
1824  xfree(write_info.bw_conv_buf);
1825  if (write_info.bw_iconv_fd != (iconv_t)-1) {
1826    iconv_close(write_info.bw_iconv_fd);
1827    write_info.bw_iconv_fd = (iconv_t)-1;
1828  }
1829  os_free_acl(acl);
1830
1831  if (err.msg != NULL) {
1832    // - 100 to save some space for further error message.
1833    add_quoted_fname(IObuff, IOSIZE - 100, buf, msgname);
1834    // The error ends the progress-msg started by filemess_progress().
1835    emit_err(&err, filtering ? NULL : msg_id);
1836
1837    retval = FAIL;
1838    if (end == 0) {
1839      const int hl_id = HLF_E;  // Set highlight for error messages.
1840      msg_puts_hl(_("\nWARNING: Original file may be lost or damaged\n"), hl_id, true);
1841      msg_puts_hl(_("don't quit the editor until the file is successfully written!"), hl_id, true);
1842
1843      // Update the timestamp to avoid an "overwrite changed file"
1844      // prompt when writing again.
1845      if (os_fileinfo(fname, &file_info_old)) {
1846        buf_store_file_info(buf, &file_info_old);
1847        buf->b_mtime_read = buf->b_mtime;
1848        buf->b_mtime_read_ns = buf->b_mtime_ns;
1849      }
1850    }
1851  }
1852  msg_scroll = msg_save;
1853
1854  // When writing the whole file and 'undofile' is set, also write the undo
1855  // file.
1856  if (retval == OK && write_undo_file) {
1857    uint8_t hash[UNDO_HASH_SIZE];
1858
1859    sha256_finish(&sha_ctx, hash);
1860    u_write_undo(NULL, false, buf, hash);
1861  }
1862
1863  if (!should_abort(retval)) {
1864    buf_write_do_post_autocmds(buf, fname, eap, append, filtering, reset_changed, whole);
1865    if (aborting()) {       // autocmds may abort script processing
1866      retval = false;
1867    }
1868  }
1869
1870  got_int |= prev_got_int;
1871
1872  xfree(fname_copy);
1873  xfree(sfname_copy);
1874  xfree(ffname_copy);
1875
1876  return retval;
1877}