From: Adrian Bridgett <adrian@smop.co.uk>
Date: Fri, 24 Jul 2020 14:59:35 +0200
Subject: chkproc

1. Fix race condition where processes that start/exit between checking
/proc and ps(1) output are flagged as hidden.  This was first written
by Adrian Bridgett <adrian@smop.co.uk> in Fri, 24 Jul 2020 14:59:35
+0200. (Except for a single-line change to set pv to 3, which was from
Giuseppe Iuculano <giuseppe@iuculano.it> Date: Sun, 9 Jul 2017
18:42:55 +0200 -- this is kept, as it seems a suitable default for all
platforms, but in fact chkrootkit explicitly sets pv anyway)

2. Comment out code that sends signals to individual processes. This
is very risky as it is most likely to result in non-rootkits being
killed or resuming. It does slightly reduce functionality -- ideally
such a feature would be done in a separate process to keep
chkproc. This was contributed by Francois Marier <francois@debian.org>
with a date: Mon, 21 Apr 2008 11:17:03 +0000. (This is merged into
this patch to make it easier to maintain).

3. Fix various compilation errors and warnings. These were originally contributed
by =?utf-8?q?Christian_G=C3=B6ttsche?= <cgzones@googlemail.com>
Date: on Fri, 24 Jul 2020 16:08:40 +0200.
Mainly:
a) ignore return value from fgets in readline
b) use size_t not int in readline, dodgy_process
c) use ssize_t in dodgy_process
d) declare ps_cmds and commands that use it as 'const'
(This is merged into this patch to make it easier to maintain).

4. various fixes (Author: richard.lewis.debian@googlemail.com)
a) Support NetBSD
   PID 0 is allowed (although 1 is still init)
   netbsd's ps(1) is incompatible with
   the other ps commands.
	 It does support getpriority(2) (As does FreeBSD?) so enable that check.
	 The contents of /proc/pid are similar to linux (excpet for hidden thread ids)
	  so reuse that code.

b) Also works on __android (termux)
   Android is linux, but many things are not accessible.

c) Simplify and correct checking for linux threads
   We do not need a separate isathread variable, just set psproc snd dirproc to 1
	 for numeric tids (TIDs are always numeric)

d) Allow -p on any OS
   chkrootkit is actually passing -p already, but chkproc only allowed it on linux
   keep the checks for "numeric tids have hidden dirs in /proc" linux-specific
	 This allows you to, eg, use gnu's ps on OpenBSD, or to test parsing

e) replace tabs with spaces

f) New (deliberately undocumented) args to allow using custom commands for ps
   (use -p to choose how to parse output!) or to use a different dir as /proc
	 and to disable the use of getpriority(2). This allows for testing of the logic

g) Ensure a valid return value
   exit codes should be 0...255 not an arbitrary int: so just return 0 or 1

h) Include fnctl.h -- needed on some systems

i) Better output
   When outputting details of processes, include the contents,
   without trailing whitespce, of
    /proc/pid/cmdline
	/proc/pid/comm    (linux only)
	/proc/pid/cgroup  (linux only)
   (Introduce a new function showfile to do this)
   Refactor code to show a symlink target into a function to avoid duplication.
   readdir is section 3 not 2
   Last-Updated: 2024-12-15

Forwarded: yes
 (Forwarded by email: 21 Dec 2024)
Last-Updated: 2024-12-15
---
 chkproc.c | 709 +++++++++++++++++++++++++++++++++++++++-----------------------
 1 file changed, 443 insertions(+), 266 deletions(-)

diff --git a/chkproc.c b/chkproc.c
index 353a269..6c4b6e3 100644
--- a/chkproc.c
+++ b/chkproc.c
@@ -51,16 +51,13 @@
   2006/01/11 - Fix signal 25 on parisc linux and return of kill() -
                Thanks to Lantz Moore
 
-  2014/07/16 -  MAX_PROCESSES now is 999999 - 
-		Thanks to Nico Koenrades
+  2014/07/16 -  MAX_PROCESSES now is 999999 -
+   Thanks to Nico Koenrades
 
