1 //===-- ptrace_example.c --------------------------------------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 #include <asm/ptrace.h>
10 #include <linux/elf.h>
13 #include <sys/prctl.h>
14 #include <sys/ptrace.h>
19 // The demo program shows how to do basic ptrace operations without lldb
20 // or lldb-server. For the purposes of experimentation or reporting bugs
23 // It is AArch64 Linux specific, adapt as needed.
30 if (ptrace(PTRACE_TRACEME
, 0, 0, 0) < 0) {
35 printf("Before breakpoint\n");
37 // Go into debugger. Instruction replaced with nop later.
38 // We write 2 instuctions because POKETEXT works with
39 // 64 bit values and we don't want to overwrite the
40 // call to printf accidentally.
41 asm volatile("BRK #0 \n nop");
43 printf("After breakpoint\n");
46 void debugger(pid_t child
) {
48 // Wait until it hits the breakpoint.
51 while (WIFSTOPPED(wait_status
)) {
52 if (WIFEXITED(wait_status
)) {
53 printf("inferior exited normally\n");
57 // Read general purpose registers to find the PC value.
58 struct user_pt_regs regs
;
61 io
.iov_len
= sizeof(regs
);
62 if (ptrace(PTRACE_GETREGSET
, child
, NT_PRSTATUS
, &io
) < 0) {
63 printf("getregset failed\n");
67 // Replace brk #0 / nop with nop / nop by writing to memory
69 uint64_t replace
= 0xd503201fd503201f;
70 if (ptrace(PTRACE_POKETEXT
, child
, regs
.pc
, replace
) < 0) {
71 printf("replacing bkpt failed\n");
75 // Single step over where the brk was.
76 if (ptrace(PTRACE_SINGLESTEP
, child
, 0, 0) < 0) {
81 // Wait for single step to be done.
85 if (ptrace(PTRACE_CONT
, child
, 0, 0) < 0) {
90 // Wait to see that the inferior exited.