hash_table_test.php 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. <?php
  2. /*
  3. * Copyright 2024 carl.guo <[email protected]>
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. $prog = <<<EOT
  18. BPF_HASH(counts, u32);
  19. int kprobe__do_sys_openat2(struct pt_regs *ctx) {
  20. u32 key = 0;
  21. u64 *val, zero = 0;
  22. val = counts.lookup_or_init(&key, &zero);
  23. (*val)++;
  24. bpf_trace_printk("openat2 called %d times\\n", *val);
  25. return 0;
  26. }
  27. EOT;
  28. try {
  29. $bpf = new Bpf(["text" => $prog]);
  30. echo "BPF program loaded successfully\n";
  31. // Get the hash table
  32. $counts = $bpf->get_table("counts");
  33. // Start monitoring
  34. echo "Monitoring openat2 syscalls with counter...\n";
  35. while (true) {
  36. try {
  37. list($task, $pid, $cpu, $flags, $ts, $msg) = $bpf->trace_fields();
  38. printf("%-18.9f %-16s %-6d %s\n", $ts, $task, $pid, $msg);
  39. // Print current count
  40. $values = $counts->values();
  41. foreach ($values as $key => $value) {
  42. echo "Total calls: " . $value . "\n";
  43. }
  44. flush();
  45. } catch (Exception $e) {
  46. continue;
  47. }
  48. }
  49. } catch (Exception $e) {
  50. echo "Error: " . $e->getMessage() . "\n";
  51. exit(1);
  52. }