Re: [bpf-next v2 1/2] libbpf: Add pathname_concat() helper

From: Daniel Borkmann
Date: Fri Sep 16 2022 - 11:54:30 EST


On 9/16/22 9:36 AM, Wang Yufen wrote:
Move snprintf and len check to common helper pathname_concat() to make the
code simpler.

Signed-off-by: Wang Yufen <wangyufen@xxxxxxxxxx>
---
tools/lib/bpf/libbpf.c | 76 +++++++++++++++++++-------------------------------
1 file changed, 29 insertions(+), 47 deletions(-)

diff --git a/tools/lib/bpf/libbpf.c b/tools/lib/bpf/libbpf.c
index 3ad1392..7ab977c 100644
--- a/tools/lib/bpf/libbpf.c
+++ b/tools/lib/bpf/libbpf.c
@@ -2096,19 +2096,30 @@ static bool get_map_field_int(const char *map_name, const struct btf *btf,
return true;
}
+static int pathname_concat(const char *path, const char *name, char *buf)
+{
+ int len;
+
+ len = snprintf(buf, PATH_MAX, "%s/%s", path, name);
+ if (len < 0)
+ return -EINVAL;
+ if (len >= PATH_MAX)
+ return -ENAMETOOLONG;
+
+ return 0;
+}
+
static int build_map_pin_path(struct bpf_map *map, const char *path)
{
char buf[PATH_MAX];
- int len;
+ int err;
if (!path)
path = "/sys/fs/bpf";
- len = snprintf(buf, PATH_MAX, "%s/%s", path, bpf_map__name(map));
- if (len < 0)
- return -EINVAL;
- else if (len >= PATH_MAX)
- return -ENAMETOOLONG;
+ err = pathname_concat(path, bpf_map__name(map), buf);

Small nit, but would be good to not make the assumption that buf is always
PATH_MAX so lets add size_t len to pathname_concat().

+ if (err)
+ return err;
return bpf_map__set_pin_path(map, buf);
}