Skip to content

Commit 0210381

Browse files
MichaelRabekigaw
authored andcommitted
lib: save one strdup by using GNU basename() implementation
POSIX states that basename(3) may modify its input string. For this reason, strdup(3) is used in__nvme_transport_handle_open_direct() so that it is safe to call basename(3) on a const char*. This patch introduces an nvme_basename() function that is guaranteed to never modify its input and is thus safe to be used on string literals. It is a copy of basename(3) implementation from glibc. This change allows us to avoid one needless dynamic allocation. Signed-off-by: Michal Rábek <[email protected]>
1 parent 69347e1 commit 0210381

3 files changed

Lines changed: 17 additions & 5 deletions

File tree

libnvme/src/nvme/lib.c

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -125,15 +125,11 @@ static int __nvme_transport_handle_open_direct(
125125
{
126126
struct nvme_passthru_cmd dummy = { 0 };
127127
_cleanup_free_ char *path = NULL;
128-
_cleanup_free_ char *_devname = NULL;
129128
char *name;
130129
int ret, id, ns;
131130
bool c = true;
132131

133-
_devname = strdup(devname);
134-
if (!_devname)
135-
return -ENOMEM;
136-
name = basename(_devname);
132+
name = nvme_basename(devname);
137133

138134
hdl->type = NVME_TRANSPORT_HANDLE_TYPE_DIRECT;
139135

libnvme/src/nvme/util.c

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -981,3 +981,12 @@ const struct ifaddrs *nvme_getifaddrs(struct nvme_global_ctx *ctx)
981981

982982
return ctx->ifaddrs_cache;
983983
}
984+
985+
/* This used instead of basename() due to behavioral differences between
986+
* the POSIX and the GNU version. This is the glibc implementation.
987+
* Original source: https://github.com/bminor/glibc/blob/master/string/basename.c */
988+
char *nvme_basename(const char *path)
989+
{
990+
char *p = (char *) strrchr(path, '/');
991+
return p ? p + 1 : (char *) path;
992+
}

libnvme/src/nvme/util.h

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -218,3 +218,10 @@ int nvme_uuid_random(unsigned char uuid[NVME_UUID_LEN]);
218218
*/
219219
int nvme_uuid_find(struct nvme_id_uuid_list *uuid_list, const unsigned char uuid[NVME_UUID_LEN]);
220220

221+
/**
222+
* nvme_basename - Return the final path component (the one after the last '/')
223+
* @path: A string containing a filesystem path
224+
*
225+
* Return: A pointer into the original null-terminated path string.
226+
*/
227+
char *nvme_basename(const char *path);

0 commit comments

Comments
 (0)