robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
aa1d8a2702
master
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 { 70const char * num ; 71char * msg ; 72int arg ; 73bool 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 { 80int bw_fd ;// file descriptor 81char * bw_buf ;// buffer with data to be written 82int bw_len ;// length of data 83int bw_flags ;// FIO_ flags 84int bw_first ;// first write call 85char * bw_conv_buf ;// buffer for writing converted chars 86size_t bw_conv_buflen ;// size of bw_conv_buf 87int bw_conv_error ;// set for conversion error 88linenr_T bw_conv_error_lnum ;// first line with error or zero 89linenr_T bw_start_lnum ;// line number at start of buffer 90iconv_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 ) 103FUNC_ATTR_NONNULL_ALL 104{ 105uint8_t * p = (uint8_t * )(* pp ); 106bool error = false; 107 108if (flags & FIO_UCS4 ) { 109if (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 )) { 121if (c >=0x10000 ) { 122if (flags & FIO_UTF16 ) { 123// Make two words, ten bits of the character in each. First 124// word is 0xd800 - 0xdbff, second one 0xdc00 - 0xdfff 125c -= 0x10000 ; 126if (c >=0x100000 ) { 127error = true; 128 } 129int cc = (int )(((c >>10 )& 0x3ff )+ 0xd800 ); 130if (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 } 137c = (c & 0x3ff )+ 0xdc00 ; 138 }else { 139error = true; 140 } 141 } 142if (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 150if (c >=0x100 ) { 151error = true; 152* p ++ = 0xBF ; 153 }else { 154* p ++ = (uint8_t )c ; 155 } 156 } 157 158* pp = (char * )p ; 159return 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{ 167int len = * lenp ; 168 169// Convert with iconv(). 170const char * from = * bufp ; 171size_t fromlen = (size_t )len ; 172size_t tolen = ip -> bw_conv_buflen ; 173char * to = ip -> bw_conv_buf ; 174 175if (ip -> bw_first ) { 176size_t save_len = tolen ; 177 178// output the initial shift state sequence 179iconv (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". 183if (to == NULL ) { 184to = ip -> bw_conv_buf ; 185tolen = save_len ; 186 } 187ip -> bw_first = false; 188 } 189 190// If iconv() has an error, fail. 191if (iconv (ip -> bw_iconv_fd , (void * )& from ,& fromlen ,& to ,& tolen ) 192== (size_t )-1 && ICONV_ERRNO != ICONV_EINVAL ) { 193ip -> bw_conv_error = true; 194return -1 ; 195 } 196 197* bufp = ip -> bw_conv_buf ; 198* lenp = (int )(to - ip -> bw_conv_buf ); 199 200return 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{ 214int flags = ip -> bw_flags ;// extra flags 215 216int wlen = * lenp ; 217if (flags & (FIO_UCS4 |FIO_UTF16 |FIO_UCS2 |FIO_LATIN1 )) { 218unsigned c ; 219int 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 223char * p = flags & FIO_LATIN1 ?* bufp :ip -> bw_conv_buf ; 224for (wlen = 0 ;wlen < * lenp ;wlen += n ) { 225n = utf_ptr2len_len (* bufp + wlen ,* lenp - wlen ); 226if (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. 230break ; 231 } 232c = n > 1 ? (unsigned )utf_ptr2char (* bufp + wlen ) 233 : (uint8_t )(* bufp )[wlen ]; 234// Check that there is enough space 235if (!(flags & FIO_LATIN1 )) { 236size_t need = (flags & FIO_UCS4 ) ?4 :2 ; 237if ((flags & FIO_UTF16 )&& c >=0x10000 ) { 238need = 4 ; 239 } 240 241if ((size_t )(p - ip -> bw_conv_buf )+ need > ip -> bw_conv_buflen ) { 242return FAIL ; 243 } 244 } 245 246if (ucs2bytes (c ,& p ,flags )&& !ip -> bw_conv_error ) { 247ip -> bw_conv_error = true; 248ip -> bw_conv_error_lnum = ip -> bw_start_lnum ; 249 } 250if (c == NL ) { 251ip -> bw_start_lnum ++ ; 252 } 253 } 254if (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 262if (ip -> bw_iconv_fd != (iconv_t )- 1 ) { 263return buf_write_convert_with_iconv (ip ,bufp ,lenp ); 264 } 265 266return 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{ 275char * buf = ip -> bw_buf ;// data to write 276int len = ip -> bw_len ;// length of data 277int flags = ip -> bw_flags ;// extra flags 278 279int converted = len ; 280int remaining = 0 ; 281 282// Skip conversion when writing the BOM. 283if (!(flags & FIO_NOCONVERT )) { 284if ((converted = buf_write_convert (ip ,& buf ,& len ))< 0 ) { 285return FAIL ; 286 } 287 288remaining = ip -> bw_len - converted ; 289 } 290 291ip -> bw_len = remaining ; 292 293// Skip writing while checking conversion 294if (ip -> bw_fd >=0 ) { 295int wlen = (int )write_eintr (ip -> bw_fd ,buf , (size_t )len ); 296if (wlen < len ) { 297return FAIL ; 298 } 299 } 300 301if (remaining > 0 ) { 302memmove (ip -> bw_buf ,ip -> bw_buf + converted , (size_t )remaining ); 303 } 304 305return 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{ 313if (buf -> b_mtime_read != 0 314&& time_differs (file_info ,buf -> b_mtime_read ,buf -> b_mtime_read_ns )) { 315msg_scroll = true;// Don't overwrite messages here. 316msg_silent = 0 ;// Must give this prompt. 317// Don't use emsg() here, don't want to flush the buffers. 318msg (_ ("WARNING: The file has been changed since reading it!!!" ),HLF_E ); 319if (ask_yesno (_ ("Do you really want to write to it" ))== 'n' ) { 320return FAIL ; 321 } 322msg_scroll = false;// Always overwrite the file message now. 323 } 324return 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{ 332uint8_t * buf = (uint8_t * )buf_in ; 333int flags = get_fio_flags (name ); 334 335// Can't put a BOM in a non-Unicode file. 336if (flags == FIO_LATIN1 || flags == 0 ) { 337return 0 ; 338 } 339 340if (flags == FIO_UTF8 ) {// UTF-8 341buf [0 ]= 0xef ; 342buf [1 ]= 0xbb ; 343buf [2 ]= 0xbf ; 344return 3 ; 345 } 346char * p = (char * )buf ; 347ucs2bytes (0xfeff ,& p ,flags ); 348return (int )((uint8_t * )p - buf ); 349} 350 351static int buf_write_do_autocmds (buf_T * buf ,char ** fnamep ,char ** sfnamep ,char ** ffnamep , 352linenr_T start ,linenr_T * endp ,exarg_T * eap ,bool append , 353bool filtering ,bool reset_changed ,bool overwriting ,bool whole , 354const pos_T orig_start ,const pos_T orig_end ) 355{ 356linenr_T old_line_count = buf -> b_ml .ml_line_count ; 357int msg_save = msg_scroll ; 358 359CtxSwitch aco = {0 }; 360bool did_cmd = false; 361bool nofile_err = false; 362bool empty_memline = buf -> b_ml .ml_mfp == NULL ; 363bufref_T bufref ; 364 365char * 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! 370bool buf_ffname = * ffnamep == buf -> b_ffname ; 371bool buf_sfname = sfname == buf -> b_sfname ; 372bool buf_fname_f = * fnamep == buf -> b_ffname ; 373bool buf_fname_s = * fnamep == buf -> b_sfname ; 374 375// Set curwin/curbuf to buf and save a few things. 376ctx_switch (& aco ,NULL ,NULL ,buf ,0 ); 377set_bufref (& bufref ,buf ); 378 379if (append ) { 380did_cmd = apply_autocmds_exarg (EVENT_FILEAPPENDCMD ,sfname ,sfname , false,curbuf ,eap ); 381if (!did_cmd ) { 382if (overwriting && bt_nofilename (curbuf )) { 383nofile_err = true; 384 }else { 385apply_autocmds_exarg (EVENT_FILEAPPENDPRE , 386sfname ,sfname , false,curbuf ,eap ); 387 } 388 } 389 }else if (filtering ) { 390apply_autocmds_exarg (EVENT_FILTERWRITEPRE , 391NULL ,sfname , false,curbuf ,eap ); 392 }else if (reset_changed && whole ) { 393bool was_changed = curbufIsChanged (); 394 395did_cmd = apply_autocmds_exarg (EVENT_BUFWRITECMD ,sfname ,sfname , false,curbuf ,eap ); 396if (did_cmd ) { 397if (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'. 401u_unchanged (curbuf ); 402u_update_save_nr (curbuf ); 403 } 404 }else { 405if (overwriting && bt_nofilename (curbuf )) { 406nofile_err = true; 407 }else { 408apply_autocmds_exarg (EVENT_BUFWRITEPRE , 409sfname ,sfname , false,curbuf ,eap ); 410 } 411 } 412 }else { 413did_cmd = apply_autocmds_exarg (EVENT_FILEWRITECMD ,sfname ,sfname , false,curbuf ,eap ); 414if (!did_cmd ) { 415if (overwriting && bt_nofilename (curbuf )) { 416nofile_err = true; 417 }else { 418apply_autocmds_exarg (EVENT_FILEWRITEPRE , 419sfname ,sfname , false,curbuf ,eap ); 420 } 421 } 422 } 423 424// restore curwin/curbuf and a few other things 425ctx_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. 431if (!bufref_valid (& bufref )) { 432buf = NULL ; 433 } 434if (buf == NULL || (buf -> b_ml .ml_mfp == NULL && !empty_memline ) 435|| did_cmd || nofile_err 436|| aborting ()) { 437if (buf != NULL && (cmdmod .cmod_flags & CMOD_LOCKMARKS )) { 438// restore the original '[ and '] positions 439buf -> b_op_start = orig_start ; 440buf -> b_op_end = orig_end ; 441 } 442 443no_wait_return -- ; 444msg_scroll = msg_save ; 445if (nofile_err ) { 446semsg (_ (e_no_matching_autocommands_for_buftype_str_buffer ),curbuf -> b_p_bt ); 447 } 448 449if (nofile_err || aborting ()) { 450// An aborting error, interrupt or exception in the 451// autocommands. 452return FAIL ; 453 } 454if (did_cmd ) { 455if (buf == NULL ) { 456// The buffer was deleted. We assume it was written 457// (can't retry anyway). 458return OK ; 459 } 460if (overwriting ) { 461// Assume the buffer was written, update the timestamp. 462ml_timestamp (buf ); 463if (append ) { 464buf -> b_flags &= ~BF_NEW ; 465 }else { 466buf -> b_flags &= ~BF_WRITE_MASK ; 467 } 468 } 469if (reset_changed && buf -> b_changed && !append 470&& (overwriting || vim_strchr (p_cpo ,kCpoPlus )!= NULL )) { 471// Buffer still changed, the autocommands didn't work properly. 472return FAIL ; 473 } 474return OK ; 475 } 476if (!aborting ()) { 477emsg (_ ("E203: Autocommands deleted or unloaded buffer to be written" )); 478 } 479return 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!). 486if (buf -> b_ml .ml_line_count != old_line_count ) { 487if (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 ; 493if (* endp < start ) { 494no_wait_return -- ; 495msg_scroll = msg_save ; 496emsg (_ ("E204: Autocommand changed number of lines in unexpected way" )); 497return 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. 505if (buf_ffname ) { 506* ffnamep = buf -> b_ffname ; 507 } 508if (buf_sfname ) { 509* sfnamep = buf -> b_fname ; 510 } 511if (buf_fname_f ) { 512* fnamep = buf -> b_ffname ; 513 } 514if (buf_fname_s ) { 515* fnamep = buf -> b_fname ; 516 } 517return NOTDONE ; 518} 519 520static void buf_write_do_post_autocmds (buf_T * buf ,char * fname ,exarg_T * eap ,bool append , 521bool filtering ,bool reset_changed ,bool whole ) 522{ 523CtxSwitch aco = {0 }; 524 525curbuf -> 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! 529ctx_switch (& aco ,NULL ,NULL ,buf ,0 ); 530 531if (append ) { 532apply_autocmds_exarg (EVENT_FILEAPPENDPOST ,fname ,fname , 533 false,curbuf ,eap ); 534 }else if (filtering ) { 535apply_autocmds_exarg (EVENT_FILTERWRITEPOST ,NULL ,fname , 536 false,curbuf ,eap ); 537 }else if (reset_changed && whole ) { 538apply_autocmds_exarg (EVENT_BUFWRITEPOST ,fname ,fname , 539 false,curbuf ,eap ); 540 }else { 541apply_autocmds_exarg (EVENT_FILEWRITEPOST ,fname ,fname , 542 false,curbuf ,eap ); 543 } 544 545// restore curwin/curbuf and a few other things 546ctx_restore (& aco ); 547} 548 549static inline Error_T set_err_num (const char * num ,const char * msg ) 550{ 551return (Error_T ){ .num = num , .msg = (char * )msg , .arg = 0 }; 552} 553 554static inline Error_T set_err (const char * msg ) 555{ 556return (Error_T ){ .num = NULL , .msg = (char * )msg , .arg = 0 }; 557} 558 559static inline Error_T set_err_arg (const char * msg ,int arg ) 560{ 561return (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{ 569char errmsg [IOSIZE ]; 570if (e -> num != NULL && e -> arg != 0 ) { 571vim_snprintf (errmsg ,IOSIZE ,"%s: %s%s: %s" ,e -> num ,IObuff ,e -> msg ,os_strerror (e -> arg )); 572 }else if (e -> num != NULL ) { 573vim_snprintf (errmsg ,IOSIZE ,"%s: %s%s" ,e -> num ,IObuff ,e -> msg ); 574 }else if (e -> arg != 0 ) { 575vim_snprintf (errmsg ,IOSIZE ,e -> msg ,os_strerror (e -> arg )); 576 }else { 577xstrlcpy (errmsg ,e -> msg ,IOSIZE ); 578 } 579if (msg_id != NULL ) { 580msg_progress (errmsg ,msg_id ,"failed" ,HLF_E , false, false, true); 581 }else { 582emsg (errmsg ); 583 } 584if (e -> alloc ) { 585xfree (e -> msg ); 586 } 587} 588 589#ifdef UNIX 590 591static int get_fileinfo_os (char * fname ,FileInfo * file_info_old ,bool overwriting ,int * perm , 592bool * device ,bool * newfile ,Error_T * err ) 593{ 594* perm = -1 ; 595if (!os_fileinfo (fname ,file_info_old )) { 596* newfile = true; 597 }else { 598* perm = (int )file_info_old -> stat .st_mode ; 599if (!S_ISREG (file_info_old -> stat .st_mode )) {// not a file 600if (S_ISDIR (file_info_old -> stat .st_mode )) { 601* err = set_err_num ("E502" ,_ ("is a directory" )); 602return FAIL ; 603 } 604if (os_nodetype (fname )!= NODE_WRITABLE ) { 605* err = set_err_num ("E503" ,_ ("is not a file or writable device" )); 606return 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 } 615return OK ; 616} 617 618#else 619 620static int get_fileinfo_os (char * fname ,FileInfo * file_info_old ,bool overwriting ,int * perm , 621bool * device ,bool * newfile ,Error_T * err ) 622{ 623// Check for a writable device name. 624char nodetype = fname == NULL ?NODE_OTHER : (char )os_nodetype (fname ); 625if (nodetype == NODE_OTHER ) { 626* err = set_err_num ("E503" ,_ ("is not a file or writable device" )); 627return FAIL ; 628 } 629if (nodetype == NODE_WRITABLE ) { 630* device = true; 631* newfile = true; 632* perm = -1 ; 633 }else { 634* perm = os_getperm (fname ); 635if (* perm < 0 ) { 636* newfile = true; 637 }else if (os_isdir (fname )) { 638* err = set_err_num ("E502" ,_ ("is a directory" )); 639return FAIL ; 640 } 641if (overwriting ) { 642os_fileinfo (fname ,file_info_old ); 643 } 644 } 645return 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 , 660FileInfo * file_info_old ,int * perm ,bool * device ,bool * newfile , 661bool * readonly ,Error_T * err ) 662{ 663if (get_fileinfo_os (fname ,file_info_old ,overwriting ,perm ,device ,newfile ,err )== FAIL ) { 664return FAIL ; 665 } 666 667* readonly = false;// overwritten file is read-only 668 669if (!* 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 674if (!forceit && * readonly ) { 675if (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 } 680return FAIL ; 681 } 682 683// If 'forceit' is false, check if the timestamp hasn't changed since reading the file. 684if (overwriting && !forceit ) { 685int retval = check_mtime (buf ,file_info_old ); 686if (retval == FAIL ) { 687return FAIL ; 688 } 689 } 690 } 691return 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{ 697char * backup = NULL ; 698// Isolate one directory name, using an entry in 'bdir'. 699size_t dir_len = copy_option_part (dirp ,IObuff ,IOSIZE ,"," ); 700char * p = IObuff + dir_len ; 701if (** dirp == NUL && !os_isdir (IObuff )) { 702int ret ; 703char * failed_dir ; 704if ((ret = os_mkdir_recurse (IObuff ,0755 ,& failed_dir ,NULL ))!= 0 ) { 705semsg (_ ("E303: Unable to create directory \"%s\" for backup file: %s" ), 706failed_dir ,os_strerror (ret )); 707xfree (failed_dir ); 708 } 709 } 710if (dir_len > 1 && after_pathsep (IObuff ,p )&& p [-1 ]== p [-2 ]) { 711// path ends with '//', use full path 712if ((p = make_percent_swname (IObuff ,p ,fname )) 713!= NULL ) { 714backup = modname (p ,backup_ext ,no_prepend_dot ); 715xfree (p ); 716 } 717 } 718if (backup == NULL ) { 719char * rootname = get_file_in_dir (fname ,IObuff ); 720if (rootname != NULL ) { 721backup = modname (rootname ,backup_ext ,no_prepend_dot ); 722xfree (rootname ); 723 } 724 } 725return backup ; 726} 727 728static int buf_write_make_backup (char * fname ,bool append ,FileInfo * file_info_old ,vim_acl_T acl , 729int perm ,unsigned bkc ,bool file_readonly ,bool forceit , 730bool * backup_copyp ,char ** backupp ,Error_T * err ) 731{ 732FileInfo file_info ; 733const bool no_prepend_dot = false; 734 735if ((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 742if (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). 751size_t dirlen = (size_t )(path_tail (fname )- fname ); 752assert (dirlen < MAXPATHL ); 753char tmp_fname [MAXPATHL ]; 754xmemcpyz (tmp_fname ,fname ,dirlen ); 755for (int i = 4913 ;;i += 123 ) { 756snprintf (tmp_fname + dirlen ,sizeof (tmp_fname )- dirlen ,"%d" ,i ); 757if (!os_fileinfo_link (tmp_fname ,& file_info )) { 758break ; 759 } 760 } 761int fd = os_open (tmp_fname , 762O_CREAT |O_WRONLY |O_EXCL |O_NOFOLLOW ,perm ); 763if (fd < 0 ) {// can't write in directory 764* backup_copyp = true; 765 }else { 766#ifdef UNIX 767os_fchown (fd , (uv_uid_t )file_info_old -> stat .st_uid , (uv_gid_t )file_info_old -> stat .st_gid ); 768os_fsetperm (fd ,perm ); 769if (!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. 778close (fd ); 779os_remove (tmp_fname ); 780 } 781 } 782 } 783 784// Break symlinks and/or hardlinks if we've been asked to. 785if ((bkc & kOptBkcFlagBreaksymlink )|| (bkc & kOptBkcFlagBreakhardlink )) { 786#ifdef UNIX 787bool file_info_link_ok = os_fileinfo_link (fname ,& file_info ); 788 789// Symlinks. 790if ((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. 797if ((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 807char * backup_ext = * p_bex == NUL ?".bak" :p_bex ; 808 809if (* backup_copyp ) { 810bool 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. 822char * dirp = p_bdir ; 823while (* dirp ) { 824* backupp = buf_get_backup_name (fname ,& dirp ,no_prepend_dot ,backup_ext ); 825if (* backupp == NULL ) { 826some_error = true;// out of memory 827 gotonobackup ; 828 } 829 830FileInfo file_info_new ; 831 { 832// Check if backup file already exists. 833if (os_fileinfo (* backupp ,& file_info_new )) { 834if (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// 841XFREE_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// 847char * wp = * backupp + strlen (* backupp )- 1 - strlen (backup_ext ); 848wp = MAX (wp ,* backupp );// empty file name ??? 849* wp = 'z' ; 850while (* wp > 'a' && os_fileinfo (* backupp ,& file_info_new )) { 851 (* wp )-- ; 852 } 853// They all exist??? Must be something wrong. 854if (* wp == 'a' ) { 855XFREE_CLEAR (* backupp ); 856 } 857 } 858 } 859 } 860 861// Try to create the backup file 862if (* backupp != NULL ) { 863// remove old backup, if present 864os_remove (* backupp ); 865 866// copy the file 867if (os_copy (fname ,* backupp ,UV_FS_COPYFILE_FICLONE )!= 0 ) { 868* err = set_err (_ ("E509: Cannot create backup file (add ! to override)" )); 869XFREE_CLEAR (* backupp ); 870* backupp = NULL ; 871continue ; 872 } 873 874// set file protection same as original file, but 875// strip s-bit. 876os_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. 882if (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 ) { 884os_setperm (* backupp , (perm & 0707 ) | ((perm & 07 ) <<3 )); 885 } 886os_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 891os_set_acl (* backupp ,acl ); 892#ifdef HAVE_XATTR 893os_copy_xattr (fname ,* backupp ); 894#endif 895* err = set_err (NULL ); 896break ; 897 } 898 } 899 900nobackup : 901if (* 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. 905if ((some_error || err -> msg != NULL )&& !forceit ) { 906return 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. 915if (file_readonly && vim_strchr (p_cpo ,kCpoFwrite )!= NULL ) { 916* err = set_err_num ("E504" ,_ (err_readonly )); 917return 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. 923char * dirp = p_bdir ; 924while (* dirp ) { 925* backupp = buf_get_backup_name (fname ,& dirp ,no_prepend_dot ,backup_ext ); 926if (* 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. 930if (!p_bk && os_path_exists (* backupp )) { 931char * p = * backupp + strlen (* backupp )- 1 - strlen (backup_ext ); 932p = MAX (p ,* backupp );// empty file name ??? 933* p = 'z' ; 934while (* p > 'a' && os_path_exists (* backupp )) { 935 (* p )-- ; 936 } 937// They all exist??? Must be something wrong! 938if (* p == 'a' ) { 939XFREE_CLEAR (* backupp ); 940 } 941 } 942 } 943if (* 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/// 952if (vim_rename (fname ,* backupp )== 0 ) { 953break ; 954 } 955 956XFREE_CLEAR (* backupp );// don't do the rename below 957 } 958 } 959if (* backupp == NULL && !forceit ) { 960* err = set_err (_ ("E510: Can't make backup file (add ! to override)" )); 961return FAIL ; 962 } 963 } 964return 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 , 986bool append ,bool forceit ,bool reset_changed ,bool filtering ) 987{ 988int retval = OK ; 989int msg_save = msg_scroll ; 990bool prev_got_int = got_int ; 991// writing everything 992bool whole = (start == 1 && end == buf -> b_ml .ml_line_count ); 993bool write_undo_file = false; 994context_sha256_T sha_ctx ; 995unsigned bkc = get_bkc_flags (buf ); 996 997if (fname == NULL || * fname == NUL ) {// safety check 998return FAIL ; 999 } 1000if (buf -> b_ml .ml_mfp == NULL ) { 1001// This can happen during startup when there is a stray "w" in the 1002// vimrc file. 1003emsg (_ (e_empty_buffer )); 1004return FAIL ; 1005 } 1006 1007// Disallow writing in secure mode. 1008if (check_secure ()) { 1009return FAIL ; 1010 } 1011 1012// Avoid a crash for a long name. 1013if (strlen (fname ) >=MAXPATHL ) { 1014emsg (_ (e_longname )); 1015return FAIL ; 1016 } 1017 1018// Ensure all fields are initialized (zeroed, or else specified here). 1019struct 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. 1028if (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 ) { 1036if (set_rw_fname (fname ,sfname )== FAIL ) { 1037return FAIL ; 1038 } 1039buf = curbuf ;// just in case autocmds made "buf" invalid 1040 } 1041 1042if (sfname == NULL ) { 1043sfname = 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. 1050char * ffname = fname ;// remember full fname 1051#ifdef UNIX 1052fname = sfname ; 1053#endif 1054 1055// true if writing over original 1056bool overwriting = buf -> b_ffname != NULL && path_equal (ffname ,buf -> b_ffname ,kPathCmpLiteral ); 1057 1058no_wait_return ++ ;// don't wait for return yet 1059 1060const pos_T orig_start = buf -> b_op_start ; 1061const pos_T orig_end = buf -> b_op_end ; 1062 1063// Set '[ and '] marks to the lines to be written. 1064buf -> b_op_start .lnum = start ; 1065buf -> b_op_start .col = 0 ; 1066buf -> b_op_end .lnum = end ; 1067buf -> b_op_end .col = 0 ; 1068 1069int res = buf_write_do_autocmds (buf ,& fname ,& sfname ,& ffname ,start ,& end ,eap ,append , 1070filtering ,reset_changed ,overwriting ,whole ,orig_start , 1071orig_end ); 1072if (res != NOTDONE ) { 1073return 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 1078char * const fname_copy = xstrdup (fname ); 1079char * const sfname_copy = xstrdup (sfname ); 1080char * const ffname_copy = xstrdup (ffname ); 1081fname = fname_copy ; 1082sfname = sfname_copy ; 1083ffname = ffname_copy ; 1084 1085if (cmdmod .cmod_flags & CMOD_LOCKMARKS ) { 1086// restore the original '[ and '] positions 1087buf -> b_op_start = orig_start ; 1088buf -> b_op_end = orig_end ; 1089 } 1090 1091if (shortmess (kShmOver )&& !exiting ) { 1092msg_scroll = false;// overwrite previous file message 1093 }else { 1094msg_scroll = true;// don't overwrite previous file message 1095 } 1096// Progress-msg id, e.g. `nvim.bufwrite "foo.txt"`. 1097char msg_id [MAXPATHL + 32 ]; 1098#ifndef UNIX 1099char * msgname = sfname ; 1100#else 1101char * msgname = fname ; 1102#endif 1103size_t id_len = xstrlcpy (msg_id ,"nvim.bufwrite " ,sizeof (msg_id )); 1104add_quoted_fname (msg_id + id_len ,sizeof (msg_id )- id_len ,buf ,msgname ); 1105msg_id [strlen (msg_id )- 1 ]= NUL ;// add_quoted_fname() appends a space, for display only. 1106 1107if (!filtering ) { 1108// show that we are busy 1109filemess_progress (buf ,msgname ,msg_id ); 1110 } 1111msg_scroll = false;// always overwrite the file message now 1112 1113char * buffer = verbose_try_malloc (WRITEBUFSIZE ); 1114int bufsize ; 1115char smallbuf [SMALLBUFSIZE ]; 1116// can't allocate big buffer, use small one (to be able to write when out of 1117// memory) 1118if (buffer == NULL ) { 1119buffer = smallbuf ; 1120bufsize = SMALLBUFSIZE ; 1121 }else { 1122bufsize = WRITEBUFSIZE ; 1123 } 1124 1125Error_T err = {0 }; 1126int perm ;// file permissions 1127bool newfile = false;// true if file doesn't exist yet 1128bool device = false;// writing to a device 1129bool file_readonly = false;// overwritten file is read-only 1130char * backup = NULL ; 1131char * fenc_tofree = NULL ;// allocated "fenc" 1132 1133// Get information about original file (if there is one). 1134FileInfo file_info_old ; 1135 1136vim_acl_T acl = NULL ;// ACL copied from original file to 1137// backup or new file 1138 1139if (get_fileinfo (buf ,fname ,overwriting ,forceit ,& file_info_old ,& perm ,& device ,& newfile , 1140& file_readonly ,& err )== FAIL ) { 1141 gotofail ; 1142 } 1143 1144// For systems that support ACL: get the ACL from the original file. 1145if (!newfile ) { 1146acl = os_get_acl (fname ); 1147 } 1148 1149// If 'backupskip' is not empty, don't make a backup for some files. 1150bool dobackup = (p_wb || p_bk || * p_pm != NUL ); 1151if (dobackup && * p_bsk != NUL && match_file_list (p_bsk ,sfname ,ffname )) { 1152dobackup = false; 1153 } 1154 1155bool 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. 1160prev_got_int = got_int ; 1161got_int = false; 1162 1163// Mark the buffer as 'being saved' to prevent changed buffer warnings 1164buf -> 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. 1172if (!(append && * p_pm == NUL )&& !filtering && perm >=0 && dobackup ) { 1173if (buf_write_make_backup (fname ,append ,& file_info_old ,acl ,perm ,bkc ,file_readonly ,forceit , 1174& backup_copy ,& backup ,& err )== FAIL ) { 1175retval = FAIL ; 1176 gotofail ; 1177 } 1178 } 1179 1180#ifdef UNIX 1181bool made_writable = false;// 'w' bit has been set 1182 1183// When using ":w!" and the file was read-only: make it writable 1184if (forceit && perm >=0 && !(perm & 0200 ) 1185&& file_info_old .stat .st_uid == getuid () 1186&& vim_strchr (p_cpo ,kCpoFwrite )== NULL ) { 1187perm |=0200 ; 1188os_setperm (fname ,perm ); 1189made_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'. 1195if (forceit && overwriting && vim_strchr (p_cpo ,kCpoKeepro )== NULL ) { 1196buf -> b_p_ro = false; 1197need_maketitle = true;// set window title later 1198status_redraw_all ();// redraw status lines later 1199 } 1200 1201end = MIN (end ,buf -> b_ml .ml_line_count ); 1202if (buf -> b_ml .ml_flags & ML_EMPTY ) { 1203start = end + 1 ; 1204 } 1205 1206char * 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. 1213if (reset_changed && !newfile && overwriting && !(exiting && backup != NULL )) { 1214ml_preserve (buf , false, !!(buf -> b_p_fs >=0 ?buf -> b_p_fs :p_fs )); 1215if (got_int ) { 1216err = set_err (_ (e_interr )); 1217 gotorestore_backup ; 1218 } 1219 } 1220 1221// Default: write the file directly. May write to a temp file for 1222// multi-byte conversion. 1223wfname = fname ; 1224 1225char * fenc ;// effective 'fileencoding' 1226 1227// Check for forced 'fileencoding' from "++opt=val" argument. 1228if (eap != NULL && eap -> force_enc != 0 ) { 1229fenc = eap -> cmd + eap -> force_enc ; 1230fenc = enc_canonize (fenc ); 1231fenc_tofree = fenc ; 1232 }else { 1233fenc = buf -> b_p_fenc ; 1234 } 1235 1236// Check if the file needs to be converted. 1237bool converted = need_conversion (fenc ); 1238int 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. 1243if (converted ) { 1244wb_flags = get_fio_flags (fenc ); 1245if (wb_flags & (FIO_UCS2 |FIO_UCS4 |FIO_UTF16 |FIO_UTF8 )) { 1246// Need to allocate a buffer to translate into. 1247if (wb_flags & (FIO_UCS2 |FIO_UTF16 |FIO_UTF8 )) { 1248write_info .bw_conv_buflen = (size_t )bufsize * 2 ; 1249 }else {// FIO_UCS4 1250write_info .bw_conv_buflen = (size_t )bufsize * 4 ; 1251 } 1252write_info .bw_conv_buf = verbose_try_malloc (write_info .bw_conv_buflen ); 1253if (!write_info .bw_conv_buf ) { 1254end = 0 ; 1255 } 1256 } 1257 } 1258 1259if (converted && wb_flags == 0 ) { 1260// Use iconv() conversion when conversion is needed and it's not done 1261// internally. 1262write_info .bw_iconv_fd = (iconv_t )my_iconv_open (fenc ,"utf-8" ); 1263if (write_info .bw_iconv_fd != (iconv_t )- 1 ) { 1264// We're going to use iconv(), allocate a buffer to convert in. 1265write_info .bw_conv_buflen = (size_t )bufsize * ICONV_MULT ; 1266write_info .bw_conv_buf = verbose_try_malloc (write_info .bw_conv_buflen ); 1267if (!write_info .bw_conv_buf ) { 1268end = 0 ; 1269 } 1270write_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. 1275if (p_ccv .type != kCallbackNone ) { 1276wfname = vim_tempname (); 1277if (wfname == NULL ) {// Can't write without a tempfile! 1278err = set_err (_ ("E214: Can't find temp file for writing" )); 1279 gotorestore_backup ; 1280 } 1281 } 1282 } 1283 } 1284 1285bool notconverted = false; 1286 1287if (converted && wb_flags == 0 1288&& write_info .bw_iconv_fd == (iconv_t )- 1 1289&& wfname == fname ) { 1290if (!forceit ) { 1291err = set_err (_ ("E213: Cannot convert (add ! to write without conversion)" )); 1292 gotorestore_backup ; 1293 } 1294notconverted = true; 1295 } 1296 1297bool no_eol = false;// no end-of-line written 1298int nchars ; 1299linenr_T lnum ; 1300int fileformat ; 1301bool checking_conversion ; 1302 1303int 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. 1308for (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. 1313if (!converted || dobackup ) { 1314checking_conversion = false; 1315 } 1316 1317if (checking_conversion ) { 1318// Make sure we don't write anything. 1319fd = -1 ; 1320write_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. 1330const int fflags = O_WRONLY | (append 1331 ? (forceit ? (O_APPEND |O_CREAT ) :O_APPEND ) 1332 : (O_CREAT |O_TRUNC )); 1333const int mode = perm < 0 ?0666 : (perm & 0777 ); 1334 1335while ((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. 1339if (err .msg == NULL ) { 1340#ifdef UNIX 1341FileInfo file_info ; 1342 1343// Don't delete the file when it's a hard or symbolic link. 1344if ((!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 ))) { 1347err = set_err (_ ("E166: Can't open linked file for writing" )); 1348 }else { 1349err = set_err_arg (_ ("E212: Can't open file for writing: %s" ),fd ); 1350if (forceit && vim_strchr (p_cpo ,kCpoFwrite )== NULL && perm >=0 ) { 1351// we write to the file, thus it should be marked 1352// writable after all 1353if (!(perm & 0200 )) { 1354made_writable = true; 1355 } 1356perm |=0200 ; 1357if (file_info_old .stat .st_uid != getuid () 1358|| file_info_old .stat .st_gid != getgid ()) { 1359perm &=0777 ; 1360 } 1361if (!append ) {// don't remove when appending 1362os_remove (wfname ); 1363 } 1364continue ; 1365 } 1366 } 1367#else 1368err = set_err_arg (_ ("E212: Can't open file for writing: %s" ),fd ); 1369if (forceit && vim_strchr (p_cpo ,kCpoFwrite )== NULL && perm >=0 ) { 1370if (!append ) {// don't remove when appending 1371os_remove (wfname ); 1372 } 1373continue ; 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. 1383if (backup != NULL && wfname == fname ) { 1384if (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 1390if (!os_path_exists (fname )) { 1391vim_rename (backup ,fname ); 1392 } 1393// if original file does exist throw away the copy 1394if (os_path_exists (fname )) { 1395os_remove (backup ); 1396 } 1397 }else { 1398// try to put the original file back 1399vim_rename (backup ,fname ); 1400 } 1401 } 1402 1403// if original file no longer exists give an extra warning 1404if (!newfile && !os_path_exists (fname )) { 1405end = 0 ; 1406 } 1407 } 1408 1409if (wfname != fname ) { 1410xfree (wfname ); 1411 } 1412 gotofail ; 1413 } 1414write_info .bw_fd = fd ; 1415 } 1416err = set_err (NULL ); 1417 1418write_info .bw_buf = buffer ; 1419nchars = 0 ; 1420 1421// use "++bin", "++nobin" or 'binary' 1422int write_bin ; 1423if (eap != NULL && eap -> force_bin != 0 ) { 1424write_bin = (eap -> force_bin == FORCE_BIN ); 1425 }else { 1426write_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. 1431if (buf -> b_p_bomb && !write_bin && (!append || perm < 0 )) { 1432write_info .bw_len = make_bom (buffer ,fenc ); 1433if (write_info .bw_len > 0 ) { 1434// don't convert 1435write_info .bw_flags = FIO_NOCONVERT |wb_flags ; 1436if (buf_write_bytes (& write_info )== FAIL ) { 1437end = 0 ; 1438 }else { 1439nchars += write_info .bw_len ; 1440 } 1441 } 1442 } 1443write_info .bw_start_lnum = start ; 1444 1445write_undo_file = (buf -> b_p_udf && overwriting && !append 1446&& !filtering && reset_changed && !checking_conversion ); 1447if (write_undo_file ) { 1448// Prepare for computing the hash value of the text. 1449sha256_start (& sha_ctx ); 1450 } 1451 1452write_info .bw_len = 0 ; 1453write_info .bw_flags = wb_flags ; 1454fileformat = get_fileformat_force (buf ,eap ); 1455char * s = buffer ; 1456for (lnum = start ;lnum <=end ;lnum ++ ) { 1457// The next while loop is done once for each character written. 1458// Keep it fast! 1459char * ptr = ml_get_buf (buf ,lnum )- 1 ; 1460if (write_undo_file ) { 1461sha256_update (& sha_ctx , (uint8_t * )ptr + 1 , (uint32_t )(strlen (ptr + 1 )+ 1 )); 1462 } 1463char c ; 1464while ((c = *++ ptr )!= NUL ) { 1465if (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 } 1472s ++ ; 1473if (++ write_info .bw_len != bufsize ) { 1474continue ; 1475 } 1476if (buf_write_bytes (& write_info )== FAIL ) { 1477end = 0 ;// write error: break loop 1478break ; 1479 } 1480nchars += bufsize - write_info .bw_len ; 1481s = buffer + write_info .bw_len ; 1482write_info .bw_start_lnum = lnum ; 1483 } 1484// write failed or last line has no EOL: stop here 1485if (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 )))) { 1490lnum ++ ;// written the line, count it 1491no_eol = true; 1492break ; 1493 } 1494if (fileformat == EOL_UNIX ) { 1495* s ++ = NL ; 1496 }else { 1497* s ++ = CAR ;// EOL_MAC or EOL_DOS: write CR 1498if (fileformat == EOL_DOS ) {// write CR-NL 1499if (++ write_info .bw_len == bufsize ) { 1500if (buf_write_bytes (& write_info )== FAIL ) { 1501end = 0 ;// write error: break loop 1502break ; 1503 } 1504nchars += bufsize - write_info .bw_len ; 1505s = buffer + write_info .bw_len ; 1506 } 1507* s ++ = NL ; 1508 } 1509 } 1510if (++ write_info .bw_len == bufsize ) { 1511if (buf_write_bytes (& write_info )== FAIL ) { 1512end = 0 ;// Write error: break loop. 1513break ; 1514 } 1515nchars += bufsize - write_info .bw_len ; 1516s = buffer + write_info .bw_len ; 1517 1518os_breakcheck (); 1519if (got_int ) { 1520end = 0 ;// Interrupted, break loop. 1521break ; 1522 } 1523 } 1524 } 1525if (write_info .bw_len > 0 && end > 0 ) { 1526int remaining = write_info .bw_len ; 1527if (buf_write_bytes (& write_info )== FAIL ) { 1528end = 0 ;// write error 1529 } 1530nchars += remaining - write_info .bw_len ; 1531 } 1532 1533// Did we convert & write everything? 1534if (end != 0 && write_info .bw_len > 0 ) { 1535write_info .bw_conv_error = true; 1536write_info .bw_conv_error_lnum = end ; 1537end = 0 ; 1538 } 1539 1540if (!buf -> b_p_fixeol && buf -> b_p_eof ) { 1541// write trailing CTRL-Z 1542write_eintr (write_info .bw_fd ,"\x1a" ,1 ); 1543 } 1544 1545// Stop when writing done or an error was encountered. 1546if (!checking_conversion || end == 0 ) { 1547break ; 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. 1556if (!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. 1565int error ; 1566if ((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 ) { 1569err = set_err_arg (e_fsync ,error ); 1570end = 0 ; 1571 } 1572 1573if (!backup_copy ) { 1574#ifdef HAVE_XATTR 1575os_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. 1582if (backup != NULL && !backup_copy ) { 1583// don't change the owner when it's already OK, some systems remove 1584// permission or ACL stuff 1585FileInfo file_info ; 1586if (!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 ) { 1589os_fchown (fd , (uv_uid_t )file_info_old .stat .st_uid , (uv_gid_t )file_info_old .stat .st_gid ); 1590if (perm >=0 ) {// Set permission again, may have changed. 1591os_setperm (wfname ,perm ); 1592 } 1593 } 1594buf_set_file_id (buf ); 1595 }else if (!buf -> file_id_valid ) { 1596// Set the file_id when creating a new file. 1597buf_set_file_id (buf ); 1598 } 1599#endif 1600 1601if ((error = os_close (fd ))!= 0 ) { 1602err = set_err_arg (_ ("E512: Close failed: %s" ),error ); 1603end = 0 ; 1604 } 1605 1606#ifdef UNIX 1607if (made_writable ) { 1608perm &= ~0200 ;// reset 'w' bit for security reasons 1609 } 1610#endif 1611if (perm >=0 ) {// Set perm. of new file same as old file. 1612os_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). 1616if (!backup_copy ) { 1617os_set_acl (wfname ,acl ); 1618 } 1619 1620if (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. 1623if (end != 0 ) { 1624if (eval_charconvert ("utf-8" ,fenc ,wfname ,fname )== FAIL ) { 1625write_info .bw_conv_error = true; 1626end = 0 ; 1627 } 1628 } 1629os_remove (wfname ); 1630xfree (wfname ); 1631 } 1632 } 1633 1634if (end == 0 ) { 1635// Error encountered. 1636if (err .msg == NULL ) { 1637if (write_info .bw_conv_error ) { 1638if (write_info .bw_conv_error_lnum == 0 ) { 1639err = set_err (_ (e_write_error_conversion_failed_make_fenc_empty_to_override )); 1640 }else { 1641err = set_err (xmalloc (300 )); 1642err .alloc = true; 1643vim_snprintf (err .msg ,300 ,// NOLINT(runtime/printf) 1644_ (e_write_error_conversion_failed_in_line_nr_make_fenc_empty_to_override ), 1645write_info .bw_conv_error_lnum ); 1646 } 1647 }else if (got_int ) { 1648err = set_err (_ (e_interr )); 1649 }else { 1650err = 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. 1661if (backup != NULL ) { 1662if (backup_copy ) { 1663// This may take a while, if we were interrupted let the user 1664// know we got the message. 1665if (got_int ) { 1666msg (_ (e_interr ),0 ); 1667ui_flush (); 1668 } 1669 1670// copy the file. 1671if (os_copy (backup ,fname ,UV_FS_COPYFILE_FICLONE ) 1672== 0 ) { 1673end = 1 ;// success 1674 } 1675 }else { 1676if (vim_rename (backup ,fname )== 0 ) { 1677end = 1 ; 1678 } 1679 } 1680 } 1681 gotofail ; 1682 } 1683 1684lnum -= start ;// compute number of written lines 1685no_wait_return -- ;// may wait for return now 1686 1687#ifndef UNIX 1688fname = sfname ;// use shortname now, for the messages 1689#endif 1690if (!filtering ) { 1691add_quoted_fname (IObuff ,IOSIZE ,buf ,fname ); 1692bool insert_space = false; 1693if (write_info .bw_conv_error ) { 1694xstrlcat (IObuff ,_ (" CONVERSION ERROR" ),IOSIZE ); 1695insert_space = true; 1696if (write_info .bw_conv_error_lnum != 0 ) { 1697vim_snprintf_add (IObuff ,IOSIZE ,_ (" in line %" PRId64 ";" ), 1698 (int64_t )write_info .bw_conv_error_lnum ); 1699 } 1700 }else if (notconverted ) { 1701xstrlcat (IObuff ,_ ("[NOT converted]" ),IOSIZE ); 1702insert_space = true; 1703 }else if (converted ) { 1704xstrlcat (IObuff ,_ ("[converted]" ),IOSIZE ); 1705insert_space = true; 1706 } 1707if (device ) { 1708xstrlcat (IObuff ,_ ("[Device]" ),IOSIZE ); 1709insert_space = true; 1710 }else if (newfile ) { 1711xstrlcat (IObuff ,_ ("[New]" ),IOSIZE ); 1712insert_space = true; 1713 } 1714if (no_eol ) { 1715xstrlcat (IObuff ,_ ("[noeol]" ),IOSIZE ); 1716insert_space = true; 1717 } 1718// may add [unix/dos/mac] 1719if (msg_add_fileformat (fileformat )) { 1720insert_space = true; 1721 } 1722msg_add_lines (insert_space ,lnum ,nchars );// add line/char count 1723if (!shortmess (kShmWrite )) { 1724if (append ) { 1725xstrlcat (IObuff ,shortmess (kShmWri ) ?_ (" [a]" ) :_ (" appended" ),IOSIZE ); 1726 }else { 1727xstrlcat (IObuff ,shortmess (kShmWri ) ?_ (" [w]" ) :_ (" written" ),IOSIZE ); 1728 } 1729 } 1730// Hide cursor while emitting "written" message, so cursor doesn't flicker in cmdline. #25974 1731ui_busy_start (); 1732set_keep_msg (msg_progress (IObuff ,msg_id ,"success" ,0 , true, true, false),0 ); 1733ui_busy_stop (); 1734 } 1735 1736// When written everything correctly: reset 'modified'. Unless not 1737// writing to the original file and '+' is not in 'cpoptions'. 1738if (reset_changed && whole && !append 1739&& !write_info .bw_conv_error 1740&& (overwriting || vim_strchr (p_cpo ,kCpoPlus )!= NULL )) { 1741unchanged (buf , true, false); 1742const varnumber_T changedtick = buf_get_changedtick (buf ); 1743if (buf -> b_last_changedtick + 1 == changedtick ) { 1744// b:changedtick may be incremented in unchanged() but that should not 1745// trigger a TextChanged event. 1746buf -> b_last_changedtick = changedtick ; 1747 } 1748u_unchanged (buf ); 1749u_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. 1754if (overwriting ) { 1755ml_timestamp (buf ); 1756if (append ) { 1757buf -> b_flags &= ~BF_NEW ; 1758 }else { 1759buf -> 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. 1765if (* p_pm && dobackup ) { 1766char * const org = modname (fname ,p_pm , false); 1767 1768if (backup != NULL ) { 1769// If the original file does not exist yet 1770// the current backup file becomes the original file 1771if (org == NULL ) { 1772emsg (_ ("E205: Patchmode: can't save original file" )); 1773 }else if (!os_path_exists (org )) { 1774vim_rename (backup ,org ); 1775XFREE_CLEAR (backup );// don't delete the file 1776#ifdef UNIX 1777os_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. 1785int empty_fd ; 1786 1787if (org == NULL 1788|| (empty_fd = os_open (org , 1789O_CREAT |O_EXCL |O_NOFOLLOW , 1790perm < 0 ?0666 : (perm & 0777 )))< 0 ) { 1791emsg (_ (e_patchmode_cant_touch_empty_original_file )); 1792 }else { 1793close (empty_fd ); 1794 } 1795 } 1796if (org != NULL ) { 1797os_setperm (org ,os_getperm (fname )& 0777 ); 1798xfree (org ); 1799 } 1800 } 1801 1802// Remove the backup unless 'backup' option is set 1803if (!p_bk && backup != NULL 1804&& !write_info .bw_conv_error 1805&& os_remove (backup )!= 0 ) { 1806emsg (_ ("E207: Can't delete backup file" )); 1807 } 1808 1809 gotonofail ; 1810 1811// Finish up. We get here either after failure or success. 1812fail : 1813no_wait_return -- ;// may wait for return now 1814nofail : 1815 1816// Done saving, we accept changed buffer warnings again 1817buf -> b_saving = false; 1818 1819xfree (backup ); 1820if (buffer != smallbuf ) { 1821xfree (buffer ); 1822 } 1823xfree (fenc_tofree ); 1824xfree (write_info .bw_conv_buf ); 1825if (write_info .bw_iconv_fd != (iconv_t )- 1 ) { 1826iconv_close (write_info .bw_iconv_fd ); 1827write_info .bw_iconv_fd = (iconv_t )- 1 ; 1828 } 1829os_free_acl (acl ); 1830 1831if (err .msg != NULL ) { 1832// - 100 to save some space for further error message. 1833add_quoted_fname (IObuff ,IOSIZE - 100 ,buf ,msgname ); 1834// The error ends the progress-msg started by filemess_progress(). 1835emit_err (& err ,filtering ?NULL :msg_id ); 1836 1837retval = FAIL ; 1838if (end == 0 ) { 1839const int hl_id = HLF_E ;// Set highlight for error messages. 1840msg_puts_hl (_ ("\nWARNING: Original file may be lost or damaged\n" ),hl_id , true); 1841msg_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. 1845if (os_fileinfo (fname ,& file_info_old )) { 1846buf_store_file_info (buf ,& file_info_old ); 1847buf -> b_mtime_read = buf -> b_mtime ; 1848buf -> b_mtime_read_ns = buf -> b_mtime_ns ; 1849 } 1850 } 1851 } 1852msg_scroll = msg_save ; 1853 1854// When writing the whole file and 'undofile' is set, also write the undo 1855// file. 1856if (retval == OK && write_undo_file ) { 1857uint8_t hash [UNDO_HASH_SIZE ]; 1858 1859sha256_finish (& sha_ctx ,hash ); 1860u_write_undo (NULL , false,buf ,hash ); 1861 } 1862 1863if (!should_abort (retval )) { 1864buf_write_do_post_autocmds (buf ,fname ,eap ,append ,filtering ,reset_changed ,whole ); 1865if (aborting ()) {// autocmds may abort script processing 1866retval = false; 1867 } 1868 } 1869 1870got_int |=prev_got_int ; 1871 1872xfree (fname_copy ); 1873xfree (sfname_copy ); 1874xfree (ffname_copy ); 1875 1876return retval ; 1877}