#ifndef lint
static char rcsid[] = "$Header: hpux-91.c,v 1.10 1996/07/19 15:32:24 forys Exp $";
#endif

/*
**  This program may be freely redistributed for noncommercial purposes.
**  This entire comment MUST remain intact.
**
**  HP-UX 8.0 support by Christos Zoulas (christos@deshaw.com)
**
**  Copyright 1994, 1996 by Jeff Forys (jeff@forys.cranbury.nj.us)
*/

#define	WOPR	/* some headers do magic when this is defined */

#define	NO_MEXTERN
#include "conf.h"
#undef	NO_MEXTERN

#include <sys/user.h>
#include <sys/proc.h>
#include <sys/rtprio.h>

#include <stdio.h>

/*
** Note: HP-UX finally supports setpriority(2); snice has been changed to
** use this, rather than rtprio(2).  If you need the old behavior, you can
** #define OLD_RTPRIO.
*/

/*
 * Define SigNames, NSig, and TtyDevDir here; they are used by other
 * routines and must be global.  Everyone seems to have their own
 * idea as to what NSIG should be.  Here, `NSig' is the number of
 * signals available, not counting zero.
 */
char *SigMap[] = { "0",
	"HUP", "INT", "QUIT", "ILL", "TRAP", "IOT",		/*  1 -  6 */
	"EMT", "FPE", "KILL", "BUS", "SEGV", "SYS",		/*  7 - 12 */
	"PIPE", "ALRM", "TERM", "USR1", "USR2", "CLD",		/* 13 - 18 */
	"PWR", "VTALRM", "PROF", "IO", "WINDOW", "STOP",	/* 19 - 24 */
	"TSTP", "CONT", "TTIN", "TTOU", "URG", "LOST",		/* 25 - 30 */
	"31", "DIL",						/* 31 - 32 */
};
int NSig = NSIG-1;

#define	SETCMD(dst,src,maxlen) {			\
	extern char *strrchr();				\
	if (maxlen > 0) src[maxlen] = '\0';		\
	dst = (dst = strrchr(src, '/')) ? ++dst: src;	\
}

static char *TtyDevDir = "/dev";

int	Skill;			/* set 1 if running `skill', 0 if `snice' */
int	PrioMin, PrioMax;	/* min and max process priorities */
int	SigPri;			/* signal to send or priority to set */
pid_T	MyPid;			/* pid of this process */
uid_T	MyUid;			/* uid of this process */
char	*ProgName;		/* program name */

/*
 * This is the machine-dependent initialization routine.
 *
 *   - The following global variables must be initialized:
 *     MyPid, MyUid, ProgName, Skill, PrioMin, PrioMax, SigPri
 *   - The working directory will be changed to that which contains the
 *     tty devices (`TtyDevDir'); this makes argument parsing go faster.
 *   - If possible, this routine should raise the priority of this process.
 */
void
MdepInit(pname)
	char *pname;
{
	extern char *rindex(), *SysErr();

	MyPid = (pid_T) getpid();
	MyUid = (uid_T) getuid();
	SETCMD(ProgName, pname, 0)

	/*
	 * If we are running as root, raise our priority to better
	 * catch runaway processes.
	 */
	if (MyUid == ROOTUID)
#ifdef OLD_RTPRIO
		(void) rtprio(MyPid, RTPRIO_MIN);
#else
		(void) setpriority(PRIO_PROCESS, MyPid, PRIO_MIN);
#endif

	/*
	 * Determine what we are doing to processes we find.  We will
	 * either send them a signal (skill), or renice them (snice).
	 */
	Skill = (strstr(ProgName, "snice") == NULL);

	/*
	 * chdir to `TtyDevDir' to speed up tty argument parsing.
	 */
	if (chdir(TtyDevDir) < 0) {
		fprintf(stderr, "%s: chdir(%s): %s\n", ProgName, TtyDevDir,
		        SysErr());
		exit(EX_SERR);
	}

	/*
	 * Set up minimum and maximum process priorities.
	 * Initialize SigPri to either default signal (`skill') or
	 * default priority (`snice').
	 */
#ifdef OLD_RTPRIO
	PrioMin = RTPRIO_MIN;
	PrioMax = RTPRIO_MAX;
	SigPri = Skill? SIGTERM: RTPRIO_RTOFF;
#else
	PrioMin = PRIO_MIN;
	PrioMax = PRIO_MAX;
	SigPri = Skill? SIGTERM: 4;
#endif
}

