diff --git a/.editorconfig b/.editorconfig index 188078926..dd881dd0a 100644 --- a/.editorconfig +++ b/.editorconfig @@ -14,3 +14,4 @@ charset = utf-8 [*.{c,h}] indent_style = space indent_size = 3 +trim_trailing_whitespace = true diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 000000000..dd81407ac --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,105 @@ +name: CI + +on: [ push, pull_request ] + +jobs: + build-ubuntu-latest-minimal-gcc: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - name: Install Dependencies + run: sudo apt-get install libncursesw5-dev + - name: Bootstrap + run: ./autogen.sh + - name: Configure + run: ./configure --enable-werror --enable-linux-affinity --disable-taskstats --disable-unicode + - name: Build + run: make -k + - name: Distcheck + run: make distcheck DISTCHECK_CONFIGURE_FLAGS="--enable-werror --enable-linux-affinity --disable-taskstats --disable-unicode" + + build-ubuntu-latest-minimal-clang: + runs-on: ubuntu-latest + env: + CC: clang-10 + steps: + - uses: actions/checkout@v2 + - name: install clang repo + run: | + wget -O - https://apt.llvm.org/llvm-snapshot.gpg.key 2>/dev/null | sudo apt-key add - + sudo add-apt-repository 'deb http://apt.llvm.org/bionic/ llvm-toolchain-bionic-10 main' -y + sudo apt-get update -q + - name: Install Dependencies + run: sudo apt-get install clang-10 libncursesw5-dev + - name: Bootstrap + run: ./autogen.sh + - name: Configure + run: ./configure --enable-werror --enable-linux-affinity --disable-taskstats --disable-unicode + - name: Build + run: make -k + - name: Distcheck + run: make distcheck DISTCHECK_CONFIGURE_FLAGS="--enable-werror --enable-linux-affinity --disable-taskstats --disable-unicode" + + build-ubuntu-latest-full-featured-gcc: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - name: Install Dependencies + run: sudo apt-get install libncursesw5-dev libhwloc-dev libnl-3-dev libnl-genl-3-dev + - name: Bootstrap + run: ./autogen.sh + - name: Configure + run: ./configure --enable-werror --enable-openvz --enable-cgroup --enable-vserver --enable-ancient-vserver --enable-taskstats --enable-unicode --enable-hwloc --enable-setuid --enable-delayacct + - name: Build + run: make -k + - name: Distcheck + run: make distcheck DISTCHECK_CONFIGURE_FLAGS='--enable-werror --enable-openvz --enable-cgroup --enable-vserver --enable-ancient-vserver --enable-taskstats --enable-unicode --enable-hwloc --enable-setuid --enable-delayacct' + + build-ubuntu-latest-full-featured-clang: + runs-on: ubuntu-latest + env: + CC: clang-10 + steps: + - uses: actions/checkout@v2 + - name: install clang repo + run: | + wget -O - https://apt.llvm.org/llvm-snapshot.gpg.key 2>/dev/null | sudo apt-key add - + sudo add-apt-repository 'deb http://apt.llvm.org/bionic/ llvm-toolchain-bionic-10 main' -y + sudo apt-get update -q + - name: Install Dependencies + run: sudo apt-get install clang-10 libncursesw5-dev libhwloc-dev libnl-3-dev libnl-genl-3-dev + - name: Bootstrap + run: ./autogen.sh + - name: Configure + run: ./configure --enable-werror --enable-openvz --enable-cgroup --enable-vserver --enable-ancient-vserver --enable-taskstats --enable-unicode --enable-hwloc --enable-setuid --enable-delayacct + - name: Build + run: make -k + - name: Distcheck + run: make distcheck DISTCHECK_CONFIGURE_FLAGS='--enable-werror --enable-openvz --enable-cgroup --enable-vserver --enable-ancient-vserver --enable-taskstats --enable-unicode --enable-hwloc --enable-setuid --enable-delayacct' + + build-ubuntu-latest-clang-analyzer: + runs-on: ubuntu-latest + env: + CC: clang-11 + steps: + - uses: actions/checkout@v2 + - name: install clang repo + run: | + wget -O - https://apt.llvm.org/llvm-snapshot.gpg.key 2>/dev/null | sudo apt-key add - + sudo add-apt-repository 'deb http://apt.llvm.org/bionic/ llvm-toolchain-bionic-11 main' -y + sudo apt-get update -q + - name: Install Dependencies + run: sudo apt-get install clang-11 clang-tools-11 libncursesw5-dev libhwloc-dev libnl-3-dev libnl-genl-3-dev + - name: Bootstrap + run: ./autogen.sh + - name: Configure + run: scan-build-11 -analyze-headers --status-bugs ./configure --enable-debug --enable-werror --enable-openvz --enable-cgroup --enable-vserver --enable-ancient-vserver --enable-taskstats --enable-unicode --enable-hwloc --enable-setuid --enable-delayacct + - name: Build + run: scan-build-11 -analyze-headers --status-bugs make -j"$(nproc)" + + whitespace_check: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - name: check-whitespaces + run: git diff-tree --check $(git hash-object -t tree /dev/null) HEAD diff --git a/.gitignore b/.gitignore index f94f3f52e..3d522b065 100644 --- a/.gitignore +++ b/.gitignore @@ -17,6 +17,7 @@ htop *.h.gch */.dirstamp +# automake/autoconf related files .deps/ Makefile Makefile.in @@ -24,6 +25,7 @@ INSTALL aclocal.m4 autom4te.cache/ compile +conf*/ config.guess config.h config.h.in @@ -40,3 +42,6 @@ ltmain.sh m4/ missing stamp-h1 + +# files related to valgrind/callgrind +callgrind.out.* diff --git a/.travis.yml b/.travis.yml index 22a5e07c0..bb79560df 100644 --- a/.travis.yml +++ b/.travis.yml @@ -5,7 +5,22 @@ compiler: - gcc os: + - freebsd - linux - osx -script: ./autogen.sh && ./configure && make +arch: + - amd64 + - s390x + +before_script: + if [[ ${TRAVIS_CPU_ARCH} == 's390x' ]]; then + sudo apt-get update && sudo apt-get install -y libncursesw5-dev ; + fi + +script: + - ./autogen.sh + # clang might warn about C11 generic selections in isnan() + - CFLAGS=-Wno-c11-extensions ./configure --enable-werror + - make -k + - CFLAGS=-Wno-c11-extensions make distcheck DISTCHECK_CONFIGURE_FLAGS=--enable-werror diff --git a/Action.c b/Action.c index 9a7c3c560..822c9174b 100644 --- a/Action.c +++ b/Action.c @@ -1,82 +1,56 @@ /* htop - Action.c (C) 2015 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ #include "config.h" #include "Action.h" + +#include +#include +#include + #include "Affinity.h" #include "AffinityPanel.h" #include "CategoriesPanel.h" +#include "CommandScreen.h" #include "CRT.h" #include "EnvScreen.h" +#include "FunctionBar.h" +#include "IncSet.h" +#include "InfoScreen.h" +#include "ListItem.h" +#include "Macros.h" #include "MainPanel.h" #include "OpenFilesScreen.h" #include "Process.h" +#include "ProcessLocksScreen.h" +#include "ProvideCurses.h" #include "ScreenManager.h" #include "SignalsPanel.h" -#include "StringUtils.h" #include "TraceScreen.h" -#include "Platform.h" +#include "Vector.h" +#include "XUtils.h" -#include -#include -#include -#include -#include -#include -#include -/*{ - -#include "IncSet.h" -#include "Settings.h" -#include "Header.h" -#include "UsersTable.h" -#include "ProcessList.h" -#include "Panel.h" - -typedef enum { - HTOP_OK = 0x00, - HTOP_REFRESH = 0x01, - HTOP_RECALCULATE = 0x03, // implies HTOP_REFRESH - HTOP_SAVE_SETTINGS = 0x04, - HTOP_KEEP_FOLLOWING = 0x08, - HTOP_QUIT = 0x10, - HTOP_REDRAW_BAR = 0x20, - HTOP_UPDATE_PANELHDR = 0x41, // implies HTOP_REFRESH -} Htop_Reaction; - -typedef Htop_Reaction (*Htop_Action)(); - -typedef struct State_ { - Settings* settings; - UsersTable* ut; - ProcessList* pl; - Panel* panel; - Header* header; -} State; - -}*/ - -Object* Action_pickFromVector(State* st, Panel* list, int x) { +Object* Action_pickFromVector(State* st, Panel* list, int x, bool followProcess) { Panel* panel = st->panel; Header* header = st->header; Settings* settings = st->settings; - + int y = panel->y; - ScreenManager* scr = ScreenManager_new(0, header->height, 0, -1, HORIZONTAL, header, settings, false); + ScreenManager* scr = ScreenManager_new(0, header->height, 0, -1, HORIZONTAL, header, settings, st, false); scr->allowFocusChange = false; ScreenManager_add(scr, list, x - 1); ScreenManager_add(scr, panel, -1); Panel* panelFocus; int ch; bool unfollow = false; - int pid = MainPanel_selectedPid((MainPanel*)panel); - if (header->pl->following == -1) { + int pid = followProcess ? MainPanel_selectedPid((MainPanel*)panel) : -1; + if (followProcess && header->pl->following == -1) { header->pl->following = pid; unfollow = true; } @@ -86,54 +60,59 @@ Object* Action_pickFromVector(State* st, Panel* list, int x) { } ScreenManager_delete(scr); Panel_move(panel, 0, y); - Panel_resize(panel, COLS, LINES-y-1); + Panel_resize(panel, COLS, LINES - y - 1); if (panelFocus == list && ch == 13) { - Process* selected = (Process*)Panel_getSelected(panel); - if (selected && selected->pid == pid) - return Panel_getSelected(list); - else + if (followProcess) { + Process* selected = (Process*)Panel_getSelected(panel); + if (selected && selected->pid == pid) + return Panel_getSelected(list); + beep(); + } else { + return Panel_getSelected(list); + } } + return NULL; } // ---------------------------------------- -static void Action_runSetup(Settings* settings, const Header* header, ProcessList* pl) { - ScreenManager* scr = ScreenManager_new(0, header->height, 0, -1, HORIZONTAL, header, settings, true); - CategoriesPanel* panelCategories = CategoriesPanel_new(scr, settings, (Header*) header, pl); +static void Action_runSetup(State* st) { + ScreenManager* scr = ScreenManager_new(0, st->header->height, 0, -1, HORIZONTAL, st->header, st->settings, st, true); + CategoriesPanel* panelCategories = CategoriesPanel_new(scr, st->settings, st->header, st->pl); ScreenManager_add(scr, (Panel*) panelCategories, 16); CategoriesPanel_makeMetersPage(panelCategories); Panel* panelFocus; int ch; ScreenManager_run(scr, &panelFocus, &ch); ScreenManager_delete(scr); - if (settings->changed) { - Header_writeBackToSettings(header); + if (st->settings->changed) { + Header_writeBackToSettings(st->header); } } static bool changePriority(MainPanel* panel, int delta) { bool anyTagged; - bool ok = MainPanel_foreachProcess(panel, (MainPanel_ForeachProcessFn) Process_changePriorityBy, (Arg){ .i = delta }, &anyTagged); + bool ok = MainPanel_foreachProcess(panel, Process_changePriorityBy, (Arg) { .i = delta }, &anyTagged); if (!ok) beep(); return anyTagged; } -static void addUserToVector(int key, void* userCast, void* panelCast) { - char* user = (char*) userCast; - Panel* panel = (Panel*) panelCast; +static void addUserToVector(hkey_t key, void* userCast, void* panelCast) { + const char* user = userCast; + Panel* panel = panelCast; Panel_add(panel, (Object*) ListItem_new(user, key)); } bool Action_setUserOnly(const char* userName, uid_t* userId) { - struct passwd* user = getpwnam(userName); + const struct passwd* user = getpwnam(userName); if (user) { *userId = user->pw_uid; return true; } - *userId = -1; + *userId = (uid_t)-1; return false; } @@ -150,14 +129,18 @@ static void tagAllChildren(Panel* panel, Process* parent) { static bool expandCollapse(Panel* panel) { Process* p = (Process*) Panel_getSelected(panel); - if (!p) return false; + if (!p) + return false; + p->showChildren = !p->showChildren; return true; } static bool collapseIntoParent(Panel* panel) { Process* p = (Process*) Panel_getSelected(panel); - if (!p) return false; + if (!p) + return false; + pid_t ppid = Process_getParentPid(p); for (int i = 0; i < Panel_size(panel); i++) { Process* q = (Process*) Panel_get(panel, i); @@ -187,13 +170,18 @@ static Htop_Reaction sortBy(State* st) { Panel_add(sortPanel, (Object*) ListItem_new(name, fields[i])); if (fields[i] == st->settings->sortKey) Panel_setSelected(sortPanel, i); + free(name); } - ListItem* field = (ListItem*) Action_pickFromVector(st, sortPanel, 15); + ListItem* field = (ListItem*) Action_pickFromVector(st, sortPanel, 15, false); if (field) { reaction |= Action_setSortKey(st->settings, field->key); } Object_delete(sortPanel); + + if (st->pauseProcessUpdate) + ProcessList_sort(st->pl); + return reaction | HTOP_REFRESH | HTOP_REDRAW_BAR | HTOP_UPDATE_PANELHDR; } @@ -201,7 +189,7 @@ static Htop_Reaction sortBy(State* st) { static Htop_Reaction actionResize(State* st) { clear(); - Panel_resize(st->panel, COLS, LINES-(st->panel->y)-1); + Panel_resize(st->panel, COLS, LINES - (st->panel->y) - 1); return HTOP_REDRAW_BAR; } @@ -224,7 +212,6 @@ static Htop_Reaction actionToggleKernelThreads(State* st) { static Htop_Reaction actionToggleUserlandThreads(State* st) { st->settings->hideUserlandThreads = !st->settings->hideUserlandThreads; - st->settings->hideThreads = st->settings->hideUserlandThreads; return HTOP_RECALCULATE | HTOP_SAVE_SETTINGS; } @@ -235,7 +222,10 @@ static Htop_Reaction actionToggleProgramPath(State* st) { static Htop_Reaction actionToggleTreeView(State* st) { st->settings->treeView = !st->settings->treeView; - if (st->settings->treeView) st->settings->direction = 1; + if (st->settings->treeView) { + st->settings->direction = 1; + } + ProcessList_expandTree(st->pl); return HTOP_REFRESH | HTOP_SAVE_SETTINGS | HTOP_KEEP_FOLLOWING | HTOP_REDRAW_BAR | HTOP_UPDATE_PANELHDR; } @@ -248,10 +238,21 @@ static Htop_Reaction actionIncFilter(State* st) { } static Htop_Reaction actionIncSearch(State* st) { + IncSet_reset(((MainPanel*)st->panel)->inc, INC_SEARCH); IncSet_activate(((MainPanel*)st->panel)->inc, INC_SEARCH, st->panel); return HTOP_REFRESH | HTOP_KEEP_FOLLOWING; } +static Htop_Reaction actionIncNext(State* st) { + IncSet_next(((MainPanel*)st->panel)->inc, INC_SEARCH, st->panel, (IncMode_GetPanelValue) MainPanel_getValue); + return HTOP_REFRESH | HTOP_KEEP_FOLLOWING; +} + +static Htop_Reaction actionIncPrev(State* st) { + IncSet_prev(((MainPanel*)st->panel)->inc, INC_SEARCH, st->panel, (IncMode_GetPanelValue) MainPanel_getValue); + return HTOP_REFRESH | HTOP_KEEP_FOLLOWING; +} + static Htop_Reaction actionHigherPriority(State* st) { bool changed = changePriority((MainPanel*)st->panel, -1); return changed ? HTOP_REFRESH : HTOP_OK; @@ -288,44 +289,52 @@ static Htop_Reaction actionExpandCollapseOrSortColumn(State* st) { return st->settings->treeView ? actionExpandOrCollapse(st) : actionSetSortColumn(st); } -static Htop_Reaction actionQuit() { +static Htop_Reaction actionQuit(ATTR_UNUSED State* st) { return HTOP_QUIT; } static Htop_Reaction actionSetAffinity(State* st) { if (st->pl->cpuCount == 1) return HTOP_OK; -#if (HAVE_LIBHWLOC || HAVE_LINUX_AFFINITY) + +#if (defined(HAVE_LIBHWLOC) || defined(HAVE_LINUX_AFFINITY)) Panel* panel = st->panel; - + Process* p = (Process*) Panel_getSelected(panel); - if (!p) return HTOP_OK; - Affinity* affinity = Affinity_get(p, st->pl); - if (!affinity) return HTOP_OK; - Panel* affinityPanel = AffinityPanel_new(st->pl, affinity); - Affinity_delete(affinity); + if (!p) + return HTOP_OK; + + Affinity* affinity1 = Affinity_get(p, st->pl); + if (!affinity1) + return HTOP_OK; + + int width; + Panel* affinityPanel = AffinityPanel_new(st->pl, affinity1, &width); + width += 1; /* we add a gap between the panels */ + Affinity_delete(affinity1); - void* set = Action_pickFromVector(st, affinityPanel, 15); + void* set = Action_pickFromVector(st, affinityPanel, width, true); if (set) { - Affinity* affinity = AffinityPanel_getAffinity(affinityPanel, st->pl); - bool ok = MainPanel_foreachProcess((MainPanel*)panel, (MainPanel_ForeachProcessFn) Affinity_set, (Arg){ .v = affinity }, NULL); - if (!ok) beep(); - Affinity_delete(affinity); + Affinity* affinity2 = AffinityPanel_getAffinity(affinityPanel, st->pl); + bool ok = MainPanel_foreachProcess((MainPanel*)panel, Affinity_set, (Arg) { .v = affinity2 }, NULL); + if (!ok) + beep(); + Affinity_delete(affinity2); } - Panel_delete((Object*)affinityPanel); + Object_delete(affinityPanel); #endif return HTOP_REFRESH | HTOP_REDRAW_BAR | HTOP_UPDATE_PANELHDR; } static Htop_Reaction actionKill(State* st) { - Panel* signalsPanel = (Panel*) SignalsPanel_new(); - ListItem* sgn = (ListItem*) Action_pickFromVector(st, signalsPanel, 15); + Panel* signalsPanel = SignalsPanel_new(); + ListItem* sgn = (ListItem*) Action_pickFromVector(st, signalsPanel, 15, true); if (sgn) { if (sgn->key != 0) { Panel_setHeader(st->panel, "Sending..."); Panel_draw(st->panel, true); refresh(); - MainPanel_foreachProcess((MainPanel*)st->panel, (MainPanel_ForeachProcessFn) Process_sendSignal, (Arg){ .i = sgn->key }, NULL); + MainPanel_foreachProcess((MainPanel*)st->panel, Process_sendSignal, (Arg) { .i = sgn->key }, NULL); napms(500); } } @@ -340,10 +349,10 @@ static Htop_Reaction actionFilterByUser(State* st) { Vector_insertionSort(usersPanel->items); ListItem* allUsers = ListItem_new("All users", -1); Panel_insert(usersPanel, 0, (Object*) allUsers); - ListItem* picked = (ListItem*) Action_pickFromVector(st, usersPanel, 20); + ListItem* picked = (ListItem*) Action_pickFromVector(st, usersPanel, 20, false); if (picked) { if (picked == allUsers) { - st->pl->userId = -1; + st->pl->userId = (uid_t)-1; } else { Action_setUserOnly(ListItem_getRef(picked), &(st->pl->userId)); } @@ -359,7 +368,7 @@ Htop_Reaction Action_follow(State* st) { } static Htop_Reaction actionSetup(State* st) { - Action_runSetup(st->settings, st->header, st->pl); + Action_runSetup(st); // TODO: shouldn't need this, colors should be dynamic int headerHeight = Header_calculateHeight(st->header); Panel_move(st->panel, 0, headerHeight); @@ -369,7 +378,9 @@ static Htop_Reaction actionSetup(State* st) { static Htop_Reaction actionLsof(State* st) { Process* p = (Process*) Panel_getSelected(st->panel); - if (!p) return HTOP_OK; + if (!p) + return HTOP_OK; + OpenFilesScreen* ofs = OpenFilesScreen_new(p); InfoScreen_run((InfoScreen*)ofs); OpenFilesScreen_delete((Object*)ofs); @@ -378,9 +389,22 @@ static Htop_Reaction actionLsof(State* st) { return HTOP_REFRESH | HTOP_REDRAW_BAR; } -static Htop_Reaction actionStrace(State* st) { +static Htop_Reaction actionShowLocks(State* st) { Process* p = (Process*) Panel_getSelected(st->panel); if (!p) return HTOP_OK; + ProcessLocksScreen* pls = ProcessLocksScreen_new(p); + InfoScreen_run((InfoScreen*)pls); + ProcessLocksScreen_delete((Object*)pls); + clear(); + CRT_enableDelay(); + return HTOP_REFRESH | HTOP_REDRAW_BAR; +} + +static Htop_Reaction actionStrace(State* st) { + Process* p = (Process*) Panel_getSelected(st->panel); + if (!p) + return HTOP_OK; + TraceScreen* ts = TraceScreen_new(p); bool ok = TraceScreen_forkTracer(ts); if (ok) { @@ -394,24 +418,35 @@ static Htop_Reaction actionStrace(State* st) { static Htop_Reaction actionTag(State* st) { Process* p = (Process*) Panel_getSelected(st->panel); - if (!p) return HTOP_OK; + if (!p) + return HTOP_OK; + Process_toggleTag(p); Panel_onKey(st->panel, KEY_DOWN); return HTOP_OK; } -static Htop_Reaction actionRedraw() { +static Htop_Reaction actionRedraw(ATTR_UNUSED State* st) { clear(); return HTOP_REFRESH | HTOP_REDRAW_BAR; } -static const struct { const char* key; const char* info; } helpLeft[] = { +static Htop_Reaction actionTogglePauseProcessUpdate(State* st) { + st->pauseProcessUpdate = !st->pauseProcessUpdate; + return HTOP_REFRESH | HTOP_REDRAW_BAR; +} + +static const struct { + const char* key; + const char* info; +} helpLeft[] = { { .key = " Arrows: ", .info = "scroll process list" }, { .key = " Digits: ", .info = "incremental PID search" }, { .key = " F3 /: ", .info = "incremental name search" }, { .key = " F4 \\: ",.info = "incremental name filtering" }, { .key = " F5 t: ", .info = "tree view" }, { .key = " p: ", .info = "toggle program path" }, + { .key = " Z: ", .info = "pause/resume process updates" }, { .key = " u: ", .info = "show processes of a single user" }, { .key = " H: ", .info = "hide/show user process threads" }, { .key = " K: ", .info = "hide/show kernel threads" }, @@ -423,47 +458,59 @@ static const struct { const char* key; const char* info; } helpLeft[] = { { .key = NULL, .info = NULL } }; -static const struct { const char* key; const char* info; } helpRight[] = { +static const struct { + const char* key; + const char* info; +} helpRight[] = { { .key = " Space: ", .info = "tag process" }, { .key = " c: ", .info = "tag process and its children" }, { .key = " U: ", .info = "untag all processes" }, { .key = " F9 k: ", .info = "kill process/tagged processes" }, { .key = " F7 ]: ", .info = "higher priority (root only)" }, { .key = " F8 [: ", .info = "lower priority (+ nice)" }, -#if (HAVE_LIBHWLOC || HAVE_LINUX_AFFINITY) +#if (defined(HAVE_LIBHWLOC) || defined(HAVE_LINUX_AFFINITY)) { .key = " a: ", .info = "set CPU affinity" }, #endif { .key = " e: ", .info = "show process environment" }, { .key = " i: ", .info = "set IO priority" }, { .key = " l: ", .info = "list open files with lsof" }, + { .key = " x: ", .info = "list file locks of process" }, { .key = " s: ", .info = "trace syscalls with strace" }, - { .key = " ", .info = "" }, + { .key = " w: ", .info = "wrap process command in multiple lines" }, { .key = " F2 C S: ", .info = "setup" }, { .key = " F1 h: ", .info = "show this help screen" }, { .key = " F10 q: ", .info = "quit" }, { .key = NULL, .info = NULL } }; +static inline void addattrstr( int attr, const char* str) { + attrset(attr); + addstr(str); +} + static Htop_Reaction actionHelp(State* st) { Settings* settings = st->settings; clear(); attrset(CRT_colors[HELP_BOLD]); - for (int i = 0; i < LINES-1; i++) + for (int i = 0; i < LINES - 1; i++) mvhline(i, 0, ' ', COLS); - mvaddstr(0, 0, "htop " VERSION " - " COPYRIGHT); - mvaddstr(1, 0, "Released under the GNU GPL. See 'man' page for more info."); + int line = 0; + + mvaddstr(line++, 0, "htop " VERSION " - " COPYRIGHT); + mvaddstr(line++, 0, "Released under the GNU GPLv2. See 'man' page for more info."); attrset(CRT_colors[DEFAULT_COLOR]); - mvaddstr(3, 0, "CPU usage bar: "); - #define addattrstr(a,s) attrset(a);addstr(s) + line++; + mvaddstr(line++, 0, "CPU usage bar: "); + addattrstr(CRT_colors[BAR_BORDER], "["); if (settings->detailedCPUTime) { addattrstr(CRT_colors[CPU_NICE_TEXT], "low"); addstr("/"); addattrstr(CRT_colors[CPU_NORMAL], "normal"); addstr("/"); - addattrstr(CRT_colors[CPU_KERNEL], "kernel"); addstr("/"); + addattrstr(CRT_colors[CPU_SYSTEM], "kernel"); addstr("/"); addattrstr(CRT_colors[CPU_IRQ], "irq"); addstr("/"); addattrstr(CRT_colors[CPU_SOFTIRQ], "soft-irq"); addstr("/"); addattrstr(CRT_colors[CPU_STEAL], "steal"); addstr("/"); @@ -473,13 +520,13 @@ static Htop_Reaction actionHelp(State* st) { } else { addattrstr(CRT_colors[CPU_NICE_TEXT], "low-priority"); addstr("/"); addattrstr(CRT_colors[CPU_NORMAL], "normal"); addstr("/"); - addattrstr(CRT_colors[CPU_KERNEL], "kernel"); addstr("/"); + addattrstr(CRT_colors[CPU_SYSTEM], "kernel"); addstr("/"); addattrstr(CRT_colors[CPU_GUEST], "virtualiz"); addattrstr(CRT_colors[BAR_SHADOW], " used%"); } addattrstr(CRT_colors[BAR_BORDER], "]"); attrset(CRT_colors[DEFAULT_COLOR]); - mvaddstr(4, 0, "Memory bar: "); + mvaddstr(line++, 0, "Memory bar: "); addattrstr(CRT_colors[BAR_BORDER], "["); addattrstr(CRT_colors[MEMORY_USED], "used"); addstr("/"); addattrstr(CRT_colors[MEMORY_BUFFERS_TEXT], "buffers"); addstr("/"); @@ -487,29 +534,49 @@ static Htop_Reaction actionHelp(State* st) { addattrstr(CRT_colors[BAR_SHADOW], " used/total"); addattrstr(CRT_colors[BAR_BORDER], "]"); attrset(CRT_colors[DEFAULT_COLOR]); - mvaddstr(5, 0, "Swap bar: "); + mvaddstr(line++, 0, "Swap bar: "); addattrstr(CRT_colors[BAR_BORDER], "["); addattrstr(CRT_colors[SWAP], "used"); addattrstr(CRT_colors[BAR_SHADOW], " used/total"); addattrstr(CRT_colors[BAR_BORDER], "]"); attrset(CRT_colors[DEFAULT_COLOR]); - mvaddstr(6,0, "Type and layout of header meters are configurable in the setup screen."); + mvaddstr(line++, 0, "Type and layout of header meters are configurable in the setup screen."); if (CRT_colorScheme == COLORSCHEME_MONOCHROME) { - mvaddstr(7, 0, "In monochrome, meters display as different chars, in order: |#*@$%&."); + mvaddstr(line, 0, "In monochrome, meters display as different chars, in order: |#*@$%&."); } - mvaddstr( 8, 0, " Status: R: running; S: sleeping; T: traced/stopped; Z: zombie; D: disk sleep"); - for (int i = 0; helpLeft[i].info; i++) { mvaddstr(9+i, 9, helpLeft[i].info); } - for (int i = 0; helpRight[i].info; i++) { mvaddstr(9+i, 49, helpRight[i].info); } - attrset(CRT_colors[HELP_BOLD]); - for (int i = 0; helpLeft[i].key; i++) { mvaddstr(9+i, 0, helpLeft[i].key); } - for (int i = 0; helpRight[i].key; i++) { mvaddstr(9+i, 40, helpRight[i].key); } - attrset(CRT_colors[PROCESS_THREAD]); - mvaddstr(16, 32, "threads"); - mvaddstr(17, 26, "threads"); - attrset(CRT_colors[DEFAULT_COLOR]); + line++; + + mvaddstr(line++, 0, "Process state: R: running; S: sleeping; T: traced/stopped; Z: zombie; D: disk sleep"); + + line++; + + int item; + for (item = 0; helpLeft[item].key; item++) { + attrset(CRT_colors[DEFAULT_COLOR]); + mvaddstr(line + item, 9, helpLeft[item].info); + attrset(CRT_colors[HELP_BOLD]); + mvaddstr(line + item, 0, helpLeft[item].key); + if (String_eq(helpLeft[item].key, " H: ")) { + attrset(CRT_colors[PROCESS_THREAD]); + mvaddstr(line + item, 32, "threads"); + } else if (String_eq(helpLeft[item].key, " K: ")) { + attrset(CRT_colors[PROCESS_THREAD]); + mvaddstr(line + item, 26, "threads"); + } + } + int leftHelpItems = item; + + for (item = 0; helpRight[item].key; item++) { + attrset(CRT_colors[HELP_BOLD]); + mvaddstr(line + item, 40, helpRight[item].key); + attrset(CRT_colors[DEFAULT_COLOR]); + mvaddstr(line + item, 49, helpRight[item].info); + } + line += MAXIMUM(leftHelpItems, item); + line++; attrset(CRT_colors[HELP_BOLD]); - mvaddstr(23,0, "Press any key to return."); + mvaddstr(line++, 0, "Press any key to return."); attrset(CRT_colors[DEFAULT_COLOR]); refresh(); CRT_readKey(); @@ -528,14 +595,18 @@ static Htop_Reaction actionUntagAll(State* st) { static Htop_Reaction actionTagAllChildren(State* st) { Process* p = (Process*) Panel_getSelected(st->panel); - if (!p) return HTOP_OK; + if (!p) + return HTOP_OK; + tagAllChildren(st->panel, p); return HTOP_OK; } static Htop_Reaction actionShowEnvScreen(State* st) { Process* p = (Process*) Panel_getSelected(st->panel); - if (!p) return HTOP_OK; + if (!p) + return HTOP_OK; + EnvScreen* es = EnvScreen_new(p); InfoScreen_run((InfoScreen*)es); EnvScreen_delete((Object*)es); @@ -544,6 +615,18 @@ static Htop_Reaction actionShowEnvScreen(State* st) { return HTOP_REFRESH | HTOP_REDRAW_BAR; } +static Htop_Reaction actionShowCommandScreen(State* st) { + Process* p = (Process*) Panel_getSelected(st->panel); + if (!p) + return HTOP_OK; + + CommandScreen* cmdScr = CommandScreen_new(p); + InfoScreen_run((InfoScreen*)cmdScr); + CommandScreen_delete((Object*)cmdScr); + clear(); + CRT_enableDelay(); + return HTOP_REFRESH | HTOP_REDRAW_BAR; +} void Action_setBindings(Htop_Action* keys) { keys[KEY_RESIZE] = actionResize; @@ -559,6 +642,8 @@ void Action_setBindings(Htop_Action* keys) { keys['\\'] = actionIncFilter; keys[KEY_F(3)] = actionIncSearch; keys['/'] = actionIncSearch; + keys['n'] = actionIncNext; + keys['N'] = actionIncPrev; keys[']'] = actionHigherPriority; keys[KEY_F(7)] = actionHigherPriority; @@ -586,6 +671,7 @@ void Action_setBindings(Htop_Action* keys) { keys['S'] = actionSetup; keys['C'] = actionSetup; keys[KEY_F(2)] = actionSetup; + keys['x'] = actionShowLocks; keys['l'] = actionLsof; keys['s'] = actionStrace; keys[' '] = actionTag; @@ -596,5 +682,6 @@ void Action_setBindings(Htop_Action* keys) { keys['U'] = actionUntagAll; keys['c'] = actionTagAllChildren; keys['e'] = actionShowEnvScreen; + keys['w'] = actionShowCommandScreen; + keys['Z'] = actionTogglePauseProcessUpdate; } - diff --git a/Action.h b/Action.h index 1dfdcb476..68aa2e2ed 100644 --- a/Action.h +++ b/Action.h @@ -1,21 +1,24 @@ -/* Do not edit this file. It was automatically generated. */ - #ifndef HEADER_Action #define HEADER_Action /* htop - Action.h (C) 2015 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ +#include "config.h" // IWYU pragma: keep + +#include +#include -#include "IncSet.h" -#include "Settings.h" #include "Header.h" -#include "UsersTable.h" -#include "ProcessList.h" +#include "Object.h" #include "Panel.h" +#include "Process.h" +#include "ProcessList.h" +#include "Settings.h" +#include "UsersTable.h" typedef enum { HTOP_OK = 0x00, @@ -28,31 +31,25 @@ typedef enum { HTOP_UPDATE_PANELHDR = 0x41, // implies HTOP_REFRESH } Htop_Reaction; -typedef Htop_Reaction (*Htop_Action)(); - typedef struct State_ { Settings* settings; UsersTable* ut; ProcessList* pl; Panel* panel; Header* header; + bool pauseProcessUpdate; } State; +typedef Htop_Reaction (*Htop_Action)(State* st); -Object* Action_pickFromVector(State* st, Panel* list, int x); - -// ---------------------------------------- +Object* Action_pickFromVector(State* st, Panel* list, int x, bool followProcess); bool Action_setUserOnly(const char* userName, uid_t* userId); Htop_Reaction Action_setSortKey(Settings* settings, ProcessField sortKey); -// ---------------------------------------- - Htop_Reaction Action_follow(State* st); - void Action_setBindings(Htop_Action* keys); - #endif diff --git a/Affinity.c b/Affinity.c index c928fec16..6fb5846c7 100644 --- a/Affinity.c +++ b/Affinity.c @@ -1,37 +1,31 @@ /* htop - Affinity.c (C) 2004-2011 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +(C) 2020 Red Hat, Inc. All Rights Reserved. +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ +#include "config.h" + #include "Affinity.h" #include +#include "XUtils.h" + #ifdef HAVE_LIBHWLOC #include -#if __linux__ +#include +#ifdef __linux__ #define HTOP_HWLOC_CPUBIND_FLAG HWLOC_CPUBIND_THREAD #else #define HTOP_HWLOC_CPUBIND_FLAG HWLOC_CPUBIND_PROCESS #endif -#elif HAVE_LINUX_AFFINITY +#elif defined(HAVE_LINUX_AFFINITY) #include #endif -/*{ -#include "Process.h" -#include "ProcessList.h" - -typedef struct Affinity_ { - ProcessList* pl; - int size; - int used; - int* cpus; -} Affinity; - -}*/ Affinity* Affinity_new(ProcessList* pl) { Affinity* this = xCalloc(1, sizeof(Affinity)); @@ -71,7 +65,7 @@ Affinity* Affinity_get(Process* proc, ProcessList* pl) { } else { unsigned int id; hwloc_bitmap_foreach_begin(id, cpuset); - Affinity_add(affinity, id); + Affinity_add(affinity, id); hwloc_bitmap_foreach_end(); } } @@ -79,7 +73,8 @@ Affinity* Affinity_get(Process* proc, ProcessList* pl) { return affinity; } -bool Affinity_set(Process* proc, Affinity* this) { +bool Affinity_set(Process* proc, Arg arg) { + Affinity* this = arg.v; hwloc_cpuset_t cpuset = hwloc_bitmap_alloc(); for (int i = 0; i < this->used; i++) { hwloc_bitmap_set(cpuset, this->cpus[i]); @@ -89,21 +84,25 @@ bool Affinity_set(Process* proc, Affinity* this) { return ok; } -#elif HAVE_LINUX_AFFINITY +#elif defined(HAVE_LINUX_AFFINITY) Affinity* Affinity_get(Process* proc, ProcessList* pl) { cpu_set_t cpuset; bool ok = (sched_getaffinity(proc->pid, sizeof(cpu_set_t), &cpuset) == 0); - if (!ok) return NULL; + if (!ok) + return NULL; + Affinity* affinity = Affinity_new(pl); for (int i = 0; i < pl->cpuCount; i++) { - if (CPU_ISSET(i, &cpuset)) + if (CPU_ISSET(i, &cpuset)) { Affinity_add(affinity, i); + } } return affinity; } -bool Affinity_set(Process* proc, Affinity* this) { +bool Affinity_set(Process* proc, Arg arg) { + Affinity* this = arg.v; cpu_set_t cpuset; CPU_ZERO(&cpuset); for (int i = 0; i < this->used; i++) { diff --git a/Affinity.h b/Affinity.h index fd2c599ee..0797b3664 100644 --- a/Affinity.h +++ b/Affinity.h @@ -1,26 +1,25 @@ -/* Do not edit this file. It was automatically generated. */ - #ifndef HEADER_Affinity #define HEADER_Affinity /* htop - Affinity.h (C) 2004-2011 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +(C) 2020 Red Hat, Inc. All Rights Reserved. +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ -#ifdef HAVE_LIBHWLOC -#if __linux__ -#define HTOP_HWLOC_CPUBIND_FLAG HWLOC_CPUBIND_THREAD -#else -#define HTOP_HWLOC_CPUBIND_FLAG HWLOC_CPUBIND_PROCESS -#endif -#elif HAVE_LINUX_AFFINITY -#endif +#include "config.h" +#include + +#include "Object.h" #include "Process.h" #include "ProcessList.h" +#if defined(HAVE_LIBHWLOC) && defined(HAVE_LINUX_AFFINITY) +#error hwlock and linux affinity are mutual exclusive. +#endif + typedef struct Affinity_ { ProcessList* pl; int size; @@ -28,24 +27,17 @@ typedef struct Affinity_ { int* cpus; } Affinity; - Affinity* Affinity_new(ProcessList* pl); void Affinity_delete(Affinity* this); void Affinity_add(Affinity* this, int id); -#ifdef HAVE_LIBHWLOC - -Affinity* Affinity_get(Process* proc, ProcessList* pl); - -bool Affinity_set(Process* proc, Affinity* this); - -#elif HAVE_LINUX_AFFINITY +#if defined(HAVE_LIBHWLOC) || defined(HAVE_LINUX_AFFINITY) Affinity* Affinity_get(Process* proc, ProcessList* pl); -bool Affinity_set(Process* proc, Affinity* this); +bool Affinity_set(Process* proc, Arg arg); #endif diff --git a/AffinityPanel.c b/AffinityPanel.c index d9f1612bd..9c2a6e7c4 100644 --- a/AffinityPanel.c +++ b/AffinityPanel.c @@ -1,76 +1,440 @@ /* htop - AffinityPanel.c (C) 2004-2011 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ -#include "AffinityPanel.h" -#include "CRT.h" +#include "config.h" // IWYU pragma: keep -#include "CheckItem.h" +#include "AffinityPanel.h" #include +#include +#include #include -/*{ -#include "Panel.h" -#include "Affinity.h" -#include "ProcessList.h" -#include "ListItem.h" -}*/ +#include "CRT.h" +#include "FunctionBar.h" +#include "Object.h" +#include "ProvideCurses.h" +#include "RichString.h" +#include "Settings.h" +#include "Vector.h" +#include "XUtils.h" + +#ifdef HAVE_LIBHWLOC +#include +#include +#endif + + +typedef struct MaskItem_ { + Object super; + char* text; + char* indent; /* used also as an condition whether this is a tree node */ + int value; /* tri-state: 0 - off, 1 - some set, 2 - all set */ + int sub_tree; /* tri-state: 0 - no sub-tree, 1 - open sub-tree, 2 - closed sub-tree */ + Vector* children; + #ifdef HAVE_LIBHWLOC + bool ownCpuset; + hwloc_bitmap_t cpuset; + #else + int cpu; + #endif +} MaskItem; + +static void MaskItem_delete(Object* cast) { + MaskItem* this = (MaskItem*) cast; + free(this->text); + free(this->indent); + Vector_delete(this->children); + #ifdef HAVE_LIBHWLOC + if (this->ownCpuset) + hwloc_bitmap_free(this->cpuset); + #endif + free(this); +} + +static void MaskItem_display(const Object* cast, RichString* out) { + const MaskItem* this = (const MaskItem*)cast; + assert (this != NULL); + RichString_append(out, CRT_colors[CHECK_BOX], "["); + if (this->value == 2) { + RichString_append(out, CRT_colors[CHECK_MARK], "x"); + } else if (this->value == 1) { + RichString_append(out, CRT_colors[CHECK_MARK], "o"); + } else { + RichString_append(out, CRT_colors[CHECK_MARK], " "); + } + RichString_append(out, CRT_colors[CHECK_BOX], "]"); + RichString_append(out, CRT_colors[CHECK_TEXT], " "); + if (this->indent) { + RichString_append(out, CRT_colors[PROCESS_TREE], this->indent); + RichString_append(out, CRT_colors[PROCESS_TREE], + this->sub_tree == 2 + ? CRT_treeStr[TREE_STR_OPEN] + : CRT_treeStr[TREE_STR_SHUT]); + RichString_append(out, CRT_colors[CHECK_TEXT], " "); + } + RichString_append(out, CRT_colors[CHECK_TEXT], this->text); +} + +static const ObjectClass MaskItem_class = { + .display = MaskItem_display, + .delete = MaskItem_delete +}; + +#ifdef HAVE_LIBHWLOC + +static MaskItem* MaskItem_newMask(const char* text, const char* indent, hwloc_bitmap_t cpuset, bool owner) { + MaskItem* this = AllocThis(MaskItem); + this->text = xStrdup(text); + this->indent = xStrdup(indent); /* nonnull for tree node */ + this->value = 0; + this->ownCpuset = owner; + this->cpuset = cpuset; + this->sub_tree = hwloc_bitmap_weight(cpuset) > 1 ? 1 : 0; + this->children = Vector_new(Class(MaskItem), true, DEFAULT_SIZE); + return this; +} + +#endif + +static MaskItem* MaskItem_newSingleton(const char* text, int cpu, bool isSet) { + MaskItem* this = AllocThis(MaskItem); + this->text = xStrdup(text); + this->indent = NULL; /* not a tree node */ + this->sub_tree = 0; + this->children = Vector_new(Class(MaskItem), true, DEFAULT_SIZE); + + #ifdef HAVE_LIBHWLOC + this->ownCpuset = true; + this->cpuset = hwloc_bitmap_alloc(); + hwloc_bitmap_set(this->cpuset, cpu); + #else + this->cpu = cpu; + #endif + this->value = isSet ? 2 : 0; + + return this; +} + +typedef struct AffinityPanel_ { + Panel super; + ProcessList* pl; + bool topoView; + Vector* cpuids; + unsigned width; + + #ifdef HAVE_LIBHWLOC + MaskItem* topoRoot; + hwloc_const_cpuset_t allCpuset; + hwloc_bitmap_t workCpuset; + #endif +} AffinityPanel; + +static void AffinityPanel_delete(Object* cast) { + AffinityPanel* this = (AffinityPanel*) cast; + Panel* super = (Panel*) this; + Panel_done(super); + Vector_delete(this->cpuids); + #ifdef HAVE_LIBHWLOC + hwloc_bitmap_free(this->workCpuset); + MaskItem_delete((Object*) this->topoRoot); + #endif + free(this); +} + +#ifdef HAVE_LIBHWLOC + +static void AffinityPanel_updateItem(AffinityPanel* this, MaskItem* item) { + Panel* super = (Panel*) this; + + item->value = hwloc_bitmap_isincluded(item->cpuset, this->workCpuset) ? 2 : + hwloc_bitmap_intersects(item->cpuset, this->workCpuset) ? 1 : 0; + + Panel_add(super, (Object*) item); +} + +static void AffinityPanel_updateTopo(AffinityPanel* this, MaskItem* item) { + AffinityPanel_updateItem(this, item); + + if (item->sub_tree == 2) + return; + + for (int i = 0; i < Vector_size(item->children); i++) + AffinityPanel_updateTopo(this, (MaskItem*) Vector_get(item->children, i)); +} + +#endif + +static void AffinityPanel_update(AffinityPanel* this, bool keepSelected) { + Panel* super = (Panel*) this; + + FunctionBar_setLabel(super->currentBar, KEY_F(3), this->topoView ? "Collapse/Expand" : ""); + FunctionBar_draw(super->currentBar); + + int oldSelected = Panel_getSelectedIndex(super); + Panel_prune(super); + + #ifdef HAVE_LIBHWLOC + if (this->topoView) { + AffinityPanel_updateTopo(this, this->topoRoot); + } else { + for (int i = 0; i < Vector_size(this->cpuids); i++) { + AffinityPanel_updateItem(this, (MaskItem*) Vector_get(this->cpuids, i)); + } + } + #else + Panel_splice(super, this->cpuids); + #endif + + if (keepSelected) + Panel_setSelected(super, oldSelected); + + super->needsRedraw = true; +} + +static HandlerResult AffinityPanel_eventHandler(Panel* super, int ch) { + AffinityPanel* this = (AffinityPanel*) super; + HandlerResult result = IGNORED; + MaskItem* selected = (MaskItem*) Panel_getSelected(super); + bool keepSelected = true; -static HandlerResult AffinityPanel_eventHandler(Panel* this, int ch) { - CheckItem* selected = (CheckItem*) Panel_getSelected(this); switch(ch) { case KEY_MOUSE: case KEY_RECLICK: case ' ': - CheckItem_set(selected, ! (CheckItem_get(selected)) ); - return HANDLED; + #ifdef HAVE_LIBHWLOC + if (selected->value == 2) { + /* Item was selected, so remove this mask from the top cpuset. */ + hwloc_bitmap_andnot(this->workCpuset, this->workCpuset, selected->cpuset); + selected->value = 0; + } else { + /* Item was not or only partial selected, so set all bits from this object + in the top cpuset. */ + hwloc_bitmap_or(this->workCpuset, this->workCpuset, selected->cpuset); + selected->value = 2; + } + #else + selected->value = selected->value ? 0 : 2; /* toggle between 0 and 2 */ + #endif + + result = HANDLED; + break; + + #ifdef HAVE_LIBHWLOC + + case KEY_F(1): + hwloc_bitmap_copy(this->workCpuset, this->allCpuset); + result = HANDLED; + break; + + case KEY_F(2): + this->topoView = !this->topoView; + keepSelected = false; + + result = HANDLED; + break; + + case KEY_F(3): + case '-': + case '+': + if (selected->sub_tree) + selected->sub_tree = 1 + !(selected->sub_tree - 1); /* toggle between 1 and 2 */ + + result = HANDLED; + break; + + #endif + case 0x0a: case 0x0d: case KEY_ENTER: - return BREAK_LOOP; + result = BREAK_LOOP; + break; + } + + if (HANDLED == result) + AffinityPanel_update(this, keepSelected); + + return result; +} + +#ifdef HAVE_LIBHWLOC + +static MaskItem* AffinityPanel_addObject(AffinityPanel* this, hwloc_obj_t obj, unsigned indent, MaskItem* parent) { + const char* type_name = hwloc_obj_type_string(obj->type); + const char* index_prefix = "#"; + unsigned depth = obj->depth; + unsigned index = obj->logical_index; + size_t off = 0, left = 10 * depth; + char buf[64], indent_buf[left + 1]; + + if (obj->type == HWLOC_OBJ_PU) { + index = Settings_cpuId(this->pl->settings, obj->os_index); + type_name = "CPU"; + index_prefix = ""; + } + + indent_buf[0] = '\0'; + if (depth > 0) { + for (unsigned i = 1; i < depth; i++) { + xSnprintf(&indent_buf[off], left, "%s ", (indent & (1u << i)) ? CRT_treeStr[TREE_STR_VERT] : " "); + size_t len = strlen(&indent_buf[off]); + off += len; + left -= len; + } + xSnprintf(&indent_buf[off], left, "%s", + obj->next_sibling ? CRT_treeStr[TREE_STR_RTEE] : CRT_treeStr[TREE_STR_BEND]); + // Uncomment when further appending to indent_buf + //size_t len = strlen(&indent_buf[off]); + //off += len; + //left -= len; + } + + xSnprintf(buf, 64, "%s %s%u", type_name, index_prefix, index); + + MaskItem* item = MaskItem_newMask(buf, indent_buf, obj->complete_cpuset, false); + if (parent) + Vector_add(parent->children, item); + + if (item->sub_tree && parent && parent->sub_tree == 1) { + /* if obj is fully included or fully excluded, collapse the item */ + hwloc_bitmap_t result = hwloc_bitmap_alloc(); + hwloc_bitmap_and(result, obj->complete_cpuset, this->workCpuset); + int weight = hwloc_bitmap_weight(result); + hwloc_bitmap_free(result); + if (weight == 0 || weight == (hwloc_bitmap_weight(this->workCpuset) + hwloc_bitmap_weight(obj->complete_cpuset))) { + item->sub_tree = 2; + } + } + + /* "[x] " + "|- " * depth + ("- ")?(if root node) + name */ + unsigned width = 4 + 3 * depth + (2 * !depth) + strlen(buf); + if (width > this->width) { + this->width = width; + } + + return item; +} + +static MaskItem* AffinityPanel_buildTopology(AffinityPanel* this, hwloc_obj_t obj, unsigned indent, MaskItem* parent) { + MaskItem* item = AffinityPanel_addObject(this, obj, indent, parent); + if (obj->next_sibling) { + indent |= (1u << obj->depth); + } else { + indent &= ~(1u << obj->depth); + } + + for (unsigned i = 0; i < obj->arity; i++) { + AffinityPanel_buildTopology(this, obj->children[i], indent, item); } - return IGNORED; + + return parent == NULL ? item : NULL; } -PanelClass AffinityPanel_class = { +#endif + +const PanelClass AffinityPanel_class = { .super = { .extends = Class(Panel), - .delete = Panel_delete + .delete = AffinityPanel_delete }, .eventHandler = AffinityPanel_eventHandler }; -Panel* AffinityPanel_new(ProcessList* pl, Affinity* affinity) { - Panel* this = Panel_new(1, 1, 1, 1, true, Class(CheckItem), FunctionBar_newEnterEsc("Set ", "Cancel ")); - Object_setClass(this, Class(AffinityPanel)); +static const char* const AffinityPanelFunctions[] = { + "Set ", + "Cancel ", + #ifdef HAVE_LIBHWLOC + "All", + "Topology", + " ", + #endif + NULL +}; +static const char* const AffinityPanelKeys[] = {"Enter", "Esc", "F1", "F2", "F3"}; +static const int AffinityPanelEvents[] = {13, 27, KEY_F(1), KEY_F(2), KEY_F(3)}; + +Panel* AffinityPanel_new(ProcessList* pl, Affinity* affinity, int* width) { + AffinityPanel* this = AllocThis(AffinityPanel); + Panel* super = (Panel*) this; + Panel_init(super, 1, 1, 1, 1, Class(MaskItem), false, FunctionBar_new(AffinityPanelFunctions, AffinityPanelKeys, AffinityPanelEvents)); + + this->pl = pl; + /* defaults to 15, this also includes the gap between the panels, + * but this will be added by the caller */ + this->width = 14; + + this->cpuids = Vector_new(Class(MaskItem), true, DEFAULT_SIZE); + + #ifdef HAVE_LIBHWLOC + this->topoView = pl->settings->topologyAffinity; + #else + this->topoView = false; + #endif + + #ifdef HAVE_LIBHWLOC + this->allCpuset = hwloc_topology_get_complete_cpuset(pl->topology); + this->workCpuset = hwloc_bitmap_alloc(); + #endif + + Panel_setHeader(super, "Use CPUs:"); - Panel_setHeader(this, "Use CPUs:"); int curCpu = 0; for (int i = 0; i < pl->cpuCount; i++) { - char number[10]; - xSnprintf(number, 9, "%d", Settings_cpuId(pl->settings, i)); - bool mode; + char number[16]; + xSnprintf(number, 9, "CPU %d", Settings_cpuId(pl->settings, i)); + unsigned cpu_width = 4 + strlen(number); + if (cpu_width > this->width) { + this->width = cpu_width; + } + + bool isSet = false; if (curCpu < affinity->used && affinity->cpus[curCpu] == i) { - mode = true; + #ifdef HAVE_LIBHWLOC + hwloc_bitmap_set(this->workCpuset, i); + #endif + isSet = true; curCpu++; - } else { - mode = false; } - Panel_add(this, (Object*) CheckItem_newByVal(xStrdup(number), mode)); + + MaskItem* cpuItem = MaskItem_newSingleton(number, i, isSet); + Vector_add(this->cpuids, (Object*) cpuItem); } - return this; + + #ifdef HAVE_LIBHWLOC + this->topoRoot = AffinityPanel_buildTopology(this, hwloc_get_root_obj(pl->topology), 0, NULL); + #endif + + if (width) { + *width = this->width; + } + + AffinityPanel_update(this, false); + + return super; } -Affinity* AffinityPanel_getAffinity(Panel* this, ProcessList* pl) { +Affinity* AffinityPanel_getAffinity(Panel* super, ProcessList* pl) { + AffinityPanel* this = (AffinityPanel*) super; Affinity* affinity = Affinity_new(pl); - int size = Panel_size(this); - for (int i = 0; i < size; i++) { - if (CheckItem_get((CheckItem*)Panel_get(this, i))) - Affinity_add(affinity, i); + + #ifdef HAVE_LIBHWLOC + int i; + hwloc_bitmap_foreach_begin(i, this->workCpuset) + Affinity_add(affinity, i); + hwloc_bitmap_foreach_end(); + #else + for (int i = 0; i < this->pl->cpuCount; i++) { + MaskItem* item = (MaskItem*)Vector_get(this->cpuids, i); + if (item->value) { + Affinity_add(affinity, item->cpu); + } } + #endif + return affinity; } diff --git a/AffinityPanel.h b/AffinityPanel.h index 2b6059b08..fdefeae40 100644 --- a/AffinityPanel.h +++ b/AffinityPanel.h @@ -1,23 +1,20 @@ -/* Do not edit this file. It was automatically generated. */ - #ifndef HEADER_AffinityPanel #define HEADER_AffinityPanel /* htop - AffinityPanel.h (C) 2004-2011 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ #include "Panel.h" #include "Affinity.h" #include "ProcessList.h" -#include "ListItem.h" -extern PanelClass AffinityPanel_class; +extern const PanelClass AffinityPanel_class; -Panel* AffinityPanel_new(ProcessList* pl, Affinity* affinity); +Panel* AffinityPanel_new(ProcessList* pl, Affinity* affinity, int* width); -Affinity* AffinityPanel_getAffinity(Panel* this, ProcessList* pl); +Affinity* AffinityPanel_getAffinity(Panel* super, ProcessList* pl); #endif diff --git a/AvailableColumnsPanel.c b/AvailableColumnsPanel.c index 1e548dce9..feea5786b 100644 --- a/AvailableColumnsPanel.c +++ b/AvailableColumnsPanel.c @@ -1,30 +1,25 @@ /* htop - AvailableColumnsPanel.c (C) 2004-2011 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ #include "AvailableColumnsPanel.h" -#include "Platform.h" - -#include "Header.h" -#include "ColumnsPanel.h" -#include -#include #include -#include - -/*{ -#include "Panel.h" +#include +#include -typedef struct AvailableColumnsPanel_ { - Panel super; - Panel* columns; -} AvailableColumnsPanel; +#include "ColumnsPanel.h" +#include "FunctionBar.h" +#include "ListItem.h" +#include "Object.h" +#include "Platform.h" +#include "Process.h" +#include "ProvideCurses.h" +#include "XUtils.h" -}*/ static const char* const AvailableColumnsFunctions[] = {" ", " ", " ", " ", "Add ", " ", " ", " ", " ", "Done ", NULL}; @@ -37,7 +32,6 @@ static void AvailableColumnsPanel_delete(Object* object) { static HandlerResult AvailableColumnsPanel_eventHandler(Panel* super, int ch) { AvailableColumnsPanel* this = (AvailableColumnsPanel*) super; - int key = ((ListItem*) Panel_getSelected(super))->key; HandlerResult result = IGNORED; switch(ch) { @@ -45,6 +39,11 @@ static HandlerResult AvailableColumnsPanel_eventHandler(Panel* super, int ch) { case KEY_ENTER: case KEY_F(5): { + const ListItem* selected = (ListItem*) Panel_getSelected(super); + if (!selected) + break; + + int key = selected->key; int at = Panel_getSelectedIndex(this->columns); Panel_insert(this->columns, at, (Object*) ListItem_new(Process_fields[key].name, key)); Panel_setSelected(this->columns, at+1); @@ -54,7 +53,7 @@ static HandlerResult AvailableColumnsPanel_eventHandler(Panel* super, int ch) { } default: { - if (ch < 255 && isalpha(ch)) + if (0 < ch && ch < 255 && isalpha((unsigned char)ch)) result = Panel_selectByTyping(super, ch); break; } @@ -62,7 +61,7 @@ static HandlerResult AvailableColumnsPanel_eventHandler(Panel* super, int ch) { return result; } -PanelClass AvailableColumnsPanel_class = { +const PanelClass AvailableColumnsPanel_class = { .super = { .extends = Class(Panel), .delete = AvailableColumnsPanel_delete diff --git a/AvailableColumnsPanel.h b/AvailableColumnsPanel.h index 5a8371ddb..8672eb9e7 100644 --- a/AvailableColumnsPanel.h +++ b/AvailableColumnsPanel.h @@ -1,11 +1,9 @@ -/* Do not edit this file. It was automatically generated. */ - #ifndef HEADER_AvailableColumnsPanel #define HEADER_AvailableColumnsPanel /* htop - AvailableColumnsPanel.h (C) 2004-2011 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ @@ -16,8 +14,7 @@ typedef struct AvailableColumnsPanel_ { Panel* columns; } AvailableColumnsPanel; - -extern PanelClass AvailableColumnsPanel_class; +extern const PanelClass AvailableColumnsPanel_class; AvailableColumnsPanel* AvailableColumnsPanel_new(Panel* columns); diff --git a/AvailableMetersPanel.c b/AvailableMetersPanel.c index ddb553679..33006e94e 100644 --- a/AvailableMetersPanel.c +++ b/AvailableMetersPanel.c @@ -1,38 +1,27 @@ /* htop - AvailableMetersPanel.c (C) 2004-2011 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ #include "AvailableMetersPanel.h" -#include "MetersPanel.h" + +#include +#include +#include #include "CPUMeter.h" +#include "FunctionBar.h" #include "Header.h" #include "ListItem.h" +#include "Meter.h" +#include "MetersPanel.h" +#include "Object.h" #include "Platform.h" +#include "ProvideCurses.h" +#include "XUtils.h" -#include -#include - -/*{ -#include "Settings.h" -#include "Panel.h" -#include "ScreenManager.h" -#include "ProcessList.h" - -typedef struct AvailableMetersPanel_ { - Panel super; - ScreenManager* scr; - - Settings* settings; - Header* header; - Panel* leftPanel; - Panel* rightPanel; -} AvailableMetersPanel; - -}*/ static void AvailableMetersPanel_delete(Object* object) { Panel* super = (Panel*) object; @@ -41,19 +30,22 @@ static void AvailableMetersPanel_delete(Object* object) { free(this); } -static inline void AvailableMetersPanel_addMeter(Header* header, Panel* panel, MeterClass* type, int param, int column) { - Meter* meter = (Meter*) Header_addMeterByClass(header, type, param, column); +static inline void AvailableMetersPanel_addMeter(Header* header, Panel* panel, const MeterClass* type, int param, int column) { + Meter* meter = Header_addMeterByClass(header, type, param, column); Panel_add(panel, (Object*) Meter_toListItem(meter, false)); Panel_setSelected(panel, Panel_size(panel) - 1); MetersPanel_setMoving((MetersPanel*)panel, true); - FunctionBar_draw(panel->currentBar, NULL); + FunctionBar_draw(panel->currentBar); } static HandlerResult AvailableMetersPanel_eventHandler(Panel* super, int ch) { AvailableMetersPanel* this = (AvailableMetersPanel*) super; Header* header = this->header; - - ListItem* selected = (ListItem*) Panel_getSelected(super); + + const ListItem* selected = (ListItem*) Panel_getSelected(super); + if (!selected) + return IGNORED; + int param = selected->key & 0xff; int type = selected->key >> 16; HandlerResult result = IGNORED; @@ -91,7 +83,7 @@ static HandlerResult AvailableMetersPanel_eventHandler(Panel* super, int ch) { return result; } -PanelClass AvailableMetersPanel_class = { +const PanelClass AvailableMetersPanel_class = { .super = { .extends = Class(Panel), .delete = AvailableMetersPanel_delete @@ -104,7 +96,7 @@ AvailableMetersPanel* AvailableMetersPanel_new(Settings* settings, Header* heade Panel* super = (Panel*) this; FunctionBar* fuBar = FunctionBar_newEnterEsc("Add ", "Done "); Panel_init(super, 1, 1, 1, 1, Class(ListItem), true, fuBar); - + this->settings = settings; this->header = header; this->leftPanel = leftMeters; @@ -115,19 +107,19 @@ AvailableMetersPanel* AvailableMetersPanel_new(Settings* settings, Header* heade // Platform_meterTypes[0] should be always (&CPUMeter_class), which we will // handle separately in the code below. for (int i = 1; Platform_meterTypes[i]; i++) { - MeterClass* type = Platform_meterTypes[i]; + const MeterClass* type = Platform_meterTypes[i]; assert(type != &CPUMeter_class); const char* label = type->description ? type->description : type->uiName; Panel_add(super, (Object*) ListItem_new(label, i << 16)); } // Handle (&CPUMeter_class) - MeterClass* type = &CPUMeter_class; + const MeterClass* type = &CPUMeter_class; int cpus = pl->cpuCount; if (cpus > 1) { Panel_add(super, (Object*) ListItem_new("CPU average", 0)); for (int i = 1; i <= cpus; i++) { char buffer[50]; - xSnprintf(buffer, 50, "%s %d", type->uiName, i); + xSnprintf(buffer, 50, "%s %d", type->uiName, Settings_cpuId(this->settings, i - 1)); Panel_add(super, (Object*) ListItem_new(buffer, i)); } } else { diff --git a/AvailableMetersPanel.h b/AvailableMetersPanel.h index e9b949b0c..f7359365f 100644 --- a/AvailableMetersPanel.h +++ b/AvailableMetersPanel.h @@ -1,18 +1,17 @@ -/* Do not edit this file. It was automatically generated. */ - #ifndef HEADER_AvailableMetersPanel #define HEADER_AvailableMetersPanel /* htop - AvailableMetersPanel.h (C) 2004-2011 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ -#include "Settings.h" +#include "Header.h" #include "Panel.h" -#include "ScreenManager.h" #include "ProcessList.h" +#include "ScreenManager.h" +#include "Settings.h" typedef struct AvailableMetersPanel_ { Panel super; @@ -24,8 +23,7 @@ typedef struct AvailableMetersPanel_ { Panel* rightPanel; } AvailableMetersPanel; - -extern PanelClass AvailableMetersPanel_class; +extern const PanelClass AvailableMetersPanel_class; AvailableMetersPanel* AvailableMetersPanel_new(Settings* settings, Header* header, Panel* leftMeters, Panel* rightMeters, ScreenManager* scr, ProcessList* pl); diff --git a/BatteryMeter.c b/BatteryMeter.c index 214248e2e..cd8439c4c 100644 --- a/BatteryMeter.c +++ b/BatteryMeter.c @@ -1,7 +1,7 @@ /* htop - BatteryMeter.c (C) 2004-2011 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. This meter written by Ian P. Hands (iphands@gmail.com, ihands@redhat.com). @@ -9,37 +9,26 @@ This meter written by Ian P. Hands (iphands@gmail.com, ihands@redhat.com). #include "BatteryMeter.h" -#include "Battery.h" -#include "ProcessList.h" -#include "CRT.h" -#include "StringUtils.h" -#include "Platform.h" +#include -#include -#include - -/*{ -#include "Meter.h" +#include "Platform.h" +#include "CRT.h" +#include "Object.h" +#include "XUtils.h" -typedef enum ACPresence_ { - AC_ABSENT, - AC_PRESENT, - AC_ERROR -} ACPresence; -}*/ -int BatteryMeter_attributes[] = { +static const int BatteryMeter_attributes[] = { BATTERY }; -static void BatteryMeter_updateValues(Meter * this, char *buffer, int len) { +static void BatteryMeter_updateValues(Meter* this, char* buffer, int len) { ACPresence isOnAC; double percent; - - Battery_getData(&percent, &isOnAC); - if (percent == -1) { - this->values[0] = 0; + Platform_getBattery(&percent, &isOnAC); + + if (isnan(percent)) { + this->values[0] = NAN; xSnprintf(buffer, len, "n/a"); return; } @@ -64,11 +53,9 @@ static void BatteryMeter_updateValues(Meter * this, char *buffer, int len) { } else { xSnprintf(buffer, len, unknownText, percent); } - - return; } -MeterClass BatteryMeter_class = { +const MeterClass BatteryMeter_class = { .super = { .extends = Class(Meter), .delete = Meter_delete diff --git a/BatteryMeter.h b/BatteryMeter.h index bf8d2e82a..b6e8c5201 100644 --- a/BatteryMeter.h +++ b/BatteryMeter.h @@ -1,11 +1,9 @@ -/* Do not edit this file. It was automatically generated. */ - #ifndef HEADER_BatteryMeter #define HEADER_BatteryMeter /* htop - BatteryMeter.h (C) 2004-2011 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. This meter written by Ian P. Hands (iphands@gmail.com, ihands@redhat.com). @@ -19,8 +17,6 @@ typedef enum ACPresence_ { AC_ERROR } ACPresence; -extern int BatteryMeter_attributes[]; - -extern MeterClass BatteryMeter_class; +extern const MeterClass BatteryMeter_class; #endif diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 61b4ca0eb..65eb95c9a 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,56 +1,45 @@ - Contributing Guide ================== -Hello, and thank you so much for taking your time to contribute in any way to -htop! There are many ways to contribute, and I'll try to list them below. The -support from the free software community has been amazing over the years and -it is the number one thing that keeps me going, maintaining and improving -something that started as a tiny pet project back in 2004 and that nowadays is -a piece of software used all over the world, in both reality [and -fiction!](http://hisham.hm/htop/index.php?page=sightings). Cheers! - --- Hisham Muhammad +Thank you so much for taking the time to contribute in to htop! Bug Reports ----------- Bug reports should be posted in the [Github issue -tracker](http://github.com/hishamhm/htop/issues). (I reply to them all, but I -usually do it in batches! :) ) Bug reports are extremely important since it's -impossible for me to test htop in every possible system, distribution and -scenario. Your feedback is what keeps the tool stable and always improving! -Thank you! +tracker](https://github.com/htop-dev/htop/issues). +Bug reports are extremely important since it's impossible for us to test +htop in every possible system, distribution and scenario. Your feedback +is what keeps the tool stable and always improving! Thank you! Pull Requests ------------- Code contributions are most welcome! Just [fork the -repo](http://github.com/hishamhm/htop) and send a [pull -request](https://github.com/hishamhm/htop/pulls). Help is especially -appreciated for support of platforms other than Linux. If proposing new +repo](https://github.com/htop-dev/htop) and send a [pull +request](https://github.com/htop-dev/htop/pulls). Help is especially +appreciated for support of platforms other than Linux. If proposing new features, please be mindful that htop is a system tool that needs to keep a -small footprint and perform well on systems under stress -- so unfortunately I -can't accept every new feature proposed, as I need to keep the tool slim and -maintainable. Great ideas backed by a PR are always carefully considered for -inclusion, though! Also, PRs containing bug fixes and portability tweaks are a -no-brainer, please send those in! +small footprint and perform well on systems under stress -- so unfortunately +we can't accept every new feature proposed, as we need to keep the tool slim +and maintainable. Great ideas backed by a PR are always carefully considered +for inclusion though! Also, PRs containing bug fixes and portability tweaks +are always included, please send those in! Feature Requests ---------------- -Back when htop was hosted in SourceForge, there used to be separate Bug -Tracker and Feature Request pages. These go all lumped together under "Issues" -in Github, which is a bit confusing. For this reason, I close Feature Requests -and file them with the [`feature -request`](https://github.com/hishamhm/htop/issues?utf8=%E2%9C%93&q=is%3Aissue+label%3A%22feature+request%22+) -label, where they remain accessible, but not mixed with actual bug reports. -This doesn't mean I'm dismissing or ignoring feature requests right away! It's -just an organizational issue (with Github, really!). +Please label Github issues that are feature requests with the [`feature +request`](https://github.com/htop-dev/htop/issues?utf8=%E2%9C%93&q=is%3Aissue+label%3A%22feature+request%22+) +label. -Donations ---------- +Style Guide +----------- -If you like htop, feel free to [buy the author a -beer](http://hisham.hm/htop/index.php?page=donate). :-) +To make working with the code easier a set of guidelines have evolved in +the past that new contributions should try to follow. While they are not set +in stone and always up for changes should the need arise they still provide +a first orientation to go by when contributing to this repository. +The details of the coding style as well as what to take care about with your +contributions can be found in our [style guide](docs/styleguide.md). diff --git a/COPYING b/COPYING index 393445c42..1bd75b9fe 100644 --- a/COPYING +++ b/COPYING @@ -353,4 +353,3 @@ Public License instead of this License. applicable licenses of the version of PLPA used in your combined work, provided that you include the source code of such version of PLPA when and as the GNU GPL requires distribution of source code. - diff --git a/CPUMeter.c b/CPUMeter.c index de5490df1..ff129cd25 100644 --- a/CPUMeter.c +++ b/CPUMeter.c @@ -1,54 +1,46 @@ /* htop - CPUMeter.c (C) 2004-2011 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ #include "CPUMeter.h" +#include +#include +#include + #include "CRT.h" -#include "Settings.h" +#include "Object.h" #include "Platform.h" +#include "ProcessList.h" +#include "RichString.h" +#include "Settings.h" +#include "XUtils.h" -#include -#include -#include -#include -/*{ -#include "Meter.h" - -typedef enum { - CPU_METER_NICE = 0, - CPU_METER_NORMAL = 1, - CPU_METER_KERNEL = 2, - CPU_METER_IRQ = 3, - CPU_METER_SOFTIRQ = 4, - CPU_METER_STEAL = 5, - CPU_METER_GUEST = 6, - CPU_METER_IOWAIT = 7, - CPU_METER_ITEMCOUNT = 8, // number of entries in this enum -} CPUMeterValues; - -}*/ - -int CPUMeter_attributes[] = { - CPU_NICE, CPU_NORMAL, CPU_KERNEL, CPU_IRQ, CPU_SOFTIRQ, CPU_STEAL, CPU_GUEST, CPU_IOWAIT +static const int CPUMeter_attributes[] = { + CPU_NICE, + CPU_NORMAL, + CPU_SYSTEM, + CPU_IRQ, + CPU_SOFTIRQ, + CPU_STEAL, + CPU_GUEST, + CPU_IOWAIT }; -#ifndef MIN -#define MIN(a,b) ((a)<(b)?(a):(b)) -#endif -#ifndef MAX -#define MAX(a,b) ((a)>(b)?(a):(b)) -#endif +typedef struct CPUMeterData_ { + int cpus; + Meter** meters; +} CPUMeterData; static void CPUMeter_init(Meter* this) { int cpu = this->param; if (this->pl->cpuCount > 1) { char caption[10]; - xSnprintf(caption, sizeof(caption), "%-3d", Settings_cpuId(this->pl->settings, cpu - 1)); + xSnprintf(caption, sizeof(caption), "%3d", Settings_cpuId(this->pl->settings, cpu - 1)); Meter_setCaption(this, caption); } if (this->param == 0) @@ -59,16 +51,35 @@ static void CPUMeter_updateValues(Meter* this, char* buffer, int size) { int cpu = this->param; if (cpu > this->pl->cpuCount) { xSnprintf(buffer, size, "absent"); + for (uint8_t i = 0; i < this->curItems; i++) + this->values[i] = 0; return; } memset(this->values, 0, sizeof(double) * CPU_METER_ITEMCOUNT); double percent = Platform_setCPUValues(this, cpu); - xSnprintf(buffer, size, "%5.1f%%", percent); + if (this->pl->settings->showCPUFrequency) { + double cpuFrequency = this->values[CPU_METER_FREQUENCY]; + char cpuFrequencyBuffer[16]; + if (isnan(cpuFrequency)) { + xSnprintf(cpuFrequencyBuffer, sizeof(cpuFrequencyBuffer), "N/A"); + } else { + xSnprintf(cpuFrequencyBuffer, sizeof(cpuFrequencyBuffer), "%4uMHz", (unsigned)cpuFrequency); + } + if (this->pl->settings->showCPUUsage) { + xSnprintf(buffer, size, "%5.1f%% %s", percent, cpuFrequencyBuffer); + } else { + xSnprintf(buffer, size, "%s", cpuFrequencyBuffer); + } + } else if (this->pl->settings->showCPUUsage) { + xSnprintf(buffer, size, "%5.1f%%", percent); + } else if (size > 0) { + buffer[0] = '\0'; + } } -static void CPUMeter_display(Object* cast, RichString* out) { +static void CPUMeter_display(const Object* cast, RichString* out) { char buffer[50]; - Meter* this = (Meter*)cast; + const Meter* this = (const Meter*)cast; RichString_prune(out); if (this->param > this->pl->cpuCount) { RichString_append(out, CRT_colors[METER_TEXT], "absent"); @@ -80,7 +91,7 @@ static void CPUMeter_display(Object* cast, RichString* out) { if (this->pl->settings->detailedCPUTime) { xSnprintf(buffer, sizeof(buffer), "%5.1f%% ", this->values[CPU_METER_KERNEL]); RichString_append(out, CRT_colors[METER_TEXT], "sy:"); - RichString_append(out, CRT_colors[CPU_KERNEL], buffer); + RichString_append(out, CRT_colors[CPU_SYSTEM], buffer); xSnprintf(buffer, sizeof(buffer), "%5.1f%% ", this->values[CPU_METER_NICE]); RichString_append(out, CRT_colors[METER_TEXT], "ni:"); RichString_append(out, CRT_colors[CPU_NICE_TEXT], buffer); @@ -90,12 +101,12 @@ static void CPUMeter_display(Object* cast, RichString* out) { xSnprintf(buffer, sizeof(buffer), "%5.1f%% ", this->values[CPU_METER_SOFTIRQ]); RichString_append(out, CRT_colors[METER_TEXT], "si:"); RichString_append(out, CRT_colors[CPU_SOFTIRQ], buffer); - if (this->values[CPU_METER_STEAL]) { + if (!isnan(this->values[CPU_METER_STEAL])) { xSnprintf(buffer, sizeof(buffer), "%5.1f%% ", this->values[CPU_METER_STEAL]); RichString_append(out, CRT_colors[METER_TEXT], "st:"); RichString_append(out, CRT_colors[CPU_STEAL], buffer); } - if (this->values[CPU_METER_GUEST]) { + if (!isnan(this->values[CPU_METER_GUEST])) { xSnprintf(buffer, sizeof(buffer), "%5.1f%% ", this->values[CPU_METER_GUEST]); RichString_append(out, CRT_colors[METER_TEXT], "gu:"); RichString_append(out, CRT_colors[CPU_GUEST], buffer); @@ -106,11 +117,11 @@ static void CPUMeter_display(Object* cast, RichString* out) { } else { xSnprintf(buffer, sizeof(buffer), "%5.1f%% ", this->values[CPU_METER_KERNEL]); RichString_append(out, CRT_colors[METER_TEXT], "sys:"); - RichString_append(out, CRT_colors[CPU_KERNEL], buffer); + RichString_append(out, CRT_colors[CPU_SYSTEM], buffer); xSnprintf(buffer, sizeof(buffer), "%5.1f%% ", this->values[CPU_METER_NICE]); RichString_append(out, CRT_colors[METER_TEXT], "low:"); RichString_append(out, CRT_colors[CPU_NICE_TEXT], buffer); - if (this->values[CPU_METER_IRQ]) { + if (!isnan(this->values[CPU_METER_IRQ])) { xSnprintf(buffer, sizeof(buffer), "%5.1f%% ", this->values[CPU_METER_IRQ]); RichString_append(out, CRT_colors[METER_TEXT], "vir:"); RichString_append(out, CRT_colors[CPU_GUEST], buffer); @@ -119,7 +130,8 @@ static void CPUMeter_display(Object* cast, RichString* out) { } static void AllCPUsMeter_getRange(Meter* this, int* start, int* count) { - int cpus = this->pl->cpuCount; + CPUMeterData* data = this->meterData; + int cpus = data->cpus; switch(Meter_name(this)[0]) { default: case 'A': // All @@ -137,70 +149,119 @@ static void AllCPUsMeter_getRange(Meter* this, int* start, int* count) { } } -static void AllCPUsMeter_init(Meter* this) { +static void CPUMeterCommonInit(Meter* this, int ncol) { int cpus = this->pl->cpuCount; - if (!this->drawData) - this->drawData = xCalloc(cpus, sizeof(Meter*)); - Meter** meters = (Meter**) this->drawData; + CPUMeterData* data = this->meterData; + if (!data) { + data = this->meterData = xMalloc(sizeof(CPUMeterData)); + data->cpus = cpus; + data->meters = xCalloc(cpus, sizeof(Meter*)); + } + Meter** meters = data->meters; int start, count; AllCPUsMeter_getRange(this, &start, &count); for (int i = 0; i < count; i++) { if (!meters[i]) - meters[i] = Meter_new(this->pl, start+i+1, (MeterClass*) Class(CPUMeter)); + meters[i] = Meter_new(this->pl, start + i + 1, (const MeterClass*) Class(CPUMeter)); + Meter_init(meters[i]); } + if (this->mode == 0) this->mode = BAR_METERMODE; + int h = Meter_modes[this->mode]->h; - if (strchr(Meter_name(this), '2')) - this->h = h * ((count+1) / 2); - else - this->h = h * count; + this->h = h * ((count + ncol - 1) / ncol); +} + +static void CPUMeterCommonUpdateMode(Meter* this, int mode, int ncol) { + CPUMeterData* data = this->meterData; + Meter** meters = data->meters; + this->mode = mode; + int h = Meter_modes[mode]->h; + int start, count; + AllCPUsMeter_getRange(this, &start, &count); + for (int i = 0; i < count; i++) { + Meter_setMode(meters[i], mode); + } + this->h = h * ((count + ncol - 1) / ncol); } static void AllCPUsMeter_done(Meter* this) { - Meter** meters = (Meter**) this->drawData; + CPUMeterData* data = this->meterData; + Meter** meters = data->meters; int start, count; AllCPUsMeter_getRange(this, &start, &count); for (int i = 0; i < count; i++) Meter_delete((Object*)meters[i]); + free(data->meters); + free(data); } -static void AllCPUsMeter_updateMode(Meter* this, int mode) { - Meter** meters = (Meter**) this->drawData; - this->mode = mode; - int h = Meter_modes[mode]->h; +static void SingleColCPUsMeter_init(Meter* this) { + CPUMeterCommonInit(this, 1); +} + +static void SingleColCPUsMeter_updateMode(Meter* this, int mode) { + CPUMeterCommonUpdateMode(this, mode, 1); +} + +static void DualColCPUsMeter_init(Meter* this) { + CPUMeterCommonInit(this, 2); +} + +static void DualColCPUsMeter_updateMode(Meter* this, int mode) { + CPUMeterCommonUpdateMode(this, mode, 2); +} + +static void QuadColCPUsMeter_init(Meter* this) { + CPUMeterCommonInit(this, 4); +} + +static void QuadColCPUsMeter_updateMode(Meter* this, int mode) { + CPUMeterCommonUpdateMode(this, mode, 4); +} + +static void OctoColCPUsMeter_init(Meter* this) { + CPUMeterCommonInit(this, 8); +} + +static void OctoColCPUsMeter_updateMode(Meter* this, int mode) { + CPUMeterCommonUpdateMode(this, mode, 8); +} + +static void CPUMeterCommonDraw(Meter* this, int x, int y, int w, int ncol) { + CPUMeterData* data = this->meterData; + Meter** meters = data->meters; int start, count; AllCPUsMeter_getRange(this, &start, &count); + int colwidth = (w - ncol) / ncol + 1; + int diff = (w - (colwidth * ncol)); + int nrows = (count + ncol - 1) / ncol; for (int i = 0; i < count; i++) { - Meter_setMode(meters[i], mode); + int d = (i / nrows) > diff ? diff : (i / nrows); // dynamic spacer + int xpos = x + ((i / nrows) * colwidth) + d; + int ypos = y + ((i % nrows) * meters[0]->h); + meters[i]->draw(meters[i], xpos, ypos, colwidth); } - if (strchr(Meter_name(this), '2')) - this->h = h * ((count+1) / 2); - else - this->h = h * count; } static void DualColCPUsMeter_draw(Meter* this, int x, int y, int w) { - Meter** meters = (Meter**) this->drawData; - int start, count; - int pad = this->pl->settings->headerMargin ? 2 : 0; - AllCPUsMeter_getRange(this, &start, &count); - int height = (count+1)/2; - int startY = y; - for (int i = 0; i < height; i++) { - meters[i]->draw(meters[i], x, y, (w-pad)/2); - y += meters[i]->h; - } - y = startY; - for (int i = height; i < count; i++) { - meters[i]->draw(meters[i], x+(w-1)/2+1+(pad/2), y, (w-pad)/2); - y += meters[i]->h; - } + CPUMeterCommonDraw(this, x, y, w, 2); +} + +static void QuadColCPUsMeter_draw(Meter* this, int x, int y, int w) { + CPUMeterCommonDraw(this, x, y, w, 4); } +static void OctoColCPUsMeter_draw(Meter* this, int x, int y, int w) { + CPUMeterCommonDraw(this, x, y, w, 8); +} + + static void SingleColCPUsMeter_draw(Meter* this, int x, int y, int w) { - Meter** meters = (Meter**) this->drawData; + CPUMeterData* data = this->meterData; + Meter** meters = data->meters; int start, count; AllCPUsMeter_getRange(this, &start, &count); for (int i = 0; i < count; i++) { @@ -209,7 +270,8 @@ static void SingleColCPUsMeter_draw(Meter* this, int x, int y, int w) { } } -MeterClass CPUMeter_class = { + +const MeterClass CPUMeter_class = { .super = { .extends = Class(Meter), .delete = Meter_delete, @@ -219,14 +281,14 @@ MeterClass CPUMeter_class = { .defaultMode = BAR_METERMODE, .maxItems = CPU_METER_ITEMCOUNT, .total = 100.0, - .attributes = CPUMeter_attributes, + .attributes = CPUMeter_attributes, .name = "CPU", .uiName = "CPU", .caption = "CPU", .init = CPUMeter_init }; -MeterClass AllCPUsMeter_class = { +const MeterClass AllCPUsMeter_class = { .super = { .extends = Class(Meter), .delete = Meter_delete, @@ -234,18 +296,18 @@ MeterClass AllCPUsMeter_class = { }, .defaultMode = CUSTOM_METERMODE, .total = 100.0, - .attributes = CPUMeter_attributes, + .attributes = CPUMeter_attributes, .name = "AllCPUs", .uiName = "CPUs (1/1)", .description = "CPUs (1/1): all CPUs", .caption = "CPU", .draw = SingleColCPUsMeter_draw, - .init = AllCPUsMeter_init, - .updateMode = AllCPUsMeter_updateMode, + .init = SingleColCPUsMeter_init, + .updateMode = SingleColCPUsMeter_updateMode, .done = AllCPUsMeter_done }; -MeterClass AllCPUs2Meter_class = { +const MeterClass AllCPUs2Meter_class = { .super = { .extends = Class(Meter), .delete = Meter_delete, @@ -253,18 +315,18 @@ MeterClass AllCPUs2Meter_class = { }, .defaultMode = CUSTOM_METERMODE, .total = 100.0, - .attributes = CPUMeter_attributes, + .attributes = CPUMeter_attributes, .name = "AllCPUs2", .uiName = "CPUs (1&2/2)", .description = "CPUs (1&2/2): all CPUs in 2 shorter columns", .caption = "CPU", .draw = DualColCPUsMeter_draw, - .init = AllCPUsMeter_init, - .updateMode = AllCPUsMeter_updateMode, + .init = DualColCPUsMeter_init, + .updateMode = DualColCPUsMeter_updateMode, .done = AllCPUsMeter_done }; -MeterClass LeftCPUsMeter_class = { +const MeterClass LeftCPUsMeter_class = { .super = { .extends = Class(Meter), .delete = Meter_delete, @@ -272,18 +334,18 @@ MeterClass LeftCPUsMeter_class = { }, .defaultMode = CUSTOM_METERMODE, .total = 100.0, - .attributes = CPUMeter_attributes, + .attributes = CPUMeter_attributes, .name = "LeftCPUs", .uiName = "CPUs (1/2)", .description = "CPUs (1/2): first half of list", .caption = "CPU", .draw = SingleColCPUsMeter_draw, - .init = AllCPUsMeter_init, - .updateMode = AllCPUsMeter_updateMode, + .init = SingleColCPUsMeter_init, + .updateMode = SingleColCPUsMeter_updateMode, .done = AllCPUsMeter_done }; -MeterClass RightCPUsMeter_class = { +const MeterClass RightCPUsMeter_class = { .super = { .extends = Class(Meter), .delete = Meter_delete, @@ -291,18 +353,18 @@ MeterClass RightCPUsMeter_class = { }, .defaultMode = CUSTOM_METERMODE, .total = 100.0, - .attributes = CPUMeter_attributes, + .attributes = CPUMeter_attributes, .name = "RightCPUs", .uiName = "CPUs (2/2)", .description = "CPUs (2/2): second half of list", .caption = "CPU", .draw = SingleColCPUsMeter_draw, - .init = AllCPUsMeter_init, - .updateMode = AllCPUsMeter_updateMode, + .init = SingleColCPUsMeter_init, + .updateMode = SingleColCPUsMeter_updateMode, .done = AllCPUsMeter_done }; -MeterClass LeftCPUs2Meter_class = { +const MeterClass LeftCPUs2Meter_class = { .super = { .extends = Class(Meter), .delete = Meter_delete, @@ -310,18 +372,18 @@ MeterClass LeftCPUs2Meter_class = { }, .defaultMode = CUSTOM_METERMODE, .total = 100.0, - .attributes = CPUMeter_attributes, + .attributes = CPUMeter_attributes, .name = "LeftCPUs2", .uiName = "CPUs (1&2/4)", .description = "CPUs (1&2/4): first half in 2 shorter columns", .caption = "CPU", .draw = DualColCPUsMeter_draw, - .init = AllCPUsMeter_init, - .updateMode = AllCPUsMeter_updateMode, + .init = DualColCPUsMeter_init, + .updateMode = DualColCPUsMeter_updateMode, .done = AllCPUsMeter_done }; -MeterClass RightCPUs2Meter_class = { +const MeterClass RightCPUs2Meter_class = { .super = { .extends = Class(Meter), .delete = Meter_delete, @@ -329,14 +391,127 @@ MeterClass RightCPUs2Meter_class = { }, .defaultMode = CUSTOM_METERMODE, .total = 100.0, - .attributes = CPUMeter_attributes, + .attributes = CPUMeter_attributes, .name = "RightCPUs2", .uiName = "CPUs (3&4/4)", .description = "CPUs (3&4/4): second half in 2 shorter columns", .caption = "CPU", .draw = DualColCPUsMeter_draw, - .init = AllCPUsMeter_init, - .updateMode = AllCPUsMeter_updateMode, + .init = DualColCPUsMeter_init, + .updateMode = DualColCPUsMeter_updateMode, + .done = AllCPUsMeter_done +}; + +const MeterClass AllCPUs4Meter_class = { + .super = { + .extends = Class(Meter), + .delete = Meter_delete, + .display = CPUMeter_display + }, + .defaultMode = CUSTOM_METERMODE, + .total = 100.0, + .attributes = CPUMeter_attributes, + .name = "AllCPUs4", + .uiName = "CPUs (1&2&3&4/4)", + .description = "CPUs (1&2&3&4/4): all CPUs in 4 shorter columns", + .caption = "CPU", + .draw = QuadColCPUsMeter_draw, + .init = QuadColCPUsMeter_init, + .updateMode = QuadColCPUsMeter_updateMode, .done = AllCPUsMeter_done }; +const MeterClass LeftCPUs4Meter_class = { + .super = { + .extends = Class(Meter), + .delete = Meter_delete, + .display = CPUMeter_display + }, + .defaultMode = CUSTOM_METERMODE, + .total = 100.0, + .attributes = CPUMeter_attributes, + .name = "LeftCPUs4", + .uiName = "CPUs (1-4/8)", + .description = "CPUs (1-4/8): first half in 4 shorter columns", + .caption = "CPU", + .draw = QuadColCPUsMeter_draw, + .init = QuadColCPUsMeter_init, + .updateMode = QuadColCPUsMeter_updateMode, + .done = AllCPUsMeter_done +}; + +const MeterClass RightCPUs4Meter_class = { + .super = { + .extends = Class(Meter), + .delete = Meter_delete, + .display = CPUMeter_display + }, + .defaultMode = CUSTOM_METERMODE, + .total = 100.0, + .attributes = CPUMeter_attributes, + .name = "RightCPUs4", + .uiName = "CPUs (5-8/8)", + .description = "CPUs (5-8/8): second half in 4 shorter columns", + .caption = "CPU", + .draw = QuadColCPUsMeter_draw, + .init = QuadColCPUsMeter_init, + .updateMode = QuadColCPUsMeter_updateMode, + .done = AllCPUsMeter_done +}; + +const MeterClass AllCPUs8Meter_class = { + .super = { + .extends = Class(Meter), + .delete = Meter_delete, + .display = CPUMeter_display + }, + .defaultMode = CUSTOM_METERMODE, + .total = 100.0, + .attributes = CPUMeter_attributes, + .name = "AllCPUs8", + .uiName = "CPUs (1-8/8)", + .description = "CPUs (1-8/8): all CPUs in 8 shorter columns", + .caption = "CPU", + .draw = OctoColCPUsMeter_draw, + .init = OctoColCPUsMeter_init, + .updateMode = OctoColCPUsMeter_updateMode, + .done = AllCPUsMeter_done +}; + +const MeterClass LeftCPUs8Meter_class = { + .super = { + .extends = Class(Meter), + .delete = Meter_delete, + .display = CPUMeter_display + }, + .defaultMode = CUSTOM_METERMODE, + .total = 100.0, + .attributes = CPUMeter_attributes, + .name = "LeftCPUs8", + .uiName = "CPUs (1-8/16)", + .description = "CPUs (1-8/16): first half in 8 shorter columns", + .caption = "CPU", + .draw = OctoColCPUsMeter_draw, + .init = OctoColCPUsMeter_init, + .updateMode = OctoColCPUsMeter_updateMode, + .done = AllCPUsMeter_done +}; + +const MeterClass RightCPUs8Meter_class = { + .super = { + .extends = Class(Meter), + .delete = Meter_delete, + .display = CPUMeter_display + }, + .defaultMode = CUSTOM_METERMODE, + .total = 100.0, + .attributes = CPUMeter_attributes, + .name = "RightCPUs8", + .uiName = "CPUs (9-16/16)", + .description = "CPUs (9-16/16): second half in 8 shorter columns", + .caption = "CPU", + .draw = OctoColCPUsMeter_draw, + .init = OctoColCPUsMeter_init, + .updateMode = OctoColCPUsMeter_updateMode, + .done = AllCPUsMeter_done +}; diff --git a/CPUMeter.h b/CPUMeter.h index 2f1639680..d60e82f73 100644 --- a/CPUMeter.h +++ b/CPUMeter.h @@ -1,11 +1,9 @@ -/* Do not edit this file. It was automatically generated. */ - #ifndef HEADER_CPUMeter #define HEADER_CPUMeter /* htop - CPUMeter.h (C) 2004-2011 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ @@ -20,32 +18,34 @@ typedef enum { CPU_METER_STEAL = 5, CPU_METER_GUEST = 6, CPU_METER_IOWAIT = 7, - CPU_METER_ITEMCOUNT = 8, // number of entries in this enum + CPU_METER_FREQUENCY = 8, + CPU_METER_ITEMCOUNT = 9, // number of entries in this enum } CPUMeterValues; +extern const MeterClass CPUMeter_class; -extern int CPUMeter_attributes[]; +extern const MeterClass AllCPUsMeter_class; -#ifndef MIN -#define MIN(a,b) ((a)<(b)?(a):(b)) -#endif -#ifndef MAX -#define MAX(a,b) ((a)>(b)?(a):(b)) -#endif +extern const MeterClass AllCPUs2Meter_class; + +extern const MeterClass LeftCPUsMeter_class; + +extern const MeterClass RightCPUsMeter_class; -extern MeterClass CPUMeter_class; +extern const MeterClass LeftCPUs2Meter_class; -extern MeterClass AllCPUsMeter_class; +extern const MeterClass RightCPUs2Meter_class; -extern MeterClass AllCPUs2Meter_class; +extern const MeterClass AllCPUs4Meter_class; -extern MeterClass LeftCPUsMeter_class; +extern const MeterClass LeftCPUs4Meter_class; -extern MeterClass RightCPUsMeter_class; +extern const MeterClass RightCPUs4Meter_class; -extern MeterClass LeftCPUs2Meter_class; +extern const MeterClass AllCPUs8Meter_class; -extern MeterClass RightCPUs2Meter_class; +extern const MeterClass LeftCPUs8Meter_class; +extern const MeterClass RightCPUs8Meter_class; #endif diff --git a/CRT.c b/CRT.c index ca9a10dd8..96bc15662 100644 --- a/CRT.c +++ b/CRT.c @@ -1,145 +1,48 @@ /* htop - CRT.c (C) 2004-2011 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ -#include "config.h" -#include "CRT.h" +#include "config.h" // IWYU pragma: keep -#include "StringUtils.h" -#include "RichString.h" +#include "CRT.h" -#include #include +#include +#include #include +#include #include #include -#include -#include -#if HAVE_SETUID_ENABLED #include -#include + +#include "ProvideCurses.h" +#include "XUtils.h" + +#ifdef HAVE_EXECINFO_H +#include #endif -#define ColorIndex(i,j) ((7-i)*8+j) + +#define ColorIndex(i,j) ((7-(i))*8+(j)) #define ColorPair(i,j) COLOR_PAIR(ColorIndex(i,j)) -#define Black COLOR_BLACK -#define Red COLOR_RED -#define Green COLOR_GREEN -#define Yellow COLOR_YELLOW -#define Blue COLOR_BLUE +#define Black COLOR_BLACK +#define Red COLOR_RED +#define Green COLOR_GREEN +#define Yellow COLOR_YELLOW +#define Blue COLOR_BLUE #define Magenta COLOR_MAGENTA -#define Cyan COLOR_CYAN -#define White COLOR_WHITE +#define Cyan COLOR_CYAN +#define White COLOR_WHITE -#define ColorPairGrayBlack ColorPair(Magenta,Magenta) +#define ColorPairGrayBlack ColorPair(Magenta,Magenta) #define ColorIndexGrayBlack ColorIndex(Magenta,Magenta) -#define KEY_WHEELUP KEY_F(20) -#define KEY_WHEELDOWN KEY_F(21) -#define KEY_RECLICK KEY_F(22) - -//#link curses - -/*{ -#include - -typedef enum TreeStr_ { - TREE_STR_HORZ, - TREE_STR_VERT, - TREE_STR_RTEE, - TREE_STR_BEND, - TREE_STR_TEND, - TREE_STR_OPEN, - TREE_STR_SHUT, - TREE_STR_COUNT -} TreeStr; - -typedef enum ColorSchemes_ { - COLORSCHEME_DEFAULT = 0, - COLORSCHEME_MONOCHROME = 1, - COLORSCHEME_BLACKONWHITE = 2, - COLORSCHEME_LIGHTTERMINAL = 3, - COLORSCHEME_MIDNIGHT = 4, - COLORSCHEME_BLACKNIGHT = 5, - COLORSCHEME_BROKENGRAY = 6, - LAST_COLORSCHEME = 7, -} ColorSchemes; - -typedef enum ColorElements_ { - RESET_COLOR, - DEFAULT_COLOR, - FUNCTION_BAR, - FUNCTION_KEY, - FAILED_SEARCH, - PANEL_HEADER_FOCUS, - PANEL_HEADER_UNFOCUS, - PANEL_SELECTION_FOCUS, - PANEL_SELECTION_FOLLOW, - PANEL_SELECTION_UNFOCUS, - LARGE_NUMBER, - METER_TEXT, - METER_VALUE, - LED_COLOR, - UPTIME, - BATTERY, - TASKS_RUNNING, - SWAP, - PROCESS, - PROCESS_SHADOW, - PROCESS_TAG, - PROCESS_MEGABYTES, - PROCESS_TREE, - PROCESS_R_STATE, - PROCESS_D_STATE, - PROCESS_BASENAME, - PROCESS_HIGH_PRIORITY, - PROCESS_LOW_PRIORITY, - PROCESS_THREAD, - PROCESS_THREAD_BASENAME, - BAR_BORDER, - BAR_SHADOW, - GRAPH_1, - GRAPH_2, - MEMORY_USED, - MEMORY_BUFFERS, - MEMORY_BUFFERS_TEXT, - MEMORY_CACHE, - LOAD, - LOAD_AVERAGE_FIFTEEN, - LOAD_AVERAGE_FIVE, - LOAD_AVERAGE_ONE, - CHECK_BOX, - CHECK_MARK, - CHECK_TEXT, - CLOCK, - HELP_BOLD, - HOSTNAME, - CPU_NICE, - CPU_NICE_TEXT, - CPU_NORMAL, - CPU_KERNEL, - CPU_IOWAIT, - CPU_IRQ, - CPU_SOFTIRQ, - CPU_STEAL, - CPU_GUEST, - LAST_COLORELEMENT -} ColorElements; - -void CRT_fatalError(const char* note) __attribute__ ((noreturn)); - -void CRT_handleSIGSEGV(int sgn); - -#define KEY_ALT(x) (KEY_F(64 - 26) + (x - 'A')) - -}*/ - -const char *CRT_treeStrAscii[TREE_STR_COUNT] = { +static const char* const CRT_treeStrAscii[TREE_STR_COUNT] = { "-", // TREE_STR_HORZ "|", // TREE_STR_VERT "`", // TREE_STR_RTEE @@ -151,13 +54,15 @@ const char *CRT_treeStrAscii[TREE_STR_COUNT] = { #ifdef HAVE_LIBNCURSESW -const char *CRT_treeStrUtf8[TREE_STR_COUNT] = { +static const char* const CRT_treeStrUtf8[TREE_STR_COUNT] = { "\xe2\x94\x80", // TREE_STR_HORZ ─ "\xe2\x94\x82", // TREE_STR_VERT │ "\xe2\x94\x9c", // TREE_STR_RTEE ├ "\xe2\x94\x94", // TREE_STR_BEND └ "\xe2\x94\x8c", // TREE_STR_TEND ┌ - "+", // TREE_STR_OPEN + + "+", // TREE_STR_OPEN +, TODO use 🮯 'BOX DRAWINGS LIGHT HORIZONTAL + // WITH VERTICAL STROKE' (U+1FBAF, "\xf0\x9f\xae\xaf") when + // Unicode 13 is common "\xe2\x94\x80", // TREE_STR_SHUT ─ }; @@ -165,73 +70,93 @@ bool CRT_utf8 = false; #endif -const char **CRT_treeStr = CRT_treeStrAscii; - -static bool CRT_hasColors; +const char* const* CRT_treeStr = CRT_treeStrAscii; -int CRT_delay = 0; +int CRT_delay; -int* CRT_colors; +const int* CRT_colors; int CRT_colorSchemes[LAST_COLORSCHEME][LAST_COLORELEMENT] = { [COLORSCHEME_DEFAULT] = { - [RESET_COLOR] = ColorPair(White,Black), - [DEFAULT_COLOR] = ColorPair(White,Black), - [FUNCTION_BAR] = ColorPair(Black,Cyan), - [FUNCTION_KEY] = ColorPair(White,Black), - [PANEL_HEADER_FOCUS] = ColorPair(Black,Green), - [PANEL_HEADER_UNFOCUS] = ColorPair(Black,Green), - [PANEL_SELECTION_FOCUS] = ColorPair(Black,Cyan), - [PANEL_SELECTION_FOLLOW] = ColorPair(Black,Yellow), - [PANEL_SELECTION_UNFOCUS] = ColorPair(Black,White), - [FAILED_SEARCH] = ColorPair(Red,Cyan), - [UPTIME] = A_BOLD | ColorPair(Cyan,Black), - [BATTERY] = A_BOLD | ColorPair(Cyan,Black), - [LARGE_NUMBER] = A_BOLD | ColorPair(Red,Black), - [METER_TEXT] = ColorPair(Cyan,Black), - [METER_VALUE] = A_BOLD | ColorPair(Cyan,Black), - [LED_COLOR] = ColorPair(Green,Black), - [TASKS_RUNNING] = A_BOLD | ColorPair(Green,Black), + [RESET_COLOR] = ColorPair(White, Black), + [DEFAULT_COLOR] = ColorPair(White, Black), + [FUNCTION_BAR] = ColorPair(Black, Cyan), + [FUNCTION_KEY] = ColorPair(White, Black), + [PANEL_HEADER_FOCUS] = ColorPair(Black, Green), + [PANEL_HEADER_UNFOCUS] = ColorPair(Black, Green), + [PANEL_SELECTION_FOCUS] = ColorPair(Black, Cyan), + [PANEL_SELECTION_FOLLOW] = ColorPair(Black, Yellow), + [PANEL_SELECTION_UNFOCUS] = ColorPair(Black, White), + [FAILED_SEARCH] = ColorPair(Red, Cyan), + [PAUSED] = A_BOLD | ColorPair(Yellow, Cyan), + [UPTIME] = A_BOLD | ColorPair(Cyan, Black), + [BATTERY] = A_BOLD | ColorPair(Cyan, Black), + [LARGE_NUMBER] = A_BOLD | ColorPair(Red, Black), + [METER_TEXT] = ColorPair(Cyan, Black), + [METER_VALUE] = A_BOLD | ColorPair(Cyan, Black), + [METER_VALUE_ERROR] = A_BOLD | ColorPair(Red, Black), + [METER_VALUE_IOREAD] = ColorPair(Green, Black), + [METER_VALUE_IOWRITE] = ColorPair(Blue, Black), + [METER_VALUE_NOTICE] = A_BOLD | ColorPair(White, Black), + [METER_VALUE_OK] = ColorPair(Green, Black), + [LED_COLOR] = ColorPair(Green, Black), + [TASKS_RUNNING] = A_BOLD | ColorPair(Green, Black), [PROCESS] = A_NORMAL, [PROCESS_SHADOW] = A_BOLD | ColorPairGrayBlack, - [PROCESS_TAG] = A_BOLD | ColorPair(Yellow,Black), - [PROCESS_MEGABYTES] = ColorPair(Cyan,Black), - [PROCESS_BASENAME] = A_BOLD | ColorPair(Cyan,Black), - [PROCESS_TREE] = ColorPair(Cyan,Black), - [PROCESS_R_STATE] = ColorPair(Green,Black), - [PROCESS_D_STATE] = A_BOLD | ColorPair(Red,Black), - [PROCESS_HIGH_PRIORITY] = ColorPair(Red,Black), - [PROCESS_LOW_PRIORITY] = ColorPair(Green,Black), - [PROCESS_THREAD] = ColorPair(Green,Black), - [PROCESS_THREAD_BASENAME] = A_BOLD | ColorPair(Green,Black), + [PROCESS_TAG] = A_BOLD | ColorPair(Yellow, Black), + [PROCESS_MEGABYTES] = ColorPair(Cyan, Black), + [PROCESS_GIGABYTES] = ColorPair(Green, Black), + [PROCESS_BASENAME] = A_BOLD | ColorPair(Cyan, Black), + [PROCESS_TREE] = ColorPair(Cyan, Black), + [PROCESS_R_STATE] = ColorPair(Green, Black), + [PROCESS_D_STATE] = A_BOLD | ColorPair(Red, Black), + [PROCESS_HIGH_PRIORITY] = ColorPair(Red, Black), + [PROCESS_LOW_PRIORITY] = ColorPair(Green, Black), + [PROCESS_NEW] = ColorPair(Black, Green), + [PROCESS_TOMB] = ColorPair(Black, Red), + [PROCESS_THREAD] = ColorPair(Green, Black), + [PROCESS_THREAD_BASENAME] = A_BOLD | ColorPair(Green, Black), [BAR_BORDER] = A_BOLD, [BAR_SHADOW] = A_BOLD | ColorPairGrayBlack, - [SWAP] = ColorPair(Red,Black), - [GRAPH_1] = A_BOLD | ColorPair(Cyan,Black), - [GRAPH_2] = ColorPair(Cyan,Black), - [MEMORY_USED] = ColorPair(Green,Black), - [MEMORY_BUFFERS] = ColorPair(Blue,Black), - [MEMORY_BUFFERS_TEXT] = A_BOLD | ColorPair(Blue,Black), - [MEMORY_CACHE] = ColorPair(Yellow,Black), - [LOAD_AVERAGE_FIFTEEN] = ColorPair(Cyan,Black), - [LOAD_AVERAGE_FIVE] = A_BOLD | ColorPair(Cyan,Black), - [LOAD_AVERAGE_ONE] = A_BOLD | ColorPair(White,Black), + [SWAP] = ColorPair(Red, Black), + [GRAPH_1] = A_BOLD | ColorPair(Cyan, Black), + [GRAPH_2] = ColorPair(Cyan, Black), + [MEMORY_USED] = ColorPair(Green, Black), + [MEMORY_BUFFERS] = ColorPair(Blue, Black), + [MEMORY_BUFFERS_TEXT] = A_BOLD | ColorPair(Blue, Black), + [MEMORY_CACHE] = ColorPair(Yellow, Black), + [LOAD_AVERAGE_FIFTEEN] = ColorPair(Cyan, Black), + [LOAD_AVERAGE_FIVE] = A_BOLD | ColorPair(Cyan, Black), + [LOAD_AVERAGE_ONE] = A_BOLD | ColorPair(White, Black), [LOAD] = A_BOLD, - [HELP_BOLD] = A_BOLD | ColorPair(Cyan,Black), + [HELP_BOLD] = A_BOLD | ColorPair(Cyan, Black), [CLOCK] = A_BOLD, - [CHECK_BOX] = ColorPair(Cyan,Black), + [DATE] = A_BOLD, + [DATETIME] = A_BOLD, + [CHECK_BOX] = ColorPair(Cyan, Black), [CHECK_MARK] = A_BOLD, [CHECK_TEXT] = A_NORMAL, [HOSTNAME] = A_BOLD, - [CPU_NICE] = ColorPair(Blue,Black), - [CPU_NICE_TEXT] = A_BOLD | ColorPair(Blue,Black), - [CPU_NORMAL] = ColorPair(Green,Black), - [CPU_KERNEL] = ColorPair(Red,Black), - [CPU_IOWAIT] = A_BOLD | ColorPair(Black, Black), - [CPU_IRQ] = ColorPair(Yellow,Black), - [CPU_SOFTIRQ] = ColorPair(Magenta,Black), - [CPU_STEAL] = ColorPair(Cyan,Black), - [CPU_GUEST] = ColorPair(Cyan,Black), + [CPU_NICE] = ColorPair(Blue, Black), + [CPU_NICE_TEXT] = A_BOLD | ColorPair(Blue, Black), + [CPU_NORMAL] = ColorPair(Green, Black), + [CPU_SYSTEM] = ColorPair(Red, Black), + [CPU_IOWAIT] = A_BOLD | ColorPairGrayBlack, + [CPU_IRQ] = ColorPair(Yellow, Black), + [CPU_SOFTIRQ] = ColorPair(Magenta, Black), + [CPU_STEAL] = ColorPair(Cyan, Black), + [CPU_GUEST] = ColorPair(Cyan, Black), + [PRESSURE_STALL_THREEHUNDRED] = ColorPair(Cyan, Black), + [PRESSURE_STALL_SIXTY] = A_BOLD | ColorPair(Cyan, Black), + [PRESSURE_STALL_TEN] = A_BOLD | ColorPair(White, Black), + [ZFS_MFU] = ColorPair(Blue, Black), + [ZFS_MRU] = ColorPair(Yellow, Black), + [ZFS_ANON] = ColorPair(Magenta, Black), + [ZFS_HEADER] = ColorPair(Cyan, Black), + [ZFS_OTHER] = ColorPair(Magenta, Black), + [ZFS_COMPRESSED] = ColorPair(Blue, Black), + [ZFS_RATIO] = ColorPair(Magenta, Black), + [ZRAM] = ColorPair(Yellow, Black), }, [COLORSCHEME_MONOCHROME] = { [RESET_COLOR] = A_NORMAL, @@ -244,23 +169,32 @@ int CRT_colorSchemes[LAST_COLORSCHEME][LAST_COLORELEMENT] = { [PANEL_SELECTION_FOLLOW] = A_REVERSE, [PANEL_SELECTION_UNFOCUS] = A_BOLD, [FAILED_SEARCH] = A_REVERSE | A_BOLD, + [PAUSED] = A_BOLD | A_REVERSE, [UPTIME] = A_BOLD, [BATTERY] = A_BOLD, [LARGE_NUMBER] = A_BOLD, [METER_TEXT] = A_NORMAL, [METER_VALUE] = A_BOLD, + [METER_VALUE_ERROR] = A_BOLD, + [METER_VALUE_IOREAD] = A_NORMAL, + [METER_VALUE_IOWRITE] = A_NORMAL, + [METER_VALUE_NOTICE] = A_BOLD, + [METER_VALUE_OK] = A_NORMAL, [LED_COLOR] = A_NORMAL, [TASKS_RUNNING] = A_BOLD, [PROCESS] = A_NORMAL, [PROCESS_SHADOW] = A_DIM, [PROCESS_TAG] = A_BOLD, [PROCESS_MEGABYTES] = A_BOLD, + [PROCESS_GIGABYTES] = A_BOLD, [PROCESS_BASENAME] = A_BOLD, [PROCESS_TREE] = A_BOLD, [PROCESS_R_STATE] = A_BOLD, [PROCESS_D_STATE] = A_BOLD, [PROCESS_HIGH_PRIORITY] = A_BOLD, [PROCESS_LOW_PRIORITY] = A_DIM, + [PROCESS_NEW] = A_BOLD, + [PROCESS_TOMB] = A_DIM, [PROCESS_THREAD] = A_BOLD, [PROCESS_THREAD_BASENAME] = A_REVERSE, [BAR_BORDER] = A_BOLD, @@ -278,6 +212,8 @@ int CRT_colorSchemes[LAST_COLORSCHEME][LAST_COLORELEMENT] = { [LOAD] = A_BOLD, [HELP_BOLD] = A_BOLD, [CLOCK] = A_BOLD, + [DATE] = A_BOLD, + [DATETIME] = A_BOLD, [CHECK_BOX] = A_BOLD, [CHECK_MARK] = A_NORMAL, [CHECK_TEXT] = A_NORMAL, @@ -285,248 +221,345 @@ int CRT_colorSchemes[LAST_COLORSCHEME][LAST_COLORELEMENT] = { [CPU_NICE] = A_NORMAL, [CPU_NICE_TEXT] = A_NORMAL, [CPU_NORMAL] = A_BOLD, - [CPU_KERNEL] = A_BOLD, + [CPU_SYSTEM] = A_BOLD, [CPU_IOWAIT] = A_NORMAL, [CPU_IRQ] = A_BOLD, [CPU_SOFTIRQ] = A_BOLD, - [CPU_STEAL] = A_REVERSE, - [CPU_GUEST] = A_REVERSE, + [CPU_STEAL] = A_DIM, + [CPU_GUEST] = A_DIM, + [PRESSURE_STALL_THREEHUNDRED] = A_DIM, + [PRESSURE_STALL_SIXTY] = A_NORMAL, + [PRESSURE_STALL_TEN] = A_BOLD, + [ZFS_MFU] = A_NORMAL, + [ZFS_MRU] = A_NORMAL, + [ZFS_ANON] = A_DIM, + [ZFS_HEADER] = A_BOLD, + [ZFS_OTHER] = A_DIM, + [ZFS_COMPRESSED] = A_BOLD, + [ZFS_RATIO] = A_BOLD, + [ZRAM] = A_NORMAL, }, [COLORSCHEME_BLACKONWHITE] = { - [RESET_COLOR] = ColorPair(Black,White), - [DEFAULT_COLOR] = ColorPair(Black,White), - [FUNCTION_BAR] = ColorPair(Black,Cyan), - [FUNCTION_KEY] = ColorPair(Black,White), - [PANEL_HEADER_FOCUS] = ColorPair(Black,Green), - [PANEL_HEADER_UNFOCUS] = ColorPair(Black,Green), - [PANEL_SELECTION_FOCUS] = ColorPair(Black,Cyan), - [PANEL_SELECTION_FOLLOW] = ColorPair(Black,Yellow), - [PANEL_SELECTION_UNFOCUS] = ColorPair(Blue,White), - [FAILED_SEARCH] = ColorPair(Red,Cyan), - [UPTIME] = ColorPair(Yellow,White), - [BATTERY] = ColorPair(Yellow,White), - [LARGE_NUMBER] = ColorPair(Red,White), - [METER_TEXT] = ColorPair(Blue,White), - [METER_VALUE] = ColorPair(Black,White), - [LED_COLOR] = ColorPair(Green,White), - [TASKS_RUNNING] = ColorPair(Green,White), - [PROCESS] = ColorPair(Black,White), - [PROCESS_SHADOW] = A_BOLD | ColorPair(Black,White), - [PROCESS_TAG] = ColorPair(White,Blue), - [PROCESS_MEGABYTES] = ColorPair(Blue,White), - [PROCESS_BASENAME] = ColorPair(Blue,White), - [PROCESS_TREE] = ColorPair(Green,White), - [PROCESS_R_STATE] = ColorPair(Green,White), - [PROCESS_D_STATE] = A_BOLD | ColorPair(Red,White), - [PROCESS_HIGH_PRIORITY] = ColorPair(Red,White), - [PROCESS_LOW_PRIORITY] = ColorPair(Green,White), - [PROCESS_THREAD] = ColorPair(Blue,White), - [PROCESS_THREAD_BASENAME] = A_BOLD | ColorPair(Blue,White), - [BAR_BORDER] = ColorPair(Blue,White), - [BAR_SHADOW] = ColorPair(Black,White), - [SWAP] = ColorPair(Red,White), - [GRAPH_1] = A_BOLD | ColorPair(Blue,White), - [GRAPH_2] = ColorPair(Blue,White), - [MEMORY_USED] = ColorPair(Green,White), - [MEMORY_BUFFERS] = ColorPair(Cyan,White), - [MEMORY_BUFFERS_TEXT] = ColorPair(Cyan,White), - [MEMORY_CACHE] = ColorPair(Yellow,White), - [LOAD_AVERAGE_FIFTEEN] = ColorPair(Black,White), - [LOAD_AVERAGE_FIVE] = ColorPair(Black,White), - [LOAD_AVERAGE_ONE] = ColorPair(Black,White), - [LOAD] = ColorPair(Black,White), - [HELP_BOLD] = ColorPair(Blue,White), - [CLOCK] = ColorPair(Black,White), - [CHECK_BOX] = ColorPair(Blue,White), - [CHECK_MARK] = ColorPair(Black,White), - [CHECK_TEXT] = ColorPair(Black,White), - [HOSTNAME] = ColorPair(Black,White), - [CPU_NICE] = ColorPair(Cyan,White), - [CPU_NICE_TEXT] = ColorPair(Cyan,White), - [CPU_NORMAL] = ColorPair(Green,White), - [CPU_KERNEL] = ColorPair(Red,White), + [RESET_COLOR] = ColorPair(Black, White), + [DEFAULT_COLOR] = ColorPair(Black, White), + [FUNCTION_BAR] = ColorPair(Black, Cyan), + [FUNCTION_KEY] = ColorPair(Black, White), + [PANEL_HEADER_FOCUS] = ColorPair(Black, Green), + [PANEL_HEADER_UNFOCUS] = ColorPair(Black, Green), + [PANEL_SELECTION_FOCUS] = ColorPair(Black, Cyan), + [PANEL_SELECTION_FOLLOW] = ColorPair(Black, Yellow), + [PANEL_SELECTION_UNFOCUS] = ColorPair(Blue, White), + [FAILED_SEARCH] = ColorPair(Red, Cyan), + [PAUSED] = A_BOLD | ColorPair(Yellow, Cyan), + [UPTIME] = ColorPair(Yellow, White), + [BATTERY] = ColorPair(Yellow, White), + [LARGE_NUMBER] = ColorPair(Red, White), + [METER_TEXT] = ColorPair(Blue, White), + [METER_VALUE] = ColorPair(Black, White), + [METER_VALUE_ERROR] = A_BOLD | ColorPair(Red, White), + [METER_VALUE_IOREAD] = ColorPair(Green, White), + [METER_VALUE_IOWRITE] = ColorPair(Yellow, White), + [METER_VALUE_NOTICE] = A_BOLD | ColorPair(Yellow, White), + [METER_VALUE_OK] = ColorPair(Green, White), + [LED_COLOR] = ColorPair(Green, White), + [TASKS_RUNNING] = ColorPair(Green, White), + [PROCESS] = ColorPair(Black, White), + [PROCESS_SHADOW] = A_BOLD | ColorPair(Black, White), + [PROCESS_TAG] = ColorPair(White, Blue), + [PROCESS_MEGABYTES] = ColorPair(Blue, White), + [PROCESS_GIGABYTES] = ColorPair(Green, White), + [PROCESS_BASENAME] = ColorPair(Blue, White), + [PROCESS_TREE] = ColorPair(Green, White), + [PROCESS_R_STATE] = ColorPair(Green, White), + [PROCESS_D_STATE] = A_BOLD | ColorPair(Red, White), + [PROCESS_HIGH_PRIORITY] = ColorPair(Red, White), + [PROCESS_LOW_PRIORITY] = ColorPair(Green, White), + [PROCESS_NEW] = ColorPair(White, Green), + [PROCESS_TOMB] = ColorPair(White, Red), + [PROCESS_THREAD] = ColorPair(Blue, White), + [PROCESS_THREAD_BASENAME] = A_BOLD | ColorPair(Blue, White), + [BAR_BORDER] = ColorPair(Blue, White), + [BAR_SHADOW] = ColorPair(Black, White), + [SWAP] = ColorPair(Red, White), + [GRAPH_1] = A_BOLD | ColorPair(Blue, White), + [GRAPH_2] = ColorPair(Blue, White), + [MEMORY_USED] = ColorPair(Green, White), + [MEMORY_BUFFERS] = ColorPair(Cyan, White), + [MEMORY_BUFFERS_TEXT] = ColorPair(Cyan, White), + [MEMORY_CACHE] = ColorPair(Yellow, White), + [LOAD_AVERAGE_FIFTEEN] = ColorPair(Black, White), + [LOAD_AVERAGE_FIVE] = ColorPair(Black, White), + [LOAD_AVERAGE_ONE] = ColorPair(Black, White), + [LOAD] = ColorPair(Black, White), + [HELP_BOLD] = ColorPair(Blue, White), + [CLOCK] = ColorPair(Black, White), + [DATE] = ColorPair(Black, White), + [DATETIME] = ColorPair(Black, White), + [CHECK_BOX] = ColorPair(Blue, White), + [CHECK_MARK] = ColorPair(Black, White), + [CHECK_TEXT] = ColorPair(Black, White), + [HOSTNAME] = ColorPair(Black, White), + [CPU_NICE] = ColorPair(Cyan, White), + [CPU_NICE_TEXT] = ColorPair(Cyan, White), + [CPU_NORMAL] = ColorPair(Green, White), + [CPU_SYSTEM] = ColorPair(Red, White), [CPU_IOWAIT] = A_BOLD | ColorPair(Black, White), - [CPU_IRQ] = ColorPair(Blue,White), - [CPU_SOFTIRQ] = ColorPair(Blue,White), - [CPU_STEAL] = ColorPair(Cyan,White), - [CPU_GUEST] = ColorPair(Cyan,White), + [CPU_IRQ] = ColorPair(Blue, White), + [CPU_SOFTIRQ] = ColorPair(Blue, White), + [CPU_STEAL] = ColorPair(Cyan, White), + [CPU_GUEST] = ColorPair(Cyan, White), + [PRESSURE_STALL_THREEHUNDRED] = ColorPair(Black, White), + [PRESSURE_STALL_SIXTY] = ColorPair(Black, White), + [PRESSURE_STALL_TEN] = ColorPair(Black, White), + [ZFS_MFU] = ColorPair(Cyan, White), + [ZFS_MRU] = ColorPair(Yellow, White), + [ZFS_ANON] = ColorPair(Magenta, White), + [ZFS_HEADER] = ColorPair(Yellow, White), + [ZFS_OTHER] = ColorPair(Magenta, White), + [ZFS_COMPRESSED] = ColorPair(Cyan, White), + [ZFS_RATIO] = ColorPair(Magenta, White), + [ZRAM] = ColorPair(Yellow, White) }, [COLORSCHEME_LIGHTTERMINAL] = { - [RESET_COLOR] = ColorPair(Black,Black), - [DEFAULT_COLOR] = ColorPair(Black,Black), - [FUNCTION_BAR] = ColorPair(Black,Cyan), - [FUNCTION_KEY] = ColorPair(Black,Black), - [PANEL_HEADER_FOCUS] = ColorPair(Black,Green), - [PANEL_HEADER_UNFOCUS] = ColorPair(Black,Green), - [PANEL_SELECTION_FOCUS] = ColorPair(Black,Cyan), - [PANEL_SELECTION_FOLLOW] = ColorPair(Black,Yellow), - [PANEL_SELECTION_UNFOCUS] = ColorPair(Blue,Black), - [FAILED_SEARCH] = ColorPair(Red,Cyan), - [UPTIME] = ColorPair(Yellow,Black), - [BATTERY] = ColorPair(Yellow,Black), - [LARGE_NUMBER] = ColorPair(Red,Black), - [METER_TEXT] = ColorPair(Blue,Black), - [METER_VALUE] = ColorPair(Black,Black), - [LED_COLOR] = ColorPair(Green,Black), - [TASKS_RUNNING] = ColorPair(Green,Black), - [PROCESS] = ColorPair(Black,Black), + [RESET_COLOR] = ColorPair(Blue, Black), + [DEFAULT_COLOR] = ColorPair(Blue, Black), + [FUNCTION_BAR] = ColorPair(Black, Cyan), + [FUNCTION_KEY] = ColorPair(Blue, Black), + [PANEL_HEADER_FOCUS] = ColorPair(Black, Green), + [PANEL_HEADER_UNFOCUS] = ColorPair(Black, Green), + [PANEL_SELECTION_FOCUS] = ColorPair(Black, Cyan), + [PANEL_SELECTION_FOLLOW] = ColorPair(Black, Yellow), + [PANEL_SELECTION_UNFOCUS] = ColorPair(Blue, Black), + [FAILED_SEARCH] = ColorPair(Red, Cyan), + [PAUSED] = A_BOLD | ColorPair(Yellow, Cyan), + [UPTIME] = ColorPair(Yellow, Black), + [BATTERY] = ColorPair(Yellow, Black), + [LARGE_NUMBER] = ColorPair(Red, Black), + [METER_TEXT] = ColorPair(Blue, Black), + [METER_VALUE] = ColorPair(Blue, Black), + [METER_VALUE_ERROR] = A_BOLD | ColorPair(Red, Black), + [METER_VALUE_IOREAD] = ColorPair(Green, Black), + [METER_VALUE_IOWRITE] = ColorPair(Yellow, Black), + [METER_VALUE_NOTICE] = A_BOLD | ColorPair(Yellow, Black), + [METER_VALUE_OK] = ColorPair(Green, Black), + [LED_COLOR] = ColorPair(Green, Black), + [TASKS_RUNNING] = ColorPair(Green, Black), + [PROCESS] = ColorPair(Blue, Black), [PROCESS_SHADOW] = A_BOLD | ColorPairGrayBlack, - [PROCESS_TAG] = ColorPair(White,Blue), - [PROCESS_MEGABYTES] = ColorPair(Blue,Black), - [PROCESS_BASENAME] = ColorPair(Green,Black), - [PROCESS_TREE] = ColorPair(Blue,Black), - [PROCESS_R_STATE] = ColorPair(Green,Black), - [PROCESS_D_STATE] = A_BOLD | ColorPair(Red,Black), - [PROCESS_HIGH_PRIORITY] = ColorPair(Red,Black), - [PROCESS_LOW_PRIORITY] = ColorPair(Green,Black), - [PROCESS_THREAD] = ColorPair(Blue,Black), - [PROCESS_THREAD_BASENAME] = A_BOLD | ColorPair(Blue,Black), - [BAR_BORDER] = ColorPair(Blue,Black), + [PROCESS_TAG] = ColorPair(Yellow, Blue), + [PROCESS_MEGABYTES] = ColorPair(Blue, Black), + [PROCESS_GIGABYTES] = ColorPair(Green, Black), + [PROCESS_BASENAME] = ColorPair(Green, Black), + [PROCESS_TREE] = ColorPair(Blue, Black), + [PROCESS_R_STATE] = ColorPair(Green, Black), + [PROCESS_D_STATE] = A_BOLD | ColorPair(Red, Black), + [PROCESS_HIGH_PRIORITY] = ColorPair(Red, Black), + [PROCESS_LOW_PRIORITY] = ColorPair(Green, Black), + [PROCESS_NEW] = ColorPair(Black, Green), + [PROCESS_TOMB] = ColorPair(Black, Red), + [PROCESS_THREAD] = ColorPair(Blue, Black), + [PROCESS_THREAD_BASENAME] = A_BOLD | ColorPair(Blue, Black), + [BAR_BORDER] = ColorPair(Blue, Black), [BAR_SHADOW] = ColorPairGrayBlack, - [SWAP] = ColorPair(Red,Black), - [GRAPH_1] = A_BOLD | ColorPair(Cyan,Black), - [GRAPH_2] = ColorPair(Cyan,Black), - [MEMORY_USED] = ColorPair(Green,Black), - [MEMORY_BUFFERS] = ColorPair(Cyan,Black), - [MEMORY_BUFFERS_TEXT] = ColorPair(Cyan,Black), - [MEMORY_CACHE] = ColorPair(Yellow,Black), - [LOAD_AVERAGE_FIFTEEN] = ColorPair(Black,Black), - [LOAD_AVERAGE_FIVE] = ColorPair(Black,Black), - [LOAD_AVERAGE_ONE] = ColorPair(Black,Black), - [LOAD] = ColorPair(White,Black), - [HELP_BOLD] = ColorPair(Blue,Black), - [CLOCK] = ColorPair(White,Black), - [CHECK_BOX] = ColorPair(Blue,Black), - [CHECK_MARK] = ColorPair(Black,Black), - [CHECK_TEXT] = ColorPair(Black,Black), - [HOSTNAME] = ColorPair(White,Black), - [CPU_NICE] = ColorPair(Cyan,Black), - [CPU_NICE_TEXT] = ColorPair(Cyan,Black), - [CPU_NORMAL] = ColorPair(Green,Black), - [CPU_KERNEL] = ColorPair(Red,Black), - [CPU_IOWAIT] = A_BOLD | ColorPair(Black, Black), - [CPU_IRQ] = A_BOLD | ColorPair(Blue,Black), - [CPU_SOFTIRQ] = ColorPair(Blue,Black), - [CPU_STEAL] = ColorPair(Black,Black), - [CPU_GUEST] = ColorPair(Black,Black), + [SWAP] = ColorPair(Red, Black), + [GRAPH_1] = A_BOLD | ColorPair(Cyan, Black), + [GRAPH_2] = ColorPair(Cyan, Black), + [MEMORY_USED] = ColorPair(Green, Black), + [MEMORY_BUFFERS] = ColorPair(Cyan, Black), + [MEMORY_BUFFERS_TEXT] = ColorPair(Cyan, Black), + [MEMORY_CACHE] = ColorPair(Yellow, Black), + [LOAD_AVERAGE_FIFTEEN] = ColorPair(Blue, Black), + [LOAD_AVERAGE_FIVE] = ColorPair(Blue, Black), + [LOAD_AVERAGE_ONE] = ColorPair(Yellow, Black), + [LOAD] = ColorPair(Yellow, Black), + [HELP_BOLD] = ColorPair(Blue, Black), + [CLOCK] = ColorPair(Yellow, Black), + [DATE] = ColorPair(White, Black), + [DATETIME] = ColorPair(White, Black), + [CHECK_BOX] = ColorPair(Blue, Black), + [CHECK_MARK] = ColorPair(Blue, Black), + [CHECK_TEXT] = ColorPair(Blue, Black), + [HOSTNAME] = ColorPair(Yellow, Black), + [CPU_NICE] = ColorPair(Cyan, Black), + [CPU_NICE_TEXT] = ColorPair(Cyan, Black), + [CPU_NORMAL] = ColorPair(Green, Black), + [CPU_SYSTEM] = ColorPair(Red, Black), + [CPU_IOWAIT] = A_BOLD | ColorPair(Blue, Black), + [CPU_IRQ] = A_BOLD | ColorPair(Blue, Black), + [CPU_SOFTIRQ] = ColorPair(Blue, Black), + [CPU_STEAL] = ColorPair(Blue, Black), + [CPU_GUEST] = ColorPair(Blue, Black), + [PRESSURE_STALL_THREEHUNDRED] = ColorPair(Blue, Black), + [PRESSURE_STALL_SIXTY] = ColorPair(Blue, Black), + [PRESSURE_STALL_TEN] = ColorPair(Blue, Black), + [ZFS_MFU] = ColorPair(Cyan, Black), + [ZFS_MRU] = ColorPair(Yellow, Black), + [ZFS_ANON] = A_BOLD | ColorPair(Magenta, Black), + [ZFS_HEADER] = ColorPair(Blue, Black), + [ZFS_OTHER] = A_BOLD | ColorPair(Magenta, Black), + [ZFS_COMPRESSED] = ColorPair(Cyan, Black), + [ZFS_RATIO] = A_BOLD | ColorPair(Magenta, Black), + [ZRAM] = ColorPair(Yellow, Black), }, [COLORSCHEME_MIDNIGHT] = { - [RESET_COLOR] = ColorPair(White,Blue), - [DEFAULT_COLOR] = ColorPair(White,Blue), - [FUNCTION_BAR] = ColorPair(Black,Cyan), + [RESET_COLOR] = ColorPair(White, Blue), + [DEFAULT_COLOR] = ColorPair(White, Blue), + [FUNCTION_BAR] = ColorPair(Black, Cyan), [FUNCTION_KEY] = A_NORMAL, - [PANEL_HEADER_FOCUS] = ColorPair(Black,Cyan), - [PANEL_HEADER_UNFOCUS] = ColorPair(Black,Cyan), - [PANEL_SELECTION_FOCUS] = ColorPair(Black,White), - [PANEL_SELECTION_FOLLOW] = ColorPair(Black,Yellow), - [PANEL_SELECTION_UNFOCUS] = A_BOLD | ColorPair(Yellow,Blue), - [FAILED_SEARCH] = ColorPair(Red,Cyan), - [UPTIME] = A_BOLD | ColorPair(Yellow,Blue), - [BATTERY] = A_BOLD | ColorPair(Yellow,Blue), - [LARGE_NUMBER] = A_BOLD | ColorPair(Red,Blue), - [METER_TEXT] = ColorPair(Cyan,Blue), - [METER_VALUE] = A_BOLD | ColorPair(Cyan,Blue), - [LED_COLOR] = ColorPair(Green,Blue), - [TASKS_RUNNING] = A_BOLD | ColorPair(Green,Blue), - [PROCESS] = ColorPair(White,Blue), - [PROCESS_SHADOW] = A_BOLD | ColorPair(Black,Blue), - [PROCESS_TAG] = A_BOLD | ColorPair(Yellow,Blue), - [PROCESS_MEGABYTES] = ColorPair(Cyan,Blue), - [PROCESS_BASENAME] = A_BOLD | ColorPair(Cyan,Blue), - [PROCESS_TREE] = ColorPair(Cyan,Blue), - [PROCESS_R_STATE] = ColorPair(Green,Blue), - [PROCESS_D_STATE] = A_BOLD | ColorPair(Red,Blue), - [PROCESS_HIGH_PRIORITY] = ColorPair(Red,Blue), - [PROCESS_LOW_PRIORITY] = ColorPair(Green,Blue), - [PROCESS_THREAD] = ColorPair(Green,Blue), - [PROCESS_THREAD_BASENAME] = A_BOLD | ColorPair(Green,Blue), - [BAR_BORDER] = A_BOLD | ColorPair(Yellow,Blue), - [BAR_SHADOW] = ColorPair(Cyan,Blue), - [SWAP] = ColorPair(Red,Blue), - [GRAPH_1] = A_BOLD | ColorPair(Cyan,Blue), - [GRAPH_2] = ColorPair(Cyan,Blue), - [MEMORY_USED] = A_BOLD | ColorPair(Green,Blue), - [MEMORY_BUFFERS] = A_BOLD | ColorPair(Cyan,Blue), - [MEMORY_BUFFERS_TEXT] = A_BOLD | ColorPair(Cyan,Blue), - [MEMORY_CACHE] = A_BOLD | ColorPair(Yellow,Blue), - [LOAD_AVERAGE_FIFTEEN] = A_BOLD | ColorPair(Black,Blue), - [LOAD_AVERAGE_FIVE] = A_NORMAL | ColorPair(White,Blue), - [LOAD_AVERAGE_ONE] = A_BOLD | ColorPair(White,Blue), - [LOAD] = A_BOLD | ColorPair(White,Blue), - [HELP_BOLD] = A_BOLD | ColorPair(Cyan,Blue), - [CLOCK] = ColorPair(White,Blue), - [CHECK_BOX] = ColorPair(Cyan,Blue), - [CHECK_MARK] = A_BOLD | ColorPair(White,Blue), - [CHECK_TEXT] = A_NORMAL | ColorPair(White,Blue), - [HOSTNAME] = ColorPair(White,Blue), - [CPU_NICE] = A_BOLD | ColorPair(Cyan,Blue), - [CPU_NICE_TEXT] = A_BOLD | ColorPair(Cyan,Blue), - [CPU_NORMAL] = A_BOLD | ColorPair(Green,Blue), - [CPU_KERNEL] = A_BOLD | ColorPair(Red,Blue), - [CPU_IOWAIT] = A_BOLD | ColorPair(Blue,Blue), - [CPU_IRQ] = A_BOLD | ColorPair(Black,Blue), - [CPU_SOFTIRQ] = ColorPair(Black,Blue), - [CPU_STEAL] = ColorPair(White,Blue), - [CPU_GUEST] = ColorPair(White,Blue), + [PANEL_HEADER_FOCUS] = ColorPair(Black, Cyan), + [PANEL_HEADER_UNFOCUS] = ColorPair(Black, Cyan), + [PANEL_SELECTION_FOCUS] = ColorPair(Black, White), + [PANEL_SELECTION_FOLLOW] = ColorPair(Black, Yellow), + [PANEL_SELECTION_UNFOCUS] = A_BOLD | ColorPair(Yellow, Blue), + [FAILED_SEARCH] = ColorPair(Red, Cyan), + [PAUSED] = A_BOLD | ColorPair(Yellow, Cyan), + [UPTIME] = A_BOLD | ColorPair(Yellow, Blue), + [BATTERY] = A_BOLD | ColorPair(Yellow, Blue), + [LARGE_NUMBER] = A_BOLD | ColorPair(Red, Blue), + [METER_TEXT] = ColorPair(Cyan, Blue), + [METER_VALUE] = A_BOLD | ColorPair(Cyan, Blue), + [METER_VALUE_ERROR] = A_BOLD | ColorPair(Red, Blue), + [METER_VALUE_IOREAD] = ColorPair(Green, Blue), + [METER_VALUE_IOWRITE] = ColorPair(Black, Blue), + [METER_VALUE_NOTICE] = A_BOLD | ColorPair(White, Blue), + [METER_VALUE_OK] = ColorPair(Green, Blue), + [LED_COLOR] = ColorPair(Green, Blue), + [TASKS_RUNNING] = A_BOLD | ColorPair(Green, Blue), + [PROCESS] = ColorPair(White, Blue), + [PROCESS_SHADOW] = A_BOLD | ColorPair(Black, Blue), + [PROCESS_TAG] = A_BOLD | ColorPair(Yellow, Blue), + [PROCESS_MEGABYTES] = ColorPair(Cyan, Blue), + [PROCESS_GIGABYTES] = ColorPair(Green, Blue), + [PROCESS_BASENAME] = A_BOLD | ColorPair(Cyan, Blue), + [PROCESS_TREE] = ColorPair(Cyan, Blue), + [PROCESS_R_STATE] = ColorPair(Green, Blue), + [PROCESS_D_STATE] = A_BOLD | ColorPair(Red, Blue), + [PROCESS_HIGH_PRIORITY] = ColorPair(Red, Blue), + [PROCESS_LOW_PRIORITY] = ColorPair(Green, Blue), + [PROCESS_NEW] = ColorPair(Blue, Green), + [PROCESS_TOMB] = ColorPair(Blue, Red), + [PROCESS_THREAD] = ColorPair(Green, Blue), + [PROCESS_THREAD_BASENAME] = A_BOLD | ColorPair(Green, Blue), + [BAR_BORDER] = A_BOLD | ColorPair(Yellow, Blue), + [BAR_SHADOW] = ColorPair(Cyan, Blue), + [SWAP] = ColorPair(Red, Blue), + [GRAPH_1] = A_BOLD | ColorPair(Cyan, Blue), + [GRAPH_2] = ColorPair(Cyan, Blue), + [MEMORY_USED] = A_BOLD | ColorPair(Green, Blue), + [MEMORY_BUFFERS] = A_BOLD | ColorPair(Cyan, Blue), + [MEMORY_BUFFERS_TEXT] = A_BOLD | ColorPair(Cyan, Blue), + [MEMORY_CACHE] = A_BOLD | ColorPair(Yellow, Blue), + [LOAD_AVERAGE_FIFTEEN] = A_BOLD | ColorPair(Black, Blue), + [LOAD_AVERAGE_FIVE] = A_NORMAL | ColorPair(White, Blue), + [LOAD_AVERAGE_ONE] = A_BOLD | ColorPair(White, Blue), + [LOAD] = A_BOLD | ColorPair(White, Blue), + [HELP_BOLD] = A_BOLD | ColorPair(Cyan, Blue), + [CLOCK] = ColorPair(White, Blue), + [DATE] = ColorPair(White, Blue), + [DATETIME] = ColorPair(White, Blue), + [CHECK_BOX] = ColorPair(Cyan, Blue), + [CHECK_MARK] = A_BOLD | ColorPair(White, Blue), + [CHECK_TEXT] = A_NORMAL | ColorPair(White, Blue), + [HOSTNAME] = ColorPair(White, Blue), + [CPU_NICE] = A_BOLD | ColorPair(Cyan, Blue), + [CPU_NICE_TEXT] = A_BOLD | ColorPair(Cyan, Blue), + [CPU_NORMAL] = A_BOLD | ColorPair(Green, Blue), + [CPU_SYSTEM] = A_BOLD | ColorPair(Red, Blue), + [CPU_IOWAIT] = A_BOLD | ColorPair(Black, Blue), + [CPU_IRQ] = A_BOLD | ColorPair(Black, Blue), + [CPU_SOFTIRQ] = ColorPair(Black, Blue), + [CPU_STEAL] = ColorPair(White, Blue), + [CPU_GUEST] = ColorPair(White, Blue), + [PRESSURE_STALL_THREEHUNDRED] = A_BOLD | ColorPair(Black, Blue), + [PRESSURE_STALL_SIXTY] = A_NORMAL | ColorPair(White, Blue), + [PRESSURE_STALL_TEN] = A_BOLD | ColorPair(White, Blue), + [ZFS_MFU] = A_BOLD | ColorPair(White, Blue), + [ZFS_MRU] = A_BOLD | ColorPair(Yellow, Blue), + [ZFS_ANON] = A_BOLD | ColorPair(Magenta, Blue), + [ZFS_HEADER] = A_BOLD | ColorPair(Yellow, Blue), + [ZFS_OTHER] = A_BOLD | ColorPair(Magenta, Blue), + [ZFS_COMPRESSED] = A_BOLD | ColorPair(White, Blue), + [ZFS_RATIO] = A_BOLD | ColorPair(Magenta, Blue), + [ZRAM] = A_BOLD | ColorPair(Yellow, Blue), }, [COLORSCHEME_BLACKNIGHT] = { - [RESET_COLOR] = ColorPair(Cyan,Black), - [DEFAULT_COLOR] = ColorPair(Cyan,Black), - [FUNCTION_BAR] = ColorPair(Black,Green), - [FUNCTION_KEY] = ColorPair(Cyan,Black), - [PANEL_HEADER_FOCUS] = ColorPair(Black,Green), - [PANEL_HEADER_UNFOCUS] = ColorPair(Black,Green), - [PANEL_SELECTION_FOCUS] = ColorPair(Black,Cyan), - [PANEL_SELECTION_FOLLOW] = ColorPair(Black,Yellow), - [PANEL_SELECTION_UNFOCUS] = ColorPair(Black,White), - [FAILED_SEARCH] = ColorPair(Red,Cyan), - [UPTIME] = ColorPair(Green,Black), - [BATTERY] = ColorPair(Green,Black), - [LARGE_NUMBER] = A_BOLD | ColorPair(Red,Black), - [METER_TEXT] = ColorPair(Cyan,Black), - [METER_VALUE] = ColorPair(Green,Black), - [LED_COLOR] = ColorPair(Green,Black), - [TASKS_RUNNING] = A_BOLD | ColorPair(Green,Black), - [PROCESS] = ColorPair(Cyan,Black), + [RESET_COLOR] = ColorPair(Cyan, Black), + [DEFAULT_COLOR] = ColorPair(Cyan, Black), + [FUNCTION_BAR] = ColorPair(Black, Green), + [FUNCTION_KEY] = ColorPair(Cyan, Black), + [PANEL_HEADER_FOCUS] = ColorPair(Black, Green), + [PANEL_HEADER_UNFOCUS] = ColorPair(Black, Green), + [PANEL_SELECTION_FOCUS] = ColorPair(Black, Cyan), + [PANEL_SELECTION_FOLLOW] = ColorPair(Black, Yellow), + [PANEL_SELECTION_UNFOCUS] = ColorPair(Black, White), + [FAILED_SEARCH] = ColorPair(Red, Green), + [PAUSED] = A_BOLD | ColorPair(Yellow, Green), + [UPTIME] = ColorPair(Green, Black), + [BATTERY] = ColorPair(Green, Black), + [LARGE_NUMBER] = A_BOLD | ColorPair(Red, Black), + [METER_TEXT] = ColorPair(Cyan, Black), + [METER_VALUE] = ColorPair(Green, Black), + [METER_VALUE_ERROR] = A_BOLD | ColorPair(Red, Black), + [METER_VALUE_IOREAD] = ColorPair(Green, Black), + [METER_VALUE_IOWRITE] = ColorPair(Blue, Black), + [METER_VALUE_NOTICE] = A_BOLD | ColorPair(Yellow, Black), + [METER_VALUE_OK] = ColorPair(Green, Black), + [LED_COLOR] = ColorPair(Green, Black), + [TASKS_RUNNING] = A_BOLD | ColorPair(Green, Black), + [PROCESS] = ColorPair(Cyan, Black), [PROCESS_SHADOW] = A_BOLD | ColorPairGrayBlack, - [PROCESS_TAG] = A_BOLD | ColorPair(Yellow,Black), - [PROCESS_MEGABYTES] = A_BOLD | ColorPair(Green,Black), - [PROCESS_BASENAME] = A_BOLD | ColorPair(Green,Black), - [PROCESS_TREE] = ColorPair(Cyan,Black), - [PROCESS_THREAD] = ColorPair(Green,Black), - [PROCESS_THREAD_BASENAME] = A_BOLD | ColorPair(Blue,Black), - [PROCESS_R_STATE] = ColorPair(Green,Black), - [PROCESS_D_STATE] = A_BOLD | ColorPair(Red,Black), - [PROCESS_HIGH_PRIORITY] = ColorPair(Red,Black), - [PROCESS_LOW_PRIORITY] = ColorPair(Green,Black), - [BAR_BORDER] = A_BOLD | ColorPair(Green,Black), - [BAR_SHADOW] = ColorPair(Cyan,Black), - [SWAP] = ColorPair(Red,Black), - [GRAPH_1] = A_BOLD | ColorPair(Green,Black), - [GRAPH_2] = ColorPair(Green,Black), - [MEMORY_USED] = ColorPair(Green,Black), - [MEMORY_BUFFERS] = ColorPair(Blue,Black), - [MEMORY_BUFFERS_TEXT] = A_BOLD | ColorPair(Blue,Black), - [MEMORY_CACHE] = ColorPair(Yellow,Black), - [LOAD_AVERAGE_FIFTEEN] = ColorPair(Green,Black), - [LOAD_AVERAGE_FIVE] = ColorPair(Green,Black), - [LOAD_AVERAGE_ONE] = A_BOLD | ColorPair(Green,Black), + [PROCESS_TAG] = A_BOLD | ColorPair(Yellow, Black), + [PROCESS_MEGABYTES] = A_BOLD | ColorPair(Green, Black), + [PROCESS_GIGABYTES] = A_BOLD | ColorPair(Yellow, Black), + [PROCESS_BASENAME] = A_BOLD | ColorPair(Green, Black), + [PROCESS_TREE] = ColorPair(Cyan, Black), + [PROCESS_THREAD] = ColorPair(Green, Black), + [PROCESS_THREAD_BASENAME] = A_BOLD | ColorPair(Blue, Black), + [PROCESS_R_STATE] = ColorPair(Green, Black), + [PROCESS_D_STATE] = A_BOLD | ColorPair(Red, Black), + [PROCESS_HIGH_PRIORITY] = ColorPair(Red, Black), + [PROCESS_LOW_PRIORITY] = ColorPair(Green, Black), + [PROCESS_NEW] = ColorPair(Black, Green), + [PROCESS_TOMB] = ColorPair(Black, Red), + [BAR_BORDER] = A_BOLD | ColorPair(Green, Black), + [BAR_SHADOW] = ColorPair(Cyan, Black), + [SWAP] = ColorPair(Red, Black), + [GRAPH_1] = A_BOLD | ColorPair(Green, Black), + [GRAPH_2] = ColorPair(Green, Black), + [MEMORY_USED] = ColorPair(Green, Black), + [MEMORY_BUFFERS] = ColorPair(Blue, Black), + [MEMORY_BUFFERS_TEXT] = A_BOLD | ColorPair(Blue, Black), + [MEMORY_CACHE] = ColorPair(Yellow, Black), + [LOAD_AVERAGE_FIFTEEN] = ColorPair(Green, Black), + [LOAD_AVERAGE_FIVE] = ColorPair(Green, Black), + [LOAD_AVERAGE_ONE] = A_BOLD | ColorPair(Green, Black), [LOAD] = A_BOLD, - [HELP_BOLD] = A_BOLD | ColorPair(Cyan,Black), - [CLOCK] = ColorPair(Green,Black), - [CHECK_BOX] = ColorPair(Green,Black), - [CHECK_MARK] = A_BOLD | ColorPair(Green,Black), - [CHECK_TEXT] = ColorPair(Cyan,Black), - [HOSTNAME] = ColorPair(Green,Black), - [CPU_NICE] = ColorPair(Blue,Black), - [CPU_NICE_TEXT] = A_BOLD | ColorPair(Blue,Black), - [CPU_NORMAL] = ColorPair(Green,Black), - [CPU_KERNEL] = ColorPair(Red,Black), - [CPU_IOWAIT] = ColorPair(Yellow,Black), - [CPU_IRQ] = A_BOLD | ColorPair(Blue,Black), - [CPU_SOFTIRQ] = ColorPair(Blue,Black), - [CPU_STEAL] = ColorPair(Cyan,Black), - [CPU_GUEST] = ColorPair(Cyan,Black), + [HELP_BOLD] = A_BOLD | ColorPair(Cyan, Black), + [CLOCK] = ColorPair(Green, Black), + [CHECK_BOX] = ColorPair(Green, Black), + [CHECK_MARK] = A_BOLD | ColorPair(Green, Black), + [CHECK_TEXT] = ColorPair(Cyan, Black), + [HOSTNAME] = ColorPair(Green, Black), + [CPU_NICE] = ColorPair(Blue, Black), + [CPU_NICE_TEXT] = A_BOLD | ColorPair(Blue, Black), + [CPU_NORMAL] = ColorPair(Green, Black), + [CPU_SYSTEM] = ColorPair(Red, Black), + [CPU_IOWAIT] = ColorPair(Yellow, Black), + [CPU_IRQ] = A_BOLD | ColorPair(Blue, Black), + [CPU_SOFTIRQ] = ColorPair(Blue, Black), + [CPU_STEAL] = ColorPair(Cyan, Black), + [CPU_GUEST] = ColorPair(Cyan, Black), + [PRESSURE_STALL_THREEHUNDRED] = ColorPair(Green, Black), + [PRESSURE_STALL_SIXTY] = ColorPair(Green, Black), + [PRESSURE_STALL_TEN] = A_BOLD | ColorPair(Green, Black), + [ZFS_MFU] = ColorPair(Blue, Black), + [ZFS_MRU] = ColorPair(Yellow, Black), + [ZFS_ANON] = ColorPair(Magenta, Black), + [ZFS_HEADER] = ColorPair(Yellow, Black), + [ZFS_OTHER] = ColorPair(Magenta, Black), + [ZFS_COMPRESSED] = ColorPair(Blue, Black), + [ZFS_RATIO] = ColorPair(Magenta, Black), + [ZRAM] = ColorPair(Yellow, Black), }, [COLORSCHEME_BROKENGRAY] = { 0 } // dynamically generated. }; @@ -537,96 +570,85 @@ int CRT_scrollHAmount = 5; int CRT_scrollWheelVAmount = 10; -char* CRT_termType; - -// TODO move color scheme to Settings, perhaps? +const char* CRT_termType; int CRT_colorScheme = 0; -void *backtraceArray[128]; +long CRT_pageSize = -1; +long CRT_pageSizeKB = -1; +ATTR_NORETURN static void CRT_handleSIGTERM(int sgn) { (void) sgn; CRT_done(); exit(0); } -#if HAVE_SETUID_ENABLED +#ifdef HAVE_SETUID_ENABLED static int CRT_euid = -1; static int CRT_egid = -1; -#define DIE(msg) do { CRT_done(); fprintf(stderr, msg); exit(1); } while(0) - void CRT_dropPrivileges() { CRT_egid = getegid(); CRT_euid = geteuid(); if (setegid(getgid()) == -1) { - DIE("Fatal error: failed dropping group privileges.\n"); + CRT_fatalError("Fatal error: failed dropping group privileges"); } if (seteuid(getuid()) == -1) { - DIE("Fatal error: failed dropping user privileges.\n"); + CRT_fatalError("Fatal error: failed dropping user privileges"); } } void CRT_restorePrivileges() { if (CRT_egid == -1 || CRT_euid == -1) { - DIE("Fatal error: internal inconsistency.\n"); + CRT_fatalError("Fatal error: internal inconsistency"); } if (setegid(CRT_egid) == -1) { - DIE("Fatal error: failed restoring group privileges.\n"); + CRT_fatalError("Fatal error: failed restoring group privileges"); } if (seteuid(CRT_euid) == -1) { - DIE("Fatal error: failed restoring user privileges.\n"); + CRT_fatalError("Fatal error: failed restoring user privileges"); } } -#else - -/* Turn setuid operations into NOPs */ - -#ifndef CRT_dropPrivileges -#define CRT_dropPrivileges() -#define CRT_restorePrivileges() -#endif +#endif /* HAVE_SETUID_ENABLED */ -#endif +static struct sigaction old_sig_handler[32]; // TODO: pass an instance of Settings instead. -void CRT_init(int delay, int colorScheme) { +void CRT_init(int delay, int colorScheme, bool allowUnicode) { initscr(); noecho(); - CRT_delay = delay; - if (CRT_delay == 0) { - CRT_delay = 1; - } + CRT_delay = CLAMP(delay, 1, 255); CRT_colors = CRT_colorSchemes[colorScheme]; CRT_colorScheme = colorScheme; - + for (int i = 0; i < LAST_COLORELEMENT; i++) { unsigned int color = CRT_colorSchemes[COLORSCHEME_DEFAULT][i]; - CRT_colorSchemes[COLORSCHEME_BROKENGRAY][i] = color == (A_BOLD | ColorPairGrayBlack) ? ColorPair(White,Black) : color; + CRT_colorSchemes[COLORSCHEME_BROKENGRAY][i] = color == (A_BOLD | ColorPairGrayBlack) ? ColorPair(White, Black) : color; } - + halfdelay(CRT_delay); nonl(); intrflush(stdscr, false); keypad(stdscr, true); mouseinterval(0); curs_set(0); + if (has_colors()) { start_color(); - CRT_hasColors = true; - } else { - CRT_hasColors = false; } + CRT_termType = getenv("TERM"); - if (String_eq(CRT_termType, "linux")) + if (String_eq(CRT_termType, "linux")) { CRT_scrollHAmount = 20; - else + } else { CRT_scrollHAmount = 5; + } + if (String_startsWith(CRT_termType, "xterm") || String_eq(CRT_termType, "vt220")) { define_key("\033[H", KEY_HOME); define_key("\033[F", KEY_END); @@ -647,9 +669,19 @@ void CRT_init(int delay, int colorScheme) { define_key(sequence, KEY_ALT('A' + (c - 'a'))); } } -#ifndef DEBUG - signal(11, CRT_handleSIGSEGV); -#endif + + struct sigaction act; + sigemptyset (&act.sa_mask); + act.sa_flags = (int)SA_RESETHAND | SA_NODEFER; + act.sa_handler = CRT_handleSIGSEGV; + sigaction (SIGSEGV, &act, &old_sig_handler[SIGSEGV]); + sigaction (SIGFPE, &act, &old_sig_handler[SIGFPE]); + sigaction (SIGILL, &act, &old_sig_handler[SIGILL]); + sigaction (SIGBUS, &act, &old_sig_handler[SIGBUS]); + sigaction (SIGPIPE, &act, &old_sig_handler[SIGPIPE]); + sigaction (SIGSYS, &act, &old_sig_handler[SIGSYS]); + sigaction (SIGABRT, &act, &old_sig_handler[SIGABRT]); + signal(SIGTERM, CRT_handleSIGTERM); signal(SIGQUIT, CRT_handleSIGTERM); use_default_colors(); @@ -661,10 +693,13 @@ void CRT_init(int delay, int colorScheme) { setlocale(LC_CTYPE, ""); #ifdef HAVE_LIBNCURSESW - if(strcmp(nl_langinfo(CODESET), "UTF-8") == 0) + if (allowUnicode && String_eq(nl_langinfo(CODESET), "UTF-8")) { CRT_utf8 = true; - else + } else { CRT_utf8 = false; + } +#else + (void) allowUnicode; #endif CRT_treeStr = @@ -679,6 +714,10 @@ void CRT_init(int delay, int colorScheme) { mousemask(BUTTON1_RELEASED, NULL); #endif + CRT_pageSize = sysconf(_SC_PAGESIZE); + if (CRT_pageSize == -1) + CRT_fatalError("Fatal error: Can not get PAGE_SIZE by sysconf(_SC_PAGESIZE)"); + CRT_pageSizeKB = CRT_pageSize / 1024; } void CRT_done() { @@ -717,11 +756,11 @@ void CRT_setColors(int colorScheme) { for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { - if (ColorIndex(i,j) != ColorPairGrayBlack) { + if (ColorIndex(i, j) != ColorPairGrayBlack) { int bg = (colorScheme != COLORSCHEME_BLACKNIGHT) - ? (j==0 ? -1 : j) + ? (j == 0 ? -1 : j) : j; - init_pair(ColorIndex(i,j), i, bg); + init_pair(ColorIndex(i, j), i, bg); } } } @@ -734,3 +773,92 @@ void CRT_setColors(int colorScheme) { CRT_colors = CRT_colorSchemes[colorScheme]; } + +void CRT_handleSIGSEGV(int signal) { + CRT_done(); + + fprintf(stderr, "\n\n" + "FATAL PROGRAM ERROR DETECTED\n" + "============================\n" + "Please check at https://htop.dev/issues whether this issue has already been reported.\n" + "If no similar issue has been reported before, please create a new issue with the following information:\n" + "\n" + "- Your htop version (htop --version)\n" + "- Your OS and kernel version (uname -a)\n" + "- Your distribution and release (lsb_release -a)\n" + "- Likely steps to reproduce (How did it happened?)\n" +#ifdef HAVE_EXECINFO_H + "- Backtrace of the issue (see below)\n" +#endif + "\n" + ); + + const char* signal_str = strsignal(signal); + if (!signal_str) { + signal_str = "unknown reason"; + } + fprintf(stderr, + "Error information:\n" + "------------------\n" + "A signal %d (%s) was received.\n" + "\n", + signal, signal_str + ); + +#ifdef HAVE_EXECINFO_H + fprintf(stderr, + "Backtrace information:\n" + "----------------------\n" + "The following function calls were active when the issue was detected:\n" + "---\n" + ); + + void *backtraceArray[256]; + + size_t size = backtrace(backtraceArray, ARRAYSIZE(backtraceArray)); + backtrace_symbols_fd(backtraceArray, size, 2); + fprintf(stderr, + "---\n" + "\n" + "To make the above information more practical to work with,\n" + "you should provide a disassembly of your binary.\n" + "This can usually be done by running the following command:\n" + "\n" +#ifdef HTOP_DARWIN + " otool -tvV `which htop` > ~/htop.otool\n" +#else + " objdump -d -S -w `which htop` > ~/htop.objdump\n" +#endif + "\n" + "Please include the generated file in your report.\n" + "\n" + ); +#endif + + fprintf(stderr, + "Running this program with debug symbols or inside a debugger may provide further insights.\n" + "\n" + "Thank you for helping to improve htop!\n" + "\n" + "htop " VERSION " aborting.\n" + "\n" + ); + + /* Call old sigsegv handler; may be default exit or third party one (e.g. ASAN) */ + if (sigaction (signal, &old_sig_handler[signal], NULL) < 0) { + /* This avoids an infinite loop in case the handler could not be reset. */ + fprintf(stderr, + "!!! Chained handler could not be restored. Forcing exit.\n" + ); + _exit(1); + } + + /* Trigger the previous signal handler. */ + raise(signal); + + // Always terminate, even if installed handler returns + fprintf(stderr, + "!!! Chained handler did not exit. Forcing exit.\n" + ); + _exit(1); +} diff --git a/CRT.h b/CRT.h index 933fe068e..00fa06573 100644 --- a/CRT.h +++ b/CRT.h @@ -1,40 +1,19 @@ -/* Do not edit this file. It was automatically generated. */ - #ifndef HEADER_CRT #define HEADER_CRT /* htop - CRT.h (C) 2004-2011 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ -#if HAVE_SETUID_ENABLED -#endif - -#define ColorIndex(i,j) ((7-i)*8+j) - -#define ColorPair(i,j) COLOR_PAIR(ColorIndex(i,j)) - -#define Black COLOR_BLACK -#define Red COLOR_RED -#define Green COLOR_GREEN -#define Yellow COLOR_YELLOW -#define Blue COLOR_BLUE -#define Magenta COLOR_MAGENTA -#define Cyan COLOR_CYAN -#define White COLOR_WHITE +#include "config.h" -#define ColorPairGrayBlack ColorPair(Magenta,Magenta) -#define ColorIndexGrayBlack ColorIndex(Magenta,Magenta) +#include -#define KEY_WHEELUP KEY_F(20) -#define KEY_WHEELDOWN KEY_F(21) -#define KEY_RECLICK KEY_F(22) +#include "Macros.h" +#include "ProvideCurses.h" -//#link curses - -#include typedef enum TreeStr_ { TREE_STR_HORZ, @@ -49,13 +28,13 @@ typedef enum TreeStr_ { typedef enum ColorSchemes_ { COLORSCHEME_DEFAULT = 0, - COLORSCHEME_MONOCHROME = 1, - COLORSCHEME_BLACKONWHITE = 2, - COLORSCHEME_LIGHTTERMINAL = 3, - COLORSCHEME_MIDNIGHT = 4, - COLORSCHEME_BLACKNIGHT = 5, - COLORSCHEME_BROKENGRAY = 6, - LAST_COLORSCHEME = 7, + COLORSCHEME_MONOCHROME, + COLORSCHEME_BLACKONWHITE, + COLORSCHEME_LIGHTTERMINAL, + COLORSCHEME_MIDNIGHT, + COLORSCHEME_BLACKNIGHT, + COLORSCHEME_BROKENGRAY, + LAST_COLORSCHEME, } ColorSchemes; typedef enum ColorElements_ { @@ -64,6 +43,7 @@ typedef enum ColorElements_ { FUNCTION_BAR, FUNCTION_KEY, FAILED_SEARCH, + PAUSED, PANEL_HEADER_FOCUS, PANEL_HEADER_UNFOCUS, PANEL_SELECTION_FOCUS, @@ -72,6 +52,11 @@ typedef enum ColorElements_ { LARGE_NUMBER, METER_TEXT, METER_VALUE, + METER_VALUE_ERROR, + METER_VALUE_IOREAD, + METER_VALUE_IOWRITE, + METER_VALUE_NOTICE, + METER_VALUE_OK, LED_COLOR, UPTIME, BATTERY, @@ -81,12 +66,15 @@ typedef enum ColorElements_ { PROCESS_SHADOW, PROCESS_TAG, PROCESS_MEGABYTES, + PROCESS_GIGABYTES, PROCESS_TREE, PROCESS_R_STATE, PROCESS_D_STATE, PROCESS_BASENAME, PROCESS_HIGH_PRIORITY, PROCESS_LOW_PRIORITY, + PROCESS_NEW, + PROCESS_TOMB, PROCESS_THREAD, PROCESS_THREAD_BASENAME, BAR_BORDER, @@ -105,42 +93,54 @@ typedef enum ColorElements_ { CHECK_MARK, CHECK_TEXT, CLOCK, + DATE, + DATETIME, HELP_BOLD, HOSTNAME, CPU_NICE, CPU_NICE_TEXT, CPU_NORMAL, - CPU_KERNEL, + CPU_SYSTEM, CPU_IOWAIT, CPU_IRQ, CPU_SOFTIRQ, CPU_STEAL, CPU_GUEST, + PRESSURE_STALL_TEN, + PRESSURE_STALL_SIXTY, + PRESSURE_STALL_THREEHUNDRED, + ZFS_MFU, + ZFS_MRU, + ZFS_ANON, + ZFS_HEADER, + ZFS_OTHER, + ZFS_COMPRESSED, + ZFS_RATIO, + ZRAM, LAST_COLORELEMENT } ColorElements; -void CRT_fatalError(const char* note) __attribute__ ((noreturn)); - -void CRT_handleSIGSEGV(int sgn); +void CRT_fatalError(const char* note) ATTR_NORETURN; -#define KEY_ALT(x) (KEY_F(64 - 26) + (x - 'A')) +void CRT_handleSIGSEGV(int signal) ATTR_NORETURN; +#define KEY_WHEELUP KEY_F(20) +#define KEY_WHEELDOWN KEY_F(21) +#define KEY_RECLICK KEY_F(22) +#define KEY_ALT(x) (KEY_F(64 - 26) + ((x) - 'A')) -extern const char *CRT_treeStrAscii[TREE_STR_COUNT]; #ifdef HAVE_LIBNCURSESW -extern const char *CRT_treeStrUtf8[TREE_STR_COUNT]; - extern bool CRT_utf8; #endif -extern const char **CRT_treeStr; +extern const char* const* CRT_treeStr; extern int CRT_delay; -int* CRT_colors; +extern const int* CRT_colors; extern int CRT_colorSchemes[LAST_COLORSCHEME][LAST_COLORELEMENT]; @@ -150,46 +150,36 @@ extern int CRT_scrollHAmount; extern int CRT_scrollWheelVAmount; -char* CRT_termType; - -// TODO move color scheme to Settings, perhaps? +extern const char* CRT_termType; extern int CRT_colorScheme; -void *backtraceArray[128]; +extern long CRT_pageSize; +extern long CRT_pageSizeKB; -#if HAVE_SETUID_ENABLED +#ifdef HAVE_SETUID_ENABLED -#define DIE(msg) do { CRT_done(); fprintf(stderr, msg); exit(1); } while(0) +void CRT_dropPrivileges(void); -void CRT_dropPrivileges(); +void CRT_restorePrivileges(void); -void CRT_restorePrivileges(); - -#else +#else /* HAVE_SETUID_ENABLED */ /* Turn setuid operations into NOPs */ +static inline void CRT_dropPrivileges(void) { } +static inline void CRT_restorePrivileges(void) { } -#ifndef CRT_dropPrivileges -#define CRT_dropPrivileges() -#define CRT_restorePrivileges() -#endif - -#endif - -// TODO: pass an instance of Settings instead. - -void CRT_init(int delay, int colorScheme); +#endif /* HAVE_SETUID_ENABLED */ -void CRT_done(); +void CRT_init(int delay, int colorScheme, bool allowUnicode); -void CRT_fatalError(const char* note); +void CRT_done(void); -int CRT_readKey(); +int CRT_readKey(void); -void CRT_disableDelay(); +void CRT_disableDelay(void); -void CRT_enableDelay(); +void CRT_enableDelay(void); void CRT_setColors(int colorScheme); diff --git a/CategoriesPanel.c b/CategoriesPanel.c index 437f1a7be..2dc1c3bfb 100644 --- a/CategoriesPanel.c +++ b/CategoriesPanel.c @@ -1,38 +1,28 @@ /* htop - CategoriesPanel.c (C) 2004-2011 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ #include "CategoriesPanel.h" -#include "AvailableMetersPanel.h" -#include "MetersPanel.h" -#include "DisplayOptionsPanel.h" -#include "ColumnsPanel.h" -#include "ColorsPanel.h" -#include "AvailableColumnsPanel.h" - -#include +#include +#include #include -/*{ -#include "Panel.h" -#include "Settings.h" -#include "ScreenManager.h" -#include "ProcessList.h" - -typedef struct CategoriesPanel_ { - Panel super; - ScreenManager* scr; - - Settings* settings; - Header* header; - ProcessList* pl; -} CategoriesPanel; +#include "AvailableColumnsPanel.h" +#include "AvailableMetersPanel.h" +#include "ColorsPanel.h" +#include "ColumnsPanel.h" +#include "DisplayOptionsPanel.h" +#include "FunctionBar.h" +#include "ListItem.h" +#include "MetersPanel.h" +#include "Object.h" +#include "ProvideCurses.h" +#include "Vector.h" -}*/ static const char* const CategoriesFunctions[] = {" ", " ", " ", " ", " ", " ", " ", " ", " ", "Done ", NULL}; @@ -97,7 +87,7 @@ static HandlerResult CategoriesPanel_eventHandler(Panel* super, int ch) { break; } default: - if (ch < 255 && isalpha(ch)) + if (0 < ch && ch < 255 && isalpha((unsigned char)ch)) result = Panel_selectByTyping(super, ch); if (result == BREAK_LOOP) result = IGNORED; @@ -107,6 +97,7 @@ static HandlerResult CategoriesPanel_eventHandler(Panel* super, int ch) { int size = ScreenManager_size(this->scr); for (int i = 1; i < size; i++) ScreenManager_remove(this->scr, 1); + switch (selected) { case 0: CategoriesPanel_makeMetersPage(this); @@ -125,7 +116,7 @@ static HandlerResult CategoriesPanel_eventHandler(Panel* super, int ch) { return result; } -PanelClass CategoriesPanel_class = { +const PanelClass CategoriesPanel_class = { .super = { .extends = Class(Panel), .delete = CategoriesPanel_delete diff --git a/CategoriesPanel.h b/CategoriesPanel.h index ccef0fae8..0582c642d 100644 --- a/CategoriesPanel.h +++ b/CategoriesPanel.h @@ -1,18 +1,17 @@ -/* Do not edit this file. It was automatically generated. */ - #ifndef HEADER_CategoriesPanel #define HEADER_CategoriesPanel /* htop - CategoriesPanel.h (C) 2004-2011 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ +#include "Header.h" #include "Panel.h" -#include "Settings.h" -#include "ScreenManager.h" #include "ProcessList.h" +#include "ScreenManager.h" +#include "Settings.h" typedef struct CategoriesPanel_ { Panel super; @@ -23,10 +22,9 @@ typedef struct CategoriesPanel_ { ProcessList* pl; } CategoriesPanel; - void CategoriesPanel_makeMetersPage(CategoriesPanel* this); -extern PanelClass CategoriesPanel_class; +extern const PanelClass CategoriesPanel_class; CategoriesPanel* CategoriesPanel_new(ScreenManager* scr, Settings* settings, Header* header, ProcessList* pl); diff --git a/ChangeLog b/ChangeLog index 453b96306..4df88d54c 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,89 @@ +What's new in version 3.0.2 + +* BUGFIX: Drop 'vim_mode' - several issues, needs rethink +* BUGFIX: fix regression in -u optional-argument handling +* Build system rework to remove python, header generation + (thanks to Zev Weiss and Hugo Musso Gualandi) +* BUGFIX: report nice level correctly on Solaris + (thanks to Dominik Hassler) +* CI, code quality improvements + (thanks to Tobias Kortkamp, Christian Hesse, Benny Baumann) + +What's new in version 3.0.1 + +* Coverity fixes, CI improvements, documentation updates +* BUGFIX: Fix early exit with longer sysfs battery paths +* BUGFIX: Improve OOM output, fix sorting + (thanks to Christian Göttsche) +* Rework check buttons and tree open/closed + (thanks to Bert Wesarg) +* Add -U/--no-unicode option to disable unicode + (thanks to Christian Hesse) +* Improvements to the affinity panel + (thanks to Bert Wesarg) + +What's new in version 3.0.0 + +* New maintainers - after a prolonged period of inactivity + from Hisham, the creator and original maintainer, a team + of community maintainers have volunteered to take over a + fork at https://htop.dev and https://github.com/htop-dev + to keep the project going. +* Support ZFS ARC statistics + (thanks to Ross Williams) +* Support more than 2 smaller CPU meter columns + (thanks to Christoph Budziszewski) +* Support Linux proportional set size metrics + (thanks to @linvinus, @ntninja and @himikof) +* Support Linux pressure stall information metrics + (thanks to Ran Benita) +* New display option to show CPU frequency in CPU meters + (thanks to Arnav Singh) +* Update Linux sysfs battery discovery for recent kernels + (thanks to @smattie) +* Add hardware topology information in the affinity panel + (thanks to Bert Wesarg) +* Add timestamp reporting to the strace screen + (thanks to Mario Harjac) +* Add simple, optional vim key mapping mode + (thanks to Daniel Flanagan) +* Added an option to disable the mouse + (thanks to MartinJM) +* Add Solaris11 compatibility + (thanks to Jan Senolt) +* Without an argument -u uses $USER value automatically + (thanks to @solanav) +* Support less(1) search navigation shortcuts + (thanks to @syrrim) +* Update the FreeBSD maximum PID to match FreeBSD change + (thanks to @multiplexd) +* Report values larger than 100 terabytes + (thanks to @adrien1018) +* Widen ST_UID (UID) column to allow for UIDs > 9999 + (thanks to DLange) +* BUGFIX: fix makefiles for building with clang + (thanks to Jorge Pereira) +* BUGFIX: fix major() usage + (thanks to @wataash and Kang-Che Sung) +* BUGFIX: fix the STARTTIME column on FreeBSD + (thanks to Rob Crowston) +* BUGFIX: truncate overwide jail names on FreeBSD + (thanks to Rob Crowston) +* BUGFIX: fix reported memory values on FreeBSD + (thanks to Tobias Kortkamp) +* BUGFIX: fix reported CPU meter values on OpenBSD + (thanks to @motet-a) +* BUGFIX: correctly identify other types of zombie process + (thanks to @joder) +* BUGFIX: improve follow-process handling in some situations + (thanks to @wangqr) +* BUGFIX: fix custom meters reverting to unexpected setting + (thanks to @wangqr) +* BUGFIX: close pipe after running lsof(1) + (thanks to Jesin) +* BUGFIX: meters honour setting of counting CPUs from 0/1 + (thanks to @rnsanchez) + What's new in version 2.2.0 * Solaris/Illumos/OpenIndiana support @@ -158,7 +244,7 @@ What's new in version 1.0.2 What's new in version 1.0.1 * Move .htoprc to XDG-compliant path ~/.config/htop/htoprc, - respecting $XDG_CONFIG_HOME + respecting $XDG_CONFIG_HOME (thanks to Hadzhimurad Ustarkhan for the suggestion.) * Safer behavior on the kill screen, to make it harder to kill the wrong process. * Fix for building in FreeBSD 8.2 @@ -546,7 +632,7 @@ What's new in version 0.3.1 What's new in version 0.3 -* BUGFIX: no dirt left on screen on horizontal scrolling +* BUGFIX: no dirt left on screen on horizontal scrolling * Signal selection on "kill" command * Color-coding for users, nice and process status * "Follow" function diff --git a/CheckItem.c b/CheckItem.c index b7ba6fec6..5fcae96bd 100644 --- a/CheckItem.c +++ b/CheckItem.c @@ -1,28 +1,18 @@ /* htop - CheckItem.c (C) 2004-2011 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ #include "CheckItem.h" -#include "CRT.h" - #include #include -/*{ -#include "Object.h" - -typedef struct CheckItem_ { - Object super; - char* text; - bool* ref; - bool value; -} CheckItem; +#include "CRT.h" +#include "RichString.h" -}*/ static void CheckItem_delete(Object* cast) { CheckItem* this = (CheckItem*)cast; @@ -32,19 +22,20 @@ static void CheckItem_delete(Object* cast) { free(this); } -static void CheckItem_display(Object* cast, RichString* out) { - CheckItem* this = (CheckItem*)cast; +static void CheckItem_display(const Object* cast, RichString* out) { + const CheckItem* this = (const CheckItem*)cast; assert (this != NULL); RichString_write(out, CRT_colors[CHECK_BOX], "["); - if (CheckItem_get(this)) + if (CheckItem_get(this)) { RichString_append(out, CRT_colors[CHECK_MARK], "x"); - else + } else { RichString_append(out, CRT_colors[CHECK_MARK], " "); + } RichString_append(out, CRT_colors[CHECK_BOX], "] "); RichString_append(out, CRT_colors[CHECK_TEXT], this->text); } -ObjectClass CheckItem_class = { +const ObjectClass CheckItem_class = { .display = CheckItem_display, .delete = CheckItem_delete }; @@ -66,15 +57,17 @@ CheckItem* CheckItem_newByVal(char* text, bool value) { } void CheckItem_set(CheckItem* this, bool value) { - if (this->ref) + if (this->ref) { *(this->ref) = value; - else + } else { this->value = value; + } } -bool CheckItem_get(CheckItem* this) { - if (this->ref) +bool CheckItem_get(const CheckItem* this) { + if (this->ref) { return *(this->ref); - else + } else { return this->value; + } } diff --git a/CheckItem.h b/CheckItem.h index 5847d4b2e..a357111f7 100644 --- a/CheckItem.h +++ b/CheckItem.h @@ -1,14 +1,14 @@ -/* Do not edit this file. It was automatically generated. */ - #ifndef HEADER_CheckItem #define HEADER_CheckItem /* htop - CheckItem.h (C) 2004-2011 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ +#include + #include "Object.h" typedef struct CheckItem_ { @@ -18,8 +18,7 @@ typedef struct CheckItem_ { bool value; } CheckItem; - -extern ObjectClass CheckItem_class; +extern const ObjectClass CheckItem_class; CheckItem* CheckItem_newByRef(char* text, bool* ref); @@ -27,6 +26,6 @@ CheckItem* CheckItem_newByVal(char* text, bool value); void CheckItem_set(CheckItem* this, bool value); -bool CheckItem_get(CheckItem* this); +bool CheckItem_get(const CheckItem* this); #endif diff --git a/ClockMeter.c b/ClockMeter.c index 0af886269..3cc9dd032 100644 --- a/ClockMeter.c +++ b/ClockMeter.c @@ -1,33 +1,33 @@ /* htop - ClockMeter.c (C) 2004-2011 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ -#include "ClockMeter.h" +#include "config.h" // IWYU pragma: keep -#include "CRT.h" +#include "ClockMeter.h" #include -/*{ -#include "Meter.h" -}*/ +#include "CRT.h" +#include "Object.h" + -int ClockMeter_attributes[] = { +static const int ClockMeter_attributes[] = { CLOCK }; static void ClockMeter_updateValues(Meter* this, char* buffer, int size) { time_t t = time(NULL); struct tm result; - struct tm *lt = localtime_r(&t, &result); + struct tm* lt = localtime_r(&t, &result); this->values[0] = lt->tm_hour * 60 + lt->tm_min; strftime(buffer, size, "%H:%M:%S", lt); } -MeterClass ClockMeter_class = { +const MeterClass ClockMeter_class = { .super = { .extends = Class(Meter), .delete = Meter_delete diff --git a/ClockMeter.h b/ClockMeter.h index 3e0aef538..ecd4b6a93 100644 --- a/ClockMeter.h +++ b/ClockMeter.h @@ -1,18 +1,14 @@ -/* Do not edit this file. It was automatically generated. */ - #ifndef HEADER_ClockMeter #define HEADER_ClockMeter /* htop - ClockMeter.h (C) 2004-2011 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ #include "Meter.h" -extern int ClockMeter_attributes[]; - -extern MeterClass ClockMeter_class; +extern const MeterClass ClockMeter_class; #endif diff --git a/ColorsPanel.c b/ColorsPanel.c index 2028335f9..9da71545b 100644 --- a/ColorsPanel.c +++ b/ColorsPanel.c @@ -1,18 +1,25 @@ /* htop - ColorsPanel.c (C) 2004-2011 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ #include "ColorsPanel.h" -#include "CRT.h" +#include +#include + #include "CheckItem.h" +#include "CRT.h" +#include "FunctionBar.h" +#include "Header.h" +#include "Object.h" +#include "ProvideCurses.h" +#include "RichString.h" +#include "Vector.h" +#include "XUtils.h" -#include -#include -#include // TO ADD A NEW SCHEME: // * Increment the size of bool check in ColorsPanel.h @@ -20,19 +27,6 @@ in the source distribution for its full text. // * Add a define in CRT.h that matches the order of the array // * Add the colors in CRT_setColors -/*{ -#include "Panel.h" -#include "Settings.h" -#include "ScreenManager.h" - -typedef struct ColorsPanel_ { - Panel super; - - Settings* settings; - ScreenManager* scr; -} ColorsPanel; - -}*/ static const char* const ColorsFunctions[] = {" ", " ", " ", " ", " ", " ", " ", " ", " ", "Done ", NULL}; @@ -56,7 +50,7 @@ static void ColorsPanel_delete(Object* object) { static HandlerResult ColorsPanel_eventHandler(Panel* super, int ch) { ColorsPanel* this = (ColorsPanel*) super; - + HandlerResult result = IGNORED; int mark = Panel_getSelectedIndex(super); @@ -70,6 +64,7 @@ static HandlerResult ColorsPanel_eventHandler(Panel* super, int ch) { for (int i = 0; ColorSchemeNames[i] != NULL; i++) CheckItem_set((CheckItem*)Panel_get(super, i), false); CheckItem_set((CheckItem*)Panel_get(super, mark), true); + this->settings->colorScheme = mark; result = HANDLED; } @@ -81,6 +76,7 @@ static HandlerResult ColorsPanel_eventHandler(Panel* super, int ch) { clear(); Panel* menu = (Panel*) Vector_get(this->scr->panels, 0); Header_draw(header); + FunctionBar_draw(super->currentBar); RichString_setAttr(&(super->header), CRT_colors[PANEL_HEADER_FOCUS]); RichString_setAttr(&(menu->header), CRT_colors[PANEL_HEADER_UNFOCUS]); ScreenManager_resize(this->scr, this->scr->x1, header->height, this->scr->x2, this->scr->y2); @@ -88,7 +84,7 @@ static HandlerResult ColorsPanel_eventHandler(Panel* super, int ch) { return result; } -PanelClass ColorsPanel_class = { +const PanelClass ColorsPanel_class = { .super = { .extends = Class(Panel), .delete = ColorsPanel_delete diff --git a/ColorsPanel.h b/ColorsPanel.h index ee3111e07..f63ca3563 100644 --- a/ColorsPanel.h +++ b/ColorsPanel.h @@ -1,23 +1,15 @@ -/* Do not edit this file. It was automatically generated. */ - #ifndef HEADER_ColorsPanel #define HEADER_ColorsPanel /* htop - ColorsPanel.h (C) 2004-2011 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ -// TO ADD A NEW SCHEME: -// * Increment the size of bool check in ColorsPanel.h -// * Add the entry in the ColorSchemeNames array below in the file -// * Add a define in CRT.h that matches the order of the array -// * Add the colors in CRT_setColors - #include "Panel.h" -#include "Settings.h" #include "ScreenManager.h" +#include "Settings.h" typedef struct ColorsPanel_ { Panel super; @@ -26,8 +18,7 @@ typedef struct ColorsPanel_ { ScreenManager* scr; } ColorsPanel; - -extern PanelClass ColorsPanel_class; +extern const PanelClass ColorsPanel_class; ColorsPanel* ColorsPanel_new(Settings* settings, ScreenManager* scr); diff --git a/ColumnsPanel.c b/ColumnsPanel.c index 8974ffdc3..ffd4d0bbe 100644 --- a/ColumnsPanel.c +++ b/ColumnsPanel.c @@ -1,33 +1,24 @@ /* htop - ColumnsPanel.c (C) 2004-2011 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ #include "ColumnsPanel.h" -#include "Platform.h" -#include "StringUtils.h" -#include "ListItem.h" -#include "CRT.h" - -#include -#include #include +#include -/*{ -#include "Panel.h" -#include "Settings.h" - -typedef struct ColumnsPanel_ { - Panel super; - - Settings* settings; - bool moving; -} ColumnsPanel; +#include "CRT.h" +#include "FunctionBar.h" +#include "ListItem.h" +#include "Object.h" +#include "Platform.h" +#include "Process.h" +#include "ProvideCurses.h" +#include "XUtils.h" -}*/ static const char* const ColumnsFunctions[] = {" ", " ", " ", " ", " ", " ", "MoveUp", "MoveDn", "Remove", "Done ", NULL}; @@ -40,7 +31,7 @@ static void ColumnsPanel_delete(Object* object) { static HandlerResult ColumnsPanel_eventHandler(Panel* super, int ch) { ColumnsPanel* const this = (ColumnsPanel*) super; - + int selected = Panel_getSelectedIndex(super); HandlerResult result = IGNORED; int size = Panel_size(super); @@ -55,7 +46,9 @@ static HandlerResult ColumnsPanel_eventHandler(Panel* super, int ch) { if (selected < size - 1) { this->moving = !(this->moving); Panel_setSelectionColor(super, this->moving ? CRT_colors[PANEL_SELECTION_FOLLOW] : CRT_colors[PANEL_SELECTION_FOCUS]); - ((ListItem*)Panel_getSelected(super))->moving = this->moving; + ListItem* selectedItem = (ListItem*) Panel_getSelected(super); + if (selectedItem) + selectedItem->moving = this->moving; result = HANDLED; } break; @@ -87,7 +80,7 @@ static HandlerResult ColumnsPanel_eventHandler(Panel* super, int ch) { case ']': case '+': { - if (selected < size - 2) + if (selected < size - 2) Panel_moveSelectedDown(super); result = HANDLED; break; @@ -103,7 +96,7 @@ static HandlerResult ColumnsPanel_eventHandler(Panel* super, int ch) { } default: { - if (ch < 255 && isalpha(ch)) + if (0 < ch && ch < 255 && isalpha((unsigned char)ch)) result = Panel_selectByTyping(super, ch); if (result == BREAK_LOOP) result = IGNORED; @@ -115,7 +108,7 @@ static HandlerResult ColumnsPanel_eventHandler(Panel* super, int ch) { return result; } -PanelClass ColumnsPanel_class = { +const PanelClass ColumnsPanel_class = { .super = { .extends = Class(Panel), .delete = ColumnsPanel_delete @@ -142,20 +135,11 @@ ColumnsPanel* ColumnsPanel_new(Settings* settings) { return this; } -int ColumnsPanel_fieldNameToIndex(const char* name) { - for (int j = 1; j <= Platform_numberOfFields; j++) { - if (String_eq(name, Process_fields[j].name)) { - return j; - } - } - return -1; -} - void ColumnsPanel_update(Panel* super) { ColumnsPanel* this = (ColumnsPanel*) super; int size = Panel_size(super); this->settings->changed = true; - this->settings->fields = xRealloc(this->settings->fields, sizeof(ProcessField) * (size+1)); + this->settings->fields = xRealloc(this->settings->fields, sizeof(ProcessField) * (size + 1)); this->settings->flags = 0; for (int i = 0; i < size; i++) { int key = ((ListItem*) Panel_get(super, i))->key; @@ -164,4 +148,3 @@ void ColumnsPanel_update(Panel* super) { } this->settings->fields[size] = 0; } - diff --git a/ColumnsPanel.h b/ColumnsPanel.h index 0da674a87..173e039bf 100644 --- a/ColumnsPanel.h +++ b/ColumnsPanel.h @@ -1,14 +1,14 @@ -/* Do not edit this file. It was automatically generated. */ - #ifndef HEADER_ColumnsPanel #define HEADER_ColumnsPanel /* htop - ColumnsPanel.h (C) 2004-2011 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ +#include + #include "Panel.h" #include "Settings.h" @@ -19,14 +19,10 @@ typedef struct ColumnsPanel_ { bool moving; } ColumnsPanel; - -extern PanelClass ColumnsPanel_class; +extern const PanelClass ColumnsPanel_class; ColumnsPanel* ColumnsPanel_new(Settings* settings); -int ColumnsPanel_fieldNameToIndex(const char* name); - void ColumnsPanel_update(Panel* super); - #endif diff --git a/CommandScreen.c b/CommandScreen.c new file mode 100644 index 000000000..578b3ae1a --- /dev/null +++ b/CommandScreen.c @@ -0,0 +1,68 @@ +#include "config.h" // IWYU pragma: keep + +#include "CommandScreen.h" + +#include +#include + +#include "Macros.h" +#include "Panel.h" +#include "ProvideCurses.h" +#include "XUtils.h" + + +static void CommandScreen_scan(InfoScreen* this) { + Panel* panel = this->display; + int idx = MAXIMUM(Panel_getSelectedIndex(panel), 0); + Panel_prune(panel); + + const char* p = this->process->comm; + char* line = xMalloc(COLS + 1); + int line_offset = 0, last_spc = -1, len; + for (; *p != '\0'; p++, line_offset++) { + line[line_offset] = *p; + if (*p == ' ') { + last_spc = line_offset; + } + + if (line_offset == COLS) { + len = (last_spc == -1) ? line_offset : last_spc; + line[len] = '\0'; + InfoScreen_addLine(this, line); + + line_offset -= len; + last_spc = -1; + memcpy(line, p - line_offset, line_offset + 1); + } + } + + if (line_offset > 0) { + line[line_offset] = '\0'; + InfoScreen_addLine(this, line); + } + + free(line); + Panel_setSelected(panel, idx); +} + +static void CommandScreen_draw(InfoScreen* this) { + InfoScreen_drawTitled(this, "Command of process %d - %s", this->process->pid, this->process->comm); +} + +const InfoScreenClass CommandScreen_class = { + .super = { + .extends = Class(Object), + .delete = CommandScreen_delete + }, + .scan = CommandScreen_scan, + .draw = CommandScreen_draw +}; + +CommandScreen* CommandScreen_new(Process* process) { + CommandScreen* this = AllocThis(CommandScreen); + return (CommandScreen*) InfoScreen_init(&this->super, process, NULL, LINES - 3, " "); +} + +void CommandScreen_delete(Object* this) { + free(InfoScreen_done((InfoScreen*)this)); +} diff --git a/CommandScreen.h b/CommandScreen.h new file mode 100644 index 000000000..e56982b2e --- /dev/null +++ b/CommandScreen.h @@ -0,0 +1,19 @@ +#ifndef HEADER_CommandScreen +#define HEADER_CommandScreen + +#include "InfoScreen.h" +#include "Object.h" +#include "Process.h" + + +typedef struct CommandScreen_ { + InfoScreen super; +} CommandScreen; + +extern const InfoScreenClass CommandScreen_class; + +CommandScreen* CommandScreen_new(Process* process); + +void CommandScreen_delete(Object* this); + +#endif diff --git a/Compat.c b/Compat.c new file mode 100644 index 000000000..6401f696a --- /dev/null +++ b/Compat.c @@ -0,0 +1,68 @@ +/* +htop - Compat.c +(C) 2020 Christian Göttsche +Released under the GNU GPLv2, see the COPYING file +in the source distribution for its full text. +*/ + +#include "config.h" // IWYU pragma: keep + +#include +#include +#include +#include + +#include "Compat.h" +#include "XUtils.h" + + +int Compat_fstatat(int dirfd, + const char* dirpath, + const char* pathname, + struct stat* statbuf, + int flags) { + +#ifdef HAVE_FSTATAT + + (void)dirpath; + + return fstatat(dirfd, pathname, statbuf, flags); + +#else + + (void)dirfd; + + char path[4096]; + xSnprintf(path, sizeof(path), "%s/%s", dirpath, pathname); + + if (flags & AT_SYMLINK_NOFOLLOW) + return lstat(path, statbuf); + + return stat(path, statbuf); + +#endif +} + +int Compat_readlinkat(int dirfd, + const char* dirpath, + const char* pathname, + char* buf, + size_t bufsize) { + +#ifdef HAVE_READLINKAT + + (void)dirpath; + + return readlinkat(dirfd, pathname, buf, bufsize); + +#else + + (void)dirfd; + + char path[4096]; + xSnprintf(path, sizeof(path), "%s/%s", dirpath, pathname); + + return readlink(path, buf, bufsize); + +#endif +} diff --git a/Compat.h b/Compat.h new file mode 100644 index 000000000..c0085d5ce --- /dev/null +++ b/Compat.h @@ -0,0 +1,26 @@ +#ifndef HEADER_Compat +#define HEADER_Compat +/* +htop - Compat.h +(C) 2020 Christian Göttsche +Released under the GNU GPLv2, see the COPYING file +in the source distribution for its full text. +*/ + +#include +#include + + +int Compat_fstatat(int dirfd, + const char* dirpath, + const char* pathname, + struct stat* statbuf, + int flags); + +int Compat_readlinkat(int dirfd, + const char* dirpath, + const char* pathname, + char* buf, + size_t bufsize); + +#endif /* HEADER_Compat */ diff --git a/DateMeter.c b/DateMeter.c new file mode 100644 index 000000000..bfe0cbf19 --- /dev/null +++ b/DateMeter.c @@ -0,0 +1,50 @@ +/* +htop - DateMeter.c +(C) 2004-2020 Hisham H. Muhammad, Michael Schönitzer +Released under the GNU GPL, see the COPYING file +in the source distribution for its full text. +*/ + +#include "config.h" // IWYU pragma: keep + +#include "DateMeter.h" + +#include + +#include "CRT.h" +#include "Object.h" + + +static const int DateMeter_attributes[] = { + DATE +}; + +static void DateMeter_updateValues(Meter* this, char* buffer, int size) { + time_t t = time(NULL); + struct tm result; + struct tm* lt = localtime_r(&t, &result); + this->values[0] = lt->tm_yday; + int year = lt->tm_year + 1900; + if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)) { + this->total = 366; + } + else { + this->total = 365; + } + strftime(buffer, size, "%F", lt); +} + +const MeterClass DateMeter_class = { + .super = { + .extends = Class(Meter), + .delete = Meter_delete + }, + .updateValues = DateMeter_updateValues, + .defaultMode = TEXT_METERMODE, + .maxItems = 1, + .total = 365, + .attributes = DateMeter_attributes, + .name = "Date", + .uiName = "Date", + .caption = "Date: ", +}; diff --git a/DateMeter.h b/DateMeter.h new file mode 100644 index 000000000..634557674 --- /dev/null +++ b/DateMeter.h @@ -0,0 +1,14 @@ +#ifndef HEADER_DateMeter +#define HEADER_DateMeter +/* +htop - DateMeter.h +(C) 2004-2011 Hisham H. Muhammad +Released under the GNU GPL, see the COPYING file +in the source distribution for its full text. +*/ + +#include "Meter.h" + +extern const MeterClass DateMeter_class; + +#endif diff --git a/DateTimeMeter.c b/DateTimeMeter.c new file mode 100644 index 000000000..ad5e81ea4 --- /dev/null +++ b/DateTimeMeter.c @@ -0,0 +1,50 @@ +/* +htop - DateTimeMeter.c +(C) 2004-2020 Hisham H. Muhammad, Michael Schönitzer +Released under the GNU GPL, see the COPYING file +in the source distribution for its full text. +*/ + +#include "config.h" // IWYU pragma: keep + +#include "DateTimeMeter.h" + +#include + +#include "CRT.h" +#include "Object.h" + + +static const int DateTimeMeter_attributes[] = { + DATETIME +}; + +static void DateTimeMeter_updateValues(Meter* this, char* buffer, int size) { + time_t t = time(NULL); + struct tm result; + struct tm* lt = localtime_r(&t, &result); + int year = lt->tm_year + 1900; + if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)) { + this->total = 366; + } + else { + this->total = 365; + } + this->values[0] = lt->tm_yday; + strftime(buffer, size, "%F %H:%M:%S", lt); +} + +const MeterClass DateTimeMeter_class = { + .super = { + .extends = Class(Meter), + .delete = Meter_delete + }, + .updateValues = DateTimeMeter_updateValues, + .defaultMode = TEXT_METERMODE, + .maxItems = 1, + .total = 365, + .attributes = DateTimeMeter_attributes, + .name = "DateTime", + .uiName = "Date and Time", + .caption = "Date & Time: ", +}; diff --git a/DateTimeMeter.h b/DateTimeMeter.h new file mode 100644 index 000000000..6cb73c24f --- /dev/null +++ b/DateTimeMeter.h @@ -0,0 +1,14 @@ +#ifndef HEADER_DateTimeMeter +#define HEADER_DateTimeMeter +/* +htop - DateTimeMeter.h +(C) 2004-2011 Hisham H. Muhammad +Released under the GNU GPL, see the COPYING file +in the source distribution for its full text. +*/ + +#include "Meter.h" + +extern const MeterClass DateTimeMeter_class; + +#endif diff --git a/DiskIOMeter.c b/DiskIOMeter.c new file mode 100644 index 000000000..e2d025247 --- /dev/null +++ b/DiskIOMeter.c @@ -0,0 +1,122 @@ +/* +htop - DiskIOMeter.c +(C) 2020 Christian Göttsche +Released under the GNU GPLv2, see the COPYING file +in the source distribution for its full text. +*/ + +#include "DiskIOMeter.h" + +#include +#include + +#include "CRT.h" +#include "Macros.h" +#include "Object.h" +#include "Platform.h" +#include "RichString.h" +#include "XUtils.h" + + +static const int DiskIOMeter_attributes[] = { + METER_VALUE_NOTICE, + METER_VALUE_IOREAD, + METER_VALUE_IOWRITE, +}; + +static bool hasData = false; +static unsigned long int cached_read_diff = 0; +static unsigned long int cached_write_diff = 0; +static double cached_utilisation_diff = 0.0; + +static void DiskIOMeter_updateValues(Meter* this, char* buffer, int len) { + static unsigned long int cached_read_total = 0; + static unsigned long int cached_write_total = 0; + static unsigned long int cached_msTimeSpend_total = 0; + static unsigned long long int cached_last_update = 0; + + struct timeval tv; + gettimeofday(&tv, NULL); + unsigned long long int timeInMilliSeconds = (unsigned long long int)tv.tv_sec * 1000 + (unsigned long long int)tv.tv_usec / 1000; + unsigned long long int passedTimeInMs = timeInMilliSeconds - cached_last_update; + + /* update only every 500ms */ + if (passedTimeInMs > 500) { + cached_last_update = timeInMilliSeconds; + + DiskIOData data; + + hasData = Platform_getDiskIO(&data); + if (!hasData) { + this->values[0] = 0; + xSnprintf(buffer, len, "no data"); + return; + } + + if (data.totalBytesRead > cached_read_total) { + cached_read_diff = (data.totalBytesRead - cached_read_total) / 1024; /* Meter_humanUnit() expects unit in kilo */ + } else { + cached_read_diff = 0; + } + cached_read_total = data.totalBytesRead; + + if (data.totalBytesWritten > cached_write_total) { + cached_write_diff = (data.totalBytesWritten - cached_write_total) / 1024; /* Meter_humanUnit() expects unit in kilo */ + } else { + cached_write_diff = 0; + } + cached_write_total = data.totalBytesWritten; + + if (data.totalMsTimeSpend > cached_msTimeSpend_total) { + cached_utilisation_diff = 100 * (double)(data.totalMsTimeSpend - cached_msTimeSpend_total) / passedTimeInMs; + } else { + cached_utilisation_diff = 0.0; + } + cached_msTimeSpend_total = data.totalMsTimeSpend; + } + + this->values[0] = cached_utilisation_diff; + this->total = MAXIMUM(this->values[0], 100.0); /* fix total after (initial) spike */ + + char bufferRead[12], bufferWrite[12]; + Meter_humanUnit(bufferRead, cached_read_diff, sizeof(bufferRead)); + Meter_humanUnit(bufferWrite, cached_write_diff, sizeof(bufferWrite)); + snprintf(buffer, len, "%sB %sB %.1f%%", bufferRead, bufferWrite, cached_utilisation_diff); +} + +static void DIskIOMeter_display(ATTR_UNUSED const Object* cast, RichString* out) { + if (!hasData) { + RichString_write(out, CRT_colors[METER_VALUE_ERROR], "no data"); + return; + } + + char buffer[16]; + + int color = cached_utilisation_diff > 40.0 ? METER_VALUE_NOTICE : METER_VALUE; + xSnprintf(buffer, sizeof(buffer), "%.1f%%", cached_utilisation_diff); + RichString_write(out, CRT_colors[color], buffer); + + RichString_append(out, CRT_colors[METER_TEXT], " read: "); + Meter_humanUnit(buffer, cached_read_diff, sizeof(buffer)); + RichString_append(out, CRT_colors[METER_VALUE_IOREAD], buffer); + + RichString_append(out, CRT_colors[METER_TEXT], " write: "); + Meter_humanUnit(buffer, cached_write_diff, sizeof(buffer)); + RichString_append(out, CRT_colors[METER_VALUE_IOWRITE], buffer); +} + +const MeterClass DiskIOMeter_class = { + .super = { + .extends = Class(Meter), + .delete = Meter_delete, + .display = DIskIOMeter_display + }, + .updateValues = DiskIOMeter_updateValues, + .defaultMode = TEXT_METERMODE, + .maxItems = 1, + .total = 100.0, + .attributes = DiskIOMeter_attributes, + .name = "DiskIO", + .uiName = "Disk IO", + .caption = "Disk IO: " +}; diff --git a/DiskIOMeter.h b/DiskIOMeter.h new file mode 100644 index 000000000..9fca35b1c --- /dev/null +++ b/DiskIOMeter.h @@ -0,0 +1,20 @@ +#ifndef HEADER_DiskIOMeter +#define HEADER_DiskIOMeter +/* + h top - DiskIOMeter*.h +(C) 2020 Christian Göttsche +Released under the GNU GPLv2, see the COPYING file +in the source distribution for its full text. +*/ + +#include "Meter.h" + +typedef struct DiskIOData_ { + unsigned long int totalBytesRead; + unsigned long int totalBytesWritten; + unsigned long int totalMsTimeSpend; +} DiskIOData; + +extern const MeterClass DiskIOMeter_class; + +#endif /* HEADER_DiskIOMeter */ diff --git a/DisplayOptionsPanel.c b/DisplayOptionsPanel.c index 0ff54e331..e539906c0 100644 --- a/DisplayOptionsPanel.c +++ b/DisplayOptionsPanel.c @@ -1,32 +1,25 @@ /* htop - DisplayOptionsPanel.c (C) 2004-2011 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ -#include "DisplayOptionsPanel.h" +#include "config.h" // IWYU pragma: keep -#include "CheckItem.h" -#include "CRT.h" +#include "DisplayOptionsPanel.h" -#include +#include #include -#include - -/*{ -#include "Panel.h" -#include "Settings.h" -#include "ScreenManager.h" -typedef struct DisplayOptionsPanel_ { - Panel super; - - Settings* settings; - ScreenManager* scr; -} DisplayOptionsPanel; +#include "CheckItem.h" +#include "CRT.h" +#include "FunctionBar.h" +#include "Header.h" +#include "Object.h" +#include "ProvideCurses.h" +#include "XUtils.h" -}*/ static const char* const DisplayOptionsFunctions[] = {" ", " ", " ", " ", " ", " ", " ", " ", " ", "Done ", NULL}; @@ -39,7 +32,7 @@ static void DisplayOptionsPanel_delete(Object* object) { static HandlerResult DisplayOptionsPanel_eventHandler(Panel* super, int ch) { DisplayOptionsPanel* this = (DisplayOptionsPanel*) super; - + HandlerResult result = IGNORED; CheckItem* selected = (CheckItem*) Panel_getSelected(super); @@ -56,16 +49,16 @@ static HandlerResult DisplayOptionsPanel_eventHandler(Panel* super, int ch) { if (result == HANDLED) { this->settings->changed = true; - const Header* header = this->scr->header; - Header_calculateHeight((Header*) header); - Header_reinit((Header*) header); + Header* header = this->scr->header; + Header_calculateHeight(header); + Header_reinit(header); Header_draw(header); ScreenManager_resize(this->scr, this->scr->x1, header->height, this->scr->x2, this->scr->y2); } return result; } -PanelClass DisplayOptionsPanel_class = { +const PanelClass DisplayOptionsPanel_class = { .super = { .extends = Class(Panel), .delete = DisplayOptionsPanel_delete @@ -94,8 +87,15 @@ DisplayOptionsPanel* DisplayOptionsPanel_new(Settings* settings, ScreenManager* Panel_add(super, (Object*) CheckItem_newByRef(xStrdup("Highlight large numbers in memory counters"), &(settings->highlightMegabytes))); Panel_add(super, (Object*) CheckItem_newByRef(xStrdup("Leave a margin around header"), &(settings->headerMargin))); Panel_add(super, (Object*) CheckItem_newByRef(xStrdup("Detailed CPU time (System/IO-Wait/Hard-IRQ/Soft-IRQ/Steal/Guest)"), &(settings->detailedCPUTime))); - Panel_add(super, (Object*) CheckItem_newByRef(xStrdup("Count CPUs from 0 instead of 1"), &(settings->countCPUsFromZero))); + Panel_add(super, (Object*) CheckItem_newByRef(xStrdup("Count CPUs from 1 instead of 0"), &(settings->countCPUsFromOne))); Panel_add(super, (Object*) CheckItem_newByRef(xStrdup("Update process names on every refresh"), &(settings->updateProcessNames))); Panel_add(super, (Object*) CheckItem_newByRef(xStrdup("Add guest time in CPU meter percentage"), &(settings->accountGuestInCPUMeter))); + Panel_add(super, (Object*) CheckItem_newByRef(xStrdup("Also show CPU percentage numerically"), &(settings->showCPUUsage))); + Panel_add(super, (Object*) CheckItem_newByRef(xStrdup("Also show CPU frequency"), &(settings->showCPUFrequency))); + Panel_add(super, (Object*) CheckItem_newByRef(xStrdup("Enable the mouse"), &(settings->enableMouse))); + Panel_add(super, (Object*) CheckItem_newByRef(xStrdup("Highlight new and old processes"), &(settings->highlightChanges))); + #ifdef HAVE_LIBHWLOC + Panel_add(super, (Object*) CheckItem_newByRef(xStrdup("Show topology when selecting affinity by default"), &(settings->topologyAffinity))); + #endif return this; } diff --git a/DisplayOptionsPanel.h b/DisplayOptionsPanel.h index 2a7509ae8..02b67a087 100644 --- a/DisplayOptionsPanel.h +++ b/DisplayOptionsPanel.h @@ -1,17 +1,15 @@ -/* Do not edit this file. It was automatically generated. */ - #ifndef HEADER_DisplayOptionsPanel #define HEADER_DisplayOptionsPanel /* htop - DisplayOptionsPanel.h (C) 2004-2011 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ #include "Panel.h" -#include "Settings.h" #include "ScreenManager.h" +#include "Settings.h" typedef struct DisplayOptionsPanel_ { Panel super; @@ -20,8 +18,7 @@ typedef struct DisplayOptionsPanel_ { ScreenManager* scr; } DisplayOptionsPanel; - -extern PanelClass DisplayOptionsPanel_class; +extern const PanelClass DisplayOptionsPanel_class; DisplayOptionsPanel* DisplayOptionsPanel_new(Settings* settings, ScreenManager* scr); diff --git a/EnvScreen.c b/EnvScreen.c index 855023a47..30faaaba1 100644 --- a/EnvScreen.c +++ b/EnvScreen.c @@ -1,25 +1,20 @@ -#include "EnvScreen.h" +#include "config.h" // IWYU pragma: keep -#include "config.h" -#include "CRT.h" -#include "IncSet.h" -#include "ListItem.h" -#include "Platform.h" -#include "StringUtils.h" +#include "EnvScreen.h" #include #include -#include -/*{ -#include "InfoScreen.h" +#include "CRT.h" +#include "Macros.h" +#include "Panel.h" +#include "Platform.h" +#include "ProvideCurses.h" +#include "Vector.h" +#include "XUtils.h" -typedef struct EnvScreen_ { - InfoScreen super; -} EnvScreen; -}*/ -InfoScreenClass EnvScreen_class = { +const InfoScreenClass EnvScreen_class = { .super = { .extends = Class(Object), .delete = EnvScreen_delete @@ -31,7 +26,7 @@ InfoScreenClass EnvScreen_class = { EnvScreen* EnvScreen_new(Process* process) { EnvScreen* this = xMalloc(sizeof(EnvScreen)); Object_setClass(this, Class(EnvScreen)); - return (EnvScreen*) InfoScreen_init(&this->super, process, NULL, LINES-3, " "); + return (EnvScreen*) InfoScreen_init(&this->super, process, NULL, LINES - 3, " "); } void EnvScreen_delete(Object* this) { @@ -44,7 +39,7 @@ void EnvScreen_draw(InfoScreen* this) { void EnvScreen_scan(InfoScreen* this) { Panel* panel = this->display; - int idx = MAX(Panel_getSelectedIndex(panel), 0); + int idx = MAXIMUM(Panel_getSelectedIndex(panel), 0); Panel_prune(panel); @@ -52,7 +47,7 @@ void EnvScreen_scan(InfoScreen* this) { char* env = Platform_getProcessEnv(this->process->pid); CRT_restorePrivileges(); if (env) { - for (char *p = env; *p; p = strrchr(p, 0)+1) + for (char* p = env; *p; p = strrchr(p, 0) + 1) InfoScreen_addLine(this, p); free(env); } diff --git a/EnvScreen.h b/EnvScreen.h index 7cdbb8652..bf385801d 100644 --- a/EnvScreen.h +++ b/EnvScreen.h @@ -1,15 +1,15 @@ -/* Do not edit this file. It was automatically generated. */ - #ifndef HEADER_EnvScreen #define HEADER_EnvScreen #include "InfoScreen.h" +#include "Object.h" +#include "Process.h" typedef struct EnvScreen_ { InfoScreen super; } EnvScreen; -extern InfoScreenClass EnvScreen_class; +extern const InfoScreenClass EnvScreen_class; EnvScreen* EnvScreen_new(Process* process); diff --git a/FunctionBar.c b/FunctionBar.c index 4e4baaf3b..627bc777a 100644 --- a/FunctionBar.c +++ b/FunctionBar.c @@ -1,32 +1,22 @@ /* htop - FunctionBar.c (C) 2004-2011 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ +#include "config.h" // IWYU pragma: keep + #include "FunctionBar.h" -#include "CRT.h" -#include "RichString.h" -#include "XAlloc.h" -#include -#include #include +#include -/*{ - -#include - -typedef struct FunctionBar_ { - int size; - char** functions; - char** keys; - int* events; - bool staticData; -} FunctionBar; +#include "CRT.h" +#include "Macros.h" +#include "ProvideCurses.h" +#include "XUtils.h" -}*/ static const char* const FunctionBar_FKeys[] = {"F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10", NULL}; @@ -37,6 +27,8 @@ static int FunctionBar_FEvents[] = {KEY_F(1), KEY_F(2), KEY_F(3), KEY_F(4), KEY_ static const char* const FunctionBar_EnterEscKeys[] = {"Enter", "Esc", NULL}; static const int FunctionBar_EnterEscEvents[] = {13, 27}; +static int currentLen = 0; + FunctionBar* FunctionBar_newEnterEsc(const char* enter, const char* esc) { const char* functions[] = {enter, esc, NULL}; return FunctionBar_new(functions, FunctionBar_EnterEscKeys, FunctionBar_EnterEscEvents); @@ -52,21 +44,21 @@ FunctionBar* FunctionBar_new(const char* const* functions, const char* const* ke this->functions[i] = xStrdup(functions[i]); } if (keys && events) { - this->staticData = false; - this->keys = xCalloc(15, sizeof(char*)); + this->staticData = false; + this->keys.keys = xCalloc(15, sizeof(char*)); this->events = xCalloc(15, sizeof(int)); int i = 0; while (i < 15 && functions[i]) { - this->keys[i] = xStrdup(keys[i]); + this->keys.keys[i] = xStrdup(keys[i]); this->events[i] = events[i]; i++; } this->size = i; } else { this->staticData = true; - this->keys = (char**) FunctionBar_FKeys; + this->keys.constKeys = FunctionBar_FKeys; this->events = FunctionBar_FEvents; - this->size = 10; + this->size = ARRAYSIZE(FunctionBar_FEvents); } return this; } @@ -78,9 +70,9 @@ void FunctionBar_delete(FunctionBar* this) { free(this->functions); if (!this->staticData) { for (int i = 0; i < this->size; i++) { - free(this->keys[i]); + free(this->keys.keys[i]); } - free(this->keys); + free(this->keys.keys); free(this->events); } free(this); @@ -96,37 +88,60 @@ void FunctionBar_setLabel(FunctionBar* this, int event, const char* text) { } } -void FunctionBar_draw(const FunctionBar* this, char* buffer) { - FunctionBar_drawAttr(this, buffer, CRT_colors[FUNCTION_BAR]); +void FunctionBar_draw(const FunctionBar* this) { + FunctionBar_drawExtra(this, NULL, -1, false); } -void FunctionBar_drawAttr(const FunctionBar* this, char* buffer, int attr) { +void FunctionBar_drawExtra(const FunctionBar* this, const char* buffer, int attr, bool setCursor) { attrset(CRT_colors[FUNCTION_BAR]); - mvhline(LINES-1, 0, ' ', COLS); + mvhline(LINES - 1, 0, ' ', COLS); int x = 0; for (int i = 0; i < this->size; i++) { attrset(CRT_colors[FUNCTION_KEY]); - mvaddstr(LINES-1, x, this->keys[i]); - x += strlen(this->keys[i]); + mvaddstr(LINES - 1, x, this->keys.constKeys[i]); + x += strlen(this->keys.constKeys[i]); attrset(CRT_colors[FUNCTION_BAR]); - mvaddstr(LINES-1, x, this->functions[i]); + mvaddstr(LINES - 1, x, this->functions[i]); x += strlen(this->functions[i]); } + if (buffer) { - attrset(attr); - mvaddstr(LINES-1, x, buffer); - CRT_cursorX = x + strlen(buffer); + if (attr == -1) { + attrset(CRT_colors[FUNCTION_BAR]); + } else { + attrset(attr); + } + mvaddstr(LINES - 1, x, buffer); + attrset(CRT_colors[RESET_COLOR]); + x += strlen(buffer); + } + + if (setCursor) { + CRT_cursorX = x; curs_set(1); } else { curs_set(0); } + + currentLen = x; +} + +void FunctionBar_append(const char* buffer, int attr) { + if (attr == -1) { + attrset(CRT_colors[FUNCTION_BAR]); + } else { + attrset(attr); + } + mvaddstr(LINES - 1, currentLen, buffer); attrset(CRT_colors[RESET_COLOR]); + + currentLen += strlen(buffer); } int FunctionBar_synthesizeEvent(const FunctionBar* this, int pos) { int x = 0; for (int i = 0; i < this->size; i++) { - x += strlen(this->keys[i]); + x += strlen(this->keys.constKeys[i]); x += strlen(this->functions[i]); if (pos < x) { return this->events[i]; diff --git a/FunctionBar.h b/FunctionBar.h index b60f6582a..925e323bb 100644 --- a/FunctionBar.h +++ b/FunctionBar.h @@ -1,27 +1,25 @@ -/* Do not edit this file. It was automatically generated. */ - #ifndef HEADER_FunctionBar #define HEADER_FunctionBar /* htop - FunctionBar.h (C) 2004-2011 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ - #include typedef struct FunctionBar_ { int size; char** functions; - char** keys; + union { + char** keys; + const char* const* constKeys; + } keys; int* events; bool staticData; } FunctionBar; - - FunctionBar* FunctionBar_newEnterEsc(const char* enter, const char* esc); FunctionBar* FunctionBar_new(const char* const* functions, const char* const* keys, const int* events); @@ -30,9 +28,11 @@ void FunctionBar_delete(FunctionBar* this); void FunctionBar_setLabel(FunctionBar* this, int event, const char* text); -void FunctionBar_draw(const FunctionBar* this, char* buffer); +void FunctionBar_draw(const FunctionBar* this); + +void FunctionBar_drawExtra(const FunctionBar* this, const char* buffer, int attr, bool setCursor); -void FunctionBar_drawAttr(const FunctionBar* this, char* buffer, int attr); +void FunctionBar_append(const char* buffer, int attr); int FunctionBar_synthesizeEvent(const FunctionBar* this, int pos); diff --git a/Hashtable.c b/Hashtable.c index b3eac8daa..cdfb4ec3b 100644 --- a/Hashtable.c +++ b/Hashtable.c @@ -1,172 +1,291 @@ /* htop - Hashtable.c (C) 2004-2011 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ #include "Hashtable.h" -#include "XAlloc.h" +#include "XUtils.h" -#include #include +#include +#include -/*{ -#include -typedef struct Hashtable_ Hashtable; +#ifndef NDEBUG -typedef void(*Hashtable_PairFunction)(int, void*, void*); +static void Hashtable_dump(const Hashtable* this) { + fprintf(stderr, "Hashtable %p: size=%u items=%u owner=%s\n", + (const void*)this, + this->size, + this->items, + this->owner ? "yes" : "no"); -typedef struct HashtableItem { - unsigned int key; - void* value; - struct HashtableItem* next; -} HashtableItem; + unsigned int items = 0; + for (unsigned int i = 0; i < this->size; i++) { + fprintf(stderr, " item %5u: key = %5u probe = %2u value = %p\n", + i, + this->buckets[i].key, + this->buckets[i].probe, + this->buckets[i].value ? (const void*)this->buckets[i].value : "(nil)"); -struct Hashtable_ { - int size; - HashtableItem** buckets; - int items; - bool owner; -}; -}*/ + if (this->buckets[i].value) + items++; + } -#ifdef DEBUG + fprintf(stderr, "Hashtable %p: items=%u counted=%u\n", + (const void*)this, + this->items, + items); +} -static bool Hashtable_isConsistent(Hashtable* this) { - int items = 0; - for (int i = 0; i < this->size; i++) { - HashtableItem* bucket = this->buckets[i]; - while (bucket) { +static bool Hashtable_isConsistent(const Hashtable* this) { + unsigned int items = 0; + for (unsigned int i = 0; i < this->size; i++) { + if (this->buckets[i].value) items++; - bucket = bucket->next; - } } - return items == this->items; + bool res = items == this->items; + if (!res) + Hashtable_dump(this); + return res; } -int Hashtable_count(Hashtable* this) { - int items = 0; - for (int i = 0; i < this->size; i++) { - HashtableItem* bucket = this->buckets[i]; - while (bucket) { +unsigned int Hashtable_count(const Hashtable* this) { + unsigned int items = 0; + for (unsigned int i = 0; i < this->size; i++) { + if (this->buckets[i].value) items++; - bucket = bucket->next; - } } assert(items == this->items); return items; } -#endif +#endif /* NDEBUG */ -static HashtableItem* HashtableItem_new(unsigned int key, void* value) { - HashtableItem* this; - - this = xMalloc(sizeof(HashtableItem)); - this->key = key; - this->value = value; - this->next = NULL; - return this; +/* https://oeis.org/A014234 */ +static const uint64_t OEISprimes[] = { + 2, 3, 7, 13, 31, 61, 127, 251, 509, 1021, 2039, 4093, 8191, + 16381, 32749, 65521, 131071, 262139, 524287, 1048573, + 2097143, 4194301, 8388593, 16777213, 33554393, + 67108859, 134217689, 268435399, 536870909, 1073741789, + 2147483647, 4294967291, 8589934583, 17179869143, + 34359738337, 68719476731, 137438953447 +}; + +static uint64_t nextPrime(unsigned int n) { + assert(n <= OEISprimes[ARRAYSIZE(OEISprimes) - 1]); + + for (unsigned int i = 0; i < ARRAYSIZE(OEISprimes); i++) { + if (n <= OEISprimes[i]) + return OEISprimes[i]; + } + + return OEISprimes[ARRAYSIZE(OEISprimes) - 1]; } -Hashtable* Hashtable_new(int size, bool owner) { +Hashtable* Hashtable_new(unsigned int size, bool owner) { Hashtable* this; - + this = xMalloc(sizeof(Hashtable)); this->items = 0; - this->size = size; - this->buckets = (HashtableItem**) xCalloc(size, sizeof(HashtableItem*)); + this->size = size ? nextPrime(size) : 13; + this->buckets = (HashtableItem*) xCalloc(this->size, sizeof(HashtableItem)); this->owner = owner; assert(Hashtable_isConsistent(this)); return this; } void Hashtable_delete(Hashtable* this) { + assert(Hashtable_isConsistent(this)); - for (int i = 0; i < this->size; i++) { - HashtableItem* walk = this->buckets[i]; - while (walk != NULL) { - if (this->owner) - free(walk->value); - HashtableItem* savedWalk = walk; - walk = savedWalk->next; - free(savedWalk); - } + + if (this->owner) { + for (unsigned int i = 0; i < this->size; i++) + free(this->buckets[i].value); } + free(this->buckets); free(this); } -void Hashtable_put(Hashtable* this, unsigned int key, void* value) { +static void insert(Hashtable* this, hkey_t key, void* value) { unsigned int index = key % this->size; - HashtableItem** bucketPtr = &(this->buckets[index]); - while (true) - if (*bucketPtr == NULL) { - *bucketPtr = HashtableItem_new(key, value); + unsigned int probe = 0; +#ifndef NDEBUG + unsigned int origIndex = index; +#endif + + for (;;) { + if (!this->buckets[index].value) { this->items++; - break; - } else if ((*bucketPtr)->key == key) { - if (this->owner) - free((*bucketPtr)->value); - (*bucketPtr)->value = value; - break; - } else - bucketPtr = &((*bucketPtr)->next); + this->buckets[index].key = key; + this->buckets[index].probe = probe; + this->buckets[index].value = value; + return; + } + + if (this->buckets[index].key == key) { + if (this->owner && this->buckets[index].value != value) + free(this->buckets[index].value); + this->buckets[index].value = value; + return; + } + + /* Robin Hood swap */ + if (probe > this->buckets[index].probe) { + HashtableItem tmp = this->buckets[index]; + + this->buckets[index].key = key; + this->buckets[index].probe = probe; + this->buckets[index].value = value; + + key = tmp.key; + probe = tmp.probe; + value = tmp.value; + } + + index = (index + 1) % this->size; + probe++; + + assert(index != origIndex); + } +} + +void Hashtable_setSize(Hashtable* this, unsigned int size) { + + assert(Hashtable_isConsistent(this)); + + if (size <= this->items) + return; + + HashtableItem* oldBuckets = this->buckets; + unsigned int oldSize = this->size; + + this->size = nextPrime(size); + this->buckets = (HashtableItem*) xCalloc(this->size, sizeof(HashtableItem)); + this->items = 0; + + /* rehash */ + for (unsigned int i = 0; i < oldSize; i++) { + if (!oldBuckets[i].value) + continue; + + insert(this, oldBuckets[i].key, oldBuckets[i].value); + } + + free(oldBuckets); + + assert(Hashtable_isConsistent(this)); +} + +void Hashtable_put(Hashtable* this, hkey_t key, void* value) { + + assert(Hashtable_isConsistent(this)); + assert(this->size > 0); + assert(value); + + /* grow on load-factor > 0.7 */ + if (10 * this->items > 7 * this->size) + Hashtable_setSize(this, 2 * this->size); + + insert(this, key, value); + assert(Hashtable_isConsistent(this)); + assert(Hashtable_get(this, key) != NULL); + assert(this->size > this->items); } -void* Hashtable_remove(Hashtable* this, unsigned int key) { +void* Hashtable_remove(Hashtable* this, hkey_t key) { unsigned int index = key % this->size; - + unsigned int probe = 0; +#ifndef NDEBUG + unsigned int origIndex = index; +#endif + assert(Hashtable_isConsistent(this)); - HashtableItem** bucket; - for (bucket = &(this->buckets[index]); *bucket; bucket = &((*bucket)->next) ) { - if ((*bucket)->key == key) { - void* value = (*bucket)->value; - HashtableItem* next = (*bucket)->next; - free(*bucket); - (*bucket) = next; - this->items--; + void* res = NULL; + + while (this->buckets[index].value) { + if (this->buckets[index].key == key) { if (this->owner) { - free(value); - assert(Hashtable_isConsistent(this)); - return NULL; + free(this->buckets[index].value); } else { - assert(Hashtable_isConsistent(this)); - return value; + res = this->buckets[index].value; } + + unsigned int next = (index + 1) % this->size; + + while (this->buckets[next].value && this->buckets[next].probe > 0) { + this->buckets[index] = this->buckets[next]; + this->buckets[index].probe -= 1; + + index = next; + next = (index + 1) % this->size; + } + + /* set empty after backward shifting */ + this->buckets[index].value = NULL; + this->items--; + + break; } + + if (this->buckets[index].probe < probe) + break; + + index = (index + 1) % this->size; + probe++; + + assert(index != origIndex); } + assert(Hashtable_isConsistent(this)); - return NULL; + assert(Hashtable_get(this, key) == NULL); + + /* shrink on load-factor < 0.125 */ + if (8 * this->items < this->size) + Hashtable_setSize(this, this->size / 2); + + return res; } -inline void* Hashtable_get(Hashtable* this, unsigned int key) { +void* Hashtable_get(Hashtable* this, hkey_t key) { unsigned int index = key % this->size; - HashtableItem* bucketPtr = this->buckets[index]; - while (true) { - if (bucketPtr == NULL) { - assert(Hashtable_isConsistent(this)); - return NULL; - } else if (bucketPtr->key == key) { - assert(Hashtable_isConsistent(this)); - return bucketPtr->value; - } else - bucketPtr = bucketPtr->next; + unsigned int probe = 0; + void* res = NULL; +#ifndef NDEBUG + unsigned int origIndex = index; +#endif + + assert(Hashtable_isConsistent(this)); + + while (this->buckets[index].value) { + if (this->buckets[index].key == key) { + res = this->buckets[index].value; + break; + } + + if (this->buckets[index].probe < probe) + break; + + index = (index + 1) != this->size ? (index + 1) : 0; + probe++; + + assert(index != origIndex); } + + return res; } void Hashtable_foreach(Hashtable* this, Hashtable_PairFunction f, void* userData) { assert(Hashtable_isConsistent(this)); - for (int i = 0; i < this->size; i++) { - HashtableItem* walk = this->buckets[i]; - while (walk != NULL) { + for (unsigned int i = 0; i < this->size; i++) { + HashtableItem* walk = &this->buckets[i]; + if (walk->value) f(walk->key, walk->value, userData); - walk = walk->next; - } } assert(Hashtable_isConsistent(this)); } diff --git a/Hashtable.h b/Hashtable.h index 25608961c..f7d1aae24 100644 --- a/Hashtable.h +++ b/Hashtable.h @@ -1,48 +1,49 @@ -/* Do not edit this file. It was automatically generated. */ - #ifndef HEADER_Hashtable #define HEADER_Hashtable /* htop - Hashtable.h (C) 2004-2011 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ #include -typedef struct Hashtable_ Hashtable; -typedef void(*Hashtable_PairFunction)(int, void*, void*); +typedef unsigned int hkey_t; + +typedef void(*Hashtable_PairFunction)(hkey_t key, void* value, void* userdata); -typedef struct HashtableItem { - unsigned int key; +typedef struct HashtableItem_ { + hkey_t key; + unsigned int probe; void* value; - struct HashtableItem* next; } HashtableItem; -struct Hashtable_ { - int size; - HashtableItem** buckets; - int items; +typedef struct Hashtable_ { + unsigned int size; + HashtableItem* buckets; + unsigned int items; bool owner; -}; +} Hashtable; -#ifdef DEBUG +#ifndef NDEBUG -int Hashtable_count(Hashtable* this); +unsigned int Hashtable_count(const Hashtable* this); -#endif +#endif /* NDEBUG */ -Hashtable* Hashtable_new(int size, bool owner); +Hashtable* Hashtable_new(unsigned int size, bool owner); void Hashtable_delete(Hashtable* this); -void Hashtable_put(Hashtable* this, unsigned int key, void* value); +void Hashtable_setSize(Hashtable* this, unsigned int size); + +void Hashtable_put(Hashtable* this, hkey_t key, void* value); -void* Hashtable_remove(Hashtable* this, unsigned int key); +void* Hashtable_remove(Hashtable* this, hkey_t key); -extern void* Hashtable_get(Hashtable* this, unsigned int key); +void* Hashtable_get(Hashtable* this, hkey_t key); void Hashtable_foreach(Hashtable* this, Hashtable_PairFunction f, void* userData); diff --git a/Header.c b/Header.c index e048ee556..0b522f54d 100644 --- a/Header.c +++ b/Header.c @@ -1,44 +1,24 @@ /* htop - Header.c (C) 2004-2011 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ #include "Header.h" -#include "CRT.h" -#include "StringUtils.h" -#include "Platform.h" - -#include -#include -#include +#include +#include #include +#include -/*{ -#include "Meter.h" -#include "Settings.h" -#include "Vector.h" - -typedef struct Header_ { - Vector** columns; - Settings* settings; - struct ProcessList_* pl; - int nrColumns; - int pad; - int height; -} Header; - -}*/ - -#ifndef MAX -#define MAX(a,b) ((a)>(b)?(a):(b)) -#endif +#include "CRT.h" +#include "Macros.h" +#include "Object.h" +#include "Platform.h" +#include "ProvideCurses.h" +#include "XUtils.h" -#ifndef Header_forEachColumn -#define Header_forEachColumn(this_, i_) for (int (i_)=0; (i_) < (this_)->nrColumns; ++(i_)) -#endif Header* Header_new(struct ProcessList_* pl, Settings* settings, int nrColumns) { Header* this = xCalloc(1, sizeof(Header)); @@ -76,17 +56,17 @@ void Header_populateFromSettings(Header* this) { void Header_writeBackToSettings(const Header* this) { Header_forEachColumn(this, col) { MeterColumnSettings* colSettings = &this->settings->columns[col]; - + String_freeArray(colSettings->names); free(colSettings->modes); - + Vector* vec = this->columns[col]; int len = Vector_size(vec); - - colSettings->names = xCalloc(len+1, sizeof(char*)); + + colSettings->names = xCalloc(len + 1, sizeof(char*)); colSettings->modes = xCalloc(len, sizeof(int)); colSettings->len = len; - + for (int i = 0; i < len; i++) { Meter* meter = (Meter*) Vector_get(vec, i); char* name = xCalloc(64, sizeof(char)); @@ -108,11 +88,12 @@ MeterModeId Header_addMeterByName(Header* this, char* name, int column) { int param = 0; if (paren) { int ok = sscanf(paren, "(%10d)", ¶m); - if (!ok) param = 0; + if (!ok) + param = 0; *paren = '\0'; } MeterModeId mode = TEXT_METERMODE; - for (MeterClass** type = Platform_meterTypes; *type; type++) { + for (const MeterClass* const* type = Platform_meterTypes; *type; type++) { if (String_eq(name, (*type)->name)) { Meter* meter = Meter_new(this->pl, param, *type); Vector_add(meters, meter); @@ -120,6 +101,10 @@ MeterModeId Header_addMeterByName(Header* this, char* name, int column) { break; } } + + if (paren) + *paren = '('; + return mode; } @@ -128,11 +113,12 @@ void Header_setMode(Header* this, int i, MeterModeId mode, int column) { if (i >= Vector_size(meters)) return; + Meter* meter = (Meter*) Vector_get(meters, i); Meter_setMode(meter, mode); } -Meter* Header_addMeterByClass(Header* this, MeterClass* type, int param, int column) { +Meter* Header_addMeterByClass(Header* this, const MeterClass* type, int param, int column) { Vector* meters = this->columns[column]; Meter* meter = Meter_new(this->pl, param, type); @@ -152,7 +138,7 @@ char* Header_readMeterName(Header* this, int i, int column) { int nameLen = strlen(Meter_name(meter)); int len = nameLen + 100; char* name = xMalloc(len); - strncpy(name, Meter_name(meter), nameLen); + memcpy(name, Meter_name(meter), nameLen); name[nameLen] = '\0'; if (meter->param) xSnprintf(name + nameLen, len - nameLen, "(%d)", meter->param); @@ -171,8 +157,9 @@ void Header_reinit(Header* this) { Header_forEachColumn(this, col) { for (int i = 0; i < Vector_size(this->columns[col]); i++) { Meter* meter = (Meter*) Vector_get(this->columns[col], i); - if (Meter_initFn(meter)) + if (Meter_initFn(meter)) { Meter_init(meter); + } } } } @@ -186,7 +173,7 @@ void Header_draw(const Header* this) { } int width = COLS / this->nrColumns - (pad * this->nrColumns - 1) - 1; int x = pad; - + Header_forEachColumn(this, col) { Vector* meters = this->columns[col]; for (int y = (pad / 2), i = 0; i < Vector_size(meters); i++) { @@ -209,7 +196,7 @@ int Header_calculateHeight(Header* this) { Meter* meter = (Meter*) Vector_get(meters, i); height += meter->h; } - maxHeight = MAX(maxHeight, height); + maxHeight = MAXIMUM(maxHeight, height); } this->height = maxHeight; this->pad = pad; diff --git a/Header.h b/Header.h index 700ad354b..f99966c3d 100644 --- a/Header.h +++ b/Header.h @@ -1,15 +1,14 @@ -/* Do not edit this file. It was automatically generated. */ - #ifndef HEADER_Header #define HEADER_Header /* htop - Header.h (C) 2004-2011 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ #include "Meter.h" +#include "ProcessList.h" #include "Settings.h" #include "Vector.h" @@ -22,14 +21,7 @@ typedef struct Header_ { int height; } Header; - -#ifndef MAX -#define MAX(a,b) ((a)>(b)?(a):(b)) -#endif - -#ifndef Header_forEachColumn #define Header_forEachColumn(this_, i_) for (int (i_)=0; (i_) < (this_)->nrColumns; ++(i_)) -#endif Header* Header_new(struct ProcessList_* pl, Settings* settings, int nrColumns); @@ -43,7 +35,7 @@ MeterModeId Header_addMeterByName(Header* this, char* name, int column); void Header_setMode(Header* this, int i, MeterModeId mode, int column); -Meter* Header_addMeterByClass(Header* this, MeterClass* type, int param, int column); +Meter* Header_addMeterByClass(Header* this, const MeterClass* type, int param, int column); int Header_size(Header* this, int column); diff --git a/HostnameMeter.c b/HostnameMeter.c index 4c3b051e4..000bc3fd8 100644 --- a/HostnameMeter.c +++ b/HostnameMeter.c @@ -1,30 +1,30 @@ /* htop - HostnameMeter.c (C) 2004-2011 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ -#include "HostnameMeter.h" +#include "config.h" // IWYU pragma: keep -#include "CRT.h" +#include "HostnameMeter.h" #include -/*{ -#include "Meter.h" -}*/ +#include "CRT.h" +#include "Object.h" + -int HostnameMeter_attributes[] = { +static const int HostnameMeter_attributes[] = { HOSTNAME }; static void HostnameMeter_updateValues(Meter* this, char* buffer, int size) { (void) this; - gethostname(buffer, size-1); + gethostname(buffer, size - 1); } -MeterClass HostnameMeter_class = { +const MeterClass HostnameMeter_class = { .super = { .extends = Class(Meter), .delete = Meter_delete diff --git a/HostnameMeter.h b/HostnameMeter.h index 3697dff85..77fe3da92 100644 --- a/HostnameMeter.h +++ b/HostnameMeter.h @@ -1,18 +1,14 @@ -/* Do not edit this file. It was automatically generated. */ - #ifndef HEADER_HostnameMeter #define HEADER_HostnameMeter /* htop - HostnameMeter.h (C) 2004-2011 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ #include "Meter.h" -extern int HostnameMeter_attributes[]; - -extern MeterClass HostnameMeter_class; +extern const MeterClass HostnameMeter_class; #endif diff --git a/IncSet.c b/IncSet.c index bb9f9544d..d280caf42 100644 --- a/IncSet.c +++ b/IncSet.c @@ -1,57 +1,34 @@ /* htop - IncSet.c (C) 2005-2012 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ +#include "config.h" // IWYU pragma: keep + #include "IncSet.h" -#include "StringUtils.h" -#include "Panel.h" -#include "ListItem.h" -#include "CRT.h" + +#include #include #include -/*{ - -#include "FunctionBar.h" -#include "Panel.h" -#include - -#define INCMODE_MAX 40 - -typedef enum { - INC_SEARCH = 0, - INC_FILTER = 1 -} IncType; - -#define IncSet_filter(inc_) (inc_->filtering ? inc_->modes[INC_FILTER].buffer : NULL) - -typedef struct IncMode_ { - char buffer[INCMODE_MAX+1]; - int index; - FunctionBar* bar; - bool isFilter; -} IncMode; - -typedef struct IncSet_ { - IncMode modes[2]; - IncMode* active; - FunctionBar* defaultBar; - bool filtering; - bool found; -} IncSet; - -typedef const char* (*IncMode_GetPanelValue)(Panel*, int); +#include "CRT.h" +#include "ListItem.h" +#include "Object.h" +#include "ProvideCurses.h" +#include "XUtils.h" -}*/ static void IncMode_reset(IncMode* mode) { mode->index = 0; mode->buffer[0] = 0; } +void IncSet_reset(IncSet* this, IncType type) { + IncMode_reset(&this->modes[type]); +} + static const char* const searchFunctions[] = {"Next ", "Cancel ", " Search: ", NULL}; static const char* const searchKeys[] = {"F3", "Esc", " "}; static int searchEvents[] = {KEY_F(3), 27, ERR}; @@ -102,7 +79,10 @@ static void updateWeakPanel(IncSet* this, Panel* panel, Vector* lines) { ListItem* line = (ListItem*)Vector_get(lines, i); if (String_contains_i(line->value, incFilter)) { Panel_add(panel, (Object*)line); - if (selected == (Object*)line) Panel_setSelected(panel, n); + if (selected == (Object*)line) { + Panel_setSelected(panel, n); + } + n++; } } @@ -110,7 +90,9 @@ static void updateWeakPanel(IncSet* this, Panel* panel, Vector* lines) { for (int i = 0; i < Vector_size(lines); i++) { Object* line = Vector_get(lines, i); Panel_add(panel, line); - if (selected == line) Panel_setSelected(panel, i); + if (selected == line) { + Panel_setSelected(panel, i); + } } } } @@ -125,42 +107,69 @@ static bool search(IncMode* mode, Panel* panel, IncMode_GetPanelValue getPanelVa break; } } - if (found) - FunctionBar_draw(mode->bar, mode->buffer); - else - FunctionBar_drawAttr(mode->bar, mode->buffer, CRT_colors[FAILED_SEARCH]); + + FunctionBar_drawExtra(mode->bar, + mode->buffer, + found ? -1 : CRT_colors[FAILED_SEARCH], + true); return found; } +static bool IncMode_find(IncMode* mode, Panel* panel, IncMode_GetPanelValue getPanelValue, int step) { + int size = Panel_size(panel); + int here = Panel_getSelectedIndex(panel); + int i = here; + for (;;) { + i += step; + if (i == size) { + i = 0; + } + if (i == -1) { + i = size - 1; + } + if (i == here) { + return false; + } + + if (String_contains_i(getPanelValue(panel, i), mode->buffer)) { + Panel_setSelected(panel, i); + return true; + } + } +} + +bool IncSet_next(IncSet* this, IncType type, Panel* panel, IncMode_GetPanelValue getPanelValue) { + return IncMode_find(&this->modes[type], panel, getPanelValue, 1); +} + +bool IncSet_prev(IncSet* this, IncType type, Panel* panel, IncMode_GetPanelValue getPanelValue) { + return IncMode_find(&this->modes[type], panel, getPanelValue, -1); +} + bool IncSet_handleKey(IncSet* this, int ch, Panel* panel, IncMode_GetPanelValue getPanelValue, Vector* lines) { if (ch == ERR) return true; + IncMode* mode = this->active; int size = Panel_size(panel); bool filterChanged = false; bool doSearch = true; if (ch == KEY_F(3)) { - if (size == 0) return true; - int here = Panel_getSelectedIndex(panel); - int i = here; - for(;;) { - i++; - if (i == size) i = 0; - if (i == here) break; - if (String_contains_i(getPanelValue(panel, i), mode->buffer)) { - Panel_setSelected(panel, i); - break; - } - } + if (size == 0) + return true; + + IncMode_find(mode, panel, getPanelValue, 1); doSearch = false; - } else if (ch < 255 && isprint((char)ch)) { + } else if (0 < ch && ch < 255 && isprint((unsigned char)ch)) { if (mode->index < INCMODE_MAX) { mode->buffer[mode->index] = ch; mode->index++; mode->buffer[mode->index] = 0; if (mode->isFilter) { filterChanged = true; - if (mode->index == 1) this->filtering = true; + if (mode->index == 1) { + this->filtering = true; + } } } } else if ((ch == KEY_BACKSPACE || ch == 127)) { @@ -178,7 +187,7 @@ bool IncSet_handleKey(IncSet* this, int ch, Panel* panel, IncMode_GetPanelValue doSearch = false; } } else if (ch == KEY_RESIZE) { - Panel_resize(panel, COLS, LINES-panel->y-1); + Panel_resize(panel, COLS, LINES - panel->y - 1); } else { if (mode->isFilter) { filterChanged = true; @@ -187,11 +196,13 @@ bool IncSet_handleKey(IncSet* this, int ch, Panel* panel, IncMode_GetPanelValue IncMode_reset(mode); } } else { - IncMode_reset(mode); + if (ch == 27) { + IncMode_reset(mode); + } } this->active = NULL; Panel_setDefaultBar(panel); - FunctionBar_draw(this->defaultBar, NULL); + FunctionBar_draw(this->defaultBar); doSearch = false; } if (doSearch) { @@ -205,22 +216,20 @@ bool IncSet_handleKey(IncSet* this, int ch, Panel* panel, IncMode_GetPanelValue const char* IncSet_getListItemValue(Panel* panel, int i) { ListItem* l = (ListItem*) Panel_get(panel, i); - if (l) - return l->value; - return ""; + return l ? l->value : ""; } void IncSet_activate(IncSet* this, IncType type, Panel* panel) { this->active = &(this->modes[type]); - FunctionBar_draw(this->active->bar, this->active->buffer); + FunctionBar_drawExtra(this->active->bar, this->active->buffer, -1, true); panel->currentBar = this->active->bar; } -void IncSet_drawBar(IncSet* this) { +void IncSet_drawBar(const IncSet* this) { if (this->active) { - FunctionBar_draw(this->active->bar, this->active->buffer); + FunctionBar_drawExtra(this->active->bar, this->active->buffer, -1, true); } else { - FunctionBar_draw(this->defaultBar, NULL); + FunctionBar_draw(this->defaultBar); } } diff --git a/IncSet.h b/IncSet.h index 27538f4b8..b07840f7e 100644 --- a/IncSet.h +++ b/IncSet.h @@ -1,18 +1,18 @@ -/* Do not edit this file. It was automatically generated. */ - #ifndef HEADER_IncSet #define HEADER_IncSet /* htop - IncSet.h (C) 2005-2012 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ +#include +#include #include "FunctionBar.h" #include "Panel.h" -#include +#include "Vector.h" #define INCMODE_MAX 40 @@ -21,10 +21,8 @@ typedef enum { INC_FILTER = 1 } IncType; -#define IncSet_filter(inc_) (inc_->filtering ? inc_->modes[INC_FILTER].buffer : NULL) - typedef struct IncMode_ { - char buffer[INCMODE_MAX+1]; + char buffer[INCMODE_MAX + 1]; int index; FunctionBar* bar; bool isFilter; @@ -38,20 +36,29 @@ typedef struct IncSet_ { bool found; } IncSet; +static inline const char* IncSet_filter(const IncSet* this) { + return this->filtering ? this->modes[INC_FILTER].buffer : NULL; +} + typedef const char* (*IncMode_GetPanelValue)(Panel*, int); +void IncSet_reset(IncSet* this, IncType type); IncSet* IncSet_new(FunctionBar* bar); void IncSet_delete(IncSet* this); +bool IncSet_next(IncSet* this, IncType type, Panel* panel, IncMode_GetPanelValue getPanelValue); + +bool IncSet_prev(IncSet* this, IncType type, Panel* panel, IncMode_GetPanelValue getPanelValue); + bool IncSet_handleKey(IncSet* this, int ch, Panel* panel, IncMode_GetPanelValue getPanelValue, Vector* lines); const char* IncSet_getListItemValue(Panel* panel, int i); void IncSet_activate(IncSet* this, IncType type, Panel* panel); -void IncSet_drawBar(IncSet* this); +void IncSet_drawBar(const IncSet* this); int IncSet_synthesizeEvent(IncSet* this, int x); diff --git a/InfoScreen.c b/InfoScreen.c index fab8daeaf..b7cbd4c64 100644 --- a/InfoScreen.c +++ b/InfoScreen.c @@ -1,54 +1,19 @@ -#include "InfoScreen.h" +#include "config.h" // IWYU pragma: keep -#include "config.h" -#include "Object.h" -#include "CRT.h" -#include "IncSet.h" -#include "ListItem.h" -#include "Platform.h" -#include "StringUtils.h" +#include "InfoScreen.h" +#include +#include #include #include -#include -#include -/*{ -#include "Process.h" -#include "Panel.h" -#include "FunctionBar.h" +#include "CRT.h" #include "IncSet.h" +#include "ListItem.h" +#include "Object.h" +#include "ProvideCurses.h" +#include "XUtils.h" -typedef struct InfoScreen_ InfoScreen; - -typedef void(*InfoScreen_Scan)(InfoScreen*); -typedef void(*InfoScreen_Draw)(InfoScreen*); -typedef void(*InfoScreen_OnErr)(InfoScreen*); -typedef bool(*InfoScreen_OnKey)(InfoScreen*, int); - -typedef struct InfoScreenClass_ { - ObjectClass super; - const InfoScreen_Scan scan; - const InfoScreen_Draw draw; - const InfoScreen_OnErr onErr; - const InfoScreen_OnKey onKey; -} InfoScreenClass; - -#define As_InfoScreen(this_) ((InfoScreenClass*)(((InfoScreen*)(this_))->super.klass)) -#define InfoScreen_scan(this_) As_InfoScreen(this_)->scan((InfoScreen*)(this_)) -#define InfoScreen_draw(this_) As_InfoScreen(this_)->draw((InfoScreen*)(this_)) -#define InfoScreen_onErr(this_) As_InfoScreen(this_)->onErr((InfoScreen*)(this_)) -#define InfoScreen_onKey(this_, ch_) As_InfoScreen(this_)->onKey((InfoScreen*)(this_), ch_) - -struct InfoScreen_ { - Object super; - Process* process; - Panel* display; - FunctionBar* bar; - IncSet* inc; - Vector* lines; -}; -}*/ static const char* const InfoScreenFunctions[] = {"Search ", "Filter ", "Refresh", "Done ", NULL}; @@ -56,7 +21,7 @@ static const char* const InfoScreenKeys[] = {"F3", "F4", "F5", "Esc"}; static int InfoScreenEvents[] = {KEY_F(3), KEY_F(4), KEY_F(5), 27}; -InfoScreen* InfoScreen_init(InfoScreen* this, Process* process, FunctionBar* bar, int height, char* panelHeader) { +InfoScreen* InfoScreen_init(InfoScreen* this, const Process* process, FunctionBar* bar, int height, const char* panelHeader) { this->process = process; if (!bar) { bar = FunctionBar_new(InfoScreenFunctions, InfoScreenKeys, InfoScreenEvents); @@ -75,39 +40,50 @@ InfoScreen* InfoScreen_done(InfoScreen* this) { return this; } -void InfoScreen_drawTitled(InfoScreen* this, char* fmt, ...) { +void InfoScreen_drawTitled(InfoScreen* this, const char* fmt, ...) { va_list ap; va_start(ap, fmt); + + char* title = xMalloc(COLS + 1); + int len = vsnprintf(title, COLS + 1, fmt, ap); + if (len > COLS) { + memset(&title[COLS - 3], '.', 3); + } + attrset(CRT_colors[METER_TEXT]); mvhline(0, 0, ' ', COLS); - wmove(stdscr, 0, 0); - vw_printw(stdscr, fmt, ap); + mvwprintw(stdscr, 0, 0, title); attrset(CRT_colors[DEFAULT_COLOR]); this->display->needsRedraw = true; Panel_draw(this->display, true); IncSet_drawBar(this->inc); + free(title); va_end(ap); } void InfoScreen_addLine(InfoScreen* this, const char* line) { Vector_add(this->lines, (Object*) ListItem_new(line, 0)); const char* incFilter = IncSet_filter(this->inc); - if (!incFilter || String_contains_i(line, incFilter)) - Panel_add(this->display, (Object*)Vector_get(this->lines, Vector_size(this->lines)-1)); + if (!incFilter || String_contains_i(line, incFilter)) { + Panel_add(this->display, Vector_get(this->lines, Vector_size(this->lines) - 1)); + } } void InfoScreen_appendLine(InfoScreen* this, const char* line) { - ListItem* last = (ListItem*)Vector_get(this->lines, Vector_size(this->lines)-1); + ListItem* last = (ListItem*)Vector_get(this->lines, Vector_size(this->lines) - 1); ListItem_append(last, line); const char* incFilter = IncSet_filter(this->inc); - if (incFilter && Panel_get(this->display, Panel_size(this->display)-1) != (Object*)last && String_contains_i(line, incFilter)) + if (incFilter && Panel_get(this->display, Panel_size(this->display) - 1) != (Object*)last && String_contains_i(line, incFilter)) { Panel_add(this->display, (Object*)last); + } } void InfoScreen_run(InfoScreen* this) { Panel* panel = this->display; - if (As_InfoScreen(this)->scan) InfoScreen_scan(this); + if (As_InfoScreen(this)->scan) + InfoScreen_scan(this); + InfoScreen_draw(this); bool looping = true; @@ -116,11 +92,11 @@ void InfoScreen_run(InfoScreen* this) { Panel_draw(panel, true); if (this->inc->active) { - (void) move(LINES-1, CRT_cursorX); + (void) move(LINES - 1, CRT_cursorX); } set_escdelay(25); int ch = getch(); - + if (ch == ERR) { if (As_InfoScreen(this)->onErr) { InfoScreen_onErr(this); @@ -131,19 +107,21 @@ void InfoScreen_run(InfoScreen* this) { if (ch == KEY_MOUSE) { MEVENT mevent; int ok = getmouse(&mevent); - if (ok == OK) + if (ok == OK) { if (mevent.y >= panel->y && mevent.y < LINES - 1) { Panel_setSelected(panel, mevent.y - panel->y + panel->scrollV); ch = 0; - } if (mevent.y == LINES - 1) + } else if (mevent.y == LINES - 1) { ch = IncSet_synthesizeEvent(this->inc, mevent.x); + } + } } if (this->inc->active) { IncSet_handleKey(this->inc, ch, panel, IncSet_getListItemValue, this->lines); continue; } - + switch(ch) { case ERR: continue; @@ -157,7 +135,9 @@ void InfoScreen_run(InfoScreen* this) { break; case KEY_F(5): clear(); - if (As_InfoScreen(this)->scan) InfoScreen_scan(this); + if (As_InfoScreen(this)->scan) + InfoScreen_scan(this); + InfoScreen_draw(this); break; case '\014': // Ctrl+L @@ -170,7 +150,10 @@ void InfoScreen_run(InfoScreen* this) { looping = false; break; case KEY_RESIZE: - Panel_resize(panel, COLS, LINES-2); + Panel_resize(panel, COLS, LINES - 2); + if (As_InfoScreen(this)->scan) + InfoScreen_scan(this); + InfoScreen_draw(this); break; default: diff --git a/InfoScreen.h b/InfoScreen.h index 2e1599f90..0d80367d4 100644 --- a/InfoScreen.h +++ b/InfoScreen.h @@ -1,14 +1,25 @@ -/* Do not edit this file. It was automatically generated. */ - #ifndef HEADER_InfoScreen #define HEADER_InfoScreen -#include "Process.h" -#include "Panel.h" +#include + #include "FunctionBar.h" #include "IncSet.h" +#include "Macros.h" +#include "Object.h" +#include "Panel.h" +#include "Process.h" +#include "Vector.h" + -typedef struct InfoScreen_ InfoScreen; +typedef struct InfoScreen_ { + Object super; + const Process* process; + Panel* display; + FunctionBar* bar; + IncSet* inc; + Vector* lines; +} InfoScreen; typedef void(*InfoScreen_Scan)(InfoScreen*); typedef void(*InfoScreen_Draw)(InfoScreen*); @@ -16,33 +27,25 @@ typedef void(*InfoScreen_OnErr)(InfoScreen*); typedef bool(*InfoScreen_OnKey)(InfoScreen*, int); typedef struct InfoScreenClass_ { - ObjectClass super; + const ObjectClass super; const InfoScreen_Scan scan; const InfoScreen_Draw draw; const InfoScreen_OnErr onErr; const InfoScreen_OnKey onKey; } InfoScreenClass; -#define As_InfoScreen(this_) ((InfoScreenClass*)(((InfoScreen*)(this_))->super.klass)) +#define As_InfoScreen(this_) ((const InfoScreenClass*)(((InfoScreen*)(this_))->super.klass)) #define InfoScreen_scan(this_) As_InfoScreen(this_)->scan((InfoScreen*)(this_)) #define InfoScreen_draw(this_) As_InfoScreen(this_)->draw((InfoScreen*)(this_)) #define InfoScreen_onErr(this_) As_InfoScreen(this_)->onErr((InfoScreen*)(this_)) #define InfoScreen_onKey(this_, ch_) As_InfoScreen(this_)->onKey((InfoScreen*)(this_), ch_) -struct InfoScreen_ { - Object super; - Process* process; - Panel* display; - FunctionBar* bar; - IncSet* inc; - Vector* lines; -}; - -InfoScreen* InfoScreen_init(InfoScreen* this, Process* process, FunctionBar* bar, int height, char* panelHeader); +InfoScreen* InfoScreen_init(InfoScreen* this, const Process* process, FunctionBar* bar, int height, const char* panelHeader); InfoScreen* InfoScreen_done(InfoScreen* this); -void InfoScreen_drawTitled(InfoScreen* this, char* fmt, ...); +ATTR_FORMAT(printf, 2, 3) +void InfoScreen_drawTitled(InfoScreen* this, const char* fmt, ...); void InfoScreen_addLine(InfoScreen* this, const char* line); diff --git a/ListItem.c b/ListItem.c index 05c5c0b37..c3c1a7d3a 100644 --- a/ListItem.c +++ b/ListItem.c @@ -1,31 +1,22 @@ /* htop - ListItem.c (C) 2004-2011 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ -#include "ListItem.h" +#include "config.h" // IWYU pragma: keep -#include "CRT.h" -#include "StringUtils.h" -#include "RichString.h" +#include "ListItem.h" -#include #include #include +#include -/*{ -#include "Object.h" - -typedef struct ListItem_ { - Object super; - char* value; - int key; - bool moving; -} ListItem; +#include "CRT.h" +#include "RichString.h" +#include "XUtils.h" -}*/ static void ListItem_delete(Object* cast) { ListItem* this = (ListItem*)cast; @@ -33,32 +24,22 @@ static void ListItem_delete(Object* cast) { free(this); } -static void ListItem_display(Object* cast, RichString* out) { - ListItem* const this = (ListItem*)cast; +static void ListItem_display(const Object* cast, RichString* out) { + const ListItem* const this = (const ListItem*)cast; assert (this != NULL); - /* - int len = strlen(this->value)+1; - char buffer[len+1]; - xSnprintf(buffer, len, "%s", this->value); - */ + if (this->moving) { RichString_write(out, CRT_colors[DEFAULT_COLOR], #ifdef HAVE_LIBNCURSESW - CRT_utf8 ? "↕ " : + CRT_utf8 ? "↕ " : #endif - "+ "); + "+ "); } else { RichString_prune(out); } - RichString_append(out, CRT_colors[DEFAULT_COLOR], this->value/*buffer*/); + RichString_append(out, CRT_colors[DEFAULT_COLOR], this->value); } -ObjectClass ListItem_class = { - .display = ListItem_display, - .delete = ListItem_delete, - .compare = ListItem_compare -}; - ListItem* ListItem_new(const char* value, int key) { ListItem* this = AllocThis(ListItem); this->value = xStrdup(value); @@ -68,21 +49,22 @@ ListItem* ListItem_new(const char* value, int key) { } void ListItem_append(ListItem* this, const char* text) { - int oldLen = strlen(this->value); - int textLen = strlen(text); - int newLen = strlen(this->value) + textLen; + size_t oldLen = strlen(this->value); + size_t textLen = strlen(text); + size_t newLen = oldLen + textLen; this->value = xRealloc(this->value, newLen + 1); memcpy(this->value + oldLen, text, textLen); this->value[newLen] = '\0'; } -const char* ListItem_getRef(ListItem* this) { - return this->value; -} - -long ListItem_compare(const void* cast1, const void* cast2) { - ListItem* obj1 = (ListItem*) cast1; - ListItem* obj2 = (ListItem*) cast2; +static long ListItem_compare(const void* cast1, const void* cast2) { + const ListItem* obj1 = (const ListItem*) cast1; + const ListItem* obj2 = (const ListItem*) cast2; return strcmp(obj1->value, obj2->value); } +const ObjectClass ListItem_class = { + .display = ListItem_display, + .delete = ListItem_delete, + .compare = ListItem_compare +}; diff --git a/ListItem.h b/ListItem.h index b48f0acd3..87a7c073f 100644 --- a/ListItem.h +++ b/ListItem.h @@ -1,14 +1,14 @@ -/* Do not edit this file. It was automatically generated. */ - #ifndef HEADER_ListItem #define HEADER_ListItem /* htop - ListItem.h (C) 2004-2011 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ +#include + #include "Object.h" typedef struct ListItem_ { @@ -18,16 +18,14 @@ typedef struct ListItem_ { bool moving; } ListItem; - -extern ObjectClass ListItem_class; +extern const ObjectClass ListItem_class; ListItem* ListItem_new(const char* value, int key); void ListItem_append(ListItem* this, const char* text); -const char* ListItem_getRef(ListItem* this); - -long ListItem_compare(const void* cast1, const void* cast2); - +static inline const char* ListItem_getRef(const ListItem* this) { + return this->value; +} #endif diff --git a/LoadAverageMeter.c b/LoadAverageMeter.c index e29433f14..76b89ea11 100644 --- a/LoadAverageMeter.c +++ b/LoadAverageMeter.c @@ -1,32 +1,36 @@ /* htop - LoadAverageMeter.c (C) 2004-2011 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ #include "LoadAverageMeter.h" #include "CRT.h" +#include "Object.h" #include "Platform.h" +#include "RichString.h" +#include "XUtils.h" -/*{ -#include "Meter.h" -}*/ -int LoadAverageMeter_attributes[] = { - LOAD_AVERAGE_ONE, LOAD_AVERAGE_FIVE, LOAD_AVERAGE_FIFTEEN +static const int LoadAverageMeter_attributes[] = { + LOAD_AVERAGE_ONE, + LOAD_AVERAGE_FIVE, + LOAD_AVERAGE_FIFTEEN }; -int LoadMeter_attributes[] = { LOAD }; +static const int LoadMeter_attributes[] = { + LOAD +}; static void LoadAverageMeter_updateValues(Meter* this, char* buffer, int size) { Platform_getLoadAverage(&this->values[0], &this->values[1], &this->values[2]); xSnprintf(buffer, size, "%.2f/%.2f/%.2f", this->values[0], this->values[1], this->values[2]); } -static void LoadAverageMeter_display(Object* cast, RichString* out) { - Meter* this = (Meter*)cast; +static void LoadAverageMeter_display(const Object* cast, RichString* out) { + const Meter* this = (const Meter*)cast; char buffer[20]; xSnprintf(buffer, sizeof(buffer), "%.2f ", this->values[0]); RichString_write(out, CRT_colors[LOAD_AVERAGE_ONE], buffer); @@ -45,14 +49,14 @@ static void LoadMeter_updateValues(Meter* this, char* buffer, int size) { xSnprintf(buffer, size, "%.2f", this->values[0]); } -static void LoadMeter_display(Object* cast, RichString* out) { - Meter* this = (Meter*)cast; +static void LoadMeter_display(const Object* cast, RichString* out) { + const Meter* this = (const Meter*)cast; char buffer[20]; - xSnprintf(buffer, sizeof(buffer), "%.2f ", ((Meter*)this)->values[0]); + xSnprintf(buffer, sizeof(buffer), "%.2f ", this->values[0]); RichString_write(out, CRT_colors[LOAD], buffer); } -MeterClass LoadAverageMeter_class = { +const MeterClass LoadAverageMeter_class = { .super = { .extends = Class(Meter), .delete = Meter_delete, @@ -69,7 +73,7 @@ MeterClass LoadAverageMeter_class = { .caption = "Load average: " }; -MeterClass LoadMeter_class = { +const MeterClass LoadMeter_class = { .super = { .extends = Class(Meter), .delete = Meter_delete, diff --git a/LoadAverageMeter.h b/LoadAverageMeter.h index bd18f4d01..776c8bf63 100644 --- a/LoadAverageMeter.h +++ b/LoadAverageMeter.h @@ -1,22 +1,16 @@ -/* Do not edit this file. It was automatically generated. */ - #ifndef HEADER_LoadAverageMeter #define HEADER_LoadAverageMeter /* htop - LoadAverageMeter.h (C) 2004-2011 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ #include "Meter.h" -extern int LoadAverageMeter_attributes[]; - -extern int LoadMeter_attributes[]; - -extern MeterClass LoadAverageMeter_class; +extern const MeterClass LoadAverageMeter_class; -extern MeterClass LoadMeter_class; +extern const MeterClass LoadMeter_class; #endif diff --git a/Macros.h b/Macros.h new file mode 100644 index 000000000..64aaefa5a --- /dev/null +++ b/Macros.h @@ -0,0 +1,62 @@ +#ifndef HEADER_Macros +#define HEADER_Macros + +#include // IWYU pragma: keep + +#ifndef MINIMUM +#define MINIMUM(a, b) ((a) < (b) ? (a) : (b)) +#endif + +#ifndef MAXIMUM +#define MAXIMUM(a, b) ((a) > (b) ? (a) : (b)) +#endif + +#ifndef CLAMP +#define CLAMP(x, low, high) (assert((low) <= (high)), ((x) > (high)) ? (high) : MAXIMUM(x, low)) +#endif + +#ifndef ARRAYSIZE +#define ARRAYSIZE(x) (sizeof(x) / sizeof((x)[0])) +#endif + +#ifndef SPACESHIP_NUMBER +#define SPACESHIP_NUMBER(a, b) (((a) > (b)) - ((a) < (b))) +#endif + +#ifndef SPACESHIP_NULLSTR +#define SPACESHIP_NULLSTR(a, b) strcmp((a) ? (a) : "", (b) ? (b) : "") +#endif + +#ifdef __GNUC__ // defined by GCC and Clang + +#define ATTR_FORMAT(type, index, check) __attribute__((format (type, index, check))) +#define ATTR_NONNULL __attribute__((nonnull)) +#define ATTR_NORETURN __attribute__((noreturn)) +#define ATTR_UNUSED __attribute__((unused)) + +#else /* __GNUC__ */ + +#define ATTR_FORMAT(type, index, check) +#define ATTR_NONNULL +#define ATTR_NORETURN +#define ATTR_UNUSED + +#endif /* __GNUC__ */ + +// ignore casts discarding const specifier, e.g. +// const char [] -> char * / void * +// const char *[2]' -> char *const * +#ifdef __clang__ +#define IGNORE_WCASTQUAL_BEGIN _Pragma("clang diagnostic push") \ + _Pragma("clang diagnostic ignored \"-Wcast-qual\"") +#define IGNORE_WCASTQUAL_END _Pragma("clang diagnostic pop") +#elif defined(__GNUC__) +#define IGNORE_WCASTQUAL_BEGIN _Pragma("GCC diagnostic push") \ + _Pragma("GCC diagnostic ignored \"-Wcast-qual\"") +#define IGNORE_WCASTQUAL_END _Pragma("GCC diagnostic pop") +#else +#define IGNORE_WCASTQUAL_BEGIN +#define IGNORE_WCASTQUAL_END +#endif + +#endif diff --git a/MainPanel.c b/MainPanel.c index 25023367f..5a1fe8f56 100644 --- a/MainPanel.c +++ b/MainPanel.c @@ -1,40 +1,25 @@ /* htop - ColumnsPanel.c (C) 2004-2015 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +(C) 2020 Red Hat, Inc. All Rights Reserved. +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ #include "MainPanel.h" -#include "Process.h" -#include "Platform.h" -#include "CRT.h" +#include #include -/*{ -#include "Panel.h" -#include "Action.h" +#include "CRT.h" +#include "FunctionBar.h" +#include "Platform.h" +#include "Process.h" +#include "ProcessList.h" +#include "ProvideCurses.h" #include "Settings.h" +#include "XUtils.h" -typedef struct MainPanel_ { - Panel super; - State* state; - IncSet* inc; - Htop_Action *keys; - pid_t pidSearch; -} MainPanel; - -typedef union { - int i; - void* v; -} Arg; - -typedef bool(*MainPanel_ForeachProcessFn)(Process*, Arg); - -#define MainPanel_getFunctionBar(this_) (((Panel*)(this_))->defaultBar) - -}*/ static const char* const MainFunctions[] = {"Help ", "Setup ", "Search", "Filter", "Tree ", "SortBy", "Nice -", "Nice +", "Kill ", "Quit ", NULL}; @@ -51,7 +36,7 @@ void MainPanel_updateTreeFunctions(MainPanel* this, bool mode) { void MainPanel_pidSearch(MainPanel* this, int ch) { Panel* super = (Panel*) this; - pid_t pid = ch-48 + this->pidSearch; + pid_t pid = ch - 48 + this->pidSearch; for (int i = 0; i < Panel_size(super); i++) { Process* p = (Process*) Panel_get(super, i); if (p && p->pid == pid) { @@ -69,12 +54,12 @@ static HandlerResult MainPanel_eventHandler(Panel* super, int ch) { MainPanel* this = (MainPanel*) super; HandlerResult result = IGNORED; - + Htop_Reaction reaction = HTOP_OK; if (EVENT_IS_HEADER_CLICK(ch)) { int x = EVENT_HEADER_CLICK_GET_X(ch); - ProcessList* pl = this->state->pl; + const ProcessList* pl = this->state->pl; Settings* settings = this->state->settings; int hx = super->scrollH + x + 1; ProcessField field = ProcessList_keyAt(pl, hx); @@ -84,7 +69,7 @@ static HandlerResult MainPanel_eventHandler(Panel* super, int ch) { } else { reaction |= Action_setSortKey(settings, field); } - reaction |= HTOP_RECALCULATE | HTOP_REDRAW_BAR | HTOP_SAVE_SETTINGS; + reaction |= HTOP_RECALCULATE | HTOP_REDRAW_BAR | HTOP_SAVE_SETTINGS; result = HANDLED; } else if (ch != ERR && this->inc->active) { bool filterChanged = IncSet_handleKey(this->inc, ch, super, (IncMode_GetPanelValue) MainPanel_getValue, NULL); @@ -102,7 +87,7 @@ static HandlerResult MainPanel_eventHandler(Panel* super, int ch) { } else if (ch != ERR && ch > 0 && ch < KEY_MAX && this->keys[ch]) { reaction |= (this->keys[ch])(this->state); result = HANDLED; - } else if (isdigit(ch)) { + } else if (0 < ch && ch < 255 && isdigit((unsigned char)ch)) { MainPanel_pidSearch(this, ch); } else { if (ch != ERR) { @@ -115,13 +100,16 @@ static HandlerResult MainPanel_eventHandler(Panel* super, int ch) { if (reaction & HTOP_REDRAW_BAR) { MainPanel_updateTreeFunctions(this, this->state->settings->treeView); IncSet_drawBar(this->inc); + if (this->state->pauseProcessUpdate) { + FunctionBar_append("PAUSED", CRT_colors[PAUSED]); + } } if (reaction & HTOP_UPDATE_PANELHDR) { ProcessList_printHeader(this->state->pl, Panel_getHeader(super)); } if (reaction & HTOP_REFRESH) { result |= REDRAW; - } + } if (reaction & HTOP_RECALCULATE) { result |= RESCAN; } @@ -148,9 +136,7 @@ int MainPanel_selectedPid(MainPanel* this) { const char* MainPanel_getValue(MainPanel* this, int i) { Process* p = (Process*) Panel_get((Panel*)this, i); - if (p) - return p->comm; - return ""; + return p ? p->comm : ""; } bool MainPanel_foreachProcess(MainPanel* this, MainPanel_ForeachProcessFn fn, Arg arg, bool* wasAnyTagged) { @@ -166,14 +152,18 @@ bool MainPanel_foreachProcess(MainPanel* this, MainPanel_ForeachProcessFn fn, Ar } if (!anyTagged) { Process* p = (Process*) Panel_getSelected(super); - if (p) ok = fn(p, arg) && ok; + if (p) { + ok &= fn(p, arg); + } } + if (wasAnyTagged) *wasAnyTagged = anyTagged; + return ok; } -PanelClass MainPanel_class = { +const PanelClass MainPanel_class = { .super = { .extends = Class(Panel), .delete = MainPanel_delete diff --git a/MainPanel.h b/MainPanel.h index 884965977..03a1affde 100644 --- a/MainPanel.h +++ b/MainPanel.h @@ -1,36 +1,37 @@ -/* Do not edit this file. It was automatically generated. */ - #ifndef HEADER_MainPanel #define HEADER_MainPanel /* htop - ColumnsPanel.h (C) 2004-2015 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +(C) 2020 Red Hat, Inc. All Rights Reserved. +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ -#include "Panel.h" +#include "config.h" // IWYU pragma: keep + +#include +#include + #include "Action.h" -#include "Settings.h" +#include "IncSet.h" +#include "Object.h" +#include "Panel.h" +#include "Process.h" + typedef struct MainPanel_ { Panel super; State* state; IncSet* inc; - Htop_Action *keys; + Htop_Action* keys; pid_t pidSearch; } MainPanel; -typedef union { - int i; - void* v; -} Arg; - typedef bool(*MainPanel_ForeachProcessFn)(Process*, Arg); #define MainPanel_getFunctionBar(this_) (((Panel*)(this_))->defaultBar) - void MainPanel_updateTreeFunctions(MainPanel* this, bool mode); void MainPanel_pidSearch(MainPanel* this, int ch); @@ -41,9 +42,9 @@ const char* MainPanel_getValue(MainPanel* this, int i); bool MainPanel_foreachProcess(MainPanel* this, MainPanel_ForeachProcessFn fn, Arg arg, bool* wasAnyTagged); -extern PanelClass MainPanel_class; +extern const PanelClass MainPanel_class; -MainPanel* MainPanel_new(); +MainPanel* MainPanel_new(void); void MainPanel_setState(MainPanel* this, State* state); diff --git a/Makefile.am b/Makefile.am index 7d19600f6..7b90dfd06 100644 --- a/Makefile.am +++ b/Makefile.am @@ -1,61 +1,157 @@ - -ACLOCAL_AMFLAGS = -I m4 AUTOMAKE_OPTIONS = subdir-objects bin_PROGRAMS = htop dist_man_MANS = htop.1 -EXTRA_DIST = $(dist_man_MANS) htop.desktop htop.png scripts/MakeHeader.py \ +EXTRA_DIST = $(dist_man_MANS) htop.desktop htop.png \ install-sh autogen.sh missing applicationsdir = $(datadir)/applications applications_DATA = htop.desktop pixmapdir = $(datadir)/pixmaps pixmap_DATA = htop.png -AM_CFLAGS = -pedantic -Wall $(wextra_flag) -std=c99 -D_XOPEN_SOURCE_EXTENDED -DSYSCONFDIR=\"$(sysconfdir)\" -I"$(top_srcdir)/$(my_htop_platform)" +AM_CFLAGS += -pedantic -std=c99 -D_XOPEN_SOURCE_EXTENDED -DSYSCONFDIR=\"$(sysconfdir)\" -I"$(top_srcdir)/$(my_htop_platform)" AM_LDFLAGS = -AM_CPPFLAGS = -DNDEBUG - -myhtopsources = AvailableMetersPanel.c CategoriesPanel.c CheckItem.c \ -ClockMeter.c ColorsPanel.c ColumnsPanel.c CPUMeter.c CRT.c MainPanel.c \ -DisplayOptionsPanel.c FunctionBar.c Hashtable.c Header.c htop.c ListItem.c \ -LoadAverageMeter.c MemoryMeter.c Meter.c MetersPanel.c Object.c Panel.c \ -BatteryMeter.c Process.c ProcessList.c RichString.c ScreenManager.c Settings.c \ -SignalsPanel.c StringUtils.c SwapMeter.c TasksMeter.c UptimeMeter.c \ -TraceScreen.c UsersTable.c Vector.c AvailableColumnsPanel.c AffinityPanel.c \ -HostnameMeter.c OpenFilesScreen.c Affinity.c IncSet.c Action.c EnvScreen.c \ -InfoScreen.c XAlloc.c - -myhtopheaders = AvailableColumnsPanel.h AvailableMetersPanel.h \ -CategoriesPanel.h CheckItem.h ClockMeter.h ColorsPanel.h ColumnsPanel.h \ -CPUMeter.h CRT.h MainPanel.h DisplayOptionsPanel.h FunctionBar.h \ -Hashtable.h Header.h htop.h ListItem.h LoadAverageMeter.h MemoryMeter.h \ -BatteryMeter.h Meter.h MetersPanel.h Object.h Panel.h ProcessList.h RichString.h \ -ScreenManager.h Settings.h SignalsPanel.h StringUtils.h SwapMeter.h \ -TasksMeter.h UptimeMeter.h TraceScreen.h UsersTable.h Vector.h Process.h \ -AffinityPanel.h HostnameMeter.h OpenFilesScreen.h Affinity.h IncSet.h Action.h \ -EnvScreen.h InfoScreen.h XAlloc.h - -all_platform_headers = + +myhtopsources = \ + Action.c \ + Affinity.c \ + AffinityPanel.c \ + AvailableColumnsPanel.c \ + AvailableMetersPanel.c \ + BatteryMeter.c \ + CategoriesPanel.c \ + CheckItem.c \ + ClockMeter.c \ + ColorsPanel.c \ + ColumnsPanel.c \ + CommandScreen.c \ + Compat.c \ + CPUMeter.c \ + CRT.c \ + DateMeter.c \ + DateTimeMeter.c \ + DiskIOMeter.c \ + DisplayOptionsPanel.c \ + EnvScreen.c \ + FunctionBar.c \ + Hashtable.c \ + Header.c \ + HostnameMeter.c \ + htop.c \ + IncSet.c \ + InfoScreen.c \ + ListItem.c \ + LoadAverageMeter.c \ + MainPanel.c \ + MemoryMeter.c \ + Meter.c \ + MetersPanel.c \ + NetworkIOMeter.c \ + Object.c \ + OpenFilesScreen.c \ + Panel.c \ + Process.c \ + ProcessList.c \ + ProcessLocksScreen.c \ + RichString.c \ + ScreenManager.c \ + Settings.c \ + SignalsPanel.c \ + SwapMeter.c \ + TasksMeter.c \ + TraceScreen.c \ + UptimeMeter.c \ + UsersTable.c \ + Vector.c \ + XUtils.c + +myhtopheaders = \ + Action.h \ + Affinity.h \ + AffinityPanel.h \ + AvailableColumnsPanel.h \ + AvailableMetersPanel.h \ + BatteryMeter.h \ + CPUMeter.h \ + CRT.h \ + CategoriesPanel.h \ + CheckItem.h \ + ClockMeter.h \ + ColorsPanel.h \ + ColumnsPanel.h \ + CommandScreen.h \ + Compat.h \ + DateMeter.h \ + DateTimeMeter.h \ + DiskIOMeter.h \ + DisplayOptionsPanel.h \ + EnvScreen.h \ + FunctionBar.h \ + Hashtable.h \ + Header.h \ + HostnameMeter.h \ + IncSet.h \ + InfoScreen.h \ + ListItem.h \ + LoadAverageMeter.h \ + Macros.h \ + MainPanel.h \ + MemoryMeter.h \ + Meter.h \ + MetersPanel.h \ + NetworkIOMeter.h \ + Object.h \ + OpenFilesScreen.h \ + Panel.h \ + Process.h \ + ProcessList.h \ + ProcessLocksScreen.h \ + ProvideCurses.h \ + RichString.h \ + ScreenManager.h \ + Settings.h \ + SignalsPanel.h \ + SwapMeter.h \ + TasksMeter.h \ + TraceScreen.h \ + UptimeMeter.h \ + UsersTable.h \ + Vector.h \ + XUtils.h # Linux # ----- linux_platform_headers = \ - linux/Platform.h \ - linux/IOPriorityPanel.h \ linux/IOPriority.h \ + linux/IOPriorityPanel.h \ linux/LinuxProcess.h \ linux/LinuxProcessList.h \ - linux/LinuxCRT.h \ - linux/Battery.h - -all_platform_headers += $(linux_platform_headers) + linux/Platform.h \ + linux/PressureStallMeter.h \ + linux/SELinuxMeter.h \ + linux/SystemdMeter.h \ + linux/ZramMeter.h \ + linux/ZramStats.h \ + zfs/ZfsArcMeter.h \ + zfs/ZfsArcStats.h \ + zfs/ZfsCompressedArcMeter.h if HTOP_LINUX -AM_CFLAGS += -rdynamic -myhtopplatsources = linux/Platform.c linux/IOPriorityPanel.c linux/IOPriority.c \ -linux/LinuxProcess.c linux/LinuxProcessList.c linux/LinuxCRT.c linux/Battery.c +AM_LDFLAGS += -rdynamic +myhtopplatsources = \ + linux/IOPriorityPanel.c \ + linux/LinuxProcess.c \ + linux/LinuxProcessList.c \ + linux/Platform.c \ + linux/PressureStallMeter.c \ + linux/SELinuxMeter.c \ + linux/SystemdMeter.c \ + linux/ZramMeter.c \ + zfs/ZfsArcMeter.c \ + zfs/ZfsArcStats.c \ + zfs/ZfsCompressedArcMeter.c myhtopplatheaders = $(linux_platform_headers) endif @@ -67,14 +163,15 @@ freebsd_platform_headers = \ freebsd/Platform.h \ freebsd/FreeBSDProcessList.h \ freebsd/FreeBSDProcess.h \ - freebsd/FreeBSDCRT.h \ - freebsd/Battery.h - -all_platform_headers += $(freebsd_platform_headers) + zfs/ZfsArcMeter.h \ + zfs/ZfsCompressedArcMeter.h \ + zfs/ZfsArcStats.h \ + zfs/openzfs_sysctl.h if HTOP_FREEBSD myhtopplatsources = freebsd/Platform.c freebsd/FreeBSDProcessList.c \ -freebsd/FreeBSDProcess.c freebsd/FreeBSDCRT.c freebsd/Battery.c +freebsd/FreeBSDProcess.c \ +zfs/ZfsArcMeter.c zfs/ZfsCompressedArcMeter.c zfs/ZfsArcStats.c zfs/openzfs_sysctl.c myhtopplatheaders = $(freebsd_platform_headers) endif @@ -85,16 +182,12 @@ endif dragonflybsd_platform_headers = \ dragonflybsd/Platform.h \ dragonflybsd/DragonFlyBSDProcessList.h \ - dragonflybsd/DragonFlyBSDProcess.h \ - dragonflybsd/DragonFlyBSDCRT.h \ - dragonflybsd/Battery.h - -all_platform_headers += $(dragonflybsd_platform_headers) + dragonflybsd/DragonFlyBSDProcess.h if HTOP_DRAGONFLYBSD -AM_LDFLAGS += -lkvm -lkinfo -lexecinfo +AM_LDFLAGS += -lkvm -lkinfo myhtopplatsources = dragonflybsd/Platform.c dragonflybsd/DragonFlyBSDProcessList.c \ -dragonflybsd/DragonFlyBSDProcess.c dragonflybsd/DragonFlyBSDCRT.c dragonflybsd/Battery.c +dragonflybsd/DragonFlyBSDProcess.c myhtopplatheaders = $(dragonflybsd_platform_headers) endif @@ -105,15 +198,11 @@ endif openbsd_platform_headers = \ openbsd/Platform.h \ openbsd/OpenBSDProcessList.h \ - openbsd/OpenBSDProcess.h \ - openbsd/OpenBSDCRT.h \ - openbsd/Battery.h - -all_platform_headers += $(openbsd_platform_headers) + openbsd/OpenBSDProcess.h if HTOP_OPENBSD myhtopplatsources = openbsd/Platform.c openbsd/OpenBSDProcessList.c \ -openbsd/OpenBSDProcess.c openbsd/OpenBSDCRT.c openbsd/Battery.c +openbsd/OpenBSDProcess.c myhtopplatheaders = $(openbsd_platform_headers) endif @@ -125,15 +214,16 @@ darwin_platform_headers = \ darwin/Platform.h \ darwin/DarwinProcess.h \ darwin/DarwinProcessList.h \ - darwin/DarwinCRT.h \ - darwin/Battery.h - -all_platform_headers += $(darwin_platform_headers) + zfs/ZfsArcMeter.h \ + zfs/ZfsCompressedArcMeter.h \ + zfs/ZfsArcStats.h \ + zfs/openzfs_sysctl.h if HTOP_DARWIN AM_LDFLAGS += -framework IOKit -framework CoreFoundation myhtopplatsources = darwin/Platform.c darwin/DarwinProcess.c \ -darwin/DarwinProcessList.c darwin/DarwinCRT.c darwin/Battery.c +darwin/DarwinProcessList.c +zfs/ZfsArcMeter.c zfs/ZfsCompressedArcMeter.c zfs/ZfsArcStats.c zfs/openzfs_sysctl.c myhtopplatheaders = $(darwin_platform_headers) endif @@ -145,15 +235,14 @@ solaris_platform_headers = \ solaris/Platform.h \ solaris/SolarisProcess.h \ solaris/SolarisProcessList.h \ - solaris/SolarisCRT.h \ - solaris/Battery.h - -all_platform_headers += $(solaris_platform_headers) + zfs/ZfsArcMeter.h \ + zfs/ZfsCompressedArcMeter.h \ + zfs/ZfsArcStats.h if HTOP_SOLARIS myhtopplatsources = solaris/Platform.c \ solaris/SolarisProcess.c solaris/SolarisProcessList.c \ -solaris/SolarisCRT.c solaris/Battery.c +zfs/ZfsArcMeter.c zfs/ZfsCompressedArcMeter.c zfs/ZfsArcStats.c myhtopplatheaders = $(solaris_platform_headers) endif @@ -164,33 +253,19 @@ endif unsupported_platform_headers = \ unsupported/Platform.h \ unsupported/UnsupportedProcess.h \ - unsupported/UnsupportedProcessList.h \ - unsupported/UnsupportedCRT.h \ - unsupported/Battery.h - -all_platform_headers += $(unsupported_platform_headers) + unsupported/UnsupportedProcessList.h if HTOP_UNSUPPORTED myhtopplatsources = unsupported/Platform.c \ -unsupported/UnsupportedProcess.c unsupported/UnsupportedProcessList.c \ -unsupported/UnsupportedCRT.c unsupported/Battery.c +unsupported/UnsupportedProcess.c unsupported/UnsupportedProcessList.c myhtopplatheaders = $(unsupported_platform_headers) endif # ---- -SUFFIXES = .h - -BUILT_SOURCES = $(myhtopheaders) $(myhtopplatheaders) -htop_SOURCES = $(myhtopheaders) $(myhtopplatheaders) $(myhtopsources) $(myhtopplatsources) config.h - -.PHONY: htop-headers clean-htop-headers - -htop-headers: $(myhtopheaders) $(all_platform_headers) - -clean-htop-headers: - -rm -f $(myhtopheaders) $(all_platform_headers) +htop_SOURCES = $(myhtopheaders) $(myhtopplatheaders) $(myhtopsources) $(myhtopplatsources) +nodist_htop_SOURCES = config.h target: echo $(htop_SOURCES) @@ -204,9 +279,6 @@ debug: coverage: $(MAKE) all CFLAGS="" AM_CPPFLAGS="-fprofile-arcs -ftest-coverage -DDEBUG" LDFLAGS="-lgcov" -.c.h: - @srcdir@/scripts/MakeHeader.py $< - cppcheck: cppcheck -q -v . --enable=all -DHAVE_CGROUP -DHAVE_OPENVZ -DHAVE_TASKSTATS diff --git a/MemoryMeter.c b/MemoryMeter.c index fbf5330c9..3d29ddf4d 100644 --- a/MemoryMeter.c +++ b/MemoryMeter.c @@ -1,27 +1,22 @@ /* htop - MemoryMeter.c (C) 2004-2011 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ #include "MemoryMeter.h" #include "CRT.h" +#include "Object.h" #include "Platform.h" +#include "RichString.h" -#include -#include -#include -#include -#include -/*{ -#include "Meter.h" -}*/ - -int MemoryMeter_attributes[] = { - MEMORY_USED, MEMORY_BUFFERS, MEMORY_CACHE +static const int MemoryMeter_attributes[] = { + MEMORY_USED, + MEMORY_BUFFERS, + MEMORY_CACHE }; static void MemoryMeter_updateValues(Meter* this, char* buffer, int size) { @@ -37,9 +32,9 @@ static void MemoryMeter_updateValues(Meter* this, char* buffer, int size) { } } -static void MemoryMeter_display(Object* cast, RichString* out) { +static void MemoryMeter_display(const Object* cast, RichString* out) { char buffer[50]; - Meter* this = (Meter*)cast; + const Meter* this = (const Meter*)cast; RichString_write(out, CRT_colors[METER_TEXT], ":"); Meter_humanUnit(buffer, this->total, 50); RichString_append(out, CRT_colors[METER_VALUE], buffer); @@ -54,13 +49,13 @@ static void MemoryMeter_display(Object* cast, RichString* out) { RichString_append(out, CRT_colors[MEMORY_CACHE], buffer); } -MeterClass MemoryMeter_class = { +const MeterClass MemoryMeter_class = { .super = { .extends = Class(Meter), .delete = Meter_delete, .display = MemoryMeter_display, }, - .updateValues = MemoryMeter_updateValues, + .updateValues = MemoryMeter_updateValues, .defaultMode = BAR_METERMODE, .maxItems = 3, .total = 100.0, diff --git a/MemoryMeter.h b/MemoryMeter.h index 6ddae9233..d299483ae 100644 --- a/MemoryMeter.h +++ b/MemoryMeter.h @@ -1,18 +1,14 @@ -/* Do not edit this file. It was automatically generated. */ - #ifndef HEADER_MemoryMeter #define HEADER_MemoryMeter /* htop - MemoryMeter.h (C) 2004-2011 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ #include "Meter.h" -extern int MemoryMeter_attributes[]; - -extern MeterClass MemoryMeter_class; +extern const MeterClass MemoryMeter_class; #endif diff --git a/Meter.c b/Meter.c index 05a4eb239..cf8ccc52b 100644 --- a/Meter.c +++ b/Meter.c @@ -1,154 +1,59 @@ /* htop - Meter.c (C) 2004-2011 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ -#include "Meter.h" +#include "config.h" // IWYU pragma: keep -#include "RichString.h" -#include "Object.h" -#include "CRT.h" -#include "StringUtils.h" -#include "ListItem.h" -#include "Settings.h" +#include "Meter.h" +#include #include -#include #include -#include -#include -#include +#include +#include -#define METER_BUFFER_LEN 256 +#include "CRT.h" +#include "Macros.h" +#include "Object.h" +#include "ProvideCurses.h" +#include "RichString.h" +#include "XUtils.h" -#define GRAPH_DELAY (DEFAULT_DELAY/2) #define GRAPH_HEIGHT 4 /* Unit: rows (lines) */ -/*{ -#include "ListItem.h" - -#include - -typedef struct Meter_ Meter; - -typedef void(*Meter_Init)(Meter*); -typedef void(*Meter_Done)(Meter*); -typedef void(*Meter_UpdateMode)(Meter*, int); -typedef void(*Meter_UpdateValues)(Meter*, char*, int); -typedef void(*Meter_Draw)(Meter*, int, int, int); - -typedef struct MeterClass_ { - ObjectClass super; - const Meter_Init init; - const Meter_Done done; - const Meter_UpdateMode updateMode; - const Meter_Draw draw; - const Meter_UpdateValues updateValues; - const int defaultMode; - const double total; - const int* attributes; - const char* name; - const char* uiName; - const char* caption; - const char* description; - const char maxItems; - char curItems; -} MeterClass; - -#define As_Meter(this_) ((MeterClass*)((this_)->super.klass)) -#define Meter_initFn(this_) As_Meter(this_)->init -#define Meter_init(this_) As_Meter(this_)->init((Meter*)(this_)) -#define Meter_done(this_) As_Meter(this_)->done((Meter*)(this_)) -#define Meter_updateModeFn(this_) As_Meter(this_)->updateMode -#define Meter_updateMode(this_, m_) As_Meter(this_)->updateMode((Meter*)(this_), m_) -#define Meter_drawFn(this_) As_Meter(this_)->draw -#define Meter_doneFn(this_) As_Meter(this_)->done -#define Meter_updateValues(this_, buf_, sz_) \ - As_Meter(this_)->updateValues((Meter*)(this_), buf_, sz_) -#define Meter_defaultMode(this_) As_Meter(this_)->defaultMode -#define Meter_getItems(this_) As_Meter(this_)->curItems -#define Meter_setItems(this_, n_) As_Meter(this_)->curItems = (n_) -#define Meter_attributes(this_) As_Meter(this_)->attributes -#define Meter_name(this_) As_Meter(this_)->name -#define Meter_uiName(this_) As_Meter(this_)->uiName - -struct Meter_ { - Object super; - Meter_Draw draw; - - char* caption; - int mode; - int param; - void* drawData; - int h; - struct ProcessList_* pl; - double* values; - double total; -}; - -typedef struct MeterMode_ { - Meter_Draw draw; - const char* uiName; - int h; -} MeterMode; - -typedef enum { - CUSTOM_METERMODE = 0, - BAR_METERMODE, - TEXT_METERMODE, - GRAPH_METERMODE, - LED_METERMODE, - LAST_METERMODE -} MeterModeId; - -typedef struct GraphData_ { - struct timeval time; - double values[METER_BUFFER_LEN]; -} GraphData; - -}*/ - -#ifndef MIN -#define MIN(a,b) ((a)<(b)?(a):(b)) -#endif -#ifndef MAX -#define MAX(a,b) ((a)>(b)?(a):(b)) -#endif -#ifndef CLAMP -#define CLAMP(x,low,high) (((x)>(high))?(high):(((x)<(low))?(low):(x))) -#endif - -MeterClass Meter_class = { +const MeterClass Meter_class = { .super = { .extends = Class(Object) } }; -Meter* Meter_new(struct ProcessList_* pl, int param, MeterClass* type) { +Meter* Meter_new(const struct ProcessList_* pl, int param, const MeterClass* type) { Meter* this = xCalloc(1, sizeof(Meter)); Object_setClass(this, type); this->h = 1; this->param = param; this->pl = pl; - type->curItems = type->maxItems; - this->values = xCalloc(type->maxItems, sizeof(double)); + this->curItems = type->maxItems; + this->values = type->maxItems ? xCalloc(type->maxItems, sizeof(double)) : NULL; this->total = type->total; this->caption = xStrdup(type->caption); - if (Meter_initFn(this)) + if (Meter_initFn(this)) { Meter_init(this); + } Meter_setMode(this, type->defaultMode); return this; } int Meter_humanUnit(char* buffer, unsigned long int value, int size) { - const char * prefix = "KMGTPEZY"; + const char* prefix = "KMGTPEZY"; unsigned long int powi = 1; unsigned int written, powj = 1, precision = 2; - for(;;) { + for (;;) { if (value / 1024 < powi) break; @@ -177,6 +82,7 @@ int Meter_humanUnit(char* buffer, unsigned long int value, int size) { void Meter_delete(Object* cast) { if (!cast) return; + Meter* this = (Meter*) cast; if (Meter_doneFn(this)) { Meter_done(this); @@ -192,7 +98,7 @@ void Meter_setCaption(Meter* this, const char* caption) { this->caption = xStrdup(caption); } -static inline void Meter_displayBuffer(Meter* this, char* buffer, RichString* out) { +static inline void Meter_displayBuffer(const Meter* this, const char* buffer, RichString* out) { if (Object_displayFn(this)) { Object_display(this, out); } else { @@ -201,21 +107,26 @@ static inline void Meter_displayBuffer(Meter* this, char* buffer, RichString* ou } void Meter_setMode(Meter* this, int modeIndex) { - if (modeIndex > 0 && modeIndex == this->mode) + if (modeIndex > 0 && modeIndex == this->mode) { return; - if (!modeIndex) + } + + if (!modeIndex) { modeIndex = 1; + } + assert(modeIndex < LAST_METERMODE); if (Meter_defaultMode(this) == CUSTOM_METERMODE) { this->draw = Meter_drawFn(this); - if (Meter_updateModeFn(this)) + if (Meter_updateModeFn(this)) { Meter_updateMode(this, modeIndex); + } } else { assert(modeIndex >= 1); free(this->drawData); this->drawData = NULL; - MeterMode* mode = Meter_modes[modeIndex]; + const MeterMode* mode = Meter_modes[modeIndex]; this->draw = mode->draw; this->h = mode->h; } @@ -224,15 +135,17 @@ void Meter_setMode(Meter* this, int modeIndex) { ListItem* Meter_toListItem(Meter* this, bool moving) { char mode[21]; - if (this->mode) + if (this->mode) { xSnprintf(mode, 20, " [%s]", Meter_modes[this->mode]->uiName); - else + } else { mode[0] = '\0'; + } char number[11]; - if (this->param > 0) + if (this->param > 0) { xSnprintf(number, 10, " %d", this->param); - else + } else { number[0] = '\0'; + } char buffer[51]; xSnprintf(buffer, 50, "%s%s%s", Meter_uiName(this), number, mode); ListItem* li = ListItem_new(buffer, 0); @@ -275,7 +188,7 @@ static void BarMeterMode_draw(Meter* this, int x, int y, int w) { attrset(CRT_colors[BAR_BORDER]); mvaddch(y, x, '['); mvaddch(y, x + w, ']'); - + w--; x++; @@ -284,19 +197,18 @@ static void BarMeterMode_draw(Meter* this, int x, int y, int w) { return; } char bar[w + 1]; - + int blockSizes[10]; xSnprintf(bar, w + 1, "%*.*s", w, w, buffer); // First draw in the bar[] buffer... int offset = 0; - int items = Meter_getItems(this); - for (int i = 0; i < items; i++) { + for (uint8_t i = 0; i < this->curItems; i++) { double value = this->values[i]; value = CLAMP(value, 0.0, this->total); if (value > 0) { - blockSizes[i] = ceil((value/this->total) * w); + blockSizes[i] = ceil((value / this->total) * w); } else { blockSizes[i] = 0; } @@ -316,7 +228,7 @@ static void BarMeterMode_draw(Meter* this, int x, int y, int w) { // ...then print the buffer. offset = 0; - for (int i = 0; i < items; i++) { + for (uint8_t i = 0; i < this->curItems; i++) { attrset(CRT_colors[Meter_attributes(this)[i]]); mvaddnstr(y, x + offset, bar + offset, blockSizes[i]); offset += blockSizes[i]; @@ -358,8 +270,10 @@ static int GraphMeterMode_pixPerRow; static void GraphMeterMode_draw(Meter* this, int x, int y, int w) { - if (!this->drawData) this->drawData = xCalloc(1, sizeof(GraphData)); - GraphData* data = (GraphData*) this->drawData; + if (!this->drawData) { + this->drawData = xCalloc(1, sizeof(GraphData)); + } + GraphData* data = this->drawData; const int nValues = METER_BUFFER_LEN; #ifdef HAVE_LIBNCURSESW @@ -378,36 +292,35 @@ static void GraphMeterMode_draw(Meter* this, int x, int y, int w) { mvaddnstr(y, x, this->caption, captionLen); x += captionLen; w -= captionLen; - + struct timeval now; gettimeofday(&now, NULL); if (!timercmp(&now, &(data->time), <)) { - struct timeval delay = { .tv_sec = (int)(CRT_delay/10), .tv_usec = (CRT_delay-((int)(CRT_delay/10)*10)) * 100000 }; + struct timeval delay = { .tv_sec = CRT_delay / 10, .tv_usec = (CRT_delay - ((CRT_delay / 10) * 10)) * 100000 }; timeradd(&now, &delay, &(data->time)); for (int i = 0; i < nValues - 1; i++) - data->values[i] = data->values[i+1]; - + data->values[i] = data->values[i + 1]; + char buffer[nValues]; Meter_updateValues(this, buffer, nValues - 1); - + double value = 0.0; - int items = Meter_getItems(this); - for (int i = 0; i < items; i++) + for (uint8_t i = 0; i < this->curItems; i++) value += this->values[i]; value /= this->total; data->values[nValues - 1] = value; } - - int i = nValues - (w*2) + 2, k = 0; + + int i = nValues - (w * 2) + 2, k = 0; if (i < 0) { - k = -i/2; + k = -i / 2; i = 0; } - for (; i < nValues - 1; i+=2, k++) { + for (; i < nValues - 1; i += 2, k++) { int pix = GraphMeterMode_pixPerRow * GRAPH_HEIGHT; int v1 = CLAMP((int) lround(data->values[i] * pix), 1, pix); - int v2 = CLAMP((int) lround(data->values[i+1] * pix), 1, pix); + int v2 = CLAMP((int) lround(data->values[i + 1] * pix), 1, pix); int colorIdx = GRAPH_1; for (int line = 0; line < GRAPH_HEIGHT; line++) { @@ -415,7 +328,7 @@ static void GraphMeterMode_draw(Meter* this, int x, int y, int w) { int line2 = CLAMP(v2 - (GraphMeterMode_pixPerRow * (GRAPH_HEIGHT - 1 - line)), 0, GraphMeterMode_pixPerRow); attrset(CRT_colors[colorIdx]); - mvaddstr(y+line, x+k, GraphMeterMode_dots[line1 * (GraphMeterMode_pixPerRow + 1) + line2]); + mvaddstr(y + line, x + k, GraphMeterMode_dots[line1 * (GraphMeterMode_pixPerRow + 1) + line2]); colorIdx = GRAPH_2; } } @@ -425,17 +338,17 @@ static void GraphMeterMode_draw(Meter* this, int x, int y, int w) { /* ---------- LEDMeterMode ---------- */ static const char* const LEDMeterMode_digitsAscii[] = { - " __ "," "," __ "," __ "," "," __ "," __ "," __ "," __ "," __ ", - "| |"," |"," __|"," __|","|__|","|__ ","|__ "," |","|__|","|__|", - "|__|"," |","|__ "," __|"," |"," __|","|__|"," |","|__|"," __|" + " __ ", " ", " __ ", " __ ", " ", " __ ", " __ ", " __ ", " __ ", " __ ", + "| |", " |", " __|", " __|", "|__|", "|__ ", "|__ ", " |", "|__|", "|__|", + "|__|", " |", "|__ ", " __|", " |", " __|", "|__|", " |", "|__|", " __|" }; #ifdef HAVE_LIBNCURSESW static const char* const LEDMeterMode_digitsUtf8[] = { - "┌──┐"," ┐ ","╶──┐","╶──┐","╷ ╷","┌──╴","┌──╴","╶──┐","┌──┐","┌──┐", - "│ │"," │ ","┌──┘"," ──┤","└──┤","└──┐","├──┐"," │","├──┤","└──┤", - "└──┘"," ╵ ","└──╴","╶──┘"," ╵","╶──┘","└──┘"," ╵","└──┘"," ──┘" + "┌──┐", " ┐ ", "╶──┐", "╶──┐", "╷ ╷", "┌──╴", "┌──╴", "╶──┐", "┌──┐", "┌──┐", + "│ │", " │ ", "┌──┘", " ──┤", "└──┤", "└──┐", "├──┐", " │", "├──┤", "└──┤", + "└──┘", " ╵ ", "└──╴", "╶──┘", " ╵", "╶──┘", "└──┘", " ╵", "└──┘", " ──┘" }; #endif @@ -459,15 +372,15 @@ static void LEDMeterMode_draw(Meter* this, int x, int y, int w) { char buffer[METER_BUFFER_LEN]; Meter_updateValues(this, buffer, METER_BUFFER_LEN - 1); - + RichString_begin(out); Meter_displayBuffer(this, buffer, &out); int yText = #ifdef HAVE_LIBNCURSESW - CRT_utf8 ? y+1 : + CRT_utf8 ? y + 1 : #endif - y+2; + y + 2; attrset(CRT_colors[LED_COLOR]); mvaddstr(yText, x, this->caption); int xx = x + strlen(this->caption); @@ -475,7 +388,7 @@ static void LEDMeterMode_draw(Meter* this, int x, int y, int w) { for (int i = 0; i < len; i++) { char c = RichString_getCharVal(out, i); if (c >= '0' && c <= '9') { - LEDMeterMode_drawDigit(xx, y, c-48); + LEDMeterMode_drawDigit(xx, y, c - 48); xx += 4; } else { mvaddch(yText, xx, c); @@ -510,7 +423,7 @@ static MeterMode LEDMeterMode = { .draw = LEDMeterMode_draw, }; -MeterMode* Meter_modes[] = { +const MeterMode* const Meter_modes[] = { NULL, &BarMeterMode, &TextMeterMode, @@ -523,18 +436,20 @@ MeterMode* Meter_modes[] = { static void BlankMeter_updateValues(Meter* this, char* buffer, int size) { (void) this; (void) buffer; (void) size; + if (size > 0) { + *buffer = 0; + } } -static void BlankMeter_display(Object* cast, RichString* out) { - (void) cast; +static void BlankMeter_display(ATTR_UNUSED const Object* cast, RichString* out) { RichString_prune(out); } -int BlankMeter_attributes[] = { +static const int BlankMeter_attributes[] = { DEFAULT_COLOR }; -MeterClass BlankMeter_class = { +const MeterClass BlankMeter_class = { .super = { .extends = Class(Meter), .delete = Meter_delete, diff --git a/Meter.h b/Meter.h index d98c910ed..125c0cd50 100644 --- a/Meter.h +++ b/Meter.h @@ -1,24 +1,25 @@ -/* Do not edit this file. It was automatically generated. */ - #ifndef HEADER_Meter #define HEADER_Meter /* htop - Meter.h (C) 2004-2011 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ -#define METER_BUFFER_LEN 256 - -#define GRAPH_DELAY (DEFAULT_DELAY/2) +#include "config.h" // IWYU pragma: keep -#define GRAPH_HEIGHT 4 /* Unit: rows (lines) */ +#include +#include #include "ListItem.h" +#include "Object.h" +#include "ProcessList.h" -#include +#define METER_BUFFER_LEN 256 + +struct Meter_; typedef struct Meter_ Meter; typedef void(*Meter_Init)(Meter*); @@ -28,7 +29,7 @@ typedef void(*Meter_UpdateValues)(Meter*, char*, int); typedef void(*Meter_Draw)(Meter*, int, int, int); typedef struct MeterClass_ { - ObjectClass super; + const ObjectClass super; const Meter_Init init; const Meter_Done done; const Meter_UpdateMode updateMode; @@ -36,16 +37,15 @@ typedef struct MeterClass_ { const Meter_UpdateValues updateValues; const int defaultMode; const double total; - const int* attributes; - const char* name; - const char* uiName; - const char* caption; - const char* description; - const char maxItems; - char curItems; + const int* const attributes; + const char* const name; + const char* const uiName; + const char* const caption; + const char* const description; + const uint8_t maxItems; } MeterClass; -#define As_Meter(this_) ((MeterClass*)((this_)->super.klass)) +#define As_Meter(this_) ((const MeterClass*)((this_)->super.klass)) #define Meter_initFn(this_) As_Meter(this_)->init #define Meter_init(this_) As_Meter(this_)->init((Meter*)(this_)) #define Meter_done(this_) As_Meter(this_)->done((Meter*)(this_)) @@ -56,24 +56,29 @@ typedef struct MeterClass_ { #define Meter_updateValues(this_, buf_, sz_) \ As_Meter(this_)->updateValues((Meter*)(this_), buf_, sz_) #define Meter_defaultMode(this_) As_Meter(this_)->defaultMode -#define Meter_getItems(this_) As_Meter(this_)->curItems -#define Meter_setItems(this_, n_) As_Meter(this_)->curItems = (n_) #define Meter_attributes(this_) As_Meter(this_)->attributes #define Meter_name(this_) As_Meter(this_)->name #define Meter_uiName(this_) As_Meter(this_)->uiName +typedef struct GraphData_ { + struct timeval time; + double values[METER_BUFFER_LEN]; +} GraphData; + struct Meter_ { Object super; Meter_Draw draw; - + char* caption; int mode; int param; - void* drawData; + GraphData* drawData; int h; - struct ProcessList_* pl; + const ProcessList* pl; + uint8_t curItems; double* values; double total; + void* meterData; }; typedef struct MeterMode_ { @@ -91,25 +96,9 @@ typedef enum { LAST_METERMODE } MeterModeId; -typedef struct GraphData_ { - struct timeval time; - double values[METER_BUFFER_LEN]; -} GraphData; +extern const MeterClass Meter_class; - -#ifndef MIN -#define MIN(a,b) ((a)<(b)?(a):(b)) -#endif -#ifndef MAX -#define MAX(a,b) ((a)>(b)?(a):(b)) -#endif -#ifndef CLAMP -#define CLAMP(x,low,high) (((x)>(high))?(high):(((x)<(low))?(low):(x))) -#endif - -extern MeterClass Meter_class; - -Meter* Meter_new(struct ProcessList_* pl, int param, MeterClass* type); +Meter* Meter_new(const ProcessList* pl, int param, const MeterClass* type); int Meter_humanUnit(char* buffer, unsigned long int value, int size); @@ -121,31 +110,8 @@ void Meter_setMode(Meter* this, int modeIndex); ListItem* Meter_toListItem(Meter* this, bool moving); -/* ---------- TextMeterMode ---------- */ - -/* ---------- BarMeterMode ---------- */ - -/* ---------- GraphMeterMode ---------- */ - -#ifdef HAVE_LIBNCURSESW - -#define PIXPERROW_UTF8 4 -#endif - -#define PIXPERROW_ASCII 2 - -/* ---------- LEDMeterMode ---------- */ - -#ifdef HAVE_LIBNCURSESW - -#endif - -extern MeterMode* Meter_modes[]; - -/* Blank meter */ - -extern int BlankMeter_attributes[]; +extern const MeterMode* const Meter_modes[]; -extern MeterClass BlankMeter_class; +extern const MeterClass BlankMeter_class; #endif diff --git a/MetersPanel.c b/MetersPanel.c index 3cf3e0758..7e47ad8b6 100644 --- a/MetersPanel.c +++ b/MetersPanel.c @@ -1,35 +1,22 @@ /* htop - MetersPanel.c (C) 2004-2011 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ #include "MetersPanel.h" #include -#include -#include "CRT.h" - -/*{ -#include "Panel.h" -#include "Settings.h" -#include "ScreenManager.h" - -typedef struct MetersPanel_ MetersPanel; -struct MetersPanel_ { - Panel super; - - Settings* settings; - Vector* meters; - ScreenManager* scr; - MetersPanel* leftNeighbor; - MetersPanel* rightNeighbor; - bool moving; -}; +#include "CRT.h" +#include "FunctionBar.h" +#include "Header.h" +#include "ListItem.h" +#include "Meter.h" +#include "Object.h" +#include "ProvideCurses.h" -}*/ // Note: In code the meters are known to have bar/text/graph "Modes", but in UI // we call them "Styles". @@ -46,6 +33,13 @@ static const char* const MetersMovingKeys[] = {"Space", "Enter", "Up", "Dn", "<- static int MetersMovingEvents[] = {' ', 13, KEY_UP, KEY_DOWN, KEY_LEFT, KEY_RIGHT, ERR, KEY_DC, KEY_F(10)}; static FunctionBar* Meters_movingBar = NULL; +void MetersPanel_cleanup() { + if (Meters_movingBar) { + FunctionBar_delete(Meters_movingBar); + Meters_movingBar = NULL; + } +} + static void MetersPanel_delete(Object* object) { Panel* super = (Panel*) object; MetersPanel* this = (MetersPanel*) object; @@ -67,7 +61,7 @@ void MetersPanel_setMoving(MetersPanel* this, bool moving) { Panel_setSelectionColor(super, CRT_colors[PANEL_SELECTION_FOLLOW]); super->currentBar = Meters_movingBar; } - FunctionBar_draw(this->super.currentBar, NULL); + FunctionBar_draw(this->super.currentBar); } static inline bool moveToNeighbor(MetersPanel* this, MetersPanel* neighbor, int selected) { @@ -93,7 +87,7 @@ static inline bool moveToNeighbor(MetersPanel* this, MetersPanel* neighbor, int static HandlerResult MetersPanel_eventHandler(Panel* super, int ch) { MetersPanel* this = (MetersPanel*) super; - + int selected = Panel_getSelectedIndex(super); HandlerResult result = IGNORED; bool sideMove = false; @@ -189,7 +183,7 @@ static HandlerResult MetersPanel_eventHandler(Panel* super, int ch) { } } if (result == HANDLED || sideMove) { - Header* header = (Header*) this->scr->header; + Header* header = this->scr->header; this->settings->changed = true; Header_calculateHeight(header); Header_draw(header); @@ -198,7 +192,7 @@ static HandlerResult MetersPanel_eventHandler(Panel* super, int ch) { return result; } -PanelClass MetersPanel_class = { +const PanelClass MetersPanel_class = { .super = { .extends = Class(Panel), .delete = MetersPanel_delete diff --git a/MetersPanel.h b/MetersPanel.h index e00169c8c..cf4de6042 100644 --- a/MetersPanel.h +++ b/MetersPanel.h @@ -1,18 +1,21 @@ -/* Do not edit this file. It was automatically generated. */ - #ifndef HEADER_MetersPanel #define HEADER_MetersPanel /* htop - MetersPanel.h (C) 2004-2011 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ +#include + #include "Panel.h" -#include "Settings.h" #include "ScreenManager.h" +#include "Settings.h" +#include "Vector.h" + +struct MetersPanel_; typedef struct MetersPanel_ MetersPanel; struct MetersPanel_ { @@ -26,17 +29,11 @@ struct MetersPanel_ { bool moving; }; - -// Note: In code the meters are known to have bar/text/graph "Modes", but in UI -// we call them "Styles". -// We avoid UTF-8 arrows ← → here as they might display full-width on Chinese -// terminals, breaking our aligning. -// In , arrows (U+2019..U+2199) are -// considered "Ambiguous characters". +void MetersPanel_cleanup(void); void MetersPanel_setMoving(MetersPanel* this, bool moving); -extern PanelClass MetersPanel_class; +extern const PanelClass MetersPanel_class; MetersPanel* MetersPanel_new(Settings* settings, const char* header, Vector* meters, ScreenManager* scr); diff --git a/NEWS b/NEWS index fef048b6e..27fd578ef 100644 --- a/NEWS +++ b/NEWS @@ -2,4 +2,3 @@ See the commit history for news of the past. See the bug tracker for news of the future. Run the program for news of the present. - diff --git a/NetworkIOMeter.c b/NetworkIOMeter.c new file mode 100644 index 000000000..a13e3f1ca --- /dev/null +++ b/NetworkIOMeter.c @@ -0,0 +1,122 @@ +#include "NetworkIOMeter.h" + +#include +#include + +#include "CRT.h" +#include "Macros.h" +#include "Object.h" +#include "Platform.h" +#include "RichString.h" +#include "XUtils.h" + + +static const int NetworkIOMeter_attributes[] = { + METER_VALUE_IOREAD, + METER_VALUE_IOWRITE, +}; + +static bool hasData = false; +static unsigned long int cached_rxb_diff = 0; +static unsigned long int cached_rxp_diff = 0; +static unsigned long int cached_txb_diff = 0; +static unsigned long int cached_txp_diff = 0; + +static void NetworkIOMeter_updateValues(ATTR_UNUSED Meter* this, char* buffer, int len) { + static unsigned long int cached_rxb_total = 0; + static unsigned long int cached_rxp_total = 0; + static unsigned long int cached_txb_total = 0; + static unsigned long int cached_txp_total = 0; + static unsigned long long int cached_last_update = 0; + + struct timeval tv; + gettimeofday(&tv, NULL); + unsigned long long int timeInMilliSeconds = (unsigned long long int)tv.tv_sec * 1000 + (unsigned long long int)tv.tv_usec / 1000; + unsigned long long int passedTimeInMs = timeInMilliSeconds - cached_last_update; + + /* update only every 500ms */ + if (passedTimeInMs > 500) { + cached_last_update = timeInMilliSeconds; + + unsigned long int bytesReceived, packetsReceived, bytesTransmitted, packetsTransmitted; + + hasData = Platform_getNetworkIO(&bytesReceived, &packetsReceived, &bytesTransmitted, &packetsTransmitted); + if (!hasData) { + xSnprintf(buffer, len, "no data"); + return; + } + + if (bytesReceived > cached_rxb_total) { + cached_rxb_diff = (bytesReceived - cached_rxb_total) / 1024; /* Meter_humanUnit() expects unit in kilo */ + cached_rxb_diff = 1000.0 * cached_rxb_diff / passedTimeInMs; /* convert to per second */ + } else { + cached_rxb_diff = 0; + } + cached_rxb_total = bytesReceived; + + if (packetsReceived > cached_rxp_total) { + cached_rxp_diff = packetsReceived - cached_rxp_total; + } else { + cached_rxp_diff = 0; + } + cached_rxp_total = packetsReceived; + + if (bytesTransmitted > cached_txb_total) { + cached_txb_diff = (bytesTransmitted - cached_txb_total) / 1024; /* Meter_humanUnit() expects unit in kilo */ + cached_txb_diff = 1000.0 * cached_txb_diff / passedTimeInMs; /* convert to per second */ + } else { + cached_txb_diff = 0; + } + cached_txb_total = bytesTransmitted; + + if (packetsTransmitted > cached_txp_total) { + cached_txp_diff = packetsTransmitted - cached_txp_total; + } else { + cached_txp_diff = 0; + } + cached_txp_total = packetsTransmitted; + } + + char bufferBytesReceived[12], bufferBytesTransmitted[12]; + Meter_humanUnit(bufferBytesReceived, cached_rxb_diff, sizeof(bufferBytesReceived)); + Meter_humanUnit(bufferBytesTransmitted, cached_txb_diff, sizeof(bufferBytesTransmitted)); + xSnprintf(buffer, len, "rx:%siB/s tx:%siB/s", bufferBytesReceived, bufferBytesTransmitted); +} + +static void NetworkIOMeter_display(ATTR_UNUSED const Object* cast, RichString* out) { + if (!hasData) { + RichString_write(out, CRT_colors[METER_VALUE_ERROR], "no data"); + return; + } + + char buffer[64]; + + RichString_write(out, CRT_colors[METER_TEXT], "rx: "); + Meter_humanUnit(buffer, cached_rxb_diff, sizeof(buffer)); + RichString_append(out, CRT_colors[METER_VALUE_IOREAD], buffer); + RichString_append(out, CRT_colors[METER_VALUE_IOREAD], "iB/s"); + + RichString_append(out, CRT_colors[METER_TEXT], " tx: "); + Meter_humanUnit(buffer, cached_txb_diff, sizeof(buffer)); + RichString_append(out, CRT_colors[METER_VALUE_IOWRITE], buffer); + RichString_append(out, CRT_colors[METER_VALUE_IOWRITE], "iB/s"); + + xSnprintf(buffer, sizeof(buffer), " (%lu/%lu packets) ", cached_rxp_diff, cached_txp_diff); + RichString_append(out, CRT_colors[METER_TEXT], buffer); +} + +const MeterClass NetworkIOMeter_class = { + .super = { + .extends = Class(Meter), + .delete = Meter_delete, + .display = NetworkIOMeter_display + }, + .updateValues = NetworkIOMeter_updateValues, + .defaultMode = TEXT_METERMODE, + .maxItems = 0, + .total = 100.0, + .attributes = NetworkIOMeter_attributes, + .name = "NetworkIO", + .uiName = "Network IO", + .caption = "Network: " +}; diff --git a/NetworkIOMeter.h b/NetworkIOMeter.h new file mode 100644 index 000000000..311b5e645 --- /dev/null +++ b/NetworkIOMeter.h @@ -0,0 +1,8 @@ +#ifndef HEADER_NetworkIOMeter +#define HEADER_NetworkIOMeter + +#include "Meter.h" + +extern const MeterClass NetworkIOMeter_class; + +#endif /* HEADER_NetworkIOMeter */ diff --git a/Object.c b/Object.c index 120d28c14..975c8d483 100644 --- a/Object.c +++ b/Object.c @@ -1,63 +1,36 @@ /* htop - Object.c (C) 2004-2012 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +(C) 2020 Red Hat, Inc. All Rights Reserved. +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ #include "Object.h" -/*{ -#include "RichString.h" -#include "XAlloc.h" +#include -typedef struct Object_ Object; -typedef void(*Object_Display)(Object*, RichString*); -typedef long(*Object_Compare)(const void*, const void*); -typedef void(*Object_Delete)(Object*); - -#define Object_getClass(obj_) ((Object*)(obj_))->klass -#define Object_setClass(obj_, class_) Object_getClass(obj_) = (ObjectClass*) class_ - -#define Object_delete(obj_) Object_getClass(obj_)->delete((Object*)(obj_)) -#define Object_displayFn(obj_) Object_getClass(obj_)->display -#define Object_display(obj_, str_) Object_getClass(obj_)->display((Object*)(obj_), str_) -#define Object_compare(obj_, other_) Object_getClass(obj_)->compare((const void*)(obj_), other_) - -#define Class(class_) ((ObjectClass*)(&(class_ ## _class))) - -#define AllocThis(class_) (class_*) xMalloc(sizeof(class_)); Object_setClass(this, Class(class_)); - -typedef struct ObjectClass_ { - const void* extends; - const Object_Display display; - const Object_Delete delete; - const Object_Compare compare; -} ObjectClass; - -struct Object_ { - ObjectClass* klass; -}; - -}*/ - -ObjectClass Object_class = { +const ObjectClass Object_class = { .extends = NULL }; -#ifdef DEBUG +#ifndef NDEBUG -bool Object_isA(Object* o, const ObjectClass* klass) { +bool Object_isA(const Object* o, const ObjectClass* klass) { if (!o) return false; + const ObjectClass* type = o->klass; while (type) { - if (type == klass) + if (type == klass) { return true; + } + type = type->extends; } + return false; } -#endif +#endif /* NDEBUG */ diff --git a/Object.h b/Object.h index 19a667c8a..05a9a72db 100644 --- a/Object.h +++ b/Object.h @@ -1,53 +1,62 @@ -/* Do not edit this file. It was automatically generated. */ - #ifndef HEADER_Object #define HEADER_Object /* htop - Object.h (C) 2004-2012 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +(C) 2020 Red Hat, Inc. All Rights Reserved. +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ #include "RichString.h" -#include "XAlloc.h" +#include "XUtils.h" // IWYU pragma: keep + +#ifndef NDEBUG +#include +#endif + +struct Object_; typedef struct Object_ Object; -typedef void(*Object_Display)(Object*, RichString*); +typedef void(*Object_Display)(const Object*, RichString*); typedef long(*Object_Compare)(const void*, const void*); typedef void(*Object_Delete)(Object*); -#define Object_getClass(obj_) ((Object*)(obj_))->klass -#define Object_setClass(obj_, class_) Object_getClass(obj_) = (ObjectClass*) class_ +#define Object_getClass(obj_) ((const Object*)(obj_))->klass +#define Object_setClass(obj_, class_) (((Object*)(obj_))->klass = (const ObjectClass*) (class_)) #define Object_delete(obj_) Object_getClass(obj_)->delete((Object*)(obj_)) #define Object_displayFn(obj_) Object_getClass(obj_)->display -#define Object_display(obj_, str_) Object_getClass(obj_)->display((Object*)(obj_), str_) +#define Object_display(obj_, str_) Object_getClass(obj_)->display((const Object*)(obj_), str_) #define Object_compare(obj_, other_) Object_getClass(obj_)->compare((const void*)(obj_), other_) -#define Class(class_) ((ObjectClass*)(&(class_ ## _class))) +#define Class(class_) ((const ObjectClass*)(&(class_ ## _class))) + +#define AllocThis(class_) (class_*) xMalloc(sizeof(class_)); Object_setClass(this, Class(class_)) -#define AllocThis(class_) (class_*) xMalloc(sizeof(class_)); Object_setClass(this, Class(class_)); - typedef struct ObjectClass_ { - const void* extends; + const void* const extends; const Object_Display display; const Object_Delete delete; const Object_Compare compare; } ObjectClass; struct Object_ { - ObjectClass* klass; + const ObjectClass* klass; }; +typedef union { + int i; + void* v; +} Arg; -extern ObjectClass Object_class; +extern const ObjectClass Object_class; -#ifdef DEBUG +#ifndef NDEBUG -bool Object_isA(Object* o, const ObjectClass* klass); +bool Object_isA(const Object* o, const ObjectClass* klass); -#endif +#endif /* NDEBUG */ #endif diff --git a/OpenFilesScreen.c b/OpenFilesScreen.c index 9ea333bf7..cd309648b 100644 --- a/OpenFilesScreen.c +++ b/OpenFilesScreen.c @@ -1,33 +1,31 @@ /* htop - OpenFilesScreen.c (C) 2005-2006 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ -#include "OpenFilesScreen.h" +#include "config.h" // IWYU pragma: keep -#include "CRT.h" -#include "ProcessList.h" -#include "IncSet.h" -#include "StringUtils.h" -#include "FunctionBar.h" +#include "OpenFilesScreen.h" -#include +#include #include -#include -#include -#include #include -#include +#include +#include #include #include -/*{ -#include "InfoScreen.h" +#include "Macros.h" +#include "Panel.h" +#include "ProvideCurses.h" +#include "Vector.h" +#include "XUtils.h" + typedef struct OpenFiles_Data_ { - char* data[256]; + char* data[7]; } OpenFiles_Data; typedef struct OpenFiles_ProcessData_ { @@ -41,77 +39,105 @@ typedef struct OpenFiles_FileData_ { struct OpenFiles_FileData_* next; } OpenFiles_FileData; -typedef struct OpenFilesScreen_ { - InfoScreen super; - pid_t pid; -} OpenFilesScreen; +static size_t getIndexForType(char type) { + switch (type) { + case 'f': + return 0; + case 'a': + return 1; + case 'D': + return 2; + case 'i': + return 3; + case 'n': + return 4; + case 's': + return 5; + case 't': + return 6; + } -}*/ + /* should never reach here */ + abort(); +} -InfoScreenClass OpenFilesScreen_class = { - .super = { - .extends = Class(Object), - .delete = OpenFilesScreen_delete - }, - .scan = OpenFilesScreen_scan, - .draw = OpenFilesScreen_draw -}; +static const char* getDataForType(const OpenFiles_Data* data, char type) { + size_t index = getIndexForType(type); + return data->data[index] ? data->data[index] : ""; +} -OpenFilesScreen* OpenFilesScreen_new(Process* process) { +OpenFilesScreen* OpenFilesScreen_new(const Process* process) { OpenFilesScreen* this = xMalloc(sizeof(OpenFilesScreen)); Object_setClass(this, Class(OpenFilesScreen)); - if (Process_isThread(process)) + if (Process_isThread(process)) { this->pid = process->tgid; - else + } else { this->pid = process->pid; - return (OpenFilesScreen*) InfoScreen_init(&this->super, process, NULL, LINES-3, " FD TYPE DEVICE SIZE NODE NAME"); + } + return (OpenFilesScreen*) InfoScreen_init(&this->super, process, NULL, LINES - 3, " FD TYPE MODE DEVICE SIZE NODE NAME"); } void OpenFilesScreen_delete(Object* this) { free(InfoScreen_done((InfoScreen*)this)); } -void OpenFilesScreen_draw(InfoScreen* this) { +static void OpenFilesScreen_draw(InfoScreen* this) { InfoScreen_drawTitled(this, "Snapshot of files open in process %d - %s", ((OpenFilesScreen*)this)->pid, this->process->comm); } static OpenFiles_ProcessData* OpenFilesScreen_getProcessData(pid_t pid) { - char buffer[1025]; - xSnprintf(buffer, 1024, "%d", pid); OpenFiles_ProcessData* pdata = xCalloc(1, sizeof(OpenFiles_ProcessData)); - OpenFiles_FileData* fdata = NULL; - OpenFiles_Data* item = &(pdata->data); - int fdpair[2]; + + int fdpair[2] = {0, 0}; if (pipe(fdpair) == -1) { pdata->error = 1; return pdata; } + pid_t child = fork(); if (child == -1) { + close(fdpair[1]); + close(fdpair[0]); pdata->error = 1; return pdata; } + if (child == 0) { close(fdpair[0]); dup2(fdpair[1], STDOUT_FILENO); close(fdpair[1]); int fdnull = open("/dev/null", O_WRONLY); - if (fdnull < 0) + if (fdnull < 0) { exit(1); + } + dup2(fdnull, STDERR_FILENO); close(fdnull); + char buffer[32] = {0}; + xSnprintf(buffer, sizeof(buffer), "%d", pid); execlp("lsof", "lsof", "-P", "-p", buffer, "-F", NULL); exit(127); } close(fdpair[1]); + + OpenFiles_Data* item = &(pdata->data); + OpenFiles_FileData* fdata = NULL; + FILE* fd = fdopen(fdpair[0], "r"); + if (!fd) { + pdata->error = 1; + return pdata; + } for (;;) { char* line = String_readLine(fd); if (!line) { break; } + unsigned char cmd = line[0]; - if (cmd == 'f') { + switch (cmd) { + case 'f': /* file descriptor */ + { OpenFiles_FileData* nextFile = xCalloc(1, sizeof(OpenFiles_FileData)); if (fdata == NULL) { pdata->files = nextFile; @@ -120,29 +146,60 @@ static OpenFiles_ProcessData* OpenFilesScreen_getProcessData(pid_t pid) { } fdata = nextFile; item = &(fdata->data); + } /* FALLTHRU */ + case 'a': /* file access mode */ + case 'D': /* file's major/minor device number */ + case 'i': /* file's inode number */ + case 'n': /* file name, comment, Internet address */ + case 's': /* file's size */ + case 't': /* file's type */ + { + size_t index = getIndexForType(cmd); + free(item->data[index]); + item->data[index] = xStrdup(line + 1); + break; + } + case 'c': /* process command name */ + case 'd': /* file's device character code */ + case 'g': /* process group ID */ + case 'G': /* file flags */ + case 'k': /* link count */ + case 'l': /* file's lock status */ + case 'L': /* process login name */ + case 'o': /* file's offset */ + case 'p': /* process ID */ + case 'P': /* protocol name */ + case 'R': /* parent process ID */ + case 'T': /* TCP/TPI information, identified by prefixes */ + case 'u': /* process user ID */ + /* ignore */ + break; } - item->data[cmd] = xStrdup(line + 1); free(line); } + fclose(fd); + int wstatus; if (waitpid(child, &wstatus, 0) == -1) { pdata->error = 1; return pdata; } - if (!WIFEXITED(wstatus)) + + if (!WIFEXITED(wstatus)) { pdata->error = 1; - else + } else { pdata->error = WEXITSTATUS(wstatus); + } + return pdata; } -static inline void OpenFiles_Data_clear(OpenFiles_Data* data) { - for (int i = 0; i < 255; i++) - if (data->data[i]) - free(data->data[i]); +static void OpenFiles_Data_clear(OpenFiles_Data* data) { + for (size_t i = 0; i < ARRAYSIZE(data->data); i++) + free(data->data[i]); } -void OpenFilesScreen_scan(InfoScreen* this) { +static void OpenFilesScreen_scan(InfoScreen* this) { Panel* panel = this->display; int idx = Panel_getSelectedIndex(panel); Panel_prune(panel); @@ -154,19 +211,20 @@ void OpenFilesScreen_scan(InfoScreen* this) { } else { OpenFiles_FileData* fdata = pdata->files; while (fdata) { - char** data = fdata->data.data; - int lenN = data['n'] ? strlen(data['n']) : 0; - int sizeEntry = 5 + 7 + 10 + 10 + 10 + lenN + 5 /*spaces*/ + 1 /*null*/; + OpenFiles_Data* data = &fdata->data; + size_t lenN = strlen(getDataForType(data, 'n')); + size_t sizeEntry = 5 + 7 + 4 + 10 + 10 + 10 + lenN + 7 /*spaces*/ + 1 /*null*/; char entry[sizeEntry]; - xSnprintf(entry, sizeEntry, "%5.5s %7.7s %10.10s %10.10s %10.10s %s", - data['f'] ? data['f'] : "", - data['t'] ? data['t'] : "", - data['D'] ? data['D'] : "", - data['s'] ? data['s'] : "", - data['i'] ? data['i'] : "", - data['n'] ? data['n'] : ""); + xSnprintf(entry, sizeof(entry), "%5.5s %-7.7s %-4.4s %-10.10s %10.10s %10.10s %s", + getDataForType(data, 'f'), + getDataForType(data, 't'), + getDataForType(data, 'a'), + getDataForType(data, 'D'), + getDataForType(data, 's'), + getDataForType(data, 'i'), + getDataForType(data, 'n')); InfoScreen_addLine(this, entry); - OpenFiles_Data_clear(&fdata->data); + OpenFiles_Data_clear(data); OpenFiles_FileData* old = fdata; fdata = fdata->next; free(old); @@ -178,3 +236,12 @@ void OpenFilesScreen_scan(InfoScreen* this) { Vector_insertionSort(panel->items); Panel_setSelected(panel, idx); } + +const InfoScreenClass OpenFilesScreen_class = { + .super = { + .extends = Class(Object), + .delete = OpenFilesScreen_delete + }, + .scan = OpenFilesScreen_scan, + .draw = OpenFilesScreen_draw +}; diff --git a/OpenFilesScreen.h b/OpenFilesScreen.h index 8160cfe21..0fbafe0e1 100644 --- a/OpenFilesScreen.h +++ b/OpenFilesScreen.h @@ -1,45 +1,27 @@ -/* Do not edit this file. It was automatically generated. */ - #ifndef HEADER_OpenFilesScreen #define HEADER_OpenFilesScreen /* htop - OpenFilesScreen.h (C) 2005-2006 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ -#include "InfoScreen.h" - -typedef struct OpenFiles_Data_ { - char* data[256]; -} OpenFiles_Data; - -typedef struct OpenFiles_ProcessData_ { - OpenFiles_Data data; - int error; - struct OpenFiles_FileData_* files; -} OpenFiles_ProcessData; +#include -typedef struct OpenFiles_FileData_ { - OpenFiles_Data data; - struct OpenFiles_FileData_* next; -} OpenFiles_FileData; +#include "InfoScreen.h" +#include "Object.h" +#include "Process.h" typedef struct OpenFilesScreen_ { InfoScreen super; pid_t pid; } OpenFilesScreen; +extern const InfoScreenClass OpenFilesScreen_class; -extern InfoScreenClass OpenFilesScreen_class; - -OpenFilesScreen* OpenFilesScreen_new(Process* process); +OpenFilesScreen* OpenFilesScreen_new(const Process* process); void OpenFilesScreen_delete(Object* this); -void OpenFilesScreen_draw(InfoScreen* this); - -void OpenFilesScreen_scan(InfoScreen* this); - #endif diff --git a/Panel.c b/Panel.c index 1e53b4a4d..fd9de2b11 100644 --- a/Panel.c +++ b/Panel.c @@ -1,91 +1,28 @@ /* htop - Panel.c (C) 2004-2011 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ #include "Panel.h" -#include "CRT.h" -#include "RichString.h" -#include "ListItem.h" -#include "StringUtils.h" - -#include +#include +#include #include #include -#include #include -#include +#include -//#link curses - -/*{ -#include "Object.h" -#include "Vector.h" -#include "FunctionBar.h" - -typedef struct Panel_ Panel; - -typedef enum HandlerResult_ { - HANDLED = 0x01, - IGNORED = 0x02, - BREAK_LOOP = 0x04, - REDRAW = 0x08, - RESCAN = 0x10, - SYNTH_KEY = 0x20, -} HandlerResult; - -#define EVENT_SET_SELECTED -1 - -#define EVENT_HEADER_CLICK(x_) (-10000 + x_) -#define EVENT_IS_HEADER_CLICK(ev_) (ev_ >= -10000 && ev_ <= -9000) -#define EVENT_HEADER_CLICK_GET_X(ev_) (ev_ + 10000) - -typedef HandlerResult(*Panel_EventHandler)(Panel*, int); - -typedef struct PanelClass_ { - const ObjectClass super; - const Panel_EventHandler eventHandler; -} PanelClass; - -#define As_Panel(this_) ((PanelClass*)((this_)->super.klass)) -#define Panel_eventHandlerFn(this_) As_Panel(this_)->eventHandler -#define Panel_eventHandler(this_, ev_) As_Panel(this_)->eventHandler((Panel*)(this_), ev_) - -struct Panel_ { - Object super; - int x, y, w, h; - WINDOW* window; - Vector* items; - int selected; - int oldSelected; - int selectedLen; - void* eventHandlerState; - int scrollV; - short scrollH; - bool needsRedraw; - FunctionBar* currentBar; - FunctionBar* defaultBar; - RichString header; - int selectionColor; -}; - -#define Panel_setDefaultBar(this_) do{ (this_)->currentBar = (this_)->defaultBar; }while(0) - -}*/ - -#ifndef MIN -#define MIN(a,b) ((a)<(b)?(a):(b)) -#endif -#ifndef MAX -#define MAX(a,b) ((a)>(b)?(a):(b)) -#endif +#include "CRT.h" +#include "ListItem.h" +#include "Macros.h" +#include "ProvideCurses.h" +#include "RichString.h" +#include "XUtils.h" -#define KEY_CTRL(l) ((l)-'A'+1) -PanelClass Panel_class = { +const PanelClass Panel_class = { .super = { .extends = Class(Object), .delete = Panel_delete @@ -93,7 +30,7 @@ PanelClass Panel_class = { .eventHandler = Panel_selectByTyping, }; -Panel* Panel_new(int x, int y, int w, int h, bool owner, ObjectClass* type, FunctionBar* fuBar) { +Panel* Panel_new(int x, int y, int w, int h, bool owner, const ObjectClass* type, FunctionBar* fuBar) { Panel* this; this = xMalloc(sizeof(Panel)); Object_setClass(this, Class(Panel)); @@ -107,7 +44,7 @@ void Panel_delete(Object* cast) { free(this); } -void Panel_init(Panel* this, int x, int y, int w, int h, ObjectClass* type, bool owner, FunctionBar* fuBar) { +void Panel_init(Panel* this, int x, int y, int w, int h, const ObjectClass* type, bool owner, FunctionBar* fuBar) { this->x = x; this->y = y; this->w = w; @@ -160,8 +97,10 @@ void Panel_move(Panel* this, int x, int y) { void Panel_resize(Panel* this, int w, int h) { assert (this != NULL); - if (RichString_sizeVal(this->header) > 0) + if (RichString_sizeVal(this->header) > 0) { h--; + } + this->w = w; this->h = h; this->needsRedraw = true; @@ -208,33 +147,38 @@ Object* Panel_remove(Panel* this, int i) { this->needsRedraw = true; Object* removed = Vector_remove(this->items, i); - if (this->selected > 0 && this->selected >= Vector_size(this->items)) + if (this->selected > 0 && this->selected >= Vector_size(this->items)) { this->selected--; + } + return removed; } Object* Panel_getSelected(Panel* this) { assert (this != NULL); - if (Vector_size(this->items) > 0) + if (Vector_size(this->items) > 0) { return Vector_get(this->items, this->selected); - else + } else { return NULL; + } } void Panel_moveSelectedUp(Panel* this) { assert (this != NULL); Vector_moveUp(this->items, this->selected); - if (this->selected > 0) + if (this->selected > 0) { this->selected--; + } } void Panel_moveSelectedDown(Panel* this) { assert (this != NULL); Vector_moveDown(this->items, this->selected); - if (this->selected + 1 < Vector_size(this->items)) + if (this->selected + 1 < Vector_size(this->items)) { this->selected++; + } } int Panel_getSelectedIndex(Panel* this) { @@ -256,14 +200,23 @@ void Panel_setSelected(Panel* this, int selected) { if (selected >= size) { selected = size - 1; } - if (selected < 0) + if (selected < 0) { selected = 0; + } this->selected = selected; if (Panel_eventHandlerFn(this)) { Panel_eventHandler(this, EVENT_SET_SELECTED); } } +void Panel_splice(Panel* this, Vector* from) { + assert (this != NULL); + assert (from != NULL); + + Vector_splice(this->items, from); + this->needsRedraw = true; +} + void Panel_draw(Panel* this, bool focus) { assert (this != NULL); @@ -282,7 +235,7 @@ void Panel_draw(Panel* this, bool focus) { mvhline(y, x, ' ', this->w); if (scrollH < headerLen) { RichString_printoffnVal(this->header, y, x, scrollH, - MIN(headerLen - scrollH, this->w)); + MINIMUM(headerLen - scrollH, this->w)); } attrset(CRT_colors[RESET_COLOR]); y++; @@ -293,7 +246,7 @@ void Panel_draw(Panel* this, bool focus) { this->scrollV = 0; this->needsRedraw = true; } else if (this->scrollV >= size) { - this->scrollV = MAX(size - 1, 0); + this->scrollV = MAXIMUM(size - 1, 0); this->needsRedraw = true; } // ensure selection is on screen @@ -306,31 +259,32 @@ void Panel_draw(Panel* this, bool focus) { } int first = this->scrollV; - int upTo = MIN(first + h, size); + int upTo = MINIMUM(first + h, size); int selectionColor = focus - ? this->selectionColor - : CRT_colors[PANEL_SELECTION_UNFOCUS]; + ? this->selectionColor + : CRT_colors[PANEL_SELECTION_UNFOCUS]; if (this->needsRedraw) { int line = 0; - for(int i = first; line < h && i < upTo; i++) { + for (int i = first; line < h && i < upTo; i++) { Object* itemObj = Vector_get(this->items, i); - assert(itemObj); if(!itemObj) continue; RichString_begin(item); Object_display(itemObj, &item); int itemLen = RichString_sizeVal(item); - int amt = MIN(itemLen - scrollH, this->w); - bool selected = (i == this->selected); - if (selected) { - attrset(selectionColor); - RichString_setAttr(&item, selectionColor); + int amt = MINIMUM(itemLen - scrollH, this->w); + if (i == this->selected) { + item.highlightAttr = selectionColor; + } + if (item.highlightAttr) { + attrset(item.highlightAttr); + RichString_setAttr(&item, item.highlightAttr); this->selectedLen = itemLen; } mvhline(y + line, x, ' ', this->w); if (amt > 0) RichString_printoffnVal(item, y + line, x, scrollH, amt); - if (selected) + if (item.highlightAttr) attrset(CRT_colors[RESET_COLOR]); RichString_end(item); line++; @@ -343,7 +297,6 @@ void Panel_draw(Panel* this, bool focus) { } else { Object* oldObj = Vector_get(this->items, this->oldSelected); - assert(oldObj); RichString_begin(old); Object_display(oldObj, &old); int oldLen = RichString_sizeVal(old); @@ -352,16 +305,16 @@ void Panel_draw(Panel* this, bool focus) { Object_display(newObj, &new); int newLen = RichString_sizeVal(new); this->selectedLen = newLen; - mvhline(y+ this->oldSelected - first, x+0, ' ', this->w); + mvhline(y + this->oldSelected - first, x + 0, ' ', this->w); if (scrollH < oldLen) - RichString_printoffnVal(old, y+this->oldSelected - first, x, - scrollH, MIN(oldLen - scrollH, this->w)); + RichString_printoffnVal(old, y + this->oldSelected - first, x, + scrollH, MINIMUM(oldLen - scrollH, this->w)); attrset(selectionColor); - mvhline(y+this->selected - first, x+0, ' ', this->w); + mvhline(y + this->selected - first, x + 0, ' ', this->w); RichString_setAttr(&new, selectionColor); if (scrollH < newLen) - RichString_printoffnVal(new, y+this->selected - first, x, - scrollH, MIN(newLen - scrollH, this->w)); + RichString_printoffnVal(new, y + this->selected - first, x, + scrollH, MINIMUM(newLen - scrollH, this->w)); attrset(CRT_colors[RESET_COLOR]); RichString_end(new); RichString_end(old); @@ -372,7 +325,7 @@ void Panel_draw(Panel* this, bool focus) { bool Panel_onKey(Panel* this, int key) { assert (this != NULL); - + int size = Vector_size(this->items); switch (key) { case KEY_DOWN: @@ -396,7 +349,7 @@ bool Panel_onKey(Panel* this, int key) { case KEY_LEFT: case KEY_CTRL('B'): if (this->scrollH > 0) { - this->scrollH -= MAX(CRT_scrollHAmount, 0); + this->scrollH -= MAXIMUM(CRT_scrollHAmount, 0); this->needsRedraw = true; } break; @@ -407,12 +360,12 @@ bool Panel_onKey(Panel* this, int key) { break; case KEY_PPAGE: this->selected -= (this->h - 1); - this->scrollV = MAX(0, this->scrollV - this->h + 1); + this->scrollV = MAXIMUM(0, this->scrollV - this->h + 1); this->needsRedraw = true; break; case KEY_NPAGE: this->selected += (this->h - 1); - this->scrollV = MAX(0, MIN(Vector_size(this->items) - this->h, + this->scrollV = MAXIMUM(0, MINIMUM(Vector_size(this->items) - this->h, this->scrollV + this->h - 1)); this->needsRedraw = true; break; @@ -444,7 +397,7 @@ bool Panel_onKey(Panel* this, int key) { break; case KEY_CTRL('E'): case '$': - this->scrollH = MAX(this->selectedLen - this->w, 0); + this->scrollH = MAXIMUM(this->selectedLen - this->w, 0); this->needsRedraw = true; break; default: @@ -455,7 +408,7 @@ bool Panel_onKey(Panel* this, int key) { if (this->selected < 0 || size == 0) { this->selected = 0; this->needsRedraw = true; - } else if (this->selected >= size) { + } else if (this->selected >= size) { this->selected = size - 1; this->needsRedraw = true; } @@ -469,7 +422,7 @@ HandlerResult Panel_selectByTyping(Panel* this, int ch) { this->eventHandlerState = xCalloc(100, sizeof(char)); char* buffer = this->eventHandlerState; - if (ch > 0 && ch < 255 && isalnum(ch)) { + if (0 < ch && ch < 255 && isalnum((unsigned char)ch)) { int len = strlen(buffer); if (len < 99) { buffer[len] = ch; @@ -478,7 +431,7 @@ HandlerResult Panel_selectByTyping(Panel* this, int ch) { for (int try = 0; try < 2; try++) { len = strlen(buffer); for (int i = 0; i < size; i++) { - char* cur = ((ListItem*) Panel_get(this, i))->value; + const char* cur = ((ListItem*) Panel_get(this, i))->value; while (*cur == ' ') cur++; if (strncasecmp(cur, buffer, len) == 0) { Panel_setSelected(this, i); diff --git a/Panel.h b/Panel.h index 5253fc2e7..1ea5c7b82 100644 --- a/Panel.h +++ b/Panel.h @@ -1,20 +1,21 @@ -/* Do not edit this file. It was automatically generated. */ - #ifndef HEADER_Panel #define HEADER_Panel /* htop - Panel.h (C) 2004-2011 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ -//#link curses +#include +#include "FunctionBar.h" #include "Object.h" +#include "RichString.h" #include "Vector.h" -#include "FunctionBar.h" + +struct Panel_; typedef struct Panel_ Panel; typedef enum HandlerResult_ { @@ -26,11 +27,11 @@ typedef enum HandlerResult_ { SYNTH_KEY = 0x20, } HandlerResult; -#define EVENT_SET_SELECTED -1 +#define EVENT_SET_SELECTED (-1) -#define EVENT_HEADER_CLICK(x_) (-10000 + x_) -#define EVENT_IS_HEADER_CLICK(ev_) (ev_ >= -10000 && ev_ <= -9000) -#define EVENT_HEADER_CLICK_GET_X(ev_) (ev_ + 10000) +#define EVENT_HEADER_CLICK(x_) (-10000 + (x_)) +#define EVENT_IS_HEADER_CLICK(ev_) ((ev_) >= -10000 && (ev_) <= -9000) +#define EVENT_HEADER_CLICK_GET_X(ev_) ((ev_) + 10000) typedef HandlerResult(*Panel_EventHandler)(Panel*, int); @@ -39,14 +40,13 @@ typedef struct PanelClass_ { const Panel_EventHandler eventHandler; } PanelClass; -#define As_Panel(this_) ((PanelClass*)((this_)->super.klass)) +#define As_Panel(this_) ((const PanelClass*)((this_)->super.klass)) #define Panel_eventHandlerFn(this_) As_Panel(this_)->eventHandler #define Panel_eventHandler(this_, ev_) As_Panel(this_)->eventHandler((Panel*)(this_), ev_) struct Panel_ { Object super; int x, y, w, h; - WINDOW* window; Vector* items; int selected; int oldSelected; @@ -61,25 +61,17 @@ struct Panel_ { int selectionColor; }; -#define Panel_setDefaultBar(this_) do{ (this_)->currentBar = (this_)->defaultBar; }while(0) - - -#ifndef MIN -#define MIN(a,b) ((a)<(b)?(a):(b)) -#endif -#ifndef MAX -#define MAX(a,b) ((a)>(b)?(a):(b)) -#endif +#define Panel_setDefaultBar(this_) do { (this_)->currentBar = (this_)->defaultBar; } while (0) #define KEY_CTRL(l) ((l)-'A'+1) -extern PanelClass Panel_class; +extern const PanelClass Panel_class; -Panel* Panel_new(int x, int y, int w, int h, bool owner, ObjectClass* type, FunctionBar* fuBar); +Panel* Panel_new(int x, int y, int w, int h, bool owner, const ObjectClass* type, FunctionBar* fuBar); void Panel_delete(Object* cast); -void Panel_init(Panel* this, int x, int y, int w, int h, ObjectClass* type, bool owner, FunctionBar* fuBar); +void Panel_init(Panel* this, int x, int y, int w, int h, const ObjectClass* type, bool owner, FunctionBar* fuBar); void Panel_done(Panel* this); @@ -87,7 +79,7 @@ void Panel_setSelectionColor(Panel* this, int color); RichString* Panel_getHeader(Panel* this); -extern void Panel_setHeader(Panel* this, const char* header); +void Panel_setHeader(Panel* this, const char* header); void Panel_move(Panel* this, int x, int y); @@ -119,6 +111,8 @@ void Panel_setSelected(Panel* this, int selected); void Panel_draw(Panel* this, bool focus); +void Panel_splice(Panel* this, Vector* from); + bool Panel_onKey(Panel* this, int key); HandlerResult Panel_selectByTyping(Panel* this, int ch); diff --git a/Process.c b/Process.c index 54c41af4f..b24e3a2f5 100644 --- a/Process.c +++ b/Process.c @@ -1,200 +1,41 @@ /* htop - Process.c (C) 2004-2015 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +(C) 2020 Red Hat, Inc. All Rights Reserved. +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ -#include "Process.h" -#include "Settings.h" +#include "config.h" // IWYU pragma: keep -#include "CRT.h" -#include "StringUtils.h" -#include "RichString.h" -#include "Platform.h" +#include "Process.h" +#include +#include +#include +#include +#include #include -#include -#include -#include -#include -#include -#include #include -#include #include -#include -#include #include -#include -#include -#ifdef MAJOR_IN_MKDEV +#include +#include + +#include "CRT.h" +#include "Platform.h" +#include "RichString.h" +#include "Settings.h" +#include "XUtils.h" + +#if defined(MAJOR_IN_MKDEV) #include -#elif defined(MAJOR_IN_SYSMACROS) || \ - (defined(HAVE_SYS_SYSMACROS_H) && HAVE_SYS_SYSMACROS_H) +#elif defined(MAJOR_IN_SYSMACROS) #include #endif -#ifdef __ANDROID__ -#define SYS_ioprio_get __NR_ioprio_get -#define SYS_ioprio_set __NR_ioprio_set -#endif -// On Linux, this works only with glibc 2.1+. On earlier versions -// the behavior is similar to have a hardcoded page size. -#ifndef PAGE_SIZE -#define PAGE_SIZE ( sysconf(_SC_PAGESIZE) ) -#endif -#define PAGE_SIZE_KB ( PAGE_SIZE / ONE_K ) - -/*{ -#include "Object.h" - -#include - -#define PROCESS_FLAG_IO 0x0001 - -typedef enum ProcessFields { - NULL_PROCESSFIELD = 0, - PID = 1, - COMM = 2, - STATE = 3, - PPID = 4, - PGRP = 5, - SESSION = 6, - TTY_NR = 7, - TPGID = 8, - MINFLT = 10, - MAJFLT = 12, - PRIORITY = 18, - NICE = 19, - STARTTIME = 21, - PROCESSOR = 38, - M_SIZE = 39, - M_RESIDENT = 40, - ST_UID = 46, - PERCENT_CPU = 47, - PERCENT_MEM = 48, - USER = 49, - TIME = 50, - NLWP = 51, - TGID = 52, -} ProcessField; - -typedef struct ProcessPidColumn_ { - int id; - char* label; -} ProcessPidColumn; - -typedef struct Process_ { - Object super; - - struct Settings_* settings; - - unsigned long long int time; - pid_t pid; - pid_t ppid; - pid_t tgid; - char* comm; - int commLen; - int indent; - - int basenameOffset; - bool updated; - - char state; - bool tag; - bool showChildren; - bool show; - unsigned int pgrp; - unsigned int session; - unsigned int tty_nr; - int tpgid; - uid_t st_uid; - unsigned long int flags; - int processor; - - float percent_cpu; - float percent_mem; - char* user; - - long int priority; - long int nice; - long int nlwp; - char starttime_show[8]; - time_t starttime_ctime; - - long m_size; - long m_resident; - - int exit_signal; - - unsigned long int minflt; - unsigned long int majflt; - #ifdef DEBUG - long int itrealvalue; - unsigned long int vsize; - long int rss; - unsigned long int rlim; - unsigned long int startcode; - unsigned long int endcode; - unsigned long int startstack; - unsigned long int kstkesp; - unsigned long int kstkeip; - unsigned long int signal; - unsigned long int blocked; - unsigned long int sigignore; - unsigned long int sigcatch; - unsigned long int wchan; - unsigned long int nswap; - unsigned long int cnswap; - #endif - -} Process; - -typedef struct ProcessFieldData_ { - const char* name; - const char* title; - const char* description; - int flags; -} ProcessFieldData; - -// Implemented in platform-specific code: -void Process_writeField(Process* this, RichString* str, ProcessField field); -long Process_compare(const void* v1, const void* v2); -void Process_delete(Object* cast); -bool Process_isThread(Process* this); -extern ProcessFieldData Process_fields[]; -extern ProcessPidColumn Process_pidColumns[]; -extern char Process_pidFormat[20]; - -typedef Process*(*Process_New)(struct Settings_*); -typedef void (*Process_WriteField)(Process*, RichString*, ProcessField); - -typedef struct ProcessClass_ { - const ObjectClass super; - const Process_WriteField writeField; -} ProcessClass; - -#define As_Process(this_) ((ProcessClass*)((this_)->super.klass)) - -#define Process_getParentPid(process_) (process_->tgid == process_->pid ? process_->ppid : process_->tgid) - -#define Process_isChildOf(process_, pid_) (process_->tgid == pid_ || (process_->tgid == process_->pid && process_->ppid == pid_)) - -#define Process_sortState(state) ((state) == 'I' ? 0x100 : (state)) - -}*/ - -static int Process_getuid = -1; - -#define ONE_K 1024L -#define ONE_M (ONE_K * ONE_K) -#define ONE_G (ONE_M * ONE_K) - -#define ONE_DECIMAL_K 1000L -#define ONE_DECIMAL_M (ONE_DECIMAL_K * ONE_DECIMAL_K) -#define ONE_DECIMAL_G (ONE_DECIMAL_M * ONE_DECIMAL_K) +static uid_t Process_getuid = (uid_t)-1; char Process_pidFormat[20] = "%7d "; @@ -202,7 +43,9 @@ static char Process_titleBuffer[20][20]; void Process_setupColumnWidths() { int maxPid = Platform_getMaxPid(); - if (maxPid == -1) return; + if (maxPid == -1) + return; + int digits = ceil(log10(maxPid)); assert(digits < 20); for (int i = 0; Process_pidColumns[i].label; i++) { @@ -213,52 +56,70 @@ void Process_setupColumnWidths() { xSnprintf(Process_pidFormat, sizeof(Process_pidFormat), "%%%dd ", digits); } -void Process_humanNumber(RichString* str, unsigned long number, bool coloring) { +void Process_humanNumber(RichString* str, unsigned long long number, bool coloring) { char buffer[11]; int len; - + int largeNumberColor = CRT_colors[LARGE_NUMBER]; int processMegabytesColor = CRT_colors[PROCESS_MEGABYTES]; + int processGigabytesColor = CRT_colors[PROCESS_GIGABYTES]; int processColor = CRT_colors[PROCESS]; if (!coloring) { largeNumberColor = CRT_colors[PROCESS]; processMegabytesColor = CRT_colors[PROCESS]; + processGigabytesColor = CRT_colors[PROCESS]; } - - if(number >= (10 * ONE_DECIMAL_M)) { - #ifdef __LP64__ - if(number >= (100 * ONE_DECIMAL_G)) { - len = snprintf(buffer, 10, "%4luT ", number / ONE_G); - RichString_appendn(str, largeNumberColor, buffer, len); - return; - } else if (number >= (1000 * ONE_DECIMAL_M)) { - len = snprintf(buffer, 10, "%4.1lfT ", (double)number / ONE_G); - RichString_appendn(str, largeNumberColor, buffer, len); - return; - } - #endif - if(number >= (100 * ONE_DECIMAL_M)) { - len = snprintf(buffer, 10, "%4luG ", number / ONE_M); - RichString_appendn(str, largeNumberColor, buffer, len); - return; - } - len = snprintf(buffer, 10, "%4.1lfG ", (double)number / ONE_M); - RichString_appendn(str, largeNumberColor, buffer, len); - return; - } else if (number >= 100000) { - len = snprintf(buffer, 10, "%4luM ", number / ONE_K); - RichString_appendn(str, processMegabytesColor, buffer, len); - return; - } else if (number >= 1000) { - len = snprintf(buffer, 10, "%2lu", number/1000); + + if (number < 1000) { + //Plain number, no markings + len = snprintf(buffer, 10, "%5llu ", number); + RichString_appendn(str, processColor, buffer, len); + } else if (number < 100000) { + //2 digit MB, 3 digit KB + len = snprintf(buffer, 10, "%2llu", number/1000); RichString_appendn(str, processMegabytesColor, buffer, len); number %= 1000; - len = snprintf(buffer, 10, "%03lu ", number); + len = snprintf(buffer, 10, "%03llu ", number); RichString_appendn(str, processColor, buffer, len); - return; + } else if (number < 1000 * ONE_K) { + //3 digit MB + number /= ONE_K; + len = snprintf(buffer, 10, "%4lluM ", number); + RichString_appendn(str, processMegabytesColor, buffer, len); + } else if (number < 10000 * ONE_K) { + //1 digit GB, 3 digit MB + number /= ONE_K; + len = snprintf(buffer, 10, "%1llu", number/1000); + RichString_appendn(str, processGigabytesColor, buffer, len); + number %= 1000; + len = snprintf(buffer, 10, "%03lluM ", number); + RichString_appendn(str, processMegabytesColor, buffer, len); + } else if (number < 100000 * ONE_K) { + //2 digit GB, 1 digit MB + number /= 100 * ONE_K; + len = snprintf(buffer, 10, "%2llu", number/10); + RichString_appendn(str, processGigabytesColor, buffer, len); + number %= 10; + len = snprintf(buffer, 10, ".%1lluG ", number); + RichString_appendn(str, processMegabytesColor, buffer, len); + } else if (number < 1000 * ONE_M) { + //3 digit GB + number /= ONE_M; + len = snprintf(buffer, 10, "%4lluG ", number); + RichString_appendn(str, processGigabytesColor, buffer, len); + } else if (number < 10000ULL * ONE_M) { + //1 digit TB, 3 digit GB + number /= ONE_M; + len = snprintf(buffer, 10, "%1llu", number/1000); + RichString_appendn(str, largeNumberColor, buffer, len); + number %= 1000; + len = snprintf(buffer, 10, "%03lluG ", number); + RichString_appendn(str, processGigabytesColor, buffer, len); + } else { + //2 digit TB and above + len = snprintf(buffer, 10, "%4.1lfT ", (double)number/ONE_G); + RichString_appendn(str, largeNumberColor, buffer, len); } - len = snprintf(buffer, 10, "%5lu ", number); - RichString_appendn(str, processColor, buffer, len); } void Process_colorNumber(RichString* str, unsigned long long number, bool coloring) { @@ -274,11 +135,18 @@ void Process_colorNumber(RichString* str, unsigned long long number, bool colori processShadowColor = CRT_colors[PROCESS]; } - if ((long long) number == -1LL) { + if (number == ULLONG_MAX) { int len = snprintf(buffer, 13, " no perm "); RichString_appendn(str, CRT_colors[PROCESS_SHADOW], buffer, len); - } else if (number > 10000000000) { - xSnprintf(buffer, 13, "%11llu ", number / 1000); + } else if (number >= 100000LL * ONE_DECIMAL_T) { + xSnprintf(buffer, 13, "%11llu ", number / ONE_DECIMAL_G); + RichString_appendn(str, largeNumberColor, buffer, 12); + } else if (number >= 100LL * ONE_DECIMAL_T) { + xSnprintf(buffer, 13, "%11llu ", number / ONE_DECIMAL_M); + RichString_appendn(str, largeNumberColor, buffer, 8); + RichString_appendn(str, processMegabytesColor, buffer+8, 4); + } else if (number >= 10LL * ONE_DECIMAL_G) { + xSnprintf(buffer, 13, "%11llu ", number / ONE_DECIMAL_K); RichString_appendn(str, largeNumberColor, buffer, 5); RichString_appendn(str, processMegabytesColor, buffer+5, 3); RichString_appendn(str, processColor, buffer+8, 4); @@ -314,9 +182,15 @@ void Process_printTime(RichString* str, unsigned long long totalHundredths) { } } -static inline void Process_writeCommand(Process* this, int attr, int baseattr, RichString* str) { +void Process_fillStarttimeBuffer(Process* this) { + struct tm date; + (void) localtime_r(&this->starttime_ctime, &date); + strftime(this->starttime_show, sizeof(this->starttime_show) - 1, (this->starttime_ctime > (time(NULL) - 86400)) ? "%R " : "%b%d ", &date); +} + +static inline void Process_writeCommand(const Process* this, int attr, int baseattr, RichString* str) { int start = RichString_size(str), finish = 0; - char* comm = this->comm; + const char* comm = this->comm; if (this->settings->highlightBaseName || !this->settings->showProgramPath) { int i, basename = 0; @@ -329,10 +203,11 @@ static inline void Process_writeCommand(Process* this, int attr, int baseattr, R } } if (!finish) { - if (this->settings->showProgramPath) + if (this->settings->showProgramPath) { start += basename; - else + } else { comm += basename; + } finish = this->basenameOffset - basename; } finish += start - 1; @@ -340,8 +215,9 @@ static inline void Process_writeCommand(Process* this, int attr, int baseattr, R RichString_append(str, attr, comm); - if (this->settings->highlightBaseName) + if (this->settings->highlightBaseName) { RichString_setAttrn(str, baseattr, start, finish); + } } void Process_outputRate(RichString* str, char* buffer, int n, double rate, int coloring) { @@ -352,25 +228,28 @@ void Process_outputRate(RichString* str, char* buffer, int n, double rate, int c largeNumberColor = CRT_colors[PROCESS]; processMegabytesColor = CRT_colors[PROCESS]; } - if (rate == -1) { + if (isnan(rate)) { int len = snprintf(buffer, n, " no perm "); RichString_appendn(str, CRT_colors[PROCESS_SHADOW], buffer, len); } else if (rate < ONE_K) { int len = snprintf(buffer, n, "%7.2f B/s ", rate); RichString_appendn(str, processColor, buffer, len); - } else if (rate < ONE_K * ONE_K) { + } else if (rate < ONE_M) { int len = snprintf(buffer, n, "%7.2f K/s ", rate / ONE_K); RichString_appendn(str, processColor, buffer, len); - } else if (rate < ONE_K * ONE_K * ONE_K) { - int len = snprintf(buffer, n, "%7.2f M/s ", rate / ONE_K / ONE_K); + } else if (rate < ONE_G) { + int len = snprintf(buffer, n, "%7.2f M/s ", rate / ONE_M); RichString_appendn(str, processMegabytesColor, buffer, len); + } else if (rate < ONE_T) { + int len = snprintf(buffer, n, "%7.2f G/s ", rate / ONE_G); + RichString_appendn(str, largeNumberColor, buffer, len); } else { - int len = snprintf(buffer, n, "%7.2f G/s ", rate / ONE_K / ONE_K / ONE_K); + int len = snprintf(buffer, n, "%7.2f T/s ", rate / ONE_T); RichString_appendn(str, largeNumberColor, buffer, len); } } -void Process_writeField(Process* this, RichString* str, ProcessField field) { +void Process_writeField(const Process* this, RichString* str, ProcessField field) { char buffer[256]; buffer[255] = '\0'; int attr = CRT_colors[DEFAULT_COLOR]; int baseattr = CRT_colors[PROCESS_BASENAME]; @@ -378,19 +257,24 @@ void Process_writeField(Process* this, RichString* str, ProcessField field) { bool coloring = this->settings->highlightMegabytes; switch (field) { - case PERCENT_CPU: { - if (this->percent_cpu > 999.9) { - xSnprintf(buffer, n, "%4u ", (unsigned int)this->percent_cpu); - } else if (this->percent_cpu > 99.9) { - xSnprintf(buffer, n, "%3u. ", (unsigned int)this->percent_cpu); + case PERCENT_CPU: + case PERCENT_NORM_CPU: { + float cpuPercentage = this->percent_cpu; + if (field == PERCENT_NORM_CPU) { + cpuPercentage /= this->processList->cpuCount; + } + if (cpuPercentage > 999.9) { + xSnprintf(buffer, n, "%4u ", (unsigned int)cpuPercentage); + } else if (cpuPercentage > 99.9) { + xSnprintf(buffer, n, "%3u. ", (unsigned int)cpuPercentage); } else { - xSnprintf(buffer, n, "%4.1f ", this->percent_cpu); + xSnprintf(buffer, n, "%4.1f ", cpuPercentage); } break; } case PERCENT_MEM: { if (this->percent_mem > 99.9) { - xSnprintf(buffer, n, "100. "); + xSnprintf(buffer, n, "100. "); } else { xSnprintf(buffer, n, "%4.1f ", this->percent_mem); } @@ -410,15 +294,19 @@ void Process_writeField(Process* this, RichString* str, ProcessField field) { bool lastItem = (this->indent < 0); int indent = (this->indent < 0 ? -this->indent : this->indent); - for (int i = 0; i < 32; i++) - if (indent & (1U << i)) + for (int i = 0; i < 32; i++) { + if (indent & (1U << i)) { maxIndent = i+1; + } + } + for (int i = 0; i < maxIndent - 1; i++) { int written, ret; - if (indent & (1 << i)) + if (indent & (1 << i)) { ret = snprintf(buf, n, "%s ", CRT_treeStr[TREE_STR_VERT]); - else + } else { ret = snprintf(buf, n, " "); + } if (ret < 0 || ret >= n) { written = n; } else { @@ -436,8 +324,8 @@ void Process_writeField(Process* this, RichString* str, ProcessField field) { } case MAJFLT: Process_colorNumber(str, this->majflt, coloring); return; case MINFLT: Process_colorNumber(str, this->minflt, coloring); return; - case M_RESIDENT: Process_humanNumber(str, this->m_resident * PAGE_SIZE_KB, coloring); return; - case M_SIZE: Process_humanNumber(str, this->m_size * PAGE_SIZE_KB, coloring); return; + case M_RESIDENT: Process_humanNumber(str, this->m_resident * CRT_pageSizeKB, coloring); return; + case M_SIZE: Process_humanNumber(str, this->m_size * CRT_pageSizeKB, coloring); return; case NICE: { xSnprintf(buffer, n, "%3ld ", this->nice); attr = this->nice < 0 ? CRT_colors[PROCESS_HIGH_PRIORITY] @@ -471,13 +359,13 @@ void Process_writeField(Process* this, RichString* str, ProcessField field) { } break; } - case ST_UID: xSnprintf(buffer, n, "%4d ", this->st_uid); break; + case ST_UID: xSnprintf(buffer, n, "%5d ", this->st_uid); break; case TIME: Process_printTime(str, this->time); return; case TGID: xSnprintf(buffer, n, Process_pidFormat, this->tgid); break; case TPGID: xSnprintf(buffer, n, Process_pidFormat, this->tpgid); break; case TTY_NR: xSnprintf(buffer, n, "%3u:%3u ", major(this->tty_nr), minor(this->tty_nr)); break; case USER: { - if (Process_getuid != (int) this->st_uid) + if (Process_getuid != this->st_uid) attr = CRT_colors[PROCESS_SHADOW]; if (this->user) { xSnprintf(buffer, n, "%-9s ", this->user); @@ -496,16 +384,29 @@ void Process_writeField(Process* this, RichString* str, ProcessField field) { RichString_append(str, attr, buffer); } -void Process_display(Object* cast, RichString* out) { - Process* this = (Process*) cast; - ProcessField* fields = this->settings->fields; +void Process_display(const Object* cast, RichString* out) { + const Process* this = (const Process*) cast; + const ProcessField* fields = this->settings->fields; RichString_prune(out); for (int i = 0; fields[i]; i++) As_Process(this)->writeField(this, out, fields[i]); - if (this->settings->shadowOtherUsers && (int)this->st_uid != Process_getuid) + + if (this->settings->shadowOtherUsers && this->st_uid != Process_getuid) { RichString_setAttr(out, CRT_colors[PROCESS_SHADOW]); - if (this->tag == true) + } + + if (this->tag == true) { RichString_setAttr(out, CRT_colors[PROCESS_TAG]); + } + + if (this->settings->highlightChanges) { + if (Process_isTomb(this)) { + out->highlightAttr = CRT_colors[PROCESS_TOMB]; + } else if (Process_isNew(this)) { + out->highlightAttr = CRT_colors[PROCESS_NEW]; + } + } + assert(out->chlen > 0); } @@ -514,7 +415,7 @@ void Process_done(Process* this) { free(this->comm); } -ProcessClass Process_class = { +const ProcessClass Process_class = { .super = { .extends = Class(Object), .display = Process_display, @@ -524,20 +425,35 @@ ProcessClass Process_class = { .writeField = Process_writeField, }; -void Process_init(Process* this, struct Settings_* settings) { +void Process_init(Process* this, const struct Settings_* settings) { this->settings = settings; this->tag = false; this->showChildren = true; this->show = true; this->updated = false; this->basenameOffset = -1; - if (Process_getuid == -1) Process_getuid = getuid(); + + if (Process_getuid == (uid_t)-1) { + Process_getuid = getuid(); + } } void Process_toggleTag(Process* this) { this->tag = this->tag == true ? false : true; } +bool Process_isNew(const Process* this) { + assert(this->processList); + if (this->processList->scanTs >= this->seenTs) { + return this->processList->scanTs - this->seenTs <= this->processList->settings->highlightDelaySecs; + } + return false; +} + +bool Process_isTomb(const Process* this) { + return this->tombTs > 0; +} + bool Process_setPriority(Process* this, int priority) { CRT_dropPrivileges(); int old_prio = getpriority(PRIO_PROCESS, this->pid); @@ -549,84 +465,86 @@ bool Process_setPriority(Process* this, int priority) { return (err == 0); } -bool Process_changePriorityBy(Process* this, int delta) { - return Process_setPriority(this, this->nice + delta); +bool Process_changePriorityBy(Process* this, Arg delta) { + return Process_setPriority(this, this->nice + delta.i); } -void Process_sendSignal(Process* this, int sgn) { +bool Process_sendSignal(Process* this, Arg sgn) { CRT_dropPrivileges(); - kill(this->pid, (int) sgn); + bool ok = (kill(this->pid, sgn.i) == 0); CRT_restorePrivileges(); + return ok; } long Process_pidCompare(const void* v1, const void* v2) { - Process* p1 = (Process*)v1; - Process* p2 = (Process*)v2; + const Process* p1 = (const Process*)v1; + const Process* p2 = (const Process*)v2; return (p1->pid - p2->pid); } long Process_compare(const void* v1, const void* v2) { - Process *p1, *p2; - Settings *settings = ((Process*)v1)->settings; + const Process *p1, *p2; + const Settings *settings = ((const Process*)v1)->settings; + int r; + if (settings->direction == 1) { - p1 = (Process*)v1; - p2 = (Process*)v2; + p1 = (const Process*)v1; + p2 = (const Process*)v2; } else { - p2 = (Process*)v1; - p1 = (Process*)v2; + p2 = (const Process*)v1; + p1 = (const Process*)v2; } + switch (settings->sortKey) { case PERCENT_CPU: - return (p2->percent_cpu > p1->percent_cpu ? 1 : -1); + case PERCENT_NORM_CPU: + return SPACESHIP_NUMBER(p2->percent_cpu, p1->percent_cpu); case PERCENT_MEM: - return (p2->m_resident - p1->m_resident); + return SPACESHIP_NUMBER(p2->m_resident, p1->m_resident); case COMM: - return strcmp(p1->comm, p2->comm); + return SPACESHIP_NULLSTR(p1->comm, p2->comm); case MAJFLT: - return (p2->majflt - p1->majflt); + return SPACESHIP_NUMBER(p2->majflt, p1->majflt); case MINFLT: - return (p2->minflt - p1->minflt); + return SPACESHIP_NUMBER(p2->minflt, p1->minflt); case M_RESIDENT: - return (p2->m_resident - p1->m_resident); + return SPACESHIP_NUMBER(p2->m_resident, p1->m_resident); case M_SIZE: - return (p2->m_size - p1->m_size); + return SPACESHIP_NUMBER(p2->m_size, p1->m_size); case NICE: - return (p1->nice - p2->nice); + return SPACESHIP_NUMBER(p1->nice, p2->nice); case NLWP: - return (p1->nlwp - p2->nlwp); + return SPACESHIP_NUMBER(p1->nlwp, p2->nlwp); case PGRP: - return (p1->pgrp - p2->pgrp); + return SPACESHIP_NUMBER(p1->pgrp, p2->pgrp); case PID: - return (p1->pid - p2->pid); + return SPACESHIP_NUMBER(p1->pid, p2->pid); case PPID: - return (p1->ppid - p2->ppid); + return SPACESHIP_NUMBER(p1->ppid, p2->ppid); case PRIORITY: - return (p1->priority - p2->priority); + return SPACESHIP_NUMBER(p1->priority, p2->priority); case PROCESSOR: - return (p1->processor - p2->processor); + return SPACESHIP_NUMBER(p1->processor, p2->processor); case SESSION: - return (p1->session - p2->session); - case STARTTIME: { - if (p1->starttime_ctime == p2->starttime_ctime) - return (p1->pid - p2->pid); - else - return (p1->starttime_ctime - p2->starttime_ctime); - } + return SPACESHIP_NUMBER(p1->session, p2->session); + case STARTTIME: + r = SPACESHIP_NUMBER(p1->starttime_ctime, p2->starttime_ctime); + return r != 0 ? r : SPACESHIP_NUMBER(p1->pid, p2->pid); case STATE: - return (Process_sortState(p1->state) - Process_sortState(p2->state)); + return SPACESHIP_NUMBER(Process_sortState(p1->state), Process_sortState(p2->state)); case ST_UID: - return (p1->st_uid - p2->st_uid); + return SPACESHIP_NUMBER(p1->st_uid, p2->st_uid); case TIME: - return ((p2->time) - (p1->time)); + return SPACESHIP_NUMBER(p2->time, p1->time); case TGID: - return (p1->tgid - p2->tgid); + return SPACESHIP_NUMBER(p1->tgid, p2->tgid); case TPGID: - return (p1->tpgid - p2->tpgid); + return SPACESHIP_NUMBER(p1->tpgid, p2->tpgid); case TTY_NR: - return (p1->tty_nr - p2->tty_nr); + return SPACESHIP_NUMBER(p1->tty_nr, p2->tty_nr); case USER: - return strcmp(p1->user ? p1->user : "", p2->user ? p2->user : ""); + return SPACESHIP_NULLSTR(p1->user, p2->user); default: - return (p1->pid - p2->pid); + return SPACESHIP_NUMBER(p1->pid, p2->pid); } } diff --git a/Process.h b/Process.h index f702ca006..631eba74c 100644 --- a/Process.h +++ b/Process.h @@ -1,36 +1,27 @@ -/* Do not edit this file. It was automatically generated. */ - #ifndef HEADER_Process #define HEADER_Process /* htop - Process.h (C) 2004-2015 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +(C) 2020 Red Hat, Inc. All Rights Reserved. +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ -#ifdef MAJOR_IN_MKDEV -#elif defined(MAJOR_IN_SYSMACROS) || \ - (defined(HAVE_SYS_SYSMACROS_H) && HAVE_SYS_SYSMACROS_H) -#endif +#include +#include +#include + +#include "Object.h" +#include "RichString.h" #ifdef __ANDROID__ #define SYS_ioprio_get __NR_ioprio_get #define SYS_ioprio_set __NR_ioprio_set #endif -// On Linux, this works only with glibc 2.1+. On earlier versions -// the behavior is similar to have a hardcoded page size. -#ifndef PAGE_SIZE -#define PAGE_SIZE ( sysconf(_SC_PAGESIZE) ) -#endif -#define PAGE_SIZE_KB ( PAGE_SIZE / ONE_K ) - -#include "Object.h" - -#include - #define PROCESS_FLAG_IO 0x0001 +#define DEFAULT_HIGHLIGHT_SECS 5 typedef enum ProcessFields { NULL_PROCESSFIELD = 0, @@ -57,17 +48,21 @@ typedef enum ProcessFields { TIME = 50, NLWP = 51, TGID = 52, + PERCENT_NORM_CPU = 53, } ProcessField; typedef struct ProcessPidColumn_ { int id; - char* label; + const char* label; } ProcessPidColumn; +struct Settings_; + typedef struct Process_ { Object super; - struct Settings_* settings; + const struct ProcessList_* processList; + const struct Settings_* settings; unsigned long long int time; pid_t pid; @@ -84,6 +79,7 @@ typedef struct Process_ { bool tag; bool showChildren; bool show; + bool wasShown; unsigned int pgrp; unsigned int session; unsigned int tty_nr; @@ -94,7 +90,7 @@ typedef struct Process_ { float percent_cpu; float percent_mem; - char* user; + const char* user; long int priority; long int nice; @@ -107,27 +103,11 @@ typedef struct Process_ { int exit_signal; + time_t seenTs; + time_t tombTs; + unsigned long int minflt; unsigned long int majflt; - #ifdef DEBUG - long int itrealvalue; - unsigned long int vsize; - long int rss; - unsigned long int rlim; - unsigned long int startcode; - unsigned long int endcode; - unsigned long int startstack; - unsigned long int kstkesp; - unsigned long int kstkeip; - unsigned long int signal; - unsigned long int blocked; - unsigned long int sigignore; - unsigned long int sigcatch; - unsigned long int wchan; - unsigned long int nswap; - unsigned long int cnswap; - #endif - } Process; typedef struct ProcessFieldData_ { @@ -138,71 +118,77 @@ typedef struct ProcessFieldData_ { } ProcessFieldData; // Implemented in platform-specific code: -void Process_writeField(Process* this, RichString* str, ProcessField field); +void Process_writeField(const Process* this, RichString* str, ProcessField field); long Process_compare(const void* v1, const void* v2); void Process_delete(Object* cast); -bool Process_isThread(Process* this); +bool Process_isThread(const Process* this); extern ProcessFieldData Process_fields[]; extern ProcessPidColumn Process_pidColumns[]; extern char Process_pidFormat[20]; -typedef Process*(*Process_New)(struct Settings_*); -typedef void (*Process_WriteField)(Process*, RichString*, ProcessField); +typedef Process*(*Process_New)(const struct Settings_*); +typedef void (*Process_WriteField)(const Process*, RichString*, ProcessField); typedef struct ProcessClass_ { const ObjectClass super; const Process_WriteField writeField; } ProcessClass; -#define As_Process(this_) ((ProcessClass*)((this_)->super.klass)) +#define As_Process(this_) ((const ProcessClass*)((this_)->super.klass)) -#define Process_getParentPid(process_) (process_->tgid == process_->pid ? process_->ppid : process_->tgid) +static inline pid_t Process_getParentPid(const Process* this) { + return this->tgid == this->pid ? this->ppid : this->tgid; +} -#define Process_isChildOf(process_, pid_) (process_->tgid == pid_ || (process_->tgid == process_->pid && process_->ppid == pid_)) +static inline bool Process_isChildOf(const Process* this, pid_t pid) { + return pid == Process_getParentPid(this); +} #define Process_sortState(state) ((state) == 'I' ? 0x100 : (state)) -#define ONE_K 1024L +#define ONE_K 1024UL #define ONE_M (ONE_K * ONE_K) #define ONE_G (ONE_M * ONE_K) +#define ONE_T (1ULL * ONE_G * ONE_K) -#define ONE_DECIMAL_K 1000L +#define ONE_DECIMAL_K 1000UL #define ONE_DECIMAL_M (ONE_DECIMAL_K * ONE_DECIMAL_K) #define ONE_DECIMAL_G (ONE_DECIMAL_M * ONE_DECIMAL_K) +#define ONE_DECIMAL_T (1ULL * ONE_DECIMAL_G * ONE_DECIMAL_K) -extern char Process_pidFormat[20]; - -void Process_setupColumnWidths(); +void Process_setupColumnWidths(void); -void Process_humanNumber(RichString* str, unsigned long number, bool coloring); +void Process_humanNumber(RichString* str, unsigned long long number, bool coloring); void Process_colorNumber(RichString* str, unsigned long long number, bool coloring); void Process_printTime(RichString* str, unsigned long long totalHundredths); -void Process_outputRate(RichString* str, char* buffer, int n, double rate, int coloring); +void Process_fillStarttimeBuffer(Process* this); -void Process_writeField(Process* this, RichString* str, ProcessField field); +void Process_outputRate(RichString* str, char* buffer, int n, double rate, int coloring); -void Process_display(Object* cast, RichString* out); +void Process_display(const Object* cast, RichString* out); void Process_done(Process* this); -extern ProcessClass Process_class; +extern const ProcessClass Process_class; -void Process_init(Process* this, struct Settings_* settings); +void Process_init(Process* this, const struct Settings_* settings); void Process_toggleTag(Process* this); +bool Process_isNew(const Process* this); + +bool Process_isTomb(const Process* this); + bool Process_setPriority(Process* this, int priority); -bool Process_changePriorityBy(Process* this, int delta); +bool Process_changePriorityBy(Process* this, Arg delta); -void Process_sendSignal(Process* this, int sgn); +bool Process_sendSignal(Process* this, Arg sgn); long Process_pidCompare(const void* v1, const void* v2); -long Process_compare(const void* v1, const void* v2); - #endif diff --git a/ProcessList.c b/ProcessList.c index 7482b0377..8c3f6403e 100644 --- a/ProcessList.c +++ b/ProcessList.c @@ -1,104 +1,50 @@ /* htop - ProcessList.c (C) 2004,2005 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ #include "ProcessList.h" -#include "Platform.h" -#include "CRT.h" -#include "StringUtils.h" - -#include +#include #include +#include -/*{ -#include "Vector.h" -#include "Hashtable.h" -#include "UsersTable.h" -#include "Panel.h" -#include "Process.h" -#include "Settings.h" - -#ifdef HAVE_LIBHWLOC -#include -#endif - -#ifndef MAX_NAME -#define MAX_NAME 128 -#endif - -#ifndef MAX_READ -#define MAX_READ 2048 -#endif - -typedef struct ProcessList_ { - Settings* settings; - - Vector* processes; - Vector* processes2; - Hashtable* processTable; - UsersTable* usersTable; - - Panel* panel; - int following; - uid_t userId; - const char* incFilter; - Hashtable* pidWhiteList; - - #ifdef HAVE_LIBHWLOC - hwloc_topology_t topology; - bool topologyOk; - #endif - - int totalTasks; - int runningTasks; - int userlandThreads; - int kernelThreads; - - unsigned long long int totalMem; - unsigned long long int usedMem; - unsigned long long int freeMem; - unsigned long long int sharedMem; - unsigned long long int buffersMem; - unsigned long long int cachedMem; - unsigned long long int totalSwap; - unsigned long long int usedSwap; - unsigned long long int freeSwap; - - int cpuCount; - -} ProcessList; - -ProcessList* ProcessList_new(UsersTable* ut, Hashtable* pidWhiteList, uid_t userId); -void ProcessList_delete(ProcessList* pl); -void ProcessList_goThroughEntries(ProcessList* pl); +#include "CRT.h" +#include "XUtils.h" -}*/ -ProcessList* ProcessList_init(ProcessList* this, ObjectClass* klass, UsersTable* usersTable, Hashtable* pidWhiteList, uid_t userId) { +ProcessList* ProcessList_init(ProcessList* this, const ObjectClass* klass, UsersTable* usersTable, Hashtable* pidMatchList, uid_t userId) { this->processes = Vector_new(klass, true, DEFAULT_SIZE); this->processTable = Hashtable_new(140, false); this->usersTable = usersTable; - this->pidWhiteList = pidWhiteList; + this->pidMatchList = pidMatchList; this->userId = userId; - + // tree-view auxiliary buffer this->processes2 = Vector_new(klass, true, DEFAULT_SIZE); - + // set later by platform-specific code this->cpuCount = 0; + this->scanTs = 0; + #ifdef HAVE_LIBHWLOC this->topologyOk = false; - int topoErr = hwloc_topology_init(&this->topology); - if (topoErr == 0) { - topoErr = hwloc_topology_load(this->topology); - } - if (topoErr == 0) { - this->topologyOk = true; + if (hwloc_topology_init(&this->topology) == 0) { + this->topologyOk = + #if HWLOC_API_VERSION < 0x00020000 + /* try to ignore the top-level machine object type */ + 0 == hwloc_topology_ignore_type_keep_structure(this->topology, HWLOC_OBJ_MACHINE) && + /* ignore caches, which don't add structure */ + 0 == hwloc_topology_ignore_type_keep_structure(this->topology, HWLOC_OBJ_CORE) && + 0 == hwloc_topology_ignore_type_keep_structure(this->topology, HWLOC_OBJ_CACHE) && + 0 == hwloc_topology_set_flags(this->topology, HWLOC_TOPOLOGY_FLAG_WHOLE_SYSTEM) && + #else + 0 == hwloc_topology_set_all_types_filter(this->topology, HWLOC_TYPE_FILTER_KEEP_STRUCTURE) && + #endif + 0 == hwloc_topology_load(this->topology); } #endif @@ -124,24 +70,32 @@ void ProcessList_setPanel(ProcessList* this, Panel* panel) { void ProcessList_printHeader(ProcessList* this, RichString* header) { RichString_prune(header); - ProcessField* fields = this->settings->fields; + const ProcessField* fields = this->settings->fields; for (int i = 0; fields[i]; i++) { const char* field = Process_fields[fields[i]].title; - if (!field) field = "- "; - if (!this->settings->treeView && this->settings->sortKey == fields[i]) + if (!field) { + field = "- "; + } + + if (!this->settings->treeView && this->settings->sortKey == fields[i]) { RichString_append(header, CRT_colors[PANEL_SELECTION_FOCUS], field); - else + } else { RichString_append(header, CRT_colors[PANEL_HEADER_FOCUS], field); + } } } void ProcessList_add(ProcessList* this, Process* p) { assert(Vector_indexOf(this->processes, p, Process_pidCompare) == -1); assert(Hashtable_get(this->processTable, p->pid) == NULL); - + p->processList = this; + + // highlighting processes found in first scan by first scan marked "far in the past" + p->seenTs = this->scanTs; + Vector_add(this->processes, p); Hashtable_put(this->processTable, p->pid, p); - + assert(Vector_indexOf(this->processes, p, Process_pidCompare) != -1); assert(Hashtable_get(this->processTable, p->pid) != NULL); assert(Hashtable_count(this->processTable) == Vector_count(this->processes)); @@ -150,12 +104,18 @@ void ProcessList_add(ProcessList* this, Process* p) { void ProcessList_remove(ProcessList* this, Process* p) { assert(Vector_indexOf(this->processes, p, Process_pidCompare) != -1); assert(Hashtable_get(this->processTable, p->pid) != NULL); + Process* pp = Hashtable_remove(this->processTable, p->pid); assert(pp == p); (void)pp; + unsigned int pid = p->pid; int idx = Vector_indexOf(this->processes, p, Process_pidCompare); assert(idx != -1); - if (idx >= 0) Vector_remove(this->processes, idx); + + if (idx >= 0) { + Vector_remove(this->processes, idx); + } + assert(Hashtable_get(this->processTable, pid) == NULL); (void)pid; assert(Hashtable_count(this->processTable) == Vector_count(this->processes)); } @@ -181,38 +141,46 @@ static void ProcessList_buildTree(ProcessList* this, pid_t pid, int level, int i int size = Vector_size(children); for (int i = 0; i < size; i++) { Process* process = (Process*) (Vector_get(children, i)); - if (!show) + if (!show) { process->show = false; - int s = this->processes2->items; - if (direction == 1) + } + + int s = Vector_size(this->processes2); + if (direction == 1) { Vector_add(this->processes2, process); - else + } else { Vector_insert(this->processes2, 0, process); - assert(this->processes2->items == s+1); (void)s; + } + + assert(Vector_size(this->processes2) == s+1); (void)s; + int nextIndent = indent | (1 << level); ProcessList_buildTree(this, process->pid, level+1, (i < size - 1) ? nextIndent : indent, direction, show ? process->showChildren : false); - if (i == size - 1) + + if (i == size - 1) { process->indent = -nextIndent; - else + } else { process->indent = nextIndent; + } } Vector_delete(children); } +static long ProcessList_treeProcessCompare(const void* v1, const void* v2) { + const Process *p1 = (const Process*)v1; + const Process *p2 = (const Process*)v2; + + return p1->pid - p2->pid; +} + void ProcessList_sort(ProcessList* this) { if (!this->settings->treeView) { Vector_insertionSort(this->processes); } else { // Save settings int direction = this->settings->direction; - int sortKey = this->settings->sortKey; // Sort by PID - this->settings->sortKey = PID; - this->settings->direction = 1; - Vector_quickSort(this->processes); - // Restore settings - this->settings->sortKey = sortKey; - this->settings->direction = direction; + Vector_quickSortCustomCompare(this->processes, ProcessList_treeProcessCompare); int vsize = Vector_size(this->processes); // Find all processes whose parent is not visible int size; @@ -236,6 +204,7 @@ void ProcessList_sort(ProcessList* this) { // root. if (process->pid == ppid) r = 0; + while (l < r) { int c = (l + r) / 2; pid_t pid = ((Process*)(Vector_get(this->processes, c)))->pid; @@ -269,13 +238,16 @@ void ProcessList_sort(ProcessList* this) { } -ProcessField ProcessList_keyAt(ProcessList* this, int at) { +ProcessField ProcessList_keyAt(const ProcessList* this, int at) { int x = 0; - ProcessField* fields = this->settings->fields; + const ProcessField* fields = this->settings->fields; ProcessField field; for (int i = 0; (field = fields[i]); i++) { const char* title = Process_fields[field].title; - if (!title) title = "- "; + if (!title) { + title = "- "; + } + int len = strlen(title); if (at >= x && at <= x + len) { return field; @@ -310,7 +282,7 @@ void ProcessList_rebuildPanel(ProcessList* this) { if ( (!p->show) || (this->userId != (uid_t) -1 && (p->st_uid != this->userId)) || (incFilter && !(String_contains_i(p->comm, incFilter))) - || (this->pidWhiteList && !Hashtable_get(this->pidWhiteList, p->tgid)) ) + || (this->pidMatchList && !Hashtable_get(this->pidMatchList, p->tgid)) ) hidden = true; if (!hidden) { @@ -338,12 +310,20 @@ Process* ProcessList_getProcess(ProcessList* this, pid_t pid, bool* preExisting, return proc; } -void ProcessList_scan(ProcessList* this) { +void ProcessList_scan(ProcessList* this, bool pauseProcessUpdate) { + struct timespec now; + + // in pause mode only gather global data for meters (CPU/memory/...) + if (pauseProcessUpdate) { + ProcessList_goThroughEntries(this, true); + return; + } // mark all process as "dirty" for (int i = 0; i < Vector_size(this->processes); i++) { Process* p = (Process*) Vector_get(this->processes, i); p->updated = false; + p->wasShown = p->show; p->show = true; } @@ -352,13 +332,36 @@ void ProcessList_scan(ProcessList* this) { this->kernelThreads = 0; this->runningTasks = 0; - ProcessList_goThroughEntries(this); - + + // set scanTs + static bool firstScanDone = false; + if (!firstScanDone) { + this->scanTs = 0; + firstScanDone = true; + } else if (clock_gettime(CLOCK_MONOTONIC, &now) == 0) { + this->scanTs = now.tv_sec; + } + + ProcessList_goThroughEntries(this, false); + for (int i = Vector_size(this->processes) - 1; i >= 0; i--) { Process* p = (Process*) Vector_get(this->processes, i); - if (p->updated == false) + if (p->tombTs > 0) { + // remove tombed process + if (this->scanTs >= p->tombTs) { ProcessList_remove(this, p); - else + } + } else if (p->updated == false) { + // process no longer exists + if (this->settings->highlightChanges && p->wasShown) { + // mark tombed + p->tombTs = this->scanTs + this->settings->highlightDelaySecs; + } else { + // immediately remove + ProcessList_remove(this, p); + } + } else { p->updated = false; + } } } diff --git a/ProcessList.h b/ProcessList.h index 572d48431..a4b0cd6fa 100644 --- a/ProcessList.h +++ b/ProcessList.h @@ -1,25 +1,31 @@ -/* Do not edit this file. It was automatically generated. */ - #ifndef HEADER_ProcessList #define HEADER_ProcessList /* htop - ProcessList.h (C) 2004,2005 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ -#include "Vector.h" +#include "config.h" // IWYU pragma: keep + +#include +#include + #include "Hashtable.h" -#include "UsersTable.h" +#include "Object.h" #include "Panel.h" #include "Process.h" +#include "RichString.h" #include "Settings.h" +#include "UsersTable.h" +#include "Vector.h" #ifdef HAVE_LIBHWLOC #include #endif + #ifndef MAX_NAME #define MAX_NAME 128 #endif @@ -29,7 +35,7 @@ in the source distribution for its full text. #endif typedef struct ProcessList_ { - Settings* settings; + const Settings* settings; Vector* processes; Vector* processes2; @@ -40,7 +46,7 @@ typedef struct ProcessList_ { int following; uid_t userId; const char* incFilter; - Hashtable* pidWhiteList; + Hashtable* pidMatchList; #ifdef HAVE_LIBHWLOC hwloc_topology_t topology; @@ -64,14 +70,15 @@ typedef struct ProcessList_ { int cpuCount; + time_t scanTs; } ProcessList; -ProcessList* ProcessList_new(UsersTable* ut, Hashtable* pidWhiteList, uid_t userId); +ProcessList* ProcessList_new(UsersTable* usersTable, Hashtable* pidMatchList, uid_t userId); void ProcessList_delete(ProcessList* pl); -void ProcessList_goThroughEntries(ProcessList* pl); +void ProcessList_goThroughEntries(ProcessList* super, bool pauseProcessUpdate); -ProcessList* ProcessList_init(ProcessList* this, ObjectClass* klass, UsersTable* usersTable, Hashtable* pidWhiteList, uid_t userId); +ProcessList* ProcessList_init(ProcessList* this, const ObjectClass* klass, UsersTable* usersTable, Hashtable* pidMatchList, uid_t userId); void ProcessList_done(ProcessList* this); @@ -89,7 +96,7 @@ int ProcessList_size(ProcessList* this); void ProcessList_sort(ProcessList* this); -ProcessField ProcessList_keyAt(ProcessList* this, int at); +ProcessField ProcessList_keyAt(const ProcessList* this, int at); void ProcessList_expandTree(ProcessList* this); @@ -97,6 +104,6 @@ void ProcessList_rebuildPanel(ProcessList* this); Process* ProcessList_getProcess(ProcessList* this, pid_t pid, bool* preExisting, Process_New constructor); -void ProcessList_scan(ProcessList* this); +void ProcessList_scan(ProcessList* this, bool pauseProcessUpdate); #endif diff --git a/ProcessLocksScreen.c b/ProcessLocksScreen.c new file mode 100644 index 000000000..67743c941 --- /dev/null +++ b/ProcessLocksScreen.c @@ -0,0 +1,116 @@ +/* +htop - ProcessLocksScreen.c +(C) 2020 htop dev team +Released under the GNU GPLv2, see the COPYING file +in the source distribution for its full text. +*/ + +#include "config.h" // IWYU pragma: keep + +#include "ProcessLocksScreen.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "CRT.h" +#include "Compat.h" +#include "FunctionBar.h" +#include "IncSet.h" +#include "Platform.h" +#include "ProcessList.h" +#include "XUtils.h" + + +ProcessLocksScreen* ProcessLocksScreen_new(const Process* process) { + ProcessLocksScreen* this = xMalloc(sizeof(ProcessLocksScreen)); + Object_setClass(this, Class(ProcessLocksScreen)); + if (Process_isThread(process)) + this->pid = process->tgid; + else + this->pid = process->pid; + return (ProcessLocksScreen*) InfoScreen_init(&this->super, process, NULL, LINES-3, " ID TYPE EXCLUSION READ/WRITE DEVICE:INODE START END FILENAME"); +} + +void ProcessLocksScreen_delete(Object* this) { + free(InfoScreen_done((InfoScreen*)this)); +} + +static void ProcessLocksScreen_draw(InfoScreen* this) { + InfoScreen_drawTitled(this, "Snapshot of file locks of process %d - %s", ((ProcessLocksScreen*)this)->pid, this->process->comm); +} + +static inline void FileLocks_Data_clear(FileLocks_Data* data) { + free(data->locktype); + free(data->exclusive); + free(data->readwrite); + free(data->filename); +} + +static void ProcessLocksScreen_scan(InfoScreen* this) { + Panel* panel = this->display; + int idx = Panel_getSelectedIndex(panel); + Panel_prune(panel); + FileLocks_ProcessData* pdata = Platform_getProcessLocks(((ProcessLocksScreen*)this)->pid); + if (!pdata) { + InfoScreen_addLine(this, "This feature is not supported on your platform."); + } else if (pdata->error) { + InfoScreen_addLine(this, "Could not determine file locks."); + } else { + FileLocks_LockData* ldata = pdata->locks; + if (!ldata) { + InfoScreen_addLine(this, "No locks have been found for the selected process."); + } + while (ldata) { + FileLocks_Data* data = &ldata->data; + + char entry[512]; + if (ULLONG_MAX == data->end) { + xSnprintf(entry, sizeof(entry), "%10d %-10s %-10s %-10s %02x:%02x:%020"PRIu64" %20"PRIu64" %20s %s", + data->id, + data->locktype, data->exclusive, data->readwrite, + data->dev[0], data->dev[1], data->inode, + data->start, "", + data->filename ? data->filename : "" + ); + } else { + xSnprintf(entry, sizeof(entry), "%10d %-10s %-10s %-10s %02x:%02x:%020"PRIu64" %20"PRIu64" %20"PRIu64" %s", + data->id, + data->locktype, data->exclusive, data->readwrite, + data->dev[0], data->dev[1], data->inode, + data->start, data->end, + data->filename ? data->filename : "" + ); + } + + InfoScreen_addLine(this, entry); + FileLocks_Data_clear(&ldata->data); + + FileLocks_LockData* old = ldata; + ldata = ldata->next; + free(old); + } + } + free(pdata); + Vector_insertionSort(this->lines); + Vector_insertionSort(panel->items); + Panel_setSelected(panel, idx); +} + +const InfoScreenClass ProcessLocksScreen_class = { + .super = { + .extends = Class(Object), + .delete = ProcessLocksScreen_delete + }, + .scan = ProcessLocksScreen_scan, + .draw = ProcessLocksScreen_draw +}; diff --git a/ProcessLocksScreen.h b/ProcessLocksScreen.h new file mode 100644 index 000000000..daffd6299 --- /dev/null +++ b/ProcessLocksScreen.h @@ -0,0 +1,48 @@ +#ifndef HEADER_ProcessLocksScreen +#define HEADER_ProcessLocksScreen +/* +htop - ProcessLocksScreen.h +(C) 2020 htop dev team +Released under the GNU GPLv2, see the COPYING file +in the source distribution for its full text. +*/ + +#include "InfoScreen.h" + +#include + + +typedef struct ProcessLocksScreen_ { + InfoScreen super; + pid_t pid; +} ProcessLocksScreen; + +typedef struct FileLocks_Data_ { + char* locktype; + char* exclusive; + char* readwrite; + char* filename; + int id; + unsigned int dev[2]; + uint64_t inode; + uint64_t start; + uint64_t end; +} FileLocks_Data; + +typedef struct FileLocks_LockData_ { + FileLocks_Data data; + struct FileLocks_LockData_* next; +} FileLocks_LockData; + +typedef struct FileLocks_ProcessData_ { + bool error; + struct FileLocks_LockData_* locks; +} FileLocks_ProcessData; + +extern const InfoScreenClass ProcessLocksScreen_class; + +ProcessLocksScreen* ProcessLocksScreen_new(const Process* process); + +void ProcessLocksScreen_delete(Object* this); + +#endif diff --git a/ProvideCurses.h b/ProvideCurses.h new file mode 100644 index 000000000..c35d696d4 --- /dev/null +++ b/ProvideCurses.h @@ -0,0 +1,34 @@ +#ifndef HEADER_ProvideCurses +#define HEADER_ProvideCurses +/* +htop - RichString.h +(C) 2004,2011 Hisham H. Muhammad +Released under the GNU GPL, see the COPYING file +in the source distribution for its full text. +*/ + + +#include "config.h" + +// IWYU pragma: begin_exports + +#ifdef HAVE_NCURSESW_CURSES_H +#include +#elif defined(HAVE_NCURSES_NCURSES_H) +#include +#elif defined(HAVE_NCURSES_CURSES_H) +#include +#elif defined(HAVE_NCURSES_H) +#include +#elif defined(HAVE_CURSES_H) +#include +#endif + +#ifdef HAVE_LIBNCURSESW +#include +#include +#endif + +// IWYU pragma: end_exports + +#endif // HEADER_ProvideCurses diff --git a/README b/README index 33a8739eb..880597d8a 100644 --- a/README +++ b/README @@ -1,60 +1,69 @@ -[![Build Status](https://travis-ci.org/hishamhm/htop.svg?branch=master)](https://travis-ci.org/hishamhm/htop) -[![PayPal donate](https://img.shields.io/badge/paypal-donate-green.svg)](http://hisham.hm/htop/index.php?page=donate) +# [![htop](htop.png)](https://htop.dev) -[htop](http://hisham.hm/htop/) -==== +[![CI](https://github.com/htop-dev/htop/workflows/CI/badge.svg)](https://github.com/htop-dev/htop/actions) +[![Coverity Scan Build Status](https://scan.coverity.com/projects/21665/badge.svg)](https://scan.coverity.com/projects/21665) +[![Mailing List](https://img.shields.io/badge/Mailing%20List-htop-blue.svg)](https://groups.io/g/htop) +[![IRC #htop](https://img.shields.io/badge/IRC-htop-blue.svg)](https://webchat.freenode.net/#htop) +[![Github Release](https://img.shields.io/github/release/htop-dev/htop.svg)](https://github.com/htop-dev/htop/releases/latest) +[![Download](https://api.bintray.com/packages/htop/source/htop/images/download.svg)](https://bintray.com/htop/source/htop/_latestVersion) -by Hisham Muhammad (2004 - 2016) +![Screenshot of htop](docs/images/screenshot.png?raw=true) -Introduction ------------- +## Introduction -This is `htop`, an interactive process viewer. -It requires `ncurses`. It is developed primarily on Linux, -but we also have code for running under FreeBSD and Mac OS X -(help and testing are wanted for these platforms!) +`htop` is a cross-platform interactive process viewer. -This software has evolved considerably over the years, -and is reasonably complete, but there is always room for improvement. +`htop` allows scrolling the list of processes vertically and horizontally to see their full command lines and related information like memory and CPU consumption. -Comparison between `htop` and classic `top` -------------------------------------------- +The information displayed is configurable through a graphical setup and can be sorted and filtered interactively. -* In `htop` you can scroll the list vertically and horizontally - to see all processes and full command lines. -* In `top` you are subject to a delay for each unassigned - key you press (especially annoying when multi-key escape - sequences are triggered by accident). -* `htop` starts faster (`top` seems to collect data for a while - before displaying anything). -* In `htop` you don't need to type the process number to - kill a process, in `top` you do. -* In `htop` you don't need to type the process number or - the priority value to renice a process, in `top` you do. -* In `htop` you can kill multiple processes at once. -* `top` is older, hence, more tested. +Tasks related to processes (e.g. killing and renicing) can be done without entering their PIDs. -Compilation instructions ------------------------- +Running `htop` requires `ncurses` libraries (typically named libncursesw*). -This program is distributed as a standard autotools-based package. -See the [INSTALL](/INSTALL) file for detailed instructions. +For more information and details on how to contribute to `htop` visit [htop.dev](https://htop.dev). -When compiling from a [release tarball](https://hisham.hm/htop/releases/), run: +## Build instructions - ./configure && make +This program is distributed as a standard GNU autotools-based package. -For compiling sources downloaded from the Git repository, run: +Compiling `htop` requires the header files for `ncurses` (libncursesw*-dev). Install these and other required packages for C development from your package manager. - ./autogen.sh && ./configure && make +Then, when compiling from a [release tarball](https://bintray.com/htop/source/htop), run: -By default `make install` will install into `/usr/local`, for changing -the path use `./configure --prefix=/some/path`. +~~~ shell +./configure && make +~~~ -See the manual page (`man htop`) or the on-line help ('F1' or 'h' -inside `htop`) for a list of supported key commands. +Alternatively, for compiling sources downloaded from the Git repository (`git clone` or downloads from [Github releases](https://github.com/htop-dev/htop/releases/)), +install the header files for `ncurses` (libncursesw*-dev) and other required development packages from your distribution's package manager. Then run: -If not all keys work check your curses configuration. +~~~ shell +./autogen.sh && ./configure && make +~~~ + +By default `make install` will install into `/usr/local`, for changing the path use `./configure --prefix=/some/path`. + +See the manual page (`man htop`) or the on-line help ('F1' or 'h' inside `htop`) for a list of supported key commands. + +## Support + +If you have trouble running `htop` please consult your Operating System / Linux distribution documentation for getting support and filing bugs. + +## Bugs, development feedback + +We have a [development mailing list](https://htop.dev/mailinglist.html). Feel free to subscribe for release announcements or asking questions on the development of htop. + +You can also join our IRC channel #htop on freenode and talk to the developers there. + +If you have found an issue with the source of htop, please check whether this has already been reported in our [Github issue tracker](https://github.com/htop-dev/htop/issues). +If not, please file a new issue describing the problem you have found, the location in the source code you are referring to and a possible fix. + +## History + +`htop` was invented, developed and maintained by Hisham Muhammad from 2004 to 2019. His [legacy repository](https://github.com/hishamhm/htop/) has been archived to preserve the history. + +In 2020 a [team](https://github.com/orgs/htop-dev/people) took over the development amicably and continues to maintain `htop` collaboratively. ## License diff --git a/RichString.c b/RichString.c index 370566a87..904b44b65 100644 --- a/RichString.c +++ b/RichString.c @@ -1,73 +1,20 @@ /* htop - RichString.c (C) 2004,2011 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ #include "RichString.h" -#include "XAlloc.h" #include #include -#define RICHSTRING_MAXLEN 350 - -/*{ -#include "config.h" -#include - -#include -#ifdef HAVE_NCURSESW_CURSES_H -#include -#elif HAVE_NCURSES_NCURSES_H -#include -#elif HAVE_NCURSES_CURSES_H -#include -#elif HAVE_NCURSES_H -#include -#elif HAVE_CURSES_H -#include -#endif +#include "Macros.h" +#include "XUtils.h" -#ifdef HAVE_LIBNCURSESW -#include -#endif - -#define RichString_size(this) ((this)->chlen) -#define RichString_sizeVal(this) ((this).chlen) -#define RichString_begin(this) RichString (this); memset(&this, 0, sizeof(RichString)); (this).chptr = (this).chstr; -#define RichString_beginAllocated(this) memset(&this, 0, sizeof(RichString)); (this).chptr = (this).chstr; -#define RichString_end(this) RichString_prune(&(this)); - -#ifdef HAVE_LIBNCURSESW -#define RichString_printVal(this, y, x) mvadd_wchstr(y, x, (this).chptr) -#define RichString_printoffnVal(this, y, x, off, n) mvadd_wchnstr(y, x, (this).chptr + off, n) -#define RichString_getCharVal(this, i) ((this).chptr[i].chars[0] & 255) -#define RichString_setChar(this, at, ch) do{ (this)->chptr[(at)] = (CharType) { .chars = { ch, 0 } }; } while(0) -#define CharType cchar_t -#else -#define RichString_printVal(this, y, x) mvaddchstr(y, x, (this).chptr) -#define RichString_printoffnVal(this, y, x, off, n) mvaddchnstr(y, x, (this).chptr + off, n) -#define RichString_getCharVal(this, i) ((this).chptr[i]) -#define RichString_setChar(this, at, ch) do{ (this)->chptr[(at)] = ch; } while(0) -#define CharType chtype -#endif - -typedef struct RichString_ { - int chlen; - CharType* chptr; - CharType chstr[RICHSTRING_MAXLEN+1]; -} RichString; - -}*/ - -#ifndef CLAMP -#define CLAMP(x,low,high) (((x)>(high))?(high):(((x)<(low))?(low):(x))) -#endif - -#define charBytes(n) (sizeof(CharType) * (n)) +#define charBytes(n) (sizeof(CharType) * (n)) static void RichString_extendLen(RichString* this, int len) { if (this->chlen <= RICHSTRING_MAXLEN) { @@ -89,15 +36,23 @@ static void RichString_extendLen(RichString* this, int len) { this->chlen = len; } -#define RichString_setLen(this, len) do{ if(len < RICHSTRING_MAXLEN && this->chlen < RICHSTRING_MAXLEN) { RichString_setChar(this,len,0); this->chlen=len; } else RichString_extendLen(this,len); }while(0) +static void RichString_setLen(RichString* this, int len) { + if (len < RICHSTRING_MAXLEN && this->chlen < RICHSTRING_MAXLEN) { + RichString_setChar(this, len, 0); + this->chlen = len; + } else { + RichString_extendLen(this, len); + } +} #ifdef HAVE_LIBNCURSESW static inline void RichString_writeFrom(RichString* this, int attrs, const char* data_c, int from, int len) { - wchar_t data[len+1]; + wchar_t data[len + 1]; len = mbstowcs(data, data_c, len); if (len < 0) return; + int newLen = from + len; RichString_setLen(this, newLen); for (int i = from, j = 0; i < newLen; i++, j++) { @@ -125,13 +80,14 @@ int RichString_findChar(RichString* this, char c, int start) { return -1; } -#else +#else /* HAVE_LIBNCURSESW */ static inline void RichString_writeFrom(RichString* this, int attrs, const char* data_c, int from, int len) { int newLen = from + len; RichString_setLen(this, newLen); - for (int i = from, j = 0; i < newLen; i++, j++) + for (int i = from, j = 0; i < newLen; i++, j++) { this->chptr[i] = (data_c[j] >= 32 ? data_c[j] : '?') | attrs; + } this->chptr[newLen] = 0; } @@ -154,7 +110,7 @@ int RichString_findChar(RichString* this, char c, int start) { return -1; } -#endif +#endif /* HAVE_LIBNCURSESW */ void RichString_prune(RichString* this) { if (this->chlen > RICHSTRING_MAXLEN) diff --git a/RichString.h b/RichString.h index f5b5cba10..12b095400 100644 --- a/RichString.h +++ b/RichString.h @@ -1,86 +1,51 @@ -/* Do not edit this file. It was automatically generated. */ - #ifndef HEADER_RichString #define HEADER_RichString /* htop - RichString.h (C) 2004,2011 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ -#define RICHSTRING_MAXLEN 350 - #include "config.h" -#include - -#include -#ifdef HAVE_NCURSESW_CURSES_H -#include -#elif HAVE_NCURSES_NCURSES_H -#include -#elif HAVE_NCURSES_CURSES_H -#include -#elif HAVE_NCURSES_H -#include -#elif HAVE_CURSES_H -#include -#endif -#ifdef HAVE_LIBNCURSESW -#include -#endif +#include "ProvideCurses.h" + #define RichString_size(this) ((this)->chlen) #define RichString_sizeVal(this) ((this).chlen) -#define RichString_begin(this) RichString (this); memset(&this, 0, sizeof(RichString)); (this).chptr = (this).chstr; -#define RichString_beginAllocated(this) memset(&this, 0, sizeof(RichString)); (this).chptr = (this).chstr; -#define RichString_end(this) RichString_prune(&(this)); +#define RichString_begin(this) RichString (this); RichString_beginAllocated(this) +#define RichString_beginAllocated(this) do { memset(&(this), 0, sizeof(RichString)); (this).chptr = (this).chstr; } while(0) +#define RichString_end(this) RichString_prune(&(this)) #ifdef HAVE_LIBNCURSESW #define RichString_printVal(this, y, x) mvadd_wchstr(y, x, (this).chptr) -#define RichString_printoffnVal(this, y, x, off, n) mvadd_wchnstr(y, x, (this).chptr + off, n) +#define RichString_printoffnVal(this, y, x, off, n) mvadd_wchnstr(y, x, (this).chptr + (off), n) #define RichString_getCharVal(this, i) ((this).chptr[i].chars[0] & 255) -#define RichString_setChar(this, at, ch) do{ (this)->chptr[(at)] = (CharType) { .chars = { ch, 0 } }; } while(0) +#define RichString_setChar(this, at, ch) do { (this)->chptr[(at)] = (CharType) { .chars = { ch, 0 } }; } while (0) #define CharType cchar_t #else #define RichString_printVal(this, y, x) mvaddchstr(y, x, (this).chptr) -#define RichString_printoffnVal(this, y, x, off, n) mvaddchnstr(y, x, (this).chptr + off, n) +#define RichString_printoffnVal(this, y, x, off, n) mvaddchnstr(y, x, (this).chptr + (off), n) #define RichString_getCharVal(this, i) ((this).chptr[i]) -#define RichString_setChar(this, at, ch) do{ (this)->chptr[(at)] = ch; } while(0) +#define RichString_setChar(this, at, ch) do { (this)->chptr[(at)] = ch; } while (0) #define CharType chtype #endif +#define RICHSTRING_MAXLEN 350 + typedef struct RichString_ { int chlen; CharType* chptr; - CharType chstr[RICHSTRING_MAXLEN+1]; + CharType chstr[RICHSTRING_MAXLEN + 1]; + int highlightAttr; } RichString; - -#ifndef CLAMP -#define CLAMP(x,low,high) (((x)>(high))?(high):(((x)<(low))?(low):(x))) -#endif - -#define charBytes(n) (sizeof(CharType) * (n)) - -#define RichString_setLen(this, len) do{ if(len < RICHSTRING_MAXLEN && this->chlen < RICHSTRING_MAXLEN) { RichString_setChar(this,len,0); this->chlen=len; } else RichString_extendLen(this,len); }while(0) - -#ifdef HAVE_LIBNCURSESW - -extern void RichString_setAttrn(RichString* this, int attrs, int start, int finish); - -int RichString_findChar(RichString* this, char c, int start); - -#else - void RichString_setAttrn(RichString* this, int attrs, int start, int finish); int RichString_findChar(RichString* this, char c, int start); -#endif - void RichString_prune(RichString* this); void RichString_setAttr(RichString* this, int attrs); diff --git a/ScreenManager.c b/ScreenManager.c index 06e901938..28f289dba 100644 --- a/ScreenManager.c +++ b/ScreenManager.c @@ -1,50 +1,26 @@ /* htop - ScreenManager.c (C) 2004-2011 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ #include "ScreenManager.h" -#include "ProcessList.h" - -#include "Object.h" -#include "CRT.h" #include -#include -#include #include +#include +#include -/*{ +#include "CRT.h" #include "FunctionBar.h" -#include "Vector.h" -#include "Header.h" -#include "Settings.h" -#include "Panel.h" - -typedef enum Orientation_ { - VERTICAL, - HORIZONTAL -} Orientation; - -typedef struct ScreenManager_ { - int x1; - int y1; - int x2; - int y2; - Orientation orientation; - Vector* panels; - int panelCount; - const Header* header; - const Settings* settings; - bool owner; - bool allowFocusChange; -} ScreenManager; - -}*/ - -ScreenManager* ScreenManager_new(int x1, int y1, int x2, int y2, Orientation orientation, const Header* header, const Settings* settings, bool owner) { +#include "Object.h" +#include "ProcessList.h" +#include "ProvideCurses.h" +#include "XUtils.h" + + +ScreenManager* ScreenManager_new(int x1, int y1, int x2, int y2, Orientation orientation, Header* header, const Settings* settings, const State* state, bool owner) { ScreenManager* this; this = xMalloc(sizeof(ScreenManager)); this->x1 = x1; @@ -56,6 +32,7 @@ ScreenManager* ScreenManager_new(int x1, int y1, int x2, int y2, Orientation ori this->panelCount = 0; this->header = header; this->settings = settings; + this->state = state; this->owner = owner; this->allowFocusChange = true; return this; @@ -81,7 +58,7 @@ void ScreenManager_add(ScreenManager* this, Panel* item, int size) { if (size > 0) { Panel_resize(item, size, height); } else { - Panel_resize(item, COLS-this->x1+this->x2-lastX, height); + Panel_resize(item, COLS - this->x1 + this->x2 - lastX, height); } Panel_move(item, lastX, this->y1); } @@ -108,29 +85,34 @@ void ScreenManager_resize(ScreenManager* this, int x1, int y1, int x2, int y2) { int lastX = 0; for (int i = 0; i < panels - 1; i++) { Panel* panel = (Panel*) Vector_get(this->panels, i); - Panel_resize(panel, panel->w, LINES-y1+y2); + Panel_resize(panel, panel->w, LINES - y1 + y2); Panel_move(panel, lastX, y1); lastX = panel->x + panel->w + 1; } - Panel* panel = (Panel*) Vector_get(this->panels, panels-1); - Panel_resize(panel, COLS-x1+x2-lastX, LINES-y1+y2); + Panel* panel = (Panel*) Vector_get(this->panels, panels - 1); + Panel_resize(panel, COLS - x1 + x2 - lastX, LINES - y1 + y2); Panel_move(panel, lastX, y1); } // TODO: VERTICAL } -static void checkRecalculation(ScreenManager* this, double* oldTime, int* sortTimeout, bool* redraw, bool *rescan, bool *timedOut) { +static void checkRecalculation(ScreenManager* this, double* oldTime, int* sortTimeout, bool* redraw, bool* rescan, bool* timedOut) { ProcessList* pl = this->header->pl; struct timeval tv; gettimeofday(&tv, NULL); double newTime = ((double)tv.tv_sec * 10) + ((double)tv.tv_usec / 100000); + *timedOut = (newTime - *oldTime > this->settings->delay); - *rescan = *rescan || *timedOut; - if (newTime < *oldTime) *rescan = true; // clock was adjusted? + *rescan |= *timedOut; + + if (newTime < *oldTime) { + *rescan = true; // clock was adjusted? + } + if (*rescan) { *oldTime = newTime; - ProcessList_scan(pl); + ProcessList_scan(pl, this->state->pauseProcessUpdate); if (*sortTimeout == 0 || this->settings->treeView) { ProcessList_sort(pl); *sortTimeout = 1; @@ -150,21 +132,25 @@ static void ScreenManager_drawPanels(ScreenManager* this, int focus) { Panel* panel = (Panel*) Vector_get(this->panels, i); Panel_draw(panel, i == focus); if (this->orientation == HORIZONTAL) { - mvvline(panel->y, panel->x+panel->w, ' ', panel->h+1); + mvvline(panel->y, panel->x + panel->w, ' ', panel->h + 1); } } } -static Panel* setCurrentPanel(Panel* panel) { - FunctionBar_draw(panel->currentBar, NULL); +static Panel* setCurrentPanel(const ScreenManager* this, Panel* panel) { + FunctionBar_draw(panel->currentBar); + if (panel == this->state->panel && this->state->pauseProcessUpdate) { + FunctionBar_append("PAUSED", CRT_colors[PAUSED]); + } + return panel; } void ScreenManager_run(ScreenManager* this, Panel** lastFocus, int* lastKey) { bool quit = false; int focus = 0; - - Panel* panelFocus = setCurrentPanel((Panel*) Vector_get(this->panels, focus)); + + Panel* panelFocus = setCurrentPanel(this, (Panel*) Vector_get(this->panels, focus)); double oldTime = 0.0; @@ -181,7 +167,7 @@ void ScreenManager_run(ScreenManager* this, Panel** lastFocus, int* lastKey) { if (this->header) { checkRecalculation(this, &oldTime, &sortTimeout, &redraw, &rescan, &timedOut); } - + if (redraw) { ScreenManager_drawPanels(this, focus); } @@ -191,7 +177,7 @@ void ScreenManager_run(ScreenManager* this, Panel** lastFocus, int* lastKey) { ch = getch(); HandlerResult result = IGNORED; - if (ch == KEY_MOUSE) { + if (ch == KEY_MOUSE && this->settings->enableMouse) { ch = ERR; MEVENT mevent; int ok = getmouse(&mevent); @@ -202,15 +188,15 @@ void ScreenManager_run(ScreenManager* this, Panel** lastFocus, int* lastKey) { } else { for (int i = 0; i < this->panelCount; i++) { Panel* panel = (Panel*) Vector_get(this->panels, i); - if (mevent.x >= panel->x && mevent.x <= panel->x+panel->w) { + if (mevent.x >= panel->x && mevent.x <= panel->x + panel->w) { if (mevent.y == panel->y) { ch = EVENT_HEADER_CLICK(mevent.x - panel->x); break; - } else if (mevent.y > panel->y && mevent.y <= panel->y+panel->h) { + } else if (mevent.y > panel->y && mevent.y <= panel->y + panel->h) { ch = KEY_MOUSE; if (panel == panelFocus || this->allowFocusChange) { focus = i; - panelFocus = setCurrentPanel(panel); + panelFocus = setCurrentPanel(this, panel); Object* oldSelection = Panel_getSelected(panel); Panel_setSelected(panel, mevent.y - panel->y + panel->scrollV - 1); if (Panel_getSelected(panel) == oldSelection) { @@ -238,8 +224,9 @@ void ScreenManager_run(ScreenManager* this, Panel** lastFocus, int* lastKey) { if (closeTimeout == 100) { break; } - } else + } else { closeTimeout = 0; + } redraw = false; continue; } @@ -269,7 +256,7 @@ void ScreenManager_run(ScreenManager* this, Panel** lastFocus, int* lastKey) { quit = true; continue; } - + switch (ch) { case KEY_RESIZE: { @@ -281,14 +268,21 @@ void ScreenManager_run(ScreenManager* this, Panel** lastFocus, int* lastKey) { if (this->panelCount < 2) { goto defaultHandler; } - if (!this->allowFocusChange) + + if (!this->allowFocusChange) { break; - tryLeft: - if (focus > 0) + } + +tryLeft: + if (focus > 0) { focus--; - panelFocus = setCurrentPanel((Panel*) Vector_get(this->panels, focus)); - if (Panel_size(panelFocus) == 0 && focus > 0) + } + + panelFocus = setCurrentPanel(this, (Panel*) Vector_get(this->panels, focus)); + if (Panel_size(panelFocus) == 0 && focus > 0) { goto tryLeft; + } + break; case KEY_RIGHT: case KEY_CTRL('F'): @@ -296,14 +290,20 @@ void ScreenManager_run(ScreenManager* this, Panel** lastFocus, int* lastKey) { if (this->panelCount < 2) { goto defaultHandler; } - if (!this->allowFocusChange) + if (!this->allowFocusChange) { break; - tryRight: - if (focus < this->panelCount - 1) + } + +tryRight: + if (focus < this->panelCount - 1) { focus++; - panelFocus = setCurrentPanel((Panel*) Vector_get(this->panels, focus)); - if (Panel_size(panelFocus) == 0 && focus < this->panelCount - 1) + } + + panelFocus = setCurrentPanel(this, (Panel*) Vector_get(this->panels, focus)); + if (Panel_size(panelFocus) == 0 && focus < this->panelCount - 1) { goto tryRight; + } + break; case KEY_F(10): case 'q': @@ -311,15 +311,18 @@ void ScreenManager_run(ScreenManager* this, Panel** lastFocus, int* lastKey) { quit = true; continue; default: - defaultHandler: +defaultHandler: sortTimeout = resetSortTimeout; Panel_onKey(panelFocus, ch); break; } } - if (lastFocus) + if (lastFocus) { *lastFocus = panelFocus; - if (lastKey) + } + + if (lastKey) { *lastKey = ch; + } } diff --git a/ScreenManager.h b/ScreenManager.h index 3d02a8835..97e849f39 100644 --- a/ScreenManager.h +++ b/ScreenManager.h @@ -1,19 +1,20 @@ -/* Do not edit this file. It was automatically generated. */ - #ifndef HEADER_ScreenManager #define HEADER_ScreenManager /* htop - ScreenManager.h (C) 2004-2011 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ -#include "FunctionBar.h" -#include "Vector.h" +#include + +#include "Action.h" #include "Header.h" -#include "Settings.h" #include "Panel.h" +#include "Settings.h" +#include "Vector.h" + typedef enum Orientation_ { VERTICAL, @@ -28,18 +29,18 @@ typedef struct ScreenManager_ { Orientation orientation; Vector* panels; int panelCount; - const Header* header; + Header* header; const Settings* settings; + const State* state; bool owner; bool allowFocusChange; } ScreenManager; - -ScreenManager* ScreenManager_new(int x1, int y1, int x2, int y2, Orientation orientation, const Header* header, const Settings* settings, bool owner); +ScreenManager* ScreenManager_new(int x1, int y1, int x2, int y2, Orientation orientation, Header* header, const Settings* settings, const State* state, bool owner); void ScreenManager_delete(ScreenManager* this); -extern int ScreenManager_size(ScreenManager* this); +int ScreenManager_size(ScreenManager* this); void ScreenManager_add(ScreenManager* this, Panel* item, int size); diff --git a/Settings.c b/Settings.c index db2fa0668..158264710 100644 --- a/Settings.c +++ b/Settings.c @@ -1,77 +1,28 @@ /* htop - Settings.c (C) 2004-2011 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ #include "Settings.h" -#include "Platform.h" - -#include "StringUtils.h" -#include "Vector.h" -#include "CRT.h" -#include +#include #include -#include #include +#include -#define DEFAULT_DELAY 15 - -/*{ -#include "Process.h" -#include - -typedef struct { - int len; - char** names; - int* modes; -} MeterColumnSettings; - -typedef struct Settings_ { - char* filename; - - MeterColumnSettings columns[2]; - - ProcessField* fields; - int flags; - int colorScheme; - int delay; - - int cpuCount; - int direction; - ProcessField sortKey; - - bool countCPUsFromZero; - bool detailedCPUTime; - bool treeView; - bool showProgramPath; - bool hideThreads; - bool shadowOtherUsers; - bool showThreadNames; - bool hideKernelThreads; - bool hideUserlandThreads; - bool highlightBaseName; - bool highlightMegabytes; - bool highlightThreads; - bool updateProcessNames; - bool accountGuestInCPUMeter; - bool headerMargin; - - bool changed; -} Settings; - -#ifndef Settings_cpuId -#define Settings_cpuId(settings, cpu) ((settings)->countCPUsFromZero ? (cpu) : (cpu)+1) -#endif +#include "CRT.h" +#include "Macros.h" +#include "Meter.h" +#include "Platform.h" +#include "XUtils.h" -}*/ void Settings_delete(Settings* this) { free(this->filename); free(this->fields); - for (unsigned int i = 0; i < (sizeof(this->columns)/sizeof(MeterColumnSettings)); i++) { + for (unsigned int i = 0; i < ARRAYSIZE(this->columns); i++) { String_freeArray(this->columns[i].names); free(this->columns[i].modes); } @@ -80,16 +31,14 @@ void Settings_delete(Settings* this) { static void Settings_readMeters(Settings* this, char* line, int column) { char* trim = String_trim(line); - int nIds; - char** ids = String_split(trim, ' ', &nIds); + char** ids = String_split(trim, ' ', NULL); free(trim); this->columns[column].names = ids; } static void Settings_readMeterModes(Settings* this, char* line, int column) { char* trim = String_trim(line); - int nIds; - char** ids = String_split(trim, ' ', &nIds); + char** ids = String_split(trim, ' ', NULL); free(trim); int len = 0; for (int i = 0; ids[i]; i++) { @@ -104,9 +53,9 @@ static void Settings_readMeterModes(Settings* this, char* line, int column) { this->columns[column].modes = modes; } -static void Settings_defaultMeters(Settings* this) { +static void Settings_defaultMeters(Settings* this, int initialCpuCount) { int sizes[] = { 3, 3 }; - if (this->cpuCount > 4) { + if (initialCpuCount > 4) { sizes[1]++; } for (int i = 0; i < 2; i++) { @@ -114,14 +63,13 @@ static void Settings_defaultMeters(Settings* this) { this->columns[i].modes = xCalloc(sizes[i], sizeof(int)); this->columns[i].len = sizes[i]; } - int r = 0; - if (this->cpuCount > 8) { + if (initialCpuCount > 8) { this->columns[0].names[0] = xStrdup("LeftCPUs2"); this->columns[0].modes[0] = BAR_METERMODE; this->columns[1].names[r] = xStrdup("RightCPUs2"); this->columns[1].modes[r++] = BAR_METERMODE; - } else if (this->cpuCount > 4) { + } else if (initialCpuCount > 4) { this->columns[0].names[0] = xStrdup("LeftCPUs"); this->columns[0].modes[0] = BAR_METERMODE; this->columns[1].names[r] = xStrdup("RightCPUs"); @@ -134,7 +82,6 @@ static void Settings_defaultMeters(Settings* this) { this->columns[0].modes[1] = BAR_METERMODE; this->columns[0].names[2] = xStrdup("Swap"); this->columns[0].modes[2] = BAR_METERMODE; - this->columns[1].names[r] = xStrdup("Tasks"); this->columns[1].modes[r++] = TEXT_METERMODE; this->columns[1].names[r] = xStrdup("LoadAverage"); @@ -145,15 +92,14 @@ static void Settings_defaultMeters(Settings* this) { static void readFields(ProcessField* fields, int* flags, const char* line) { char* trim = String_trim(line); - int nIds; - char** ids = String_split(trim, ' ', &nIds); + char** ids = String_split(trim, ' ', NULL); free(trim); int i, j; *flags = 0; for (j = 0, i = 0; i < Platform_numberOfFields && ids[i]; i++) { // This "+1" is for compatibility with the older enum format. int id = atoi(ids[i]) + 1; - if (id > 0 && Process_fields[id].name && id < Platform_numberOfFields) { + if (id > 0 && id < Platform_numberOfFields && Process_fields[id].name) { fields[j] = id; *flags |= Process_fields[id].flags; j++; @@ -163,15 +109,14 @@ static void readFields(ProcessField* fields, int* flags, const char* line) { String_freeArray(ids); } -static bool Settings_read(Settings* this, const char* fileName) { +static bool Settings_read(Settings* this, const char* fileName, int initialCpuCount) { FILE* fd; - CRT_dropPrivileges(); fd = fopen(fileName, "r"); CRT_restorePrivileges(); if (!fd) return false; - + bool didReadMeters = false; bool didReadFields = false; for (;;) { @@ -179,7 +124,7 @@ static bool Settings_read(Settings* this, const char* fileName) { if (!line) { break; } - int nOptions; + size_t nOptions; char** option = String_split(line, '=', &nOptions); free (line); if (nOptions < 2) { @@ -196,8 +141,6 @@ static bool Settings_read(Settings* this, const char* fileName) { this->direction = atoi(option[1]); } else if (String_eq(option[0], "tree_view")) { this->treeView = atoi(option[1]); - } else if (String_eq(option[0], "hide_threads")) { - this->hideThreads = atoi(option[1]); } else if (String_eq(option[0], "hide_kernel_threads")) { this->hideKernelThreads = atoi(option[1]); } else if (String_eq(option[0], "hide_userland_threads")) { @@ -214,6 +157,10 @@ static bool Settings_read(Settings* this, const char* fileName) { this->highlightMegabytes = atoi(option[1]); } else if (String_eq(option[0], "highlight_threads")) { this->highlightThreads = atoi(option[1]); + } else if (String_eq(option[0], "highlight_changes")) { + this->highlightChanges = atoi(option[1]); + } else if (String_eq(option[0], "highlight_changes_delay_secs")) { + this->highlightDelaySecs = atoi(option[1]); } else if (String_eq(option[0], "header_margin")) { this->headerMargin = atoi(option[1]); } else if (String_eq(option[0], "expand_system_time")) { @@ -221,8 +168,15 @@ static bool Settings_read(Settings* this, const char* fileName) { this->detailedCPUTime = atoi(option[1]); } else if (String_eq(option[0], "detailed_cpu_time")) { this->detailedCPUTime = atoi(option[1]); + } else if (String_eq(option[0], "cpu_count_from_one")) { + this->countCPUsFromOne = atoi(option[1]); } else if (String_eq(option[0], "cpu_count_from_zero")) { - this->countCPUsFromZero = atoi(option[1]); + // old (inverted) naming also supported for backwards compatibility + this->countCPUsFromOne = !atoi(option[1]); + } else if (String_eq(option[0], "show_cpu_usage")) { + this->showCPUUsage = atoi(option[1]); + } else if (String_eq(option[0], "show_cpu_frequency")) { + this->showCPUFrequency = atoi(option[1]); } else if (String_eq(option[0], "update_process_names")) { this->updateProcessNames = atoi(option[1]); } else if (String_eq(option[0], "account_guest_in_cpu_meter")) { @@ -231,7 +185,11 @@ static bool Settings_read(Settings* this, const char* fileName) { this->delay = atoi(option[1]); } else if (String_eq(option[0], "color_scheme")) { this->colorScheme = atoi(option[1]); - if (this->colorScheme < 0 || this->colorScheme >= LAST_COLORSCHEME) this->colorScheme = 0; + if (this->colorScheme < 0 || this->colorScheme >= LAST_COLORSCHEME) { + this->colorScheme = 0; + } + } else if (String_eq(option[0], "enable_mouse")) { + this->enableMouse = atoi(option[1]); } else if (String_eq(option[0], "left_meters")) { Settings_readMeters(this, option[1], 0); didReadMeters = true; @@ -244,12 +202,16 @@ static bool Settings_read(Settings* this, const char* fileName) { } else if (String_eq(option[0], "right_meter_modes")) { Settings_readMeterModes(this, option[1], 1); didReadMeters = true; + #ifdef HAVE_LIBHWLOC + } else if (String_eq(option[0], "topology_affinity")) { + this->topologyAffinity = !!atoi(option[1]); + #endif } String_freeArray(option); } fclose(fd); if (!didReadMeters) { - Settings_defaultMeters(this); + Settings_defaultMeters(this, initialCpuCount); } return didReadFields; } @@ -259,7 +221,7 @@ static void writeFields(FILE* fd, ProcessField* fields, const char* name) { const char* sep = ""; for (int i = 0; fields[i]; i++) { // This "-1" is for compatibility with the older enum format. - fprintf(fd, "%s%d", sep, (int) fields[i]-1); + fprintf(fd, "%s%d", sep, (int) fields[i] - 1); sep = " "; } fprintf(fd, "\n"); @@ -297,9 +259,8 @@ bool Settings_write(Settings* this) { fprintf(fd, "# The parser is also very primitive, and not human-friendly.\n"); writeFields(fd, this->fields, "fields"); // This "-1" is for compatibility with the older enum format. - fprintf(fd, "sort_key=%d\n", (int) this->sortKey-1); + fprintf(fd, "sort_key=%d\n", (int) this->sortKey - 1); fprintf(fd, "sort_direction=%d\n", (int) this->direction); - fprintf(fd, "hide_threads=%d\n", (int) this->hideThreads); fprintf(fd, "hide_kernel_threads=%d\n", (int) this->hideKernelThreads); fprintf(fd, "hide_userland_threads=%d\n", (int) this->hideUserlandThreads); fprintf(fd, "shadow_other_users=%d\n", (int) this->shadowOtherUsers); @@ -308,29 +269,35 @@ bool Settings_write(Settings* this) { fprintf(fd, "highlight_base_name=%d\n", (int) this->highlightBaseName); fprintf(fd, "highlight_megabytes=%d\n", (int) this->highlightMegabytes); fprintf(fd, "highlight_threads=%d\n", (int) this->highlightThreads); + fprintf(fd, "highlight_changes=%d\n", (int) this->highlightChanges); + fprintf(fd, "highlight_changes_delay_secs=%d\n", (int) this->highlightDelaySecs); fprintf(fd, "tree_view=%d\n", (int) this->treeView); fprintf(fd, "header_margin=%d\n", (int) this->headerMargin); fprintf(fd, "detailed_cpu_time=%d\n", (int) this->detailedCPUTime); - fprintf(fd, "cpu_count_from_zero=%d\n", (int) this->countCPUsFromZero); + fprintf(fd, "cpu_count_from_one=%d\n", (int) this->countCPUsFromOne); + fprintf(fd, "show_cpu_usage=%d\n", (int) this->showCPUUsage); + fprintf(fd, "show_cpu_frequency=%d\n", (int) this->showCPUFrequency); fprintf(fd, "update_process_names=%d\n", (int) this->updateProcessNames); fprintf(fd, "account_guest_in_cpu_meter=%d\n", (int) this->accountGuestInCPUMeter); fprintf(fd, "color_scheme=%d\n", (int) this->colorScheme); + fprintf(fd, "enable_mouse=%d\n", (int) this->enableMouse); fprintf(fd, "delay=%d\n", (int) this->delay); fprintf(fd, "left_meters="); writeMeters(this, fd, 0); fprintf(fd, "left_meter_modes="); writeMeterModes(this, fd, 0); fprintf(fd, "right_meters="); writeMeters(this, fd, 1); fprintf(fd, "right_meter_modes="); writeMeterModes(this, fd, 1); + #ifdef HAVE_LIBHWLOC + fprintf(fd, "topology_affinity=%d\n", (int) this->topologyAffinity); + #endif fclose(fd); return true; } -Settings* Settings_new(int cpuCount) { - +Settings* Settings_new(int initialCpuCount) { Settings* this = xCalloc(1, sizeof(Settings)); this->sortKey = PERCENT_CPU; this->direction = 1; - this->hideThreads = false; this->shadowOtherUsers = false; this->showThreadNames = false; this->hideKernelThreads = false; @@ -339,13 +306,18 @@ Settings* Settings_new(int cpuCount) { this->highlightBaseName = false; this->highlightMegabytes = false; this->detailedCPUTime = false; - this->countCPUsFromZero = false; + this->countCPUsFromOne = false; + this->showCPUUsage = true; + this->showCPUFrequency = false; this->updateProcessNames = false; - this->cpuCount = cpuCount; this->showProgramPath = true; this->highlightThreads = true; - - this->fields = xCalloc(Platform_numberOfFields+1, sizeof(ProcessField)); + this->highlightChanges = false; + this->highlightDelaySecs = DEFAULT_HIGHLIGHT_SECS; + #ifdef HAVE_LIBHWLOC + this->topologyAffinity = false; + #endif + this->fields = xCalloc(Platform_numberOfFields + 1, sizeof(ProcessField)); // TODO: turn 'fields' into a Vector, // (and ProcessFields into proper objects). this->flags = 0; @@ -361,7 +333,9 @@ Settings* Settings_new(int cpuCount) { this->filename = xStrdup(rcfile); } else { const char* home = getenv("HOME"); - if (!home) home = ""; + if (!home) + home = ""; + const char* xdgConfigHome = getenv("XDG_CONFIG_HOME"); char* configDir = NULL; char* htopDir = NULL; @@ -375,7 +349,6 @@ Settings* Settings_new(int cpuCount) { htopDir = String_cat(home, "/.config/htop"); } legacyDotfile = String_cat(home, "/.htoprc"); - CRT_dropPrivileges(); (void) mkdir(configDir, 0700); (void) mkdir(htopDir, 0700); @@ -390,30 +363,32 @@ Settings* Settings_new(int cpuCount) { CRT_restorePrivileges(); } this->colorScheme = 0; + this->enableMouse = true; this->changed = false; this->delay = DEFAULT_DELAY; bool ok = false; if (legacyDotfile) { - ok = Settings_read(this, legacyDotfile); + ok = Settings_read(this, legacyDotfile, initialCpuCount); if (ok) { // Transition to new location and delete old configuration file - if (Settings_write(this)) + if (Settings_write(this)) { unlink(legacyDotfile); + } } free(legacyDotfile); } if (!ok) { - ok = Settings_read(this, this->filename); + ok = Settings_read(this, this->filename, initialCpuCount); } if (!ok) { this->changed = true; // TODO: how to get SYSCONFDIR correctly through Autoconf? char* systemSettings = String_cat(SYSCONFDIR, "/htoprc"); - ok = Settings_read(this, systemSettings); + ok = Settings_read(this, systemSettings, initialCpuCount); free(systemSettings); } if (!ok) { - Settings_defaultMeters(this); + Settings_defaultMeters(this, initialCpuCount); this->hideKernelThreads = true; this->highlightMegabytes = true; this->highlightThreads = true; @@ -423,8 +398,9 @@ Settings* Settings_new(int cpuCount) { } void Settings_invertSortOrder(Settings* this) { - if (this->direction == 1) + if (this->direction == 1) { this->direction = -1; - else + } else { this->direction = 1; + } } diff --git a/Settings.h b/Settings.h index d9dc0683c..93b98bd8a 100644 --- a/Settings.h +++ b/Settings.h @@ -1,19 +1,21 @@ -/* Do not edit this file. It was automatically generated. */ - #ifndef HEADER_Settings #define HEADER_Settings /* htop - Settings.h (C) 2004-2011 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ -#define DEFAULT_DELAY 15 +#include "config.h" // IWYU pragma: keep -#include "Process.h" #include +#include "Process.h" + + +#define DEFAULT_DELAY 15 + typedef struct { int len; char** names; @@ -22,7 +24,6 @@ typedef struct { typedef struct Settings_ { char* filename; - MeterColumnSettings columns[2]; ProcessField* fields; @@ -30,15 +31,15 @@ typedef struct Settings_ { int colorScheme; int delay; - int cpuCount; int direction; ProcessField sortKey; - bool countCPUsFromZero; + bool countCPUsFromOne; bool detailedCPUTime; + bool showCPUUsage; + bool showCPUFrequency; bool treeView; bool showProgramPath; - bool hideThreads; bool shadowOtherUsers; bool showThreadNames; bool hideKernelThreads; @@ -46,23 +47,26 @@ typedef struct Settings_ { bool highlightBaseName; bool highlightMegabytes; bool highlightThreads; + bool highlightChanges; + int highlightDelaySecs; bool updateProcessNames; bool accountGuestInCPUMeter; bool headerMargin; + bool enableMouse; + #ifdef HAVE_LIBHWLOC + bool topologyAffinity; + #endif bool changed; } Settings; -#ifndef Settings_cpuId -#define Settings_cpuId(settings, cpu) ((settings)->countCPUsFromZero ? (cpu) : (cpu)+1) -#endif - +#define Settings_cpuId(settings, cpu) ((settings)->countCPUsFromOne ? (cpu)+1 : (cpu)) void Settings_delete(Settings* this); bool Settings_write(Settings* this); -Settings* Settings_new(int cpuCount); +Settings* Settings_new(int initialCpuCount); void Settings_invertSortOrder(Settings* this); diff --git a/SignalsPanel.c b/SignalsPanel.c index 2bfbcbf2b..7937c5dc4 100644 --- a/SignalsPanel.c +++ b/SignalsPanel.c @@ -1,31 +1,22 @@ /* htop - SignalsPanel.c (C) 2004-2011 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ -#include "Panel.h" #include "SignalsPanel.h" -#include "Platform.h" -#include "ListItem.h" -#include "RichString.h" - -#include -#include #include +#include -#include - -/*{ - -typedef struct SignalItem_ { - const char* name; - int number; -} SignalItem; +#include "FunctionBar.h" +#include "ListItem.h" +#include "Object.h" +#include "Panel.h" +#include "Platform.h" +#include "XUtils.h" -}*/ Panel* SignalsPanel_new() { Panel* this = Panel_new(1, 1, 1, 1, true, Class(ListItem), FunctionBar_newEnterEsc("Send ", "Cancel ")); diff --git a/SignalsPanel.h b/SignalsPanel.h index da753546d..0a90b08e5 100644 --- a/SignalsPanel.h +++ b/SignalsPanel.h @@ -1,21 +1,19 @@ -/* Do not edit this file. It was automatically generated. */ - #ifndef HEADER_SignalsPanel #define HEADER_SignalsPanel /* htop - SignalsPanel.h (C) 2004-2011 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ +#include "Panel.h" typedef struct SignalItem_ { const char* name; int number; } SignalItem; - -Panel* SignalsPanel_new(); +Panel* SignalsPanel_new(void); #endif diff --git a/StringUtils.c b/StringUtils.c deleted file mode 100644 index 0578cdea4..000000000 --- a/StringUtils.c +++ /dev/null @@ -1,156 +0,0 @@ -/* -htop - StringUtils.c -(C) 2004-2011 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file -in the source distribution for its full text. -*/ - -#include "StringUtils.h" -#include "XAlloc.h" - -#include "config.h" - -#include -#include -#include - -/*{ -#include - -#define String_startsWith(s, match) (strncmp((s),(match),strlen(match)) == 0) -#define String_contains_i(s1, s2) (strcasestr(s1, s2) != NULL) -}*/ - -/* - * String_startsWith gives better performance if strlen(match) can be computed - * at compile time (e.g. when they are immutable string literals). :) - */ - -char* String_cat(const char* s1, const char* s2) { - int l1 = strlen(s1); - int l2 = strlen(s2); - char* out = xMalloc(l1 + l2 + 1); - strncpy(out, s1, l1); - strncpy(out+l1, s2, l2+1); - return out; -} - -char* String_trim(const char* in) { - while (in[0] == ' ' || in[0] == '\t' || in[0] == '\n') { - in++; - } - int len = strlen(in); - while (len > 0 && (in[len-1] == ' ' || in[len-1] == '\t' || in[len-1] == '\n')) { - len--; - } - char* out = xMalloc(len+1); - strncpy(out, in, len); - out[len] = '\0'; - return out; -} - -inline int String_eq(const char* s1, const char* s2) { - if (s1 == NULL || s2 == NULL) { - if (s1 == NULL && s2 == NULL) - return 1; - else - return 0; - } - return (strcmp(s1, s2) == 0); -} - -char** String_split(const char* s, char sep, int* n) { - *n = 0; - const int rate = 10; - char** out = xCalloc(rate, sizeof(char*)); - int ctr = 0; - int blocks = rate; - char* where; - while ((where = strchr(s, sep)) != NULL) { - int size = where - s; - char* token = xMalloc(size + 1); - strncpy(token, s, size); - token[size] = '\0'; - out[ctr] = token; - ctr++; - if (ctr == blocks) { - blocks += rate; - out = (char**) xRealloc(out, sizeof(char*) * blocks); - } - s += size + 1; - } - if (s[0] != '\0') { - int size = strlen(s); - char* token = xMalloc(size + 1); - strncpy(token, s, size + 1); - out[ctr] = token; - ctr++; - } - out = xRealloc(out, sizeof(char*) * (ctr + 1)); - out[ctr] = NULL; - *n = ctr; - return out; -} - -void String_freeArray(char** s) { - if (!s) { - return; - } - for (int i = 0; s[i] != NULL; i++) { - free(s[i]); - } - free(s); -} - -char* String_getToken(const char* line, const unsigned short int numMatch) { - const unsigned short int len = strlen(line); - char inWord = 0; - unsigned short int count = 0; - char match[50]; - - unsigned short int foundCount = 0; - - for (unsigned short int i = 0; i < len; i++) { - char lastState = inWord; - inWord = line[i] == ' ' ? 0:1; - - if (lastState == 0 && inWord == 1) - count++; - - if(inWord == 1){ - if (count == numMatch && line[i] != ' ' && line[i] != '\0' && line[i] != '\n' && line[i] != (char)EOF) { - match[foundCount] = line[i]; - foundCount++; - } - } - } - - match[foundCount] = '\0'; - return((char*)xStrdup(match)); -} - -char* String_readLine(FILE* fd) { - const int step = 1024; - int bufSize = step; - char* buffer = xMalloc(step + 1); - char* at = buffer; - for (;;) { - char* ok = fgets(at, step + 1, fd); - if (!ok) { - free(buffer); - return NULL; - } - char* newLine = strrchr(at, '\n'); - if (newLine) { - *newLine = '\0'; - return buffer; - } else { - if (feof(fd)) { - return buffer; - } - } - bufSize += step; - buffer = xRealloc(buffer, bufSize + 1); - at = buffer + bufSize - step; - } -} diff --git a/StringUtils.h b/StringUtils.h deleted file mode 100644 index d3378b38e..000000000 --- a/StringUtils.h +++ /dev/null @@ -1,36 +0,0 @@ -/* Do not edit this file. It was automatically generated. */ - -#ifndef HEADER_StringUtils -#define HEADER_StringUtils -/* -htop - StringUtils.h -(C) 2004-2011 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file -in the source distribution for its full text. -*/ - -#include - -#define String_startsWith(s, match) (strncmp((s),(match),strlen(match)) == 0) -#define String_contains_i(s1, s2) (strcasestr(s1, s2) != NULL) - -/* - * String_startsWith gives better performance if strlen(match) can be computed - * at compile time (e.g. when they are immutable string literals). :) - */ - -char* String_cat(const char* s1, const char* s2); - -char* String_trim(const char* in); - -extern int String_eq(const char* s1, const char* s2); - -char** String_split(const char* s, char sep, int* n); - -void String_freeArray(char** s); - -char* String_getToken(const char* line, const unsigned short int numMatch); - -char* String_readLine(FILE* fd); - -#endif diff --git a/SwapMeter.c b/SwapMeter.c index 1406d6fb0..9de7fa354 100644 --- a/SwapMeter.c +++ b/SwapMeter.c @@ -1,26 +1,19 @@ /* htop - SwapMeter.c (C) 2004-2011 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ #include "SwapMeter.h" #include "CRT.h" +#include "Object.h" #include "Platform.h" +#include "RichString.h" -#include -#include -#include -#include -#include -/*{ -#include "Meter.h" -}*/ - -int SwapMeter_attributes[] = { +static const int SwapMeter_attributes[] = { SWAP }; @@ -37,9 +30,9 @@ static void SwapMeter_updateValues(Meter* this, char* buffer, int size) { } } -static void SwapMeter_display(Object* cast, RichString* out) { +static void SwapMeter_display(const Object* cast, RichString* out) { char buffer[50]; - Meter* this = (Meter*)cast; + const Meter* this = (const Meter*)cast; RichString_write(out, CRT_colors[METER_TEXT], ":"); Meter_humanUnit(buffer, this->total, 50); RichString_append(out, CRT_colors[METER_VALUE], buffer); @@ -48,7 +41,7 @@ static void SwapMeter_display(Object* cast, RichString* out) { RichString_append(out, CRT_colors[METER_VALUE], buffer); } -MeterClass SwapMeter_class = { +const MeterClass SwapMeter_class = { .super = { .extends = Class(Meter), .delete = Meter_delete, diff --git a/SwapMeter.h b/SwapMeter.h index 2b57fe548..623a0364a 100644 --- a/SwapMeter.h +++ b/SwapMeter.h @@ -1,18 +1,14 @@ -/* Do not edit this file. It was automatically generated. */ - #ifndef HEADER_SwapMeter #define HEADER_SwapMeter /* htop - SwapMeter.h (C) 2004-2011 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ #include "Meter.h" -extern int SwapMeter_attributes[]; - -extern MeterClass SwapMeter_class; +extern const MeterClass SwapMeter_class; #endif diff --git a/TESTPLAN b/TESTPLAN index 8dc050104..7669485fb 100644 --- a/TESTPLAN +++ b/TESTPLAN @@ -4,47 +4,47 @@ Main screen: For all views, all modes: Mouse click header - nothing happens. - + Mouse click on ProcessList title bar - exit Tree view, update FunctionBar, title bar updates, sort by clicked field. *** FAILING: wrong FB update depending on mode; does not change sort in wip branch click on same entry - invert sort. click on another entry - sort another field. - + Mouse click on a process - select that process. - + for each entry in FunctionBar: Mouse click entry - perform action of associated key. - + In Normal mode, Sorted view: - + <+> or <-> - do nothing. - + - enter SortBy screen. - + In Normal mode, Tree view: select process - update F6 in FunctionBar if subtree is collapsed or expanded. - + , <+> or <-> - expand/collapse subtree. - + In Normal mode, either Sorted or Tree view: , - activate Search mode. - + , <\> - activate Filter mode. , <]> - as root only, decrease process NICE value. - + , <[> - increase process NICE value. - enter Affinity screen. - do nothing. - + - select process and all its children. - + , , , - do nothing. - + , , - enter Help screen. - on Linux, enter IOPriority screen. @@ -64,67 +64,67 @@ Main screen: - enter STrace screen. , - toggle between Tree and Sorted view, update F5 in FunctionBar, follow process - + - enter User screen. , , , , - do nothing. - + , - do nothing. - + , , - enter Setup screen. , - do nothing. - + - follow process. - do nothing. - + - toggle show/hide userland threads. - + - invert sort order. - + - do nothing. - + - toggle show/hide kernel threads. - do nothing. - enter Sorted view, update function bar, sort by MEM%. - + , - do nothing.

- enter Sorted view, update function bar, sort by CPU%. , - do nothing. - + - enter Sorted view, update function bar, sort by TIME. - + - untag all processes. - + , , , , - do nothing. - + <<>, <>>, <,>, <.> - enter SortBy screen. - + space - tag current process, move down cursor. numbers - incremental PID search. - + In Search mode: TODO - + In Filter mode: - + TODO Setup screen: TODO - + SortBy screen: TODO - + User screen: TODO @@ -136,7 +136,7 @@ Kill screen: Affinity screen: TODO - + Help screen: any key - back to Main screen. @@ -152,4 +152,3 @@ STrace screen: LSOF screen: TODO - diff --git a/TasksMeter.c b/TasksMeter.c index f56c86133..562cc8fc3 100644 --- a/TasksMeter.c +++ b/TasksMeter.c @@ -1,45 +1,50 @@ /* htop - TasksMeter.c (C) 2004-2011 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ #include "TasksMeter.h" -#include "Platform.h" #include "CRT.h" +#include "Macros.h" +#include "Object.h" +#include "ProcessList.h" +#include "RichString.h" +#include "Settings.h" +#include "XUtils.h" -/*{ -#include "Meter.h" -}*/ -int TasksMeter_attributes[] = { - CPU_KERNEL, PROCESS_THREAD, PROCESS, TASKS_RUNNING +static const int TasksMeter_attributes[] = { + CPU_SYSTEM, + PROCESS_THREAD, + PROCESS, + TASKS_RUNNING }; static void TasksMeter_updateValues(Meter* this, char* buffer, int len) { - ProcessList* pl = this->pl; + const ProcessList* pl = this->pl; this->values[0] = pl->kernelThreads; this->values[1] = pl->userlandThreads; this->values[2] = pl->totalTasks - pl->kernelThreads - pl->userlandThreads; - this->values[3] = MIN(pl->runningTasks, pl->cpuCount); + this->values[3] = MINIMUM(pl->runningTasks, pl->cpuCount); if (pl->totalTasks > this->total) { this->total = pl->totalTasks; } - if (this->pl->settings->hideKernelThreads) { + if (pl->settings->hideKernelThreads) { this->values[0] = 0; } xSnprintf(buffer, len, "%d/%d", (int) this->values[3], (int) this->total); } -static void TasksMeter_display(Object* cast, RichString* out) { - Meter* this = (Meter*)cast; - Settings* settings = this->pl->settings; +static void TasksMeter_display(const Object* cast, RichString* out) { + const Meter* this = (const Meter*)cast; + const Settings* settings = this->pl->settings; char buffer[20]; - + int processes = (int) this->values[2]; - + xSnprintf(buffer, sizeof(buffer), "%d", processes); RichString_write(out, CRT_colors[METER_VALUE], buffer); int threadValueColor = CRT_colors[METER_VALUE]; @@ -66,7 +71,7 @@ static void TasksMeter_display(Object* cast, RichString* out) { RichString_append(out, CRT_colors[METER_TEXT], " running"); } -MeterClass TasksMeter_class = { +const MeterClass TasksMeter_class = { .super = { .extends = Class(Meter), .delete = Meter_delete, @@ -76,7 +81,7 @@ MeterClass TasksMeter_class = { .defaultMode = TEXT_METERMODE, .maxItems = 4, .total = 100.0, - .attributes = TasksMeter_attributes, + .attributes = TasksMeter_attributes, .name = "Tasks", .uiName = "Task counter", .caption = "Tasks: " diff --git a/TasksMeter.h b/TasksMeter.h index a7a0db701..cecb40136 100644 --- a/TasksMeter.h +++ b/TasksMeter.h @@ -1,18 +1,14 @@ -/* Do not edit this file. It was automatically generated. */ - #ifndef HEADER_TasksMeter #define HEADER_TasksMeter /* htop - TasksMeter.h (C) 2004-2011 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ #include "Meter.h" -extern int TasksMeter_attributes[]; - -extern MeterClass TasksMeter_class; +extern const MeterClass TasksMeter_class; #endif diff --git a/TraceScreen.c b/TraceScreen.c index 91f71ae8b..1280b1e4c 100644 --- a/TraceScreen.c +++ b/TraceScreen.c @@ -1,47 +1,33 @@ /* htop - TraceScreen.c (C) 2005-2006 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ -#include "TraceScreen.h" +#include "config.h" // IWYU pragma: keep -#include "CRT.h" -#include "InfoScreen.h" -#include "ProcessList.h" -#include "ListItem.h" -#include "IncSet.h" -#include "StringUtils.h" -#include "FunctionBar.h" +#include "TraceScreen.h" +#include +#include +#include +#include #include -#include -#include #include -#include +#include #include -#include +#include #include -#include #include -#include -/*{ -#include "InfoScreen.h" - -typedef struct TraceScreen_ { - InfoScreen super; - bool tracing; - int fdpair[2]; - int child; - FILE* strace; - int fd_strace; - bool contLine; - bool follow; -} TraceScreen; +#include "CRT.h" +#include "FunctionBar.h" +#include "IncSet.h" +#include "Panel.h" +#include "ProvideCurses.h" +#include "XUtils.h" -}*/ static const char* const TraceScreenFunctions[] = {"Search ", "Filter ", "AutoScroll ", "Stop Tracing ", "Done ", NULL}; @@ -49,7 +35,7 @@ static const char* const TraceScreenKeys[] = {"F3", "F4", "F8", "F9", "Esc"}; static int TraceScreenEvents[] = {KEY_F(3), KEY_F(4), KEY_F(8), KEY_F(9), 27}; -InfoScreenClass TraceScreen_class = { +const InfoScreenClass TraceScreen_class = { .super = { .extends = Class(Object), .delete = TraceScreen_delete @@ -60,14 +46,13 @@ InfoScreenClass TraceScreen_class = { }; TraceScreen* TraceScreen_new(Process* process) { - TraceScreen* this = xMalloc(sizeof(TraceScreen)); + // This initializes all TraceScreen variables to "false" so only default = true ones need to be set below + TraceScreen* this = xCalloc(1, sizeof(TraceScreen)); Object_setClass(this, Class(TraceScreen)); this->tracing = true; - this->contLine = false; - this->follow = false; FunctionBar* fuBar = FunctionBar_new(TraceScreenFunctions, TraceScreenKeys, TraceScreenEvents); CRT_disableDelay(); - return (TraceScreen*) InfoScreen_init(&this->super, process, fuBar, LINES-2, ""); + return (TraceScreen*) InfoScreen_init(&this->super, process, fuBar, LINES - 2, ""); } void TraceScreen_delete(Object* cast) { @@ -75,10 +60,14 @@ void TraceScreen_delete(Object* cast) { if (this->child > 0) { kill(this->child, SIGTERM); waitpid(this->child, NULL, 0); + } + + if (this->strace) { fclose(this->strace); } + CRT_enableDelay(); - free(InfoScreen_done((InfoScreen*)cast)); + free(InfoScreen_done((InfoScreen*)this)); } void TraceScreen_draw(InfoScreen* this) { @@ -90,48 +79,81 @@ void TraceScreen_draw(InfoScreen* this) { } bool TraceScreen_forkTracer(TraceScreen* this) { - char buffer[1001]; - int error = pipe(this->fdpair); - if (error == -1) return false; - this->child = fork(); - if (this->child == -1) return false; - if (this->child == 0) { + int fdpair[2] = {0, 0}; + + if (pipe(fdpair) == -1) + return false; + + if (fcntl(fdpair[0], F_SETFL, O_NONBLOCK) < 0) + goto err; + + if (fcntl(fdpair[1], F_SETFL, O_NONBLOCK) < 0) + goto err; + + pid_t child = fork(); + if (child == -1) + goto err; + + if (child == 0) { + close(fdpair[0]); + + dup2(fdpair[1], STDOUT_FILENO); + dup2(fdpair[1], STDERR_FILENO); + close(fdpair[1]); + CRT_dropPrivileges(); - dup2(this->fdpair[1], STDERR_FILENO); - int ok = fcntl(this->fdpair[1], F_SETFL, O_NONBLOCK); - if (ok != -1) { - xSnprintf(buffer, sizeof(buffer), "%d", this->super.process->pid); - execlp("strace", "strace", "-s", "512", "-p", buffer, NULL); - } + + char buffer[32] = {0}; + xSnprintf(buffer, sizeof(buffer), "%d", this->super.process->pid); + execlp("strace", "strace", "-T", "-tt", "-s", "512", "-p", buffer, NULL); + + // Should never reach here, unless execlp fails ... const char* message = "Could not execute 'strace'. Please make sure it is available in your $PATH."; - ssize_t written = write(this->fdpair[1], message, strlen(message)); + ssize_t written = write(STDERR_FILENO, message, strlen(message)); (void) written; - exit(1); + + exit(127); } - int ok = fcntl(this->fdpair[0], F_SETFL, O_NONBLOCK); - if (ok == -1) return false; - this->strace = fdopen(this->fdpair[0], "r"); - this->fd_strace = fileno(this->strace); + + FILE* fd = fdopen(fdpair[0], "r"); + if (!fd) + goto err; + + close(fdpair[1]); + + this->child = child; + this->strace = fd; return true; + +err: + close(fdpair[1]); + close(fdpair[0]); + return false; } void TraceScreen_updateTrace(InfoScreen* super) { TraceScreen* this = (TraceScreen*) super; - char buffer[1001]; + char buffer[1025]; + + int fd_strace = fileno(this->strace); + assert(fd_strace != -1); + fd_set fds; FD_ZERO(&fds); // FD_SET(STDIN_FILENO, &fds); - FD_SET(this->fd_strace, &fds); - struct timeval tv; - tv.tv_sec = 0; tv.tv_usec = 500; - int ready = select(this->fd_strace+1, &fds, NULL, NULL, &tv); - int nread = 0; - if (ready > 0 && FD_ISSET(this->fd_strace, &fds)) - nread = fread(buffer, 1, 1000, this->strace); + FD_SET(fd_strace, &fds); + + struct timeval tv = { .tv_sec = 0, .tv_usec = 500 }; + int ready = select(fd_strace + 1, &fds, NULL, NULL, &tv); + + size_t nread = 0; + if (ready > 0 && FD_ISSET(fd_strace, &fds)) + nread = fread(buffer, 1, sizeof(buffer) - 1, this->strace); + if (nread && this->tracing) { - char* line = buffer; + const char* line = buffer; buffer[nread] = '\0'; - for (int i = 0; i < nread; i++) { + for (size_t i = 0; i < nread; i++) { if (buffer[i] == '\n') { buffer[i] = '\0'; if (this->contLine) { @@ -140,16 +162,17 @@ void TraceScreen_updateTrace(InfoScreen* super) { } else { InfoScreen_addLine(&this->super, line); } - line = buffer+i+1; + line = buffer + i + 1; } } - if (line < buffer+nread) { + if (line < buffer + nread) { InfoScreen_addLine(&this->super, line); buffer[nread] = '\0'; this->contLine = true; } - if (this->follow) - Panel_setSelected(this->super.display, Panel_size(this->super.display)-1); + if (this->follow) { + Panel_setSelected(this->super.display, Panel_size(this->super.display) - 1); + } } } diff --git a/TraceScreen.h b/TraceScreen.h index 8845c51aa..819204792 100644 --- a/TraceScreen.h +++ b/TraceScreen.h @@ -1,29 +1,32 @@ -/* Do not edit this file. It was automatically generated. */ - #ifndef HEADER_TraceScreen #define HEADER_TraceScreen /* htop - TraceScreen.h (C) 2005-2006 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ +#include +#include +#include + #include "InfoScreen.h" +#include "Object.h" +#include "Process.h" + typedef struct TraceScreen_ { InfoScreen super; bool tracing; - int fdpair[2]; - int child; + pid_t child; FILE* strace; - int fd_strace; bool contLine; bool follow; } TraceScreen; -extern InfoScreenClass TraceScreen_class; +extern const InfoScreenClass TraceScreen_class; TraceScreen* TraceScreen_new(Process* process); diff --git a/UptimeMeter.c b/UptimeMeter.c index 61f60905b..790702869 100644 --- a/UptimeMeter.c +++ b/UptimeMeter.c @@ -1,19 +1,19 @@ /* htop - UptimeMeter.c (C) 2004-2011 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ #include "UptimeMeter.h" -#include "Platform.h" + #include "CRT.h" +#include "Object.h" +#include "Platform.h" +#include "XUtils.h" -/*{ -#include "Meter.h" -}*/ -int UptimeMeter_attributes[] = { +static const int UptimeMeter_attributes[] = { UPTIME }; @@ -24,9 +24,9 @@ static void UptimeMeter_updateValues(Meter* this, char* buffer, int len) { return; } int seconds = totalseconds % 60; - int minutes = (totalseconds/60) % 60; - int hours = (totalseconds/3600) % 24; - int days = (totalseconds/86400); + int minutes = (totalseconds / 60) % 60; + int hours = (totalseconds / 3600) % 24; + int days = (totalseconds / 86400); this->values[0] = days; if (days > this->total) { this->total = days; @@ -44,7 +44,7 @@ static void UptimeMeter_updateValues(Meter* this, char* buffer, int len) { xSnprintf(buffer, len, "%s%02d:%02d:%02d", daysbuf, hours, minutes, seconds); } -MeterClass UptimeMeter_class = { +const MeterClass UptimeMeter_class = { .super = { .extends = Class(Meter), .delete = Meter_delete diff --git a/UptimeMeter.h b/UptimeMeter.h index fe0bbba94..49300bbb1 100644 --- a/UptimeMeter.h +++ b/UptimeMeter.h @@ -1,18 +1,14 @@ -/* Do not edit this file. It was automatically generated. */ - #ifndef HEADER_UptimeMeter #define HEADER_UptimeMeter /* htop - UptimeMeter.h (C) 2004-2011 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ #include "Meter.h" -extern int UptimeMeter_attributes[]; - -extern MeterClass UptimeMeter_class; +extern const MeterClass UptimeMeter_class; #endif diff --git a/UsersTable.c b/UsersTable.c index f383256a9..fdbfd68fb 100644 --- a/UsersTable.c +++ b/UsersTable.c @@ -1,35 +1,26 @@ /* htop - UsersTable.c (C) 2004-2011 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ -#include "UsersTable.h" -#include "XAlloc.h" +#include "config.h" // IWYU pragma: keep -#include "config.h" +#include "UsersTable.h" -#include -#include -#include #include -#include +#include +#include #include -#include -/*{ -#include "Hashtable.h" +#include "XUtils.h" -typedef struct UsersTable_ { - Hashtable* users; -} UsersTable; -}*/ UsersTable* UsersTable_new() { UsersTable* this; this = xMalloc(sizeof(UsersTable)); - this->users = Hashtable_new(20, true); + this->users = Hashtable_new(10, true); return this; } @@ -39,9 +30,9 @@ void UsersTable_delete(UsersTable* this) { } char* UsersTable_getRef(UsersTable* this, unsigned int uid) { - char* name = (char*) (Hashtable_get(this->users, uid)); + char* name = Hashtable_get(this->users, uid); if (name == NULL) { - struct passwd* userData = getpwuid(uid); + const struct passwd* userData = getpwuid(uid); if (userData != NULL) { name = xStrdup(userData->pw_name); Hashtable_put(this->users, uid, name); diff --git a/UsersTable.h b/UsersTable.h index 93ece0dcd..0cac7dc4b 100644 --- a/UsersTable.h +++ b/UsersTable.h @@ -1,11 +1,9 @@ -/* Do not edit this file. It was automatically generated. */ - #ifndef HEADER_UsersTable #define HEADER_UsersTable /* htop - UsersTable.h (C) 2004-2011 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ @@ -15,12 +13,12 @@ typedef struct UsersTable_ { Hashtable* users; } UsersTable; -UsersTable* UsersTable_new(); +UsersTable* UsersTable_new(void); void UsersTable_delete(UsersTable* this); char* UsersTable_getRef(UsersTable* this, unsigned int uid); -extern void UsersTable_foreach(UsersTable* this, Hashtable_PairFunction f, void* userData); +void UsersTable_foreach(UsersTable* this, Hashtable_PairFunction f, void* userData); #endif diff --git a/Vector.c b/Vector.c index 6eb91ae69..721ebdd35 100644 --- a/Vector.c +++ b/Vector.c @@ -1,7 +1,7 @@ /* htop - Vector.c (C) 2004-2011 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ @@ -10,33 +10,18 @@ in the source distribution for its full text. #include #include #include -#include -/*{ -#include "Object.h" +#include "XUtils.h" -#define swap(a_,x_,y_) do{ void* tmp_ = a_[x_]; a_[x_] = a_[y_]; a_[y_] = tmp_; }while(0) -#ifndef DEFAULT_SIZE -#define DEFAULT_SIZE -1 -#endif - -typedef struct Vector_ { - Object **array; - ObjectClass* type; - int arraySize; - int growthRate; - int items; - bool owner; -} Vector; - -}*/ - -Vector* Vector_new(ObjectClass* type, bool owner, int size) { +Vector* Vector_new(const ObjectClass* type, bool owner, int size) { Vector* this; - if (size == DEFAULT_SIZE) + if (size == DEFAULT_SIZE) { size = 10; + } + + assert(size > 0); this = xMalloc(sizeof(Vector)); this->growthRate = size; this->array = (Object**) xCalloc(size, sizeof(Object*)); @@ -49,39 +34,56 @@ Vector* Vector_new(ObjectClass* type, bool owner, int size) { void Vector_delete(Vector* this) { if (this->owner) { - for (int i = 0; i < this->items; i++) - if (this->array[i]) + for (int i = 0; i < this->items; i++) { + if (this->array[i]) { Object_delete(this->array[i]); + } + } } free(this->array); free(this); } -#ifdef DEBUG +#ifndef NDEBUG -static inline bool Vector_isConsistent(Vector* this) { +static bool Vector_isConsistent(const Vector* this) { assert(this->items <= this->arraySize); if (this->owner) { - for (int i = 0; i < this->items; i++) - if (this->array[i] && !Object_isA(this->array[i], this->type)) + for (int i = 0; i < this->items; i++) { + if (this->array[i] && !Object_isA(this->array[i], this->type)) { return false; + } + } return true; } else { return true; } } -int Vector_count(Vector* this) { - int items = 0; +unsigned int Vector_count(const Vector* this) { + unsigned int items = 0; for (int i = 0; i < this->items; i++) { - if (this->array[i]) + if (this->array[i]) { items++; + } } - assert(items == this->items); + assert(items == (unsigned int)this->items); return items; } -#endif +Object* Vector_get(Vector* this, int idx) { + assert(idx >= 0 && idx < this->items); + assert(Vector_isConsistent(this)); + assert(this->array[idx]); + return this->array[idx]; +} + +int Vector_size(const Vector* this) { + assert(Vector_isConsistent(this)); + return this->items; +} + +#endif /* NDEBUG */ void Vector_prune(Vector* this) { assert(Vector_isConsistent(this)); @@ -95,14 +97,22 @@ void Vector_prune(Vector* this) { this->items = 0; } -static int comparisons = 0; +//static int comparisons = 0; + +static void swap(Object** array, int indexA, int indexB) { + assert(indexA >= 0); + assert(indexB >= 0); + Object* tmp = array[indexA]; + array[indexA] = array[indexB]; + array[indexB] = tmp; +} static int partition(Object** array, int left, int right, int pivotIndex, Object_Compare compare) { - void* pivotValue = array[pivotIndex]; + const Object* pivotValue = array[pivotIndex]; swap(array, pivotIndex, right); int storeIndex = left; for (int i = left; i < right; i++) { - comparisons++; + //comparisons++; if (compare(array[i], pivotValue) <= 0) { swap(array, i, storeIndex); storeIndex++; @@ -115,7 +125,8 @@ static int partition(Object** array, int left, int right, int pivotIndex, Object static void quickSort(Object** array, int left, int right, Object_Compare compare) { if (left >= right) return; - int pivotIndex = (left+right) / 2; + + int pivotIndex = (left + right) / 2; int pivotNewIndex = partition(array, left, right, pivotIndex, compare); quickSort(array, left, pivotNewIndex - 1, compare); quickSort(array, pivotNewIndex + 1, right, compare); @@ -145,24 +156,25 @@ static void combSort(Object** array, int left, int right, Object_Compare compare */ static void insertionSort(Object** array, int left, int right, Object_Compare compare) { - for (int i = left+1; i <= right; i++) { - void* t = array[i]; + for (int i = left + 1; i <= right; i++) { + Object* t = array[i]; int j = i - 1; while (j >= left) { - comparisons++; + //comparisons++; if (compare(array[j], t) <= 0) break; - array[j+1] = array[j]; + + array[j + 1] = array[j]; j--; } - array[j+1] = t; + array[j + 1] = t; } } -void Vector_quickSort(Vector* this) { - assert(this->type->compare); +void Vector_quickSortCustomCompare(Vector* this, Object_Compare compare) { + assert(compare); assert(Vector_isConsistent(this)); - quickSort(this->array, 0, this->items - 1, this->type->compare); + quickSort(this->array, 0, this->items - 1, compare); assert(Vector_isConsistent(this)); } @@ -195,11 +207,11 @@ void Vector_insert(Vector* this, int idx, void* data_) { if (idx > this->items) { idx = this->items; } - + Vector_checkArraySize(this); //assert(this->array[this->items] == NULL); - for (int i = this->items; i > idx; i--) { - this->array[i] = this->array[i-1]; + if (idx < this->items) { + memmove(&this->array[idx + 1], &this->array[idx], (this->items - idx) * sizeof(this->array[0])); } this->array[idx] = data; this->items++; @@ -210,10 +222,11 @@ Object* Vector_take(Vector* this, int idx) { assert(idx >= 0 && idx < this->items); assert(Vector_isConsistent(this)); Object* removed = this->array[idx]; - //assert (removed != NULL); + assert(removed); this->items--; - for (int i = idx; i < this->items; i++) - this->array[i] = this->array[i+1]; + if (idx < this->items) { + memmove(&this->array[idx], &this->array[idx + 1], (this->items - idx) * sizeof(this->array[0])); + } //this->array[this->items] = NULL; assert(Vector_isConsistent(this)); return removed; @@ -224,15 +237,18 @@ Object* Vector_remove(Vector* this, int idx) { if (this->owner) { Object_delete(removed); return NULL; - } else + } else { return removed; + } } void Vector_moveUp(Vector* this, int idx) { assert(idx >= 0 && idx < this->items); assert(Vector_isConsistent(this)); + if (idx == 0) return; + Object* temp = this->array[idx]; this->array[idx] = this->array[idx - 1]; this->array[idx - 1] = temp; @@ -241,8 +257,10 @@ void Vector_moveUp(Vector* this, int idx) { void Vector_moveDown(Vector* this, int idx) { assert(idx >= 0 && idx < this->items); assert(Vector_isConsistent(this)); + if (idx == this->items - 1) return; + Object* temp = this->array[idx]; this->array[idx] = this->array[idx + 1]; this->array[idx + 1] = temp; @@ -251,58 +269,29 @@ void Vector_moveDown(Vector* this, int idx) { void Vector_set(Vector* this, int idx, void* data_) { Object* data = data_; assert(idx >= 0); - assert(Object_isA((Object*)data, this->type)); + assert(Object_isA(data, this->type)); assert(Vector_isConsistent(this)); Vector_checkArraySize(this); if (idx >= this->items) { - this->items = idx+1; + this->items = idx + 1; } else { if (this->owner) { Object* removed = this->array[idx]; assert (removed != NULL); - if (this->owner) { - Object_delete(removed); - } + Object_delete(removed); } } this->array[idx] = data; assert(Vector_isConsistent(this)); } -#ifdef DEBUG - -inline Object* Vector_get(Vector* this, int idx) { - assert(idx < this->items); - assert(Vector_isConsistent(this)); - return this->array[idx]; -} - -#else - -#define Vector_get(v_, idx_) ((v_)->array[idx_]) - -#endif - -#ifdef DEBUG - -inline int Vector_size(Vector* this) { - assert(Vector_isConsistent(this)); - return this->items; -} - -#else - -#define Vector_size(v_) ((v_)->items) - -#endif - /* static void Vector_merge(Vector* this, Vector* v2) { int i; assert(Vector_isConsistent(this)); - + for (i = 0; i < v2->items; i++) Vector_add(this, v2->array[i]); v2->items = 0; @@ -314,24 +303,38 @@ static void Vector_merge(Vector* this, Vector* v2) { void Vector_add(Vector* this, void* data_) { Object* data = data_; - assert(Object_isA((Object*)data, this->type)); + assert(Object_isA(data, this->type)); assert(Vector_isConsistent(this)); int i = this->items; Vector_set(this, this->items, data); - assert(this->items == i+1); (void)(i); + assert(this->items == i + 1); (void)(i); assert(Vector_isConsistent(this)); } -inline int Vector_indexOf(Vector* this, void* search_, Object_Compare compare) { - Object* search = search_; - assert(Object_isA((Object*)search, this->type)); +int Vector_indexOf(const Vector* this, const void* search_, Object_Compare compare) { + const Object* search = search_; + assert(Object_isA(search, this->type)); assert(compare); assert(Vector_isConsistent(this)); for (int i = 0; i < this->items; i++) { - Object* o = (Object*)this->array[i]; + const Object* o = this->array[i]; assert(o); - if (compare(search, o) == 0) + if (compare(search, o) == 0) { return i; + } } return -1; } + +void Vector_splice(Vector* this, Vector* from) { + assert(Vector_isConsistent(this)); + assert(Vector_isConsistent(from)); + assert(!(this->owner && from->owner)); + + int olditems = this->items; + this->items += from->items; + Vector_checkArraySize(this); + for (int j = 0; j < from->items; j++) { + this->array[olditems + j] = from->array[j]; + } +} diff --git a/Vector.h b/Vector.h index 85939bf18..ec354b168 100644 --- a/Vector.h +++ b/Vector.h @@ -1,50 +1,40 @@ -/* Do not edit this file. It was automatically generated. */ - #ifndef HEADER_Vector #define HEADER_Vector /* htop - Vector.h (C) 2004-2011 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ #include "Object.h" -#define swap(a_,x_,y_) do{ void* tmp_ = a_[x_]; a_[x_] = a_[y_]; a_[y_] = tmp_; }while(0) +#include + #ifndef DEFAULT_SIZE -#define DEFAULT_SIZE -1 +#define DEFAULT_SIZE (-1) #endif typedef struct Vector_ { - Object **array; - ObjectClass* type; + Object** array; + const ObjectClass* type; int arraySize; int growthRate; int items; bool owner; } Vector; - -Vector* Vector_new(ObjectClass* type, bool owner, int size); +Vector* Vector_new(const ObjectClass* type, bool owner, int size); void Vector_delete(Vector* this); -#ifdef DEBUG - -int Vector_count(Vector* this); - -#endif - void Vector_prune(Vector* this); -// If I were to use only one sorting algorithm for both cases, it would probably be this one: -/* - -*/ - -void Vector_quickSort(Vector* this); +void Vector_quickSortCustomCompare(Vector* this, Object_Compare compare); +static inline void Vector_quickSort(Vector* this) { + Vector_quickSortCustomCompare(this, this->type->compare); +} void Vector_insertionSort(Vector* this); @@ -60,32 +50,28 @@ void Vector_moveDown(Vector* this, int idx); void Vector_set(Vector* this, int idx, void* data_); -#ifdef DEBUG +#ifndef NDEBUG -extern Object* Vector_get(Vector* this, int idx); +Object* Vector_get(Vector* this, int idx); +int Vector_size(const Vector* this); +unsigned int Vector_count(const Vector* this); -#else +#else /* NDEBUG */ -#define Vector_get(v_, idx_) ((v_)->array[idx_]) +static inline Object* Vector_get(Vector* this, int idx) { + return this->array[idx]; +} -#endif - -#ifdef DEBUG - -extern int Vector_size(Vector* this); +static inline int Vector_size(const Vector* this) { + return this->items; +} -#else - -#define Vector_size(v_) ((v_)->items) - -#endif - -/* - -*/ +#endif /* NDEBUG */ void Vector_add(Vector* this, void* data_); -extern int Vector_indexOf(Vector* this, void* search_, Object_Compare compare); +int Vector_indexOf(const Vector* this, const void* search_, Object_Compare compare); + +void Vector_splice(Vector* this, Vector* from); #endif diff --git a/XAlloc.c b/XAlloc.c deleted file mode 100644 index fbc642cc4..000000000 --- a/XAlloc.c +++ /dev/null @@ -1,71 +0,0 @@ - -#include "XAlloc.h" -#include "RichString.h" - -#ifndef _GNU_SOURCE -#define _GNU_SOURCE -#endif -#include -#include - -/*{ -#include -#include -#include -}*/ - -static inline void fail() { - curs_set(1); - endwin(); - err(1, NULL); -} - -void* xMalloc(size_t size) { - void* data = malloc(size); - if (!data && size > 0) { - fail(); - } - return data; -} - -void* xCalloc(size_t nmemb, size_t size) { - void* data = calloc(nmemb, size); - if (!data && nmemb > 0 && size > 0) { - fail(); - } - return data; -} - -void* xRealloc(void* ptr, size_t size) { - void* data = realloc(ptr, size); - if (!data && size > 0) { - fail(); - } - return data; -} - -#define xSnprintf(fmt, len, ...) do { int _l=len; int _n=snprintf(fmt, _l, __VA_ARGS__); if (!(_n > -1 && _n < _l)) { curs_set(1); endwin(); err(1, NULL); } } while(0) - -#undef xStrdup -#undef xStrdup_ -#ifdef NDEBUG -# define xStrdup_ xStrdup -#else -# define xStrdup(str_) (assert(str_), xStrdup_(str_)) -#endif - -#ifndef __has_attribute // Clang's macro -# define __has_attribute(x) 0 -#endif -#if (__has_attribute(nonnull) || \ - ((__GNUC__ > 3) || (__GNUC__ == 3 && __GNUC_MINOR__ >= 3))) -char* xStrdup_(const char* str) __attribute__((nonnull)); -#endif // __has_attribute(nonnull) || GNU C 3.3 or later - -char* xStrdup_(const char* str) { - char* data = strdup(str); - if (!data) { - fail(); - } - return data; -} diff --git a/XAlloc.h b/XAlloc.h deleted file mode 100644 index 2ebee1a8d..000000000 --- a/XAlloc.h +++ /dev/null @@ -1,40 +0,0 @@ -/* Do not edit this file. It was automatically generated. */ - -#ifndef HEADER_XAlloc -#define HEADER_XAlloc - -#ifndef _GNU_SOURCE -#define _GNU_SOURCE -#endif - -#include -#include -#include - -void* xMalloc(size_t size); - -void* xCalloc(size_t nmemb, size_t size); - -void* xRealloc(void* ptr, size_t size); - -#define xSnprintf(fmt, len, ...) do { int _l=len; int _n=snprintf(fmt, _l, __VA_ARGS__); if (!(_n > -1 && _n < _l)) { curs_set(1); endwin(); err(1, NULL); } } while(0) - -#undef xStrdup -#undef xStrdup_ -#ifdef NDEBUG -# define xStrdup_ xStrdup -#else -# define xStrdup(str_) (assert(str_), xStrdup_(str_)) -#endif - -#ifndef __has_attribute // Clang's macro -# define __has_attribute(x) 0 -#endif -#if (__has_attribute(nonnull) || \ - ((__GNUC__ > 3) || (__GNUC__ == 3 && __GNUC_MINOR__ >= 3))) -char* xStrdup_(const char* str) __attribute__((nonnull)); -#endif // __has_attribute(nonnull) || GNU C 3.3 or later - -char* xStrdup_(const char* str); - -#endif diff --git a/XUtils.c b/XUtils.c new file mode 100644 index 000000000..dcc8b390b --- /dev/null +++ b/XUtils.c @@ -0,0 +1,212 @@ +/* +htop - StringUtils.c +(C) 2004-2011 Hisham H. Muhammad +Released under the GNU GPLv2, see the COPYING file +in the source distribution for its full text. +*/ + +#include "config.h" // IWYU pragma: keep + +#include "XUtils.h" + +#include +#include +#include +#include +#include + +#include "CRT.h" + + +void fail() { + CRT_done(); + abort(); + + _exit(1); // Should never reach here +} + +void* xMalloc(size_t size) { + assert(size > 0); + void* data = malloc(size); + if (!data) { + fail(); + } + return data; +} + +void* xCalloc(size_t nmemb, size_t size) { + assert(nmemb > 0); + assert(size > 0); + void* data = calloc(nmemb, size); + if (!data) { + fail(); + } + return data; +} + +void* xRealloc(void* ptr, size_t size) { + assert(size > 0); + void* data = realloc(ptr, size); // deepcode ignore MemoryLeakOnRealloc: this goes to fail() + if (!data) { + free(ptr); + fail(); + } + return data; +} + +char* String_cat(const char* s1, const char* s2) { + const size_t l1 = strlen(s1); + const size_t l2 = strlen(s2); + char* out = xMalloc(l1 + l2 + 1); + memcpy(out, s1, l1); + memcpy(out + l1, s2, l2); + out[l1 + l2] = '\0'; + return out; +} + +char* String_trim(const char* in) { + while (in[0] == ' ' || in[0] == '\t' || in[0] == '\n') { + in++; + } + + size_t len = strlen(in); + while (len > 0 && (in[len - 1] == ' ' || in[len - 1] == '\t' || in[len - 1] == '\n')) { + len--; + } + + return xStrndup(in, len); +} + +char** String_split(const char* s, char sep, size_t* n) { + const unsigned int rate = 10; + char** out = xCalloc(rate, sizeof(char*)); + size_t ctr = 0; + unsigned int blocks = rate; + const char* where; + while ((where = strchr(s, sep)) != NULL) { + size_t size = (size_t)(where - s); + out[ctr] = xStrndup(s, size); + ctr++; + if (ctr == blocks) { + blocks += rate; + out = (char**) xRealloc(out, sizeof(char*) * blocks); + } + s += size + 1; + } + if (s[0] != '\0') { + out[ctr] = xStrdup(s); + ctr++; + } + out = xRealloc(out, sizeof(char*) * (ctr + 1)); + out[ctr] = NULL; + + if (n) + *n = ctr; + + return out; +} + +void String_freeArray(char** s) { + if (!s) { + return; + } + for (size_t i = 0; s[i] != NULL; i++) { + free(s[i]); + } + free(s); +} + +char* String_getToken(const char* line, const unsigned short int numMatch) { + const size_t len = strlen(line); + char inWord = 0; + unsigned short int count = 0; + char match[50]; + + size_t foundCount = 0; + + for (size_t i = 0; i < len; i++) { + char lastState = inWord; + inWord = line[i] == ' ' ? 0 : 1; + + if (lastState == 0 && inWord == 1) + count++; + + if (inWord == 1) { + if (count == numMatch && line[i] != ' ' && line[i] != '\0' && line[i] != '\n' && line[i] != (char)EOF) { + match[foundCount] = line[i]; + foundCount++; + } + } + } + + match[foundCount] = '\0'; + return xStrdup(match); +} + +char* String_readLine(FILE* fd) { + const unsigned int step = 1024; + unsigned int bufSize = step; + char* buffer = xMalloc(step + 1); + char* at = buffer; + for (;;) { + char* ok = fgets(at, step + 1, fd); + if (!ok) { + free(buffer); + return NULL; + } + char* newLine = strrchr(at, '\n'); + if (newLine) { + *newLine = '\0'; + return buffer; + } else { + if (feof(fd)) { + return buffer; + } + } + bufSize += step; + buffer = xRealloc(buffer, bufSize + 1); + at = buffer + bufSize - step; + } +} + +int xAsprintf(char** strp, const char* fmt, ...) { + va_list vl; + va_start(vl, fmt); + int r = vasprintf(strp, fmt, vl); + va_end(vl); + + if (r < 0 || !*strp) { + fail(); + } + + return r; +} + +int xSnprintf(char* buf, int len, const char* fmt, ...) { + va_list vl; + va_start(vl, fmt); + int n = vsnprintf(buf, len, fmt, vl); + va_end(vl); + + if (n < 0 || n >= len) { + fail(); + } + + return n; +} + +char* xStrdup(const char* str) { + char* data = strdup(str); + if (!data) { + fail(); + } + return data; +} + +char* xStrndup(const char* str, size_t len) { + char* data = strndup(str, len); + if (!data) { + fail(); + } + return data; +} diff --git a/XUtils.h b/XUtils.h new file mode 100644 index 000000000..a978a0eda --- /dev/null +++ b/XUtils.h @@ -0,0 +1,66 @@ +#ifndef HEADER_XUtils +#define HEADER_XUtils +/* +htop - StringUtils.h +(C) 2004-2011 Hisham H. Muhammad +Released under the GNU GPLv2, see the COPYING file +in the source distribution for its full text. +*/ + +#include "config.h" // IWYU pragma: keep + +#include +#include +#include // IWYU pragma: keep +#include // IWYU pragma: keep + +#include "Macros.h" + + +void fail(void) ATTR_NORETURN; + +void* xMalloc(size_t size); + +void* xCalloc(size_t nmemb, size_t size); + +void* xRealloc(void* ptr, size_t size); + +/* + * String_startsWith gives better performance if strlen(match) can be computed + * at compile time (e.g. when they are immutable string literals). :) + */ +static inline bool String_startsWith(const char* s, const char* match) { + return strncmp(s, match, strlen(match)) == 0; +} + +static inline bool String_contains_i(const char* s1, const char* s2) { + return strcasestr(s1, s2) != NULL; +} + +static inline bool String_eq(const char* s1, const char* s2) { + return strcmp(s1, s2) == 0; +} + +char* String_cat(const char* s1, const char* s2); + +char* String_trim(const char* in); + +char** String_split(const char* s, char sep, size_t* n); + +void String_freeArray(char** s); + +char* String_getToken(const char* line, unsigned short int numMatch); + +char* String_readLine(FILE* fd); + +ATTR_FORMAT(printf, 2, 3) +int xAsprintf(char** strp, const char* fmt, ...); + +ATTR_FORMAT(printf, 3, 4) +int xSnprintf(char* buf, int len, const char* fmt, ...); + +char* xStrdup(const char* str) ATTR_NONNULL; + +char* xStrndup(const char* str, size_t len) ATTR_NONNULL; + +#endif diff --git a/autogen.sh b/autogen.sh index c07e08544..fb38e5e27 100755 --- a/autogen.sh +++ b/autogen.sh @@ -1,3 +1,2 @@ #!/bin/sh -mkdir -p m4 -autoreconf --install --force +autoreconf --force --install --verbose -Wall diff --git a/configure.ac b/configure.ac index ffd8fedeb..f774c8efb 100644 --- a/configure.ac +++ b/configure.ac @@ -2,15 +2,11 @@ # Process this file with autoconf to produce a configure script. AC_PREREQ(2.65) -AC_INIT([htop],[2.2.0],[hisham@gobolinux.org]) - -SOURCE_DATE_EPOCH="${SOURCE_DATE_EPOCH:-$(date +%s)}" -year=$(date -u -d "@$SOURCE_DATE_EPOCH" "+%Y" 2>/dev/null || date -u -r "$SOURCE_DATE_EPOCH" "+%Y" 2>/dev/null || date -u "+%Y") +AC_INIT([htop],[3.0.3-dev],[htop@groups.io]) AC_CONFIG_SRCDIR([htop.c]) AC_CONFIG_AUX_DIR([.]) AC_CONFIG_HEADERS([config.h]) -AC_CONFIG_MACRO_DIR([m4]) # Required by hwloc scripts AC_CANONICAL_TARGET @@ -30,24 +26,31 @@ AC_USE_SYSTEM_EXTENSIONS case "$target_os" in linux*|gnu*) my_htop_platform=linux + AC_DEFINE([HTOP_LINUX], [], [Building for Linux]) ;; freebsd*|kfreebsd*) my_htop_platform=freebsd + AC_DEFINE([HTOP_FREEBSD], [], [Building for FreeBSD]) ;; openbsd*) my_htop_platform=openbsd + AC_DEFINE([HTOP_OPENBSD], [], [Building for OpenBSD]) ;; dragonfly*) my_htop_platform=dragonflybsd + AC_DEFINE([HTOP_DRAGONFLYBSD], [], [Building for DragonFlyBSD]) ;; darwin*) my_htop_platform=darwin + AC_DEFINE([HTOP_DARWIN], [], [Building for Darwin]) ;; solaris*) my_htop_platform=solaris + AC_DEFINE([HTOP_SOLARIS], [], [Building for Solaris]) ;; *) my_htop_platform=unsupported + AC_DEFINE([HTOP_UNSUPPORTED], [], [Building for an unsupported platform]) ;; esac @@ -69,7 +72,7 @@ dnl glibc 2.25 deprecates 'major' and 'minor' in and requires to dnl include . However the logic in AC_HEADER_MAJOR has not yet dnl been updated in Autoconf 2.69, so use a workaround: m4_version_prereq([2.70], [], -[if test "x$ac_cv_header_sys_mkdev_h" = xno; then +[if test "x$ac_cv_header_sys_mkdev_h" != xyes; then AC_CHECK_HEADER(sys/sysmacros.h, [AC_DEFINE(MAJOR_IN_SYSMACROS, 1, [Define to 1 if `major', `minor', and `makedev' are declared in .])]) fi]) @@ -84,57 +87,36 @@ AC_TYPE_UID_T # Checks for library functions and compiler features. # ---------------------------------------------------------------------- AC_FUNC_CLOSEDIR_VOID -AC_TYPE_SIGNAL AC_FUNC_STAT -AC_CHECK_FUNCS([memmove strncasecmp strstr strdup]) +AC_CHECK_FUNCS([fstatat memmove readlinkat strdup strncasecmp strstr]) + +AC_SEARCH_LIBS([dlopen], [dl dld]) save_cflags="${CFLAGS}" CFLAGS="${CFLAGS} -std=c99" -AC_MSG_CHECKING([whether gcc -std=c99 option works]) +AC_MSG_CHECKING([whether cc -std=c99 option works]) AC_COMPILE_IFELSE([AC_LANG_PROGRAM( [AC_INCLUDES_DEFAULT], [[char *a; a = strdup("foo"); int i = 0; i++; // C99]])], [AC_MSG_RESULT([yes])], - [AC_MSG_ERROR([htop is written in C99. A newer version of gcc is required.])]) + [AC_MSG_ERROR([htop is written in C99. A newer compiler is required.])]) CFLAGS="$save_cflags" -save_cflags="${CFLAGS}" -CFLAGS="$CFLAGS -Wextra" -AC_MSG_CHECKING([if compiler supports -Wextra]) -AC_COMPILE_IFELSE([AC_LANG_PROGRAM([], [])],[ - wextra_flag=-Wextra - AC_MSG_RESULT([yes]) -],[ - wextra_flag= - AC_MSG_RESULT([no]) -]) -CFLAGS="$save_cflags" -AC_SUBST(wextra_flag) +# Add -lexecinfo if needed +AC_SEARCH_LIBS([backtrace], [execinfo]) + +# Add -ldevstat if needed +AC_SEARCH_LIBS([devstat_checkversion], [devstat]) # Checks for features and flags. # ---------------------------------------------------------------------- PROCDIR=/proc -AC_ARG_ENABLE(proc, [AS_HELP_STRING([--enable-proc], [use Linux-compatible proc filesystem])], enable_proc="yes", enable_proc="no") -if test "x$enable_proc" = xyes; then - # An enabled proc assumes we're emulating Linux. - my_htop_platform=linux - AC_DEFINE(HAVE_PROC, 1, [Define if using a Linux-compatible proc filesystem.]) -fi - AC_ARG_WITH(proc, [AS_HELP_STRING([--with-proc=DIR], [Location of a Linux-compatible proc filesystem (default=/proc).])], - -if test -n "$withval"; then - AC_DEFINE_UNQUOTED(PROCDIR, "$withval", [Path of proc filesystem]) - PROCDIR="$withval" -fi, -AC_DEFINE(PROCDIR, "/proc", [Path of proc filesystem])) - -if test "x$cross_compiling" = xno; then - if test "x$enable_proc" = xyes; then - AC_CHECK_FILE($PROCDIR/stat,,AC_MSG_ERROR(Cannot find $PROCDIR/stat. Make sure you have a Linux-compatible /proc filesystem mounted. See the file README for help.)) - AC_CHECK_FILE($PROCDIR/meminfo,,AC_MSG_ERROR(Cannot find $PROCDIR/meminfo. Make sure you have a Linux-compatible /proc filesystem mounted. See the file README for help.)) - fi -fi + if test -n "$withval"; then + AC_DEFINE_UNQUOTED(PROCDIR, "$withval", [Path of proc filesystem]) + PROCDIR="$withval" + fi, + AC_DEFINE(PROCDIR, "/proc", [Path of proc filesystem])) AC_ARG_ENABLE(openvz, [AS_HELP_STRING([--enable-openvz], [enable OpenVZ support])], ,enable_openvz="no") if test "x$enable_openvz" = xyes; then @@ -202,6 +184,23 @@ m4_define([HTOP_CHECK_LIB], ], [$4]) ]) +dnl https://www.gnu.org/software/autoconf-archive/ax_check_compile_flag.html +AC_DEFUN([AX_CHECK_COMPILE_FLAG], +[AC_PREREQ(2.64)dnl for _AC_LANG_PREFIX and AS_VAR_IF +AS_VAR_PUSHDEF([CACHEVAR],[ax_cv_check_[]_AC_LANG_ABBREV[]flags_$4_$1])dnl +AC_CACHE_CHECK([whether _AC_LANG compiler accepts $1], CACHEVAR, [ + ax_check_save_flags=$[]_AC_LANG_PREFIX[]FLAGS + _AC_LANG_PREFIX[]FLAGS="$[]_AC_LANG_PREFIX[]FLAGS $4 $1" + AC_COMPILE_IFELSE([m4_default([$5],[AC_LANG_PROGRAM()])], + [AS_VAR_SET(CACHEVAR,[yes])], + [AS_VAR_SET(CACHEVAR,[no])]) + _AC_LANG_PREFIX[]FLAGS=$ax_check_save_flags]) +AS_VAR_IF(CACHEVAR,yes, + [m4_default([$2], :)], + [m4_default([$3], :)]) +AS_VAR_POPDEF([CACHEVAR])dnl +])dnl AX_CHECK_COMPILE_FLAGS + AC_ARG_ENABLE(unicode, [AS_HELP_STRING([--enable-unicode], [enable Unicode support])], ,enable_unicode="yes") if test "x$enable_unicode" = xyes; then HTOP_CHECK_SCRIPT([ncursesw6], [addnwstr], [HAVE_LIBNCURSESW], "ncursesw6-config", @@ -226,7 +225,7 @@ else HTOP_CHECK_LIB([ncurses], [refresh], [HAVE_LIBNCURSES], missing_libraries="$missing_libraries libncurses" )))) - + AC_CHECK_HEADERS([curses.h],[:], [AC_CHECK_HEADERS([ncurses/curses.h],[:], [AC_CHECK_HEADERS([ncurses/ncurses.h],[:], @@ -247,32 +246,43 @@ if test "$my_htop_platform" = "solaris"; then AC_CHECK_LIB([malloc], [free], [], [missing_libraries="$missing_libraries libmalloc"]) fi -AC_ARG_ENABLE(linux_affinity, [AS_HELP_STRING([--enable-linux-affinity], [enable Linux sched_setaffinity and sched_getaffinity for affinity support, disables hwloc])], ,enable_linux_affinity="yes") -if test "x$enable_linux_affinity" = xyes -a "x$cross_compiling" = xno; then - AC_MSG_CHECKING([for usable sched_setaffinity]) - AC_RUN_IFELSE([ - AC_LANG_PROGRAM([[ - #include - #include - static cpu_set_t cpuset; - ]], [[ - CPU_ZERO(&cpuset); - sched_setaffinity(0, sizeof(cpu_set_t), &cpuset); - if (errno == ENOSYS) return 1; - ]])], - [AC_MSG_RESULT([yes])], - [enable_linux_affinity=no - AC_MSG_RESULT([no])]) +AC_ARG_ENABLE(hwloc, [AS_HELP_STRING([--enable-hwloc], [enable hwloc support for CPU affinity, disables Linux affinity])],, enable_hwloc="no") +if test "x$enable_hwloc" = xyes +then + AC_CHECK_LIB([hwloc], [hwloc_get_proc_cpubind], [], [missing_libraries="$missing_libraries libhwloc"]) + AC_CHECK_HEADERS([hwloc.h],[:], [missing_headers="$missing_headers $ac_header"]) +fi + +AC_ARG_ENABLE(linux_affinity, [AS_HELP_STRING([--enable-linux-affinity], [enable Linux sched_setaffinity and sched_getaffinity for affinity support, conflicts with hwloc])], ,enable_linux_affinity="check") +if test "x$enable_linux_affinity" = xcheck; then + if test "x$enable_hwloc" = xyes; then + enable_linux_affinity=no + else + AC_MSG_CHECKING([for usable sched_setaffinity]) + AC_RUN_IFELSE([ + AC_LANG_PROGRAM([[ + #include + #include + static cpu_set_t cpuset; + ]], [[ + CPU_ZERO(&cpuset); + sched_setaffinity(0, sizeof(cpu_set_t), &cpuset); + if (errno == ENOSYS) return 1; + ]])], + [enable_linux_affinity=yes + AC_MSG_RESULT([yes])], + [enable_linux_affinity=no + AC_MSG_RESULT([no])], + [AC_MSG_RESULT([yes (assumed while cross compiling)])]) + fi fi if test "x$enable_linux_affinity" = xyes; then AC_DEFINE(HAVE_LINUX_AFFINITY, 1, [Define if Linux sched_setaffinity and sched_getaffinity are to be used.]) fi -AC_ARG_ENABLE(hwloc, [AS_HELP_STRING([--enable-hwloc], [enable hwloc support for CPU affinity])],, enable_hwloc="no") -if test "x$enable_hwloc" = xyes +if test "x$enable_linux_affinity" = xyes -a "x$enable_hwloc" = xyes then - AC_CHECK_LIB([hwloc], [hwloc_get_proc_cpubind], [], [missing_libraries="$missing_libraries libhwloc"]) - AC_CHECK_HEADERS([hwloc.h],[:], [missing_headers="$missing_headers $ac_header"]) + AC_MSG_ERROR([--enable-hwloc and --enable-linux-affinity are mutual exclusive. Specify at most one of them.]) fi AC_ARG_ENABLE(setuid, [AS_HELP_STRING([--enable-setuid], [enable setuid support for platforms that need it])],, enable_setuid="no") @@ -298,6 +308,33 @@ then ]) fi +AM_CFLAGS="\ + -Wall\ + -Wcast-align\ + -Wcast-qual\ + -Wextra\ + -Wfloat-equal\ + -Wmissing-format-attribute\ + -Wmissing-noreturn\ + -Wmissing-prototypes\ + -Wpointer-arith\ + -Wshadow\ + -Wstrict-prototypes\ + -Wundef\ + -Wunused\ + -Wwrite-strings" + +AX_CHECK_COMPILE_FLAG([-Wnull-dereference], [AM_CFLAGS="$AM_CFLAGS -Wnull-dereference"], , [-Werror]) + +AC_ARG_ENABLE([werror], [AS_HELP_STRING([--enable-werror], [Treat warnings as errors (default: warnings are not errors)])], [enable_werror="$enableval"], [enable_werror=no]) +AS_IF([test "x$enable_werror" = "xyes"], [AM_CFLAGS="$AM_CFLAGS -Werror"]) + +AC_SUBST([AM_CFLAGS]) + +AC_ARG_ENABLE([debug], [AS_HELP_STRING([--enable-debug], [Enable asserts (default: asserts are disabled)])], [enable_debug="$enableval"], [enable_debug=no]) +AS_IF([test "x$enable_debug" = "xyes"], , [AM_CPPFLAGS="$AM_CPPFLAGS -DNDEBUG"]) + +AC_SUBST([AM_CPPFLAGS]) # Bail out on errors. # ---------------------------------------------------------------------- @@ -308,7 +345,7 @@ if test ! -z "$missing_headers"; then AC_MSG_ERROR([missing headers: $missing_headers]) fi -AC_DEFINE_UNQUOTED(COPYRIGHT, "(C) 2004-$year Hisham Muhammad", [Copyright message.]) +AC_DEFINE_UNQUOTED(COPYRIGHT, "(C) 2004-2019 Hisham Muhammad. (C) 2020 htop dev team.", [Copyright message.]) # We're done, let's go! # ---------------------------------------------------------------------- @@ -336,3 +373,21 @@ then echo "****************************************************************" echo "" fi + +AC_MSG_RESULT([ + ${PACKAGE_NAME} ${VERSION} + + platform: $my_htop_platform + (Linux) proc directory: $PROCDIR + (Linux) openvz: $enable_openvz + (Linux) cgroup: $enable_cgroup + (Linux) vserver: $enable_vserver + (Linux) ancient vserver: $enable_ancient_vserver + (Linux) taskstats: $enable_taskstats + (Linux) affinity: $enable_linux_affinity + (Linux) delay accounting: $enable_delayacct + unicode: $enable_unicode + hwloc: $enable_hwloc + setuid: $enable_setuid + debug: $enable_debug +]) diff --git a/darwin/Battery.c b/darwin/Battery.c deleted file mode 100644 index d197c049b..000000000 --- a/darwin/Battery.c +++ /dev/null @@ -1,75 +0,0 @@ - -#include "BatteryMeter.h" - -#include -#include -#include -#include - -void Battery_getData(double* level, ACPresence* isOnAC) { - CFTypeRef power_sources = IOPSCopyPowerSourcesInfo(); - - *level = -1; - *isOnAC = AC_ERROR; - - if(NULL == power_sources) { - return; - } - - if(power_sources != NULL) { - CFArrayRef list = IOPSCopyPowerSourcesList(power_sources); - CFDictionaryRef battery = NULL; - int len; - - if(NULL == list) { - CFRelease(power_sources); - - return; - } - - len = CFArrayGetCount(list); - - /* Get the battery */ - for(int i = 0; i < len && battery == NULL; ++i) { - CFDictionaryRef candidate = IOPSGetPowerSourceDescription(power_sources, - CFArrayGetValueAtIndex(list, i)); /* GET rule */ - CFStringRef type; - - if(NULL != candidate) { - type = (CFStringRef) CFDictionaryGetValue(candidate, - CFSTR(kIOPSTransportTypeKey)); /* GET rule */ - - if(kCFCompareEqualTo == CFStringCompare(type, CFSTR(kIOPSInternalType), 0)) { - CFRetain(candidate); - battery = candidate; - } - } - } - - if(NULL != battery) { - /* Determine the AC state */ - CFStringRef power_state = CFDictionaryGetValue(battery, CFSTR(kIOPSPowerSourceStateKey)); - - *isOnAC = (kCFCompareEqualTo == CFStringCompare(power_state, CFSTR(kIOPSACPowerValue), 0)) - ? AC_PRESENT - : AC_ABSENT; - - /* Get the percentage remaining */ - double current; - double max; - - CFNumberGetValue(CFDictionaryGetValue(battery, CFSTR(kIOPSCurrentCapacityKey)), - kCFNumberDoubleType, ¤t); - CFNumberGetValue(CFDictionaryGetValue(battery, CFSTR(kIOPSMaxCapacityKey)), - kCFNumberDoubleType, &max); - - *level = (current * 100.0) / max; - - CFRelease(battery); - } - - CFRelease(list); - CFRelease(power_sources); - } -} - diff --git a/darwin/Battery.h b/darwin/Battery.h deleted file mode 100644 index 8dc0cef6d..000000000 --- a/darwin/Battery.h +++ /dev/null @@ -1,9 +0,0 @@ -/* Do not edit this file. It was automatically generated. */ - -#ifndef HEADER_Battery -#define HEADER_Battery - -void Battery_getData(double* level, ACPresence* isOnAC); - - -#endif diff --git a/darwin/DarwinCRT.c b/darwin/DarwinCRT.c deleted file mode 100644 index 51725984f..000000000 --- a/darwin/DarwinCRT.c +++ /dev/null @@ -1,35 +0,0 @@ -/* -htop - DarwinCRT.c -(C) 2014 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file -in the source distribution for its full text. -*/ - -#include "config.h" -#include "CRT.h" -#include -#include -#include - -void CRT_handleSIGSEGV(int sgn) { - (void) sgn; - CRT_done(); - #ifdef __APPLE__ - fprintf(stderr, "\n\nhtop " VERSION " aborting. Please report bug at http://hisham.hm/htop\n"); - #ifdef HAVE_EXECINFO_H - size_t size = backtrace(backtraceArray, sizeof(backtraceArray) / sizeof(void *)); - fprintf(stderr, "\n Please include in your report the following backtrace: \n"); - backtrace_symbols_fd(backtraceArray, size, 2); - fprintf(stderr, "\nAdditionally, in order to make the above backtrace useful,"); - fprintf(stderr, "\nplease also run the following command to generate a disassembly of your binary:"); - fprintf(stderr, "\n\n otool -tvV `which htop` > ~/htop.otool"); - fprintf(stderr, "\n\nand then attach the file ~/htop.otool to your bug report."); - fprintf(stderr, "\n\nThank you for helping to improve htop!\n\n"); - #endif - #else - fprintf(stderr, "\nUnfortunately, you seem to be using an unsupported platform!"); - fprintf(stderr, "\nPlease contact your platform package maintainer!\n\n"); - #endif - abort(); -} - diff --git a/darwin/DarwinCRT.h b/darwin/DarwinCRT.h deleted file mode 100644 index e1c22bbdc..000000000 --- a/darwin/DarwinCRT.h +++ /dev/null @@ -1,15 +0,0 @@ -/* Do not edit this file. It was automatically generated. */ - -#ifndef HEADER_DarwinCRT -#define HEADER_DarwinCRT -/* -htop - DarwinCRT.h -(C) 2014 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file -in the source distribution for its full text. -*/ - -void CRT_handleSIGSEGV(int sgn); - - -#endif diff --git a/darwin/DarwinProcess.c b/darwin/DarwinProcess.c index e1a16f9cf..c06ec4a6c 100644 --- a/darwin/DarwinProcess.c +++ b/darwin/DarwinProcess.c @@ -1,7 +1,7 @@ /* htop - DarwinProcess.c (C) 2015 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ @@ -15,23 +15,10 @@ in the source distribution for its full text. #include -/*{ -#include "Settings.h" -#include "DarwinProcessList.h" +#include "CRT.h" -#include -typedef struct DarwinProcess_ { - Process super; - - uint64_t utime; - uint64_t stime; - bool taskAccess; -} DarwinProcess; - -}*/ - -ProcessClass DarwinProcess_class = { +const ProcessClass DarwinProcess_class = { .super = { .extends = Class(Process), .display = Process_display, @@ -41,7 +28,7 @@ ProcessClass DarwinProcess_class = { .writeField = Process_writeField, }; -DarwinProcess* DarwinProcess_new(Settings* settings) { +Process* DarwinProcess_new(const Settings* settings) { DarwinProcess* this = xCalloc(1, sizeof(DarwinProcess)); Object_setClass(this, Class(DarwinProcess)); Process_init(&this->super, settings); @@ -50,7 +37,7 @@ DarwinProcess* DarwinProcess_new(Settings* settings) { this->stime = 0; this->taskAccess = true; - return this; + return &this->super; } void Process_delete(Object* cast) { @@ -60,20 +47,12 @@ void Process_delete(Object* cast) { free(this); } -bool Process_isThread(Process* this) { +bool Process_isThread(const Process* this) { (void) this; return false; } -void DarwinProcess_setStartTime(Process *proc, struct extern_proc *ep, time_t now) { - struct tm date; - - proc->starttime_ctime = ep->p_starttime.tv_sec; - (void) localtime_r(&proc->starttime_ctime, &date); - strftime(proc->starttime_show, 7, ((proc->starttime_ctime > now - 86400) ? "%R " : "%b%d "), &date); -} - -char *DarwinProcess_getCmdLine(struct kinfo_proc* k, int* basenameOffset) { +char* DarwinProcess_getCmdLine(struct kinfo_proc* k, int* basenameOffset) { /* This function is from the old Mac version of htop. Originally from ps? */ int mib[3], argmax, nargs, c = 0; size_t size; @@ -89,7 +68,7 @@ char *DarwinProcess_getCmdLine(struct kinfo_proc* k, int* basenameOffset) { } /* Allocate space for the arguments. */ - procargs = ( char * ) xMalloc( argmax ); + procargs = (char*)xMalloc(argmax); if ( procargs == NULL ) { goto ERROR_A; } @@ -179,12 +158,12 @@ char *DarwinProcess_getCmdLine(struct kinfo_proc* k, int* basenameOffset) { /* Convert previous '\0'. */ *np = ' '; } - /* Note location of current '\0'. */ - np = cp; - if (*basenameOffset == 0) { - *basenameOffset = cp - sp; - } - } + /* Note location of current '\0'. */ + np = cp; + if (*basenameOffset == 0) { + *basenameOffset = cp - sp; + } + } } /* @@ -212,12 +191,12 @@ char *DarwinProcess_getCmdLine(struct kinfo_proc* k, int* basenameOffset) { ERROR_A: retval = xStrdup(k->kp_proc.p_comm); *basenameOffset = strlen(retval); - + return retval; } -void DarwinProcess_setFromKInfoProc(Process *proc, struct kinfo_proc *ps, time_t now, bool exists) { - struct extern_proc *ep = &ps->kp_proc; +void DarwinProcess_setFromKInfoProc(Process* proc, struct kinfo_proc* ps, bool exists) { + struct extern_proc* ep = &ps->kp_proc; /* UNSET HERE : * @@ -233,7 +212,7 @@ void DarwinProcess_setFromKInfoProc(Process *proc, struct kinfo_proc *ps, time_t */ /* First, the "immutable" parts */ - if(!exists) { + if (!exists) { /* Set the PID/PGID/etc. */ proc->pid = ep->p_pid; proc->ppid = ps->kp_eproc.e_ppid; @@ -246,7 +225,9 @@ void DarwinProcess_setFromKInfoProc(Process *proc, struct kinfo_proc *ps, time_t /* e_tdev == -1 for "no device" */ proc->tty_nr = ps->kp_eproc.e_tdev & 0xff; /* TODO tty_nr is unsigned */ - DarwinProcess_setStartTime(proc, ep, now); + proc->starttime_ctime = ep->p_starttime.tv_sec; + Process_fillStarttimeBuffer(proc); + proc->comm = DarwinProcess_getCmdLine(ps, &(proc->basenameOffset)); } @@ -260,16 +241,16 @@ void DarwinProcess_setFromKInfoProc(Process *proc, struct kinfo_proc *ps, time_t proc->updated = true; } -void DarwinProcess_setFromLibprocPidinfo(DarwinProcess *proc, DarwinProcessList *dpl) { +void DarwinProcess_setFromLibprocPidinfo(DarwinProcess* proc, DarwinProcessList* dpl) { struct proc_taskinfo pti; - if(sizeof(pti) == proc_pidinfo(proc->super.pid, PROC_PIDTASKINFO, 0, &pti, sizeof(pti))) { - if(0 != proc->utime || 0 != proc->stime) { + if (sizeof(pti) == proc_pidinfo(proc->super.pid, PROC_PIDTASKINFO, 0, &pti, sizeof(pti))) { + if (0 != proc->utime || 0 != proc->stime) { uint64_t diff = (pti.pti_total_system - proc->stime) - + (pti.pti_total_user - proc->utime); + + (pti.pti_total_user - proc->utime); proc->super.percent_cpu = (double)diff * (double)dpl->super.cpuCount - / ((double)dpl->global_diff * 100000.0); + / ((double)dpl->global_diff * 100000.0); // fprintf(stderr, "%f %llu %llu %llu %llu %llu\n", proc->super.percent_cpu, // proc->stime, proc->utime, pti.pti_total_system, pti.pti_total_user, dpl->global_diff); @@ -278,11 +259,11 @@ void DarwinProcess_setFromLibprocPidinfo(DarwinProcess *proc, DarwinProcessList proc->super.time = (pti.pti_total_system + pti.pti_total_user) / 10000000; proc->super.nlwp = pti.pti_threadnum; - proc->super.m_size = pti.pti_virtual_size / 1024 / PAGE_SIZE_KB; - proc->super.m_resident = pti.pti_resident_size / 1024 / PAGE_SIZE_KB; + proc->super.m_size = pti.pti_virtual_size / CRT_pageSize; + proc->super.m_resident = pti.pti_resident_size / CRT_pageSize; proc->super.majflt = pti.pti_faults; proc->super.percent_mem = (double)pti.pti_resident_size * 100.0 - / (double)dpl->host_info.max_mem; + / (double)dpl->host_info.max_mem; proc->stime = pti.pti_total_system; proc->utime = pti.pti_total_user; @@ -299,14 +280,14 @@ void DarwinProcess_setFromLibprocPidinfo(DarwinProcess *proc, DarwinProcessList * Based on: http://stackoverflow.com/questions/6788274/ios-mac-cpu-usage-for-thread * and https://github.com/max-horvath/htop-osx/blob/e86692e869e30b0bc7264b3675d2a4014866ef46/ProcessList.c */ -void DarwinProcess_scanThreads(DarwinProcess *dp) { +void DarwinProcess_scanThreads(DarwinProcess* dp) { Process* proc = (Process*) dp; kern_return_t ret; - + if (!dp->taskAccess) { return; } - + if (proc->state == 'Z') { return; } @@ -317,7 +298,7 @@ void DarwinProcess_scanThreads(DarwinProcess *dp) { dp->taskAccess = false; return; } - + task_info_data_t tinfo; mach_msg_type_number_t task_info_count = TASK_INFO_MAX; ret = task_info(port, TASK_BASIC_INFO, (task_info_t) tinfo, &task_info_count); @@ -325,7 +306,7 @@ void DarwinProcess_scanThreads(DarwinProcess *dp) { dp->taskAccess = false; return; } - + thread_array_t thread_list; mach_msg_type_number_t thread_count; ret = task_threads(port, &thread_list, &thread_count); @@ -334,7 +315,7 @@ void DarwinProcess_scanThreads(DarwinProcess *dp) { mach_port_deallocate(mach_task_self(), port); return; } - + integer_t run_state = 999; for (unsigned int i = 0; i < thread_count; i++) { thread_info_data_t thinfo; diff --git a/darwin/DarwinProcess.h b/darwin/DarwinProcess.h index c2058e21c..627a6bcba 100644 --- a/darwin/DarwinProcess.h +++ b/darwin/DarwinProcess.h @@ -1,11 +1,9 @@ -/* Do not edit this file. It was automatically generated. */ - #ifndef HEADER_DarwinProcess #define HEADER_DarwinProcess /* htop - DarwinProcess.h (C) 2015 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ @@ -22,28 +20,25 @@ typedef struct DarwinProcess_ { bool taskAccess; } DarwinProcess; +extern const ProcessClass DarwinProcess_class; -extern ProcessClass DarwinProcess_class; - -DarwinProcess* DarwinProcess_new(Settings* settings); +Process* DarwinProcess_new(const Settings* settings); void Process_delete(Object* cast); -bool Process_isThread(Process* this); - -void DarwinProcess_setStartTime(Process *proc, struct extern_proc *ep, time_t now); +bool Process_isThread(const Process* this); -char *DarwinProcess_getCmdLine(struct kinfo_proc* k, int* basenameOffset); +char* DarwinProcess_getCmdLine(struct kinfo_proc* k, int* basenameOffset); -void DarwinProcess_setFromKInfoProc(Process *proc, struct kinfo_proc *ps, time_t now, bool exists); +void DarwinProcess_setFromKInfoProc(Process* proc, struct kinfo_proc* ps, bool exists); -void DarwinProcess_setFromLibprocPidinfo(DarwinProcess *proc, DarwinProcessList *dpl); +void DarwinProcess_setFromLibprocPidinfo(DarwinProcess* proc, DarwinProcessList* dpl); /* * Scan threads for process state information. * Based on: http://stackoverflow.com/questions/6788274/ios-mac-cpu-usage-for-thread * and https://github.com/max-horvath/htop-osx/blob/e86692e869e30b0bc7264b3675d2a4014866ef46/ProcessList.c */ -void DarwinProcess_scanThreads(DarwinProcess *dp); +void DarwinProcess_scanThreads(DarwinProcess* dp); #endif diff --git a/darwin/DarwinProcessList.c b/darwin/DarwinProcessList.c index 098844809..99f49d5c7 100644 --- a/darwin/DarwinProcessList.c +++ b/darwin/DarwinProcessList.c @@ -1,7 +1,7 @@ /* htop - DarwinProcessList.c (C) 2014 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ @@ -9,6 +9,8 @@ in the source distribution for its full text. #include "DarwinProcess.h" #include "DarwinProcessList.h" #include "CRT.h" +#include "zfs/ZfsArcStats.h" +#include "zfs/openzfs_sysctl.h" #include #include @@ -22,10 +24,10 @@ in the source distribution for its full text. #include struct kern { - short int version[3]; + short int version[3]; }; -void GetKernelVersion(struct kern *k) { +void GetKernelVersion(struct kern* k) { static short int version_[3] = {0}; if (!version_[0]) { // just in case it fails someday @@ -33,9 +35,11 @@ void GetKernelVersion(struct kern *k) { char str[256] = {0}; size_t size = sizeof(str); int ret = sysctlbyname("kern.osrelease", str, &size, NULL, 0); - if (ret == 0) sscanf(str, "%hd.%hd.%hd", &version_[0], &version_[1], &version_[2]); - } - memcpy(k->version, version_, sizeof(version_)); + if (ret == 0) { + sscanf(str, "%hd.%hd.%hd", &version_[0], &version_[1], &version_[2]); + } + } + memcpy(k->version, version_, sizeof(version_)); } /* compare the given os version with the one installed returns: @@ -44,98 +48,90 @@ positive value if less than the installed version negative value if more than the installed version */ int CompareKernelVersion(short int major, short int minor, short int component) { - struct kern k; - GetKernelVersion(&k); - if ( k.version[0] != major) return k.version[0] - major; - if ( k.version[1] != minor) return k.version[1] - minor; - if ( k.version[2] != component) return k.version[2] - component; - return 0; -} - -/*{ -#include "ProcessList.h" -#include -#include - -typedef struct DarwinProcessList_ { - ProcessList super; + struct kern k; + GetKernelVersion(&k); - host_basic_info_data_t host_info; - vm_statistics_data_t vm_stats; - processor_cpu_load_info_t prev_load; - processor_cpu_load_info_t curr_load; - uint64_t kernel_threads; - uint64_t user_threads; - uint64_t global_diff; -} DarwinProcessList; + if (k.version[0] != major) { + return k.version[0] - major; + } + if (k.version[1] != minor) { + return k.version[1] - minor; + } + if (k.version[2] != component) { + return k.version[2] - component; + } -}*/ + return 0; +} -void ProcessList_getHostInfo(host_basic_info_data_t *p) { +void ProcessList_getHostInfo(host_basic_info_data_t* p) { mach_msg_type_number_t info_size = HOST_BASIC_INFO_COUNT; - if(0 != host_info(mach_host_self(), HOST_BASIC_INFO, (host_info_t)p, &info_size)) { - CRT_fatalError("Unable to retrieve host info\n"); + if (0 != host_info(mach_host_self(), HOST_BASIC_INFO, (host_info_t)p, &info_size)) { + CRT_fatalError("Unable to retrieve host info\n"); } } -void ProcessList_freeCPULoadInfo(processor_cpu_load_info_t *p) { - if(NULL != p && NULL != *p) { - if(0 != munmap(*p, vm_page_size)) { - CRT_fatalError("Unable to free old CPU load information\n"); - } - *p = NULL; +void ProcessList_freeCPULoadInfo(processor_cpu_load_info_t* p) { + if (NULL != p && NULL != *p) { + if (0 != munmap(*p, vm_page_size)) { + CRT_fatalError("Unable to free old CPU load information\n"); + } + *p = NULL; } } -unsigned ProcessList_allocateCPULoadInfo(processor_cpu_load_info_t *p) { +unsigned ProcessList_allocateCPULoadInfo(processor_cpu_load_info_t* p) { mach_msg_type_number_t info_size = sizeof(processor_cpu_load_info_t); unsigned cpu_count; // TODO Improving the accuracy of the load counts woule help a lot. - if(0 != host_processor_info(mach_host_self(), PROCESSOR_CPU_LOAD_INFO, &cpu_count, (processor_info_array_t *)p, &info_size)) { - CRT_fatalError("Unable to retrieve CPU info\n"); + if (0 != host_processor_info(mach_host_self(), PROCESSOR_CPU_LOAD_INFO, &cpu_count, (processor_info_array_t*)p, &info_size)) { + CRT_fatalError("Unable to retrieve CPU info\n"); } return cpu_count; } void ProcessList_getVMStats(vm_statistics_t p) { - mach_msg_type_number_t info_size = HOST_VM_INFO_COUNT; + mach_msg_type_number_t info_size = HOST_VM_INFO_COUNT; - if (host_statistics(mach_host_self(), HOST_VM_INFO, (host_info_t)p, &info_size) != 0) - CRT_fatalError("Unable to retrieve VM statistics\n"); + if (host_statistics(mach_host_self(), HOST_VM_INFO, (host_info_t)p, &info_size) != 0) { + CRT_fatalError("Unable to retrieve VM statistics\n"); + } } -struct kinfo_proc *ProcessList_getKInfoProcs(size_t *count) { +struct kinfo_proc* ProcessList_getKInfoProcs(size_t* count) { int mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_ALL, 0 }; - struct kinfo_proc *processes = NULL; + struct kinfo_proc* processes = NULL; /* Note the two calls to sysctl(). One to get length and one to get the * data. This -does- mean that the second call could end up with a missing * process entry or two. */ *count = 0; - if (sysctl(mib, 4, NULL, count, NULL, 0) < 0) + if (sysctl(mib, 4, NULL, count, NULL, 0) < 0) { CRT_fatalError("Unable to get size of kproc_infos"); + } processes = xMalloc(*count); - if (processes == NULL) + if (processes == NULL) { CRT_fatalError("Out of memory for kproc_infos"); + } - if (sysctl(mib, 4, processes, count, NULL, 0) < 0) + if (sysctl(mib, 4, processes, count, NULL, 0) < 0) { CRT_fatalError("Unable to get kinfo_procs"); + } *count = *count / sizeof(struct kinfo_proc); return processes; } - -ProcessList* ProcessList_new(UsersTable* usersTable, Hashtable* pidWhiteList, uid_t userId) { +ProcessList* ProcessList_new(UsersTable* usersTable, Hashtable* pidMatchList, uid_t userId) { DarwinProcessList* this = xCalloc(1, sizeof(DarwinProcessList)); - ProcessList_init(&this->super, Class(Process), usersTable, pidWhiteList, userId); + ProcessList_init(&this->super, Class(Process), usersTable, pidMatchList, userId); /* Initialize the CPU information */ this->super.cpuCount = ProcessList_allocateCPULoadInfo(&this->prev_load); @@ -145,6 +141,10 @@ ProcessList* ProcessList_new(UsersTable* usersTable, Hashtable* pidWhiteList, ui /* Initialize the VM statistics */ ProcessList_getVMStats(&this->vm_stats); + /* Initialize the ZFS kstats, if zfs.kext loaded */ + openzfs_sysctl_init(&this->zfs); + openzfs_sysctl_updateArcStats(&this->zfs); + this->super.kernelThreads = 0; this->super.userlandThreads = 0; this->super.totalTasks = 0; @@ -158,66 +158,69 @@ void ProcessList_delete(ProcessList* this) { free(this); } -void ProcessList_goThroughEntries(ProcessList* super) { - DarwinProcessList *dpl = (DarwinProcessList *)super; - bool preExisting = true; - struct kinfo_proc *ps; - size_t count; - DarwinProcess *proc; - struct timeval tv; - - gettimeofday(&tv, NULL); /* Start processing time */ - - /* Update the global data (CPU times and VM stats) */ - ProcessList_freeCPULoadInfo(&dpl->prev_load); - dpl->prev_load = dpl->curr_load; - ProcessList_allocateCPULoadInfo(&dpl->curr_load); - ProcessList_getVMStats(&dpl->vm_stats); - - /* Get the time difference */ - dpl->global_diff = 0; - for(int i = 0; i < dpl->super.cpuCount; ++i) { - for(size_t j = 0; j < CPU_STATE_MAX; ++j) { - dpl->global_diff += dpl->curr_load[i].cpu_ticks[j] - dpl->prev_load[i].cpu_ticks[j]; - } - } - - /* Clear the thread counts */ - super->kernelThreads = 0; - super->userlandThreads = 0; - super->totalTasks = 0; - super->runningTasks = 0; - - /* We use kinfo_procs for initial data since : - * - * 1) They always succeed. - * 2) The contain the basic information. - * - * We attempt to fill-in additional information with libproc. - */ - ps = ProcessList_getKInfoProcs(&count); - - for(size_t i = 0; i < count; ++i) { - proc = (DarwinProcess *)ProcessList_getProcess(super, ps[i].kp_proc.p_pid, &preExisting, (Process_New)DarwinProcess_new); - - DarwinProcess_setFromKInfoProc(&proc->super, &ps[i], tv.tv_sec, preExisting); - DarwinProcess_setFromLibprocPidinfo(proc, dpl); - - // Disabled for High Sierra due to bug in macOS High Sierra - bool isScanThreadSupported = ! ( CompareKernelVersion(17, 0, 0) >= 0 && CompareKernelVersion(17, 5, 0) < 0); - - if (isScanThreadSupported){ - DarwinProcess_scanThreads(proc); - } - - super->totalTasks += 1; - - if(!preExisting) { - proc->super.user = UsersTable_getRef(super->usersTable, proc->super.st_uid); - - ProcessList_add(super, &proc->super); - } - } - - free(ps); +void ProcessList_goThroughEntries(ProcessList* super, bool pauseProcessUpdate) { + DarwinProcessList* dpl = (DarwinProcessList*)super; + bool preExisting = true; + struct kinfo_proc* ps; + size_t count; + DarwinProcess* proc; + + /* Update the global data (CPU times and VM stats) */ + ProcessList_freeCPULoadInfo(&dpl->prev_load); + dpl->prev_load = dpl->curr_load; + ProcessList_allocateCPULoadInfo(&dpl->curr_load); + ProcessList_getVMStats(&dpl->vm_stats); + openzfs_sysctl_updateArcStats(&dpl->zfs); + + // in pause mode only gather global data for meters (CPU/memory/...) + if (pauseProcessUpdate) { + return; + } + + /* Get the time difference */ + dpl->global_diff = 0; + for (int i = 0; i < dpl->super.cpuCount; ++i) { + for (size_t j = 0; j < CPU_STATE_MAX; ++j) { + dpl->global_diff += dpl->curr_load[i].cpu_ticks[j] - dpl->prev_load[i].cpu_ticks[j]; + } + } + + /* Clear the thread counts */ + super->kernelThreads = 0; + super->userlandThreads = 0; + super->totalTasks = 0; + super->runningTasks = 0; + + /* We use kinfo_procs for initial data since : + * + * 1) They always succeed. + * 2) The contain the basic information. + * + * We attempt to fill-in additional information with libproc. + */ + ps = ProcessList_getKInfoProcs(&count); + + for (size_t i = 0; i < count; ++i) { + proc = (DarwinProcess*)ProcessList_getProcess(super, ps[i].kp_proc.p_pid, &preExisting, DarwinProcess_new); + + DarwinProcess_setFromKInfoProc(&proc->super, &ps[i], preExisting); + DarwinProcess_setFromLibprocPidinfo(proc, dpl); + + // Disabled for High Sierra due to bug in macOS High Sierra + bool isScanThreadSupported = ! ( CompareKernelVersion(17, 0, 0) >= 0 && CompareKernelVersion(17, 5, 0) < 0); + + if (isScanThreadSupported) { + DarwinProcess_scanThreads(proc); + } + + super->totalTasks += 1; + + if (!preExisting) { + proc->super.user = UsersTable_getRef(super->usersTable, proc->super.st_uid); + + ProcessList_add(super, &proc->super); + } + } + + free(ps); } diff --git a/darwin/DarwinProcessList.h b/darwin/DarwinProcessList.h index c216a8040..bdcbb183c 100644 --- a/darwin/DarwinProcessList.h +++ b/darwin/DarwinProcessList.h @@ -1,15 +1,25 @@ -/* Do not edit this file. It was automatically generated. */ - #ifndef HEADER_DarwinProcessList #define HEADER_DarwinProcessList /* htop - DarwinProcessList.h (C) 2014 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ +struct kern; + +void GetKernelVersion(struct kern* k); + +/* compare the given os version with the one installed returns: +0 if equals the installed version +positive value if less than the installed version +negative value if more than the installed version +*/ +int CompareKernelVersion(short int major, short int minor, short int component); + #include "ProcessList.h" +#include "zfs/ZfsArcStats.h" #include #include @@ -23,23 +33,24 @@ typedef struct DarwinProcessList_ { uint64_t kernel_threads; uint64_t user_threads; uint64_t global_diff; -} DarwinProcessList; + ZfsArcStats zfs; +} DarwinProcessList; -void ProcessList_getHostInfo(host_basic_info_data_t *p); +void ProcessList_getHostInfo(host_basic_info_data_t* p); -void ProcessList_freeCPULoadInfo(processor_cpu_load_info_t *p); +void ProcessList_freeCPULoadInfo(processor_cpu_load_info_t* p); -unsigned ProcessList_allocateCPULoadInfo(processor_cpu_load_info_t *p); +unsigned ProcessList_allocateCPULoadInfo(processor_cpu_load_info_t* p); void ProcessList_getVMStats(vm_statistics_t p); -struct kinfo_proc *ProcessList_getKInfoProcs(size_t *count); +struct kinfo_proc* ProcessList_getKInfoProcs(size_t* count); -ProcessList* ProcessList_new(UsersTable* usersTable, Hashtable* pidWhiteList, uid_t userId); +ProcessList* ProcessList_new(UsersTable* usersTable, Hashtable* pidMatchList, uid_t userId); void ProcessList_delete(ProcessList* this); -void ProcessList_goThroughEntries(ProcessList* super); +void ProcessList_goThroughEntries(ProcessList* super, bool pauseProcessUpdate); #endif diff --git a/darwin/Platform.c b/darwin/Platform.c index 1dce8b67a..9051de7c0 100644 --- a/darwin/Platform.c +++ b/darwin/Platform.c @@ -2,34 +2,34 @@ htop - darwin/Platform.c (C) 2014 Hisham H. Muhammad (C) 2015 David C. Hunt -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ #include "Platform.h" +#include "Macros.h" #include "CPUMeter.h" #include "MemoryMeter.h" #include "SwapMeter.h" #include "TasksMeter.h" #include "LoadAverageMeter.h" #include "ClockMeter.h" +#include "DateMeter.h" +#include "DateTimeMeter.h" #include "HostnameMeter.h" +#include "ProcessLocksScreen.h" #include "UptimeMeter.h" +#include "zfs/ZfsArcMeter.h" +#include "zfs/ZfsCompressedArcMeter.h" #include "DarwinProcessList.h" +#include #include -/*{ -#include "Action.h" -#include "SignalsPanel.h" -#include "CPUMeter.h" -#include "BatteryMeter.h" -#include "DarwinProcess.h" -}*/ - -#ifndef CLAMP -#define CLAMP(x,low,high) (((x)>(high))?(high):(((x)<(low))?(low):(x))) -#endif +#include +#include +#include +#include ProcessField Platform_defaultFields[] = { PID, USER, PRIORITY, NICE, M_SIZE, M_RESIDENT, STATE, PERCENT_CPU, PERCENT_MEM, TIME, COMM, 0 }; @@ -69,7 +69,7 @@ const SignalItem Platform_signals[] = { { .name = "31 SIGUSR2", .number = 31 }, }; -const unsigned int Platform_numberOfSignals = sizeof(Platform_signals)/sizeof(SignalItem); +const unsigned int Platform_numberOfSignals = ARRAYSIZE(Platform_signals); ProcessFieldData Process_fields[] = { [0] = { .name = "", .title = NULL, .description = NULL, .flags = 0, }, @@ -90,7 +90,7 @@ ProcessFieldData Process_fields[] = { [PROCESSOR] = { .name = "PROCESSOR", .title = "CPU ", .description = "Id of the CPU the process last executed on", .flags = 0, }, [M_SIZE] = { .name = "M_SIZE", .title = " VIRT ", .description = "Total program size in virtual memory", .flags = 0, }, [M_RESIDENT] = { .name = "M_RESIDENT", .title = " RES ", .description = "Resident set size, size of the text and data sections, plus stack usage", .flags = 0, }, - [ST_UID] = { .name = "ST_UID", .title = " UID ", .description = "User ID of the process owner", .flags = 0, }, + [ST_UID] = { .name = "ST_UID", .title = " UID ", .description = "User ID of the process owner", .flags = 0, }, [PERCENT_CPU] = { .name = "PERCENT_CPU", .title = "CPU% ", .description = "Percentage of the CPU time the process used in the last sampling", .flags = 0, }, [PERCENT_MEM] = { .name = "PERCENT_MEM", .title = "MEM% ", .description = "Percentage of the memory the process is using, based on resident memory size", .flags = 0, }, [USER] = { .name = "USER", .title = "USER ", .description = "Username of the process owner (or user ID if name cannot be determined)", .flags = 0, }, @@ -100,9 +100,11 @@ ProcessFieldData Process_fields[] = { [100] = { .name = "*** report bug! ***", .title = NULL, .description = NULL, .flags = 0, }, }; -MeterClass* Platform_meterTypes[] = { +const MeterClass* const Platform_meterTypes[] = { &CPUMeter_class, &ClockMeter_class, + &DateMeter_class, + &DateTimeMeter_class, &LoadAverageMeter_class, &LoadMeter_class, &MemoryMeter_class, @@ -113,10 +115,18 @@ MeterClass* Platform_meterTypes[] = { &UptimeMeter_class, &AllCPUsMeter_class, &AllCPUs2Meter_class, + &AllCPUs4Meter_class, + &AllCPUs8Meter_class, &LeftCPUsMeter_class, &RightCPUsMeter_class, &LeftCPUs2Meter_class, &RightCPUs2Meter_class, + &LeftCPUs4Meter_class, + &RightCPUs4Meter_class, + &LeftCPUs8Meter_class, + &RightCPUs8Meter_class, + &ZfsArcMeter_class, + &ZfsCompressedArcMeter_class, &BlankMeter_class, NULL }; @@ -144,7 +154,7 @@ int Platform_getUptime() { void Platform_getLoadAverage(double* one, double* five, double* fifteen) { double results[3]; - if(3 == getloadavg(results, 3)) { + if (3 == getloadavg(results, 3)) { *one = results[0]; *five = results[1]; *fifteen = results[2]; @@ -171,8 +181,8 @@ ProcessPidColumn Process_pidColumns[] = { }; static double Platform_setCPUAverageValues(Meter* mtr) { - DarwinProcessList *dpl = (DarwinProcessList *)mtr->pl; - int cpus = dpl->super.cpuCount; + const ProcessList* dpl = mtr->pl; + int cpus = dpl->cpuCount; double sumNice = 0.0; double sumNormal = 0.0; double sumKernel = 0.0; @@ -195,34 +205,36 @@ double Platform_setCPUValues(Meter* mtr, int cpu) { return Platform_setCPUAverageValues(mtr); } - DarwinProcessList *dpl = (DarwinProcessList *)mtr->pl; - processor_cpu_load_info_t prev = &dpl->prev_load[cpu-1]; - processor_cpu_load_info_t curr = &dpl->curr_load[cpu-1]; + const DarwinProcessList* dpl = (const DarwinProcessList*)mtr->pl; + const processor_cpu_load_info_t prev = &dpl->prev_load[cpu - 1]; + const processor_cpu_load_info_t curr = &dpl->curr_load[cpu - 1]; double total = 0; /* Take the sums */ - for(size_t i = 0; i < CPU_STATE_MAX; ++i) { + for (size_t i = 0; i < CPU_STATE_MAX; ++i) { total += (double)curr->cpu_ticks[i] - (double)prev->cpu_ticks[i]; } mtr->values[CPU_METER_NICE] - = ((double)curr->cpu_ticks[CPU_STATE_NICE] - (double)prev->cpu_ticks[CPU_STATE_NICE])* 100.0 / total; + = ((double)curr->cpu_ticks[CPU_STATE_NICE] - (double)prev->cpu_ticks[CPU_STATE_NICE]) * 100.0 / total; mtr->values[CPU_METER_NORMAL] - = ((double)curr->cpu_ticks[CPU_STATE_USER] - (double)prev->cpu_ticks[CPU_STATE_USER])* 100.0 / total; + = ((double)curr->cpu_ticks[CPU_STATE_USER] - (double)prev->cpu_ticks[CPU_STATE_USER]) * 100.0 / total; mtr->values[CPU_METER_KERNEL] - = ((double)curr->cpu_ticks[CPU_STATE_SYSTEM] - (double)prev->cpu_ticks[CPU_STATE_SYSTEM])* 100.0 / total; + = ((double)curr->cpu_ticks[CPU_STATE_SYSTEM] - (double)prev->cpu_ticks[CPU_STATE_SYSTEM]) * 100.0 / total; - Meter_setItems(mtr, 3); + mtr->curItems = 3; /* Convert to percent and return */ total = mtr->values[CPU_METER_NICE] + mtr->values[CPU_METER_NORMAL] + mtr->values[CPU_METER_KERNEL]; + mtr->values[CPU_METER_FREQUENCY] = NAN; + return CLAMP(total, 0.0, 100.0); } void Platform_setMemoryValues(Meter* mtr) { - DarwinProcessList *dpl = (DarwinProcessList *)mtr->pl; - vm_statistics_t vm = &dpl->vm_stats; + const DarwinProcessList* dpl = (const DarwinProcessList*)mtr->pl; + const struct vm_statistics* vm = &dpl->vm_stats; double page_K = (double)vm_page_size / (double)1024; mtr->total = dpl->host_info.max_mem / 1024; @@ -232,13 +244,25 @@ void Platform_setMemoryValues(Meter* mtr) { } void Platform_setSwapValues(Meter* mtr) { - int mib[2] = {CTL_VM, VM_SWAPUSAGE}; - struct xsw_usage swapused; - size_t swlen = sizeof(swapused); - sysctl(mib, 2, &swapused, &swlen, NULL, 0); + int mib[2] = {CTL_VM, VM_SWAPUSAGE}; + struct xsw_usage swapused; + size_t swlen = sizeof(swapused); + sysctl(mib, 2, &swapused, &swlen, NULL, 0); + + mtr->total = swapused.xsu_total / 1024; + mtr->values[0] = swapused.xsu_used / 1024; +} - mtr->total = swapused.xsu_total / 1024; - mtr->values[0] = swapused.xsu_used / 1024; +void Platform_setZfsArcValues(Meter* this) { + const DarwinProcessList* dpl = (const DarwinProcessList*) this->pl; + + ZfsArcMeter_readStats(this, &(dpl->zfs)); +} + +void Platform_setZfsCompressedArcValues(Meter* this) { + const DarwinProcessList* dpl = (const DarwinProcessList*) this->pl; + + ZfsCompressedArcMeter_readStats(this, &(dpl->zfs)); } char* Platform_getProcessEnv(pid_t pid) { @@ -256,33 +280,33 @@ char* Platform_getProcessEnv(pid_t pid) { mib[0] = CTL_KERN; mib[1] = KERN_PROCARGS2; mib[2] = pid; - size_t bufsz = argmax; + bufsz = argmax; if (sysctl(mib, 3, buf, &bufsz, 0, 0) == 0) { if (bufsz > sizeof(int)) { char *p = buf, *endp = buf + bufsz; - int argc = *(int*)p; + int argc = *(int*)(void*)p; p += sizeof(int); // skip exe - p = strchr(p, 0)+1; + p = strchr(p, 0) + 1; // skip padding - while(!*p && p < endp) + while (!*p && p < endp) ++p; // skip argv - for (; argc-- && p < endp; p = strrchr(p, 0)+1) + for (; argc-- && p < endp; p = strrchr(p, 0) + 1) ; // skip padding - while(!*p && p < endp) + while (!*p && p < endp) ++p; size_t size = endp - p; - env = xMalloc(size+2); + env = xMalloc(size + 2); memcpy(env, p, size); env[size] = 0; - env[size+1] = 0; + env[size + 1] = 0; } } free(buf); @@ -291,3 +315,96 @@ char* Platform_getProcessEnv(pid_t pid) { return env; } + +char* Platform_getInodeFilename(pid_t pid, ino_t inode) { + (void)pid; + (void)inode; + return NULL; +} + +FileLocks_ProcessData* Platform_getProcessLocks(pid_t pid) { + (void)pid; + return NULL; +} + +bool Platform_getDiskIO(DiskIOData* data) { + // TODO + (void)data; + return false; +} + +bool Platform_getNetworkIO(unsigned long int* bytesReceived, + unsigned long int* packetsReceived, + unsigned long int* bytesTransmitted, + unsigned long int* packetsTransmitted) { + // TODO + *bytesReceived = 0; + *packetsReceived = 0; + *bytesTransmitted = 0; + *packetsTransmitted = 0; + return false; +} + +void Platform_getBattery(double* level, ACPresence* isOnAC) { + CFTypeRef power_sources = IOPSCopyPowerSourcesInfo(); + + *level = NAN; + *isOnAC = AC_ERROR; + + if (NULL == power_sources) + return; + + CFArrayRef list = IOPSCopyPowerSourcesList(power_sources); + CFDictionaryRef battery = NULL; + int len; + + if (NULL == list) { + CFRelease(power_sources); + + return; + } + + len = CFArrayGetCount(list); + + /* Get the battery */ + for (int i = 0; i < len && battery == NULL; ++i) { + CFDictionaryRef candidate = IOPSGetPowerSourceDescription(power_sources, + CFArrayGetValueAtIndex(list, i)); /* GET rule */ + CFStringRef type; + + if (NULL != candidate) { + type = (CFStringRef) CFDictionaryGetValue(candidate, + CFSTR(kIOPSTransportTypeKey)); /* GET rule */ + + if (kCFCompareEqualTo == CFStringCompare(type, CFSTR(kIOPSInternalType), 0)) { + CFRetain(candidate); + battery = candidate; + } + } + } + + if (NULL != battery) { + /* Determine the AC state */ + CFStringRef power_state = CFDictionaryGetValue(battery, CFSTR(kIOPSPowerSourceStateKey)); + + *isOnAC = (kCFCompareEqualTo == CFStringCompare(power_state, CFSTR(kIOPSACPowerValue), 0)) + ? AC_PRESENT + : AC_ABSENT; + + /* Get the percentage remaining */ + double current; + double max; + + CFNumberGetValue(CFDictionaryGetValue(battery, CFSTR(kIOPSCurrentCapacityKey)), + kCFNumberDoubleType, ¤t); + CFNumberGetValue(CFDictionaryGetValue(battery, CFSTR(kIOPSMaxCapacityKey)), + kCFNumberDoubleType, &max); + + *level = (current * 100.0) / max; + + CFRelease(battery); + } + + CFRelease(list); + CFRelease(power_sources); +} diff --git a/darwin/Platform.h b/darwin/Platform.h index 1231217b1..40b7d7304 100644 --- a/darwin/Platform.h +++ b/darwin/Platform.h @@ -1,24 +1,24 @@ -/* Do not edit this file. It was automatically generated. */ - #ifndef HEADER_Platform #define HEADER_Platform /* htop - darwin/Platform.h (C) 2014 Hisham H. Muhammad (C) 2015 David C. Hunt -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ +#include +#include + #include "Action.h" -#include "SignalsPanel.h" -#include "CPUMeter.h" #include "BatteryMeter.h" +#include "CPUMeter.h" #include "DarwinProcess.h" +#include "DiskIOMeter.h" +#include "ProcessLocksScreen.h" +#include "SignalsPanel.h" -#ifndef CLAMP -#define CLAMP(x,low,high) (((x)>(high))?(high):(((x)<(low))?(low):(x))) -#endif extern ProcessField Platform_defaultFields[]; @@ -28,17 +28,17 @@ extern const unsigned int Platform_numberOfSignals; extern ProcessFieldData Process_fields[]; -extern MeterClass* Platform_meterTypes[]; +extern const MeterClass* const Platform_meterTypes[]; void Platform_setBindings(Htop_Action* keys); extern int Platform_numberOfFields; -int Platform_getUptime(); +int Platform_getUptime(void); void Platform_getLoadAverage(double* one, double* five, double* fifteen); -int Platform_getMaxPid(); +int Platform_getMaxPid(void); extern ProcessPidColumn Process_pidColumns[]; @@ -48,6 +48,23 @@ void Platform_setMemoryValues(Meter* mtr); void Platform_setSwapValues(Meter* mtr); +void Platform_setZfsArcValues(Meter* this); + +void Platform_setZfsCompressedArcValues(Meter* this); + char* Platform_getProcessEnv(pid_t pid); +char* Platform_getInodeFilename(pid_t pid, ino_t inode); + +FileLocks_ProcessData* Platform_getProcessLocks(pid_t pid); + +bool Platform_getDiskIO(DiskIOData* data); + +bool Platform_getNetworkIO(unsigned long int* bytesReceived, + unsigned long int* packetsReceived, + unsigned long int* bytesTransmitted, + unsigned long int* packetsTransmitted); + +void Platform_getBattery(double *percent, ACPresence *isOnAC); + #endif diff --git a/docs/images/screenshot.png b/docs/images/screenshot.png new file mode 100644 index 000000000..0ff3cfead Binary files /dev/null and b/docs/images/screenshot.png differ diff --git a/docs/styleguide.md b/docs/styleguide.md new file mode 100644 index 000000000..4c0ac1f55 --- /dev/null +++ b/docs/styleguide.md @@ -0,0 +1,185 @@ +htop coding style guide +======================= + +Naming conventions +------------------ + +Names are important to convey what all those things inside the project are for. +Filenames for source code traditionally used camel-case naming with the first letter written in uppercase. +The file extension is always lowercase. + +The only exception here is `htop.c` which is the main entrance point into the code. + +Folders for e.g. platform-specific code or complex features spawning multiple files are written in lowercase, e.g. `linux`, `freebsd`, `zfs`. + +Inside files, the naming somewhat depends on the context. +For functions names should include a camel-case prefix before the actual name, separated by an underscore. +While this prefix usually coincides with the module name, this is not required, yet strongly advised. +One important exception to this rule are the memory management and the string utility functions from `XUtils.h`. + +Variable names inside functions should be short and precise. +Using `i` for some loop counter is totally fine, using `someCounterValueForThisSimpleLoop` is not. +On the other hand, when you need to hold global storage try to keep this local to your module, i.e. declare such variables `static` within the C source file. +Only if your variable really needs to be visible for the whole project (which is really rare) it deserves a declaration in the header, marked `extern`. + +File content structure +---------------------- + +The content within each file is usually structured according to the following loose template: + +* Copyright declaration +* Inclusion of used headers +* Necessary data structures and forward declarations +* Static module-private function implementations +* Externally visible function implementations +* Externally visible constant structures (pseudo-OOP definitions) + +For header files header guards based on `#ifdef` should be used. +These header guards are historically placed **before** the Copyright declaration. +Stick to that for consistency please. + +Example: + +```c +#ifndef HEADER_FILENAME +#define HEADER_FILENAME +/* +htop - Filename.h +(C) 2020 htop dev team +Released under the GNU GPLv2, see the COPYING file +in the source distribution for its full text. +*/ +``` + +Import and use of headers +------------------------- + +Every file should import headers for all symbols it's using. +Thus when using a symbol from a header, even if that symbol is already imported by something else you use, you should declare an import for that header. +Doing so allows for easier restructuring of the code when things need to be moved around. +If you are unsure if all necessary headers are included you might use IWYU to tell you. + +The list of includes should be the first thing in the file, after the copyright comment and be followed by two blank lines. +The include list should be in the following order, with each group separated by one blank line: + +1. `include "config.h" // IWYU pragma: keep` if the global configuration + from automake&autoconfigure or any of the feature guards for C library headers + (like `__GNU_SOURCE`) are required, optional otherwise. Beware of the IWYU comment. +2. Accompanying module header file (for C source files only, missing inside headers) +3. List of used system headers (non-conditional includes) +4. List of used program headers +5. Conditionally included header files, system headers first + +The list of headers should be sorted with includes from subdirectories following after files inside their parent directory. +Thus `unistd.h` sorts before `sys/time.h`. + +Symbol Exports +-------------- + +Exports of symbols should be used sparingly. +Thus unless a function you write is intended to become public API of a module you should mark it as `static`. +If a function should be public API an appropriate declaration for that function has to be placed in the accompaying header file. + +Please avoid function-like macros, in particular when exporting them in a header file. +They have several downsides (re-evaluation of arguments, syntactic escapes, weak typing) for which usually a better alternative like an actual function exists. +Furthermore when using function-like `define`s you may need to mark certain headers for IWYU so tracking of used symbols works. + +Memory Management +----------------- + +When allocating memory make sure to free resources properly. +For allocation this project uses a set of tiny wrappers around the common functions `malloc`, `calloc` and `realloc` named `xMalloc`, `xCalloc` and `xRealloc`. +These functions check that memory allocation worked and error out on failure. + +Allocation functions assert the amount of memory requested is non-zero. +Trying to allocate 0 bytes of memory is an error. +Please use the explicit value `NULL` in this case and handle it in your code accordingly. + +Working with Strings +-------------------- + +It is strongly encouraged to use the functions starting with `String_` from `XUtils.h` for working with zero-terminated strings as these make the API easier to use and are intended to make the intent of your code easier to grasp. + +Thus instead of `!strcmp(foo, "foo")` it's preferred to use `String_eq(foo, "foo")` instead. +While sometimes a bit more to type, this helps a lot with making the code easier to follow. + +Styling the code +---------------- + +Now for the style details that can mostly be automated: Indentation, spacing and bracing. +While there is no definitve code style we use, a set of rules loosely enforced has evolved. + +Indentation in the code is done by three (3) spaces. No tabs are used. Ever. + +Before and after keywords should be a space, e.g. `if (condition)` and `do { … } while (condition);`. + +After opening and before closing braces a new line should be started. +Content of such encoded blocks should be indented one level further than their enclosing block. + +If a line of source code becomes too long, or when structuring it into multiple parts for clarity, the continuation line should be indented one more level than the first line it continues: + +```c +if (very_long_condition && + another_very_complex_expression && + something_else_to_check) { + // Code follows as normal ... +} else { + +} +``` + +While braces around single code statements are strongly encouraged, they are usually left out for single statements when only redirecting code flow: + +```c +if (termination condition) + return 42; +``` + +Control flow statements and the instruction making up their body should not be put on a single line, i.e. after the condition of an if statement a new line should be inserted and the body indented accordingly. +When an if statement uses more than just the true branch it should use braces for all statements that follow: + +```c +if (condition1) { + // Some code +} else if (condition2) { + // Some more code +} else { + // something else +} +``` + +While this code style isn't fully consistent in the existing code base it is strongly recommended that new code follows these rules. +Adapting surrounding code near places you need to touch is encouraged. +Try to separate such changes into a single, clean-up only commit to reduce noise while reviewing your changes. + +If you want to automate formatting your code, the following command gives you a good baseline of how it should look: + +```bash +astyle -r -j -xb -s3 -p -xg -c -k1 -W1 \*.c \*.h +``` + +Working with System APIs +------------------------ + +Please try to be considerate when using modern platform features. +While they usually provide quite a performance gain or make your life easier, it is benefitial if `htop` runs on rather ancient systems. +Thus when you want to use such features you should try to have an alternative available that works as a fallback. + +An example for this are functions like `fstatat` on Linux that extend the kernel API on modern systems. +But even though it has been around for over a decade you are asked to provide a POSIX alternative like emulating such calls by `fstat` if this is doable. +If an alternative can not be provided you should gracefully downgrade. That could make a feature that requires this shiny API unavailable on systems that lack support for that API. Make this case visually clear to the user. + +In general, code written for the project should be able to compile on any C99-compliant compiler. + +Writing documentation +--------------------- + +The primary user documentation should be the man file which you can find in `htop.1.in`. + +Additional documentation, like this file, should be written in gh-style markdown. +Make each sentence one line. +Markdown will combined these in output formats. +It does only insert a paragraph if you insert a blank line into the source file. +This way git can better diff and present the changes when documentation is altered. + +Documentation files reside in the `docs/` directory and have a `.md` extension. diff --git a/dragonflybsd/Battery.c b/dragonflybsd/Battery.c deleted file mode 100644 index f17efb5da..000000000 --- a/dragonflybsd/Battery.c +++ /dev/null @@ -1,26 +0,0 @@ -/* -htop - dragonflybsd/Battery.c -(C) 2015 Hisham H. Muhammad -(C) 2017 Diederik de Groot -Released under the GNU GPL, see the COPYING file -in the source distribution for its full text. -*/ - -#include "BatteryMeter.h" -#include - -void Battery_getData(double* level, ACPresence* isOnAC) { - int life; - size_t life_len = sizeof(life); - if (sysctlbyname("hw.acpi.battery.life", &life, &life_len, NULL, 0) == -1) - *level = -1; - else - *level = life; - - int acline; - size_t acline_len = sizeof(acline); - if (sysctlbyname("hw.acpi.acline", &acline, &acline_len, NULL, 0) == -1) - *isOnAC = AC_ERROR; - else - *isOnAC = acline == 0 ? AC_ABSENT : AC_PRESENT; -} diff --git a/dragonflybsd/Battery.h b/dragonflybsd/Battery.h deleted file mode 100644 index efb44a8eb..000000000 --- a/dragonflybsd/Battery.h +++ /dev/null @@ -1,15 +0,0 @@ -/* Do not edit this file. It was automatically generated. */ - -#ifndef HEADER_Battery -#define HEADER_Battery -/* -htop - dragonflybsd/Battery.h -(C) 2015 Hisham H. Muhammad -(C) 2017 Diederik de Groot -Released under the GNU GPL, see the COPYING file -in the source distribution for its full text. -*/ - -void Battery_getData(double* level, ACPresence* isOnAC); - -#endif diff --git a/dragonflybsd/DragonFlyBSDCRT.c b/dragonflybsd/DragonFlyBSDCRT.c deleted file mode 100644 index ba311856f..000000000 --- a/dragonflybsd/DragonFlyBSDCRT.c +++ /dev/null @@ -1,35 +0,0 @@ -/* -htop - dragonflybsd/DragonFlyBSDCRT.c -(C) 2014 Hisham H. Muhammad -(C) 2017 Diederik de Groot -Released under the GNU GPL, see the COPYING file -in the source distribution for its full text. -*/ - -#include "config.h" -#include "CRT.h" -#include -#include -#ifdef HAVE_EXECINFO_H -#include -#endif - -void CRT_handleSIGSEGV(int sgn) { - (void) sgn; - CRT_done(); - fprintf(stderr, "\n\nhtop " VERSION " aborting. Please report bug at http://hisham.hm/htop\n"); - #ifdef HAVE_EXECINFO_H - size_t size = backtrace(backtraceArray, sizeof(backtraceArray) / sizeof(void *)); - fprintf(stderr, "\n Please include in your report the following backtrace: \n"); - backtrace_symbols_fd(backtraceArray, size, 2); - fprintf(stderr, "\nAdditionally, in order to make the above backtrace useful,"); - fprintf(stderr, "\nplease also run the following command to generate a disassembly of your binary:"); - fprintf(stderr, "\n\n objdump -d `which htop` > ~/htop.objdump"); - fprintf(stderr, "\n\nand then attach the file ~/htop.objdump to your bug report."); - fprintf(stderr, "\n\nThank you for helping to improve htop!\n\n"); - #else - fprintf(stderr, "\nPlease contact your DragonFlyBSD package maintainer!\n\n"); - #endif - abort(); -} - diff --git a/dragonflybsd/DragonFlyBSDCRT.h b/dragonflybsd/DragonFlyBSDCRT.h deleted file mode 100644 index b934ac328..000000000 --- a/dragonflybsd/DragonFlyBSDCRT.h +++ /dev/null @@ -1,19 +0,0 @@ -/* Do not edit this file. It was automatically generated. */ - -#ifndef HEADER_DragonFlyBSDCRT -#define HEADER_DragonFlyBSDCRT -/* -htop - dragonflybsd/DragonFlyBSDCRT.h -(C) 2014 Hisham H. Muhammad -(C) 2017 Diederik de Groot -Released under the GNU GPL, see the COPYING file -in the source distribution for its full text. -*/ - -#ifdef HAVE_EXECINFO_H -#endif - -void CRT_handleSIGSEGV(int sgn); - - -#endif diff --git a/dragonflybsd/DragonFlyBSDProcess.c b/dragonflybsd/DragonFlyBSDProcess.c index dade106d0..4130e799d 100644 --- a/dragonflybsd/DragonFlyBSDProcess.c +++ b/dragonflybsd/DragonFlyBSDProcess.c @@ -2,7 +2,7 @@ htop - dragonflybsd/DragonFlyBSDProcess.c (C) 2015 Hisham H. Muhammad (C) 2017 Diederik de Groot -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ @@ -17,43 +17,15 @@ in the source distribution for its full text. #include #include -/*{ -typedef enum DragonFlyBSDProcessFields { - // Add platform-specific fields here, with ids >= 100 - JID = 100, - JAIL = 101, - LAST_PROCESSFIELD = 102, -} DragonFlyBSDProcessField; - - -typedef struct DragonFlyBSDProcess_ { - Process super; - int kernel; - int jid; - char* jname; -} DragonFlyBSDProcess; - - -#ifndef Process_isKernelThread -#define Process_isKernelThread(_process) (_process->kernel == 1) -#endif - -#ifndef Process_isUserlandThread -//#define Process_isUserlandThread(_process) (_process->pid != _process->tgid) -#define Process_isUserlandThread(_process) (_process->nlwp > 1) -#endif - -}*/ - -ProcessClass DragonFlyBSDProcess_class = { +const ProcessClass DragonFlyBSDProcess_class = { .super = { .extends = Class(Process), .display = Process_display, .delete = Process_delete, .compare = DragonFlyBSDProcess_compare }, - .writeField = (Process_WriteField) DragonFlyBSDProcess_writeField, + .writeField = DragonFlyBSDProcess_writeField, }; ProcessFieldData Process_fields[] = { @@ -74,8 +46,9 @@ ProcessFieldData Process_fields[] = { [PROCESSOR] = { .name = "PROCESSOR", .title = "CPU ", .description = "Id of the CPU the process last executed on", .flags = 0, }, [M_SIZE] = { .name = "M_SIZE", .title = " VIRT ", .description = "Total program size in virtual memory", .flags = 0, }, [M_RESIDENT] = { .name = "M_RESIDENT", .title = " RES ", .description = "Resident set size, size of the text and data sections, plus stack usage", .flags = 0, }, - [ST_UID] = { .name = "ST_UID", .title = " UID ", .description = "User ID of the process owner", .flags = 0, }, + [ST_UID] = { .name = "ST_UID", .title = " UID ", .description = "User ID of the process owner", .flags = 0, }, [PERCENT_CPU] = { .name = "PERCENT_CPU", .title = "CPU% ", .description = "Percentage of the CPU time the process used in the last sampling", .flags = 0, }, + [PERCENT_NORM_CPU] = { .name = "PERCENT_NORM_CPU", .title = "NCPU%", .description = "Normalized percentage of the CPU time the process used in the last sampling (normalized by cpu count)", .flags = 0, }, [PERCENT_MEM] = { .name = "PERCENT_MEM", .title = "MEM% ", .description = "Percentage of the memory the process is using, based on resident memory size", .flags = 0, }, [USER] = { .name = "USER", .title = "USER ", .description = "Username of the process owner (or user ID if name cannot be determined)", .flags = 0, }, [TIME] = { .name = "TIME", .title = " TIME+ ", .description = "Total time the process has spent in user and system time", .flags = 0, }, @@ -97,11 +70,11 @@ ProcessPidColumn Process_pidColumns[] = { { .id = 0, .label = NULL }, }; -DragonFlyBSDProcess* DragonFlyBSDProcess_new(Settings* settings) { +Process* DragonFlyBSDProcess_new(const Settings* settings) { DragonFlyBSDProcess* this = xCalloc(1, sizeof(DragonFlyBSDProcess)); Object_setClass(this, Class(DragonFlyBSDProcess)); Process_init(&this->super, settings); - return this; + return &this->super; } void Process_delete(Object* cast) { @@ -111,8 +84,8 @@ void Process_delete(Object* cast) { free(this); } -void DragonFlyBSDProcess_writeField(Process* this, RichString* str, ProcessField field) { - DragonFlyBSDProcess* fp = (DragonFlyBSDProcess*) this; +void DragonFlyBSDProcess_writeField(const Process* this, RichString* str, ProcessField field) { + const DragonFlyBSDProcess* fp = (const DragonFlyBSDProcess*) this; char buffer[256]; buffer[255] = '\0'; int attr = CRT_colors[DEFAULT_COLOR]; int n = sizeof(buffer) - 1; @@ -120,8 +93,8 @@ void DragonFlyBSDProcess_writeField(Process* this, RichString* str, ProcessField // add Platform-specific fields here case PID: xSnprintf(buffer, n, Process_pidFormat, (fp->kernel ? -1 : this->pid)); break; case JID: xSnprintf(buffer, n, Process_pidFormat, fp->jid); break; - case JAIL:{ - xSnprintf(buffer, n, "%-11s ", fp->jname); break; + case JAIL: { + xSnprintf(buffer, n, "%-11s ", fp->jname); if (buffer[11] != '\0') { buffer[11] = ' '; buffer[12] = '\0'; @@ -136,31 +109,34 @@ void DragonFlyBSDProcess_writeField(Process* this, RichString* str, ProcessField } long DragonFlyBSDProcess_compare(const void* v1, const void* v2) { - DragonFlyBSDProcess *p1, *p2; - Settings *settings = ((Process*)v1)->settings; + const DragonFlyBSDProcess *p1, *p2; + const Settings *settings = ((const Process*)v1)->settings; + if (settings->direction == 1) { - p1 = (DragonFlyBSDProcess*)v1; - p2 = (DragonFlyBSDProcess*)v2; + p1 = (const DragonFlyBSDProcess*)v1; + p2 = (const DragonFlyBSDProcess*)v2; } else { - p2 = (DragonFlyBSDProcess*)v1; - p1 = (DragonFlyBSDProcess*)v2; + p2 = (const DragonFlyBSDProcess*)v1; + p1 = (const DragonFlyBSDProcess*)v2; } + switch ((int) settings->sortKey) { // add Platform-specific fields here case JID: - return (p1->jid - p2->jid); + return SPACESHIP_NUMBER(p1->jid, p2->jid); case JAIL: - return strcmp(p1->jname ? p1->jname : "", p2->jname ? p2->jname : ""); + return SPACESHIP_NULLSTR(p1->jname, p2->jname); default: return Process_compare(v1, v2); } } -bool Process_isThread(Process* this) { - DragonFlyBSDProcess* fp = (DragonFlyBSDProcess*) this; +bool Process_isThread(const Process* this) { + const DragonFlyBSDProcess* fp = (const DragonFlyBSDProcess*) this; - if (fp->kernel == 1 ) + if (fp->kernel == 1 ) { return 1; - else + } else { return (Process_isUserlandThread(this)); + } } diff --git a/dragonflybsd/DragonFlyBSDProcess.h b/dragonflybsd/DragonFlyBSDProcess.h index 4a0f9a5a3..1befd9466 100644 --- a/dragonflybsd/DragonFlyBSDProcess.h +++ b/dragonflybsd/DragonFlyBSDProcess.h @@ -1,16 +1,13 @@ -/* Do not edit this file. It was automatically generated. */ - #ifndef HEADER_DragonFlyBSDProcess #define HEADER_DragonFlyBSDProcess /* htop - dragonflybsd/DragonFlyBSDProcess.h (C) 2015 Hisham H. Muhammad (C) 2017 Diederik de Groot -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ - typedef enum DragonFlyBSDProcessFields { // Add platform-specific fields here, with ids >= 100 JID = 100, @@ -18,7 +15,6 @@ typedef enum DragonFlyBSDProcessFields { LAST_PROCESSFIELD = 102, } DragonFlyBSDProcessField; - typedef struct DragonFlyBSDProcess_ { Process super; int kernel; @@ -26,31 +22,25 @@ typedef struct DragonFlyBSDProcess_ { char* jname; } DragonFlyBSDProcess; - -#ifndef Process_isKernelThread #define Process_isKernelThread(_process) (_process->kernel == 1) -#endif -#ifndef Process_isUserlandThread //#define Process_isUserlandThread(_process) (_process->pid != _process->tgid) #define Process_isUserlandThread(_process) (_process->nlwp > 1) -#endif - -extern ProcessClass DragonFlyBSDProcess_class; +extern const ProcessClass DragonFlyBSDProcess_class; extern ProcessFieldData Process_fields[]; extern ProcessPidColumn Process_pidColumns[]; -DragonFlyBSDProcess* DragonFlyBSDProcess_new(Settings* settings); +Process* DragonFlyBSDProcess_new(const Settings* settings); void Process_delete(Object* cast); -void DragonFlyBSDProcess_writeField(Process* this, RichString* str, ProcessField field); +void DragonFlyBSDProcess_writeField(const Process* this, RichString* str, ProcessField field); long DragonFlyBSDProcess_compare(const void* v1, const void* v2); -bool Process_isThread(Process* this); +bool Process_isThread(const Process* this); #endif diff --git a/dragonflybsd/DragonFlyBSDProcessList.c b/dragonflybsd/DragonFlyBSDProcessList.c index a41af8544..b66dc0e83 100644 --- a/dragonflybsd/DragonFlyBSDProcessList.c +++ b/dragonflybsd/DragonFlyBSDProcessList.c @@ -2,7 +2,7 @@ htop - DragonFlyBSDProcessList.c (C) 2014 Hisham H. Muhammad (C) 2017 Diederik de Groot -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ @@ -21,56 +21,9 @@ in the source distribution for its full text. #include #include -/*{ +#include "CRT.h" +#include "Macros.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include "Hashtable.h" -#include "DragonFlyBSDProcess.h" - -#define JAIL_ERRMSGLEN 1024 -char jail_errmsg[JAIL_ERRMSGLEN]; - -typedef struct CPUData_ { - - double userPercent; - double nicePercent; - double systemPercent; - double irqPercent; - double idlePercent; - double systemAllPercent; - -} CPUData; - -typedef struct DragonFlyBSDProcessList_ { - ProcessList super; - kvm_t* kd; - - unsigned long long int memWire; - unsigned long long int memActive; - unsigned long long int memInactive; - unsigned long long int memFree; - - CPUData* cpus; - - unsigned long *cp_time_o; - unsigned long *cp_time_n; - - unsigned long *cp_times_o; - unsigned long *cp_times_n; - - Hashtable *jails; -} DragonFlyBSDProcessList; - -}*/ - -#define _UNUSED_ __attribute__((unused)) static int MIB_hw_physmem[2]; static int MIB_vm_stats_vm_v_page_count[4]; @@ -89,12 +42,12 @@ static int MIB_kern_cp_time[2]; static int MIB_kern_cp_times[2]; static int kernelFScale; -ProcessList* ProcessList_new(UsersTable* usersTable, Hashtable* pidWhiteList, uid_t userId) { +ProcessList* ProcessList_new(UsersTable* usersTable, Hashtable* pidMatchList, uid_t userId) { size_t len; char errbuf[_POSIX2_LINE_MAX]; DragonFlyBSDProcessList* dfpl = xCalloc(1, sizeof(DragonFlyBSDProcessList)); ProcessList* pl = (ProcessList*) dfpl; - ProcessList_init(pl, Class(DragonFlyBSDProcess), usersTable, pidWhiteList, userId); + ProcessList_init(pl, Class(DragonFlyBSDProcess), usersTable, pidMatchList, userId); // physical memory in system: hw.physmem // physical page size: hw.pagesize @@ -103,8 +56,8 @@ ProcessList* ProcessList_new(UsersTable* usersTable, Hashtable* pidWhiteList, ui len = sizeof(pageSize); if (sysctlbyname("vm.stats.vm.v_page_size", &pageSize, &len, NULL, 0) == -1) { - pageSize = PAGE_SIZE; - pageSizeKb = PAGE_SIZE_KB; + pageSize = CRT_pageSize; + pageSizeKb = CRT_pageSizeKB; } else { pageSizeKb = pageSize / ONE_K; } @@ -145,13 +98,13 @@ ProcessList* ProcessList_new(UsersTable* usersTable, Hashtable* pidWhiteList, ui sysctl(MIB_kern_cp_times, 2, dfpl->cp_times_o, &len, NULL, 0); } - pl->cpuCount = MAX(cpus, 1); + pl->cpuCount = MAXIMUM(cpus, 1); if (cpus == 1 ) { - dfpl->cpus = xRealloc(dfpl->cpus, sizeof(CPUData)); + dfpl->cpus = xRealloc(dfpl->cpus, sizeof(CPUData)); } else { - // on smp we need CPUs + 1 to store averages too (as kernel kindly provides that as well) - dfpl->cpus = xRealloc(dfpl->cpus, (pl->cpuCount + 1) * sizeof(CPUData)); + // on smp we need CPUs + 1 to store averages too (as kernel kindly provides that as well) + dfpl->cpus = xRealloc(dfpl->cpus, (pl->cpuCount + 1) * sizeof(CPUData)); } len = sizeof(kernelFScale); @@ -170,7 +123,9 @@ ProcessList* ProcessList_new(UsersTable* usersTable, Hashtable* pidWhiteList, ui void ProcessList_delete(ProcessList* this) { const DragonFlyBSDProcessList* dfpl = (DragonFlyBSDProcessList*) this; - if (dfpl->kd) kvm_close(dfpl->kd); + if (dfpl->kd) { + kvm_close(dfpl->kd); + } if (dfpl->jails) { Hashtable_delete(dfpl->jails); @@ -196,8 +151,8 @@ static inline void DragonFlyBSDProcessList_scanCPUTime(ProcessList* pl) { size_t sizeof_cp_time_array; - unsigned long *cp_time_n; // old clicks state - unsigned long *cp_time_o; // current clicks state + unsigned long* cp_time_n; // old clicks state + unsigned long* cp_time_o; // current clicks state unsigned long cp_time_d[CPUSTATES]; double cp_time_p[CPUSTATES]; @@ -208,12 +163,12 @@ static inline void DragonFlyBSDProcessList_scanCPUTime(ProcessList* pl) { // get rest of CPUs if (cpus > 1) { - // on smp systems DragonFlyBSD kernel concats all CPU states into one long array in - // kern.cp_times sysctl OID - // we store averages in dfpl->cpus[0], and actual cores after that - maxcpu = cpus + 1; - sizeof_cp_time_array = cpus * sizeof(unsigned long) * CPUSTATES; - sysctl(MIB_kern_cp_times, 2, dfpl->cp_times_n, &sizeof_cp_time_array, NULL, 0); + // on smp systems DragonFlyBSD kernel concats all CPU states into one long array in + // kern.cp_times sysctl OID + // we store averages in dfpl->cpus[0], and actual cores after that + maxcpu = cpus + 1; + sizeof_cp_time_array = cpus * sizeof(unsigned long) * CPUSTATES; + sysctl(MIB_kern_cp_times, 2, dfpl->cp_times_n, &sizeof_cp_time_array, NULL, 0); } for (int i = 0; i < maxcpu; i++) { @@ -223,14 +178,14 @@ static inline void DragonFlyBSDProcessList_scanCPUTime(ProcessList* pl) { cp_time_o = dfpl->cp_time_o; } else { if (i == 0 ) { - // average - cp_time_n = dfpl->cp_time_n; - cp_time_o = dfpl->cp_time_o; + // average + cp_time_n = dfpl->cp_time_n; + cp_time_o = dfpl->cp_time_o; } else { - // specific smp cores - cp_times_offset = i - 1; - cp_time_n = dfpl->cp_times_n + (cp_times_offset * CPUSTATES); - cp_time_o = dfpl->cp_times_o + (cp_times_offset * CPUSTATES); + // specific smp cores + cp_times_offset = i - 1; + cp_time_n = dfpl->cp_times_n + (cp_times_offset * CPUSTATES); + cp_time_o = dfpl->cp_times_o + (cp_times_offset * CPUSTATES); } } @@ -239,19 +194,21 @@ static inline void DragonFlyBSDProcessList_scanCPUTime(ProcessList* pl) { unsigned long long total_n = 0; unsigned long long total_d = 0; for (int s = 0; s < CPUSTATES; s++) { - cp_time_d[s] = cp_time_n[s] - cp_time_o[s]; - total_o += cp_time_o[s]; - total_n += cp_time_n[s]; + cp_time_d[s] = cp_time_n[s] - cp_time_o[s]; + total_o += cp_time_o[s]; + total_n += cp_time_n[s]; } // totals total_d = total_n - total_o; - if (total_d < 1 ) total_d = 1; + if (total_d < 1 ) { + total_d = 1; + } // save current state as old and calc percentages for (int s = 0; s < CPUSTATES; ++s) { - cp_time_o[s] = cp_time_n[s]; - cp_time_p[s] = ((double)cp_time_d[s]) / ((double)total_d) * 100; + cp_time_o[s] = cp_time_n[s]; + cp_time_p[s] = ((double)cp_time_d[s]) / ((double)total_d) * 100; } CPUData* cpuData = &(dfpl->cpus[i]); @@ -303,7 +260,7 @@ static inline void DragonFlyBSDProcessList_scanMemoryInfo(ProcessList* pl) { //pl->freeMem *= pageSizeKb; struct kvm_swap swap[16]; - int nswap = kvm_getswapinfo(dfpl->kd, swap, sizeof(swap)/sizeof(swap[0]), 0); + int nswap = kvm_getswapinfo(dfpl->kd, swap, ARRAYSIZE(swap), 0); pl->totalSwap = 0; pl->usedSwap = 0; for (int i = 0; i < nswap; i++) { @@ -343,9 +300,9 @@ char* DragonFlyBSDProcessList_readProcessName(kvm_t* kd, struct kinfo_proc* kpro static inline void DragonFlyBSDProcessList_scanJails(DragonFlyBSDProcessList* dfpl) { size_t len; - char *jls; /* Jail list */ - char *curpos; - char *nextpos; + char* jls; /* Jail list */ + char* curpos; + char* nextpos; if (sysctlbyname("jail.list", NULL, &len, NULL, 0) == -1) { fprintf(stderr, "initial sysctlbyname / jail.list failed\n"); @@ -376,30 +333,32 @@ static inline void DragonFlyBSDProcessList_scanJails(DragonFlyBSDProcessList* df curpos = jls; while (curpos) { int jailid; - char *str_hostname; + char* str_hostname; nextpos = strchr(curpos, '\n'); - if (nextpos) + if (nextpos) { *nextpos++ = 0; + } jailid = atoi(strtok(curpos, " ")); str_hostname = strtok(NULL, " "); - char *jname = (char *) (Hashtable_get(dfpl->jails, jailid)); + char* jname = (char*) (Hashtable_get(dfpl->jails, jailid)); if (jname == NULL) { jname = xStrdup(str_hostname); Hashtable_put(dfpl->jails, jailid, jname); } curpos = nextpos; - } - free(jls); + } + + free(jls); } char* DragonFlyBSDProcessList_readJailName(DragonFlyBSDProcessList* dfpl, int jailid) { char* hostname; char* jname; - if (jailid != 0 && dfpl->jails && (hostname = (char *)Hashtable_get(dfpl->jails, jailid))) { + if (jailid != 0 && dfpl->jails && (hostname = (char*)Hashtable_get(dfpl->jails, jailid))) { jname = xStrdup(hostname); } else { jname = xStrdup("-"); @@ -407,16 +366,21 @@ char* DragonFlyBSDProcessList_readJailName(DragonFlyBSDProcessList* dfpl, int ja return jname; } -void ProcessList_goThroughEntries(ProcessList* this) { - DragonFlyBSDProcessList* dfpl = (DragonFlyBSDProcessList*) this; - Settings* settings = this->settings; +void ProcessList_goThroughEntries(ProcessList* super, bool pauseProcessUpdate) { + DragonFlyBSDProcessList* dfpl = (DragonFlyBSDProcessList*) super; + const Settings* settings = super->settings; bool hideKernelThreads = settings->hideKernelThreads; bool hideUserlandThreads = settings->hideUserlandThreads; - DragonFlyBSDProcessList_scanMemoryInfo(this); - DragonFlyBSDProcessList_scanCPUTime(this); + DragonFlyBSDProcessList_scanMemoryInfo(super); + DragonFlyBSDProcessList_scanCPUTime(super); DragonFlyBSDProcessList_scanJails(dfpl); + // in pause mode only gather global data for meters (CPU/memory/...) + if (pauseProcessUpdate) { + return; + } + int count = 0; // TODO Kernel Threads seem to be skipped, need to figure out the correct flag @@ -425,10 +389,10 @@ void ProcessList_goThroughEntries(ProcessList* this) { for (int i = 0; i < count; i++) { struct kinfo_proc* kproc = &kprocs[i]; bool preExisting = false; - bool _UNUSED_ isIdleProcess = false; + bool ATTR_UNUSED isIdleProcess = false; // note: dragonflybsd kernel processes all have the same pid, so we misuse the kernel thread address to give them a unique identifier - Process* proc = ProcessList_getProcess(this, kproc->kp_ktaddr ? (pid_t)kproc->kp_ktaddr : kproc->kp_pid, &preExisting, (Process_New) DragonFlyBSDProcess_new); + Process* proc = ProcessList_getProcess(super, kproc->kp_ktaddr ? (pid_t)kproc->kp_ktaddr : kproc->kp_pid, &preExisting, DragonFlyBSDProcess_new); DragonFlyBSDProcess* dfp = (DragonFlyBSDProcess*) proc; proc->show = ! ((hideKernelThreads && Process_isKernelThread(dfp)) || (hideUserlandThreads && Process_isUserlandThread(proc))); @@ -453,14 +417,14 @@ void ProcessList_goThroughEntries(ProcessList* this) { proc->st_uid = kproc->kp_uid; // user ID proc->processor = kproc->kp_lwp.kl_origcpu; proc->starttime_ctime = kproc->kp_start.tv_sec; - proc->user = UsersTable_getRef(this->usersTable, proc->st_uid); + proc->user = UsersTable_getRef(super->usersTable, proc->st_uid); - ProcessList_add((ProcessList*)this, proc); + ProcessList_add(super, proc); proc->comm = DragonFlyBSDProcessList_readProcessName(dfpl->kd, kproc, &proc->basenameOffset); dfp->jname = DragonFlyBSDProcessList_readJailName(dfpl, kproc->kp_jailid); } else { proc->processor = kproc->kp_lwp.kl_cpuid; - if(dfp->jid != kproc->kp_jailid) { // process can enter jail anytime + if (dfp->jid != kproc->kp_jailid) { // process can enter jail anytime dfp->jid = kproc->kp_jailid; free(dfp->jname); dfp->jname = DragonFlyBSDProcessList_readJailName(dfpl, kproc->kp_jailid); @@ -468,9 +432,9 @@ void ProcessList_goThroughEntries(ProcessList* this) { if (proc->ppid != kproc->kp_ppid) { // if there are reapers in the system, process can get reparented anytime proc->ppid = kproc->kp_ppid; } - if(proc->st_uid != kproc->kp_uid) { // some processes change users (eg. to lower privs) + if (proc->st_uid != kproc->kp_uid) { // some processes change users (eg. to lower privs) proc->st_uid = kproc->kp_uid; - proc->user = UsersTable_getRef(this->usersTable, proc->st_uid); + proc->user = UsersTable_getRef(super->usersTable, proc->st_uid); } if (settings->updateProcessNames) { free(proc->comm); @@ -480,12 +444,11 @@ void ProcessList_goThroughEntries(ProcessList* this) { proc->m_size = kproc->kp_vm_map_size / 1024 / pageSizeKb; proc->m_resident = kproc->kp_vm_rssize; - proc->percent_mem = (proc->m_resident * PAGE_SIZE_KB) / (double)(this->totalMem) * 100.0; proc->nlwp = kproc->kp_nthreads; // number of lwp thread proc->time = (kproc->kp_swtime + 5000) / 10000; proc->percent_cpu = 100.0 * ((double)kproc->kp_lwp.kl_pctcpu / (double)kernelFScale); - proc->percent_mem = 100.0 * (proc->m_resident * PAGE_SIZE_KB) / (double)(this->totalMem); + proc->percent_mem = 100.0 * (proc->m_resident * pageSizeKb) / (double)(super->totalMem); if (proc->percent_cpu > 0.1) { // system idle process should own all CPU time left regardless of CPU count @@ -565,14 +528,14 @@ void ProcessList_goThroughEntries(ProcessList* this) { if (kproc->kp_flags & P_JAILED) { proc->state = 'J'; } - + if (Process_isKernelThread(dfp)) { - this->kernelThreads++; + super->kernelThreads++; } - this->totalTasks++; + super->totalTasks++; if (proc->state == 'R') - this->runningTasks++; + super->runningTasks++; proc->updated = true; } } diff --git a/dragonflybsd/DragonFlyBSDProcessList.h b/dragonflybsd/DragonFlyBSDProcessList.h index 816e66d6e..ff65a6369 100644 --- a/dragonflybsd/DragonFlyBSDProcessList.h +++ b/dragonflybsd/DragonFlyBSDProcessList.h @@ -1,16 +1,13 @@ -/* Do not edit this file. It was automatically generated. */ - #ifndef HEADER_DragonFlyBSDProcessList #define HEADER_DragonFlyBSDProcessList /* htop - DragonFlyBSDProcessList.h (C) 2014 Hisham H. Muhammad (C) 2017 Diederik de Groot -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ - #include #include #include @@ -22,18 +19,16 @@ in the source distribution for its full text. #include "Hashtable.h" #include "DragonFlyBSDProcess.h" -#define JAIL_ERRMSGLEN 1024 -char jail_errmsg[JAIL_ERRMSGLEN]; +#define JAIL_ERRMSGLEN 1024 +extern char jail_errmsg[JAIL_ERRMSGLEN]; typedef struct CPUData_ { - double userPercent; double nicePercent; double systemPercent; double irqPercent; double idlePercent; double systemAllPercent; - } CPUData; typedef struct DragonFlyBSDProcessList_ { @@ -47,20 +42,16 @@ typedef struct DragonFlyBSDProcessList_ { CPUData* cpus; - unsigned long *cp_time_o; - unsigned long *cp_time_n; + unsigned long* cp_time_o; + unsigned long* cp_time_n; - unsigned long *cp_times_o; - unsigned long *cp_times_n; + unsigned long* cp_times_o; + unsigned long* cp_times_n; - Hashtable *jails; + Hashtable* jails; } DragonFlyBSDProcessList; - -#define _UNUSED_ __attribute__((unused)) - - -ProcessList* ProcessList_new(UsersTable* usersTable, Hashtable* pidWhiteList, uid_t userId); +ProcessList* ProcessList_new(UsersTable* usersTable, Hashtable* pidMatchList, uid_t userId); void ProcessList_delete(ProcessList* this); @@ -68,6 +59,6 @@ char* DragonFlyBSDProcessList_readProcessName(kvm_t* kd, struct kinfo_proc* kpro char* DragonFlyBSDProcessList_readJailName(DragonFlyBSDProcessList* dfpl, int jailid); -void ProcessList_goThroughEntries(ProcessList* this); +void ProcessList_goThroughEntries(ProcessList* super, pauseProcessUpdate); #endif diff --git a/dragonflybsd/Platform.c b/dragonflybsd/Platform.c index 370943d7a..78d11fb0d 100644 --- a/dragonflybsd/Platform.c +++ b/dragonflybsd/Platform.c @@ -2,11 +2,12 @@ htop - dragonflybsd/Platform.c (C) 2014 Hisham H. Muhammad (C) 2017 Diederik de Groot -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ #include "Platform.h" +#include "Macros.h" #include "Meter.h" #include "CPUMeter.h" #include "MemoryMeter.h" @@ -15,6 +16,8 @@ in the source distribution for its full text. #include "LoadAverageMeter.h" #include "UptimeMeter.h" #include "ClockMeter.h" +#include "DateMeter.h" +#include "DateTimeMeter.h" #include "HostnameMeter.h" #include "DragonFlyBSDProcess.h" #include "DragonFlyBSDProcessList.h" @@ -27,18 +30,6 @@ in the source distribution for its full text. #include #include -/*{ -#include "Action.h" -#include "BatteryMeter.h" -#include "SignalsPanel.h" - -extern ProcessFieldData Process_fields[]; - -}*/ - -#ifndef CLAMP -#define CLAMP(x,low,high) (((x)>(high))?(high):(((x)<(low))?(low):(x))) -#endif ProcessField Platform_defaultFields[] = { PID, USER, PRIORITY, NICE, M_SIZE, M_RESIDENT, STATE, PERCENT_CPU, PERCENT_MEM, TIME, COMM, 0 }; @@ -81,15 +72,17 @@ const SignalItem Platform_signals[] = { { .name = "33 SIGLIBRT", .number = 33 }, }; -const unsigned int Platform_numberOfSignals = sizeof(Platform_signals)/sizeof(SignalItem); +const unsigned int Platform_numberOfSignals = ARRAYSIZE(Platform_signals); void Platform_setBindings(Htop_Action* keys) { (void) keys; } -MeterClass* Platform_meterTypes[] = { +const MeterClass* const Platform_meterTypes[] = { &CPUMeter_class, &ClockMeter_class, + &DateMeter_class, + &DateTimeMeter_class, &LoadAverageMeter_class, &LoadMeter_class, &MemoryMeter_class, @@ -100,10 +93,16 @@ MeterClass* Platform_meterTypes[] = { &HostnameMeter_class, &AllCPUsMeter_class, &AllCPUs2Meter_class, + &AllCPUs4Meter_class, + &AllCPUs8Meter_class, &LeftCPUsMeter_class, &RightCPUsMeter_class, &LeftCPUs2Meter_class, &RightCPUs2Meter_class, + &LeftCPUs4Meter_class, + &RightCPUs4Meter_class, + &LeftCPUs8Meter_class, + &RightCPUs8Meter_class, &BlankMeter_class, NULL }; @@ -150,15 +149,15 @@ int Platform_getMaxPid() { } double Platform_setCPUValues(Meter* this, int cpu) { - DragonFlyBSDProcessList* fpl = (DragonFlyBSDProcessList*) this->pl; + const DragonFlyBSDProcessList* fpl = (const DragonFlyBSDProcessList*) this->pl; int cpus = this->pl->cpuCount; - CPUData* cpuData; + const CPUData* cpuData; if (cpus == 1) { - // single CPU box has everything in fpl->cpus[0] - cpuData = &(fpl->cpus[0]); + // single CPU box has everything in fpl->cpus[0] + cpuData = &(fpl->cpus[0]); } else { - cpuData = &(fpl->cpus[cpu]); + cpuData = &(fpl->cpus[cpu]); } double percent; @@ -169,22 +168,24 @@ double Platform_setCPUValues(Meter* this, int cpu) { if (this->pl->settings->detailedCPUTime) { v[CPU_METER_KERNEL] = cpuData->systemPercent; v[CPU_METER_IRQ] = cpuData->irqPercent; - Meter_setItems(this, 4); - percent = v[0]+v[1]+v[2]+v[3]; + this->curItems = 4; + percent = v[0] + v[1] + v[2] + v[3]; } else { v[2] = cpuData->systemAllPercent; - Meter_setItems(this, 3); - percent = v[0]+v[1]+v[2]; + this->curItems = 3; + percent = v[0] + v[1] + v[2]; } - percent = CLAMP(percent, 0.0, 100.0); - if (isnan(percent)) percent = 0.0; + percent = isnan(percent) ? 0.0 : CLAMP(percent, 0.0, 100.0); + + v[CPU_METER_FREQUENCY] = NAN; + return percent; } void Platform_setMemoryValues(Meter* this) { // TODO - ProcessList* pl = (ProcessList*) this->pl; + const ProcessList* pl = this->pl; this->total = pl->totalMem; this->values[0] = pl->usedMem; @@ -193,18 +194,58 @@ void Platform_setMemoryValues(Meter* this) { } void Platform_setSwapValues(Meter* this) { - ProcessList* pl = (ProcessList*) this->pl; + const ProcessList* pl = this->pl; this->total = pl->totalSwap; this->values[0] = pl->usedSwap; } -void Platform_setTasksValues(Meter* this) { +char* Platform_getProcessEnv(pid_t pid) { // TODO - (void)this; // prevent unused warning + (void)pid; // prevent unused warning + return NULL; } -char* Platform_getProcessEnv(pid_t pid) { +char* Platform_getInodeFilename(pid_t pid, ino_t inode) { + (void)pid; + (void)inode; + return NULL; +} + +FileLocks_ProcessData* Platform_getProcessLocks(pid_t pid) { + (void)pid; + return NULL; +} + +bool Platform_getDiskIO(DiskIOData* data) { // TODO - (void)pid; // prevent unused warning - return NULL; + (void)data; + return false; +} + +bool Platform_getNetworkIO(unsigned long int* bytesReceived, + unsigned long int* packetsReceived, + unsigned long int* bytesTransmitted, + unsigned long int* packetsTransmitted) { + // TODO + *bytesReceived = 0; + *packetsReceived = 0; + *bytesTransmitted = 0; + *packetsTransmitted = 0; + return false; +} + +void Platform_getBattery(double* level, ACPresence* isOnAC) { + int life; + size_t life_len = sizeof(life); + if (sysctlbyname("hw.acpi.battery.life", &life, &life_len, NULL, 0) == -1) + *level = NAN; + else + *level = life; + + int acline; + size_t acline_len = sizeof(acline); + if (sysctlbyname("hw.acpi.acline", &acline, &acline_len, NULL, 0) == -1) + *isOnAC = AC_ERROR; + else + *isOnAC = acline == 0 ? AC_ABSENT : AC_PRESENT; } diff --git a/dragonflybsd/Platform.h b/dragonflybsd/Platform.h index c2684f340..267b8f37f 100644 --- a/dragonflybsd/Platform.h +++ b/dragonflybsd/Platform.h @@ -1,26 +1,24 @@ -/* Do not edit this file. It was automatically generated. */ - #ifndef HEADER_Platform #define HEADER_Platform /* htop - dragonflybsd/Platform.h (C) 2014 Hisham H. Muhammad (C) 2017 Diederik de Groot -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ +#include +#include + #include "Action.h" #include "BatteryMeter.h" +#include "DiskIOMeter.h" +#include "ProcessLocksScreen.h" #include "SignalsPanel.h" extern ProcessFieldData Process_fields[]; - -#ifndef CLAMP -#define CLAMP(x,low,high) (((x)>(high))?(high):(((x)<(low))?(low):(x))) -#endif - extern ProcessField Platform_defaultFields[]; extern int Platform_numberOfFields; @@ -31,13 +29,13 @@ extern const unsigned int Platform_numberOfSignals; void Platform_setBindings(Htop_Action* keys); -extern MeterClass* Platform_meterTypes[]; +extern const MeterClass* const Platform_meterTypes[]; -int Platform_getUptime(); +int Platform_getUptime(void); void Platform_getLoadAverage(double* one, double* five, double* fifteen); -int Platform_getMaxPid(); +int Platform_getMaxPid(void); double Platform_setCPUValues(Meter* this, int cpu); @@ -45,8 +43,19 @@ void Platform_setMemoryValues(Meter* this); void Platform_setSwapValues(Meter* this); -void Platform_setTasksValues(Meter* this); - char* Platform_getProcessEnv(pid_t pid); +char* Platform_getInodeFilename(pid_t pid, ino_t inode); + +FileLocks_ProcessData* Platform_getProcessLocks(pid_t pid); + +bool Platform_getDiskIO(DiskIOData* data); + +bool Platform_getNetworkIO(unsigned long int* bytesReceived, + unsigned long int* packetsReceived, + unsigned long int* bytesTransmitted, + unsigned long int* packetsTransmitted); + +void Platform_getBattery(double* level, ACPresence* isOnAC); + #endif diff --git a/freebsd/Battery.c b/freebsd/Battery.c deleted file mode 100644 index b8c5e3124..000000000 --- a/freebsd/Battery.c +++ /dev/null @@ -1,25 +0,0 @@ -/* -htop - freebsd/Battery.c -(C) 2015 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file -in the source distribution for its full text. -*/ - -#include "BatteryMeter.h" -#include - -void Battery_getData(double* level, ACPresence* isOnAC) { - int life; - size_t life_len = sizeof(life); - if (sysctlbyname("hw.acpi.battery.life", &life, &life_len, NULL, 0) == -1) - *level = -1; - else - *level = life; - - int acline; - size_t acline_len = sizeof(acline); - if (sysctlbyname("hw.acpi.acline", &acline, &acline_len, NULL, 0) == -1) - *isOnAC = AC_ERROR; - else - *isOnAC = acline == 0 ? AC_ABSENT : AC_PRESENT; -} diff --git a/freebsd/Battery.h b/freebsd/Battery.h deleted file mode 100644 index cc5b1fed8..000000000 --- a/freebsd/Battery.h +++ /dev/null @@ -1,14 +0,0 @@ -/* Do not edit this file. It was automatically generated. */ - -#ifndef HEADER_Battery -#define HEADER_Battery -/* -htop - freebsd/Battery.h -(C) 2015 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file -in the source distribution for its full text. -*/ - -void Battery_getData(double* level, ACPresence* isOnAC); - -#endif diff --git a/freebsd/FreeBSDCRT.c b/freebsd/FreeBSDCRT.c deleted file mode 100644 index 5c3a9de45..000000000 --- a/freebsd/FreeBSDCRT.c +++ /dev/null @@ -1,21 +0,0 @@ -/* -htop - UnsupportedCRT.c -(C) 2014 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file -in the source distribution for its full text. -*/ - -#include "config.h" -#include "CRT.h" -#include -#include - -void CRT_handleSIGSEGV(int sgn) { - (void) sgn; - CRT_done(); - fprintf(stderr, "\n\nhtop " VERSION " aborting.\n"); - fprintf(stderr, "\nUnfortunately, you seem to be using an unsupported platform!"); - fprintf(stderr, "\nPlease contact your platform package maintainer!\n\n"); - abort(); -} - diff --git a/freebsd/FreeBSDCRT.h b/freebsd/FreeBSDCRT.h deleted file mode 100644 index eb1091a9b..000000000 --- a/freebsd/FreeBSDCRT.h +++ /dev/null @@ -1,15 +0,0 @@ -/* Do not edit this file. It was automatically generated. */ - -#ifndef HEADER_FreeBSDCRT -#define HEADER_FreeBSDCRT -/* -htop - UnsupportedCRT.h -(C) 2014 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file -in the source distribution for its full text. -*/ - -void CRT_handleSIGSEGV(int sgn); - - -#endif diff --git a/freebsd/FreeBSDProcess.c b/freebsd/FreeBSDProcess.c index f81fadf50..57e64118c 100644 --- a/freebsd/FreeBSDProcess.c +++ b/freebsd/FreeBSDProcess.c @@ -1,7 +1,7 @@ /* htop - FreeBSDProcess.c (C) 2015 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ @@ -16,43 +16,8 @@ in the source distribution for its full text. #include #include -/*{ -typedef enum FreeBSDProcessFields { - // Add platform-specific fields here, with ids >= 100 - JID = 100, - JAIL = 101, - LAST_PROCESSFIELD = 102, -} FreeBSDProcessField; - - -typedef struct FreeBSDProcess_ { - Process super; - int kernel; - int jid; - char* jname; -} FreeBSDProcess; - - -#ifndef Process_isKernelThread -#define Process_isKernelThread(_process) (_process->kernel == 1) -#endif - -#ifndef Process_isUserlandThread -#define Process_isUserlandThread(_process) (_process->pid != _process->tgid) -#endif - -}*/ - -ProcessClass FreeBSDProcess_class = { - .super = { - .extends = Class(Process), - .display = Process_display, - .delete = Process_delete, - .compare = FreeBSDProcess_compare - }, - .writeField = (Process_WriteField) FreeBSDProcess_writeField, -}; +const char* const nodevStr = "nodev"; ProcessFieldData Process_fields[] = { [0] = { .name = "", .title = NULL, .description = NULL, .flags = 0, }, @@ -62,7 +27,7 @@ ProcessFieldData Process_fields[] = { [PPID] = { .name = "PPID", .title = " PPID ", .description = "Parent process ID", .flags = 0, }, [PGRP] = { .name = "PGRP", .title = " PGRP ", .description = "Process group ID", .flags = 0, }, [SESSION] = { .name = "SESSION", .title = " SID ", .description = "Process's session ID", .flags = 0, }, - [TTY_NR] = { .name = "TTY_NR", .title = " TTY ", .description = "Controlling terminal", .flags = 0, }, + [TTY_NR] = { .name = "TTY_NR", .title = " TTY ", .description = "Controlling terminal", .flags = PROCESS_FLAG_FREEBSD_TTY, }, [TPGID] = { .name = "TPGID", .title = " TPGID ", .description = "Process ID of the fg process group of the controlling terminal", .flags = 0, }, [MINFLT] = { .name = "MINFLT", .title = " MINFLT ", .description = "Number of minor faults which have not required loading a memory page from disk", .flags = 0, }, [MAJFLT] = { .name = "MAJFLT", .title = " MAJFLT ", .description = "Number of major faults which have required loading a memory page from disk", .flags = 0, }, @@ -73,8 +38,9 @@ ProcessFieldData Process_fields[] = { [PROCESSOR] = { .name = "PROCESSOR", .title = "CPU ", .description = "Id of the CPU the process last executed on", .flags = 0, }, [M_SIZE] = { .name = "M_SIZE", .title = " VIRT ", .description = "Total program size in virtual memory", .flags = 0, }, [M_RESIDENT] = { .name = "M_RESIDENT", .title = " RES ", .description = "Resident set size, size of the text and data sections, plus stack usage", .flags = 0, }, - [ST_UID] = { .name = "ST_UID", .title = " UID ", .description = "User ID of the process owner", .flags = 0, }, + [ST_UID] = { .name = "ST_UID", .title = " UID ", .description = "User ID of the process owner", .flags = 0, }, [PERCENT_CPU] = { .name = "PERCENT_CPU", .title = "CPU% ", .description = "Percentage of the CPU time the process used in the last sampling", .flags = 0, }, + [PERCENT_NORM_CPU] = { .name = "PERCENT_NORM_CPU", .title = "NCPU%", .description = "Normalized percentage of the CPU time the process used in the last sampling (normalized by cpu count)", .flags = 0, }, [PERCENT_MEM] = { .name = "PERCENT_MEM", .title = "MEM% ", .description = "Percentage of the memory the process is using, based on resident memory size", .flags = 0, }, [USER] = { .name = "USER", .title = "USER ", .description = "Username of the process owner (or user ID if name cannot be determined)", .flags = 0, }, [TIME] = { .name = "TIME", .title = " TIME+ ", .description = "Total time the process has spent in user and system time", .flags = 0, }, @@ -96,11 +62,11 @@ ProcessPidColumn Process_pidColumns[] = { { .id = 0, .label = NULL }, }; -FreeBSDProcess* FreeBSDProcess_new(Settings* settings) { +Process* FreeBSDProcess_new(const Settings* settings) { FreeBSDProcess* this = xCalloc(1, sizeof(FreeBSDProcess)); Object_setClass(this, Class(FreeBSDProcess)); Process_init(&this->super, settings); - return this; + return &this->super; } void Process_delete(Object* cast) { @@ -110,22 +76,32 @@ void Process_delete(Object* cast) { free(this); } -void FreeBSDProcess_writeField(Process* this, RichString* str, ProcessField field) { - FreeBSDProcess* fp = (FreeBSDProcess*) this; +static void FreeBSDProcess_writeField(const Process* this, RichString* str, ProcessField field) { + const FreeBSDProcess* fp = (const FreeBSDProcess*) this; char buffer[256]; buffer[255] = '\0'; int attr = CRT_colors[DEFAULT_COLOR]; int n = sizeof(buffer) - 1; switch ((int) field) { // add FreeBSD-specific fields here case JID: xSnprintf(buffer, n, Process_pidFormat, fp->jid); break; - case JAIL:{ - xSnprintf(buffer, n, "%-11s ", fp->jname); break; + case JAIL: { + xSnprintf(buffer, n, "%-11s ", fp->jname); if (buffer[11] != '\0') { buffer[11] = ' '; buffer[12] = '\0'; } break; } + case TTY_NR: + if (fp->ttyPath) { + if (fp->ttyPath == nodevStr) + attr = CRT_colors[PROCESS_SHADOW]; + xSnprintf(buffer, n, "%-8s", fp->ttyPath); + } else { + attr = CRT_colors[PROCESS_SHADOW]; + xSnprintf(buffer, n, "? "); + } + break; default: Process_writeField(this, str, field); return; @@ -133,32 +109,47 @@ void FreeBSDProcess_writeField(Process* this, RichString* str, ProcessField fiel RichString_append(str, attr, buffer); } -long FreeBSDProcess_compare(const void* v1, const void* v2) { - FreeBSDProcess *p1, *p2; - Settings *settings = ((Process*)v1)->settings; +static long FreeBSDProcess_compare(const void* v1, const void* v2) { + const FreeBSDProcess *p1, *p2; + const Settings *settings = ((const Process*)v1)->settings; + if (settings->direction == 1) { - p1 = (FreeBSDProcess*)v1; - p2 = (FreeBSDProcess*)v2; + p1 = (const FreeBSDProcess*)v1; + p2 = (const FreeBSDProcess*)v2; } else { - p2 = (FreeBSDProcess*)v1; - p1 = (FreeBSDProcess*)v2; + p2 = (const FreeBSDProcess*)v1; + p1 = (const FreeBSDProcess*)v2; } + switch ((int) settings->sortKey) { // add FreeBSD-specific fields here case JID: - return (p1->jid - p2->jid); + return SPACESHIP_NUMBER(p1->jid, p2->jid); case JAIL: - return strcmp(p1->jname ? p1->jname : "", p2->jname ? p2->jname : ""); + return SPACESHIP_NULLSTR(p1->jname, p2->jname); + case TTY_NR: + return SPACESHIP_NULLSTR(p1->ttyPath, p2->ttyPath); default: return Process_compare(v1, v2); } } -bool Process_isThread(Process* this) { - FreeBSDProcess* fp = (FreeBSDProcess*) this; +bool Process_isThread(const Process* this) { + const FreeBSDProcess* fp = (const FreeBSDProcess*) this; - if (fp->kernel == 1 ) + if (fp->kernel == 1 ) { return 1; - else - return (Process_isUserlandThread(this)); + } else { + return Process_isUserlandThread(this); + } } + +const ProcessClass FreeBSDProcess_class = { + .super = { + .extends = Class(Process), + .display = Process_display, + .delete = Process_delete, + .compare = FreeBSDProcess_compare + }, + .writeField = FreeBSDProcess_writeField, +}; diff --git a/freebsd/FreeBSDProcess.h b/freebsd/FreeBSDProcess.h index 23d298a31..d2fee956a 100644 --- a/freebsd/FreeBSDProcess.h +++ b/freebsd/FreeBSDProcess.h @@ -1,54 +1,57 @@ -/* Do not edit this file. It was automatically generated. */ - #ifndef HEADER_FreeBSDProcess #define HEADER_FreeBSDProcess /* htop - FreeBSDProcess.h (C) 2015 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ +#include + +#include "Object.h" +#include "Process.h" +#include "RichString.h" +#include "Settings.h" + -typedef enum FreeBSDProcessFields { +#define PROCESS_FLAG_FREEBSD_TTY 0x0100 + +extern const char* const nodevStr; + +typedef enum FreeBSDProcessFields_ { // Add platform-specific fields here, with ids >= 100 JID = 100, JAIL = 101, LAST_PROCESSFIELD = 102, } FreeBSDProcessField; - typedef struct FreeBSDProcess_ { Process super; int kernel; int jid; char* jname; + const char* ttyPath; } FreeBSDProcess; +static inline bool Process_isKernelThread(const Process* this) { + return ((const FreeBSDProcess*)this)->kernel == 1; +} -#ifndef Process_isKernelThread -#define Process_isKernelThread(_process) (_process->kernel == 1) -#endif - -#ifndef Process_isUserlandThread -#define Process_isUserlandThread(_process) (_process->pid != _process->tgid) -#endif +static inline bool Process_isUserlandThread(const Process* this) { + return this->pid != this->tgid; +} - -extern ProcessClass FreeBSDProcess_class; +extern const ProcessClass FreeBSDProcess_class; extern ProcessFieldData Process_fields[]; extern ProcessPidColumn Process_pidColumns[]; -FreeBSDProcess* FreeBSDProcess_new(Settings* settings); +Process* FreeBSDProcess_new(const Settings* settings); void Process_delete(Object* cast); -void FreeBSDProcess_writeField(Process* this, RichString* str, ProcessField field); - -long FreeBSDProcess_compare(const void* v1, const void* v2); - -bool Process_isThread(Process* this); +bool Process_isThread(const Process* this); #endif diff --git a/freebsd/FreeBSDProcessList.c b/freebsd/FreeBSDProcessList.c index 9fef324a5..7ce787f84 100644 --- a/freebsd/FreeBSDProcessList.c +++ b/freebsd/FreeBSDProcessList.c @@ -1,72 +1,39 @@ /* htop - FreeBSDProcessList.c (C) 2014 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ -#include "ProcessList.h" #include "FreeBSDProcessList.h" -#include "FreeBSDProcess.h" -#include -#include -#include -#include -#include +#include +#include #include #include #include +#include #include +#include +#include +#include +#include +#include +#include +#include -/*{ +#include "Compat.h" +#include "CRT.h" +#include "FreeBSDProcess.h" +#include "Macros.h" +#include "ProcessList.h" +#include "XUtils.h" +#include "zfs/ZfsArcStats.h" +#include "zfs/openzfs_sysctl.h" -#include -#include -#include -#include -#include -#define JAIL_ERRMSGLEN 1024 char jail_errmsg[JAIL_ERRMSGLEN]; -typedef struct CPUData_ { - - double userPercent; - double nicePercent; - double systemPercent; - double irqPercent; - double idlePercent; - double systemAllPercent; - -} CPUData; - -typedef struct FreeBSDProcessList_ { - ProcessList super; - kvm_t* kd; - - int zfsArcEnabled; - - unsigned long long int memWire; - unsigned long long int memActive; - unsigned long long int memInactive; - unsigned long long int memFree; - unsigned long long int memZfsArc; - - - CPUData* cpus; - - unsigned long *cp_time_o; - unsigned long *cp_time_n; - - unsigned long *cp_times_o; - unsigned long *cp_times_n; - -} FreeBSDProcessList; - -}*/ - - static int MIB_hw_physmem[2]; static int MIB_vm_stats_vm_v_page_count[4]; static int pageSize; @@ -80,18 +47,16 @@ static int MIB_vm_stats_vm_v_free_count[4]; static int MIB_vfs_bufspace[2]; -static int MIB_kstat_zfs_misc_arcstats_size[5]; - static int MIB_kern_cp_time[2]; static int MIB_kern_cp_times[2]; static int kernelFScale; -ProcessList* ProcessList_new(UsersTable* usersTable, Hashtable* pidWhiteList, uid_t userId) { +ProcessList* ProcessList_new(UsersTable* usersTable, Hashtable* pidMatchList, 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); + ProcessList_init(pl, Class(FreeBSDProcess), usersTable, pidMatchList, userId); // physical memory in system: hw.physmem // physical page size: hw.pagesize @@ -100,8 +65,8 @@ ProcessList* ProcessList_new(UsersTable* usersTable, Hashtable* pidWhiteList, ui len = sizeof(pageSize); if (sysctlbyname("vm.stats.vm.v_page_size", &pageSize, &len, NULL, 0) == -1) { - pageSize = PAGE_SIZE; - pageSizeKb = PAGE_SIZE_KB; + pageSize = CRT_pageSize; + pageSizeKb = CRT_pageSize; } else { pageSizeKb = pageSize / ONE_K; } @@ -118,15 +83,8 @@ ProcessList* ProcessList_new(UsersTable* usersTable, Hashtable* pidWhiteList, ui 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; - } - + openzfs_sysctl_init(&fpl->zfs); + openzfs_sysctl_updateArcStats(&fpl->zfs); int smp = 0; len = sizeof(smp); @@ -140,7 +98,9 @@ ProcessList* ProcessList_new(UsersTable* usersTable, Hashtable* pidWhiteList, ui if (smp) { int err = sysctlbyname("kern.smp.cpus", &cpus, &len, NULL, 0); - if (err) cpus = 1; + if (err) { + cpus = 1; + } } else { cpus = 1; } @@ -163,13 +123,13 @@ ProcessList* ProcessList_new(UsersTable* usersTable, Hashtable* pidWhiteList, ui sysctl(MIB_kern_cp_times, 2, fpl->cp_times_o, &len, NULL, 0); } - pl->cpuCount = MAX(cpus, 1); + pl->cpuCount = MAXIMUM(cpus, 1); if (cpus == 1 ) { - fpl->cpus = xRealloc(fpl->cpus, sizeof(CPUData)); + 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)); + // 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)); } @@ -184,12 +144,19 @@ ProcessList* ProcessList_new(UsersTable* usersTable, Hashtable* pidWhiteList, ui errx(1, "kvm_open: %s", errbuf); } + fpl->ttys = Hashtable_new(20, true); + return pl; } void ProcessList_delete(ProcessList* this) { const FreeBSDProcessList* fpl = (FreeBSDProcessList*) this; - if (fpl->kd) kvm_close(fpl->kd); + + Hashtable_delete(fpl->ttys); + + if (fpl->kd) { + kvm_close(fpl->kd); + } free(fpl->cp_time_o); free(fpl->cp_time_n); @@ -212,8 +179,8 @@ static inline void FreeBSDProcessList_scanCPUTime(ProcessList* pl) { size_t sizeof_cp_time_array; - unsigned long *cp_time_n; // old clicks state - unsigned long *cp_time_o; // current clicks state + unsigned long* cp_time_n; // old clicks state + unsigned long* cp_time_o; // current clicks state unsigned long cp_time_d[CPUSTATES]; double cp_time_p[CPUSTATES]; @@ -224,12 +191,12 @@ static inline void FreeBSDProcessList_scanCPUTime(ProcessList* pl) { // get rest of CPUs if (cpus > 1) { - // on smp systems FreeBSD kernel concats all CPU states into one long array in - // kern.cp_times sysctl OID - // we store averages in fpl->cpus[0], and actual cores after that - maxcpu = cpus + 1; - sizeof_cp_time_array = cpus * sizeof(unsigned long) * CPUSTATES; - sysctl(MIB_kern_cp_times, 2, fpl->cp_times_n, &sizeof_cp_time_array, NULL, 0); + // on smp systems FreeBSD kernel concats all CPU states into one long array in + // kern.cp_times sysctl OID + // we store averages in fpl->cpus[0], and actual cores after that + maxcpu = cpus + 1; + sizeof_cp_time_array = cpus * sizeof(unsigned long) * CPUSTATES; + sysctl(MIB_kern_cp_times, 2, fpl->cp_times_n, &sizeof_cp_time_array, NULL, 0); } for (int i = 0; i < maxcpu; i++) { @@ -239,14 +206,14 @@ static inline void FreeBSDProcessList_scanCPUTime(ProcessList* pl) { cp_time_o = fpl->cp_time_o; } else { if (i == 0 ) { - // average - cp_time_n = fpl->cp_time_n; - cp_time_o = fpl->cp_time_o; + // average + cp_time_n = fpl->cp_time_n; + cp_time_o = fpl->cp_time_o; } else { - // specific smp cores - cp_times_offset = i - 1; - cp_time_n = fpl->cp_times_n + (cp_times_offset * CPUSTATES); - cp_time_o = fpl->cp_times_o + (cp_times_offset * CPUSTATES); + // specific smp cores + cp_times_offset = i - 1; + cp_time_n = fpl->cp_times_n + (cp_times_offset * CPUSTATES); + cp_time_o = fpl->cp_times_o + (cp_times_offset * CPUSTATES); } } @@ -255,19 +222,21 @@ static inline void FreeBSDProcessList_scanCPUTime(ProcessList* pl) { unsigned long long total_n = 0; unsigned long long total_d = 0; for (int s = 0; s < CPUSTATES; s++) { - cp_time_d[s] = cp_time_n[s] - cp_time_o[s]; - total_o += cp_time_o[s]; - total_n += cp_time_n[s]; + cp_time_d[s] = cp_time_n[s] - cp_time_o[s]; + total_o += cp_time_o[s]; + total_n += cp_time_n[s]; } // totals total_d = total_n - total_o; - if (total_d < 1 ) total_d = 1; + if (total_d < 1 ) { + total_d = 1; + } // save current state as old and calc percentages for (int s = 0; s < CPUSTATES; ++s) { - cp_time_o[s] = cp_time_n[s]; - cp_time_p[s] = ((double)cp_time_d[s]) / ((double)total_d) * 100; + cp_time_o[s] = cp_time_n[s]; + cp_time_p[s] = ((double)cp_time_d[s]) / ((double)total_d) * 100; } CPUData* cpuData = &(fpl->cpus[i]); @@ -296,35 +265,43 @@ static inline void FreeBSDProcessList_scanMemoryInfo(ProcessList* pl) { // // htop_used = active + (wired - arc) // htop_cache = buffers + cache + arc - size_t len = sizeof(pl->totalMem); + u_long totalMem; + u_int memActive, memWire, cachedMem; + long buffersMem; + size_t len; //disabled for now, as it is always smaller than phycal amount of memory... //...to avoid "where is my memory?" questions //sysctl(MIB_vm_stats_vm_v_page_count, 4, &(pl->totalMem), &len, NULL, 0); //pl->totalMem *= pageSizeKb; - sysctl(MIB_hw_physmem, 2, &(pl->totalMem), &len, NULL, 0); - pl->totalMem /= 1024; - - sysctl(MIB_vm_stats_vm_v_active_count, 4, &(fpl->memActive), &len, NULL, 0); - fpl->memActive *= pageSizeKb; - - sysctl(MIB_vm_stats_vm_v_wire_count, 4, &(fpl->memWire), &len, NULL, 0); - fpl->memWire *= pageSizeKb; - - sysctl(MIB_vfs_bufspace, 2, &(pl->buffersMem), &len, NULL, 0); - pl->buffersMem /= 1024; - - sysctl(MIB_vm_stats_vm_v_cache_count, 4, &(pl->cachedMem), &len, NULL, 0); - pl->cachedMem *= pageSizeKb; - - if (fpl->zfsArcEnabled) { - len = sizeof(fpl->memZfsArc); - sysctl(MIB_kstat_zfs_misc_arcstats_size, 5, &(fpl->memZfsArc), &len , NULL, 0); - fpl->memZfsArc /= 1024; - fpl->memWire -= fpl->memZfsArc; - pl->cachedMem += fpl->memZfsArc; - // maybe when we learn how to make custom memory meter - // we could do custom arc breakdown? + len = sizeof(totalMem); + sysctl(MIB_hw_physmem, 2, &(totalMem), &len, NULL, 0); + totalMem /= 1024; + pl->totalMem = totalMem; + + len = sizeof(memActive); + sysctl(MIB_vm_stats_vm_v_active_count, 4, &(memActive), &len, NULL, 0); + memActive *= pageSizeKb; + fpl->memActive = memActive; + + len = sizeof(memWire); + sysctl(MIB_vm_stats_vm_v_wire_count, 4, &(memWire), &len, NULL, 0); + memWire *= pageSizeKb; + fpl->memWire = memWire; + + len = sizeof(buffersMem); + sysctl(MIB_vfs_bufspace, 2, &(buffersMem), &len, NULL, 0); + buffersMem /= 1024; + pl->buffersMem = buffersMem; + + len = sizeof(cachedMem); + sysctl(MIB_vm_stats_vm_v_cache_count, 4, &(cachedMem), &len, NULL, 0); + cachedMem *= pageSizeKb; + pl->cachedMem = cachedMem; + + if (fpl->zfs.enabled) { + fpl->memWire -= fpl->zfs.size; + pl->cachedMem += fpl->zfs.size; } pl->usedMem = fpl->memActive + fpl->memWire; @@ -336,7 +313,7 @@ static inline void FreeBSDProcessList_scanMemoryInfo(ProcessList* pl) { //pl->freeMem *= pageSizeKb; struct kvm_swap swap[16]; - int nswap = kvm_getswapinfo(fpl->kd, swap, sizeof(swap)/sizeof(swap[0]), 0); + int nswap = kvm_getswapinfo(fpl->kd, swap, ARRAYSIZE(swap), 0); pl->totalSwap = 0; pl->usedSwap = 0; for (int i = 0; i < nswap; i++) { @@ -349,7 +326,71 @@ static inline void FreeBSDProcessList_scanMemoryInfo(ProcessList* pl) { pl->sharedMem = 0; // currently unused } -char* FreeBSDProcessList_readProcessName(kvm_t* kd, struct kinfo_proc* kproc, int* basenameEnd) { +static void FreeBSDProcessList_scanTTYs(ProcessList* pl) { + FreeBSDProcessList* fpl = (FreeBSDProcessList*) pl; + + // scan /dev/tty* + { + DIR* dirPtr = opendir("/dev"); + if (!dirPtr) + return; + + int dirFd = dirfd(dirPtr); + if (dirFd < 0) + goto err1; + + const struct dirent* entry; + while ((entry = readdir(dirPtr))) { + if (!String_startsWith(entry->d_name, "tty")) + continue; + + struct stat info; + if (Compat_fstatat(dirFd, "/dev", entry->d_name, &info, 0) < 0) + continue; + + if (!S_ISCHR(info.st_mode)) + continue; + + if (!Hashtable_get(fpl->ttys, info.st_rdev)) + Hashtable_put(fpl->ttys, info.st_rdev, xStrdup(entry->d_name)); + } + +err1: + closedir(dirPtr); + } + + // scan /dev/pts/* + { + DIR* dirPtr = opendir("/dev/pts"); + if (!dirPtr) + return; + + int dirFd = dirfd(dirPtr); + if (dirFd < 0) + goto err2; + + const struct dirent* entry; + while ((entry = readdir(dirPtr))) { + struct stat info; + if (Compat_fstatat(dirFd, "/dev/pts", entry->d_name, &info, 0) < 0) + continue; + + if (!S_ISCHR(info.st_mode)) + continue; + + if (!Hashtable_get(fpl->ttys, info.st_rdev)) { + char* path; + xAsprintf(&path, "pts/%s", entry->d_name); + Hashtable_put(fpl->ttys, info.st_rdev, path); + } + } + +err2: + closedir(dirPtr); + } +} + +static char* FreeBSDProcessList_readProcessName(kvm_t* kd, const struct kinfo_proc* kproc, int* basenameEnd) { char** argv = kvm_getargv(kd, kproc, 0); if (!argv) { return xStrdup(kproc->ki_comm); @@ -374,91 +415,105 @@ char* FreeBSDProcessList_readProcessName(kvm_t* kd, struct kinfo_proc* kproc, in return comm; } -char* FreeBSDProcessList_readJailName(struct kinfo_proc* kproc) { +static char* FreeBSDProcessList_readJailName(const struct kinfo_proc* kproc) { int jid; struct iovec jiov[6]; char* jname; char jnamebuf[MAXHOSTNAMELEN]; - if (kproc->ki_jid != 0 ){ + if (kproc->ki_jid != 0 ) { memset(jnamebuf, 0, sizeof(jnamebuf)); - *(const void **)&jiov[0].iov_base = "jid"; +IGNORE_WCASTQUAL_BEGIN + *(const void**)&jiov[0].iov_base = "jid"; jiov[0].iov_len = sizeof("jid"); - jiov[1].iov_base = &kproc->ki_jid; + jiov[1].iov_base = (void*) &kproc->ki_jid; jiov[1].iov_len = sizeof(kproc->ki_jid); - *(const void **)&jiov[2].iov_base = "name"; + *(const void**)&jiov[2].iov_base = "name"; jiov[2].iov_len = sizeof("name"); jiov[3].iov_base = jnamebuf; jiov[3].iov_len = sizeof(jnamebuf); - *(const void **)&jiov[4].iov_base = "errmsg"; + *(const void**)&jiov[4].iov_base = "errmsg"; jiov[4].iov_len = sizeof("errmsg"); jiov[5].iov_base = jail_errmsg; jiov[5].iov_len = JAIL_ERRMSGLEN; +IGNORE_WCASTQUAL_END jail_errmsg[0] = 0; jid = jail_get(jiov, 6, 0); if (jid < 0) { - if (!jail_errmsg[0]) + if (!jail_errmsg[0]) { xSnprintf(jail_errmsg, JAIL_ERRMSGLEN, "jail_get: %s", strerror(errno)); - return NULL; + } + return NULL; } else if (jid == kproc->ki_jid) { jname = xStrdup(jnamebuf); - if (jname == NULL) + if (jname == NULL) { strerror_r(errno, jail_errmsg, JAIL_ERRMSGLEN); + } return jname; } else { return NULL; } } else { - jnamebuf[0]='-'; - jnamebuf[1]='\0'; + jnamebuf[0] = '-'; + jnamebuf[1] = '\0'; jname = xStrdup(jnamebuf); } return jname; } -void ProcessList_goThroughEntries(ProcessList* this) { - FreeBSDProcessList* fpl = (FreeBSDProcessList*) this; - Settings* settings = this->settings; +void ProcessList_goThroughEntries(ProcessList* super, bool pauseProcessUpdate) { + FreeBSDProcessList* fpl = (FreeBSDProcessList*) super; + const Settings* settings = super->settings; bool hideKernelThreads = settings->hideKernelThreads; bool hideUserlandThreads = settings->hideUserlandThreads; - FreeBSDProcessList_scanMemoryInfo(this); - FreeBSDProcessList_scanCPUTime(this); + openzfs_sysctl_updateArcStats(&fpl->zfs); + FreeBSDProcessList_scanMemoryInfo(super); + FreeBSDProcessList_scanCPUTime(super); + + // in pause mode only gather global data for meters (CPU/memory/...) + if (pauseProcessUpdate) { + return; + } + + if (settings->flags & PROCESS_FLAG_FREEBSD_TTY) { + FreeBSDProcessList_scanTTYs(super); + } - int cpus = this->cpuCount; int count = 0; struct kinfo_proc* kprocs = kvm_getprocs(fpl->kd, KERN_PROC_PROC, 0, &count); for (int i = 0; i < count; i++) { struct kinfo_proc* kproc = &kprocs[i]; bool preExisting = false; - bool isIdleProcess = false; - Process* proc = ProcessList_getProcess(this, kproc->ki_pid, &preExisting, (Process_New) FreeBSDProcess_new); + // TODO: bool isIdleProcess = false; + Process* proc = ProcessList_getProcess(super, kproc->ki_pid, &preExisting, FreeBSDProcess_new); FreeBSDProcess* fp = (FreeBSDProcess*) proc; - proc->show = ! ((hideKernelThreads && Process_isKernelThread(fp)) || (hideUserlandThreads && Process_isUserlandThread(proc))); + proc->show = ! ((hideKernelThreads && Process_isKernelThread(proc)) || (hideUserlandThreads && Process_isUserlandThread(proc))); if (!preExisting) { fp->jid = kproc->ki_jid; proc->pid = kproc->ki_pid; - if ( ! ((kproc->ki_pid == 0) || (kproc->ki_pid == 1) ) && kproc->ki_flag & P_SYSTEM) - fp->kernel = 1; - else - fp->kernel = 0; + if ( ! ((kproc->ki_pid == 0) || (kproc->ki_pid == 1) ) && kproc->ki_flag & P_SYSTEM) { + fp->kernel = 1; + } else { + fp->kernel = 0; + } proc->ppid = kproc->ki_ppid; proc->tpgid = kproc->ki_tpgid; proc->tgid = kproc->ki_pid; proc->session = kproc->ki_sid; - proc->tty_nr = kproc->ki_tdev; proc->pgrp = kproc->ki_pgid; proc->st_uid = kproc->ki_uid; proc->starttime_ctime = kproc->ki_start.tv_sec; - proc->user = UsersTable_getRef(this->usersTable, proc->st_uid); - ProcessList_add((ProcessList*)this, proc); + Process_fillStarttimeBuffer(proc); + proc->user = UsersTable_getRef(super->usersTable, proc->st_uid); + ProcessList_add(super, proc); proc->comm = FreeBSDProcessList_readProcessName(fpl->kd, kproc, &proc->basenameOffset); fp->jname = FreeBSDProcessList_readJailName(kproc); } else { - if(fp->jid != kproc->ki_jid) { + if (fp->jid != kproc->ki_jid) { // process can enter jail anytime fp->jid = kproc->ki_jid; free(fp->jname); @@ -468,10 +523,10 @@ void ProcessList_goThroughEntries(ProcessList* this) { // if there are reapers in the system, process can get reparented anytime proc->ppid = kproc->ki_ppid; } - if(proc->st_uid != kproc->ki_uid) { + if (proc->st_uid != kproc->ki_uid) { // some processes change users (eg. to lower privs) proc->st_uid = kproc->ki_uid; - proc->user = UsersTable_getRef(this->usersTable, proc->st_uid); + proc->user = UsersTable_getRef(super->usersTable, proc->st_uid); } if (settings->updateProcessNames) { free(proc->comm); @@ -482,19 +537,21 @@ void ProcessList_goThroughEntries(ProcessList* this) { // from FreeBSD source /src/usr.bin/top/machine.c proc->m_size = kproc->ki_size / 1024 / pageSizeKb; proc->m_resident = kproc->ki_rssize; - proc->percent_mem = (proc->m_resident * PAGE_SIZE_KB) / (double)(this->totalMem) * 100.0; proc->nlwp = kproc->ki_numthreads; proc->time = (kproc->ki_runtime + 5000) / 10000; proc->percent_cpu = 100.0 * ((double)kproc->ki_pctcpu / (double)kernelFScale); - proc->percent_mem = 100.0 * (proc->m_resident * PAGE_SIZE_KB) / (double)(this->totalMem); - - if (proc->percent_cpu > 0.1) { - // system idle process should own all CPU time left regardless of CPU count - if ( strcmp("idle", kproc->ki_comm) == 0 ) { - isIdleProcess = true; - } - } + proc->percent_mem = 100.0 * (proc->m_resident * pageSizeKb) / (double)(super->totalMem); + + /* + * TODO + * if (proc->percent_cpu > 0.1) { + * // system idle process should own all CPU time left regardless of CPU count + * if ( strcmp("idle", kproc->ki_comm) == 0 ) { + * isIdleProcess = true; + * } + * } + */ proc->priority = kproc->ki_pri.pri_level - PZERO; @@ -519,13 +576,16 @@ void ProcessList_goThroughEntries(ProcessList* this) { default: proc->state = '?'; } - if (Process_isKernelThread(fp)) { - this->kernelThreads++; + if (settings->flags & PROCESS_FLAG_FREEBSD_TTY) { + fp->ttyPath = (kproc->ki_tdev == NODEV) ? nodevStr : Hashtable_get(fpl->ttys, kproc->ki_tdev); } - this->totalTasks++; + if (Process_isKernelThread(proc)) + super->kernelThreads++; + + super->totalTasks++; if (proc->state == 'R') - this->runningTasks++; + super->runningTasks++; proc->updated = true; } } diff --git a/freebsd/FreeBSDProcessList.h b/freebsd/FreeBSDProcessList.h index af343fb0b..cbe4742c6 100644 --- a/freebsd/FreeBSDProcessList.h +++ b/freebsd/FreeBSDProcessList.h @@ -1,68 +1,65 @@ -/* Do not edit this file. It was automatically generated. */ - #ifndef HEADER_FreeBSDProcessList #define HEADER_FreeBSDProcessList /* htop - FreeBSDProcessList.h (C) 2014 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ - #include -#include +#include // needs to be included before for MAXPATHLEN #include -#include #include +#include -#define JAIL_ERRMSGLEN 1024 -char jail_errmsg[JAIL_ERRMSGLEN]; +#include "FreeBSDProcess.h" +#include "Hashtable.h" +#include "Process.h" +#include "ProcessList.h" +#include "UsersTable.h" +#include "zfs/ZfsArcStats.h" -typedef struct CPUData_ { +#define JAIL_ERRMSGLEN 1024 +extern char jail_errmsg[JAIL_ERRMSGLEN]; + +typedef struct CPUData_ { double userPercent; double nicePercent; double systemPercent; double irqPercent; double idlePercent; double systemAllPercent; - } CPUData; typedef struct FreeBSDProcessList_ { ProcessList super; kvm_t* kd; - int zfsArcEnabled; - unsigned long long int memWire; unsigned long long int memActive; unsigned long long int memInactive; unsigned long long int memFree; - unsigned long long int memZfsArc; + ZfsArcStats zfs; CPUData* cpus; - unsigned long *cp_time_o; - unsigned long *cp_time_n; + Hashtable* ttys; - unsigned long *cp_times_o; - unsigned long *cp_times_n; - -} FreeBSDProcessList; + unsigned long* cp_time_o; + unsigned long* cp_time_n; + unsigned long* cp_times_o; + unsigned long* cp_times_n; +} FreeBSDProcessList; -ProcessList* ProcessList_new(UsersTable* usersTable, Hashtable* pidWhiteList, uid_t userId); +ProcessList* ProcessList_new(UsersTable* usersTable, Hashtable* pidMatchList, uid_t userId); void ProcessList_delete(ProcessList* this); -char* FreeBSDProcessList_readProcessName(kvm_t* kd, struct kinfo_proc* kproc, int* basenameEnd); - -char* FreeBSDProcessList_readJailName(struct kinfo_proc* kproc); - -void ProcessList_goThroughEntries(ProcessList* this); +void ProcessList_goThroughEntries(ProcessList* super, bool pauseProcessUpdate); #endif diff --git a/freebsd/Platform.c b/freebsd/Platform.c index 5dd6ca41a..9c53ba818 100644 --- a/freebsd/Platform.c +++ b/freebsd/Platform.c @@ -1,43 +1,42 @@ /* htop - freebsd/Platform.c (C) 2014 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ #include "Platform.h" -#include "Meter.h" -#include "CPUMeter.h" -#include "MemoryMeter.h" -#include "SwapMeter.h" -#include "TasksMeter.h" -#include "LoadAverageMeter.h" -#include "UptimeMeter.h" -#include "ClockMeter.h" -#include "HostnameMeter.h" -#include "FreeBSDProcess.h" -#include "FreeBSDProcessList.h" -#include +#include +#include +#include +#include +#include +#include #include #include -#include +#include #include -#include -#include - -/*{ -#include "Action.h" -#include "BatteryMeter.h" -#include "SignalsPanel.h" -extern ProcessFieldData Process_fields[]; - -}*/ +#include "CPUMeter.h" +#include "ClockMeter.h" +#include "DateMeter.h" +#include "DateTimeMeter.h" +#include "DiskIOMeter.h" +#include "FreeBSDProcess.h" +#include "FreeBSDProcessList.h" +#include "HostnameMeter.h" +#include "LoadAverageMeter.h" +#include "Macros.h" +#include "MemoryMeter.h" +#include "Meter.h" +#include "NetworkIOMeter.h" +#include "SwapMeter.h" +#include "TasksMeter.h" +#include "UptimeMeter.h" +#include "zfs/ZfsArcMeter.h" +#include "zfs/ZfsCompressedArcMeter.h" -#ifndef CLAMP -#define CLAMP(x,low,high) (((x)>(high))?(high):(((x)<(low))?(low):(x))) -#endif ProcessField Platform_defaultFields[] = { PID, USER, PRIORITY, NICE, M_SIZE, M_RESIDENT, STATE, PERCENT_CPU, PERCENT_MEM, TIME, COMM, 0 }; @@ -80,15 +79,17 @@ const SignalItem Platform_signals[] = { { .name = "33 SIGLIBRT", .number = 33 }, }; -const unsigned int Platform_numberOfSignals = sizeof(Platform_signals)/sizeof(SignalItem); +const unsigned int Platform_numberOfSignals = ARRAYSIZE(Platform_signals); void Platform_setBindings(Htop_Action* keys) { (void) keys; } -MeterClass* Platform_meterTypes[] = { +const MeterClass* const Platform_meterTypes[] = { &CPUMeter_class, &ClockMeter_class, + &DateMeter_class, + &DateTimeMeter_class, &LoadAverageMeter_class, &LoadMeter_class, &MemoryMeter_class, @@ -99,11 +100,21 @@ MeterClass* Platform_meterTypes[] = { &HostnameMeter_class, &AllCPUsMeter_class, &AllCPUs2Meter_class, + &AllCPUs4Meter_class, + &AllCPUs8Meter_class, &LeftCPUsMeter_class, &RightCPUsMeter_class, &LeftCPUs2Meter_class, &RightCPUs2Meter_class, + &LeftCPUs4Meter_class, + &RightCPUs4Meter_class, + &LeftCPUs8Meter_class, + &RightCPUs8Meter_class, &BlankMeter_class, + &ZfsArcMeter_class, + &ZfsCompressedArcMeter_class, + &DiskIOMeter_class, + &NetworkIOMeter_class, NULL }; @@ -149,15 +160,15 @@ int Platform_getMaxPid() { } double Platform_setCPUValues(Meter* this, int cpu) { - FreeBSDProcessList* fpl = (FreeBSDProcessList*) this->pl; + const FreeBSDProcessList* fpl = (const FreeBSDProcessList*) this->pl; int cpus = this->pl->cpuCount; - CPUData* cpuData; + const CPUData* cpuData; if (cpus == 1) { - // single CPU box has everything in fpl->cpus[0] - cpuData = &(fpl->cpus[0]); + // single CPU box has everything in fpl->cpus[0] + cpuData = &(fpl->cpus[0]); } else { - cpuData = &(fpl->cpus[cpu]); + cpuData = &(fpl->cpus[cpu]); } double percent; @@ -168,22 +179,24 @@ double Platform_setCPUValues(Meter* this, int cpu) { if (this->pl->settings->detailedCPUTime) { v[CPU_METER_KERNEL] = cpuData->systemPercent; v[CPU_METER_IRQ] = cpuData->irqPercent; - Meter_setItems(this, 4); - percent = v[0]+v[1]+v[2]+v[3]; + this->curItems = 4; + percent = v[0] + v[1] + v[2] + v[3]; } else { v[2] = cpuData->systemAllPercent; - Meter_setItems(this, 3); - percent = v[0]+v[1]+v[2]; + this->curItems = 3; + percent = v[0] + v[1] + v[2]; } percent = CLAMP(percent, 0.0, 100.0); - if (isnan(percent)) percent = 0.0; + + v[CPU_METER_FREQUENCY] = NAN; + return percent; } void Platform_setMemoryValues(Meter* this) { // TODO - ProcessList* pl = (ProcessList*) this->pl; + const ProcessList* pl = this->pl; this->total = pl->totalMem; this->values[0] = pl->usedMem; @@ -192,16 +205,151 @@ void Platform_setMemoryValues(Meter* this) { } void Platform_setSwapValues(Meter* this) { - ProcessList* pl = (ProcessList*) this->pl; + const ProcessList* pl = this->pl; this->total = pl->totalSwap; this->values[0] = pl->usedSwap; } -void Platform_setTasksValues(Meter* this) { - // TODO +void Platform_setZfsArcValues(Meter* this) { + const FreeBSDProcessList* fpl = (const FreeBSDProcessList*) this->pl; + + ZfsArcMeter_readStats(this, &(fpl->zfs)); +} + +void Platform_setZfsCompressedArcValues(Meter* this) { + const FreeBSDProcessList* fpl = (const FreeBSDProcessList*) this->pl; + + ZfsCompressedArcMeter_readStats(this, &(fpl->zfs)); } char* Platform_getProcessEnv(pid_t pid) { - // TODO - return NULL; + int mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_ENV, pid }; + + size_t capacity = ARG_MAX; + char* env = xMalloc(capacity); + + int err = sysctl(mib, 4, env, &capacity, NULL, 0); + if (err) { + free(env); + return NULL; + } + + if (env[capacity - 1] || env[capacity - 2]) { + env = xRealloc(env, capacity + 2); + env[capacity] = 0; + env[capacity + 1] = 0; + } + + return env; +} + +char* Platform_getInodeFilename(pid_t pid, ino_t inode) { + (void)pid; + (void)inode; + return NULL; +} + +FileLocks_ProcessData* Platform_getProcessLocks(pid_t pid) { + (void)pid; + return NULL; +} + +bool Platform_getDiskIO(DiskIOData* data) { + + if (devstat_checkversion(NULL) < 0) + return false; + + struct devinfo info = { 0 }; + struct statinfo current = { .dinfo = &info }; + + // get number of devices + if (devstat_getdevs(NULL, ¤t) < 0) + return false; + + int count = current.dinfo->numdevs; + + unsigned long int bytesReadSum = 0, bytesWriteSum = 0, timeSpendSum = 0; + + // get data + for (int i = 0; i < count; i++) { + uint64_t bytes_read, bytes_write; + long double busy_time; + + devstat_compute_statistics(¤t.dinfo->devices[i], + NULL, + 1.0, + DSM_TOTAL_BYTES_READ, &bytes_read, + DSM_TOTAL_BYTES_WRITE, &bytes_write, + DSM_TOTAL_BUSY_TIME, &busy_time, + DSM_NONE); + + bytesReadSum += bytes_read; + bytesWriteSum += bytes_write; + timeSpendSum += 1000 * busy_time; + } + + data->totalBytesRead = bytesReadSum; + data->totalBytesWritten = bytesWriteSum; + data->totalMsTimeSpend = timeSpendSum; + return true; +} + +bool Platform_getNetworkIO(unsigned long int* bytesReceived, + unsigned long int* packetsReceived, + unsigned long int* bytesTransmitted, + unsigned long int* packetsTransmitted) { + int r; + + // get number of interfaces + int count; + size_t countLen = sizeof(count); + const int countMib[] = { CTL_NET, PF_LINK, NETLINK_GENERIC, IFMIB_SYSTEM, IFMIB_IFCOUNT }; + + r = sysctl(countMib, ARRAYSIZE(countMib), &count, &countLen, NULL, 0); + if (r < 0) + return false; + + + unsigned long int bytesReceivedSum = 0, packetsReceivedSum = 0, bytesTransmittedSum = 0, packetsTransmittedSum = 0; + + for (int i = 1; i <= count; i++) { + struct ifmibdata ifmd; + size_t ifmdLen = sizeof(ifmd); + + const int dataMib[] = { CTL_NET, PF_LINK, NETLINK_GENERIC, IFMIB_IFDATA, i, IFDATA_GENERAL }; + + r = sysctl(dataMib, ARRAYSIZE(dataMib), &ifmd, &ifmdLen, NULL, 0); + if (r < 0) + continue; + + if (ifmd.ifmd_flags & IFF_LOOPBACK) + continue; + + bytesReceivedSum += ifmd.ifmd_data.ifi_ibytes; + packetsReceivedSum += ifmd.ifmd_data.ifi_ipackets; + bytesTransmittedSum += ifmd.ifmd_data.ifi_obytes; + packetsTransmittedSum += ifmd.ifmd_data.ifi_opackets; + } + + *bytesReceived = bytesReceivedSum; + *packetsReceived = packetsReceivedSum; + *bytesTransmitted = bytesTransmittedSum; + *packetsTransmitted = packetsTransmittedSum; + return true; +} + +void Platform_getBattery(double* level, ACPresence* isOnAC) { + int life; + size_t life_len = sizeof(life); + if (sysctlbyname("hw.acpi.battery.life", &life, &life_len, NULL, 0) == -1) + *level = NAN; + else + *level = life; + + int acline; + size_t acline_len = sizeof(acline); + if (sysctlbyname("hw.acpi.acline", &acline, &acline_len, NULL, 0) == -1) + *isOnAC = AC_ERROR; + else + *isOnAC = acline == 0 ? AC_ABSENT : AC_PRESENT; } diff --git a/freebsd/Platform.h b/freebsd/Platform.h index 1735e7e3b..5e3b29fb6 100644 --- a/freebsd/Platform.h +++ b/freebsd/Platform.h @@ -1,25 +1,23 @@ -/* Do not edit this file. It was automatically generated. */ - #ifndef HEADER_Platform #define HEADER_Platform /* htop - freebsd/Platform.h (C) 2014 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ +#include +#include + #include "Action.h" #include "BatteryMeter.h" +#include "DiskIOMeter.h" +#include "ProcessLocksScreen.h" #include "SignalsPanel.h" extern ProcessFieldData Process_fields[]; - -#ifndef CLAMP -#define CLAMP(x,low,high) (((x)>(high))?(high):(((x)<(low))?(low):(x))) -#endif - extern ProcessField Platform_defaultFields[]; extern int Platform_numberOfFields; @@ -30,13 +28,13 @@ extern const unsigned int Platform_numberOfSignals; void Platform_setBindings(Htop_Action* keys); -extern MeterClass* Platform_meterTypes[]; +extern const MeterClass* const Platform_meterTypes[]; -int Platform_getUptime(); +int Platform_getUptime(void); void Platform_getLoadAverage(double* one, double* five, double* fifteen); -int Platform_getMaxPid(); +int Platform_getMaxPid(void); double Platform_setCPUValues(Meter* this, int cpu); @@ -44,8 +42,23 @@ void Platform_setMemoryValues(Meter* this); void Platform_setSwapValues(Meter* this); -void Platform_setTasksValues(Meter* this); +void Platform_setZfsArcValues(Meter* this); + +void Platform_setZfsCompressedArcValues(Meter* this); char* Platform_getProcessEnv(pid_t pid); +char* Platform_getInodeFilename(pid_t pid, ino_t inode); + +FileLocks_ProcessData* Platform_getProcessLocks(pid_t pid); + +bool Platform_getDiskIO(DiskIOData* data); + +bool Platform_getNetworkIO(unsigned long int* bytesReceived, + unsigned long int* packetsReceived, + unsigned long int* bytesTransmitted, + unsigned long int* packetsTransmitted); + +void Platform_getBattery(double* level, ACPresence* isOnAC); + #endif diff --git a/htop.1.in b/htop.1.in index 149b1465a..6048449d7 100644 --- a/htop.1.in +++ b/htop.1.in @@ -1,31 +1,43 @@ -.TH "HTOP" "1" "2015" "@PACKAGE_STRING@" "Utils" +.TH "HTOP" "1" "2020" "@PACKAGE_STRING@" "User Commands" .SH "NAME" htop \- interactive process viewer .SH "SYNOPSIS" -.LP -.B htop [\fI\-dChustv\fR] +.LP +.B htop +.RB [ \-dCFhpustvH ] .SH "DESCRIPTION" -.LP -Htop is a free (GPL) ncurses-based process viewer for Linux. .LP -It is similar to top, but allows you to scroll vertically and horizontally, -so you can see all the processes running on the system, along with their full -command lines, as well as viewing them as a process tree, selecting multiple -processes and acting on them all at once. +.B htop +is a cross-platform ncurses-based process viewer. +.LP +It is similar to +.BR top , +but allows you to scroll vertically and horizontally, and interact using +a pointing device (mouse). +You can observe all processes running on the system, along with their +command line arguments, as well as view them in a tree format, select +multiple processes and acting on them all at once. .LP Tasks related to processes (killing, renicing) can be done without entering their PIDs. -.br +.br .SH "COMMAND-LINE OPTIONS" .LP Mandatory arguments to long options are mandatory for short options too. -.LP +.LP .TP \fB\-d \-\-delay=DELAY\fR -Delay between updates, in tenths of seconds +Delay between updates, in tenths of seconds. If the delay value is +less than 1 it is increased to 1, i.e. 1/10 second. If the delay value +is greater than 100, it is decreased to 100, i.e. 10 seconds. .TP \fB\-C \-\-no-color \-\-no-colour\fR -Start htop in monochrome mode +Start +.B htop +in monochrome mode +.TP +\fB\-F \-\-filter=FILTER +Filter processes by command .TP \fB\-h \-\-help Display a help message and exit @@ -39,17 +51,25 @@ Sort by this column (use \-\-sort\-key help for a column list) \fB\-u \-\-user=USERNAME\fR Show only the processes of a given user .TP -\fB\-v \-\-version +\fB\-U \-\-no-unicode\fR +Do not use unicode but ASCII characters for graph meters +.TP +\fB\-M \-\-no-mouse\fR +Disable support of mouse control +.TP +\fB\-V \-\-version Output version information and exit .TP \fB\-t \-\-tree Show processes in tree view -.PP -.br +.TP +\fB\-H \-\-highlight-changes=DELAY\fR +Highlight new and old processes .SH "INTERACTIVE COMMANDS" -.LP -The following commands are supported while in htop: -.LP +.LP +The following commands are supported while in +.BR htop : +.LP .TP 5 .B Up, Alt-k Select (highlight) the previous process in the process list. Scroll the list @@ -102,6 +122,13 @@ update of system calls issued by the process. Display open files for a process: if lsof(1) is installed, pressing this key will display the list of file descriptors opened by the process. .TP +.B w +Display the command line of the selected process in a separate screen, wrapped +onto multiple lines as needed. +.TP +.B x +Display the active file locks of the selected process in a separate screen. +.TP .B F1, h, ? Go to the help screen .TP @@ -151,7 +178,7 @@ Quit Invert the sort order: if sort order is increasing, switch to decreasing, and vice-versa. .TP -.B +, \- +.B +, \- When in tree view mode, expand or collapse subtree. When a subtree is collapsed a "+" sign shows to the left of the process name. .TP @@ -188,25 +215,31 @@ userspace processes in the process list. (This is a toggle key.) .B p Show full paths to running programs, where applicable. (This is a toggle key.) .TP +.B Z +Pause/resume process updates. +.TP .B Ctrl-L Refresh: redraw screen and recalculate values. .TP .B Numbers PID search: type in process ID and the selection highlight will be moved to it. .PD - .SH "COLUMNS" -.LP +.LP The following columns can display data about each process. A value of '\-' in all the rows indicates that a column is unsupported on your system, or -currently unimplemented in htop. The names below are the ones used in the +currently unimplemented in +.BR htop . +The names below are the ones used in the "Available Columns" section of the setup screen. If a different name is -shown in htop's main screen, it is shown below in parenthesis. -.LP +shown in +.BR htop 's +main screen, it is shown below in parenthesis. +.LP .TP 5 .B Command The full command line of the process (i.e. program name and arguments). -.TP +.TP .B PID The process ID. .TP @@ -227,7 +260,7 @@ The process's group ID. .TP .B SESSION (SID) The process's session ID. -.TP +.TP .B TTY_NR (TTY) The controlling terminal of the process. .TP @@ -303,6 +336,17 @@ The library size of the process. .B M_DT (DIRTY) The size of the dirty pages of the process. .TP +.B M_SWAP (SWAP) +The size of the process's swapped pages. +.TP +.B M_PSS (PSS) +The proportional set size, same as M_RESIDENT but each page is divided by the +number of processes sharing it. +.TP +.B M_M_PSSWP (PSSWP) +The proportional swap share of this mapping, unlike M_SWAP this does not take +into account swapped out page of underlying shmem objects. +.TP .B ST_UID (UID) The user ID of the process owner. .TP @@ -372,6 +416,9 @@ Which cgroup the process is in. .B OOM OOM killer score. .TP +.B CTXT +Incremental sum of voluntary and nonvoluntary context switches. +.TP .B IO_PRIORITY (IO) The I/O scheduling class followed by the priority if the class supports it: \fBR\fR for Realtime @@ -389,36 +436,44 @@ The percentage of time spent swapping in pages. Requires CAP_NET_ADMIN. .TP .B All other flags Currently unsupported (always displays '-'). - .SH "CONFIG FILE" -.LP -By default htop reads its configuration from the XDG-compliant path -~/.config/htop/htoprc -- the configuration file is overwritten by htop's -in-program Setup configuration, so it should not be hand-edited. If no -user configuration exists htop tries to read the system-wide configuration -from @sysconfdir@/htoprc and as a last resort, falls back to its -hard coded defaults. +.LP +By default +.B htop +reads its configuration from the XDG-compliant path +.IR ~/.config/htop/htoprc . +The configuration file is overwritten by +.BR htop 's +in-program Setup configuration, so it should not be hand-edited. +If no user configuration exists +.B htop +tries to read the system-wide configuration from +.I @sysconfdir@/htoprc +and as a last resort, falls back to its hard coded defaults. .LP You may override the location of the configuration file using the $HTOPRC environment variable (so you can have multiple configurations for different machines that share the same home directory, for example). - .SH "MEMORY SIZES" .LP -Memory sizes in htop are displayed as they are in tools from the GNU Coreutils -(when ran with the --human-readable option). This means that sizes are printed -in powers of 1024. (e.g., 1023M = 1072693248 Bytes) +Memory sizes in +.B htop +are displayed in a human-readable form. +Sizes are printed in powers of 1024. (e.g., 1023M = 1072693248 Bytes) .LP -The decision to use this convention was made in order to conserve screen space -and make memory size representations consistent throughout htop. - +The decision to use this convention was made in order to conserve screen +space and make memory size representations consistent throughout +.BR htop . .SH "SEE ALSO" -proc(5), top(1), free(1), ps(1), uptime(1), limits.conf(5) - +.BR proc (5), +.BR top (1), +.BR free (1), +.BR ps (1), +.BR uptime (1) +and +.BR limits.conf (5). .SH "AUTHORS" -.LP -htop is developed by Hisham Muhammad . .LP -This man page was written by Bartosz Fenski for the Debian -GNU/Linux distribution (but it may be used by others). It was updated by Hisham -Muhammad, and later by Vincent Launchbury, who wrote the 'Columns' section. +.B htop +was originally developed by Hisham Muhammad. +Nowadays it is maintained by the community at . diff --git a/htop.c b/htop.c index 8c88c782a..b36bd4b04 100644 --- a/htop.c +++ b/htop.c @@ -1,117 +1,152 @@ /* htop - htop.c (C) 2004-2011 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ -#include "config.h" +#include "config.h" // IWYU pragma: keep -#include "FunctionBar.h" -#include "Hashtable.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "Action.h" #include "ColumnsPanel.h" #include "CRT.h" +#include "Hashtable.h" +#include "Header.h" +#include "IncSet.h" #include "MainPanel.h" +#include "MetersPanel.h" +#include "Panel.h" +#include "Platform.h" +#include "Process.h" #include "ProcessList.h" +#include "ProvideCurses.h" #include "ScreenManager.h" #include "Settings.h" #include "UsersTable.h" -#include "Platform.h" +#include "XUtils.h" -#include -#include -#include -#include -#include -#include -#include //#link m -static void printVersionFlag() { - fputs("htop " VERSION " - " COPYRIGHT "\n" - "Released under the GNU GPL.\n\n", - stdout); - exit(0); +static void printVersionFlag(void) { + fputs("htop " VERSION "\n", stdout); } - -static void printHelpFlag() { - fputs("htop " VERSION " - " COPYRIGHT "\n" - "Released under the GNU GPL.\n\n" + +static void printHelpFlag(void) { + fputs("htop " VERSION "\n" + COPYRIGHT "\n" + "Released under the GNU GPLv2.\n\n" "-C --no-color Use a monochrome color scheme\n" "-d --delay=DELAY Set the delay between updates, in tenths of seconds\n" + "-F --filter=FILTER Show only the commands matching the given filter\n" "-h --help Print this help screen\n" + "-H --highlight-changes[=DELAY] Highlight new and old processes\n" + "-M --no-mouse Disable the mouse\n" + "-p --pid=PID[,PID,PID...] Show only the given PIDs\n" "-s --sort-key=COLUMN Sort by COLUMN (try --sort-key=help for a list)\n" "-t --tree Show the tree view by default\n" - "-u --user=USERNAME Show only processes of a given user\n" - "-p --pid=PID,[,PID,PID...] Show only the given PIDs\n" - "-v --version Print version info\n" + "-u --user[=USERNAME] Show only processes for a given user (or $USER)\n" + "-U --no-unicode Do not use unicode but plain ASCII\n" + "-V --version Print version info\n" "\n" "Long options may be passed with a single dash.\n\n" "Press F1 inside htop for online help.\n" "See 'man htop' for more information.\n", stdout); - exit(0); } // ---------------------------------------- typedef struct CommandLineSettings_ { - Hashtable* pidWhiteList; + Hashtable* pidMatchList; + char* commFilter; uid_t userId; int sortKey; int delay; bool useColors; + bool enableMouse; bool treeView; + bool allowUnicode; + bool highlightChanges; + int highlightDelaySecs; } CommandLineSettings; static CommandLineSettings parseArguments(int argc, char** argv) { CommandLineSettings flags = { - .pidWhiteList = NULL, - .userId = -1, // -1 is guaranteed to be an invalid uid_t (see setreuid(2)) + .pidMatchList = NULL, + .commFilter = NULL, + .userId = (uid_t)-1, // -1 is guaranteed to be an invalid uid_t (see setreuid(2)) .sortKey = 0, .delay = -1, .useColors = true, + .enableMouse = true, .treeView = false, + .allowUnicode = true, + .highlightChanges = false, + .highlightDelaySecs = -1, }; static struct option long_opts[] = { - {"help", no_argument, 0, 'h'}, - {"version", no_argument, 0, 'v'}, - {"delay", required_argument, 0, 'd'}, - {"sort-key", required_argument, 0, 's'}, - {"user", required_argument, 0, 'u'}, - {"no-color", no_argument, 0, 'C'}, - {"no-colour",no_argument, 0, 'C'}, - {"tree", no_argument, 0, 't'}, - {"pid", required_argument, 0, 'p'}, + {"help", no_argument, 0, 'h'}, + {"version", no_argument, 0, 'V'}, + {"delay", required_argument, 0, 'd'}, + {"sort-key", required_argument, 0, 's'}, + {"user", optional_argument, 0, 'u'}, + {"no-color", no_argument, 0, 'C'}, + {"no-colour", no_argument, 0, 'C'}, + {"no-mouse", no_argument, 0, 'M'}, + {"no-unicode", no_argument, 0, 'U'}, + {"tree", no_argument, 0, 't'}, + {"pid", required_argument, 0, 'p'}, + {"filter", required_argument, 0, 'F'}, + {"highlight-changes", optional_argument, 0, 'H'}, {0,0,0,0} }; int opt, opti=0; /* Parse arguments */ - while ((opt = getopt_long(argc, argv, "hvCs:td:u:p:", long_opts, &opti))) { + while ((opt = getopt_long(argc, argv, "hVMCs:td:u::Up:F:H::", long_opts, &opti))) { if (opt == EOF) break; switch (opt) { case 'h': printHelpFlag(); - break; - case 'v': + exit(0); + case 'V': printVersionFlag(); - break; + exit(0); case 's': - if (strcmp(optarg, "help") == 0) { + assert(optarg); /* please clang analyzer, cause optarg can be NULL in the 'u' case */ + if (String_eq(optarg, "help")) { for (int j = 1; j < Platform_numberOfFields; j++) { const char* name = Process_fields[j].name; if (name) printf ("%s\n", name); } exit(0); } - flags.sortKey = ColumnsPanel_fieldNameToIndex(optarg); + flags.sortKey = -1; + for (int j = 1; j < Platform_numberOfFields; j++) { + if (Process_fields[j].name == NULL) + continue; + if (String_eq(optarg, Process_fields[j].name)) { + flags.sortKey = j; + break; + } + } if (flags.sortKey == -1) { fprintf(stderr, "Error: invalid column \"%s\".\n", optarg); + exit(1); } break; case 'd': @@ -120,37 +155,81 @@ static CommandLineSettings parseArguments(int argc, char** argv) { if (flags.delay > 100) flags.delay = 100; } else { fprintf(stderr, "Error: invalid delay value \"%s\".\n", optarg); + exit(1); } break; case 'u': - if (!Action_setUserOnly(optarg, &(flags.userId))) { - fprintf(stderr, "Error: invalid user \"%s\".\n", optarg); + { + const char *username = optarg; + if (!username && optind < argc && argv[optind] != NULL && + (argv[optind][0] != '\0' && argv[optind][0] != '-')) { + username = argv[optind++]; + } + + if (!username) { + flags.userId = geteuid(); + } else if (!Action_setUserOnly(username, &(flags.userId))) { + fprintf(stderr, "Error: invalid user \"%s\".\n", username); + exit(1); } break; + } case 'C': flags.useColors = false; break; + case 'M': + flags.enableMouse = false; + break; + case 'U': + flags.allowUnicode = false; + break; case 't': flags.treeView = true; break; case 'p': { + assert(optarg); /* please clang analyzer, cause optarg can be NULL in the 'u' case */ char* argCopy = xStrdup(optarg); char* saveptr; char* pid = strtok_r(argCopy, ",", &saveptr); - if(!flags.pidWhiteList) { - flags.pidWhiteList = Hashtable_new(8, false); + if(!flags.pidMatchList) { + flags.pidMatchList = Hashtable_new(8, false); } while(pid) { unsigned int num_pid = atoi(pid); - Hashtable_put(flags.pidWhiteList, num_pid, (void *) 1); + // deepcode ignore CastIntegerToAddress: we just want a non-NUll pointer here + Hashtable_put(flags.pidMatchList, num_pid, (void *) 1); pid = strtok_r(NULL, ",", &saveptr); } free(argCopy); break; } + case 'F': { + assert(optarg); + flags.commFilter = xStrdup(optarg); + + break; + } + case 'H': { + const char *delay = optarg; + if (!delay && optind < argc && argv[optind] != NULL && + (argv[optind][0] != '\0' && argv[optind][0] != '-')) { + delay = argv[optind++]; + } + if (delay) { + if (sscanf(delay, "%16d", &(flags.highlightDelaySecs)) == 1) { + if (flags.highlightDelaySecs < 1) + flags.highlightDelaySecs = 1; + } else { + fprintf(stderr, "Error: invalid highlight delay value \"%s\".\n", delay); + exit(1); + } + } + flags.highlightChanges = true; + break; + } default: exit(1); } @@ -168,30 +247,48 @@ static void millisleep(unsigned long millisec) { } } +static void setCommFilter(State* state, char** commFilter) { + MainPanel* panel = (MainPanel*)state->panel; + ProcessList* pl = state->pl; + IncSet* inc = panel->inc; + size_t maxlen = sizeof(inc->modes[INC_FILTER].buffer) - 1; + char* buffer = inc->modes[INC_FILTER].buffer; + + strncpy(buffer, *commFilter, maxlen); + buffer[maxlen] = 0; + inc->modes[INC_FILTER].index = strlen(buffer); + inc->filtering = true; + pl->incFilter = IncSet_filter(inc); + + free(*commFilter); + *commFilter = NULL; +} + int main(int argc, char** argv) { char *lc_ctype = getenv("LC_CTYPE"); - if(lc_ctype != NULL) + if (lc_ctype != NULL) { setlocale(LC_CTYPE, lc_ctype); - else if ((lc_ctype = getenv("LC_ALL"))) + } else if ((lc_ctype = getenv("LC_ALL"))) { setlocale(LC_CTYPE, lc_ctype); - else + } else { setlocale(LC_CTYPE, ""); + } CommandLineSettings flags = parseArguments(argc, argv); // may exit() -#ifdef HAVE_PROC +#ifdef HTOP_LINUX if (access(PROCDIR, R_OK) != 0) { fprintf(stderr, "Error: could not read procfs (compiled to look in %s).\n", PROCDIR); exit(1); } #endif - + Process_setupColumnWidths(); - + UsersTable* ut = UsersTable_new(); - ProcessList* pl = ProcessList_new(ut, flags.pidWhiteList, flags.userId); - + ProcessList* pl = ProcessList_new(ut, flags.pidMatchList, flags.userId); + Settings* settings = Settings_new(pl->cpuCount); pl->settings = settings; @@ -199,20 +296,32 @@ int main(int argc, char** argv) { Header_populateFromSettings(header); - if (flags.delay != -1) + if (flags.delay != -1) { settings->delay = flags.delay; - if (!flags.useColors) + } + if (!flags.useColors) { settings->colorScheme = COLORSCHEME_MONOCHROME; - if (flags.treeView) + } + if (!flags.enableMouse) { + settings->enableMouse = false; + } + if (flags.treeView) { settings->treeView = true; + } + if (flags.highlightChanges) { + settings->highlightChanges = true; + } + if (flags.highlightDelaySecs != -1) { + settings->highlightDelaySecs = flags.highlightDelaySecs; + } + + CRT_init(settings->delay, settings->colorScheme, flags.allowUnicode); - CRT_init(settings->delay, settings->colorScheme); - MainPanel* panel = MainPanel_new(); ProcessList_setPanel(pl, (Panel*) panel); MainPanel_updateTreeFunctions(panel, settings->treeView); - + if (flags.sortKey > 0) { settings->sortKey = flags.sortKey; settings->treeView = false; @@ -226,23 +335,28 @@ int main(int argc, char** argv) { .pl = pl, .panel = (Panel*) panel, .header = header, + .pauseProcessUpdate = false, }; + MainPanel_setState(panel, &state); - - ScreenManager* scr = ScreenManager_new(0, header->height, 0, -1, HORIZONTAL, header, settings, true); + if (flags.commFilter) { + setCommFilter(&state, &(flags.commFilter)); + } + + ScreenManager* scr = ScreenManager_new(0, header->height, 0, -1, HORIZONTAL, header, settings, &state, true); ScreenManager_add(scr, (Panel*) panel, -1); - ProcessList_scan(pl); + ProcessList_scan(pl, false); millisleep(75); - ProcessList_scan(pl); + ProcessList_scan(pl, false); + + ScreenManager_run(scr, NULL, NULL); - ScreenManager_run(scr, NULL, NULL); - attron(CRT_colors[RESET_COLOR]); mvhline(LINES-1, 0, ' ', COLS); attroff(CRT_colors[RESET_COLOR]); refresh(); - + CRT_done(); if (settings->changed) Settings_write(settings); @@ -250,12 +364,13 @@ int main(int argc, char** argv) { ProcessList_delete(pl); ScreenManager_delete(scr); - + MetersPanel_cleanup(); + UsersTable_delete(ut); Settings_delete(settings); - - if(flags.pidWhiteList) { - Hashtable_delete(flags.pidWhiteList); + + if(flags.pidMatchList) { + Hashtable_delete(flags.pidMatchList); } return 0; } diff --git a/htop.desktop b/htop.desktop index d59a26508..20bed4902 100644 --- a/htop.desktop +++ b/htop.desktop @@ -4,6 +4,7 @@ Version=1.0 Name=Htop GenericName=Process Viewer GenericName[ca]=Visualitzador de processos +GenericName[da]=Procesfremviser GenericName[de]=Prozessanzeige GenericName[en_GB]=Process Viewer GenericName[es]=Visor de procesos @@ -32,6 +33,7 @@ GenericName[zh_CN]=进程查看器 GenericName[zh_TW]=行程檢視器 Comment=Show System Processes Comment[ca]=Visualitzeu els processos del sistema +Comment[da]=Vis systemprocesser Comment[de]=Systemprozesse anzeigen Comment[en_GB]=Show System Processes Comment[es]=Mostrar procesos del sistema diff --git a/htop.h b/htop.h deleted file mode 100644 index 7faa6c64d..000000000 --- a/htop.h +++ /dev/null @@ -1,19 +0,0 @@ -/* Do not edit this file. It was automatically generated. */ - -#ifndef HEADER_htop -#define HEADER_htop -/* -htop - htop.h -(C) 2004-2011 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file -in the source distribution for its full text. -*/ - -//#link m - -// ---------------------------------------- - - -int main(int argc, char** argv); - -#endif diff --git a/iwyu/htop.imp b/iwyu/htop.imp new file mode 100644 index 000000000..c95bfaffb --- /dev/null +++ b/iwyu/htop.imp @@ -0,0 +1,10 @@ +[ + { include: ["", "private", "\"ProvideCurses.h\"", "public"] }, + { include: ["", "private", "\"ProvideCurses.h\"", "public"] }, + { include: ["", "private", "\"ProvideCurses.h\"", "public"] }, + { include: ["", "private", "\"ProvideCurses.h\"", "public"] }, + + { include: ["", "private", "", "public"] }, + + { include: ["", "private", "", "public"] }, +] diff --git a/iwyu/run_iwyu.sh b/iwyu/run_iwyu.sh new file mode 100755 index 000000000..37843dcf9 --- /dev/null +++ b/iwyu/run_iwyu.sh @@ -0,0 +1,14 @@ +#!/bin/sh + +SCRIPT=$(readlink -f "$0") +SCRIPTDIR=$(dirname "$SCRIPT") +SOURCEDIR="$SCRIPTDIR/.." + +PKG_NL3=$(pkg-config --cflags libnl-3.0) + +IWYU=${IWYU:-iwyu} + +cd "$SOURCEDIR" || exit + +make clean +make --keep-going --silent CC="$IWYU" CFLAGS="-Xiwyu --no_comments -Xiwyu --no_fwd_decl -Xiwyu --mapping_file='$SCRIPTDIR/htop.imp' $PKG_NL3" diff --git a/linux/Battery.c b/linux/Battery.c deleted file mode 100644 index aedacabc8..000000000 --- a/linux/Battery.c +++ /dev/null @@ -1,312 +0,0 @@ -/* -htop - linux/Battery.c -(C) 2004-2014 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file -in the source distribution for its full text. - -Linux battery readings written by Ian P. Hands (iphands@gmail.com, ihands@redhat.com). -*/ - -#ifndef _GNU_SOURCE -#define _GNU_SOURCE -#endif -#include -#include -#include -#include -#include -#include -#include -#include "BatteryMeter.h" -#include "StringUtils.h" - -#define SYS_POWERSUPPLY_DIR "/sys/class/power_supply" - -// ---------------------------------------- -// READ FROM /proc -// ---------------------------------------- - -// This implementation reading from from /proc/acpi is really inefficient, -// but I think this is on the way out so I did not rewrite it. -// The /sys implementation below does things the right way. - -static unsigned long int parseBatInfo(const char *fileName, const unsigned short int lineNum, const unsigned short int wordNum) { - const char batteryPath[] = PROCDIR "/acpi/battery/"; - DIR* batteryDir = opendir(batteryPath); - if (!batteryDir) - return 0; - - #define MAX_BATTERIES 64 - char* batteries[MAX_BATTERIES]; - unsigned int nBatteries = 0; - memset(batteries, 0, MAX_BATTERIES * sizeof(char*)); - - while (nBatteries < MAX_BATTERIES) { - struct dirent* dirEntry = readdir(batteryDir); - if (!dirEntry) - break; - char* entryName = dirEntry->d_name; - if (strncmp(entryName, "BAT", 3)) - continue; - batteries[nBatteries] = xStrdup(entryName); - nBatteries++; - } - closedir(batteryDir); - - unsigned long int total = 0; - for (unsigned int i = 0; i < nBatteries; i++) { - char infoPath[30]; - xSnprintf(infoPath, sizeof infoPath, "%s%s/%s", batteryPath, batteries[i], fileName); - - FILE* file = fopen(infoPath, "r"); - if (!file) { - break; - } - - char* line = NULL; - for (unsigned short int i = 0; i < lineNum; i++) { - free(line); - line = String_readLine(file); - if (!line) break; - } - - fclose(file); - - if (!line) break; - - char *foundNumStr = String_getToken(line, wordNum); - const unsigned long int foundNum = atoi(foundNumStr); - free(foundNumStr); - free(line); - - total += foundNum; - } - - for (unsigned int i = 0; i < nBatteries; i++) { - free(batteries[i]); - } - - return total; -} - -static ACPresence procAcpiCheck() { - ACPresence isOn = AC_ERROR; - const char *power_supplyPath = PROCDIR "/acpi/ac_adapter"; - DIR *dir = opendir(power_supplyPath); - if (!dir) { - return AC_ERROR; - } - - for (;;) { - struct dirent* dirEntry = readdir((DIR *) dir); - if (!dirEntry) - break; - - char* entryName = (char *) dirEntry->d_name; - - if (entryName[0] != 'A') - continue; - - char statePath[50]; - xSnprintf((char *) statePath, sizeof statePath, "%s/%s/state", power_supplyPath, entryName); - FILE* file = fopen(statePath, "r"); - if (!file) { - isOn = AC_ERROR; - continue; - } - char* line = String_readLine(file); - fclose(file); - if (!line) continue; - - const char *isOnline = String_getToken(line, 2); - free(line); - - if (strcmp(isOnline, "on-line") == 0) { - isOn = AC_PRESENT; - } else { - isOn = AC_ABSENT; - } - free((char *) isOnline); - if (isOn == AC_PRESENT) { - break; - } - } - - if (dir) - closedir(dir); - return isOn; -} - -static double Battery_getProcBatData() { - const unsigned long int totalFull = parseBatInfo("info", 3, 4); - if (totalFull == 0) - return 0; - - const unsigned long int totalRemain = parseBatInfo("state", 5, 3); - if (totalRemain == 0) - return 0; - - return totalRemain * 100.0 / (double) totalFull; -} - -static void Battery_getProcData(double* level, ACPresence* isOnAC) { - *level = Battery_getProcBatData(); - *isOnAC = procAcpiCheck(); -} - -// ---------------------------------------- -// READ FROM /sys -// ---------------------------------------- - -static inline ssize_t xread(int fd, void *buf, size_t count) { - // Read some bytes. Retry on EINTR and when we don't get as many bytes as we requested. - size_t alreadyRead = 0; - for(;;) { - ssize_t res = read(fd, buf, count); - if (res == -1 && errno == EINTR) continue; - if (res > 0) { - buf = ((char*)buf)+res; - count -= res; - alreadyRead += res; - } - if (res == -1) return -1; - if (count == 0 || res == 0) return alreadyRead; - } -} - -static void Battery_getSysData(double* level, ACPresence* isOnAC) { - - *level = 0; - *isOnAC = AC_ERROR; - - DIR *dir = opendir(SYS_POWERSUPPLY_DIR); - if (!dir) - return; - - unsigned long int totalFull = 0; - unsigned long int totalRemain = 0; - - for (;;) { - struct dirent* dirEntry = readdir((DIR *) dir); - if (!dirEntry) - break; - char* entryName = (char *) dirEntry->d_name; - const char filePath[50]; - - if (entryName[0] == 'B' && entryName[1] == 'A' && entryName[2] == 'T') { - - xSnprintf((char *) filePath, sizeof filePath, SYS_POWERSUPPLY_DIR "/%s/uevent", entryName); - int fd = open(filePath, O_RDONLY); - if (fd == -1) { - closedir(dir); - return; - } - char buffer[1024]; - ssize_t buflen = xread(fd, buffer, 1023); - close(fd); - if (buflen < 1) { - closedir(dir); - return; - } - buffer[buflen] = '\0'; - char *buf = buffer; - char *line = NULL; - bool full = false; - bool now = false; - while ((line = strsep(&buf, "\n")) != NULL) { - #define match(str,prefix) \ - (String_startsWith(str,prefix) ? (str) + strlen(prefix) : NULL) - const char* ps = match(line, "POWER_SUPPLY_"); - if (!ps) { - continue; - } - const char* energy = match(ps, "ENERGY_"); - if (!energy) { - energy = match(ps, "CHARGE_"); - } - if (!energy) { - continue; - } - const char* value = (!full) ? match(energy, "FULL=") : NULL; - if (value) { - totalFull += atoi(value); - full = true; - if (now) break; - continue; - } - value = (!now) ? match(energy, "NOW=") : NULL; - if (value) { - totalRemain += atoi(value); - now = true; - if (full) break; - continue; - } - } - #undef match - } else if (entryName[0] == 'A') { - if (*isOnAC != AC_ERROR) { - continue; - } - - xSnprintf((char *) filePath, sizeof filePath, SYS_POWERSUPPLY_DIR "/%s/online", entryName); - int fd = open(filePath, O_RDONLY); - if (fd == -1) { - closedir(dir); - return; - } - char buffer[2] = ""; - for(;;) { - ssize_t res = read(fd, buffer, 1); - if (res == -1 && errno == EINTR) continue; - break; - } - close(fd); - if (buffer[0] == '0') { - *isOnAC = AC_ABSENT; - } else if (buffer[0] == '1') { - *isOnAC = AC_PRESENT; - } - } - } - closedir(dir); - *level = totalFull > 0 ? ((double) totalRemain * 100) / (double) totalFull : 0; -} - -static enum { BAT_PROC, BAT_SYS, BAT_ERR } Battery_method = BAT_PROC; - -static time_t Battery_cacheTime = 0; -static double Battery_cacheLevel = 0; -static ACPresence Battery_cacheIsOnAC = 0; - -void Battery_getData(double* level, ACPresence* isOnAC) { - time_t now = time(NULL); - // update battery reading is slow. Update it each 10 seconds only. - if (now < Battery_cacheTime + 10) { - *level = Battery_cacheLevel; - *isOnAC = Battery_cacheIsOnAC; - return; - } - - if (Battery_method == BAT_PROC) { - Battery_getProcData(level, isOnAC); - if (*level == 0) { - Battery_method = BAT_SYS; - } - } - if (Battery_method == BAT_SYS) { - Battery_getSysData(level, isOnAC); - if (*level == 0) { - Battery_method = BAT_ERR; - } - } - if (Battery_method == BAT_ERR) { - *level = -1; - *isOnAC = AC_ERROR; - } - if (*level > 100.0) { - *level = 100.0; - } - Battery_cacheLevel = *level; - Battery_cacheIsOnAC = *isOnAC; - Battery_cacheTime = now; -} diff --git a/linux/Battery.h b/linux/Battery.h deleted file mode 100644 index cfb6c3242..000000000 --- a/linux/Battery.h +++ /dev/null @@ -1,34 +0,0 @@ -/* Do not edit this file. It was automatically generated. */ - -#ifndef HEADER_Battery -#define HEADER_Battery -/* -htop - linux/Battery.h -(C) 2004-2014 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file -in the source distribution for its full text. - -Linux battery readings written by Ian P. Hands (iphands@gmail.com, ihands@redhat.com). -*/ - -#ifndef _GNU_SOURCE -#define _GNU_SOURCE -#endif - -#define SYS_POWERSUPPLY_DIR "/sys/class/power_supply" - -// ---------------------------------------- -// READ FROM /proc -// ---------------------------------------- - -// This implementation reading from from /proc/acpi is really inefficient, -// but I think this is on the way out so I did not rewrite it. -// The /sys implementation below does things the right way. - -// ---------------------------------------- -// READ FROM /sys -// ---------------------------------------- - -void Battery_getData(double* level, ACPresence* isOnAC); - -#endif diff --git a/linux/IOPriority.c b/linux/IOPriority.c deleted file mode 100644 index dd7c84a14..000000000 --- a/linux/IOPriority.c +++ /dev/null @@ -1,41 +0,0 @@ -/* -htop - IOPriority.c -(C) 2004-2012 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file -in the source distribution for its full text. - -Based on ionice, -Copyright (C) 2005 Jens Axboe -Released under the terms of the GNU General Public License version 2 -*/ - -#include "IOPriority.h" - -/*{ - -enum { - IOPRIO_CLASS_NONE, - IOPRIO_CLASS_RT, - IOPRIO_CLASS_BE, - IOPRIO_CLASS_IDLE, -}; - -#define IOPRIO_WHO_PROCESS 1 - -#define IOPRIO_CLASS_SHIFT (13) -#define IOPRIO_PRIO_MASK ((1UL << IOPRIO_CLASS_SHIFT) - 1) - -#define IOPriority_class(ioprio_) ((int) ((ioprio_) >> IOPRIO_CLASS_SHIFT) ) -#define IOPriority_data(ioprio_) ((int) ((ioprio_) & IOPRIO_PRIO_MASK) ) - -typedef int IOPriority; - -#define IOPriority_tuple(class_, data_) (((class_) << IOPRIO_CLASS_SHIFT) | data_) - -#define IOPriority_error 0xffffffff - -#define IOPriority_None IOPriority_tuple(IOPRIO_CLASS_NONE, 0) -#define IOPriority_Idle IOPriority_tuple(IOPRIO_CLASS_IDLE, 7) - -}*/ - diff --git a/linux/IOPriority.h b/linux/IOPriority.h index 148e344c5..551a7d501 100644 --- a/linux/IOPriority.h +++ b/linux/IOPriority.h @@ -1,19 +1,16 @@ -/* Do not edit this file. It was automatically generated. */ - #ifndef HEADER_IOPriority #define HEADER_IOPriority /* htop - IOPriority.h (C) 2004-2012 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. -Based on ionice, +Based on ionice, Copyright (C) 2005 Jens Axboe Released under the terms of the GNU General Public License version 2 */ - enum { IOPRIO_CLASS_NONE, IOPRIO_CLASS_RT, @@ -31,13 +28,11 @@ enum { typedef int IOPriority; -#define IOPriority_tuple(class_, data_) (((class_) << IOPRIO_CLASS_SHIFT) | data_) +#define IOPriority_tuple(class_, data_) (((class_) << IOPRIO_CLASS_SHIFT) | (data_)) #define IOPriority_error 0xffffffff #define IOPriority_None IOPriority_tuple(IOPRIO_CLASS_NONE, 0) #define IOPriority_Idle IOPriority_tuple(IOPRIO_CLASS_IDLE, 7) - - #endif diff --git a/linux/IOPriorityPanel.c b/linux/IOPriorityPanel.c index 2b315b828..bd84241e2 100644 --- a/linux/IOPriorityPanel.c +++ b/linux/IOPriorityPanel.c @@ -1,25 +1,33 @@ /* htop - IOPriorityPanel.c (C) 2004-2012 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ #include "IOPriorityPanel.h" -/*{ -#include "Panel.h" -#include "IOPriority.h" +#include +#include + +#include "FunctionBar.h" #include "ListItem.h" -}*/ +#include "Object.h" +#include "XUtils.h" + Panel* IOPriorityPanel_new(IOPriority currPrio) { Panel* this = Panel_new(1, 1, 1, 1, true, Class(ListItem), FunctionBar_newEnterEsc("Set ", "Cancel ")); Panel_setHeader(this, "IO Priority:"); Panel_add(this, (Object*) ListItem_new("None (based on nice)", IOPriority_None)); - if (currPrio == IOPriority_None) Panel_setSelected(this, 0); - static const struct { int klass; const char* name; } classes[] = { + if (currPrio == IOPriority_None) { + Panel_setSelected(this, 0); + } + static const struct { + int klass; + const char* name; + } classes[] = { { .klass = IOPRIO_CLASS_RT, .name = "Realtime" }, { .klass = IOPRIO_CLASS_BE, .name = "Best-effort" }, { .klass = 0, .name = NULL } @@ -27,18 +35,22 @@ Panel* IOPriorityPanel_new(IOPriority currPrio) { for (int c = 0; classes[c].name; c++) { for (int i = 0; i < 8; i++) { char name[50]; - xSnprintf(name, sizeof(name)-1, "%s %d %s", classes[c].name, i, i == 0 ? "(High)" : (i == 7 ? "(Low)" : "")); + xSnprintf(name, sizeof(name) - 1, "%s %d %s", classes[c].name, i, i == 0 ? "(High)" : (i == 7 ? "(Low)" : "")); IOPriority ioprio = IOPriority_tuple(classes[c].klass, i); Panel_add(this, (Object*) ListItem_new(name, ioprio)); - if (currPrio == ioprio) Panel_setSelected(this, Panel_size(this) - 1); + if (currPrio == ioprio) { + Panel_setSelected(this, Panel_size(this) - 1); + } } } Panel_add(this, (Object*) ListItem_new("Idle", IOPriority_Idle)); - if (currPrio == IOPriority_Idle) Panel_setSelected(this, Panel_size(this) - 1); + if (currPrio == IOPriority_Idle) { + Panel_setSelected(this, Panel_size(this) - 1); + } return this; } IOPriority IOPriorityPanel_getIOPriority(Panel* this) { - return (IOPriority) ( ((ListItem*) Panel_getSelected(this))->key ); + const ListItem* selected = (ListItem*) Panel_getSelected(this); + return selected ? selected->key : IOPriority_None; } - diff --git a/linux/IOPriorityPanel.h b/linux/IOPriorityPanel.h index 9f77a4d9c..2ac4b3166 100644 --- a/linux/IOPriorityPanel.h +++ b/linux/IOPriorityPanel.h @@ -1,21 +1,17 @@ -/* Do not edit this file. It was automatically generated. */ - #ifndef HEADER_IOPriorityPanel #define HEADER_IOPriorityPanel /* htop - IOPriorityPanel.h (C) 2004-2012 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ #include "Panel.h" #include "IOPriority.h" -#include "ListItem.h" Panel* IOPriorityPanel_new(IOPriority currPrio); IOPriority IOPriorityPanel_getIOPriority(Panel* this); - #endif diff --git a/linux/LinuxCRT.c b/linux/LinuxCRT.c deleted file mode 100644 index 5b2a21fda..000000000 --- a/linux/LinuxCRT.c +++ /dev/null @@ -1,36 +0,0 @@ -/* -htop - LinuxCRT.c -(C) 2014 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file -in the source distribution for its full text. -*/ - -#include "config.h" -#include "CRT.h" -#include -#include -#ifdef HAVE_EXECINFO_H -#include -#endif - -void CRT_handleSIGSEGV(int sgn) { - (void) sgn; - CRT_done(); - #ifdef __linux - fprintf(stderr, "\n\nhtop " VERSION " aborting. Please report bug at http://hisham.hm/htop\n"); - #ifdef HAVE_EXECINFO_H - size_t size = backtrace(backtraceArray, sizeof(backtraceArray) / sizeof(void *)); - fprintf(stderr, "\n Please include in your report the following backtrace: \n"); - backtrace_symbols_fd(backtraceArray, size, 2); - fprintf(stderr, "\nAdditionally, in order to make the above backtrace useful,"); - fprintf(stderr, "\nplease also run the following command to generate a disassembly of your binary:"); - fprintf(stderr, "\n\n objdump -d `which htop` > ~/htop.objdump"); - fprintf(stderr, "\n\nand then attach the file ~/htop.objdump to your bug report."); - fprintf(stderr, "\n\nThank you for helping to improve htop!\n\n"); - #endif - #else - fprintf(stderr, "\nUnfortunately, you seem to be using an unsupported platform!"); - fprintf(stderr, "\nPlease contact your platform package maintainer!\n\n"); - #endif - abort(); -} diff --git a/linux/LinuxCRT.h b/linux/LinuxCRT.h deleted file mode 100644 index f8c43e4d3..000000000 --- a/linux/LinuxCRT.h +++ /dev/null @@ -1,17 +0,0 @@ -/* Do not edit this file. It was automatically generated. */ - -#ifndef HEADER_LinuxCRT -#define HEADER_LinuxCRT -/* -htop - LinuxCRT.h -(C) 2014 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file -in the source distribution for its full text. -*/ - -#ifdef HAVE_EXECINFO_H -#endif - -void CRT_handleSIGSEGV(int sgn); - -#endif diff --git a/linux/LinuxProcess.c b/linux/LinuxProcess.c index 5f697078f..5868ea29d 100644 --- a/linux/LinuxProcess.c +++ b/linux/LinuxProcess.c @@ -1,160 +1,28 @@ /* htop - LinuxProcess.c (C) 2014 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +(C) 2020 Red Hat, Inc. All Rights Reserved. +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ -#include "Process.h" -#include "ProcessList.h" #include "LinuxProcess.h" -#include "Platform.h" -#include "CRT.h" +#include +#include #include -#include #include -#include -#include - -/*{ - -#define PROCESS_FLAG_LINUX_IOPRIO 0x0100 -#define PROCESS_FLAG_LINUX_OPENVZ 0x0200 -#define PROCESS_FLAG_LINUX_VSERVER 0x0400 -#define PROCESS_FLAG_LINUX_CGROUP 0x0800 -#define PROCESS_FLAG_LINUX_OOM 0x1000 - -typedef enum UnsupportedProcessFields { - FLAGS = 9, - ITREALVALUE = 20, - VSIZE = 22, - RSS = 23, - RLIM = 24, - STARTCODE = 25, - ENDCODE = 26, - STARTSTACK = 27, - KSTKESP = 28, - KSTKEIP = 29, - SIGNAL = 30, - BLOCKED = 31, - SSIGIGNORE = 32, - SIGCATCH = 33, - WCHAN = 34, - NSWAP = 35, - CNSWAP = 36, - EXIT_SIGNAL = 37, -} UnsupportedProcessField; - -typedef enum LinuxProcessFields { - CMINFLT = 11, - CMAJFLT = 13, - UTIME = 14, - STIME = 15, - CUTIME = 16, - CSTIME = 17, - M_SHARE = 41, - M_TRS = 42, - M_DRS = 43, - M_LRS = 44, - M_DT = 45, - #ifdef HAVE_OPENVZ - CTID = 100, - VPID = 101, - #endif - #ifdef HAVE_VSERVER - VXID = 102, - #endif - #ifdef HAVE_TASKSTATS - RCHAR = 103, - WCHAR = 104, - SYSCR = 105, - SYSCW = 106, - RBYTES = 107, - WBYTES = 108, - CNCLWB = 109, - IO_READ_RATE = 110, - IO_WRITE_RATE = 111, - IO_RATE = 112, - #endif - #ifdef HAVE_CGROUP - CGROUP = 113, - #endif - OOM = 114, - IO_PRIORITY = 115, - #ifdef HAVE_DELAYACCT - PERCENT_CPU_DELAY = 116, - PERCENT_IO_DELAY = 117, - PERCENT_SWAP_DELAY = 118, - #endif - LAST_PROCESSFIELD = 119, -} LinuxProcessField; - -#include "IOPriority.h" - -typedef struct LinuxProcess_ { - Process super; - bool isKernelThread; - IOPriority ioPriority; - unsigned long int cminflt; - unsigned long int cmajflt; - unsigned long long int utime; - unsigned long long int stime; - unsigned long long int cutime; - unsigned long long int cstime; - long m_share; - long m_trs; - long m_drs; - long m_lrs; - long m_dt; - unsigned long long starttime; - #ifdef HAVE_TASKSTATS - unsigned long long io_rchar; - unsigned long long io_wchar; - unsigned long long io_syscr; - unsigned long long io_syscw; - unsigned long long io_read_bytes; - unsigned long long io_write_bytes; - unsigned long long io_cancelled_write_bytes; - unsigned long long io_rate_read_time; - unsigned long long io_rate_write_time; - double io_rate_read_bps; - double io_rate_write_bps; - #endif - #ifdef HAVE_OPENVZ - unsigned int ctid; - unsigned int vpid; - #endif - #ifdef HAVE_VSERVER - unsigned int vxid; - #endif - #ifdef HAVE_CGROUP - char* cgroup; - #endif - unsigned int oom; - char* ttyDevice; - #ifdef HAVE_DELAYACCT - unsigned long long int delay_read_time; - unsigned long long cpu_delay_total; - unsigned long long blkio_delay_total; - unsigned long long swapin_delay_total; - float cpu_delay_percent; - float blkio_delay_percent; - float swapin_delay_percent; - #endif -} LinuxProcess; - -#ifndef Process_isKernelThread -#define Process_isKernelThread(_process) (((LinuxProcess*)(_process))->isKernelThread) -#endif +#include +#include -#ifndef Process_isUserlandThread -#define Process_isUserlandThread(_process) (_process->pid != _process->tgid) -#endif +#include "CRT.h" +#include "Process.h" +#include "ProvideCurses.h" +#include "XUtils.h" -}*/ -long long btime; /* semi-global */ +/* semi-global */ +long long btime; ProcessFieldData Process_fields[] = { [0] = { .name = "", .title = NULL, .description = NULL, .flags = 0, }, @@ -201,18 +69,19 @@ ProcessFieldData Process_fields[] = { [M_SHARE] = { .name = "M_SHARE", .title = " SHR ", .description = "Size of the process's shared pages", .flags = 0, }, [M_TRS] = { .name = "M_TRS", .title = " CODE ", .description = "Size of the text segment of the process", .flags = 0, }, [M_DRS] = { .name = "M_DRS", .title = " DATA ", .description = "Size of the data segment plus stack usage of the process", .flags = 0, }, - [M_LRS] = { .name = "M_LRS", .title = " LIB ", .description = "The library size of the process", .flags = 0, }, - [M_DT] = { .name = "M_DT", .title = " DIRTY ", .description = "Size of the dirty pages of the process", .flags = 0, }, - [ST_UID] = { .name = "ST_UID", .title = " UID ", .description = "User ID of the process owner", .flags = 0, }, + [M_LRS] = { .name = "M_LRS", .title = " LIB ", .description = "The library size of the process (unused since Linux 2.6; always 0)", .flags = 0, }, + [M_DT] = { .name = "M_DT", .title = " DIRTY ", .description = "Size of the dirty pages of the process (unused since Linux 2.6; always 0)", .flags = 0, }, + [ST_UID] = { .name = "ST_UID", .title = " UID ", .description = "User ID of the process owner", .flags = 0, }, [PERCENT_CPU] = { .name = "PERCENT_CPU", .title = "CPU% ", .description = "Percentage of the CPU time the process used in the last sampling", .flags = 0, }, + [PERCENT_NORM_CPU] = { .name = "PERCENT_NORM_CPU", .title = "NCPU%", .description = "Normalized percentage of the CPU time the process used in the last sampling (normalized by cpu count)", .flags = 0, }, [PERCENT_MEM] = { .name = "PERCENT_MEM", .title = "MEM% ", .description = "Percentage of the memory the process is using, based on resident memory size", .flags = 0, }, [USER] = { .name = "USER", .title = "USER ", .description = "Username of the process owner (or user ID if name cannot be determined)", .flags = 0, }, [TIME] = { .name = "TIME", .title = " TIME+ ", .description = "Total time the process has spent in user and system time", .flags = 0, }, [NLWP] = { .name = "NLWP", .title = "NLWP ", .description = "Number of threads in the process", .flags = 0, }, [TGID] = { .name = "TGID", .title = " TGID ", .description = "Thread group ID (i.e. process ID)", .flags = 0, }, #ifdef HAVE_OPENVZ - [CTID] = { .name = "CTID", .title = " CTID ", .description = "OpenVZ container ID (a.k.a. virtual environment ID)", .flags = PROCESS_FLAG_LINUX_OPENVZ, }, - [VPID] = { .name = "VPID", .title = " VPID ", .description = "OpenVZ process ID", .flags = PROCESS_FLAG_LINUX_OPENVZ, }, + [CTID] = { .name = "CTID", .title = " CTID ", .description = "OpenVZ container ID (a.k.a. virtual environment ID)", .flags = PROCESS_FLAG_LINUX_OPENVZ, }, + [VPID] = { .name = "VPID", .title = " VPID ", .description = "OpenVZ process ID", .flags = PROCESS_FLAG_LINUX_OPENVZ, }, #endif #ifdef HAVE_VSERVER [VXID] = { .name = "VXID", .title = " VXID ", .description = "VServer process ID", .flags = PROCESS_FLAG_LINUX_VSERVER, }, @@ -232,13 +101,18 @@ ProcessFieldData Process_fields[] = { #ifdef HAVE_CGROUP [CGROUP] = { .name = "CGROUP", .title = " CGROUP ", .description = "Which cgroup the process is in", .flags = PROCESS_FLAG_LINUX_CGROUP, }, #endif - [OOM] = { .name = "OOM", .title = " OOM ", .description = "OOM (Out-of-Memory) killer score", .flags = PROCESS_FLAG_LINUX_OOM, }, + [OOM] = { .name = "OOM", .title = " OOM ", .description = "OOM (Out-of-Memory) killer score", .flags = PROCESS_FLAG_LINUX_OOM, }, [IO_PRIORITY] = { .name = "IO_PRIORITY", .title = "IO ", .description = "I/O priority", .flags = PROCESS_FLAG_LINUX_IOPRIO, }, #ifdef HAVE_DELAYACCT [PERCENT_CPU_DELAY] = { .name = "PERCENT_CPU_DELAY", .title = "CPUD% ", .description = "CPU delay %", .flags = 0, }, [PERCENT_IO_DELAY] = { .name = "PERCENT_IO_DELAY", .title = "IOD% ", .description = "Block I/O delay %", .flags = 0, }, [PERCENT_SWAP_DELAY] = { .name = "PERCENT_SWAP_DELAY", .title = "SWAPD% ", .description = "Swapin delay %", .flags = 0, }, #endif + [M_PSS] = { .name = "M_PSS", .title = " PSS ", .description = "proportional set size, same as M_RESIDENT but each page is divided by the number of processes sharing it.", .flags = PROCESS_FLAG_LINUX_SMAPS, }, + [M_SWAP] = { .name = "M_SWAP", .title = " SWAP ", .description = "Size of the process's swapped pages", .flags = PROCESS_FLAG_LINUX_SMAPS, }, + [M_PSSWP] = { .name = "M_PSSWP", .title = " PSSWP ", .description = "shows proportional swap share of this mapping, Unlike \"Swap\", this does not take into account swapped out page of underlying shmem objects.", .flags = PROCESS_FLAG_LINUX_SMAPS, }, + [CTXT] = { .name = "CTXT", .title = " CTXT ", .description = "Context switches (incremental sum of voluntary_ctxt_switches and nonvoluntary_ctxt_switches)", .flags = PROCESS_FLAG_LINUX_CTXT, }, + [SECATTR] = { .name = "SECATTR", .title = " Security Attribute ", .description = "Security attribute of the process (e.g. SELinux or AppArmor)", .flags = PROCESS_FLAG_LINUX_SECATTR, }, [LAST_PROCESSFIELD] = { .name = "*** report bug! ***", .title = NULL, .description = NULL, .flags = 0, }, }; @@ -252,25 +126,14 @@ ProcessPidColumn Process_pidColumns[] = { { .id = TGID, .label = "TGID" }, { .id = PGRP, .label = "PGRP" }, { .id = SESSION, .label = "SID" }, - { .id = OOM, .label = "OOM" }, { .id = 0, .label = NULL }, }; -ProcessClass LinuxProcess_class = { - .super = { - .extends = Class(Process), - .display = Process_display, - .delete = Process_delete, - .compare = LinuxProcess_compare - }, - .writeField = (Process_WriteField) LinuxProcess_writeField, -}; - -LinuxProcess* LinuxProcess_new(Settings* settings) { +Process* LinuxProcess_new(const Settings* settings) { LinuxProcess* this = xCalloc(1, sizeof(LinuxProcess)); Object_setClass(this, Class(LinuxProcess)); Process_init(&this->super, settings); - return this; + return &this->super; } void Process_delete(Object* cast) { @@ -279,6 +142,10 @@ void Process_delete(Object* cast) { #ifdef HAVE_CGROUP free(this->cgroup); #endif +#ifdef HAVE_OPENVZ + free(this->ctid); +#endif + free(this->secattr); free(this->ttyDevice); free(this); } @@ -291,7 +158,13 @@ effort class. The priority within the best effort class will be dynamically derived from the cpu nice level of the process: io_priority = (cpu_nice + 20) / 5. -- From ionice(1) man page */ -#define LinuxProcess_effectiveIOPriority(p_) (IOPriority_class(p_->ioPriority) == IOPRIO_CLASS_NONE ? IOPriority_tuple(IOPRIO_CLASS_BE, (p_->super.nice + 20) / 5) : p_->ioPriority) +static int LinuxProcess_effectiveIOPriority(const LinuxProcess* this) { + if (IOPriority_class(this->ioPriority) == IOPRIO_CLASS_NONE) { + return IOPriority_tuple(IOPRIO_CLASS_BE, (this->super.nice + 20) / 5); + } + + return this->ioPriority; +} IOPriority LinuxProcess_updateIOPriority(LinuxProcess* this) { IOPriority ioprio = 0; @@ -303,26 +176,26 @@ IOPriority LinuxProcess_updateIOPriority(LinuxProcess* this) { return ioprio; } -bool LinuxProcess_setIOPriority(LinuxProcess* this, IOPriority ioprio) { +bool LinuxProcess_setIOPriority(Process* this, Arg ioprio) { // Other OSes masquerading as Linux (NetBSD?) don't have this syscall #ifdef SYS_ioprio_set - syscall(SYS_ioprio_set, IOPRIO_WHO_PROCESS, this->super.pid, ioprio); + syscall(SYS_ioprio_set, IOPRIO_WHO_PROCESS, this->pid, ioprio.i); #endif - return (LinuxProcess_updateIOPriority(this) == ioprio); + return (LinuxProcess_updateIOPriority((LinuxProcess*)this) == ioprio.i); } #ifdef HAVE_DELAYACCT void LinuxProcess_printDelay(float delay_percent, char* buffer, int n) { - if (delay_percent == -1LL) { - xSnprintf(buffer, n, " N/A "); - } else { - xSnprintf(buffer, n, "%4.1f ", delay_percent); - } + if (isnan(delay_percent)) { + xSnprintf(buffer, n, " N/A "); + } else { + xSnprintf(buffer, n, "%4.1f ", delay_percent); + } } #endif -void LinuxProcess_writeField(Process* this, RichString* str, ProcessField field) { - LinuxProcess* lp = (LinuxProcess*) this; +static void LinuxProcess_writeField(const Process* this, RichString* str, ProcessField field) { + const LinuxProcess* lp = (const LinuxProcess*) this; bool coloring = this->settings->highlightMegabytes; char buffer[256]; buffer[255] = '\0'; int attr = CRT_colors[DEFAULT_COLOR]; @@ -339,22 +212,18 @@ void LinuxProcess_writeField(Process* this, RichString* str, ProcessField field) } case CMINFLT: Process_colorNumber(str, lp->cminflt, coloring); return; case CMAJFLT: Process_colorNumber(str, lp->cmajflt, coloring); return; - case M_DRS: Process_humanNumber(str, lp->m_drs * PAGE_SIZE_KB, coloring); return; - case M_DT: Process_humanNumber(str, lp->m_dt * PAGE_SIZE_KB, coloring); return; - case M_LRS: Process_humanNumber(str, lp->m_lrs * PAGE_SIZE_KB, coloring); return; - case M_TRS: Process_humanNumber(str, lp->m_trs * PAGE_SIZE_KB, coloring); return; - case M_SHARE: Process_humanNumber(str, lp->m_share * PAGE_SIZE_KB, coloring); return; + case M_DRS: Process_humanNumber(str, lp->m_drs * CRT_pageSizeKB, coloring); return; + case M_DT: Process_humanNumber(str, lp->m_dt * CRT_pageSizeKB, coloring); return; + case M_LRS: Process_humanNumber(str, lp->m_lrs * CRT_pageSizeKB, coloring); return; + case M_TRS: Process_humanNumber(str, lp->m_trs * CRT_pageSizeKB, coloring); return; + case M_SHARE: Process_humanNumber(str, lp->m_share * CRT_pageSizeKB, coloring); return; + case M_PSS: Process_humanNumber(str, lp->m_pss, coloring); return; + case M_SWAP: Process_humanNumber(str, lp->m_swap, coloring); return; + case M_PSSWP: Process_humanNumber(str, lp->m_psswp, coloring); return; case UTIME: Process_printTime(str, lp->utime); return; case STIME: Process_printTime(str, lp->stime); return; case CUTIME: Process_printTime(str, lp->cutime); return; case CSTIME: Process_printTime(str, lp->cstime); return; - case STARTTIME: { - struct tm date; - time_t starttimewall = btime + (lp->starttime / sysconf(_SC_CLK_TCK)); - (void) localtime_r(&starttimewall, &date); - strftime(buffer, n, ((starttimewall > time(NULL) - 86400) ? "%R " : "%b%d "), &date); - break; - } #ifdef HAVE_TASKSTATS case RCHAR: Process_colorNumber(str, lp->io_rchar, coloring); return; case WCHAR: Process_colorNumber(str, lp->io_wchar, coloring); return; @@ -366,23 +235,29 @@ void LinuxProcess_writeField(Process* this, RichString* str, ProcessField field) case IO_READ_RATE: Process_outputRate(str, buffer, n, lp->io_rate_read_bps, coloring); return; case IO_WRITE_RATE: Process_outputRate(str, buffer, n, lp->io_rate_write_bps, coloring); return; case IO_RATE: { - double totalRate = (lp->io_rate_read_bps != -1) - ? (lp->io_rate_read_bps + lp->io_rate_write_bps) - : -1; + double totalRate = NAN; + if (!isnan(lp->io_rate_read_bps) && !isnan(lp->io_rate_write_bps)) + totalRate = lp->io_rate_read_bps + lp->io_rate_write_bps; + else if (!isnan(lp->io_rate_read_bps)) + totalRate = lp->io_rate_read_bps; + else if (!isnan(lp->io_rate_write_bps)) + totalRate = lp->io_rate_write_bps; + else + totalRate = NAN; Process_outputRate(str, buffer, n, totalRate, coloring); return; } #endif #ifdef HAVE_OPENVZ - case CTID: xSnprintf(buffer, n, "%7u ", lp->ctid); break; + case CTID: xSnprintf(buffer, n, "%-8s ", lp->ctid ? lp->ctid : ""); break; case VPID: xSnprintf(buffer, n, Process_pidFormat, lp->vpid); break; #endif #ifdef HAVE_VSERVER case VXID: xSnprintf(buffer, n, "%5u ", lp->vxid); break; #endif #ifdef HAVE_CGROUP - case CGROUP: xSnprintf(buffer, n, "%-10s ", lp->cgroup); break; + case CGROUP: xSnprintf(buffer, n, "%-10s ", lp->cgroup ? lp->cgroup : ""); break; #endif - case OOM: xSnprintf(buffer, n, Process_pidFormat, lp->oom); break; + case OOM: xSnprintf(buffer, n, "%4u ", lp->oom); break; case IO_PRIORITY: { int klass = IOPriority_class(lp->ioPriority); if (klass == IOPRIO_CLASS_NONE) { @@ -394,7 +269,7 @@ void LinuxProcess_writeField(Process* this, RichString* str, ProcessField field) attr = CRT_colors[PROCESS_HIGH_PRIORITY]; xSnprintf(buffer, n, "R%1d ", IOPriority_data(lp->ioPriority)); } else if (klass == IOPRIO_CLASS_IDLE) { - attr = CRT_colors[PROCESS_LOW_PRIORITY]; + attr = CRT_colors[PROCESS_LOW_PRIORITY]; xSnprintf(buffer, n, "id "); } else { xSnprintf(buffer, n, "?? "); @@ -406,91 +281,124 @@ void LinuxProcess_writeField(Process* this, RichString* str, ProcessField field) case PERCENT_IO_DELAY: LinuxProcess_printDelay(lp->blkio_delay_percent, buffer, n); break; case PERCENT_SWAP_DELAY: LinuxProcess_printDelay(lp->swapin_delay_percent, buffer, n); break; #endif + case CTXT: + if (lp->ctxt_diff > 1000) { + attr |= A_BOLD; + } + xSnprintf(buffer, n, "%5lu ", lp->ctxt_diff); + break; + case SECATTR: snprintf(buffer, n, "%-30s ", lp->secattr ? lp->secattr : "?"); break; default: - Process_writeField((Process*)this, str, field); + Process_writeField(this, str, field); return; } RichString_append(str, attr, buffer); } -long LinuxProcess_compare(const void* v1, const void* v2) { - LinuxProcess *p1, *p2; - Settings *settings = ((Process*)v1)->settings; +static long LinuxProcess_compare(const void* v1, const void* v2) { + const LinuxProcess *p1, *p2; + const Settings *settings = ((const Process*)v1)->settings; + if (settings->direction == 1) { - p1 = (LinuxProcess*)v1; - p2 = (LinuxProcess*)v2; + p1 = (const LinuxProcess*)v1; + p2 = (const LinuxProcess*)v2; } else { - p2 = (LinuxProcess*)v1; - p1 = (LinuxProcess*)v2; + p2 = (const LinuxProcess*)v1; + p1 = (const LinuxProcess*)v2; } - long long diff; + switch ((int)settings->sortKey) { case M_DRS: - return (p2->m_drs - p1->m_drs); + return SPACESHIP_NUMBER(p2->m_drs, p1->m_drs); case M_DT: - return (p2->m_dt - p1->m_dt); + return SPACESHIP_NUMBER(p2->m_dt, p1->m_dt); case M_LRS: - return (p2->m_lrs - p1->m_lrs); + return SPACESHIP_NUMBER(p2->m_lrs, p1->m_lrs); case M_TRS: - return (p2->m_trs - p1->m_trs); + return SPACESHIP_NUMBER(p2->m_trs, p1->m_trs); case M_SHARE: - return (p2->m_share - p1->m_share); - case UTIME: diff = p2->utime - p1->utime; goto test_diff; - case CUTIME: diff = p2->cutime - p1->cutime; goto test_diff; - case STIME: diff = p2->stime - p1->stime; goto test_diff; - case CSTIME: diff = p2->cstime - p1->cstime; goto test_diff; - case STARTTIME: { - if (p1->starttime == p2->starttime) - return (p1->super.pid - p2->super.pid); - else - return (p1->starttime - p2->starttime); - } + return SPACESHIP_NUMBER(p2->m_share, p1->m_share); + case M_PSS: + return SPACESHIP_NUMBER(p2->m_pss, p1->m_pss); + case M_SWAP: + return SPACESHIP_NUMBER(p2->m_swap, p1->m_swap); + case M_PSSWP: + return SPACESHIP_NUMBER(p2->m_psswp, p1->m_psswp); + case UTIME: + return SPACESHIP_NUMBER(p2->utime, p1->utime); + case CUTIME: + return SPACESHIP_NUMBER(p2->cutime, p1->cutime); + case STIME: + return SPACESHIP_NUMBER(p2->stime, p1->stime); + case CSTIME: + return SPACESHIP_NUMBER(p2->cstime, p1->cstime); #ifdef HAVE_TASKSTATS - case RCHAR: diff = p2->io_rchar - p1->io_rchar; goto test_diff; - case WCHAR: diff = p2->io_wchar - p1->io_wchar; goto test_diff; - case SYSCR: diff = p2->io_syscr - p1->io_syscr; goto test_diff; - case SYSCW: diff = p2->io_syscw - p1->io_syscw; goto test_diff; - case RBYTES: diff = p2->io_read_bytes - p1->io_read_bytes; goto test_diff; - case WBYTES: diff = p2->io_write_bytes - p1->io_write_bytes; goto test_diff; - case CNCLWB: diff = p2->io_cancelled_write_bytes - p1->io_cancelled_write_bytes; goto test_diff; - case IO_READ_RATE: diff = p2->io_rate_read_bps - p1->io_rate_read_bps; goto test_diff; - case IO_WRITE_RATE: diff = p2->io_rate_write_bps - p1->io_rate_write_bps; goto test_diff; - case IO_RATE: diff = (p2->io_rate_read_bps + p2->io_rate_write_bps) - (p1->io_rate_read_bps + p1->io_rate_write_bps); goto test_diff; + case RCHAR: + return SPACESHIP_NUMBER(p2->io_rchar, p1->io_rchar); + case WCHAR: + return SPACESHIP_NUMBER(p2->io_wchar, p1->io_wchar); + case SYSCR: + return SPACESHIP_NUMBER(p2->io_syscr, p1->io_syscr); + case SYSCW: + return SPACESHIP_NUMBER(p2->io_syscw, p1->io_syscw); + case RBYTES: + return SPACESHIP_NUMBER(p2->io_read_bytes, p1->io_read_bytes); + case WBYTES: + return SPACESHIP_NUMBER(p2->io_write_bytes, p1->io_write_bytes); + case CNCLWB: + return SPACESHIP_NUMBER(p2->io_cancelled_write_bytes, p1->io_cancelled_write_bytes); + case IO_READ_RATE: + return SPACESHIP_NUMBER(p2->io_rate_read_bps, p1->io_rate_read_bps); + case IO_WRITE_RATE: + return SPACESHIP_NUMBER(p2->io_rate_write_bps, p1->io_rate_write_bps); + case IO_RATE: + return SPACESHIP_NUMBER(p2->io_rate_read_bps + p2->io_rate_write_bps, p1->io_rate_read_bps + p1->io_rate_write_bps); #endif #ifdef HAVE_OPENVZ case CTID: - return (p2->ctid - p1->ctid); + return SPACESHIP_NULLSTR(p1->ctid, p2->ctid); case VPID: - return (p2->vpid - p1->vpid); + return SPACESHIP_NUMBER(p2->vpid, p1->vpid); #endif #ifdef HAVE_VSERVER case VXID: - return (p2->vxid - p1->vxid); + return SPACESHIP_NUMBER(p2->vxid, p1->vxid); #endif #ifdef HAVE_CGROUP case CGROUP: - return strcmp(p1->cgroup ? p1->cgroup : "", p2->cgroup ? p2->cgroup : ""); + return SPACESHIP_NULLSTR(p1->cgroup, p2->cgroup); #endif case OOM: - return (p2->oom - p1->oom); + return SPACESHIP_NUMBER(p2->oom, p1->oom); #ifdef HAVE_DELAYACCT case PERCENT_CPU_DELAY: - return (p2->cpu_delay_percent > p1->cpu_delay_percent ? 1 : -1); + return SPACESHIP_NUMBER(p2->cpu_delay_percent, p1->cpu_delay_percent); case PERCENT_IO_DELAY: - return (p2->blkio_delay_percent > p1->blkio_delay_percent ? 1 : -1); + return SPACESHIP_NUMBER(p2->blkio_delay_percent, p1->blkio_delay_percent); case PERCENT_SWAP_DELAY: - return (p2->swapin_delay_percent > p1->swapin_delay_percent ? 1 : -1); + return SPACESHIP_NUMBER(p2->swapin_delay_percent, p1->swapin_delay_percent); #endif case IO_PRIORITY: - return LinuxProcess_effectiveIOPriority(p1) - LinuxProcess_effectiveIOPriority(p2); + return SPACESHIP_NUMBER(LinuxProcess_effectiveIOPriority(p1), LinuxProcess_effectiveIOPriority(p2)); + case CTXT: + return SPACESHIP_NUMBER(p2->ctxt_diff, p1->ctxt_diff); + case SECATTR: + return SPACESHIP_NULLSTR(p1->secattr, p2->secattr); default: return Process_compare(v1, v2); } - test_diff: - return (diff > 0) ? 1 : (diff < 0 ? -1 : 0); } -bool Process_isThread(Process* this) { +bool Process_isThread(const Process* this) { return (Process_isUserlandThread(this) || Process_isKernelThread(this)); } +const ProcessClass LinuxProcess_class = { + .super = { + .extends = Class(Process), + .display = Process_display, + .delete = Process_delete, + .compare = LinuxProcess_compare + }, + .writeField = LinuxProcess_writeField +}; diff --git a/linux/LinuxProcess.h b/linux/LinuxProcess.h index 6ce3037d2..856b7bee4 100644 --- a/linux/LinuxProcess.h +++ b/linux/LinuxProcess.h @@ -1,20 +1,32 @@ -/* Do not edit this file. It was automatically generated. */ - #ifndef HEADER_LinuxProcess #define HEADER_LinuxProcess /* htop - LinuxProcess.h (C) 2014 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +(C) 2020 Red Hat, Inc. All Rights Reserved. +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ +#include "config.h" + +#include +#include + +#include "IOPriority.h" +#include "Object.h" +#include "Process.h" +#include "RichString.h" +#include "Settings.h" #define PROCESS_FLAG_LINUX_IOPRIO 0x0100 #define PROCESS_FLAG_LINUX_OPENVZ 0x0200 #define PROCESS_FLAG_LINUX_VSERVER 0x0400 #define PROCESS_FLAG_LINUX_CGROUP 0x0800 #define PROCESS_FLAG_LINUX_OOM 0x1000 +#define PROCESS_FLAG_LINUX_SMAPS 0x2000 +#define PROCESS_FLAG_LINUX_CTXT 0x4000 +#define PROCESS_FLAG_LINUX_SECATTR 0x8000 typedef enum UnsupportedProcessFields { FLAGS = 9, @@ -78,11 +90,14 @@ typedef enum LinuxProcessFields { PERCENT_IO_DELAY = 117, PERCENT_SWAP_DELAY = 118, #endif - LAST_PROCESSFIELD = 119, + M_PSS = 119, + M_SWAP = 120, + M_PSSWP = 121, + CTXT = 122, + SECATTR = 123, + LAST_PROCESSFIELD = 124, } LinuxProcessField; -#include "IOPriority.h" - typedef struct LinuxProcess_ { Process super; bool isKernelThread; @@ -94,11 +109,13 @@ typedef struct LinuxProcess_ { unsigned long long int cutime; unsigned long long int cstime; long m_share; + long m_pss; + long m_swap; + long m_psswp; long m_trs; long m_drs; long m_lrs; long m_dt; - unsigned long long starttime; #ifdef HAVE_TASKSTATS unsigned long long io_rchar; unsigned long long io_wchar; @@ -108,13 +125,13 @@ typedef struct LinuxProcess_ { unsigned long long io_write_bytes; unsigned long long io_cancelled_write_bytes; unsigned long long io_rate_read_time; - unsigned long long io_rate_write_time; + unsigned long long io_rate_write_time; double io_rate_read_bps; double io_rate_write_bps; #endif #ifdef HAVE_OPENVZ - unsigned int ctid; - unsigned int vpid; + char* ctid; + pid_t vpid; #endif #ifdef HAVE_VSERVER unsigned int vxid; @@ -133,52 +150,37 @@ typedef struct LinuxProcess_ { float blkio_delay_percent; float swapin_delay_percent; #endif + unsigned long ctxt_total; + unsigned long ctxt_diff; + char* secattr; } LinuxProcess; -#ifndef Process_isKernelThread -#define Process_isKernelThread(_process) (((LinuxProcess*)(_process))->isKernelThread) -#endif +#define Process_isKernelThread(_process) (((const LinuxProcess*)(_process))->isKernelThread) -#ifndef Process_isUserlandThread -#define Process_isUserlandThread(_process) (_process->pid != _process->tgid) -#endif +static inline bool Process_isUserlandThread(const Process* this) { + return this->pid != this->tgid; +} - -long long btime; /* semi-global */ +extern long long btime; extern ProcessFieldData Process_fields[]; extern ProcessPidColumn Process_pidColumns[]; -extern ProcessClass LinuxProcess_class; +extern const ProcessClass LinuxProcess_class; -LinuxProcess* LinuxProcess_new(Settings* settings); +Process* LinuxProcess_new(const Settings* settings); void Process_delete(Object* cast); -/* -[1] Note that before kernel 2.6.26 a process that has not asked for -an io priority formally uses "none" as scheduling class, but the -io scheduler will treat such processes as if it were in the best -effort class. The priority within the best effort class will be -dynamically derived from the cpu nice level of the process: -extern io_priority; -*/ -#define LinuxProcess_effectiveIOPriority(p_) (IOPriority_class(p_->ioPriority) == IOPRIO_CLASS_NONE ? IOPriority_tuple(IOPRIO_CLASS_BE, (p_->super.nice + 20) / 5) : p_->ioPriority) - IOPriority LinuxProcess_updateIOPriority(LinuxProcess* this); -bool LinuxProcess_setIOPriority(LinuxProcess* this, IOPriority ioprio); +bool LinuxProcess_setIOPriority(Process* this, Arg ioprio); #ifdef HAVE_DELAYACCT void LinuxProcess_printDelay(float delay_percent, char* buffer, int n); #endif -void LinuxProcess_writeField(Process* this, RichString* str, ProcessField field); - -long LinuxProcess_compare(const void* v1, const void* v2); - -bool Process_isThread(Process* this); - +bool Process_isThread(const Process* this); #endif diff --git a/linux/LinuxProcessList.c b/linux/LinuxProcessList.c index 5f38540c6..63b77326c 100644 --- a/linux/LinuxProcessList.c +++ b/linux/LinuxProcessList.c @@ -1,147 +1,88 @@ /* htop - LinuxProcessList.c (C) 2014 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ +#include "config.h" // IWYU pragma: keep + #include "LinuxProcessList.h" -#include "LinuxProcess.h" -#include "CRT.h" -#include "StringUtils.h" -#include -#include -#include -#include -#include + +#include #include -#include -#include -#include -#include -#include +#include +#include #include +#include +#include +#include #include -#include -#include +#include +#include +#include +#include #include -#include -#ifdef MAJOR_IN_MKDEV -#include -#elif defined(MAJOR_IN_SYSMACROS) || \ - (defined(HAVE_SYS_SYSMACROS_H) && HAVE_SYS_SYSMACROS_H) -#include -#endif #ifdef HAVE_DELAYACCT +#include +#include #include +#include +#include #include +#include #include #include -#include -#include -#include -#endif - -/*{ - -#include "ProcessList.h" - -extern long long btime; - -typedef struct CPUData_ { - unsigned long long int totalTime; - unsigned long long int userTime; - unsigned long long int systemTime; - unsigned long long int systemAllTime; - unsigned long long int idleAllTime; - unsigned long long int idleTime; - unsigned long long int niceTime; - unsigned long long int ioWaitTime; - unsigned long long int irqTime; - unsigned long long int softIrqTime; - unsigned long long int stealTime; - unsigned long long int guestTime; - - unsigned long long int totalPeriod; - unsigned long long int userPeriod; - unsigned long long int systemPeriod; - unsigned long long int systemAllPeriod; - unsigned long long int idleAllPeriod; - unsigned long long int idlePeriod; - unsigned long long int nicePeriod; - unsigned long long int ioWaitPeriod; - unsigned long long int irqPeriod; - unsigned long long int softIrqPeriod; - unsigned long long int stealPeriod; - unsigned long long int guestPeriod; -} CPUData; - -typedef struct TtyDriver_ { - char* path; - unsigned int major; - unsigned int minorFrom; - unsigned int minorTo; -} TtyDriver; - -typedef struct LinuxProcessList_ { - ProcessList super; - - CPUData* cpus; - TtyDriver* ttyDrivers; - - #ifdef HAVE_DELAYACCT - struct nl_sock *netlink_socket; - int netlink_family; - #endif -} LinuxProcessList; - -#ifndef PROCDIR -#define PROCDIR "/proc" -#endif - -#ifndef PROCSTATFILE -#define PROCSTATFILE PROCDIR "/stat" #endif -#ifndef PROCMEMINFOFILE -#define PROCMEMINFOFILE PROCDIR "/meminfo" -#endif +#include "CRT.h" +#include "LinuxProcess.h" +#include "Macros.h" +#include "Object.h" +#include "Process.h" +#include "Settings.h" +#include "XUtils.h" -#ifndef PROCTTYDRIVERSFILE -#define PROCTTYDRIVERSFILE PROCDIR "/tty/drivers" +#ifdef MAJOR_IN_MKDEV +#include +#elif defined(MAJOR_IN_SYSMACROS) +#include #endif -#ifndef PROC_LINE_LENGTH -#define PROC_LINE_LENGTH 4096 -#endif -}*/ +static ssize_t xread(int fd, void* buf, size_t count) { + // Read some bytes. Retry on EINTR and when we don't get as many bytes as we requested. + size_t alreadyRead = 0; + for (;;) { + ssize_t res = read(fd, buf, count); + if (res == -1) { + if (errno == EINTR) + continue; + return -1; + } -#ifndef CLAMP -#define CLAMP(x,low,high) (((x)>(high))?(high):(((x)<(low))?(low):(x))) -#endif + if (res > 0) { + buf = ((char*)buf) + res; + count -= res; + alreadyRead += res; + } -static ssize_t xread(int fd, void *buf, size_t count) { - // Read some bytes. Retry on EINTR and when we don't get as many bytes as we requested. - size_t alreadyRead = 0; - for(;;) { - ssize_t res = read(fd, buf, count); - if (res == -1 && errno == EINTR) continue; - if (res > 0) { - buf = ((char*)buf)+res; - count -= res; - alreadyRead += res; - } - if (res == -1) return -1; - if (count == 0 || res == 0) return alreadyRead; - } + if (count == 0 || res == 0) { + return alreadyRead; + } + } } static int sortTtyDrivers(const void* va, const void* vb) { - TtyDriver* a = (TtyDriver*) va; - TtyDriver* b = (TtyDriver*) vb; - return (a->major == b->major) ? (a->minorFrom - b->minorFrom) : (a->major - b->major); + const TtyDriver* a = (const TtyDriver*) va; + const TtyDriver* b = (const TtyDriver*) vb; + + int r = SPACESHIP_NUMBER(a->major, b->major); + if (r) + return r; + + return SPACESHIP_NUMBER(a->minorFrom, b->minorFrom); } static void LinuxProcessList_initTtyDrivers(LinuxProcessList* this) { @@ -149,11 +90,12 @@ static void LinuxProcessList_initTtyDrivers(LinuxProcessList* this) { int fd = open(PROCTTYDRIVERSFILE, O_RDONLY); if (fd == -1) return; + char* buf = NULL; int bufSize = MAX_READ; int bufLen = 0; - for(;;) { - buf = realloc(buf, bufSize); + for (;;) { + buf = xRealloc(buf, bufSize); int size = xread(fd, buf + bufLen, MAX_READ); if (size <= 0) { buf[bufLen] = '\0'; @@ -169,7 +111,7 @@ static void LinuxProcessList_initTtyDrivers(LinuxProcessList* this) { } int numDrivers = 0; int allocd = 10; - ttyDrivers = malloc(sizeof(TtyDriver) * allocd); + ttyDrivers = xMalloc(sizeof(TtyDriver) * allocd); char* at = buf; while (*at != '\0') { at = strchr(at, ' '); // skip first token @@ -177,7 +119,7 @@ static void LinuxProcessList_initTtyDrivers(LinuxProcessList* this) { char* token = at; // mark beginning of path at = strchr(at, ' '); // find end of path *at = '\0'; at++; // clear and skip - ttyDrivers[numDrivers].path = strdup(token); // save + ttyDrivers[numDrivers].path = xStrdup(token); // save while (*at == ' ') at++; // skip spaces token = at; // mark beginning of major at = strchr(at, ' '); // find end of major @@ -203,12 +145,12 @@ static void LinuxProcessList_initTtyDrivers(LinuxProcessList* this) { numDrivers++; if (numDrivers == allocd) { allocd += 10; - ttyDrivers = realloc(ttyDrivers, sizeof(TtyDriver) * allocd); + ttyDrivers = xRealloc(ttyDrivers, sizeof(TtyDriver) * allocd); } } free(buf); numDrivers++; - ttyDrivers = realloc(ttyDrivers, sizeof(TtyDriver) * numDrivers); + ttyDrivers = xRealloc(ttyDrivers, sizeof(TtyDriver) * numDrivers); ttyDrivers[numDrivers - 1].path = NULL; qsort(ttyDrivers, numDrivers - 1, sizeof(TtyDriver), sortTtyDrivers); this->ttyDrivers = ttyDrivers; @@ -229,44 +171,100 @@ static void LinuxProcessList_initNetlinkSocket(LinuxProcessList* this) { #endif -ProcessList* ProcessList_new(UsersTable* usersTable, Hashtable* pidWhiteList, uid_t userId) { +static int LinuxProcessList_computeCPUcount(void) { + FILE* file = fopen(PROCSTATFILE, "r"); + if (file == NULL) { + CRT_fatalError("Cannot open " PROCSTATFILE); + } + + int cpus = 0; + char buffer[PROC_LINE_LENGTH + 1]; + while (fgets(buffer, sizeof(buffer), file)) { + if (String_startsWith(buffer, "cpu")) { + cpus++; + } + } + + fclose(file); + + /* subtract raw cpu entry */ + if (cpus > 0) { + cpus--; + } + + return cpus; +} + +static void LinuxProcessList_updateCPUcount(LinuxProcessList* this) { + ProcessList* pl = &(this->super); + int cpus = LinuxProcessList_computeCPUcount(); + if (cpus == 0 || cpus == pl->cpuCount) + return; + + pl->cpuCount = cpus; + free(this->cpus); + this->cpus = xCalloc(cpus + 1, sizeof(CPUData)); + + for (int i = 0; i <= cpus; i++) { + this->cpus[i].totalTime = 1; + this->cpus[i].totalPeriod = 1; + } +} + +ProcessList* ProcessList_new(UsersTable* usersTable, Hashtable* pidMatchList, uid_t userId) { LinuxProcessList* this = xCalloc(1, sizeof(LinuxProcessList)); ProcessList* pl = &(this->super); - ProcessList_init(pl, Class(LinuxProcess), usersTable, pidWhiteList, userId); + ProcessList_init(pl, Class(LinuxProcess), usersTable, pidMatchList, userId); LinuxProcessList_initTtyDrivers(this); #ifdef HAVE_DELAYACCT LinuxProcessList_initNetlinkSocket(this); #endif - // Update CPU count: - FILE* file = fopen(PROCSTATFILE, "r"); - if (file == NULL) { - CRT_fatalError("Cannot open " PROCSTATFILE); + // Check for /proc/*/smaps_rollup availability (improves smaps parsing speed, Linux 4.14+) + FILE* file = fopen(PROCDIR "/self/smaps_rollup", "r"); + if (file != NULL) { + this->haveSmapsRollup = true; + fclose(file); + } else { + this->haveSmapsRollup = false; } - int cpus = 0; - do { - char buffer[PROC_LINE_LENGTH + 1]; - if (fgets(buffer, PROC_LINE_LENGTH + 1, file) == NULL) { - CRT_fatalError("No btime in " PROCSTATFILE); - } else if (String_startsWith(buffer, "cpu")) { - cpus++; - } else if (String_startsWith(buffer, "btime ")) { - sscanf(buffer, "btime %lld\n", &btime); - break; + + // Read btime + { + FILE* statfile = fopen(PROCSTATFILE, "r"); + if (statfile == NULL) { + CRT_fatalError("Cannot open " PROCSTATFILE); } - } while(true); - fclose(file); + while (true) { + char buffer[PROC_LINE_LENGTH + 1]; + if (fgets(buffer, sizeof(buffer), statfile) == NULL) { + CRT_fatalError("No btime in " PROCSTATFILE); + } else if (String_startsWith(buffer, "btime ")) { + if (sscanf(buffer, "btime %lld\n", &btime) != 1) { + CRT_fatalError("Failed to parse btime from " PROCSTATFILE); + } + break; + } + } - pl->cpuCount = MAX(cpus - 1, 1); - this->cpus = xCalloc(cpus, sizeof(CPUData)); + fclose(statfile); + } - for (int i = 0; i < cpus; i++) { - this->cpus[i].totalTime = 1; - this->cpus[i].totalPeriod = 1; + // Initialze CPU count + { + int cpus = LinuxProcessList_computeCPUcount(); + pl->cpuCount = MAXIMUM(cpus, 1); + this->cpus = xCalloc(cpus + 1, sizeof(CPUData)); + + for (int i = 0; i <= cpus; i++) { + this->cpus[i].totalTime = 1; + this->cpus[i].totalPeriod = 1; + } } + return pl; } @@ -275,7 +273,7 @@ void ProcessList_delete(ProcessList* pl) { ProcessList_done(pl); free(this->cpus); if (this->ttyDrivers) { - for(int i = 0; this->ttyDrivers[i].path; i++) { + for (int i = 0; this->ttyDrivers[i].path; i++) { free(this->ttyDrivers[i].path); } free(this->ttyDrivers); @@ -289,38 +287,51 @@ void ProcessList_delete(ProcessList* pl) { free(this); } -static double jiffy = 0.0; - static inline unsigned long long LinuxProcess_adjustTime(unsigned long long t) { - if(jiffy == 0.0) jiffy = sysconf(_SC_CLK_TCK); + static double jiffy = NAN; + if (isnan(jiffy)) { + errno = 0; + long sc_jiffy = sysconf(_SC_CLK_TCK); + if (errno || -1 == sc_jiffy) { + jiffy = NAN; + return t; // Assume 100Hz clock + } + jiffy = sc_jiffy; + } double jiffytime = 1.0 / jiffy; - return (unsigned long long) t * jiffytime * 100; + return t * jiffytime * 100; } -static bool LinuxProcessList_readStatFile(Process *process, const char* dirname, const char* name, char* command, int* commLen) { +static bool LinuxProcessList_readStatFile(Process* process, const char* dirname, const char* name, char* command, int* commLen) { LinuxProcess* lp = (LinuxProcess*) process; - char filename[MAX_NAME+1]; + const int commLenIn = *commLen; + *commLen = 0; + char filename[MAX_NAME + 1]; xSnprintf(filename, MAX_NAME, "%s/%s/stat", dirname, name); int fd = open(filename, O_RDONLY); if (fd == -1) return false; - static char buf[MAX_READ+1]; + static char buf[MAX_READ + 1]; int size = xread(fd, buf, MAX_READ); close(fd); - if (size <= 0) return false; + if (size <= 0) + return false; buf[size] = '\0'; assert(process->pid == atoi(buf)); - char *location = strchr(buf, ' '); - if (!location) return false; + char* location = strchr(buf, ' '); + if (!location) + return false; location += 2; - char *end = strrchr(location, ')'); - if (!end) return false; - - int commsize = end - location; + char* end = strrchr(location, ')'); + if (!end) + return false; + + int commsize = MINIMUM(end - location, commLenIn - 1); + // deepcode ignore BufferOverflow: commsize is bounded by the allocated length passed in by commLen, saved into commLenIn memcpy(command, location, commsize); command[commsize] = '\0'; *commLen = commsize; @@ -362,23 +373,29 @@ static bool LinuxProcessList_readStatFile(Process *process, const char* dirname, location += 1; process->nlwp = strtol(location, &location, 10); location += 1; - location = strchr(location, ' ')+1; - lp->starttime = strtoll(location, &location, 10); + location = strchr(location, ' ') + 1; + if (process->starttime_ctime == 0) { + process->starttime_ctime = btime + LinuxProcess_adjustTime(strtoll(location, &location, 10)) / 100; + } else { + location = strchr(location, ' ') + 1; + } location += 1; - for (int i=0; i<15; i++) location = strchr(location, ' ')+1; + for (int i = 0; i < 15; i++) { + location = strchr(location, ' ') + 1; + } process->exit_signal = strtol(location, &location, 10); location += 1; assert(location != NULL); process->processor = strtol(location, &location, 10); - + process->time = lp->utime + lp->stime; - + return true; } -static bool LinuxProcessList_statProcessDir(Process* process, const char* dirname, char* name) { - char filename[MAX_NAME+1]; +static bool LinuxProcessList_statProcessDir(Process* process, const char* dirname, const char* name) { + char filename[MAX_NAME + 1]; filename[MAX_NAME] = '\0'; xSnprintf(filename, MAX_NAME, "%s/%s", dirname, name); @@ -392,15 +409,15 @@ static bool LinuxProcessList_statProcessDir(Process* process, const char* dirnam #ifdef HAVE_TASKSTATS -static void LinuxProcessList_readIoFile(LinuxProcess* process, const char* dirname, char* name, unsigned long long now) { - char filename[MAX_NAME+1]; +static void LinuxProcessList_readIoFile(LinuxProcess* process, const char* dirname, const char* name, unsigned long long now) { + char filename[MAX_NAME + 1]; filename[MAX_NAME] = '\0'; xSnprintf(filename, MAX_NAME, "%s/%s/io", dirname, name); int fd = open(filename, O_RDONLY); if (fd == -1) { - process->io_rate_read_bps = -1; - process->io_rate_write_bps = -1; + process->io_rate_read_bps = NAN; + process->io_rate_write_bps = NAN; process->io_rchar = -1LL; process->io_wchar = -1LL; process->io_syscr = -1LL; @@ -412,49 +429,51 @@ static void LinuxProcessList_readIoFile(LinuxProcess* process, const char* dirna process->io_rate_write_time = -1LL; return; } - + char buffer[1024]; ssize_t buflen = xread(fd, buffer, 1023); close(fd); - if (buflen < 1) return; + if (buflen < 1) + return; + buffer[buflen] = '\0'; unsigned long long last_read = process->io_read_bytes; unsigned long long last_write = process->io_write_bytes; - char *buf = buffer; - char *line = NULL; + char* buf = buffer; + char* line = NULL; while ((line = strsep(&buf, "\n")) != NULL) { switch (line[0]) { case 'r': - if (line[1] == 'c' && strncmp(line+2, "har: ", 5) == 0) - process->io_rchar = strtoull(line+7, NULL, 10); - else if (strncmp(line+1, "ead_bytes: ", 11) == 0) { - process->io_read_bytes = strtoull(line+12, NULL, 10); - process->io_rate_read_bps = - ((double)(process->io_read_bytes - last_read))/(((double)(now - process->io_rate_read_time))/1000); + if (line[1] == 'c' && String_startsWith(line + 2, "har: ")) { + process->io_rchar = strtoull(line + 7, NULL, 10); + } else if (String_startsWith(line + 1, "ead_bytes: ")) { + process->io_read_bytes = strtoull(line + 12, NULL, 10); + process->io_rate_read_bps = + ((double)(process->io_read_bytes - last_read)) / (((double)(now - process->io_rate_read_time)) / 1000); process->io_rate_read_time = now; } break; case 'w': - if (line[1] == 'c' && strncmp(line+2, "har: ", 5) == 0) - process->io_wchar = strtoull(line+7, NULL, 10); - else if (strncmp(line+1, "rite_bytes: ", 12) == 0) { - process->io_write_bytes = strtoull(line+13, NULL, 10); - process->io_rate_write_bps = - ((double)(process->io_write_bytes - last_write))/(((double)(now - process->io_rate_write_time))/1000); + if (line[1] == 'c' && String_startsWith(line + 2, "har: ")) { + process->io_wchar = strtoull(line + 7, NULL, 10); + } else if (String_startsWith(line + 1, "rite_bytes: ")) { + process->io_write_bytes = strtoull(line + 13, NULL, 10); + process->io_rate_write_bps = + ((double)(process->io_write_bytes - last_write)) / (((double)(now - process->io_rate_write_time)) / 1000); process->io_rate_write_time = now; } break; case 's': - if (line[4] == 'r' && strncmp(line+1, "yscr: ", 6) == 0) { - process->io_syscr = strtoull(line+7, NULL, 10); - } else if (strncmp(line+1, "yscw: ", 6) == 0) { - process->io_syscw = strtoull(line+7, NULL, 10); + if (line[4] == 'r' && String_startsWith(line + 1, "yscr: ")) { + process->io_syscr = strtoull(line + 7, NULL, 10); + } else if (String_startsWith(line + 1, "yscw: ")) { + process->io_syscw = strtoull(line + 7, NULL, 10); } break; case 'c': - if (strncmp(line+1, "ancelled_write_bytes: ", 22) == 0) { - process->io_cancelled_write_bytes = strtoull(line+23, NULL, 10); - } + if (String_startsWith(line + 1, "ancelled_write_bytes: ")) { + process->io_cancelled_write_bytes = strtoull(line + 23, NULL, 10); + } } } } @@ -464,52 +483,160 @@ static void LinuxProcessList_readIoFile(LinuxProcess* process, const char* dirna static bool LinuxProcessList_readStatmFile(LinuxProcess* process, const char* dirname, const char* name) { - char filename[MAX_NAME+1]; - xSnprintf(filename, MAX_NAME, "%s/%s/statm", dirname, name); - int fd = open(filename, O_RDONLY); - if (fd == -1) + char filename[MAX_NAME + 1]; + xSnprintf(filename, sizeof(filename), "%s/%s/statm", dirname, name); + FILE* statmfile = fopen(filename, "r"); + if (!statmfile) return false; - char buf[PROC_LINE_LENGTH + 1]; - ssize_t rres = xread(fd, buf, PROC_LINE_LENGTH); - close(fd); - if (rres < 1) return false; - - char *p = buf; - errno = 0; - process->super.m_size = strtol(p, &p, 10); if (*p == ' ') p++; - process->super.m_resident = strtol(p, &p, 10); if (*p == ' ') p++; - process->m_share = strtol(p, &p, 10); if (*p == ' ') p++; - process->m_trs = strtol(p, &p, 10); if (*p == ' ') p++; - process->m_lrs = strtol(p, &p, 10); if (*p == ' ') p++; - process->m_drs = strtol(p, &p, 10); if (*p == ' ') p++; - process->m_dt = strtol(p, &p, 10); - return (errno == 0); + + int r = fscanf(statmfile, "%ld %ld %ld %ld %ld %ld %ld", + &process->super.m_size, + &process->super.m_resident, + &process->m_share, + &process->m_trs, + &process->m_lrs, + &process->m_drs, + &process->m_dt); + fclose(statmfile); + return r == 7; +} + +static bool LinuxProcessList_readSmapsFile(LinuxProcess* process, const char* dirname, const char* name, bool haveSmapsRollup) { + //http://elixir.free-electrons.com/linux/v4.10/source/fs/proc/task_mmu.c#L719 + //kernel will return data in chunks of size PAGE_SIZE or less. + + char buffer[256]; + + if (haveSmapsRollup) {// only available in Linux 4.14+ + xSnprintf(buffer, sizeof(buffer), "%s/%s/smaps_rollup", dirname, name); + } else { + xSnprintf(buffer, sizeof(buffer), "%s/%s/smaps", dirname, name); + } + + FILE* f = fopen(buffer, "r"); + if (!f) + return false; + + process->m_pss = 0; + process->m_swap = 0; + process->m_psswp = 0; + + while (fgets(buffer, sizeof(buffer), f)) { + if (!strchr(buffer, '\n')) { + // Partial line, skip to end of this line + while (fgets(buffer, sizeof(buffer), f)) { + if (strchr(buffer, '\n')) { + break; + } + } + continue; + } + + if (String_startsWith(buffer, "Pss:")) { + process->m_pss += strtol(buffer + 4, NULL, 10); + } else if (String_startsWith(buffer, "Swap:")) { + process->m_swap += strtol(buffer + 5, NULL, 10); + } else if (String_startsWith(buffer, "SwapPss:")) { + process->m_psswp += strtol(buffer + 8, NULL, 10); + } + } + + fclose(f); + return true; } #ifdef HAVE_OPENVZ static void LinuxProcessList_readOpenVZData(LinuxProcess* process, const char* dirname, const char* name) { - if ( (access("/proc/vz", R_OK) != 0)) { + if ( (access(PROCDIR "/vz", R_OK) != 0)) { + free(process->ctid); + process->ctid = NULL; process->vpid = process->super.pid; - process->ctid = 0; return; } - char filename[MAX_NAME+1]; - xSnprintf(filename, MAX_NAME, "%s/%s/stat", dirname, name); + + char filename[MAX_NAME + 1]; + xSnprintf(filename, sizeof(filename), "%s/%s/status", dirname, name); FILE* file = fopen(filename, "r"); - if (!file) + if (!file) { + free(process->ctid); + process->ctid = NULL; + process->vpid = process->super.pid; return; - (void) fscanf(file, - "%*32u %*32s %*1c %*32u %*32u %*32u %*32u %*32u %*32u %*32u " - "%*32u %*32u %*32u %*32u %*32u %*32u %*32u %*32u " - "%*32u %*32u %*32u %*32u %*32u %*32u %*32u %*32u " - "%*32u %*32u %*32u %*32u %*32u %*32u %*32u %*32u " - "%*32u %*32u %*32u %*32u %*32u %*32u %*32u %*32u " - "%*32u %*32u %*32u %*32u %*32u %*32u %*32u " - "%*32u %*32u %32u %32u", - &process->vpid, &process->ctid); + } + + bool foundEnvID = false; + bool foundVPid = false; + char linebuf[256]; + while (fgets(linebuf, sizeof(linebuf), file) != NULL) { + if (strchr(linebuf, '\n') == NULL) { + // Partial line, skip to end of this line + while (fgets(linebuf, sizeof(linebuf), file) != NULL) { + if (strchr(linebuf, '\n') != NULL) { + break; + } + } + continue; + } + + char* name_value_sep = strchr(linebuf, ':'); + if (name_value_sep == NULL) { + continue; + } + + int field; + if (0 == strncasecmp(linebuf, "envID", name_value_sep - linebuf)) { + field = 1; + } else if (0 == strncasecmp(linebuf, "VPid", name_value_sep - linebuf)) { + field = 2; + } else { + continue; + } + + do { + name_value_sep++; + } while (*name_value_sep != '\0' && *name_value_sep <= 32); + + char* value_end = name_value_sep; + + while(*value_end > 32) { + value_end++; + } + + if (name_value_sep == value_end) { + continue; + } + + *value_end = '\0'; + + switch(field) { + case 1: + foundEnvID = true; + if (!String_eq(name_value_sep, process->ctid ? process->ctid : "")) { + free(process->ctid); + process->ctid = xStrdup(name_value_sep); + } + break; + case 2: + foundVPid = true; + process->vpid = strtoul(name_value_sep, NULL, 0); + break; + default: + //Sanity Check: Should never reach here, or the implementation is missing something! + assert(false && "OpenVZ handling: Unimplemented case for field handling reached."); + } + } + fclose(file); - return; + + if (!foundEnvID) { + free(process->ctid); + process->ctid = NULL; + } + + if (!foundVPid) { + process->vpid = process->super.pid; + } } #endif @@ -517,11 +644,14 @@ static void LinuxProcessList_readOpenVZData(LinuxProcess* process, const char* d #ifdef HAVE_CGROUP static void LinuxProcessList_readCGroupFile(LinuxProcess* process, const char* dirname, const char* name) { - char filename[MAX_NAME+1]; + char filename[MAX_NAME + 1]; xSnprintf(filename, MAX_NAME, "%s/%s/cgroup", dirname, name); FILE* file = fopen(filename, "r"); if (!file) { - process->cgroup = xStrdup(""); + if (process->cgroup) { + free(process->cgroup); + process->cgroup = NULL; + } return; } char output[PROC_LINE_LENGTH + 1]; @@ -530,10 +660,14 @@ static void LinuxProcessList_readCGroupFile(LinuxProcess* process, const char* d int left = PROC_LINE_LENGTH; while (!feof(file) && left > 0) { char buffer[PROC_LINE_LENGTH + 1]; - char *ok = fgets(buffer, PROC_LINE_LENGTH, file); - if (!ok) break; + char* ok = fgets(buffer, PROC_LINE_LENGTH, file); + if (!ok) + break; + char* group = strchr(buffer, ':'); - if (!group) break; + if (!group) + break; + if (at != output) { *at = ';'; at++; @@ -552,11 +686,12 @@ static void LinuxProcessList_readCGroupFile(LinuxProcess* process, const char* d #ifdef HAVE_VSERVER static void LinuxProcessList_readVServerData(LinuxProcess* process, const char* dirname, const char* name) { - char filename[MAX_NAME+1]; + char filename[MAX_NAME + 1]; xSnprintf(filename, MAX_NAME, "%s/%s/status", dirname, name); FILE* file = fopen(filename, "r"); if (!file) return; + char buffer[PROC_LINE_LENGTH + 1]; process->vxid = 0; while (fgets(buffer, PROC_LINE_LENGTH, file)) { @@ -583,7 +718,7 @@ static void LinuxProcessList_readVServerData(LinuxProcess* process, const char* #endif static void LinuxProcessList_readOomData(LinuxProcess* process, const char* dirname, const char* name) { - char filename[MAX_NAME+1]; + char filename[MAX_NAME + 1]; xSnprintf(filename, MAX_NAME, "%s/%s/oom_score", dirname, name); FILE* file = fopen(filename, "r"); if (!file) { @@ -592,7 +727,7 @@ static void LinuxProcessList_readOomData(LinuxProcess* process, const char* dirn char buffer[PROC_LINE_LENGTH + 1]; if (fgets(buffer, PROC_LINE_LENGTH, file)) { unsigned int oom; - int ok = sscanf(buffer, "%32u", &oom); + int ok = sscanf(buffer, "%u", &oom); if (ok >= 1) { process->oom = oom; } @@ -600,13 +735,70 @@ static void LinuxProcessList_readOomData(LinuxProcess* process, const char* dirn fclose(file); } +static void LinuxProcessList_readCtxtData(LinuxProcess* process, const char* dirname, const char* name) { + char filename[MAX_NAME + 1]; + xSnprintf(filename, MAX_NAME, "%s/%s/status", dirname, name); + FILE* file = fopen(filename, "r"); + if (!file) + return; + + char buffer[PROC_LINE_LENGTH + 1]; + unsigned long ctxt = 0; + while (fgets(buffer, PROC_LINE_LENGTH, file)) { + if (String_startsWith(buffer, "voluntary_ctxt_switches:")) { + unsigned long vctxt; + int ok = sscanf(buffer, "voluntary_ctxt_switches:\t%lu", &vctxt); + if (ok >= 1) { + ctxt += vctxt; + } + } else if (String_startsWith(buffer, "nonvoluntary_ctxt_switches:")) { + unsigned long nvctxt; + int ok = sscanf(buffer, "nonvoluntary_ctxt_switches:\t%lu", &nvctxt); + if (ok >= 1) { + ctxt += nvctxt; + } + } + } + fclose(file); + process->ctxt_diff = (ctxt > process->ctxt_total) ? (ctxt - process->ctxt_total) : 0; + process->ctxt_total = ctxt; +} + +static void LinuxProcessList_readSecattrData(LinuxProcess* process, const char* dirname, const char* name) { + char filename[MAX_NAME + 1]; + xSnprintf(filename, sizeof(filename), "%s/%s/attr/current", dirname, name); + FILE* file = fopen(filename, "r"); + if (!file) { + free(process->secattr); + process->secattr = NULL; + return; + } + char buffer[PROC_LINE_LENGTH + 1]; + char* res = fgets(buffer, sizeof(buffer), file); + fclose(file); + if (!res) { + free(process->secattr); + process->secattr = NULL; + return; + } + char* newline = strchr(buffer, '\n'); + if (newline) { + *newline = '\0'; + } + if (process->secattr && String_eq(process->secattr, buffer)) { + return; + } + free(process->secattr); + process->secattr = xStrdup(buffer); +} + #ifdef HAVE_DELAYACCT -static int handleNetlinkMsg(struct nl_msg *nlmsg, void *linuxProcess) { - struct nlmsghdr *nlhdr; - struct nlattr *nlattrs[TASKSTATS_TYPE_MAX + 1]; - struct nlattr *nlattr; - struct taskstats *stats; +static int handleNetlinkMsg(struct nl_msg* nlmsg, void* linuxProcess) { + struct nlmsghdr* nlhdr; + struct nlattr* nlattrs[TASKSTATS_TYPE_MAX + 1]; + struct nlattr* nlattr; + struct taskstats stats; int rem; unsigned long long int timeDelta; LinuxProcess* lp = (LinuxProcess*) linuxProcess; @@ -618,26 +810,28 @@ static int handleNetlinkMsg(struct nl_msg *nlmsg, void *linuxProcess) { } if ((nlattr = nlattrs[TASKSTATS_TYPE_AGGR_PID]) || (nlattr = nlattrs[TASKSTATS_TYPE_NULL])) { - stats = nla_data(nla_next(nla_data(nlattr), &rem)); - assert(lp->super.pid == stats->ac_pid); - timeDelta = (stats->ac_etime*1000 - lp->delay_read_time); - #define BOUNDS(x) isnan(x) ? 0.0 : (x > 100) ? 100.0 : x; - #define DELTAPERC(x,y) BOUNDS((float) (x - y) / timeDelta * 100); - lp->cpu_delay_percent = DELTAPERC(stats->cpu_delay_total, lp->cpu_delay_total); - lp->blkio_delay_percent = DELTAPERC(stats->blkio_delay_total, lp->blkio_delay_total); - lp->swapin_delay_percent = DELTAPERC(stats->swapin_delay_total, lp->swapin_delay_total); + memcpy(&stats, nla_data(nla_next(nla_data(nlattr), &rem)), sizeof(stats)); + assert(lp->super.pid == (pid_t)stats.ac_pid); + + timeDelta = stats.ac_etime * 1000 - lp->delay_read_time; + #define BOUNDS(x) (isnan(x) ? 0.0 : ((x) > 100) ? 100.0 : (x)) + #define DELTAPERC(x,y) BOUNDS((float) ((x) - (y)) / timeDelta * 100) + lp->cpu_delay_percent = DELTAPERC(stats.cpu_delay_total, lp->cpu_delay_total); + lp->blkio_delay_percent = DELTAPERC(stats.blkio_delay_total, lp->blkio_delay_total); + lp->swapin_delay_percent = DELTAPERC(stats.swapin_delay_total, lp->swapin_delay_total); #undef DELTAPERC #undef BOUNDS - lp->swapin_delay_total = stats->swapin_delay_total; - lp->blkio_delay_total = stats->blkio_delay_total; - lp->cpu_delay_total = stats->cpu_delay_total; - lp->delay_read_time = stats->ac_etime*1000; + + lp->swapin_delay_total = stats.swapin_delay_total; + lp->blkio_delay_total = stats.blkio_delay_total; + lp->cpu_delay_total = stats.cpu_delay_total; + lp->delay_read_time = stats.ac_etime * 1000; } return NL_OK; } static void LinuxProcessList_readDelayAcctData(LinuxProcessList* this, LinuxProcess* process) { - struct nl_msg *msg; + struct nl_msg* msg; if (nl_socket_modify_cb(this->netlink_socket, NL_CB_VALID, NL_CB_CUSTOM, handleNetlinkMsg, process) < 0) { return; @@ -656,12 +850,12 @@ static void LinuxProcessList_readDelayAcctData(LinuxProcessList* this, LinuxProc } if (nl_send_sync(this->netlink_socket, msg) < 0) { - process->swapin_delay_percent = -1LL; - process->blkio_delay_percent = -1LL; - process->cpu_delay_percent = -1LL; + process->swapin_delay_percent = NAN; + process->blkio_delay_percent = NAN; + process->cpu_delay_percent = NAN; return; } - + if (nl_recvmsgs_default(this->netlink_socket) < 0) { return; } @@ -680,19 +874,23 @@ static void setCommand(Process* process, const char* command, int len) { } static bool LinuxProcessList_readCmdlineFile(Process* process, const char* dirname, const char* name) { - char filename[MAX_NAME+1]; + char filename[MAX_NAME + 1]; xSnprintf(filename, MAX_NAME, "%s/%s/cmdline", dirname, name); int fd = open(filename, O_RDONLY); if (fd == -1) return false; - - char command[4096+1]; // max cmdline length on Linux + + char command[4096 + 1]; // max cmdline length on Linux int amtRead = xread(fd, command, sizeof(command) - 1); close(fd); - int tokenEnd = 0; + int tokenEnd = 0; int lastChar = 0; if (amtRead == 0) { - ((LinuxProcess*)process)->isKernelThread = true; + if (process->state == 'Z') { + process->basenameOffset = 0; + } else { + ((LinuxProcess*)process)->isKernelThread = true; + } return true; } else if (amtRead < 0) { return false; @@ -726,60 +924,78 @@ static char* LinuxProcessList_updateTtyDevice(TtyDriver* ttyDrivers, unsigned in i++; if ((!ttyDrivers[i].path) || maj < ttyDrivers[i].major) { break; - } + } if (maj > ttyDrivers[i].major) { continue; } if (min < ttyDrivers[i].minorFrom) { break; - } + } if (min > ttyDrivers[i].minorTo) { continue; } unsigned int idx = min - ttyDrivers[i].minorFrom; struct stat sstat; char* fullPath; - for(;;) { - asprintf(&fullPath, "%s/%d", ttyDrivers[i].path, idx); + for (;;) { + xAsprintf(&fullPath, "%s/%d", ttyDrivers[i].path, idx); int err = stat(fullPath, &sstat); - if (err == 0 && major(sstat.st_rdev) == maj && minor(sstat.st_rdev) == min) return fullPath; + if (err == 0 && major(sstat.st_rdev) == maj && minor(sstat.st_rdev) == min) { + return fullPath; + } free(fullPath); - asprintf(&fullPath, "%s%d", ttyDrivers[i].path, idx); + + xAsprintf(&fullPath, "%s%d", ttyDrivers[i].path, idx); err = stat(fullPath, &sstat); - if (err == 0 && major(sstat.st_rdev) == maj && minor(sstat.st_rdev) == min) return fullPath; + if (err == 0 && major(sstat.st_rdev) == maj && minor(sstat.st_rdev) == min) { + return fullPath; + } free(fullPath); - if (idx == min) break; + + if (idx == min) { + break; + } + idx = min; } int err = stat(ttyDrivers[i].path, &sstat); - if (err == 0 && tty_nr == sstat.st_rdev) return strdup(ttyDrivers[i].path); + if (err == 0 && tty_nr == sstat.st_rdev) { + return xStrdup(ttyDrivers[i].path); + } } char* out; - asprintf(&out, "/dev/%u:%u", maj, min); + xAsprintf(&out, "/dev/%u:%u", maj, min); return out; } static bool LinuxProcessList_recurseProcTree(LinuxProcessList* this, const char* dirname, Process* parent, double period, struct timeval tv) { ProcessList* pl = (ProcessList*) this; DIR* dir; - struct dirent* entry; - Settings* settings = pl->settings; + const struct dirent* entry; + const Settings* settings = pl->settings; #ifdef HAVE_TASKSTATS - unsigned long long now = tv.tv_sec*1000LL+tv.tv_usec/1000LL; + unsigned long long now = tv.tv_sec * 1000LL + tv.tv_usec / 1000LL; #endif dir = opendir(dirname); - if (!dir) return false; + if (!dir) + return false; + int cpus = pl->cpuCount; bool hideKernelThreads = settings->hideKernelThreads; bool hideUserlandThreads = settings->hideUserlandThreads; while ((entry = readdir(dir)) != NULL) { - char* name = entry->d_name; + const char* name = entry->d_name; + + // Ignore all non-directories + if (entry->d_type != DT_DIR && entry->d_type != DT_UNKNOWN) { + continue; + } // The RedHat kernel hides threads with a dot. // I believe this is non-standard. - if ((!settings->hideThreads) && name[0] == '.') { + if (name[0] == '.') { name++; } @@ -790,20 +1006,20 @@ static bool LinuxProcessList_recurseProcTree(LinuxProcessList* this, const char* // filename is a number: process directory int pid = atoi(name); - + if (parent && pid == parent->pid) continue; - if (pid <= 0) + if (pid <= 0) continue; bool preExisting = false; - Process* proc = ProcessList_getProcess(pl, pid, &preExisting, (Process_New) LinuxProcess_new); + Process* proc = ProcessList_getProcess(pl, pid, &preExisting, LinuxProcess_new); proc->tgid = parent ? parent->pid : pid; - + LinuxProcess* lp = (LinuxProcess*) proc; - char subdirname[MAX_NAME+1]; + char subdirname[MAX_NAME + 1]; xSnprintf(subdirname, MAX_NAME, "%s/%s/task", dirname, name); LinuxProcessList_recurseProcTree(this, subdirname, proc, period, tv); @@ -815,26 +1031,44 @@ static bool LinuxProcessList_recurseProcTree(LinuxProcessList* this, const char* if (! LinuxProcessList_readStatmFile(lp, dirname, name)) goto errorReadingProcess; + if ((settings->flags & PROCESS_FLAG_LINUX_SMAPS) && !Process_isKernelThread(proc)) { + if (!parent) { + // Read smaps file of each process only every second pass to improve performance + static int smaps_flag = 0; + if ((pid & 1) == smaps_flag) { + LinuxProcessList_readSmapsFile(lp, dirname, name, this->haveSmapsRollup); + } + if (pid == 1) { + smaps_flag = !smaps_flag; + } + } else { + lp->m_pss = ((LinuxProcess*)parent)->m_pss; + } + } + proc->show = ! ((hideKernelThreads && Process_isKernelThread(proc)) || (hideUserlandThreads && Process_isUserlandThread(proc))); - char command[MAX_NAME+1]; + char command[MAX_NAME + 1]; unsigned long long int lasttimes = (lp->utime + lp->stime); - int commLen = 0; + int commLen = sizeof(command); unsigned int tty_nr = proc->tty_nr; if (! LinuxProcessList_readStatFile(proc, dirname, name, command, &commLen)) goto errorReadingProcess; + if (tty_nr != proc->tty_nr && this->ttyDrivers) { free(lp->ttyDevice); lp->ttyDevice = LinuxProcessList_updateTtyDevice(this->ttyDrivers, proc->tty_nr); } - if (settings->flags & PROCESS_FLAG_LINUX_IOPRIO) + + if (settings->flags & PROCESS_FLAG_LINUX_IOPRIO) { LinuxProcess_updateIOPriority(lp); + } + float percent_cpu = (lp->utime + lp->stime - lasttimes) / period * 100.0; - proc->percent_cpu = CLAMP(percent_cpu, 0.0, cpus * 100.0); - if (isnan(proc->percent_cpu)) proc->percent_cpu = 0.0; - proc->percent_mem = (proc->m_resident * PAGE_SIZE_KB) / (double)(pl->totalMem) * 100.0; + proc->percent_cpu = isnan(percent_cpu) ? 0.0 : CLAMP(percent_cpu, 0.0, cpus * 100.0); + proc->percent_mem = (proc->m_resident * CRT_pageSizeKB) / (double)(pl->totalMem) * 100.0; - if(!preExisting) { + if (!preExisting) { if (! LinuxProcessList_statProcessDir(proc, dirname, name)) goto errorReadingProcess; @@ -846,7 +1080,7 @@ static bool LinuxProcessList_recurseProcTree(LinuxProcessList* this, const char* LinuxProcessList_readOpenVZData(lp, dirname, name); } #endif - + #ifdef HAVE_VSERVER if (settings->flags & PROCESS_FLAG_LINUX_VSERVER) { LinuxProcessList_readVServerData(lp, dirname, name); @@ -857,6 +1091,8 @@ static bool LinuxProcessList_recurseProcTree(LinuxProcessList* this, const char* goto errorReadingProcess; } + Process_fillStarttimeBuffer(proc); + ProcessList_add(pl, proc); } else { if (settings->updateProcessNames && proc->state != 'Z') { @@ -871,12 +1107,22 @@ static bool LinuxProcessList_recurseProcTree(LinuxProcessList* this, const char* #endif #ifdef HAVE_CGROUP - if (settings->flags & PROCESS_FLAG_LINUX_CGROUP) + if (settings->flags & PROCESS_FLAG_LINUX_CGROUP) { LinuxProcessList_readCGroupFile(lp, dirname, name); + } #endif - - if (settings->flags & PROCESS_FLAG_LINUX_OOM) + + if (settings->flags & PROCESS_FLAG_LINUX_OOM) { LinuxProcessList_readOomData(lp, dirname, name); + } + + if (settings->flags & PROCESS_FLAG_LINUX_CTXT) { + LinuxProcessList_readCtxtData(lp, dirname, name); + } + + if (settings->flags & PROCESS_FLAG_LINUX_SECATTR) { + LinuxProcessList_readSecattrData(lp, dirname, name); + } if (proc->state == 'Z' && (proc->basenameOffset == 0)) { proc->basenameOffset = -1; @@ -886,8 +1132,9 @@ static bool LinuxProcessList_recurseProcTree(LinuxProcessList* this, const char* proc->basenameOffset = -1; setCommand(proc, command, commLen); } else if (settings->showThreadNames) { - if (! LinuxProcessList_readCmdlineFile(proc, dirname, name)) + if (! LinuxProcessList_readCmdlineFile(proc, dirname, name)) { goto errorReadingProcess; + } } if (Process_isKernelThread(proc)) { pl->kernelThreads++; @@ -903,7 +1150,9 @@ static bool LinuxProcessList_recurseProcTree(LinuxProcessList* this, const char* continue; // Exception handler. - errorReadingProcess: { + +errorReadingProcess: + { if (preExisting) { ProcessList_remove(pl, proc); } else { @@ -927,7 +1176,12 @@ static inline void LinuxProcessList_scanMemoryInfo(ProcessList* this) { char buffer[128]; while (fgets(buffer, 128, file)) { - #define tryRead(label, variable) do { if (String_startsWith(buffer, label) && sscanf(buffer + strlen(label), " %32llu kB", variable)) { break; } } while(0) + #define tryRead(label, variable) \ + if (String_startsWith(buffer, label)) { \ + sscanf(buffer + strlen(label), " %32llu kB", variable); \ + break; \ + } + switch (buffer[0]) { case 'M': tryRead("MemTotal:", &this->totalMem); @@ -964,6 +1218,125 @@ static inline void LinuxProcessList_scanMemoryInfo(ProcessList* this) { fclose(file); } +static inline void LinuxProcessList_scanZramInfo(LinuxProcessList* this) { + unsigned long long int totalZram = 0; + unsigned long long int usedZramComp = 0; + unsigned long long int usedZramOrig = 0; + + char mm_stat[34]; + char disksize[34]; + + unsigned int i = 0; + for (;;) { + xSnprintf(mm_stat, sizeof(mm_stat), "/sys/block/zram%u/mm_stat", i); + xSnprintf(disksize, sizeof(disksize), "/sys/block/zram%u/disksize", i); + i++; + FILE* disksize_file = fopen(disksize, "r"); + FILE* mm_stat_file = fopen(mm_stat, "r"); + if (disksize_file == NULL || mm_stat_file == NULL) { + if (disksize_file) { + fclose(disksize_file); + } + if (mm_stat_file) { + fclose(mm_stat_file); + } + break; + } + unsigned long long int size = 0; + unsigned long long int orig_data_size = 0; + unsigned long long int compr_data_size = 0; + + if (!fscanf(disksize_file, "%llu\n", &size) || + !fscanf(mm_stat_file, " %llu %llu", &orig_data_size, &compr_data_size)) { + fclose(disksize_file); + fclose(mm_stat_file); + break; + } + + totalZram += size; + usedZramComp += compr_data_size; + usedZramOrig += orig_data_size; + + fclose(disksize_file); + fclose(mm_stat_file); + } + + this->zram.totalZram = totalZram / 1024; + this->zram.usedZramComp = usedZramComp / 1024; + this->zram.usedZramOrig = usedZramOrig / 1024; +} + +static inline void LinuxProcessList_scanZfsArcstats(LinuxProcessList* lpl) { + unsigned long long int dbufSize = 0; + unsigned long long int dnodeSize = 0; + unsigned long long int bonusSize = 0; + + FILE* file = fopen(PROCARCSTATSFILE, "r"); + if (file == NULL) { + lpl->zfs.enabled = 0; + return; + } + char buffer[128]; + while (fgets(buffer, 128, file)) { + #define tryRead(label, variable) \ + if (String_startsWith(buffer, label)) { \ + sscanf(buffer + strlen(label), " %*2u %32llu", variable); \ + break; \ + } + #define tryReadFlag(label, variable, flag) \ + if (String_startsWith(buffer, label)) { \ + (flag) = sscanf(buffer + strlen(label), " %*2u %32llu", variable); \ + break; \ + } + + switch (buffer[0]) { + case 'c': + tryRead("c_max", &lpl->zfs.max); + tryReadFlag("compressed_size", &lpl->zfs.compressed, lpl->zfs.isCompressed); + break; + case 'u': + tryRead("uncompressed_size", &lpl->zfs.uncompressed); + break; + case 's': + tryRead("size", &lpl->zfs.size); + break; + case 'h': + tryRead("hdr_size", &lpl->zfs.header); + break; + case 'd': + tryRead("dbuf_size", &dbufSize); + tryRead("dnode_size", &dnodeSize); + break; + case 'b': + tryRead("bonus_size", &bonusSize); + break; + case 'a': + tryRead("anon_size", &lpl->zfs.anon); + break; + case 'm': + tryRead("mfu_size", &lpl->zfs.MFU); + tryRead("mru_size", &lpl->zfs.MRU); + break; + } + #undef tryRead + #undef tryReadFlag + } + fclose(file); + + lpl->zfs.enabled = (lpl->zfs.size > 0 ? 1 : 0); + lpl->zfs.size /= 1024; + lpl->zfs.max /= 1024; + lpl->zfs.MFU /= 1024; + lpl->zfs.MRU /= 1024; + lpl->zfs.anon /= 1024; + lpl->zfs.header /= 1024; + lpl->zfs.other = (dbufSize + dnodeSize + bonusSize) / 1024; + if ( lpl->zfs.isCompressed ) { + lpl->zfs.compressed /= 1024; + lpl->zfs.uncompressed /= 1024; + } +} + static inline double LinuxProcessList_scanCPUTime(LinuxProcessList* this) { FILE* file = fopen(PROCSTATFILE, "r"); @@ -981,12 +1354,15 @@ static inline double LinuxProcessList_scanCPUTime(LinuxProcessList* this) { // 5, 7, 8 or 9 of these fields will be set. // The rest will remain at zero. char* ok = fgets(buffer, PROC_LINE_LENGTH, file); - if (!ok) buffer[0] = '\0'; - if (i == 0) - sscanf(buffer, "cpu %16llu %16llu %16llu %16llu %16llu %16llu %16llu %16llu %16llu %16llu", &usertime, &nicetime, &systemtime, &idletime, &ioWait, &irq, &softIrq, &steal, &guest, &guestnice); - else { + if (!ok) { + buffer[0] = '\0'; + } + + if (i == 0) { + (void) sscanf(buffer, "cpu %16llu %16llu %16llu %16llu %16llu %16llu %16llu %16llu %16llu %16llu", &usertime, &nicetime, &systemtime, &idletime, &ioWait, &irq, &softIrq, &steal, &guest, &guestnice); + } else { int cpuid; - sscanf(buffer, "cpu%4d %16llu %16llu %16llu %16llu %16llu %16llu %16llu %16llu %16llu %16llu", &cpuid, &usertime, &nicetime, &systemtime, &idletime, &ioWait, &irq, &softIrq, &steal, &guest, &guestnice); + (void) sscanf(buffer, "cpu%4d %16llu %16llu %16llu %16llu %16llu %16llu %16llu %16llu %16llu %16llu", &cpuid, &usertime, &nicetime, &systemtime, &idletime, &ioWait, &irq, &softIrq, &steal, &guest, &guestnice); assert(cpuid == i - 1); } // Guest time is already accounted in usertime @@ -1002,7 +1378,7 @@ static inline double LinuxProcessList_scanCPUTime(LinuxProcessList* this) { // Since we do a subtraction (usertime - guest) and cputime64_to_clock_t() // used in /proc/stat rounds down numbers, it can lead to a case where the // integer overflow. - #define WRAP_SUBTRACT(a,b) (a > b) ? a - b : 0 + #define WRAP_SUBTRACT(a,b) (((a) > (b)) ? (a) - (b) : 0) cpuData->userPeriod = WRAP_SUBTRACT(usertime, cpuData->userTime); cpuData->nicePeriod = WRAP_SUBTRACT(nicetime, cpuData->niceTime); cpuData->systemPeriod = WRAP_SUBTRACT(systemtime, cpuData->systemTime); @@ -1029,17 +1405,126 @@ static inline double LinuxProcessList_scanCPUTime(LinuxProcessList* this) { cpuData->guestTime = virtalltime; cpuData->totalTime = totaltime; } + double period = (double)this->cpus[0].totalPeriod / cpus; fclose(file); return period; } -void ProcessList_goThroughEntries(ProcessList* super) { +static int scanCPUFreqencyFromSysCPUFreq(LinuxProcessList* this) { + int cpus = this->super.cpuCount; + int numCPUsWithFrequency = 0; + unsigned long totalFrequency = 0; + + for (int i = 0; i < cpus; ++i) { + char pathBuffer[64]; + xSnprintf(pathBuffer, sizeof(pathBuffer), "/sys/devices/system/cpu/cpu%d/cpufreq/scaling_cur_freq", i); + + FILE* file = fopen(pathBuffer, "r"); + if (!file) + return -errno; + + unsigned long frequency; + if (fscanf(file, "%lu", &frequency) == 1) { + /* convert kHz to MHz */ + frequency = frequency / 1000; + this->cpus[i + 1].frequency = frequency; + numCPUsWithFrequency++; + totalFrequency += frequency; + } + + fclose(file); + } + + if (numCPUsWithFrequency > 0) + this->cpus[0].frequency = (double)totalFrequency / numCPUsWithFrequency; + + return 0; +} + +static void scanCPUFreqencyFromCPUinfo(LinuxProcessList* this) { + FILE* file = fopen(PROCCPUINFOFILE, "r"); + if (file == NULL) + return; + + int cpus = this->super.cpuCount; + int numCPUsWithFrequency = 0; + double totalFrequency = 0; + int cpuid = -1; + + while (!feof(file)) { + double frequency; + char buffer[PROC_LINE_LENGTH]; + + if (fgets(buffer, PROC_LINE_LENGTH, file) == NULL) + break; + + if ( + (sscanf(buffer, "processor : %d", &cpuid) == 1) || + (sscanf(buffer, "processor: %d", &cpuid) == 1) + ) { + continue; + } else if ( + (sscanf(buffer, "cpu MHz : %lf", &frequency) == 1) || + (sscanf(buffer, "cpu MHz: %lf", &frequency) == 1) + ) { + if (cpuid < 0 || cpuid > (cpus - 1)) { + continue; + } + + CPUData* cpuData = &(this->cpus[cpuid + 1]); + /* do not override sysfs data */ + if (isnan(cpuData->frequency)) { + cpuData->frequency = frequency; + } + numCPUsWithFrequency++; + totalFrequency += frequency; + } else if (buffer[0] == '\n') { + cpuid = -1; + } + } + fclose(file); + + if (numCPUsWithFrequency > 0) { + this->cpus[0].frequency = totalFrequency / numCPUsWithFrequency; + } +} + +static void LinuxProcessList_scanCPUFrequency(LinuxProcessList* this) { + int cpus = this->super.cpuCount; + assert(cpus > 0); + + for (int i = 0; i <= cpus; i++) { + this->cpus[i].frequency = NAN; + } + + if (scanCPUFreqencyFromSysCPUFreq(this) == 0) { + return; + } + + scanCPUFreqencyFromCPUinfo(this); +} + +void ProcessList_goThroughEntries(ProcessList* super, bool pauseProcessUpdate) { LinuxProcessList* this = (LinuxProcessList*) super; + const Settings* settings = super->settings; LinuxProcessList_scanMemoryInfo(super); + LinuxProcessList_scanZfsArcstats(this); + LinuxProcessList_updateCPUcount(this); + LinuxProcessList_scanZramInfo(this); + double period = LinuxProcessList_scanCPUTime(this); + if (settings->showCPUFrequency) { + LinuxProcessList_scanCPUFrequency(this); + } + + // in pause mode only gather global data for meters (CPU/memory/...) + if (pauseProcessUpdate) { + return; + } + struct timeval tv; gettimeofday(&tv, NULL); LinuxProcessList_recurseProcTree(this, PROCDIR, NULL, period, tv); diff --git a/linux/LinuxProcessList.h b/linux/LinuxProcessList.h index f30b487d6..6ecf2103c 100644 --- a/linux/LinuxProcessList.h +++ b/linux/LinuxProcessList.h @@ -1,26 +1,23 @@ -/* Do not edit this file. It was automatically generated. */ - #ifndef HEADER_LinuxProcessList #define HEADER_LinuxProcessList /* htop - LinuxProcessList.h (C) 2014 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ -#ifdef MAJOR_IN_MKDEV -#elif defined(MAJOR_IN_SYSMACROS) || \ - (defined(HAVE_SYS_SYSMACROS_H) && HAVE_SYS_SYSMACROS_H) -#endif - -#ifdef HAVE_DELAYACCT -#endif +#include "config.h" +#include +#include +#include "Hashtable.h" #include "ProcessList.h" +#include "UsersTable.h" +#include "ZramStats.h" +#include "zfs/ZfsArcStats.h" -extern long long btime; typedef struct CPUData_ { unsigned long long int totalTime; @@ -35,7 +32,7 @@ typedef struct CPUData_ { unsigned long long int softIrqTime; unsigned long long int stealTime; unsigned long long int guestTime; - + unsigned long long int totalPeriod; unsigned long long int userPeriod; unsigned long long int systemPeriod; @@ -48,6 +45,8 @@ typedef struct CPUData_ { unsigned long long int softIrqPeriod; unsigned long long int stealPeriod; unsigned long long int guestPeriod; + + double frequency; } CPUData; typedef struct TtyDriver_ { @@ -59,20 +58,28 @@ typedef struct TtyDriver_ { typedef struct LinuxProcessList_ { ProcessList super; - + CPUData* cpus; TtyDriver* ttyDrivers; - + bool haveSmapsRollup; + #ifdef HAVE_DELAYACCT - struct nl_sock *netlink_socket; + struct nl_sock* netlink_socket; int netlink_family; #endif + + ZfsArcStats zfs; + ZramStats zram; } LinuxProcessList; #ifndef PROCDIR #define PROCDIR "/proc" #endif +#ifndef PROCCPUINFOFILE +#define PROCCPUINFOFILE PROCDIR "/cpuinfo" +#endif + #ifndef PROCSTATFILE #define PROCSTATFILE PROCDIR "/stat" #endif @@ -81,6 +88,10 @@ typedef struct LinuxProcessList_ { #define PROCMEMINFOFILE PROCDIR "/meminfo" #endif +#ifndef PROCARCSTATSFILE +#define PROCARCSTATSFILE PROCDIR "/spl/kstat/zfs/arcstats" +#endif + #ifndef PROCTTYDRIVERSFILE #define PROCTTYDRIVERSFILE PROCDIR "/tty/drivers" #endif @@ -89,40 +100,10 @@ typedef struct LinuxProcessList_ { #define PROC_LINE_LENGTH 4096 #endif - -#ifndef CLAMP -#define CLAMP(x,low,high) (((x)>(high))?(high):(((x)<(low))?(low):(x))) -#endif - -#ifdef HAVE_DELAYACCT - -#endif - -ProcessList* ProcessList_new(UsersTable* usersTable, Hashtable* pidWhiteList, uid_t userId); +ProcessList* ProcessList_new(UsersTable* usersTable, Hashtable* pidMatchList, uid_t userId); void ProcessList_delete(ProcessList* pl); - -#ifdef HAVE_TASKSTATS - -#endif - -#ifdef HAVE_OPENVZ - -#endif - -#ifdef HAVE_CGROUP - -#endif - -#ifdef HAVE_VSERVER - -#endif - -#ifdef HAVE_DELAYACCT - -#endif - -void ProcessList_goThroughEntries(ProcessList* super); +void ProcessList_goThroughEntries(ProcessList* super, bool pauseProcessUpdate); #endif diff --git a/linux/Platform.c b/linux/Platform.c index ab90ca74b..575e6e01f 100644 --- a/linux/Platform.c +++ b/linux/Platform.c @@ -1,47 +1,63 @@ /* htop - linux/Platform.c (C) 2014 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ +#include "config.h" + #include "Platform.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "BatteryMeter.h" +#include "ClockMeter.h" +#include "Compat.h" +#include "CPUMeter.h" +#include "DateMeter.h" +#include "DateTimeMeter.h" +#include "DiskIOMeter.h" +#include "HostnameMeter.h" #include "IOPriority.h" #include "IOPriorityPanel.h" #include "LinuxProcess.h" #include "LinuxProcessList.h" -#include "Battery.h" - +#include "LoadAverageMeter.h" +#include "Macros.h" +#include "MainPanel.h" #include "Meter.h" -#include "CPUMeter.h" #include "MemoryMeter.h" +#include "NetworkIOMeter.h" +#include "Object.h" +#include "Panel.h" +#include "PressureStallMeter.h" +#include "ProcessList.h" +#include "ProvideCurses.h" +#include "SELinuxMeter.h" +#include "Settings.h" #include "SwapMeter.h" +#include "SystemdMeter.h" #include "TasksMeter.h" -#include "LoadAverageMeter.h" #include "UptimeMeter.h" -#include "ClockMeter.h" -#include "HostnameMeter.h" -#include "LinuxProcess.h" - -#include -#include -#include -#include -#include +#include "XUtils.h" +#include "ZramMeter.h" -/*{ -#include "Action.h" -#include "MainPanel.h" -#include "BatteryMeter.h" -#include "LinuxProcess.h" -#include "SignalsPanel.h" -}*/ +#include "zfs/ZfsArcMeter.h" +#include "zfs/ZfsArcStats.h" +#include "zfs/ZfsCompressedArcMeter.h" -#ifndef CLAMP -#define CLAMP(x,low,high) (((x)>(high))?(high):(((x)<(low))?(low):(x))) -#endif -ProcessField Platform_defaultFields[] = { PID, USER, PRIORITY, NICE, M_SIZE, M_RESIDENT, M_SHARE, STATE, PERCENT_CPU, PERCENT_MEM, TIME, COMM, 0 }; +ProcessField Platform_defaultFields[] = { PID, USER, PRIORITY, NICE, M_SIZE, M_RESIDENT, (int)M_SHARE, STATE, PERCENT_CPU, PERCENT_MEM, TIME, COMM, 0 }; //static ProcessField defaultIoFields[] = { PID, IO_PRIORITY, USER, IO_READ_RATE, IO_WRITE_RATE, IO_RATE, COMM, 0 }; @@ -84,21 +100,24 @@ const SignalItem Platform_signals[] = { { .name = "31 SIGSYS", .number = 31 }, }; -const unsigned int Platform_numberOfSignals = sizeof(Platform_signals)/sizeof(SignalItem); +const unsigned int Platform_numberOfSignals = ARRAYSIZE(Platform_signals); static Htop_Reaction Platform_actionSetIOPriority(State* st) { Panel* panel = st->panel; LinuxProcess* p = (LinuxProcess*) Panel_getSelected(panel); - if (!p) return HTOP_OK; - IOPriority ioprio = p->ioPriority; - Panel* ioprioPanel = IOPriorityPanel_new(ioprio); - void* set = Action_pickFromVector(st, ioprioPanel, 21); + if (!p) + return HTOP_OK; + + IOPriority ioprio1 = p->ioPriority; + Panel* ioprioPanel = IOPriorityPanel_new(ioprio1); + void* set = Action_pickFromVector(st, ioprioPanel, 21, true); if (set) { - IOPriority ioprio = IOPriorityPanel_getIOPriority(ioprioPanel); - bool ok = MainPanel_foreachProcess((MainPanel*)panel, (MainPanel_ForeachProcessFn) LinuxProcess_setIOPriority, (Arg){ .i = ioprio }, NULL); - if (!ok) + IOPriority ioprio2 = IOPriorityPanel_getIOPriority(ioprioPanel); + bool ok = MainPanel_foreachProcess((MainPanel*)panel, LinuxProcess_setIOPriority, (Arg) { .i = ioprio2 }, NULL); + if (!ok) { beep(); + } } Panel_delete((Object*)ioprioPanel); return HTOP_REFRESH | HTOP_REDRAW_BAR | HTOP_UPDATE_PANELHDR; @@ -108,9 +127,11 @@ void Platform_setBindings(Htop_Action* keys) { keys['i'] = Platform_actionSetIOPriority; } -MeterClass* Platform_meterTypes[] = { +const MeterClass* const Platform_meterTypes[] = { &CPUMeter_class, &ClockMeter_class, + &DateMeter_class, + &DateTimeMeter_class, &LoadAverageMeter_class, &LoadMeter_class, &MemoryMeter_class, @@ -121,11 +142,29 @@ MeterClass* Platform_meterTypes[] = { &HostnameMeter_class, &AllCPUsMeter_class, &AllCPUs2Meter_class, + &AllCPUs4Meter_class, + &AllCPUs8Meter_class, &LeftCPUsMeter_class, &RightCPUsMeter_class, &LeftCPUs2Meter_class, &RightCPUs2Meter_class, + &LeftCPUs4Meter_class, + &RightCPUs4Meter_class, + &LeftCPUs8Meter_class, + &RightCPUs8Meter_class, &BlankMeter_class, + &PressureStallCPUSomeMeter_class, + &PressureStallIOSomeMeter_class, + &PressureStallIOFullMeter_class, + &PressureStallMemorySomeMeter_class, + &PressureStallMemoryFullMeter_class, + &ZfsArcMeter_class, + &ZfsCompressedArcMeter_class, + &ZramMeter_class, + &DiskIOMeter_class, + &NetworkIOMeter_class, + &SELinuxMeter_class, + &SystemdMeter_class, NULL }; @@ -135,15 +174,20 @@ int Platform_getUptime() { if (fd) { int n = fscanf(fd, "%64lf", &uptime); fclose(fd); - if (n <= 0) return 0; + if (n <= 0) { + return 0; + } } - return (int) floor(uptime); + return floor(uptime); } void Platform_getLoadAverage(double* one, double* five, double* fifteen) { int activeProcs, totalProcs, lastProc; - *one = 0; *five = 0; *fifteen = 0; - FILE *fd = fopen(PROCDIR "/loadavg", "r"); + *one = 0; + *five = 0; + *fifteen = 0; + + FILE* fd = fopen(PROCDIR "/loadavg", "r"); if (fd) { int total = fscanf(fd, "%32lf %32lf %32lf %32d/%32d %32d", one, five, fifteen, &activeProcs, &totalProcs, &lastProc); @@ -155,7 +199,9 @@ void Platform_getLoadAverage(double* one, double* five, double* fifteen) { int Platform_getMaxPid() { FILE* file = fopen(PROCDIR "/sys/kernel/pid_max", "r"); - if (!file) return -1; + if (!file) + return -1; + int maxPid = 4194303; int match = fscanf(file, "%32d", &maxPid); (void) match; @@ -164,8 +210,8 @@ int Platform_getMaxPid() { } double Platform_setCPUValues(Meter* this, int cpu) { - LinuxProcessList* pl = (LinuxProcessList*) this->pl; - CPUData* cpuData = &(pl->cpus[cpu]); + const LinuxProcessList* pl = (const LinuxProcessList*) this->pl; + const CPUData* cpuData = &(pl->cpus[cpu]); double total = (double) ( cpuData->totalPeriod == 0 ? 1 : cpuData->totalPeriod); double percent; double* v = this->values; @@ -178,25 +224,32 @@ double Platform_setCPUValues(Meter* this, int cpu) { v[CPU_METER_STEAL] = cpuData->stealPeriod / total * 100.0; v[CPU_METER_GUEST] = cpuData->guestPeriod / total * 100.0; v[CPU_METER_IOWAIT] = cpuData->ioWaitPeriod / total * 100.0; - Meter_setItems(this, 8); + this->curItems = 8; if (this->pl->settings->accountGuestInCPUMeter) { - percent = v[0]+v[1]+v[2]+v[3]+v[4]+v[5]+v[6]; + percent = v[0] + v[1] + v[2] + v[3] + v[4] + v[5] + v[6]; } else { - percent = v[0]+v[1]+v[2]+v[3]+v[4]; + percent = v[0] + v[1] + v[2] + v[3] + v[4]; } } else { v[2] = cpuData->systemAllPeriod / total * 100.0; v[3] = (cpuData->stealPeriod + cpuData->guestPeriod) / total * 100.0; - Meter_setItems(this, 4); - percent = v[0]+v[1]+v[2]+v[3]; + this->curItems = 4; + percent = v[0] + v[1] + v[2] + v[3]; } percent = CLAMP(percent, 0.0, 100.0); - if (isnan(percent)) percent = 0.0; + if (isnan(percent)) { + percent = 0.0; + } + + v[CPU_METER_FREQUENCY] = cpuData->frequency; + return percent; } void Platform_setMemoryValues(Meter* this) { - ProcessList* pl = (ProcessList*) this->pl; + const ProcessList* pl = this->pl; + const LinuxProcessList* lpl = (const LinuxProcessList*) pl; + long int usedMem = pl->usedMem; long int buffersMem = pl->buffersMem; long int cachedMem = pl->cachedMem; @@ -205,35 +258,606 @@ void Platform_setMemoryValues(Meter* this) { this->values[0] = usedMem; this->values[1] = buffersMem; this->values[2] = cachedMem; + + if (lpl->zfs.enabled != 0) { + this->values[0] -= lpl->zfs.size; + this->values[2] += lpl->zfs.size; + } } void Platform_setSwapValues(Meter* this) { - ProcessList* pl = (ProcessList*) this->pl; + const ProcessList* pl = this->pl; this->total = pl->totalSwap; this->values[0] = pl->usedSwap; } +void Platform_setZramValues(Meter* this) { + const LinuxProcessList* lpl = (const LinuxProcessList*) this->pl; + this->total = lpl->zram.totalZram; + this->values[0] = lpl->zram.usedZramComp; + this->values[1] = lpl->zram.usedZramOrig; +} + +void Platform_setZfsArcValues(Meter* this) { + const LinuxProcessList* lpl = (const LinuxProcessList*) this->pl; + + ZfsArcMeter_readStats(this, &(lpl->zfs)); +} + +void Platform_setZfsCompressedArcValues(Meter* this) { + const LinuxProcessList* lpl = (const LinuxProcessList*) this->pl; + + ZfsCompressedArcMeter_readStats(this, &(lpl->zfs)); +} + char* Platform_getProcessEnv(pid_t pid) { - char procname[32+1]; - xSnprintf(procname, 32, "/proc/%d/environ", pid); + char procname[128]; + xSnprintf(procname, sizeof(procname), PROCDIR "/%d/environ", pid); FILE* fd = fopen(procname, "r"); - char *env = NULL; - if (fd) { - size_t capacity = 4096, size = 0, bytes; - env = xMalloc(capacity); - while (env && (bytes = fread(env+size, 1, capacity-size, fd)) > 0) { - size += bytes; - capacity *= 2; - env = xRealloc(env, capacity); + if (!fd) + return NULL; + + char* env = NULL; + + size_t capacity = 0; + size_t size = 0; + ssize_t bytes = 0; + + do { + size += bytes; + capacity += 4096; + env = xRealloc(env, capacity); + } while ((bytes = fread(env + size, 1, capacity - size, fd)) > 0); + + fclose(fd); + + if (bytes < 0) { + free(env); + return NULL; + } + + size += bytes; + + env = xRealloc(env, size + 2); + + env[size] = '\0'; + env[size + 1] = '\0'; + + return env; +} + +/* + * Return the absolute path of a file given its pid&inode number + * + * Based on implementation of lslocks from util-linux: + * https://sources.debian.org/src/util-linux/2.36-3/misc-utils/lslocks.c/#L162 + */ +char* Platform_getInodeFilename(pid_t pid, ino_t inode) { + struct stat sb; + struct dirent *de; + DIR *dirp; + size_t len; + int fd; + + char path[PATH_MAX]; + char sym[PATH_MAX]; + char* ret = NULL; + + memset(path, 0, sizeof(path)); + memset(sym, 0, sizeof(sym)); + + xSnprintf(path, sizeof(path), "%s/%d/fd/", PROCDIR, pid); + if (strlen(path) >= (sizeof(path) - 2)) + return NULL; + + if (!(dirp = opendir(path))) + return NULL; + + if ((fd = dirfd(dirp)) < 0 ) + goto out; + + while ((de = readdir(dirp))) { + if (String_eq(de->d_name, ".") || String_eq(de->d_name, "..")) + continue; + + /* care only for numerical descriptors */ + if (!strtoull(de->d_name, (char **) NULL, 10)) + continue; + + if (!Compat_fstatat(fd, path, de->d_name, &sb, 0) && inode != sb.st_ino) + continue; + + if ((len = Compat_readlinkat(fd, path, de->d_name, sym, sizeof(sym) - 1)) < 1) + goto out; + + sym[len] = '\0'; + + ret = xStrdup(sym); + break; + } + +out: + closedir(dirp); + return ret; +} + +FileLocks_ProcessData* Platform_getProcessLocks(pid_t pid) { + FileLocks_ProcessData* pdata = xCalloc(1, sizeof(FileLocks_ProcessData)); + + FILE* f = fopen(PROCDIR "/locks", "r"); + if (!f) { + pdata->error = true; + return pdata; + } + + char buffer[1024]; + FileLocks_LockData** data_ref = &pdata->locks; + while(fgets(buffer, sizeof(buffer), f)) { + if (!strchr(buffer, '\n')) + continue; + + int lock_id; + char lock_type[16]; + char lock_excl[16]; + char lock_rw[16]; + pid_t lock_pid; + unsigned int lock_dev[2]; + uint64_t lock_inode; + char lock_start[25]; + char lock_end[25]; + + if (10 != sscanf(buffer, "%d: %15s %15s %15s %d %x:%x:%"PRIu64" %24s %24s", + &lock_id, lock_type, lock_excl, lock_rw, &lock_pid, + &lock_dev[0], &lock_dev[1], &lock_inode, + lock_start, lock_end)) + continue; + + if (pid != lock_pid) + continue; + + FileLocks_LockData* ldata = xCalloc(1, sizeof(FileLocks_LockData)); + FileLocks_Data* data = &ldata->data; + data->id = lock_id; + data->locktype = xStrdup(lock_type); + data->exclusive = xStrdup(lock_excl); + data->readwrite = xStrdup(lock_rw); + data->filename = Platform_getInodeFilename(lock_pid, lock_inode); + data->dev[0] = lock_dev[0]; + data->dev[1] = lock_dev[1]; + data->inode = lock_inode; + data->start = strtoull(lock_start, NULL, 10); + if (!String_eq(lock_end, "EOF")) { + data->end = strtoull(lock_end, NULL, 10); + } else { + data->end = ULLONG_MAX; } - fclose(fd); - if (size < 2 || env[size-1] || env[size-2]) { - if (size + 2 < capacity) { - env = xRealloc(env, capacity+2); + + *data_ref = ldata; + data_ref = &ldata->next; + } + + fclose(f); + return pdata; +} + +void Platform_getPressureStall(const char* file, bool some, double* ten, double* sixty, double* threehundred) { + *ten = *sixty = *threehundred = 0; + char procname[128 + 1]; + xSnprintf(procname, 128, PROCDIR "/pressure/%s", file); + FILE* fd = fopen(procname, "r"); + if (!fd) { + *ten = *sixty = *threehundred = NAN; + return; + } + int total = fscanf(fd, "some avg10=%32lf avg60=%32lf avg300=%32lf total=%*f ", ten, sixty, threehundred); + if (!some) { + total = fscanf(fd, "full avg10=%32lf avg60=%32lf avg300=%32lf total=%*f ", ten, sixty, threehundred); + } + (void) total; + assert(total == 3); + fclose(fd); +} + +bool Platform_getDiskIO(DiskIOData* data) { + FILE* fd = fopen(PROCDIR "/diskstats", "r"); + if (!fd) + return false; + + unsigned long int read_sum = 0, write_sum = 0, timeSpend_sum = 0; + char lineBuffer[256]; + while (fgets(lineBuffer, sizeof(lineBuffer), fd)) { + char diskname[32]; + unsigned long int read_tmp, write_tmp, timeSpend_tmp; + if (sscanf(lineBuffer, "%*d %*d %31s %*u %*u %lu %*u %*u %*u %lu %*u %*u %lu", diskname, &read_tmp, &write_tmp, &timeSpend_tmp) == 4) { + if (String_startsWith(diskname, "dm-")) + continue; + + /* only count root disks, e.g. do not count IO from sda and sda1 twice */ + if ((diskname[0] == 's' || diskname[0] == 'h') + && diskname[1] == 'd' + && isalpha((unsigned char)diskname[2]) + && isdigit((unsigned char)diskname[3])) + continue; + + /* only count root disks, e.g. do not count IO from mmcblk0 and mmcblk0p1 twice */ + if (diskname[0] == 'm' + && diskname[1] == 'm' + && diskname[2] == 'c' + && diskname[3] == 'b' + && diskname[4] == 'l' + && diskname[5] == 'k' + && isdigit((unsigned char)diskname[6]) + && diskname[7] == 'p') + continue; + + read_sum += read_tmp; + write_sum += write_tmp; + timeSpend_sum += timeSpend_tmp; + } + } + fclose(fd); + /* multiply with sector size */ + data->totalBytesRead = 512 * read_sum; + data->totalBytesWritten = 512 * write_sum; + data->totalMsTimeSpend = timeSpend_sum; + return true; +} + +bool Platform_getNetworkIO(unsigned long int* bytesReceived, + unsigned long int* packetsReceived, + unsigned long int* bytesTransmitted, + unsigned long int* packetsTransmitted) { + FILE* fd = fopen(PROCDIR "/net/dev", "r"); + if (!fd) + return false; + + unsigned long int bytesReceivedSum = 0, packetsReceivedSum = 0, bytesTransmittedSum = 0, packetsTransmittedSum = 0; + char lineBuffer[512]; + while (fgets(lineBuffer, sizeof(lineBuffer), fd)) { + char interfaceName[32]; + unsigned long int bytesReceivedParsed, packetsReceivedParsed, bytesTransmittedParsed, packetsTransmittedParsed; + if (sscanf(lineBuffer, "%31s %lu %lu %*u %*u %*u %*u %*u %*u %lu %lu", + interfaceName, + &bytesReceivedParsed, + &packetsReceivedParsed, + &bytesTransmittedParsed, + &packetsTransmittedParsed) != 5) + continue; + + if (String_eq(interfaceName, "lo:")) + continue; + + bytesReceivedSum += bytesReceivedParsed; + packetsReceivedSum += packetsReceivedParsed; + bytesTransmittedSum += bytesTransmittedParsed; + packetsTransmittedSum += packetsTransmittedParsed; + } + + fclose(fd); + + *bytesReceived = bytesReceivedSum; + *packetsReceived = packetsReceivedSum; + *bytesTransmitted = bytesTransmittedSum; + *packetsTransmitted = packetsTransmittedSum; + return true; +} + +// Linux battery reading by Ian P. Hands (iphands@gmail.com, ihands@redhat.com). + +#define MAX_BATTERIES 64 +#define PROC_BATTERY_DIR PROCDIR "/acpi/battery" +#define PROC_POWERSUPPLY_DIR PROCDIR "/acpi/ac_adapter" +#define SYS_POWERSUPPLY_DIR "/sys/class/power_supply" + +// ---------------------------------------- +// READ FROM /proc +// ---------------------------------------- + +static unsigned long int parseBatInfo(const char* fileName, const unsigned short int lineNum, const unsigned short int wordNum) { + const char batteryPath[] = PROC_BATTERY_DIR; + DIR* batteryDir = opendir(batteryPath); + if (!batteryDir) + return 0; + + char* batteries[MAX_BATTERIES]; + unsigned int nBatteries = 0; + memset(batteries, 0, MAX_BATTERIES * sizeof(char*)); + + while (nBatteries < MAX_BATTERIES) { + struct dirent* dirEntry = readdir(batteryDir); + if (!dirEntry) + break; + + char* entryName = dirEntry->d_name; + if (!String_startsWith(entryName, "BAT")) + continue; + + batteries[nBatteries] = xStrdup(entryName); + nBatteries++; + } + closedir(batteryDir); + + unsigned long int total = 0; + for (unsigned int i = 0; i < nBatteries; i++) { + char infoPath[30]; + xSnprintf(infoPath, sizeof infoPath, "%s%s/%s", batteryPath, batteries[i], fileName); + + FILE* file = fopen(infoPath, "r"); + if (!file) + break; + + char* line = NULL; + for (unsigned short int j = 0; j < lineNum; j++) { + free(line); + line = String_readLine(file); + if (!line) + break; + } + + fclose(file); + + if (!line) + break; + + char* foundNumStr = String_getToken(line, wordNum); + const unsigned long int foundNum = atoi(foundNumStr); + free(foundNumStr); + free(line); + + total += foundNum; + } + + for (unsigned int i = 0; i < nBatteries; i++) + free(batteries[i]); + + return total; +} + +static ACPresence procAcpiCheck(void) { + ACPresence isOn = AC_ERROR; + const char* power_supplyPath = PROC_POWERSUPPLY_DIR; + DIR* dir = opendir(power_supplyPath); + if (!dir) + return AC_ERROR; + + for (;;) { + struct dirent* dirEntry = readdir(dir); + if (!dirEntry) + break; + + const char* entryName = dirEntry->d_name; + + if (entryName[0] != 'A') + continue; + + char statePath[256]; + xSnprintf(statePath, sizeof(statePath), "%s/%s/state", power_supplyPath, entryName); + FILE* file = fopen(statePath, "r"); + if (!file) { + isOn = AC_ERROR; + continue; + } + char* line = String_readLine(file); + + fclose(file); + + if (!line) + continue; + + char* isOnline = String_getToken(line, 2); + free(line); + + if (String_eq(isOnline, "on-line")) + isOn = AC_PRESENT; + else + isOn = AC_ABSENT; + free(isOnline); + if (isOn == AC_PRESENT) + break; + } + + if (dir) + closedir(dir); + + return isOn; +} + +static double Platform_Battery_getProcBatInfo(void) { + const unsigned long int totalFull = parseBatInfo("info", 3, 4); + if (totalFull == 0) + return NAN; + + const unsigned long int totalRemain = parseBatInfo("state", 5, 3); + if (totalRemain == 0) + return NAN; + + return totalRemain * 100.0 / (double) totalFull; +} + +static void Platform_Battery_getProcData(double* level, ACPresence* isOnAC) { + *isOnAC = procAcpiCheck(); + *level = AC_ERROR != *isOnAC ? Platform_Battery_getProcBatInfo() : NAN; +} + +// ---------------------------------------- +// READ FROM /sys +// ---------------------------------------- + +static inline ssize_t xread(int fd, void* buf, size_t count) { + // Read some bytes. Retry on EINTR and when we don't get as many bytes as we requested. + size_t alreadyRead = 0; + for (;;) { + ssize_t res = read(fd, buf, count); + if (res == -1) { + if (errno == EINTR) + continue; + return -1; + } + + if (res > 0) { + buf = ((char*)buf) + res; + count -= res; + alreadyRead += res; + } + + if (count == 0 || res == 0) + return alreadyRead; + } +} + +static void Platform_Battery_getSysData(double* level, ACPresence* isOnAC) { + + *level = NAN; + *isOnAC = AC_ERROR; + + DIR* dir = opendir(SYS_POWERSUPPLY_DIR); + if (!dir) + return; + + unsigned long int totalFull = 0; + unsigned long int totalRemain = 0; + + for (;;) { + struct dirent* dirEntry = readdir(dir); + if (!dirEntry) + break; + + const char* entryName = dirEntry->d_name; + char filePath[256]; + + xSnprintf(filePath, sizeof filePath, SYS_POWERSUPPLY_DIR "/%s/type", entryName); + int fd1 = open(filePath, O_RDONLY); + if (fd1 == -1) + continue; + + char type[8]; + ssize_t typelen = xread(fd1, type, 7); + close(fd1); + if (typelen < 1) + continue; + + if (type[0] == 'B' && type[1] == 'a' && type[2] == 't') { + xSnprintf(filePath, sizeof filePath, SYS_POWERSUPPLY_DIR "/%s/uevent", entryName); + int fd2 = open(filePath, O_RDONLY); + if (fd2 == -1) { + closedir(dir); + return; + } + char buffer[1024]; + ssize_t buflen = xread(fd2, buffer, 1023); + close(fd2); + if (buflen < 1) { + closedir(dir); + return; + } + buffer[buflen] = '\0'; + char* buf = buffer; + char* line = NULL; + bool full = false; + bool now = false; + int fullSize = 0; + double capacityLevel = NAN; + + #define match(str,prefix) \ + (String_startsWith(str,prefix) ? (str) + strlen(prefix) : NULL) + + while ((line = strsep(&buf, "\n")) != NULL) { + const char* ps = match(line, "POWER_SUPPLY_"); + if (!ps) + continue; + const char* capacity = match(ps, "CAPACITY="); + if (capacity) + capacityLevel = atoi(capacity) / 100.0; + const char* energy = match(ps, "ENERGY_"); + if (!energy) + energy = match(ps, "CHARGE_"); + if (!energy) + continue; + const char* value = (!full) ? match(energy, "FULL=") : NULL; + if (value) { + fullSize = atoi(value); + totalFull += fullSize; + full = true; + if (now) + break; + continue; + } + value = (!now) ? match(energy, "NOW=") : NULL; + if (value) { + totalRemain += atoi(value); + now = true; + if (full) + break; + continue; + } + } + + #undef match + + if (!now && full && !isnan(capacityLevel)) + totalRemain += (capacityLevel * fullSize); + + } else if (entryName[0] == 'A') { + if (*isOnAC != AC_ERROR) + continue; + + xSnprintf(filePath, sizeof filePath, SYS_POWERSUPPLY_DIR "/%s/online", entryName); + int fd3 = open(filePath, O_RDONLY); + if (fd3 == -1) { + closedir(dir); + return; + } + char buffer[2] = ""; + for (;;) { + ssize_t res = read(fd3, buffer, 1); + if (res == -1 && errno == EINTR) + continue; + break; } - env[size] = 0; - env[size+1] = 0; + close(fd3); + if (buffer[0] == '0') + *isOnAC = AC_ABSENT; + else if (buffer[0] == '1') + *isOnAC = AC_PRESENT; } } - return env; + closedir(dir); + + *level = totalFull > 0 ? ((double) totalRemain * 100.0) / (double) totalFull : NAN; +} + +static enum { BAT_PROC, BAT_SYS, BAT_ERR } Platform_Battery_method = BAT_PROC; + +static time_t Platform_Battery_cacheTime; +static double Platform_Battery_cacheLevel = NAN; +static ACPresence Platform_Battery_cacheIsOnAC; + +void Platform_getBattery(double* level, ACPresence* isOnAC) { + time_t now = time(NULL); + // update battery reading is slow. Update it each 10 seconds only. + if (now < Platform_Battery_cacheTime + 10) { + *level = Platform_Battery_cacheLevel; + *isOnAC = Platform_Battery_cacheIsOnAC; + return; + } + + if (Platform_Battery_method == BAT_PROC) { + Platform_Battery_getProcData(level, isOnAC); + if (isnan(*level)) + Platform_Battery_method = BAT_SYS; + } + if (Platform_Battery_method == BAT_SYS) { + Platform_Battery_getSysData(level, isOnAC); + if (isnan(*level)) + Platform_Battery_method = BAT_ERR; + } + if (Platform_Battery_method == BAT_ERR) { + *level = NAN; + *isOnAC = AC_ERROR; + } else { + *level = CLAMP(*level, 0.0, 100.0); + } + Platform_Battery_cacheLevel = *level; + Platform_Battery_cacheIsOnAC = *isOnAC; + Platform_Battery_cacheTime = now; } diff --git a/linux/Platform.h b/linux/Platform.h index b0456e5b5..dbd6bb462 100644 --- a/linux/Platform.h +++ b/linux/Platform.h @@ -1,24 +1,23 @@ -/* Do not edit this file. It was automatically generated. */ - #ifndef HEADER_Platform #define HEADER_Platform /* htop - linux/Platform.h (C) 2014 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ +#include +#include + #include "Action.h" -#include "MainPanel.h" #include "BatteryMeter.h" -#include "LinuxProcess.h" +#include "DiskIOMeter.h" +#include "Meter.h" +#include "Process.h" +#include "ProcessLocksScreen.h" #include "SignalsPanel.h" -#ifndef CLAMP -#define CLAMP(x,low,high) (((x)>(high))?(high):(((x)<(low))?(low):(x))) -#endif - extern ProcessField Platform_defaultFields[]; extern int Platform_numberOfFields; @@ -29,13 +28,13 @@ extern const unsigned int Platform_numberOfSignals; void Platform_setBindings(Htop_Action* keys); -extern MeterClass* Platform_meterTypes[]; +extern const MeterClass* const Platform_meterTypes[]; -int Platform_getUptime(); +int Platform_getUptime(void); void Platform_getLoadAverage(double* one, double* five, double* fifteen); -int Platform_getMaxPid(); +int Platform_getMaxPid(void); double Platform_setCPUValues(Meter* this, int cpu); @@ -43,6 +42,27 @@ void Platform_setMemoryValues(Meter* this); void Platform_setSwapValues(Meter* this); +void Platform_setZramValues(Meter* this); + +void Platform_setZfsArcValues(Meter* this); + +void Platform_setZfsCompressedArcValues(Meter* this); + char* Platform_getProcessEnv(pid_t pid); +char* Platform_getInodeFilename(pid_t pid, ino_t inode); + +FileLocks_ProcessData* Platform_getProcessLocks(pid_t pid); + +void Platform_getPressureStall(const char *file, bool some, double* ten, double* sixty, double* threehundred); + +bool Platform_getDiskIO(DiskIOData* data); + +bool Platform_getNetworkIO(unsigned long int* bytesReceived, + unsigned long int* packetsReceived, + unsigned long int* bytesTransmitted, + unsigned long int* packetsTransmitted); + +void Platform_getBattery(double *percent, ACPresence *isOnAC); + #endif diff --git a/linux/PressureStallMeter.c b/linux/PressureStallMeter.c new file mode 100644 index 000000000..3b5415c5f --- /dev/null +++ b/linux/PressureStallMeter.c @@ -0,0 +1,136 @@ +/* +htop - PressureStallMeter.c +(C) 2004-2011 Hisham H. Muhammad +(C) 2019 Ran Benita +Released under the GNU GPLv2, see the COPYING file +in the source distribution for its full text. +*/ + +#include "PressureStallMeter.h" + +#include +#include + +#include "CRT.h" +#include "Meter.h" +#include "Object.h" +#include "Platform.h" +#include "RichString.h" +#include "XUtils.h" + + +static const int PressureStallMeter_attributes[] = { + PRESSURE_STALL_TEN, PRESSURE_STALL_SIXTY, PRESSURE_STALL_THREEHUNDRED +}; + +static void PressureStallMeter_updateValues(Meter* this, char* buffer, int len) { + const char* file; + if (strstr(Meter_name(this), "CPU")) { + file = "cpu"; + } else if (strstr(Meter_name(this), "IO")) { + file = "io"; + } else { + file = "memory"; + } + + bool some; + if (strstr(Meter_name(this), "Some")) { + some = true; + } else { + some = false; + } + + Platform_getPressureStall(file, some, &this->values[0], &this->values[1], &this->values[2]); + xSnprintf(buffer, len, "xxxx %.2lf%% %.2lf%% %.2lf%%", this->values[0], this->values[1], this->values[2]); +} + +static void PressureStallMeter_display(const Object* cast, RichString* out) { + const Meter* this = (const Meter*)cast; + char buffer[20]; + xSnprintf(buffer, sizeof(buffer), "%.2lf%% ", this->values[0]); + RichString_write(out, CRT_colors[PRESSURE_STALL_TEN], buffer); + xSnprintf(buffer, sizeof(buffer), "%.2lf%% ", this->values[1]); + RichString_append(out, CRT_colors[PRESSURE_STALL_SIXTY], buffer); + xSnprintf(buffer, sizeof(buffer), "%.2lf%% ", this->values[2]); + RichString_append(out, CRT_colors[PRESSURE_STALL_THREEHUNDRED], buffer); +} + +const MeterClass PressureStallCPUSomeMeter_class = { + .super = { + .extends = Class(Meter), + .delete = Meter_delete, + .display = PressureStallMeter_display, + }, + .updateValues = PressureStallMeter_updateValues, + .defaultMode = TEXT_METERMODE, + .maxItems = 3, + .total = 100.0, + .attributes = PressureStallMeter_attributes, + .name = "PressureStallCPUSome", + .uiName = "Pressure Stall Information, some CPU", + .caption = "Some CPU pressure: " +}; + +const MeterClass PressureStallIOSomeMeter_class = { + .super = { + .extends = Class(Meter), + .delete = Meter_delete, + .display = PressureStallMeter_display, + }, + .updateValues = PressureStallMeter_updateValues, + .defaultMode = TEXT_METERMODE, + .maxItems = 3, + .total = 100.0, + .attributes = PressureStallMeter_attributes, + .name = "PressureStallIOSome", + .uiName = "Pressure Stall Information, some IO", + .caption = "Some IO pressure: " +}; + +const MeterClass PressureStallIOFullMeter_class = { + .super = { + .extends = Class(Meter), + .delete = Meter_delete, + .display = PressureStallMeter_display, + }, + .updateValues = PressureStallMeter_updateValues, + .defaultMode = TEXT_METERMODE, + .maxItems = 3, + .total = 100.0, + .attributes = PressureStallMeter_attributes, + .name = "PressureStallIOFull", + .uiName = "Pressure Stall Information, full IO", + .caption = "Full IO pressure: " +}; + +const MeterClass PressureStallMemorySomeMeter_class = { + .super = { + .extends = Class(Meter), + .delete = Meter_delete, + .display = PressureStallMeter_display, + }, + .updateValues = PressureStallMeter_updateValues, + .defaultMode = TEXT_METERMODE, + .maxItems = 3, + .total = 100.0, + .attributes = PressureStallMeter_attributes, + .name = "PressureStallMemorySome", + .uiName = "Pressure Stall Information, some memory", + .caption = "Some Mem pressure: " +}; + +const MeterClass PressureStallMemoryFullMeter_class = { + .super = { + .extends = Class(Meter), + .delete = Meter_delete, + .display = PressureStallMeter_display, + }, + .updateValues = PressureStallMeter_updateValues, + .defaultMode = TEXT_METERMODE, + .maxItems = 3, + .total = 100.0, + .attributes = PressureStallMeter_attributes, + .name = "PressureStallMemoryFull", + .uiName = "Pressure Stall Information, full memory", + .caption = "Full Mem pressure: " +}; diff --git a/linux/PressureStallMeter.h b/linux/PressureStallMeter.h new file mode 100644 index 000000000..1a0ad5847 --- /dev/null +++ b/linux/PressureStallMeter.h @@ -0,0 +1,25 @@ +/* Do not edit this file. It was automatically generated. */ + +#ifndef HEADER_PressureStallMeter +#define HEADER_PressureStallMeter +/* +htop - PressureStallMeter.h +(C) 2004-2011 Hisham H. Muhammad +(C) 2019 Ran Benita +Released under the GNU GPLv2, see the COPYING file +in the source distribution for its full text. +*/ + +#include "Meter.h" + +extern const MeterClass PressureStallCPUSomeMeter_class; + +extern const MeterClass PressureStallIOSomeMeter_class; + +extern const MeterClass PressureStallIOFullMeter_class; + +extern const MeterClass PressureStallMemorySomeMeter_class; + +extern const MeterClass PressureStallMemoryFullMeter_class; + +#endif diff --git a/linux/SELinuxMeter.c b/linux/SELinuxMeter.c new file mode 100644 index 000000000..ee1d84701 --- /dev/null +++ b/linux/SELinuxMeter.c @@ -0,0 +1,102 @@ +/* +htop - SELinuxMeter.c +(C) 2020 Christian Goettsche +Released under the GNU GPLv2, see the COPYING file +in the source distribution for its full text. +*/ + +#include "SELinuxMeter.h" + +#include "CRT.h" + +#include +#include +#include +#include +#include +#include +#include + +#include "Macros.h" +#include "Object.h" +#include "XUtils.h" + + +static const int SELinuxMeter_attributes[] = { + METER_TEXT, +}; + +static bool enabled = false; +static bool enforcing = false; + +static bool hasSELinuxMount(void) { + struct statfs sfbuf; + int r = statfs("/sys/fs/selinux", &sfbuf); + if (r != 0) { + return false; + } + + if (sfbuf.f_type != SELINUX_MAGIC) { + return false; + } + + struct statvfs vfsbuf; + r = statvfs("/sys/fs/selinux", &vfsbuf); + if (r != 0 || (vfsbuf.f_flag & ST_RDONLY)) { + return false; + } + + return true; +} + +static bool isSelinuxEnabled(void) { + return hasSELinuxMount() && (0 == access("/etc/selinux/config", F_OK)); +} + +static bool isSelinuxEnforcing(void) { + if (!enabled) { + return false; + } + + int fd = open("/sys/fs/selinux/enforce", O_RDONLY); + if (fd < 0) { + return false; + } + + char buf[20] = {0}; + int r = read(fd, buf, sizeof(buf) - 1); + close(fd); + if (r < 0) { + return false; + } + + int enforce = 0; + if (sscanf(buf, "%d", &enforce) != 1) { + return false; + } + + return !!enforce; +} + +static void SELinuxMeter_updateValues(ATTR_UNUSED Meter* this, char* buffer, int len) { + enabled = isSelinuxEnabled(); + enforcing = isSelinuxEnforcing(); + + xSnprintf(buffer, len, "%s%s", enabled ? "enabled" : "disabled", enabled ? (enforcing ? "; mode: enforcing" : "; mode: permissive") : ""); +} + +const MeterClass SELinuxMeter_class = { + .super = { + .extends = Class(Meter), + .delete = Meter_delete, + }, + .updateValues = SELinuxMeter_updateValues, + .defaultMode = TEXT_METERMODE, + .maxItems = 0, + .total = 100.0, + .attributes = SELinuxMeter_attributes, + .name = "SELinux", + .uiName = "SELinux", + .description = "SELinux state overview", + .caption = "SELinux: " +}; diff --git a/linux/SELinuxMeter.h b/linux/SELinuxMeter.h new file mode 100644 index 000000000..02362bf1e --- /dev/null +++ b/linux/SELinuxMeter.h @@ -0,0 +1,14 @@ +#ifndef HEADER_SELinuxMeter +#define HEADER_SELinuxMeter +/* +htop - SELinuxMeter.h +(C) 2020 Christian Goettsche +Released under the GNU GPLv2, see the COPYING file +in the source distribution for its full text. +*/ + +#include "Meter.h" + +extern const MeterClass SELinuxMeter_class; + +#endif /* HEADER_SELinuxMeter */ diff --git a/linux/SystemdMeter.c b/linux/SystemdMeter.c new file mode 100644 index 000000000..368d5ccaf --- /dev/null +++ b/linux/SystemdMeter.c @@ -0,0 +1,329 @@ +/* +htop - SystemdMeter.c +(C) 2020 Christian Göttsche +Released under the GNU GPLv2, see the COPYING file +in the source distribution for its full text. +*/ + +#include "SystemdMeter.h" + +#include +#include +#include +#include +#include +#include + +#include "CRT.h" +#include "XUtils.h" + + +#define INVALID_VALUE ((unsigned int)-1) + +typedef void sd_bus; +typedef void sd_bus_error; +static int (*sym_sd_bus_open_system)(sd_bus**); +static int (*sym_sd_bus_get_property_string)(sd_bus*, const char*, const char*, const char*, const char*, sd_bus_error*, char**); +static int (*sym_sd_bus_get_property_trivial)(sd_bus*, const char*, const char*, const char*, const char*, sd_bus_error*, char, void*); +static sd_bus* (*sym_sd_bus_unref)(sd_bus*); + +static char* systemState = NULL; +static unsigned int nFailedUnits = INVALID_VALUE; +static unsigned int nInstalledJobs = INVALID_VALUE; +static unsigned int nNames = INVALID_VALUE; +static unsigned int nJobs = INVALID_VALUE; +static void* dlopenHandle = NULL; +static sd_bus* bus = NULL; + +static void SystemdMeter_done(ATTR_UNUSED Meter* this) { + free(systemState); + systemState = NULL; + + if (bus && dlopenHandle) { + sym_sd_bus_unref(bus); + } + bus = NULL; + + if (dlopenHandle) { + dlclose(dlopenHandle); + dlopenHandle = NULL; + } +} + +static int updateViaLib(void) { + if (!dlopenHandle) { + dlopenHandle = dlopen("libsystemd.so.0", RTLD_LAZY); + if (!dlopenHandle) + goto dlfailure; + + /* Clear any errors */ + dlerror(); + + #define resolve(symbolname) do { \ + *(void **)(&sym_##symbolname) = dlsym(dlopenHandle, #symbolname); \ + if (!sym_##symbolname || dlerror() != NULL) \ + goto dlfailure; \ + } while(0) + + resolve(sd_bus_open_system); + resolve(sd_bus_get_property_string); + resolve(sd_bus_get_property_trivial); + resolve(sd_bus_unref); + + #undef resolve + } + + int r; + + /* Connect to the system bus */ + if (!bus) { + r = sym_sd_bus_open_system(&bus); + if (r < 0) + goto busfailure; + } + + static const char* const busServiceName = "org.freedesktop.systemd1"; + static const char* const busObjectPath = "/org/freedesktop/systemd1"; + static const char* const busInterfaceName = "org.freedesktop.systemd1.Manager"; + + r = sym_sd_bus_get_property_string(bus, + busServiceName, /* service to contact */ + busObjectPath, /* object path */ + busInterfaceName, /* interface name */ + "SystemState", /* property name */ + NULL, /* object to return error in */ + &systemState); + if (r < 0) + goto busfailure; + + r = sym_sd_bus_get_property_trivial(bus, + busServiceName, /* service to contact */ + busObjectPath, /* object path */ + busInterfaceName, /* interface name */ + "NFailedUnits", /* property name */ + NULL, /* object to return error in */ + 'u', /* property type */ + &nFailedUnits); + if (r < 0) + goto busfailure; + + r = sym_sd_bus_get_property_trivial(bus, + busServiceName, /* service to contact */ + busObjectPath, /* object path */ + busInterfaceName, /* interface name */ + "NInstalledJobs", /* property name */ + NULL, /* object to return error in */ + 'u', /* property type */ + &nInstalledJobs); + if (r < 0) + goto busfailure; + + r = sym_sd_bus_get_property_trivial(bus, + busServiceName, /* service to contact */ + busObjectPath, /* object path */ + busInterfaceName, /* interface name */ + "NNames", /* property name */ + NULL, /* object to return error in */ + 'u', /* property type */ + &nNames); + if (r < 0) + goto busfailure; + + r = sym_sd_bus_get_property_trivial(bus, + busServiceName, /* service to contact */ + busObjectPath, /* object path */ + busInterfaceName, /* interface name */ + "NJobs", /* property name */ + NULL, /* object to return error in */ + 'u', /* property type */ + &nJobs); + if (r < 0) + goto busfailure; + + /* success */ + return 0; + +busfailure: + sym_sd_bus_unref(bus); + bus = NULL; + return -2; + +dlfailure: + if (dlopenHandle) { + dlclose(dlopenHandle); + dlopenHandle = NULL; + } + return -1; +} + +static void updateViaExec(void) { + int fdpair[2]; + if (pipe(fdpair) < 0) + return; + + pid_t child = fork(); + if (child < 0) { + close(fdpair[1]); + close(fdpair[0]); + return; + } + + if (child == 0) { + close(fdpair[0]); + dup2(fdpair[1], STDOUT_FILENO); + close(fdpair[1]); + int fdnull = open("/dev/null", O_WRONLY); + if (fdnull < 0) + exit(1); + dup2(fdnull, STDERR_FILENO); + close(fdnull); + execl("/bin/systemctl", + "/bin/systemctl", + "show", + "--property=SystemState", + "--property=NFailedUnits", + "--property=NNames", + "--property=NJobs", + "--property=NInstalledJobs", + NULL); + exit(127); + } + close(fdpair[1]); + + int wstatus; + if (waitpid(child, &wstatus, 0) < 0 || !WIFEXITED(wstatus) || WEXITSTATUS(wstatus) != 0) { + close(fdpair[0]); + return; + } + + FILE* commandOutput = fdopen(fdpair[0], "r"); + if (!commandOutput) { + close(fdpair[0]); + return; + } + + char lineBuffer[128]; + while (fgets(lineBuffer, sizeof(lineBuffer), commandOutput)) { + if (String_startsWith(lineBuffer, "SystemState=")) { + char* newline = strchr(lineBuffer + strlen("SystemState="), '\n'); + if (newline) + *newline = '\0'; + systemState = xStrdup(lineBuffer + strlen("SystemState=")); + } else if (String_startsWith(lineBuffer, "NFailedUnits=")) { + nFailedUnits = strtoul(lineBuffer + strlen("NFailedUnits="), NULL, 10); + } else if (String_startsWith(lineBuffer, "NNames=")) { + nNames = strtoul(lineBuffer + strlen("NNames="), NULL, 10); + } else if (String_startsWith(lineBuffer, "NJobs=")) { + nJobs = strtoul(lineBuffer + strlen("NJobs="), NULL, 10); + } else if (String_startsWith(lineBuffer, "NInstalledJobs=")) { + nInstalledJobs = strtoul(lineBuffer + strlen("NInstalledJobs="), NULL, 10); + } + } + + fclose(commandOutput); +} + +static void SystemdMeter_updateValues(ATTR_UNUSED Meter* this, char* buffer, int size) { + free(systemState); + systemState = NULL; + nFailedUnits = nInstalledJobs = nNames = nJobs = INVALID_VALUE; + + if (updateViaLib() < 0) + updateViaExec(); + + xSnprintf(buffer, size, "%s", systemState ? systemState : "???"); +} + +static int zeroDigitColor(unsigned int value) { + switch (value) { + case 0: + return CRT_colors[METER_VALUE]; + case INVALID_VALUE: + return CRT_colors[METER_VALUE_ERROR]; + default: + return CRT_colors[METER_VALUE_NOTICE]; + } +} + +static int valueDigitColor(unsigned int value) { + switch (value) { + case 0: + return CRT_colors[METER_VALUE_NOTICE]; + case INVALID_VALUE: + return CRT_colors[METER_VALUE_ERROR]; + default: + return CRT_colors[METER_VALUE]; + } +} + + +static void SystemdMeter_display(ATTR_UNUSED const Object* cast, RichString* out) { + char buffer[16]; + + int color = (systemState && 0 == strcmp(systemState, "running")) ? METER_VALUE_OK : METER_VALUE_ERROR; + RichString_write(out, CRT_colors[color], systemState ? systemState : "???"); + + RichString_append(out, CRT_colors[METER_TEXT], " ("); + + if (nFailedUnits == INVALID_VALUE) { + buffer[0] = '?'; + buffer[1] = '\0'; + } else { + xSnprintf(buffer, sizeof(buffer), "%u", nFailedUnits); + } + RichString_append(out, zeroDigitColor(nFailedUnits), buffer); + + RichString_append(out, CRT_colors[METER_TEXT], "/"); + + if (nNames == INVALID_VALUE) { + buffer[0] = '?'; + buffer[1] = '\0'; + } else { + xSnprintf(buffer, sizeof(buffer), "%u", nNames); + } + RichString_append(out, valueDigitColor(nNames), buffer); + + RichString_append(out, CRT_colors[METER_TEXT], " failed) ("); + + if (nJobs == INVALID_VALUE) { + buffer[0] = '?'; + buffer[1] = '\0'; + } else { + xSnprintf(buffer, sizeof(buffer), "%u", nJobs); + } + RichString_append(out, zeroDigitColor(nJobs), buffer); + + RichString_append(out, CRT_colors[METER_TEXT], "/"); + + if (nInstalledJobs == INVALID_VALUE) { + buffer[0] = '?'; + buffer[1] = '\0'; + } else { + xSnprintf(buffer, sizeof(buffer), "%u", nInstalledJobs); + } + RichString_append(out, valueDigitColor(nInstalledJobs), buffer); + + RichString_append(out, CRT_colors[METER_TEXT], " jobs)"); +} + +static const int SystemdMeter_attributes[] = { + METER_VALUE +}; + +const MeterClass SystemdMeter_class = { + .super = { + .extends = Class(Meter), + .delete = Meter_delete, + .display = SystemdMeter_display + }, + .updateValues = SystemdMeter_updateValues, + .done = SystemdMeter_done, + .defaultMode = TEXT_METERMODE, + .maxItems = 0, + .total = 100.0, + .attributes = SystemdMeter_attributes, + .name = "Systemd", + .uiName = "Systemd state", + .description = "Systemd system state and unit overview", + .caption = "Systemd: ", +}; diff --git a/linux/SystemdMeter.h b/linux/SystemdMeter.h new file mode 100644 index 000000000..6ab4834de --- /dev/null +++ b/linux/SystemdMeter.h @@ -0,0 +1,15 @@ +#ifndef HEADER_SystemdMeter +#define HEADER_SystemdMeter + +/* +htop - SystemdMeter.h +(C) 2020 Christian Göttsche +Released under the GNU GPLv2, see the COPYING file +in the source distribution for its full text. +*/ + +#include "Meter.h" + +extern const MeterClass SystemdMeter_class; + +#endif /* HEADER_SystemdMeter */ diff --git a/linux/ZramMeter.c b/linux/ZramMeter.c new file mode 100644 index 000000000..30d78eaac --- /dev/null +++ b/linux/ZramMeter.c @@ -0,0 +1,75 @@ +#include "ZramMeter.h" + +#include "CRT.h" +#include "Meter.h" +#include "Platform.h" + +static const int ZramMeter_attributes[] = { + ZRAM +}; + +static void ZramMeter_updateValues(Meter* this, char* buffer, int size) { + int written; + + Platform_setZramValues(this); + + /* on print bar for compressed data size, not uncompressed */ + this->curItems = 1; + + written = Meter_humanUnit(buffer, this->values[0], size); + buffer += written; + size -= written; + if (size <= 0) { + return; + } + *buffer++ = '('; + size--; + if (size <= 0) { + return; + } + written = Meter_humanUnit(buffer, this->values[1], size); + buffer += written; + size -= written; + if (size <= 0) { + return; + } + *buffer++ = ')'; + size--; + if ((size -= written) > 0) { + *buffer++ = '/'; + size--; + Meter_humanUnit(buffer, this->total, size); + } +} + +static void ZramMeter_display(const Object* cast, RichString* out) { + char buffer[50]; + const Meter* this = (const Meter*)cast; + RichString_write(out, CRT_colors[METER_TEXT], ":"); + Meter_humanUnit(buffer, this->total, sizeof(buffer)); + + RichString_append(out, CRT_colors[METER_VALUE], buffer); + Meter_humanUnit(buffer, this->values[0], sizeof(buffer)); + RichString_append(out, CRT_colors[METER_TEXT], " used:"); + RichString_append(out, CRT_colors[METER_VALUE], buffer); + + Meter_humanUnit(buffer, this->values[1], sizeof(buffer)); + RichString_append(out, CRT_colors[METER_TEXT], " uncompressed:"); + RichString_append(out, CRT_colors[METER_VALUE], buffer); +} + +const MeterClass ZramMeter_class = { + .super = { + .extends = Class(Meter), + .delete = Meter_delete, + .display = ZramMeter_display, + }, + .updateValues = ZramMeter_updateValues, + .defaultMode = BAR_METERMODE, + .maxItems = 2, + .total = 100.0, + .attributes = ZramMeter_attributes, + .name = "Zram", + .uiName = "Zram", + .caption = "zrm" +}; diff --git a/linux/ZramMeter.h b/linux/ZramMeter.h new file mode 100644 index 000000000..7cf7861ec --- /dev/null +++ b/linux/ZramMeter.h @@ -0,0 +1,8 @@ +#ifndef HEADER_ZramMeter +#define HEADER_ZramMeter + +#include "Meter.h" + +extern const MeterClass ZramMeter_class; + +#endif diff --git a/linux/ZramStats.h b/linux/ZramStats.h new file mode 100644 index 000000000..2305cfd2b --- /dev/null +++ b/linux/ZramStats.h @@ -0,0 +1,10 @@ +#ifndef HEADER_ZramStats +#define HEADER_ZramStats + +typedef struct ZramStats_ { + unsigned long long int totalZram; + unsigned long long int usedZramComp; + unsigned long long int usedZramOrig; +} ZramStats; + +#endif diff --git a/openbsd/Battery.c b/openbsd/Battery.c deleted file mode 100644 index 3a0bae143..000000000 --- a/openbsd/Battery.c +++ /dev/null @@ -1,71 +0,0 @@ -/* -htop - openbsd/Battery.c -(C) 2015 Hisham H. Muhammad -(C) 2015 Michael McConville -Released under the GNU GPL, see the COPYING file -in the source distribution for its full text. -*/ - -#include "BatteryMeter.h" -#include -#include -#include - -static bool findDevice(const char* name, int* mib, struct sensordev* snsrdev, size_t* sdlen) { - for (int devn = 0;; devn++) { - mib[2] = devn; - if (sysctl(mib, 3, snsrdev, sdlen, NULL, 0) == -1) { - if (errno == ENXIO) - continue; - if (errno == ENOENT) - return false; - } - if (strcmp(name, snsrdev->xname) == 0) { - return true; - } - } -} - -void Battery_getData(double* level, ACPresence* isOnAC) { - static int mib[] = {CTL_HW, HW_SENSORS, 0, 0, 0}; - struct sensor s; - size_t slen = sizeof(struct sensor); - struct sensordev snsrdev; - size_t sdlen = sizeof(struct sensordev); - - bool found = findDevice("acpibat0", mib, &snsrdev, &sdlen); - - *level = -1; - if (found) { - /* last full capacity */ - mib[3] = 7; - mib[4] = 0; - double last_full_capacity = 0; - if (sysctl(mib, 5, &s, &slen, NULL, 0) != -1) { - last_full_capacity = s.value; - } - if (last_full_capacity > 0) { - /* remaining capacity */ - mib[3] = 7; - mib[4] = 3; - if (sysctl(mib, 5, &s, &slen, NULL, 0) != -1) { - double charge = s.value; - *level = 100*(charge / last_full_capacity); - if (charge >= last_full_capacity) { - *level = 100; - } - } - } - } - - found = findDevice("acpiac0", mib, &snsrdev, &sdlen); - - *isOnAC = AC_ERROR; - if (found) { - mib[3] = 9; - mib[4] = 0; - if (sysctl(mib, 5, &s, &slen, NULL, 0) != -1) { - *isOnAC = s.value; - } - } -} diff --git a/openbsd/Battery.h b/openbsd/Battery.h deleted file mode 100644 index b1a4982ec..000000000 --- a/openbsd/Battery.h +++ /dev/null @@ -1,16 +0,0 @@ -/* Do not edit this file. It was automatically generated. */ - -#ifndef HEADER_Battery -#define HEADER_Battery -/* -htop - openbsd/Battery.h -(C) 2015 Hisham H. Muhammad -(C) 2015 Michael McConville -Released under the GNU GPL, see the COPYING file -in the source distribution for its full text. -*/ - -void Battery_getData(double* level, ACPresence* isOnAC); - - -#endif diff --git a/openbsd/OpenBSDCRT.c b/openbsd/OpenBSDCRT.c deleted file mode 100644 index c5dcec4ae..000000000 --- a/openbsd/OpenBSDCRT.c +++ /dev/null @@ -1,22 +0,0 @@ -/* -htop - UnsupportedCRT.c -(C) 2014 Hisham H. Muhammad -(C) 2015 Michael McConville -Released under the GNU GPL, see the COPYING file -in the source distribution for its full text. -*/ - -#include "config.h" -#include "CRT.h" -#include -#include - -void CRT_handleSIGSEGV(int sgn) { - (void) sgn; - CRT_done(); - fprintf(stderr, "\n\nhtop " VERSION " aborting.\n"); - fprintf(stderr, "\nUnfortunately, you seem to be using an unsupported platform!"); - fprintf(stderr, "\nPlease contact your platform package maintainer!\n\n"); - abort(); -} - diff --git a/openbsd/OpenBSDCRT.h b/openbsd/OpenBSDCRT.h deleted file mode 100644 index c48309a72..000000000 --- a/openbsd/OpenBSDCRT.h +++ /dev/null @@ -1,16 +0,0 @@ -/* Do not edit this file. It was automatically generated. */ - -#ifndef HEADER_OpenBSDCRT -#define HEADER_OpenBSDCRT -/* -htop - UnsupportedCRT.h -(C) 2014 Hisham H. Muhammad -(C) 2015 Michael McConville -Released under the GNU GPL, see the COPYING file -in the source distribution for its full text. -*/ - -void CRT_handleSIGSEGV(int sgn); - - -#endif diff --git a/openbsd/OpenBSDProcess.c b/openbsd/OpenBSDProcess.c index 70f9653bc..de823ce4d 100644 --- a/openbsd/OpenBSDProcess.c +++ b/openbsd/OpenBSDProcess.c @@ -2,7 +2,7 @@ htop - OpenBSDProcess.c (C) 2015 Hisham H. Muhammad (C) 2015 Michael McConville -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ @@ -16,35 +16,15 @@ in the source distribution for its full text. #include #include -/*{ -typedef enum OpenBSDProcessFields { - // Add platform-specific fields here, with ids >= 100 - LAST_PROCESSFIELD = 100, -} OpenBSDProcessField; - -typedef struct OpenBSDProcess_ { - Process super; -} OpenBSDProcess; - -#ifndef Process_isKernelThread -#define Process_isKernelThread(_process) (_process->pgrp == 0) -#endif - -#ifndef Process_isUserlandThread -#define Process_isUserlandThread(_process) (_process->pid != _process->tgid) -#endif - -}*/ - -ProcessClass OpenBSDProcess_class = { +const ProcessClass OpenBSDProcess_class = { .super = { .extends = Class(Process), .display = Process_display, .delete = Process_delete, .compare = OpenBSDProcess_compare }, - .writeField = (Process_WriteField) OpenBSDProcess_writeField, + .writeField = OpenBSDProcess_writeField, }; ProcessFieldData Process_fields[] = { @@ -52,127 +32,158 @@ ProcessFieldData Process_fields[] = { .name = "", .title = NULL, .description = NULL, - .flags = 0, }, + .flags = 0, + }, [PID] = { .name = "PID", .title = " PID ", .description = "Process/thread ID", - .flags = 0, }, + .flags = 0, + }, [COMM] = { .name = "Command", .title = "Command ", .description = "Command line", - .flags = 0, }, + .flags = 0, + }, [STATE] = { .name = "STATE", .title = "S ", .description = "Process state (S sleeping, R running, D disk, Z zombie, T traced, W paging)", - .flags = 0, }, + .flags = 0, + }, [PPID] = { .name = "PPID", .title = " PPID ", .description = "Parent process ID", - .flags = 0, }, + .flags = 0, + }, [PGRP] = { .name = "PGRP", .title = " PGRP ", .description = "Process group ID", - .flags = 0, }, + .flags = 0, + }, [SESSION] = { .name = "SESSION", .title = " SESN ", .description = "Process's session ID", - .flags = 0, }, + .flags = 0, + }, [TTY_NR] = { .name = "TTY_NR", .title = " TTY ", .description = "Controlling terminal", - .flags = 0, }, + .flags = 0, + }, [TPGID] = { .name = "TPGID", .title = " TPGID ", .description = "Process ID of the fg process group of the controlling terminal", - .flags = 0, }, + .flags = 0, + }, [MINFLT] = { .name = "MINFLT", .title = " MINFLT ", .description = "Number of minor faults which have not required loading a memory page from disk", - .flags = 0, }, + .flags = 0, + }, [MAJFLT] = { .name = "MAJFLT", .title = " MAJFLT ", .description = "Number of major faults which have required loading a memory page from disk", - .flags = 0, }, + .flags = 0, + }, [PRIORITY] = { .name = "PRIORITY", .title = "PRI ", .description = "Kernel's internal priority for the process", - .flags = 0, }, + .flags = 0, + }, [NICE] = { .name = "NICE", .title = " NI ", .description = "Nice value (the higher the value, the more it lets other processes take priority)", - .flags = 0, }, + .flags = 0, + }, [STARTTIME] = { .name = "STARTTIME", .title = "START ", .description = "Time the process was started", - .flags = 0, }, + .flags = 0, + }, [PROCESSOR] = { .name = "PROCESSOR", .title = "CPU ", .description = "Id of the CPU the process last executed on", - .flags = 0, }, + .flags = 0, + }, [M_SIZE] = { .name = "M_SIZE", .title = " VIRT ", .description = "Total program size in virtual memory", - .flags = 0, }, + .flags = 0, + }, [M_RESIDENT] = { .name = "M_RESIDENT", .title = " RES ", .description = "Resident set size, size of the text and data sections, plus stack usage", - .flags = 0, }, + .flags = 0, + }, [ST_UID] = { .name = "ST_UID", - .title = " UID ", + .title = " UID ", .description = "User ID of the process owner", - .flags = 0, }, + .flags = 0, + }, [PERCENT_CPU] = { .name = "PERCENT_CPU", .title = "CPU% ", .description = "Percentage of the CPU time the process used in the last sampling", - .flags = 0, }, + .flags = 0, + }, + [PERCENT_NORM_CPU] = { + .name = "PERCENT_NORM_CPU", + .title = "NCPU%", + .description = "Normalized percentage of the CPU time the process used in the last sampling (normalized by cpu count)", + .flags = 0, + }, [PERCENT_MEM] = { .name = "PERCENT_MEM", .title = "MEM% ", .description = "Percentage of the memory the process is using, based on resident memory size", - .flags = 0, }, + .flags = 0, + }, [USER] = { .name = "USER", .title = "USER ", .description = "Username of the process owner (or user ID if name cannot be determined)", - .flags = 0, }, + .flags = 0, + }, [TIME] = { .name = "TIME", .title = " TIME+ ", .description = "Total time the process has spent in user and system time", - .flags = 0, }, + .flags = 0, + }, [NLWP] = { .name = "NLWP", .title = "NLWP ", .description = "Number of threads in the process", - .flags = 0, }, + .flags = 0, + }, [TGID] = { .name = "TGID", .title = " TGID ", .description = "Thread group ID (i.e. process ID)", - .flags = 0, }, + .flags = 0, + }, [LAST_PROCESSFIELD] = { .name = "*** report bug! ***", .title = NULL, .description = NULL, - .flags = 0, }, + .flags = 0, + }, }; ProcessPidColumn Process_pidColumns[] = { @@ -185,11 +196,11 @@ ProcessPidColumn Process_pidColumns[] = { { .id = 0, .label = NULL }, }; -OpenBSDProcess* OpenBSDProcess_new(Settings* settings) { +Process* OpenBSDProcess_new(const Settings* settings) { OpenBSDProcess* this = xCalloc(sizeof(OpenBSDProcess), 1); Object_setClass(this, Class(OpenBSDProcess)); Process_init(&this->super, settings); - return this; + return &this->this; } void Process_delete(Object* cast) { @@ -198,7 +209,7 @@ void Process_delete(Object* cast) { free(this); } -void OpenBSDProcess_writeField(Process* this, RichString* str, ProcessField field) { +void OpenBSDProcess_writeField(const Process* this, RichString* str, ProcessField field) { //OpenBSDProcess* fp = (OpenBSDProcess*) this; char buffer[256]; buffer[255] = '\0'; int attr = CRT_colors[DEFAULT_COLOR]; @@ -213,15 +224,17 @@ void OpenBSDProcess_writeField(Process* this, RichString* str, ProcessField fiel } long OpenBSDProcess_compare(const void* v1, const void* v2) { - OpenBSDProcess *p1, *p2; - Settings *settings = ((Process*)v1)->settings; + const OpenBSDProcess *p1, *p2; + const Settings *settings = ((const Process*)v1)->settings; + if (settings->direction == 1) { - p1 = (OpenBSDProcess*)v1; - p2 = (OpenBSDProcess*)v2; + p1 = (const OpenBSDProcess*)v1; + p2 = (const OpenBSDProcess*)v2; } else { - p2 = (OpenBSDProcess*)v1; - p1 = (OpenBSDProcess*)v2; + p2 = (const OpenBSDProcess*)v1; + p1 = (const OpenBSDProcess*)v2; } + switch (settings->sortKey) { // add OpenBSD-specific fields here default: @@ -229,6 +242,6 @@ long OpenBSDProcess_compare(const void* v1, const void* v2) { } } -bool Process_isThread(Process* this) { +bool Process_isThread(const Process* this) { return (Process_isKernelThread(this)); } diff --git a/openbsd/OpenBSDProcess.h b/openbsd/OpenBSDProcess.h index ba55e5ea0..12ce18409 100644 --- a/openbsd/OpenBSDProcess.h +++ b/openbsd/OpenBSDProcess.h @@ -1,17 +1,14 @@ -/* Do not edit this file. It was automatically generated. */ - #ifndef HEADER_OpenBSDProcess #define HEADER_OpenBSDProcess /* htop - OpenBSDProcess.h (C) 2015 Hisham H. Muhammad (C) 2015 Michael McConville -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ - -typedef enum OpenBSDProcessFields { +typedef enum OpenBSDProcessFields_ { // Add platform-specific fields here, with ids >= 100 LAST_PROCESSFIELD = 100, } OpenBSDProcessField; @@ -20,29 +17,24 @@ typedef struct OpenBSDProcess_ { Process super; } OpenBSDProcess; -#ifndef Process_isKernelThread #define Process_isKernelThread(_process) (_process->pgrp == 0) -#endif -#ifndef Process_isUserlandThread #define Process_isUserlandThread(_process) (_process->pid != _process->tgid) -#endif - -extern ProcessClass OpenBSDProcess_class; +extern const ProcessClass OpenBSDProcess_class; extern ProcessFieldData Process_fields[]; extern ProcessPidColumn Process_pidColumns[]; -OpenBSDProcess* OpenBSDProcess_new(Settings* settings); +Process* OpenBSDProcess_new(const Settings* settings); void Process_delete(Object* cast); -void OpenBSDProcess_writeField(Process* this, RichString* str, ProcessField field); +void OpenBSDProcess_writeField(const Process* this, RichString* str, ProcessField field); long OpenBSDProcess_compare(const void* v1, const void* v2); -bool Process_isThread(Process* this); +bool Process_isThread(const Process* this); #endif diff --git a/openbsd/OpenBSDProcessList.c b/openbsd/OpenBSDProcessList.c index e49cbd71f..aec13477d 100644 --- a/openbsd/OpenBSDProcessList.c +++ b/openbsd/OpenBSDProcessList.c @@ -2,13 +2,15 @@ htop - OpenBSDProcessList.c (C) 2014 Hisham H. Muhammad (C) 2015 Michael McConville -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ +#include "CRT.h" #include "ProcessList.h" #include "OpenBSDProcessList.h" #include "OpenBSDProcess.h" +#include "Macros.h" #include #include @@ -17,6 +19,7 @@ in the source distribution for its full text. #include #include #include +#include #include #include #include @@ -25,43 +28,9 @@ in the source distribution for its full text. #include #include -/*{ - -#include - -typedef struct CPUData_ { - unsigned long long int totalTime; - unsigned long long int totalPeriod; -} CPUData; - -typedef struct OpenBSDProcessList_ { - ProcessList super; - kvm_t* kd; - - CPUData* cpus; - -} OpenBSDProcessList; - -}*/ - -/* - * avoid relying on or conflicting with MIN() and MAX() in sys/param.h - */ -#ifndef MINIMUM -#define MINIMUM(x, y) ((x) > (y) ? (y) : (x)) -#endif - -#ifndef MAXIMUM -#define MAXIMUM(x, y) ((x) > (y) ? (x) : (y)) -#endif - -#ifndef CLAMP -#define CLAMP(x, low, high) (((x) > (high)) ? (high) : MAXIMUM(x, low)) -#endif - static long fscale; -ProcessList* ProcessList_new(UsersTable* usersTable, Hashtable* pidWhiteList, uid_t userId) { +ProcessList* ProcessList_new(UsersTable* usersTable, Hashtable* pidMatchList, uid_t userId) { int mib[] = { CTL_HW, HW_NCPU }; int fmib[] = { CTL_KERN, KERN_FSCALE }; int i, e; @@ -73,22 +42,23 @@ ProcessList* ProcessList_new(UsersTable* usersTable, Hashtable* pidWhiteList, ui opl = xCalloc(1, sizeof(OpenBSDProcessList)); pl = (ProcessList*) opl; size = sizeof(pl->cpuCount); - ProcessList_init(pl, Class(OpenBSDProcess), usersTable, pidWhiteList, userId); + ProcessList_init(pl, Class(OpenBSDProcess), usersTable, pidMatchList, userId); e = sysctl(mib, 2, &pl->cpuCount, &size, NULL, 0); if (e == -1 || pl->cpuCount < 1) { pl->cpuCount = 1; } - opl->cpus = xRealloc(opl->cpus, pl->cpuCount * sizeof(CPUData)); + opl->cpus = xCalloc(pl->cpuCount + 1, sizeof(CPUData)); size = sizeof(fscale); if (sysctl(fmib, 2, &fscale, &size, NULL, 0) < 0) { err(1, "fscale sysctl call failed"); } - for (i = 0; i < pl->cpuCount; i++) { - opl->cpus[i].totalTime = 1; - opl->cpus[i].totalPeriod = 1; + for (i = 0; i <= pl->cpuCount; i++) { + CPUData* d = opl->cpus + i; + d->totalTime = 1; + d->totalPeriod = 1; } opl->kd = kvm_openfiles(NULL, NULL, NULL, KVM_NO_FILES, errbuf); @@ -121,7 +91,7 @@ static inline void OpenBSDProcessList_scanMemoryInfo(ProcessList* pl) { err(1, "uvmexp sysctl call failed"); } - pl->totalMem = uvmexp.npages * PAGE_SIZE_KB; + pl->totalMem = uvmexp.npages * CRT_pageSizeKB; // Taken from OpenBSD systat/iostat.c, top/machine.c and uvm_sysctl(9) static int bcache_mib[] = {CTL_VFS, VFS_GENERIC, VFS_BCACHESTAT}; @@ -132,9 +102,9 @@ static inline void OpenBSDProcessList_scanMemoryInfo(ProcessList* pl) { err(1, "cannot get vfs.bcachestat"); } - pl->cachedMem = bcstats.numbufpages * PAGE_SIZE_KB; - pl->freeMem = uvmexp.free * PAGE_SIZE_KB; - pl->usedMem = (uvmexp.npages - uvmexp.free - uvmexp.paging) * PAGE_SIZE_KB; + pl->cachedMem = bcstats.numbufpages * CRT_pageSizeKB; + pl->freeMem = uvmexp.free * CRT_pageSizeKB; + pl->usedMem = (uvmexp.npages - uvmexp.free - uvmexp.paging) * CRT_pageSizeKB; /* const OpenBSDProcessList* opl = (OpenBSDProcessList*) pl; @@ -143,28 +113,28 @@ static inline void OpenBSDProcessList_scanMemoryInfo(ProcessList* pl) { sysctl(MIB_hw_physmem, 2, &(pl->totalMem), &len, NULL, 0); pl->totalMem /= 1024; sysctl(MIB_vm_stats_vm_v_wire_count, 4, &(pl->usedMem), &len, NULL, 0); - pl->usedMem *= PAGE_SIZE_KB; + pl->usedMem *= CRT_pageSizeKB; pl->freeMem = pl->totalMem - pl->usedMem; sysctl(MIB_vm_stats_vm_v_cache_count, 4, &(pl->cachedMem), &len, NULL, 0); - pl->cachedMem *= PAGE_SIZE_KB; + pl->cachedMem *= CRT_pageSizeKB; struct kvm_swap swap[16]; - int nswap = kvm_getswapinfo(opl->kd, swap, sizeof(swap)/sizeof(swap[0]), 0); + int nswap = kvm_getswapinfo(opl->kd, swap, ARRAYSIZE(swap), 0); pl->totalSwap = 0; pl->usedSwap = 0; for (int i = 0; i < nswap; i++) { pl->totalSwap += swap[i].ksw_total; pl->usedSwap += swap[i].ksw_used; } - pl->totalSwap *= PAGE_SIZE_KB; - pl->usedSwap *= PAGE_SIZE_KB; + pl->totalSwap *= CRT_pageSizeKB; + pl->usedSwap *= CRT_pageSizeKB; pl->sharedMem = 0; // currently unused pl->buffersMem = 0; // not exposed to userspace */ } -char *OpenBSDProcessList_readProcessName(kvm_t* kd, struct kinfo_proc* kproc, int* basenameEnd) { +char* OpenBSDProcessList_readProcessName(kvm_t* kd, struct kinfo_proc* kproc, int* basenameEnd) { char *s, **arg; size_t len = 0, n; int i; @@ -193,7 +163,7 @@ char *OpenBSDProcessList_readProcessName(kvm_t* kd, struct kinfo_proc* kproc, in n = strlcat(s, arg[i], len); if (i == 0) { /* TODO: rename all basenameEnd to basenameLen, make size_t */ - *basenameEnd = MINIMUM(n, len-1); + *basenameEnd = MINIMUM(n, len - 1); } /* the trailing space should get truncated anyway */ strlcat(s, " ", len); @@ -205,42 +175,35 @@ char *OpenBSDProcessList_readProcessName(kvm_t* kd, struct kinfo_proc* kproc, in /* * Taken from OpenBSD's ps(1). */ -double getpcpu(const struct kinfo_proc *kp) { +static double getpcpu(const struct kinfo_proc* kp) { if (fscale == 0) - return (0.0); + return 0.0; #define fxtofl(fixpt) ((double)(fixpt) / fscale) return (100.0 * fxtofl(kp->p_pctcpu)); } -void ProcessList_goThroughEntries(ProcessList* this) { - OpenBSDProcessList* opl = (OpenBSDProcessList*) this; - Settings* settings = this->settings; +static inline void OpenBSDProcessList_scanProcs(OpenBSDProcessList* this) { + const Settings* settings = this->super.settings; bool hideKernelThreads = settings->hideKernelThreads; bool hideUserlandThreads = settings->hideUserlandThreads; struct kinfo_proc* kproc; bool preExisting; Process* proc; OpenBSDProcess* fp; - struct tm date; - struct timeval tv; int count = 0; int i; - OpenBSDProcessList_scanMemoryInfo(this); - // use KERN_PROC_KTHREAD to also include kernel threads - struct kinfo_proc* kprocs = kvm_getprocs(opl->kd, KERN_PROC_ALL, 0, sizeof(struct kinfo_proc), &count); + struct kinfo_proc* kprocs = kvm_getprocs(this->kd, KERN_PROC_ALL, 0, sizeof(struct kinfo_proc), &count); //struct kinfo_proc* kprocs = getprocs(KERN_PROC_ALL, 0, &count); - gettimeofday(&tv, NULL); - for (i = 0; i < count; i++) { kproc = &kprocs[i]; preExisting = false; - proc = ProcessList_getProcess(this, kproc->p_pid, &preExisting, (Process_New) OpenBSDProcess_new); + proc = ProcessList_getProcess(&this->super, kproc->p_pid, &preExisting, OpenBSDProcess_new); fp = (OpenBSDProcess*) proc; proc->show = ! ((hideKernelThreads && Process_isKernelThread(proc)) @@ -255,22 +218,21 @@ void ProcessList_goThroughEntries(ProcessList* this) { proc->pgrp = kproc->p__pgid; proc->st_uid = kproc->p_uid; proc->starttime_ctime = kproc->p_ustart_sec; - proc->user = UsersTable_getRef(this->usersTable, proc->st_uid); - ProcessList_add((ProcessList*)this, proc); - proc->comm = OpenBSDProcessList_readProcessName(opl->kd, kproc, &proc->basenameOffset); - (void) localtime_r((time_t*) &kproc->p_ustart_sec, &date); - strftime(proc->starttime_show, 7, ((proc->starttime_ctime > tv.tv_sec - 86400) ? "%R " : "%b%d "), &date); + Process_fillStarttimeBuffer(proc); + proc->user = UsersTable_getRef(this->super.usersTable, proc->st_uid); + ProcessList_add(&this->super, proc); + proc->comm = OpenBSDProcessList_readProcessName(this->kd, kproc, &proc->basenameOffset); } else { if (settings->updateProcessNames) { free(proc->comm); - proc->comm = OpenBSDProcessList_readProcessName(opl->kd, kproc, &proc->basenameOffset); + proc->comm = OpenBSDProcessList_readProcessName(this->kd, kproc, &proc->basenameOffset); } } proc->m_size = kproc->p_vm_dsize; proc->m_resident = kproc->p_vm_rssize; - proc->percent_mem = (proc->m_resident * PAGE_SIZE_KB) / (double)(this->totalMem) * 100.0; - proc->percent_cpu = CLAMP(getpcpu(kproc), 0.0, this->cpuCount*100.0); + proc->percent_mem = (proc->m_resident * CRT_pageSizeKB) / (double)(this->super.totalMem) * 100.0; + proc->percent_cpu = CLAMP(getpcpu(kproc), 0.0, this->super.cpuCount * 100.0); //proc->nlwp = kproc->p_numthreads; //proc->time = kproc->p_rtime_sec + ((kproc->p_rtime_usec + 500000) / 10); proc->nice = kproc->p_nice - 20; @@ -290,14 +252,104 @@ void ProcessList_goThroughEntries(ProcessList* this) { } if (Process_isKernelThread(proc)) { - this->kernelThreads++; + this->super.kernelThreads++; } - this->totalTasks++; + this->super.totalTasks++; // SRUN ('R') means runnable, not running if (proc->state == 'P') { - this->runningTasks++; + this->super.runningTasks++; } proc->updated = true; } } + +static unsigned long long saturatingSub(unsigned long long a, unsigned long long b) { + return a > b ? a - b : 0; +} + +static void getKernelCPUTimes(int cpuId, u_int64_t* times) { + int mib[] = { CTL_KERN, KERN_CPTIME2, cpuId }; + size_t length = sizeof(u_int64_t) * CPUSTATES; + if (sysctl(mib, 3, times, &length, NULL, 0) == -1 || + length != sizeof(u_int64_t) * CPUSTATES) { + CRT_fatalError("sysctl kern.cp_time2 failed"); + } +} + +static void kernelCPUTimesToHtop(const u_int64_t* times, CPUData* cpu) { + unsigned long long totalTime = 0; + for (int i = 0; i < CPUSTATES; i++) { + totalTime += times[i]; + } + + unsigned long long sysAllTime = times[CP_INTR] + times[CP_SYS]; + + // XXX Not sure if CP_SPIN should be added to sysAllTime. + // See https://github.com/openbsd/src/commit/531d8034253fb82282f0f353c086e9ad827e031c + #ifdef CP_SPIN + sysAllTime += times[CP_SPIN]; + #endif + + cpu->totalPeriod = saturatingSub(totalTime, cpu->totalTime); + cpu->userPeriod = saturatingSub(times[CP_USER], cpu->userTime); + cpu->nicePeriod = saturatingSub(times[CP_NICE], cpu->niceTime); + cpu->sysPeriod = saturatingSub(times[CP_SYS], cpu->sysTime); + cpu->sysAllPeriod = saturatingSub(sysAllTime, cpu->sysAllTime); + #ifdef CP_SPIN + cpu->spinPeriod = saturatingSub(times[CP_SPIN], cpu->spinTime); + #endif + cpu->intrPeriod = saturatingSub(times[CP_INTR], cpu->intrTime); + cpu->idlePeriod = saturatingSub(times[CP_IDLE], cpu->idleTime); + + cpu->totalTime = totalTime; + cpu->userTime = times[CP_USER]; + cpu->niceTime = times[CP_NICE]; + cpu->sysTime = times[CP_SYS]; + cpu->sysAllTime = sysAllTime; + #ifdef CP_SPIN + cpu->spinTime = times[CP_SPIN]; + #endif + cpu->intrTime = times[CP_INTR]; + cpu->idleTime = times[CP_IDLE]; +} + +static void OpenBSDProcessList_scanCPUTime(OpenBSDProcessList* this) { + u_int64_t kernelTimes[CPUSTATES] = {0}; + u_int64_t avg[CPUSTATES] = {0}; + + for (int i = 0; i < this->super.cpuCount; i++) { + getKernelCPUTimes(i, kernelTimes); + CPUData* cpu = this->cpus + i + 1; + kernelCPUTimesToHtop(kernelTimes, cpu); + + avg[CP_USER] += cpu->userTime; + avg[CP_NICE] += cpu->niceTime; + avg[CP_SYS] += cpu->sysTime; + #ifdef CP_SPIN + avg[CP_SPIN] += cpu->spinTime; + #endif + avg[CP_INTR] += cpu->intrTime; + avg[CP_IDLE] += cpu->idleTime; + } + + for (int i = 0; i < CPUSTATES; i++) { + avg[i] /= this->super.cpuCount; + } + + kernelCPUTimesToHtop(avg, this->cpus); +} + +void ProcessList_goThroughEntries(ProcessList* super, bool pauseProcessUpdate) { + OpenBSDProcessList* opl = (OpenBSDProcessList*) super; + + OpenBSDProcessList_scanMemoryInfo(super); + OpenBSDProcessList_scanCPUTime(opl); + + // in pause mode only gather global data for meters (CPU/memory/...) + if (pauseProcessUpdate) { + return; + } + + OpenBSDProcessList_scanProcs(opl); +} diff --git a/openbsd/OpenBSDProcessList.h b/openbsd/OpenBSDProcessList.h index ba9e6d14b..1b40faf1f 100644 --- a/openbsd/OpenBSDProcessList.h +++ b/openbsd/OpenBSDProcessList.h @@ -1,21 +1,33 @@ -/* Do not edit this file. It was automatically generated. */ - #ifndef HEADER_OpenBSDProcessList #define HEADER_OpenBSDProcessList /* htop - OpenBSDProcessList.h (C) 2014 Hisham H. Muhammad (C) 2015 Michael McConville -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ - #include typedef struct CPUData_ { unsigned long long int totalTime; + unsigned long long int userTime; + unsigned long long int niceTime; + unsigned long long int sysTime; + unsigned long long int sysAllTime; + unsigned long long int spinTime; + unsigned long long int intrTime; + unsigned long long int idleTime; + unsigned long long int totalPeriod; + unsigned long long int userPeriod; + unsigned long long int nicePeriod; + unsigned long long int sysPeriod; + unsigned long long int sysAllPeriod; + unsigned long long int spinPeriod; + unsigned long long int intrPeriod; + unsigned long long int idlePeriod; } CPUData; typedef struct OpenBSDProcessList_ { @@ -27,32 +39,12 @@ typedef struct OpenBSDProcessList_ { } OpenBSDProcessList; -/* - * avoid relying on or conflicting with MIN() and MAX() in sys/param.h - */ -#ifndef MINIMUM -#define MINIMUM(x, y) ((x) > (y) ? (y) : (x)) -#endif - -#ifndef MAXIMUM -#define MAXIMUM(x, y) ((x) > (y) ? (x) : (y)) -#endif - -#ifndef CLAMP -#define CLAMP(x, low, high) (((x) > (high)) ? (high) : MAXIMUM(x, low)) -#endif - -ProcessList* ProcessList_new(UsersTable* usersTable, Hashtable* pidWhiteList, uid_t userId); +ProcessList* ProcessList_new(UsersTable* usersTable, Hashtable* pidMatchList, uid_t userId); void ProcessList_delete(ProcessList* this); -char *OpenBSDProcessList_readProcessName(kvm_t* kd, struct kinfo_proc* kproc, int* basenameEnd); - -/* - * Taken from OpenBSD's ps(1). - */ -double getpcpu(const struct kinfo_proc *kp); +char* OpenBSDProcessList_readProcessName(kvm_t* kd, struct kinfo_proc* kproc, int* basenameEnd); -void ProcessList_goThroughEntries(ProcessList* this); +void ProcessList_goThroughEntries(ProcessList* super, bool pauseProcessUpdate); #endif diff --git a/openbsd/Platform.c b/openbsd/Platform.c index 4bb2e35ee..b7cc5190c 100644 --- a/openbsd/Platform.c +++ b/openbsd/Platform.c @@ -2,11 +2,12 @@ htop - openbsd/Platform.c (C) 2014 Hisham H. Muhammad (C) 2015 Michael McConville -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ #include "Platform.h" +#include "Macros.h" #include "Meter.h" #include "CPUMeter.h" #include "MemoryMeter.h" @@ -15,15 +16,16 @@ in the source distribution for its full text. #include "LoadAverageMeter.h" #include "UptimeMeter.h" #include "ClockMeter.h" +#include "DateMeter.h" +#include "DateTimeMeter.h" #include "HostnameMeter.h" #include "SignalsPanel.h" #include "OpenBSDProcess.h" #include "OpenBSDProcessList.h" -#include -#include #include #include +#include #include #include @@ -31,70 +33,15 @@ in the source distribution for its full text. #include #include #include -#include #include #include #include #include #include #include +#include +#include -/*{ -#include "Action.h" -#include "BatteryMeter.h" -#include "SignalsPanel.h" - -extern ProcessFieldData Process_fields[]; - -}*/ - -#define MAXCPU 256 -// XXX: probably should be a struct member -static int64_t old_v[MAXCPU][5]; - -/* - * Copyright (c) 1984, 1989, William LeFebvre, Rice University - * Copyright (c) 1989, 1990, 1992, William LeFebvre, Northwestern University - * - * Taken directly from OpenBSD's top(1). - * - * percentages(cnt, out, new, old, diffs) - calculate percentage change - * between array "old" and "new", putting the percentages in "out". - * "cnt" is size of each array and "diffs" is used for scratch space. - * The array "old" is updated on each call. - * The routine assumes modulo arithmetic. This function is especially - * useful on BSD machines for calculating cpu state percentages. - */ -static int percentages(int cnt, int64_t *out, int64_t *new, int64_t *old, int64_t *diffs) { - int64_t change, total_change, *dp, half_total; - int i; - - /* initialization */ - total_change = 0; - dp = diffs; - - /* calculate changes for each state and the overall change */ - for (i = 0; i < cnt; i++) { - if ((change = *new - *old) < 0) { - /* this only happens when the counter wraps */ - change = INT64_MAX - *old + *new; - } - total_change += (*dp++ = change); - *old++ = *new++; - } - - /* avoid divide by zero potential */ - if (total_change == 0) - total_change = 1; - - /* calculate percentages based on overall change, rounding up */ - half_total = total_change / 2l; - for (i = 0; i < cnt; i++) - *out++ = ((*diffs++ * 1000 + half_total) / total_change); - - /* return the total in case the caller wants to use it */ - return (total_change); -} ProcessField Platform_defaultFields[] = { PID, USER, PRIORITY, NICE, M_SIZE, M_RESIDENT, STATE, PERCENT_CPU, PERCENT_MEM, TIME, COMM, 0 }; @@ -140,15 +87,17 @@ const SignalItem Platform_signals[] = { { .name = "32 SIGTHR", .number = 32 }, }; -const unsigned int Platform_numberOfSignals = sizeof(Platform_signals)/sizeof(SignalItem); +const unsigned int Platform_numberOfSignals = ARRAYSIZE(Platform_signals); void Platform_setBindings(Htop_Action* keys) { (void) keys; } -MeterClass* Platform_meterTypes[] = { +const MeterClass* const Platform_meterTypes[] = { &CPUMeter_class, &ClockMeter_class, + &DateMeter_class, + &DateTimeMeter_class, &LoadAverageMeter_class, &LoadMeter_class, &MemoryMeter_class, @@ -159,10 +108,16 @@ MeterClass* Platform_meterTypes[] = { &HostnameMeter_class, &AllCPUsMeter_class, &AllCPUs2Meter_class, + &AllCPUs4Meter_class, + &AllCPUs8Meter_class, &LeftCPUsMeter_class, &RightCPUsMeter_class, &LeftCPUs2Meter_class, &RightCPUs2Meter_class, + &LeftCPUs4Meter_class, + &RightCPUs4Meter_class, + &LeftCPUs8Meter_class, + &RightCPUs8Meter_class, &BlankMeter_class, NULL }; @@ -201,47 +156,44 @@ void Platform_getLoadAverage(double* one, double* five, double* fifteen) { int Platform_getMaxPid() { // this is hard-coded in sys/sys/proc.h - no sysctl exists - return 32766; + return 99999; } double Platform_setCPUValues(Meter* this, int cpu) { - int i; - double perc; - - OpenBSDProcessList* pl = (OpenBSDProcessList*) this->pl; - CPUData* cpuData = &(pl->cpus[cpu]); - int64_t new_v[CPUSTATES], diff_v[CPUSTATES], scratch_v[CPUSTATES]; - double *v = this->values; - size_t size = sizeof(double) * CPUSTATES; - int mib[] = { CTL_KERN, KERN_CPTIME2, cpu-1 }; - if (sysctl(mib, 3, new_v, &size, NULL, 0) == -1) { - return 0.; - } - - // XXX: why? - cpuData->totalPeriod = 1; - - percentages(CPUSTATES, diff_v, new_v, - (int64_t *)old_v[cpu-1], scratch_v); - - for (i = 0; i < CPUSTATES; i++) { - old_v[cpu-1][i] = new_v[i]; - v[i] = diff_v[i] / 10.; + const OpenBSDProcessList* pl = (OpenBSDProcessList*) this->pl; + const CPUData* cpuData = &(pl->cpus[cpu]); + double total = cpuData->totalPeriod == 0 ? 1 : cpuData->totalPeriod; + double totalPercent; + double* v = this->values; + + v[CPU_METER_NICE] = cpuData->nicePeriod / total * 100.0; + v[CPU_METER_NORMAL] = cpuData->userPeriod / total * 100.0; + if (this->pl->settings->detailedCPUTime) { + v[CPU_METER_KERNEL] = cpuData->sysPeriod / total * 100.0; + v[CPU_METER_IRQ] = cpuData->intrPeriod / total * 100.0; + v[CPU_METER_SOFTIRQ] = 0.0; + v[CPU_METER_STEAL] = 0.0; + v[CPU_METER_GUEST] = 0.0; + v[CPU_METER_IOWAIT] = 0.0; + v[CPU_METER_FREQUENCY] = NAN; + this->curItems = 8; + totalPercent = v[0] + v[1] + v[2] + v[3]; + } else { + v[2] = cpuData->sysAllPeriod / total * 100.0; + v[3] = 0.0; // No steal nor guest on OpenBSD + totalPercent = v[0] + v[1] + v[2]; + this->curItems = 4; } - Meter_setItems(this, 4); - - perc = v[0] + v[1] + v[2] + v[3]; - - if (perc <= 100. && perc >= 0.) { - return perc; - } else { - return 0.; + totalPercent = CLAMP(totalPercent, 0.0, 100.0); + if (isnan(totalPercent)) { + totalPercent = 0.0; } + return totalPercent; } void Platform_setMemoryValues(Meter* this) { - ProcessList* pl = (ProcessList*) this->pl; + const ProcessList* pl = this->pl; long int usedMem = pl->usedMem; long int buffersMem = pl->buffersMem; long int cachedMem = pl->cachedMem; @@ -259,8 +211,8 @@ void Platform_setMemoryValues(Meter* this) { * Taken almost directly from OpenBSD's top(1) */ void Platform_setSwapValues(Meter* this) { - ProcessList* pl = (ProcessList*) this->pl; - struct swapent *swdev; + const ProcessList* pl = this->pl; + struct swapent* swdev; unsigned long long int total, used; int nswap, rnswap, i; nswap = swapctl(SWAP_NSWAP, 0, 0); @@ -293,24 +245,21 @@ void Platform_setSwapValues(Meter* this) { free(swdev); } -void Platform_setTasksValues(Meter* this) { - // TODO -} - char* Platform_getProcessEnv(pid_t pid) { char errbuf[_POSIX2_LINE_MAX]; - char *env; - char **ptr; + char* env; + char** ptr; int count; - kvm_t *kt; - struct kinfo_proc *kproc; + kvm_t* kt; + struct kinfo_proc* kproc; size_t capacity = 4096, size = 0; - if ((kt = kvm_openfiles(NULL, NULL, NULL, KVM_NO_FILES, errbuf)) == NULL) + if ((kt = kvm_openfiles(NULL, NULL, NULL, KVM_NO_FILES, errbuf)) == NULL) { return NULL; + } if ((kproc = kvm_getprocs(kt, KERN_PROC_PID, pid, - sizeof(struct kinfo_proc), &count)) == NULL) {\ + sizeof(struct kinfo_proc), &count)) == NULL) { (void) kvm_close(kt); return NULL; } @@ -321,7 +270,7 @@ char* Platform_getProcessEnv(pid_t pid) { } env = xMalloc(capacity); - for (char **p = ptr; *p; p++) { + for (char** p = ptr; *p; p++) { size_t len = strlen(*p) + 1; if (size + len > capacity) { @@ -334,12 +283,98 @@ char* Platform_getProcessEnv(pid_t pid) { } if (size < 2 || env[size - 1] || env[size - 2]) { - if (size + 2 < capacity) - env = xRealloc(env, capacity + 2); - env[size] = 0; - env[size+1] = 0; + if (size + 2 < capacity) + env = xRealloc(env, capacity + 2); + env[size] = 0; + env[size + 1] = 0; } (void) kvm_close(kt); return env; } + +char* Platform_getInodeFilename(pid_t pid, ino_t inode) { + (void)pid; + (void)inode; + return NULL; +} + +FileLocks_ProcessData* Platform_getProcessLocks(pid_t pid) { + (void)pid; + return NULL; +} + +bool Platform_getDiskIO(DiskIOData* data) { + // TODO + (void)data; + return false; +} + +bool Platform_getNetworkIO(unsigned long int* bytesReceived, + unsigned long int* packetsReceived, + unsigned long int* bytesTransmitted, + unsigned long int* packetsTransmitted) { + // TODO + *bytesReceived = 0; + *packetsReceived = 0; + *bytesTransmitted = 0; + *packetsTransmitted = 0; + return false; +} + +static bool findDevice(const char* name, int* mib, struct sensordev* snsrdev, size_t* sdlen) { + for (int devn = 0;; devn++) { + mib[2] = devn; + if (sysctl(mib, 3, snsrdev, sdlen, NULL, 0) == -1) { + if (errno == ENXIO) + continue; + if (errno == ENOENT) + return false; + } + if (strcmp(name, snsrdev->xname) == 0) { + return true; + } + } +} + +void Platform_getBattery(double* level, ACPresence* isOnAC) { + static int mib[] = {CTL_HW, HW_SENSORS, 0, 0, 0}; + struct sensor s; + size_t slen = sizeof(struct sensor); + struct sensordev snsrdev; + size_t sdlen = sizeof(struct sensordev); + + bool found = findDevice("acpibat0", mib, &snsrdev, &sdlen); + + *level = NAN; + if (found) { + /* last full capacity */ + mib[3] = 7; + mib[4] = 0; + double last_full_capacity = 0; + if (sysctl(mib, 5, &s, &slen, NULL, 0) != -1) + last_full_capacity = s.value; + if (last_full_capacity > 0) { + /* remaining capacity */ + mib[3] = 7; + mib[4] = 3; + if (sysctl(mib, 5, &s, &slen, NULL, 0) != -1) { + double charge = s.value; + *level = 100 * (charge / last_full_capacity); + if (charge >= last_full_capacity) { + *level = 100; + } + } + } + } + + found = findDevice("acpiac0", mib, &snsrdev, &sdlen); + + *isOnAC = AC_ERROR; + if (found) { + mib[3] = 9; + mib[4] = 0; + if (sysctl(mib, 5, &s, &slen, NULL, 0) != -1) + *isOnAC = s.value; + } +} diff --git a/openbsd/Platform.h b/openbsd/Platform.h index e0da7b9ff..9d2701dce 100644 --- a/openbsd/Platform.h +++ b/openbsd/Platform.h @@ -1,73 +1,60 @@ -/* Do not edit this file. It was automatically generated. */ - #ifndef HEADER_Platform #define HEADER_Platform /* htop - openbsd/Platform.h (C) 2014 Hisham H. Muhammad (C) 2015 Michael McConville -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ +#include +#include + #include "Action.h" #include "BatteryMeter.h" +#include "DiskIOMeter.h" +#include "ProcessLocksScreen.h" #include "SignalsPanel.h" extern ProcessFieldData Process_fields[]; - -#define MAXCPU 256 -// XXX: probably should be a struct member -/* - * Copyright (c) 1984, 1989, William LeFebvre, Rice University - * Copyright (c) 1989, 1990, 1992, William LeFebvre, Northwestern University - * - * Taken directly from OpenBSD's top(1). - * - * percentages(cnt, out, new, old, diffs) - calculate percentage change - * between array "old" and "new", putting the percentages in "out". - * "cnt" is size of each array and "diffs" is used for scratch space. - * The array "old" is updated on each call. - * The routine assumes modulo arithmetic. This function is especially - * useful on BSD machines for calculating cpu state percentages. - */ extern ProcessField Platform_defaultFields[]; extern int Platform_numberOfFields; -/* - * See /usr/include/sys/signal.h - */ +/* see /usr/include/sys/signal.h */ extern const SignalItem Platform_signals[]; extern const unsigned int Platform_numberOfSignals; void Platform_setBindings(Htop_Action* keys); -extern MeterClass* Platform_meterTypes[]; +extern const MeterClass* const Platform_meterTypes[]; -// preserved from FreeBSD port -int Platform_getUptime(); +int Platform_getUptime(void); void Platform_getLoadAverage(double* one, double* five, double* fifteen); -int Platform_getMaxPid(); +int Platform_getMaxPid(void); double Platform_setCPUValues(Meter* this, int cpu); void Platform_setMemoryValues(Meter* this); -/* - * Copyright (c) 1994 Thorsten Lockert - * All rights reserved. - * - * Taken almost directly from OpenBSD's top(1) - */ void Platform_setSwapValues(Meter* this); -void Platform_setTasksValues(Meter* this); - char* Platform_getProcessEnv(pid_t pid); +char* Platform_getInodeFilename(pid_t pid, ino_t inode); + +FileLocks_ProcessData* Platform_getProcessLocks(pid_t pid); + +bool Platform_getDiskIO(DiskIOData* data); + +bool Platform_getNetworkIO(unsigned long int* bytesReceived, + unsigned long int* packetsReceived, + unsigned long int* bytesTransmitted, + unsigned long int* packetsTransmitted); + #endif diff --git a/scripts/MakeHeader.py b/scripts/MakeHeader.py deleted file mode 100755 index 349531b8e..000000000 --- a/scripts/MakeHeader.py +++ /dev/null @@ -1,102 +0,0 @@ -#!/usr/bin/env python -import os, sys, string, io -try: - from StringIO import StringIO -except ImportError: - StringIO = io.StringIO - -ANY=1 -COPY=2 -SKIP=3 -SKIPONE=4 - -state = ANY -static = 0 - -file = io.open(sys.argv[1], "r", encoding="utf-8") -name = sys.argv[1][:-2] - -out = StringIO() - -selfheader = '#include "' + name + '.h"' - -out.write( "/* Do not edit this file. It was automatically generated. */\n" ) -out.write( "\n" ) - -out.write( "#ifndef HEADER_" + os.path.basename(name) + "\n") -out.write( "#define HEADER_" + os.path.basename(name) + "\n") -is_blank = False -for line in file.readlines(): - line = line[:-1] - if state == ANY: - if line == '/*{': - state = COPY - elif line == selfheader: - pass - elif line.find("#include") == 0: - pass - elif line.find("htop - ") == 0 and line[-2:] == ".c": - out.write(line[:-2] + ".h\n") - elif line.find("static ") != -1: - if line[-1] == "{": - state = SKIP - static = 1 - else: - state = SKIPONE - elif len(line) > 1: - static = 0 - equals = line.find(" = ") - if line[-3:] == "= {": - out.write( "extern " + line[:-4] + ";\n" ) - state = SKIP - elif equals != -1: - out.write("extern " + line[:equals] + ";\n" ) - elif line.startswith("typedef struct"): - state = SKIP - elif line[-1] == "{": - out.write( line[:-2].replace("inline", "extern") + ";\n" ) - state = SKIP - else: - out.write( line + "\n") - is_blank = False - elif line == "": - if not is_blank: - out.write( line + "\n") - is_blank = True - else: - out.write( line + "\n") - is_blank = False - elif state == COPY: - is_blank = False - if line == "}*/": - state = ANY - else: - out.write( line + "\n") - elif state == SKIP: - is_blank = False - if len(line) >= 1 and line[0] == "}": - if static == 1: - state = SKIPONE - else: - state = ANY - static = 0 - elif state == SKIPONE: - is_blank = False - state = ANY - -out.write( "\n" ) -out.write( "#endif\n" ) - -# only write a new .h file if something changed. -# This prevents a lot of recompilation during development -out.seek(0) -try: - with io.open(name + ".h", "r", encoding="utf-8") as orig: - origcontents = orig.readlines() -except: - origcontents = "" -if origcontents != out.readlines(): - with io.open(name + ".h", "w", encoding="utf-8") as new: - print("Writing "+name+".h") - new.write(out.getvalue()) -out.close() diff --git a/scripts/htop_suppressions.valgrind b/scripts/htop_suppressions.valgrind new file mode 100644 index 000000000..a7afb0fd4 --- /dev/null +++ b/scripts/htop_suppressions.valgrind @@ -0,0 +1,63 @@ +{ + + Memcheck:Leak + match-leak-kinds: reachable + ... + fun:CRT_init + fun:main +} + +{ + + Memcheck:Leak + match-leak-kinds: reachable + ... + fun:CRT_init +} + +{ + + Memcheck:Leak + match-leak-kinds: reachable + ... + fun:wgetch + fun:ScreenManager_run + fun:Action_runSetup + fun:actionSetup + fun:MainPanel_eventHandler + fun:ScreenManager_run + fun:main +} + +{ + + Memcheck:Leak + match-leak-kinds: reachable + ... + fun:wgetch + fun:ScreenManager_run + fun:main +} + +{ + + Memcheck:Leak + match-leak-kinds: reachable + ... + fun:wrefresh + fun:main +} + +{ + + Memcheck:Leak + match-leak-kinds: reachable + fun:realloc + fun:_nc_doalloc + fun:_nc_tparm_analyze + fun:tparm + ... + fun:doupdate_sp + fun:wrefresh + obj:* +} diff --git a/scripts/run_valgrind.sh b/scripts/run_valgrind.sh new file mode 100755 index 000000000..f635b93b8 --- /dev/null +++ b/scripts/run_valgrind.sh @@ -0,0 +1,6 @@ +#!/bin/sh + +SCRIPT=$(readlink -f "$0") +SCRIPTDIR=$(dirname "$SCRIPT") + +valgrind --leak-check=full --show-reachable=yes --show-leak-kinds=all --errors-for-leak-kinds=all --suppressions="${SCRIPTDIR}/htop_suppressions.valgrind" "${SCRIPTDIR}/../htop" diff --git a/solaris/Battery.c b/solaris/Battery.c deleted file mode 100644 index 6d6e94bd2..000000000 --- a/solaris/Battery.c +++ /dev/null @@ -1,8 +0,0 @@ - -#include "BatteryMeter.h" - -void Battery_getData(double* level, ACPresence* isOnAC) { - *level = -1; - *isOnAC = AC_ERROR; -} - diff --git a/solaris/Battery.h b/solaris/Battery.h deleted file mode 100644 index 8dc0cef6d..000000000 --- a/solaris/Battery.h +++ /dev/null @@ -1,9 +0,0 @@ -/* Do not edit this file. It was automatically generated. */ - -#ifndef HEADER_Battery -#define HEADER_Battery - -void Battery_getData(double* level, ACPresence* isOnAC); - - -#endif diff --git a/solaris/Platform.c b/solaris/Platform.c index a29fcb479..1a032758b 100644 --- a/solaris/Platform.c +++ b/solaris/Platform.c @@ -3,11 +3,12 @@ htop - solaris/Platform.c (C) 2014 Hisham H. Muhammad (C) 2015 David C. Hunt (C) 2017,2018 Guy M. Broome -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ #include "Platform.h" +#include "Macros.h" #include "Meter.h" #include "CPUMeter.h" #include "MemoryMeter.h" @@ -15,8 +16,12 @@ in the source distribution for its full text. #include "TasksMeter.h" #include "LoadAverageMeter.h" #include "ClockMeter.h" +#include "DateMeter.h" +#include "DateTimeMeter.h" #include "HostnameMeter.h" #include "UptimeMeter.h" +#include "zfs/ZfsArcMeter.h" +#include "zfs/ZfsCompressedArcMeter.h" #include "SolarisProcess.h" #include "SolarisProcessList.h" @@ -31,28 +36,6 @@ in the source distribution for its full text. #include #include -/*{ -#include "Action.h" -#include "BatteryMeter.h" -#include "SignalsPanel.h" -#include -#include -#include -#include - -#define kill(pid, signal) kill(pid / 1024, signal) - -extern ProcessFieldData Process_fields[]; -typedef struct var kvar_t; - -typedef struct envAccum_ { - size_t capacity; - size_t size; - size_t bytes; - char *env; -} envAccum; - -}*/ double plat_loadavg[3] = {0}; @@ -101,13 +84,15 @@ const SignalItem Platform_signals[] = { { .name = "41 SIGINFO", .number = 41 }, }; -const unsigned int Platform_numberOfSignals = sizeof(Platform_signals)/sizeof(SignalItem); +const unsigned int Platform_numberOfSignals = ARRAYSIZE(Platform_signals); ProcessField Platform_defaultFields[] = { PID, LWPID, USER, PRIORITY, NICE, M_SIZE, M_RESIDENT, STATE, PERCENT_CPU, PERCENT_MEM, TIME, COMM, 0 }; -MeterClass* Platform_meterTypes[] = { +const MeterClass* const Platform_meterTypes[] = { &CPUMeter_class, &ClockMeter_class, + &DateMeter_class, + &DateTimeMeter_class, &LoadAverageMeter_class, &LoadMeter_class, &MemoryMeter_class, @@ -118,10 +103,18 @@ MeterClass* Platform_meterTypes[] = { &UptimeMeter_class, &AllCPUsMeter_class, &AllCPUs2Meter_class, + &AllCPUs4Meter_class, + &AllCPUs8Meter_class, &LeftCPUsMeter_class, &RightCPUsMeter_class, &LeftCPUs2Meter_class, &RightCPUs2Meter_class, + &LeftCPUs4Meter_class, + &RightCPUs4Meter_class, + &LeftCPUs8Meter_class, + &RightCPUs8Meter_class, + &ZfsArcMeter_class, + &ZfsCompressedArcMeter_class, &BlankMeter_class, NULL }; @@ -136,8 +129,8 @@ extern char Process_pidFormat[20]; int Platform_getUptime() { int boot_time = 0; - int curr_time = time(NULL); - struct utmpx * ent; + int curr_time = time(NULL); + struct utmpx* ent; while (( ent = getutxent() )) { if ( !strcmp("system boot", ent->ut_line )) { @@ -147,7 +140,7 @@ int Platform_getUptime() { endutxent(); - return (curr_time-boot_time); + return (curr_time - boot_time); } void Platform_getLoadAverage(double* one, double* five, double* fifteen) { @@ -158,31 +151,37 @@ void Platform_getLoadAverage(double* one, double* five, double* fifteen) { } int Platform_getMaxPid() { - kstat_ctl_t *kc = NULL; - kstat_t *kshandle = NULL; - kvar_t *ksvar = NULL; + kstat_ctl_t* kc = NULL; + kstat_t* kshandle = NULL; + kvar_t* ksvar = NULL; int vproc = 32778; // Reasonable Solaris default kc = kstat_open(); - if (kc != NULL) { kshandle = kstat_lookup(kc,"unix",0,"var"); } - if (kshandle != NULL) { kstat_read(kc,kshandle,NULL); } + if (kc != NULL) { + kshandle = kstat_lookup(kc, "unix", 0, "var"); + } + if (kshandle != NULL) { + kstat_read(kc, kshandle, NULL); + } ksvar = kshandle->ks_data; if (ksvar->v_proc > 0 ) { vproc = ksvar->v_proc; } - if (kc != NULL) { kstat_close(kc); } - return vproc; + if (kc != NULL) { + kstat_close(kc); + } + return vproc; } double Platform_setCPUValues(Meter* this, int cpu) { - SolarisProcessList* spl = (SolarisProcessList*) this->pl; + const SolarisProcessList* spl = (const SolarisProcessList*) this->pl; int cpus = this->pl->cpuCount; - CPUData* cpuData = NULL; + const CPUData* cpuData = NULL; if (cpus == 1) { - // single CPU box has everything in spl->cpus[0] - cpuData = &(spl->cpus[0]); + // single CPU box has everything in spl->cpus[0] + cpuData = &(spl->cpus[0]); } else { - cpuData = &(spl->cpus[cpu]); + cpuData = &(spl->cpus[cpu]); } double percent; @@ -193,21 +192,23 @@ double Platform_setCPUValues(Meter* this, int cpu) { if (this->pl->settings->detailedCPUTime) { v[CPU_METER_KERNEL] = cpuData->systemPercent; v[CPU_METER_IRQ] = cpuData->irqPercent; - Meter_setItems(this, 4); - percent = v[0]+v[1]+v[2]+v[3]; + this->curItems = 4; + percent = v[0] + v[1] + v[2] + v[3]; } else { v[2] = cpuData->systemAllPercent; - Meter_setItems(this, 3); - percent = v[0]+v[1]+v[2]; + this->curItems = 3; + percent = v[0] + v[1] + v[2]; } - percent = CLAMP(percent, 0.0, 100.0); - if (isnan(percent)) percent = 0.0; + percent = isnan(percent) ? 0.0 : CLAMP(percent, 0.0, 100.0); + + v[CPU_METER_FREQUENCY] = NAN; + return percent; } void Platform_setMemoryValues(Meter* this) { - ProcessList* pl = (ProcessList*) this->pl; + const ProcessList* pl = this->pl; this->total = pl->totalMem; this->values[0] = pl->usedMem; this->values[1] = pl->buffersMem; @@ -215,43 +216,92 @@ void Platform_setMemoryValues(Meter* this) { } void Platform_setSwapValues(Meter* this) { - ProcessList* pl = (ProcessList*) this->pl; + const ProcessList* pl = this->pl; this->total = pl->totalSwap; this->values[0] = pl->usedSwap; } -static int Platform_buildenv(void *accum, struct ps_prochandle *Phandle, uintptr_t addr, const char *str) { - envAccum *accump = accum; +void Platform_setZfsArcValues(Meter* this) { + const SolarisProcessList* spl = (const SolarisProcessList*) this->pl; + + ZfsArcMeter_readStats(this, &(spl->zfs)); +} + +void Platform_setZfsCompressedArcValues(Meter* this) { + const SolarisProcessList* spl = (const SolarisProcessList*) this->pl; + + ZfsCompressedArcMeter_readStats(this, &(spl->zfs)); +} + +static int Platform_buildenv(void* accum, struct ps_prochandle* Phandle, uintptr_t addr, const char* str) { + envAccum* accump = accum; (void) Phandle; - (void) addr; + (void) addr; size_t thissz = strlen(str); - if ((thissz + 2) > (accump->capacity - accump->size)) + if ((thissz + 2) > (accump->capacity - accump->size)) { accump->env = xRealloc(accump->env, accump->capacity *= 2); - if ((thissz + 2) > (accump->capacity - accump->size)) + } + if ((thissz + 2) > (accump->capacity - accump->size)) { return 1; + } strlcpy( accump->env + accump->size, str, (accump->capacity - accump->size)); strncpy( accump->env + accump->size + thissz + 1, "\n", 1); accump->size = accump->size + thissz + 1; - return 0; + return 0; } char* Platform_getProcessEnv(pid_t pid) { envAccum envBuilder; pid_t realpid = pid / 1024; int graberr; - struct ps_prochandle *Phandle; - - if ((Phandle = Pgrab(realpid,PGRAB_RDONLY,&graberr)) == NULL) + struct ps_prochandle* Phandle; + + if ((Phandle = Pgrab(realpid, PGRAB_RDONLY, &graberr)) == NULL) { return "Unable to read process environment."; + } envBuilder.capacity = 4096; envBuilder.size = 0; envBuilder.env = xMalloc(envBuilder.capacity); - (void) Penv_iter(Phandle,Platform_buildenv,&envBuilder); + (void) Penv_iter(Phandle, Platform_buildenv, &envBuilder); Prelease(Phandle, 0); strncpy( envBuilder.env + envBuilder.size, "\0", 1); return envBuilder.env; } + +char* Platform_getInodeFilename(pid_t pid, ino_t inode) { + (void)pid; + (void)inode; + return NULL; +} + +FileLocks_ProcessData* Platform_getProcessLocks(pid_t pid) { + (void)pid; + return NULL; +} + +bool Platform_getDiskIO(DiskIOData* data) { + // TODO + (void)data; + return false; +} + +bool Platform_getNetworkIO(unsigned long int* bytesReceived, + unsigned long int* packetsReceived, + unsigned long int* bytesTransmitted, + unsigned long int* packetsTransmitted) { + // TODO + *bytesReceived = 0; + *packetsReceived = 0; + *bytesTransmitted = 0; + *packetsTransmitted = 0; + return false; +} + +void Platform_getBattery(double* level, ACPresence* isOnAC) { + *level = NAN; + *isOnAC = AC_ERROR; +} diff --git a/solaris/Platform.h b/solaris/Platform.h index f961b913b..051a64dad 100644 --- a/solaris/Platform.h +++ b/solaris/Platform.h @@ -1,5 +1,3 @@ -/* Do not edit this file. It was automatically generated. */ - #ifndef HEADER_Platform #define HEADER_Platform /* @@ -7,17 +5,23 @@ htop - solaris/Platform.h (C) 2014 Hisham H. Muhammad (C) 2015 David C. Hunt (C) 2017,2018 Guy M. Broome -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ -#include "Action.h" -#include "BatteryMeter.h" -#include "SignalsPanel.h" +#include #include +#include #include #include -#include +#include + +#include "Action.h" +#include "BatteryMeter.h" +#include "DiskIOMeter.h" +#include "ProcessLocksScreen.h" +#include "SignalsPanel.h" + #define kill(pid, signal) kill(pid / 1024, signal) @@ -27,11 +31,10 @@ typedef struct var kvar_t; typedef struct envAccum_ { size_t capacity; size_t size; - size_t bytes; - char *env; + size_t bytes; + char* env; } envAccum; - extern double plat_loadavg[3]; extern const SignalItem Platform_signals[]; @@ -40,7 +43,7 @@ extern const unsigned int Platform_numberOfSignals; extern ProcessField Platform_defaultFields[]; -extern MeterClass* Platform_meterTypes[]; +extern const MeterClass* const Platform_meterTypes[]; void Platform_setBindings(Htop_Action* keys); @@ -48,11 +51,11 @@ extern int Platform_numberOfFields; extern char Process_pidFormat[20]; -int Platform_getUptime(); +int Platform_getUptime(void); void Platform_getLoadAverage(double* one, double* five, double* fifteen); -int Platform_getMaxPid(); +int Platform_getMaxPid(void); double Platform_setCPUValues(Meter* this, int cpu); @@ -60,6 +63,23 @@ void Platform_setMemoryValues(Meter* this); void Platform_setSwapValues(Meter* this); +void Platform_setZfsArcValues(Meter* this); + +void Platform_setZfsCompressedArcValues(Meter* this); + char* Platform_getProcessEnv(pid_t pid); +char* Platform_getInodeFilename(pid_t pid, ino_t inode); + +FileLocks_ProcessData* Platform_getProcessLocks(pid_t pid); + +bool Platform_getDiskIO(DiskIOData* data); + +bool Platform_getNetworkIO(unsigned long int* bytesReceived, + unsigned long int* packetsReceived, + unsigned long int* bytesTransmitted, + unsigned long int* packetsTransmitted); + +void Platform_getBattery(double* level, ACPresence* isOnAC); + #endif diff --git a/solaris/SolarisCRT.c b/solaris/SolarisCRT.c deleted file mode 100644 index d7f8f52e4..000000000 --- a/solaris/SolarisCRT.c +++ /dev/null @@ -1,32 +0,0 @@ -/* -htop - SolarisCRT.c -(C) 2014 Hisham H. Muhammad -(C) 2018 Guy M. Broome -Released under the GNU GPL, see the COPYING file -in the source distribution for its full text. -*/ - -#include "config.h" -#include "CRT.h" -#include -#include -#ifdef HAVE_EXECINFO_H -#include -#endif - -void CRT_handleSIGSEGV(int sgn) { - (void) sgn; - CRT_done(); - fprintf(stderr, "\n\nhtop " VERSION " aborting. Please report bug at http://hisham.hm/htop\n"); - #ifdef HAVE_EXECINFO_H - size_t size = backtrace(backtraceArray, sizeof(backtraceArray) / sizeof(void *)); - fprintf(stderr, "\n Please include in your report the following backtrace: \n"); - backtrace_symbols_fd(backtraceArray, size, 2); - fprintf(stderr, "\nAdditionally, in order to make the above backtrace useful,"); - fprintf(stderr, "\nplease also run the following command to generate a disassembly of your binary:"); - fprintf(stderr, "\n\n objdump -d `which htop` > ~/htop.objdump"); - fprintf(stderr, "\n\nand then attach the file ~/htop.objdump to your bug report."); - fprintf(stderr, "\n\nThank you for helping to improve htop!\n\n"); - #endif - abort(); -} diff --git a/solaris/SolarisCRT.h b/solaris/SolarisCRT.h deleted file mode 100644 index 6ab6dfcac..000000000 --- a/solaris/SolarisCRT.h +++ /dev/null @@ -1,18 +0,0 @@ -/* Do not edit this file. It was automatically generated. */ - -#ifndef HEADER_SolarisCRT -#define HEADER_SolarisCRT -/* -htop - SolarisCRT.h -(C) 2014 Hisham H. Muhammad -(C) 2018 Guy M. Broome -Released under the GNU GPL, see the COPYING file -in the source distribution for its full text. -*/ - -#ifdef HAVE_EXECINFO_H -#endif - -void CRT_handleSIGSEGV(int sgn); - -#endif diff --git a/solaris/SolarisProcess.c b/solaris/SolarisProcess.c index 31f488ef6..c11c6de8a 100644 --- a/solaris/SolarisProcess.c +++ b/solaris/SolarisProcess.c @@ -2,7 +2,7 @@ htop - SolarisProcess.c (C) 2015 Hisham H. Muhammad (C) 2017,2018 Guy M. Broome -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ @@ -17,59 +17,15 @@ in the source distribution for its full text. #include #include -/*{ -#include "Settings.h" -#include -#include -#include -typedef enum SolarisProcessFields { - // Add platform-specific fields here, with ids >= 100 - ZONEID = 100, - ZONE = 101, - PROJID = 102, - TASKID = 103, - POOLID = 104, - CONTID = 105, - LWPID = 106, - LAST_PROCESSFIELD = 107, -} SolarisProcessField; - - -typedef struct SolarisProcess_ { - Process super; - int kernel; - zoneid_t zoneid; - char* zname; - taskid_t taskid; - projid_t projid; - poolid_t poolid; - ctid_t contid; - bool is_lwp; - pid_t realpid; - pid_t realppid; - pid_t lwpid; -} SolarisProcess; - - -#ifndef Process_isKernelThread -#define Process_isKernelThread(_process) (_process->kernel == 1) -#endif - -#ifndef Process_isUserlandThread -#define Process_isUserlandThread(_process) (_process->pid != _process->tgid) -#endif - -}*/ - -ProcessClass SolarisProcess_class = { +const ProcessClass SolarisProcess_class = { .super = { .extends = Class(Process), .display = Process_display, .delete = Process_delete, .compare = SolarisProcess_compare }, - .writeField = (Process_WriteField) SolarisProcess_writeField, + .writeField = SolarisProcess_writeField, }; ProcessFieldData Process_fields[] = { @@ -90,8 +46,9 @@ ProcessFieldData Process_fields[] = { [PROCESSOR] = { .name = "PROCESSOR", .title = "CPU ", .description = "Id of the CPU the process last executed on", .flags = 0, }, [M_SIZE] = { .name = "M_SIZE", .title = " VIRT ", .description = "Total program size in virtual memory", .flags = 0, }, [M_RESIDENT] = { .name = "M_RESIDENT", .title = " RES ", .description = "Resident set size, size of the text and data sections, plus stack usage", .flags = 0, }, - [ST_UID] = { .name = "ST_UID", .title = " UID ", .description = "User ID of the process owner", .flags = 0, }, + [ST_UID] = { .name = "ST_UID", .title = " UID ", .description = "User ID of the process owner", .flags = 0, }, [PERCENT_CPU] = { .name = "PERCENT_CPU", .title = "CPU% ", .description = "Percentage of the CPU time the process used in the last sampling", .flags = 0, }, + [PERCENT_NORM_CPU] = { .name = "PERCENT_NORM_CPU", .title = "NCPU%", .description = "Normalized percentage of the CPU time the process used in the last sampling (normalized by cpu count)", .flags = 0, }, [PERCENT_MEM] = { .name = "PERCENT_MEM", .title = "MEM% ", .description = "Percentage of the memory the process is using, based on resident memory size", .flags = 0, }, [USER] = { .name = "USER", .title = "USER ", .description = "Username of the process owner (or user ID if name cannot be determined)", .flags = 0, }, [TIME] = { .name = "TIME", .title = " TIME+ ", .description = "Total time the process has spent in user and system time", .flags = 0, }, @@ -123,11 +80,11 @@ ProcessPidColumn Process_pidColumns[] = { { .id = 0, .label = NULL }, }; -SolarisProcess* SolarisProcess_new(Settings* settings) { +Process* SolarisProcess_new(const Settings* settings) { SolarisProcess* this = xCalloc(1, sizeof(SolarisProcess)); Object_setClass(this, Class(SolarisProcess)); Process_init(&this->super, settings); - return this; + return &this->super; } void Process_delete(Object* cast) { @@ -137,8 +94,8 @@ void Process_delete(Object* cast) { free(sp); } -void SolarisProcess_writeField(Process* this, RichString* str, ProcessField field) { - SolarisProcess* sp = (SolarisProcess*) this; +void SolarisProcess_writeField(const Process* this, RichString* str, ProcessField field) { + const SolarisProcess* sp = (const SolarisProcess*) this; char buffer[256]; buffer[255] = '\0'; int attr = CRT_colors[DEFAULT_COLOR]; int n = sizeof(buffer) - 1; @@ -149,14 +106,7 @@ void SolarisProcess_writeField(Process* this, RichString* str, ProcessField fiel case TASKID: xSnprintf(buffer, n, Process_pidFormat, sp->taskid); break; case POOLID: xSnprintf(buffer, n, Process_pidFormat, sp->poolid); break; case CONTID: xSnprintf(buffer, n, Process_pidFormat, sp->contid); break; - case ZONE:{ - xSnprintf(buffer, n, "%-*s ", ZONENAME_MAX/4, sp->zname); break; - if (buffer[ZONENAME_MAX/4] != '\0') { - buffer[ZONENAME_MAX/4] = ' '; - buffer[(ZONENAME_MAX/4)+1] = '\0'; - } - break; - } + case ZONE: xSnprintf(buffer, n, "%-*s ", ZONENAME_MAX/4, sp->zname); break; case PID: xSnprintf(buffer, n, Process_pidFormat, sp->realpid); break; case PPID: xSnprintf(buffer, n, Process_pidFormat, sp->realppid); break; case LWPID: xSnprintf(buffer, n, Process_pidFormat, sp->lwpid); break; @@ -168,41 +118,43 @@ void SolarisProcess_writeField(Process* this, RichString* str, ProcessField fiel } long SolarisProcess_compare(const void* v1, const void* v2) { - SolarisProcess *p1, *p2; - Settings* settings = ((Process*)v1)->settings; + const SolarisProcess *p1, *p2; + const Settings* settings = ((const Process*)v1)->settings; + if (settings->direction == 1) { - p1 = (SolarisProcess*)v1; - p2 = (SolarisProcess*)v2; + p1 = (const SolarisProcess*)v1; + p2 = (const SolarisProcess*)v2; } else { - p2 = (SolarisProcess*)v1; - p1 = (SolarisProcess*)v2; + p2 = (const SolarisProcess*)v1; + p1 = (const SolarisProcess*)v2; } + switch ((int) settings->sortKey) { case ZONEID: - return (p1->zoneid - p2->zoneid); + return SPACESHIP_NUMBER(p1->zoneid, p2->zoneid); case PROJID: - return (p1->projid - p2->projid); + return SPACESHIP_NUMBER(p1->projid, p2->projid); case TASKID: - return (p1->taskid - p2->taskid); + return SPACESHIP_NUMBER(p1->taskid, p2->taskid); case POOLID: - return (p1->poolid - p2->poolid); + return SPACESHIP_NUMBER(p1->poolid, p2->poolid); case CONTID: - return (p1->contid - p2->contid); + return SPACESHIP_NUMBER(p1->contid, p2->contid); case ZONE: return strcmp(p1->zname ? p1->zname : "global", p2->zname ? p2->zname : "global"); case PID: - return (p1->realpid - p2->realpid); + return SPACESHIP_NUMBER(p1->realpid, p2->realpid); case PPID: - return (p1->realppid - p2->realppid); + return SPACESHIP_NUMBER(p1->realppid, p2->realppid); case LWPID: - return (p1->lwpid - p2->lwpid); + return SPACESHIP_NUMBER(p1->lwpid, p2->lwpid); default: return Process_compare(v1, v2); } } -bool Process_isThread(Process* this) { - SolarisProcess* fp = (SolarisProcess*) this; +bool Process_isThread(const Process* this) { + const SolarisProcess* fp = (const SolarisProcess*) this; if (fp->kernel == 1 ) { return 1; diff --git a/solaris/SolarisProcess.h b/solaris/SolarisProcess.h index 1b3492a77..4756634dc 100644 --- a/solaris/SolarisProcess.h +++ b/solaris/SolarisProcess.h @@ -1,12 +1,10 @@ -/* Do not edit this file. It was automatically generated. */ - #ifndef HEADER_SolarisProcess #define HEADER_SolarisProcess /* htop - SolarisProcess.h (C) 2015 Hisham H. Muhammad (C) 2017,2018 Guy M. Broome -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ @@ -15,7 +13,7 @@ in the source distribution for its full text. #include #include -typedef enum SolarisProcessFields { +typedef enum SolarisProcessField_ { // Add platform-specific fields here, with ids >= 100 ZONEID = 100, ZONE = 101, @@ -27,7 +25,6 @@ typedef enum SolarisProcessFields { LAST_PROCESSFIELD = 107, } SolarisProcessField; - typedef struct SolarisProcess_ { Process super; int kernel; @@ -43,30 +40,24 @@ typedef struct SolarisProcess_ { pid_t lwpid; } SolarisProcess; - -#ifndef Process_isKernelThread #define Process_isKernelThread(_process) (_process->kernel == 1) -#endif -#ifndef Process_isUserlandThread #define Process_isUserlandThread(_process) (_process->pid != _process->tgid) -#endif - -extern ProcessClass SolarisProcess_class; +extern const ProcessClass SolarisProcess_class; extern ProcessFieldData Process_fields[]; extern ProcessPidColumn Process_pidColumns[]; -SolarisProcess* SolarisProcess_new(Settings* settings); +Process* SolarisProcess_new(const Settings* settings); void Process_delete(Object* cast); -void SolarisProcess_writeField(Process* this, RichString* str, ProcessField field); +void SolarisProcess_writeField(const Process* this, RichString* str, ProcessField field); long SolarisProcess_compare(const void* v1, const void* v2); -bool Process_isThread(Process* this); +bool Process_isThread(const Process* this); #endif diff --git a/solaris/SolarisProcessList.c b/solaris/SolarisProcessList.c index 2c681852b..49aeb24c5 100644 --- a/solaris/SolarisProcessList.c +++ b/solaris/SolarisProcessList.c @@ -2,7 +2,7 @@ htop - SolarisProcessList.c (C) 2014 Hisham H. Muhammad (C) 2017,2018 Guy M. Broome -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ @@ -23,59 +23,30 @@ in the source distribution for its full text. #include #include -#define MAXCMDLINE 255 +#include "CRT.h" + -/*{ - -#include -#include -#include -#include -#include -#include -#include - -#define ZONE_ERRMSGLEN 1024 -char zone_errmsg[ZONE_ERRMSGLEN]; - -typedef struct CPUData_ { - double userPercent; - double nicePercent; - double systemPercent; - double irqPercent; - double idlePercent; - double systemAllPercent; - uint64_t luser; - uint64_t lkrnl; - uint64_t lintr; - uint64_t lidle; -} CPUData; - -typedef struct SolarisProcessList_ { - ProcessList super; - kstat_ctl_t* kd; - CPUData* cpus; -} SolarisProcessList; - -}*/ +#define MAXCMDLINE 255 char* SolarisProcessList_readZoneName(kstat_ctl_t* kd, SolarisProcess* sproc) { - char* zname; - if ( sproc->zoneid == 0 ) { - zname = xStrdup("global "); - } else if ( kd == NULL ) { - zname = xStrdup("unknown "); - } else { - kstat_t* ks = kstat_lookup( kd, "zones", sproc->zoneid, NULL ); - zname = xStrdup(ks->ks_name); - } - return zname; + char* zname; + + if ( sproc->zoneid == 0 ) { + zname = xStrdup(GZONE); + } else if ( kd == NULL ) { + zname = xStrdup(UZONE); + } else { + kstat_t* ks = kstat_lookup( kd, "zones", sproc->zoneid, NULL ); + zname = xStrdup(ks == NULL ? UZONE : ks->ks_name); + } + + return zname; } -ProcessList* ProcessList_new(UsersTable* usersTable, Hashtable* pidWhiteList, uid_t userId) { +ProcessList* ProcessList_new(UsersTable* usersTable, Hashtable* pidMatchList, uid_t userId) { SolarisProcessList* spl = xCalloc(1, sizeof(SolarisProcessList)); ProcessList* pl = (ProcessList*) spl; - ProcessList_init(pl, Class(SolarisProcess), usersTable, pidWhiteList, userId); + ProcessList_init(pl, Class(SolarisProcess), usersTable, pidMatchList, userId); spl->kd = kstat_open(); @@ -93,12 +64,12 @@ ProcessList* ProcessList_new(UsersTable* usersTable, Hashtable* pidWhiteList, ui static inline void SolarisProcessList_scanCPUTime(ProcessList* pl) { const SolarisProcessList* spl = (SolarisProcessList*) pl; int cpus = pl->cpuCount; - kstat_t *cpuinfo = NULL; + kstat_t* cpuinfo = NULL; int kchain = 0; - kstat_named_t *idletime = NULL; - kstat_named_t *intrtime = NULL; - kstat_named_t *krnltime = NULL; - kstat_named_t *usertime = NULL; + kstat_named_t* idletime = NULL; + kstat_named_t* intrtime = NULL; + kstat_named_t* krnltime = NULL; + kstat_named_t* usertime = NULL; double idlebuf = 0; double intrbuf = 0; double krnlbuf = 0; @@ -109,26 +80,30 @@ static inline void SolarisProcessList_scanCPUTime(ProcessList* pl) { assert(cpus > 0); if (cpus > 1) { - // Store values for the stats loop one extra element up in the array - // to leave room for the average to be calculated afterwards - arrskip++; + // Store values for the stats loop one extra element up in the array + // to leave room for the average to be calculated afterwards + arrskip++; } // Calculate per-CPU statistics first for (int i = 0; i < cpus; i++) { - if (spl->kd != NULL) { cpuinfo = kstat_lookup(spl->kd,"cpu",i,"sys"); } - if (cpuinfo != NULL) { kchain = kstat_read(spl->kd,cpuinfo,NULL); } + if (spl->kd != NULL) { + cpuinfo = kstat_lookup(spl->kd, "cpu", i, "sys"); + } + if (cpuinfo != NULL) { + kchain = kstat_read(spl->kd, cpuinfo, NULL); + } if (kchain != -1 ) { - idletime = kstat_data_lookup(cpuinfo,"cpu_nsec_idle"); - intrtime = kstat_data_lookup(cpuinfo,"cpu_nsec_intr"); - krnltime = kstat_data_lookup(cpuinfo,"cpu_nsec_kernel"); - usertime = kstat_data_lookup(cpuinfo,"cpu_nsec_user"); + idletime = kstat_data_lookup(cpuinfo, "cpu_nsec_idle"); + intrtime = kstat_data_lookup(cpuinfo, "cpu_nsec_intr"); + krnltime = kstat_data_lookup(cpuinfo, "cpu_nsec_kernel"); + usertime = kstat_data_lookup(cpuinfo, "cpu_nsec_user"); } assert( (idletime != NULL) && (intrtime != NULL) && (krnltime != NULL) && (usertime != NULL) ); - CPUData* cpuData = &(spl->cpus[i+arrskip]); + CPUData* cpuData = &(spl->cpus[i + arrskip]); totaltime = (idletime->value.ui64 - cpuData->lidle) + (intrtime->value.ui64 - cpuData->lintr) + (krnltime->value.ui64 - cpuData->lkrnl) @@ -153,7 +128,7 @@ static inline void SolarisProcessList_scanCPUTime(ProcessList* pl) { idlebuf += cpuData->idlePercent; } } - + if (cpus > 1) { CPUData* cpuData = &(spl->cpus[0]); cpuData->userPercent = userbuf / cpus; @@ -167,47 +142,60 @@ static inline void SolarisProcessList_scanCPUTime(ProcessList* pl) { static inline void SolarisProcessList_scanMemoryInfo(ProcessList* pl) { SolarisProcessList* spl = (SolarisProcessList*) pl; - kstat_t *meminfo = NULL; + static kstat_t *meminfo = NULL; int ksrphyserr = -1; kstat_named_t *totalmem_pgs = NULL; - kstat_named_t *lockedmem_pgs = NULL; + kstat_named_t *freemem_pgs = NULL; kstat_named_t *pages = NULL; struct swaptable *sl = NULL; struct swapent *swapdev = NULL; uint64_t totalswap = 0; uint64_t totalfree = 0; int nswap = 0; - char *spath = NULL; + char *spath = NULL; char *spathbase = NULL; // Part 1 - physical memory - if (spl->kd != NULL) { meminfo = kstat_lookup(spl->kd,"unix",0,"system_pages"); } - if (meminfo != NULL) { ksrphyserr = kstat_read(spl->kd,meminfo,NULL); } + if (spl->kd != NULL && meminfo == NULL) { + // Look up the kstat chain just one, it never changes + meminfo = kstat_lookup(spl->kd, "unix", 0, "system_pages"); + } + if (meminfo != NULL) { + ksrphyserr = kstat_read(spl->kd, meminfo, NULL); + } if (ksrphyserr != -1) { - totalmem_pgs = kstat_data_lookup( meminfo, "physmem" ); - lockedmem_pgs = kstat_data_lookup( meminfo, "pageslocked" ); - pages = kstat_data_lookup( meminfo, "pagestotal" ); + totalmem_pgs = kstat_data_lookup(meminfo, "physmem"); + freemem_pgs = kstat_data_lookup(meminfo, "freemem"); + pages = kstat_data_lookup(meminfo, "pagestotal"); - pl->totalMem = totalmem_pgs->value.ui64 * PAGE_SIZE_KB; - pl->usedMem = lockedmem_pgs->value.ui64 * PAGE_SIZE_KB; + pl->totalMem = totalmem_pgs->value.ui64 * CRT_pageSizeKB; + if (pl->totalMem > freemem_pgs->value.ui64 * CRT_pageSizeKB) { + pl->usedMem = pl->totalMem - freemem_pgs->value.ui64 * CRT_pageSizeKB; + } else { + pl->usedMem = 0; // This can happen in non-global zone (in theory) + } // Not sure how to implement this on Solaris - suggestions welcome! - pl->cachedMem = 0; + pl->cachedMem = 0; // Not really "buffers" but the best Solaris analogue that I can find to // "memory in use but not by programs or the kernel itself" - pl->buffersMem = (totalmem_pgs->value.ui64 - pages->value.ui64) * PAGE_SIZE_KB; - } else { + pl->buffersMem = (totalmem_pgs->value.ui64 - pages->value.ui64) * CRT_pageSizeKB; + } else { // Fall back to basic sysconf if kstat isn't working - pl->totalMem = sysconf(_SC_PHYS_PAGES) * PAGE_SIZE; + pl->totalMem = sysconf(_SC_PHYS_PAGES) * CRT_pageSize; pl->buffersMem = 0; pl->cachedMem = 0; - pl->usedMem = pl->totalMem - (sysconf(_SC_AVPHYS_PAGES) * PAGE_SIZE); + pl->usedMem = pl->totalMem - (sysconf(_SC_AVPHYS_PAGES) * CRT_pageSize); } - + // Part 2 - swap nswap = swapctl(SC_GETNSWP, NULL); - if (nswap > 0) { sl = xMalloc((nswap * sizeof(swapent_t)) + sizeof(int)); } - if (sl != NULL) { spathbase = xMalloc( nswap * MAXPATHLEN ); } - if (spathbase != NULL) { + if (nswap > 0) { + sl = xMalloc((nswap * sizeof(swapent_t)) + sizeof(int)); + } + if (sl != NULL) { + spathbase = xMalloc( nswap * MAXPATHLEN ); + } + if (spathbase != NULL) { spath = spathbase; swapdev = sl->swt_ent; for (int i = 0; i < nswap; i++, swapdev++) { @@ -217,7 +205,7 @@ static inline void SolarisProcessList_scanMemoryInfo(ProcessList* pl) { sl->swt_n = nswap; } nswap = swapctl(SC_LIST, sl); - if (nswap > 0) { + if (nswap > 0) { swapdev = sl->swt_ent; for (int i = 0; i < nswap; i++, swapdev++) { totalswap += swapdev->ste_pages; @@ -226,15 +214,64 @@ static inline void SolarisProcessList_scanMemoryInfo(ProcessList* pl) { } free(spathbase); free(sl); - pl->totalSwap = totalswap * PAGE_SIZE_KB; - pl->usedSwap = pl->totalSwap - (totalfree * PAGE_SIZE_KB); + pl->totalSwap = totalswap * CRT_pageSizeKB; + pl->usedSwap = pl->totalSwap - (totalfree * CRT_pageSizeKB); +} + +static inline void SolarisProcessList_scanZfsArcstats(ProcessList* pl) { + SolarisProcessList* spl = (SolarisProcessList*) pl; + kstat_t *arcstats = NULL; + int ksrphyserr = -1; + kstat_named_t *cur_kstat = NULL; + + if (spl->kd != NULL) { + arcstats = kstat_lookup(spl->kd, "zfs", 0, "arcstats"); + } + if (arcstats != NULL) { + ksrphyserr = kstat_read(spl->kd, arcstats, NULL); + } + if (ksrphyserr != -1) { + cur_kstat = kstat_data_lookup( arcstats, "size" ); + spl->zfs.size = cur_kstat->value.ui64 / 1024; + spl->zfs.enabled = spl->zfs.size > 0 ? 1 : 0; + + cur_kstat = kstat_data_lookup( arcstats, "c_max" ); + spl->zfs.max = cur_kstat->value.ui64 / 1024; + + cur_kstat = kstat_data_lookup( arcstats, "mfu_size" ); + spl->zfs.MFU = cur_kstat != NULL ? cur_kstat->value.ui64 / 1024 : 0; + + cur_kstat = kstat_data_lookup( arcstats, "mru_size" ); + spl->zfs.MRU = cur_kstat != NULL ? cur_kstat->value.ui64 / 1024 : 0; + + cur_kstat = kstat_data_lookup( arcstats, "anon_size" ); + spl->zfs.anon = cur_kstat != NULL ? cur_kstat->value.ui64 / 1024 : 0; + + cur_kstat = kstat_data_lookup( arcstats, "hdr_size" ); + spl->zfs.header = cur_kstat != NULL ? cur_kstat->value.ui64 / 1024 : 0; + + cur_kstat = kstat_data_lookup( arcstats, "other_size" ); + spl->zfs.other = cur_kstat != NULL ? cur_kstat->value.ui64 / 1024 : 0; + + if ((cur_kstat = kstat_data_lookup( arcstats, "compressed_size" )) != NULL) { + spl->zfs.compressed = cur_kstat->value.ui64 / 1024; + spl->zfs.isCompressed = 1; + + cur_kstat = kstat_data_lookup( arcstats, "uncompressed_size" ); + spl->zfs.uncompressed = cur_kstat->value.ui64 / 1024; + } else { + spl->zfs.isCompressed = 0; + } + } } void ProcessList_delete(ProcessList* pl) { SolarisProcessList* spl = (SolarisProcessList*) pl; ProcessList_done(pl); free(spl->cpus); - if (spl->kd) kstat_close(spl->kd); + if (spl->kd) { + kstat_close(spl->kd); + } free(spl); } @@ -242,31 +279,30 @@ void ProcessList_delete(ProcessList* pl) { * and MUST conform to the appropriate definition in order * to work. See libproc(3LIB) on a Solaris or Illumos * system for more info. - */ + */ -int SolarisProcessList_walkproc(psinfo_t *_psinfo, lwpsinfo_t *_lwpsinfo, void *listptr) { - struct timeval tv; - struct tm date; +int SolarisProcessList_walkproc(psinfo_t* _psinfo, lwpsinfo_t* _lwpsinfo, void* listptr) { bool preExisting; pid_t getpid; // Setup process list - ProcessList *pl = (ProcessList*) listptr; - SolarisProcessList *spl = (SolarisProcessList*) listptr; + ProcessList* pl = (ProcessList*) listptr; + SolarisProcessList* spl = (SolarisProcessList*) listptr; id_t lwpid_real = _lwpsinfo->pr_lwpid; - if (lwpid_real > 1023) return 0; + if (lwpid_real > 1023) { + return 0; + } + pid_t lwpid = (_psinfo->pr_pid * 1024) + lwpid_real; bool onMasterLWP = (_lwpsinfo->pr_lwpid == _psinfo->pr_lwp.pr_lwpid); if (onMasterLWP) { getpid = _psinfo->pr_pid * 1024; } else { getpid = lwpid; - } - Process *proc = ProcessList_getProcess(pl, getpid, &preExisting, (Process_New) SolarisProcess_new); - SolarisProcess *sproc = (SolarisProcess*) proc; - - gettimeofday(&tv, NULL); + } + Process* proc = ProcessList_getProcess(pl, getpid, &preExisting, SolarisProcess_new); + SolarisProcess* sproc = (SolarisProcess*) proc; // Common code pass 1 proc->show = false; @@ -275,28 +311,28 @@ int SolarisProcessList_walkproc(psinfo_t *_psinfo, lwpsinfo_t *_lwpsinfo, void * sproc->poolid = _psinfo->pr_poolid; sproc->contid = _psinfo->pr_contract; proc->priority = _lwpsinfo->pr_pri; - proc->nice = _lwpsinfo->pr_nice; + proc->nice = _lwpsinfo->pr_nice - NZERO; proc->processor = _lwpsinfo->pr_onpro; proc->state = _lwpsinfo->pr_sname; // NOTE: This 'percentage' is a 16-bit BINARY FRACTIONS where 1.0 = 0x8000 // Source: https://docs.oracle.com/cd/E19253-01/816-5174/proc-4/index.html // (accessed on 18 November 2017) - proc->percent_mem = ((uint16_t)_psinfo->pr_pctmem/(double)32768)*(double)100.0; + proc->percent_mem = ((uint16_t)_psinfo->pr_pctmem / (double)32768) * (double)100.0; proc->st_uid = _psinfo->pr_euid; proc->pgrp = _psinfo->pr_pgid; proc->nlwp = _psinfo->pr_nlwp; proc->tty_nr = _psinfo->pr_ttydev; - proc->m_resident = _psinfo->pr_rssize/PAGE_SIZE_KB; - proc->m_size = _psinfo->pr_size/PAGE_SIZE_KB; + proc->m_resident = _psinfo->pr_rssize / CRT_pageSizeKB; + proc->m_size = _psinfo->pr_size / CRT_pageSizeKB; if (!preExisting) { sproc->realpid = _psinfo->pr_pid; sproc->lwpid = lwpid_real; sproc->zoneid = _psinfo->pr_zoneid; - sproc->zname = SolarisProcessList_readZoneName(spl->kd,sproc); + sproc->zname = SolarisProcessList_readZoneName(spl->kd, sproc); proc->user = UsersTable_getRef(pl->usersTable, proc->st_uid); proc->comm = xStrdup(_psinfo->pr_fname); - proc->commLen = strnlen(_psinfo->pr_fname,PRFNSZ); + proc->commLen = strnlen(_psinfo->pr_fname, PRFNSZ); } // End common code pass 1 @@ -306,9 +342,9 @@ int SolarisProcessList_walkproc(psinfo_t *_psinfo, lwpsinfo_t *_lwpsinfo, void * proc->tgid = (_psinfo->pr_ppid * 1024); sproc->realppid = _psinfo->pr_ppid; // See note above (in common section) about this BINARY FRACTION - proc->percent_cpu = ((uint16_t)_psinfo->pr_pctcpu/(double)32768)*(double)100.0; + proc->percent_cpu = ((uint16_t)_psinfo->pr_pctcpu / (double)32768) * (double)100.0; proc->time = _psinfo->pr_time.tv_sec; - if(!preExisting) { // Tasks done only for NEW processes + if (!preExisting) { // Tasks done only for NEW processes sproc->is_lwp = false; proc->starttime_ctime = _psinfo->pr_start.tv_sec; } @@ -316,23 +352,27 @@ int SolarisProcessList_walkproc(psinfo_t *_psinfo, lwpsinfo_t *_lwpsinfo, void * // Update proc and thread counts based on settings if (sproc->kernel && !pl->settings->hideKernelThreads) { pl->kernelThreads += proc->nlwp; - pl->totalTasks += proc->nlwp+1; - if (proc->state == 'O') pl->runningTasks++; + pl->totalTasks += proc->nlwp + 1; + if (proc->state == 'O') { + pl->runningTasks++; + } } else if (!sproc->kernel) { - if (proc->state == 'O') pl->runningTasks++; + if (proc->state == 'O') { + pl->runningTasks++; + } if (pl->settings->hideUserlandThreads) { pl->totalTasks++; } else { pl->userlandThreads += proc->nlwp; - pl->totalTasks += proc->nlwp+1; + pl->totalTasks += proc->nlwp + 1; } } proc->show = !(pl->settings->hideKernelThreads && sproc->kernel); } else { // We are not in the master LWP, so jump to the LWP handling code - proc->percent_cpu = ((uint16_t)_lwpsinfo->pr_pctcpu/(double)32768)*(double)100.0; + proc->percent_cpu = ((uint16_t)_lwpsinfo->pr_pctcpu / (double)32768) * (double)100.0; proc->time = _lwpsinfo->pr_time.tv_sec; if (!preExisting) { // Tasks done only for NEW LWPs - sproc->is_lwp = true; + sproc->is_lwp = true; proc->basenameOffset = -1; proc->ppid = _psinfo->pr_pid * 1024; proc->tgid = _psinfo->pr_pid * 1024; @@ -341,8 +381,12 @@ int SolarisProcessList_walkproc(psinfo_t *_psinfo, lwpsinfo_t *_lwpsinfo, void * } // Top-level process only gets this for the representative LWP - if (sproc->kernel && !pl->settings->hideKernelThreads) proc->show = true; - if (!sproc->kernel && !pl->settings->hideUserlandThreads) proc->show = true; + if (sproc->kernel && !pl->settings->hideKernelThreads) { + proc->show = true; + } + if (!sproc->kernel && !pl->settings->hideUserlandThreads) { + proc->show = true; + } } // Top-level LWP or subordinate LWP // Common code pass 2 @@ -353,8 +397,7 @@ int SolarisProcessList_walkproc(psinfo_t *_psinfo, lwpsinfo_t *_lwpsinfo, void * } else { sproc->kernel = false; } - (void) localtime_r((time_t*) &proc->starttime_ctime, &date); - strftime(proc->starttime_show, 7, ((proc->starttime_ctime > tv.tv_sec - 86400) ? "%R " : "%b%d "), &date); + Process_fillStarttimeBuffer(proc); ProcessList_add(pl, proc); } proc->updated = true; @@ -364,10 +407,16 @@ int SolarisProcessList_walkproc(psinfo_t *_psinfo, lwpsinfo_t *_lwpsinfo, void * return 0; } -void ProcessList_goThroughEntries(ProcessList* this) { - SolarisProcessList_scanCPUTime(this); - SolarisProcessList_scanMemoryInfo(this); - this->kernelThreads = 1; - proc_walk(&SolarisProcessList_walkproc, this, PR_WALK_LWP); -} +void ProcessList_goThroughEntries(ProcessList* super, bool pauseProcessUpdate) { + SolarisProcessList_scanCPUTime(super); + SolarisProcessList_scanMemoryInfo(super); + SolarisProcessList_scanZfsArcstats(super); + // in pause mode only gather global data for meters (CPU/memory/...) + if (pauseProcessUpdate) { + return; + } + + super->kernelThreads = 1; + proc_walk(&SolarisProcessList_walkproc, super, PR_WALK_LWP); +} diff --git a/solaris/SolarisProcessList.h b/solaris/SolarisProcessList.h index a5f2fbc25..f800d9da9 100644 --- a/solaris/SolarisProcessList.h +++ b/solaris/SolarisProcessList.h @@ -1,17 +1,19 @@ -/* Do not edit this file. It was automatically generated. */ - #ifndef HEADER_SolarisProcessList #define HEADER_SolarisProcessList /* htop - SolarisProcessList.h (C) 2014 Hisham H. Muhammad (C) 2017,2018 Guy M. Broome -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ #define MAXCMDLINE 255 +#define GZONE "global " +#define UZONE "unknown " + +#include "zfs/ZfsArcStats.h" #include #include @@ -22,7 +24,7 @@ in the source distribution for its full text. #include #define ZONE_ERRMSGLEN 1024 -char zone_errmsg[ZONE_ERRMSGLEN]; +extern char zone_errmsg[ZONE_ERRMSGLEN]; typedef struct CPUData_ { double userPercent; @@ -41,12 +43,12 @@ typedef struct SolarisProcessList_ { ProcessList super; kstat_ctl_t* kd; CPUData* cpus; + ZfsArcStats zfs; } SolarisProcessList; - char* SolarisProcessList_readZoneName(kstat_ctl_t* kd, SolarisProcess* sproc); -ProcessList* ProcessList_new(UsersTable* usersTable, Hashtable* pidWhiteList, uid_t userId); +ProcessList* ProcessList_new(UsersTable* usersTable, Hashtable* pidMatchList, uid_t userId); void ProcessList_delete(ProcessList* pl); @@ -54,11 +56,10 @@ void ProcessList_delete(ProcessList* pl); * and MUST conform to the appropriate definition in order * to work. See libproc(3LIB) on a Solaris or Illumos * system for more info. - */ - -int SolarisProcessList_walkproc(psinfo_t *_psinfo, lwpsinfo_t *_lwpsinfo, void *listptr); + */ -void ProcessList_goThroughEntries(ProcessList* this); +int SolarisProcessList_walkproc(psinfo_t* _psinfo, lwpsinfo_t* _lwpsinfo, void* listptr); +void ProcessList_goThroughEntries(ProcessList* super, bool pauseProcessUpdate); #endif diff --git a/test_spec.lua b/test_spec.lua index 7fd6c0c0d..2ae8015d6 100755 --- a/test_spec.lua +++ b/test_spec.lua @@ -1,7 +1,7 @@ #!/usr/bin/env lua local VISUALDELAY = os.getenv("VISUALDELAY") - + local visual = VISUALDELAY or false local visual_delay = VISUALDELAY and (tonumber(VISUALDELAY)) or 0.1 local short_delay = 0.3 @@ -70,7 +70,7 @@ local function show(key) term_win:mvaddstr(0, 0, tostring(key)) end term_win:refresh() - + delay(visual_delay) end end @@ -191,7 +191,7 @@ local function set_display_option(n) end describe("htop test suite", function() - + running_it("performs incremental filter", function() send("\\") send("x\127bux\127sted") -- test backspace @@ -397,13 +397,13 @@ describe("htop test suite", function() assert.not_equal(pair[1], pair[2]) end end) - + running_it("visits each setup screen", function() send("S") send(curses.KEY_DOWN, 3) send(curses.KEY_F10) end) - + running_it("adds and removes PPID column", function() send("S") send(curses.KEY_DOWN, 3) @@ -423,7 +423,7 @@ describe("htop test suite", function() assert.equal(check(ppid)) assert.not_equal(check(not_ppid)) end) - + running_it("changes CPU affinity for a process", function() send("a") send(" \n") @@ -468,7 +468,7 @@ describe("htop test suite", function() assert.equal(check(zerocpu)) assert.not_equal(check(nonzerocpu)) end) - + running_it("changes IO priority for a process", function() send("/") send("htop") @@ -502,7 +502,7 @@ describe("htop test suite", function() send("\n") send(curses.KEY_F10) end) - + local meters = { { name = "clock", down = 0, string = "Time" }, { name = "load", down = 2, string = "Load" }, @@ -558,7 +558,7 @@ describe("htop test suite", function() send("\n") send(curses.KEY_F10) end) - + local display_options = { { name = "tree view", down = 0 }, { name = "shadow other user's process", down = 1 }, @@ -574,7 +574,7 @@ describe("htop test suite", function() { name = "update process names", down = 11 }, { name = "guest time in CPU%", down = 12 }, } - + for _, item in ipairs(display_options) do running_it("checks display option to "..item.name, function() for _ = 1, 2 do @@ -641,7 +641,7 @@ describe("htop test suite", function() assert.equal(attrs.white_on_black, untaggedattr) end end) - + for i = 1, 62 do running_it("show column "..i, function() send("S") @@ -670,7 +670,7 @@ describe("htop test suite", function() end end) end - + it("finally quits", function() assert(not terminated()) send("q") @@ -685,4 +685,3 @@ describe("htop test suite", function() os.execute("make lcov && xdg-open lcov/index.html") end) end) - diff --git a/unsupported/Battery.c b/unsupported/Battery.c deleted file mode 100644 index 6d6e94bd2..000000000 --- a/unsupported/Battery.c +++ /dev/null @@ -1,8 +0,0 @@ - -#include "BatteryMeter.h" - -void Battery_getData(double* level, ACPresence* isOnAC) { - *level = -1; - *isOnAC = AC_ERROR; -} - diff --git a/unsupported/Battery.h b/unsupported/Battery.h deleted file mode 100644 index 8dc0cef6d..000000000 --- a/unsupported/Battery.h +++ /dev/null @@ -1,9 +0,0 @@ -/* Do not edit this file. It was automatically generated. */ - -#ifndef HEADER_Battery -#define HEADER_Battery - -void Battery_getData(double* level, ACPresence* isOnAC); - - -#endif diff --git a/unsupported/Platform.c b/unsupported/Platform.c index ba8441913..c7c2a2cf0 100644 --- a/unsupported/Platform.c +++ b/unsupported/Platform.c @@ -2,32 +2,31 @@ htop - unsupported/Platform.c (C) 2014 Hisham H. Muhammad (C) 2015 David C. Hunt -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ +#include + #include "Platform.h" +#include "Macros.h" #include "CPUMeter.h" #include "MemoryMeter.h" #include "SwapMeter.h" #include "TasksMeter.h" #include "LoadAverageMeter.h" #include "ClockMeter.h" +#include "DateMeter.h" +#include "DateTimeMeter.h" #include "HostnameMeter.h" #include "UptimeMeter.h" -/*{ -#include "Action.h" -#include "BatteryMeter.h" -#include "SignalsPanel.h" -#include "UnsupportedProcess.h" -}*/ const SignalItem Platform_signals[] = { { .name = " 0 Cancel", .number = 0 }, }; -const unsigned int Platform_numberOfSignals = sizeof(Platform_signals)/sizeof(SignalItem); +const unsigned int Platform_numberOfSignals = ARRAYSIZE(Platform_signals); ProcessField Platform_defaultFields[] = { PID, USER, PRIORITY, NICE, M_SIZE, M_RESIDENT, STATE, PERCENT_CPU, PERCENT_MEM, TIME, COMM, 0 }; @@ -50,7 +49,7 @@ ProcessFieldData Process_fields[] = { [PROCESSOR] = { .name = "PROCESSOR", .title = "CPU ", .description = "Id of the CPU the process last executed on", .flags = 0, }, [M_SIZE] = { .name = "M_SIZE", .title = " VIRT ", .description = "Total program size in virtual memory", .flags = 0, }, [M_RESIDENT] = { .name = "M_RESIDENT", .title = " RES ", .description = "Resident set size, size of the text and data sections, plus stack usage", .flags = 0, }, - [ST_UID] = { .name = "ST_UID", .title = " UID ", .description = "User ID of the process owner", .flags = 0, }, + [ST_UID] = { .name = "ST_UID", .title = " UID ", .description = "User ID of the process owner", .flags = 0, }, [PERCENT_CPU] = { .name = "PERCENT_CPU", .title = "CPU% ", .description = "Percentage of the CPU time the process used in the last sampling", .flags = 0, }, [PERCENT_MEM] = { .name = "PERCENT_MEM", .title = "MEM% ", .description = "Percentage of the memory the process is using, based on resident memory size", .flags = 0, }, [USER] = { .name = "USER", .title = "USER ", .description = "Username of the process owner (or user ID if name cannot be determined)", .flags = 0, }, @@ -60,9 +59,11 @@ ProcessFieldData Process_fields[] = { [100] = { .name = "*** report bug! ***", .title = NULL, .description = NULL, .flags = 0, }, }; -MeterClass* Platform_meterTypes[] = { +const MeterClass* const Platform_meterTypes[] = { &CPUMeter_class, &ClockMeter_class, + &DateMeter_class, + &DateTimeMeter_class, &LoadAverageMeter_class, &LoadMeter_class, &MemoryMeter_class, @@ -73,10 +74,16 @@ MeterClass* Platform_meterTypes[] = { &UptimeMeter_class, &AllCPUsMeter_class, &AllCPUs2Meter_class, + &AllCPUs4Meter_class, + &AllCPUs8Meter_class, &LeftCPUsMeter_class, &RightCPUsMeter_class, &LeftCPUs2Meter_class, &RightCPUs2Meter_class, + &LeftCPUs4Meter_class, + &RightCPUs4Meter_class, + &LeftCPUs8Meter_class, + &RightCPUs8Meter_class, &BlankMeter_class, NULL }; @@ -108,8 +115,11 @@ int Platform_getMaxPid() { } double Platform_setCPUValues(Meter* this, int cpu) { - (void) this; (void) cpu; + + double* v = this->values; + v[CPU_METER_FREQUENCY] = NAN; + return 0.0; } @@ -121,7 +131,7 @@ void Platform_setSwapValues(Meter* this) { (void) this; } -bool Process_isThread(Process* this) { +bool Process_isThread(const Process* this) { (void) this; return false; } @@ -130,3 +140,35 @@ char* Platform_getProcessEnv(pid_t pid) { (void) pid; return NULL; } + +char* Platform_getInodeFilename(pid_t pid, ino_t inode) { + (void)pid; + (void)inode; + return NULL; +} + +FileLocks_ProcessData* Platform_getProcessLocks(pid_t pid) { + (void)pid; + return NULL; +} + +bool Platform_getDiskIO(DiskIOData* data) { + (void)data; + return false; +} + +bool Platform_getNetworkIO(unsigned long int* bytesReceived, + unsigned long int* packetsReceived, + unsigned long int* bytesTransmitted, + unsigned long int* packetsTransmitted) { + *bytesReceived = 0; + *packetsReceived = 0; + *bytesTransmitted = 0; + *packetsTransmitted = 0; + return false; +} + +void Platform_getBattery(double* level, ACPresence* isOnAC) { + *level = NAN; + *isOnAC = AC_ERROR; +} diff --git a/unsupported/Platform.h b/unsupported/Platform.h index 14f3d1a6d..c75a283ad 100644 --- a/unsupported/Platform.h +++ b/unsupported/Platform.h @@ -1,17 +1,17 @@ -/* Do not edit this file. It was automatically generated. */ - #ifndef HEADER_Platform #define HEADER_Platform /* htop - unsupported/Platform.h (C) 2014 Hisham H. Muhammad (C) 2015 David C. Hunt -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ #include "Action.h" #include "BatteryMeter.h" +#include "DiskIOMeter.h" +#include "ProcessLocksScreen.h" #include "SignalsPanel.h" #include "UnsupportedProcess.h" @@ -23,7 +23,7 @@ extern ProcessField Platform_defaultFields[]; extern ProcessFieldData Process_fields[]; -extern MeterClass* Platform_meterTypes[]; +extern const MeterClass* const Platform_meterTypes[]; void Platform_setBindings(Htop_Action* keys); @@ -33,11 +33,11 @@ extern char Process_pidFormat[20]; extern ProcessPidColumn Process_pidColumns[]; -int Platform_getUptime(); +int Platform_getUptime(void); void Platform_getLoadAverage(double* one, double* five, double* fifteen); -int Platform_getMaxPid(); +int Platform_getMaxPid(void); double Platform_setCPUValues(Meter* this, int cpu); @@ -45,8 +45,21 @@ void Platform_setMemoryValues(Meter* this); void Platform_setSwapValues(Meter* this); -bool Process_isThread(Process* this); +bool Process_isThread(const Process* this); char* Platform_getProcessEnv(pid_t pid); +char* Platform_getInodeFilename(pid_t pid, ino_t inode); + +FileLocks_ProcessData* Platform_getProcessLocks(pid_t pid); + +bool Platform_getDiskIO(DiskIOData* data); + +bool Platform_getNetworkIO(unsigned long int* bytesReceived, + unsigned long int* packetsReceived, + unsigned long int* bytesTransmitted, + unsigned long int* packetsTransmitted); + +void Platform_getBattery(double *percent, ACPresence *isOnAC); + #endif diff --git a/unsupported/UnsupportedCRT.c b/unsupported/UnsupportedCRT.c deleted file mode 100644 index 5c3a9de45..000000000 --- a/unsupported/UnsupportedCRT.c +++ /dev/null @@ -1,21 +0,0 @@ -/* -htop - UnsupportedCRT.c -(C) 2014 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file -in the source distribution for its full text. -*/ - -#include "config.h" -#include "CRT.h" -#include -#include - -void CRT_handleSIGSEGV(int sgn) { - (void) sgn; - CRT_done(); - fprintf(stderr, "\n\nhtop " VERSION " aborting.\n"); - fprintf(stderr, "\nUnfortunately, you seem to be using an unsupported platform!"); - fprintf(stderr, "\nPlease contact your platform package maintainer!\n\n"); - abort(); -} - diff --git a/unsupported/UnsupportedCRT.h b/unsupported/UnsupportedCRT.h deleted file mode 100644 index 3c808ca6f..000000000 --- a/unsupported/UnsupportedCRT.h +++ /dev/null @@ -1,15 +0,0 @@ -/* Do not edit this file. It was automatically generated. */ - -#ifndef HEADER_UnsupportedCRT -#define HEADER_UnsupportedCRT -/* -htop - UnsupportedCRT.h -(C) 2014 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file -in the source distribution for its full text. -*/ - -void CRT_handleSIGSEGV(int sgn); - - -#endif diff --git a/unsupported/UnsupportedProcess.c b/unsupported/UnsupportedProcess.c index ec1de78ec..0827c6088 100644 --- a/unsupported/UnsupportedProcess.c +++ b/unsupported/UnsupportedProcess.c @@ -1,7 +1,7 @@ /* htop - UnsupportedProcess.c (C) 2015 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ @@ -9,12 +9,6 @@ in the source distribution for its full text. #include "UnsupportedProcess.h" #include -/*{ -#include "Settings.h" - -#define Process_delete UnsupportedProcess_delete - -}*/ Process* UnsupportedProcess_new(Settings* settings) { Process* this = xCalloc(1, sizeof(Process)); @@ -30,4 +24,3 @@ void UnsupportedProcess_delete(Object* cast) { // free platform-specific fields here free(this); } - diff --git a/unsupported/UnsupportedProcess.h b/unsupported/UnsupportedProcess.h index 4ca30436d..11335cdb9 100644 --- a/unsupported/UnsupportedProcess.h +++ b/unsupported/UnsupportedProcess.h @@ -1,11 +1,9 @@ -/* Do not edit this file. It was automatically generated. */ - #ifndef HEADER_UnsupportedProcess #define HEADER_UnsupportedProcess /* htop - UnsupportedProcess.h (C) 2015 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ @@ -13,10 +11,8 @@ in the source distribution for its full text. #define Process_delete UnsupportedProcess_delete - Process* UnsupportedProcess_new(Settings* settings); void UnsupportedProcess_delete(Object* cast); - #endif diff --git a/unsupported/UnsupportedProcessList.c b/unsupported/UnsupportedProcessList.c index 9be4eee48..6c0e0229f 100644 --- a/unsupported/UnsupportedProcessList.c +++ b/unsupported/UnsupportedProcessList.c @@ -1,7 +1,7 @@ /* htop - UnsupportedProcessList.c (C) 2014 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ @@ -11,14 +11,11 @@ in the source distribution for its full text. #include #include -/*{ -}*/ - -ProcessList* ProcessList_new(UsersTable* usersTable, Hashtable* pidWhiteList, uid_t userId) { +ProcessList* ProcessList_new(UsersTable* usersTable, Hashtable* pidMatchList, uid_t userId) { ProcessList* this = xCalloc(1, sizeof(ProcessList)); - ProcessList_init(this, Class(Process), usersTable, pidWhiteList, userId); - + ProcessList_init(this, Class(Process), usersTable, pidMatchList, userId); + return this; } @@ -27,44 +24,50 @@ void ProcessList_delete(ProcessList* this) { free(this); } -void ProcessList_goThroughEntries(ProcessList* super) { - bool preExisting = true; - Process *proc; - - proc = ProcessList_getProcess(super, 1, &preExisting, UnsupportedProcess_new); - - /* Empty values */ - proc->time = proc->time + 10; - proc->pid = 1; - proc->ppid = 1; - proc->tgid = 0; - proc->comm = ""; - proc->basenameOffset = 0; - proc->updated = true; - - proc->state = 'R'; - proc->show = true; /* Reflected in proc->settings-> "hideXXX" really */ - proc->pgrp = 0; - proc->session = 0; - proc->tty_nr = 0; - proc->tpgid = 0; - proc->st_uid = 0; - proc->flags = 0; - proc->processor = 0; - - proc->percent_cpu = 2.5; - proc->percent_mem = 2.5; - proc->user = "nobody"; - - proc->priority = 0; - proc->nice = 0; - proc->nlwp = 1; - strncpy(proc->starttime_show, "Jun 01 ", sizeof(proc->starttime_show)); - proc->starttime_ctime = 1433116800; // Jun 01, 2015 - - proc->m_size = 100; - proc->m_resident = 100; - - proc->minflt = 20; - proc->majflt = 20; +void ProcessList_goThroughEntries(ProcessList* super, bool pauseProcessUpdate) { + + // in pause mode only gather global data for meters (CPU/memory/...) + if (pauseProcessUpdate) { + return; + } + + bool preExisting = true; + Process* proc; + + proc = ProcessList_getProcess(super, 1, &preExisting, UnsupportedProcess_new); + + /* Empty values */ + proc->time = proc->time + 10; + proc->pid = 1; + proc->ppid = 1; + proc->tgid = 0; + proc->comm = ""; + proc->basenameOffset = 0; + proc->updated = true; + + proc->state = 'R'; + proc->show = true; /* Reflected in proc->settings-> "hideXXX" really */ + proc->pgrp = 0; + proc->session = 0; + proc->tty_nr = 0; + proc->tpgid = 0; + proc->st_uid = 0; + proc->flags = 0; + proc->processor = 0; + + proc->percent_cpu = 2.5; + proc->percent_mem = 2.5; + proc->user = "nobody"; + + proc->priority = 0; + proc->nice = 0; + proc->nlwp = 1; + proc->starttime_ctime = 1433116800; // Jun 01, 2015 + Process_fillStarttimeBuffer(proc); + + proc->m_size = 100; + proc->m_resident = 100; + + proc->minflt = 20; + proc->majflt = 20; } diff --git a/unsupported/UnsupportedProcessList.h b/unsupported/UnsupportedProcessList.h index 6eb13086c..1c537713b 100644 --- a/unsupported/UnsupportedProcessList.h +++ b/unsupported/UnsupportedProcessList.h @@ -1,20 +1,16 @@ -/* Do not edit this file. It was automatically generated. */ - #ifndef HEADER_UnsupportedProcessList #define HEADER_UnsupportedProcessList /* htop - UnsupportedProcessList.h (C) 2014 Hisham H. Muhammad -Released under the GNU GPL, see the COPYING file +Released under the GNU GPLv2, see the COPYING file in the source distribution for its full text. */ - - -ProcessList* ProcessList_new(UsersTable* usersTable, Hashtable* pidWhiteList, uid_t userId); +ProcessList* ProcessList_new(UsersTable* usersTable, Hashtable* pidMatchList, uid_t userId); void ProcessList_delete(ProcessList* this); -void ProcessList_goThroughEntries(ProcessList* super); +void ProcessList_goThroughEntries(ProcessList* super, bool pauseProcessUpdate); #endif diff --git a/zfs/ZfsArcMeter.c b/zfs/ZfsArcMeter.c new file mode 100644 index 000000000..72af3bc78 --- /dev/null +++ b/zfs/ZfsArcMeter.c @@ -0,0 +1,94 @@ +/* +htop - ZfsArcMeter.c +(C) 2004-2011 Hisham H. Muhammad +Released under the GNU GPLv2, see the COPYING file +in the source distribution for its full text. +*/ + +#include "ZfsArcMeter.h" +#include "ZfsArcStats.h" + +#include "CRT.h" +#include "Object.h" +#include "Platform.h" +#include "RichString.h" + + +static const int ZfsArcMeter_attributes[] = { + ZFS_MFU, ZFS_MRU, ZFS_ANON, ZFS_HEADER, ZFS_OTHER +}; + +void ZfsArcMeter_readStats(Meter* this, const ZfsArcStats* stats) { + this->total = stats->max; + this->values[0] = stats->MFU; + this->values[1] = stats->MRU; + this->values[2] = stats->anon; + this->values[3] = stats->header; + this->values[4] = stats->other; + + // "Hide" the last value so it can + // only be accessed by index and is not + // displayed by the Bar or Graph style + this->curItems = 5; + this->values[5] = stats->size; +} + +static void ZfsArcMeter_updateValues(Meter* this, char* buffer, int size) { + int written; + Platform_setZfsArcValues(this); + + written = Meter_humanUnit(buffer, this->values[5], size); + buffer += written; + if ((size -= written) > 0) { + *buffer++ = '/'; + size--; + Meter_humanUnit(buffer, this->total, size); + } +} + +static void ZfsArcMeter_display(const Object* cast, RichString* out) { + char buffer[50]; + const Meter* this = (const Meter*)cast; + + if (this->values[5] > 0) { + Meter_humanUnit(buffer, this->total, 50); + RichString_append(out, CRT_colors[METER_VALUE], buffer); + Meter_humanUnit(buffer, this->values[5], 50); + RichString_append(out, CRT_colors[METER_TEXT], " Used:"); + RichString_append(out, CRT_colors[METER_VALUE], buffer); + Meter_humanUnit(buffer, this->values[0], 50); + RichString_append(out, CRT_colors[METER_TEXT], " MFU:"); + RichString_append(out, CRT_colors[ZFS_MFU], buffer); + Meter_humanUnit(buffer, this->values[1], 50); + RichString_append(out, CRT_colors[METER_TEXT], " MRU:"); + RichString_append(out, CRT_colors[ZFS_MRU], buffer); + Meter_humanUnit(buffer, this->values[2], 50); + RichString_append(out, CRT_colors[METER_TEXT], " Anon:"); + RichString_append(out, CRT_colors[ZFS_ANON], buffer); + Meter_humanUnit(buffer, this->values[3], 50); + RichString_append(out, CRT_colors[METER_TEXT], " Hdr:"); + RichString_append(out, CRT_colors[ZFS_HEADER], buffer); + Meter_humanUnit(buffer, this->values[4], 50); + RichString_append(out, CRT_colors[METER_TEXT], " Oth:"); + RichString_append(out, CRT_colors[ZFS_OTHER], buffer); + } else { + RichString_write(out, CRT_colors[METER_TEXT], " "); + RichString_append(out, CRT_colors[FAILED_SEARCH], "Unavailable"); + } +} + +const MeterClass ZfsArcMeter_class = { + .super = { + .extends = Class(Meter), + .delete = Meter_delete, + .display = ZfsArcMeter_display, + }, + .updateValues = ZfsArcMeter_updateValues, + .defaultMode = TEXT_METERMODE, + .maxItems = 6, + .total = 100.0, + .attributes = ZfsArcMeter_attributes, + .name = "ZFSARC", + .uiName = "ZFS ARC", + .caption = "ARC: " +}; diff --git a/zfs/ZfsArcMeter.h b/zfs/ZfsArcMeter.h new file mode 100644 index 000000000..52bf7842d --- /dev/null +++ b/zfs/ZfsArcMeter.h @@ -0,0 +1,18 @@ +#ifndef HEADER_ZfsArcMeter +#define HEADER_ZfsArcMeter +/* +htop - ZfsArcMeter.h +(C) 2004-2011 Hisham H. Muhammad +Released under the GNU GPLv2, see the COPYING file +in the source distribution for its full text. +*/ + +#include "ZfsArcStats.h" + +#include "Meter.h" + +void ZfsArcMeter_readStats(Meter* this, const ZfsArcStats* stats); + +extern const MeterClass ZfsArcMeter_class; + +#endif diff --git a/zfs/ZfsArcStats.c b/zfs/ZfsArcStats.c new file mode 100644 index 000000000..ae5656337 --- /dev/null +++ b/zfs/ZfsArcStats.c @@ -0,0 +1,26 @@ +/* +htop - ZfsArcStats.c +(C) 2014 Hisham H. Muhammad +Released under the GNU GPLv2, see the COPYING file +in the source distribution for its full text. +*/ + +/*{ +typedef struct ZfsArcStats_ { + int enabled; + int isCompressed; + unsigned long long int max; + unsigned long long int size; + unsigned long long int MFU; + unsigned long long int MRU; + unsigned long long int anon; + unsigned long long int header; + unsigned long long int other; + unsigned long long int compressed; + unsigned long long int uncompressed; +} ZfsArcStats; +}*/ + +#include "Macros.h" + +static int make_iso_compilers_happy ATTR_UNUSED; diff --git a/zfs/ZfsArcStats.h b/zfs/ZfsArcStats.h new file mode 100644 index 000000000..d891dc2fa --- /dev/null +++ b/zfs/ZfsArcStats.h @@ -0,0 +1,24 @@ +#ifndef HEADER_ZfsArcStats +#define HEADER_ZfsArcStats +/* +htop - ZfsArcStats.h +(C) 2014 Hisham H. Muhammad +Released under the GNU GPLv2, see the COPYING file +in the source distribution for its full text. +*/ + +typedef struct ZfsArcStats_ { + int enabled; + int isCompressed; + unsigned long long int max; + unsigned long long int size; + unsigned long long int MFU; + unsigned long long int MRU; + unsigned long long int anon; + unsigned long long int header; + unsigned long long int other; + unsigned long long int compressed; + unsigned long long int uncompressed; +} ZfsArcStats; + +#endif diff --git a/zfs/ZfsCompressedArcMeter.c b/zfs/ZfsCompressedArcMeter.c new file mode 100644 index 000000000..d0278a9df --- /dev/null +++ b/zfs/ZfsCompressedArcMeter.c @@ -0,0 +1,80 @@ +/* +htop - ZfsCompressedArcMeter.c +(C) 2004-2011 Hisham H. Muhammad +Released under the GNU GPLv2, see the COPYING file +in the source distribution for its full text. +*/ + +#include "ZfsCompressedArcMeter.h" + +#include "CRT.h" +#include "Meter.h" +#include "Object.h" +#include "Platform.h" +#include "RichString.h" +#include "XUtils.h" + +#include "zfs/ZfsArcStats.h" + + +static const int ZfsCompressedArcMeter_attributes[] = { + ZFS_COMPRESSED +}; + +void ZfsCompressedArcMeter_readStats(Meter* this, const ZfsArcStats* stats) { + if ( stats->isCompressed ) { + this->total = stats->uncompressed; + this->values[0] = stats->compressed; + } else { + // For uncompressed ARC, report 1:1 ratio + this->total = stats->size; + this->values[0] = stats->size; + } +} + +static void ZfsCompressedArcMeter_printRatioString(const Meter* this, char* buffer, int size) { + xSnprintf(buffer, size, "%.2f:1", this->total / this->values[0]); +} + +static void ZfsCompressedArcMeter_updateValues(Meter* this, char* buffer, int size) { + Platform_setZfsCompressedArcValues(this); + + ZfsCompressedArcMeter_printRatioString(this, buffer, size); +} + +static void ZfsCompressedArcMeter_display(const Object* cast, RichString* out) { + char buffer[50]; + const Meter* this = (const Meter*)cast; + + if (this->values[0] > 0) { + Meter_humanUnit(buffer, this->total, 50); + RichString_append(out, CRT_colors[METER_VALUE], buffer); + RichString_append(out, CRT_colors[METER_TEXT], " Uncompressed, "); + Meter_humanUnit(buffer, this->values[0], 50); + RichString_append(out, CRT_colors[METER_VALUE], buffer); + RichString_append(out, CRT_colors[METER_TEXT], " Compressed, "); + ZfsCompressedArcMeter_printRatioString(this, buffer, 50); + RichString_append(out, CRT_colors[METER_VALUE], buffer); + RichString_append(out, CRT_colors[METER_TEXT], " Ratio"); + } else { + RichString_write(out, CRT_colors[METER_TEXT], " "); + RichString_append(out, CRT_colors[FAILED_SEARCH], "Compression Unavailable"); + } +} + +const MeterClass ZfsCompressedArcMeter_class = { + .super = { + .extends = Class(Meter), + .delete = Meter_delete, + .display = ZfsCompressedArcMeter_display, + }, + .updateValues = ZfsCompressedArcMeter_updateValues, + .defaultMode = TEXT_METERMODE, + .maxItems = 1, + .total = 100.0, + .attributes = ZfsCompressedArcMeter_attributes, + .name = "ZFSCARC", + .uiName = "ZFS CARC", + .description = "ZFS CARC: Compressed ARC statistics", + .caption = "ARC: " +}; diff --git a/zfs/ZfsCompressedArcMeter.h b/zfs/ZfsCompressedArcMeter.h new file mode 100644 index 000000000..025a9dd8d --- /dev/null +++ b/zfs/ZfsCompressedArcMeter.h @@ -0,0 +1,18 @@ +#ifndef HEADER_ZfsCompressedArcMeter +#define HEADER_ZfsCompressedArcMeter +/* +htop - ZfsCompressedArcMeter.h +(C) 2004-2011 Hisham H. Muhammad +Released under the GNU GPLv2, see the COPYING file +in the source distribution for its full text. +*/ + +#include "ZfsArcStats.h" + +#include "Meter.h" + +void ZfsCompressedArcMeter_readStats(Meter* this, const ZfsArcStats* stats); + +extern const MeterClass ZfsCompressedArcMeter_class; + +#endif diff --git a/zfs/openzfs_sysctl.c b/zfs/openzfs_sysctl.c new file mode 100644 index 000000000..59d7469f8 --- /dev/null +++ b/zfs/openzfs_sysctl.c @@ -0,0 +1,101 @@ +/* +htop - zfs/openzfs_sysctl.c +(C) 2014 Hisham H. Muhammad +Released under the GNU GPLv2, see the COPYING file +in the source distribution for its full text. +*/ + +#include "zfs/openzfs_sysctl.h" +#include "zfs/ZfsArcStats.h" + +#include +#include +#include +#include + +static int MIB_kstat_zfs_misc_arcstats_size[5]; +static int MIB_kstat_zfs_misc_arcstats_c_max[5]; +static int MIB_kstat_zfs_misc_arcstats_mfu_size[5]; +static int MIB_kstat_zfs_misc_arcstats_mru_size[5]; +static int MIB_kstat_zfs_misc_arcstats_anon_size[5]; +static int MIB_kstat_zfs_misc_arcstats_hdr_size[5]; +static int MIB_kstat_zfs_misc_arcstats_other_size[5]; +static int MIB_kstat_zfs_misc_arcstats_compressed_size[5]; +static int MIB_kstat_zfs_misc_arcstats_uncompressed_size[5]; + +/*{ +#include "zfs/ZfsArcStats.h" +}*/ + +void openzfs_sysctl_init(ZfsArcStats* stats) { + size_t len; + unsigned long long int arcSize; + + len = sizeof(arcSize); + if (sysctlbyname("kstat.zfs.misc.arcstats.size", &arcSize, &len, NULL, 0) == 0 && arcSize != 0) { + stats->enabled = 1; + + len = 5; + sysctlnametomib("kstat.zfs.misc.arcstats.size", MIB_kstat_zfs_misc_arcstats_size, &len); + + sysctlnametomib("kstat.zfs.misc.arcstats.c_max", MIB_kstat_zfs_misc_arcstats_c_max, &len); + sysctlnametomib("kstat.zfs.misc.arcstats.mfu_size", MIB_kstat_zfs_misc_arcstats_mfu_size, &len); + sysctlnametomib("kstat.zfs.misc.arcstats.mru_size", MIB_kstat_zfs_misc_arcstats_mru_size, &len); + sysctlnametomib("kstat.zfs.misc.arcstats.anon_size", MIB_kstat_zfs_misc_arcstats_anon_size, &len); + sysctlnametomib("kstat.zfs.misc.arcstats.hdr_size", MIB_kstat_zfs_misc_arcstats_hdr_size, &len); + sysctlnametomib("kstat.zfs.misc.arcstats.other_size", MIB_kstat_zfs_misc_arcstats_other_size, &len); + + if (sysctlnametomib("kstat.zfs.misc.arcstats.compressed_size", MIB_kstat_zfs_misc_arcstats_compressed_size, &len) == 0) { + stats->isCompressed = 1; + sysctlnametomib("kstat.zfs.misc.arcstats.uncompressed_size", MIB_kstat_zfs_misc_arcstats_uncompressed_size, &len); + } else { + stats->isCompressed = 0; + } + } else { + stats->enabled = 0; + } +} + +void openzfs_sysctl_updateArcStats(ZfsArcStats* stats) { + size_t len; + + if (stats->enabled) { + len = sizeof(stats->size); + sysctl(MIB_kstat_zfs_misc_arcstats_size, 5, &(stats->size), &len, NULL, 0); + stats->size /= 1024; + + len = sizeof(stats->max); + sysctl(MIB_kstat_zfs_misc_arcstats_c_max, 5, &(stats->max), &len, NULL, 0); + stats->max /= 1024; + + len = sizeof(stats->MFU); + sysctl(MIB_kstat_zfs_misc_arcstats_mfu_size, 5, &(stats->MFU), &len, NULL, 0); + stats->MFU /= 1024; + + len = sizeof(stats->MRU); + sysctl(MIB_kstat_zfs_misc_arcstats_mru_size, 5, &(stats->MRU), &len, NULL, 0); + stats->MRU /= 1024; + + len = sizeof(stats->anon); + sysctl(MIB_kstat_zfs_misc_arcstats_anon_size, 5, &(stats->anon), &len, NULL, 0); + stats->anon /= 1024; + + len = sizeof(stats->header); + sysctl(MIB_kstat_zfs_misc_arcstats_hdr_size, 5, &(stats->header), &len, NULL, 0); + stats->header /= 1024; + + len = sizeof(stats->other); + sysctl(MIB_kstat_zfs_misc_arcstats_other_size, 5, &(stats->other), &len, NULL, 0); + stats->other /= 1024; + + if (stats->isCompressed) { + len = sizeof(stats->compressed); + sysctl(MIB_kstat_zfs_misc_arcstats_compressed_size, 5, &(stats->compressed), &len, NULL, 0); + stats->compressed /= 1024; + + len = sizeof(stats->uncompressed); + sysctl(MIB_kstat_zfs_misc_arcstats_uncompressed_size, 5, &(stats->uncompressed), &len, NULL, 0); + stats->uncompressed /= 1024; + } + } +} diff --git a/zfs/openzfs_sysctl.h b/zfs/openzfs_sysctl.h new file mode 100644 index 000000000..b49128e36 --- /dev/null +++ b/zfs/openzfs_sysctl.h @@ -0,0 +1,16 @@ +#ifndef HEADER_openzfs_sysctl +#define HEADER_openzfs_sysctl +/* +htop - zfs/openzfs_sysctl.h +(C) 2014 Hisham H. Muhammad +Released under the GNU GPLv2, see the COPYING file +in the source distribution for its full text. +*/ + +#include "zfs/ZfsArcStats.h" + +void openzfs_sysctl_init(ZfsArcStats* stats); + +void openzfs_sysctl_updateArcStats(ZfsArcStats* stats); + +#endif