[PATCH v2] top: fix and merge code to parse /proc/meminfo

Timo Teräs timo.teras at iki.fi
Mon Jul 21 11:14:24 UTC 2014


display_header() code to parse meminfo as is was buggy:
- uninitialized variables were used if meminfo was not as expected
- meminfo parsing failed on new kernels (3.14+) as new field 'MemAvailable'
  was introduced between MemFree and Buffers
- shared memory was handled only for ancient kernels (2.4.x and earlier)

as result Buffers and shared memory fields were shown with bogus values
on current kernels.

The new code does not try to parse the old style summary header, as the
separated fields are always present (it saves code size). Additionally,
both Shmem (2.6+) and MemShared (2.4 and earlier) fields are now parsed
and summed for shared memory usage; as only one of them exists depending
on kernel version.

display_topmem_header() parses also meminfo so this makes it use the
same code for code shrink.

function                                             old     new   delta
display_header                                         -     681    +681
display_topmem_process_list                          465     684    +219
parse_meminfo                                          -     189    +189
static.fields                                          -     106    +106
static.match                                         132       -    -132
.rodata                                           120254  120117    -137
display_topmem_header                                513       -    -513
display_process_list                                1705     667   -1038
------------------------------------------------------------------------------
(add/remove: 3/2 grow/shrink: 1/2 up/down: 1195/-1820)       Total: -625 bytes

Signed-off-by: Timo Teräs <timo.teras at iki.fi>
---
Fixed typoed printf specifiers from %ul to %lu.

 procps/top.c | 176 ++++++++++++++++++++++++++---------------------------------
 1 file changed, 76 insertions(+), 100 deletions(-)

diff --git a/procps/top.c b/procps/top.c
index 530f45f..bcd0394 100644
--- a/procps/top.c
+++ b/procps/top.c
@@ -499,66 +499,75 @@ static void display_cpus(int scr_width, char *scrbuf, int *lines_rem_p)
 # define display_cpus(scr_width, scrbuf, lines_rem) ((void)0)
 #endif
 
-static unsigned long display_header(int scr_width, int *lines_rem_p)
-{
-	FILE *fp;
-	char buf[80];
-	char scrbuf[80];
-	unsigned long total, used, mfree, shared, buffers, cached;
+enum {
+	MI_MEMTOTAL,
+	MI_MEMFREE,
+	MI_MEMSHARED,
+	MI_SHMEM,
+	MI_BUFFERS,
+	MI_CACHED,
+	MI_SWAPTOTAL,
+	MI_SWAPFREE,
+	MI_DIRTY,
+	MI_WRITEBACK,
+	MI_ANONPAGES,
+	MI_MAPPED,
+	MI_SLAB,
+	MI_MAX
+};
 
-	/* read memory info */
-	fp = xfopen_for_read("meminfo");
+static void parse_meminfo(unsigned long meminfo[MI_MAX])
+{
+	static const char fields[] =
+		"MemTotal\0"
+		"MemFree\0"
+		"MemShared\0"
+		"Shmem\0"
+		"Buffers\0"
+		"Cached\0"
+		"SwapTotal\0"
+		"SwapFree\0"
+		"Dirty\0"
+		"Writeback\0"
+		"AnonPages\0"
+		"Mapped\0"
+		"Slab\0";
+	char buf[80], *c;
+	FILE *f;
+	int i;
 
-	/*
-	 * Old kernels (such as 2.4.x) had a nice summary of memory info that
-	 * we could parse, however this is gone entirely in 2.6. Try parsing
-	 * the old way first, and if that fails, parse each field manually.
-	 *
-	 * First, we read in the first line. Old kernels will have bogus
-	 * strings we don't care about, whereas new kernels will start right
-	 * out with MemTotal:
-	 *                              -- PFM.
-	 */
-	if (fscanf(fp, "MemTotal: %lu %s\n", &total, buf) != 2) {
-		fgets(buf, sizeof(buf), fp);    /* skip first line */
-
-		fscanf(fp, "Mem: %lu %lu %lu %lu %lu %lu",
-			&total, &used, &mfree, &shared, &buffers, &cached);
-		/* convert to kilobytes */
-		used /= 1024;
-		mfree /= 1024;
-		shared /= 1024;
-		buffers /= 1024;
-		cached /= 1024;
-		total /= 1024;
-	} else {
-		/*
-		 * Revert to manual parsing, which incidentally already has the
-		 * sizes in kilobytes. This should be safe for both 2.4 and
-		 * 2.6.
-		 */
-		fscanf(fp, "MemFree: %lu %s\n", &mfree, buf);
+	memset(meminfo, 0, sizeof(meminfo));
+	f = xfopen_for_read("meminfo");
+	while (fgets(buf, sizeof(buf), f)) {
+		c = strchr(buf, ':');
+		if (!c)
+			continue;
+		*c = 0;
+		i = index_in_strings(fields, buf);
+		if (i >= 0)
+			meminfo[i] = strtoul(c+1, NULL, 0);
+	}
+	fclose(f);
+}
 
-		/*
-		 * MemShared: is no longer present in 2.6. Report this as 0,
-		 * to maintain consistent behavior with normal procps.
-		 */
-		if (fscanf(fp, "MemShared: %lu %s\n", &shared, buf) != 2)
-			shared = 0;
 
-		fscanf(fp, "Buffers: %lu %s\n", &buffers, buf);
-		fscanf(fp, "Cached: %lu %s\n", &cached, buf);
+static unsigned long display_header(int scr_width, int *lines_rem_p)
+{
+	char scrbuf[80], buf[80];
+	unsigned long meminfo[MI_MAX];
 
-		used = total - mfree;
-	}
-	fclose(fp);
+	parse_meminfo(meminfo);
 
 	/* output memory info */
 	if (scr_width > (int)sizeof(scrbuf))
 		scr_width = sizeof(scrbuf);
 	snprintf(scrbuf, scr_width,
 		"Mem: %luK used, %luK free, %luK shrd, %luK buff, %luK cached",
-		used, mfree, shared, buffers, cached);
+		meminfo[MI_MEMTOTAL] - meminfo[MI_MEMFREE],
+		meminfo[MI_MEMFREE],
+		meminfo[MI_MEMSHARED] + meminfo[MI_SHMEM],
+		meminfo[MI_BUFFERS],
+		meminfo[MI_CACHED]);
 	/* go to top & clear to the end of screen */
 	printf(OPT_BATCH_MODE ? "%s\n" : "\033[H\033[J%s\n", scrbuf);
 	(*lines_rem_p)--;
@@ -577,7 +586,7 @@ static unsigned long display_header(int scr_width, int *lines_rem_p)
 	puts(scrbuf);
 	(*lines_rem_p)--;
 
-	return total;
+	return meminfo[MI_MEMTOTAL];
 }
 
 static NOINLINE void display_process_list(int lines_rem, int scr_width)