/*
 * Carry out an action on a particular process.  If this is `skill',
 * then send the process a signal, otherwise this is `snice' so change
 * it's priority.
 *
 * If 0 is returned, the operation was successful, otherwise -1 is
 * returned and `errno' set.
 */
int
MdepAction(pid)
	pid_T pid;
{
	if (Skill)
		return(kill((int)pid, SigPri));
	else
#ifdef OLD_RTPRIO
		return(rtprio((int)pid, SigPri));
#else
		return(setpriority(PRIO_PROCESS, (int)pid, SigPri));
#endif
}

/*
 * Now, set up everything we need to write a GetProc() routine.
 */

#include <sys/file.h>
#include <sys/vm.h>
#include <sys/pstat.h>

#if defined(hp9000s800) || defined(__hp9000s800)
#include <nlist.h>
#endif

static char *kmemf =	"/dev/kmem";	/* window into kernel virtual memory */
static char *memf =	"/dev/mem";	/* window into physical memory */
#ifdef VFORK_INIT	/* true for hpux 9.x, false for 10.x (and future?) */
static char *kernf =	"/hp-ux";	/* kernel image */
#else
static char *kernf =	"/stand/vmunix";/* kernel image */
#endif
static int kmem = 0, mem = 0;

#ifdef hp9000s800
static struct nlist nl[] = {
	{ "nproc" },
#define	X_NPROC		0
	{ "proc" },
#define	X_PROC		1
	{ "" },
#define	X_LAST		2
};
#else
static struct nlist nl[] = {
	{ "_nproc" },
#define	X_NPROC		0
	{ "_proc" },
#define	X_PROC		1
	{ "" },
#define	X_LAST		2
};
#endif

static	int	nproc = -1;
static	struct	proc *procp;

#define	NPROCS	32			/* number of procs to read at once */

#ifdef hp9000s800
static	char	*pidmap[] = { "swapper", "init", "vhand", "statdaemon" };
#else
static	char	*pidmap[] = { "swapper", "init", "vhand" };
#endif
static	int	pidmapsiz = sizeof(pidmap) / sizeof(pidmap[0]);

extern	off_t lseek();

#define	SKRD(file, src, dst, size)			\
	(lseek(file, (off_t)(src), L_SET) == -1) ||	\
	(read(file, (char *)(dst), (size)) != (size))
/*
 * GetWord(loc)
 *
 * Read in word at `loc' from kernel virtual memory.
 * If an error occurs, call exit(2) with EX_SERR.
 */
static int
GetWord(loc)
	off_t loc;
{
	int val;

	if (SKRD(kmem, loc, &val, sizeof(val))) {
		fprintf(stderr, "%s: can't read word at %lx in %s\n",
		        ProgName, (u_long)loc, kmemf);
		exit(EX_SERR);
	}
	return (val);
}
#undef	SKRD

/*
 * GetProc()
 *
 * Fill in and return a `struct ProcInfo' with information about the
 * next process.  If no processes are left, return NULL.
 */
