Index: head/contrib/top/commands.c =================================================================== --- head/contrib/top/commands.c (revision 300394) +++ head/contrib/top/commands.c (revision 300395) @@ -1,527 +1,541 @@ /* * Top users/processes display for Unix * Version 3 * * This program may be freely redistributed, * but this entire comment MUST remain intact. * * Copyright (c) 1984, 1989, William LeFebvre, Rice University * Copyright (c) 1989, 1990, 1992, William LeFebvre, Northwestern University * * $FreeBSD$ */ /* * This file contains the routines that implement some of the interactive * mode commands. Note that some of the commands are implemented in-line * in "main". This is necessary because they change the global state of * "top" (i.e.: changing the number of processes to display). */ #include "os.h" -#include -#include -#include + #include #include +#include +#include +#include +#include + +#include "commands.h" #include "sigdesc.h" /* generated automatically */ #include "top.h" #include "boolean.h" #include "utils.h" +#include "machine.h" extern int errno; extern char *copyright; /* imported from screen.c */ extern int overstrike; int err_compar(); char *err_string(); +static int str_adderr(char *str, int len, int err); +static int str_addarg(char *str, int len, char *arg, int first); /* * show_help() - display the help screen; invoked in response to * either 'h' or '?'. */ +void show_help() { printf("Top version %s, %s\n", version_string(), copyright); fputs("\n\n\ A top users display for Unix\n\ \n\ These single-character commands are available:\n\ \n\ ^L - redraw screen\n\ q - quit\n\ h or ? - help; show this text\n", stdout); /* not all commands are availalbe with overstrike terminals */ if (overstrike) { fputs("\n\ Other commands are also available, but this terminal is not\n\ sophisticated enough to handle those commands gracefully.\n\n", stdout); } else { fputs("\ C - toggle the displaying of weighted CPU percentage\n\ d - change number of displays to show\n\ e - list errors generated by last \"kill\" or \"renice\" command\n\ H - toggle the displaying of threads\n\ i or I - toggle the displaying of idle processes\n\ j - toggle the displaying of jail ID\n\ J - display processes for only one jail (+ selects all jails)\n\ k - kill processes; send a signal to a list of processes\n\ m - toggle the display between 'cpu' and 'io' modes\n\ n or # - change number of processes to display\n", stdout); #ifdef ORDER if (displaymode == DISP_CPU) fputs("\ o - specify sort order (pri, size, res, cpu, time, threads, jid, pid)\n", stdout); else fputs("\ o - specify sort order (vcsw, ivcsw, read, write, fault, total, jid, pid)\n", stdout); #endif fputs("\ P - toggle the displaying of per-CPU statistics\n\ r - renice a process\n\ s - change number of seconds to delay between updates\n\ S - toggle the displaying of system processes\n\ a - toggle the displaying of process titles\n\ t - toggle the display of this process\n\ u - display processes for only one user (+ selects all users)\n\ z - toggle the displaying of the system idle process\n\ \n\ \n", stdout); } } /* * Utility routines that help with some of the commands. */ char *next_field(str) register char *str; { if ((str = strchr(str, ' ')) == NULL) { return(NULL); } *str = '\0'; while (*++str == ' ') /* loop */; /* if there is nothing left of the string, return NULL */ /* This fix is dedicated to Greg Earle */ return(*str == '\0' ? NULL : str); } +int scanint(str, intp) char *str; int *intp; { register int val = 0; register char ch; /* if there is nothing left of the string, flag it as an error */ /* This fix is dedicated to Greg Earle */ if (*str == '\0') { return(-1); } while ((ch = *str++) != '\0') { if (isdigit(ch)) { val = val * 10 + (ch - '0'); } else if (isspace(ch)) { break; } else { return(-1); } } *intp = val; return(0); } /* * Some of the commands make system calls that could generate errors. * These errors are collected up in an array of structures for later * contemplation and display. Such routines return a string containing an * error message, or NULL if no errors occurred. The next few routines are * for manipulating and displaying these errors. We need an upper limit on * the number of errors, so we arbitrarily choose 20. */ #define ERRMAX 20 struct errs /* structure for a system-call error */ { int errnum; /* value of errno (that is, the actual error) */ char *arg; /* argument that caused the error */ }; static struct errs errs[ERRMAX]; static int errcnt; static char *err_toomany = " too many errors occurred"; static char *err_listem = " Many errors occurred. Press `e' to display the list of errors."; /* These macros get used to reset and log the errors */ #define ERR_RESET errcnt = 0 #define ERROR(p, e) if (errcnt >= ERRMAX) \ { \ return(err_toomany); \ } \ else \ { \ errs[errcnt].arg = (p); \ errs[errcnt++].errnum = (e); \ } /* * err_string() - return an appropriate error string. This is what the * command will return for displaying. If no errors were logged, then * return NULL. The maximum length of the error string is defined by * "STRMAX". */ #define STRMAX 80 char *err_string() { register struct errs *errp; register int cnt = 0; register int first = Yes; register int currerr = -1; int stringlen; /* characters still available in "string" */ static char string[STRMAX]; /* if there are no errors, return NULL */ if (errcnt == 0) { return(NULL); } /* sort the errors */ qsort((char *)errs, errcnt, sizeof(struct errs), err_compar); /* need a space at the front of the error string */ string[0] = ' '; string[1] = '\0'; stringlen = STRMAX - 2; /* loop thru the sorted list, building an error string */ while (cnt < errcnt) { errp = &(errs[cnt++]); if (errp->errnum != currerr) { if (currerr != -1) { if ((stringlen = str_adderr(string, stringlen, currerr)) < 2) { return(err_listem); } (void) strcat(string, "; "); /* we know there's more */ } currerr = errp->errnum; first = Yes; } if ((stringlen = str_addarg(string, stringlen, errp->arg, first)) ==0) { return(err_listem); } first = No; } /* add final message */ stringlen = str_adderr(string, stringlen, currerr); /* return the error string */ return(stringlen == 0 ? err_listem : string); } /* * str_adderr(str, len, err) - add an explanation of error "err" to * the string "str". */ +static int str_adderr(str, len, err) char *str; int len; int err; { register char *msg; register int msglen; msg = err == 0 ? "Not a number" : errmsg(err); msglen = strlen(msg) + 2; if (len <= msglen) { return(0); } (void) strcat(str, ": "); (void) strcat(str, msg); return(len - msglen); } /* * str_addarg(str, len, arg, first) - add the string argument "arg" to * the string "str". This is the first in the group when "first" * is set (indicating that a comma should NOT be added to the front). */ +static int str_addarg(str, len, arg, first) char *str; int len; char *arg; int first; { register int arglen; arglen = strlen(arg); if (!first) { arglen += 2; } if (len <= arglen) { return(0); } if (!first) { (void) strcat(str, ", "); } (void) strcat(str, arg); return(len - arglen); } /* * err_compar(p1, p2) - comparison routine used by "qsort" * for sorting errors. */ +int err_compar(p1, p2) register struct errs *p1, *p2; { register int result; if ((result = p1->errnum - p2->errnum) == 0) { return(strcmp(p1->arg, p2->arg)); } return(result); } /* * error_count() - return the number of errors currently logged. */ +int error_count() { return(errcnt); } /* * show_errors() - display on stdout the current log of errors. */ +void show_errors() { register int cnt = 0; register struct errs *errp = errs; printf("%d error%s:\n\n", errcnt, errcnt == 1 ? "" : "s"); while (cnt++ < errcnt) { printf("%5s: %s\n", errp->arg, errp->errnum == 0 ? "Not a number" : errmsg(errp->errnum)); errp++; } } /* * kill_procs(str) - send signals to processes, much like the "kill" * command does; invoked in response to 'k'. */ char *kill_procs(str) char *str; { register char *nptr; int signum = SIGTERM; /* default */ int procnum; struct sigdesc *sigp; int uid; /* reset error array */ ERR_RESET; /* remember our uid */ uid = getuid(); /* skip over leading white space */ while (isspace(*str)) str++; if (str[0] == '-') { /* explicit signal specified */ if ((nptr = next_field(str)) == NULL) { return(" kill: no processes specified"); } if (isdigit(str[1])) { (void) scanint(str + 1, &signum); if (signum <= 0 || signum >= NSIG) { return(" invalid signal number"); } } else { /* translate the name into a number */ for (sigp = sigdesc; sigp->name != NULL; sigp++) { if (strcmp(sigp->name, str + 1) == 0) { signum = sigp->number; break; } } /* was it ever found */ if (sigp->name == NULL) { return(" bad signal name"); } } /* put the new pointer in place */ str = nptr; } /* loop thru the string, killing processes */ do { if (scanint(str, &procnum) == -1) { ERROR(str, 0); } else { /* check process owner if we're not root */ if (uid && (uid != proc_owner(procnum))) { ERROR(str, EACCES); } /* go in for the kill */ else if (kill(procnum, signum) == -1) { /* chalk up an error */ ERROR(str, errno); } } } while ((str = next_field(str)) != NULL); /* return appropriate error string */ return(err_string()); } /* * renice_procs(str) - change the "nice" of processes, much like the * "renice" command does; invoked in response to 'r'. */ char *renice_procs(str) char *str; { register char negate; int prio; int procnum; int uid; ERR_RESET; uid = getuid(); /* allow for negative priority values */ if ((negate = (*str == '-')) != 0) { /* move past the minus sign */ str++; } /* use procnum as a temporary holding place and get the number */ procnum = scanint(str, &prio); /* negate if necessary */ if (negate) { prio = -prio; } #if defined(PRIO_MIN) && defined(PRIO_MAX) /* check for validity */ if (procnum == -1 || prio < PRIO_MIN || prio > PRIO_MAX) { return(" bad priority value"); } #endif /* move to the first process number */ if ((str = next_field(str)) == NULL) { return(" no processes specified"); } /* loop thru the process numbers, renicing each one */ do { if (scanint(str, &procnum) == -1) { ERROR(str, 0); } /* check process owner if we're not root */ else if (uid && (uid != proc_owner(procnum))) { ERROR(str, EACCES); } else if (setpriority(PRIO_PROCESS, procnum, prio) == -1) { ERROR(str, errno); } } while ((str = next_field(str)) != NULL); /* return appropriate error string */ return(err_string()); } Index: head/contrib/top/commands.h =================================================================== --- head/contrib/top/commands.h (nonexistent) +++ head/contrib/top/commands.h (revision 300395) @@ -0,0 +1,21 @@ +/* + * Top users/processes display for Unix + * Version 3 + * + * This program may be freely redistributed, + * but this entire comment MUST remain intact. + * + * Copyright (c) 1984, 1989, William LeFebvre, Rice University + * Copyright (c) 1989, 1990, 1992, William LeFebvre, Northwestern University + * Copyright (c) 2016, Randy Westlund + * + * $FreeBSD$ + */ +#ifndef COMMANDS_H +#define COMMANDS_H + +void show_errors(void); +int error_count(void); +void show_help(void); + +#endif /* COMMANDS_H */ Property changes on: head/contrib/top/commands.h ___________________________________________________________________ Added: svn:eol-style ## -0,0 +1 ## +native \ No newline at end of property Added: svn:keywords ## -0,0 +1 ## +FreeBSD=%H \ No newline at end of property Added: svn:mime-type ## -0,0 +1 ## +text/plain \ No newline at end of property Index: head/contrib/top/display.c =================================================================== --- head/contrib/top/display.c (revision 300394) +++ head/contrib/top/display.c (revision 300395) @@ -1,1371 +1,1399 @@ /* * Top users/processes display for Unix * Version 3 * * This program may be freely redistributed, * but this entire comment MUST remain intact. * * Copyright (c) 1984, 1989, William LeFebvre, Rice University * Copyright (c) 1989, 1990, 1992, William LeFebvre, Northwestern University * * $FreeBSD$ */ /* * This file contains the routines that display information on the screen. * Each section of the screen has two routines: one for initially writing * all constant and dynamic text, and one for only updating the text that * changes. The prefix "i_" is used on all the "initial" routines and the * prefix "u_" is used for all the "updating" routines. * * ASSUMPTIONS: * None of the "i_" routines use any of the termcap capabilities. * In this way, those routines can be safely used on terminals that * have minimal (or nonexistant) terminal capabilities. * * The routines are called in this order: *_loadave, i_timeofday, * *_procstates, *_cpustates, *_memory, *_message, *_header, * *_process, u_endscreen. */ #include "os.h" + +#include + #include #include -#include +#include #include "screen.h" /* interface to screen package */ #include "layout.h" /* defines for screen position layout */ #include "display.h" #include "top.h" #include "top.local.h" #include "boolean.h" #include "machine.h" /* we should eliminate this!!! */ #include "utils.h" #ifdef DEBUG FILE *debug; #endif /* imported from screen.c */ extern int overstrike; static int lmpid = 0; static int last_hi = 0; /* used in u_process and u_endscreen */ static int lastline = 0; static int display_width = MAX_COLS; #define lineindex(l) ((l)*display_width) -char *printable(); /* things initialized by display_init and used thruout */ /* buffer of proc information lines for display updating */ char *screenbuf = NULL; static char **procstate_names; static char **cpustate_names; static char **memory_names; static char **arc_names; static char **swap_names; static int num_procstates; static int num_cpustates; static int num_memory; static int num_swap; static int *lprocstates; static int *lcpustates; static int *lmemory; static int *lswap; static int num_cpus; static int *cpustate_columns; static int cpustate_total_length; static int cpustates_column; static enum { OFF, ON, ERASE } header_status = ON; static int string_count(); static void summary_format(); static void line_update(); int x_lastpid = 10; int y_lastpid = 0; int x_loadave = 33; int x_loadave_nompid = 15; int y_loadave = 0; int x_procstate = 0; int y_procstate = 1; int x_brkdn = 15; int y_brkdn = 1; int x_mem = 5; int y_mem = 3; int x_arc = 5; int y_arc = 4; int x_swap = 6; int y_swap = 4; int y_message = 5; int x_header = 0; int y_header = 6; int x_idlecursor = 0; int y_idlecursor = 5; int y_procs = 7; int y_cpustates = 2; int Header_lines = 7; int display_resize() { register int lines; /* first, deallocate any previous buffer that may have been there */ if (screenbuf != NULL) { free(screenbuf); } /* calculate the current dimensions */ /* if operating in "dumb" mode, we only need one line */ lines = smart_terminal ? screen_length - Header_lines : 1; if (lines < 0) lines = 0; /* we don't want more than MAX_COLS columns, since the machine-dependent modules make static allocations based on MAX_COLS and we don't want to run off the end of their buffers */ display_width = screen_width; if (display_width >= MAX_COLS) { display_width = MAX_COLS - 1; } /* now, allocate space for the screen buffer */ screenbuf = (char *)malloc(lines * display_width); if (screenbuf == (char *)NULL) { /* oops! */ return(-1); } /* return number of lines available */ /* for dumb terminals, pretend like we can show any amount */ return(smart_terminal ? lines : Largest); } int display_updatecpus(statics) struct statics *statics; { register int *lp; register int lines; register int i; /* call resize to do the dirty work */ lines = display_resize(); if (pcpu_stats) num_cpus = statics->ncpus; else num_cpus = 1; cpustates_column = 5; /* CPU: */ if (num_cpus != 1) cpustates_column += 2; /* CPU 0: */ for (i = num_cpus; i > 9; i /= 10) cpustates_column++; /* fill the "last" array with all -1s, to insure correct updating */ lp = lcpustates; i = num_cpustates * num_cpus; while (--i >= 0) { *lp++ = -1; } return(lines); } int display_init(statics) struct statics *statics; { register int lines; register char **pp; register int *ip; register int i; lines = display_updatecpus(statics); /* only do the rest if we need to */ if (lines > -1) { /* save pointers and allocate space for names */ procstate_names = statics->procstate_names; num_procstates = string_count(procstate_names); lprocstates = (int *)malloc(num_procstates * sizeof(int)); cpustate_names = statics->cpustate_names; swap_names = statics->swap_names; num_swap = string_count(swap_names); lswap = (int *)malloc(num_swap * sizeof(int)); num_cpustates = string_count(cpustate_names); lcpustates = (int *)malloc(num_cpustates * sizeof(int) * statics->ncpus); cpustate_columns = (int *)malloc(num_cpustates * sizeof(int)); memory_names = statics->memory_names; num_memory = string_count(memory_names); lmemory = (int *)malloc(num_memory * sizeof(int)); arc_names = statics->arc_names; /* calculate starting columns where needed */ cpustate_total_length = 0; pp = cpustate_names; ip = cpustate_columns; while (*pp != NULL) { *ip++ = cpustate_total_length; if ((i = strlen(*pp++)) > 0) { cpustate_total_length += i + 8; } } } /* return number of lines available */ return(lines); } +void i_loadave(mpid, avenrun) int mpid; double *avenrun; { register int i; /* i_loadave also clears the screen, since it is first */ clear(); /* mpid == -1 implies this system doesn't have an _mpid */ if (mpid != -1) { printf("last pid: %5d; ", mpid); } printf("load averages"); for (i = 0; i < 3; i++) { printf("%c %5.2f", i == 0 ? ':' : ',', avenrun[i]); } lmpid = mpid; } +void u_loadave(mpid, avenrun) int mpid; double *avenrun; { register int i; if (mpid != -1) { /* change screen only when value has really changed */ if (mpid != lmpid) { Move_to(x_lastpid, y_lastpid); printf("%5d", mpid); lmpid = mpid; } /* i remembers x coordinate to move to */ i = x_loadave; } else { i = x_loadave_nompid; } /* move into position for load averages */ Move_to(i, y_loadave); /* display new load averages */ /* we should optimize this and only display changes */ for (i = 0; i < 3; i++) { printf("%s%5.2f", i == 0 ? "" : ", ", avenrun[i]); } } +void i_timeofday(tod) time_t *tod; { /* * Display the current time. * "ctime" always returns a string that looks like this: * * Sun Sep 16 01:03:52 1973 * 012345678901234567890123 * 1 2 * * We want indices 11 thru 18 (length 8). */ if (smart_terminal) { Move_to(screen_width - 8, 0); } else { fputs(" ", stdout); } #ifdef DEBUG { char *foo; foo = ctime(tod); fputs(foo, stdout); } #endif printf("%-8.8s\n", &(ctime(tod)[11])); lastline = 1; } static int ltotal = 0; static char procstates_buffer[MAX_COLS]; /* * *_procstates(total, brkdn, names) - print the process summary line * * Assumptions: cursor is at the beginning of the line on entry * lastline is valid */ +void i_procstates(total, brkdn) int total; int *brkdn; { register int i; /* write current number of processes and remember the value */ printf("%d processes:", total); ltotal = total; /* put out enough spaces to get to column 15 */ i = digits(total); while (i++ < 4) { putchar(' '); } /* format and print the process state summary */ summary_format(procstates_buffer, brkdn, procstate_names); fputs(procstates_buffer, stdout); /* save the numbers for next time */ memcpy(lprocstates, brkdn, num_procstates * sizeof(int)); } +void u_procstates(total, brkdn) int total; int *brkdn; { static char new[MAX_COLS]; register int i; /* update number of processes only if it has changed */ if (ltotal != total) { /* move and overwrite */ #if (x_procstate == 0) Move_to(x_procstate, y_procstate); #else /* cursor is already there...no motion needed */ /* assert(lastline == 1); */ #endif printf("%d", total); /* if number of digits differs, rewrite the label */ if (digits(total) != digits(ltotal)) { fputs(" processes:", stdout); /* put out enough spaces to get to column 15 */ i = digits(total); while (i++ < 4) { putchar(' '); } /* cursor may end up right where we want it!!! */ } /* save new total */ ltotal = total; } /* see if any of the state numbers has changed */ if (memcmp(lprocstates, brkdn, num_procstates * sizeof(int)) != 0) { /* format and update the line */ summary_format(new, brkdn, procstate_names); line_update(procstates_buffer, new, x_brkdn, y_brkdn); memcpy(lprocstates, brkdn, num_procstates * sizeof(int)); } } #ifdef no_more /* * *_cpustates(states, names) - print the cpu state percentages * * Assumptions: cursor is on the PREVIOUS line */ /* cpustates_tag() calculates the correct tag to use to label the line */ char *cpustates_tag() { register char *use; static char *short_tag = "CPU: "; static char *long_tag = "CPU states: "; /* if length + strlen(long_tag) >= screen_width, then we have to use the shorter tag (we subtract 2 to account for ": ") */ if (cpustate_total_length + (int)strlen(long_tag) - 2 >= screen_width) { use = short_tag; } else { use = long_tag; } /* set cpustates_column accordingly then return result */ cpustates_column = strlen(use); return(use); } #endif +void i_cpustates(states) -register int *states; +int *states; { register int i = 0; register int value; register char **names; register char *thisname; int cpu; for (cpu = 0; cpu < num_cpus; cpu++) { names = cpustate_names; /* print tag and bump lastline */ if (num_cpus == 1) printf("\nCPU: "); else { value = printf("\nCPU %d: ", cpu); while (value++ <= cpustates_column) printf(" "); } lastline++; /* now walk thru the names and print the line */ while ((thisname = *names++) != NULL) { if (*thisname != '\0') { /* retrieve the value and remember it */ value = *states++; /* if percentage is >= 1000, print it as 100% */ printf((value >= 1000 ? "%s%4.0f%% %s" : "%s%4.1f%% %s"), (i++ % num_cpustates) == 0 ? "" : ", ", ((float)value)/10., thisname); } } } /* copy over values into "last" array */ memcpy(lcpustates, states, num_cpustates * sizeof(int) * num_cpus); } +void u_cpustates(states) -register int *states; +int *states; { register int value; register char **names; register char *thisname; register int *lp; register int *colp; int cpu; for (cpu = 0; cpu < num_cpus; cpu++) { names = cpustate_names; Move_to(cpustates_column, y_cpustates + cpu); lastline = y_cpustates + cpu; lp = lcpustates + (cpu * num_cpustates); colp = cpustate_columns; /* we could be much more optimal about this */ while ((thisname = *names++) != NULL) { if (*thisname != '\0') { /* did the value change since last time? */ if (*lp != *states) { /* yes, move and change */ Move_to(cpustates_column + *colp, y_cpustates + cpu); lastline = y_cpustates + cpu; /* retrieve value and remember it */ value = *states; /* if percentage is >= 1000, print it as 100% */ printf((value >= 1000 ? "%4.0f" : "%4.1f"), ((double)value)/10.); /* remember it for next time */ *lp = value; } } /* increment and move on */ lp++; states++; colp++; } } } +void z_cpustates() { register int i = 0; register char **names; register char *thisname; register int *lp; int cpu, value; for (cpu = 0; cpu < num_cpus; cpu++) { names = cpustate_names; /* show tag and bump lastline */ if (num_cpus == 1) printf("\nCPU: "); else { value = printf("\nCPU %d: ", cpu); while (value++ <= cpustates_column) printf(" "); } lastline++; while ((thisname = *names++) != NULL) { if (*thisname != '\0') { printf("%s %% %s", (i++ % num_cpustates) == 0 ? "" : ", ", thisname); } } } /* fill the "last" array with all -1s, to insure correct updating */ lp = lcpustates; i = num_cpustates * num_cpus; while (--i >= 0) { *lp++ = -1; } } /* * *_memory(stats) - print "Memory: " followed by the memory summary string * * Assumptions: cursor is on "lastline" * for i_memory ONLY: cursor is on the previous line */ char memory_buffer[MAX_COLS]; +void i_memory(stats) int *stats; { fputs("\nMem: ", stdout); lastline++; /* format and print the memory summary */ summary_format(memory_buffer, stats, memory_names); fputs(memory_buffer, stdout); } +void u_memory(stats) int *stats; { static char new[MAX_COLS]; /* format the new line */ summary_format(new, stats, memory_names); line_update(memory_buffer, new, x_mem, y_mem); } /* * *_arc(stats) - print "ARC: " followed by the ARC summary string * * Assumptions: cursor is on "lastline" * for i_arc ONLY: cursor is on the previous line */ char arc_buffer[MAX_COLS]; +void i_arc(stats) int *stats; { if (arc_names == NULL) - return (0); + return; fputs("\nARC: ", stdout); lastline++; /* format and print the memory summary */ summary_format(arc_buffer, stats, arc_names); fputs(arc_buffer, stdout); } +void u_arc(stats) int *stats; { static char new[MAX_COLS]; if (arc_names == NULL) - return (0); + return; /* format the new line */ summary_format(new, stats, arc_names); line_update(arc_buffer, new, x_arc, y_arc); } /* * *_swap(stats) - print "Swap: " followed by the swap summary string * * Assumptions: cursor is on "lastline" * for i_swap ONLY: cursor is on the previous line */ char swap_buffer[MAX_COLS]; +void i_swap(stats) int *stats; { fputs("\nSwap: ", stdout); lastline++; /* format and print the swap summary */ summary_format(swap_buffer, stats, swap_names); fputs(swap_buffer, stdout); } +void u_swap(stats) int *stats; { static char new[MAX_COLS]; /* format the new line */ summary_format(new, stats, swap_names); line_update(swap_buffer, new, x_swap, y_swap); } /* * *_message() - print the next pending message line, or erase the one * that is there. * * Note that u_message is (currently) the same as i_message. * * Assumptions: lastline is consistent */ /* * i_message is funny because it gets its message asynchronously (with * respect to screen updates). */ static char next_msg[MAX_COLS + 5]; static int msglen = 0; /* Invariant: msglen is always the length of the message currently displayed on the screen (even when next_msg doesn't contain that message). */ +void i_message() { while (lastline < y_message) { fputc('\n', stdout); lastline++; } if (next_msg[0] != '\0') { standout(next_msg); msglen = strlen(next_msg); next_msg[0] = '\0'; } else if (msglen > 0) { (void) clear_eol(msglen); msglen = 0; } } +void u_message() { i_message(); } static int header_length; /* * Trim a header string to the current display width and return a newly * allocated area with the trimmed header. */ char * trim_header(text) char *text; { char *s; int width; s = NULL; width = display_width; header_length = strlen(text); if (header_length >= width) { s = malloc((width + 1) * sizeof(char)); if (s == NULL) return (NULL); strncpy(s, text, width); s[width] = '\0'; } return (s); } /* * *_header(text) - print the header for the process area * * Assumptions: cursor is on the previous line and lastline is consistent */ +void i_header(text) char *text; { char *s; s = trim_header(text); if (s != NULL) text = s; if (header_status == ON) { putchar('\n'); fputs(text, stdout); lastline++; } else if (header_status == ERASE) { header_status = OFF; } free(s); } /*ARGSUSED*/ +void u_header(text) -char *text; /* ignored */ +char *text __unused; /* ignored */ { if (header_status == ERASE) { putchar('\n'); lastline++; clear_eol(header_length); header_status = OFF; } } /* * *_process(line, thisline) - print one process line * * Assumptions: lastline is consistent */ +void i_process(line, thisline) int line; char *thisline; { register char *p; register char *base; /* make sure we are on the correct line */ while (lastline < y_procs + line) { putchar('\n'); lastline++; } /* truncate the line to conform to our current screen width */ thisline[display_width] = '\0'; /* write the line out */ fputs(thisline, stdout); /* copy it in to our buffer */ base = smart_terminal ? screenbuf + lineindex(line) : screenbuf; p = strecpy(base, thisline); /* zero fill the rest of it */ memzero(p, display_width - (p - base)); } +void u_process(line, newline) int line; char *newline; { register char *optr; register int screen_line = line + Header_lines; register char *bufferline; /* remember a pointer to the current line in the screen buffer */ bufferline = &screenbuf[lineindex(line)]; /* truncate the line to conform to our current screen width */ newline[display_width] = '\0'; /* is line higher than we went on the last display? */ if (line >= last_hi) { /* yes, just ignore screenbuf and write it out directly */ /* get positioned on the correct line */ if (screen_line - lastline == 1) { putchar('\n'); lastline++; } else { Move_to(0, screen_line); lastline = screen_line; } /* now write the line */ fputs(newline, stdout); /* copy it in to the buffer */ optr = strecpy(bufferline, newline); /* zero fill the rest of it */ memzero(optr, display_width - (optr - bufferline)); } else { line_update(bufferline, newline, 0, line + Header_lines); } } +void u_endscreen(hi) -register int hi; +int hi; { register int screen_line = hi + Header_lines; register int i; if (smart_terminal) { if (hi < last_hi) { /* need to blank the remainder of the screen */ /* but only if there is any screen left below this line */ if (lastline + 1 < screen_length) { /* efficiently move to the end of currently displayed info */ if (screen_line - lastline < 5) { while (lastline < screen_line) { putchar('\n'); lastline++; } } else { Move_to(0, screen_line); lastline = screen_line; } if (clear_to_end) { /* we can do this the easy way */ putcap(clear_to_end); } else { /* use clear_eol on each line */ i = hi; while ((void) clear_eol(strlen(&screenbuf[lineindex(i++)])), i < last_hi) { putchar('\n'); } } } } last_hi = hi; /* move the cursor to a pleasant place */ Move_to(x_idlecursor, y_idlecursor); lastline = y_idlecursor; } else { /* separate this display from the next with some vertical room */ fputs("\n\n", stdout); } } +void display_header(t) int t; { if (t) { header_status = ON; } else if (header_status == ON) { header_status = ERASE; } } /*VARARGS2*/ +void new_message(type, msgfmt, a1, a2, a3) int type; char *msgfmt; caddr_t a1, a2, a3; { register int i; /* first, format the message */ (void) snprintf(next_msg, sizeof(next_msg), msgfmt, a1, a2, a3); if (msglen > 0) { /* message there already -- can we clear it? */ if (!overstrike) { /* yes -- write it and clear to end */ i = strlen(next_msg); if ((type & MT_delayed) == 0) { type & MT_standout ? standout(next_msg) : fputs(next_msg, stdout); (void) clear_eol(msglen - i); msglen = i; next_msg[0] = '\0'; } } } else { if ((type & MT_delayed) == 0) { type & MT_standout ? standout(next_msg) : fputs(next_msg, stdout); msglen = strlen(next_msg); next_msg[0] = '\0'; } } } +void clear_message() { if (clear_eol(msglen) == 1) { putchar('\r'); } } +int readline(buffer, size, numeric) char *buffer; int size; int numeric; { register char *ptr = buffer; register char ch; register char cnt = 0; register char maxcnt = 0; /* allow room for null terminator */ size -= 1; /* read loop */ while ((fflush(stdout), read(0, ptr, 1) > 0)) { /* newline means we are done */ if ((ch = *ptr) == '\n' || ch == '\r') { break; } /* handle special editing characters */ if (ch == ch_kill) { /* kill line -- account for overstriking */ if (overstrike) { msglen += maxcnt; } /* return null string */ *buffer = '\0'; putchar('\r'); return(-1); } else if (ch == ch_erase) { /* erase previous character */ if (cnt <= 0) { /* none to erase! */ putchar('\7'); } else { fputs("\b \b", stdout); ptr--; cnt--; } } /* check for character validity and buffer overflow */ else if (cnt == size || (numeric && !isdigit(ch)) || !isprint(ch)) { /* not legal */ putchar('\7'); } else { /* echo it and store it in the buffer */ putchar(ch); ptr++; cnt++; if (cnt > maxcnt) { maxcnt = cnt; } } } /* all done -- null terminate the string */ *ptr = '\0'; /* account for the extra characters in the message area */ /* (if terminal overstrikes, remember the furthest they went) */ msglen += overstrike ? maxcnt : cnt; /* return either inputted number or string length */ putchar('\r'); return(cnt == 0 ? -1 : numeric ? atoi(buffer) : cnt); } /* internal support routines */ static int string_count(pp) register char **pp; { register int cnt; cnt = 0; while (*pp++ != NULL) { cnt++; } return(cnt); } static void summary_format(str, numbers, names) char *str; int *numbers; register char **names; { register char *p; register int num; register char *thisname; register int useM = No; /* format each number followed by its string */ p = str; while ((thisname = *names++) != NULL) { /* get the number to format */ num = *numbers++; /* display only non-zero numbers */ if (num > 0) { /* is this number in kilobytes? */ if (thisname[0] == 'K') { /* yes: format it as a memory value */ p = strecpy(p, format_k(num)); /* skip over the K, since it was included by format_k */ p = strecpy(p, thisname+1); } else { p = strecpy(p, itoa(num)); p = strecpy(p, thisname); } } /* ignore negative numbers, but display corresponding string */ else if (num < 0) { p = strecpy(p, thisname); } } /* if the last two characters in the string are ", ", delete them */ p -= 2; if (p >= str && p[0] == ',' && p[1] == ' ') { *p = '\0'; } } static void line_update(old, new, start, line) register char *old; register char *new; int start; int line; { register int ch; register int diff; register int newcol = start + 1; register int lastcol = start; char cursor_on_line = No; char *current; /* compare the two strings and only rewrite what has changed */ current = old; #ifdef DEBUG fprintf(debug, "line_update, starting at %d\n", start); fputs(old, debug); fputc('\n', debug); fputs(new, debug); fputs("\n-\n", debug); #endif /* start things off on the right foot */ /* this is to make sure the invariants get set up right */ if ((ch = *new++) != *old) { if (line - lastline == 1 && start == 0) { putchar('\n'); } else { Move_to(start, line); } cursor_on_line = Yes; putchar(ch); *old = ch; lastcol = 1; } old++; /* * main loop -- check each character. If the old and new aren't the * same, then update the display. When the distance from the * current cursor position to the new change is small enough, * the characters that belong there are written to move the * cursor over. * * Invariants: * lastcol is the column where the cursor currently is sitting * (always one beyond the end of the last mismatch). */ do /* yes, a do...while */ { if ((ch = *new++) != *old) { /* new character is different from old */ /* make sure the cursor is on top of this character */ diff = newcol - lastcol; if (diff > 0) { /* some motion is required--figure out which is shorter */ if (diff < 6 && cursor_on_line) { /* overwrite old stuff--get it out of the old buffer */ printf("%.*s", diff, ¤t[lastcol-start]); } else { /* use cursor addressing */ Move_to(newcol, line); cursor_on_line = Yes; } /* remember where the cursor is */ lastcol = newcol + 1; } else { /* already there, update position */ lastcol++; } /* write what we need to */ if (ch == '\0') { /* at the end--terminate with a clear-to-end-of-line */ (void) clear_eol(strlen(old)); } else { /* write the new character */ putchar(ch); } /* put the new character in the screen buffer */ *old = ch; } /* update working column and screen buffer pointer */ newcol++; old++; } while (ch != '\0'); /* zero out the rest of the line buffer -- MUST BE DONE! */ diff = display_width - newcol; if (diff > 0) { memzero(old, diff); } /* remember where the current line is */ if (cursor_on_line) { lastline = line; } } /* * printable(str) - make the string pointed to by "str" into one that is * printable (i.e.: all ascii), by converting all non-printable * characters into '?'. Replacements are done in place and a pointer * to the original buffer is returned. */ char *printable(str) char *str; { register char *ptr; register char ch; ptr = str; while ((ch = *ptr) != '\0') { if (!isprint(ch)) { *ptr = '?'; } ptr++; } return(str); } +void i_uptime(bt, tod) struct timeval* bt; time_t *tod; { time_t uptime; int days, hrs, mins, secs; if (bt->tv_sec != -1) { uptime = *tod - bt->tv_sec; days = uptime / 86400; uptime %= 86400; hrs = uptime / 3600; uptime %= 3600; mins = uptime / 60; secs = uptime % 60; /* * Display the uptime. */ if (smart_terminal) { Move_to((screen_width - 24) - (days > 9 ? 1 : 0), 0); } else { fputs(" ", stdout); } printf(" up %d+%02d:%02d:%02d", days, hrs, mins, secs); } } Index: head/contrib/top/display.h =================================================================== --- head/contrib/top/display.h (revision 300394) +++ head/contrib/top/display.h (revision 300395) @@ -1,7 +1,41 @@ /* constants needed for display.c */ /* "type" argument for new_message function */ #define MT_standout 1 #define MT_delayed 2 +#include "machine.h" + +int display_updatecpus(struct statics *statics); +void clear_message(void); +int display_resize(void); +void i_header(char *text); +char *printable(char *string); +char *cpustates_tag(void); +void display_header(int t); +int display_init(struct statics *statics); +void i_arc(int *stats); +void i_cpustates(int *states); +void i_loadave(int mpid, double *avenrun); +void i_memory(int *stats); +void i_message(void); +void i_process(int line, char *thisline); +void i_procstates(int total, int *brkdn); +void i_swap(int *stats); +void i_timeofday(time_t *tod); +void i_uptime(struct timeval *bt, time_t *tod); +void new_message(); +int readline(char *buffer, int size, int numeric); +char *trim_header(char *text); +void u_arc(int *stats); +void u_cpustates(int *states); +void u_endscreen(int hi); +void u_header(char *text); +void u_loadave(int mpid, double *avenrun); +void u_memory(int *stats); +void u_message(void); +void u_process(int line, char *newline); +void u_procstates(int total, int *brkdn); +void u_swap(int *stats); +void z_cpustates(void); Index: head/contrib/top/machine.h =================================================================== --- head/contrib/top/machine.h (revision 300394) +++ head/contrib/top/machine.h (revision 300395) @@ -1,81 +1,91 @@ /* * $FreeBSD$ */ /* * This file defines the interface between top and the machine-dependent * module. It is NOT machine dependent and should not need to be changed * for any specific machine. */ +#ifndef MACHINE_H +#define MACHINE_H +#include "top.h" + /* * the statics struct is filled in by machine_init */ struct statics { char **procstate_names; char **cpustate_names; char **memory_names; char **arc_names; char **swap_names; #ifdef ORDER char **order_names; #endif int ncpus; }; /* * the system_info struct is filled in by a machine dependent routine. */ #ifdef p_active /* uw7 define macro p_active */ #define P_ACTIVE p_pactive #else #define P_ACTIVE p_active #endif struct system_info { int last_pid; double load_avg[NUM_AVERAGES]; int p_total; int P_ACTIVE; /* number of procs considered "active" */ int *procstates; int *cpustates; int *memory; int *arc; int *swap; struct timeval boottime; int ncpus; }; /* cpu_states is an array of percentages * 10. For example, the (integer) value 105 is 10.5% (or .105). */ /* * the process_select struct tells get_process_info what processes we * are interested in seeing */ struct process_select { int idle; /* show idle processes */ int self; /* show self */ int system; /* show system processes */ int thread; /* show threads */ int uid; /* only this uid (unless uid == -1) */ int wcpu; /* show weighted cpu */ int jid; /* only this jid (unless jid == -1) */ int jail; /* show jail ID */ int kidle; /* show per-CPU idle threads */ char *command; /* only this command (unless == NULL) */ }; /* routines defined by the machine dependent module */ -char *format_header(); -char *format_next_process(); +char *format_header(); +char *format_next_process(); +void toggle_pcpustats(void); +void get_system_info(struct system_info *si); +int machine_init(struct statics *statics, char do_unames); +int proc_owner(int pid); /* non-int routines typically used by the machine dependent module */ -char *printable(); +char *printable(); + +#endif /* MACHINE_H */ Index: head/contrib/top/screen.c =================================================================== --- head/contrib/top/screen.c (revision 300394) +++ head/contrib/top/screen.c (revision 300395) @@ -1,499 +1,507 @@ /* * Top users/processes display for Unix * Version 3 * * This program may be freely redistributed, * but this entire comment MUST remain intact. * * Copyright (c) 1984, 1989, William LeFebvre, Rice University * Copyright (c) 1989, 1990, 1992, William LeFebvre, Northwestern University * * $FreeBSD$ */ /* This file contains the routines that interface to termcap and stty/gtty. * * Paul Vixie, February 1987: converted to use ioctl() instead of stty/gtty. * * I put in code to turn on the TOSTOP bit while top was running, but I * didn't really like the results. If you desire it, turn on the * preprocessor variable "TOStop". --wnl */ #include "os.h" #include "top.h" #include #ifdef CBREAK # include # define SGTTY #else # ifdef TCGETA # define TERMIO # include # else # define TERMIOS # include # endif #endif #if defined(TERMIO) || defined(TERMIOS) # ifndef TAB3 # ifdef OXTABS # define TAB3 OXTABS # else # define TAB3 0 # endif # endif #endif #include "screen.h" #include "boolean.h" extern char *myname; -int putstdout(); int overstrike; int screen_length; int screen_width; char ch_erase; char ch_kill; char smart_terminal; char PC; char *tgetstr(); char *tgoto(); char termcap_buf[1024]; char string_buffer[1024]; char home[15]; char lower_left[15]; char *clear_line; char *clear_screen; char *clear_to_end; char *cursor_motion; char *start_standout; char *end_standout; char *terminal_init; char *terminal_end; #ifdef SGTTY static struct sgttyb old_settings; static struct sgttyb new_settings; #endif #ifdef TERMIO static struct termio old_settings; static struct termio new_settings; #endif #ifdef TERMIOS static struct termios old_settings; static struct termios new_settings; #endif static char is_a_terminal = No; #ifdef TOStop static int old_lword; static int new_lword; #endif #define STDIN 0 #define STDOUT 1 #define STDERR 2 void init_termcap(interactive) int interactive; { char *bufptr; char *PCptr; char *term_name; char *getenv(); int status; /* set defaults in case we aren't smart */ screen_width = MAX_COLS; screen_length = 0; if (!interactive) { /* pretend we have a dumb terminal */ smart_terminal = No; return; } /* assume we have a smart terminal until proven otherwise */ smart_terminal = Yes; /* get the terminal name */ term_name = getenv("TERM"); /* if there is no TERM, assume it's a dumb terminal */ /* patch courtesy of Sam Horrocks at telegraph.ics.uci.edu */ if (term_name == NULL) { smart_terminal = No; return; } /* now get the termcap entry */ if ((status = tgetent(termcap_buf, term_name)) != 1) { if (status == -1) { fprintf(stderr, "%s: can't open termcap file\n", myname); } else { fprintf(stderr, "%s: no termcap entry for a `%s' terminal\n", myname, term_name); } /* pretend it's dumb and proceed */ smart_terminal = No; return; } /* "hardcopy" immediately indicates a very stupid terminal */ if (tgetflag("hc")) { smart_terminal = No; return; } /* set up common terminal capabilities */ if ((screen_length = tgetnum("li")) <= 0) { screen_length = smart_terminal = 0; return; } /* screen_width is a little different */ if ((screen_width = tgetnum("co")) == -1) { screen_width = 79; } else { screen_width -= 1; } /* terminals that overstrike need special attention */ overstrike = tgetflag("os"); /* initialize the pointer into the termcap string buffer */ bufptr = string_buffer; /* get "ce", clear to end */ if (!overstrike) { clear_line = tgetstr("ce", &bufptr); } /* get necessary capabilities */ if ((clear_screen = tgetstr("cl", &bufptr)) == NULL || (cursor_motion = tgetstr("cm", &bufptr)) == NULL) { smart_terminal = No; return; } /* get some more sophisticated stuff -- these are optional */ clear_to_end = tgetstr("cd", &bufptr); terminal_init = tgetstr("ti", &bufptr); terminal_end = tgetstr("te", &bufptr); start_standout = tgetstr("so", &bufptr); end_standout = tgetstr("se", &bufptr); /* pad character */ PC = (PCptr = tgetstr("pc", &bufptr)) ? *PCptr : 0; /* set convenience strings */ (void) strncpy(home, tgoto(cursor_motion, 0, 0), sizeof(home) - 1); home[sizeof(home) - 1] = '\0'; /* (lower_left is set in get_screensize) */ /* get the actual screen size with an ioctl, if needed */ /* This may change screen_width and screen_length, and it always sets lower_left. */ get_screensize(); /* if stdout is not a terminal, pretend we are a dumb terminal */ #ifdef SGTTY if (ioctl(STDOUT, TIOCGETP, &old_settings) == -1) { smart_terminal = No; } #endif #ifdef TERMIO if (ioctl(STDOUT, TCGETA, &old_settings) == -1) { smart_terminal = No; } #endif #ifdef TERMIOS if (tcgetattr(STDOUT, &old_settings) == -1) { smart_terminal = No; } #endif } +void init_screen() { /* get the old settings for safe keeping */ #ifdef SGTTY if (ioctl(STDOUT, TIOCGETP, &old_settings) != -1) { /* copy the settings so we can modify them */ new_settings = old_settings; /* turn on CBREAK and turn off character echo and tab expansion */ new_settings.sg_flags |= CBREAK; new_settings.sg_flags &= ~(ECHO|XTABS); (void) ioctl(STDOUT, TIOCSETP, &new_settings); /* remember the erase and kill characters */ ch_erase = old_settings.sg_erase; ch_kill = old_settings.sg_kill; #ifdef TOStop /* get the local mode word */ (void) ioctl(STDOUT, TIOCLGET, &old_lword); /* modify it */ new_lword = old_lword | LTOSTOP; (void) ioctl(STDOUT, TIOCLSET, &new_lword); #endif /* remember that it really is a terminal */ is_a_terminal = Yes; /* send the termcap initialization string */ putcap(terminal_init); } #endif #ifdef TERMIO if (ioctl(STDOUT, TCGETA, &old_settings) != -1) { /* copy the settings so we can modify them */ new_settings = old_settings; /* turn off ICANON, character echo and tab expansion */ new_settings.c_lflag &= ~(ICANON|ECHO); new_settings.c_oflag &= ~(TAB3); new_settings.c_cc[VMIN] = 1; new_settings.c_cc[VTIME] = 0; (void) ioctl(STDOUT, TCSETA, &new_settings); /* remember the erase and kill characters */ ch_erase = old_settings.c_cc[VERASE]; ch_kill = old_settings.c_cc[VKILL]; /* remember that it really is a terminal */ is_a_terminal = Yes; /* send the termcap initialization string */ putcap(terminal_init); } #endif #ifdef TERMIOS if (tcgetattr(STDOUT, &old_settings) != -1) { /* copy the settings so we can modify them */ new_settings = old_settings; /* turn off ICANON, character echo and tab expansion */ new_settings.c_lflag &= ~(ICANON|ECHO); new_settings.c_oflag &= ~(TAB3); new_settings.c_cc[VMIN] = 1; new_settings.c_cc[VTIME] = 0; (void) tcsetattr(STDOUT, TCSADRAIN, &new_settings); /* remember the erase and kill characters */ ch_erase = old_settings.c_cc[VERASE]; ch_kill = old_settings.c_cc[VKILL]; /* remember that it really is a terminal */ is_a_terminal = Yes; /* send the termcap initialization string */ putcap(terminal_init); } #endif if (!is_a_terminal) { /* not a terminal at all---consider it dumb */ smart_terminal = No; } } +void end_screen() { /* move to the lower left, clear the line and send "te" */ if (smart_terminal) { putcap(lower_left); putcap(clear_line); fflush(stdout); putcap(terminal_end); } /* if we have settings to reset, then do so */ if (is_a_terminal) { #ifdef SGTTY (void) ioctl(STDOUT, TIOCSETP, &old_settings); #ifdef TOStop (void) ioctl(STDOUT, TIOCLSET, &old_lword); #endif #endif #ifdef TERMIO (void) ioctl(STDOUT, TCSETA, &old_settings); #endif #ifdef TERMIOS (void) tcsetattr(STDOUT, TCSADRAIN, &old_settings); #endif } } +void reinit_screen() { /* install our settings if it is a terminal */ if (is_a_terminal) { #ifdef SGTTY (void) ioctl(STDOUT, TIOCSETP, &new_settings); #ifdef TOStop (void) ioctl(STDOUT, TIOCLSET, &new_lword); #endif #endif #ifdef TERMIO (void) ioctl(STDOUT, TCSETA, &new_settings); #endif #ifdef TERMIOS (void) tcsetattr(STDOUT, TCSADRAIN, &new_settings); #endif } /* send init string */ if (smart_terminal) { putcap(terminal_init); } } +void get_screensize() { #ifdef TIOCGWINSZ struct winsize ws; if (ioctl (1, TIOCGWINSZ, &ws) != -1) { if (ws.ws_row != 0) { screen_length = ws.ws_row; } if (ws.ws_col != 0) { screen_width = ws.ws_col - 1; } } #else #ifdef TIOCGSIZE struct ttysize ts; if (ioctl (1, TIOCGSIZE, &ts) != -1) { if (ts.ts_lines != 0) { screen_length = ts.ts_lines; } if (ts.ts_cols != 0) { screen_width = ts.ts_cols - 1; } } #endif /* TIOCGSIZE */ #endif /* TIOCGWINSZ */ (void) strncpy(lower_left, tgoto(cursor_motion, 0, screen_length - 1), sizeof(lower_left) - 1); lower_left[sizeof(lower_left) - 1] = '\0'; } +void standout(msg) char *msg; { if (smart_terminal) { putcap(start_standout); fputs(msg, stdout); putcap(end_standout); } else { fputs(msg, stdout); } } +void clear() { if (smart_terminal) { putcap(clear_screen); } } +int clear_eol(len) int len; { if (smart_terminal && !overstrike && len > 0) { if (clear_line) { putcap(clear_line); return(0); } else { while (len-- > 0) { putchar(' '); } return(1); } } return(-1); } +void go_home() { if (smart_terminal) { putcap(home); } } /* This has to be defined as a subroutine for tputs (instead of a macro) */ +void putstdout(ch) char ch; { putchar(ch); } Index: head/contrib/top/screen.h =================================================================== --- head/contrib/top/screen.h (revision 300394) +++ head/contrib/top/screen.h (revision 300395) @@ -1,31 +1,41 @@ /* * top - a top users display for Unix 4.2 * * This file contains all the definitions necessary to use the hand-written * screen package in "screen.c" */ #define TCputs(str) tputs(str, 1, putstdout) #define putcap(str) (void)((str) != NULL ? TCputs(str) : 0) #define Move_to(x, y) TCputs(tgoto(cursor_motion, x, y)) /* declare return values for termcap functions */ char *tgetstr(); char *tgoto(); extern char ch_erase; /* set to the user's erase character */ extern char ch_kill; /* set to the user's kill character */ extern char smart_terminal; /* set if the terminal has sufficient termcap capabilities for normal operation */ /* These are some termcap strings for use outside of "screen.c" */ extern char *cursor_motion; extern char *clear_line; extern char *clear_to_end; /* rows and columns on the screen according to termcap */ extern int screen_length; extern int screen_width; /* a function that puts a single character on stdout */ -int putstdout(); +void putstdout(char ch); +int clear_eol(int len); +void standout(char *msg); +void clear(void); +void go_home(void); +void reinit_screen(void); +void get_screensize(void); +void init_termcap(int interactive); +void end_screen(void); +void init_screen(void); + Index: head/contrib/top/top.c =================================================================== --- head/contrib/top/top.c (revision 300394) +++ head/contrib/top/top.c (revision 300395) @@ -1,1231 +1,1220 @@ char *copyright = "Copyright (c) 1984 through 1996, William LeFebvre"; /* * Top users/processes display for Unix * Version 3 * * This program may be freely redistributed, * but this entire comment MUST remain intact. * * Copyright (c) 1984, 1989, William LeFebvre, Rice University * Copyright (c) 1989 - 1994, William LeFebvre, Northwestern University * Copyright (c) 1994, 1995, William LeFebvre, Argonne National Laboratory * Copyright (c) 1996, William LeFebvre, Group sys Consulting * * $FreeBSD$ */ /* * See the file "Changes" for information on version-to-version changes. */ /* * This file contains "main" and other high-level routines. */ /* * The following preprocessor variables, when defined, are used to * distinguish between different Unix implementations: * * SIGHOLD - use SVR4 sighold function when defined * SIGRELSE - use SVR4 sigrelse function when defined * FD_SET - macros FD_SET and FD_ZERO are used when defined */ #include "os.h" -#include -#include -#include -#include + #include #include + +#include +#include #include +#include +#include +#include /* includes specific to top */ +#include "commands.h" #include "display.h" /* interface to display package */ #include "screen.h" /* interface to screen package */ #include "top.h" #include "top.local.h" #include "boolean.h" #include "machine.h" #include "utils.h" +#include "username.h" /* Size of the stdio buffer given to stdout */ #define Buffersize 2048 /* The buffer that stdio will use */ char stdoutbuf[Buffersize]; /* build Signal masks */ #define Smask(s) (1 << ((s) - 1)) /* for getopt: */ extern int optind; extern char *optarg; /* imported from screen.c */ extern int overstrike; static int fmt_flags = 0; int pcpu_stats = No; /* signal handling routines */ sigret_t leave(); sigret_t tstop(); #ifdef SIGWINCH sigret_t winch(); #endif volatile sig_atomic_t leaveflag; volatile sig_atomic_t tstopflag; volatile sig_atomic_t winchflag; /* internal routines */ void quit(); /* values which need to be accessed by signal handlers */ static int max_topn; /* maximum displayable processes */ /* miscellaneous things */ struct process_select ps; char *myname = "top"; jmp_buf jmp_int; /* routines that don't return int */ char *username(); char *ctime(); char *kill_procs(); char *renice_procs(); #ifdef ORDER extern int (*compares[])(); #else extern int proc_compare(); extern int io_compare(); #endif time_t time(); caddr_t get_process_info(); /* different routines for displaying the user's identification */ /* (values assigned to get_userid) */ char *username(); char *itoa7(); -/* display routines that need to be predeclared */ -int i_loadave(); -int u_loadave(); -int i_procstates(); -int u_procstates(); -int i_cpustates(); -int u_cpustates(); -int i_memory(); -int u_memory(); -int i_arc(); -int u_arc(); -int i_swap(); -int u_swap(); -int i_message(); -int u_message(); -int i_header(); -int u_header(); -int i_process(); -int u_process(); - /* pointers to display routines */ -int (*d_loadave)() = i_loadave; -int (*d_procstates)() = i_procstates; -int (*d_cpustates)() = i_cpustates; -int (*d_memory)() = i_memory; -int (*d_arc)() = i_arc; -int (*d_swap)() = i_swap; -int (*d_message)() = i_message; -int (*d_header)() = i_header; -int (*d_process)() = i_process; +void (*d_loadave)() = i_loadave; +void (*d_procstates)() = i_procstates; +void (*d_cpustates)() = i_cpustates; +void (*d_memory)() = i_memory; +void (*d_arc)() = i_arc; +void (*d_swap)() = i_swap; +void (*d_message)() = i_message; +void (*d_header)() = i_header; +void (*d_process)() = i_process; +void reset_display(void); + +int main(argc, argv) int argc; char *argv[]; { register int i; register int active_procs; register int change; struct system_info system_info; struct statics statics; caddr_t processes; static char tempbuf1[50]; static char tempbuf2[50]; int old_sigmask; /* only used for BSD-style signals */ int topn = Default_TOPN; int delay = Default_DELAY; int displays = 0; /* indicates unspecified */ int sel_ret = 0; time_t curr_time; char *(*get_userid)() = username; char *uname_field = "USERNAME"; char *header_text; char *env_top; char **preset_argv; int preset_argc = 0; char **av; int ac; char dostates = No; char do_unames = Yes; char interactive = Maybe; char warnings = 0; #if Default_TOPN == Infinity char topn_specified = No; #endif char ch; char *iptr; char no_command = 1; struct timeval timeout; #ifdef ORDER char *order_name = NULL; int order_index = 0; #endif #ifndef FD_SET /* FD_SET and friends are not present: fake it */ typedef int fd_set; #define FD_ZERO(x) (*(x) = 0) #define FD_SET(f, x) (*(x) = 1< 0) { if ((myname = strrchr(argv[0], '/')) == 0) { myname = argv[0]; } else { myname++; } } /* initialize some selection options */ ps.idle = Yes; ps.self = -1; ps.system = No; ps.uid = -1; ps.thread = No; ps.wcpu = 1; ps.jid = -1; ps.jail = No; ps.kidle = Yes; ps.command = NULL; /* get preset options from the environment */ if ((env_top = getenv("TOP")) != NULL) { av = preset_argv = argparse(env_top, &preset_argc); ac = preset_argc; /* set the dummy argument to an explanatory message, in case getopt encounters a bad argument */ preset_argv[0] = "while processing environment"; } /* process options */ do { /* if we're done doing the presets, then process the real arguments */ if (preset_argc == 0) { ac = argc; av = argv; /* this should keep getopt happy... */ optind = 1; } while ((i = getopt(ac, av, "CSIHPabijJ:nquvzs:d:U:m:o:t")) != EOF) { switch(i) { case 'v': /* show version number */ fprintf(stderr, "%s: version %s\n", myname, version_string()); exit(1); break; case 'u': /* toggle uid/username display */ do_unames = !do_unames; break; case 'U': /* display only username's processes */ if ((ps.uid = userid(optarg)) == -1) { fprintf(stderr, "%s: unknown user\n", optarg); exit(1); } break; case 'S': /* show system processes */ ps.system = !ps.system; break; case 'I': /* show idle processes */ ps.idle = !ps.idle; break; case 'i': /* go interactive regardless */ interactive = Yes; break; case 'n': /* batch, or non-interactive */ case 'b': interactive = No; break; case 'a': fmt_flags ^= FMT_SHOWARGS; break; case 'd': /* number of displays to show */ if ((i = atoiwi(optarg)) == Invalid || i == 0) { fprintf(stderr, "%s: warning: display count should be positive -- option ignored\n", myname); warnings++; } else { displays = i; } break; case 's': if ((delay = atoi(optarg)) < 0 || (delay == 0 && getuid() != 0)) { fprintf(stderr, "%s: warning: seconds delay should be positive -- using default\n", myname); delay = Default_DELAY; warnings++; } break; case 'q': /* be quick about it */ /* only allow this if user is really root */ if (getuid() == 0) { /* be very un-nice! */ (void) nice(-20); } else { fprintf(stderr, "%s: warning: `-q' option can only be used by root\n", myname); warnings++; } break; case 'm': /* select display mode */ if (strcmp(optarg, "io") == 0) { displaymode = DISP_IO; } else if (strcmp(optarg, "cpu") == 0) { displaymode = DISP_CPU; } else { fprintf(stderr, "%s: warning: `-m' option can only take args " "'io' or 'cpu'\n", myname); exit(1); } break; case 'o': /* select sort order */ #ifdef ORDER order_name = optarg; #else fprintf(stderr, "%s: this platform does not support arbitrary ordering. Sorry.\n", myname); warnings++; #endif break; case 't': ps.self = (ps.self == -1) ? getpid() : -1; break; case 'C': ps.wcpu = !ps.wcpu; break; case 'H': ps.thread = !ps.thread; break; case 'j': ps.jail = !ps.jail; break; case 'J': /* display only jail's processes */ if ((ps.jid = jail_getid(optarg)) == -1) { fprintf(stderr, "%s: unknown jail\n", optarg); exit(1); } ps.jail = 1; break; case 'P': pcpu_stats = !pcpu_stats; break; case 'z': ps.kidle = !ps.kidle; break; default: fprintf(stderr, "Top version %s\n" "Usage: %s [-abCHIijnPqStuvz] [-d count] [-m io | cpu] [-o field] [-s time]\n" " [-J jail] [-U username] [number]\n", version_string(), myname); exit(1); } } /* get count of top processes to display (if any) */ if (optind < ac) { if ((topn = atoiwi(av[optind])) == Invalid) { fprintf(stderr, "%s: warning: process display count should be non-negative -- using default\n", myname); warnings++; } #if Default_TOPN == Infinity else { topn_specified = Yes; } #endif } /* tricky: remember old value of preset_argc & set preset_argc = 0 */ i = preset_argc; preset_argc = 0; /* repeat only if we really did the preset arguments */ } while (i != 0); /* set constants for username/uid display correctly */ if (!do_unames) { uname_field = " UID "; get_userid = itoa7; } /* initialize the kernel memory interface */ if (machine_init(&statics, do_unames) == -1) { exit(1); } #ifdef ORDER /* determine sorting order index, if necessary */ if (order_name != NULL) { if ((order_index = string_index(order_name, statics.order_names)) == -1) { char **pp; fprintf(stderr, "%s: '%s' is not a recognized sorting order.\n", myname, order_name); fprintf(stderr, "\tTry one of these:"); pp = statics.order_names; while (*pp != NULL) { fprintf(stderr, " %s", *pp++); } fputc('\n', stderr); exit(1); } } #endif #ifdef no_initialization_needed /* initialize the hashing stuff */ if (do_unames) { init_hash(); } #endif /* initialize termcap */ init_termcap(interactive); /* get the string to use for the process area header */ header_text = format_header(uname_field); /* initialize display interface */ if ((max_topn = display_init(&statics)) == -1) { fprintf(stderr, "%s: can't allocate sufficient memory\n", myname); exit(4); } /* print warning if user requested more processes than we can display */ if (topn > max_topn) { fprintf(stderr, "%s: warning: this terminal can only display %d processes.\n", myname, max_topn); warnings++; } /* adjust for topn == Infinity */ if (topn == Infinity) { /* * For smart terminals, infinity really means everything that can * be displayed, or Largest. * On dumb terminals, infinity means every process in the system! * We only really want to do that if it was explicitly specified. * This is always the case when "Default_TOPN != Infinity". But if * topn wasn't explicitly specified and we are on a dumb terminal * and the default is Infinity, then (and only then) we use * "Nominal_TOPN" instead. */ #if Default_TOPN == Infinity topn = smart_terminal ? Largest : (topn_specified ? Largest : Nominal_TOPN); #else topn = Largest; #endif } /* set header display accordingly */ display_header(topn > 0); /* determine interactive state */ if (interactive == Maybe) { interactive = smart_terminal; } /* if # of displays not specified, fill it in */ if (displays == 0) { displays = smart_terminal ? Infinity : 1; } /* hold interrupt signals while setting up the screen and the handlers */ #ifdef SIGHOLD sighold(SIGINT); sighold(SIGQUIT); sighold(SIGTSTP); #else old_sigmask = sigblock(Smask(SIGINT) | Smask(SIGQUIT) | Smask(SIGTSTP)); #endif init_screen(); (void) signal(SIGINT, leave); (void) signal(SIGQUIT, leave); (void) signal(SIGTSTP, tstop); #ifdef SIGWINCH (void) signal(SIGWINCH, winch); #endif #ifdef SIGRELSE sigrelse(SIGINT); sigrelse(SIGQUIT); sigrelse(SIGTSTP); #else (void) sigsetmask(old_sigmask); #endif if (warnings) { fputs("....", stderr); fflush(stderr); /* why must I do this? */ sleep((unsigned)(3 * warnings)); fputc('\n', stderr); } restart: /* * main loop -- repeat while display count is positive or while it * indicates infinity (by being -1) */ while ((displays == -1) || (displays-- > 0)) { int (*compare)(); /* get the current stats */ get_system_info(&system_info); #ifdef ORDER compare = compares[order_index]; #else if (displaymode == DISP_CPU) compare = proc_compare; else compare = io_compare; #endif /* get the current set of processes */ processes = get_process_info(&system_info, &ps, compare); /* display the load averages */ (*d_loadave)(system_info.last_pid, system_info.load_avg); /* display the current time */ /* this method of getting the time SHOULD be fairly portable */ time(&curr_time); i_uptime(&system_info.boottime, &curr_time); i_timeofday(&curr_time); /* display process state breakdown */ (*d_procstates)(system_info.p_total, system_info.procstates); /* display the cpu state percentage breakdown */ if (dostates) /* but not the first time */ { (*d_cpustates)(system_info.cpustates); } else { /* we'll do it next time */ if (smart_terminal) { z_cpustates(); } else { putchar('\n'); } dostates = Yes; } /* display memory stats */ (*d_memory)(system_info.memory); (*d_arc)(system_info.arc); /* display swap stats */ (*d_swap)(system_info.swap); /* handle message area */ (*d_message)(); /* update the header area */ (*d_header)(header_text); if (topn > 0) { /* determine number of processes to actually display */ /* this number will be the smallest of: active processes, number user requested, number current screen accomodates */ active_procs = system_info.P_ACTIVE; if (active_procs > topn) { active_procs = topn; } if (active_procs > max_topn) { active_procs = max_topn; } /* now show the top "n" processes. */ for (i = 0; i < active_procs; i++) { (*d_process)(i, format_next_process(processes, get_userid, fmt_flags)); } } else { i = 0; } /* do end-screen processing */ u_endscreen(i); /* now, flush the output buffer */ if (fflush(stdout) != 0) { new_message(MT_standout, " Write error on stdout"); putchar('\r'); quit(1); /*NOTREACHED*/ } /* only do the rest if we have more displays to show */ if (displays) { /* switch out for new display on smart terminals */ if (smart_terminal) { if (overstrike) { reset_display(); } else { d_loadave = u_loadave; d_procstates = u_procstates; d_cpustates = u_cpustates; d_memory = u_memory; d_arc = u_arc; d_swap = u_swap; d_message = u_message; d_header = u_header; d_process = u_process; } } no_command = Yes; if (!interactive) { sleep(delay); if (leaveflag) { end_screen(); exit(0); } } else while (no_command) { /* assume valid command unless told otherwise */ no_command = No; /* set up arguments for select with timeout */ FD_ZERO(&readfds); FD_SET(0, &readfds); /* for standard input */ timeout.tv_sec = delay; timeout.tv_usec = 0; if (leaveflag) { end_screen(); exit(0); } if (tstopflag) { /* move to the lower left */ end_screen(); fflush(stdout); /* default the signal handler action */ (void) signal(SIGTSTP, SIG_DFL); /* unblock the signal and send ourselves one */ #ifdef SIGRELSE sigrelse(SIGTSTP); #else (void) sigsetmask(sigblock(0) & ~(1 << (SIGTSTP - 1))); #endif (void) kill(0, SIGTSTP); /* reset the signal handler */ (void) signal(SIGTSTP, tstop); /* reinit screen */ reinit_screen(); reset_display(); tstopflag = 0; goto restart; } if (winchflag) { /* reascertain the screen dimensions */ get_screensize(); /* tell display to resize */ max_topn = display_resize(); /* reset the signal handler */ (void) signal(SIGWINCH, winch); reset_display(); winchflag = 0; goto restart; } /* wait for either input or the end of the delay period */ sel_ret = select(2, &readfds, NULL, NULL, &timeout); if (sel_ret < 0 && errno != EINTR) quit(0); if (sel_ret > 0) { int newval; char *errmsg; /* something to read -- clear the message area first */ clear_message(); /* now read it and convert to command strchr */ /* (use "change" as a temporary to hold strchr) */ if (read(0, &ch, 1) != 1) { /* read error: either 0 or -1 */ new_message(MT_standout, " Read error on stdin"); putchar('\r'); quit(1); /*NOTREACHED*/ } if ((iptr = strchr(command_chars, ch)) == NULL) { if (ch != '\r' && ch != '\n') { /* illegal command */ new_message(MT_standout, " Command not understood"); } putchar('\r'); no_command = Yes; } else { change = iptr - command_chars; if (overstrike && change > CMD_OSLIMIT) { /* error */ new_message(MT_standout, " Command cannot be handled by this terminal"); putchar('\r'); no_command = Yes; } else switch(change) { case CMD_redraw: /* redraw screen */ reset_display(); break; case CMD_update: /* merely update display */ /* is the load average high? */ if (system_info.load_avg[0] > LoadMax) { /* yes, go home for visual feedback */ go_home(); fflush(stdout); } break; case CMD_quit: /* quit */ quit(0); /*NOTREACHED*/ break; case CMD_help1: /* help */ case CMD_help2: reset_display(); clear(); show_help(); standout("Hit any key to continue: "); fflush(stdout); (void) read(0, &ch, 1); break; case CMD_errors: /* show errors */ if (error_count() == 0) { new_message(MT_standout, " Currently no errors to report."); putchar('\r'); no_command = Yes; } else { reset_display(); clear(); show_errors(); standout("Hit any key to continue: "); fflush(stdout); (void) read(0, &ch, 1); } break; case CMD_number1: /* new number */ case CMD_number2: new_message(MT_standout, "Number of processes to show: "); newval = readline(tempbuf1, 8, Yes); if (newval > -1) { if (newval > max_topn) { new_message(MT_standout | MT_delayed, " This terminal can only display %d processes.", max_topn); putchar('\r'); } if (newval == 0) { /* inhibit the header */ display_header(No); } else if (newval > topn && topn == 0) { /* redraw the header */ display_header(Yes); d_header = i_header; } topn = newval; } break; case CMD_delay: /* new seconds delay */ new_message(MT_standout, "Seconds to delay: "); if ((i = readline(tempbuf1, 8, Yes)) > -1) { if ((delay = i) == 0 && getuid() != 0) { delay = 1; } } clear_message(); break; case CMD_displays: /* change display count */ new_message(MT_standout, "Displays to show (currently %s): ", displays == -1 ? "infinite" : itoa(displays)); if ((i = readline(tempbuf1, 10, Yes)) > 0) { displays = i; } else if (i == 0) { quit(0); } clear_message(); break; case CMD_kill: /* kill program */ new_message(0, "kill "); if (readline(tempbuf2, sizeof(tempbuf2), No) > 0) { if ((errmsg = kill_procs(tempbuf2)) != NULL) { new_message(MT_standout, "%s", errmsg); putchar('\r'); no_command = Yes; } } else { clear_message(); } break; case CMD_renice: /* renice program */ new_message(0, "renice "); if (readline(tempbuf2, sizeof(tempbuf2), No) > 0) { if ((errmsg = renice_procs(tempbuf2)) != NULL) { new_message(MT_standout, "%s", errmsg); putchar('\r'); no_command = Yes; } } else { clear_message(); } break; case CMD_idletog: case CMD_idletog2: ps.idle = !ps.idle; new_message(MT_standout | MT_delayed, " %sisplaying idle processes.", ps.idle ? "D" : "Not d"); putchar('\r'); break; case CMD_selftog: ps.self = (ps.self == -1) ? getpid() : -1; new_message(MT_standout | MT_delayed, " %sisplaying self.", (ps.self == -1) ? "D" : "Not d"); putchar('\r'); break; case CMD_user: new_message(MT_standout, "Username to show (+ for all): "); if (readline(tempbuf2, sizeof(tempbuf2), No) > 0) { if (tempbuf2[0] == '+' && tempbuf2[1] == '\0') { ps.uid = -1; } else if ((i = userid(tempbuf2)) == -1) { new_message(MT_standout, " %s: unknown user", tempbuf2); no_command = Yes; } else { ps.uid = i; } putchar('\r'); } else { clear_message(); } break; case CMD_thrtog: ps.thread = !ps.thread; new_message(MT_standout | MT_delayed, " Displaying threads %s", ps.thread ? "separately" : "as a count"); header_text = format_header(uname_field); reset_display(); putchar('\r'); break; case CMD_wcputog: ps.wcpu = !ps.wcpu; new_message(MT_standout | MT_delayed, " Displaying %s CPU", ps.wcpu ? "weighted" : "raw"); header_text = format_header(uname_field); reset_display(); putchar('\r'); break; case CMD_viewtog: if (++displaymode == DISP_MAX) displaymode = 0; header_text = format_header(uname_field); display_header(Yes); d_header = i_header; reset_display(); break; case CMD_viewsys: ps.system = !ps.system; break; case CMD_showargs: fmt_flags ^= FMT_SHOWARGS; break; #ifdef ORDER case CMD_order: new_message(MT_standout, "Order to sort: "); if (readline(tempbuf2, sizeof(tempbuf2), No) > 0) { if ((i = string_index(tempbuf2, statics.order_names)) == -1) { new_message(MT_standout, " %s: unrecognized sorting order", tempbuf2); no_command = Yes; } else { order_index = i; } putchar('\r'); } else { clear_message(); } break; #endif case CMD_jidtog: ps.jail = !ps.jail; new_message(MT_standout | MT_delayed, " %sisplaying jail ID.", ps.jail ? "D" : "Not d"); header_text = format_header(uname_field); reset_display(); putchar('\r'); break; case CMD_jail: new_message(MT_standout, "Jail to show (+ for all): "); if (readline(tempbuf2, sizeof(tempbuf2), No) > 0) { if (tempbuf2[0] == '+' && tempbuf2[1] == '\0') { ps.jid = -1; } else if ((i = jail_getid(tempbuf2)) == -1) { new_message(MT_standout, " %s: unknown jail", tempbuf2); no_command = Yes; } else { ps.jid = i; } if (ps.jail == 0) { ps.jail = 1; new_message(MT_standout | MT_delayed, " Displaying jail " "ID."); header_text = format_header(uname_field); reset_display(); } putchar('\r'); } else { clear_message(); } break; case CMD_kidletog: ps.kidle = !ps.kidle; new_message(MT_standout | MT_delayed, " %sisplaying system idle process.", ps.kidle ? "D" : "Not d"); putchar('\r'); break; case CMD_pcputog: pcpu_stats = !pcpu_stats; new_message(MT_standout | MT_delayed, " Displaying %sCPU statistics.", pcpu_stats ? "per-" : "global "); toggle_pcpustats(); max_topn = display_updatecpus(&statics); reset_display(); putchar('\r'); break; default: new_message(MT_standout, " BAD CASE IN SWITCH!"); putchar('\r'); } } /* flush out stuff that may have been written */ fflush(stdout); } } } } #ifdef DEBUG fclose(debug); #endif quit(0); /*NOTREACHED*/ } /* * reset_display() - reset all the display routine pointers so that entire * screen will get redrawn. */ +void reset_display() { d_loadave = i_loadave; d_procstates = i_procstates; d_cpustates = i_cpustates; d_memory = i_memory; d_arc = i_arc; d_swap = i_swap; d_message = i_message; d_header = i_header; d_process = i_process; } /* * signal handlers */ sigret_t leave() /* exit under normal conditions -- INT handler */ { leaveflag = 1; } sigret_t tstop(i) /* SIGTSTP handler */ int i; { tstopflag = 1; } #ifdef SIGWINCH sigret_t winch(i) /* SIGWINCH handler */ int i; { winchflag = 1; } #endif void quit(status) /* exit under duress */ int status; { end_screen(); exit(status); /*NOTREACHED*/ } Index: head/contrib/top/top.h =================================================================== --- head/contrib/top/top.h (revision 300394) +++ head/contrib/top/top.h (revision 300395) @@ -1,49 +1,54 @@ /* * $FreeBSD$ */ /* * Top - a top users display for Berkeley Unix * * General (global) definitions */ +#ifndef TOP_H +#define TOP_H + /* Current major version number */ #define VERSION 3 /* Number of lines of header information on the standard screen */ extern int Header_lines; /* 7 */ /* Maximum number of columns allowed for display */ #define MAX_COLS 512 /* Log base 2 of 1024 is 10 (2^10 == 1024) */ #define LOG1024 10 char *itoa(); char *itoa7(); char *version_string(); /* Special atoi routine returns either a non-negative number or one of: */ #define Infinity -1 #define Invalid -2 /* maximum number we can have */ #define Largest 0x7fffffff /* * The entire display is based on these next numbers being defined as is. */ #define NUM_AVERAGES 3 enum displaymodes { DISP_CPU = 0, DISP_IO, DISP_MAX }; /* * Format modifiers */ #define FMT_SHOWARGS 0x00000001 extern enum displaymodes displaymode; extern int pcpu_stats; + +#endif /* TOP_H */ Index: head/contrib/top/username.c =================================================================== --- head/contrib/top/username.c (revision 300394) +++ head/contrib/top/username.c (revision 300395) @@ -1,189 +1,195 @@ /* * Top users/processes display for Unix * Version 3 * * This program may be freely redistributed, * but this entire comment MUST remain intact. * * Copyright (c) 1984, 1989, William LeFebvre, Rice University * Copyright (c) 1989, 1990, 1992, William LeFebvre, Northwestern University * * $FreeBSD$ */ /* * Username translation code for top. * * These routines handle uid to username mapping. * They use a hashing table scheme to reduce reading overhead. * For the time being, these are very straightforward hashing routines. * Maybe someday I'll put in something better. But with the advent of * "random access" password files, it might not be worth the effort. * * Changes to these have been provided by John Gilmore (gnu@toad.com). * * The hash has been simplified in this release, to avoid the * table overflow problems of previous releases. If the value * at the initial hash location is not right, it is replaced * by the right value. Collisions will cause us to call getpw* * but hey, this is a cache, not the Library of Congress. * This makes the table size independent of the passwd file size. */ #include #include -#include + #include +#include +#include +#include #include "top.local.h" #include "utils.h" +#include "username.h" struct hash_el { int uid; char name[MAXLOGNAME]; }; #define is_empty_hash(x) (hash_table[x].name[0] == 0) /* simple minded hashing function */ /* Uid "nobody" is -2 results in hashit(-2) = -2 which is out of bounds for the hash_table. Applied abs() function to fix. 2/16/96 tpugh */ #define hashit(i) (abs(i) % Table_size) /* K&R requires that statically declared tables be initialized to zero. */ /* We depend on that for hash_table and YOUR compiler had BETTER do it! */ struct hash_el hash_table[Table_size]; + +void init_hash() { /* * There used to be some steps we had to take to initialize things. * We don't need to do that anymore, but we will leave this stub in * just in case future changes require initialization steps. */ } char *username(uid) -register int uid; +int uid; { register int hashindex; hashindex = hashit(uid); if (is_empty_hash(hashindex) || (hash_table[hashindex].uid != uid)) { /* not here or not right -- get it out of passwd */ hashindex = get_user(uid); } return(hash_table[hashindex].name); } int userid(username) char *username; { struct passwd *pwd; /* Eventually we want this to enter everything in the hash table, but for now we just do it simply and remember just the result. */ if ((pwd = getpwnam(username)) == NULL) { return(-1); } /* enter the result in the hash table */ enter_user(pwd->pw_uid, username, 1); /* return our result */ return(pwd->pw_uid); } int enter_user(uid, name, wecare) -register int uid; -register char *name; +int uid; +char *name; int wecare; /* 1 = enter it always, 0 = nice to have */ { register int hashindex; #ifdef DEBUG fprintf(stderr, "enter_hash(%d, %s, %d)\n", uid, name, wecare); #endif hashindex = hashit(uid); if (!is_empty_hash(hashindex)) { if (!wecare) return 0; /* Don't clobber a slot for trash */ if (hash_table[hashindex].uid == uid) return(hashindex); /* Fortuitous find */ } /* empty or wrong slot -- fill it with new value */ hash_table[hashindex].uid = uid; (void) strncpy(hash_table[hashindex].name, name, MAXLOGNAME - 1); return(hashindex); } /* * Get a userid->name mapping from the system. * If the passwd database is hashed (#define RANDOM_PW), we * just handle this uid. Otherwise we scan the passwd file * and cache any entries we pass over while looking. */ int get_user(uid) -register int uid; +int uid; { struct passwd *pwd; #ifdef RANDOM_PW /* no performance penalty for using getpwuid makes it easy */ if ((pwd = getpwuid(uid)) != NULL) { return(enter_user(pwd->pw_uid, pwd->pw_name, 1)); } #else int from_start = 0; /* * If we just called getpwuid each time, things would be very slow * since that just iterates through the passwd file each time. So, * we walk through the file instead (using getpwent) and cache each * entry as we go. Once the right record is found, we cache it and * return immediately. The next time we come in, getpwent will get * the next record. In theory, we never have to read the passwd file * a second time (because we cache everything we read). But in * practice, the cache may not be large enough, so if we don't find * it the first time we have to scan the file a second time. This * is not very efficient, but it will do for now. */ while (from_start++ < 2) { while ((pwd = getpwent()) != NULL) { if (pwd->pw_uid == uid) { return(enter_user(pwd->pw_uid, pwd->pw_name, 1)); } (void) enter_user(pwd->pw_uid, pwd->pw_name, 0); } /* try again */ setpwent(); } #endif /* if we can't find the name at all, then use the uid as the name */ return(enter_user(uid, itoa7(uid), 1)); } Index: head/contrib/top/username.h =================================================================== --- head/contrib/top/username.h (nonexistent) +++ head/contrib/top/username.h (revision 300395) @@ -0,0 +1,23 @@ +/* + * Top users/processes display for Unix + * Version 3 + * + * This program may be freely redistributed, + * but this entire comment MUST remain intact. + * + * Copyright (c) 1984, 1989, William LeFebvre, Rice University + * Copyright (c) 1989, 1990, 1992, William LeFebvre, Northwestern University + * Copyright (c) 2016, Randy Westlund + * + * $FreeBSD$ + */ +#ifndef USERNAME_H +#define USERNAME_H + +int enter_user(int uid, char *name, int wecare); +int get_user(int uid); +void init_hash(void); +char *username(int uid); +int userid(char *username); + +#endif /* USERNAME_H */ Property changes on: head/contrib/top/username.h ___________________________________________________________________ Added: svn:eol-style ## -0,0 +1 ## +native \ No newline at end of property Added: svn:keywords ## -0,0 +1 ## +FreeBSD=%H \ No newline at end of property Added: svn:mime-type ## -0,0 +1 ## +text/plain \ No newline at end of property Index: head/contrib/top/utils.h =================================================================== --- head/contrib/top/utils.h (revision 300394) +++ head/contrib/top/utils.h (revision 300395) @@ -1,24 +1,26 @@ /* * Top users/processes display for Unix * Version 3 * * This program may be freely redistributed, * but this entire comment MUST remain intact. * * Copyright (c) 1984, 1989, William LeFebvre, Rice University * Copyright (c) 1989, 1990, 1992, William LeFebvre, Northwestern University */ /* prototypes for functions found in utils.c */ int atoiwi(); char *itoa(); char *itoa7(); int digits(); char *strecpy(); char **argparse(); long percentages(); char *errmsg(); char *format_time(); char *format_k(); char *format_k2(unsigned long long); +int string_index(char *string, char **array); + Index: head/contrib/top/version.c =================================================================== --- head/contrib/top/version.c (revision 300394) +++ head/contrib/top/version.c (revision 300395) @@ -1,25 +1,28 @@ /* * Top users/processes display for Unix * Version 3 * * This program may be freely redistributed, * but this entire comment MUST remain intact. * * Copyright (c) 1984, 1989, William LeFebvre, Rice University * Copyright (c) 1989, 1990, 1992, William LeFebvre, Northwestern University */ +#include +#include + #include "top.h" #include "patchlevel.h" static char version[16]; char *version_string() { sprintf(version, "%d.%d", VERSION, PATCHLEVEL); #ifdef BETA strcat(version, BETA); #endif return(version); }