From 9e0e5e835fea3effa6319ed68e5c84b5fe284ab3 Mon Sep 17 00:00:00 2001 From: =?utf8?q?Jos=C3=A9=20Fonseca?= Date: Mon, 17 Jun 2013 21:05:14 +0100 Subject: [PATCH] os: Ensure len is properly computed on all getProcessName code paths. And that truncate is always called. Thanks to Alexander Monakov for spotting this. --- common/os_posix.cpp | 20 ++++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/common/os_posix.cpp b/common/os_posix.cpp index 7ddd895..9e8580f 100644 --- a/common/os_posix.cpp +++ b/common/os_posix.cpp @@ -71,25 +71,33 @@ getProcessName(void) #ifdef __APPLE__ uint32_t len = size; if (_NSGetExecutablePath(buf, &len) != 0) { - *buf = 0; - return path; + // grow buf and retry + buf = path.buf(len); + _NSGetExecutablePath(buf, &len); } len = strlen(buf); #else ssize_t len; len = readlink("/proc/self/exe", buf, size - 1); - if (len == -1) { + if (len <= 0) { // /proc/self/exe is not available on setuid processes, so fallback to // /proc/self/cmdline. int fd = open("/proc/self/cmdline", O_RDONLY); if (fd >= 0) { - len = read(fd, buf, size - 1); + // buf already includes trailing zero + len = read(fd, buf, size); close(fd); + if (len >= 0) { + len = strlen(buf); + } } } if (len <= 0) { - snprintf(buf, size, "%i", (int)getpid()); - return path; + // fallback to process ID + len = snprintf(buf, size, "%i", (int)getpid()); + if (len >= size) { + len = size - 1; + } } #endif path.truncate(len); -- 2.43.0