struct ProcInfo *
GetProc()
{
	extern char *SysErr();
	static struct proc procs[NPROCS], *procsp;
	static struct ProcInfo procinfo;
	static struct pst_status apst;
	union pstun apstun;
	register struct proc *aproc;
	static int thisproc = 0;

	/*
	 * If this is our first time here, open various files,
	 * and set up the nlist.
	 */
	if (nproc == -1) {
		char *errstr = "%s: %s: %s\n";
		int nfound;

		if ((kmem=open(kmemf, 0)) < 0) {	/* open kmem */
			fprintf(stderr, errstr, ProgName, kmemf, SysErr());
			exit(EX_SERR);
		}

		if ((mem=open(memf, 0)) < 0) {		/* open mem */
			fprintf(stderr, errstr, ProgName, memf, SysErr());
			exit(EX_SERR);
		}

		if ((nfound=nlist(kernf, nl)) < 0) {	/* kernel name list */
			fprintf(stderr, errstr, ProgName, kernf,"no name list");
			exit(EX_SERR);
		}
		if (nfound != 0) {
			register int i;

			fprintf(stderr, "%s: nlist: unresolved symbols:",
			        ProgName);
			for (i = 0; i < X_LAST; i++)
				if (nl[i].n_type == 0)
					fprintf(stderr, " %s", nl[i].n_name);
			(void) putc('\n', stderr);
			exit(EX_SERR);
		}

		procp = (struct proc *)GetWord((off_t)nl[X_PROC].n_value);
		nproc = GetWord((off_t)nl[X_NPROC].n_value);
	}

	/*
	 * Read in NPROCS proc structures at-a-time.  Decrement `nproc'
	 * by the number of proc structures we have read; when it reaches
	 * zero, we are finished (return NULL).
	 */
	do {
		while (thisproc == 0) {
			int nread;
			int psize;

			if (nproc == 0)
				return((struct ProcInfo *)NULL);

			thisproc = MIN(NPROCS, nproc);
			psize = thisproc * sizeof(struct proc);
			nproc -= thisproc;
			if (lseek(kmem, (off_t)procp, L_SET) == -1 ||
			    (nread = read(kmem, (char *)procs, psize)) < 0) {
				fprintf(stderr, "%s: read proc: %s\n",
				        ProgName, SysErr());
				return((struct ProcInfo *)NULL);
			} else if (nread != psize) {
				thisproc = nread / sizeof(struct proc);
				nproc = 0;
				fprintf(stderr, "%s: read proc: short read\n",
				        ProgName);
			}
			procsp = procs;
			procp += thisproc;
		}

		aproc = procsp++;
		thisproc--;
		if (aproc->p_stat != 0) {
			apstun.pst_status = &apst;
			if (pstat(PSTAT_PROC, apstun, sizeof(apst), 0, 
				  aproc->p_pid) != 1)
			    aproc->p_stat = 0;
			/*
			 * Before we fill in the rest of `procinfo', let's
			 * make sure this isn't a "zombie" or "exiting"
			 * process.  If it is, we have all the information
			 * we need; fill in procinfo and return.
			 */
			procinfo.pi_flags = 0;
			procinfo.pi_pid = (pid_T) apst.pst_pid;
			procinfo.pi_uid = (uid_T) apst.pst_uid;

			if (aproc->p_stat == SZOMB) {		/* zombie */
				static char *zombie = "<defunct>";
				procinfo.pi_flags |= PI_ZOMBIE;
				procinfo.pi_cmd = zombie;
			} else if (aproc->p_flag & SWEXIT) {	/* exiting */
				static char *exiting = "<exiting>";
				procinfo.pi_flags |= PI_SWEXIT;
				procinfo.pi_cmd = exiting;
			}
			if (procinfo.pi_flags)
				return(&procinfo);
		}

	} while (aproc->p_stat == 0);

	/*
	 * We now have a process (`aproc') and process info (`apst').
	 * Fill in the rest of `procinfo'.
	 */
	if (apst.pst_term.psd_major != -1) {
		procinfo.pi_flags |= PI_CTLTTY;
		procinfo.pi_tty = (tty_T) makedev(apst.pst_term.psd_major,
						  apst.pst_term.psd_minor);
	}

	if (aproc->p_pid < pidmapsiz) {	/* special */
		procinfo.pi_cmd = pidmap[aproc->p_pid];
		procinfo.pi_flags |= PI_ASKUSR;
	} else { /* set path-stripped command name */
		char *s, *strtok();
		if ((s = strtok(apst.pst_cmd, "\n\t ")) == NULL)
			s = apst.pst_cmd;
		if (*s == '-')
			s++;
#ifdef PST_CLEN
		SETCMD(procinfo.pi_cmd, s, PST_CLEN)
#else
		SETCMD(procinfo.pi_cmd, s, MAXCOMLEN)
#endif
	}

	return(&procinfo);
}
