test_progs.c 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961
  1. // SPDX-License-Identifier: GPL-2.0-only
  2. /* Copyright (c) 2017 Facebook
  3. */
  4. #define _GNU_SOURCE
  5. #include "test_progs.h"
  6. #include "testing_helpers.h"
  7. #include "cgroup_helpers.h"
  8. #include <argp.h>
  9. #include <pthread.h>
  10. #include <sched.h>
  11. #include <signal.h>
  12. #include <string.h>
  13. #include <sys/sysinfo.h> /* get_nprocs */
  14. #include <netinet/in.h>
  15. #include <sys/select.h>
  16. #include <sys/socket.h>
  17. #include <sys/un.h>
  18. #include <bpf/btf.h>
  19. #include "json_writer.h"
  20. #include "network_helpers.h"
  21. /* backtrace() and backtrace_symbols_fd() are glibc specific,
  22. * use header file when glibc is available and provide stub
  23. * implementations when another libc implementation is used.
  24. */
  25. #ifdef __GLIBC__
  26. #include <execinfo.h> /* backtrace */
  27. #else
  28. __weak int backtrace(void **buffer, int size)
  29. {
  30. return 0;
  31. }
  32. __weak void backtrace_symbols_fd(void *const *buffer, int size, int fd)
  33. {
  34. dprintf(fd, "<backtrace not supported>\n");
  35. }
  36. #endif /*__GLIBC__ */
  37. int env_verbosity = 0;
  38. static bool verbose(void)
  39. {
  40. return env.verbosity > VERBOSE_NONE;
  41. }
  42. static void stdio_hijack_init(char **log_buf, size_t *log_cnt)
  43. {
  44. #ifdef __GLIBC__
  45. if (verbose() && env.worker_id == -1) {
  46. /* nothing to do, output to stdout by default */
  47. return;
  48. }
  49. fflush(stdout);
  50. fflush(stderr);
  51. stdout = open_memstream(log_buf, log_cnt);
  52. if (!stdout) {
  53. stdout = env.stdout_saved;
  54. perror("open_memstream");
  55. return;
  56. }
  57. if (env.subtest_state)
  58. env.subtest_state->stdout_saved = stdout;
  59. else
  60. env.test_state->stdout_saved = stdout;
  61. stderr = stdout;
  62. #endif
  63. }
  64. static void stdio_hijack(char **log_buf, size_t *log_cnt)
  65. {
  66. #ifdef __GLIBC__
  67. if (verbose() && env.worker_id == -1) {
  68. /* nothing to do, output to stdout by default */
  69. return;
  70. }
  71. env.stdout_saved = stdout;
  72. env.stderr_saved = stderr;
  73. stdio_hijack_init(log_buf, log_cnt);
  74. #endif
  75. }
  76. static void stdio_restore_cleanup(void)
  77. {
  78. #ifdef __GLIBC__
  79. if (verbose() && env.worker_id == -1) {
  80. /* nothing to do, output to stdout by default */
  81. return;
  82. }
  83. fflush(stdout);
  84. if (env.subtest_state) {
  85. fclose(env.subtest_state->stdout_saved);
  86. env.subtest_state->stdout_saved = NULL;
  87. stdout = env.test_state->stdout_saved;
  88. stderr = env.test_state->stdout_saved;
  89. } else {
  90. fclose(env.test_state->stdout_saved);
  91. env.test_state->stdout_saved = NULL;
  92. }
  93. #endif
  94. }
  95. static void stdio_restore(void)
  96. {
  97. #ifdef __GLIBC__
  98. if (verbose() && env.worker_id == -1) {
  99. /* nothing to do, output to stdout by default */
  100. return;
  101. }
  102. if (stdout == env.stdout_saved)
  103. return;
  104. stdio_restore_cleanup();
  105. stdout = env.stdout_saved;
  106. stderr = env.stderr_saved;
  107. #endif
  108. }
  109. /* Adapted from perf/util/string.c */
  110. static bool glob_match(const char *str, const char *pat)
  111. {
  112. while (*str && *pat && *pat != '*') {
  113. if (*str != *pat)
  114. return false;
  115. str++;
  116. pat++;
  117. }
  118. /* Check wild card */
  119. if (*pat == '*') {
  120. while (*pat == '*')
  121. pat++;
  122. if (!*pat) /* Tail wild card matches all */
  123. return true;
  124. while (*str)
  125. if (glob_match(str++, pat))
  126. return true;
  127. }
  128. return !*str && !*pat;
  129. }
  130. #define EXIT_NO_TEST 2
  131. #define EXIT_ERR_SETUP_INFRA 3
  132. /* defined in test_progs.h */
  133. struct test_env env = {};
  134. struct prog_test_def {
  135. const char *test_name;
  136. int test_num;
  137. void (*run_test)(void);
  138. void (*run_serial_test)(void);
  139. bool should_run;
  140. bool need_cgroup_cleanup;
  141. bool should_tmon;
  142. };
  143. /* Override C runtime library's usleep() implementation to ensure nanosleep()
  144. * is always called. Usleep is frequently used in selftests as a way to
  145. * trigger kprobe and tracepoints.
  146. */
  147. int usleep(useconds_t usec)
  148. {
  149. struct timespec ts = {
  150. .tv_sec = usec / 1000000,
  151. .tv_nsec = (usec % 1000000) * 1000,
  152. };
  153. return syscall(__NR_nanosleep, &ts, NULL);
  154. }
  155. static bool should_run(struct test_selector *sel, int num, const char *name)
  156. {
  157. int i;
  158. for (i = 0; i < sel->blacklist.cnt; i++) {
  159. if (glob_match(name, sel->blacklist.tests[i].name) &&
  160. !sel->blacklist.tests[i].subtest_cnt)
  161. return false;
  162. }
  163. for (i = 0; i < sel->whitelist.cnt; i++) {
  164. if (glob_match(name, sel->whitelist.tests[i].name))
  165. return true;
  166. }
  167. if (!sel->whitelist.cnt && !sel->num_set)
  168. return true;
  169. return num < sel->num_set_len && sel->num_set[num];
  170. }
  171. static bool match_subtest(struct test_filter_set *filter,
  172. const char *test_name,
  173. const char *subtest_name)
  174. {
  175. int i, j;
  176. for (i = 0; i < filter->cnt; i++) {
  177. if (glob_match(test_name, filter->tests[i].name)) {
  178. if (!filter->tests[i].subtest_cnt)
  179. return true;
  180. for (j = 0; j < filter->tests[i].subtest_cnt; j++) {
  181. if (glob_match(subtest_name,
  182. filter->tests[i].subtests[j]))
  183. return true;
  184. }
  185. }
  186. }
  187. return false;
  188. }
  189. static bool should_run_subtest(struct test_selector *sel,
  190. struct test_selector *subtest_sel,
  191. int subtest_num,
  192. const char *test_name,
  193. const char *subtest_name)
  194. {
  195. if (match_subtest(&sel->blacklist, test_name, subtest_name))
  196. return false;
  197. if (match_subtest(&sel->whitelist, test_name, subtest_name))
  198. return true;
  199. if (!sel->whitelist.cnt && !subtest_sel->num_set)
  200. return true;
  201. return subtest_num < subtest_sel->num_set_len && subtest_sel->num_set[subtest_num];
  202. }
  203. static bool should_tmon(struct test_selector *sel, const char *name)
  204. {
  205. int i;
  206. for (i = 0; i < sel->whitelist.cnt; i++) {
  207. if (glob_match(name, sel->whitelist.tests[i].name) &&
  208. !sel->whitelist.tests[i].subtest_cnt)
  209. return true;
  210. }
  211. return false;
  212. }
  213. static char *test_result(bool failed, bool skipped)
  214. {
  215. return failed ? "FAIL" : (skipped ? "SKIP" : "OK");
  216. }
  217. #define TEST_NUM_WIDTH 7
  218. static void print_test_result(const struct prog_test_def *test, const struct test_state *test_state)
  219. {
  220. int skipped_cnt = test_state->skip_cnt;
  221. int subtests_cnt = test_state->subtest_num;
  222. fprintf(env.stdout_saved, "#%-*d %s:", TEST_NUM_WIDTH, test->test_num, test->test_name);
  223. if (test_state->error_cnt)
  224. fprintf(env.stdout_saved, "FAIL");
  225. else if (!skipped_cnt)
  226. fprintf(env.stdout_saved, "OK");
  227. else if (skipped_cnt == subtests_cnt || !subtests_cnt)
  228. fprintf(env.stdout_saved, "SKIP");
  229. else
  230. fprintf(env.stdout_saved, "OK (SKIP: %d/%d)", skipped_cnt, subtests_cnt);
  231. fprintf(env.stdout_saved, "\n");
  232. }
  233. static void print_test_log(char *log_buf, size_t log_cnt)
  234. {
  235. log_buf[log_cnt] = '\0';
  236. fprintf(env.stdout_saved, "%s", log_buf);
  237. if (log_buf[log_cnt - 1] != '\n')
  238. fprintf(env.stdout_saved, "\n");
  239. }
  240. static void print_subtest_name(int test_num, int subtest_num,
  241. const char *test_name, char *subtest_name,
  242. char *result)
  243. {
  244. char test_num_str[32];
  245. snprintf(test_num_str, sizeof(test_num_str), "%d/%d", test_num, subtest_num);
  246. fprintf(env.stdout_saved, "#%-*s %s/%s",
  247. TEST_NUM_WIDTH, test_num_str,
  248. test_name, subtest_name);
  249. if (result)
  250. fprintf(env.stdout_saved, ":%s", result);
  251. fprintf(env.stdout_saved, "\n");
  252. }
  253. static void jsonw_write_log_message(json_writer_t *w, char *log_buf, size_t log_cnt)
  254. {
  255. /* open_memstream (from stdio_hijack_init) ensures that log_bug is terminated by a
  256. * null byte. Yet in parallel mode, log_buf will be NULL if there is no message.
  257. */
  258. if (log_cnt) {
  259. jsonw_string_field(w, "message", log_buf);
  260. } else {
  261. jsonw_string_field(w, "message", "");
  262. }
  263. }
  264. static void dump_test_log(const struct prog_test_def *test,
  265. const struct test_state *test_state,
  266. bool skip_ok_subtests,
  267. bool par_exec_result,
  268. json_writer_t *w)
  269. {
  270. bool test_failed = test_state->error_cnt > 0;
  271. bool force_log = test_state->force_log;
  272. bool print_test = verbose() || force_log || test_failed;
  273. int i;
  274. struct subtest_state *subtest_state;
  275. bool subtest_failed;
  276. bool subtest_filtered;
  277. bool print_subtest;
  278. /* we do not print anything in the worker thread */
  279. if (env.worker_id != -1)
  280. return;
  281. /* there is nothing to print when verbose log is used and execution
  282. * is not in parallel mode
  283. */
  284. if (verbose() && !par_exec_result)
  285. return;
  286. if (test_state->log_cnt && print_test)
  287. print_test_log(test_state->log_buf, test_state->log_cnt);
  288. if (w && print_test) {
  289. jsonw_start_object(w);
  290. jsonw_string_field(w, "name", test->test_name);
  291. jsonw_uint_field(w, "number", test->test_num);
  292. jsonw_write_log_message(w, test_state->log_buf, test_state->log_cnt);
  293. jsonw_bool_field(w, "failed", test_failed);
  294. jsonw_name(w, "subtests");
  295. jsonw_start_array(w);
  296. }
  297. for (i = 0; i < test_state->subtest_num; i++) {
  298. subtest_state = &test_state->subtest_states[i];
  299. subtest_failed = subtest_state->error_cnt;
  300. subtest_filtered = subtest_state->filtered;
  301. print_subtest = verbose() || force_log || subtest_failed;
  302. if ((skip_ok_subtests && !subtest_failed) || subtest_filtered)
  303. continue;
  304. if (subtest_state->log_cnt && print_subtest) {
  305. print_test_log(subtest_state->log_buf,
  306. subtest_state->log_cnt);
  307. }
  308. print_subtest_name(test->test_num, i + 1,
  309. test->test_name, subtest_state->name,
  310. test_result(subtest_state->error_cnt,
  311. subtest_state->skipped));
  312. if (w && print_subtest) {
  313. jsonw_start_object(w);
  314. jsonw_string_field(w, "name", subtest_state->name);
  315. jsonw_uint_field(w, "number", i+1);
  316. jsonw_write_log_message(w, subtest_state->log_buf, subtest_state->log_cnt);
  317. jsonw_bool_field(w, "failed", subtest_failed);
  318. jsonw_end_object(w);
  319. }
  320. }
  321. if (w && print_test) {
  322. jsonw_end_array(w);
  323. jsonw_end_object(w);
  324. }
  325. print_test_result(test, test_state);
  326. }
  327. static void stdio_restore(void);
  328. /* A bunch of tests set custom affinity per-thread and/or per-process. Reset
  329. * it after each test/sub-test.
  330. */
  331. static void reset_affinity(void)
  332. {
  333. cpu_set_t cpuset;
  334. int i, err;
  335. CPU_ZERO(&cpuset);
  336. for (i = 0; i < env.nr_cpus; i++)
  337. CPU_SET(i, &cpuset);
  338. err = sched_setaffinity(0, sizeof(cpuset), &cpuset);
  339. if (err < 0) {
  340. stdio_restore();
  341. fprintf(stderr, "Failed to reset process affinity: %d!\n", err);
  342. exit(EXIT_ERR_SETUP_INFRA);
  343. }
  344. err = pthread_setaffinity_np(pthread_self(), sizeof(cpuset), &cpuset);
  345. if (err < 0) {
  346. stdio_restore();
  347. fprintf(stderr, "Failed to reset thread affinity: %d!\n", err);
  348. exit(EXIT_ERR_SETUP_INFRA);
  349. }
  350. }
  351. static void save_netns(void)
  352. {
  353. env.saved_netns_fd = open("/proc/self/ns/net", O_RDONLY);
  354. if (env.saved_netns_fd == -1) {
  355. perror("open(/proc/self/ns/net)");
  356. exit(EXIT_ERR_SETUP_INFRA);
  357. }
  358. }
  359. static void restore_netns(void)
  360. {
  361. if (setns(env.saved_netns_fd, CLONE_NEWNET) == -1) {
  362. stdio_restore();
  363. perror("setns(CLONE_NEWNS)");
  364. exit(EXIT_ERR_SETUP_INFRA);
  365. }
  366. }
  367. void test__end_subtest(void)
  368. {
  369. struct prog_test_def *test = env.test;
  370. struct test_state *test_state = env.test_state;
  371. struct subtest_state *subtest_state = env.subtest_state;
  372. if (subtest_state->error_cnt) {
  373. test_state->error_cnt++;
  374. } else {
  375. if (!subtest_state->skipped)
  376. test_state->sub_succ_cnt++;
  377. else
  378. test_state->skip_cnt++;
  379. }
  380. if (verbose() && !env.workers)
  381. print_subtest_name(test->test_num, test_state->subtest_num,
  382. test->test_name, subtest_state->name,
  383. test_result(subtest_state->error_cnt,
  384. subtest_state->skipped));
  385. stdio_restore_cleanup();
  386. env.subtest_state = NULL;
  387. }
  388. bool test__start_subtest(const char *subtest_name)
  389. {
  390. struct prog_test_def *test = env.test;
  391. struct test_state *state = env.test_state;
  392. struct subtest_state *subtest_state;
  393. size_t sub_state_size = sizeof(*subtest_state);
  394. if (env.subtest_state)
  395. test__end_subtest();
  396. state->subtest_num++;
  397. state->subtest_states =
  398. realloc(state->subtest_states,
  399. state->subtest_num * sub_state_size);
  400. if (!state->subtest_states) {
  401. fprintf(stderr, "Not enough memory to allocate subtest result\n");
  402. return false;
  403. }
  404. subtest_state = &state->subtest_states[state->subtest_num - 1];
  405. memset(subtest_state, 0, sub_state_size);
  406. if (!subtest_name || !subtest_name[0]) {
  407. fprintf(env.stderr_saved,
  408. "Subtest #%d didn't provide sub-test name!\n",
  409. state->subtest_num);
  410. return false;
  411. }
  412. subtest_state->name = strdup(subtest_name);
  413. if (!subtest_state->name) {
  414. fprintf(env.stderr_saved,
  415. "Subtest #%d: failed to copy subtest name!\n",
  416. state->subtest_num);
  417. return false;
  418. }
  419. if (!should_run_subtest(&env.test_selector,
  420. &env.subtest_selector,
  421. state->subtest_num,
  422. test->test_name,
  423. subtest_name)) {
  424. subtest_state->filtered = true;
  425. return false;
  426. }
  427. subtest_state->should_tmon = match_subtest(&env.tmon_selector.whitelist,
  428. test->test_name,
  429. subtest_name);
  430. env.subtest_state = subtest_state;
  431. stdio_hijack_init(&subtest_state->log_buf, &subtest_state->log_cnt);
  432. return true;
  433. }
  434. void test__force_log(void)
  435. {
  436. env.test_state->force_log = true;
  437. }
  438. void test__skip(void)
  439. {
  440. if (env.subtest_state)
  441. env.subtest_state->skipped = true;
  442. else
  443. env.test_state->skip_cnt++;
  444. }
  445. void test__fail(void)
  446. {
  447. if (env.subtest_state)
  448. env.subtest_state->error_cnt++;
  449. else
  450. env.test_state->error_cnt++;
  451. }
  452. int test__join_cgroup(const char *path)
  453. {
  454. int fd;
  455. if (!env.test->need_cgroup_cleanup) {
  456. if (setup_cgroup_environment()) {
  457. fprintf(stderr,
  458. "#%d %s: Failed to setup cgroup environment\n",
  459. env.test->test_num, env.test->test_name);
  460. return -1;
  461. }
  462. env.test->need_cgroup_cleanup = true;
  463. }
  464. fd = create_and_get_cgroup(path);
  465. if (fd < 0) {
  466. fprintf(stderr,
  467. "#%d %s: Failed to create cgroup '%s' (errno=%d)\n",
  468. env.test->test_num, env.test->test_name, path, errno);
  469. return fd;
  470. }
  471. if (join_cgroup(path)) {
  472. fprintf(stderr,
  473. "#%d %s: Failed to join cgroup '%s' (errno=%d)\n",
  474. env.test->test_num, env.test->test_name, path, errno);
  475. return -1;
  476. }
  477. return fd;
  478. }
  479. int bpf_find_map(const char *test, struct bpf_object *obj, const char *name)
  480. {
  481. struct bpf_map *map;
  482. map = bpf_object__find_map_by_name(obj, name);
  483. if (!map) {
  484. fprintf(stdout, "%s:FAIL:map '%s' not found\n", test, name);
  485. test__fail();
  486. return -1;
  487. }
  488. return bpf_map__fd(map);
  489. }
  490. int compare_map_keys(int map1_fd, int map2_fd)
  491. {
  492. __u32 key, next_key;
  493. char val_buf[PERF_MAX_STACK_DEPTH *
  494. sizeof(struct bpf_stack_build_id)];
  495. int err;
  496. err = bpf_map_get_next_key(map1_fd, NULL, &key);
  497. if (err)
  498. return err;
  499. err = bpf_map_lookup_elem(map2_fd, &key, val_buf);
  500. if (err)
  501. return err;
  502. while (bpf_map_get_next_key(map1_fd, &key, &next_key) == 0) {
  503. err = bpf_map_lookup_elem(map2_fd, &next_key, val_buf);
  504. if (err)
  505. return err;
  506. key = next_key;
  507. }
  508. if (errno != ENOENT)
  509. return -1;
  510. return 0;
  511. }
  512. int compare_stack_ips(int smap_fd, int amap_fd, int stack_trace_len)
  513. {
  514. __u32 key, next_key, *cur_key_p, *next_key_p;
  515. char *val_buf1, *val_buf2;
  516. int i, err = 0;
  517. val_buf1 = malloc(stack_trace_len);
  518. val_buf2 = malloc(stack_trace_len);
  519. cur_key_p = NULL;
  520. next_key_p = &key;
  521. while (bpf_map_get_next_key(smap_fd, cur_key_p, next_key_p) == 0) {
  522. err = bpf_map_lookup_elem(smap_fd, next_key_p, val_buf1);
  523. if (err)
  524. goto out;
  525. err = bpf_map_lookup_elem(amap_fd, next_key_p, val_buf2);
  526. if (err)
  527. goto out;
  528. for (i = 0; i < stack_trace_len; i++) {
  529. if (val_buf1[i] != val_buf2[i]) {
  530. err = -1;
  531. goto out;
  532. }
  533. }
  534. key = *next_key_p;
  535. cur_key_p = &key;
  536. next_key_p = &next_key;
  537. }
  538. if (errno != ENOENT)
  539. err = -1;
  540. out:
  541. free(val_buf1);
  542. free(val_buf2);
  543. return err;
  544. }
  545. struct netns_obj {
  546. char *nsname;
  547. struct tmonitor_ctx *tmon;
  548. struct nstoken *nstoken;
  549. };
  550. /* Create a new network namespace with the given name.
  551. *
  552. * Create a new network namespace and set the network namespace of the
  553. * current process to the new network namespace if the argument "open" is
  554. * true. This function should be paired with netns_free() to release the
  555. * resource and delete the network namespace.
  556. *
  557. * It also implements the functionality of the option "-m" by starting
  558. * traffic monitor on the background to capture the packets in this network
  559. * namespace if the current test or subtest matching the pattern.
  560. *
  561. * nsname: the name of the network namespace to create.
  562. * open: open the network namespace if true.
  563. *
  564. * Return: the network namespace object on success, NULL on failure.
  565. */
  566. struct netns_obj *netns_new(const char *nsname, bool open)
  567. {
  568. struct netns_obj *netns_obj = malloc(sizeof(*netns_obj));
  569. const char *test_name, *subtest_name;
  570. int r;
  571. if (!netns_obj)
  572. return NULL;
  573. memset(netns_obj, 0, sizeof(*netns_obj));
  574. netns_obj->nsname = strdup(nsname);
  575. if (!netns_obj->nsname)
  576. goto fail;
  577. /* Create the network namespace */
  578. r = make_netns(nsname);
  579. if (r)
  580. goto fail;
  581. /* Start traffic monitor */
  582. if (env.test->should_tmon ||
  583. (env.subtest_state && env.subtest_state->should_tmon)) {
  584. test_name = env.test->test_name;
  585. subtest_name = env.subtest_state ? env.subtest_state->name : NULL;
  586. netns_obj->tmon = traffic_monitor_start(nsname, test_name, subtest_name);
  587. if (!netns_obj->tmon) {
  588. fprintf(stderr, "Failed to start traffic monitor for %s\n", nsname);
  589. goto fail;
  590. }
  591. } else {
  592. netns_obj->tmon = NULL;
  593. }
  594. if (open) {
  595. netns_obj->nstoken = open_netns(nsname);
  596. if (!netns_obj->nstoken)
  597. goto fail;
  598. }
  599. return netns_obj;
  600. fail:
  601. traffic_monitor_stop(netns_obj->tmon);
  602. remove_netns(nsname);
  603. free(netns_obj->nsname);
  604. free(netns_obj);
  605. return NULL;
  606. }
  607. /* Delete the network namespace.
  608. *
  609. * This function should be paired with netns_new() to delete the namespace
  610. * created by netns_new().
  611. */
  612. void netns_free(struct netns_obj *netns_obj)
  613. {
  614. if (!netns_obj)
  615. return;
  616. traffic_monitor_stop(netns_obj->tmon);
  617. close_netns(netns_obj->nstoken);
  618. remove_netns(netns_obj->nsname);
  619. free(netns_obj->nsname);
  620. free(netns_obj);
  621. }
  622. /* extern declarations for test funcs */
  623. #define DEFINE_TEST(name) \
  624. extern void test_##name(void) __weak; \
  625. extern void serial_test_##name(void) __weak;
  626. #include <prog_tests/tests.h>
  627. #undef DEFINE_TEST
  628. static struct prog_test_def prog_test_defs[] = {
  629. #define DEFINE_TEST(name) { \
  630. .test_name = #name, \
  631. .run_test = &test_##name, \
  632. .run_serial_test = &serial_test_##name, \
  633. },
  634. #include <prog_tests/tests.h>
  635. #undef DEFINE_TEST
  636. };
  637. static const int prog_test_cnt = ARRAY_SIZE(prog_test_defs);
  638. static struct test_state test_states[ARRAY_SIZE(prog_test_defs)];
  639. const char *argp_program_version = "test_progs 0.1";
  640. const char *argp_program_bug_address = "<bpf@vger.kernel.org>";
  641. static const char argp_program_doc[] =
  642. "BPF selftests test runner\v"
  643. "Options accepting the NAMES parameter take either a comma-separated list\n"
  644. "of test names, or a filename prefixed with @. The file contains one name\n"
  645. "(or wildcard pattern) per line, and comments beginning with # are ignored.\n"
  646. "\n"
  647. "These options can be passed repeatedly to read multiple files.\n";
  648. enum ARG_KEYS {
  649. ARG_TEST_NUM = 'n',
  650. ARG_TEST_NAME = 't',
  651. ARG_TEST_NAME_BLACKLIST = 'b',
  652. ARG_VERIFIER_STATS = 's',
  653. ARG_VERBOSE = 'v',
  654. ARG_GET_TEST_CNT = 'c',
  655. ARG_LIST_TEST_NAMES = 'l',
  656. ARG_TEST_NAME_GLOB_ALLOWLIST = 'a',
  657. ARG_TEST_NAME_GLOB_DENYLIST = 'd',
  658. ARG_NUM_WORKERS = 'j',
  659. ARG_DEBUG = -1,
  660. ARG_JSON_SUMMARY = 'J',
  661. ARG_TRAFFIC_MONITOR = 'm',
  662. };
  663. static const struct argp_option opts[] = {
  664. { "num", ARG_TEST_NUM, "NUM", 0,
  665. "Run test number NUM only " },
  666. { "name", ARG_TEST_NAME, "NAMES", 0,
  667. "Run tests with names containing any string from NAMES list" },
  668. { "name-blacklist", ARG_TEST_NAME_BLACKLIST, "NAMES", 0,
  669. "Don't run tests with names containing any string from NAMES list" },
  670. { "verifier-stats", ARG_VERIFIER_STATS, NULL, 0,
  671. "Output verifier statistics", },
  672. { "verbose", ARG_VERBOSE, "LEVEL", OPTION_ARG_OPTIONAL,
  673. "Verbose output (use -vv or -vvv for progressively verbose output)" },
  674. { "count", ARG_GET_TEST_CNT, NULL, 0,
  675. "Get number of selected top-level tests " },
  676. { "list", ARG_LIST_TEST_NAMES, NULL, 0,
  677. "List test names that would run (without running them) " },
  678. { "allow", ARG_TEST_NAME_GLOB_ALLOWLIST, "NAMES", 0,
  679. "Run tests with name matching the pattern (supports '*' wildcard)." },
  680. { "deny", ARG_TEST_NAME_GLOB_DENYLIST, "NAMES", 0,
  681. "Don't run tests with name matching the pattern (supports '*' wildcard)." },
  682. { "workers", ARG_NUM_WORKERS, "WORKERS", OPTION_ARG_OPTIONAL,
  683. "Number of workers to run in parallel, default to number of cpus." },
  684. { "debug", ARG_DEBUG, NULL, 0,
  685. "print extra debug information for test_progs." },
  686. { "json-summary", ARG_JSON_SUMMARY, "FILE", 0, "Write report in json format to this file."},
  687. #ifdef TRAFFIC_MONITOR
  688. { "traffic-monitor", ARG_TRAFFIC_MONITOR, "NAMES", 0,
  689. "Monitor network traffic of tests with name matching the pattern (supports '*' wildcard)." },
  690. #endif
  691. {},
  692. };
  693. static FILE *libbpf_capture_stream;
  694. static struct {
  695. char *buf;
  696. size_t buf_sz;
  697. } libbpf_output_capture;
  698. /* Creates a global memstream capturing INFO and WARN level output
  699. * passed to libbpf_print_fn.
  700. * Returns 0 on success, negative value on failure.
  701. * On failure the description is printed using PRINT_FAIL and
  702. * current test case is marked as fail.
  703. */
  704. int start_libbpf_log_capture(void)
  705. {
  706. if (libbpf_capture_stream) {
  707. PRINT_FAIL("%s: libbpf_capture_stream != NULL\n", __func__);
  708. return -EINVAL;
  709. }
  710. libbpf_capture_stream = open_memstream(&libbpf_output_capture.buf,
  711. &libbpf_output_capture.buf_sz);
  712. if (!libbpf_capture_stream) {
  713. PRINT_FAIL("%s: open_memstream failed errno=%d\n", __func__, errno);
  714. return -EINVAL;
  715. }
  716. return 0;
  717. }
  718. /* Destroys global memstream created by start_libbpf_log_capture().
  719. * Returns a pointer to captured data which has to be freed.
  720. * Returned buffer is null terminated.
  721. */
  722. char *stop_libbpf_log_capture(void)
  723. {
  724. char *buf;
  725. if (!libbpf_capture_stream)
  726. return NULL;
  727. fputc(0, libbpf_capture_stream);
  728. fclose(libbpf_capture_stream);
  729. libbpf_capture_stream = NULL;
  730. /* get 'buf' after fclose(), see open_memstream() documentation */
  731. buf = libbpf_output_capture.buf;
  732. memset(&libbpf_output_capture, 0, sizeof(libbpf_output_capture));
  733. return buf;
  734. }
  735. static int libbpf_print_fn(enum libbpf_print_level level,
  736. const char *format, va_list args)
  737. {
  738. if (libbpf_capture_stream && level != LIBBPF_DEBUG) {
  739. va_list args2;
  740. va_copy(args2, args);
  741. vfprintf(libbpf_capture_stream, format, args2);
  742. }
  743. if (env.verbosity < VERBOSE_VERY && level == LIBBPF_DEBUG)
  744. return 0;
  745. vfprintf(stdout, format, args);
  746. return 0;
  747. }
  748. static void free_test_filter_set(const struct test_filter_set *set)
  749. {
  750. int i, j;
  751. if (!set)
  752. return;
  753. for (i = 0; i < set->cnt; i++) {
  754. free((void *)set->tests[i].name);
  755. for (j = 0; j < set->tests[i].subtest_cnt; j++)
  756. free((void *)set->tests[i].subtests[j]);
  757. free((void *)set->tests[i].subtests);
  758. }
  759. free((void *)set->tests);
  760. }
  761. static void free_test_selector(struct test_selector *test_selector)
  762. {
  763. free_test_filter_set(&test_selector->blacklist);
  764. free_test_filter_set(&test_selector->whitelist);
  765. free(test_selector->num_set);
  766. }
  767. extern int extra_prog_load_log_flags;
  768. static error_t parse_arg(int key, char *arg, struct argp_state *state)
  769. {
  770. struct test_env *env = state->input;
  771. int err = 0;
  772. switch (key) {
  773. case ARG_TEST_NUM: {
  774. char *subtest_str = strchr(arg, '/');
  775. if (subtest_str) {
  776. *subtest_str = '\0';
  777. if (parse_num_list(subtest_str + 1,
  778. &env->subtest_selector.num_set,
  779. &env->subtest_selector.num_set_len)) {
  780. fprintf(stderr,
  781. "Failed to parse subtest numbers.\n");
  782. return -EINVAL;
  783. }
  784. }
  785. if (parse_num_list(arg, &env->test_selector.num_set,
  786. &env->test_selector.num_set_len)) {
  787. fprintf(stderr, "Failed to parse test numbers.\n");
  788. return -EINVAL;
  789. }
  790. break;
  791. }
  792. case ARG_TEST_NAME_GLOB_ALLOWLIST:
  793. case ARG_TEST_NAME: {
  794. if (arg[0] == '@')
  795. err = parse_test_list_file(arg + 1,
  796. &env->test_selector.whitelist,
  797. key == ARG_TEST_NAME_GLOB_ALLOWLIST);
  798. else
  799. err = parse_test_list(arg,
  800. &env->test_selector.whitelist,
  801. key == ARG_TEST_NAME_GLOB_ALLOWLIST);
  802. break;
  803. }
  804. case ARG_TEST_NAME_GLOB_DENYLIST:
  805. case ARG_TEST_NAME_BLACKLIST: {
  806. if (arg[0] == '@')
  807. err = parse_test_list_file(arg + 1,
  808. &env->test_selector.blacklist,
  809. key == ARG_TEST_NAME_GLOB_DENYLIST);
  810. else
  811. err = parse_test_list(arg,
  812. &env->test_selector.blacklist,
  813. key == ARG_TEST_NAME_GLOB_DENYLIST);
  814. break;
  815. }
  816. case ARG_VERIFIER_STATS:
  817. env->verifier_stats = true;
  818. break;
  819. case ARG_VERBOSE:
  820. env->verbosity = VERBOSE_NORMAL;
  821. if (arg) {
  822. if (strcmp(arg, "v") == 0) {
  823. env->verbosity = VERBOSE_VERY;
  824. extra_prog_load_log_flags = 1;
  825. } else if (strcmp(arg, "vv") == 0) {
  826. env->verbosity = VERBOSE_SUPER;
  827. extra_prog_load_log_flags = 2;
  828. } else {
  829. fprintf(stderr,
  830. "Unrecognized verbosity setting ('%s'), only -v and -vv are supported\n",
  831. arg);
  832. return -EINVAL;
  833. }
  834. }
  835. env_verbosity = env->verbosity;
  836. if (verbose()) {
  837. if (setenv("SELFTESTS_VERBOSE", "1", 1) == -1) {
  838. fprintf(stderr,
  839. "Unable to setenv SELFTESTS_VERBOSE=1 (errno=%d)",
  840. errno);
  841. return -EINVAL;
  842. }
  843. }
  844. break;
  845. case ARG_GET_TEST_CNT:
  846. env->get_test_cnt = true;
  847. break;
  848. case ARG_LIST_TEST_NAMES:
  849. env->list_test_names = true;
  850. break;
  851. case ARG_NUM_WORKERS:
  852. if (arg) {
  853. env->workers = atoi(arg);
  854. if (!env->workers) {
  855. fprintf(stderr, "Invalid number of worker: %s.", arg);
  856. return -EINVAL;
  857. }
  858. } else {
  859. env->workers = get_nprocs();
  860. }
  861. break;
  862. case ARG_DEBUG:
  863. env->debug = true;
  864. break;
  865. case ARG_JSON_SUMMARY:
  866. env->json = fopen(arg, "w");
  867. if (env->json == NULL) {
  868. perror("Failed to open json summary file");
  869. return -errno;
  870. }
  871. break;
  872. case ARGP_KEY_ARG:
  873. argp_usage(state);
  874. break;
  875. case ARGP_KEY_END:
  876. break;
  877. #ifdef TRAFFIC_MONITOR
  878. case ARG_TRAFFIC_MONITOR:
  879. if (arg[0] == '@')
  880. err = parse_test_list_file(arg + 1,
  881. &env->tmon_selector.whitelist,
  882. true);
  883. else
  884. err = parse_test_list(arg,
  885. &env->tmon_selector.whitelist,
  886. true);
  887. break;
  888. #endif
  889. default:
  890. return ARGP_ERR_UNKNOWN;
  891. }
  892. return err;
  893. }
  894. /*
  895. * Determine if test_progs is running as a "flavored" test runner and switch
  896. * into corresponding sub-directory to load correct BPF objects.
  897. *
  898. * This is done by looking at executable name. If it contains "-flavor"
  899. * suffix, then we are running as a flavored test runner.
  900. */
  901. int cd_flavor_subdir(const char *exec_name)
  902. {
  903. /* General form of argv[0] passed here is:
  904. * some/path/to/test_progs[-flavor], where -flavor part is optional.
  905. * First cut out "test_progs[-flavor]" part, then extract "flavor"
  906. * part, if it's there.
  907. */
  908. const char *flavor = strrchr(exec_name, '/');
  909. if (!flavor)
  910. flavor = exec_name;
  911. else
  912. flavor++;
  913. flavor = strrchr(flavor, '-');
  914. if (!flavor)
  915. return 0;
  916. flavor++;
  917. if (verbose())
  918. fprintf(stdout, "Switching to flavor '%s' subdirectory...\n", flavor);
  919. return chdir(flavor);
  920. }
  921. int trigger_module_test_read(int read_sz)
  922. {
  923. int fd, err;
  924. fd = open(BPF_TESTMOD_TEST_FILE, O_RDONLY);
  925. err = -errno;
  926. if (!ASSERT_GE(fd, 0, "testmod_file_open"))
  927. return err;
  928. read(fd, NULL, read_sz);
  929. close(fd);
  930. return 0;
  931. }
  932. int trigger_module_test_write(int write_sz)
  933. {
  934. int fd, err;
  935. char *buf = malloc(write_sz);
  936. if (!buf)
  937. return -ENOMEM;
  938. memset(buf, 'a', write_sz);
  939. buf[write_sz-1] = '\0';
  940. fd = open(BPF_TESTMOD_TEST_FILE, O_WRONLY);
  941. err = -errno;
  942. if (!ASSERT_GE(fd, 0, "testmod_file_open")) {
  943. free(buf);
  944. return err;
  945. }
  946. write(fd, buf, write_sz);
  947. close(fd);
  948. free(buf);
  949. return 0;
  950. }
  951. int write_sysctl(const char *sysctl, const char *value)
  952. {
  953. int fd, err, len;
  954. fd = open(sysctl, O_WRONLY);
  955. if (!ASSERT_NEQ(fd, -1, "open sysctl"))
  956. return -1;
  957. len = strlen(value);
  958. err = write(fd, value, len);
  959. close(fd);
  960. if (!ASSERT_EQ(err, len, "write sysctl"))
  961. return -1;
  962. return 0;
  963. }
  964. int get_bpf_max_tramp_links_from(struct btf *btf)
  965. {
  966. const struct btf_enum *e;
  967. const struct btf_type *t;
  968. __u32 i, type_cnt;
  969. const char *name;
  970. __u16 j, vlen;
  971. for (i = 1, type_cnt = btf__type_cnt(btf); i < type_cnt; i++) {
  972. t = btf__type_by_id(btf, i);
  973. if (!t || !btf_is_enum(t) || t->name_off)
  974. continue;
  975. e = btf_enum(t);
  976. for (j = 0, vlen = btf_vlen(t); j < vlen; j++, e++) {
  977. name = btf__str_by_offset(btf, e->name_off);
  978. if (name && !strcmp(name, "BPF_MAX_TRAMP_LINKS"))
  979. return e->val;
  980. }
  981. }
  982. return -1;
  983. }
  984. int get_bpf_max_tramp_links(void)
  985. {
  986. struct btf *vmlinux_btf;
  987. int ret;
  988. vmlinux_btf = btf__load_vmlinux_btf();
  989. if (!ASSERT_OK_PTR(vmlinux_btf, "vmlinux btf"))
  990. return -1;
  991. ret = get_bpf_max_tramp_links_from(vmlinux_btf);
  992. btf__free(vmlinux_btf);
  993. return ret;
  994. }
  995. #define MAX_BACKTRACE_SZ 128
  996. void crash_handler(int signum)
  997. {
  998. void *bt[MAX_BACKTRACE_SZ];
  999. size_t sz;
  1000. sz = backtrace(bt, ARRAY_SIZE(bt));
  1001. if (env.stdout_saved)
  1002. stdio_restore();
  1003. if (env.test) {
  1004. env.test_state->error_cnt++;
  1005. dump_test_log(env.test, env.test_state, true, false, NULL);
  1006. }
  1007. if (env.worker_id != -1)
  1008. fprintf(stderr, "[%d]: ", env.worker_id);
  1009. fprintf(stderr, "Caught signal #%d!\nStack trace:\n", signum);
  1010. backtrace_symbols_fd(bt, sz, STDERR_FILENO);
  1011. }
  1012. static void sigint_handler(int signum)
  1013. {
  1014. int i;
  1015. for (i = 0; i < env.workers; i++)
  1016. if (env.worker_socks[i] > 0)
  1017. close(env.worker_socks[i]);
  1018. }
  1019. static int current_test_idx;
  1020. static pthread_mutex_t current_test_lock;
  1021. static pthread_mutex_t stdout_output_lock;
  1022. static inline const char *str_msg(const struct msg *msg, char *buf)
  1023. {
  1024. switch (msg->type) {
  1025. case MSG_DO_TEST:
  1026. sprintf(buf, "MSG_DO_TEST %d", msg->do_test.num);
  1027. break;
  1028. case MSG_TEST_DONE:
  1029. sprintf(buf, "MSG_TEST_DONE %d (log: %d)",
  1030. msg->test_done.num,
  1031. msg->test_done.have_log);
  1032. break;
  1033. case MSG_SUBTEST_DONE:
  1034. sprintf(buf, "MSG_SUBTEST_DONE %d (log: %d)",
  1035. msg->subtest_done.num,
  1036. msg->subtest_done.have_log);
  1037. break;
  1038. case MSG_TEST_LOG:
  1039. sprintf(buf, "MSG_TEST_LOG (cnt: %zu, last: %d)",
  1040. strlen(msg->test_log.log_buf),
  1041. msg->test_log.is_last);
  1042. break;
  1043. case MSG_EXIT:
  1044. sprintf(buf, "MSG_EXIT");
  1045. break;
  1046. default:
  1047. sprintf(buf, "UNKNOWN");
  1048. break;
  1049. }
  1050. return buf;
  1051. }
  1052. static int send_message(int sock, const struct msg *msg)
  1053. {
  1054. char buf[256];
  1055. if (env.debug)
  1056. fprintf(stderr, "Sending msg: %s\n", str_msg(msg, buf));
  1057. return send(sock, msg, sizeof(*msg), 0);
  1058. }
  1059. static int recv_message(int sock, struct msg *msg)
  1060. {
  1061. int ret;
  1062. char buf[256];
  1063. memset(msg, 0, sizeof(*msg));
  1064. ret = recv(sock, msg, sizeof(*msg), 0);
  1065. if (ret >= 0) {
  1066. if (env.debug)
  1067. fprintf(stderr, "Received msg: %s\n", str_msg(msg, buf));
  1068. }
  1069. return ret;
  1070. }
  1071. static void run_one_test(int test_num)
  1072. {
  1073. struct prog_test_def *test = &prog_test_defs[test_num];
  1074. struct test_state *state = &test_states[test_num];
  1075. env.test = test;
  1076. env.test_state = state;
  1077. stdio_hijack(&state->log_buf, &state->log_cnt);
  1078. if (test->run_test)
  1079. test->run_test();
  1080. else if (test->run_serial_test)
  1081. test->run_serial_test();
  1082. /* ensure last sub-test is finalized properly */
  1083. if (env.subtest_state)
  1084. test__end_subtest();
  1085. state->tested = true;
  1086. if (verbose() && env.worker_id == -1)
  1087. print_test_result(test, state);
  1088. reset_affinity();
  1089. restore_netns();
  1090. if (test->need_cgroup_cleanup)
  1091. cleanup_cgroup_environment();
  1092. stdio_restore();
  1093. free(stop_libbpf_log_capture());
  1094. dump_test_log(test, state, false, false, NULL);
  1095. }
  1096. struct dispatch_data {
  1097. int worker_id;
  1098. int sock_fd;
  1099. };
  1100. static int read_prog_test_msg(int sock_fd, struct msg *msg, enum msg_type type)
  1101. {
  1102. if (recv_message(sock_fd, msg) < 0)
  1103. return 1;
  1104. if (msg->type != type) {
  1105. printf("%s: unexpected message type %d. expected %d\n", __func__, msg->type, type);
  1106. return 1;
  1107. }
  1108. return 0;
  1109. }
  1110. static int dispatch_thread_read_log(int sock_fd, char **log_buf, size_t *log_cnt)
  1111. {
  1112. FILE *log_fp = NULL;
  1113. int result = 0;
  1114. log_fp = open_memstream(log_buf, log_cnt);
  1115. if (!log_fp)
  1116. return 1;
  1117. while (true) {
  1118. struct msg msg;
  1119. if (read_prog_test_msg(sock_fd, &msg, MSG_TEST_LOG)) {
  1120. result = 1;
  1121. goto out;
  1122. }
  1123. fprintf(log_fp, "%s", msg.test_log.log_buf);
  1124. if (msg.test_log.is_last)
  1125. break;
  1126. }
  1127. out:
  1128. fclose(log_fp);
  1129. log_fp = NULL;
  1130. return result;
  1131. }
  1132. static int dispatch_thread_send_subtests(int sock_fd, struct test_state *state)
  1133. {
  1134. struct msg msg;
  1135. struct subtest_state *subtest_state;
  1136. int subtest_num = state->subtest_num;
  1137. state->subtest_states = malloc(subtest_num * sizeof(*subtest_state));
  1138. for (int i = 0; i < subtest_num; i++) {
  1139. subtest_state = &state->subtest_states[i];
  1140. memset(subtest_state, 0, sizeof(*subtest_state));
  1141. if (read_prog_test_msg(sock_fd, &msg, MSG_SUBTEST_DONE))
  1142. return 1;
  1143. subtest_state->name = strdup(msg.subtest_done.name);
  1144. subtest_state->error_cnt = msg.subtest_done.error_cnt;
  1145. subtest_state->skipped = msg.subtest_done.skipped;
  1146. subtest_state->filtered = msg.subtest_done.filtered;
  1147. /* collect all logs */
  1148. if (msg.subtest_done.have_log)
  1149. if (dispatch_thread_read_log(sock_fd,
  1150. &subtest_state->log_buf,
  1151. &subtest_state->log_cnt))
  1152. return 1;
  1153. }
  1154. return 0;
  1155. }
  1156. static void *dispatch_thread(void *ctx)
  1157. {
  1158. struct dispatch_data *data = ctx;
  1159. int sock_fd;
  1160. sock_fd = data->sock_fd;
  1161. while (true) {
  1162. int test_to_run = -1;
  1163. struct prog_test_def *test;
  1164. struct test_state *state;
  1165. /* grab a test */
  1166. {
  1167. pthread_mutex_lock(&current_test_lock);
  1168. if (current_test_idx >= prog_test_cnt) {
  1169. pthread_mutex_unlock(&current_test_lock);
  1170. goto done;
  1171. }
  1172. test = &prog_test_defs[current_test_idx];
  1173. test_to_run = current_test_idx;
  1174. current_test_idx++;
  1175. pthread_mutex_unlock(&current_test_lock);
  1176. }
  1177. if (!test->should_run || test->run_serial_test)
  1178. continue;
  1179. /* run test through worker */
  1180. {
  1181. struct msg msg_do_test;
  1182. memset(&msg_do_test, 0, sizeof(msg_do_test));
  1183. msg_do_test.type = MSG_DO_TEST;
  1184. msg_do_test.do_test.num = test_to_run;
  1185. if (send_message(sock_fd, &msg_do_test) < 0) {
  1186. perror("Fail to send command");
  1187. goto done;
  1188. }
  1189. env.worker_current_test[data->worker_id] = test_to_run;
  1190. }
  1191. /* wait for test done */
  1192. do {
  1193. struct msg msg;
  1194. if (read_prog_test_msg(sock_fd, &msg, MSG_TEST_DONE))
  1195. goto error;
  1196. if (test_to_run != msg.test_done.num)
  1197. goto error;
  1198. state = &test_states[test_to_run];
  1199. state->tested = true;
  1200. state->error_cnt = msg.test_done.error_cnt;
  1201. state->skip_cnt = msg.test_done.skip_cnt;
  1202. state->sub_succ_cnt = msg.test_done.sub_succ_cnt;
  1203. state->subtest_num = msg.test_done.subtest_num;
  1204. /* collect all logs */
  1205. if (msg.test_done.have_log) {
  1206. if (dispatch_thread_read_log(sock_fd,
  1207. &state->log_buf,
  1208. &state->log_cnt))
  1209. goto error;
  1210. }
  1211. /* collect all subtests and subtest logs */
  1212. if (!state->subtest_num)
  1213. break;
  1214. if (dispatch_thread_send_subtests(sock_fd, state))
  1215. goto error;
  1216. } while (false);
  1217. pthread_mutex_lock(&stdout_output_lock);
  1218. dump_test_log(test, state, false, true, NULL);
  1219. pthread_mutex_unlock(&stdout_output_lock);
  1220. } /* while (true) */
  1221. error:
  1222. if (env.debug)
  1223. fprintf(stderr, "[%d]: Protocol/IO error: %s.\n", data->worker_id, strerror(errno));
  1224. done:
  1225. {
  1226. struct msg msg_exit;
  1227. msg_exit.type = MSG_EXIT;
  1228. if (send_message(sock_fd, &msg_exit) < 0) {
  1229. if (env.debug)
  1230. fprintf(stderr, "[%d]: send_message msg_exit: %s.\n",
  1231. data->worker_id, strerror(errno));
  1232. }
  1233. }
  1234. return NULL;
  1235. }
  1236. static void calculate_summary_and_print_errors(struct test_env *env)
  1237. {
  1238. int i;
  1239. int succ_cnt = 0, fail_cnt = 0, sub_succ_cnt = 0, skip_cnt = 0;
  1240. json_writer_t *w = NULL;
  1241. for (i = 0; i < prog_test_cnt; i++) {
  1242. struct test_state *state = &test_states[i];
  1243. if (!state->tested)
  1244. continue;
  1245. sub_succ_cnt += state->sub_succ_cnt;
  1246. skip_cnt += state->skip_cnt;
  1247. if (state->error_cnt)
  1248. fail_cnt++;
  1249. else
  1250. succ_cnt++;
  1251. }
  1252. if (env->json) {
  1253. w = jsonw_new(env->json);
  1254. if (!w)
  1255. fprintf(env->stderr_saved, "Failed to create new JSON stream.");
  1256. }
  1257. if (w) {
  1258. jsonw_start_object(w);
  1259. jsonw_uint_field(w, "success", succ_cnt);
  1260. jsonw_uint_field(w, "success_subtest", sub_succ_cnt);
  1261. jsonw_uint_field(w, "skipped", skip_cnt);
  1262. jsonw_uint_field(w, "failed", fail_cnt);
  1263. jsonw_name(w, "results");
  1264. jsonw_start_array(w);
  1265. }
  1266. /*
  1267. * We only print error logs summary when there are failed tests and
  1268. * verbose mode is not enabled. Otherwise, results may be inconsistent.
  1269. *
  1270. */
  1271. if (!verbose() && fail_cnt) {
  1272. printf("\nAll error logs:\n");
  1273. /* print error logs again */
  1274. for (i = 0; i < prog_test_cnt; i++) {
  1275. struct prog_test_def *test = &prog_test_defs[i];
  1276. struct test_state *state = &test_states[i];
  1277. if (!state->tested || !state->error_cnt)
  1278. continue;
  1279. dump_test_log(test, state, true, true, w);
  1280. }
  1281. }
  1282. if (w) {
  1283. jsonw_end_array(w);
  1284. jsonw_end_object(w);
  1285. jsonw_destroy(&w);
  1286. }
  1287. if (env->json)
  1288. fclose(env->json);
  1289. printf("Summary: %d/%d PASSED, %d SKIPPED, %d FAILED\n",
  1290. succ_cnt, sub_succ_cnt, skip_cnt, fail_cnt);
  1291. env->succ_cnt = succ_cnt;
  1292. env->sub_succ_cnt = sub_succ_cnt;
  1293. env->fail_cnt = fail_cnt;
  1294. env->skip_cnt = skip_cnt;
  1295. }
  1296. static void server_main(void)
  1297. {
  1298. pthread_t *dispatcher_threads;
  1299. struct dispatch_data *data;
  1300. struct sigaction sigact_int = {
  1301. .sa_handler = sigint_handler,
  1302. .sa_flags = SA_RESETHAND,
  1303. };
  1304. int i;
  1305. sigaction(SIGINT, &sigact_int, NULL);
  1306. dispatcher_threads = calloc(sizeof(pthread_t), env.workers);
  1307. data = calloc(sizeof(struct dispatch_data), env.workers);
  1308. env.worker_current_test = calloc(sizeof(int), env.workers);
  1309. for (i = 0; i < env.workers; i++) {
  1310. int rc;
  1311. data[i].worker_id = i;
  1312. data[i].sock_fd = env.worker_socks[i];
  1313. rc = pthread_create(&dispatcher_threads[i], NULL, dispatch_thread, &data[i]);
  1314. if (rc < 0) {
  1315. perror("Failed to launch dispatcher thread");
  1316. exit(EXIT_ERR_SETUP_INFRA);
  1317. }
  1318. }
  1319. /* wait for all dispatcher to finish */
  1320. for (i = 0; i < env.workers; i++) {
  1321. while (true) {
  1322. int ret = pthread_tryjoin_np(dispatcher_threads[i], NULL);
  1323. if (!ret) {
  1324. break;
  1325. } else if (ret == EBUSY) {
  1326. if (env.debug)
  1327. fprintf(stderr, "Still waiting for thread %d (test %d).\n",
  1328. i, env.worker_current_test[i] + 1);
  1329. usleep(1000 * 1000);
  1330. continue;
  1331. } else {
  1332. fprintf(stderr, "Unexpected error joining dispatcher thread: %d", ret);
  1333. break;
  1334. }
  1335. }
  1336. }
  1337. free(dispatcher_threads);
  1338. free(env.worker_current_test);
  1339. free(data);
  1340. /* run serial tests */
  1341. save_netns();
  1342. for (int i = 0; i < prog_test_cnt; i++) {
  1343. struct prog_test_def *test = &prog_test_defs[i];
  1344. if (!test->should_run || !test->run_serial_test)
  1345. continue;
  1346. run_one_test(i);
  1347. }
  1348. /* generate summary */
  1349. fflush(stderr);
  1350. fflush(stdout);
  1351. calculate_summary_and_print_errors(&env);
  1352. /* reap all workers */
  1353. for (i = 0; i < env.workers; i++) {
  1354. int wstatus, pid;
  1355. pid = waitpid(env.worker_pids[i], &wstatus, 0);
  1356. if (pid != env.worker_pids[i])
  1357. perror("Unable to reap worker");
  1358. }
  1359. }
  1360. static void worker_main_send_log(int sock, char *log_buf, size_t log_cnt)
  1361. {
  1362. char *src;
  1363. size_t slen;
  1364. src = log_buf;
  1365. slen = log_cnt;
  1366. while (slen) {
  1367. struct msg msg_log;
  1368. char *dest;
  1369. size_t len;
  1370. memset(&msg_log, 0, sizeof(msg_log));
  1371. msg_log.type = MSG_TEST_LOG;
  1372. dest = msg_log.test_log.log_buf;
  1373. len = slen >= MAX_LOG_TRUNK_SIZE ? MAX_LOG_TRUNK_SIZE : slen;
  1374. memcpy(dest, src, len);
  1375. src += len;
  1376. slen -= len;
  1377. if (!slen)
  1378. msg_log.test_log.is_last = true;
  1379. assert(send_message(sock, &msg_log) >= 0);
  1380. }
  1381. }
  1382. static void free_subtest_state(struct subtest_state *state)
  1383. {
  1384. if (state->log_buf) {
  1385. free(state->log_buf);
  1386. state->log_buf = NULL;
  1387. state->log_cnt = 0;
  1388. }
  1389. free(state->name);
  1390. state->name = NULL;
  1391. }
  1392. static int worker_main_send_subtests(int sock, struct test_state *state)
  1393. {
  1394. int i, result = 0;
  1395. struct msg msg;
  1396. struct subtest_state *subtest_state;
  1397. memset(&msg, 0, sizeof(msg));
  1398. msg.type = MSG_SUBTEST_DONE;
  1399. for (i = 0; i < state->subtest_num; i++) {
  1400. subtest_state = &state->subtest_states[i];
  1401. msg.subtest_done.num = i;
  1402. strncpy(msg.subtest_done.name, subtest_state->name, MAX_SUBTEST_NAME);
  1403. msg.subtest_done.error_cnt = subtest_state->error_cnt;
  1404. msg.subtest_done.skipped = subtest_state->skipped;
  1405. msg.subtest_done.filtered = subtest_state->filtered;
  1406. msg.subtest_done.have_log = false;
  1407. if (verbose() || state->force_log || subtest_state->error_cnt) {
  1408. if (subtest_state->log_cnt)
  1409. msg.subtest_done.have_log = true;
  1410. }
  1411. if (send_message(sock, &msg) < 0) {
  1412. perror("Fail to send message done");
  1413. result = 1;
  1414. goto out;
  1415. }
  1416. /* send logs */
  1417. if (msg.subtest_done.have_log)
  1418. worker_main_send_log(sock, subtest_state->log_buf, subtest_state->log_cnt);
  1419. free_subtest_state(subtest_state);
  1420. free(subtest_state->name);
  1421. }
  1422. out:
  1423. for (; i < state->subtest_num; i++)
  1424. free_subtest_state(&state->subtest_states[i]);
  1425. free(state->subtest_states);
  1426. return result;
  1427. }
  1428. static int worker_main(int sock)
  1429. {
  1430. save_netns();
  1431. while (true) {
  1432. /* receive command */
  1433. struct msg msg;
  1434. if (recv_message(sock, &msg) < 0)
  1435. goto out;
  1436. switch (msg.type) {
  1437. case MSG_EXIT:
  1438. if (env.debug)
  1439. fprintf(stderr, "[%d]: worker exit.\n",
  1440. env.worker_id);
  1441. goto out;
  1442. case MSG_DO_TEST: {
  1443. int test_to_run = msg.do_test.num;
  1444. struct prog_test_def *test = &prog_test_defs[test_to_run];
  1445. struct test_state *state = &test_states[test_to_run];
  1446. struct msg msg;
  1447. if (env.debug)
  1448. fprintf(stderr, "[%d]: #%d:%s running.\n",
  1449. env.worker_id,
  1450. test_to_run + 1,
  1451. test->test_name);
  1452. run_one_test(test_to_run);
  1453. memset(&msg, 0, sizeof(msg));
  1454. msg.type = MSG_TEST_DONE;
  1455. msg.test_done.num = test_to_run;
  1456. msg.test_done.error_cnt = state->error_cnt;
  1457. msg.test_done.skip_cnt = state->skip_cnt;
  1458. msg.test_done.sub_succ_cnt = state->sub_succ_cnt;
  1459. msg.test_done.subtest_num = state->subtest_num;
  1460. msg.test_done.have_log = false;
  1461. if (verbose() || state->force_log || state->error_cnt) {
  1462. if (state->log_cnt)
  1463. msg.test_done.have_log = true;
  1464. }
  1465. if (send_message(sock, &msg) < 0) {
  1466. perror("Fail to send message done");
  1467. goto out;
  1468. }
  1469. /* send logs */
  1470. if (msg.test_done.have_log)
  1471. worker_main_send_log(sock, state->log_buf, state->log_cnt);
  1472. if (state->log_buf) {
  1473. free(state->log_buf);
  1474. state->log_buf = NULL;
  1475. state->log_cnt = 0;
  1476. }
  1477. if (state->subtest_num)
  1478. if (worker_main_send_subtests(sock, state))
  1479. goto out;
  1480. if (env.debug)
  1481. fprintf(stderr, "[%d]: #%d:%s done.\n",
  1482. env.worker_id,
  1483. test_to_run + 1,
  1484. test->test_name);
  1485. break;
  1486. } /* case MSG_DO_TEST */
  1487. default:
  1488. if (env.debug)
  1489. fprintf(stderr, "[%d]: unknown message.\n", env.worker_id);
  1490. return -1;
  1491. }
  1492. }
  1493. out:
  1494. return 0;
  1495. }
  1496. static void free_test_states(void)
  1497. {
  1498. int i, j;
  1499. for (i = 0; i < ARRAY_SIZE(prog_test_defs); i++) {
  1500. struct test_state *test_state = &test_states[i];
  1501. for (j = 0; j < test_state->subtest_num; j++)
  1502. free_subtest_state(&test_state->subtest_states[j]);
  1503. free(test_state->subtest_states);
  1504. free(test_state->log_buf);
  1505. test_state->subtest_states = NULL;
  1506. test_state->log_buf = NULL;
  1507. }
  1508. }
  1509. int main(int argc, char **argv)
  1510. {
  1511. static const struct argp argp = {
  1512. .options = opts,
  1513. .parser = parse_arg,
  1514. .doc = argp_program_doc,
  1515. };
  1516. struct sigaction sigact = {
  1517. .sa_handler = crash_handler,
  1518. .sa_flags = SA_RESETHAND,
  1519. };
  1520. int err, i;
  1521. sigaction(SIGSEGV, &sigact, NULL);
  1522. err = argp_parse(&argp, argc, argv, 0, NULL, &env);
  1523. if (err)
  1524. return err;
  1525. err = cd_flavor_subdir(argv[0]);
  1526. if (err)
  1527. return err;
  1528. /* Use libbpf 1.0 API mode */
  1529. libbpf_set_strict_mode(LIBBPF_STRICT_ALL);
  1530. libbpf_set_print(libbpf_print_fn);
  1531. srand(time(NULL));
  1532. env.jit_enabled = is_jit_enabled();
  1533. env.nr_cpus = libbpf_num_possible_cpus();
  1534. if (env.nr_cpus < 0) {
  1535. fprintf(stderr, "Failed to get number of CPUs: %d!\n",
  1536. env.nr_cpus);
  1537. return -1;
  1538. }
  1539. env.stdout_saved = stdout;
  1540. env.stderr_saved = stderr;
  1541. env.has_testmod = true;
  1542. if (!env.list_test_names) {
  1543. /* ensure previous instance of the module is unloaded */
  1544. unload_bpf_testmod(verbose());
  1545. if (load_bpf_testmod(verbose())) {
  1546. fprintf(env.stderr_saved, "WARNING! Selftests relying on bpf_testmod.ko will be skipped.\n");
  1547. env.has_testmod = false;
  1548. }
  1549. }
  1550. /* initializing tests */
  1551. for (i = 0; i < prog_test_cnt; i++) {
  1552. struct prog_test_def *test = &prog_test_defs[i];
  1553. test->test_num = i + 1;
  1554. test->should_run = should_run(&env.test_selector,
  1555. test->test_num, test->test_name);
  1556. if ((test->run_test == NULL && test->run_serial_test == NULL) ||
  1557. (test->run_test != NULL && test->run_serial_test != NULL)) {
  1558. fprintf(stderr, "Test %d:%s must have either test_%s() or serial_test_%sl() defined.\n",
  1559. test->test_num, test->test_name, test->test_name, test->test_name);
  1560. exit(EXIT_ERR_SETUP_INFRA);
  1561. }
  1562. if (test->should_run)
  1563. test->should_tmon = should_tmon(&env.tmon_selector, test->test_name);
  1564. }
  1565. /* ignore workers if we are just listing */
  1566. if (env.get_test_cnt || env.list_test_names)
  1567. env.workers = 0;
  1568. /* launch workers if requested */
  1569. env.worker_id = -1; /* main process */
  1570. if (env.workers) {
  1571. env.worker_pids = calloc(sizeof(pid_t), env.workers);
  1572. env.worker_socks = calloc(sizeof(int), env.workers);
  1573. if (env.debug)
  1574. fprintf(stdout, "Launching %d workers.\n", env.workers);
  1575. for (i = 0; i < env.workers; i++) {
  1576. int sv[2];
  1577. pid_t pid;
  1578. if (socketpair(AF_UNIX, SOCK_SEQPACKET | SOCK_CLOEXEC, 0, sv) < 0) {
  1579. perror("Fail to create worker socket");
  1580. return -1;
  1581. }
  1582. pid = fork();
  1583. if (pid < 0) {
  1584. perror("Failed to fork worker");
  1585. return -1;
  1586. } else if (pid != 0) { /* main process */
  1587. close(sv[1]);
  1588. env.worker_pids[i] = pid;
  1589. env.worker_socks[i] = sv[0];
  1590. } else { /* inside each worker process */
  1591. close(sv[0]);
  1592. env.worker_id = i;
  1593. return worker_main(sv[1]);
  1594. }
  1595. }
  1596. if (env.worker_id == -1) {
  1597. server_main();
  1598. goto out;
  1599. }
  1600. }
  1601. /* The rest of the main process */
  1602. /* on single mode */
  1603. save_netns();
  1604. for (i = 0; i < prog_test_cnt; i++) {
  1605. struct prog_test_def *test = &prog_test_defs[i];
  1606. if (!test->should_run)
  1607. continue;
  1608. if (env.get_test_cnt) {
  1609. env.succ_cnt++;
  1610. continue;
  1611. }
  1612. if (env.list_test_names) {
  1613. fprintf(env.stdout_saved, "%s\n", test->test_name);
  1614. env.succ_cnt++;
  1615. continue;
  1616. }
  1617. run_one_test(i);
  1618. }
  1619. if (env.get_test_cnt) {
  1620. printf("%d\n", env.succ_cnt);
  1621. goto out;
  1622. }
  1623. if (env.list_test_names)
  1624. goto out;
  1625. calculate_summary_and_print_errors(&env);
  1626. close(env.saved_netns_fd);
  1627. out:
  1628. if (!env.list_test_names && env.has_testmod)
  1629. unload_bpf_testmod(verbose());
  1630. free_test_selector(&env.test_selector);
  1631. free_test_selector(&env.subtest_selector);
  1632. free_test_selector(&env.tmon_selector);
  1633. free_test_states();
  1634. if (env.succ_cnt + env.fail_cnt + env.skip_cnt == 0)
  1635. return EXIT_NO_TEST;
  1636. return env.fail_cnt ? EXIT_FAILURE : EXIT_SUCCESS;
  1637. }