1 /* Perform tilde expansion on paths for GDB and gdbserver.
3 Copyright (C) 2017-2022 Free Software Foundation, Inc.
5 This file is part of GDB.
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3 of the License, or
10 (at your option) any later version.
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program. If not, see <http://www.gnu.org/licenses/>. */
20 #include "common-defs.h"
22 #include "filenames.h"
23 #include "gdb_tilde_expand.h"
26 /* RAII-style class wrapping "glob". */
31 /* Construct a "gdb_glob" object by calling "glob" with the provided
32 parameters. This function can throw if "glob" fails. */
33 gdb_glob (const char *pattern
, int flags
,
34 int (*errfunc
) (const char *epath
, int eerrno
))
36 int ret
= glob (pattern
, flags
, errfunc
, &m_glob
);
40 if (ret
== GLOB_NOMATCH
)
41 error (_("Could not find a match for '%s'."), pattern
);
43 error (_("glob could not process pattern '%s'."),
48 /* Destroy the object and free M_GLOB. */
54 /* Return the GL_PATHC component of M_GLOB. */
57 return m_glob
.gl_pathc
;
60 /* Return the GL_PATHV component of M_GLOB. */
63 return m_glob
.gl_pathv
;
67 /* The actual glob object we're dealing with. */
71 /* See gdbsupport/gdb_tilde_expand.h. */
74 gdb_tilde_expand (const char *dir
)
77 return std::string (dir
);
79 /* This function uses glob in order to expand the ~. However, this function
80 will fail to expand if the actual dir we are looking for does not exist.
81 Given "~/does/not/exist", glob will fail.
83 In order to avoid such limitation, we only use glob to expand "~" and keep
84 "/does/not/exist" unchanged.
86 Similarly, to expand ~gdb/might/not/exist, we only expand "~gdb" using
87 glob and leave "/might/not/exist" unchanged. */
88 const std::string
d (dir
);
90 /* Look for the first dir separator (if any) and split d around it. */
92 = std::find_if (d
.cbegin (), d
.cend(),
93 [] (const char c
) -> bool
95 return IS_DIR_SEPARATOR (c
);
97 const std::string
to_expand (d
.cbegin (), first_sep
);
98 const std::string
remainder (first_sep
, d
.cend ());
100 const gdb_glob
glob (to_expand
.c_str (), GLOB_TILDE_CHECK
, nullptr);
102 gdb_assert (glob
.pathc () == 1);
103 return std::string (glob
.pathv ()[0]) + remainder
;