From c8e27b6f334931d5a609af6b50c9e0756e88b672 Mon Sep 17 00:00:00 2001 From: Andreas Schneider Date: Fri, 2 Nov 2018 18:04:28 +0100 Subject: [PATCH] lib:replace: Add getprogname() Signed-off-by: Andreas Schneider Reviewed-by: Jeremy Allison --- lib/replace/replace.c | 71 +++++++++++++++++++++++++++++++++++++++++++ lib/replace/replace.h | 5 +++ lib/replace/wscript | 1 + 3 files changed, 77 insertions(+) diff --git a/lib/replace/replace.c b/lib/replace/replace.c index 113137c2992..e38df98ea3a 100644 --- a/lib/replace/replace.c +++ b/lib/replace/replace.c @@ -978,3 +978,74 @@ int rep_memset_s(void *dest, size_t destsz, int ch, size_t count) return 0; } #endif /* HAVE_MEMSET_S */ + +#ifndef HAVE_GETPROGNAME +# ifndef _GNU_SOURCE +# define PROGNAME_SIZE 32 +static char rep_progname[PROGNAME_SIZE]; +# endif /* _GNU_SOURCE */ + +const char *rep_getprogname(void) +{ +#ifdef _GNU_SOURCE + return program_invocation_short_name; +#else /* _GNU_SOURCE */ + FILE *fp = NULL; + char cmdline[4096] = {0}; + char *p = NULL; + pid_t pid; + size_t nread; + int len; + + if (rep_progname[0] != '\0') { + return rep_progname; + } + + len = snprintf(rep_progname, sizeof(rep_progname), "%s", ""); + if (len <= 0) { + return ""; + } + + pid = getpid(); + if (pid <= 1 || pid == (pid_t)-1) { + return rep_progname; + } + + len = snprintf(cmdline, + sizeof(cmdline), + "/proc/%u/cmdline", + (unsigned int)pid); + if (len <= 0 || len == sizeof(cmdline)) { + return rep_progname; + } + + fp = fopen(cmdline, "r"); + if (fp == NULL) { + return rep_progname; + } + + nread = fread(cmdline, 1, sizeof(cmdline) - 1, fp); + if (nread == 0) { + return rep_progname; + } + + cmdline[nread] = '\0'; + + p = strrchr(cmdline, '/'); + if (p != NULL) { + p++; + } else { + p = cmdline; + } + + len = strlen(p); + if (len > PROGNAME_SIZE) { + p[PROGNAME_SIZE - 1] = '\0'; + } + + (void)snprintf(rep_progname, sizeof(rep_progname), "%s", p); + + return rep_progname; +#endif /* _GNU_SOURCE */ +} +#endif /* HAVE_GETPROGNAME */ diff --git a/lib/replace/replace.h b/lib/replace/replace.h index de4e20c4454..732a8226858 100644 --- a/lib/replace/replace.h +++ b/lib/replace/replace.h @@ -933,6 +933,11 @@ void rep_setproctitle_init(int argc, char *argv[], char *envp[]); int rep_memset_s(void *dest, size_t destsz, int ch, size_t count); #endif +#ifndef HAVE_GETPROGNAME +#define getprogname rep_getprogname +const char *rep_getprogname(void); +#endif + #ifndef FALL_THROUGH # ifdef HAVE_FALLTHROUGH_ATTRIBUTE # define FALL_THROUGH __attribute__ ((fallthrough)) diff --git a/lib/replace/wscript b/lib/replace/wscript index 8adfffe9584..c8693a3f2e1 100644 --- a/lib/replace/wscript +++ b/lib/replace/wscript @@ -426,6 +426,7 @@ def configure(conf): conf.CHECK_FUNCS('getgrent_r getgrgid_r getgrnam_r getgrouplist getpagesize') conf.CHECK_FUNCS('getpwent_r getpwnam_r getpwuid_r epoll_create') conf.CHECK_FUNCS('port_create') + conf.CHECK_FUNCS('getprogname') conf.SET_TARGET_TYPE('attr', 'EMPTY') -- 2.34.1