@@ -781,64 +790,31 @@ static int topmem_sort(char *a, char *b)
 /* display header info (meminfo / loadavg) */
 static void display_topmem_header(int scr_width, int *lines_rem_p)
 {
-	enum {
-		TOTAL = 0, MFREE, BUF, CACHE,
-		SWAPTOTAL, SWAPFREE, DIRTY,
-		MWRITE, ANON, MAP, SLAB,
-		NUM_FIELDS
-	};
-	static const char match[NUM_FIELDS][12] = {
-		"\x09" "MemTotal:",  // TOTAL
-		"\x08" "MemFree:",   // MFREE
-		"\x08" "Buffers:",   // BUF
-		"\x07" "Cached:",    // CACHE
-		"\x0a" "SwapTotal:", // SWAPTOTAL
-		"\x09" "SwapFree:",  // SWAPFREE
-		"\x06" "Dirty:",     // DIRTY
-		"\x0a" "Writeback:", // MWRITE
-		"\x0a" "AnonPages:", // ANON
-		"\x07" "Mapped:",    // MAP
-		"\x05" "Slab:",      // SLAB
-	};
-	char meminfo_buf[4 * 1024];
-	const char *Z[NUM_FIELDS];
-	unsigned i;
-	int sz;
-
-	for (i = 0; i < NUM_FIELDS; i++)
-		Z[i] = "?";
-
-	/* read memory info */
-	sz = open_read_close("meminfo", meminfo_buf, sizeof(meminfo_buf) - 1);
-	if (sz >= 0) {
-		char *p = meminfo_buf;
-		meminfo_buf[sz] = '\0';
-		/* Note that fields always appear in the match[] order */
-		for (i = 0; i < NUM_FIELDS; i++) {
-			char *found = strstr(p, match[i] + 1);
-			if (found) {
-				/* Cut "NNNN" out of "    NNNN kb" */
-				char *s = skip_whitespace(found + match[i][0]);
-				p = skip_non_whitespace(s);
-				*p++ = '\0';
-				Z[i] = s;
-			}
-		}
-	}
+	unsigned long meminfo[MI_MAX];
+
+	parse_meminfo(meminfo);
 
 	snprintf(line_buf, LINE_BUF_SIZE,
-		"Mem total:%s anon:%s map:%s free:%s",
-		Z[TOTAL], Z[ANON], Z[MAP], Z[MFREE]);
+		"Mem total:%lu anon:%lu map:%lu free:%lu",
+		meminfo[MI_MEMTOTAL],
+		meminfo[MI_ANONPAGES],
+		meminfo[MI_MAPPED],
+		meminfo[MI_MEMFREE]);
 	printf(OPT_BATCH_MODE ? "%.*s\n" : "\033[H\033[J%.*s\n", scr_width, line_buf);
 
 	snprintf(line_buf, LINE_BUF_SIZE,
-		" slab:%s buf:%s cache:%s dirty:%s write:%s",
-		Z[SLAB], Z[BUF], Z[CACHE], Z[DIRTY], Z[MWRITE]);
+		" slab:%lu buf:%lu cache:%lu dirty:%lu write:%lu",
+		meminfo[MI_SLAB],
+		meminfo[MI_BUFFERS],
+		meminfo[MI_CACHED],
+		meminfo[MI_DIRTY],
+		meminfo[MI_WRITEBACK]);
 	printf("%.*s\n", scr_width, line_buf);
 
 	snprintf(line_buf, LINE_BUF_SIZE,
-		"Swap total:%s free:%s", // TODO: % used?
-		Z[SWAPTOTAL], Z[SWAPFREE]);
+		"Swap total:%lu free:%lu", // TODO: % used?
+		meminfo[MI_SWAPTOTAL],
+		meminfo[MI_SWAPFREE]);
 	printf("%.*s\n", scr_width, line_buf);
 
 	(*lines_rem_p) -= 3;
-- 
2.0.2



More information about the busybox mailing list