test_loader.c 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119
  1. // SPDX-License-Identifier: GPL-2.0-only
  2. /* Copyright (c) 2022 Meta Platforms, Inc. and affiliates. */
  3. #include <linux/capability.h>
  4. #include <stdlib.h>
  5. #include <regex.h>
  6. #include <test_progs.h>
  7. #include <bpf/btf.h>
  8. #include "autoconf_helper.h"
  9. #include "disasm_helpers.h"
  10. #include "unpriv_helpers.h"
  11. #include "cap_helpers.h"
  12. #include "jit_disasm_helpers.h"
  13. #define str_has_pfx(str, pfx) \
  14. (strncmp(str, pfx, __builtin_constant_p(pfx) ? sizeof(pfx) - 1 : strlen(pfx)) == 0)
  15. #define TEST_LOADER_LOG_BUF_SZ 2097152
  16. #define TEST_TAG_EXPECT_FAILURE "comment:test_expect_failure"
  17. #define TEST_TAG_EXPECT_SUCCESS "comment:test_expect_success"
  18. #define TEST_TAG_EXPECT_MSG_PFX "comment:test_expect_msg="
  19. #define TEST_TAG_EXPECT_XLATED_PFX "comment:test_expect_xlated="
  20. #define TEST_TAG_EXPECT_FAILURE_UNPRIV "comment:test_expect_failure_unpriv"
  21. #define TEST_TAG_EXPECT_SUCCESS_UNPRIV "comment:test_expect_success_unpriv"
  22. #define TEST_TAG_EXPECT_MSG_PFX_UNPRIV "comment:test_expect_msg_unpriv="
  23. #define TEST_TAG_EXPECT_XLATED_PFX_UNPRIV "comment:test_expect_xlated_unpriv="
  24. #define TEST_TAG_LOG_LEVEL_PFX "comment:test_log_level="
  25. #define TEST_TAG_PROG_FLAGS_PFX "comment:test_prog_flags="
  26. #define TEST_TAG_DESCRIPTION_PFX "comment:test_description="
  27. #define TEST_TAG_RETVAL_PFX "comment:test_retval="
  28. #define TEST_TAG_RETVAL_PFX_UNPRIV "comment:test_retval_unpriv="
  29. #define TEST_TAG_AUXILIARY "comment:test_auxiliary"
  30. #define TEST_TAG_AUXILIARY_UNPRIV "comment:test_auxiliary_unpriv"
  31. #define TEST_BTF_PATH "comment:test_btf_path="
  32. #define TEST_TAG_ARCH "comment:test_arch="
  33. #define TEST_TAG_JITED_PFX "comment:test_jited="
  34. #define TEST_TAG_JITED_PFX_UNPRIV "comment:test_jited_unpriv="
  35. /* Warning: duplicated in bpf_misc.h */
  36. #define POINTER_VALUE 0xcafe4all
  37. #define TEST_DATA_LEN 64
  38. #ifdef CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS
  39. #define EFFICIENT_UNALIGNED_ACCESS 1
  40. #else
  41. #define EFFICIENT_UNALIGNED_ACCESS 0
  42. #endif
  43. static int sysctl_unpriv_disabled = -1;
  44. enum mode {
  45. PRIV = 1,
  46. UNPRIV = 2
  47. };
  48. struct expect_msg {
  49. const char *substr; /* substring match */
  50. regex_t regex;
  51. bool is_regex;
  52. bool on_next_line;
  53. };
  54. struct expected_msgs {
  55. struct expect_msg *patterns;
  56. size_t cnt;
  57. };
  58. struct test_subspec {
  59. char *name;
  60. bool expect_failure;
  61. struct expected_msgs expect_msgs;
  62. struct expected_msgs expect_xlated;
  63. struct expected_msgs jited;
  64. int retval;
  65. bool execute;
  66. };
  67. struct test_spec {
  68. const char *prog_name;
  69. struct test_subspec priv;
  70. struct test_subspec unpriv;
  71. const char *btf_custom_path;
  72. int log_level;
  73. int prog_flags;
  74. int mode_mask;
  75. int arch_mask;
  76. bool auxiliary;
  77. bool valid;
  78. };
  79. static int tester_init(struct test_loader *tester)
  80. {
  81. if (!tester->log_buf) {
  82. tester->log_buf_sz = TEST_LOADER_LOG_BUF_SZ;
  83. tester->log_buf = calloc(tester->log_buf_sz, 1);
  84. if (!ASSERT_OK_PTR(tester->log_buf, "tester_log_buf"))
  85. return -ENOMEM;
  86. }
  87. return 0;
  88. }
  89. void test_loader_fini(struct test_loader *tester)
  90. {
  91. if (!tester)
  92. return;
  93. free(tester->log_buf);
  94. }
  95. static void free_msgs(struct expected_msgs *msgs)
  96. {
  97. int i;
  98. for (i = 0; i < msgs->cnt; i++)
  99. if (msgs->patterns[i].is_regex)
  100. regfree(&msgs->patterns[i].regex);
  101. free(msgs->patterns);
  102. msgs->patterns = NULL;
  103. msgs->cnt = 0;
  104. }
  105. static void free_test_spec(struct test_spec *spec)
  106. {
  107. /* Deallocate expect_msgs arrays. */
  108. free_msgs(&spec->priv.expect_msgs);
  109. free_msgs(&spec->unpriv.expect_msgs);
  110. free_msgs(&spec->priv.expect_xlated);
  111. free_msgs(&spec->unpriv.expect_xlated);
  112. free_msgs(&spec->priv.jited);
  113. free_msgs(&spec->unpriv.jited);
  114. free(spec->priv.name);
  115. free(spec->unpriv.name);
  116. spec->priv.name = NULL;
  117. spec->unpriv.name = NULL;
  118. }
  119. /* Compiles regular expression matching pattern.
  120. * Pattern has a special syntax:
  121. *
  122. * pattern := (<verbatim text> | regex)*
  123. * regex := "{{" <posix extended regular expression> "}}"
  124. *
  125. * In other words, pattern is a verbatim text with inclusion
  126. * of regular expressions enclosed in "{{" "}}" pairs.
  127. * For example, pattern "foo{{[0-9]+}}" matches strings like
  128. * "foo0", "foo007", etc.
  129. */
  130. static int compile_regex(const char *pattern, regex_t *regex)
  131. {
  132. char err_buf[256], buf[256] = {}, *ptr, *buf_end;
  133. const char *original_pattern = pattern;
  134. bool in_regex = false;
  135. int err;
  136. buf_end = buf + sizeof(buf);
  137. ptr = buf;
  138. while (*pattern && ptr < buf_end - 2) {
  139. if (!in_regex && str_has_pfx(pattern, "{{")) {
  140. in_regex = true;
  141. pattern += 2;
  142. continue;
  143. }
  144. if (in_regex && str_has_pfx(pattern, "}}")) {
  145. in_regex = false;
  146. pattern += 2;
  147. continue;
  148. }
  149. if (in_regex) {
  150. *ptr++ = *pattern++;
  151. continue;
  152. }
  153. /* list of characters that need escaping for extended posix regex */
  154. if (strchr(".[]\\()*+?{}|^$", *pattern)) {
  155. *ptr++ = '\\';
  156. *ptr++ = *pattern++;
  157. continue;
  158. }
  159. *ptr++ = *pattern++;
  160. }
  161. if (*pattern) {
  162. PRINT_FAIL("Regexp too long: '%s'\n", original_pattern);
  163. return -EINVAL;
  164. }
  165. if (in_regex) {
  166. PRINT_FAIL("Regexp has open '{{' but no closing '}}': '%s'\n", original_pattern);
  167. return -EINVAL;
  168. }
  169. err = regcomp(regex, buf, REG_EXTENDED | REG_NEWLINE);
  170. if (err != 0) {
  171. regerror(err, regex, err_buf, sizeof(err_buf));
  172. PRINT_FAIL("Regexp compilation error in '%s': '%s'\n", buf, err_buf);
  173. return -EINVAL;
  174. }
  175. return 0;
  176. }
  177. static int __push_msg(const char *pattern, bool on_next_line, struct expected_msgs *msgs)
  178. {
  179. struct expect_msg *msg;
  180. void *tmp;
  181. int err;
  182. tmp = realloc(msgs->patterns,
  183. (1 + msgs->cnt) * sizeof(struct expect_msg));
  184. if (!tmp) {
  185. ASSERT_FAIL("failed to realloc memory for messages\n");
  186. return -ENOMEM;
  187. }
  188. msgs->patterns = tmp;
  189. msg = &msgs->patterns[msgs->cnt];
  190. msg->on_next_line = on_next_line;
  191. msg->substr = pattern;
  192. msg->is_regex = false;
  193. if (strstr(pattern, "{{")) {
  194. err = compile_regex(pattern, &msg->regex);
  195. if (err)
  196. return err;
  197. msg->is_regex = true;
  198. }
  199. msgs->cnt += 1;
  200. return 0;
  201. }
  202. static int clone_msgs(struct expected_msgs *from, struct expected_msgs *to)
  203. {
  204. struct expect_msg *msg;
  205. int i, err;
  206. for (i = 0; i < from->cnt; i++) {
  207. msg = &from->patterns[i];
  208. err = __push_msg(msg->substr, msg->on_next_line, to);
  209. if (err)
  210. return err;
  211. }
  212. return 0;
  213. }
  214. static int push_msg(const char *substr, struct expected_msgs *msgs)
  215. {
  216. return __push_msg(substr, false, msgs);
  217. }
  218. static int push_disasm_msg(const char *regex_str, bool *on_next_line, struct expected_msgs *msgs)
  219. {
  220. int err;
  221. if (strcmp(regex_str, "...") == 0) {
  222. *on_next_line = false;
  223. return 0;
  224. }
  225. err = __push_msg(regex_str, *on_next_line, msgs);
  226. if (err)
  227. return err;
  228. *on_next_line = true;
  229. return 0;
  230. }
  231. static int parse_int(const char *str, int *val, const char *name)
  232. {
  233. char *end;
  234. long tmp;
  235. errno = 0;
  236. if (str_has_pfx(str, "0x"))
  237. tmp = strtol(str + 2, &end, 16);
  238. else
  239. tmp = strtol(str, &end, 10);
  240. if (errno || end[0] != '\0') {
  241. PRINT_FAIL("failed to parse %s from '%s'\n", name, str);
  242. return -EINVAL;
  243. }
  244. *val = tmp;
  245. return 0;
  246. }
  247. static int parse_retval(const char *str, int *val, const char *name)
  248. {
  249. struct {
  250. char *name;
  251. int val;
  252. } named_values[] = {
  253. { "INT_MIN" , INT_MIN },
  254. { "POINTER_VALUE", POINTER_VALUE },
  255. { "TEST_DATA_LEN", TEST_DATA_LEN },
  256. };
  257. int i;
  258. for (i = 0; i < ARRAY_SIZE(named_values); ++i) {
  259. if (strcmp(str, named_values[i].name) != 0)
  260. continue;
  261. *val = named_values[i].val;
  262. return 0;
  263. }
  264. return parse_int(str, val, name);
  265. }
  266. static void update_flags(int *flags, int flag, bool clear)
  267. {
  268. if (clear)
  269. *flags &= ~flag;
  270. else
  271. *flags |= flag;
  272. }
  273. /* Matches a string of form '<pfx>[^=]=.*' and returns it's suffix.
  274. * Used to parse btf_decl_tag values.
  275. * Such values require unique prefix because compiler does not add
  276. * same __attribute__((btf_decl_tag(...))) twice.
  277. * Test suite uses two-component tags for such cases:
  278. *
  279. * <pfx> __COUNTER__ '='
  280. *
  281. * For example, two consecutive __msg tags '__msg("foo") __msg("foo")'
  282. * would be encoded as:
  283. *
  284. * [18] DECL_TAG 'comment:test_expect_msg=0=foo' type_id=15 component_idx=-1
  285. * [19] DECL_TAG 'comment:test_expect_msg=1=foo' type_id=15 component_idx=-1
  286. *
  287. * And the purpose of this function is to extract 'foo' from the above.
  288. */
  289. static const char *skip_dynamic_pfx(const char *s, const char *pfx)
  290. {
  291. const char *msg;
  292. if (strncmp(s, pfx, strlen(pfx)) != 0)
  293. return NULL;
  294. msg = s + strlen(pfx);
  295. msg = strchr(msg, '=');
  296. if (!msg)
  297. return NULL;
  298. return msg + 1;
  299. }
  300. enum arch {
  301. ARCH_UNKNOWN = 0x1,
  302. ARCH_X86_64 = 0x2,
  303. ARCH_ARM64 = 0x4,
  304. ARCH_RISCV64 = 0x8,
  305. };
  306. static int get_current_arch(void)
  307. {
  308. #if defined(__x86_64__)
  309. return ARCH_X86_64;
  310. #elif defined(__aarch64__)
  311. return ARCH_ARM64;
  312. #elif defined(__riscv) && __riscv_xlen == 64
  313. return ARCH_RISCV64;
  314. #endif
  315. return ARCH_UNKNOWN;
  316. }
  317. /* Uses btf_decl_tag attributes to describe the expected test
  318. * behavior, see bpf_misc.h for detailed description of each attribute
  319. * and attribute combinations.
  320. */
  321. static int parse_test_spec(struct test_loader *tester,
  322. struct bpf_object *obj,
  323. struct bpf_program *prog,
  324. struct test_spec *spec)
  325. {
  326. const char *description = NULL;
  327. bool has_unpriv_result = false;
  328. bool has_unpriv_retval = false;
  329. bool unpriv_xlated_on_next_line = true;
  330. bool xlated_on_next_line = true;
  331. bool unpriv_jit_on_next_line;
  332. bool jit_on_next_line;
  333. bool collect_jit = false;
  334. int func_id, i, err = 0;
  335. u32 arch_mask = 0;
  336. struct btf *btf;
  337. enum arch arch;
  338. memset(spec, 0, sizeof(*spec));
  339. spec->prog_name = bpf_program__name(prog);
  340. spec->prog_flags = testing_prog_flags();
  341. btf = bpf_object__btf(obj);
  342. if (!btf) {
  343. ASSERT_FAIL("BPF object has no BTF");
  344. return -EINVAL;
  345. }
  346. func_id = btf__find_by_name_kind(btf, spec->prog_name, BTF_KIND_FUNC);
  347. if (func_id < 0) {
  348. ASSERT_FAIL("failed to find FUNC BTF type for '%s'", spec->prog_name);
  349. return -EINVAL;
  350. }
  351. for (i = 1; i < btf__type_cnt(btf); i++) {
  352. const char *s, *val, *msg;
  353. const struct btf_type *t;
  354. bool clear;
  355. int flags;
  356. t = btf__type_by_id(btf, i);
  357. if (!btf_is_decl_tag(t))
  358. continue;
  359. if (t->type != func_id || btf_decl_tag(t)->component_idx != -1)
  360. continue;
  361. s = btf__str_by_offset(btf, t->name_off);
  362. if (str_has_pfx(s, TEST_TAG_DESCRIPTION_PFX)) {
  363. description = s + sizeof(TEST_TAG_DESCRIPTION_PFX) - 1;
  364. } else if (strcmp(s, TEST_TAG_EXPECT_FAILURE) == 0) {
  365. spec->priv.expect_failure = true;
  366. spec->mode_mask |= PRIV;
  367. } else if (strcmp(s, TEST_TAG_EXPECT_SUCCESS) == 0) {
  368. spec->priv.expect_failure = false;
  369. spec->mode_mask |= PRIV;
  370. } else if (strcmp(s, TEST_TAG_EXPECT_FAILURE_UNPRIV) == 0) {
  371. spec->unpriv.expect_failure = true;
  372. spec->mode_mask |= UNPRIV;
  373. has_unpriv_result = true;
  374. } else if (strcmp(s, TEST_TAG_EXPECT_SUCCESS_UNPRIV) == 0) {
  375. spec->unpriv.expect_failure = false;
  376. spec->mode_mask |= UNPRIV;
  377. has_unpriv_result = true;
  378. } else if (strcmp(s, TEST_TAG_AUXILIARY) == 0) {
  379. spec->auxiliary = true;
  380. spec->mode_mask |= PRIV;
  381. } else if (strcmp(s, TEST_TAG_AUXILIARY_UNPRIV) == 0) {
  382. spec->auxiliary = true;
  383. spec->mode_mask |= UNPRIV;
  384. } else if ((msg = skip_dynamic_pfx(s, TEST_TAG_EXPECT_MSG_PFX))) {
  385. err = push_msg(msg, &spec->priv.expect_msgs);
  386. if (err)
  387. goto cleanup;
  388. spec->mode_mask |= PRIV;
  389. } else if ((msg = skip_dynamic_pfx(s, TEST_TAG_EXPECT_MSG_PFX_UNPRIV))) {
  390. err = push_msg(msg, &spec->unpriv.expect_msgs);
  391. if (err)
  392. goto cleanup;
  393. spec->mode_mask |= UNPRIV;
  394. } else if ((msg = skip_dynamic_pfx(s, TEST_TAG_JITED_PFX))) {
  395. if (arch_mask == 0) {
  396. PRINT_FAIL("__jited used before __arch_*");
  397. goto cleanup;
  398. }
  399. if (collect_jit) {
  400. err = push_disasm_msg(msg, &jit_on_next_line,
  401. &spec->priv.jited);
  402. if (err)
  403. goto cleanup;
  404. spec->mode_mask |= PRIV;
  405. }
  406. } else if ((msg = skip_dynamic_pfx(s, TEST_TAG_JITED_PFX_UNPRIV))) {
  407. if (arch_mask == 0) {
  408. PRINT_FAIL("__unpriv_jited used before __arch_*");
  409. goto cleanup;
  410. }
  411. if (collect_jit) {
  412. err = push_disasm_msg(msg, &unpriv_jit_on_next_line,
  413. &spec->unpriv.jited);
  414. if (err)
  415. goto cleanup;
  416. spec->mode_mask |= UNPRIV;
  417. }
  418. } else if ((msg = skip_dynamic_pfx(s, TEST_TAG_EXPECT_XLATED_PFX))) {
  419. err = push_disasm_msg(msg, &xlated_on_next_line,
  420. &spec->priv.expect_xlated);
  421. if (err)
  422. goto cleanup;
  423. spec->mode_mask |= PRIV;
  424. } else if ((msg = skip_dynamic_pfx(s, TEST_TAG_EXPECT_XLATED_PFX_UNPRIV))) {
  425. err = push_disasm_msg(msg, &unpriv_xlated_on_next_line,
  426. &spec->unpriv.expect_xlated);
  427. if (err)
  428. goto cleanup;
  429. spec->mode_mask |= UNPRIV;
  430. } else if (str_has_pfx(s, TEST_TAG_RETVAL_PFX)) {
  431. val = s + sizeof(TEST_TAG_RETVAL_PFX) - 1;
  432. err = parse_retval(val, &spec->priv.retval, "__retval");
  433. if (err)
  434. goto cleanup;
  435. spec->priv.execute = true;
  436. spec->mode_mask |= PRIV;
  437. } else if (str_has_pfx(s, TEST_TAG_RETVAL_PFX_UNPRIV)) {
  438. val = s + sizeof(TEST_TAG_RETVAL_PFX_UNPRIV) - 1;
  439. err = parse_retval(val, &spec->unpriv.retval, "__retval_unpriv");
  440. if (err)
  441. goto cleanup;
  442. spec->mode_mask |= UNPRIV;
  443. spec->unpriv.execute = true;
  444. has_unpriv_retval = true;
  445. } else if (str_has_pfx(s, TEST_TAG_LOG_LEVEL_PFX)) {
  446. val = s + sizeof(TEST_TAG_LOG_LEVEL_PFX) - 1;
  447. err = parse_int(val, &spec->log_level, "test log level");
  448. if (err)
  449. goto cleanup;
  450. } else if (str_has_pfx(s, TEST_TAG_PROG_FLAGS_PFX)) {
  451. val = s + sizeof(TEST_TAG_PROG_FLAGS_PFX) - 1;
  452. clear = val[0] == '!';
  453. if (clear)
  454. val++;
  455. if (strcmp(val, "BPF_F_STRICT_ALIGNMENT") == 0) {
  456. update_flags(&spec->prog_flags, BPF_F_STRICT_ALIGNMENT, clear);
  457. } else if (strcmp(val, "BPF_F_ANY_ALIGNMENT") == 0) {
  458. update_flags(&spec->prog_flags, BPF_F_ANY_ALIGNMENT, clear);
  459. } else if (strcmp(val, "BPF_F_TEST_RND_HI32") == 0) {
  460. update_flags(&spec->prog_flags, BPF_F_TEST_RND_HI32, clear);
  461. } else if (strcmp(val, "BPF_F_TEST_STATE_FREQ") == 0) {
  462. update_flags(&spec->prog_flags, BPF_F_TEST_STATE_FREQ, clear);
  463. } else if (strcmp(val, "BPF_F_SLEEPABLE") == 0) {
  464. update_flags(&spec->prog_flags, BPF_F_SLEEPABLE, clear);
  465. } else if (strcmp(val, "BPF_F_XDP_HAS_FRAGS") == 0) {
  466. update_flags(&spec->prog_flags, BPF_F_XDP_HAS_FRAGS, clear);
  467. } else if (strcmp(val, "BPF_F_TEST_REG_INVARIANTS") == 0) {
  468. update_flags(&spec->prog_flags, BPF_F_TEST_REG_INVARIANTS, clear);
  469. } else /* assume numeric value */ {
  470. err = parse_int(val, &flags, "test prog flags");
  471. if (err)
  472. goto cleanup;
  473. update_flags(&spec->prog_flags, flags, clear);
  474. }
  475. } else if (str_has_pfx(s, TEST_TAG_ARCH)) {
  476. val = s + sizeof(TEST_TAG_ARCH) - 1;
  477. if (strcmp(val, "X86_64") == 0) {
  478. arch = ARCH_X86_64;
  479. } else if (strcmp(val, "ARM64") == 0) {
  480. arch = ARCH_ARM64;
  481. } else if (strcmp(val, "RISCV64") == 0) {
  482. arch = ARCH_RISCV64;
  483. } else {
  484. PRINT_FAIL("bad arch spec: '%s'", val);
  485. err = -EINVAL;
  486. goto cleanup;
  487. }
  488. arch_mask |= arch;
  489. collect_jit = get_current_arch() == arch;
  490. unpriv_jit_on_next_line = true;
  491. jit_on_next_line = true;
  492. } else if (str_has_pfx(s, TEST_BTF_PATH)) {
  493. spec->btf_custom_path = s + sizeof(TEST_BTF_PATH) - 1;
  494. }
  495. }
  496. spec->arch_mask = arch_mask ?: -1;
  497. if (spec->mode_mask == 0)
  498. spec->mode_mask = PRIV;
  499. if (!description)
  500. description = spec->prog_name;
  501. if (spec->mode_mask & PRIV) {
  502. spec->priv.name = strdup(description);
  503. if (!spec->priv.name) {
  504. PRINT_FAIL("failed to allocate memory for priv.name\n");
  505. err = -ENOMEM;
  506. goto cleanup;
  507. }
  508. }
  509. if (spec->mode_mask & UNPRIV) {
  510. int descr_len = strlen(description);
  511. const char *suffix = " @unpriv";
  512. char *name;
  513. name = malloc(descr_len + strlen(suffix) + 1);
  514. if (!name) {
  515. PRINT_FAIL("failed to allocate memory for unpriv.name\n");
  516. err = -ENOMEM;
  517. goto cleanup;
  518. }
  519. strcpy(name, description);
  520. strcpy(&name[descr_len], suffix);
  521. spec->unpriv.name = name;
  522. }
  523. if (spec->mode_mask & (PRIV | UNPRIV)) {
  524. if (!has_unpriv_result)
  525. spec->unpriv.expect_failure = spec->priv.expect_failure;
  526. if (!has_unpriv_retval) {
  527. spec->unpriv.retval = spec->priv.retval;
  528. spec->unpriv.execute = spec->priv.execute;
  529. }
  530. if (spec->unpriv.expect_msgs.cnt == 0)
  531. clone_msgs(&spec->priv.expect_msgs, &spec->unpriv.expect_msgs);
  532. if (spec->unpriv.expect_xlated.cnt == 0)
  533. clone_msgs(&spec->priv.expect_xlated, &spec->unpriv.expect_xlated);
  534. if (spec->unpriv.jited.cnt == 0)
  535. clone_msgs(&spec->priv.jited, &spec->unpriv.jited);
  536. }
  537. spec->valid = true;
  538. return 0;
  539. cleanup:
  540. free_test_spec(spec);
  541. return err;
  542. }
  543. static void prepare_case(struct test_loader *tester,
  544. struct test_spec *spec,
  545. struct bpf_object *obj,
  546. struct bpf_program *prog)
  547. {
  548. int min_log_level = 0, prog_flags;
  549. if (env.verbosity > VERBOSE_NONE)
  550. min_log_level = 1;
  551. if (env.verbosity > VERBOSE_VERY)
  552. min_log_level = 2;
  553. bpf_program__set_log_buf(prog, tester->log_buf, tester->log_buf_sz);
  554. /* Make sure we set at least minimal log level, unless test requires
  555. * even higher level already. Make sure to preserve independent log
  556. * level 4 (verifier stats), though.
  557. */
  558. if ((spec->log_level & 3) < min_log_level)
  559. bpf_program__set_log_level(prog, (spec->log_level & 4) | min_log_level);
  560. else
  561. bpf_program__set_log_level(prog, spec->log_level);
  562. prog_flags = bpf_program__flags(prog);
  563. bpf_program__set_flags(prog, prog_flags | spec->prog_flags);
  564. tester->log_buf[0] = '\0';
  565. }
  566. static void emit_verifier_log(const char *log_buf, bool force)
  567. {
  568. if (!force && env.verbosity == VERBOSE_NONE)
  569. return;
  570. fprintf(stdout, "VERIFIER LOG:\n=============\n%s=============\n", log_buf);
  571. }
  572. static void emit_xlated(const char *xlated, bool force)
  573. {
  574. if (!force && env.verbosity == VERBOSE_NONE)
  575. return;
  576. fprintf(stdout, "XLATED:\n=============\n%s=============\n", xlated);
  577. }
  578. static void emit_jited(const char *jited, bool force)
  579. {
  580. if (!force && env.verbosity == VERBOSE_NONE)
  581. return;
  582. fprintf(stdout, "JITED:\n=============\n%s=============\n", jited);
  583. }
  584. static void validate_msgs(char *log_buf, struct expected_msgs *msgs,
  585. void (*emit_fn)(const char *buf, bool force))
  586. {
  587. const char *log = log_buf, *prev_match;
  588. regmatch_t reg_match[1];
  589. int prev_match_line;
  590. int match_line;
  591. int i, j, err;
  592. prev_match_line = -1;
  593. match_line = 0;
  594. prev_match = log;
  595. for (i = 0; i < msgs->cnt; i++) {
  596. struct expect_msg *msg = &msgs->patterns[i];
  597. const char *match = NULL, *pat_status;
  598. bool wrong_line = false;
  599. if (!msg->is_regex) {
  600. match = strstr(log, msg->substr);
  601. if (match)
  602. log = match + strlen(msg->substr);
  603. } else {
  604. err = regexec(&msg->regex, log, 1, reg_match, 0);
  605. if (err == 0) {
  606. match = log + reg_match[0].rm_so;
  607. log += reg_match[0].rm_eo;
  608. }
  609. }
  610. if (match) {
  611. for (; prev_match < match; ++prev_match)
  612. if (*prev_match == '\n')
  613. ++match_line;
  614. wrong_line = msg->on_next_line && prev_match_line >= 0 &&
  615. prev_match_line + 1 != match_line;
  616. }
  617. if (!match || wrong_line) {
  618. PRINT_FAIL("expect_msg\n");
  619. if (env.verbosity == VERBOSE_NONE)
  620. emit_fn(log_buf, true /*force*/);
  621. for (j = 0; j <= i; j++) {
  622. msg = &msgs->patterns[j];
  623. if (j < i)
  624. pat_status = "MATCHED ";
  625. else if (wrong_line)
  626. pat_status = "WRONG LINE";
  627. else
  628. pat_status = "EXPECTED ";
  629. msg = &msgs->patterns[j];
  630. fprintf(stderr, "%s %s: '%s'\n",
  631. pat_status,
  632. msg->is_regex ? " REGEX" : "SUBSTR",
  633. msg->substr);
  634. }
  635. if (wrong_line) {
  636. fprintf(stderr,
  637. "expecting match at line %d, actual match is at line %d\n",
  638. prev_match_line + 1, match_line);
  639. }
  640. break;
  641. }
  642. prev_match_line = match_line;
  643. }
  644. }
  645. struct cap_state {
  646. __u64 old_caps;
  647. bool initialized;
  648. };
  649. static int drop_capabilities(struct cap_state *caps)
  650. {
  651. const __u64 caps_to_drop = (1ULL << CAP_SYS_ADMIN | 1ULL << CAP_NET_ADMIN |
  652. 1ULL << CAP_PERFMON | 1ULL << CAP_BPF);
  653. int err;
  654. err = cap_disable_effective(caps_to_drop, &caps->old_caps);
  655. if (err) {
  656. PRINT_FAIL("failed to drop capabilities: %i, %s\n", err, strerror(err));
  657. return err;
  658. }
  659. caps->initialized = true;
  660. return 0;
  661. }
  662. static int restore_capabilities(struct cap_state *caps)
  663. {
  664. int err;
  665. if (!caps->initialized)
  666. return 0;
  667. err = cap_enable_effective(caps->old_caps, NULL);
  668. if (err)
  669. PRINT_FAIL("failed to restore capabilities: %i, %s\n", err, strerror(err));
  670. caps->initialized = false;
  671. return err;
  672. }
  673. static bool can_execute_unpriv(struct test_loader *tester, struct test_spec *spec)
  674. {
  675. if (sysctl_unpriv_disabled < 0)
  676. sysctl_unpriv_disabled = get_unpriv_disabled() ? 1 : 0;
  677. if (sysctl_unpriv_disabled)
  678. return false;
  679. if ((spec->prog_flags & BPF_F_ANY_ALIGNMENT) && !EFFICIENT_UNALIGNED_ACCESS)
  680. return false;
  681. return true;
  682. }
  683. static bool is_unpriv_capable_map(struct bpf_map *map)
  684. {
  685. enum bpf_map_type type;
  686. __u32 flags;
  687. type = bpf_map__type(map);
  688. switch (type) {
  689. case BPF_MAP_TYPE_HASH:
  690. case BPF_MAP_TYPE_PERCPU_HASH:
  691. case BPF_MAP_TYPE_HASH_OF_MAPS:
  692. flags = bpf_map__map_flags(map);
  693. return !(flags & BPF_F_ZERO_SEED);
  694. case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
  695. case BPF_MAP_TYPE_ARRAY:
  696. case BPF_MAP_TYPE_RINGBUF:
  697. case BPF_MAP_TYPE_PROG_ARRAY:
  698. case BPF_MAP_TYPE_CGROUP_ARRAY:
  699. case BPF_MAP_TYPE_PERCPU_ARRAY:
  700. case BPF_MAP_TYPE_USER_RINGBUF:
  701. case BPF_MAP_TYPE_ARRAY_OF_MAPS:
  702. case BPF_MAP_TYPE_CGROUP_STORAGE:
  703. case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
  704. return true;
  705. default:
  706. return false;
  707. }
  708. }
  709. static int do_prog_test_run(int fd_prog, int *retval, bool empty_opts)
  710. {
  711. __u8 tmp_out[TEST_DATA_LEN << 2] = {};
  712. __u8 tmp_in[TEST_DATA_LEN] = {};
  713. int err, saved_errno;
  714. LIBBPF_OPTS(bpf_test_run_opts, topts,
  715. .data_in = tmp_in,
  716. .data_size_in = sizeof(tmp_in),
  717. .data_out = tmp_out,
  718. .data_size_out = sizeof(tmp_out),
  719. .repeat = 1,
  720. );
  721. if (empty_opts) {
  722. memset(&topts, 0, sizeof(struct bpf_test_run_opts));
  723. topts.sz = sizeof(struct bpf_test_run_opts);
  724. }
  725. err = bpf_prog_test_run_opts(fd_prog, &topts);
  726. saved_errno = errno;
  727. if (err) {
  728. PRINT_FAIL("FAIL: Unexpected bpf_prog_test_run error: %d (%s) ",
  729. saved_errno, strerror(saved_errno));
  730. return err;
  731. }
  732. ASSERT_OK(0, "bpf_prog_test_run");
  733. *retval = topts.retval;
  734. return 0;
  735. }
  736. static bool should_do_test_run(struct test_spec *spec, struct test_subspec *subspec)
  737. {
  738. if (!subspec->execute)
  739. return false;
  740. if (subspec->expect_failure)
  741. return false;
  742. if ((spec->prog_flags & BPF_F_ANY_ALIGNMENT) && !EFFICIENT_UNALIGNED_ACCESS) {
  743. if (env.verbosity != VERBOSE_NONE)
  744. printf("alignment prevents execution\n");
  745. return false;
  746. }
  747. return true;
  748. }
  749. /* Get a disassembly of BPF program after verifier applies all rewrites */
  750. static int get_xlated_program_text(int prog_fd, char *text, size_t text_sz)
  751. {
  752. struct bpf_insn *insn_start = NULL, *insn, *insn_end;
  753. __u32 insns_cnt = 0, i;
  754. char buf[64];
  755. FILE *out = NULL;
  756. int err;
  757. err = get_xlated_program(prog_fd, &insn_start, &insns_cnt);
  758. if (!ASSERT_OK(err, "get_xlated_program"))
  759. goto out;
  760. out = fmemopen(text, text_sz, "w");
  761. if (!ASSERT_OK_PTR(out, "open_memstream"))
  762. goto out;
  763. insn_end = insn_start + insns_cnt;
  764. insn = insn_start;
  765. while (insn < insn_end) {
  766. i = insn - insn_start;
  767. insn = disasm_insn(insn, buf, sizeof(buf));
  768. fprintf(out, "%d: %s\n", i, buf);
  769. }
  770. fflush(out);
  771. out:
  772. free(insn_start);
  773. if (out)
  774. fclose(out);
  775. return err;
  776. }
  777. /* this function is forced noinline and has short generic name to look better
  778. * in test_progs output (in case of a failure)
  779. */
  780. static noinline
  781. void run_subtest(struct test_loader *tester,
  782. struct bpf_object_open_opts *open_opts,
  783. const void *obj_bytes,
  784. size_t obj_byte_cnt,
  785. struct test_spec *specs,
  786. struct test_spec *spec,
  787. bool unpriv)
  788. {
  789. struct test_subspec *subspec = unpriv ? &spec->unpriv : &spec->priv;
  790. struct bpf_program *tprog = NULL, *tprog_iter;
  791. struct bpf_link *link, *links[32] = {};
  792. struct test_spec *spec_iter;
  793. struct cap_state caps = {};
  794. struct bpf_object *tobj;
  795. struct bpf_map *map;
  796. int retval, err, i;
  797. int links_cnt = 0;
  798. bool should_load;
  799. if (!test__start_subtest(subspec->name))
  800. return;
  801. if ((get_current_arch() & spec->arch_mask) == 0) {
  802. test__skip();
  803. return;
  804. }
  805. if (unpriv) {
  806. if (!can_execute_unpriv(tester, spec)) {
  807. test__skip();
  808. test__end_subtest();
  809. return;
  810. }
  811. if (drop_capabilities(&caps)) {
  812. test__end_subtest();
  813. return;
  814. }
  815. }
  816. /* Implicitly reset to NULL if next test case doesn't specify */
  817. open_opts->btf_custom_path = spec->btf_custom_path;
  818. tobj = bpf_object__open_mem(obj_bytes, obj_byte_cnt, open_opts);
  819. if (!ASSERT_OK_PTR(tobj, "obj_open_mem")) /* shouldn't happen */
  820. goto subtest_cleanup;
  821. i = 0;
  822. bpf_object__for_each_program(tprog_iter, tobj) {
  823. spec_iter = &specs[i++];
  824. should_load = false;
  825. if (spec_iter->valid) {
  826. if (strcmp(bpf_program__name(tprog_iter), spec->prog_name) == 0) {
  827. tprog = tprog_iter;
  828. should_load = true;
  829. }
  830. if (spec_iter->auxiliary &&
  831. spec_iter->mode_mask & (unpriv ? UNPRIV : PRIV))
  832. should_load = true;
  833. }
  834. bpf_program__set_autoload(tprog_iter, should_load);
  835. }
  836. prepare_case(tester, spec, tobj, tprog);
  837. /* By default bpf_object__load() automatically creates all
  838. * maps declared in the skeleton. Some map types are only
  839. * allowed in priv mode. Disable autoload for such maps in
  840. * unpriv mode.
  841. */
  842. bpf_object__for_each_map(map, tobj)
  843. bpf_map__set_autocreate(map, !unpriv || is_unpriv_capable_map(map));
  844. err = bpf_object__load(tobj);
  845. if (subspec->expect_failure) {
  846. if (!ASSERT_ERR(err, "unexpected_load_success")) {
  847. emit_verifier_log(tester->log_buf, false /*force*/);
  848. goto tobj_cleanup;
  849. }
  850. } else {
  851. if (!ASSERT_OK(err, "unexpected_load_failure")) {
  852. emit_verifier_log(tester->log_buf, true /*force*/);
  853. goto tobj_cleanup;
  854. }
  855. }
  856. emit_verifier_log(tester->log_buf, false /*force*/);
  857. validate_msgs(tester->log_buf, &subspec->expect_msgs, emit_verifier_log);
  858. /* Restore capabilities because the kernel will silently ignore requests
  859. * for program info (such as xlated program text) if we are not
  860. * bpf-capable. Also, for some reason test_verifier executes programs
  861. * with all capabilities restored. Do the same here.
  862. */
  863. if (restore_capabilities(&caps))
  864. goto tobj_cleanup;
  865. if (subspec->expect_xlated.cnt) {
  866. err = get_xlated_program_text(bpf_program__fd(tprog),
  867. tester->log_buf, tester->log_buf_sz);
  868. if (err)
  869. goto tobj_cleanup;
  870. emit_xlated(tester->log_buf, false /*force*/);
  871. validate_msgs(tester->log_buf, &subspec->expect_xlated, emit_xlated);
  872. }
  873. if (subspec->jited.cnt) {
  874. err = get_jited_program_text(bpf_program__fd(tprog),
  875. tester->log_buf, tester->log_buf_sz);
  876. if (err == -EOPNOTSUPP) {
  877. printf("%s:SKIP: jited programs disassembly is not supported,\n", __func__);
  878. printf("%s:SKIP: tests are built w/o LLVM development libs\n", __func__);
  879. test__skip();
  880. goto tobj_cleanup;
  881. }
  882. if (!ASSERT_EQ(err, 0, "get_jited_program_text"))
  883. goto tobj_cleanup;
  884. emit_jited(tester->log_buf, false /*force*/);
  885. validate_msgs(tester->log_buf, &subspec->jited, emit_jited);
  886. }
  887. if (should_do_test_run(spec, subspec)) {
  888. /* Do bpf_map__attach_struct_ops() for each struct_ops map.
  889. * This should trigger bpf_struct_ops->reg callback on kernel side.
  890. */
  891. bpf_object__for_each_map(map, tobj) {
  892. if (!bpf_map__autocreate(map) ||
  893. bpf_map__type(map) != BPF_MAP_TYPE_STRUCT_OPS)
  894. continue;
  895. if (links_cnt >= ARRAY_SIZE(links)) {
  896. PRINT_FAIL("too many struct_ops maps");
  897. goto tobj_cleanup;
  898. }
  899. link = bpf_map__attach_struct_ops(map);
  900. if (!link) {
  901. PRINT_FAIL("bpf_map__attach_struct_ops failed for map %s: err=%d\n",
  902. bpf_map__name(map), err);
  903. goto tobj_cleanup;
  904. }
  905. links[links_cnt++] = link;
  906. }
  907. if (tester->pre_execution_cb) {
  908. err = tester->pre_execution_cb(tobj);
  909. if (err) {
  910. PRINT_FAIL("pre_execution_cb failed: %d\n", err);
  911. goto tobj_cleanup;
  912. }
  913. }
  914. do_prog_test_run(bpf_program__fd(tprog), &retval,
  915. bpf_program__type(tprog) == BPF_PROG_TYPE_SYSCALL ? true : false);
  916. if (retval != subspec->retval && subspec->retval != POINTER_VALUE) {
  917. PRINT_FAIL("Unexpected retval: %d != %d\n", retval, subspec->retval);
  918. goto tobj_cleanup;
  919. }
  920. /* redo bpf_map__attach_struct_ops for each test */
  921. while (links_cnt > 0)
  922. bpf_link__destroy(links[--links_cnt]);
  923. }
  924. tobj_cleanup:
  925. while (links_cnt > 0)
  926. bpf_link__destroy(links[--links_cnt]);
  927. bpf_object__close(tobj);
  928. subtest_cleanup:
  929. test__end_subtest();
  930. restore_capabilities(&caps);
  931. }
  932. static void process_subtest(struct test_loader *tester,
  933. const char *skel_name,
  934. skel_elf_bytes_fn elf_bytes_factory)
  935. {
  936. LIBBPF_OPTS(bpf_object_open_opts, open_opts, .object_name = skel_name);
  937. struct test_spec *specs = NULL;
  938. struct bpf_object *obj = NULL;
  939. struct bpf_program *prog;
  940. const void *obj_bytes;
  941. int err, i, nr_progs;
  942. size_t obj_byte_cnt;
  943. if (tester_init(tester) < 0)
  944. return; /* failed to initialize tester */
  945. obj_bytes = elf_bytes_factory(&obj_byte_cnt);
  946. obj = bpf_object__open_mem(obj_bytes, obj_byte_cnt, &open_opts);
  947. if (!ASSERT_OK_PTR(obj, "obj_open_mem"))
  948. return;
  949. nr_progs = 0;
  950. bpf_object__for_each_program(prog, obj)
  951. ++nr_progs;
  952. specs = calloc(nr_progs, sizeof(struct test_spec));
  953. if (!ASSERT_OK_PTR(specs, "specs_alloc"))
  954. return;
  955. i = 0;
  956. bpf_object__for_each_program(prog, obj) {
  957. /* ignore tests for which we can't derive test specification */
  958. err = parse_test_spec(tester, obj, prog, &specs[i++]);
  959. if (err)
  960. PRINT_FAIL("Can't parse test spec for program '%s'\n",
  961. bpf_program__name(prog));
  962. }
  963. i = 0;
  964. bpf_object__for_each_program(prog, obj) {
  965. struct test_spec *spec = &specs[i++];
  966. if (!spec->valid || spec->auxiliary)
  967. continue;
  968. if (spec->mode_mask & PRIV)
  969. run_subtest(tester, &open_opts, obj_bytes, obj_byte_cnt,
  970. specs, spec, false);
  971. if (spec->mode_mask & UNPRIV)
  972. run_subtest(tester, &open_opts, obj_bytes, obj_byte_cnt,
  973. specs, spec, true);
  974. }
  975. for (i = 0; i < nr_progs; ++i)
  976. free_test_spec(&specs[i]);
  977. free(specs);
  978. bpf_object__close(obj);
  979. }
  980. void test_loader__run_subtests(struct test_loader *tester,
  981. const char *skel_name,
  982. skel_elf_bytes_fn elf_bytes_factory)
  983. {
  984. /* see comment in run_subtest() for why we do this function nesting */
  985. process_subtest(tester, skel_name, elf_bytes_factory);
  986. }