Skip to content

Commit

Permalink
Avoid a shell in show_backtrace.
Browse files Browse the repository at this point in the history
  • Loading branch information
gijsbers committed May 7, 2024
1 parent a73e983 commit dfb6fec
Showing 1 changed file with 48 additions and 11 deletions.
59 changes: 48 additions & 11 deletions src/misc.cc
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <pwd.h>

#if defined(__GXX_RTTI) && (__GXX_ABI_VERSION >= 1002)
Expand Down Expand Up @@ -694,6 +695,44 @@ char* progpath() {
return path;
}

FILE* process_open(const char* path, const char* args[], int* pid) {
FILE* fp = nullptr;
int fds[2];
if (pipe(fds) == 0) {
*pid = fork();
if (*pid == -1) {
close(fds[0]); close(fds[1]);
}
else if (*pid == 0) {
close(fds[0]);
dup2(fds[1], 1);
close(fds[1]);
execv(path, (char * const *) args);
_exit(1);
}
else {
close(fds[1]);
fp = fdopen(fds[0], "r");
if (fp == nullptr)
close(fds[0]);
}
}
return fp;
}

int process_close(FILE* fp, int pid) {
if (fp)
fclose(fp);
int xit = -1;
if (pid > 0) {
int status = 0;
waitpid(pid, &status, 0);
if (WIFEXITED(status))
xit = WEXITSTATUS(status);
}
return xit;
}

void show_backtrace(const int limit) {
#if defined(HAVE_BACKTRACE_SYMBOLS_FD) && defined(HAVE_EXECINFO_H)
const int asize = Elvis(limit, 20);
Expand All @@ -713,15 +752,15 @@ void show_backtrace(const int limit) {

int status(1);
if (path && access(tool, X_OK) == 0) {
const size_t bufsize(1234);
char buf[bufsize];
snprintf(buf, bufsize, "%s -C -f -p -s -e '%s'", tool, path);
size_t len = strlen(buf);
for (int i = 0; i < count && len + 21 < bufsize; ++i) {
snprintf(buf + len, bufsize - len, " %p", array[i]);
len += strlen(buf + len);
const char* args[30] = { tool, "-C", "-f", "-p", "-s", "-e", path, };
char strings[20][32];
for (int i = 0; i < count; ++i) {
sprintf(strings[i], "%p", array[i]);
args[7 + i] = strings[i];
}
FILE* fp = popen(buf, "r");
args[7 + count] = nullptr;
int pid = 0;
FILE* fp = process_open(tool, args, &pid);
if (fp) {
const int linesize(256);
char line[linesize];
Expand All @@ -733,12 +772,10 @@ void show_backtrace(const int limit) {
fputs(line, stderr);
}
}
if (pclose(fp) == 0 && lineCount >= count) {
if (process_close(fp, pid) == 0 && lineCount >= count) {
status = 0;
}
}
else
status = system(buf);
}
if (status) {
backtrace_symbols_fd(array, count, 2);
Expand Down

0 comments on commit dfb6fec

Please sign in to comment.