fix tiny memleak when $top is used wrong
[monky] / src / top.c
1 /* -*- mode: c; c-basic-offset: 4; tab-width: 4; indent-tabs-mode: t -*-
2  * vim: ts=4 sw=4 noet ai cindent syntax=c
3  *
4  * Conky, a system monitor, based on torsmo
5  *
6  * Any original torsmo code is licensed under the BSD license
7  *
8  * All code written since the fork of torsmo is licensed under the GPL
9  *
10  * Please see COPYING for details
11  *
12  * Copyright (c) 2005 Adi Zaimi, Dan Piponi <dan@tanelorn.demon.co.uk>,
13  *                                        Dave Clark <clarkd@skynet.ca>
14  * Copyright (c) 2005-2010 Brenden Matthews, Philip Kovacs, et. al.
15  *      (see AUTHORS)
16  * All rights reserved.
17  *
18  * This program is free software: you can redistribute it and/or modify
19  * it under the terms of the GNU General Public License as published by
20  * the Free Software Foundation, either version 3 of the License, or
21  * (at your option) any later version.
22  *
23  * This program is distributed in the hope that it will be useful,
24  * but WITHOUT ANY WARRANTY; without even the implied warranty of
25  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
26  * GNU General Public License for more details.
27  * You should have received a copy of the GNU General Public License
28  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
29  *
30  */
31
32 #include "top.h"
33 #include "logging.h"
34
35 static unsigned long g_time = 0;
36 static unsigned long long previous_total = 0;
37 static struct process *first_process = 0;
38
39 /* a simple hash table to speed up find_process() */
40 struct proc_hash_entry {
41         struct proc_hash_entry *next;
42         struct process *proc;
43 };
44 static struct proc_hash_entry proc_hash_table[256];
45
46 static void hash_process(struct process *p)
47 {
48         struct proc_hash_entry *phe;
49         static char first_run = 1;
50
51         /* better make sure all next pointers are zero upon first access */
52         if (first_run) {
53                 memset(proc_hash_table, 0, sizeof(struct proc_hash_entry) * 256);
54                 first_run = 0;
55         }
56
57         /* get the bucket head */
58         phe = &proc_hash_table[p->pid % 256];
59
60         /* find the bucket's end */
61         while (phe->next)
62                 phe = phe->next;
63
64         /* append process */
65         phe->next = malloc(sizeof(struct proc_hash_entry));
66         memset(phe->next, 0, sizeof(struct proc_hash_entry));
67         phe->next->proc = p;
68 }
69
70 static void unhash_process(struct process *p)
71 {
72         struct proc_hash_entry *phe, *tmp;
73
74         /* get the bucket head */
75         phe = &proc_hash_table[p->pid % 256];
76
77         /* find the entry pointing to p and drop it */
78         while (phe->next) {
79                 if (phe->next->proc == p) {
80                         tmp = phe->next;
81                         phe->next = phe->next->next;
82                         free(tmp);
83                         return;
84                 }
85                 phe = phe->next;
86         }
87 }
88
89 static void __unhash_all_processes(struct proc_hash_entry *phe)
90 {
91         if (phe->next)
92                 __unhash_all_processes(phe->next);
93         free(phe->next);
94 }
95
96 static void unhash_all_processes(void)
97 {
98         int i;
99
100         for (i = 0; i < 256; i++) {
101                 __unhash_all_processes(&proc_hash_table[i]);
102                 proc_hash_table[i].next = NULL;
103         }
104 }
105
106 struct process *get_first_process(void)
107 {
108         return first_process;
109 }
110
111 void free_all_processes(void)
112 {
113         struct process *next = NULL, *pr = first_process;
114
115         while (pr) {
116                 next = pr->next;
117                 if (pr->name) {
118                         free(pr->name);
119                 }
120                 free(pr);
121                 pr = next;
122         }
123         first_process = NULL;
124
125         /* drop the whole hash table */
126         unhash_all_processes();
127 }
128
129 struct process *get_process_by_name(const char *name)
130 {
131         struct process *p = first_process;
132
133         while (p) {
134                 if (p->name && !strcmp(p->name, name))
135                         return p;
136                 p = p->next;
137         }
138         return 0;
139 }
140
141 static struct process *find_process(pid_t pid)
142 {
143         struct proc_hash_entry *phe;
144
145         phe = &proc_hash_table[pid % 256];
146         while (phe->next) {
147                 if (phe->next->proc->pid == pid)
148                         return phe->next->proc;
149                 phe = phe->next;
150         }
151         return 0;
152 }
153
154 /* Create a new process object and insert it into the process list */
155 static struct process *new_process(int p)
156 {
157         struct process *process;
158         process = (struct process *) malloc(sizeof(struct process));
159
160         // clean up memory first
161         memset(process, 0, sizeof(struct process));
162
163         /* Do stitching necessary for doubly linked list */
164         process->name = 0;
165         process->previous = 0;
166         process->next = first_process;
167         if (process->next) {
168                 process->next->previous = process;
169         }
170         first_process = process;
171
172         process->pid = p;
173         process->time_stamp = 0;
174         process->previous_user_time = ULONG_MAX;
175         process->previous_kernel_time = ULONG_MAX;
176 #ifdef IOSTATS
177         process->previous_read_bytes = ULLONG_MAX;
178         process->previous_write_bytes = ULLONG_MAX;
179 #endif /* IOSTATS */
180         process->counted = 1;
181
182         /* process_find_name(process); */
183
184         /* add the process to the hash table */
185         hash_process(process);
186
187         return process;
188 }
189
190 /******************************************
191  * Functions                                                      *
192  ******************************************/
193
194 /******************************************
195  * Extract information from /proc                 *
196  ******************************************/
197
198 /* These are the guts that extract information out of /proc.
199  * Anyone hoping to port wmtop should look here first. */
200 static int process_parse_stat(struct process *process)
201 {
202         char line[BUFFER_LEN] = { 0 }, filename[BUFFER_LEN], procname[BUFFER_LEN];
203         char state[4];
204         int ps;
205         unsigned long user_time = 0;
206         unsigned long kernel_time = 0;
207         int rc;
208         char *r, *q;
209         int endl;
210         int nice_val;
211         char *lparen, *rparen;
212
213         snprintf(filename, sizeof(filename), PROCFS_TEMPLATE, process->pid);
214
215         ps = open(filename, O_RDONLY);
216         if (ps < 0) {
217                 /* The process must have finished in the last few jiffies! */
218                 return 1;
219         }
220
221         /* Mark process as up-to-date. */
222         process->time_stamp = g_time;
223
224         rc = read(ps, line, sizeof(line));
225         close(ps);
226         if (rc < 0) {
227                 return 1;
228         }
229
230         /* Extract cpu times from data in /proc filesystem */
231         lparen = strchr(line, '(');
232         rparen = strrchr(line, ')');
233         if(!lparen || !rparen || rparen < lparen)
234                 return 1; // this should not happen
235
236         rc = MIN((unsigned)(rparen - lparen - 1), sizeof(procname) - 1);
237         strncpy(procname, lparen + 1, rc);
238         procname[rc] = '\0';
239         rc = sscanf(rparen + 1, "%3s %*s %*s %*s %*s %*s %*s %*s %*s %*s %*s %lu "
240                         "%lu %*s %*s %*s %d %*s %*s %*s %u %u", state, &process->user_time,
241                         &process->kernel_time, &nice_val, &process->vsize, &process->rss);
242         if (rc < 6) {
243                 NORM_ERR("scaning data for %s failed, got only %d fields", procname, rc);
244                 return 1;
245         }
246
247         if(state[0]=='R')
248                 ++ info.run_procs;
249
250         /* remove any "kdeinit: " */
251         if (procname == strstr(procname, "kdeinit")) {
252                 snprintf(filename, sizeof(filename), PROCFS_CMDLINE_TEMPLATE,
253                                 process->pid);
254
255                 ps = open(filename, O_RDONLY);
256                 if (ps < 0) {
257                         /* The process must have finished in the last few jiffies! */
258                         return 1;
259                 }
260
261                 endl = read(ps, line, sizeof(line));
262                 close(ps);
263
264                 /* null terminate the input */
265                 line[endl] = 0;
266                 /* account for "kdeinit: " */
267                 if ((char *) line == strstr(line, "kdeinit: ")) {
268                         r = ((char *) line) + 9;
269                 } else {
270                         r = (char *) line;
271                 }
272
273                 q = procname;
274                 /* stop at space */
275                 while (*r && *r != ' ') {
276                         *q++ = *r++;
277                 }
278                 *q = 0;
279         }
280
281         if (process->name) {
282                 free(process->name);
283         }
284         process->name = strndup(procname, text_buffer_size);
285         process->rss *= getpagesize();
286
287         process->total_cpu_time = process->user_time + process->kernel_time;
288         if (process->previous_user_time == ULONG_MAX) {
289                 process->previous_user_time = process->user_time;
290         }
291         if (process->previous_kernel_time == ULONG_MAX) {
292                 process->previous_kernel_time = process->kernel_time;
293         }
294
295         /* strangely, the values aren't monotonous */
296         if (process->previous_user_time > process->user_time)
297                 process->previous_user_time = process->user_time;
298
299         if (process->previous_kernel_time > process->kernel_time)
300                 process->previous_kernel_time = process->kernel_time;
301
302         /* store the difference of the user_time */
303         user_time = process->user_time - process->previous_user_time;
304         kernel_time = process->kernel_time - process->previous_kernel_time;
305
306         /* backup the process->user_time for next time around */
307         process->previous_user_time = process->user_time;
308         process->previous_kernel_time = process->kernel_time;
309
310         /* store only the difference of the user_time here... */
311         process->user_time = user_time;
312         process->kernel_time = kernel_time;
313
314         return 0;
315 }
316
317 #ifdef IOSTATS
318 static int process_parse_io(struct process *process)
319 {
320         static const char *read_bytes_str="read_bytes:";
321         static const char *write_bytes_str="write_bytes:";
322
323         char line[BUFFER_LEN] = { 0 }, filename[BUFFER_LEN];
324         int ps;
325         int rc;
326         char *pos, *endpos;
327         unsigned long long read_bytes, write_bytes;
328
329         snprintf(filename, sizeof(filename), PROCFS_TEMPLATE_IO, process->pid);
330
331         ps = open(filename, O_RDONLY);
332         if (ps < 0) {
333                 /* The process must have finished in the last few jiffies!
334                  * Or, the kernel doesn't support I/O accounting.
335                  */
336                 return 1;
337         }
338
339         rc = read(ps, line, sizeof(line));
340         close(ps);
341         if (rc < 0) {
342                 return 1;
343         }
344
345         pos = strstr(line, read_bytes_str);
346         if (pos == NULL) {
347                 /* these should not happen (unless the format of the file changes) */
348                 return 1;
349         }
350         pos += strlen(read_bytes_str);
351         process->read_bytes = strtoull(pos, &endpos, 10);
352         if (endpos == pos) {
353                 return 1;
354         }
355
356         pos = strstr(line, write_bytes_str);
357         if (pos == NULL) {
358                 return 1;
359         }
360         pos += strlen(write_bytes_str);
361         process->write_bytes = strtoull(pos, &endpos, 10);
362         if (endpos == pos) {
363                 return 1;
364         }
365
366         if (process->previous_read_bytes == ULLONG_MAX) {
367                 process->previous_read_bytes = process->read_bytes;
368         }
369         if (process->previous_write_bytes == ULLONG_MAX) {
370                 process->previous_write_bytes = process->write_bytes;
371         }
372
373         /* store the difference of the byte counts */
374         read_bytes = process->read_bytes - process->previous_read_bytes;
375         write_bytes = process->write_bytes - process->previous_write_bytes;
376
377         /* backup the counts for next time around */
378         process->previous_read_bytes = process->read_bytes;
379         process->previous_write_bytes = process->write_bytes;
380
381         /* store only the difference here... */
382         process->read_bytes = read_bytes;
383         process->write_bytes = write_bytes;
384
385         return 0;
386 }
387 #endif /* IOSTATS */
388
389 /******************************************
390  * Get process structure for process pid  *
391  ******************************************/
392
393 /* This function seems to hog all of the CPU time.
394  * I can't figure out why - it doesn't do much. */
395 static int calculate_stats(struct process *process)
396 {
397         int rc;
398
399         /* compute each process cpu usage by reading /proc/<proc#>/stat */
400         rc = process_parse_stat(process);
401         if (rc) return 1;
402         /* rc = process_parse_statm(process); if (rc) return 1; */
403
404 #ifdef IOSTATS
405         rc = process_parse_io(process);
406         if (rc) return 1;
407 #endif /* IOSTATS */
408
409         /*
410          * Check name against the exclusion list
411          */
412         /* if (process->counted && exclusion_expression &&
413          * !regexec(exclusion_expression, process->name, 0, 0, 0))
414          * process->counted = 0; */
415
416         return 0;
417 }
418
419 /******************************************
420  * Update process table                                   *
421  ******************************************/
422
423 static int update_process_table(void)
424 {
425         DIR *dir;
426         struct dirent *entry;
427
428         if (!(dir = opendir("/proc"))) {
429                 return 1;
430         }
431
432         info.run_procs = 0;
433         ++g_time;
434
435         /* Get list of processes from /proc directory */
436         while ((entry = readdir(dir))) {
437                 pid_t pid;
438
439                 if (!entry) {
440                         /* Problem reading list of processes */
441                         closedir(dir);
442                         return 1;
443                 }
444
445                 if (sscanf(entry->d_name, "%d", &pid) > 0) {
446                         struct process *p;
447
448                         p = find_process(pid);
449                         if (!p) {
450                                 p = new_process(pid);
451                         }
452
453                         /* compute each process cpu usage */
454                         calculate_stats(p);
455                 }
456         }
457
458         closedir(dir);
459
460         return 0;
461 }
462
463 /******************************************
464  * Destroy and remove a process           *
465  ******************************************/
466
467 static void delete_process(struct process *p)
468 {
469 #if defined(PARANOID)
470         assert(p->id == 0x0badfeed);
471
472         /*
473          * Ensure that deleted processes aren't reused.
474          */
475         p->id = 0x007babe;
476 #endif /* defined(PARANOID) */
477
478         /*
479          * Maintain doubly linked list.
480          */
481         if (p->next)
482                 p->next->previous = p->previous;
483         if (p->previous)
484                 p->previous->next = p->next;
485         else
486                 first_process = p->next;
487
488         if (p->name) {
489                 free(p->name);
490         }
491         /* remove the process from the hash table */
492         unhash_process(p);
493         free(p);
494 }
495
496 /******************************************
497  * Strip dead process entries                     *
498  ******************************************/
499
500 static void process_cleanup(void)
501 {
502
503         struct process *p = first_process;
504
505         while (p) {
506                 struct process *current = p;
507
508 #if defined(PARANOID)
509                 assert(p->id == 0x0badfeed);
510 #endif /* defined(PARANOID) */
511
512                 p = p->next;
513                 /* Delete processes that have died */
514                 if (current->time_stamp != g_time) {
515                         delete_process(current);
516                 }
517         }
518 }
519
520 /******************************************
521  * Calculate cpu total                                    *
522  ******************************************/
523 #define TMPL_SHORTPROC "%*s %llu %llu %llu %llu"
524 #define TMPL_LONGPROC "%*s %llu %llu %llu %llu %llu %llu %llu %llu"
525
526 static unsigned long long calc_cpu_total(void)
527 {
528         unsigned long long total = 0;
529         unsigned long long t = 0;
530         int rc;
531         int ps;
532         char line[BUFFER_LEN] = { 0 };
533         unsigned long long cpu = 0;
534         unsigned long long niceval = 0;
535         unsigned long long systemval = 0;
536         unsigned long long idle = 0;
537         unsigned long long iowait = 0;
538         unsigned long long irq = 0;
539         unsigned long long softirq = 0;
540         unsigned long long steal = 0;
541         const char *template =
542                 KFLAG_ISSET(KFLAG_IS_LONGSTAT) ? TMPL_LONGPROC : TMPL_SHORTPROC;
543
544         ps = open("/proc/stat", O_RDONLY);
545         rc = read(ps, line, sizeof(line));
546         close(ps);
547         if (rc < 0) {
548                 return 0;
549         }
550
551         sscanf(line, template, &cpu, &niceval, &systemval, &idle, &iowait, &irq,
552                         &softirq, &steal);
553         total = cpu + niceval + systemval + idle + iowait + irq + softirq + steal;
554
555         t = total - previous_total;
556         previous_total = total;
557
558         return t;
559 }
560
561 /******************************************
562  * Calculate each processes cpu                   *
563  ******************************************/
564
565 inline static void calc_cpu_each(unsigned long long total)
566 {
567         struct process *p = first_process;
568
569         while (p) {
570                 p->amount = 100.0 * (cpu_separate ? info.cpu_count : 1) *
571                         (p->user_time + p->kernel_time) / (float) total;
572
573                 p = p->next;
574         }
575 }
576
577 #ifdef IOSTATS
578 static void calc_io_each(void)
579 {
580         struct process *p;
581         unsigned long long sum = 0;
582
583         for (p = first_process; p; p = p->next)
584                 sum += p->read_bytes + p->write_bytes;
585
586         if(sum == 0)
587                 sum = 1; /* to avoid having NANs if no I/O occured */
588         for (p = first_process; p; p = p->next)
589                 p->io_perc = 100.0 * (p->read_bytes + p->write_bytes) / (float) sum;
590 }
591 #endif /* IOSTATS */
592
593 /******************************************
594  * Find the top processes                                 *
595  ******************************************/
596
597 /* free a sp_process structure */
598 static void free_sp(struct sorted_process *sp)
599 {
600         free(sp);
601 }
602
603 /* create a new sp_process structure */
604 static struct sorted_process *malloc_sp(struct process *proc)
605 {
606         struct sorted_process *sp;
607         sp = malloc(sizeof(struct sorted_process));
608         memset(sp, 0, sizeof(struct sorted_process));
609         sp->proc = proc;
610         return sp;
611 }
612
613 /* cpu comparison function for insert_sp_element */
614 static int compare_cpu(struct process *a, struct process *b)
615 {
616         if (a->amount < b->amount) {
617                 return 1;
618         } else if (a->amount > b->amount) {
619                 return -1;
620         } else {
621                 return 0;
622         }
623 }
624
625 /* mem comparison function for insert_sp_element */
626 static int compare_mem(struct process *a, struct process *b)
627 {
628         if (a->rss < b->rss) {
629                 return 1;
630         } else if (a->rss > b->rss) {
631                 return -1;
632         } else {
633                 return 0;
634         }
635 }
636
637 /* CPU time comparision function for insert_sp_element */
638 static int compare_time(struct process *a, struct process *b)
639 {
640         return b->total_cpu_time - a->total_cpu_time;
641 }
642
643 #ifdef IOSTATS
644 /* I/O comparision function for insert_sp_element */
645 static int compare_io(struct process *a, struct process *b)
646 {
647         if (a->io_perc < b->io_perc) {
648                 return 1;
649         } else if (a->io_perc > b->io_perc) {
650                 return -1;
651         } else {
652                 return 0;
653         }
654 }
655 #endif /* IOSTATS */
656
657 /* insert this process into the list in a sorted fashion,
658  * or destroy it if it doesn't fit on the list */
659 static int insert_sp_element(struct sorted_process *sp_cur,
660                 struct sorted_process **p_sp_head, struct sorted_process **p_sp_tail,
661                 int max_elements, int compare_funct(struct process *, struct process *))
662 {
663
664         struct sorted_process *sp_readthru = NULL, *sp_destroy = NULL;
665         int did_insert = 0, x = 0;
666
667         if (*p_sp_head == NULL) {
668                 *p_sp_head = sp_cur;
669                 *p_sp_tail = sp_cur;
670                 return 1;
671         }
672         for (sp_readthru = *p_sp_head, x = 0;
673                         sp_readthru != NULL && x < max_elements;
674                         sp_readthru = sp_readthru->less, x++) {
675                 if (compare_funct(sp_readthru->proc, sp_cur->proc) > 0 && !did_insert) {
676                         /* sp_cur is bigger than sp_readthru
677                          * so insert it before sp_readthru */
678                         sp_cur->less = sp_readthru;
679                         if (sp_readthru == *p_sp_head) {
680                                 /* insert as the new head of the list */
681                                 *p_sp_head = sp_cur;
682                         } else {
683                                 /* insert inside the list */
684                                 sp_readthru->greater->less = sp_cur;
685                                 sp_cur->greater = sp_readthru->greater;
686                         }
687                         sp_readthru->greater = sp_cur;
688                         /* element was inserted, so increase the counter */
689                         did_insert = ++x;
690                 }
691         }
692         if (x < max_elements && sp_readthru == NULL && !did_insert) {
693                 /* sp_cur is the smallest element and list isn't full,
694                  * so insert at the end */
695                 (*p_sp_tail)->less = sp_cur;
696                 sp_cur->greater = *p_sp_tail;
697                 *p_sp_tail = sp_cur;
698                 did_insert = x;
699         } else if (x >= max_elements) {
700                 /* We inserted an element and now the list is too big by one.
701                  * Destroy the smallest element */
702                 sp_destroy = *p_sp_tail;
703                 *p_sp_tail = sp_destroy->greater;
704                 (*p_sp_tail)->less = NULL;
705                 free_sp(sp_destroy);
706         }
707         if (!did_insert) {
708                 /* sp_cur wasn't added to the sorted list, so destroy it */
709                 free_sp(sp_cur);
710         }
711         return did_insert;
712 }
713
714 /* copy the procs in the sorted list to the array, and destroy the list */
715 static void sp_acopy(struct sorted_process *sp_head, struct process **ar, int max_size)
716 {
717         struct sorted_process *sp_cur, *sp_tmp;
718         int x;
719
720         sp_cur = sp_head;
721         for (x = 0; x < max_size && sp_cur != NULL; x++) {
722                 ar[x] = sp_cur->proc;
723                 sp_tmp = sp_cur;
724                 sp_cur = sp_cur->less;
725                 free_sp(sp_tmp);
726         }
727 }
728
729 /* ****************************************************************** *
730  * Get a sorted list of the top cpu hogs and top mem hogs.                        *
731  * Results are stored in the cpu,mem arrays in decreasing order[0-9]. *
732  * ****************************************************************** */
733
734 void process_find_top(struct process **cpu, struct process **mem,
735                 struct process **ptime
736 #ifdef IOSTATS
737                 , struct process **io
738 #endif /* IOSTATS */
739                 )
740 {
741         struct sorted_process *spc_head = NULL, *spc_tail = NULL, *spc_cur = NULL;
742         struct sorted_process *spm_head = NULL, *spm_tail = NULL, *spm_cur = NULL;
743         struct sorted_process *spt_head = NULL, *spt_tail = NULL, *spt_cur = NULL;
744 #ifdef IOSTATS
745         struct sorted_process *spi_head = NULL, *spi_tail = NULL, *spi_cur = NULL;
746 #endif /* IOSTATS */
747         struct process *cur_proc = NULL;
748         unsigned long long total = 0;
749
750         if (!top_cpu && !top_mem && !top_time
751 #ifdef IOSTATS
752                         && !top_io
753 #endif /* IOSTATS */
754                         && !top_running
755            ) {
756                 return;
757         }
758
759         total = calc_cpu_total();       /* calculate the total of the processor */
760         update_process_table();         /* update the table with process list */
761         calc_cpu_each(total);           /* and then the percentage for each task */
762         process_cleanup();                      /* cleanup list from exited processes */
763 #ifdef IOSTATS
764         calc_io_each();                 /* percentage of I/O for each task */
765 #endif /* IOSTATS */
766
767         cur_proc = first_process;
768
769         while (cur_proc != NULL) {
770                 if (top_cpu) {
771                         spc_cur = malloc_sp(cur_proc);
772                         insert_sp_element(spc_cur, &spc_head, &spc_tail, MAX_SP,
773                                         &compare_cpu);
774                 }
775                 if (top_mem) {
776                         spm_cur = malloc_sp(cur_proc);
777                         insert_sp_element(spm_cur, &spm_head, &spm_tail, MAX_SP,
778                                         &compare_mem);
779                 }
780                 if (top_time) {
781                         spt_cur = malloc_sp(cur_proc);
782                         insert_sp_element(spt_cur, &spt_head, &spt_tail, MAX_SP,
783                                         &compare_time);
784                 }
785 #ifdef IOSTATS
786                 if (top_io) {
787                         spi_cur = malloc_sp(cur_proc);
788                         insert_sp_element(spi_cur, &spi_head, &spi_tail, MAX_SP,
789                                         &compare_io);
790                 }
791 #endif /* IOSTATS */
792                 cur_proc = cur_proc->next;
793         }
794
795         if (top_cpu)    sp_acopy(spc_head, cpu,         MAX_SP);
796         if (top_mem)    sp_acopy(spm_head, mem,         MAX_SP);
797         if (top_time)   sp_acopy(spt_head, ptime,       MAX_SP);
798 #ifdef IOSTATS
799         if (top_io)             sp_acopy(spi_head, io,          MAX_SP);
800 #endif /* IOSTATS */
801 }
802
803 struct top_data {
804         int num;
805         int type;
806         int was_parsed;
807         char *s;
808 };
809
810 int parse_top_args(const char *s, const char *arg, struct text_object *obj)
811 {
812         struct top_data *td;
813         char buf[64];
814         int n;
815
816         if (!arg) {
817                 NORM_ERR("top needs arguments");
818                 return 0;
819         }
820
821         if (obj->data.opaque) {
822                 return 1;
823         }
824
825         if (s[3] == 0) {
826                 obj->type = OBJ_top;
827                 top_cpu = 1;
828         } else if (strcmp(&s[3], "_mem") == EQUAL) {
829                 obj->type = OBJ_top_mem;
830                 top_mem = 1;
831         } else if (strcmp(&s[3], "_time") == EQUAL) {
832                 obj->type = OBJ_top_time;
833                 top_time = 1;
834 #ifdef IOSTATS
835         } else if (strcmp(&s[3], "_io") == EQUAL) {
836                 obj->type = OBJ_top_io;
837                 top_io = 1;
838 #endif /* IOSTATS */
839         } else {
840 #ifdef IOSTATS
841                 NORM_ERR("Must be top, top_mem, top_time or top_io");
842 #else /* IOSTATS */
843                 NORM_ERR("Must be top, top_mem or top_time");
844 #endif /* IOSTATS */
845                 return 0;
846         }
847
848         obj->data.opaque = td = malloc(sizeof(struct top_data));
849         memset(td, 0, sizeof(struct top_data));
850         td->s = strndup(arg, text_buffer_size);
851
852         if (sscanf(arg, "%63s %i", buf, &n) == 2) {
853                 if (strcmp(buf, "name") == EQUAL) {
854                         td->type = TOP_NAME;
855                 } else if (strcmp(buf, "cpu") == EQUAL) {
856                         td->type = TOP_CPU;
857                 } else if (strcmp(buf, "pid") == EQUAL) {
858                         td->type = TOP_PID;
859                 } else if (strcmp(buf, "mem") == EQUAL) {
860                         td->type = TOP_MEM;
861                 } else if (strcmp(buf, "time") == EQUAL) {
862                         td->type = TOP_TIME;
863                 } else if (strcmp(buf, "mem_res") == EQUAL) {
864                         td->type = TOP_MEM_RES;
865                 } else if (strcmp(buf, "mem_vsize") == EQUAL) {
866                         td->type = TOP_MEM_VSIZE;
867 #ifdef IOSTATS
868                 } else if (strcmp(buf, "io_read") == EQUAL) {
869                         td->type = TOP_READ_BYTES;
870                 } else if (strcmp(buf, "io_write") == EQUAL) {
871                         td->type = TOP_WRITE_BYTES;
872                 } else if (strcmp(buf, "io_perc") == EQUAL) {
873                         td->type = TOP_IO_PERC;
874 #endif /* IOSTATS */
875                 } else {
876                         NORM_ERR("invalid type arg for top");
877 #ifdef IOSTATS
878                         NORM_ERR("must be one of: name, cpu, pid, mem, time, mem_res, mem_vsize, "
879                                         "io_read, io_write, io_perc");
880 #else /* IOSTATS */
881                         NORM_ERR("must be one of: name, cpu, pid, mem, time, mem_res, mem_vsize");
882 #endif /* IOSTATS */
883                         free_and_zero(td->s);
884                         free_and_zero(obj->data.opaque);
885                         return 0;
886                 }
887                 if (n < 1 || n > 10) {
888                         NORM_ERR("invalid num arg for top. Must be between 1 and 10.");
889                         free_and_zero(td->s);
890                         free_and_zero(obj->data.opaque);
891                         return 0;
892                 } else {
893                         td->num = n - 1;
894                 }
895         } else {
896                 NORM_ERR("invalid argument count for top");
897                 free_and_zero(td->s);
898                 free_and_zero(obj->data.opaque);
899                 return 0;
900         }
901         return 1;
902 }
903
904 static char *format_time(unsigned long timeval, const int width)
905 {
906         char buf[10];
907         unsigned long nt;       // narrow time, for speed on 32-bit
908         unsigned cc;            // centiseconds
909         unsigned nn;            // multi-purpose whatever
910
911         nt = timeval;
912         cc = nt % 100;          // centiseconds past second
913         nt /= 100;                      // total seconds
914         nn = nt % 60;           // seconds past the minute
915         nt /= 60;                       // total minutes
916         if (width >= snprintf(buf, sizeof buf, "%lu:%02u.%02u",
917                                 nt, nn, cc)) {
918                 return strndup(buf, text_buffer_size);
919         }
920         if (width >= snprintf(buf, sizeof buf, "%lu:%02u", nt, nn)) {
921                 return strndup(buf, text_buffer_size);
922         }
923         nn = nt % 60;           // minutes past the hour
924         nt /= 60;                       // total hours
925         if (width >= snprintf(buf, sizeof buf, "%lu,%02u", nt, nn)) {
926                 return strndup(buf, text_buffer_size);
927         }
928         nn = nt;                        // now also hours
929         if (width >= snprintf(buf, sizeof buf, "%uh", nn)) {
930                 return strndup(buf, text_buffer_size);
931         }
932         nn /= 24;                       // now days
933         if (width >= snprintf(buf, sizeof buf, "%ud", nn)) {
934                 return strndup(buf, text_buffer_size);
935         }
936         nn /= 7;                        // now weeks
937         if (width >= snprintf(buf, sizeof buf, "%uw", nn)) {
938                 return strndup(buf, text_buffer_size);
939         }
940         // well shoot, this outta' fit...
941         return strndup("<inf>", text_buffer_size);
942 }
943
944 static unsigned int top_name_width = 15;
945
946 /* return zero on success, non-zero otherwise */
947 int set_top_name_width(const char *s)
948 {
949         if (!s)
950                 return 0;
951         return !(sscanf(s, "%u", &top_name_width) == 1);
952 }
953
954 void print_top(struct text_object *obj, char *p, int p_max_size)
955 {
956         struct information *cur = &info;
957         struct top_data *td = obj->data.opaque;
958         struct process **needed = 0;
959         int width;
960
961         if (!td)
962                 return;
963
964         switch (obj->type) {
965                 case OBJ_top:
966                         needed = cur->cpu;
967                         break;
968                 case OBJ_top_mem:
969                         needed = cur->memu;
970                         break;
971                 case OBJ_top_time:
972                         needed = cur->time;
973                         break;
974 #ifdef IOSTATS
975                 case OBJ_top_io:
976                         needed = cur->io;
977                         break;
978 #endif /* IOSTATS */
979                 default:
980                         return;
981         }
982
983
984         if (needed[td->num]) {
985                 char *timeval;
986
987                 switch (td->type) {
988                         case TOP_NAME:
989                                 width = MIN(p_max_size, (int)top_name_width + 1);
990                                 snprintf(p, width + 1, "%-*s", width,
991                                                 needed[td->num]->name);
992                                 break;
993                         case TOP_CPU:
994                                 width = MIN(p_max_size, 7);
995                                 snprintf(p, width, "%6.2f",
996                                                 needed[td->num]->amount);
997                                 break;
998                         case TOP_PID:
999                                 width = MIN(p_max_size, 6);
1000                                 snprintf(p, width, "%5i",
1001                                                 needed[td->num]->pid);
1002                                 break;
1003                         case TOP_MEM:
1004                                 /* Calculate a percentage of residential mem from total mem available.
1005                                  * Since rss is bytes and memmax kilobytes, dividing by 10 suffices here. */
1006                                 width = MIN(p_max_size, 7);
1007                                 snprintf(p, width, "%6.2f",
1008                                                 (float) ((float)needed[td->num]->rss / cur->memmax) / 10);
1009                                 break;
1010                         case TOP_TIME:
1011                                 width = MIN(p_max_size, 10);
1012                                 timeval = format_time(
1013                                                 needed[td->num]->total_cpu_time, 9);
1014                                 snprintf(p, width, "%9s", timeval);
1015                                 free(timeval);
1016                                 break;
1017                         case TOP_MEM_RES:
1018                                 human_readable(needed[td->num]->rss,
1019                                                 p, p_max_size);
1020                                 break;
1021                         case TOP_MEM_VSIZE:
1022                                 human_readable(needed[td->num]->vsize,
1023                                                 p, p_max_size);
1024                                 break;
1025 #ifdef IOSTATS
1026                         case TOP_READ_BYTES:
1027                                 human_readable(needed[td->num]->read_bytes / update_interval,
1028                                                 p, p_max_size);
1029                                 break;
1030                         case TOP_WRITE_BYTES:
1031                                 human_readable(needed[td->num]->write_bytes / update_interval,
1032                                                 p, p_max_size);
1033                                 break;
1034                         case TOP_IO_PERC:
1035                                 width = MIN(p_max_size, 7);
1036                                 snprintf(p, width, "%6.2f",
1037                                                 needed[td->num]->io_perc);
1038                                 break;
1039 #endif
1040                 }
1041         }
1042 }
1043
1044 void free_top(struct text_object *obj, int internal)
1045 {
1046         struct top_data *td = obj->data.opaque;
1047
1048         if (info.first_process && !internal) {
1049                 free_all_processes();
1050                 info.first_process = NULL;
1051         }
1052
1053         if (!td)
1054                 return;
1055         if (td->s)
1056                 free(td->s);
1057         free(obj->data.opaque);
1058         obj->data.opaque = NULL;
1059 }