Commit 97562956 authored by Teng Qin's avatar Teng Qin

Add common helper to read Process executable

parent 899d3e92
...@@ -17,6 +17,7 @@ ...@@ -17,6 +17,7 @@
#include <sstream> #include <sstream>
#include "common.h" #include "common.h"
#include "vendor/tinyformat.hpp"
namespace ebpf { namespace ebpf {
...@@ -48,4 +49,16 @@ std::vector<int> get_possible_cpus() { ...@@ -48,4 +49,16 @@ std::vector<int> get_possible_cpus() {
return read_cpu_range("/sys/devices/system/cpu/possible"); return read_cpu_range("/sys/devices/system/cpu/possible");
} }
std::string get_pid_exe(pid_t pid) {
char exe_path[4096];
int res;
std::string exe_link = tfm::format("/proc/%d/exe", pid);
res = readlink(exe_link.c_str(), exe_path, sizeof(exe_path));
if (res == -1)
return "";
exe_path[res] = '\0';
return std::string(exe_path);
}
} // namespace ebpf } // namespace ebpf
...@@ -17,6 +17,8 @@ ...@@ -17,6 +17,8 @@
#pragma once #pragma once
#include <memory> #include <memory>
#include <string>
#include <unistd.h>
#include <vector> #include <vector>
namespace ebpf { namespace ebpf {
...@@ -31,4 +33,6 @@ std::vector<int> get_online_cpus(); ...@@ -31,4 +33,6 @@ std::vector<int> get_online_cpus();
std::vector<int> get_possible_cpus(); std::vector<int> get_possible_cpus();
std::string get_pid_exe(pid_t pid);
} // namespace ebpf } // namespace ebpf
...@@ -24,6 +24,7 @@ ...@@ -24,6 +24,7 @@
#include "bcc_elf.h" #include "bcc_elf.h"
#include "bcc_proc.h" #include "bcc_proc.h"
#include "common.h"
#include "usdt.h" #include "usdt.h"
#include "vendor/tinyformat.hpp" #include "vendor/tinyformat.hpp"
#include "bcc_usdt.h" #include "bcc_usdt.h"
...@@ -314,17 +315,9 @@ Context::Context(const std::string &bin_path) ...@@ -314,17 +315,9 @@ Context::Context(const std::string &bin_path)
Context::Context(int pid) : pid_(pid), pid_stat_(pid), Context::Context(int pid) : pid_(pid), pid_stat_(pid),
mount_ns_instance_(new ProcMountNS(pid)), loaded_(false) { mount_ns_instance_(new ProcMountNS(pid)), loaded_(false) {
if (bcc_procutils_each_module(pid, _each_module, this) == 0) { if (bcc_procutils_each_module(pid, _each_module, this) == 0) {
// get exe command from /proc/<pid>/exe cmd_bin_path_ = ebpf::get_pid_exe(pid);
// assume the maximum path length 4096, which should be if (cmd_bin_path_.empty())
// sufficiently large to cover all use cases
char source[64];
char cmd_buf[4096];
snprintf(source, sizeof(source), "/proc/%d/exe", pid);
ssize_t cmd_len = readlink(source, cmd_buf, sizeof(cmd_buf) - 1);
if (cmd_len == -1)
return; return;
cmd_buf[cmd_len] = '\0';
cmd_bin_path_.assign(cmd_buf, cmd_len + 1);
loaded_ = true; loaded_ = true;
} }
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment