Subject: [PATCH bpf-next 3/6] bpftool: don't print empty key/value for maps

From: Stanislav Fomichev <[email-masked]>
Date: Tue, 15 Jan 2019 15:22:49 -0800

When doing dump or lookup, don't print key if key_size == 0 or value if
value_size == 0. The initial usecase is queue and stack, where we have
only values.

This is for regular output only, json still has all the fields.

Before:
bpftool map create /sys/fs/bpf/q type queue value 4 entries 10 name q
bpftool map update pinned /sys/fs/bpf/q value 0 1 2 3
bpftool map lookup pinned /sys/fs/bpf/q
key:   value: 00 01 02 03

After:
bpftool map create /sys/fs/bpf/q type queue value 4 entries 10 name q
bpftool map update pinned /sys/fs/bpf/q value 0 1 2 3
bpftool map lookup pinned /sys/fs/bpf/q
value: 00 01 02 03

Signed-off-by: Stanislav Fomichev <[email-masked]>
---
 tools/bpf/bpftool/map.c | 47 ++++++++++++++++++++++++-----------------
 1 file changed, 28 insertions(+), 19 deletions(-)

diff --git a/tools/bpf/bpftool/map.c b/tools/bpf/bpftool/map.c
index 4256842f9664..3f599399913b 100644
--- a/tools/bpf/bpftool/map.c
+++ b/tools/bpf/bpftool/map.c
@@ -285,16 +285,21 @@ static void print_entry_plain(struct bpf_map_info *info, unsigned char *key,
 		single_line = info->key_size + info->value_size <= 24 &&
 			!break_names;
 
-		printf("key:%c", break_names ? '\n' : ' ');
-		fprint_hex(stdout, key, info->key_size, " ");
+		if (info->key_size) {
+			printf("key:%c", break_names ? '\n' : ' ');
+			fprint_hex(stdout, key, info->key_size, " ");
 
-		printf(single_line ? "  " : "\n");
+			printf(single_line ? "  " : "\n");
+		}
 
-		printf("value:%c", break_names ? '\n' : ' ');
-		if (value)
-			fprint_hex(stdout, value, info->value_size, " ");
-		else
-			printf("<no entry>");
+		if (info->value_size) {
+			printf("value:%c", break_names ? '\n' : ' ');
+			if (value)
+				fprint_hex(stdout, value, info->value_size,
+					   " ");
+			else
+				printf("<no entry>");
+		}
 
 		printf("\n");
 	} else {
@@ -303,19 +308,23 @@ static void print_entry_plain(struct bpf_map_info *info, unsigned char *key,
 		n = get_possible_cpus();
 		step = round_up(info->value_size, 8);
 
-		printf("key:\n");
-		fprint_hex(stdout, key, info->key_size, " ");
-		printf("\n");
-		for (i = 0; i < n; i++) {
-			printf("value (CPU %02d):%c",
-			       i, info->value_size > 16 ? '\n' : ' ');
-			if (value)
-				fprint_hex(stdout, value + i * step,
-					   info->value_size, " ");
-			else
-				printf("<no entry>");
+		if (info->key_size) {
+			printf("key:\n");
+			fprint_hex(stdout, key, info->key_size, " ");
 			printf("\n");
 		}
+		if (info->value_size) {
+			for (i = 0; i < n; i++) {
+				printf("value (CPU %02d):%c",
+				       i, info->value_size > 16 ? '\n' : ' ');
+				if (value)
+					fprint_hex(stdout, value + i * step,
+						   info->value_size, " ");
+				else
+					printf("<no entry>");
+				printf("\n");
+			}
+		}
 	}
 }
 
-- 
2.20.1.97.g81188d93c3-goog