xref: /aosp_15_r20/external/bcc/examples/cpp/HelloWorld.cc (revision 387f9dfdfa2baef462e92476d413c7bc2470293e)
1 /*
2  * Copyright (c) Facebook, Inc.
3  * Licensed under the Apache License, Version 2.0 (the "License")
4  */
5 
6 #include <unistd.h>
7 #include <fstream>
8 #include <iostream>
9 #include <string>
10 
11 #include "bcc_version.h"
12 #include "BPF.h"
13 
14 const std::string BPF_PROGRAM = R"(
15 int on_sys_clone(void *ctx) {
16   bpf_trace_printk("Hello, World! Here I did a sys_clone call!\n");
17   return 0;
18 }
19 )";
20 
main()21 int main() {
22   ebpf::BPF bpf;
23   auto init_res = bpf.init(BPF_PROGRAM);
24   if (!init_res.ok()) {
25     std::cerr << init_res.msg() << std::endl;
26     return 1;
27   }
28 
29   std::ifstream pipe("/sys/kernel/debug/tracing/trace_pipe");
30   std::string line;
31   std::string clone_fnname = bpf.get_syscall_fnname("clone");
32 
33   auto attach_res = bpf.attach_kprobe(clone_fnname, "on_sys_clone");
34   if (!attach_res.ok()) {
35     std::cerr << attach_res.msg() << std::endl;
36     return 1;
37   }
38 
39   std::cout << "Starting HelloWorld with BCC " << LIBBCC_VERSION << std::endl;
40 
41   while (true) {
42     if (std::getline(pipe, line)) {
43       std::cout << line << std::endl;
44       // Detach the probe if we got at least one line.
45       auto detach_res = bpf.detach_kprobe(clone_fnname);
46       if (!detach_res.ok()) {
47         std::cerr << detach_res.msg() << std::endl;
48         return 1;
49       }
50       break;
51     } else {
52       std::cout << "Waiting for a sys_clone event" << std::endl;
53       sleep(1);
54     }
55   }
56 
57   return 0;
58 }
59