-  2017/04/13 -  MAX_PROCESSES now is 4194384 if linux64 
-		Thanks to DS Store
+  2017/04/13 -  MAX_PROCESSES now is 4194384 if linux64
+   Thanks to DS Store
 */
 
-#if !defined(__linux__) && !defined(__FreeBSD__) && !defined(__sun)
-int main (){ return 0; }
-#else
 #include <stdio.h>
 #include <string.h>
 #include <errno.h>
@@ -70,317 +67,497 @@ int main (){ return 0; }
 #include <stdlib.h>
 #include <unistd.h>
 #include <signal.h>
-#include <sys/stat.h>
+/*#include <sys/stat.h>*/
 #if defined(__sun)
 #include <procfs.h>
+#endif
 #include <fcntl.h>
-#endif
 #include <sys/resource.h>
 
-#define PS_SUN 0
-#define PS_LOL 1
-#define PS_COM 2
-#define PS_LNX 3
-#define PS_MAX 3
 #define ENYELKM "/proc/12345"
 // #define ENYELKM "/tmp/12345"
 
-#if defined(__sun)
+#if defined(__sun) || defined(__NetBSD__)
 #define FIRST_PROCESS 0
 #else
 #define FIRST_PROCESS 1
 #endif
-#define MAX_PROCESSES 9999999 
-#if (defined (__x86_64) > 0  || defined (__amd64) > 0) 
-#undef MAX_PROCESSES
+
+#if (defined (__x86_64) > 0 || defined (__amd64) > 0)
 #define MAX_PROCESSES 4194304
+#else
+#define MAX_PROCESSES 9999999
 #endif
+
 #define MAX_BUF 1024
 
 #if !defined (SIGXFSZ)
 #define SIGXFSZ 25
 #endif
 
-static char *ps_cmds[] = {
-	    "ps -edf",
-	    "ps auxw",
-	    "ps mauxw 2>&1 ",
-            "ps auxw -T|tr -s ' '|cut -d' ' -f2-",
-          };
 
-int psproc [MAX_PROCESSES+1];
-int dirproc[MAX_PROCESSES+1];
-#if defined(__linux__)
-int isathread[MAX_PROCESSES+1];
+#define PS_SUN 0
+#define PS_COM 2
+#define PS_NetBSD 4
+#define PS_LINUX 3
+#define PS_MAX 4
+const char *ps_cmds[] = {
+  "ps -edf", // SUN
+  "ps auxw", // fallback
+  "ps mauxw 2>&1 ", // "COM" - FreeBSD, etc
+  "ps -eTo pid= -o spid=", // linux
+  "ps -axo pid=" // NetBSD
+};
+
+#define PROCDIR "/proc"
+
+// nb: we rely on global vars being initialized to 0
+int psproc [MAX_PROCESSES+1]; // pids in ps(1) output
+int dirproc[MAX_PROCESSES+1]; // pids in /proc/ dir
+int recheck[MAX_PROCESSES+1]; // list of pids to recheck
+
+#if !defined(__FreeBSD__) // however, getpriority does exist on FreeBSD?
+// getpriority(2) may reveal hidden processes
+#define CHECK_PRIORITY 1
+#else
+#define CHECK_PRIORITY 0
+#endif
+
+#ifdef __GNUC__
+__attribute__((__noreturn__))
 #endif
+void usage(void){
+  fprintf(stderr, "Usage: chkproc [-v] [-p ps-syntax] [-N max-pid-to-check]\n");
+  exit(1);
+}
 
-/*
- * read at most the first (size-1) chars into s and terminate with a '\0'.
- * stops reading after a newline or EOF.  if a newline is read, it will be
- * the last char in the string.  if no newline is found in the first
- * (size-1) chars, then keep reading and discarding chars until a newline
- * is found or EOF.
+/* read a line from stream into s. the line is capped at size chars.
+ * read at most (size-1) chars from stream into s and terminate with a
+ * '\0'.  stops reading after a newline (which is retained )or EOF. If
+ * no newline was read, then also keep reading from stream discarding
+ * chars until a newline is found or EOF.
  */
