robin/laufey

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

taorefactor(path): pathcmp() #41035f0a0182285

master
34.9 KiB1245 linesraw
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{
62  nvim_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)
70  FUNC_ATTR_NONNULL_ALL
71{
72  char *e = NULL;
73  if (name[0] == NUL) {
74    return NULL;
75  }
76  int r = 0;
77#define INIT_SIZE 64
78  size_t size = INIT_SIZE;
79  char buf[INIT_SIZE];
80  r = uv_os_getenv(name, buf, &size);
81  if (r == UV_ENOBUFS) {
82    e = xmalloc(size);
83    r = uv_os_getenv(name, e, &size);
84    if (r != 0 || size == 0 || e[0] == NUL) {
85      XFREE_CLEAR(e);
86      goto end;
87    }
88  } else if (r != 0 || size == 0 || buf[0] == NUL) {
89    e = NULL;
90    goto end;
91  } else {
92    // NB: `size` param of uv_os_getenv() includes the NUL-terminator,
93    // except when it does not include the NUL-terminator.
94    e = xmemdupz(buf, size);
95  }
96end:
97  if (r != 0 && r != UV_ENOENT && r != UV_UNKNOWN) {
98    ELOG("uv_os_getenv(%s) failed: %d %s", name, r, uv_err_name(r));
99  }
100  return 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)
110  FUNC_ATTR_NONNULL_ALL
111{
112  if (name[0] == NUL) {
113    return NULL;
114  }
115
116  size_t size = bufsize;
117  int r = uv_os_getenv(name, buf, &size);
118  if (r == UV_ENOBUFS) {
119    char *e = xmalloc(size);
120    r = uv_os_getenv(name, e, &size);
121    if (r == 0 && size != 0 && e[0] != NUL) {
122      xmemcpyz(buf, e, MIN(bufsize, size) - 1);
123    }
124    xfree(e);
125  }
126
127  if (r != 0 || size == 0 || buf[0] == NUL) {
128    if (r != 0 && r != UV_ENOENT && r != UV_UNKNOWN) {
129      ELOG("uv_os_getenv(%s) failed: %d %s", name, r, uv_err_name(r));
130    }
131    return NULL;
132  }
133  return 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)
143  FUNC_ATTR_NONNULL_ALL
144{
145  return 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)
155  FUNC_ATTR_NONNULL_ALL
156{
157  if (name[0] == NUL) {
158    return 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.
162  char buf[2];
163  size_t size = sizeof(buf);
164  int r = uv_os_getenv(name, buf, &size);
165  assert(r != UV_EINVAL);
166  if (r != 0 && r != UV_ENOENT && r != UV_ENOBUFS) {
167    ELOG("uv_os_getenv(%s) failed: %d %s", name, r, uv_err_name(r));
168  }
169  return ((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)
176  FUNC_ATTR_NONNULL_ALL
177{
178  if (name[0] == NUL) {
179    return -1;
180  }
181#ifdef MSWIN
182  if (!overwrite && !os_env_exists(name, true)) {
183    return 0;
184  }
185  if (value[0] == NUL) {
186    // Windows (Vim-compat): Empty string undefines the env var.
187    return os_unsetenv(name);
188  }
189#else
190  if (!overwrite && os_env_exists(name, false)) {
191    return 0;
192  }
193#endif
194  int r;
195#ifdef MSWIN
196  // Call _putenv_s() so libintl can see LC_ALL/LANG/etc. libuv only calls SetEnvironmentVariableW.
197  if (striequal(name, "LC_ALL") || striequal(name, "LANGUAGE")
198      || striequal(name, "LANG") || striequal(name, "LC_MESSAGES")) {
199    r = _putenv_s(name, value);  // NOLINT
200    assert(r == 0);
201  }
202#endif
203  r = uv_os_setenv(name, value);
204  assert(r != UV_EINVAL);
205  if (r != 0) {
206    ELOG("uv_os_setenv(%s) failed: %d %s", name, r, uv_err_name(r));
207  }
208  return r == 0 ? 0 : -1;
209}
210
211/// Unset environment variable
212int os_unsetenv(const char *name)
213  FUNC_ATTR_NONNULL_ALL
214{
215  if (name[0] == NUL) {
216    return -1;
217  }
218  int r = uv_os_unsetenv(name);
219  if (r != 0) {
220    ELOG("uv_os_unsetenv(%s) failed: %d %s", name, r, uv_err_name(r));
221  }
222  return r == 0 ? 0 : -1;
223}
224
225void os_free_fullenv(char **env)
226{
227  if (!env) {
228    return;
229  }
230  for (char **it = env; *it; it++) {
231    XFREE_CLEAR(*it);
232  }
233  xfree(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
245  wchar_t *envstrings = GetEnvironmentStringsW();
246  if (!envstrings) {
247    return NULL;
248  }
249  wchar_t *p = envstrings;
250  char *name = NULL;
251  size_t i = 0;
252  size_t l;
253  // GetEnvironmentStringsW() result has this format:
254  //    var1=value1\0var2=value2\0...varN=valueN\0\0
255  while ((l = wcslen(p)) != 0 && i <= index) {
256    if (i == index) {
257      char *utf8_str;
258      int conversion_result = utf16_to_utf8(p, -1, &utf8_str);
259      if (conversion_result != 0) {
260        semsg("utf16_to_utf8 failed: %d", conversion_result);
261        break;
262      }
263
264      // Some Windows env vars start with =, so skip over that to find the
265      // separator between name/value
266      const char *const end = strchr(utf8_str + (utf8_str[0] == '=' ? 1 : 0), '=');
267      assert(end != NULL);
268      ptrdiff_t len = end - utf8_str;
269      assert(len > 0);
270      name = xmemdupz(utf8_str, (size_t)len);
271      xfree(utf8_str);
272      break;
273    }
274
275    // Advance past the name and NUL
276    p += l + 1;
277    i++;
278  }
279
280  FreeEnvironmentStringsW(envstrings);
281  return name;
282#else
283# ifdef HAVE__NSGETENVIRON
284  char **environ = *_NSGetEnviron();
285# else
286  extern char **environ;
287# endif
288
289  // check if index is inside the environ array
290  for (size_t i = 0; i <= index; i++) {
291    if (environ[i] == NULL) {
292      return NULL;
293    }
294  }
295  char *str = environ[index];
296  assert(str != NULL);
297  const char * const end = strchr(str, '=');
298  assert(end != NULL);
299  ptrdiff_t len = end - str;
300  assert(len > 0);
301  return 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
311  return (int64_t)GetCurrentProcessId();
312#else
313  return (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.
324  integer_t policy = TASK_DEFAULT_APPLICATION;
325  task_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
336  struct utsname vutsname;
337
338  if (uname(&vutsname) < 0) {
339    *hostname = NUL;
340  } else {
341    xstrlcpy(hostname, vutsname.nodename, size);
342  }
343#elif defined(MSWIN)
344  wchar_t host_utf16[MAX_COMPUTERNAME_LENGTH + 1];
345  DWORD host_wsize = sizeof(host_utf16) / sizeof(host_utf16[0]);
346  if (GetComputerNameW(host_utf16, &host_wsize) == 0) {
347    *hostname = NUL;
348    DWORD err = GetLastError();
349    semsg("GetComputerNameW failed: %d", err);
350    return;
351  }
352  host_utf16[host_wsize] = NUL;
353
354  char *host_utf8;
355  int conversion_result = utf16_to_utf8(host_utf16, -1, &host_utf8);
356  if (conversion_result != 0) {
357    semsg("utf16_to_utf8 failed: %d", conversion_result);
358    return;
359  }
360  xstrlcpy(hostname, host_utf8, size);
361  xfree(host_utf8);
362#else
363  emsg("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{
375  if (!homedir) {
376    emsg("os_homedir failed: homedir not initialized");
377    return NULL;
378  }
379  return 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.
399  xfree(homedir);
400  homedir = NULL;
401
402  char *var = os_getenv("HOME");
403  char *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.
410  if (var == NULL) {
411    char *homedrive = os_getenv("HOMEDRIVE");
412    char *homepath = os_getenv("HOMEPATH");
413    if (homepath == NULL) {
414      homepath = xstrdup(PATHSEPSTR);
415    }
416    if (homedrive != NULL
417        && strlen(homedrive) + strlen(homepath) < MAXPATHL) {
418      snprintf(os_buf, MAXPATHL, "%s%s", homedrive, homepath);
419      if (os_buf[0] != NUL) {
420        var = os_buf;
421      }
422    }
423    xfree(homepath);
424    xfree(homedrive);
425  }
426  if (var == NULL) {
427    var = 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.
433  if (var != NULL && *var == '%') {
434    const char *p = strchr(var + 1, '%');
435    if (p != NULL) {
436      vim_snprintf(os_buf, (size_t)(p - var), "%s", var + 1);
437      var = NULL;
438      char *exp = os_getenv(os_buf);
439      if (exp != NULL) {
440        if (*exp != NUL && strlen(exp) + strlen(p) < MAXPATHL) {
441          vim_snprintf(os_buf, MAXPATHL, "%s%s", exp, p + 1);
442          var = os_buf;
443        }
444        xfree(exp);
445      }
446    }
447  }
448
449  // Default home dir is C:/
450  // Best assumption we can make in such a situation.
451  if (var == NULL
452      // Empty means "undefined"
453      || *var == NUL) {
454    var = "C:/";
455  }
456#endif
457
458#ifdef UNIX
459  if (var == NULL) {
460    var = os_uv_homedir();
461  }
462
463  // Get the actual path.  This resolves links.
464  if (var != NULL && os_realpath(var, IObuff, IOSIZE) != NULL) {
465    var = IObuff;
466  }
467
468  // Fall back to current working directory if home is not found
469  if ((var == NULL || *var == NUL)
470      && os_dirname(os_buf, sizeof(os_buf)) == OK) {
471    var = os_buf;
472  }
473#endif
474  if (var != NULL) {
475    homedir = TO_SLASH_SAVE(var);
476  }
477  xfree(tofree);
478}
479
480static char homedir_buf[MAXPATHL];
481
482static char *os_uv_homedir(void)
483{
484  homedir_buf[0] = NUL;
485  size_t homedir_size = MAXPATHL;
486  // http://docs.libuv.org/en/v1.x/misc.html#c.uv_os_homedir
487  int ret_value = uv_os_homedir(homedir_buf, &homedir_size);
488  if (ret_value == 0 && homedir_size < MAXPATHL) {
489    return homedir_buf;
490  }
491  ELOG("uv_os_homedir() failed %d: %s", ret_value, os_strerror(ret_value));
492  homedir_buf[0] = NUL;
493  return NULL;
494}
495
496#ifdef EXITFREE
497
498void free_homedir(void)
499{
500  xfree(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{
512  return 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{
523  char *p = xmalloc(MAXPATHL);
524  expand_env_esc(src, p, MAXPATHL, esc_chars, one, NULL);
525  return 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{
538  return 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 *restrict srcp, char *restrict dst, int dstlen, char *esc_chars,
551                      bool one, char *prefix)
552  FUNC_ATTR_NONNULL_ARG(1, 2)
553{
554  char *tail;
555  char *var;
556  bool copy_char;
557  bool mustfree;  // var was allocated, need to free it later
558  bool at_start = true;  // at start of a name
559  char *const dst_start = dst;
560
561  int prefix_len = (prefix == NULL) ? 0 : (int)strlen(prefix);
562
563  char *src = skipwhite(srcp);
564  dstlen--;  // leave one char space for "\,"
565  while (*src && dstlen > 0) {
566    // Skip over `=expr`.
567    if (src[0] == '`' && src[1] == '=') {
568      var = src;
569      src += 2;
570      skip_expr(&src, NULL);
571      if (*src == '`') {
572        src++;
573      }
574      size_t len = (size_t)(src - var);
575      if (len > (size_t)dstlen) {
576        len = (size_t)dstlen;
577      }
578      memcpy(dst, var, len);
579      dst += len;
580      dstlen -= (int)len;
581      continue;
582    }
583
584    copy_char = true;
585    if ((*src == '$') || (*src == '~' && at_start)) {
586      mustfree = 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.
590      if (*src != '~') {  // environment var
591        tail = src + 1;
592        var = dst;
593        int c = dstlen - 1;
594
595#ifdef UNIX
596        // Unix has ${var-name} type environment vars
597        if (*tail == '{' && !vim_isIDc('{')) {
598          tail++;               // ignore '{'
599          while (c-- > 0 && *tail != NUL && *tail != '}') {
600            *var++ = *tail++;
601          }
602        } else
603#endif
604        {
605          while (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
612        if (src[1] == '{' && *tail != '}') {
613          var = NULL;
614        } else {
615          if (src[1] == '{') {
616            tail++;
617          }
618#endif
619        *var = NUL;
620        var = 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.
624        TO_SLASH(var);
625        mustfree = 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) {
632        var = homedir;
633        tail = src + 1;
634      } else {  // user directory
635#ifdef UNIX
636        // Copy ~user to dst[], so we can put a NUL after it.
637        tail = src;
638        var = dst;
639        int c = dstlen - 1;
640        while (c-- > 0
641               && *tail
642               && vim_isfilec((uint8_t)(*tail))
643               && !vim_ispathsep(*tail)) {
644          *var++ = *tail++;
645        }
646        *var = NUL;
647        var = (*dst == NUL) ? NULL
648                            : os_get_userdir(dst + 1);
649        mustfree = true;
650#else
651        // cannot expand user's home directory, so don't try
652        var = NULL;
653        tail = "";  // 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.
660      if (esc_chars != NULL && var != NULL && strpbrk(var, esc_chars) != NULL) {
661        char *p = vim_strsave_escaped(var, esc_chars);
662
663        if (mustfree) {
664          xfree(var);
665        }
666        var = p;
667        mustfree = true;
668      }
669
670      if (var != NULL && *var != NUL) {
671        int c = (int)strlen(var);
672        if ((size_t)c + strlen(tail) + 1 < (unsigned)dstlen) {
673          STRCPY(dst, var);
674          dstlen -= c;
675          // if var[] ends in a path separator and tail[] starts
676          // with it, skip a character
677          if (after_pathsep(dst, dst + c)
678#ifdef BACKSLASH_IN_FILENAME
679              && dst[c - 1] != ':'
680#endif
681              && vim_ispathsep(*tail)) {
682            tail++;
683          }
684          dst += c;
685          src = tail;
686          copy_char = false;
687        }
688      }
689      if (mustfree) {
690        xfree(var);
691      }
692    }
693
694    if (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".
698      at_start = false;
699      if (src[0] == '\\' && src[1] != NUL) {
700        *dst++ = *src++;
701        dstlen--;
702      } else if ((src[0] == ' ' || src[0] == ',') && !one) {
703        at_start = true;
704      }
705      if (dstlen > 0) {
706        *dst++ = *src++;
707        dstlen--;
708
709        if (prefix != NULL
710            && src - prefix_len >= srcp
711            && strncmp(src - prefix_len, prefix, (size_t)prefix_len) == 0) {
712          at_start = true;
713        }
714      }
715    }
716  }
717  *dst = NUL;
718
719  return (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{
727  if (vimdir == NULL || *vimdir == NUL) {
728    return NULL;
729  }
730  size_t vimdir_len = strlen(vimdir);
731  String p = concat_fnames(cbuf_as_string((char *)vimdir, vimdir_len),
732                           STATIC_CSTR_AS_STRING(RUNTIME_DIRNAME), true);
733  if (os_isdir(p.data)) {
734    return p.data;
735  }
736  xfree(p.data);
737  return 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{
763  size_t len = strlen(dirname);
764  char *new_tail = pend - len - 1;
765
766  if (new_tail >= path
767      && path_cmp(p_fic, new_tail, dirname, len) == 0
768      && (new_tail == path || after_pathsep(path, new_tail))) {
769    return new_tail;
770  }
771  return 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,
788                         const char **const dir, size_t *const len)
789  FUNC_ATTR_NONNULL_ARG(2, 4, 5) FUNC_ATTR_WARN_UNUSED_RESULT
790{
791  const char *varval = iter;
792  if (varval == NULL) {
793    varval = val;
794  }
795  *dir = varval;
796  const char *const dirend = strchr(varval, delim);
797  if (dirend == NULL) {
798    *len = strlen(varval);
799    return NULL;
800  }
801  *len = (size_t)(dirend - varval);
802  return 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,
819                             const char **const dir, size_t *const len)
820  FUNC_ATTR_NONNULL_ARG(2, 4, 5) FUNC_ATTR_WARN_UNUSED_RESULT
821{
822  const char *varend = iter;
823  if (varend == NULL) {
824    varend = val + strlen(val) - 1;
825  }
826  const size_t varlen = (size_t)(varend - val) + 1;
827  const char *const colon = xmemrchr(val, (uint8_t)delim, varlen);
828  if (colon == NULL) {
829    *len = varlen;
830    *dir = val;
831    return NULL;
832  }
833  *dir = colon + 1;
834  *len = (size_t)(varend - colon);
835  return 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).
843  xstrlcpy(exe_name, get_vim_var_str(VV_PROGPATH), MAXPATHL * sizeof(*exe_name));
844  char *path_end = path_tail_with_sep(exe_name);
845  *path_end = NUL;  // remove the trailing "nvim.exe"
846  path_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.
859  assert(get_vim_var_str(VV_PROGPATH)[0] != NUL);
860
861#ifdef MSWIN
862  if (strcmp(name, "HOME") == 0) {
863    return xstrdup(homedir);
864  }
865#endif
866
867  char *kos_env_path = os_getenv(name);
868#ifdef BACKSLASH_IN_FILENAME
869  if (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")) {
877    TO_SLASH(kos_env_path);
878  }
879#endif
880  if (kos_env_path != NULL) {
881    return kos_env_path;
882  }
883
884  bool vimruntime = (strcmp(name, "VIMRUNTIME") == 0);
885  if (!vimruntime && strcmp(name, "VIM") != 0) {
886    return 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.
891  char *vim_path = NULL;
892  if (vimruntime
893      && *default_vimruntime_dir == NUL) {
894    kos_env_path = os_getenv("VIM");    // kos_env_path was NULL.
895    if (kos_env_path != NULL) {
896      vim_path = vim_runtime_dir(kos_env_path);
897      if (vim_path == NULL) {
898        vim_path = kos_env_path;
899      } else {
900        xfree(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]
908  if (vim_path == NULL) {
909    if (p_hf != NULL && vim_strchr(p_hf, '$') == NULL) {
910      vim_path = p_hf;
911    }
912
913    char exe_name[MAXPATHL];
914    // Find runtime path relative to the nvim binary: ../share/nvim/runtime
915    if (vim_path == NULL) {
916      vim_get_prefix_from_exepath(exe_name);
917      if (append_path(exe_name, "share/nvim/runtime/", MAXPATHL) == OK) {
918        vim_path = exe_name;
919      }
920    }
921
922    if (vim_path != NULL) {
923      // remove the file name
924      char *vim_path_end = path_tail(vim_path);
925
926      // remove "doc/" from 'helpfile', if present
927      if (vim_path == p_hf) {
928        vim_path_end = remove_tail(vim_path, vim_path_end, "doc");
929      }
930
931      // for $VIM, remove "runtime/", if present
932      if (!vimruntime) {
933        vim_path_end = remove_tail(vim_path, vim_path_end, RUNTIME_DIRNAME);
934      }
935
936      // remove trailing path separator
937      if (vim_path_end > vim_path && after_pathsep(vim_path, vim_path_end)) {
938        vim_path_end--;
939      }
940
941      // check that the result is a directory name
942      assert(vim_path_end >= vim_path);
943      vim_path = xmemdupz(vim_path, (size_t)(vim_path_end - vim_path));
944
945      if (!os_isdir(vim_path)) {
946        xfree(vim_path);
947        vim_path = NULL;
948      }
949    }
950    assert(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
955  if (vim_path == NULL) {
956    // Only use default_vimruntime_dir when it is not empty
957    if (vimruntime && *default_vimruntime_dir != NUL) {
958      vim_path = xstrdup(default_vimruntime_dir);
959    } else if (*default_vim_dir != NUL) {
960      if (vimruntime
961          && (vim_path = vim_runtime_dir(default_vim_dir)) == NULL) {
962        vim_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).
969  if (vim_path != NULL) {
970    if (vimruntime) {
971      os_setenv("VIMRUNTIME", vim_path, 1);
972      didset_vimruntime = true;
973    } else {
974      os_setenv("VIM", vim_path, 1);
975      didset_vim = true;
976    }
977  }
978  return 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,
1000                    const bool one)
1001  FUNC_ATTR_NONNULL_ARG(3)
1002{
1003  size_t dirlen = 0;
1004  size_t envlen = 0;
1005
1006  if (src == NULL) {
1007    *dst = NUL;
1008    return 0;
1009  }
1010
1011  if (buf != NULL && buf->b_help) {
1012    const size_t dlen = xstrlcpy(dst, path_tail(src), dstlen);
1013    return MIN(dlen, dstlen - 1);
1014  }
1015
1016  // We check both the value of the $HOME environment variable and the
1017  // "real" home directory.
1018  if (homedir != NULL) {
1019    dirlen = strlen(homedir);
1020  }
1021
1022  char *homedir_env = os_getenv("HOME");
1023#ifdef MSWIN
1024  if (homedir_env == NULL) {
1025    homedir_env = os_getenv("USERPROFILE");
1026  }
1027#endif
1028  TO_SLASH(homedir_env);
1029  char *homedir_env_mod = homedir_env;
1030  bool must_free = false;
1031
1032  if (homedir_env_mod != NULL && *homedir_env_mod == '~') {
1033    must_free = true;
1034    size_t usedlen = 0;
1035    size_t flen = strlen(homedir_env_mod);
1036    char *fbuf = NULL;
1037    modify_fname(":p", false, &usedlen, &homedir_env_mod, &fbuf, &flen, false);
1038    flen = strlen(homedir_env_mod);
1039    assert(homedir_env_mod != homedir_env);
1040    if (vim_ispathsep(homedir_env_mod[flen - 1])) {
1041      // Remove the trailing / that is added to a directory.
1042      homedir_env_mod[flen - 1] = NUL;
1043    }
1044  }
1045
1046  if (homedir_env_mod != NULL) {
1047    envlen = strlen(homedir_env_mod);
1048  }
1049
1050  if (!one) {
1051    src = skipwhite(src);
1052  }
1053  char *dst_p = dst;
1054  while (*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)).
1062    char *p = homedir;
1063    size_t len = dirlen;
1064    while (true) {
1065      if (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)) {
1070        src += len;
1071        if (--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 '/'.
1078        break;
1079      }
1080      if (p == homedir_env_mod) {
1081        break;
1082      }
1083      p = homedir_env_mod;
1084      len = envlen;
1085    }
1086
1087    if (dstlen == 0) {
1088      break;  // Avoid overflowing below.
1089    }
1090    // if (!one) skip to separator: space or comma.
1091    while (*src && (one || (*src != ',' && *src != ' ')) && --dstlen > 0) {
1092      *dst_p++ = *src++;
1093    }
1094    if (dstlen == 0) {
1095      break;  // Avoid overflowing below.
1096    }
1097    // Skip separator.
1098    while ((*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
1106  xfree(homedir_env);
1107
1108  if (must_free) {
1109    xfree(homedir_env_mod);
1110  }
1111  return (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)
1118  FUNC_ATTR_NONNULL_RET
1119{
1120  size_t len = 3;             // space for "~/" and trailing NUL
1121  if (src != NULL) {          // just in case
1122    len += strlen(src);
1123  }
1124  char *dst = xmalloc(len);
1125  home_replace(buf, src, dst, len, true);
1126  return dst;
1127}
1128
1129/// Function given to ExpandGeneric() to obtain an environment variable name.
1130char *get_env_name(expand_T *xp, int idx)
1131{
1132  assert(idx >= 0);
1133  char *envname = os_getenvname_at_index((size_t)idx);
1134  if (envname) {
1135    xstrlcpy(xp->xp_buf, envname, EXPAND_BUF_LEN);
1136    xfree(envname);
1137    return xp->xp_buf;
1138  }
1139  return 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)
1148  FUNC_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
1157  if (!path_is_absolute(fname)) {
1158    internal_error("os_setenv_append_path()");
1159    return false;
1160  }
1161  const char *tail = path_tail_with_sep((char *)fname);
1162  size_t dirlen = (size_t)(tail - fname);
1163  assert(tail >= fname && dirlen + 1 < sizeof(os_buf));
1164  xmemcpyz(os_buf, fname, dirlen);
1165  char *path = os_getenv("PATH");
1166  const size_t pathlen = path ? strlen(path) : 0;
1167  const size_t newlen = pathlen + dirlen + 2;
1168  bool retval = false;
1169  if (newlen < MAX_ENVPATHLEN) {
1170    char *temp = xmalloc(newlen);
1171    if (pathlen == 0) {
1172      temp[0] = NUL;
1173    } else {
1174      xstrlcpy(temp, path, newlen);
1175      if (ENV_SEPCHAR != path[pathlen - 1]) {
1176        xstrlcat(temp, ENV_SEPSTR, newlen);
1177      }
1178    }
1179    xstrlcat(temp, os_buf, newlen);
1180    os_setenv("PATH", temp, 1);
1181    xfree(temp);
1182    retval = true;
1183  }
1184  xfree(path);
1185  return retval;
1186}
1187
1188/// Returns true if `sh` looks like it resolves to "cmd.exe".
1189bool os_shell_is_cmdexe(const char *sh)
1190  FUNC_ATTR_NONNULL_ALL
1191{
1192  if (*sh == NUL) {
1193    return false;
1194  }
1195  if (striequal(sh, "$COMSPEC")) {
1196    char *comspec = os_getenv_noalloc("COMSPEC");
1197    return striequal("cmd.exe", path_tail(comspec));
1198  }
1199  if (striequal(sh, "cmd.exe") || striequal(sh, "cmd")) {
1200    return true;
1201  }
1202  return 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{
1208  os_unsetenv(var);
1209
1210  // "homedir" is not cleared, keep using the old value until $HOME is set.
1211  if (STRICMP(var, "VIM") == 0) {
1212    didset_vim = false;
1213  } else if (STRICMP(var, "VIMRUNTIME") == 0) {
1214    didset_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{
1221  os_setenv(name, val, 1);
1222  if (STRICMP(name, "HOME") == 0) {
1223    init_homedir();
1224  } else if (didset_vim && STRICMP(name, "VIM") == 0) {
1225    didset_vim = false;
1226  } else if (didset_vimruntime && STRICMP(name, "VIMRUNTIME") == 0) {
1227    didset_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{
1236  if (old_value != NULL) {
1237    os_setenv(name, old_value, true);
1238    if (must_free) {
1239      xfree(old_value);
1240    }
1241    return;
1242  }
1243  os_unsetenv(name);
1244}
1245#endif