IsDebuggerPresent for Mac OSX

By | September 2, 2020

IsDebuggerPresent is Win32 API function which returns boolean value true if calling process is being debugged by debugger. It is the simplest way to restrict reverse engineering activity using Windows debuggers. I did not find something similar for Mac OSX platform so I implemented my own application which does debugger detection. The application is based on sysctl function. I already posted one article here related to sysctl on Mac devices. It is the second one, may be not he last because sysctl has a lot of possibilities
Here is the underdebug.cpp code to detect debugger on Apple OS programmatically:

#include <stdio.h>
#include <unistd.h>
#include <sys/sysctl.h>
int main(int n, char ** s)
   char procname[255];
   int mib[4] = { 0, 0, 0, 0 };
   size_t len = 2;
   kinfo_proc kp;
   sysctlnametomib("kern.procname", mib, &len);
   len = sizeof(procname);
   int iError = sysctl(mib,2,procname,&len, NULL, 0);
   if(iError == 0)
      printf("Process name: %s\n", procname);\
      size_t len = 4;
      sysctlnametomib("", mib, &len);
      mib[3] = getpid();
      len = sizeof(kp);
      iError = sysctl(mib, 4, &kp, &len, NULL, 0);
      if(iError != 0)
      } else {
         if(kp.kp_proc.p_flag & P_TRACED)
            printf("The \"%s\" process is under debugger\n",procname);
   return 0;

Now testing!
Run underdebug program without debugger:

# ./underdebug
Process name: underdebug

Now starting the same application under debugger, process detects lldb debugger and print “The “underdebug” process is under debugger” message:

# lldb underdebug
(lldb) target create “underdebug”
Current executable set to ‘underdebug’ (x86_64).
(lldb) run
Process 19324 launched: ‘/Alex/underdebug/underdebug’ (x86_64)
Process name: underdebug
The “underdebug” process is under debugger
Process 19324 exited with status = 0 (0x00000000)

Leave a Reply

Your email address will not be published. Required fields are marked *