xref: /xnu-12377.41.6/tests/mach_port_insert_right.c (revision bbb1b6f9e71b8cdde6e5cd6f4841f207dee3d828)
1 #include <stdio.h>
2 #include <mach/mach.h>
3 #include <mach/message.h>
4 #include <darwintest.h>
5 
6 T_GLOBAL_META(
7 	T_META_NAMESPACE("xnu.ipc"),
8 	T_META_RUN_CONCURRENTLY(TRUE),
9 	T_META_RADAR_COMPONENT_NAME("xnu"),
10 	T_META_RADAR_COMPONENT_VERSION("IPC"),
11 	T_META_TAG_VM_PREFERRED);
12 
13 static inline mach_port_type_t
get_port_type(mach_port_t mp)14 get_port_type(mach_port_t mp)
15 {
16 	mach_port_type_t type;
17 	T_QUIET;
18 	T_ASSERT_MACH_SUCCESS(mach_port_type(mach_task_self(), mp, &type),
19 	    "mach_port_type(mP)");
20 	return type;
21 }
22 
23 T_DECL(mach_port_insert_right, "insert send right for an existing right", T_META_CHECK_LEAKS(false))
24 {
25 	mach_port_t port = MACH_PORT_NULL;
26 	mach_port_t port2 = MACH_PORT_NULL;
27 	kern_return_t retval;
28 
29 	mach_port_t task = mach_task_self();
30 
31 	retval = mach_port_allocate(task, MACH_PORT_RIGHT_RECEIVE, &port);
32 	T_ASSERT_MACH_SUCCESS(retval, "allocate a port=[%d]", port);
33 
34 	T_ASSERT_EQ(get_port_type(port), MACH_PORT_TYPE_RECEIVE,
35 	    "0x%x should be a receive right", port);
36 
37 	retval = mach_port_insert_right(task, port, port, MACH_MSG_TYPE_MAKE_SEND);
38 	T_ASSERT_MACH_SUCCESS(retval, "insert a send right for port=[%d] with name=[%d]", port, port);
39 	T_ASSERT_EQ(get_port_type(port), MACH_PORT_TYPE_RECEIVE | MACH_PORT_TYPE_SEND,
40 	    "0x%x should be a send-receive right", port);
41 
42 	mach_port_name_t name = 123;
43 	/* 0x7B, lower two bits are 0b11 which is valid gen number, but index is invalid (0) */
44 	retval = mach_port_insert_right(task, name, port, MACH_MSG_TYPE_MAKE_SEND);
45 	T_ASSERT_MACH_ERROR(retval, KERN_FAILURE, "insert a send right for port=[%d] with name=[%d]", port, name);
46 
47 	name = 122;
48 	/* invalid gen number, should return KERN_INVALID_VALUE */
49 	retval = mach_port_insert_right(task, name, port, MACH_MSG_TYPE_MAKE_SEND);
50 	T_ASSERT_MACH_ERROR(retval, KERN_INVALID_VALUE, "insert a send right for port=[%d] with name=[%d]", port, name);
51 
52 	retval = mach_port_allocate(task, MACH_PORT_RIGHT_RECEIVE, &port2);
53 	T_ASSERT_MACH_SUCCESS(retval, "allocate a port=[%d]", port2);
54 
55 	T_ASSERT_EQ(get_port_type(port2), MACH_PORT_TYPE_RECEIVE,
56 	    "0x%x should be a receive right", port2);
57 
58 	name = port;
59 	retval = mach_port_insert_right(task, name, port2, MACH_MSG_TYPE_MAKE_SEND);
60 	T_ASSERT_MACH_ERROR(retval, KERN_RIGHT_EXISTS, "insert a send right for port=[%d] with name=[%d]", port2, name);
61 }
62