When you debug an app and set a breakpoint on native code, Android Studio will copy the needed files to the target device and start the lldb-server which will use ptrace to attach to the process. From this moment on, if you inspect the status file of the debugged process (/proc/<pid>/status or /proc/self/status), you will see that the "TracerPid" field has a value different from 0, which is a sign of debugging.
Remember that this only applies to native code. If you're debugging a Java/Kotlin-only app the value of the "TracerPid" field should be 0.
When trying to implement such a method yourself, you can manually check the value of TracerPid with ADB. The following listing uses Google's NDK sample app hello-jni (com.example.hellojni) to perform the check after attaching Android Studio's debugger:
$ adb shell ps -A |grep com.example.hellojni
u0_a271 11657 573 4302108 50600 ptrace_stop 0 t com.example.hellojni
u0_a271 11839 11837 14024 4548 poll_schedule_timeout 0 S lldb-server
You can see how the status file of com.example.hellojni (PID=11657) contains a TracerPID of 11839, which we can identify as the lldb-server process.
Using Fork and ptrace
You can prevent debugging of a process by forking a child process and attaching it to the parent as a debugger via code similar to the following simple example code:
voidfork_and_attach()
{
int pid =fork();
if(pid ==0)
{
int ppid =getppid();
if(ptrace(PTRACE_ATTACH, ppid,NULL,NULL)==0)
{
waitpid(ppid,NULL,0);
/* Continue the parent process */
ptrace(PTRACE_CONT,NULL,NULL);
}
}
}
With the child attached, further attempts to attach to the parent will fail. We can verify this by compiling the code into a JNI function and packing it into an app we run on the device.
root@android:/ # ps | grep -i anti
u0_a151 18190 201 1535844 54908 ffffffff b6e0f124 S sg.vantagepoint.antidebug
u0_a151 18224 18190 1495180 35824 c019a3ac b6e0ee5c S sg.vantagepoint.antidebug
Attempting to attach to the parent process with gdbserver fails with an error:
warning: process 18190 is already traced by process 18224
Cannot attach to lwp 18190: Operation not permitted (1)
Exiting
You can easily bypass this failure, however, by killing the child and "freeing" the parent from being traced. You'll therefore usually find more elaborate schemes, involving multiple processes and threads as well as some form of monitoring to impede tampering. Common methods include