robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
3b00ddb601
master
1// fs.c -- filesystem access 2#include <assert.h> 3#include <errno.h> 4#include <fcntl.h> 5#include <stdbool.h> 6#include <stddef.h> 7#include <stdint.h> 8#include <stdio.h> 9#include <stdlib.h> 10#include <string.h> 11#include <sys/stat.h> 12#include <sys/types.h> 13#include <uv.h> 14 15#ifdef MSWIN 16# include <io.h> 17# include <shlobj.h> 18#endif 19 20#include "auto/config.h" 21#include "nvim/os/fs.h" 22#include "nvim/os/os_defs.h" 23 24#ifdef HAVE_ACL 25# ifdef HAVE_SYS_ACL_H 26# include <sys/acl.h> 27# endif 28# ifdef HAVE_SYS_ACCESS_H 29# include <sys/access.h> 30# endif 31#endif 32 33#ifdef HAVE_XATTR 34# include <sys/xattr.h> 35#endif 36 37#include "nvim/api/private/helpers.h" 38#include "nvim/ascii_defs.h" 39#include "nvim/errors.h" 40#include "nvim/gettext_defs.h" 41#include "nvim/globals.h" 42#include "nvim/log.h" 43#include "nvim/macros_defs.h" 44#include "nvim/memory.h" 45#include "nvim/message.h" 46#include "nvim/option_vars.h" 47#include "nvim/os/os.h" 48#include "nvim/path.h" 49#include "nvim/types_defs.h" 50#include "nvim/ui.h" 51#include "nvim/vim_defs.h" 52 53#ifdef HAVE_SYS_UIO_H 54# include <sys/uio.h> 55#endif 56 57#ifdef MSWIN 58# include "nvim/mbyte.h" 59# include "nvim/option.h" 60# include "nvim/os/os_win_console.h" 61# include "nvim/strings.h" 62#endif 63 64#include "os/fs.c.generated.h" 65 66#ifdef HAVE_XATTR 67static const char e_xattr_erange [] 68= N_ ("E1506: Buffer too small to copy xattr value or key" ); 69static const char e_xattr_e2big [] 70= N_ ("E1508: Size of the extended attribute value is larger than the maximum size allowed" ); 71static const char e_xattr_other [] 72= N_ ("E1509: Error occurred when reading or writing extended attribute" ); 73#endif 74 75#define RUN_UV_FS_FUNC (ret ,func , ...) \ 76 do { \ 77 uv_fs_t req; \ 78 ret = func(NULL, &req, __VA_ARGS__); \ 79 uv_fs_req_cleanup(&req); \ 80 } while (0) 81 82// Many fs functions from libuv return that value on success. 83static const int kLibuvSuccess = 0 ; 84 85/// Changes the current directory to `path`. 86/// 87/// @return 0 on success, or negative error code. 88int os_chdir (const char * path ) 89FUNC_ATTR_NONNULL_ALL 90{ 91if (p_verbose >=5 ) { 92verbose_enter (); 93smsg (0 ,"chdir(%s)" ,path ); 94verbose_leave (); 95 } 96int err = uv_chdir (path ); 97if (err == 0 ) { 98ui_call_chdir (cstr_as_string (path )); 99 } 100return err ; 101} 102 103/// Get the name of current directory. 104/// 105/// @param buf Buffer to store the directory name. 106/// @param len Length of `buf`. 107/// @return `OK` for success, `FAIL` for failure. 108int os_dirname (char * buf ,size_t len ) 109FUNC_ATTR_NONNULL_ALL 110{ 111int error_number ; 112if ((error_number = uv_cwd (buf ,& len ))!= kLibuvSuccess ) { 113xstrlcpy (buf ,uv_strerror (error_number ),len ); 114return FAIL ; 115 } 116TO_SLASH (buf ); 117return OK ; 118} 119 120/// Check if the given path is a directory and not a symlink to a directory. 121/// @return `true` if `name` is a directory and NOT a symlink to a directory. 122/// `false` if `name` is not a directory or if an error occurred. 123bool os_isrealdir (const char * name ) 124FUNC_ATTR_NONNULL_ALL 125{ 126uv_fs_t request ; 127if (uv_fs_lstat (NULL ,& request ,name ,NULL )!= kLibuvSuccess ) { 128return false; 129 } 130if (S_ISLNK (request .statbuf .st_mode )) { 131return false; 132 } 133return S_ISDIR (request .statbuf .st_mode ); 134} 135 136/// Check if the given path exists and is a directory. 137/// 138/// @return `true` if `name` is a directory. 139bool os_isdir (const char * name ) 140FUNC_ATTR_NONNULL_ALL 141{ 142int32_t mode = os_getperm (name ); 143if (mode < 0 ) { 144return false; 145 } 146 147return S_ISDIR (mode ); 148} 149 150/// Check what `name` is: 151/// @return NODE_NORMAL: file or directory (or doesn't exist) 152/// NODE_WRITABLE: writable device, socket, fifo, etc. 153/// NODE_OTHER: non-writable things 154int os_nodetype (const char * name ) 155FUNC_ATTR_NONNULL_ALL 156{ 157#ifndef MSWIN // Unix 158uv_stat_t statbuf ; 159if (0 != os_stat (name ,& statbuf )) { 160return NODE_NORMAL ;// File doesn't exist. 161 } 162// uv_handle_type does not distinguish BLK and DIR. 163// Related: https://github.com/joyent/libuv/pull/1421 164if (S_ISREG (statbuf .st_mode )|| S_ISDIR (statbuf .st_mode )) { 165return NODE_NORMAL ; 166 } 167if (S_ISBLK (statbuf .st_mode )) {// block device isn't writable 168return NODE_OTHER ; 169 } 170// Everything else is writable? 171// buf_write() expects NODE_WRITABLE for char device /dev/stderr. 172return NODE_WRITABLE ; 173#else // Windows 174// Edge case from Vim os_win32.c: 175// We can't open a file with a name "\\.\con" or "\\.\prn", trying to read 176// from it later will cause Vim to hang. Thus return NODE_WRITABLE here. 177if (strncmp (name ,"\\\\.\\" ,4 )== 0 ) { 178return NODE_WRITABLE ; 179 } 180 181// Vim os_win32.c:mch_nodetype does (since 7.4.015): 182// wn = enc_to_utf16(name, NULL); 183// hFile = CreatFile(wn, ...) 184// to get a HANDLE. Whereas libuv just calls _get_osfhandle() on the fd we 185// give it. But uv_fs_open later calls fs__capture_path which does a similar 186// utf8-to-utf16 dance and saves us the hassle. 187 188// macOS: os_open(/dev/stderr) would return UV_EACCES. 189int fd = os_open (name ,O_RDONLY 190# ifdef O_NONBLOCK 191 |O_NONBLOCK 192# endif 193 ,0 ); 194if (fd < 0 ) {// open() failed. 195return NODE_NORMAL ; 196 } 197int guess = uv_guess_handle (fd ); 198if (close (fd )== -1 ) { 199ELOG ("close(%d) failed. name='%s'" ,fd ,name ); 200 } 201 202switch (guess ) { 203case UV_TTY :// FILE_TYPE_CHAR 204return NODE_WRITABLE ; 205case UV_FILE :// FILE_TYPE_DISK 206return NODE_NORMAL ; 207case UV_NAMED_PIPE :// not handled explicitly in Vim os_win32.c 208case UV_UDP :// unix only 209case UV_TCP :// unix only 210case UV_UNKNOWN_HANDLE : 211default : 212return NODE_OTHER ;// Vim os_win32.c default 213 } 214#endif 215} 216 217/// Gets the absolute path of the currently running executable. 218/// May fail if procfs is missing. #6734 219/// @see path_exepath 220/// 221/// @param[out] buffer Full path to the executable. 222/// @param[in] size Size of `buffer`. 223/// 224/// @return 0 on success, or libuv error code. 225int os_exepath (char * buffer ,size_t * size ) 226FUNC_ATTR_NONNULL_ALL 227{ 228int r = uv_exepath (buffer ,size ); 229TO_SLASH (buffer ); 230return r ; 231} 232 233/// Checks if the file `name` is executable. 234/// 235/// @param[in] name Filename to check. 236/// @param[out,allocated] abspath Returns resolved exe path, if not NULL. 237/// @param[in] use_path Also search $PATH. 238/// 239/// @return true if `name` is executable and 240/// - can be found in $PATH, 241/// - is relative to current dir or 242/// - is absolute. 243/// 244/// @return `false` otherwise. 245bool os_can_exe (const char * name ,char ** abspath ,bool use_path ) 246FUNC_ATTR_NONNULL_ARG (1 ) 247{ 248if (!use_path || gettail_dir (name )!= name ) { 249#ifdef MSWIN 250return is_executable_ext (name ,abspath ); 251#else 252// Must have path separator, cannot execute files in the current directory. 253return ((use_path || gettail_dir (name )!= name ) 254&& is_executable (name ,abspath )); 255#endif 256return false; 257 } 258 259return is_executable_in_path (name ,abspath ); 260} 261 262/// Returns true if `name` is an executable file. 263/// 264/// @param[in] name Filename to check. 265/// @param[out,allocated] abspath Returns full exe path, if not NULL. 266static bool is_executable (const char * name ,char ** abspath ) 267FUNC_ATTR_NONNULL_ARG (1 ) 268{ 269int32_t mode = os_getperm (name ); 270 271if (mode < 0 ) { 272return false; 273 } 274 275#ifdef MSWIN 276// Windows does not have exec bit; just check if the file exists and is not 277// a directory. 278const bool ok = S_ISREG (mode ); 279#else 280int r = -1 ; 281if (S_ISREG (mode )) { 282RUN_UV_FS_FUNC (r ,uv_fs_access ,name ,X_OK ,NULL ); 283 } 284const bool ok = (r == 0 ); 285#endif 286if (ok && abspath != NULL ) { 287* abspath = save_abs_path (name ); 288 } 289return ok ; 290} 291 292#ifdef MSWIN 293/// Checks if file `name` is executable under any of these conditions: 294/// - extension is in $PATHEXT and `name` is executable 295/// - result of any $PATHEXT extension appended to `name` is executable 296static bool is_executable_ext (const char * name ,char ** abspath ) 297FUNC_ATTR_NONNULL_ARG (1 ) 298{ 299const bool is_unix_shell = strstr (path_tail (p_sh ),"powershell" )== NULL 300&& strstr (path_tail (p_sh ),"pwsh" )== NULL 301&& strstr (path_tail (p_sh ),"sh" )!= NULL ; 302char * nameext = strrchr (name ,'.' ); 303size_t nameext_len = nameext ?strlen (nameext ) :0 ; 304xstrlcpy (os_buf ,name ,sizeof (os_buf )); 305char * buf_end = xstrchrnul (os_buf ,NUL ); 306const char * pathext = os_getenv_noalloc ("PATHEXT" ); 307if (!pathext ) { 308pathext = ".com;.exe;.bat;.cmd" ; 309 } 310const char * ext = pathext ; 311while (* ext ) { 312// If $PATHEXT itself contains dot: 313if (ext [0 ]== '.' && (ext [1 ]== NUL || ext [1 ]== ENV_SEPCHAR )) { 314if (is_executable (name ,abspath )) { 315return true; 316 } 317// Skip it. 318ext ++ ; 319if (* ext ) { 320ext ++ ; 321 } 322continue ; 323 } 324 325const char * ext_end = ext ; 326size_t ext_len = 327copy_option_part ((char ** )& ext_end ,buf_end , 328sizeof (os_buf )- (size_t )(buf_end - os_buf ),ENV_SEPSTR ); 329if (ext_len != 0 ) { 330bool in_pathext = nameext_len == ext_len 331&& 0 == mb_strnicmp (nameext ,ext ,ext_len ); 332 333if (((in_pathext || is_unix_shell )&& is_executable (name ,abspath )) 334|| is_executable (os_buf ,abspath )) { 335return true; 336 } 337 } 338ext = ext_end ; 339 } 340return false; 341} 342#else 343# define is_executable_ext is_executable 344#endif 345 346/// Checks if a file is in `$PATH` and is executable. 347/// 348/// @param[in] name Filename to check. 349/// @param[out] abspath Returns resolved executable path, if not NULL. 350/// 351/// @return `true` if `name` is an executable inside `$PATH`. 352static bool is_executable_in_path (const char * name ,char ** abspath ) 353FUNC_ATTR_NONNULL_ARG (1 ) 354{ 355char * path_env = os_getenv ("PATH" ); 356if (path_env == NULL ) { 357return false; 358 } 359 360#ifdef MSWIN 361char * path = NULL ; 362if (!os_env_exists ("NoDefaultCurrentDirectoryInExePath" , false) 363&& strstr (path_tail (p_sh ),"cmd.exe" )!= NULL ) { 364// Prepend ".;" to $PATH. 365size_t pathlen = strlen (path_env ); 366path = xmallocz (pathlen + 2 ); 367memcpy (path ,"." ENV_SEPSTR ,2 ); 368memcpy (path + 2 ,path_env ,pathlen ); 369 }else { 370path = xstrdup (path_env ); 371 } 372#else 373char * path = xstrdup (path_env ); 374#endif 375 376const size_t bufsize = strlen (name )+ strlen (path )+ 2 ; 377char * buf = xmalloc (bufsize ); 378 379// Walk through all entries in $PATH to check if "name" exists there and 380// is an executable file. 381char * p = path ; 382bool rv = false; 383while (true) { 384char * e = xstrchrnul (p ,ENV_SEPCHAR ); 385 386// Combine the $PATH segment with `name`. 387xmemcpyz (buf ,p , (size_t )(e - p )); 388 (void )append_path (buf ,name ,bufsize ); 389 390if (is_executable_ext (buf ,abspath )) { 391rv = true; 392 gotoend ; 393 } 394 395if (* e != ENV_SEPCHAR ) { 396// End of $PATH without finding any executable called name. 397 gotoend ; 398 } 399 400p = e + 1 ; 401 } 402 403end : 404xfree (buf ); 405xfree (path ); 406xfree (path_env ); 407return rv ; 408} 409 410/// Opens or creates a file and returns a non-negative integer representing 411/// the lowest-numbered unused file descriptor, for use in subsequent system 412/// calls (read, write, lseek, fcntl, etc.). If the operation fails, a libuv 413/// error code is returned, and no file is created or modified. 414/// 415/// @param path Filename 416/// @param flags Bitwise OR of flags defined in <fcntl.h> 417/// @param mode Permissions for the newly-created file (IGNORED if 'flags' is 418/// not `O_CREAT` or `O_TMPFILE`), subject to the current umask 419/// @return file descriptor, or negative error code on failure 420int os_open (const char * path ,int flags ,int mode ) 421{ 422if (path == NULL ) {// uv_fs_open asserts on NULL. #7561 423return UV_EINVAL ; 424 } 425int r ; 426RUN_UV_FS_FUNC (r ,uv_fs_open ,path ,flags ,mode ,NULL ); 427return r ; 428} 429 430/// Compatibility wrapper conforming to fopen(3). 431/// 432/// Windows: works with UTF-16 filepaths by delegating to libuv (os_open). 433/// 434/// Future: remove this, migrate callers to os/fileio.c ? 435/// But file_open_fd does not support O_RDWR yet. 436/// 437/// @param path Filename 438/// @param flags String flags, one of { r w a r+ w+ a+ rb wb ab } 439/// @return FILE pointer, or NULL on error. 440FILE * os_fopen (const char * path ,const char * flags ) 441{ 442assert (flags != NULL && strlen (flags )> 0 && strlen (flags ) <=2 ); 443int iflags = 0 ; 444// Per table in fopen(3) manpage. 445if (flags [1 ]== NUL || flags [1 ]== 'b' ) { 446switch (flags [0 ]) { 447case 'r' : 448iflags = O_RDONLY ; 449break ; 450case 'w' : 451iflags = O_WRONLY |O_CREAT |O_TRUNC ; 452break ; 453case 'a' : 454iflags = O_WRONLY |O_CREAT |O_APPEND ; 455break ; 456default : 457abort (); 458 } 459#ifdef MSWIN 460if (flags [1 ]== 'b' ) { 461iflags |=O_BINARY ; 462 } 463#endif 464 }else { 465// char 0 must be one of ('r','w','a'). 466// char 1 is always '+' ('b' is handled above). 467assert (flags [1 ]== '+' ); 468switch (flags [0 ]) { 469case 'r' : 470iflags = O_RDWR ; 471break ; 472case 'w' : 473iflags = O_RDWR |O_CREAT |O_TRUNC ; 474break ; 475case 'a' : 476iflags = O_RDWR |O_CREAT |O_APPEND ; 477break ; 478default : 479abort (); 480 } 481 } 482// Per fopen(3) manpage: default to 0666, it will be umask-adjusted. 483int fd = os_open (path ,iflags ,0666 ); 484if (fd < 0 ) { 485return NULL ; 486 } 487return fdopen (fd ,flags ); 488} 489 490/// Sets file descriptor `fd` to close-on-exec (Unix) or non-inheritable (Windows). 491/// 492/// @return -1 if failed to set, 0 otherwise. 493int os_set_cloexec (const int fd ) 494{ 495#ifdef HAVE_FD_CLOEXEC 496int e ; 497int fdflags = fcntl (fd ,F_GETFD ); 498if (fdflags < 0 ) { 499e = errno ; 500ELOG ("Failed to get flags on descriptor %d: %s" ,fd ,strerror (e )); 501errno = e ; 502return -1 ; 503 } 504if ((fdflags & FD_CLOEXEC )== 0 505&& fcntl (fd ,F_SETFD ,fdflags |FD_CLOEXEC )== -1 ) { 506e = errno ; 507ELOG ("Failed to set CLOEXEC on descriptor %d: %s" ,fd ,strerror (e )); 508errno = e ; 509return -1 ; 510 } 511return 0 ; 512#elif defined(MSWIN ) 513HANDLE h = (HANDLE )_get_osfhandle (fd ); 514if (h == INVALID_HANDLE_VALUE 515|| !SetHandleInformation (h ,HANDLE_FLAG_INHERIT ,0 )) { 516return -1 ; 517 } 518return 0 ; 519#else 520return -1 ; 521#endif 522} 523 524/// Close a file 525/// 526/// @return 0 or libuv error code on failure. 527int os_close (const int fd ) 528{ 529int r ; 530RUN_UV_FS_FUNC (r ,uv_fs_close ,fd ,NULL ); 531return r ; 532} 533 534/// Duplicate file descriptor 535/// 536/// @param[in] fd File descriptor to duplicate. 537/// 538/// @return New file descriptor or libuv error code (< 0). 539int os_dup (const int fd ) 540FUNC_ATTR_WARN_UNUSED_RESULT 541{ 542int ret ; 543os_dup_dup : 544ret = dup (fd ); 545if (ret < 0 ) { 546const int error = os_translate_sys_error (errno ); 547errno = 0 ; 548if (error == UV_EINTR ) { 549 gotoos_dup_dup ; 550 }else { 551return error ; 552 } 553 } 554return ret ; 555} 556 557/// Duplicates file descriptor `fd` and marks the copy close-on-exec (Unix) / non-inheritable 558/// (Windows), so the duped fd is not leaked to spawned child processes. 559/// 560/// @return New file descriptor, or libuv error code (< 0) if the dup failed. 561int os_dup_cloexec (const int fd ) 562FUNC_ATTR_WARN_UNUSED_RESULT 563{ 564int newfd = os_dup (fd ); 565if (newfd >=0 ) { 566os_set_cloexec (newfd ); 567 } 568return newfd ; 569} 570 571/// Open the file descriptor for stdin. 572int os_open_stdin_fd (void ) 573{ 574int stdin_dup_fd ; 575if (stdin_fd > 0 ) { 576stdin_dup_fd = stdin_fd ; 577 }else { 578stdin_dup_fd = os_dup (STDIN_FILENO ); 579#ifdef MSWIN 580// Replace the original stdin with the console input handle. 581os_redirect_stdin_to_conin (); 582#endif 583 } 584return stdin_dup_fd ; 585} 586 587/// Read from a file 588/// 589/// Handles EINTR, but not other errors. 590/// 591/// @param[in] fd File descriptor to read from. 592/// @param[out] ret_eof Is set to true if EOF was encountered, otherwise set 593/// to false. Initial value is ignored. 594/// @param[out] ret_buf Buffer to write to. May be NULL if size is zero. 595/// @param[in] size Amount of bytes to read. 596/// @param[in] non_blocking Do not restart syscall if EAGAIN was encountered. 597/// 598/// @return Number of bytes read or libuv error code (< 0). 599ptrdiff_t os_read (const int fd ,bool * const ret_eof ,char * const ret_buf ,const size_t size , 600const bool non_blocking ) 601FUNC_ATTR_WARN_UNUSED_RESULT 602{ 603* ret_eof = false; 604if (ret_buf == NULL ) { 605assert (size == 0 ); 606return 0 ; 607 } 608size_t read_bytes = 0 ; 609while (read_bytes != size ) { 610assert (size >=read_bytes ); 611const ptrdiff_t cur_read_bytes = read (fd ,ret_buf + read_bytes , 612IO_COUNT (size - read_bytes )); 613if (cur_read_bytes > 0 ) { 614read_bytes += (size_t )cur_read_bytes ; 615 } 616if (cur_read_bytes < 0 ) { 617const int error = os_translate_sys_error (errno ); 618errno = 0 ; 619if (non_blocking && error == UV_EAGAIN ) { 620break ; 621 }else if (error == UV_EINTR || error == UV_EAGAIN ) { 622continue ; 623 }else { 624return (ptrdiff_t )error ; 625 } 626 } 627if (cur_read_bytes == 0 ) { 628* ret_eof = true; 629break ; 630 } 631 } 632return (ptrdiff_t )read_bytes ; 633} 634 635#ifdef HAVE_READV 636/// Read from a file to multiple buffers at once 637/// 638/// Wrapper for readv(). 639/// 640/// @param[in] fd File descriptor to read from. 641/// @param[out] ret_eof Is set to true if EOF was encountered, otherwise set 642/// to false. Initial value is ignored. 643/// @param[out] iov Description of buffers to write to. Note: this description 644/// may change, it is incorrect to use data it points to after 645/// os_readv(). 646/// @param[in] iov_size Number of buffers in iov. 647/// @param[in] non_blocking Do not restart syscall if EAGAIN was encountered. 648/// 649/// @return Number of bytes read or libuv error code (< 0). 650ptrdiff_t os_readv (const int fd ,bool * const ret_eof ,struct iovec * iov ,size_t iov_size , 651const bool non_blocking ) 652FUNC_ATTR_NONNULL_ALL 653{ 654* ret_eof = false; 655size_t read_bytes = 0 ; 656size_t toread = 0 ; 657for (size_t i = 0 ;i < iov_size ;i ++ ) { 658// Overflow, trying to read too much data 659assert (toread <=SIZE_MAX - iov [i ].iov_len ); 660toread += iov [i ].iov_len ; 661 } 662while (read_bytes < toread && iov_size && !* ret_eof ) { 663ptrdiff_t cur_read_bytes = readv (fd ,iov , (int )iov_size ); 664if (cur_read_bytes == 0 ) { 665* ret_eof = true; 666 } 667if (cur_read_bytes > 0 ) { 668read_bytes += (size_t )cur_read_bytes ; 669while (iov_size && cur_read_bytes ) { 670if (cur_read_bytes < (ptrdiff_t )iov -> iov_len ) { 671iov -> iov_len -= (size_t )cur_read_bytes ; 672iov -> iov_base = (char * )iov -> iov_base + cur_read_bytes ; 673cur_read_bytes = 0 ; 674 }else { 675cur_read_bytes -= (ptrdiff_t )iov -> iov_len ; 676iov_size -- ; 677iov ++ ; 678 } 679 } 680 }else if (cur_read_bytes < 0 ) { 681const int error = os_translate_sys_error (errno ); 682errno = 0 ; 683if (non_blocking && error == UV_EAGAIN ) { 684break ; 685 }else if (error == UV_EINTR || error == UV_EAGAIN ) { 686continue ; 687 }else { 688return (ptrdiff_t )error ; 689 } 690 } 691 } 692return (ptrdiff_t )read_bytes ; 693} 694#endif // HAVE_READV 695 696/// Write to a file 697/// 698/// @param[in] fd File descriptor to write to. 699/// @param[in] buf Data to write. May be NULL if size is zero. 700/// @param[in] size Amount of bytes to write. 701/// @param[in] non_blocking Do not restart syscall if EAGAIN was encountered. 702/// 703/// @return Number of bytes written or libuv error code (< 0). 704ptrdiff_t os_write (const int fd ,const char * const buf ,const size_t size ,const bool non_blocking ) 705FUNC_ATTR_WARN_UNUSED_RESULT 706{ 707if (buf == NULL ) { 708assert (size == 0 ); 709return 0 ; 710 } 711size_t written_bytes = 0 ; 712while (written_bytes != size ) { 713assert (size >=written_bytes ); 714const ptrdiff_t cur_written_bytes = write (fd ,buf + written_bytes , 715IO_COUNT (size - written_bytes )); 716if (cur_written_bytes > 0 ) { 717written_bytes += (size_t )cur_written_bytes ; 718 } 719if (cur_written_bytes < 0 ) { 720const int error = os_translate_sys_error (errno ); 721errno = 0 ; 722if (non_blocking && error == UV_EAGAIN ) { 723break ; 724 }else if (error == UV_EINTR || error == UV_EAGAIN ) { 725continue ; 726 }else { 727return error ; 728 } 729 } 730if (cur_written_bytes == 0 ) { 731return UV_UNKNOWN ; 732 } 733 } 734return (ptrdiff_t )written_bytes ; 735} 736 737/// Copies a file from `path` to `new_path`. 738/// 739/// @see http://docs.libuv.org/en/v1.x/fs.html#c.uv_fs_copyfile 740/// 741/// @param path Path of file to be copied 742/// @param path_new Path of new file 743/// @param flags Bitwise OR of flags defined in <uv.h> 744/// @return 0 on success, or libuv error code on failure. 745int os_copy (const char * path ,const char * new_path ,int flags ) 746{ 747int r ; 748RUN_UV_FS_FUNC (r ,uv_fs_copyfile ,path ,new_path ,flags ,NULL ); 749return r ; 750} 751 752/// Flushes file modifications to disk. 753/// 754/// @param fd the file descriptor of the file to flush to disk. 755/// 756/// @return 0 on success, or libuv error code on failure. 757int os_fsync (int fd ) 758{ 759int r ; 760RUN_UV_FS_FUNC (r ,uv_fs_fsync ,fd ,NULL ); 761g_stats .fsync ++ ; 762return r ; 763} 764 765/// Get stat information for a file. 766/// 767/// @return libuv return code, or -errno 768static int os_stat (const char * name ,uv_stat_t * statbuf ) 769FUNC_ATTR_NONNULL_ARG (2 ) 770{ 771if (!name ) { 772return UV_EINVAL ; 773 } 774uv_fs_t request ; 775int result = uv_fs_stat (NULL ,& request ,name ,NULL ); 776if (result == kLibuvSuccess ) { 777* statbuf = request .statbuf ; 778 } 779uv_fs_req_cleanup (& request ); 780return result ; 781} 782 783/// Get the file permissions for a given file. 784/// 785/// @return libuv error code on error. 786int32_t os_getperm (const char * name ) 787{ 788uv_stat_t statbuf ; 789int stat_result = os_stat (name ,& statbuf ); 790if (stat_result == kLibuvSuccess ) { 791return (int32_t )statbuf .st_mode ; 792 } 793return stat_result ; 794} 795 796/// Set the permission of a file. 797/// 798/// @return `OK` for success, `FAIL` for failure. 799int os_setperm (const char * const name ,int perm ) 800FUNC_ATTR_NONNULL_ALL 801{ 802int r ; 803RUN_UV_FS_FUNC (r ,uv_fs_chmod ,name ,perm ,NULL ); 804return (r == kLibuvSuccess ?OK :FAIL ); 805} 806 807/// Set the permission of the file referred to by the open file descriptor. 808/// 809/// @return `OK` for success, `FAIL` for failure. 810int os_fsetperm (int fd ,int perm ) 811{ 812int r ; 813RUN_UV_FS_FUNC (r ,uv_fs_fchmod ,fd ,perm ,NULL ); 814return (r == kLibuvSuccess ?OK :FAIL ); 815} 816 817#ifdef HAVE_XATTR 818/// Copy extended attributes from_file to to_file 819void os_copy_xattr (const char * from_file ,const char * to_file ) 820{ 821if (from_file == NULL ) { 822return ; 823 } 824 825// get the length of the extended attributes 826ssize_t size = listxattr ((char * )from_file ,NULL ,0 ); 827// not supported or no attributes to copy 828if (size <=0 ) { 829return ; 830 } 831char * xattr_buf = xmalloc ((size_t )size ); 832size = listxattr (from_file ,xattr_buf , (size_t )size ); 833ssize_t tsize = size ; 834 835errno = 0 ; 836 837ssize_t max_vallen = 0 ; 838char * val = NULL ; 839const char * errmsg = NULL ; 840 841for (int round = 0 ;round < 2 ;round ++ ) { 842char * key = xattr_buf ; 843if (round == 1 ) { 844size = tsize ; 845 } 846 847while (size > 0 ) { 848ssize_t vallen = getxattr (from_file ,key ,val ,round ? (size_t )max_vallen :0 ); 849// only set the attribute in the second round 850if (vallen >=0 && round 851&& setxattr (to_file ,key ,val , (size_t )vallen ,0 )== 0 ) { 852// 853 }else if (errno ) { 854switch (errno ) { 855case E2BIG : 856errmsg = e_xattr_e2big ; 857 gotoerror_exit ; 858case ENOTSUP : 859case EACCES : 860case EPERM : 861break ; 862case ERANGE : 863errmsg = e_xattr_erange ; 864 gotoerror_exit ; 865default : 866errmsg = e_xattr_other ; 867 gotoerror_exit ; 868 } 869 } 870 871if (round == 0 && vallen > max_vallen ) { 872max_vallen = vallen ; 873 } 874 875// add one for terminating null 876ssize_t keylen = (ssize_t )strlen (key )+ 1 ; 877size -= keylen ; 878key += keylen ; 879 } 880if (round ) { 881break ; 882 } 883 884val = xmalloc ((size_t )max_vallen + 1 ); 885 } 886error_exit : 887xfree (xattr_buf ); 888xfree (val ); 889 890if (errmsg != NULL ) { 891emsg (_ (errmsg )); 892 } 893} 894#endif 895 896// Return a pointer to the ACL of file "fname" in allocated memory. 897// Return NULL if the ACL is not available for whatever reason. 898vim_acl_T os_get_acl (const char * fname ) 899{ 900vim_acl_T ret = NULL ; 901return ret ; 902} 903 904// Set the ACL of file "fname" to "acl" (unless it's NULL). 905void os_set_acl (const char * fname ,vim_acl_T aclent ) 906{ 907if (aclent == NULL ) { 908return ; 909 } 910} 911 912void os_free_acl (vim_acl_T aclent ) 913{ 914if (aclent == NULL ) { 915return ; 916 } 917} 918 919#ifdef UNIX 920/// Checks if the current user owns a file. 921/// 922/// Uses both uv_fs_stat() and uv_fs_lstat() via os_fileinfo() and 923/// os_fileinfo_link() respectively for extra security. 924bool os_file_owned (const char * fname ) 925FUNC_ATTR_NONNULL_ALL 926{ 927uid_t uid = getuid (); 928FileInfo finfo ; 929bool file_owned = os_fileinfo (fname ,& finfo )&& finfo .stat .st_uid == uid ; 930bool link_owned = os_fileinfo_link (fname ,& finfo )&& finfo .stat .st_uid == uid ; 931return file_owned && link_owned ; 932} 933#else 934bool os_file_owned (const char * fname ) 935{ 936return true;// TODO(justinmk): Windows. #8244 937} 938#endif 939 940/// Changes the owner and group of a file, like chown(2). 941/// 942/// @return 0 on success, or libuv error code on failure. 943/// 944/// @note If `owner` or `group` is -1, then that ID is not changed. 945int os_chown (const char * path ,uv_uid_t owner ,uv_gid_t group ) 946{ 947int r ; 948RUN_UV_FS_FUNC (r ,uv_fs_chown ,path ,owner ,group ,NULL ); 949return r ; 950} 951 952/// Changes the owner and group of the file referred to by the open file 953/// descriptor, like fchown(2). 954/// 955/// @return 0 on success, or libuv error code on failure. 956/// 957/// @note If `owner` or `group` is -1, then that ID is not changed. 958int os_fchown (int fd ,uv_uid_t owner ,uv_gid_t group ) 959{ 960int r ; 961RUN_UV_FS_FUNC (r ,uv_fs_fchown ,fd ,owner ,group ,NULL ); 962return r ; 963} 964 965/// Check if a path exists. 966/// 967/// @return `true` if `path` exists 968bool os_path_exists (const char * path ) 969{ 970uv_stat_t statbuf ; 971return os_stat (path ,& statbuf )== kLibuvSuccess ; 972} 973 974/// Sets file access and modification times. 975/// 976/// @see POSIX utime(2) 977/// 978/// @param path File path. 979/// @param atime Last access time. 980/// @param mtime Last modification time. 981/// 982/// @return 0 on success, or negative error code. 983int os_file_settime (const char * path ,double atime ,double mtime ) 984{ 985int r ; 986RUN_UV_FS_FUNC (r ,uv_fs_utime ,path ,atime ,mtime ,NULL ); 987return r ; 988} 989 990/// Check if a file is readable. 991/// 992/// @return true if `name` is readable, otherwise false. 993bool os_file_is_readable (const char * name ) 994FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT 995{ 996int r ; 997RUN_UV_FS_FUNC (r ,uv_fs_access ,name ,R_OK ,NULL ); 998return (r == 0 ); 999} 1000 1001/// Check if a file is writable. 1002/// 1003/// @return `0` if `name` is not writable, 1004/// @return `1` if `name` is writable, 1005/// @return `2` for a directory which we have rights to write into. 1006int os_file_is_writable (const char * name ) 1007FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT 1008{ 1009int r ; 1010RUN_UV_FS_FUNC (r ,uv_fs_access ,name ,W_OK ,NULL ); 1011if (r == 0 ) { 1012return os_isdir (name ) ?2 :1 ; 1013 } 1014return 0 ; 1015} 1016 1017/// Rename a file or directory. 1018/// 1019/// @return `OK` for success, `FAIL` for failure. 1020int os_rename (const char * path ,const char * new_path ) 1021FUNC_ATTR_NONNULL_ALL 1022{ 1023int r ; 1024RUN_UV_FS_FUNC (r ,uv_fs_rename ,path ,new_path ,NULL ); 1025return (r == kLibuvSuccess ?OK :FAIL ); 1026} 1027 1028/// Make a directory. 1029/// 1030/// @return `0` for success, libuv error code for failure. 1031int os_mkdir (const char * path ,int32_t mode ) 1032FUNC_ATTR_NONNULL_ALL 1033{ 1034int r ; 1035RUN_UV_FS_FUNC (r ,uv_fs_mkdir ,path ,mode ,NULL ); 1036return r ; 1037} 1038 1039/// Make a directory, with higher levels when needed 1040/// 1041/// @param[in] dir Directory to create. 1042/// @param[in] mode Permissions for the newly-created directory. 1043/// @param[out] failed_dir If it failed to create directory, then this 1044/// argument is set to an allocated string containing 1045/// the name of the directory which os_mkdir_recurse 1046/// failed to create. I.e. it will contain dir or any 1047/// of the higher level directories. 1048/// @param[out] created Set to the full name of the first created directory. 1049/// It will be NULL until that happens. 1050/// 1051/// @return `0` for success, libuv error code for failure. 1052int os_mkdir_recurse (const char * const dir ,int32_t mode ,char ** const failed_dir , 1053char ** const created ) 1054FUNC_ATTR_NONNULL_ARG (1 ,3 )FUNC_ATTR_WARN_UNUSED_RESULT 1055{ 1056// Get end of directory name in "dir". 1057// We're done when it's "/" or "c:/". 1058const size_t dirlen = strlen (dir ); 1059char * const curdir = xmemdupz (dir ,dirlen ); 1060char * const past_head = get_past_head (curdir ); 1061char * e = curdir + dirlen ; 1062const char * const real_end = e ; 1063const char past_head_save = * past_head ; 1064while (!os_isdir (curdir )) { 1065e = path_tail_with_sep (curdir ); 1066if (e <=past_head ) { 1067* past_head = NUL ; 1068break ; 1069 } 1070* e = NUL ; 1071 } 1072while (e != real_end ) { 1073if (e > past_head ) { 1074* e = PATHSEP ; 1075 }else { 1076* past_head = past_head_save ; 1077 } 1078const size_t component_len = strlen (e ); 1079e += component_len ; 1080if (e == real_end 1081&& memcnt (e - component_len ,PATHSEP ,component_len )== component_len ) { 1082// Path ends with something like "////". Ignore this. 1083break ; 1084 } 1085int ret ; 1086if ((ret = os_mkdir (curdir ,mode ))!= 0 ) { 1087* failed_dir = curdir ; 1088return ret ; 1089 }else if (created != NULL && * created == NULL ) { 1090* created = FullName_save (curdir , false); 1091 } 1092 } 1093xfree (curdir ); 1094return 0 ; 1095} 1096 1097/// Create the parent directory of a file if it does not exist 1098/// 1099/// @param[in] fname Full path of the file name whose parent directories 1100/// we want to create 1101/// @param[in] mode Permissions for the newly-created directory. 1102/// 1103/// @return `0` for success, libuv error code for failure. 1104int os_file_mkdir (char * fname ,int32_t mode ) 1105FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT 1106{ 1107if (!dir_of_file_exists (fname )) { 1108char * tail = path_tail_with_sep (fname ); 1109char * last_char = tail + strlen (tail )- 1 ; 1110if (vim_ispathsep (* last_char )) { 1111emsg (_ (e_noname )); 1112return -1 ; 1113 } 1114char c = * tail ; 1115* tail = NUL ; 1116int r ; 1117char * failed_dir ; 1118if (((r = os_mkdir_recurse (fname ,mode ,& failed_dir ,NULL ))< 0 )) { 1119semsg (_ (e_mkdir ),failed_dir ,os_strerror (r )); 1120xfree (failed_dir ); 1121 } 1122* tail = c ; 1123return r ; 1124 } 1125return 0 ; 1126} 1127 1128/// Create a unique temporary directory. 1129/// 1130/// @param[in] templ Template of the path to the directory with XXXXXX 1131/// which would be replaced by random chars. 1132/// @param[out] path Path to created directory for success, undefined for 1133/// failure. 1134/// @return `0` for success, non-zero for failure. 1135int os_mkdtemp (const char * templ ,char * path ) 1136FUNC_ATTR_NONNULL_ALL 1137{ 1138uv_fs_t request ; 1139int result = uv_fs_mkdtemp (NULL ,& request ,templ ,NULL ); 1140if (result == kLibuvSuccess ) { 1141xstrlcpy (path ,request .path ,TEMP_FILE_PATH_MAXLEN ); 1142TO_SLASH (path ); 1143 } 1144uv_fs_req_cleanup (& request ); 1145return result ; 1146} 1147 1148/// Remove a directory. 1149/// 1150/// @return `0` for success, non-zero for failure. 1151int os_rmdir (const char * path ) 1152FUNC_ATTR_NONNULL_ALL 1153{ 1154int r ; 1155RUN_UV_FS_FUNC (r ,uv_fs_rmdir ,path ,NULL ); 1156return r ; 1157} 1158 1159/// Opens a directory. 1160/// @param[out] dir The Directory object. 1161/// @param path Path to the directory. 1162/// @returns true if dir contains one or more items, false if not or an error 1163/// occurred. 1164bool os_scandir (Directory * dir ,const char * path ) 1165FUNC_ATTR_NONNULL_ALL 1166{ 1167int r = uv_fs_scandir (NULL ,& dir -> request ,path ,0 ,NULL ); 1168if (r < 0 ) { 1169os_closedir (dir ); 1170 } 1171return r >=0 ; 1172} 1173 1174/// Increments the directory pointer. 1175/// @param dir The Directory object. 1176/// @returns a pointer to the next path in `dir` or `NULL`. 1177const char * os_scandir_next (Directory * dir ) 1178FUNC_ATTR_NONNULL_ALL 1179{ 1180int err = uv_fs_scandir_next (& dir -> request ,& dir -> ent ); 1181return err != UV_EOF ?dir -> ent .name :NULL ; 1182} 1183 1184/// Frees memory associated with `os_scandir()`. 1185/// @param dir The directory. 1186void os_closedir (Directory * dir ) 1187FUNC_ATTR_NONNULL_ALL 1188{ 1189uv_fs_req_cleanup (& dir -> request ); 1190} 1191 1192/// Remove a file. 1193/// 1194/// @return `0` for success, non-zero for failure. 1195int os_remove (const char * path ) 1196FUNC_ATTR_NONNULL_ALL 1197{ 1198int r ; 1199RUN_UV_FS_FUNC (r ,uv_fs_unlink ,path ,NULL ); 1200return r ; 1201} 1202 1203/// Get the file information for a given path 1204/// 1205/// @param path Path to the file. 1206/// @param[out] file_info Pointer to a FileInfo to put the information in. 1207/// @return `true` on success, `false` for failure. 1208bool os_fileinfo (const char * path ,FileInfo * file_info ) 1209FUNC_ATTR_NONNULL_ARG (2 ) 1210{ 1211CLEAR_POINTER (file_info ); 1212return os_stat (path ,& (file_info -> stat ))== kLibuvSuccess ; 1213} 1214 1215/// Parses `path` into a `FileInfo` structure. 1216/// 1217/// TODO(ntdiary): Could be extended for path.c cleanup and path normalization 1218/// logic. Eventually merge this with `os_fileinfo` 1219/// 1220/// TODO(justinmk): return value is meaningless currently. 1221bool os_fileinfo2 (const char * path ,FileInfo * info ) 1222FUNC_ATTR_NONNULL_ALL 1223{ 1224CLEAR_POINTER (info ); 1225if (path_with_url (path )) { 1226return true; 1227 } 1228// Preserves the leading two "/"; 3+ "///…" collapse to a single "/" (IEEE 1003.1). 1229// Same rule applies to kPathUNC/kPathGeneric on Windows, but not to kPathDevice or 1230// kPathDeviceUNC, where the leading "//" is significant. 1231const char * p = path_skip_sep (path , false); 1232size_t leading_slashes = (size_t )(p - path ); 1233#ifdef MSWIN 1234if (leading_slashes == 0 && ASCII_ISALPHA (p [0 ])&& p [1 ]== ':' ) { 1235info -> type = kPathDrive ; 1236p = path_skip_sep (p + 2 , false); 1237info -> rest_off = (size_t )(p - path ); 1238return true; 1239 } 1240if (leading_slashes >=2 && (p [0 ]== '?' || p [0 ]== '.' )) { 1241if (!vim_ispathsep_nocolon (p [1 ])) { 1242return true; 1243 } 1244info -> type = kPathDevice ; 1245info -> prefix_off = leading_slashes - 2 ; 1246p = path_skip_sep (p + 2 , false); 1247if (vim_strnicmp_asc (p ,"unc" ,3 )== 0 && vim_ispathsep_nocolon (p [3 ])) { 1248info -> type = kPathDeviceUNC ; 1249p = path_skip_sep (p + 4 , false); 1250info -> root_off = (size_t )(p - path ); 1251 gotoserver ; 1252 } 1253info -> root_off = (size_t )(p - path ); 1254if (ASCII_ISALPHA (p [0 ])&& p [1 ]== ':' ) { 1255p += 2 ; 1256 } 1257p = path_skip_sep (path_next_component (p ), false); 1258info -> rest_off = (size_t )(p - path ); 1259return true; 1260 } 1261if (leading_slashes == 2 ) { 1262info -> type = kPathUNC ; 1263server : 1264p = path_skip_sep (path_next_component (p ), false); 1265p = path_skip_sep (path_next_component (p ), false); 1266info -> rest_off = (size_t )(p - path ); 1267return true; 1268 } 1269#endif 1270info -> type = kPathGeneric ; 1271info -> rest_off = leading_slashes ; 1272info -> root_off = leading_slashes > 2 ?leading_slashes - 1 :0 ; 1273info -> prefix_off = info -> root_off ; 1274return true; 1275} 1276 1277/// Get the file information for a given path without following links 1278/// 1279/// @param path Path to the file. 1280/// @param[out] file_info Pointer to a FileInfo to put the information in. 1281/// @return `true` on success, `false` for failure. 1282bool os_fileinfo_link (const char * path ,FileInfo * file_info ) 1283FUNC_ATTR_NONNULL_ARG (2 ) 1284{ 1285CLEAR_POINTER (file_info ); 1286if (path == NULL ) { 1287return false; 1288 } 1289uv_fs_t request ; 1290bool ok = uv_fs_lstat (NULL ,& request ,path ,NULL )== kLibuvSuccess ; 1291if (ok ) { 1292file_info -> stat = request .statbuf ; 1293 } 1294uv_fs_req_cleanup (& request ); 1295return ok ; 1296} 1297 1298/// Get the file information for a given file descriptor 1299/// 1300/// @param file_descriptor File descriptor of the file. 1301/// @param[out] file_info Pointer to a FileInfo to put the information in. 1302/// @return `true` on success, `false` for failure. 1303bool os_fileinfo_fd (int file_descriptor ,FileInfo * file_info ) 1304FUNC_ATTR_NONNULL_ALL 1305{ 1306uv_fs_t request ; 1307CLEAR_POINTER (file_info ); 1308bool ok = uv_fs_fstat (NULL , 1309& request , 1310file_descriptor , 1311NULL )== kLibuvSuccess ; 1312if (ok ) { 1313file_info -> stat = request .statbuf ; 1314 } 1315uv_fs_req_cleanup (& request ); 1316return ok ; 1317} 1318 1319/// Compare the inodes of two FileInfos 1320/// 1321/// @return `true` if the two FileInfos represent the same file. 1322bool os_fileinfo_id_equal (const FileInfo * file_info_1 ,const FileInfo * file_info_2 ) 1323FUNC_ATTR_NONNULL_ALL 1324{ 1325return file_info_1 -> stat .st_ino == file_info_2 -> stat .st_ino 1326&& file_info_1 -> stat .st_dev == file_info_2 -> stat .st_dev ; 1327} 1328 1329/// Get the `FileID` of a `FileInfo` 1330/// 1331/// @param file_info Pointer to the `FileInfo` 1332/// @param[out] file_id Pointer to a `FileID` 1333void os_fileinfo_id (const FileInfo * file_info ,FileID * file_id ) 1334FUNC_ATTR_NONNULL_ALL 1335{ 1336file_id -> inode = file_info -> stat .st_ino ; 1337file_id -> device_id = file_info -> stat .st_dev ; 1338} 1339 1340/// Get the inode of a `FileInfo` 1341/// 1342/// @deprecated Use `FileID` instead, this function is only needed in memline.c 1343/// @param file_info Pointer to the `FileInfo` 1344/// @return the inode number 1345uint64_t os_fileinfo_inode (const FileInfo * file_info ) 1346FUNC_ATTR_NONNULL_ALL 1347{ 1348return file_info -> stat .st_ino ; 1349} 1350 1351/// Get the size of a file from a `FileInfo`. 1352/// 1353/// @return filesize in bytes. 1354uint64_t os_fileinfo_size (const FileInfo * file_info ) 1355FUNC_ATTR_NONNULL_ALL 1356{ 1357return file_info -> stat .st_size ; 1358} 1359 1360/// Get the number of hardlinks from a `FileInfo`. 1361/// 1362/// @return number of hardlinks. 1363uint64_t os_fileinfo_hardlinks (const FileInfo * file_info ) 1364FUNC_ATTR_NONNULL_ALL 1365{ 1366return file_info -> stat .st_nlink ; 1367} 1368 1369/// Get the blocksize from a `FileInfo`. 1370/// 1371/// @return blocksize in bytes. 1372uint64_t os_fileinfo_blocksize (const FileInfo * file_info ) 1373FUNC_ATTR_NONNULL_ALL 1374{ 1375return file_info -> stat .st_blksize ; 1376} 1377 1378/// Get the `FileID` for a given path 1379/// 1380/// @param path Path to the file. 1381/// @param[out] file_info Pointer to a `FileID` to fill in. 1382/// @return `true` on success, `false` for failure. 1383bool os_fileid (const char * path ,FileID * file_id ) 1384FUNC_ATTR_NONNULL_ALL 1385{ 1386uv_stat_t statbuf ; 1387if (os_stat (path ,& statbuf )== kLibuvSuccess ) { 1388file_id -> inode = statbuf .st_ino ; 1389file_id -> device_id = statbuf .st_dev ; 1390return true; 1391 } 1392return false; 1393} 1394 1395/// Check if two `FileID`s are equal 1396/// 1397/// @param file_id_1 Pointer to first `FileID` 1398/// @param file_id_2 Pointer to second `FileID` 1399/// @return `true` if the two `FileID`s represent te same file. 1400bool os_fileid_equal (const FileID * file_id_1 ,const FileID * file_id_2 ) 1401FUNC_ATTR_NONNULL_ALL 1402{ 1403return file_id_1 -> inode == file_id_2 -> inode 1404&& file_id_1 -> device_id == file_id_2 -> device_id ; 1405} 1406 1407/// Return the canonicalized absolute pathname. 1408/// 1409/// @param[in] name Filename to be canonicalized. 1410/// @param[out] buf Buffer to store the canonicalized values. 1411/// If it is NULL, memory is allocated. In that case, the caller 1412/// should deallocate this buffer. 1413/// @param[in] len The length of the buffer. 1414/// 1415/// @return pointer to the buf on success, or NULL. 1416char * os_realpath (const char * name ,char * buf ,size_t len ) 1417FUNC_ATTR_NONNULL_ARG (1 ) 1418{ 1419uv_fs_t request ; 1420int result = uv_fs_realpath (NULL ,& request ,name ,NULL ); 1421if (result == kLibuvSuccess ) { 1422if (buf == NULL ) { 1423buf = xmalloc (len ); 1424 } 1425xstrlcpy (buf ,request .ptr ,len ); 1426TO_SLASH (buf ); 1427 } 1428uv_fs_req_cleanup (& request ); 1429return result == kLibuvSuccess ?buf :NULL ; 1430} 1431 1432#ifdef MSWIN 1433/// When "fname" is the name of a shortcut (*.lnk) resolve the file it points 1434/// to and return that name in allocated memory. 1435/// Otherwise NULL is returned. 1436char * os_resolve_shortcut (const char * fname ) 1437FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_MALLOC 1438{ 1439HRESULT hr ; 1440IPersistFile * ppf = NULL ; 1441OLECHAR wsz [MAX_PATH ]; 1442char * rfname = NULL ; 1443IShellLinkW * pslw = NULL ; 1444WIN32_FIND_DATAW ffdw ; 1445 1446// Check if the file name ends in ".lnk". Avoid calling CoCreateInstance(), 1447// it's quite slow. 1448if (fname == NULL ) { 1449return rfname ; 1450 } 1451const size_t len = strlen (fname ); 1452if (len <=4 || STRNICMP (fname + len - 4 ,".lnk" ,4 )!= 0 ) { 1453return rfname ; 1454 } 1455 1456CoInitialize (NULL ); 1457 1458// create a link manager object and request its interface 1459hr = CoCreateInstance (& CLSID_ShellLink ,NULL ,CLSCTX_INPROC_SERVER , 1460& IID_IShellLinkW , (void ** )& pslw ); 1461if (hr == S_OK ) { 1462wchar_t * p ; 1463const int r = utf8_to_utf16 (fname ,-1 ,& p ); 1464if (r != 0 ) { 1465semsg ("utf8_to_utf16 failed: %d" ,r ); 1466 }else if (p != NULL ) { 1467// Get a pointer to the IPersistFile interface. 1468hr = pslw -> lpVtbl -> QueryInterface (pslw ,& IID_IPersistFile , (void ** )& ppf ); 1469if (hr != S_OK ) { 1470 gotoshortcut_errorw ; 1471 } 1472 1473// "load" the name and resolve the link 1474hr = ppf -> lpVtbl -> Load (ppf ,p ,STGM_READ ); 1475if (hr != S_OK ) { 1476 gotoshortcut_errorw ; 1477 } 1478 1479# if 0 // This makes Vim wait a long time if the target does not exist. 1480hr = pslw -> lpVtbl -> Resolve (pslw ,NULL ,SLR_NO_UI ); 1481if (hr != S_OK ) { 1482 gotoshortcut_errorw ; 1483 } 1484# endif 1485 1486// Get the path to the link target. 1487ZeroMemory (wsz ,MAX_PATH * sizeof (wchar_t )); 1488hr = pslw -> lpVtbl -> GetPath (pslw ,wsz ,MAX_PATH ,& ffdw ,0 ); 1489if (hr == S_OK && wsz [0 ]!= NUL ) { 1490const int r2 = utf16_to_utf8 (wsz ,-1 ,& rfname ); 1491if (r2 != 0 ) { 1492semsg ("utf16_to_utf8 failed: %d" ,r2 ); 1493 } 1494 } 1495 1496shortcut_errorw : 1497xfree (p ); 1498 gotoshortcut_end ; 1499 } 1500 } 1501 1502shortcut_end : 1503// Release all interface pointers (both belong to the same object) 1504if (ppf != NULL ) { 1505ppf -> lpVtbl -> Release (ppf ); 1506 } 1507if (pslw != NULL ) { 1508pslw -> lpVtbl -> Release (pslw ); 1509 } 1510 1511CoUninitialize (); 1512TO_SLASH (rfname ); 1513return rfname ; 1514} 1515 1516# define IS_PATH_SEP (c ) ((c) == L'\\' || (c) == L'/') 1517/// Returns true if the path contains a reparse point (junction or symbolic 1518/// link). Otherwise false in returned. 1519bool os_is_reparse_point_include (const char * path ) 1520{ 1521wchar_t * p ,* q ,* utf16_path ; 1522wchar_t buf [MAX_PATH ]; 1523DWORD attr ; 1524bool result = false; 1525 1526const int r = utf8_to_utf16 (path ,-1 ,& utf16_path ); 1527if (r != 0 ) { 1528semsg ("utf8_to_utf16 failed: %d" ,r ); 1529return false; 1530 } 1531 1532p = utf16_path ; 1533if (isalpha ((uint8_t )p [0 ])&& p [1 ]== L':' && IS_PATH_SEP (p [2 ])) { 1534p += 3 ; 1535 }else if (IS_PATH_SEP (p [0 ])&& IS_PATH_SEP (p [1 ])) { 1536p += 2 ; 1537 } 1538 1539while (* p != L'\0' ) { 1540q = wcspbrk (p ,L"\\/" ); 1541if (q == NULL ) { 1542p = q = utf16_path + wcslen (utf16_path ); 1543 }else { 1544p = q + 1 ; 1545 } 1546if (q - utf16_path >=MAX_PATH ) { 1547break ; 1548 } 1549wcsncpy (buf ,utf16_path , (size_t )(q - utf16_path )); 1550buf [q - utf16_path ]= L'\0' ; 1551attr = GetFileAttributesW (buf ); 1552if (attr != INVALID_FILE_ATTRIBUTES 1553&& (attr & FILE_ATTRIBUTE_REPARSE_POINT )!= 0 ) { 1554result = true; 1555break ; 1556 } 1557 } 1558xfree (utf16_path ); 1559return result ; 1560} 1561#endif