robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
f0a0182285
master
1// Environment inspection 2 3#include <assert.h> 4#include <limits.h> 5#include <stdbool.h> 6#include <stddef.h> 7#include <stdint.h> 8#include <string.h> 9#include <uv.h> 10 11#include "auto/config.h" 12#include "nvim/api/private/helpers.h" 13#include "nvim/ascii_defs.h" 14#include "nvim/buffer_defs.h" 15#include "nvim/charset.h" 16#include "nvim/cmdexpand_defs.h" 17#include "nvim/eval.h" 18#include "nvim/eval/fs.h" 19#include "nvim/eval/vars.h" 20#include "nvim/globals.h" 21#include "nvim/log.h" 22#include "nvim/macros_defs.h" 23#include "nvim/map_defs.h" 24#include "nvim/memory.h" 25#include "nvim/message.h" 26#include "nvim/option_vars.h" 27#include "nvim/os/fs.h" 28#include "nvim/os/os.h" 29#include "nvim/os/os_defs.h" 30#include "nvim/path.h" 31#include "nvim/strings.h" 32#include "nvim/types_defs.h" 33#include "nvim/version.h" 34#include "nvim/vim_defs.h" 35 36#ifdef MSWIN 37# include "nvim/mbyte.h" 38#endif 39 40#ifdef BACKSLASH_IN_FILENAME 41# include "nvim/fileio.h" 42#endif 43 44#ifdef __APPLE__ 45# include <mach/task.h> 46#endif 47 48#ifdef HAVE__NSGETENVIRON 49# include <crt_externs.h> 50#endif 51 52#ifdef HAVE_SYS_UTSNAME_H 53# include <sys/utsname.h> 54#endif 55 56#include "auto/pathdef.h" 57 58#include "os/env.c.generated.h" 59 60void env_init (void ) 61{ 62nvim_testing = os_env_exists ("NVIM_TEST" , false); 63} 64 65/// Like getenv(), but returns NULL if the variable is empty. 66/// Result must be freed by the caller. 67/// @see os_env_exists 68/// @see os_getenv_noalloc 69char * os_getenv (const char * name ) 70FUNC_ATTR_NONNULL_ALL 71{ 72char * e = NULL ; 73if (name [0 ]== NUL ) { 74return NULL ; 75 } 76int r = 0 ; 77#define INIT_SIZE 64 78size_t size = INIT_SIZE ; 79char buf [INIT_SIZE ]; 80r = uv_os_getenv (name ,buf ,& size ); 81if (r == UV_ENOBUFS ) { 82e = xmalloc (size ); 83r = uv_os_getenv (name ,e ,& size ); 84if (r != 0 || size == 0 || e [0 ]== NUL ) { 85XFREE_CLEAR (e ); 86 gotoend ; 87 } 88 }else if (r != 0 || size == 0 || buf [0 ]== NUL ) { 89e = NULL ; 90 gotoend ; 91 }else { 92// NB: `size` param of uv_os_getenv() includes the NUL-terminator, 93// except when it does not include the NUL-terminator. 94e = xmemdupz (buf ,size ); 95 } 96end : 97if (r != 0 && r != UV_ENOENT && r != UV_UNKNOWN ) { 98ELOG ("uv_os_getenv(%s) failed: %d %s" ,name ,r ,uv_err_name (r )); 99 } 100return e ; 101} 102 103/// Like getenv(), but stores the value in `buf` instead of allocating. 104/// Value is truncated if it exceeds `bufsize`. 105/// 106/// @return `buf` on success, NULL on failure 107/// @see os_env_exists 108/// @see os_getenv_noalloc 109char * os_getenv_buf (const char * const name ,char * const buf ,const size_t bufsize ) 110FUNC_ATTR_NONNULL_ALL 111{ 112if (name [0 ]== NUL ) { 113return NULL ; 114 } 115 116size_t size = bufsize ; 117int r = uv_os_getenv (name ,buf ,& size ); 118if (r == UV_ENOBUFS ) { 119char * e = xmalloc (size ); 120r = uv_os_getenv (name ,e ,& size ); 121if (r == 0 && size != 0 && e [0 ]!= NUL ) { 122xmemcpyz (buf ,e ,MIN (bufsize ,size )- 1 ); 123 } 124xfree (e ); 125 } 126 127if (r != 0 || size == 0 || buf [0 ]== NUL ) { 128if (r != 0 && r != UV_ENOENT && r != UV_UNKNOWN ) { 129ELOG ("uv_os_getenv(%s) failed: %d %s" ,name ,r ,uv_err_name (r )); 130 } 131return NULL ; 132 } 133return buf ; 134} 135 136/// Like getenv(), but use `NameBuff` instead of allocating. 137/// Value is truncated if it exceeds sizeof(NameBuff). 138/// 139/// @return pointer to `NameBuff` on success, NULL on failure 140/// @see os_env_exists 141/// @see os_getenv_buf 142char * os_getenv_noalloc (const char * name ) 143FUNC_ATTR_NONNULL_ALL 144{ 145return os_getenv_buf (name ,NameBuff ,sizeof (NameBuff )); 146} 147 148/// Returns true if environment variable `name` is defined (even if empty). 149/// Returns false if not found (UV_ENOENT) or other failure. 150/// 151/// @param name the environment variable in question 152/// @param nonempty Require a non-empty value. Treat empty as "does not exist". 153/// @return whether the variable exists 154bool os_env_exists (const char * name ,bool nonempty ) 155FUNC_ATTR_NONNULL_ALL 156{ 157if (name [0 ]== NUL ) { 158return false; 159 } 160// Use a tiny buffer because we don't care about the value: if uv_os_getenv() 161// returns UV_ENOBUFS, the env var was found. 162char buf [2 ]; 163size_t size = sizeof (buf ); 164int r = uv_os_getenv (name ,buf ,& size ); 165assert (r != UV_EINVAL ); 166if (r != 0 && r != UV_ENOENT && r != UV_ENOBUFS ) { 167ELOG ("uv_os_getenv(%s) failed: %d %s" ,name ,r ,uv_err_name (r )); 168 } 169return ((r == 0 && (!nonempty || size > 0 ))|| r == UV_ENOBUFS ); 170} 171 172/// Sets an environment variable. 173/// 174/// Windows (Vim-compat): Empty string (:let $FOO="") undefines the env var. 175int os_setenv (const char * name ,const char * value ,int overwrite ) 176FUNC_ATTR_NONNULL_ALL 177{ 178if (name [0 ]== NUL ) { 179return -1 ; 180 } 181#ifdef MSWIN 182if (!overwrite && !os_env_exists (name , true)) { 183return 0 ; 184 } 185if (value [0 ]== NUL ) { 186// Windows (Vim-compat): Empty string undefines the env var. 187return os_unsetenv (name ); 188 } 189#else 190if (!overwrite && os_env_exists (name , false)) { 191return 0 ; 192 } 193#endif 194int r ; 195#ifdef MSWIN 196// Call _putenv_s() so libintl can see LC_ALL/LANG/etc. libuv only calls SetEnvironmentVariableW. 197if (striequal (name ,"LC_ALL" )|| striequal (name ,"LANGUAGE" ) 198|| striequal (name ,"LANG" )|| striequal (name ,"LC_MESSAGES" )) { 199r = _putenv_s (name ,value );// NOLINT 200assert (r == 0 ); 201 } 202#endif 203r = uv_os_setenv (name ,value ); 204assert (r != UV_EINVAL ); 205if (r != 0 ) { 206ELOG ("uv_os_setenv(%s) failed: %d %s" ,name ,r ,uv_err_name (r )); 207 } 208return r == 0 ?0 :-1 ; 209} 210 211/// Unset environment variable 212int os_unsetenv (const char * name ) 213FUNC_ATTR_NONNULL_ALL 214{ 215if (name [0 ]== NUL ) { 216return -1 ; 217 } 218int r = uv_os_unsetenv (name ); 219if (r != 0 ) { 220ELOG ("uv_os_unsetenv(%s) failed: %d %s" ,name ,r ,uv_err_name (r )); 221 } 222return r == 0 ?0 :-1 ; 223} 224 225void os_free_fullenv (char ** env ) 226{ 227if (!env ) { 228return ; 229 } 230for (char ** it = env ;* it ;it ++ ) { 231XFREE_CLEAR (* it ); 232 } 233xfree (env ); 234} 235 236/// Copy value of the environment variable at `index` in the current 237/// environment variables block. 238/// Result must be freed by the caller. 239/// 240/// @param index nth item in environment variables block 241/// @return [allocated] environment variable's value, or NULL 242char * os_getenvname_at_index (size_t index ) 243{ 244#ifdef MSWIN 245wchar_t * envstrings = GetEnvironmentStringsW (); 246if (!envstrings ) { 247return NULL ; 248 } 249wchar_t * p = envstrings ; 250char * name = NULL ; 251size_t i = 0 ; 252size_t l ; 253// GetEnvironmentStringsW() result has this format: 254// var1=value1\0var2=value2\0...varN=valueN\0\0 255while ((l = wcslen (p ))!= 0 && i <=index ) { 256if (i == index ) { 257char * utf8_str ; 258int conversion_result = utf16_to_utf8 (p ,-1 ,& utf8_str ); 259if (conversion_result != 0 ) { 260semsg ("utf16_to_utf8 failed: %d" ,conversion_result ); 261break ; 262 } 263 264// Some Windows env vars start with =, so skip over that to find the 265// separator between name/value 266const char * const end = strchr (utf8_str + (utf8_str [0 ]== '=' ?1 :0 ),'=' ); 267assert (end != NULL ); 268ptrdiff_t len = end - utf8_str ; 269assert (len > 0 ); 270name = xmemdupz (utf8_str , (size_t )len ); 271xfree (utf8_str ); 272break ; 273 } 274 275// Advance past the name and NUL 276p += l + 1 ; 277i ++ ; 278 } 279 280FreeEnvironmentStringsW (envstrings ); 281return name ; 282#else 283# ifdef HAVE__NSGETENVIRON 284char ** environ = * _NSGetEnviron (); 285# else 286extern char ** environ ; 287# endif 288 289// check if index is inside the environ array 290for (size_t i = 0 ;i <=index ;i ++ ) { 291if (environ [i ]== NULL ) { 292return NULL ; 293 } 294 } 295char * str = environ [index ]; 296assert (str != NULL ); 297const char * const end = strchr (str ,'=' ); 298assert (end != NULL ); 299ptrdiff_t len = end - str ; 300assert (len > 0 ); 301return xmemdupz (str , (size_t )len ); 302#endif 303} 304 305/// Get the process ID of the Nvim process. 306/// 307/// @return the process ID. 308int64_t os_get_pid (void ) 309{ 310#ifdef MSWIN 311return (int64_t )GetCurrentProcessId (); 312#else 313return (int64_t )getpid (); 314#endif 315} 316 317/// Signals to the OS that Nvim is an application for "interactive work" 318/// which should be prioritized similar to a GUI app. 319void os_hint_priority (void ) 320{ 321#ifdef __APPLE__ 322// By default, processes have the TASK_UNSPECIFIED "role", which means all of its threads are 323// clamped to Default QoS. Setting the role to TASK_DEFAULT_APPLICATION removes this clamp. 324integer_t policy = TASK_DEFAULT_APPLICATION ; 325task_policy_set (mach_task_self (),TASK_CATEGORY_POLICY ,& policy ,1 ); 326#endif 327} 328 329/// Gets the hostname of the current machine. 330/// 331/// @param hostname Buffer to store the hostname. 332/// @param size Size of `hostname`. 333void os_get_hostname (char * hostname ,size_t size ) 334{ 335#ifdef HAVE_SYS_UTSNAME_H 336struct utsname vutsname ; 337 338if (uname (& vutsname )< 0 ) { 339* hostname = NUL ; 340 }else { 341xstrlcpy (hostname ,vutsname .nodename ,size ); 342 } 343#elif defined(MSWIN ) 344wchar_t host_utf16 [MAX_COMPUTERNAME_LENGTH + 1 ]; 345DWORD host_wsize = sizeof (host_utf16 ) /sizeof (host_utf16 [0 ]); 346if (GetComputerNameW (host_utf16 ,& host_wsize )== 0 ) { 347* hostname = NUL ; 348DWORD err = GetLastError (); 349semsg ("GetComputerNameW failed: %d" ,err ); 350return ; 351 } 352host_utf16 [host_wsize ]= NUL ; 353 354char * host_utf8 ; 355int conversion_result = utf16_to_utf8 (host_utf16 ,-1 ,& host_utf8 ); 356if (conversion_result != 0 ) { 357semsg ("utf16_to_utf8 failed: %d" ,conversion_result ); 358return ; 359 } 360xstrlcpy (hostname ,host_utf8 ,size ); 361xfree (host_utf8 ); 362#else 363emsg ("os_get_hostname failed: missing uname()" ); 364* hostname = NUL ; 365#endif 366} 367 368/// The "real" home directory as determined by `init_homedir`. 369static char * homedir = NULL ; 370static char * os_uv_homedir (void ); 371 372/// Gets the "real", resolved user home directory as determined by `init_homedir`. 373const char * os_homedir (void ) 374{ 375if (!homedir ) { 376emsg ("os_homedir failed: homedir not initialized" ); 377return NULL ; 378 } 379return homedir ; 380} 381 382/// Sets `homedir` to the "real", resolved user home directory, as follows: 383/// 1. get value of $HOME 384/// 2. if $HOME is not set, try the following 385/// For Windows: 386/// 1. assemble homedir using HOMEDRIVE and HOMEPATH 387/// 2. try os_uv_homedir() 388/// 3. resolve a direct reference to another system variable 389/// 4. guess C drive 390/// For Unix: 391/// 1. try os_uv_homedir() 392/// 2. go to that directory 393/// This also works with mounts and links. 394/// Don't do this for Windows, it will change the "current dir" for a drive. 395/// 3. fall back to current working directory as a last resort 396void init_homedir (void ) 397{ 398// In case we are called a second time. 399xfree (homedir ); 400homedir = NULL ; 401 402char * var = os_getenv ("HOME" ); 403char * tofree = var ; 404 405#ifdef MSWIN 406// Typically, $HOME is not defined on Windows, unless the user has 407// specifically defined it for Vim's sake. However, on Windows NT 408// platforms, $HOMEDRIVE and $HOMEPATH are automatically defined for 409// each user. Try constructing $HOME from these. 410if (var == NULL ) { 411char * homedrive = os_getenv ("HOMEDRIVE" ); 412char * homepath = os_getenv ("HOMEPATH" ); 413if (homepath == NULL ) { 414homepath = xstrdup (PATHSEPSTR ); 415 } 416if (homedrive != NULL 417&& strlen (homedrive )+ strlen (homepath )< MAXPATHL ) { 418snprintf (os_buf ,MAXPATHL ,"%s%s" ,homedrive ,homepath ); 419if (os_buf [0 ]!= NUL ) { 420var = os_buf ; 421 } 422 } 423xfree (homepath ); 424xfree (homedrive ); 425 } 426if (var == NULL ) { 427var = os_uv_homedir (); 428 } 429 430// Weird but true: $HOME may contain an indirect reference to another 431// variable, esp. "%USERPROFILE%". Happens when $USERPROFILE isn't set 432// when $HOME is being set. 433if (var != NULL && * var == '%' ) { 434const char * p = strchr (var + 1 ,'%' ); 435if (p != NULL ) { 436vim_snprintf (os_buf , (size_t )(p - var ),"%s" ,var + 1 ); 437var = NULL ; 438char * exp = os_getenv (os_buf ); 439if (exp != NULL ) { 440if (* exp != NUL && strlen (exp )+ strlen (p )< MAXPATHL ) { 441vim_snprintf (os_buf ,MAXPATHL ,"%s%s" ,exp ,p + 1 ); 442var = os_buf ; 443 } 444xfree (exp ); 445 } 446 } 447 } 448 449// Default home dir is C:/ 450// Best assumption we can make in such a situation. 451if (var == NULL 452// Empty means "undefined" 453|| * var == NUL ) { 454var = "C:/" ; 455 } 456#endif 457 458#ifdef UNIX 459if (var == NULL ) { 460var = os_uv_homedir (); 461 } 462 463// Get the actual path. This resolves links. 464if (var != NULL && os_realpath (var ,IObuff ,IOSIZE )!= NULL ) { 465var = IObuff ; 466 } 467 468// Fall back to current working directory if home is not found 469if ((var == NULL || * var == NUL ) 470&& os_dirname (os_buf ,sizeof (os_buf ))== OK ) { 471var = os_buf ; 472 } 473#endif 474if (var != NULL ) { 475homedir = TO_SLASH_SAVE (var ); 476 } 477xfree (tofree ); 478} 479 480static char homedir_buf [MAXPATHL ]; 481 482static char * os_uv_homedir (void ) 483{ 484homedir_buf [0 ]= NUL ; 485size_t homedir_size = MAXPATHL ; 486// http://docs.libuv.org/en/v1.x/misc.html#c.uv_os_homedir 487int ret_value = uv_os_homedir (homedir_buf ,& homedir_size ); 488if (ret_value == 0 && homedir_size < MAXPATHL ) { 489return homedir_buf ; 490 } 491ELOG ("uv_os_homedir() failed %d: %s" ,ret_value ,os_strerror (ret_value )); 492homedir_buf [0 ]= NUL ; 493return NULL ; 494} 495 496#ifdef EXITFREE 497 498void free_homedir (void ) 499{ 500xfree (homedir ); 501} 502 503#endif 504 505/// Call expand_env() and store the result in an allocated string. 506/// This is not very memory efficient, this expects the result to be freed 507/// again soon. 508/// @param src String containing environment variables to expand 509/// @see {expand_env} 510char * expand_env_save (char * src ) 511{ 512return expand_env_save_opt (src , false,NULL ); 513} 514 515/// Similar to expand_env_save() but when "one" is `true` handle the string as 516/// one file name, i.e. only expand "~" at the start. 517/// @param src String containing environment variables to expand 518/// @param one Should treat as only one file name 519/// @param esc_chars chars to escape in expanded vars 520/// @see {expand_env} 521char * expand_env_save_opt (char * src ,bool one ,char * esc_chars ) 522{ 523char * p = xmalloc (MAXPATHL ); 524expand_env_esc (src ,p ,MAXPATHL ,esc_chars ,one ,NULL ); 525return p ; 526} 527 528/// Expand environment variable with path name. 529/// "~/" is also expanded, using $HOME. For Unix "~user/" is expanded. 530/// Skips over "\ ", "\~" and "\$" (not for Win32 though). 531/// If anything fails no expansion is done and dst equals src. 532/// 533/// @param src Input string e.g. "$HOME/vim.hlp" 534/// @param dst[out] Where to put the result 535/// @param dstlen Maximum length of the result 536size_t expand_env (char * src ,char * dst ,int dstlen ) 537{ 538return expand_env_esc (src ,dst ,dstlen ,NULL , false,NULL ); 539} 540 541/// Expand environment variable with path name and escaping. 542/// @see expand_env 543/// 544/// @param srcp Input string e.g. "$HOME/vim.hlp" 545/// @param dst[out] Where to put the result 546/// @param dstlen Maximum length of the result 547/// @param esc_chars chars to escape in expanded vars 548/// @param one `srcp` is a single filename 549/// @param prefix Start again after this (can be NULL) 550size_t expand_env_esc (const char * restrictsrcp ,char * restrictdst ,int dstlen ,char * esc_chars , 551bool one ,char * prefix ) 552FUNC_ATTR_NONNULL_ARG (1 ,2 ) 553{ 554char * tail ; 555char * var ; 556bool copy_char ; 557bool mustfree ;// var was allocated, need to free it later 558bool at_start = true;// at start of a name 559char * const dst_start = dst ; 560 561int prefix_len = (prefix == NULL ) ?0 : (int )strlen (prefix ); 562 563char * src = skipwhite (srcp ); 564dstlen -- ;// leave one char space for "\," 565while (* src && dstlen > 0 ) { 566// Skip over `=expr`. 567if (src [0 ]== '`' && src [1 ]== '=' ) { 568var = src ; 569src += 2 ; 570skip_expr (& src ,NULL ); 571if (* src == '`' ) { 572src ++ ; 573 } 574size_t len = (size_t )(src - var ); 575if (len > (size_t )dstlen ) { 576len = (size_t )dstlen ; 577 } 578memcpy (dst ,var ,len ); 579dst += len ; 580dstlen -= (int )len ; 581continue ; 582 } 583 584copy_char = true; 585if ((* src == '$' )|| (* src == '~' && at_start )) { 586mustfree = false; 587 588// The variable name is copied into dst temporarily, because it may 589// be a string in read-only memory and a NUL needs to be appended. 590if (* src != '~' ) {// environment var 591tail = src + 1 ; 592var = dst ; 593int c = dstlen - 1 ; 594 595#ifdef UNIX 596// Unix has ${var-name} type environment vars 597if (* tail == '{' && !vim_isIDc ('{' )) { 598tail ++ ;// ignore '{' 599while (c -- > 0 && * tail != NUL && * tail != '}' ) { 600* var ++ = * tail ++ ; 601 } 602 }else 603#endif 604 { 605while (c -- > 0 && * tail != NUL && vim_isIDc ((uint8_t )(* tail ))) { 606* var ++ = * tail ++ ; 607 } 608 } 609 610#ifdef UNIX 611// Verify that we have found the end of a Unix ${VAR} style variable 612if (src [1 ]== '{' && * tail != '}' ) { 613var = NULL ; 614 }else { 615if (src [1 ]== '{' ) { 616tail ++ ; 617 } 618#endif 619* var = NUL ; 620var = vim_getenv (dst ); 621// Backslashes in `srcp` might just be used for escaping. Expanded env 622// vars represent paths, so their backslashes can be safely normalized. 623// Autocmd file patterns require this normalization. 624TO_SLASH (var ); 625mustfree = true; 626#ifdef UNIX 627} 628#endif 629} else if ( src [ 1 ] == NUL // home directory 630|| vim_ispathsep ( src [ 1 ]) 631|| vim_strchr ( " ,\t\n" , ( uint8_t ) src [ 1 ]) != NULL ) { 632var = homedir ; 633tail = src + 1 ; 634} else { // user directory 635#ifdef UNIX 636// Copy ~user to dst[], so we can put a NUL after it. 637tail = src ; 638var = dst ; 639int c = dstlen - 1 ; 640while ( c -- > 0 641&& * tail 642&& vim_isfilec (( uint8_t )( * tail )) 643&& ! vim_ispathsep ( * tail )) { 644* var ++ = * tail ++ ; 645} 646* var = NUL ; 647var = ( * dst == NUL ) ? NULL 648: os_get_userdir ( dst + 1 ); 649mustfree = true; 650#else 651// cannot expand user's home directory, so don't try 652var = NULL ; 653tail = "" ; // for gcc 654#endif // UNIX 655} 656 657// If "var" contains any character from "esc_chars", escape it 658// with a backslash. The historical use is escaping spaces so 659// that ":e ~/tt" works when $HOME contains a space. 660if ( esc_chars != NULL && var != NULL && strpbrk ( var , esc_chars ) != NULL ) { 661char * p = vim_strsave_escaped ( var , esc_chars ); 662 663if ( mustfree ) { 664xfree ( var ); 665} 666var = p ; 667mustfree = true; 668} 669 670if ( var != NULL && * var != NUL ) { 671int c = ( int ) strlen ( var ); 672if (( size_t ) c + strlen ( tail ) + 1 < ( unsigned ) dstlen ) { 673STRCPY ( dst , var ); 674dstlen -= c ; 675// if var[] ends in a path separator and tail[] starts 676// with it, skip a character 677if ( after_pathsep ( dst , dst + c ) 678#ifdef BACKSLASH_IN_FILENAME 679&& dst [ c - 1 ] != ':' 680#endif 681&& vim_ispathsep ( * tail )) { 682tail ++ ; 683} 684dst += c ; 685src = tail ; 686copy_char = false; 687} 688} 689if ( mustfree ) { 690xfree ( var ); 691} 692} 693 694if ( copy_char ) { // copy at least one char 695// Recognize the start of a new name, for '~'. 696// Don't do this when "one" is true, to avoid expanding "~" in 697// ":edit foo ~ foo". 698at_start = false; 699if ( src [ 0 ] == '\\' && src [ 1 ] != NUL ) { 700* dst ++ = * src ++ ; 701dstlen -- ; 702} else if (( src [ 0 ] == ' ' || src [ 0 ] == ',' ) && ! one ) { 703at_start = true; 704} 705if ( dstlen > 0 ) { 706* dst ++ = * src ++ ; 707dstlen -- ; 708 709if ( prefix != NULL 710&& src - prefix_len >= srcp 711&& strncmp ( src - prefix_len , prefix , ( size_t ) prefix_len ) == 0 ) { 712at_start = true; 713} 714} 715} 716} 717* dst = NUL ; 718 719return ( size_t )( dst - dst_start ); 720} 721 722/// Check if the directory "vimdir/runtime" exists. 723/// Return NULL if not, return its name in allocated memory otherwise. 724/// @param vimdir directory to test 725static char * vim_runtime_dir (const char * vimdir ) 726{ 727if ( vimdir == NULL || * vimdir == NUL ) { 728return NULL ; 729} 730size_t vimdir_len = strlen ( vimdir ); 731String p = concat_fnames ( cbuf_as_string (( char * ) vimdir , vimdir_len ), 732STATIC_CSTR_AS_STRING ( RUNTIME_DIRNAME ), true); 733if ( os_isdir ( p . data )) { 734return p . data ; 735} 736xfree ( p . data ); 737return NULL ; 738} 739 740/// If `dirname + "/"` precedes `pend` in the path, return the pointer to 741/// `dirname + "/" + pend`. Otherwise return `pend`. 742/// 743/// Examples (path = /usr/local/share/nvim/runtime/doc/help.txt): 744/// 745/// pend = help.txt 746/// dirname = doc 747/// -> doc/help.txt 748/// 749/// pend = doc/help.txt 750/// dirname = runtime 751/// -> runtime/doc/help.txt 752/// 753/// pend = runtime/doc/help.txt 754/// dirname = vim74 755/// -> runtime/doc/help.txt 756/// 757/// @param path Path to a file 758/// @param pend A suffix of the path 759/// @param dirname The immediate path fragment before the pend 760/// @return The new pend including dirname or just pend 761static char * remove_tail ( char * path , char * pend , char * dirname ) 762{ 763size_t len = strlen ( dirname ); 764char * new_tail = pend - len - 1 ; 765 766if ( new_tail >= path 767&& path_cmp ( p_fic , new_tail , dirname , len ) == 0 768&& ( new_tail == path || after_pathsep ( path , new_tail ))) { 769return new_tail ; 770} 771return pend ; 772} 773 774/// Iterates $PATH-like delimited list `val`. 775/// 776/// @note Environment variables must not be modified during iteration. 777/// 778/// @param[in] delim Delimiter character. 779/// @param[in] val Value of the environment variable to iterate over. 780/// @param[in] iter Pointer used for iteration. Must be NULL on first 781/// iteration. 782/// @param[out] dir Location where pointer to the start of the current 783/// directory name should be saved. May be set to NULL. 784/// @param[out] len Location where current directory length should be saved. 785/// 786/// @return Next iter argument value or NULL when iteration should stop. 787const void * vim_env_iter (const char delim , const char * const val , const void * const iter , 788const char ** const dir , size_t * const len ) 789FUNC_ATTR_NONNULL_ARG ( 2 , 4 , 5 ) FUNC_ATTR_WARN_UNUSED_RESULT 790{ 791const char * varval = iter ; 792if ( varval == NULL ) { 793varval = val ; 794} 795* dir = varval ; 796const char * const dirend = strchr ( varval , delim ); 797if ( dirend == NULL ) { 798* len = strlen ( varval ); 799return NULL ; 800} 801* len = ( size_t )( dirend - varval ); 802return dirend + 1 ; 803} 804 805/// Iterates $PATH-like delimited list `val` in reverse order. 806/// 807/// @note Environment variables must not be modified during iteration. 808/// 809/// @param[in] delim Delimiter character. 810/// @param[in] val Value of the environment variable to iterate over. 811/// @param[in] iter Pointer used for iteration. Must be NULL on first 812/// iteration. 813/// @param[out] dir Location where pointer to the start of the current 814/// directory name should be saved. May be set to NULL. 815/// @param[out] len Location where current directory length should be saved. 816/// 817/// @return Next iter argument value or NULL when iteration should stop. 818const void * vim_env_iter_rev (const char delim , const char * const val , const void * const iter , 819const char ** const dir , size_t * const len ) 820FUNC_ATTR_NONNULL_ARG ( 2 , 4 , 5 ) FUNC_ATTR_WARN_UNUSED_RESULT 821{ 822const char * varend = iter ; 823if ( varend == NULL ) { 824varend = val + strlen ( val ) - 1 ; 825} 826const size_t varlen = ( size_t )( varend - val ) + 1 ; 827const char * const colon = xmemrchr ( val , ( uint8_t ) delim , varlen ); 828if ( colon == NULL ) { 829* len = varlen ; 830* dir = val ; 831return NULL ; 832} 833* dir = colon + 1 ; 834* len = ( size_t )( varend - colon ); 835return colon - 1 ; 836} 837 838/// @param[out] exe_name should be at least MAXPATHL in size 839void vim_get_prefix_from_exepath ( char * exe_name ) 840{ 841// TODO(bfredl): param could have been written as "char exe_name[MAXPATHL]" 842// but c_grammar.lua does not recognize it (yet). 843xstrlcpy ( exe_name , get_vim_var_str ( VV_PROGPATH ), MAXPATHL * sizeof( * exe_name )); 844char * path_end = path_tail_with_sep ( exe_name ); 845* path_end = NUL ; // remove the trailing "nvim.exe" 846path_end = path_tail ( exe_name ); 847* path_end = NUL ; // remove the trailing "bin/" 848} 849 850/// Vim getenv() wrapper with special handling of $HOME, $VIM, $VIMRUNTIME, 851/// allowing the user to override the Nvim runtime directory at runtime. 852/// Result must be freed by the caller. 853/// 854/// @param name Environment variable to expand 855/// @return [allocated] Expanded environment variable, or NULL 856char * vim_getenv (const char * name ) 857{ 858// init_path() should have been called before now. 859assert ( get_vim_var_str ( VV_PROGPATH )[ 0 ] != NUL ); 860 861#ifdef MSWIN 862if ( strcmp ( name , "HOME" ) == 0 ) { 863return xstrdup ( homedir ); 864} 865#endif 866 867char * kos_env_path = os_getenv ( name ); 868#ifdef BACKSLASH_IN_FILENAME 869if ( striequal ( name , "VIMRUNTIME" ) 870|| striequal ( name , "PATH" ) 871|| striequal ( name , "CDPATH" ) 872|| striequal ( name , "TMPDIR" ) 873|| striequal ( name , "TMP" ) 874|| striequal ( name , "TEMP" ) 875|| striequal ( name , "VIM" ) 876|| striequal ( name , "MYVIMRC" )) { 877TO_SLASH ( kos_env_path ); 878} 879#endif 880if ( kos_env_path != NULL ) { 881return kos_env_path ; 882} 883 884bool vimruntime = ( strcmp ( name , "VIMRUNTIME" ) == 0 ); 885if (! vimruntime && strcmp ( name , "VIM" ) != 0 ) { 886return NULL ; 887} 888 889// When expanding $VIMRUNTIME fails, try using $VIM/vim<version> or $VIM. 890// Don't do this when default_vimruntime_dir is non-empty. 891char * vim_path = NULL ; 892if ( vimruntime 893&& * default_vimruntime_dir == NUL ) { 894kos_env_path = os_getenv ( "VIM" ); // kos_env_path was NULL. 895if ( kos_env_path != NULL ) { 896vim_path = vim_runtime_dir ( kos_env_path ); 897if ( vim_path == NULL ) { 898vim_path = kos_env_path ; 899} else { 900xfree ( kos_env_path ); 901} 902} 903} 904 905// When expanding $VIM or $VIMRUNTIME fails, try using: 906// - the directory name from 'helpfile' (unless it contains '$') 907// - the executable name from argv[0] 908if ( vim_path == NULL ) { 909if ( p_hf != NULL && vim_strchr ( p_hf , '$' ) == NULL ) { 910vim_path = p_hf ; 911} 912 913char exe_name [ MAXPATHL ]; 914// Find runtime path relative to the nvim binary: ../share/nvim/runtime 915if ( vim_path == NULL ) { 916vim_get_prefix_from_exepath ( exe_name ); 917if ( append_path ( exe_name , "share/nvim/runtime/" , MAXPATHL ) == OK ) { 918vim_path = exe_name ; 919} 920} 921 922if ( vim_path != NULL ) { 923// remove the file name 924char * vim_path_end = path_tail ( vim_path ); 925 926// remove "doc/" from 'helpfile', if present 927if ( vim_path == p_hf ) { 928vim_path_end = remove_tail ( vim_path , vim_path_end , "doc" ); 929} 930 931// for $VIM, remove "runtime/", if present 932if (! vimruntime ) { 933vim_path_end = remove_tail ( vim_path , vim_path_end , RUNTIME_DIRNAME ); 934} 935 936// remove trailing path separator 937if ( vim_path_end > vim_path && after_pathsep ( vim_path , vim_path_end )) { 938vim_path_end -- ; 939} 940 941// check that the result is a directory name 942assert ( vim_path_end >= vim_path ); 943vim_path = xmemdupz ( vim_path , ( size_t )( vim_path_end - vim_path )); 944 945if (! os_isdir ( vim_path )) { 946xfree ( vim_path ); 947vim_path = NULL ; 948} 949} 950assert ( vim_path != exe_name ); 951} 952 953// When there is a pathdef.c file we can use default_vim_dir and 954// default_vimruntime_dir 955if ( vim_path == NULL ) { 956// Only use default_vimruntime_dir when it is not empty 957if ( vimruntime && * default_vimruntime_dir != NUL ) { 958vim_path = xstrdup ( default_vimruntime_dir ); 959} else if ( * default_vim_dir != NUL ) { 960if ( vimruntime 961&& ( vim_path = vim_runtime_dir ( default_vim_dir )) == NULL ) { 962vim_path = xstrdup ( default_vim_dir ); 963} 964} 965} 966 967// Set the environment variable, so that the new value can be found fast 968// next time, and others can also use it (e.g. Perl). 969if ( vim_path != NULL ) { 970if ( vimruntime ) { 971os_setenv ( "VIMRUNTIME" , vim_path , 1 ); 972didset_vimruntime = true; 973} else { 974os_setenv ( "VIM" , vim_path , 1 ); 975didset_vim = true; 976} 977} 978return vim_path ; 979} 980 981/// Replace home directory by "~" in each space or comma separated file name in 982/// 'src'. 983/// 984/// Replace home directory with tilde in each file name 985/// 986/// If anything fails (except when out of space) dst equals src. 987/// 988/// @param[in] buf When not NULL, uses this buffer to check whether it is 989/// a help file. If it is then path to file is removed 990/// completely, `one` is ignored and assumed to be true. 991/// @param[in] src Input file names. Assumed to be a space/comma separated 992/// list unless `one` is true. 993/// @param[out] dst Where to put the result. 994/// @param[in] dstlen Destination length. 995/// @param[in] one If true, assumes source is a single file name and not 996/// a list of them. 997/// 998/// @return length of the string put into dst, does not include NUL byte. 999size_t home_replace (const buf_T * const buf , const char * src , char * const dst , size_t dstlen , 1000const bool one ) 1001FUNC_ATTR_NONNULL_ARG ( 3 ) 1002{ 1003size_t dirlen = 0 ; 1004size_t envlen = 0 ; 1005 1006if ( src == NULL ) { 1007* dst = NUL ; 1008return 0 ; 1009} 1010 1011if ( buf != NULL && buf -> b_help ) { 1012const size_t dlen = xstrlcpy ( dst , path_tail ( src ), dstlen ); 1013return MIN ( dlen , dstlen - 1 ); 1014} 1015 1016// We check both the value of the $HOME environment variable and the 1017// "real" home directory. 1018if ( homedir != NULL ) { 1019dirlen = strlen ( homedir ); 1020} 1021 1022char * homedir_env = os_getenv ( "HOME" ); 1023#ifdef MSWIN 1024if ( homedir_env == NULL ) { 1025homedir_env = os_getenv ( "USERPROFILE" ); 1026} 1027#endif 1028TO_SLASH ( homedir_env ); 1029char * homedir_env_mod = homedir_env ; 1030bool must_free = false; 1031 1032if ( homedir_env_mod != NULL && * homedir_env_mod == '~' ) { 1033must_free = true; 1034size_t usedlen = 0 ; 1035size_t flen = strlen ( homedir_env_mod ); 1036char * fbuf = NULL ; 1037modify_fname ( ":p" , false, & usedlen , & homedir_env_mod , & fbuf , & flen , false); 1038flen = strlen ( homedir_env_mod ); 1039assert ( homedir_env_mod != homedir_env ); 1040if ( vim_ispathsep ( homedir_env_mod [ flen - 1 ])) { 1041// Remove the trailing / that is added to a directory. 1042homedir_env_mod [ flen - 1 ] = NUL ; 1043} 1044} 1045 1046if ( homedir_env_mod != NULL ) { 1047envlen = strlen ( homedir_env_mod ); 1048} 1049 1050if (! one ) { 1051src = skipwhite ( src ); 1052} 1053char * dst_p = dst ; 1054while ( * src && dstlen > 0 ) { 1055// Here we are at the beginning of a file name. 1056// First, check to see if the beginning of the file name matches 1057// $HOME or the "real" home directory. Check that there is a '/' 1058// after the match (so that if e.g. the file is "/home/pieter/bla", 1059// and the home directory is "/home/piet", the file does not end up 1060// as "~er/bla" (which would seem to indicate the file "bla" in user 1061// er's home directory)). 1062char * p = homedir ; 1063size_t len = dirlen ; 1064while (true) { 1065if ( len 1066&& path_cmp ( p_fic , src , p , len ) == 0 1067&& ( vim_ispathsep ( src [ len ]) 1068|| (! one && ( src [ len ] == ',' || src [ len ] == ' ' )) 1069|| src [ len ] == NUL )) { 1070src += len ; 1071if ( -- dstlen > 0 ) { 1072* dst_p ++ = '~' ; 1073} 1074 1075// Do not add directory separator into dst, because dst is 1076// expected to just return the directory name without the 1077// directory separator '/'. 1078break; 1079} 1080if ( p == homedir_env_mod ) { 1081break; 1082} 1083p = homedir_env_mod ; 1084len = envlen ; 1085} 1086 1087if ( dstlen == 0 ) { 1088break; // Avoid overflowing below. 1089} 1090// if (!one) skip to separator: space or comma. 1091while ( * src && ( one || ( * src != ',' && * src != ' ' )) && -- dstlen > 0 ) { 1092* dst_p ++ = * src ++ ; 1093} 1094if ( dstlen == 0 ) { 1095break; // Avoid overflowing below. 1096} 1097// Skip separator. 1098while (( * src == ' ' || * src == ',' ) && -- dstlen > 0 ) { 1099* dst_p ++ = * src ++ ; 1100} 1101} 1102// If (dstlen == 0) out of space, what to do??? 1103 1104* dst_p = NUL ; 1105 1106xfree ( homedir_env ); 1107 1108if ( must_free ) { 1109xfree ( homedir_env_mod ); 1110} 1111return ( size_t )( dst_p - dst ); 1112} 1113 1114/// Like home_replace, store the replaced string in allocated memory. 1115/// @param buf When not NULL, check for help files 1116/// @param src Input file name 1117char * home_replace_save ( buf_T * buf , const char * src ) 1118FUNC_ATTR_NONNULL_RET 1119{ 1120size_t len = 3 ; // space for "~/" and trailing NUL 1121if ( src != NULL ) { // just in case 1122len += strlen ( src ); 1123} 1124char * dst = xmalloc ( len ); 1125home_replace ( buf , src , dst , len , true); 1126return dst ; 1127} 1128 1129/// Function given to ExpandGeneric() to obtain an environment variable name. 1130char * get_env_name ( expand_T * xp , int idx ) 1131{ 1132assert ( idx >= 0 ); 1133char * envname = os_getenvname_at_index (( size_t ) idx ); 1134if ( envname ) { 1135xstrlcpy ( xp -> xp_buf , envname , EXPAND_BUF_LEN ); 1136xfree ( envname ); 1137return xp -> xp_buf ; 1138} 1139return NULL ; 1140} 1141 1142/// Appends the head of `fname` to $PATH and sets it in the environment. 1143/// 1144/// @param fname Full path whose parent directory will be appended to $PATH. 1145/// 1146/// @return true if `path` was appended-to 1147bool os_setenv_append_path (const char * fname ) 1148FUNC_ATTR_NONNULL_ALL 1149{ 1150#ifdef MSWIN 1151// 8191 (plus NUL) is considered the practical maximum. 1152# define MAX_ENVPATHLEN 8192 1153#else 1154// No prescribed maximum on unix. 1155# define MAX_ENVPATHLEN INT_MAX 1156#endif 1157if (! path_is_absolute ( fname )) { 1158internal_error ( "os_setenv_append_path()" ); 1159return false; 1160} 1161const char * tail = path_tail_with_sep (( char * ) fname ); 1162size_t dirlen = ( size_t )( tail - fname ); 1163assert ( tail >= fname && dirlen + 1 < sizeof( os_buf )); 1164xmemcpyz ( os_buf , fname , dirlen ); 1165char * path = os_getenv ( "PATH" ); 1166const size_t pathlen = path ? strlen ( path ) : 0 ; 1167const size_t newlen = pathlen + dirlen + 2 ; 1168bool retval = false; 1169if ( newlen < MAX_ENVPATHLEN ) { 1170char * temp = xmalloc ( newlen ); 1171if ( pathlen == 0 ) { 1172temp [ 0 ] = NUL ; 1173} else { 1174xstrlcpy ( temp , path , newlen ); 1175if ( ENV_SEPCHAR != path [ pathlen - 1 ]) { 1176xstrlcat ( temp , ENV_SEPSTR , newlen ); 1177} 1178} 1179xstrlcat ( temp , os_buf , newlen ); 1180os_setenv ( "PATH" , temp , 1 ); 1181xfree ( temp ); 1182retval = true; 1183} 1184xfree ( path ); 1185return retval ; 1186} 1187 1188/// Returns true if `sh` looks like it resolves to "cmd.exe". 1189bool os_shell_is_cmdexe (const char * sh ) 1190FUNC_ATTR_NONNULL_ALL 1191{ 1192if ( * sh == NUL ) { 1193return false; 1194} 1195if ( striequal ( sh , "$COMSPEC" )) { 1196char * comspec = os_getenv_noalloc ( "COMSPEC" ); 1197return striequal ( "cmd.exe" , path_tail ( comspec )); 1198} 1199if ( striequal ( sh , "cmd.exe" ) || striequal ( sh , "cmd" )) { 1200return true; 1201} 1202return striequal ( "cmd.exe" , path_tail ( sh )); 1203} 1204 1205/// Removes environment variable "name" and take care of side effects. 1206void vim_unsetenv_ext (const char * var ) 1207{ 1208os_unsetenv ( var ); 1209 1210// "homedir" is not cleared, keep using the old value until $HOME is set. 1211if ( STRICMP ( var , "VIM" ) == 0 ) { 1212didset_vim = false; 1213} else if ( STRICMP ( var , "VIMRUNTIME" ) == 0 ) { 1214didset_vimruntime = false; 1215} 1216} 1217 1218/// Set environment variable "name" and take care of side effects. 1219void vim_setenv_ext (const char * name , const char * val ) 1220{ 1221os_setenv ( name , val , 1 ); 1222if ( STRICMP ( name , "HOME" ) == 0 ) { 1223init_homedir (); 1224} else if ( didset_vim && STRICMP ( name , "VIM" ) == 0 ) { 1225didset_vim = false; 1226} else if ( didset_vimruntime && STRICMP ( name , "VIMRUNTIME" ) == 0 ) { 1227didset_vimruntime = false; 1228} 1229} 1230 1231#ifdef MSWIN 1232/// Restore a previous environment variable value, or unset it if NULL. 1233/// "must_free" indicates whether "old_value" was allocated. 1234void restore_env_var (const char * name , char * old_value , bool must_free ) 1235{ 1236if ( old_value != NULL ) { 1237os_setenv ( name , old_value , true); 1238if ( must_free ) { 1239xfree ( old_value ); 1240} 1241return; 1242} 1243os_unsetenv ( name ); 1244} 1245#endif