xref: /openbmc/linux/tools/bpf/bpftool/map.c (revision 7d7209cb)
1 // SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause)
2 /* Copyright (C) 2017-2018 Netronome Systems, Inc. */
3 
4 #include <assert.h>
5 #include <errno.h>
6 #include <fcntl.h>
7 #include <linux/err.h>
8 #include <linux/kernel.h>
9 #include <net/if.h>
10 #include <stdbool.h>
11 #include <stdio.h>
12 #include <stdlib.h>
13 #include <string.h>
14 #include <unistd.h>
15 #include <sys/types.h>
16 #include <sys/stat.h>
17 
18 #include <bpf.h>
19 
20 #include "btf.h"
21 #include "json_writer.h"
22 #include "main.h"
23 
24 static const char * const map_type_name[] = {
25 	[BPF_MAP_TYPE_UNSPEC]			= "unspec",
26 	[BPF_MAP_TYPE_HASH]			= "hash",
27 	[BPF_MAP_TYPE_ARRAY]			= "array",
28 	[BPF_MAP_TYPE_PROG_ARRAY]		= "prog_array",
29 	[BPF_MAP_TYPE_PERF_EVENT_ARRAY]		= "perf_event_array",
30 	[BPF_MAP_TYPE_PERCPU_HASH]		= "percpu_hash",
31 	[BPF_MAP_TYPE_PERCPU_ARRAY]		= "percpu_array",
32 	[BPF_MAP_TYPE_STACK_TRACE]		= "stack_trace",
33 	[BPF_MAP_TYPE_CGROUP_ARRAY]		= "cgroup_array",
34 	[BPF_MAP_TYPE_LRU_HASH]			= "lru_hash",
35 	[BPF_MAP_TYPE_LRU_PERCPU_HASH]		= "lru_percpu_hash",
36 	[BPF_MAP_TYPE_LPM_TRIE]			= "lpm_trie",
37 	[BPF_MAP_TYPE_ARRAY_OF_MAPS]		= "array_of_maps",
38 	[BPF_MAP_TYPE_HASH_OF_MAPS]		= "hash_of_maps",
39 	[BPF_MAP_TYPE_DEVMAP]			= "devmap",
40 	[BPF_MAP_TYPE_SOCKMAP]			= "sockmap",
41 	[BPF_MAP_TYPE_CPUMAP]			= "cpumap",
42 	[BPF_MAP_TYPE_XSKMAP]			= "xskmap",
43 	[BPF_MAP_TYPE_SOCKHASH]			= "sockhash",
44 	[BPF_MAP_TYPE_CGROUP_STORAGE]		= "cgroup_storage",
45 	[BPF_MAP_TYPE_REUSEPORT_SOCKARRAY]	= "reuseport_sockarray",
46 	[BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE]	= "percpu_cgroup_storage",
47 	[BPF_MAP_TYPE_QUEUE]			= "queue",
48 	[BPF_MAP_TYPE_STACK]			= "stack",
49 };
50 
51 static bool map_is_per_cpu(__u32 type)
52 {
53 	return type == BPF_MAP_TYPE_PERCPU_HASH ||
54 	       type == BPF_MAP_TYPE_PERCPU_ARRAY ||
55 	       type == BPF_MAP_TYPE_LRU_PERCPU_HASH ||
56 	       type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE;
57 }
58 
59 static bool map_is_map_of_maps(__u32 type)
60 {
61 	return type == BPF_MAP_TYPE_ARRAY_OF_MAPS ||
62 	       type == BPF_MAP_TYPE_HASH_OF_MAPS;
63 }
64 
65 static bool map_is_map_of_progs(__u32 type)
66 {
67 	return type == BPF_MAP_TYPE_PROG_ARRAY;
68 }
69 
70 static int map_type_from_str(const char *type)
71 {
72 	unsigned int i;
73 
74 	for (i = 0; i < ARRAY_SIZE(map_type_name); i++)
75 		/* Don't allow prefixing in case of possible future shadowing */
76 		if (map_type_name[i] && !strcmp(map_type_name[i], type))
77 			return i;
78 	return -1;
79 }
80 
81 static void *alloc_value(struct bpf_map_info *info)
82 {
83 	if (map_is_per_cpu(info->type))
84 		return malloc(round_up(info->value_size, 8) *
85 			      get_possible_cpus());
86 	else
87 		return malloc(info->value_size);
88 }
89 
90 int map_parse_fd(int *argc, char ***argv)
91 {
92 	int fd;
93 
94 	if (is_prefix(**argv, "id")) {
95 		unsigned int id;
96 		char *endptr;
97 
98 		NEXT_ARGP();
99 
100 		id = strtoul(**argv, &endptr, 0);
101 		if (*endptr) {
102 			p_err("can't parse %s as ID", **argv);
103 			return -1;
104 		}
105 		NEXT_ARGP();
106 
107 		fd = bpf_map_get_fd_by_id(id);
108 		if (fd < 0)
109 			p_err("get map by id (%u): %s", id, strerror(errno));
110 		return fd;
111 	} else if (is_prefix(**argv, "pinned")) {
112 		char *path;
113 
114 		NEXT_ARGP();
115 
116 		path = **argv;
117 		NEXT_ARGP();
118 
119 		return open_obj_pinned_any(path, BPF_OBJ_MAP);
120 	}
121 
122 	p_err("expected 'id' or 'pinned', got: '%s'?", **argv);
123 	return -1;
124 }
125 
126 int map_parse_fd_and_info(int *argc, char ***argv, void *info, __u32 *info_len)
127 {
128 	int err;
129 	int fd;
130 
131 	fd = map_parse_fd(argc, argv);
132 	if (fd < 0)
133 		return -1;
134 
135 	err = bpf_obj_get_info_by_fd(fd, info, info_len);
136 	if (err) {
137 		p_err("can't get map info: %s", strerror(errno));
138 		close(fd);
139 		return err;
140 	}
141 
142 	return fd;
143 }
144 
145 static int do_dump_btf(const struct btf_dumper *d,
146 		       struct bpf_map_info *map_info, void *key,
147 		       void *value)
148 {
149 	int ret;
150 
151 	/* start of key-value pair */
152 	jsonw_start_object(d->jw);
153 
154 	jsonw_name(d->jw, "key");
155 
156 	ret = btf_dumper_type(d, map_info->btf_key_type_id, key);
157 	if (ret)
158 		goto err_end_obj;
159 
160 	if (!map_is_per_cpu(map_info->type)) {
161 		jsonw_name(d->jw, "value");
162 		ret = btf_dumper_type(d, map_info->btf_value_type_id, value);
163 	} else {
164 		unsigned int i, n, step;
165 
166 		jsonw_name(d->jw, "values");
167 		jsonw_start_array(d->jw);
168 		n = get_possible_cpus();
169 		step = round_up(map_info->value_size, 8);
170 		for (i = 0; i < n; i++) {
171 			jsonw_start_object(d->jw);
172 			jsonw_int_field(d->jw, "cpu", i);
173 			jsonw_name(d->jw, "value");
174 			ret = btf_dumper_type(d, map_info->btf_value_type_id,
175 					      value + i * step);
176 			jsonw_end_object(d->jw);
177 			if (ret)
178 				break;
179 		}
180 		jsonw_end_array(d->jw);
181 	}
182 
183 err_end_obj:
184 	/* end of key-value pair */
185 	jsonw_end_object(d->jw);
186 
187 	return ret;
188 }
189 
190 static json_writer_t *get_btf_writer(void)
191 {
192 	json_writer_t *jw = jsonw_new(stdout);
193 
194 	if (!jw)
195 		return NULL;
196 	jsonw_pretty(jw, true);
197 
198 	return jw;
199 }
200 
201 static void print_entry_json(struct bpf_map_info *info, unsigned char *key,
202 			     unsigned char *value, struct btf *btf)
203 {
204 	jsonw_start_object(json_wtr);
205 
206 	if (!map_is_per_cpu(info->type)) {
207 		jsonw_name(json_wtr, "key");
208 		print_hex_data_json(key, info->key_size);
209 		jsonw_name(json_wtr, "value");
210 		print_hex_data_json(value, info->value_size);
211 		if (btf) {
212 			struct btf_dumper d = {
213 				.btf = btf,
214 				.jw = json_wtr,
215 				.is_plain_text = false,
216 			};
217 
218 			jsonw_name(json_wtr, "formatted");
219 			do_dump_btf(&d, info, key, value);
220 		}
221 	} else {
222 		unsigned int i, n, step;
223 
224 		n = get_possible_cpus();
225 		step = round_up(info->value_size, 8);
226 
227 		jsonw_name(json_wtr, "key");
228 		print_hex_data_json(key, info->key_size);
229 
230 		jsonw_name(json_wtr, "values");
231 		jsonw_start_array(json_wtr);
232 		for (i = 0; i < n; i++) {
233 			jsonw_start_object(json_wtr);
234 
235 			jsonw_int_field(json_wtr, "cpu", i);
236 
237 			jsonw_name(json_wtr, "value");
238 			print_hex_data_json(value + i * step,
239 					    info->value_size);
240 
241 			jsonw_end_object(json_wtr);
242 		}
243 		jsonw_end_array(json_wtr);
244 		if (btf) {
245 			struct btf_dumper d = {
246 				.btf = btf,
247 				.jw = json_wtr,
248 				.is_plain_text = false,
249 			};
250 
251 			jsonw_name(json_wtr, "formatted");
252 			do_dump_btf(&d, info, key, value);
253 		}
254 	}
255 
256 	jsonw_end_object(json_wtr);
257 }
258 
259 static void print_entry_error(struct bpf_map_info *info, unsigned char *key,
260 			      const char *value)
261 {
262 	int value_size = strlen(value);
263 	bool single_line, break_names;
264 
265 	break_names = info->key_size > 16 || value_size > 16;
266 	single_line = info->key_size + value_size <= 24 && !break_names;
267 
268 	printf("key:%c", break_names ? '\n' : ' ');
269 	fprint_hex(stdout, key, info->key_size, " ");
270 
271 	printf(single_line ? "  " : "\n");
272 
273 	printf("value:%c%s", break_names ? '\n' : ' ', value);
274 
275 	printf("\n");
276 }
277 
278 static void print_entry_plain(struct bpf_map_info *info, unsigned char *key,
279 			      unsigned char *value)
280 {
281 	if (!map_is_per_cpu(info->type)) {
282 		bool single_line, break_names;
283 
284 		break_names = info->key_size > 16 || info->value_size > 16;
285 		single_line = info->key_size + info->value_size <= 24 &&
286 			!break_names;
287 
288 		printf("key:%c", break_names ? '\n' : ' ');
289 		fprint_hex(stdout, key, info->key_size, " ");
290 
291 		printf(single_line ? "  " : "\n");
292 
293 		printf("value:%c", break_names ? '\n' : ' ');
294 		if (value)
295 			fprint_hex(stdout, value, info->value_size, " ");
296 		else
297 			printf("<no entry>");
298 
299 		printf("\n");
300 	} else {
301 		unsigned int i, n, step;
302 
303 		n = get_possible_cpus();
304 		step = round_up(info->value_size, 8);
305 
306 		printf("key:\n");
307 		fprint_hex(stdout, key, info->key_size, " ");
308 		printf("\n");
309 		for (i = 0; i < n; i++) {
310 			printf("value (CPU %02d):%c",
311 			       i, info->value_size > 16 ? '\n' : ' ');
312 			if (value)
313 				fprint_hex(stdout, value + i * step,
314 					   info->value_size, " ");
315 			else
316 				printf("<no entry>");
317 			printf("\n");
318 		}
319 	}
320 }
321 
322 static char **parse_bytes(char **argv, const char *name, unsigned char *val,
323 			  unsigned int n)
324 {
325 	unsigned int i = 0, base = 0;
326 	char *endptr;
327 
328 	if (is_prefix(*argv, "hex")) {
329 		base = 16;
330 		argv++;
331 	}
332 
333 	while (i < n && argv[i]) {
334 		val[i] = strtoul(argv[i], &endptr, base);
335 		if (*endptr) {
336 			p_err("error parsing byte: %s", argv[i]);
337 			return NULL;
338 		}
339 		i++;
340 	}
341 
342 	if (i != n) {
343 		p_err("%s expected %d bytes got %d", name, n, i);
344 		return NULL;
345 	}
346 
347 	return argv + i;
348 }
349 
350 static int parse_elem(char **argv, struct bpf_map_info *info,
351 		      void *key, void *value, __u32 key_size, __u32 value_size,
352 		      __u32 *flags, __u32 **value_fd)
353 {
354 	if (!*argv) {
355 		if (!key && !value)
356 			return 0;
357 		p_err("did not find %s", key ? "key" : "value");
358 		return -1;
359 	}
360 
361 	if (is_prefix(*argv, "key")) {
362 		if (!key) {
363 			if (key_size)
364 				p_err("duplicate key");
365 			else
366 				p_err("unnecessary key");
367 			return -1;
368 		}
369 
370 		argv = parse_bytes(argv + 1, "key", key, key_size);
371 		if (!argv)
372 			return -1;
373 
374 		return parse_elem(argv, info, NULL, value, key_size, value_size,
375 				  flags, value_fd);
376 	} else if (is_prefix(*argv, "value")) {
377 		int fd;
378 
379 		if (!value) {
380 			if (value_size)
381 				p_err("duplicate value");
382 			else
383 				p_err("unnecessary value");
384 			return -1;
385 		}
386 
387 		argv++;
388 
389 		if (map_is_map_of_maps(info->type)) {
390 			int argc = 2;
391 
392 			if (value_size != 4) {
393 				p_err("value smaller than 4B for map in map?");
394 				return -1;
395 			}
396 			if (!argv[0] || !argv[1]) {
397 				p_err("not enough value arguments for map in map");
398 				return -1;
399 			}
400 
401 			fd = map_parse_fd(&argc, &argv);
402 			if (fd < 0)
403 				return -1;
404 
405 			*value_fd = value;
406 			**value_fd = fd;
407 		} else if (map_is_map_of_progs(info->type)) {
408 			int argc = 2;
409 
410 			if (value_size != 4) {
411 				p_err("value smaller than 4B for map of progs?");
412 				return -1;
413 			}
414 			if (!argv[0] || !argv[1]) {
415 				p_err("not enough value arguments for map of progs");
416 				return -1;
417 			}
418 
419 			fd = prog_parse_fd(&argc, &argv);
420 			if (fd < 0)
421 				return -1;
422 
423 			*value_fd = value;
424 			**value_fd = fd;
425 		} else {
426 			argv = parse_bytes(argv, "value", value, value_size);
427 			if (!argv)
428 				return -1;
429 		}
430 
431 		return parse_elem(argv, info, key, NULL, key_size, value_size,
432 				  flags, NULL);
433 	} else if (is_prefix(*argv, "any") || is_prefix(*argv, "noexist") ||
434 		   is_prefix(*argv, "exist")) {
435 		if (!flags) {
436 			p_err("flags specified multiple times: %s", *argv);
437 			return -1;
438 		}
439 
440 		if (is_prefix(*argv, "any"))
441 			*flags = BPF_ANY;
442 		else if (is_prefix(*argv, "noexist"))
443 			*flags = BPF_NOEXIST;
444 		else if (is_prefix(*argv, "exist"))
445 			*flags = BPF_EXIST;
446 
447 		return parse_elem(argv + 1, info, key, value, key_size,
448 				  value_size, NULL, value_fd);
449 	}
450 
451 	p_err("expected key or value, got: %s", *argv);
452 	return -1;
453 }
454 
455 static int show_map_close_json(int fd, struct bpf_map_info *info)
456 {
457 	char *memlock;
458 
459 	memlock = get_fdinfo(fd, "memlock");
460 
461 	jsonw_start_object(json_wtr);
462 
463 	jsonw_uint_field(json_wtr, "id", info->id);
464 	if (info->type < ARRAY_SIZE(map_type_name))
465 		jsonw_string_field(json_wtr, "type",
466 				   map_type_name[info->type]);
467 	else
468 		jsonw_uint_field(json_wtr, "type", info->type);
469 
470 	if (*info->name)
471 		jsonw_string_field(json_wtr, "name", info->name);
472 
473 	jsonw_name(json_wtr, "flags");
474 	jsonw_printf(json_wtr, "%d", info->map_flags);
475 
476 	print_dev_json(info->ifindex, info->netns_dev, info->netns_ino);
477 
478 	jsonw_uint_field(json_wtr, "bytes_key", info->key_size);
479 	jsonw_uint_field(json_wtr, "bytes_value", info->value_size);
480 	jsonw_uint_field(json_wtr, "max_entries", info->max_entries);
481 
482 	if (memlock)
483 		jsonw_int_field(json_wtr, "bytes_memlock", atoi(memlock));
484 	free(memlock);
485 
486 	if (info->type == BPF_MAP_TYPE_PROG_ARRAY) {
487 		char *owner_prog_type = get_fdinfo(fd, "owner_prog_type");
488 		char *owner_jited = get_fdinfo(fd, "owner_jited");
489 
490 		if (owner_prog_type) {
491 			unsigned int prog_type = atoi(owner_prog_type);
492 
493 			if (prog_type < ARRAY_SIZE(prog_type_name))
494 				jsonw_string_field(json_wtr, "owner_prog_type",
495 						   prog_type_name[prog_type]);
496 			else
497 				jsonw_uint_field(json_wtr, "owner_prog_type",
498 						 prog_type);
499 		}
500 		if (atoi(owner_jited))
501 			jsonw_bool_field(json_wtr, "owner_jited", true);
502 		else
503 			jsonw_bool_field(json_wtr, "owner_jited", false);
504 
505 		free(owner_prog_type);
506 		free(owner_jited);
507 	}
508 	close(fd);
509 
510 	if (!hash_empty(map_table.table)) {
511 		struct pinned_obj *obj;
512 
513 		jsonw_name(json_wtr, "pinned");
514 		jsonw_start_array(json_wtr);
515 		hash_for_each_possible(map_table.table, obj, hash, info->id) {
516 			if (obj->id == info->id)
517 				jsonw_string(json_wtr, obj->path);
518 		}
519 		jsonw_end_array(json_wtr);
520 	}
521 
522 	jsonw_end_object(json_wtr);
523 
524 	return 0;
525 }
526 
527 static int show_map_close_plain(int fd, struct bpf_map_info *info)
528 {
529 	char *memlock;
530 
531 	memlock = get_fdinfo(fd, "memlock");
532 
533 	printf("%u: ", info->id);
534 	if (info->type < ARRAY_SIZE(map_type_name))
535 		printf("%s  ", map_type_name[info->type]);
536 	else
537 		printf("type %u  ", info->type);
538 
539 	if (*info->name)
540 		printf("name %s  ", info->name);
541 
542 	printf("flags 0x%x", info->map_flags);
543 	print_dev_plain(info->ifindex, info->netns_dev, info->netns_ino);
544 	printf("\n");
545 	printf("\tkey %uB  value %uB  max_entries %u",
546 	       info->key_size, info->value_size, info->max_entries);
547 
548 	if (memlock)
549 		printf("  memlock %sB", memlock);
550 	free(memlock);
551 
552 	if (info->type == BPF_MAP_TYPE_PROG_ARRAY) {
553 		char *owner_prog_type = get_fdinfo(fd, "owner_prog_type");
554 		char *owner_jited = get_fdinfo(fd, "owner_jited");
555 
556 		printf("\n\t");
557 		if (owner_prog_type) {
558 			unsigned int prog_type = atoi(owner_prog_type);
559 
560 			if (prog_type < ARRAY_SIZE(prog_type_name))
561 				printf("owner_prog_type %s  ",
562 				       prog_type_name[prog_type]);
563 			else
564 				printf("owner_prog_type %d  ", prog_type);
565 		}
566 		if (atoi(owner_jited))
567 			printf("owner jited");
568 		else
569 			printf("owner not jited");
570 
571 		free(owner_prog_type);
572 		free(owner_jited);
573 	}
574 	close(fd);
575 
576 	printf("\n");
577 	if (!hash_empty(map_table.table)) {
578 		struct pinned_obj *obj;
579 
580 		hash_for_each_possible(map_table.table, obj, hash, info->id) {
581 			if (obj->id == info->id)
582 				printf("\tpinned %s\n", obj->path);
583 		}
584 	}
585 	return 0;
586 }
587 
588 static int do_show(int argc, char **argv)
589 {
590 	struct bpf_map_info info = {};
591 	__u32 len = sizeof(info);
592 	__u32 id = 0;
593 	int err;
594 	int fd;
595 
596 	if (show_pinned)
597 		build_pinned_obj_table(&map_table, BPF_OBJ_MAP);
598 
599 	if (argc == 2) {
600 		fd = map_parse_fd_and_info(&argc, &argv, &info, &len);
601 		if (fd < 0)
602 			return -1;
603 
604 		if (json_output)
605 			return show_map_close_json(fd, &info);
606 		else
607 			return show_map_close_plain(fd, &info);
608 	}
609 
610 	if (argc)
611 		return BAD_ARG();
612 
613 	if (json_output)
614 		jsonw_start_array(json_wtr);
615 	while (true) {
616 		err = bpf_map_get_next_id(id, &id);
617 		if (err) {
618 			if (errno == ENOENT)
619 				break;
620 			p_err("can't get next map: %s%s", strerror(errno),
621 			      errno == EINVAL ? " -- kernel too old?" : "");
622 			break;
623 		}
624 
625 		fd = bpf_map_get_fd_by_id(id);
626 		if (fd < 0) {
627 			if (errno == ENOENT)
628 				continue;
629 			p_err("can't get map by id (%u): %s",
630 			      id, strerror(errno));
631 			break;
632 		}
633 
634 		err = bpf_obj_get_info_by_fd(fd, &info, &len);
635 		if (err) {
636 			p_err("can't get map info: %s", strerror(errno));
637 			close(fd);
638 			break;
639 		}
640 
641 		if (json_output)
642 			show_map_close_json(fd, &info);
643 		else
644 			show_map_close_plain(fd, &info);
645 	}
646 	if (json_output)
647 		jsonw_end_array(json_wtr);
648 
649 	return errno == ENOENT ? 0 : -1;
650 }
651 
652 static int dump_map_elem(int fd, void *key, void *value,
653 			 struct bpf_map_info *map_info, struct btf *btf,
654 			 json_writer_t *btf_wtr)
655 {
656 	int num_elems = 0;
657 	int lookup_errno;
658 
659 	if (!bpf_map_lookup_elem(fd, key, value)) {
660 		if (json_output) {
661 			print_entry_json(map_info, key, value, btf);
662 		} else {
663 			if (btf) {
664 				struct btf_dumper d = {
665 					.btf = btf,
666 					.jw = btf_wtr,
667 					.is_plain_text = true,
668 				};
669 
670 				do_dump_btf(&d, map_info, key, value);
671 			} else {
672 				print_entry_plain(map_info, key, value);
673 			}
674 			num_elems++;
675 		}
676 		return num_elems;
677 	}
678 
679 	/* lookup error handling */
680 	lookup_errno = errno;
681 
682 	if (map_is_map_of_maps(map_info->type) ||
683 	    map_is_map_of_progs(map_info->type))
684 		return 0;
685 
686 	if (json_output) {
687 		jsonw_name(json_wtr, "key");
688 		print_hex_data_json(key, map_info->key_size);
689 		jsonw_name(json_wtr, "value");
690 		jsonw_start_object(json_wtr);
691 		jsonw_string_field(json_wtr, "error", strerror(lookup_errno));
692 		jsonw_end_object(json_wtr);
693 	} else {
694 		if (errno == ENOENT)
695 			print_entry_plain(map_info, key, NULL);
696 		else
697 			print_entry_error(map_info, key,
698 					  strerror(lookup_errno));
699 	}
700 
701 	return 0;
702 }
703 
704 static int do_dump(int argc, char **argv)
705 {
706 	struct bpf_map_info info = {};
707 	void *key, *value, *prev_key;
708 	unsigned int num_elems = 0;
709 	__u32 len = sizeof(info);
710 	json_writer_t *btf_wtr;
711 	struct btf *btf = NULL;
712 	int err;
713 	int fd;
714 
715 	if (argc != 2)
716 		usage();
717 
718 	fd = map_parse_fd_and_info(&argc, &argv, &info, &len);
719 	if (fd < 0)
720 		return -1;
721 
722 	key = malloc(info.key_size);
723 	value = alloc_value(&info);
724 	if (!key || !value) {
725 		p_err("mem alloc failed");
726 		err = -1;
727 		goto exit_free;
728 	}
729 
730 	prev_key = NULL;
731 
732 	err = btf__get_from_id(info.btf_id, &btf);
733 	if (err) {
734 		p_err("failed to get btf");
735 		goto exit_free;
736 	}
737 
738 	if (json_output)
739 		jsonw_start_array(json_wtr);
740 	else
741 		if (btf) {
742 			btf_wtr = get_btf_writer();
743 			if (!btf_wtr) {
744 				p_info("failed to create json writer for btf. falling back to plain output");
745 				btf__free(btf);
746 				btf = NULL;
747 			} else {
748 				jsonw_start_array(btf_wtr);
749 			}
750 		}
751 
752 	while (true) {
753 		err = bpf_map_get_next_key(fd, prev_key, key);
754 		if (err) {
755 			if (errno == ENOENT)
756 				err = 0;
757 			break;
758 		}
759 		num_elems += dump_map_elem(fd, key, value, &info, btf, btf_wtr);
760 		prev_key = key;
761 	}
762 
763 	if (json_output)
764 		jsonw_end_array(json_wtr);
765 	else if (btf) {
766 		jsonw_end_array(btf_wtr);
767 		jsonw_destroy(&btf_wtr);
768 	} else {
769 		printf("Found %u element%s\n", num_elems,
770 		       num_elems != 1 ? "s" : "");
771 	}
772 
773 exit_free:
774 	free(key);
775 	free(value);
776 	close(fd);
777 	btf__free(btf);
778 
779 	return err;
780 }
781 
782 static int alloc_key_value(struct bpf_map_info *info, void **key, void **value)
783 {
784 	*key = NULL;
785 	*value = NULL;
786 
787 	if (info->key_size) {
788 		*key = malloc(info->key_size);
789 		if (!*key) {
790 			p_err("key mem alloc failed");
791 			return -1;
792 		}
793 	}
794 
795 	if (info->value_size) {
796 		*value = alloc_value(info);
797 		if (!*value) {
798 			p_err("value mem alloc failed");
799 			free(*key);
800 			*key = NULL;
801 			return -1;
802 		}
803 	}
804 
805 	return 0;
806 }
807 
808 static int do_update(int argc, char **argv)
809 {
810 	struct bpf_map_info info = {};
811 	__u32 len = sizeof(info);
812 	__u32 *value_fd = NULL;
813 	__u32 flags = BPF_ANY;
814 	void *key, *value;
815 	int fd, err;
816 
817 	if (argc < 2)
818 		usage();
819 
820 	fd = map_parse_fd_and_info(&argc, &argv, &info, &len);
821 	if (fd < 0)
822 		return -1;
823 
824 	err = alloc_key_value(&info, &key, &value);
825 	if (err)
826 		goto exit_free;
827 
828 	err = parse_elem(argv, &info, key, value, info.key_size,
829 			 info.value_size, &flags, &value_fd);
830 	if (err)
831 		goto exit_free;
832 
833 	err = bpf_map_update_elem(fd, key, value, flags);
834 	if (err) {
835 		p_err("update failed: %s", strerror(errno));
836 		goto exit_free;
837 	}
838 
839 exit_free:
840 	if (value_fd)
841 		close(*value_fd);
842 	free(key);
843 	free(value);
844 	close(fd);
845 
846 	if (!err && json_output)
847 		jsonw_null(json_wtr);
848 	return err;
849 }
850 
851 static int do_lookup(int argc, char **argv)
852 {
853 	struct bpf_map_info info = {};
854 	__u32 len = sizeof(info);
855 	json_writer_t *btf_wtr;
856 	struct btf *btf = NULL;
857 	void *key, *value;
858 	int err;
859 	int fd;
860 
861 	if (argc < 2)
862 		usage();
863 
864 	fd = map_parse_fd_and_info(&argc, &argv, &info, &len);
865 	if (fd < 0)
866 		return -1;
867 
868 	key = malloc(info.key_size);
869 	value = alloc_value(&info);
870 	if (!key || !value) {
871 		p_err("mem alloc failed");
872 		err = -1;
873 		goto exit_free;
874 	}
875 
876 	err = parse_elem(argv, &info, key, NULL, info.key_size, 0, NULL, NULL);
877 	if (err)
878 		goto exit_free;
879 
880 	err = bpf_map_lookup_elem(fd, key, value);
881 	if (err) {
882 		if (errno == ENOENT) {
883 			if (json_output) {
884 				jsonw_null(json_wtr);
885 			} else {
886 				printf("key:\n");
887 				fprint_hex(stdout, key, info.key_size, " ");
888 				printf("\n\nNot found\n");
889 			}
890 		} else {
891 			p_err("lookup failed: %s", strerror(errno));
892 		}
893 
894 		goto exit_free;
895 	}
896 
897 	/* here means bpf_map_lookup_elem() succeeded */
898 	err = btf__get_from_id(info.btf_id, &btf);
899 	if (err) {
900 		p_err("failed to get btf");
901 		goto exit_free;
902 	}
903 
904 	if (json_output) {
905 		print_entry_json(&info, key, value, btf);
906 	} else if (btf) {
907 		/* if here json_wtr wouldn't have been initialised,
908 		 * so let's create separate writer for btf
909 		 */
910 		btf_wtr = get_btf_writer();
911 		if (!btf_wtr) {
912 			p_info("failed to create json writer for btf. falling back to plain output");
913 			btf__free(btf);
914 			btf = NULL;
915 			print_entry_plain(&info, key, value);
916 		} else {
917 			struct btf_dumper d = {
918 				.btf = btf,
919 				.jw = btf_wtr,
920 				.is_plain_text = true,
921 			};
922 
923 			do_dump_btf(&d, &info, key, value);
924 			jsonw_destroy(&btf_wtr);
925 		}
926 	} else {
927 		print_entry_plain(&info, key, value);
928 	}
929 
930 exit_free:
931 	free(key);
932 	free(value);
933 	close(fd);
934 	btf__free(btf);
935 
936 	return err;
937 }
938 
939 static int do_getnext(int argc, char **argv)
940 {
941 	struct bpf_map_info info = {};
942 	__u32 len = sizeof(info);
943 	void *key, *nextkey;
944 	int err;
945 	int fd;
946 
947 	if (argc < 2)
948 		usage();
949 
950 	fd = map_parse_fd_and_info(&argc, &argv, &info, &len);
951 	if (fd < 0)
952 		return -1;
953 
954 	key = malloc(info.key_size);
955 	nextkey = malloc(info.key_size);
956 	if (!key || !nextkey) {
957 		p_err("mem alloc failed");
958 		err = -1;
959 		goto exit_free;
960 	}
961 
962 	if (argc) {
963 		err = parse_elem(argv, &info, key, NULL, info.key_size, 0,
964 				 NULL, NULL);
965 		if (err)
966 			goto exit_free;
967 	} else {
968 		free(key);
969 		key = NULL;
970 	}
971 
972 	err = bpf_map_get_next_key(fd, key, nextkey);
973 	if (err) {
974 		p_err("can't get next key: %s", strerror(errno));
975 		goto exit_free;
976 	}
977 
978 	if (json_output) {
979 		jsonw_start_object(json_wtr);
980 		if (key) {
981 			jsonw_name(json_wtr, "key");
982 			print_hex_data_json(key, info.key_size);
983 		} else {
984 			jsonw_null_field(json_wtr, "key");
985 		}
986 		jsonw_name(json_wtr, "next_key");
987 		print_hex_data_json(nextkey, info.key_size);
988 		jsonw_end_object(json_wtr);
989 	} else {
990 		if (key) {
991 			printf("key:\n");
992 			fprint_hex(stdout, key, info.key_size, " ");
993 			printf("\n");
994 		} else {
995 			printf("key: None\n");
996 		}
997 		printf("next key:\n");
998 		fprint_hex(stdout, nextkey, info.key_size, " ");
999 		printf("\n");
1000 	}
1001 
1002 exit_free:
1003 	free(nextkey);
1004 	free(key);
1005 	close(fd);
1006 
1007 	return err;
1008 }
1009 
1010 static int do_delete(int argc, char **argv)
1011 {
1012 	struct bpf_map_info info = {};
1013 	__u32 len = sizeof(info);
1014 	void *key;
1015 	int err;
1016 	int fd;
1017 
1018 	if (argc < 2)
1019 		usage();
1020 
1021 	fd = map_parse_fd_and_info(&argc, &argv, &info, &len);
1022 	if (fd < 0)
1023 		return -1;
1024 
1025 	key = malloc(info.key_size);
1026 	if (!key) {
1027 		p_err("mem alloc failed");
1028 		err = -1;
1029 		goto exit_free;
1030 	}
1031 
1032 	err = parse_elem(argv, &info, key, NULL, info.key_size, 0, NULL, NULL);
1033 	if (err)
1034 		goto exit_free;
1035 
1036 	err = bpf_map_delete_elem(fd, key);
1037 	if (err)
1038 		p_err("delete failed: %s", strerror(errno));
1039 
1040 exit_free:
1041 	free(key);
1042 	close(fd);
1043 
1044 	if (!err && json_output)
1045 		jsonw_null(json_wtr);
1046 	return err;
1047 }
1048 
1049 static int do_pin(int argc, char **argv)
1050 {
1051 	int err;
1052 
1053 	err = do_pin_any(argc, argv, bpf_map_get_fd_by_id);
1054 	if (!err && json_output)
1055 		jsonw_null(json_wtr);
1056 	return err;
1057 }
1058 
1059 static int do_create(int argc, char **argv)
1060 {
1061 	struct bpf_create_map_attr attr = { NULL, };
1062 	const char *pinfile;
1063 	int err, fd;
1064 
1065 	if (!REQ_ARGS(7))
1066 		return -1;
1067 	pinfile = GET_ARG();
1068 
1069 	while (argc) {
1070 		if (!REQ_ARGS(2))
1071 			return -1;
1072 
1073 		if (is_prefix(*argv, "type")) {
1074 			NEXT_ARG();
1075 
1076 			if (attr.map_type) {
1077 				p_err("map type already specified");
1078 				return -1;
1079 			}
1080 
1081 			attr.map_type = map_type_from_str(*argv);
1082 			if ((int)attr.map_type < 0) {
1083 				p_err("unrecognized map type: %s", *argv);
1084 				return -1;
1085 			}
1086 			NEXT_ARG();
1087 		} else if (is_prefix(*argv, "name")) {
1088 			NEXT_ARG();
1089 			attr.name = GET_ARG();
1090 		} else if (is_prefix(*argv, "key")) {
1091 			if (parse_u32_arg(&argc, &argv, &attr.key_size,
1092 					  "key size"))
1093 				return -1;
1094 		} else if (is_prefix(*argv, "value")) {
1095 			if (parse_u32_arg(&argc, &argv, &attr.value_size,
1096 					  "value size"))
1097 				return -1;
1098 		} else if (is_prefix(*argv, "entries")) {
1099 			if (parse_u32_arg(&argc, &argv, &attr.max_entries,
1100 					  "max entries"))
1101 				return -1;
1102 		} else if (is_prefix(*argv, "flags")) {
1103 			if (parse_u32_arg(&argc, &argv, &attr.map_flags,
1104 					  "flags"))
1105 				return -1;
1106 		} else if (is_prefix(*argv, "dev")) {
1107 			NEXT_ARG();
1108 
1109 			if (attr.map_ifindex) {
1110 				p_err("offload device already specified");
1111 				return -1;
1112 			}
1113 
1114 			attr.map_ifindex = if_nametoindex(*argv);
1115 			if (!attr.map_ifindex) {
1116 				p_err("unrecognized netdevice '%s': %s",
1117 				      *argv, strerror(errno));
1118 				return -1;
1119 			}
1120 			NEXT_ARG();
1121 		}
1122 	}
1123 
1124 	if (!attr.name) {
1125 		p_err("map name not specified");
1126 		return -1;
1127 	}
1128 
1129 	set_max_rlimit();
1130 
1131 	fd = bpf_create_map_xattr(&attr);
1132 	if (fd < 0) {
1133 		p_err("map create failed: %s", strerror(errno));
1134 		return -1;
1135 	}
1136 
1137 	err = do_pin_fd(fd, pinfile);
1138 	close(fd);
1139 	if (err)
1140 		return err;
1141 
1142 	if (json_output)
1143 		jsonw_null(json_wtr);
1144 	return 0;
1145 }
1146 
1147 static int do_help(int argc, char **argv)
1148 {
1149 	if (json_output) {
1150 		jsonw_null(json_wtr);
1151 		return 0;
1152 	}
1153 
1154 	fprintf(stderr,
1155 		"Usage: %s %s { show | list }   [MAP]\n"
1156 		"       %s %s create     FILE type TYPE key KEY_SIZE value VALUE_SIZE \\\n"
1157 		"                              entries MAX_ENTRIES name NAME [flags FLAGS] \\\n"
1158 		"                              [dev NAME]\n"
1159 		"       %s %s dump       MAP\n"
1160 		"       %s %s update     MAP [key DATA] [value VALUE] [UPDATE_FLAGS]\n"
1161 		"       %s %s lookup     MAP  key DATA\n"
1162 		"       %s %s getnext    MAP [key DATA]\n"
1163 		"       %s %s delete     MAP  key DATA\n"
1164 		"       %s %s pin        MAP  FILE\n"
1165 		"       %s %s event_pipe MAP [cpu N index M]\n"
1166 		"       %s %s help\n"
1167 		"\n"
1168 		"       " HELP_SPEC_MAP "\n"
1169 		"       DATA := { [hex] BYTES }\n"
1170 		"       " HELP_SPEC_PROGRAM "\n"
1171 		"       VALUE := { DATA | MAP | PROG }\n"
1172 		"       UPDATE_FLAGS := { any | exist | noexist }\n"
1173 		"       TYPE := { hash | array | prog_array | perf_event_array | percpu_hash |\n"
1174 		"                 percpu_array | stack_trace | cgroup_array | lru_hash |\n"
1175 		"                 lru_percpu_hash | lpm_trie | array_of_maps | hash_of_maps |\n"
1176 		"                 devmap | sockmap | cpumap | xskmap | sockhash |\n"
1177 		"                 cgroup_storage | reuseport_sockarray | percpu_cgroup_storage }\n"
1178 		"       " HELP_SPEC_OPTIONS "\n"
1179 		"",
1180 		bin_name, argv[-2], bin_name, argv[-2], bin_name, argv[-2],
1181 		bin_name, argv[-2], bin_name, argv[-2], bin_name, argv[-2],
1182 		bin_name, argv[-2], bin_name, argv[-2], bin_name, argv[-2],
1183 		bin_name, argv[-2]);
1184 
1185 	return 0;
1186 }
1187 
1188 static const struct cmd cmds[] = {
1189 	{ "show",	do_show },
1190 	{ "list",	do_show },
1191 	{ "help",	do_help },
1192 	{ "dump",	do_dump },
1193 	{ "update",	do_update },
1194 	{ "lookup",	do_lookup },
1195 	{ "getnext",	do_getnext },
1196 	{ "delete",	do_delete },
1197 	{ "pin",	do_pin },
1198 	{ "event_pipe",	do_event_pipe },
1199 	{ "create",	do_create },
1200 	{ 0 }
1201 };
1202 
1203 int do_map(int argc, char **argv)
1204 {
1205 	return cmd_select(cmds, argc, argv, do_help);
1206 }
1207