systat: Avoid incorrect reallocation in pigs.c

Stop free() even if kvm_getprocs as we can come back but set nprocs = 0.
Check nprocs in showpigs() to ensure not try displaying with kvm_getprocs failed.
Current code can have pt with non-null after kvm_getprocs() failure.

Replace to realloc for simpler operations.

Submitted by:	Yoshihiro Ota ota@j.email.ne.jp
Reviewed by:	mckusick@
Differential Revision:	https://reviews.freebsd.org/D29303
This commit is contained in:
Michael Reifenberger 2021-04-21 20:09:21 +02:00
parent 9c651561a2
commit dcc2fb3707

View File

@ -62,7 +62,7 @@ static int nproc;
static struct p_times { static struct p_times {
float pt_pctcpu; float pt_pctcpu;
struct kinfo_proc *pt_kp; struct kinfo_proc *pt_kp;
} *pt; } *pt = NULL;
static int fscale; static int fscale;
static double lccpu; static double lccpu;
@ -90,7 +90,7 @@ showpigs(void)
const char *uname, *pname; const char *uname, *pname;
char pidname[30]; char pidname[30];
if (pt == NULL) if (nproc == 0)
return; return;
qsort(pt, nproc, sizeof (struct p_times), compar); qsort(pt, nproc, sizeof (struct p_times), compar);
@ -146,23 +146,20 @@ fetchpigs(void)
float ftime; float ftime;
float *pctp; float *pctp;
struct kinfo_proc *kpp; struct kinfo_proc *kpp;
static int lastnproc = 0; static int maxnproc = 0;
if ((kpp = kvm_getprocs(kd, KERN_PROC_ALL, 0, &nproc)) == NULL) { if ((kpp = kvm_getprocs(kd, KERN_PROC_ALL, 0, &nproc)) == NULL) {
error("%s", kvm_geterr(kd)); error("%s", kvm_geterr(kd));
if (pt) nproc = 0;
free(pt);
return; return;
} }
if (nproc > lastnproc) { if (nproc > maxnproc) {
free(pt); if ((pt = realloc(pt, nproc * sizeof(*pt))) == NULL) {
if ((pt =
malloc(nproc * sizeof(struct p_times))) == NULL) {
error("Out of memory"); error("Out of memory");
die(0); die(0);
} }
maxnproc = nproc;
} }
lastnproc = nproc;
/* /*
* calculate %cpu for each proc * calculate %cpu for each proc
*/ */