log.c 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877
  1. // SPDX-License-Identifier: GPL-2.0-only
  2. /* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
  3. * Copyright (c) 2016 Facebook
  4. * Copyright (c) 2018 Covalent IO, Inc. http://covalent.io
  5. */
  6. #include <uapi/linux/btf.h>
  7. #include <linux/kernel.h>
  8. #include <linux/types.h>
  9. #include <linux/bpf.h>
  10. #include <linux/bpf_verifier.h>
  11. #include <linux/math64.h>
  12. #include <linux/string.h>
  13. #define verbose(env, fmt, args...) bpf_verifier_log_write(env, fmt, ##args)
  14. static bool bpf_verifier_log_attr_valid(const struct bpf_verifier_log *log)
  15. {
  16. /* ubuf and len_total should both be specified (or not) together */
  17. if (!!log->ubuf != !!log->len_total)
  18. return false;
  19. /* log buf without log_level is meaningless */
  20. if (log->ubuf && log->level == 0)
  21. return false;
  22. if (log->level & ~BPF_LOG_MASK)
  23. return false;
  24. if (log->len_total > UINT_MAX >> 2)
  25. return false;
  26. return true;
  27. }
  28. int bpf_vlog_init(struct bpf_verifier_log *log, u32 log_level,
  29. char __user *log_buf, u32 log_size)
  30. {
  31. log->level = log_level;
  32. log->ubuf = log_buf;
  33. log->len_total = log_size;
  34. /* log attributes have to be sane */
  35. if (!bpf_verifier_log_attr_valid(log))
  36. return -EINVAL;
  37. return 0;
  38. }
  39. static void bpf_vlog_update_len_max(struct bpf_verifier_log *log, u32 add_len)
  40. {
  41. /* add_len includes terminal \0, so no need for +1. */
  42. u64 len = log->end_pos + add_len;
  43. /* log->len_max could be larger than our current len due to
  44. * bpf_vlog_reset() calls, so we maintain the max of any length at any
  45. * previous point
  46. */
  47. if (len > UINT_MAX)
  48. log->len_max = UINT_MAX;
  49. else if (len > log->len_max)
  50. log->len_max = len;
  51. }
  52. void bpf_verifier_vlog(struct bpf_verifier_log *log, const char *fmt,
  53. va_list args)
  54. {
  55. u64 cur_pos;
  56. u32 new_n, n;
  57. n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args);
  58. if (log->level == BPF_LOG_KERNEL) {
  59. bool newline = n > 0 && log->kbuf[n - 1] == '\n';
  60. pr_err("BPF: %s%s", log->kbuf, newline ? "" : "\n");
  61. return;
  62. }
  63. n += 1; /* include terminating zero */
  64. bpf_vlog_update_len_max(log, n);
  65. if (log->level & BPF_LOG_FIXED) {
  66. /* check if we have at least something to put into user buf */
  67. new_n = 0;
  68. if (log->end_pos < log->len_total) {
  69. new_n = min_t(u32, log->len_total - log->end_pos, n);
  70. log->kbuf[new_n - 1] = '\0';
  71. }
  72. cur_pos = log->end_pos;
  73. log->end_pos += n - 1; /* don't count terminating '\0' */
  74. if (log->ubuf && new_n &&
  75. copy_to_user(log->ubuf + cur_pos, log->kbuf, new_n))
  76. goto fail;
  77. } else {
  78. u64 new_end, new_start;
  79. u32 buf_start, buf_end;
  80. new_end = log->end_pos + n;
  81. if (new_end - log->start_pos >= log->len_total)
  82. new_start = new_end - log->len_total;
  83. else
  84. new_start = log->start_pos;
  85. log->start_pos = new_start;
  86. log->end_pos = new_end - 1; /* don't count terminating '\0' */
  87. if (!log->ubuf)
  88. return;
  89. new_n = min(n, log->len_total);
  90. cur_pos = new_end - new_n;
  91. div_u64_rem(cur_pos, log->len_total, &buf_start);
  92. div_u64_rem(new_end, log->len_total, &buf_end);
  93. /* new_end and buf_end are exclusive indices, so if buf_end is
  94. * exactly zero, then it actually points right to the end of
  95. * ubuf and there is no wrap around
  96. */
  97. if (buf_end == 0)
  98. buf_end = log->len_total;
  99. /* if buf_start > buf_end, we wrapped around;
  100. * if buf_start == buf_end, then we fill ubuf completely; we
  101. * can't have buf_start == buf_end to mean that there is
  102. * nothing to write, because we always write at least
  103. * something, even if terminal '\0'
  104. */
  105. if (buf_start < buf_end) {
  106. /* message fits within contiguous chunk of ubuf */
  107. if (copy_to_user(log->ubuf + buf_start,
  108. log->kbuf + n - new_n,
  109. buf_end - buf_start))
  110. goto fail;
  111. } else {
  112. /* message wraps around the end of ubuf, copy in two chunks */
  113. if (copy_to_user(log->ubuf + buf_start,
  114. log->kbuf + n - new_n,
  115. log->len_total - buf_start))
  116. goto fail;
  117. if (copy_to_user(log->ubuf,
  118. log->kbuf + n - buf_end,
  119. buf_end))
  120. goto fail;
  121. }
  122. }
  123. return;
  124. fail:
  125. log->ubuf = NULL;
  126. }
  127. void bpf_vlog_reset(struct bpf_verifier_log *log, u64 new_pos)
  128. {
  129. char zero = 0;
  130. u32 pos;
  131. if (WARN_ON_ONCE(new_pos > log->end_pos))
  132. return;
  133. if (!bpf_verifier_log_needed(log) || log->level == BPF_LOG_KERNEL)
  134. return;
  135. /* if position to which we reset is beyond current log window,
  136. * then we didn't preserve any useful content and should adjust
  137. * start_pos to end up with an empty log (start_pos == end_pos)
  138. */
  139. log->end_pos = new_pos;
  140. if (log->end_pos < log->start_pos)
  141. log->start_pos = log->end_pos;
  142. if (!log->ubuf)
  143. return;
  144. if (log->level & BPF_LOG_FIXED)
  145. pos = log->end_pos + 1;
  146. else
  147. div_u64_rem(new_pos, log->len_total, &pos);
  148. if (pos < log->len_total && put_user(zero, log->ubuf + pos))
  149. log->ubuf = NULL;
  150. }
  151. static void bpf_vlog_reverse_kbuf(char *buf, int len)
  152. {
  153. int i, j;
  154. for (i = 0, j = len - 1; i < j; i++, j--)
  155. swap(buf[i], buf[j]);
  156. }
  157. static int bpf_vlog_reverse_ubuf(struct bpf_verifier_log *log, int start, int end)
  158. {
  159. /* we split log->kbuf into two equal parts for both ends of array */
  160. int n = sizeof(log->kbuf) / 2, nn;
  161. char *lbuf = log->kbuf, *rbuf = log->kbuf + n;
  162. /* Read ubuf's section [start, end) two chunks at a time, from left
  163. * and right side; within each chunk, swap all the bytes; after that
  164. * reverse the order of lbuf and rbuf and write result back to ubuf.
  165. * This way we'll end up with swapped contents of specified
  166. * [start, end) ubuf segment.
  167. */
  168. while (end - start > 1) {
  169. nn = min(n, (end - start ) / 2);
  170. if (copy_from_user(lbuf, log->ubuf + start, nn))
  171. return -EFAULT;
  172. if (copy_from_user(rbuf, log->ubuf + end - nn, nn))
  173. return -EFAULT;
  174. bpf_vlog_reverse_kbuf(lbuf, nn);
  175. bpf_vlog_reverse_kbuf(rbuf, nn);
  176. /* we write lbuf to the right end of ubuf, while rbuf to the
  177. * left one to end up with properly reversed overall ubuf
  178. */
  179. if (copy_to_user(log->ubuf + start, rbuf, nn))
  180. return -EFAULT;
  181. if (copy_to_user(log->ubuf + end - nn, lbuf, nn))
  182. return -EFAULT;
  183. start += nn;
  184. end -= nn;
  185. }
  186. return 0;
  187. }
  188. int bpf_vlog_finalize(struct bpf_verifier_log *log, u32 *log_size_actual)
  189. {
  190. u32 sublen;
  191. int err;
  192. *log_size_actual = 0;
  193. if (!log || log->level == 0 || log->level == BPF_LOG_KERNEL)
  194. return 0;
  195. if (!log->ubuf)
  196. goto skip_log_rotate;
  197. /* If we never truncated log, there is nothing to move around. */
  198. if (log->start_pos == 0)
  199. goto skip_log_rotate;
  200. /* Otherwise we need to rotate log contents to make it start from the
  201. * buffer beginning and be a continuous zero-terminated string. Note
  202. * that if log->start_pos != 0 then we definitely filled up entire log
  203. * buffer with no gaps, and we just need to shift buffer contents to
  204. * the left by (log->start_pos % log->len_total) bytes.
  205. *
  206. * Unfortunately, user buffer could be huge and we don't want to
  207. * allocate temporary kernel memory of the same size just to shift
  208. * contents in a straightforward fashion. Instead, we'll be clever and
  209. * do in-place array rotation. This is a leetcode-style problem, which
  210. * could be solved by three rotations.
  211. *
  212. * Let's say we have log buffer that has to be shifted left by 7 bytes
  213. * (spaces and vertical bar is just for demonstrative purposes):
  214. * E F G H I J K | A B C D
  215. *
  216. * First, we reverse entire array:
  217. * D C B A | K J I H G F E
  218. *
  219. * Then we rotate first 4 bytes (DCBA) and separately last 7 bytes
  220. * (KJIHGFE), resulting in a properly rotated array:
  221. * A B C D | E F G H I J K
  222. *
  223. * We'll utilize log->kbuf to read user memory chunk by chunk, swap
  224. * bytes, and write them back. Doing it byte-by-byte would be
  225. * unnecessarily inefficient. Altogether we are going to read and
  226. * write each byte twice, for total 4 memory copies between kernel and
  227. * user space.
  228. */
  229. /* length of the chopped off part that will be the beginning;
  230. * len(ABCD) in the example above
  231. */
  232. div_u64_rem(log->start_pos, log->len_total, &sublen);
  233. sublen = log->len_total - sublen;
  234. err = bpf_vlog_reverse_ubuf(log, 0, log->len_total);
  235. err = err ?: bpf_vlog_reverse_ubuf(log, 0, sublen);
  236. err = err ?: bpf_vlog_reverse_ubuf(log, sublen, log->len_total);
  237. if (err)
  238. log->ubuf = NULL;
  239. skip_log_rotate:
  240. *log_size_actual = log->len_max;
  241. /* properly initialized log has either both ubuf!=NULL and len_total>0
  242. * or ubuf==NULL and len_total==0, so if this condition doesn't hold,
  243. * we got a fault somewhere along the way, so report it back
  244. */
  245. if (!!log->ubuf != !!log->len_total)
  246. return -EFAULT;
  247. /* did truncation actually happen? */
  248. if (log->ubuf && log->len_max > log->len_total)
  249. return -ENOSPC;
  250. return 0;
  251. }
  252. /* log_level controls verbosity level of eBPF verifier.
  253. * bpf_verifier_log_write() is used to dump the verification trace to the log,
  254. * so the user can figure out what's wrong with the program
  255. */
  256. __printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env,
  257. const char *fmt, ...)
  258. {
  259. va_list args;
  260. if (!bpf_verifier_log_needed(&env->log))
  261. return;
  262. va_start(args, fmt);
  263. bpf_verifier_vlog(&env->log, fmt, args);
  264. va_end(args);
  265. }
  266. EXPORT_SYMBOL_GPL(bpf_verifier_log_write);
  267. __printf(2, 3) void bpf_log(struct bpf_verifier_log *log,
  268. const char *fmt, ...)
  269. {
  270. va_list args;
  271. if (!bpf_verifier_log_needed(log))
  272. return;
  273. va_start(args, fmt);
  274. bpf_verifier_vlog(log, fmt, args);
  275. va_end(args);
  276. }
  277. EXPORT_SYMBOL_GPL(bpf_log);
  278. static const struct bpf_line_info *
  279. find_linfo(const struct bpf_verifier_env *env, u32 insn_off)
  280. {
  281. const struct bpf_line_info *linfo;
  282. const struct bpf_prog *prog;
  283. u32 nr_linfo;
  284. int l, r, m;
  285. prog = env->prog;
  286. nr_linfo = prog->aux->nr_linfo;
  287. if (!nr_linfo || insn_off >= prog->len)
  288. return NULL;
  289. linfo = prog->aux->linfo;
  290. /* Loop invariant: linfo[l].insn_off <= insns_off.
  291. * linfo[0].insn_off == 0 which always satisfies above condition.
  292. * Binary search is searching for rightmost linfo entry that satisfies
  293. * the above invariant, giving us the desired record that covers given
  294. * instruction offset.
  295. */
  296. l = 0;
  297. r = nr_linfo - 1;
  298. while (l < r) {
  299. /* (r - l + 1) / 2 means we break a tie to the right, so if:
  300. * l=1, r=2, linfo[l].insn_off <= insn_off, linfo[r].insn_off > insn_off,
  301. * then m=2, we see that linfo[m].insn_off > insn_off, and so
  302. * r becomes 1 and we exit the loop with correct l==1.
  303. * If the tie was broken to the left, m=1 would end us up in
  304. * an endless loop where l and m stay at 1 and r stays at 2.
  305. */
  306. m = l + (r - l + 1) / 2;
  307. if (linfo[m].insn_off <= insn_off)
  308. l = m;
  309. else
  310. r = m - 1;
  311. }
  312. return &linfo[l];
  313. }
  314. static const char *ltrim(const char *s)
  315. {
  316. while (isspace(*s))
  317. s++;
  318. return s;
  319. }
  320. __printf(3, 4) void verbose_linfo(struct bpf_verifier_env *env,
  321. u32 insn_off,
  322. const char *prefix_fmt, ...)
  323. {
  324. const struct bpf_line_info *linfo, *prev_linfo;
  325. const struct btf *btf;
  326. const char *s, *fname;
  327. if (!bpf_verifier_log_needed(&env->log))
  328. return;
  329. prev_linfo = env->prev_linfo;
  330. linfo = find_linfo(env, insn_off);
  331. if (!linfo || linfo == prev_linfo)
  332. return;
  333. /* It often happens that two separate linfo records point to the same
  334. * source code line, but have differing column numbers. Given verifier
  335. * log doesn't emit column information, from user perspective we just
  336. * end up emitting the same source code line twice unnecessarily.
  337. * So instead check that previous and current linfo record point to
  338. * the same file (file_name_offs match) and the same line number, and
  339. * avoid emitting duplicated source code line in such case.
  340. */
  341. if (prev_linfo && linfo->file_name_off == prev_linfo->file_name_off &&
  342. BPF_LINE_INFO_LINE_NUM(linfo->line_col) == BPF_LINE_INFO_LINE_NUM(prev_linfo->line_col))
  343. return;
  344. if (prefix_fmt) {
  345. va_list args;
  346. va_start(args, prefix_fmt);
  347. bpf_verifier_vlog(&env->log, prefix_fmt, args);
  348. va_end(args);
  349. }
  350. btf = env->prog->aux->btf;
  351. s = ltrim(btf_name_by_offset(btf, linfo->line_off));
  352. verbose(env, "%s", s); /* source code line */
  353. s = btf_name_by_offset(btf, linfo->file_name_off);
  354. /* leave only file name */
  355. fname = strrchr(s, '/');
  356. fname = fname ? fname + 1 : s;
  357. verbose(env, " @ %s:%u\n", fname, BPF_LINE_INFO_LINE_NUM(linfo->line_col));
  358. env->prev_linfo = linfo;
  359. }
  360. static const char *btf_type_name(const struct btf *btf, u32 id)
  361. {
  362. return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
  363. }
  364. /* string representation of 'enum bpf_reg_type'
  365. *
  366. * Note that reg_type_str() can not appear more than once in a single verbose()
  367. * statement.
  368. */
  369. const char *reg_type_str(struct bpf_verifier_env *env, enum bpf_reg_type type)
  370. {
  371. char postfix[16] = {0}, prefix[64] = {0};
  372. static const char * const str[] = {
  373. [NOT_INIT] = "?",
  374. [SCALAR_VALUE] = "scalar",
  375. [PTR_TO_CTX] = "ctx",
  376. [CONST_PTR_TO_MAP] = "map_ptr",
  377. [PTR_TO_MAP_VALUE] = "map_value",
  378. [PTR_TO_STACK] = "fp",
  379. [PTR_TO_PACKET] = "pkt",
  380. [PTR_TO_PACKET_META] = "pkt_meta",
  381. [PTR_TO_PACKET_END] = "pkt_end",
  382. [PTR_TO_FLOW_KEYS] = "flow_keys",
  383. [PTR_TO_SOCKET] = "sock",
  384. [PTR_TO_SOCK_COMMON] = "sock_common",
  385. [PTR_TO_TCP_SOCK] = "tcp_sock",
  386. [PTR_TO_TP_BUFFER] = "tp_buffer",
  387. [PTR_TO_XDP_SOCK] = "xdp_sock",
  388. [PTR_TO_BTF_ID] = "ptr_",
  389. [PTR_TO_MEM] = "mem",
  390. [PTR_TO_ARENA] = "arena",
  391. [PTR_TO_BUF] = "buf",
  392. [PTR_TO_FUNC] = "func",
  393. [PTR_TO_MAP_KEY] = "map_key",
  394. [CONST_PTR_TO_DYNPTR] = "dynptr_ptr",
  395. };
  396. if (type & PTR_MAYBE_NULL) {
  397. if (base_type(type) == PTR_TO_BTF_ID)
  398. strscpy(postfix, "or_null_");
  399. else
  400. strscpy(postfix, "_or_null");
  401. }
  402. snprintf(prefix, sizeof(prefix), "%s%s%s%s%s%s%s",
  403. type & MEM_RDONLY ? "rdonly_" : "",
  404. type & MEM_RINGBUF ? "ringbuf_" : "",
  405. type & MEM_USER ? "user_" : "",
  406. type & MEM_PERCPU ? "percpu_" : "",
  407. type & MEM_RCU ? "rcu_" : "",
  408. type & PTR_UNTRUSTED ? "untrusted_" : "",
  409. type & PTR_TRUSTED ? "trusted_" : ""
  410. );
  411. snprintf(env->tmp_str_buf, TMP_STR_BUF_LEN, "%s%s%s",
  412. prefix, str[base_type(type)], postfix);
  413. return env->tmp_str_buf;
  414. }
  415. const char *dynptr_type_str(enum bpf_dynptr_type type)
  416. {
  417. switch (type) {
  418. case BPF_DYNPTR_TYPE_LOCAL:
  419. return "local";
  420. case BPF_DYNPTR_TYPE_RINGBUF:
  421. return "ringbuf";
  422. case BPF_DYNPTR_TYPE_SKB:
  423. return "skb";
  424. case BPF_DYNPTR_TYPE_XDP:
  425. return "xdp";
  426. case BPF_DYNPTR_TYPE_INVALID:
  427. return "<invalid>";
  428. default:
  429. WARN_ONCE(1, "unknown dynptr type %d\n", type);
  430. return "<unknown>";
  431. }
  432. }
  433. const char *iter_type_str(const struct btf *btf, u32 btf_id)
  434. {
  435. if (!btf || btf_id == 0)
  436. return "<invalid>";
  437. /* we already validated that type is valid and has conforming name */
  438. return btf_type_name(btf, btf_id) + sizeof(ITER_PREFIX) - 1;
  439. }
  440. const char *iter_state_str(enum bpf_iter_state state)
  441. {
  442. switch (state) {
  443. case BPF_ITER_STATE_ACTIVE:
  444. return "active";
  445. case BPF_ITER_STATE_DRAINED:
  446. return "drained";
  447. case BPF_ITER_STATE_INVALID:
  448. return "<invalid>";
  449. default:
  450. WARN_ONCE(1, "unknown iter state %d\n", state);
  451. return "<unknown>";
  452. }
  453. }
  454. static char slot_type_char[] = {
  455. [STACK_INVALID] = '?',
  456. [STACK_SPILL] = 'r',
  457. [STACK_MISC] = 'm',
  458. [STACK_ZERO] = '0',
  459. [STACK_DYNPTR] = 'd',
  460. [STACK_ITER] = 'i',
  461. };
  462. static void print_liveness(struct bpf_verifier_env *env,
  463. enum bpf_reg_liveness live)
  464. {
  465. if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
  466. verbose(env, "_");
  467. if (live & REG_LIVE_READ)
  468. verbose(env, "r");
  469. if (live & REG_LIVE_WRITTEN)
  470. verbose(env, "w");
  471. if (live & REG_LIVE_DONE)
  472. verbose(env, "D");
  473. }
  474. #define UNUM_MAX_DECIMAL U16_MAX
  475. #define SNUM_MAX_DECIMAL S16_MAX
  476. #define SNUM_MIN_DECIMAL S16_MIN
  477. static bool is_unum_decimal(u64 num)
  478. {
  479. return num <= UNUM_MAX_DECIMAL;
  480. }
  481. static bool is_snum_decimal(s64 num)
  482. {
  483. return num >= SNUM_MIN_DECIMAL && num <= SNUM_MAX_DECIMAL;
  484. }
  485. static void verbose_unum(struct bpf_verifier_env *env, u64 num)
  486. {
  487. if (is_unum_decimal(num))
  488. verbose(env, "%llu", num);
  489. else
  490. verbose(env, "%#llx", num);
  491. }
  492. static void verbose_snum(struct bpf_verifier_env *env, s64 num)
  493. {
  494. if (is_snum_decimal(num))
  495. verbose(env, "%lld", num);
  496. else
  497. verbose(env, "%#llx", num);
  498. }
  499. int tnum_strn(char *str, size_t size, struct tnum a)
  500. {
  501. /* print as a constant, if tnum is fully known */
  502. if (a.mask == 0) {
  503. if (is_unum_decimal(a.value))
  504. return snprintf(str, size, "%llu", a.value);
  505. else
  506. return snprintf(str, size, "%#llx", a.value);
  507. }
  508. return snprintf(str, size, "(%#llx; %#llx)", a.value, a.mask);
  509. }
  510. EXPORT_SYMBOL_GPL(tnum_strn);
  511. static void print_scalar_ranges(struct bpf_verifier_env *env,
  512. const struct bpf_reg_state *reg,
  513. const char **sep)
  514. {
  515. /* For signed ranges, we want to unify 64-bit and 32-bit values in the
  516. * output as much as possible, but there is a bit of a complication.
  517. * If we choose to print values as decimals, this is natural to do,
  518. * because negative 64-bit and 32-bit values >= -S32_MIN have the same
  519. * representation due to sign extension. But if we choose to print
  520. * them in hex format (see is_snum_decimal()), then sign extension is
  521. * misleading.
  522. * E.g., smin=-2 and smin32=-2 are exactly the same in decimal, but in
  523. * hex they will be smin=0xfffffffffffffffe and smin32=0xfffffffe, two
  524. * very different numbers.
  525. * So we avoid sign extension if we choose to print values in hex.
  526. */
  527. struct {
  528. const char *name;
  529. u64 val;
  530. bool omit;
  531. } minmaxs[] = {
  532. {"smin", reg->smin_value, reg->smin_value == S64_MIN},
  533. {"smax", reg->smax_value, reg->smax_value == S64_MAX},
  534. {"umin", reg->umin_value, reg->umin_value == 0},
  535. {"umax", reg->umax_value, reg->umax_value == U64_MAX},
  536. {"smin32",
  537. is_snum_decimal((s64)reg->s32_min_value)
  538. ? (s64)reg->s32_min_value
  539. : (u32)reg->s32_min_value, reg->s32_min_value == S32_MIN},
  540. {"smax32",
  541. is_snum_decimal((s64)reg->s32_max_value)
  542. ? (s64)reg->s32_max_value
  543. : (u32)reg->s32_max_value, reg->s32_max_value == S32_MAX},
  544. {"umin32", reg->u32_min_value, reg->u32_min_value == 0},
  545. {"umax32", reg->u32_max_value, reg->u32_max_value == U32_MAX},
  546. }, *m1, *m2, *mend = &minmaxs[ARRAY_SIZE(minmaxs)];
  547. bool neg1, neg2;
  548. for (m1 = &minmaxs[0]; m1 < mend; m1++) {
  549. if (m1->omit)
  550. continue;
  551. neg1 = m1->name[0] == 's' && (s64)m1->val < 0;
  552. verbose(env, "%s%s=", *sep, m1->name);
  553. *sep = ",";
  554. for (m2 = m1 + 2; m2 < mend; m2 += 2) {
  555. if (m2->omit || m2->val != m1->val)
  556. continue;
  557. /* don't mix negatives with positives */
  558. neg2 = m2->name[0] == 's' && (s64)m2->val < 0;
  559. if (neg2 != neg1)
  560. continue;
  561. m2->omit = true;
  562. verbose(env, "%s=", m2->name);
  563. }
  564. if (m1->name[0] == 's')
  565. verbose_snum(env, m1->val);
  566. else
  567. verbose_unum(env, m1->val);
  568. }
  569. }
  570. static bool type_is_map_ptr(enum bpf_reg_type t) {
  571. switch (base_type(t)) {
  572. case CONST_PTR_TO_MAP:
  573. case PTR_TO_MAP_KEY:
  574. case PTR_TO_MAP_VALUE:
  575. return true;
  576. default:
  577. return false;
  578. }
  579. }
  580. /*
  581. * _a stands for append, was shortened to avoid multiline statements below.
  582. * This macro is used to output a comma separated list of attributes.
  583. */
  584. #define verbose_a(fmt, ...) ({ verbose(env, "%s" fmt, sep, ##__VA_ARGS__); sep = ","; })
  585. static void print_reg_state(struct bpf_verifier_env *env,
  586. const struct bpf_func_state *state,
  587. const struct bpf_reg_state *reg)
  588. {
  589. enum bpf_reg_type t;
  590. const char *sep = "";
  591. t = reg->type;
  592. if (t == SCALAR_VALUE && reg->precise)
  593. verbose(env, "P");
  594. if (t == SCALAR_VALUE && tnum_is_const(reg->var_off)) {
  595. verbose_snum(env, reg->var_off.value);
  596. return;
  597. }
  598. verbose(env, "%s", reg_type_str(env, t));
  599. if (t == PTR_TO_ARENA)
  600. return;
  601. if (t == PTR_TO_STACK) {
  602. if (state->frameno != reg->frameno)
  603. verbose(env, "[%d]", reg->frameno);
  604. if (tnum_is_const(reg->var_off)) {
  605. verbose_snum(env, reg->var_off.value + reg->off);
  606. return;
  607. }
  608. }
  609. if (base_type(t) == PTR_TO_BTF_ID)
  610. verbose(env, "%s", btf_type_name(reg->btf, reg->btf_id));
  611. verbose(env, "(");
  612. if (reg->id)
  613. verbose_a("id=%d", reg->id & ~BPF_ADD_CONST);
  614. if (reg->id & BPF_ADD_CONST)
  615. verbose(env, "%+d", reg->off);
  616. if (reg->ref_obj_id)
  617. verbose_a("ref_obj_id=%d", reg->ref_obj_id);
  618. if (type_is_non_owning_ref(reg->type))
  619. verbose_a("%s", "non_own_ref");
  620. if (type_is_map_ptr(t)) {
  621. if (reg->map_ptr->name[0])
  622. verbose_a("map=%s", reg->map_ptr->name);
  623. verbose_a("ks=%d,vs=%d",
  624. reg->map_ptr->key_size,
  625. reg->map_ptr->value_size);
  626. }
  627. if (t != SCALAR_VALUE && reg->off) {
  628. verbose_a("off=");
  629. verbose_snum(env, reg->off);
  630. }
  631. if (type_is_pkt_pointer(t)) {
  632. verbose_a("r=");
  633. verbose_unum(env, reg->range);
  634. }
  635. if (base_type(t) == PTR_TO_MEM) {
  636. verbose_a("sz=");
  637. verbose_unum(env, reg->mem_size);
  638. }
  639. if (t == CONST_PTR_TO_DYNPTR)
  640. verbose_a("type=%s", dynptr_type_str(reg->dynptr.type));
  641. if (tnum_is_const(reg->var_off)) {
  642. /* a pointer register with fixed offset */
  643. if (reg->var_off.value) {
  644. verbose_a("imm=");
  645. verbose_snum(env, reg->var_off.value);
  646. }
  647. } else {
  648. print_scalar_ranges(env, reg, &sep);
  649. if (!tnum_is_unknown(reg->var_off)) {
  650. char tn_buf[48];
  651. tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
  652. verbose_a("var_off=%s", tn_buf);
  653. }
  654. }
  655. verbose(env, ")");
  656. }
  657. void print_verifier_state(struct bpf_verifier_env *env, const struct bpf_func_state *state,
  658. bool print_all)
  659. {
  660. const struct bpf_reg_state *reg;
  661. int i;
  662. if (state->frameno)
  663. verbose(env, " frame%d:", state->frameno);
  664. for (i = 0; i < MAX_BPF_REG; i++) {
  665. reg = &state->regs[i];
  666. if (reg->type == NOT_INIT)
  667. continue;
  668. if (!print_all && !reg_scratched(env, i))
  669. continue;
  670. verbose(env, " R%d", i);
  671. print_liveness(env, reg->live);
  672. verbose(env, "=");
  673. print_reg_state(env, state, reg);
  674. }
  675. for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
  676. char types_buf[BPF_REG_SIZE + 1];
  677. const char *sep = "";
  678. bool valid = false;
  679. u8 slot_type;
  680. int j;
  681. if (!print_all && !stack_slot_scratched(env, i))
  682. continue;
  683. for (j = 0; j < BPF_REG_SIZE; j++) {
  684. slot_type = state->stack[i].slot_type[j];
  685. if (slot_type != STACK_INVALID)
  686. valid = true;
  687. types_buf[j] = slot_type_char[slot_type];
  688. }
  689. types_buf[BPF_REG_SIZE] = 0;
  690. if (!valid)
  691. continue;
  692. reg = &state->stack[i].spilled_ptr;
  693. switch (state->stack[i].slot_type[BPF_REG_SIZE - 1]) {
  694. case STACK_SPILL:
  695. /* print MISC/ZERO/INVALID slots above subreg spill */
  696. for (j = 0; j < BPF_REG_SIZE; j++)
  697. if (state->stack[i].slot_type[j] == STACK_SPILL)
  698. break;
  699. types_buf[j] = '\0';
  700. verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
  701. print_liveness(env, reg->live);
  702. verbose(env, "=%s", types_buf);
  703. print_reg_state(env, state, reg);
  704. break;
  705. case STACK_DYNPTR:
  706. /* skip to main dynptr slot */
  707. i += BPF_DYNPTR_NR_SLOTS - 1;
  708. reg = &state->stack[i].spilled_ptr;
  709. verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
  710. print_liveness(env, reg->live);
  711. verbose(env, "=dynptr_%s(", dynptr_type_str(reg->dynptr.type));
  712. if (reg->id)
  713. verbose_a("id=%d", reg->id);
  714. if (reg->ref_obj_id)
  715. verbose_a("ref_id=%d", reg->ref_obj_id);
  716. if (reg->dynptr_id)
  717. verbose_a("dynptr_id=%d", reg->dynptr_id);
  718. verbose(env, ")");
  719. break;
  720. case STACK_ITER:
  721. /* only main slot has ref_obj_id set; skip others */
  722. if (!reg->ref_obj_id)
  723. continue;
  724. verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
  725. print_liveness(env, reg->live);
  726. verbose(env, "=iter_%s(ref_id=%d,state=%s,depth=%u)",
  727. iter_type_str(reg->iter.btf, reg->iter.btf_id),
  728. reg->ref_obj_id, iter_state_str(reg->iter.state),
  729. reg->iter.depth);
  730. break;
  731. case STACK_MISC:
  732. case STACK_ZERO:
  733. default:
  734. verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
  735. print_liveness(env, reg->live);
  736. verbose(env, "=%s", types_buf);
  737. break;
  738. }
  739. }
  740. if (state->acquired_refs && state->refs[0].id) {
  741. verbose(env, " refs=%d", state->refs[0].id);
  742. for (i = 1; i < state->acquired_refs; i++)
  743. if (state->refs[i].id)
  744. verbose(env, ",%d", state->refs[i].id);
  745. }
  746. if (state->in_callback_fn)
  747. verbose(env, " cb");
  748. if (state->in_async_callback_fn)
  749. verbose(env, " async_cb");
  750. verbose(env, "\n");
  751. if (!print_all)
  752. mark_verifier_state_clean(env);
  753. }
  754. static inline u32 vlog_alignment(u32 pos)
  755. {
  756. return round_up(max(pos + BPF_LOG_MIN_ALIGNMENT / 2, BPF_LOG_ALIGNMENT),
  757. BPF_LOG_MIN_ALIGNMENT) - pos - 1;
  758. }
  759. void print_insn_state(struct bpf_verifier_env *env, const struct bpf_func_state *state)
  760. {
  761. if (env->prev_log_pos && env->prev_log_pos == env->log.end_pos) {
  762. /* remove new line character */
  763. bpf_vlog_reset(&env->log, env->prev_log_pos - 1);
  764. verbose(env, "%*c;", vlog_alignment(env->prev_insn_print_pos), ' ');
  765. } else {
  766. verbose(env, "%d:", env->insn_idx);
  767. }
  768. print_verifier_state(env, state, false);
  769. }