xref: /netbsd-src/external/bsd/jemalloc/dist/test/unit/prof_sys_thread_name.c (revision 7bdf38e5b7a28439665f2fdeff81e36913eef7dd)
1 #include "test/jemalloc_test.h"
2 
3 #include "jemalloc/internal/prof_sys.h"
4 
5 static const char *test_thread_name = "test_name";
6 
7 static int
8 test_prof_sys_thread_name_read_error(char *buf, size_t limit) {
9 	return ENOSYS;
10 }
11 
12 static int
13 test_prof_sys_thread_name_read(char *buf, size_t limit) {
14 	assert(strlen(test_thread_name) < limit);
15 	strncpy(buf, test_thread_name, limit);
16 	return 0;
17 }
18 
19 static int
20 test_prof_sys_thread_name_read_clear(char *buf, size_t limit) {
21 	assert(limit > 0);
22 	buf[0] = '\0';
23 	return 0;
24 }
25 
26 TEST_BEGIN(test_prof_sys_thread_name) {
27 	test_skip_if(!config_prof);
28 
29 	bool oldval;
30 	size_t sz = sizeof(oldval);
31 	assert_d_eq(mallctl("opt.prof_sys_thread_name", &oldval, &sz, NULL, 0),
32 	    0, "mallctl failed");
33 	assert_true(oldval, "option was not set correctly");
34 
35 	const char *thread_name;
36 	sz = sizeof(thread_name);
37 	assert_d_eq(mallctl("thread.prof.name", &thread_name, &sz, NULL, 0), 0,
38 	    "mallctl read for thread name should not fail");
39 	expect_str_eq(thread_name, "", "Initial thread name should be empty");
40 
41 	thread_name = test_thread_name;
42 	assert_d_eq(mallctl("thread.prof.name", NULL, NULL, &thread_name, sz),
43 	    ENOENT, "mallctl write for thread name should fail");
44 	assert_ptr_eq(thread_name, test_thread_name,
45 	    "Thread name should not be touched");
46 
47 	prof_sys_thread_name_read = test_prof_sys_thread_name_read_error;
48 	void *p = malloc(1);
49 	free(p);
50 	assert_d_eq(mallctl("thread.prof.name", &thread_name, &sz, NULL, 0), 0,
51 	    "mallctl read for thread name should not fail");
52 	assert_str_eq(thread_name, "",
53 	    "Thread name should stay the same if the system call fails");
54 
55 	prof_sys_thread_name_read = test_prof_sys_thread_name_read;
56 	p = malloc(1);
57 	free(p);
58 	assert_d_eq(mallctl("thread.prof.name", &thread_name, &sz, NULL, 0), 0,
59 	    "mallctl read for thread name should not fail");
60 	assert_str_eq(thread_name, test_thread_name,
61 	    "Thread name should be changed if the system call succeeds");
62 
63 	prof_sys_thread_name_read = test_prof_sys_thread_name_read_clear;
64 	p = malloc(1);
65 	free(p);
66 	assert_d_eq(mallctl("thread.prof.name", &thread_name, &sz, NULL, 0), 0,
67 	    "mallctl read for thread name should not fail");
68 	expect_str_eq(thread_name, "", "Thread name should be updated if the "
69 	    "system call returns a different name");
70 }
71 TEST_END
72 
73 int
74 main(void) {
75 	return test(
76 	    test_prof_sys_thread_name);
77 }
78