add pid filter to profile

This commit is contained in:
officeyutong
2025-06-08 04:00:54 +08:00
parent 5087bb075a
commit 59ef373431
2 changed files with 25 additions and 3 deletions

View File

@@ -14,6 +14,8 @@ struct {
__uint(max_entries, 256 * 1024);
} events SEC(".maps");
__u32 target_pid = 0;
SEC("perf_event")
int profile(void *ctx)
{
@@ -22,6 +24,10 @@ int profile(void *ctx)
struct stacktrace_event *event;
int cp;
/* Check if we need to filter by PID */
if (target_pid != 0 && target_pid != pid)
return 0;
event = bpf_ringbuf_reserve(&events, sizeof(*event), 0);
if (!event)
return 1;
@@ -33,7 +39,6 @@ int profile(void *ctx)
event->comm[0] = 0;
event->kstack_sz = bpf_get_stack(ctx, event->kstack, sizeof(event->kstack), 0);
event->ustack_sz = bpf_get_stack(ctx, event->ustack, sizeof(event->ustack), BPF_F_USER_STACK);
bpf_ringbuf_submit(event, 0);

View File

@@ -118,7 +118,10 @@ static int event_handler(void *_ctx, void *data, size_t size)
static void show_help(const char *progname)
{
printf("Usage: %s [-f <frequency>] [-h]\n", progname);
printf("Usage: %s [-f <frequency>] [-p <pid>] [-h]\n", progname);
printf(" -f <frequency> sampling frequency (default: 1)\n");
printf(" -p <pid> target PID to profile (default: all processes)\n");
printf(" -h show this help\n");
}
int main(int argc, char * const argv[])
@@ -133,8 +136,10 @@ int main(int argc, char * const argv[])
int *pefds = NULL, pefd;
int argp, i, err = 0;
bool *online_mask = NULL;
__u32 target_pid = 0; /* 0 means profile all processes */
__u32 key = 0;
while ((argp = getopt(argc, argv, "hf:")) != -1) {
while ((argp = getopt(argc, argv, "hf:p:")) != -1) {
switch (argp) {
case 'f':
freq = atoi(optarg);
@@ -142,6 +147,10 @@ int main(int argc, char * const argv[])
freq = 1;
break;
case 'p':
target_pid = atoi(optarg);
break;
case 'h':
default:
show_help(argv[0]);
@@ -169,6 +178,14 @@ int main(int argc, char * const argv[])
goto cleanup;
}
/* Set the target PID in the BPF map */
if (target_pid) {
skel->bss->target_pid = target_pid;
printf("Profiling process with PID %u only\n", target_pid);
} else {
printf("Profiling all processes\n");
}
symbolizer = blazesym_new();
if (!symbolizer) {
fprintf(stderr, "Fail to create a symbolizer\n");