prog.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699
  1. /*
  2. * Copyright (C) 2017 Netronome Systems, Inc.
  3. *
  4. * This software is dual licensed under the GNU General License Version 2,
  5. * June 1991 as shown in the file COPYING in the top-level directory of this
  6. * source tree or the BSD 2-Clause License provided below. You have the
  7. * option to license this software under the complete terms of either license.
  8. *
  9. * The BSD 2-Clause License:
  10. *
  11. * Redistribution and use in source and binary forms, with or
  12. * without modification, are permitted provided that the following
  13. * conditions are met:
  14. *
  15. * 1. Redistributions of source code must retain the above
  16. * copyright notice, this list of conditions and the following
  17. * disclaimer.
  18. *
  19. * 2. Redistributions in binary form must reproduce the above
  20. * copyright notice, this list of conditions and the following
  21. * disclaimer in the documentation and/or other materials
  22. * provided with the distribution.
  23. *
  24. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  25. * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  26. * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  27. * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
  28. * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
  29. * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  30. * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  31. * SOFTWARE.
  32. */
  33. /* Author: Jakub Kicinski <kubakici@wp.pl> */
  34. #include <errno.h>
  35. #include <fcntl.h>
  36. #include <stdarg.h>
  37. #include <stdio.h>
  38. #include <stdlib.h>
  39. #include <string.h>
  40. #include <time.h>
  41. #include <unistd.h>
  42. #include <sys/types.h>
  43. #include <sys/stat.h>
  44. #include <bpf.h>
  45. #include <libbpf.h>
  46. #include "main.h"
  47. #include "disasm.h"
  48. static const char * const prog_type_name[] = {
  49. [BPF_PROG_TYPE_UNSPEC] = "unspec",
  50. [BPF_PROG_TYPE_SOCKET_FILTER] = "socket_filter",
  51. [BPF_PROG_TYPE_KPROBE] = "kprobe",
  52. [BPF_PROG_TYPE_SCHED_CLS] = "sched_cls",
  53. [BPF_PROG_TYPE_SCHED_ACT] = "sched_act",
  54. [BPF_PROG_TYPE_TRACEPOINT] = "tracepoint",
  55. [BPF_PROG_TYPE_XDP] = "xdp",
  56. [BPF_PROG_TYPE_PERF_EVENT] = "perf_event",
  57. [BPF_PROG_TYPE_CGROUP_SKB] = "cgroup_skb",
  58. [BPF_PROG_TYPE_CGROUP_SOCK] = "cgroup_sock",
  59. [BPF_PROG_TYPE_LWT_IN] = "lwt_in",
  60. [BPF_PROG_TYPE_LWT_OUT] = "lwt_out",
  61. [BPF_PROG_TYPE_LWT_XMIT] = "lwt_xmit",
  62. [BPF_PROG_TYPE_SOCK_OPS] = "sock_ops",
  63. [BPF_PROG_TYPE_SK_SKB] = "sk_skb",
  64. };
  65. static void print_boot_time(__u64 nsecs, char *buf, unsigned int size)
  66. {
  67. struct timespec real_time_ts, boot_time_ts;
  68. time_t wallclock_secs;
  69. struct tm load_tm;
  70. buf[--size] = '\0';
  71. if (clock_gettime(CLOCK_REALTIME, &real_time_ts) ||
  72. clock_gettime(CLOCK_BOOTTIME, &boot_time_ts)) {
  73. perror("Can't read clocks");
  74. snprintf(buf, size, "%llu", nsecs / 1000000000);
  75. return;
  76. }
  77. wallclock_secs = (real_time_ts.tv_sec - boot_time_ts.tv_sec) +
  78. nsecs / 1000000000;
  79. if (!localtime_r(&wallclock_secs, &load_tm)) {
  80. snprintf(buf, size, "%llu", nsecs / 1000000000);
  81. return;
  82. }
  83. strftime(buf, size, "%b %d/%H:%M", &load_tm);
  84. }
  85. static int prog_fd_by_tag(unsigned char *tag)
  86. {
  87. struct bpf_prog_info info = {};
  88. __u32 len = sizeof(info);
  89. unsigned int id = 0;
  90. int err;
  91. int fd;
  92. while (true) {
  93. err = bpf_prog_get_next_id(id, &id);
  94. if (err) {
  95. p_err("%s", strerror(errno));
  96. return -1;
  97. }
  98. fd = bpf_prog_get_fd_by_id(id);
  99. if (fd < 0) {
  100. p_err("can't get prog by id (%u): %s",
  101. id, strerror(errno));
  102. return -1;
  103. }
  104. err = bpf_obj_get_info_by_fd(fd, &info, &len);
  105. if (err) {
  106. p_err("can't get prog info (%u): %s",
  107. id, strerror(errno));
  108. close(fd);
  109. return -1;
  110. }
  111. if (!memcmp(tag, info.tag, BPF_TAG_SIZE))
  112. return fd;
  113. close(fd);
  114. }
  115. }
  116. int prog_parse_fd(int *argc, char ***argv)
  117. {
  118. int fd;
  119. if (is_prefix(**argv, "id")) {
  120. unsigned int id;
  121. char *endptr;
  122. NEXT_ARGP();
  123. id = strtoul(**argv, &endptr, 0);
  124. if (*endptr) {
  125. p_err("can't parse %s as ID", **argv);
  126. return -1;
  127. }
  128. NEXT_ARGP();
  129. fd = bpf_prog_get_fd_by_id(id);
  130. if (fd < 0)
  131. p_err("get by id (%u): %s", id, strerror(errno));
  132. return fd;
  133. } else if (is_prefix(**argv, "tag")) {
  134. unsigned char tag[BPF_TAG_SIZE];
  135. NEXT_ARGP();
  136. if (sscanf(**argv, BPF_TAG_FMT, tag, tag + 1, tag + 2,
  137. tag + 3, tag + 4, tag + 5, tag + 6, tag + 7)
  138. != BPF_TAG_SIZE) {
  139. p_err("can't parse tag");
  140. return -1;
  141. }
  142. NEXT_ARGP();
  143. return prog_fd_by_tag(tag);
  144. } else if (is_prefix(**argv, "pinned")) {
  145. char *path;
  146. NEXT_ARGP();
  147. path = **argv;
  148. NEXT_ARGP();
  149. return open_obj_pinned_any(path, BPF_OBJ_PROG);
  150. }
  151. p_err("expected 'id', 'tag' or 'pinned', got: '%s'?", **argv);
  152. return -1;
  153. }
  154. static void show_prog_maps(int fd, u32 num_maps)
  155. {
  156. struct bpf_prog_info info = {};
  157. __u32 len = sizeof(info);
  158. __u32 map_ids[num_maps];
  159. unsigned int i;
  160. int err;
  161. info.nr_map_ids = num_maps;
  162. info.map_ids = ptr_to_u64(map_ids);
  163. err = bpf_obj_get_info_by_fd(fd, &info, &len);
  164. if (err || !info.nr_map_ids)
  165. return;
  166. if (json_output) {
  167. jsonw_name(json_wtr, "map_ids");
  168. jsonw_start_array(json_wtr);
  169. for (i = 0; i < info.nr_map_ids; i++)
  170. jsonw_uint(json_wtr, map_ids[i]);
  171. jsonw_end_array(json_wtr);
  172. } else {
  173. printf(" map_ids ");
  174. for (i = 0; i < info.nr_map_ids; i++)
  175. printf("%u%s", map_ids[i],
  176. i == info.nr_map_ids - 1 ? "" : ",");
  177. }
  178. }
  179. static void print_prog_json(struct bpf_prog_info *info, int fd)
  180. {
  181. char *memlock;
  182. jsonw_start_object(json_wtr);
  183. jsonw_uint_field(json_wtr, "id", info->id);
  184. if (info->type < ARRAY_SIZE(prog_type_name))
  185. jsonw_string_field(json_wtr, "type",
  186. prog_type_name[info->type]);
  187. else
  188. jsonw_uint_field(json_wtr, "type", info->type);
  189. if (*info->name)
  190. jsonw_string_field(json_wtr, "name", info->name);
  191. jsonw_name(json_wtr, "tag");
  192. jsonw_printf(json_wtr, "\"" BPF_TAG_FMT "\"",
  193. info->tag[0], info->tag[1], info->tag[2], info->tag[3],
  194. info->tag[4], info->tag[5], info->tag[6], info->tag[7]);
  195. if (info->load_time) {
  196. char buf[32];
  197. print_boot_time(info->load_time, buf, sizeof(buf));
  198. /* Piggy back on load_time, since 0 uid is a valid one */
  199. jsonw_string_field(json_wtr, "loaded_at", buf);
  200. jsonw_uint_field(json_wtr, "uid", info->created_by_uid);
  201. }
  202. jsonw_uint_field(json_wtr, "bytes_xlated", info->xlated_prog_len);
  203. if (info->jited_prog_len) {
  204. jsonw_bool_field(json_wtr, "jited", true);
  205. jsonw_uint_field(json_wtr, "bytes_jited", info->jited_prog_len);
  206. } else {
  207. jsonw_bool_field(json_wtr, "jited", false);
  208. }
  209. memlock = get_fdinfo(fd, "memlock");
  210. if (memlock)
  211. jsonw_int_field(json_wtr, "bytes_memlock", atoi(memlock));
  212. free(memlock);
  213. if (info->nr_map_ids)
  214. show_prog_maps(fd, info->nr_map_ids);
  215. if (!hash_empty(prog_table.table)) {
  216. struct pinned_obj *obj;
  217. jsonw_name(json_wtr, "pinned");
  218. jsonw_start_array(json_wtr);
  219. hash_for_each_possible(prog_table.table, obj, hash, info->id) {
  220. if (obj->id == info->id)
  221. jsonw_string(json_wtr, obj->path);
  222. }
  223. jsonw_end_array(json_wtr);
  224. }
  225. jsonw_end_object(json_wtr);
  226. }
  227. static void print_prog_plain(struct bpf_prog_info *info, int fd)
  228. {
  229. char *memlock;
  230. printf("%u: ", info->id);
  231. if (info->type < ARRAY_SIZE(prog_type_name))
  232. printf("%s ", prog_type_name[info->type]);
  233. else
  234. printf("type %u ", info->type);
  235. if (*info->name)
  236. printf("name %s ", info->name);
  237. printf("tag ");
  238. fprint_hex(stdout, info->tag, BPF_TAG_SIZE, "");
  239. printf("\n");
  240. if (info->load_time) {
  241. char buf[32];
  242. print_boot_time(info->load_time, buf, sizeof(buf));
  243. /* Piggy back on load_time, since 0 uid is a valid one */
  244. printf("\tloaded_at %s uid %u\n", buf, info->created_by_uid);
  245. }
  246. printf("\txlated %uB", info->xlated_prog_len);
  247. if (info->jited_prog_len)
  248. printf(" jited %uB", info->jited_prog_len);
  249. else
  250. printf(" not jited");
  251. memlock = get_fdinfo(fd, "memlock");
  252. if (memlock)
  253. printf(" memlock %sB", memlock);
  254. free(memlock);
  255. if (info->nr_map_ids)
  256. show_prog_maps(fd, info->nr_map_ids);
  257. if (!hash_empty(prog_table.table)) {
  258. struct pinned_obj *obj;
  259. printf("\n");
  260. hash_for_each_possible(prog_table.table, obj, hash, info->id) {
  261. if (obj->id == info->id)
  262. printf("\tpinned %s\n", obj->path);
  263. }
  264. }
  265. printf("\n");
  266. }
  267. static int show_prog(int fd)
  268. {
  269. struct bpf_prog_info info = {};
  270. __u32 len = sizeof(info);
  271. int err;
  272. err = bpf_obj_get_info_by_fd(fd, &info, &len);
  273. if (err) {
  274. p_err("can't get prog info: %s", strerror(errno));
  275. return -1;
  276. }
  277. if (json_output)
  278. print_prog_json(&info, fd);
  279. else
  280. print_prog_plain(&info, fd);
  281. return 0;
  282. }
  283. static int do_show(int argc, char **argv)
  284. {
  285. __u32 id = 0;
  286. int err;
  287. int fd;
  288. if (show_pinned)
  289. build_pinned_obj_table(&prog_table, BPF_OBJ_PROG);
  290. if (argc == 2) {
  291. fd = prog_parse_fd(&argc, &argv);
  292. if (fd < 0)
  293. return -1;
  294. return show_prog(fd);
  295. }
  296. if (argc)
  297. return BAD_ARG();
  298. if (json_output)
  299. jsonw_start_array(json_wtr);
  300. while (true) {
  301. err = bpf_prog_get_next_id(id, &id);
  302. if (err) {
  303. if (errno == ENOENT) {
  304. err = 0;
  305. break;
  306. }
  307. p_err("can't get next program: %s%s", strerror(errno),
  308. errno == EINVAL ? " -- kernel too old?" : "");
  309. err = -1;
  310. break;
  311. }
  312. fd = bpf_prog_get_fd_by_id(id);
  313. if (fd < 0) {
  314. p_err("can't get prog by id (%u): %s",
  315. id, strerror(errno));
  316. err = -1;
  317. break;
  318. }
  319. err = show_prog(fd);
  320. close(fd);
  321. if (err)
  322. break;
  323. }
  324. if (json_output)
  325. jsonw_end_array(json_wtr);
  326. return err;
  327. }
  328. static void print_insn(struct bpf_verifier_env *env, const char *fmt, ...)
  329. {
  330. va_list args;
  331. va_start(args, fmt);
  332. vprintf(fmt, args);
  333. va_end(args);
  334. }
  335. static void dump_xlated_plain(void *buf, unsigned int len, bool opcodes)
  336. {
  337. struct bpf_insn *insn = buf;
  338. bool double_insn = false;
  339. unsigned int i;
  340. for (i = 0; i < len / sizeof(*insn); i++) {
  341. if (double_insn) {
  342. double_insn = false;
  343. continue;
  344. }
  345. double_insn = insn[i].code == (BPF_LD | BPF_IMM | BPF_DW);
  346. printf("% 4d: ", i);
  347. print_bpf_insn(print_insn, NULL, insn + i, true);
  348. if (opcodes) {
  349. printf(" ");
  350. fprint_hex(stdout, insn + i, 8, " ");
  351. if (double_insn && i < len - 1) {
  352. printf(" ");
  353. fprint_hex(stdout, insn + i + 1, 8, " ");
  354. }
  355. printf("\n");
  356. }
  357. }
  358. }
  359. static void print_insn_json(struct bpf_verifier_env *env, const char *fmt, ...)
  360. {
  361. unsigned int l = strlen(fmt);
  362. char chomped_fmt[l];
  363. va_list args;
  364. va_start(args, fmt);
  365. if (l > 0) {
  366. strncpy(chomped_fmt, fmt, l - 1);
  367. chomped_fmt[l - 1] = '\0';
  368. }
  369. jsonw_vprintf_enquote(json_wtr, chomped_fmt, args);
  370. va_end(args);
  371. }
  372. static void dump_xlated_json(void *buf, unsigned int len, bool opcodes)
  373. {
  374. struct bpf_insn *insn = buf;
  375. bool double_insn = false;
  376. unsigned int i;
  377. jsonw_start_array(json_wtr);
  378. for (i = 0; i < len / sizeof(*insn); i++) {
  379. if (double_insn) {
  380. double_insn = false;
  381. continue;
  382. }
  383. double_insn = insn[i].code == (BPF_LD | BPF_IMM | BPF_DW);
  384. jsonw_start_object(json_wtr);
  385. jsonw_name(json_wtr, "disasm");
  386. print_bpf_insn(print_insn_json, NULL, insn + i, true);
  387. if (opcodes) {
  388. jsonw_name(json_wtr, "opcodes");
  389. jsonw_start_object(json_wtr);
  390. jsonw_name(json_wtr, "code");
  391. jsonw_printf(json_wtr, "\"0x%02hhx\"", insn[i].code);
  392. jsonw_name(json_wtr, "src_reg");
  393. jsonw_printf(json_wtr, "\"0x%hhx\"", insn[i].src_reg);
  394. jsonw_name(json_wtr, "dst_reg");
  395. jsonw_printf(json_wtr, "\"0x%hhx\"", insn[i].dst_reg);
  396. jsonw_name(json_wtr, "off");
  397. print_hex_data_json((uint8_t *)(&insn[i].off), 2);
  398. jsonw_name(json_wtr, "imm");
  399. if (double_insn && i < len - 1)
  400. print_hex_data_json((uint8_t *)(&insn[i].imm),
  401. 12);
  402. else
  403. print_hex_data_json((uint8_t *)(&insn[i].imm),
  404. 4);
  405. jsonw_end_object(json_wtr);
  406. }
  407. jsonw_end_object(json_wtr);
  408. }
  409. jsonw_end_array(json_wtr);
  410. }
  411. static int do_dump(int argc, char **argv)
  412. {
  413. struct bpf_prog_info info = {};
  414. __u32 len = sizeof(info);
  415. unsigned int buf_size;
  416. char *filepath = NULL;
  417. bool opcodes = false;
  418. unsigned char *buf;
  419. __u32 *member_len;
  420. __u64 *member_ptr;
  421. ssize_t n;
  422. int err;
  423. int fd;
  424. if (is_prefix(*argv, "jited")) {
  425. member_len = &info.jited_prog_len;
  426. member_ptr = &info.jited_prog_insns;
  427. } else if (is_prefix(*argv, "xlated")) {
  428. member_len = &info.xlated_prog_len;
  429. member_ptr = &info.xlated_prog_insns;
  430. } else {
  431. p_err("expected 'xlated' or 'jited', got: %s", *argv);
  432. return -1;
  433. }
  434. NEXT_ARG();
  435. if (argc < 2)
  436. usage();
  437. fd = prog_parse_fd(&argc, &argv);
  438. if (fd < 0)
  439. return -1;
  440. if (is_prefix(*argv, "file")) {
  441. NEXT_ARG();
  442. if (!argc) {
  443. p_err("expected file path");
  444. return -1;
  445. }
  446. filepath = *argv;
  447. NEXT_ARG();
  448. } else if (is_prefix(*argv, "opcodes")) {
  449. opcodes = true;
  450. NEXT_ARG();
  451. }
  452. if (argc) {
  453. usage();
  454. return -1;
  455. }
  456. err = bpf_obj_get_info_by_fd(fd, &info, &len);
  457. if (err) {
  458. p_err("can't get prog info: %s", strerror(errno));
  459. return -1;
  460. }
  461. if (!*member_len) {
  462. p_info("no instructions returned");
  463. close(fd);
  464. return 0;
  465. }
  466. buf_size = *member_len;
  467. buf = malloc(buf_size);
  468. if (!buf) {
  469. p_err("mem alloc failed");
  470. close(fd);
  471. return -1;
  472. }
  473. memset(&info, 0, sizeof(info));
  474. *member_ptr = ptr_to_u64(buf);
  475. *member_len = buf_size;
  476. err = bpf_obj_get_info_by_fd(fd, &info, &len);
  477. close(fd);
  478. if (err) {
  479. p_err("can't get prog info: %s", strerror(errno));
  480. goto err_free;
  481. }
  482. if (*member_len > buf_size) {
  483. p_err("too many instructions returned");
  484. goto err_free;
  485. }
  486. if (filepath) {
  487. fd = open(filepath, O_WRONLY | O_CREAT | O_TRUNC, 0600);
  488. if (fd < 0) {
  489. p_err("can't open file %s: %s", filepath,
  490. strerror(errno));
  491. goto err_free;
  492. }
  493. n = write(fd, buf, *member_len);
  494. close(fd);
  495. if (n != *member_len) {
  496. p_err("error writing output file: %s",
  497. n < 0 ? strerror(errno) : "short write");
  498. goto err_free;
  499. }
  500. } else {
  501. if (member_len == &info.jited_prog_len)
  502. disasm_print_insn(buf, *member_len, opcodes);
  503. else
  504. if (json_output)
  505. dump_xlated_json(buf, *member_len, opcodes);
  506. else
  507. dump_xlated_plain(buf, *member_len, opcodes);
  508. }
  509. free(buf);
  510. return 0;
  511. err_free:
  512. free(buf);
  513. return -1;
  514. }
  515. static int do_pin(int argc, char **argv)
  516. {
  517. int err;
  518. err = do_pin_any(argc, argv, bpf_prog_get_fd_by_id);
  519. if (!err && json_output)
  520. jsonw_null(json_wtr);
  521. return err;
  522. }
  523. static int do_load(int argc, char **argv)
  524. {
  525. struct bpf_object *obj;
  526. int prog_fd;
  527. if (argc != 2)
  528. usage();
  529. if (bpf_prog_load(argv[0], BPF_PROG_TYPE_UNSPEC, &obj, &prog_fd)) {
  530. p_err("failed to load program\n");
  531. return -1;
  532. }
  533. if (do_pin_fd(prog_fd, argv[1])) {
  534. p_err("failed to pin program\n");
  535. return -1;
  536. }
  537. if (json_output)
  538. jsonw_null(json_wtr);
  539. return 0;
  540. }
  541. static int do_help(int argc, char **argv)
  542. {
  543. if (json_output) {
  544. jsonw_null(json_wtr);
  545. return 0;
  546. }
  547. fprintf(stderr,
  548. "Usage: %s %s show [PROG]\n"
  549. " %s %s dump xlated PROG [{ file FILE | opcodes }]\n"
  550. " %s %s dump jited PROG [{ file FILE | opcodes }]\n"
  551. " %s %s pin PROG FILE\n"
  552. " %s %s load OBJ FILE\n"
  553. " %s %s help\n"
  554. "\n"
  555. " " HELP_SPEC_PROGRAM "\n"
  556. " " HELP_SPEC_OPTIONS "\n"
  557. "",
  558. bin_name, argv[-2], bin_name, argv[-2], bin_name, argv[-2],
  559. bin_name, argv[-2], bin_name, argv[-2], bin_name, argv[-2]);
  560. return 0;
  561. }
  562. static const struct cmd cmds[] = {
  563. { "show", do_show },
  564. { "help", do_help },
  565. { "dump", do_dump },
  566. { "pin", do_pin },
  567. { "load", do_load },
  568. { 0 }
  569. };
  570. int do_prog(int argc, char **argv)
  571. {
  572. return cmd_select(cmds, argc, argv, do_help);
  573. }