-char *readline(char *s, int size, FILE *stream)
+char *readline(char *s, size_t size, FILE *stream)
 {
   char *rv = fgets(s, size, stream);
 
   if (strlen(s) == (size-1) && s[size-1] != '\n')
-  {
-    char buf[MAX_BUF];
-    fgets(buf, MAX_BUF, stream);
-    while (strlen(buf) == (MAX_BUF-1) && buf[MAX_BUF-1] != '\n')
     {
-      fgets(buf, MAX_BUF, stream);
+      char buf[MAX_BUF];
+      (void) !fgets(buf, MAX_BUF, stream);
+      while (strlen(buf) == (MAX_BUF-1) && buf[MAX_BUF-1] != '\n')
+        {
+          (void) !fgets(buf, MAX_BUF, stream);
+        }
     }
-  }
 
   return rv;
 }
 
+// show target of symlink link (at most MAX_BUF-1 chars). The other
+// args construct the output text. (eg link is relative to dir)
+void showlink(const char * link, const char * prefix, const int i, const char * buf){
+  char path[MAX_BUF];
+  ssize_t ret;
+
+  ret = readlink(link, path, sizeof(path)-1);
+  if (ret < 0)
+    printf("PID %d: %s: cannot read %s/%s: %s\n",
+           i, prefix, buf, link,  strerror(errno));
+  else
+    {
+      path[ret] = 0;
+      printf("PID %d: %s: '%s'\n", i, prefix, path);
+    }
+}
+
+// show contents of file (at most MAX_BUF-1 chars). The other
+// args construct the output text. (eg link is relative to dir)
+void showfile(const char * file, const char * prefix, const int i, const char * buf){
+  int fd;
+  char contents[MAX_BUF];
+  ssize_t ret;
+
+  if ((fd = open(file, O_RDONLY)) < 0)
+    printf("PID %d: %s: cannot open file %s%s: %s\n", i, prefix, buf, file, strerror(errno));
+  else
+    {
+      if ((ret = read(fd, contents, sizeof(contents)-1)) < 0)
+        printf("PID %d: %s: cannot read file %s%s: %s\n", i, prefix, buf, file, strerror(errno));
+      else
+        {
+          while (ret >=1 && ( contents[ret-1]==0 || contents[ret-1]=='\n' || contents[ret-1]==' '))
+            --ret; // remove trailing cruft)
+          for (ssize_t j = 0; j < ret; ++j)
+            // replace embedded \0 and \n (especially present in cmdline)
+            if (contents[j]==0 || contents[j]=='\n') contents[j]=' ';
+          contents[ret]=0; // ensure a terminator
+          printf("PID %d: %s: '%s'\n", i, prefix, contents);
+        }
+      close(fd);
+    }
+}
+
+/* see if pid i (which has a /proc/i directory) is missing from
+   readdir or ps output. if so, increment retdir and/or retps as
+   appropriate andntry and read info from proc. the string buf holds
+   /proc/i. You need to have run populate_psdir and populate_psproc first to set the global vars dirproc and psproc */
+void dodgy_process(int i, const char * buf, int * retdir, int * retps)
+{
+#if defined(__sun)
+  int fd;
+  psinfo_t psbuf;
+#endif
+  int bad = 0;
+
+  if (!dirproc[i])
+    {
+      bad = 1;
+      (*retdir)++;
+      printf("PID %d: hidden from readdir(3) but %s exists\n", i, buf);
+    }
+
+  if (!psproc[i])
+    {
+      bad = 1;
+      (*retps)++;
+      printf("PID %d: hidden from ps(1) output but %s exists\n", i, buf);
+    }
+
+  if (bad)
+    {
+#if defined(__linux__) || defined(__NetBSD__)
+      // symlink to the executable
+      showlink("exe", "EXE", i, buf);
+
+      // cmdline holds argv
+      showfile("cmdline", "CMDLINE", i, buf);
+#if defined(__linux__)
+      // comm is (usually) the basename of the command: see https://lwn.net/Articles/999770/
+      showfile("comm","COMM", i, buf);
+      showfile("cgroup","CGROUP", i, buf);
+      // systemd unit that launched the process
+#endif
+#elif defined(__FreeBSD__)
+      showlink("file", "FILE", i, buf);
+#elif defined(__sun)
+      if ((fd = open("./psinfo", O_RDONLY)) < 0)
+        {
+          if (read(fd, &psbuf, sizeof(psbuf)) == sizeof(psbuf))
+            printf("PSINFO %d: %s\n", i, psbuf.pr_psargs);
+          else
+            printf("PSINFO %d: unknown\n", i);
+          close(fd);
+        }
+      else
+        printf("PSINFO %d: unknown\n", i);
+#else
+      printf("(Getting info about PID %d not implemented on this OS)\n", i);
+#endif
+        }
+}
+
+#if CHECK_PRIORITY
+/* check if we can find PID by checking getpriority.
+   returns 1 if we can, 0 if not */
+int check_priority(int pid)
+{
+  errno = 0;
+  getpriority(PRIO_PROCESS, pid);
+  return(!errno);
+}
+#endif
+
+/* run ps_cmd and set psproc[pid]=1 for every pid we find (and also
+   dirproc[tid]=1 if pv is PS_LINUX). pv determines how we parse the
+   output: pv=n means we assume that ps_cmd is output from
+   ps_cmds[pv] */
+void populate_psproc(const char *ps_cmd, int pv, int verbose)
+{
+  char buf[MAX_BUF], *p;
+  int pid = 0, tid = 0;
+  FILE *ps;
+
+  if (!ps_cmd) exit(3); // cannot happen!
+  if (verbose) printf("Running ps(1): %s\n", ps_cmd);
+  if (!(ps = popen(ps_cmd, "r")))
+    {
+      perror("ps");
+      exit(errno);
+    }
+
+  // skip header (if there should be one)
+  if (pv != PS_LINUX && pv != PS_NetBSD)
+    {
+      readline(buf, MAX_BUF, ps); /* should be header (except Sun)*/
+      if (verbose) printf("<<%s>>\n", buf);
+#if defined(__sun)
+      if (!isspace(*buf))
+#else
+      if (!isalpha(*buf))
+#endif
+        {
+          readline(buf, MAX_BUF, ps); /* Look again for header */
+          if (verbose) printf("<<%s>>\n",buf);
+          if (!isalpha(*buf))
+            {
+              fprintf(stderr, "OooPS! failed to parse ps output: '%s'\n", buf);
+              exit(2);
+            }
+        }
+    }
+  if (!memcmp(buf, "ps:", 3))
+    {
+      fprintf(stderr, "OooPS! failed to parse ps output: '%s'\n", buf);
+      exit(2);
+    }
+
+  // main output
+  while (readline(buf, MAX_BUF, ps))
+    {
+      if (verbose) printf("<<%s>>\n", buf);
+      p = buf;
+#if defined(__sun)
+      while (isspace(*p)) /* Skip spaces */
+        p++;
+#endif
+      if (pv != PS_LINUX && pv != PS_NetBSD)
+        while (!isspace(*p)) /* Skip username */
+          p++;
+      while (isspace(*p)) /* Skip spaces */
+        p++;
+      if (!isdigit(*p))
+        fprintf(stderr,"Skipping unexpected pid (not numeric) in ps outout: '%s' while looking at: '%s'\n", buf, p);
+      else
+        {
+          pid = atoi(p);
+          if (pid < FIRST_PROCESS || pid > MAX_PROCESSES)
+            fprintf(stderr, "Unexpected pid (out of range) in ps outout: expected 'pid' got: '%s' looking at '%s'\n", buf, p);
+          else
+            {
+              if (verbose) printf("ps sees: pid=%d\n",pid);
+              psproc[pid] = 1;
+
+              if (pv == PS_LINUX && pid != -1)
+                {
+                  while (isdigit(*p)) /* skip pid */
+                    p++;
+                  while (isspace(*p)) /* Skip spaces between pid and tid */
+                    p++;
+                  if (!isdigit(*p))
+                    fprintf(stderr,"Skipping unexpected tid (not numeric) in ps outout (pid=%d): '%s' looking at '%s'\n", pid, buf, p);
+                  else
+                    {
+                      tid = atoi(p);
+                      if (tid < FIRST_PROCESS || tid > MAX_PROCESSES)
+                        fprintf(stderr, "Skipping unexpected tid (out of range, or non-numeric) in ps output: expected 'pid tid' got: '%s' (pid=%d) lookong at '%s'\n", buf, pid, p);
+                      else
+                        {
+                          if (verbose) printf("ps sees: tid=%d (pid=%d)\n", tid, pid);
+                          psproc[tid] = 1;
+                          dirproc[tid] = 1;
+                        }
+                    }
+                }
+            }
+        }
+    }
+  if (verbose) printf("Done checking ps\n");
+  pclose(ps);
+}
+
+// see which directories /proc/i exist using readdir(3). Set dirproc[i] to 1 if /proc/i is found.
+// found.
+void populate_psdir(const char * proc_dir, int verbose)
+{
+  char *d_name;
+  DIR *proc;
+  struct dirent *dir;
+  int pid;
+
+  if (!proc_dir) exit(3); // cannot happen!
+  if ((proc = opendir(proc_dir)) == NULL)
+    {
+      perror(proc_dir);
+      exit(1);
+    }
+  if (verbose) printf("Reading directory: %s\n", proc_dir);
+  while ((dir = readdir(proc)))
+    {
+      d_name = dir->d_name;
+      if (!isdigit(*d_name))
+        {
+          if (verbose) printf("Skipping non-pid: %s\n", d_name);
+          continue;
+        }
+
+      pid = atoi(d_name);
+      if (pid < FIRST_PROCESS || pid > MAX_PROCESSES)
+        fprintf(stderr, "Ignoring pid %s/%s (out of bounds)\n", proc_dir, d_name);
+      else
+        {
+          if (verbose) printf("Entry exists for pid %d: %s/%s\n",pid, proc_dir, d_name);
+          dirproc[pid] = 1;
+        }
+    }
+  closedir(proc);
+}
+
 int main(int argc, char **argv)
 {
-   char buf[MAX_BUF], *p, path[MAX_BUF];
-   char *pscmd = (char *)0;
-   FILE *ps;
-   DIR *proc = opendir("/proc");
-   struct dirent *dir;
-   struct stat sb;
-   int i, j, retps, retdir, pv, verbose;
-   long ret = 0L;
-   char * tmp_d_name;
-#if defined(__linux__)
-   int maybeathread;
-#endif
+  char buf[MAX_BUF];
+  int i, retps=0, retdir=0, retpri=0, ret=0;
+
+  int verbose=0;
+
 #if defined(__sun)
-   psinfo_t psbuf;
+  int pv = PS_SUN;
+#elif defined(__linux__)
+  int pv = PS_LINUX;
+#elif defined(__NetBSD__)
+  int pv = PS_NetBSD;
+#else
+  int pv = PS_COM;
 #endif
+  const char *ps_cmd=0; // for testing
+  const char *proc_dir=PROCDIR; // for testing
+  int get_priority=1; // for testing: 0=disable, 1=enable (supported platforms only)
+  int len; // usually 5 - we add pid to buf at this position
 
-   pv = verbose = 0;
+  int max_pid=MAX_PROCESSES;
+  int to_recheck=-1; // incremented each time we find a pid to recheck
 
-   if (!proc)
-   {
-      perror("proc");
-      exit (1);
-   }
-   for (i = 1; i < argc; i++)
-   {
+  for (i = 1; i < argc; ++i)
+    {
       if (!memcmp(argv[i], "-v", 2))
-	verbose++;
-      else if (!memcmp(argv[i], "-?", 2))
-      {
-	printf("Usage: %s [-v] [-v] -p <num>\n", argv[0]);
-	return 0;
-      }
-#if defined(__linux__)
+        verbose = 1;
       else if (!memcmp(argv[i], "-p", 2))
-      {
-         if (i+1 < argc)
+        {
+          if (i+1 < argc)
             pv = atoi(argv[++i]);
-         else
-         {
-	    printf("Usage: %s [-v] [-v] [-p procps version]\n", argv[0]);
-	    return 0;
-         }
-      }
-#endif
-   }
-#if defined(__sun)
-   pscmd = ps_cmds[PS_SUN];
-#elif !defined (__linux__)
-   pscmd = ps_cmds[PS_COM];
-#endif
-#if defined(__linux__)
-   if (pv < 1 || pv > PS_MAX)
-      pv = 1;
-   pscmd = ps_cmds[pv];
-/*  printf("pv = %d\n\r", pv); /* -- DEBUG */
-#endif
+          else
+            usage();
+        }
+      else if (!memcmp(argv[i], "-N", 2))
+        {
+          if (i+1 < argc)
+            max_pid = atoi(argv[++i]);
+          else
+            usage();
+        }
+       // Some undocumented options to test the parser
+      else if (!memcmp(argv[i], "--ps-cmd", 8))
+        {
+          /* use custom ps+args.
+             -p still determines how to parse the output */
+          if (i+1 < argc)
+            ps_cmd=argv[++i];
+          else
+            usage();
+        }
+      else if (!memcmp(argv[i], "--proc-dir", 10))
+        {
+          /* treat a custom dir as /proc  */
+          if (i+1 < argc)
+            proc_dir=argv[++i];
+          else
+            usage();
+        }
+      else if (!memcmp(argv[i], "--no-getpriority", 16))
+        // skip use of getpriority(2)
+        get_priority=0;
+      else usage();
+    }
 
-/* printf("pscmd = %s\n\r", pscmd); /* -- DEBUG */
-   if (!(ps = popen(pscmd, "r")))
-   {
-       perror("ps");
-       exit(errno);
-   }
+  if (max_pid < FIRST_PROCESS || max_pid > MAX_PROCESSES)
+    max_pid = MAX_PROCESSES;
 
-   *buf = 0;
-   readline(buf, MAX_BUF, ps); /* Skip header */
-#if defined(__sun)
-   if (!isspace(*buf))
-#else
-   if (!isalpha(*buf))
-#endif
-   {
-     readline(buf, MAX_BUF, ps); /* Skip header */
-     if (!isalpha(*buf) && pv != PS_LNX)
-     {
-	if (pv != PS_LOL)
-	   execlp(argv[0], argv[0], "-p 1", NULL);
-        fprintf(stderr, "OooPS!\n");
-        exit(2);
-     }
-   }
-   if (!memcmp(buf, "ps:", 3) && (pv != PS_LOL))
-      execlp(argv[0], argv[0], "-p 1", NULL);
+  if (pv < 0 || pv > PS_MAX)
+    pv = PS_COM;
 
-   for (i = FIRST_PROCESS; i <= MAX_PROCESSES; i++) { /* Init matrix */
-     psproc[i] = dirproc[i] = 0;
-#if defined(__linux__)
-     isathread[i] = 0;
-#endif
-   }
+  if (!ps_cmd) ps_cmd=ps_cmds[pv];
+  if (!proc_dir) proc_dir=PROCDIR;
 
-   while (readline(buf, MAX_BUF, ps))
-   {
-      p = buf;
-#if defined(__sun)
-      while (isspace(*p)) /* Skip spaces */
-          p++;
-#endif
-      while (!isspace(*p)) /* Skip User */
-          p++;
-      while (isspace(*p)) /* Skip spaces */
-          p++;
-/*  printf(">>PS %s<<\n", p);  /* -- DEBUG */
-      ret = atol(p);
-      if ( ret < 0 || ret > MAX_PROCESSES )
-      {
-         fprintf (stderr, " OooPS, not expected %ld value\n", ret);
-         exit (2);
-      }
-      psproc[ret] = 1;
-   }
-   pclose(ps);
+  len=strlen(proc_dir);
+  if (len+22 >= MAX_BUF) {
+	// unlikely, but avoid possibility for proc_dir+/+PID+\0 to overflow buf
+	// nb: the largest 64-bit unsigned integer (2^64-1) has 20 digits+/+\0
+	printf("ERROR: %s too long to use as /proc\n", proc_dir);
+	exit(2);
+  }
+  strcpy(buf, proc_dir);
 
-   while ((dir = readdir(proc)))
-   {
-#if defined(__linux__)
-      maybeathread = 0;
-#endif
-      tmp_d_name = dir->d_name;
-      if (!strcmp(tmp_d_name, ".") || !strcmp(tmp_d_name, ".."))
-         continue;
-#if defined(__linux__)
-      if (*tmp_d_name == '.') { /* here we catch the new NTPL threads in linux.  They are listed in /proc as PIDs with a period prepended */
-         tmp_d_name++;
-         maybeathread = 1;
-      }
-#endif
-      if(!isdigit(*tmp_d_name))
-         continue;
-#if defined(__linux__)
-      else if (maybeathread) {
-         isathread[atol(tmp_d_name)] = 1; /* mark it as a linux NTPL thread if it's in the form of "\.[0-9]*" */
-         if (verbose)
-            printf("%ld is a Linux Thread, marking as such...\n", atol(tmp_d_name));
-      }
-#endif
+  populate_psproc(ps_cmd, pv, verbose);
+  populate_psdir(proc_dir, verbose);
 
-/*      printf("%s\n", tmp_d_name); /* -- DEBUG */
-      dirproc[atol(tmp_d_name)] = 1;
-   }
-   closedir(proc);
-
-   /* Brute force */
-   strcpy(buf, "/proc/");
-   retps = retdir = 0;
-   for (i = FIRST_PROCESS; i <= MAX_PROCESSES; i++)
-   {
-      // snprintf(&buf[6], 6, "%d", i);
-       snprintf(&buf[6], 8, "%d", i);
+  for (i = FIRST_PROCESS; i <= max_pid; ++i)
+    {
+      if (verbose && i%100000 == 0)
+        {
+          printf("Checking for PIDS: %d/%d\n", i, max_pid);
+          fflush(stdout);
+        }
+	  // largest 64-bit unsigned integer (2^64-1) has 20 digits+/+\0
+      snprintf(&buf[len], 22, "/%d", i);
       if (!chdir(buf))
-      {
-         if (!dirproc[i] && !psproc[i])
-         {
-#if defined(__linux__)
-            if (!isathread[i]) {
-#endif
-            retdir++;
-            if (verbose)
-	       printf ("PID %5d(%s): not in readdir output\n", i, buf);
-#if defined(__linux__)
-            }
-#endif
-         }
-         if (!psproc[i] ) /* && !kill(i, 0)) */
-         {
-#if defined(__linux__)
-            if(!isathread[i]) {
-#endif
-            retps++;
-            if (verbose)
-	       printf ("PID %5d: not in ps output\n", i);
-#if defined(__linux__)
+        {
+          /* cd /proc/i worked: pid i should be in both dirproc and
+             psproc (unless it is a linux tid) */
+          if (verbose) printf("Looking at %d (ps=%d, dir=%d): ", i, psproc[i], dirproc[i]);
+          if (!psproc[i] || !dirproc[i])
+            {
+              if (verbose) printf("To recheck: %d\n", i);
+              recheck[++to_recheck] = i;
             }
-#endif
-	 }
-#if defined(__linux__)
-         if(!isathread[i]) {
-#endif
-/*	 if ((!dirproc[i] || !psproc[i]) && !kill(i, 0) && (verbose > 1)) */
-	 if ((!dirproc[i] || !psproc[i]) && (verbose > 1))
-	 {
-#if defined(__linux__)
-	    j = readlink ("./cwd", path, sizeof(path));
-	    path[(j < sizeof(path)) ? j : sizeof(path) - 1] = 0;
-	    printf ("CWD %5d: %s\n", i, path);
-	    j = readlink ("./exe", path, sizeof(path));
-	    path[(j < sizeof(path)) ? j : sizeof(path) - 1] = 0;
-	    printf ("EXE %5d: %s\n", i, path);
-#elif defined(__FreeBSD__)
-	    j = readlink ("./file", path, sizeof(path));
-	    path[(j < sizeof(path)) ? j : sizeof(path) - 1] = 0;
-	    printf ("FILE %5d: %s\n", i, path);
-#elif defined(__sun)
-	    if ((j = open("./psinfo", O_RDONLY)) != -1)
+          else if (verbose) printf("OK\n");
+        }
+#if CHECK_PRIORITY
+      else if (get_priority && check_priority(i))
+        {
+          /* no /proc/i so getpriority should fail */
+          if (verbose) printf("To recheck (due to getpriority): %d\n", i);
+          recheck[++to_recheck] = i;
+        }
+#endif
+    }
+  if (verbose) printf("Checked for PIDs up to: %d (done: %d to recheck)\n", max_pid, to_recheck + 1);
+
+  /* second pass - repopulate psproc, psdir and retry */
+  if (to_recheck >= 0)
+    {
+      if (verbose) printf("To recheck: %d PID(s)\n", to_recheck + 1);
+      for (i = 0; i <= MAX_PROCESSES; ++i)
+        psproc[i] = dirproc[i] = 0;
+      populate_psproc(ps_cmd, pv, verbose);
+      populate_psdir(proc_dir, verbose);
+
+      for (i = 0; i <= to_recheck; ++i)
+        {
+          // largest 64-bit unsigned integer (2^64-1) has 20 digits+/+\0
+          snprintf(&buf[len], 22, "/%d", recheck[i]);
+          if (!chdir(buf))
+            dodgy_process(recheck[i], buf, &retdir, &retps);
+#if CHECK_PRIORITY
+          else if (get_priority && check_priority(recheck[i]))
             {
-               if (read(j, &psbuf, sizeof(psbuf)) == sizeof(psbuf))
-                  printf ("PSINFO %5d: %s\n", i, psbuf.pr_psargs);
-               else
-                  printf ("PSINFO %5d: unknown\n", i);
-               close(j);
+              retpri++;
+              printf("PID %d: is hidden: it has getpriority(2) information but no %s entry\n", recheck[i], buf);
             }
-            else
-               printf ("PSINFO %5d: unknown\n", i);
-#endif
-         }
-#if defined(__linux__)
-         }
-#endif
-      }
-#ifndef __FreeBSD__
-      else
-      {
-         errno = 0;
-         getpriority(PRIO_PROCESS, i);
-         if (!errno)
-         {
-            retdir++;
-            if (verbose)
-	       printf ("PID %5d(%s): not in getpriority readdir output\n", i, buf);
-	 }
-      }
-#endif
-   }
-   if (retdir)
-      printf("You have % 5d process hidden for readdir command\n", retdir);
-   if (retps)
-      printf("You have % 5d process hidden for ps command\n", retps);
-#if defined(__linux__)
-   kill(1, 100); /*  Check for SIGINVISIBLE Adore signal */
-   if (kill (1, SIGXFSZ) < 0  && errno == 3)
-   {
-      printf("SIGINVISIBLE Adore found\n");
-      retdir+= errno;
-   }
-   /* Check for Enye LKM */
-   if (stat(ENYELKM, &sb) && kill (12345, 58) >= 0)
-   {
-      printf("Enye LKM found\n");
-      retdir+= errno;
-   }
 #endif
-   return (retdir+retps);
+        }
+    }
+
+  if ((ret = retdir + retps + retpri)) printf("\n");
+
+  if (retdir)
+    printf("You have %d process(es) hidden from readdir(3)\n", retdir);
+  if (retps)
+    printf("You have %d process(es) hidden from ps(1)\n", retps);
+#if defined(CHECK_PRIORITY)
+  if (retpri)
+    printf("You have %d hidden process(es) with getpriority(2) information\n", retpri);
+#endif
+
+  fflush(stdout);
+  return (ret>0);
 }
-#endif
