repo
stringlengths
1
152
file
stringlengths
14
221
code
stringlengths
501
25k
file_length
int64
501
25k
avg_line_length
float64
20
99.5
max_line_length
int64
21
134
extension_type
stringclasses
2 values
gvisor
gvisor-master/runsc/sandbox/bpf/af_xdp.ebpf.c
// Copyright 2022 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <linux/bpf.h> #define section(secname) __attribute__((section(secname), used)) char __license[] section("license") = "Apache-2.0"; // Helper functions are defined positionally in <linux/bpf.h>, and their // signatures are scattered throughout the kernel. They can be found via the // defining macro BPF_CALL_[0-5]. // TODO(b/240191988): Use vmlinux instead of this. static int (*bpf_redirect_map)(void *bpf_map, __u32 iface_index, __u64 flags) = (void *)51; struct bpf_map_def { unsigned int type; unsigned int key_size; unsigned int value_size; unsigned int max_entries; unsigned int map_flags; }; // A map of RX queue number to AF_XDP socket. We only ever use one key: 0. struct bpf_map_def section("maps") sock_map = { .type = BPF_MAP_TYPE_XSKMAP, // Note: "XSK" means AF_XDP socket. .key_size = sizeof(int), .value_size = sizeof(int), .max_entries = 1, }; section("xdp") int xdp_prog(struct xdp_md *ctx) { // Lookup the socket for the current RX queue. Veth devices by default have // only one RX queue. If one is found, redirect the packet to that socket. // Otherwise pass it on to the kernel network stack. // // TODO: We can support multiple sockets with a fancier hash-based handoff. return bpf_redirect_map(&sock_map, ctx->rx_queue_index, XDP_PASS); }
1,944
36.403846
77
c
gvisor
gvisor-master/test/benchmarks/tcp/nsjoin.c
// Copyright 2018 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef _GNU_SOURCE #define _GNU_SOURCE #endif #include <errno.h> #include <fcntl.h> #include <sched.h> #include <stdio.h> #include <string.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> int main(int argc, char** argv) { if (argc <= 2) { fprintf(stderr, "error: must provide a namespace file.\n"); fprintf(stderr, "usage: %s <file> [arguments...]\n", argv[0]); return 1; } int fd = open(argv[1], O_RDONLY); if (fd < 0) { fprintf(stderr, "error opening %s: %s\n", argv[1], strerror(errno)); return 1; } if (setns(fd, 0) < 0) { fprintf(stderr, "error joining %s: %s\n", argv[1], strerror(errno)); return 1; } execvp(argv[2], &argv[2]); return 1; }
1,314
26.395833
75
c
gvisor
gvisor-master/test/syscalls/linux/base_poll_test.h
// Copyright 2018 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef GVISOR_TEST_SYSCALLS_BASE_POLL_TEST_H_ #define GVISOR_TEST_SYSCALLS_BASE_POLL_TEST_H_ #include <signal.h> #include <sys/syscall.h> #include <sys/types.h> #include <syscall.h> #include <time.h> #include <unistd.h> #include <memory> #include "gtest/gtest.h" #include "absl/synchronization/mutex.h" #include "absl/time/time.h" #include "test/util/logging.h" #include "test/util/signal_util.h" #include "test/util/thread_util.h" namespace gvisor { namespace testing { // TimerThread is a cancelable timer. class TimerThread { public: TimerThread(absl::Time deadline, pid_t tgid, pid_t tid) : thread_([=] { mu_.Lock(); mu_.AwaitWithDeadline(absl::Condition(&cancel_), deadline); if (!cancel_) { TEST_PCHECK(tgkill(tgid, tid, SIGALRM) == 0); } mu_.Unlock(); }) {} ~TimerThread() { Cancel(); } void Cancel() { absl::MutexLock ml(&mu_); cancel_ = true; } private: mutable absl::Mutex mu_; bool cancel_ ABSL_GUARDED_BY(mu_) = false; // Must be last to ensure that the destructor for the thread is run before // any other member of the object is destroyed. ScopedThread thread_; }; // Base test fixture for poll, select, ppoll, and pselect tests. // // This fixture makes use of SIGALRM. The handler is saved in SetUp() and // restored in TearDown(). class BasePollTest : public ::testing::Test { protected: BasePollTest(); ~BasePollTest() override; // Sets a timer that will send a signal to the calling thread after // `duration`. void SetTimer(absl::Duration duration); // Returns true if the timer has fired. bool TimerFired() const; // Stops the pending timer (if any) and clear the "fired" state. void ClearTimer(); private: // Thread that implements the timer. If the timer is stopped, timer_ is null. // // We have to use a thread for this purpose because tests using this fixture // expect to be interrupted by the timer signal, but itimers/alarm(2) send // thread-group-directed signals, which may be handled by any thread in the // test process. std::unique_ptr<TimerThread> timer_; // The original SIGALRM handler, to restore in destructor. struct sigaction original_alarm_sa_; }; } // namespace testing } // namespace gvisor #endif // GVISOR_TEST_SYSCALLS_BASE_POLL_TEST_H_
2,944
27.872549
79
h
gvisor
gvisor-master/test/syscalls/linux/exec.h
// Copyright 2018 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef GVISOR_TEST_SYSCALLS_EXEC_H_ #define GVISOR_TEST_SYSCALLS_EXEC_H_ #include <sys/wait.h> namespace gvisor { namespace testing { // Returns the exit code used by exec_basic_workload. inline int ArgEnvExitCode(int args, int envs) { return args + envs * 10; } // Returns the exit status used by exec_basic_workload. inline int ArgEnvExitStatus(int args, int envs) { return W_EXITCODE(ArgEnvExitCode(args, envs), 0); } } // namespace testing } // namespace gvisor #endif // GVISOR_TEST_SYSCALLS_EXEC_H_
1,114
30.857143
75
h
gvisor
gvisor-master/test/syscalls/linux/file_base.h
// Copyright 2018 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef GVISOR_TEST_SYSCALLS_FILE_BASE_H_ #define GVISOR_TEST_SYSCALLS_FILE_BASE_H_ #include <arpa/inet.h> #include <errno.h> #include <fcntl.h> #include <netinet/in.h> #include <stddef.h> #include <stdio.h> #include <string.h> #include <sys/socket.h> #include <sys/stat.h> #include <sys/types.h> #include <sys/uio.h> #include <unistd.h> #include <cstring> #include <string> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/strings/string_view.h" #include "test/util/file_descriptor.h" #include "test/util/posix_error.h" #include "test/util/temp_path.h" #include "test/util/test_util.h" namespace gvisor { namespace testing { class FileTest : public ::testing::Test { public: void SetUp() override { test_pipe_[0] = -1; test_pipe_[1] = -1; test_file_name_ = NewTempAbsPath(); test_file_fd_ = ASSERT_NO_ERRNO_AND_VALUE( Open(test_file_name_, O_CREAT | O_RDWR, S_IRUSR | S_IWUSR)); ASSERT_THAT(pipe(test_pipe_), SyscallSucceeds()); ASSERT_THAT(fcntl(test_pipe_[0], F_SETFL, O_NONBLOCK), SyscallSucceeds()); } // CloseFile will allow the test to manually close the file descriptor. void CloseFile() { test_file_fd_.reset(); } // UnlinkFile will allow the test to manually unlink the file. void UnlinkFile() { if (!test_file_name_.empty()) { EXPECT_THAT(unlink(test_file_name_.c_str()), SyscallSucceeds()); test_file_name_.clear(); } } // ClosePipes will allow the test to manually close the pipes. void ClosePipes() { if (test_pipe_[0] > 0) { EXPECT_THAT(close(test_pipe_[0]), SyscallSucceeds()); } if (test_pipe_[1] > 0) { EXPECT_THAT(close(test_pipe_[1]), SyscallSucceeds()); } test_pipe_[0] = -1; test_pipe_[1] = -1; } void TearDown() override { CloseFile(); UnlinkFile(); ClosePipes(); } protected: std::string test_file_name_; FileDescriptor test_file_fd_; int test_pipe_[2]; }; } // namespace testing } // namespace gvisor #endif // GVISOR_TEST_SYSCALLS_FILE_BASE_H_
2,635
25.09901
78
h
gvisor
gvisor-master/test/syscalls/linux/ip_socket_test_util.h
// Copyright 2018 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef GVISOR_TEST_SYSCALLS_IP_SOCKET_TEST_UTIL_H_ #define GVISOR_TEST_SYSCALLS_IP_SOCKET_TEST_UTIL_H_ #include <arpa/inet.h> #include <ifaddrs.h> #include <sys/types.h> #include <string> #include "test/util/socket_util.h" namespace gvisor { namespace testing { // Extracts the IP address from an inet sockaddr in network byte order. uint32_t IPFromInetSockaddr(const struct sockaddr* addr); // Extracts the port from an inet sockaddr in host byte order. uint16_t PortFromInetSockaddr(const struct sockaddr* addr); // InterfaceIndex returns the index of the named interface. PosixErrorOr<int> InterfaceIndex(std::string name); // GetLoopbackIndex returns the index of the loopback interface. inline PosixErrorOr<int> GetLoopbackIndex() { return InterfaceIndex("lo"); } // IPv6TCPAcceptBindSocketPair returns a SocketPairKind that represents // SocketPairs created with bind() and accept() syscalls with AF_INET6 and the // given type bound to the IPv6 loopback. SocketPairKind IPv6TCPAcceptBindSocketPair(int type); // IPv4TCPAcceptBindSocketPair returns a SocketPairKind that represents // SocketPairs created with bind() and accept() syscalls with AF_INET and the // given type bound to the IPv4 loopback. SocketPairKind IPv4TCPAcceptBindSocketPair(int type); // DualStackTCPAcceptBindSocketPair returns a SocketPairKind that represents // SocketPairs created with bind() and accept() syscalls with AF_INET6 and the // given type bound to the IPv4 loopback. SocketPairKind DualStackTCPAcceptBindSocketPair(int type); // IPv6TCPAcceptBindPersistentListenerSocketPair is like // IPv6TCPAcceptBindSocketPair except it uses a persistent listening socket to // create all socket pairs. SocketPairKind IPv6TCPAcceptBindPersistentListenerSocketPair(int type); // IPv4TCPAcceptBindPersistentListenerSocketPair is like // IPv4TCPAcceptBindSocketPair except it uses a persistent listening socket to // create all socket pairs. SocketPairKind IPv4TCPAcceptBindPersistentListenerSocketPair(int type); // DualStackTCPAcceptBindPersistentListenerSocketPair is like // DualStackTCPAcceptBindSocketPair except it uses a persistent listening socket // to create all socket pairs. SocketPairKind DualStackTCPAcceptBindPersistentListenerSocketPair(int type); // IPv6UDPBidirectionalBindSocketPair returns a SocketPairKind that represents // SocketPairs created with bind() and connect() syscalls with AF_INET6 and the // given type bound to the IPv6 loopback. SocketPairKind IPv6UDPBidirectionalBindSocketPair(int type); // IPv4UDPBidirectionalBindSocketPair returns a SocketPairKind that represents // SocketPairs created with bind() and connect() syscalls with AF_INET and the // given type bound to the IPv4 loopback. SocketPairKind IPv4UDPBidirectionalBindSocketPair(int type); // DualStackUDPBidirectionalBindSocketPair returns a SocketPairKind that // represents SocketPairs created with bind() and connect() syscalls with // AF_INET6 and the given type bound to the IPv4 loopback. SocketPairKind DualStackUDPBidirectionalBindSocketPair(int type); // IPv4UDPUnboundSocketPair returns a SocketPairKind that represents // SocketPairs created with AF_INET and the given type. SocketPairKind IPv4UDPUnboundSocketPair(int type); // ICMPUnboundSocket returns a SocketKind that represents a SimpleSocket created // with AF_INET, SOCK_DGRAM, IPPROTO_ICMP, and the given type. SocketKind ICMPUnboundSocket(int type); // ICMPv6UnboundSocket returns a SocketKind that represents a SimpleSocket // created with AF_INET6, SOCK_DGRAM, IPPROTO_ICMPV6, and the given type. SocketKind ICMPv6UnboundSocket(int type); // IPv4RawUDPUnboundSocket returns a SocketKind that represents a SimpleSocket // created with AF_INET, SOCK_RAW, IPPROTO_UDP, and the given type. SocketKind IPv4RawUDPUnboundSocket(int type); // IPv4UDPUnboundSocket returns a SocketKind that represents a SimpleSocket // created with AF_INET, SOCK_DGRAM, IPPROTO_UDP, and the given type. SocketKind IPv4UDPUnboundSocket(int type); // IPv6UDPUnboundSocket returns a SocketKind that represents a SimpleSocket // created with AF_INET6, SOCK_DGRAM, IPPROTO_UDP, and the given type. SocketKind IPv6UDPUnboundSocket(int type); // IPv4TCPUnboundSocket returns a SocketKind that represents a SimpleSocket // created with AF_INET, SOCK_STREAM, IPPROTO_TCP and the given type. SocketKind IPv4TCPUnboundSocket(int type); // IPv6TCPUnboundSocket returns a SocketKind that represents a SimpleSocket // created with AF_INET6, SOCK_STREAM, IPPROTO_TCP and the given type. SocketKind IPv6TCPUnboundSocket(int type); // GetAddr4Str returns the given IPv4 network address structure as a string. std::string GetAddr4Str(const in_addr* a); // GetAddr6Str returns the given IPv6 network address structure as a string. std::string GetAddr6Str(const in6_addr* a); // GetAddrStr returns the given IPv4 or IPv6 network address structure as a // string. std::string GetAddrStr(const sockaddr* a); // RecvTOS attempts to read buf_size bytes into buf, and then updates buf_size // with the numbers of bytes actually read. It expects the IP_TOS cmsg to be // received. The buffer must already be allocated with at least buf_size size. void RecvTOS(int sock, char buf[], size_t* buf_size, uint8_t* out_tos); // SendTOS sends a message using buf as payload and tos as IP_TOS control // message. void SendTOS(int sock, char buf[], size_t buf_size, uint8_t tos); // RecvTClass attempts to read buf_size bytes into buf, and then updates // buf_size with the numbers of bytes actually read. It expects the IPV6_TCLASS // cmsg to be received. The buffer must already be allocated with at least // buf_size size. void RecvTClass(int sock, char buf[], size_t* buf_size, int* out_tclass); // SendTClass sends a message using buf as payload and tclass as IP_TOS control // message. void SendTClass(int sock, char buf[], size_t buf_size, int tclass); // RecvTTL attempts to read buf_size bytes into buf, and then updates buf_size // with the numbers of bytes actually read. It expects the IP_TTL cmsg to be // received. The buffer must already be allocated with at least buf_size size. void RecvTTL(int sock, char buf[], size_t* buf_size, int* out_ttl); // SendTTL sends a message using buf as payload and ttl as IP_TOS control // message. void SendTTL(int sock, char buf[], size_t buf_size, int ttl); // RecvHopLimit attempts to read buf_size bytes into buf, and then updates // buf_size with the numbers of bytes actually read. It expects the // IPV6_HOPLIMIT cmsg to be received. The buffer must already be allocated with // at least buf_size size. void RecvHopLimit(int sock, char buf[], size_t* buf_size, int* out_hoplimit); // SendHopLimit sends a message using buf as payload and hoplimit as IP_HOPLIMIT // control message. void SendHopLimit(int sock, char buf[], size_t buf_size, int hoplimit); // RecvPktInfo attempts to read buf_size bytes into buf, and then updates // buf_size with the numbers of bytes actually read. It expects the // IP_PKTINFO cmsg to be received. The buffer must already be allocated with // at least buf_size size. void RecvPktInfo(int sock, char buf[], size_t* buf_size, in_pktinfo* out_pktinfo); // RecvIPv6PktInfo attempts to read buf_size bytes into buf, and then updates // buf_size with the numbers of bytes actually read. It expects the // IPV6_PKTINFO cmsg to be received. The buffer must already be allocated with // at least buf_size size. void RecvIPv6PktInfo(int sock, char buf[], size_t* buf_size, in6_pktinfo* out_pktinfo); } // namespace testing } // namespace gvisor #endif // GVISOR_TEST_SYSCALLS_IP_SOCKET_TEST_UTIL_H_
8,247
44.071038
80
h
gvisor
gvisor-master/test/syscalls/linux/iptables.h
// Copyright 2019 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // There are a number of structs and values that we can't #include because of a // difference between C and C++ (C++ won't let you implicitly cast from void* to // struct something*). We re-define them here. #ifndef GVISOR_TEST_SYSCALLS_IPTABLES_TYPES_H_ #define GVISOR_TEST_SYSCALLS_IPTABLES_TYPES_H_ // Netfilter headers require some headers to preceed them. // clang-format off #include <netinet/in.h> #include <stddef.h> // clang-format on #include <linux/netfilter/x_tables.h> #include <linux/netfilter_ipv4.h> #include <linux/netfilter_ipv6.h> #include <net/if.h> #include <netinet/ip.h> #include <stdint.h> // // IPv4 ABI. // #define ipt_standard_target xt_standard_target #define ipt_entry_target xt_entry_target #define ipt_error_target xt_error_target enum SockOpts { // For setsockopt. IPT_BASE_CTL = 64, IPT_SO_SET_REPLACE = IPT_BASE_CTL, IPT_SO_SET_ADD_COUNTERS = IPT_BASE_CTL + 1, IPT_SO_SET_MAX = IPT_SO_SET_ADD_COUNTERS, // For getsockopt. IPT_SO_GET_INFO = IPT_BASE_CTL, IPT_SO_GET_ENTRIES = IPT_BASE_CTL + 1, IPT_SO_GET_REVISION_MATCH = IPT_BASE_CTL + 2, IPT_SO_GET_REVISION_TARGET = IPT_BASE_CTL + 3, IPT_SO_GET_MAX = IPT_SO_GET_REVISION_TARGET }; // ipt_ip specifies basic matching criteria that can be applied by examining // only the IP header of a packet. struct ipt_ip { // Source IP address. struct in_addr src; // Destination IP address. struct in_addr dst; // Source IP address mask. struct in_addr smsk; // Destination IP address mask. struct in_addr dmsk; // Input interface. char iniface[IFNAMSIZ]; // Output interface. char outiface[IFNAMSIZ]; // Input interface mask. unsigned char iniface_mask[IFNAMSIZ]; // Output interface mask. unsigned char outiface_mask[IFNAMSIZ]; // Transport protocol. uint16_t proto; // Flags. uint8_t flags; // Inverse flags. uint8_t invflags; }; // ipt_entry is an iptables rule. It contains information about what packets the // rule matches and what action (target) to perform for matching packets. struct ipt_entry { // Basic matching information used to match a packet's IP header. struct ipt_ip ip; // A caching field that isn't used by userspace. unsigned int nfcache; // The number of bytes between the start of this ipt_entry struct and the // rule's target. uint16_t target_offset; // The total size of this rule, from the beginning of the entry to the end of // the target. uint16_t next_offset; // A return pointer not used by userspace. unsigned int comefrom; // Counters for packets and bytes, which we don't yet implement. struct xt_counters counters; // The data for all this rules matches followed by the target. This runs // beyond the value of sizeof(struct ipt_entry). unsigned char elems[0]; }; // Passed to getsockopt(IPT_SO_GET_INFO). struct ipt_getinfo { // The name of the table. The user only fills this in, the rest is filled in // when returning from getsockopt. Currently "nat" and "mangle" are supported. char name[XT_TABLE_MAXNAMELEN]; // A bitmap of which hooks apply to the table. For example, a table with hooks // PREROUTING and FORWARD has the value // (1 << NF_IP_PRE_REOUTING) | (1 << NF_IP_FORWARD). unsigned int valid_hooks; // The offset into the entry table for each valid hook. The entry table is // returned by getsockopt(IPT_SO_GET_ENTRIES). unsigned int hook_entry[NF_IP_NUMHOOKS]; // For each valid hook, the underflow is the offset into the entry table to // jump to in case traversing the table yields no verdict (although I have no // clue how that could happen - builtin chains always end with a policy, and // user-defined chains always end with a RETURN. // // The entry referred to must be an "unconditional" entry, meaning it has no // matches, specifies no IP criteria, and either DROPs or ACCEPTs packets. It // basically has to be capable of making a definitive decision no matter what // it's passed. unsigned int underflow[NF_IP_NUMHOOKS]; // The number of entries in the entry table returned by // getsockopt(IPT_SO_GET_ENTRIES). unsigned int num_entries; // The size of the entry table returned by getsockopt(IPT_SO_GET_ENTRIES). unsigned int size; }; // Passed to getsockopt(IPT_SO_GET_ENTRIES). struct ipt_get_entries { // The name of the table. The user fills this in. Currently "nat" and "mangle" // are supported. char name[XT_TABLE_MAXNAMELEN]; // The size of the entry table in bytes. The user fills this in with the value // from struct ipt_getinfo.size. unsigned int size; // The entries for the given table. This will run past the size defined by // sizeof(struct ipt_get_entries). struct ipt_entry entrytable[0]; }; // Passed to setsockopt(SO_SET_REPLACE). struct ipt_replace { // The name of the table. char name[XT_TABLE_MAXNAMELEN]; // The same as struct ipt_getinfo.valid_hooks. Users don't change this. unsigned int valid_hooks; // The same as struct ipt_getinfo.num_entries. unsigned int num_entries; // The same as struct ipt_getinfo.size. unsigned int size; // The same as struct ipt_getinfo.hook_entry. unsigned int hook_entry[NF_IP_NUMHOOKS]; // The same as struct ipt_getinfo.underflow. unsigned int underflow[NF_IP_NUMHOOKS]; // The number of counters, which should equal the number of entries. unsigned int num_counters; // The unchanged values from each ipt_entry's counters. struct xt_counters* counters; // The entries to write to the table. This will run past the size defined by // sizeof(srtuct ipt_replace); struct ipt_entry entries[0]; }; // // IPv6 ABI. // enum SockOpts6 { // For setsockopt. IP6T_BASE_CTL = 64, IP6T_SO_SET_REPLACE = IP6T_BASE_CTL, IP6T_SO_SET_ADD_COUNTERS = IP6T_BASE_CTL + 1, IP6T_SO_SET_MAX = IP6T_SO_SET_ADD_COUNTERS, // For getsockopt. IP6T_SO_GET_INFO = IP6T_BASE_CTL, IP6T_SO_GET_ENTRIES = IP6T_BASE_CTL + 1, IP6T_SO_GET_REVISION_MATCH = IP6T_BASE_CTL + 4, IP6T_SO_GET_REVISION_TARGET = IP6T_BASE_CTL + 5, IP6T_SO_GET_MAX = IP6T_SO_GET_REVISION_TARGET }; // ip6t_ip6 specifies basic matching criteria that can be applied by examining // only the IP header of a packet. struct ip6t_ip6 { // Source IP address. struct in6_addr src; // Destination IP address. struct in6_addr dst; // Source IP address mask. struct in6_addr smsk; // Destination IP address mask. struct in6_addr dmsk; // Input interface. char iniface[IFNAMSIZ]; // Output interface. char outiface[IFNAMSIZ]; // Input interface mask. unsigned char iniface_mask[IFNAMSIZ]; // Output interface mask. unsigned char outiface_mask[IFNAMSIZ]; // Transport protocol. uint16_t proto; // TOS. uint8_t tos; // Flags. uint8_t flags; // Inverse flags. uint8_t invflags; }; // ip6t_entry is an ip6tables rule. struct ip6t_entry { // Basic matching information used to match a packet's IP header. struct ip6t_ip6 ipv6; // A caching field that isn't used by userspace. unsigned int nfcache; // The number of bytes between the start of this entry and the rule's target. uint16_t target_offset; // The total size of this rule, from the beginning of the entry to the end of // the target. uint16_t next_offset; // A return pointer not used by userspace. unsigned int comefrom; // Counters for packets and bytes, which we don't yet implement. struct xt_counters counters; // The data for all this rules matches followed by the target. This runs // beyond the value of sizeof(struct ip6t_entry). unsigned char elems[0]; }; // Passed to getsockopt(IP6T_SO_GET_ENTRIES). struct ip6t_get_entries { // The name of the table. char name[XT_TABLE_MAXNAMELEN]; // The size of the entry table in bytes. The user fills this in with the value // from struct ipt_getinfo.size. unsigned int size; // The entries for the given table. This will run past the size defined by // sizeof(struct ip6t_get_entries). struct ip6t_entry entrytable[0]; }; #endif // GVISOR_TEST_SYSCALLS_IPTABLES_TYPES_H_
8,693
27.693069
80
h
gvisor
gvisor-master/test/syscalls/linux/readv_common.h
// Copyright 2018 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef GVISOR_TEST_SYSCALLS_READV_COMMON_H_ #define GVISOR_TEST_SYSCALLS_READV_COMMON_H_ #include <stddef.h> namespace gvisor { namespace testing { // A NUL-terminated string containing the data used by tests using the following // test helpers. extern const char kReadvTestData[]; // The size of kReadvTestData, including the terminating NUL. extern const size_t kReadvTestDataSize; // ReadAllOneBuffer asserts that it can read kReadvTestData from an fd using // exactly one iovec. void ReadAllOneBuffer(int fd); // ReadAllOneLargeBuffer asserts that it can read kReadvTestData from an fd // using exactly one iovec containing an overly large buffer. void ReadAllOneLargeBuffer(int fd); // ReadOneHalfAtATime asserts that it can read test_data_from an fd using // exactly two iovecs that are roughly equivalent in size. void ReadOneHalfAtATime(int fd); // ReadOneBufferPerByte asserts that it can read kReadvTestData from an fd // using one iovec per byte. void ReadOneBufferPerByte(int fd); // ReadBuffersOverlapping asserts that it can read kReadvTestData from an fd // where two iovecs are overlapping. void ReadBuffersOverlapping(int fd); // ReadBuffersDiscontinuous asserts that it can read kReadvTestData from an fd // where each iovec is discontinuous from the next by 1 byte. void ReadBuffersDiscontinuous(int fd); // ReadIovecsCompletelyFilled asserts that the previous iovec is completely // filled before moving onto the next. void ReadIovecsCompletelyFilled(int fd); } // namespace testing } // namespace gvisor #endif // GVISOR_TEST_SYSCALLS_READV_COMMON_H_
2,186
34.274194
80
h
gvisor
gvisor-master/test/syscalls/linux/socket_bind_to_device_util.h
// Copyright 2019 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef GVISOR_TEST_SYSCALLS_SOCKET_BIND_TO_DEVICE_UTILS_H_ #define GVISOR_TEST_SYSCALLS_SOCKET_BIND_TO_DEVICE_UTILS_H_ #include <arpa/inet.h> #include <linux/if_tun.h> #include <net/if.h> #include <netinet/in.h> #include <sys/ioctl.h> #include <sys/socket.h> #include <sys/types.h> #include <sys/un.h> #include <unistd.h> #include <cstdio> #include <cstring> #include <map> #include <memory> #include <string> #include <unordered_map> #include <unordered_set> #include <utility> #include <vector> #include "absl/memory/memory.h" #include "test/util/test_util.h" namespace gvisor { namespace testing { class Tunnel { public: static PosixErrorOr<std::unique_ptr<Tunnel>> New( std::string tunnel_name = ""); const std::string& GetName() const { return name_; } ~Tunnel() { if (fd_ != -1) { close(fd_); } } private: Tunnel(int fd) : fd_(fd) {} int fd_ = -1; std::string name_; }; std::unordered_set<std::string> GetInterfaceNames(); } // namespace testing } // namespace gvisor #endif // GVISOR_TEST_SYSCALLS_SOCKET_BIND_TO_DEVICE_UTILS_H_
1,683
23.764706
75
h
gvisor
gvisor-master/test/syscalls/linux/socket_blocking.h
// Copyright 2018 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef GVISOR_TEST_SYSCALLS_LINUX_SOCKET_BLOCKING_H_ #define GVISOR_TEST_SYSCALLS_LINUX_SOCKET_BLOCKING_H_ #include "test/util/socket_util.h" namespace gvisor { namespace testing { // Test fixture for tests that apply to pairs of blocking connected sockets. using BlockingSocketPairTest = SocketPairTest; } // namespace testing } // namespace gvisor #endif // GVISOR_TEST_SYSCALLS_LINUX_SOCKET_BLOCKING_H_
1,012
32.766667
76
h
gvisor
gvisor-master/test/syscalls/linux/socket_generic.h
// Copyright 2018 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef GVISOR_TEST_SYSCALLS_LINUX_SOCKET_GENERIC_H_ #define GVISOR_TEST_SYSCALLS_LINUX_SOCKET_GENERIC_H_ #include "test/util/socket_util.h" namespace gvisor { namespace testing { // Test fixture for tests that apply to pairs of blocking and non-blocking // connected stream sockets. using AllSocketPairTest = SocketPairTest; } // namespace testing } // namespace gvisor #endif // GVISOR_TEST_SYSCALLS_LINUX_SOCKET_GENERIC_H_
1,031
32.290323
75
h
gvisor
gvisor-master/test/syscalls/linux/socket_inet_loopback_test_params.h
// Copyright 2018 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef GVISOR_TEST_SYSCALLS_LINUX_SOCKET_INET_LOOPBACK_TEST_PARAMS_H_ #define GVISOR_TEST_SYSCALLS_LINUX_SOCKET_INET_LOOPBACK_TEST_PARAMS_H_ #include "gtest/gtest.h" #include "test/util/socket_util.h" namespace gvisor { namespace testing { struct SocketInetTestParam { TestAddress listener; TestAddress connector; }; inline std::string DescribeSocketInetTestParam( ::testing::TestParamInfo<SocketInetTestParam> const& info) { return absl::StrCat("Listen", info.param.listener.description, "_Connect", info.param.connector.description); } inline auto SocketInetLoopbackTestValues() { return ::testing::Values( // Listeners bound to IPv4 addresses refuse connections using IPv6 // addresses. SocketInetTestParam{V4Any(), V4Any()}, SocketInetTestParam{V4Any(), V4Loopback()}, SocketInetTestParam{V4Any(), V4MappedAny()}, SocketInetTestParam{V4Any(), V4MappedLoopback()}, SocketInetTestParam{V4Loopback(), V4Any()}, SocketInetTestParam{V4Loopback(), V4Loopback()}, SocketInetTestParam{V4Loopback(), V4MappedLoopback()}, SocketInetTestParam{V4MappedAny(), V4Any()}, SocketInetTestParam{V4MappedAny(), V4Loopback()}, SocketInetTestParam{V4MappedAny(), V4MappedAny()}, SocketInetTestParam{V4MappedAny(), V4MappedLoopback()}, SocketInetTestParam{V4MappedLoopback(), V4Any()}, SocketInetTestParam{V4MappedLoopback(), V4Loopback()}, SocketInetTestParam{V4MappedLoopback(), V4MappedLoopback()}, // Listeners bound to IN6ADDR_ANY accept all connections. SocketInetTestParam{V6Any(), V4Any()}, SocketInetTestParam{V6Any(), V4Loopback()}, SocketInetTestParam{V6Any(), V4MappedAny()}, SocketInetTestParam{V6Any(), V4MappedLoopback()}, SocketInetTestParam{V6Any(), V6Any()}, SocketInetTestParam{V6Any(), V6Loopback()}, // Listeners bound to IN6ADDR_LOOPBACK refuse connections using IPv4 // addresses. SocketInetTestParam{V6Loopback(), V6Any()}, SocketInetTestParam{V6Loopback(), V6Loopback()}); } struct ProtocolTestParam { std::string description; int type; }; inline std::string DescribeProtocolTestParam( ::testing::TestParamInfo<ProtocolTestParam> const& info) { return info.param.description; } inline auto ProtocolTestValues() { return ::testing::Values(ProtocolTestParam{"TCP", SOCK_STREAM}, ProtocolTestParam{"UDP", SOCK_DGRAM}); } } // namespace testing } // namespace gvisor #endif // GVISOR_TEST_SYSCALLS_LINUX_SOCKET_INET_LOOPBACK_TEST_PARAMS_H_
3,191
35.689655
76
h
gvisor
gvisor-master/test/syscalls/linux/socket_ip_tcp_generic.h
// Copyright 2018 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef GVISOR_TEST_SYSCALLS_LINUX_SOCKET_IP_TCP_GENERIC_H_ #define GVISOR_TEST_SYSCALLS_LINUX_SOCKET_IP_TCP_GENERIC_H_ #include "test/util/socket_util.h" namespace gvisor { namespace testing { // Test fixture for tests that apply to pairs of connected TCP sockets. using TCPSocketPairTest = SocketPairTest; } // namespace testing } // namespace gvisor #endif // GVISOR_TEST_SYSCALLS_LINUX_SOCKET_IP_TCP_GENERIC_H_
1,020
33.033333
75
h
gvisor
gvisor-master/test/syscalls/linux/socket_ip_udp_generic.h
// Copyright 2018 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef GVISOR_TEST_SYSCALLS_LINUX_SOCKET_IP_UDP_GENERIC_H_ #define GVISOR_TEST_SYSCALLS_LINUX_SOCKET_IP_UDP_GENERIC_H_ #include "test/util/socket_util.h" namespace gvisor { namespace testing { // Test fixture for tests that apply to pairs of connected UDP sockets. using UDPSocketPairTest = SocketPairTest; } // namespace testing } // namespace gvisor #endif // GVISOR_TEST_SYSCALLS_LINUX_SOCKET_IP_UDP_GENERIC_H_
1,020
33.033333
75
h
gvisor
gvisor-master/test/syscalls/linux/socket_ip_udp_unbound_external_networking.h
// Copyright 2020 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef GVISOR_TEST_SYSCALLS_LINUX_SOCKET_IP_UDP_UNBOUND_EXTERNAL_NETWORKING_H_ #define GVISOR_TEST_SYSCALLS_LINUX_SOCKET_IP_UDP_UNBOUND_EXTERNAL_NETWORKING_H_ #include "test/syscalls/linux/ip_socket_test_util.h" namespace gvisor { namespace testing { // Test fixture for tests that apply to unbound IP UDP sockets in a sandbox // with external networking support. class IPUDPUnboundExternalNetworkingSocketTest : public SimpleSocketTest {}; } // namespace testing } // namespace gvisor #endif // GVISOR_TEST_SYSCALLS_LINUX_SOCKET_IP_UDP_UNBOUND_EXTERNAL_NETWORKING_H_
1,174
36.903226
82
h
gvisor
gvisor-master/test/syscalls/linux/socket_ipv4_datagram_based_socket_unbound.h
// Copyright 2019 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef GVISOR_TEST_SYSCALLS_LINUX_SOCKET_IPV4_DATAGRAM_BASED_SOCKET_UNBOUND_H_ #define GVISOR_TEST_SYSCALLS_LINUX_SOCKET_IPV4_DATAGRAM_BASED_SOCKET_UNBOUND_H_ #include "test/util/socket_util.h" namespace gvisor { namespace testing { // Test fixture for tests that apply to IPv4 datagram-based sockets. class IPv4DatagramBasedUnboundSocketTest : public SimpleSocketTest { void SetUp() override; }; } // namespace testing } // namespace gvisor #endif // GVISOR_TEST_SYSCALLS_LINUX_SOCKET_IPV4_DATAGRAM_BASED_SOCKET_UNBOUND_H_
1,132
34.40625
82
h
gvisor
gvisor-master/test/syscalls/linux/socket_ipv4_udp_unbound.h
// Copyright 2019 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef GVISOR_TEST_SYSCALLS_LINUX_SOCKET_IPV4_UDP_UNBOUND_H_ #define GVISOR_TEST_SYSCALLS_LINUX_SOCKET_IPV4_UDP_UNBOUND_H_ #include "test/util/socket_util.h" namespace gvisor { namespace testing { // Test fixture for tests that apply to IPv4 UDP sockets. using IPv4UDPUnboundSocketTest = SimpleSocketTest; } // namespace testing } // namespace gvisor #endif // GVISOR_TEST_SYSCALLS_LINUX_SOCKET_IPV4_UDP_UNBOUND_H_
1,021
33.066667
75
h
gvisor
gvisor-master/test/syscalls/linux/socket_ipv4_udp_unbound_external_networking.h
// Copyright 2019 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef GVISOR_TEST_SYSCALLS_LINUX_SOCKET_IPV4_UDP_UNBOUND_EXTERNAL_NETWORKING_H_ #define GVISOR_TEST_SYSCALLS_LINUX_SOCKET_IPV4_UDP_UNBOUND_EXTERNAL_NETWORKING_H_ #include "test/syscalls/linux/socket_ip_udp_unbound_external_networking.h" namespace gvisor { namespace testing { // Test fixture for tests that apply to unbound IPv4 UDP sockets in a sandbox // with external networking support. class IPv4UDPUnboundExternalNetworkingSocketTest : public IPUDPUnboundExternalNetworkingSocketTest { protected: void SetUp() override; int lo_if_idx() const { return std::get<0>(lo_if_.value()); } int eth_if_idx() const { return std::get<0>(eth_if_.value()); } const sockaddr_in& lo_if_addr() const { return std::get<1>(lo_if_.value()); } const sockaddr_in& eth_if_addr() const { return std::get<1>(eth_if_.value()); } private: std::optional<std::pair<int, sockaddr_in>> lo_if_, eth_if_; }; } // namespace testing } // namespace gvisor #endif // GVISOR_TEST_SYSCALLS_LINUX_SOCKET_IPV4_UDP_UNBOUND_EXTERNAL_NETWORKING_H_
1,645
34.782609
84
h
gvisor
gvisor-master/test/syscalls/linux/socket_ipv4_udp_unbound_netlink.h
// Copyright 2020 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef GVISOR_TEST_SYSCALLS_LINUX_SOCKET_IPV4_UDP_UNBOUND_NETLINK_UTIL_H_ #define GVISOR_TEST_SYSCALLS_LINUX_SOCKET_IPV4_UDP_UNBOUND_NETLINK_UTIL_H_ #include "test/util/socket_util.h" namespace gvisor { namespace testing { // Test fixture for tests that apply to IPv4 UDP sockets. using IPv4UDPUnboundSocketNetlinkTest = SimpleSocketTest; } // namespace testing } // namespace gvisor #endif // GVISOR_TEST_SYSCALLS_LINUX_SOCKET_IPV4_UDP_UNBOUND_NETLINK_UTIL_H_
1,067
34.6
77
h
gvisor
gvisor-master/test/syscalls/linux/socket_ipv6_udp_unbound.h
// Copyright 2020 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef GVISOR_TEST_SYSCALLS_LINUX_SOCKET_IPV6_UDP_UNBOUND_H_ #define GVISOR_TEST_SYSCALLS_LINUX_SOCKET_IPV6_UDP_UNBOUND_H_ #include "test/util/socket_util.h" namespace gvisor { namespace testing { // Test fixture for tests that apply to IPv6 UDP sockets. using IPv6UDPUnboundSocketTest = SimpleSocketTest; } // namespace testing } // namespace gvisor #endif // GVISOR_TEST_SYSCALLS_LINUX_SOCKET_IPV6_UDP_UNBOUND_H_
1,021
33.066667
75
h
gvisor
gvisor-master/test/syscalls/linux/socket_ipv6_udp_unbound_external_networking.h
// Copyright 2020 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef GVISOR_TEST_SYSCALLS_LINUX_SOCKET_IPV6_UDP_UNBOUND_EXTERNAL_NETWORKING_H_ #define GVISOR_TEST_SYSCALLS_LINUX_SOCKET_IPV6_UDP_UNBOUND_EXTERNAL_NETWORKING_H_ #include "test/syscalls/linux/socket_ip_udp_unbound_external_networking.h" namespace gvisor { namespace testing { // Test fixture for tests that apply to unbound IPv6 UDP sockets in a sandbox // with external networking support. using IPv6UDPUnboundExternalNetworkingSocketTest = IPUDPUnboundExternalNetworkingSocketTest; } // namespace testing } // namespace gvisor #endif // GVISOR_TEST_SYSCALLS_LINUX_SOCKET_IPV6yy_UDP_UNBOUND_EXTERNAL_NETWORKING_H_
1,226
37.34375
86
h
gvisor
gvisor-master/test/syscalls/linux/socket_ipv6_udp_unbound_netlink.h
// Copyright 2020 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef GVISOR_TEST_SYSCALLS_LINUX_SOCKET_IPV6_UDP_UNBOUND_NETLINK_UTIL_H_ #define GVISOR_TEST_SYSCALLS_LINUX_SOCKET_IPV6_UDP_UNBOUND_NETLINK_UTIL_H_ #include "test/util/socket_util.h" namespace gvisor { namespace testing { // Test fixture for tests that apply to IPv6 UDP sockets. using IPv6UDPUnboundSocketNetlinkTest = SimpleSocketTest; } // namespace testing } // namespace gvisor #endif // GVISOR_TEST_SYSCALLS_LINUX_SOCKET_IPV6_UDP_UNBOUND_NETLINK_UTIL_H_
1,067
34.6
77
h
gvisor
gvisor-master/test/syscalls/linux/socket_netlink_route_util.h
// Copyright 2020 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef GVISOR_TEST_SYSCALLS_LINUX_SOCKET_NETLINK_ROUTE_UTIL_H_ #define GVISOR_TEST_SYSCALLS_LINUX_SOCKET_NETLINK_ROUTE_UTIL_H_ #include <linux/netlink.h> #include <linux/rtnetlink.h> #include <vector> #include "test/syscalls/linux/socket_netlink_util.h" namespace gvisor { namespace testing { struct Link { int index; int16_t type; std::string name; }; PosixError DumpLinks(const FileDescriptor& fd, uint32_t seq, const std::function<void(const struct nlmsghdr* hdr)>& fn); PosixErrorOr<std::vector<Link>> DumpLinks(); // Returns the loopback link on the system. ENOENT if not found. PosixErrorOr<Link> LoopbackLink(); // LinkAddLocalAddr adds a new IFA_LOCAL address to the interface. PosixError LinkAddLocalAddr(int index, int family, int prefixlen, const void* addr, int addrlen); // LinkAddExclusiveLocalAddr adds a new IFA_LOCAL address with NLM_F_EXCL flag // to the interface. PosixError LinkAddExclusiveLocalAddr(int index, int family, int prefixlen, const void* addr, int addrlen); // LinkReplaceLocalAddr replaces an IFA_LOCAL address on the interface. PosixError LinkReplaceLocalAddr(int index, int family, int prefixlen, const void* addr, int addrlen); // LinkDelLocalAddr removes IFA_LOCAL attribute on the interface. PosixError LinkDelLocalAddr(int index, int family, int prefixlen, const void* addr, int addrlen); // LinkChangeFlags changes interface flags. E.g. IFF_UP. PosixError LinkChangeFlags(int index, unsigned int flags, unsigned int change); // LinkSetMacAddr sets IFLA_ADDRESS attribute of the interface. PosixError LinkSetMacAddr(int index, const void* addr, int addrlen); } // namespace testing } // namespace gvisor #endif // GVISOR_TEST_SYSCALLS_LINUX_SOCKET_NETLINK_ROUTE_UTIL_H_
2,479
34.942029
80
h
gvisor
gvisor-master/test/syscalls/linux/socket_netlink_util.h
// Copyright 2018 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef GVISOR_TEST_SYSCALLS_SOCKET_NETLINK_UTIL_H_ #define GVISOR_TEST_SYSCALLS_SOCKET_NETLINK_UTIL_H_ #include <sys/socket.h> // socket.h has to be included before if_arp.h. #include <linux/if_arp.h> #include <linux/netlink.h> #include <linux/rtnetlink.h> #include "test/util/file_descriptor.h" #include "test/util/posix_error.h" namespace gvisor { namespace testing { // Returns a bound netlink socket. PosixErrorOr<FileDescriptor> NetlinkBoundSocket(int protocol); // Returns the port ID of the passed socket. PosixErrorOr<uint32_t> NetlinkPortID(int fd); // Send the passed request and call fn on all response netlink messages. // // To be used on requests with NLM_F_MULTI reponses. PosixError NetlinkRequestResponse( const FileDescriptor& fd, void* request, size_t len, const std::function<void(const struct nlmsghdr* hdr)>& fn, bool expect_nlmsgerr); // Call fn on all response netlink messages. // // To be used on requests with NLM_F_MULTI reponses. PosixError NetlinkResponse( const FileDescriptor& fd, const std::function<void(const struct nlmsghdr* hdr)>& fn, bool expect_nlmsgerr); // Send the passed request and call fn on all response netlink messages. // // To be used on requests without NLM_F_MULTI reponses. PosixError NetlinkRequestResponseSingle( const FileDescriptor& fd, void* request, size_t len, const std::function<void(const struct nlmsghdr* hdr)>& fn); // Send the passed request then expect and return an ack or error. PosixError NetlinkRequestAckOrError(const FileDescriptor& fd, uint32_t seq, void* request, size_t len); // Find rtnetlink attribute in message. const struct rtattr* FindRtAttr(const struct nlmsghdr* hdr, const struct ifinfomsg* msg, int16_t attr); } // namespace testing } // namespace gvisor #endif // GVISOR_TEST_SYSCALLS_SOCKET_NETLINK_UTIL_H_
2,508
34.338028
75
h
gvisor
gvisor-master/test/syscalls/linux/socket_non_blocking.h
// Copyright 2018 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef GVISOR_TEST_SYSCALLS_LINUX_SOCKET_NON_BLOCKING_H_ #define GVISOR_TEST_SYSCALLS_LINUX_SOCKET_NON_BLOCKING_H_ #include "test/util/socket_util.h" namespace gvisor { namespace testing { // Test fixture for tests that apply to pairs of connected non-blocking sockets. using NonBlockingSocketPairTest = SocketPairTest; } // namespace testing } // namespace gvisor #endif // GVISOR_TEST_SYSCALLS_LINUX_SOCKET_NON_BLOCKING_H_
1,031
33.4
80
h
gvisor
gvisor-master/test/syscalls/linux/socket_non_stream.h
// Copyright 2018 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef GVISOR_TEST_SYSCALLS_LINUX_SOCKET_NON_STREAM_H_ #define GVISOR_TEST_SYSCALLS_LINUX_SOCKET_NON_STREAM_H_ #include "test/util/socket_util.h" namespace gvisor { namespace testing { // Test fixture for tests that apply to pairs of connected non-stream sockets. using NonStreamSocketPairTest = SocketPairTest; } // namespace testing } // namespace gvisor #endif // GVISOR_TEST_SYSCALLS_LINUX_SOCKET_NON_STREAM_H_
1,021
33.066667
78
h
gvisor
gvisor-master/test/syscalls/linux/socket_non_stream_blocking.h
// Copyright 2018 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef GVISOR_TEST_SYSCALLS_LINUX_SOCKET_NON_STREAM_BLOCKING_H_ #define GVISOR_TEST_SYSCALLS_LINUX_SOCKET_NON_STREAM_BLOCKING_H_ #include "test/util/socket_util.h" namespace gvisor { namespace testing { // Test fixture for tests that apply to pairs of blocking connected non-stream // sockets. using BlockingNonStreamSocketPairTest = SocketPairTest; } // namespace testing } // namespace gvisor #endif // GVISOR_TEST_SYSCALLS_LINUX_SOCKET_NON_STREAM_BLOCKING_H_
1,068
33.483871
78
h
gvisor
gvisor-master/test/syscalls/linux/socket_stream.h
// Copyright 2018 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef GVISOR_TEST_SYSCALLS_LINUX_SOCKET_STREAM_H_ #define GVISOR_TEST_SYSCALLS_LINUX_SOCKET_STREAM_H_ #include "test/util/socket_util.h" namespace gvisor { namespace testing { // Test fixture for tests that apply to pairs of blocking and non-blocking // connected stream sockets. using StreamSocketPairTest = SocketPairTest; } // namespace testing } // namespace gvisor #endif // GVISOR_TEST_SYSCALLS_LINUX_SOCKET_STREAM_H_
1,031
32.290323
75
h
gvisor
gvisor-master/test/syscalls/linux/socket_stream_blocking.h
// Copyright 2018 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef GVISOR_TEST_SYSCALLS_LINUX_SOCKET_STREAM_BLOCKING_H_ #define GVISOR_TEST_SYSCALLS_LINUX_SOCKET_STREAM_BLOCKING_H_ #include "test/util/socket_util.h" namespace gvisor { namespace testing { // Test fixture for tests that apply to pairs of blocking connected stream // sockets. using BlockingStreamSocketPairTest = SocketPairTest; } // namespace testing } // namespace gvisor #endif // GVISOR_TEST_SYSCALLS_LINUX_SOCKET_STREAM_BLOCKING_H_
1,049
32.870968
75
h
gvisor
gvisor-master/test/syscalls/linux/socket_stream_nonblock.h
// Copyright 2018 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef GVISOR_TEST_SYSCALLS_LINUX_SOCKET_STREAM_NONBLOCK_H_ #define GVISOR_TEST_SYSCALLS_LINUX_SOCKET_STREAM_NONBLOCK_H_ #include "test/util/socket_util.h" namespace gvisor { namespace testing { // Test fixture for tests that apply to pairs of non-blocking connected stream // sockets. using NonBlockingStreamSocketPairTest = SocketPairTest; } // namespace testing } // namespace gvisor #endif // GVISOR_TEST_SYSCALLS_LINUX_SOCKET_STREAM_NONBLOCK_H_
1,056
33.096774
78
h
gvisor
gvisor-master/test/syscalls/linux/socket_unix.h
// Copyright 2018 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef GVISOR_TEST_SYSCALLS_LINUX_SOCKET_UNIX_H_ #define GVISOR_TEST_SYSCALLS_LINUX_SOCKET_UNIX_H_ #include "test/util/socket_util.h" namespace gvisor { namespace testing { // Test fixture for tests that apply to pairs of connected unix sockets. using UnixSocketPairTest = SocketPairTest; } // namespace testing } // namespace gvisor #endif // GVISOR_TEST_SYSCALLS_LINUX_SOCKET_UNIX_H_
992
32.1
75
h
gvisor
gvisor-master/test/syscalls/linux/socket_unix_cmsg.h
// Copyright 2018 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef GVISOR_TEST_SYSCALLS_LINUX_SOCKET_UNIX_CMSG_H_ #define GVISOR_TEST_SYSCALLS_LINUX_SOCKET_UNIX_CMSG_H_ #include "test/util/socket_util.h" namespace gvisor { namespace testing { // Test fixture for tests that apply to pairs of connected unix sockets about // control messages. using UnixSocketPairCmsgTest = SocketPairTest; } // namespace testing } // namespace gvisor #endif // GVISOR_TEST_SYSCALLS_LINUX_SOCKET_UNIX_CMSG_H_
1,037
32.483871
77
h
gvisor
gvisor-master/test/syscalls/linux/socket_unix_dgram.h
// Copyright 2018 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef GVISOR_TEST_SYSCALLS_LINUX_SOCKET_UNIX_DGRAM_H_ #define GVISOR_TEST_SYSCALLS_LINUX_SOCKET_UNIX_DGRAM_H_ #include "test/util/socket_util.h" namespace gvisor { namespace testing { // Test fixture for tests that apply to pairs of connected dgram unix sockets. using DgramUnixSocketPairTest = SocketPairTest; } // namespace testing } // namespace gvisor #endif // GVISOR_TEST_SYSCALLS_LINUX_SOCKET_UNIX_DGRAM_H_
1,021
33.066667
78
h
gvisor
gvisor-master/test/syscalls/linux/socket_unix_non_stream.h
// Copyright 2018 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef GVISOR_TEST_SYSCALLS_LINUX_SOCKET_UNIX_NON_STREAM_H_ #define GVISOR_TEST_SYSCALLS_LINUX_SOCKET_UNIX_NON_STREAM_H_ #include "test/util/socket_util.h" namespace gvisor { namespace testing { // Test fixture for tests that apply to pairs of connected non-stream // unix-domain sockets. using UnixNonStreamSocketPairTest = SocketPairTest; } // namespace testing } // namespace gvisor #endif // GVISOR_TEST_SYSCALLS_LINUX_SOCKET_UNIX_NON_STREAM_H_
1,055
33.064516
75
h
gvisor
gvisor-master/test/syscalls/linux/socket_unix_seqpacket.h
// Copyright 2018 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef GVISOR_TEST_SYSCALLS_LINUX_SOCKET_UNIX_SEQPACKET_H_ #define GVISOR_TEST_SYSCALLS_LINUX_SOCKET_UNIX_SEQPACKET_H_ #include "test/util/socket_util.h" namespace gvisor { namespace testing { // Test fixture for tests that apply to pairs of connected seqpacket unix // sockets. using SeqpacketUnixSocketPairTest = SocketPairTest; } // namespace testing } // namespace gvisor #endif // GVISOR_TEST_SYSCALLS_LINUX_SOCKET_UNIX_SEQPACKET_H_
1,044
32.709677
75
h
gvisor
gvisor-master/test/syscalls/linux/unix_domain_socket_test_util.h
// Copyright 2018 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef GVISOR_TEST_SYSCALLS_UNIX_DOMAIN_SOCKET_TEST_UTIL_H_ #define GVISOR_TEST_SYSCALLS_UNIX_DOMAIN_SOCKET_TEST_UTIL_H_ #include <string> #include "test/util/socket_util.h" namespace gvisor { namespace testing { // DescribeUnixDomainSocketType returns a human-readable string explaining the // given Unix domain socket type. std::string DescribeUnixDomainSocketType(int type); // UnixDomainSocketPair returns a SocketPairKind that represents SocketPairs // created by invoking the socketpair() syscall with AF_UNIX and the given type. SocketPairKind UnixDomainSocketPair(int type); // FilesystemBoundUnixDomainSocketPair returns a SocketPairKind that represents // SocketPairs created with bind() and accept() syscalls with a temp file path, // AF_UNIX and the given type. SocketPairKind FilesystemBoundUnixDomainSocketPair(int type); // AbstractBoundUnixDomainSocketPair returns a SocketPairKind that represents // SocketPairs created with bind() and accept() syscalls with a temp abstract // path, AF_UNIX and the given type. SocketPairKind AbstractBoundUnixDomainSocketPair(int type); // SocketpairGoferUnixDomainSocketPair returns a SocketPairKind that was created // with two sockets connected to the socketpair gofer. SocketPairKind SocketpairGoferUnixDomainSocketPair(int type); // SocketpairGoferFileSocketPair returns a SocketPairKind that was created with // two open() calls on paths backed by the socketpair gofer. SocketPairKind SocketpairGoferFileSocketPair(int type); // FilesystemUnboundUnixDomainSocketPair returns a SocketPairKind that // represents two unbound sockets and a filesystem path for binding. SocketPairKind FilesystemUnboundUnixDomainSocketPair(int type); // AbstractUnboundUnixDomainSocketPair returns a SocketPairKind that represents // two unbound sockets and an abstract namespace path for binding. SocketPairKind AbstractUnboundUnixDomainSocketPair(int type); // SendSingleFD sends both a single FD and some data over a unix domain socket // specified by an FD. Note that calls to this function must be wrapped in // ASSERT_NO_FATAL_FAILURE for internal assertions to halt the test. void SendSingleFD(int sock, int fd, char buf[], int buf_size); // SendFDs sends an arbitrary number of FDs and some data over a unix domain // socket specified by an FD. Note that calls to this function must be wrapped // in ASSERT_NO_FATAL_FAILURE for internal assertions to halt the test. void SendFDs(int sock, int fds[], int fds_size, char buf[], int buf_size); // RecvSingleFD receives both a single FD and some data over a unix domain // socket specified by an FD. Note that calls to this function must be wrapped // in ASSERT_NO_FATAL_FAILURE for internal assertions to halt the test. void RecvSingleFD(int sock, int* fd, char buf[], int buf_size); // RecvSingleFD receives both a single FD and some data over a unix domain // socket specified by an FD. This version allows the expected amount of data // received to be different than the buffer size. Note that calls to this // function must be wrapped in ASSERT_NO_FATAL_FAILURE for internal assertions // to halt the test. void RecvSingleFD(int sock, int* fd, char buf[], int buf_size, int expected_size); // PeekSingleFD peeks at both a single FD and some data over a unix domain // socket specified by an FD. Note that calls to this function must be wrapped // in ASSERT_NO_FATAL_FAILURE for internal assertions to halt the test. void PeekSingleFD(int sock, int* fd, char buf[], int buf_size); // RecvFDs receives both an arbitrary number of FDs and some data over a unix // domain socket specified by an FD. Note that calls to this function must be // wrapped in ASSERT_NO_FATAL_FAILURE for internal assertions to halt the test. void RecvFDs(int sock, int fds[], int fds_size, char buf[], int buf_size); // RecvFDs receives both an arbitrary number of FDs and some data over a unix // domain socket specified by an FD. This version allows the expected amount of // data received to be different than the buffer size. Note that calls to this // function must be wrapped in ASSERT_NO_FATAL_FAILURE for internal assertions // to halt the test. void RecvFDs(int sock, int fds[], int fds_size, char buf[], int buf_size, int expected_size); // RecvNoCmsg receives some data over a unix domain socket specified by an FD // and asserts that no control messages are available for receiving. Note that // calls to this function must be wrapped in ASSERT_NO_FATAL_FAILURE for // internal assertions to halt the test. void RecvNoCmsg(int sock, char buf[], int buf_size, int expected_size); inline void RecvNoCmsg(int sock, char buf[], int buf_size) { RecvNoCmsg(sock, buf, buf_size, buf_size); } // SendCreds sends the credentials of the current process and some data over a // unix domain socket specified by an FD. Note that calls to this function must // be wrapped in ASSERT_NO_FATAL_FAILURE for internal assertions to halt the // test. void SendCreds(int sock, ucred creds, char buf[], int buf_size); // SendCredsAndFD sends the credentials of the current process, a single FD, and // some data over a unix domain socket specified by an FD. Note that calls to // this function must be wrapped in ASSERT_NO_FATAL_FAILURE for internal // assertions to halt the test. void SendCredsAndFD(int sock, ucred creds, int fd, char buf[], int buf_size); // RecvCreds receives some credentials and some data over a unix domain socket // specified by an FD. Note that calls to this function must be wrapped in // ASSERT_NO_FATAL_FAILURE for internal assertions to halt the test. void RecvCreds(int sock, ucred* creds, char buf[], int buf_size); // RecvCreds receives some credentials and some data over a unix domain socket // specified by an FD. This version allows the expected amount of data received // to be different than the buffer size. Note that calls to this function must // be wrapped in ASSERT_NO_FATAL_FAILURE for internal assertions to halt the // test. void RecvCreds(int sock, ucred* creds, char buf[], int buf_size, int expected_size); // RecvCredsAndFD receives some credentials, a single FD, and some data over a // unix domain socket specified by an FD. Note that calls to this function must // be wrapped in ASSERT_NO_FATAL_FAILURE for internal assertions to halt the // test. void RecvCredsAndFD(int sock, ucred* creds, int* fd, char buf[], int buf_size); // SendNullCmsg sends a null control message and some data over a unix domain // socket specified by an FD. Note that calls to this function must be wrapped // in ASSERT_NO_FATAL_FAILURE for internal assertions to halt the test. void SendNullCmsg(int sock, char buf[], int buf_size); // RecvSingleFDUnaligned sends both a single FD and some data over a unix domain // socket specified by an FD. This function does not obey the spec, but Linux // allows it and the apphosting code depends on this quirk. Note that calls to // this function must be wrapped in ASSERT_NO_FATAL_FAILURE for internal // assertions to halt the test. void RecvSingleFDUnaligned(int sock, int* fd, char buf[], int buf_size); // SetSoPassCred sets the SO_PASSCRED option on the specified socket. void SetSoPassCred(int sock); // UnsetSoPassCred clears the SO_PASSCRED option on the specified socket. void UnsetSoPassCred(int sock); } // namespace testing } // namespace gvisor #endif // GVISOR_TEST_SYSCALLS_UNIX_DOMAIN_SOCKET_TEST_UTIL_H_
8,036
48.306748
80
h
gvisor
gvisor-master/test/syscalls/linux/rseq/critical.h
// Copyright 2019 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef GVISOR_TEST_SYSCALLS_LINUX_RSEQ_CRITICAL_H_ #define GVISOR_TEST_SYSCALLS_LINUX_RSEQ_CRITICAL_H_ #include "test/syscalls/linux/rseq/types.h" #include "test/syscalls/linux/rseq/uapi.h" constexpr uint32_t kRseqSignature = 0x90909090; extern "C" { extern void rseq_loop(struct rseq* r, struct rseq_cs* cs); extern void* rseq_loop_early_abort; extern void* rseq_loop_start; extern void* rseq_loop_pre_commit; extern void* rseq_loop_post_commit; extern void* rseq_loop_abort; extern int rseq_getpid(struct rseq* r, struct rseq_cs* cs); extern void* rseq_getpid_start; extern void* rseq_getpid_post_commit; extern void* rseq_getpid_abort; } // extern "C" #endif // GVISOR_TEST_SYSCALLS_LINUX_RSEQ_CRITICAL_H_
1,316
31.925
75
h
gvisor
gvisor-master/test/syscalls/linux/rseq/syscalls.h
// Copyright 2019 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef GVISOR_TEST_SYSCALLS_LINUX_RSEQ_SYSCALLS_H_ #define GVISOR_TEST_SYSCALLS_LINUX_RSEQ_SYSCALLS_H_ #include "test/syscalls/linux/rseq/types.h" // Syscall numbers. #if defined(__x86_64__) constexpr int kGetpid = 39; constexpr int kExitGroup = 231; #elif defined(__aarch64__) constexpr int kGetpid = 172; constexpr int kExitGroup = 94; #else #error "Unknown architecture" #endif namespace gvisor { namespace testing { // Standalone system call interfaces. // Note that these are all "raw" system call interfaces which encode // errors by setting the return value to a small negative number. // Use sys_errno() to check system call return values for errors. // Maximum Linux error number. constexpr int kMaxErrno = 4095; // Errno values. #define EPERM 1 #define EFAULT 14 #define EBUSY 16 #define EINVAL 22 // Get the error number from a raw system call return value. // Returns a positive error number or 0 if there was no error. static inline int sys_errno(uintptr_t rval) { if (rval >= static_cast<uintptr_t>(-kMaxErrno)) { return -static_cast<int>(rval); } return 0; } extern "C" uintptr_t raw_syscall(int number, ...); static inline void sys_exit_group(int status) { raw_syscall(kExitGroup, status); } static inline int sys_getpid() { return static_cast<int>(raw_syscall(kGetpid)); } } // namespace testing } // namespace gvisor #endif // GVISOR_TEST_SYSCALLS_LINUX_RSEQ_SYSCALLS_H_
2,015
27.8
75
h
gvisor
gvisor-master/test/syscalls/linux/rseq/test.h
// Copyright 2019 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef GVISOR_TEST_SYSCALLS_LINUX_RSEQ_TEST_H_ #define GVISOR_TEST_SYSCALLS_LINUX_RSEQ_TEST_H_ namespace gvisor { namespace testing { // Test cases supported by rseq binary. constexpr char kRseqTestUnaligned[] = "unaligned"; constexpr char kRseqTestRegister[] = "register"; constexpr char kRseqTestDoubleRegister[] = "double-register"; constexpr char kRseqTestRegisterUnregister[] = "register-unregister"; constexpr char kRseqTestUnregisterDifferentPtr[] = "unregister-different-ptr"; constexpr char kRseqTestUnregisterDifferentSignature[] = "unregister-different-signature"; constexpr char kRseqTestCPU[] = "cpu"; constexpr char kRseqTestAbort[] = "abort"; constexpr char kRseqTestAbortBefore[] = "abort-before"; constexpr char kRseqTestAbortSignature[] = "abort-signature"; constexpr char kRseqTestAbortPreCommit[] = "abort-precommit"; constexpr char kRseqTestAbortClearsCS[] = "abort-clears-cs"; constexpr char kRseqTestInvalidAbortClearsCS[] = "invalid-abort-clears-cs"; } // namespace testing } // namespace gvisor #endif // GVISOR_TEST_SYSCALLS_LINUX_RSEQ_TEST_H_
1,680
39.02381
78
h
gvisor
gvisor-master/test/syscalls/linux/rseq/types.h
// Copyright 2019 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef GVISOR_TEST_SYSCALLS_LINUX_RSEQ_TYPES_H_ #define GVISOR_TEST_SYSCALLS_LINUX_RSEQ_TYPES_H_ using size_t = __SIZE_TYPE__; using uintptr_t = __UINTPTR_TYPE__; using uint8_t = __UINT8_TYPE__; using uint16_t = __UINT16_TYPE__; using uint32_t = __UINT32_TYPE__; using uint64_t = __UINT64_TYPE__; using int8_t = __INT8_TYPE__; using int16_t = __INT16_TYPE__; using int32_t = __INT32_TYPE__; using int64_t = __INT64_TYPE__; #endif // GVISOR_TEST_SYSCALLS_LINUX_RSEQ_TYPES_H_
1,077
32.6875
75
h
gvisor
gvisor-master/test/syscalls/linux/rseq/uapi.h
// Copyright 2019 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef GVISOR_TEST_SYSCALLS_LINUX_RSEQ_UAPI_H_ #define GVISOR_TEST_SYSCALLS_LINUX_RSEQ_UAPI_H_ #include <stdint.h> // User-kernel ABI for restartable sequences. // Syscall numbers. #if defined(__x86_64__) constexpr int kRseqSyscall = 334; #elif defined(__aarch64__) constexpr int kRseqSyscall = 293; #else #error "Unknown architecture" #endif // __x86_64__ struct rseq_cs { uint32_t version; uint32_t flags; uint64_t start_ip; uint64_t post_commit_offset; uint64_t abort_ip; } __attribute__((aligned(4 * sizeof(uint64_t)))); // N.B. alignment is enforced by the kernel. struct rseq { uint32_t cpu_id_start; uint32_t cpu_id; struct rseq_cs* rseq_cs; uint32_t flags; } __attribute__((aligned(4 * sizeof(uint64_t)))); constexpr int kRseqFlagUnregister = 1 << 0; constexpr int kRseqCPUIDUninitialized = -1; #endif // GVISOR_TEST_SYSCALLS_LINUX_RSEQ_UAPI_H_
1,479
27.461538
75
h
gvisor
gvisor-master/test/util/capability_util.h
// Copyright 2018 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Utilities for testing capabilities. #ifndef GVISOR_TEST_UTIL_CAPABILITY_UTIL_H_ #define GVISOR_TEST_UTIL_CAPABILITY_UTIL_H_ #include "test/util/posix_error.h" #if defined(__Fuchsia__) // Nothing to include. #elif defined(__linux__) #include "test/util/linux_capability_util.h" #else #error "Unhandled platform" #endif namespace gvisor { namespace testing { // HaveRawIPSocketCapability returns whether or not the process has access to // raw IP sockets. // // Returns an error when raw IP socket access cannot be determined. PosixErrorOr<bool> HaveRawIPSocketCapability(); // HavePacketSocketCapability returns whether or not the process has access to // packet sockets. // // Returns an error when packet socket access cannot be determined. PosixErrorOr<bool> HavePacketSocketCapability(); } // namespace testing } // namespace gvisor #endif // GVISOR_TEST_UTIL_CAPABILITY_UTIL_H_
1,493
29.489796
78
h
gvisor
gvisor-master/test/util/cgroup_util.h
// Copyright 2021 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef GVISOR_TEST_UTIL_CGROUP_UTIL_H_ #define GVISOR_TEST_UTIL_CGROUP_UTIL_H_ #include <unistd.h> #include "absl/container/flat_hash_map.h" #include "absl/container/flat_hash_set.h" #include "absl/strings/string_view.h" #include "test/util/cleanup.h" #include "test/util/fs_util.h" #include "test/util/temp_path.h" namespace gvisor { namespace testing { // Cgroup represents a cgroup directory on a mounted cgroupfs. class Cgroup { public: static Cgroup RootCgroup(absl::string_view path) { return Cgroup(path, path); } uint64_t id() const { return id_; } // Deletes the current cgroup represented by this object. PosixError Delete(); const std::string& Path() const { return cgroup_path_; } // Returns the canonical path for this cgroup, which is the absolute path // starting at the hierarchy root. const std::string CanonicalPath() const { std::string relpath = GetRelativePath(mountpoint_, cgroup_path_).ValueOrDie(); if (relpath == ".") { return "/"; } return "/" + relpath; } // Creates a child cgroup under this cgroup with the given name. PosixErrorOr<Cgroup> CreateChild(std::string_view name) const; std::string Relpath(absl::string_view leaf) const { return JoinPath(cgroup_path_, leaf); } // Returns the contents of a cgroup control file with the given name. PosixErrorOr<std::string> ReadControlFile(absl::string_view name) const; // Reads the contents of a cgroup control with the given name, and attempts // to parse it as an integer. PosixErrorOr<int64_t> ReadIntegerControlFile(absl::string_view name) const; // Writes a string to a cgroup control file. PosixError WriteControlFile(absl::string_view name, const std::string& value) const; // Writes an integer value to a cgroup control file. PosixError WriteIntegerControlFile(absl::string_view name, int64_t value) const; // Waits for a control file's value to change. PosixError PollControlFileForChange(absl::string_view name, absl::Duration timeout) const; // Waits for a control file's value to change after calling body. PosixError PollControlFileForChangeAfter(absl::string_view name, absl::Duration timeout, std::function<void()> body) const; // Returns the thread ids of the leaders of thread groups managed by this // cgroup. PosixErrorOr<absl::flat_hash_set<pid_t>> Procs() const; PosixErrorOr<absl::flat_hash_set<pid_t>> Tasks() const; // ContainsCallingProcess checks whether the calling process is part of the // cgroup. PosixError ContainsCallingProcess() const; // ContainsCallingThread checks whether the calling thread is part of the // cgroup. PosixError ContainsCallingThread() const; // Moves process with the specified pid to this cgroup. PosixError Enter(pid_t pid) const; // Moves thread with the specified pid to this cgroup. PosixError EnterThread(pid_t pid) const; private: Cgroup(std::string_view path, std::string_view mountpoint); PosixErrorOr<absl::flat_hash_set<pid_t>> ParsePIDList( absl::string_view data) const; static int64_t next_id_; int64_t id_; const std::string cgroup_path_; const std::string mountpoint_; }; // Mounter is a utility for creating cgroupfs mounts. It automatically manages // the lifetime of created mounts. class Mounter { public: Mounter(TempPath root) : root_(std::move(root)) {} PosixErrorOr<Cgroup> MountCgroupfs(std::string mopts); PosixError Unmount(const Cgroup& c); void release(const Cgroup& c); private: // The destruction order of these members avoids errors during cleanup. We // first unmount (by executing the mounts_ cleanups), then delete the // mountpoint subdirs, then delete the root. TempPath root_; absl::flat_hash_map<int64_t, TempPath> mountpoints_; absl::flat_hash_map<int64_t, Cleanup> mounts_; }; // Represents a line from /proc/cgroups. struct CgroupsEntry { std::string subsys_name; uint32_t hierarchy; uint64_t num_cgroups; bool enabled; }; // Returns a parsed representation of /proc/cgroups. PosixErrorOr<absl::flat_hash_map<std::string, CgroupsEntry>> ProcCgroupsEntries(); // Represents a line from /proc/<pid>/cgroup. struct PIDCgroupEntry { uint32_t hierarchy; std::string controllers; std::string path; }; // Returns a parsed representation of /proc/<pid>/cgroup. PosixErrorOr<absl::flat_hash_map<std::string, PIDCgroupEntry>> ProcPIDCgroupEntries(pid_t pid); } // namespace testing } // namespace gvisor #endif // GVISOR_TEST_UTIL_CGROUP_UTIL_H_
5,313
31.012048
78
h
gvisor
gvisor-master/test/util/cleanup.h
// Copyright 2018 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef GVISOR_TEST_UTIL_CLEANUP_H_ #define GVISOR_TEST_UTIL_CLEANUP_H_ #include <functional> #include <utility> namespace gvisor { namespace testing { class Cleanup { public: Cleanup() : released_(true) {} explicit Cleanup(std::function<void()>&& callback) : cb_(callback) {} Cleanup(Cleanup&& other) { released_ = other.released_; cb_ = other.Release(); } Cleanup& operator=(Cleanup&& other) { released_ = other.released_; cb_ = other.Release(); return *this; } ~Cleanup() { if (!released_) { cb_(); } } std::function<void()>&& Release() { released_ = true; return std::move(cb_); } private: Cleanup(Cleanup const& other) = delete; bool released_ = false; std::function<void(void)> cb_; }; } // namespace testing } // namespace gvisor #endif // GVISOR_TEST_UTIL_CLEANUP_H_
1,456
22.5
75
h
gvisor
gvisor-master/test/util/epoll_util.h
// Copyright 2018 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef GVISOR_TEST_UTIL_EPOLL_UTIL_H_ #define GVISOR_TEST_UTIL_EPOLL_UTIL_H_ #include "test/util/file_descriptor.h" #include "test/util/posix_error.h" namespace gvisor { namespace testing { // Returns a new epoll file descriptor. PosixErrorOr<FileDescriptor> NewEpollFD(int size = 1); // Registers `target_fd` with the epoll instance represented by `epoll_fd` for // the epoll events `events`. Events on `target_fd` will be indicated by setting // data.u64 to `data` in the returned epoll_event. PosixError RegisterEpollFD(int epoll_fd, int target_fd, int events, uint64_t data); } // namespace testing } // namespace gvisor #endif // GVISOR_TEST_UTIL_EPOLL_UTIL_H_
1,300
34.162162
80
h
gvisor
gvisor-master/test/util/eventfd_util.h
// Copyright 2019 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef GVISOR_TEST_UTIL_EVENTFD_UTIL_H_ #define GVISOR_TEST_UTIL_EVENTFD_UTIL_H_ #include <asm/unistd.h> #include <sys/eventfd.h> #include <cerrno> #include "test/util/file_descriptor.h" #include "test/util/posix_error.h" #include "test/util/save_util.h" namespace gvisor { namespace testing { // Returns a new eventfd with the given initial value and flags. inline PosixErrorOr<FileDescriptor> NewEventFD(unsigned int initval = 0, int flags = 0) { int fd = eventfd(initval, flags); MaybeSave(); if (fd < 0) { return PosixError(errno, "eventfd"); } return FileDescriptor(fd); } // This is a wrapper for the eventfd2(2) system call. inline int Eventdfd2Setup(unsigned int initval, int flags) { return syscall(__NR_eventfd2, initval, flags); } } // namespace testing } // namespace gvisor #endif // GVISOR_TEST_UTIL_EVENTFD_UTIL_H_
1,501
29.653061
75
h
gvisor
gvisor-master/test/util/file_descriptor.h
// Copyright 2018 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef GVISOR_TEST_UTIL_FILE_DESCRIPTOR_H_ #define GVISOR_TEST_UTIL_FILE_DESCRIPTOR_H_ #include <fcntl.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include <algorithm> #include <string> #include "gmock/gmock.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_format.h" #include "test/util/logging.h" #include "test/util/posix_error.h" #include "test/util/save_util.h" namespace gvisor { namespace testing { // FileDescriptor is an RAII type class which takes ownership of a file // descriptor. It will close the FD when this object goes out of scope. class FileDescriptor { public: // Constructs an empty FileDescriptor (one that does not own a file // descriptor). FileDescriptor() = default; // Constructs a FileDescriptor that owns fd. If fd is negative, constructs an // empty FileDescriptor. explicit FileDescriptor(int fd) { set_fd(fd); } FileDescriptor(FileDescriptor&& orig) : fd_(orig.release()) {} FileDescriptor& operator=(FileDescriptor&& orig) { reset(orig.release()); return *this; } PosixErrorOr<FileDescriptor> Dup() const { if (fd_ < 0) { return PosixError(EINVAL, "Attempting to Dup unset fd"); } int fd = dup(fd_); if (fd < 0) { return PosixError(errno, absl::StrCat("dup ", fd_)); } MaybeSave(); return FileDescriptor(fd); } FileDescriptor(FileDescriptor const& other) = delete; FileDescriptor& operator=(FileDescriptor const& other) = delete; ~FileDescriptor() { reset(); } // If this object is non-empty, returns the owned file descriptor. (Ownership // is retained by the FileDescriptor.) Otherwise returns -1. int get() const { return fd_; } // If this object is non-empty, transfers ownership of the file descriptor to // the caller and returns it. Otherwise returns -1. int release() { int const fd = fd_; fd_ = -1; return fd; } // If this object is non-empty, closes the owned file descriptor (recording a // test failure if the close fails). void reset() { reset(-1); } // Like no-arg reset(), but the FileDescriptor takes ownership of fd after // closing its existing file descriptor. void reset(int fd) { if (fd_ >= 0) { TEST_PCHECK(close(fd_) == 0); MaybeSave(); } set_fd(fd); } private: // Wrapper that coerces negative fd values other than -1 to -1 so that get() // etc. return -1. void set_fd(int fd) { fd_ = std::max(fd, -1); } int fd_ = -1; }; // Wrapper around open(2) that returns a FileDescriptor. inline PosixErrorOr<FileDescriptor> Open(std::string const& path, int flags, mode_t mode = 0) { int fd = open(path.c_str(), flags, mode); if (fd < 0) { return PosixError(errno, absl::StrFormat("open(%s, %#x, %#o)", path.c_str(), flags, mode)); } MaybeSave(); return FileDescriptor(fd); } // Wrapper around openat(2) that returns a FileDescriptor. inline PosixErrorOr<FileDescriptor> OpenAt(int dirfd, std::string const& path, int flags, mode_t mode = 0) { int fd = openat(dirfd, path.c_str(), flags, mode); if (fd < 0) { return PosixError(errno, absl::StrFormat("openat(%d, %s, %#x, %#o)", dirfd, path, flags, mode)); } MaybeSave(); return FileDescriptor(fd); } } // namespace testing } // namespace gvisor #endif // GVISOR_TEST_UTIL_FILE_DESCRIPTOR_H_
4,102
29.392593
80
h
gvisor
gvisor-master/test/util/fs_util.h
// Copyright 2018 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef GVISOR_TEST_UTIL_FS_UTIL_H_ #define GVISOR_TEST_UTIL_FS_UTIL_H_ #include <dirent.h> #include <sys/stat.h> #include <sys/statfs.h> #include <sys/types.h> #include <unistd.h> #include "absl/strings/string_view.h" #include "test/util/file_descriptor.h" #include "test/util/posix_error.h" namespace gvisor { namespace testing { // O_LARGEFILE as defined by Linux. glibc tries to be clever by setting it to 0 // because "it isn't needed", even though Linux can return it via F_GETFL. #if defined(__x86_64__) || defined(__riscv) constexpr int kOLargeFile = 00100000; #elif defined(__aarch64__) constexpr int kOLargeFile = 00400000; #else #error "Unknown architecture" #endif // From linux/magic.h. For some reason, not defined in the headers for some // build environments. #define OVERLAYFS_SUPER_MAGIC 0x794c7630 // Returns a status or the current working directory. PosixErrorOr<std::string> GetCWD(); // Returns true/false depending on whether or not path exists, or an error if it // can't be determined. PosixErrorOr<bool> Exists(absl::string_view path); // Returns a stat structure for the given path or an error. If the path // represents a symlink, it will be traversed. PosixErrorOr<struct stat> Stat(absl::string_view path); // Returns a stat structure for the given path or an error. If the path // represents a symlink, it will not be traversed. PosixErrorOr<struct stat> Lstat(absl::string_view path); // Returns a stat struct for the given fd. PosixErrorOr<struct stat> Fstat(int fd); // Deletes the file or directory at path or returns an error. PosixError Delete(absl::string_view path); // Changes the mode of a file or returns an error. PosixError Chmod(absl::string_view path, int mode); // Create a special or ordinary file. PosixError MknodAt(const FileDescriptor& dfd, absl::string_view path, int mode, dev_t dev); // Unlink the file. PosixError Unlink(absl::string_view path); PosixError UnlinkAt(const FileDescriptor& dfd, absl::string_view path, int flags); // Truncates a file to the given length or returns an error. PosixError Truncate(absl::string_view path, int length); // Returns true/false depending on whether or not the path is a directory or // returns an error. PosixErrorOr<bool> IsDirectory(absl::string_view path); // Makes a directory or returns an error. PosixError Mkdir(absl::string_view path, int mode = 0755); // Removes a directory or returns an error. PosixError Rmdir(absl::string_view path); // Attempts to set the contents of a file or returns an error. PosixError SetContents(absl::string_view path, absl::string_view contents); // Creates a file with the given contents and mode or returns an error. PosixError CreateWithContents(absl::string_view path, absl::string_view contents, int mode = 0666); // Attempts to read the entire contents of the file into the provided string // buffer or returns an error. PosixError GetContents(absl::string_view path, std::string* output); // Attempts to read the entire contents of the file or returns an error. PosixErrorOr<std::string> GetContents(absl::string_view path); // Attempts to read the entire contents of the provided fd into the provided // string or returns an error. PosixError GetContentsFD(int fd, std::string* output); // Attempts to read the entire contents of the provided fd or returns an error. PosixErrorOr<std::string> GetContentsFD(int fd); // Executes the readlink(2) system call or returns an error. PosixErrorOr<std::string> ReadLink(absl::string_view path); // WalkTree will walk a directory tree in a depth first search manner (if // recursive). It will invoke a provided callback for each file and directory, // the parent will always be invoked last making this appropriate for things // such as deleting an entire directory tree. // // This method will return an error when it's unable to access the provided // path, or when the path is not a directory. PosixError WalkTree( absl::string_view path, bool recursive, const std::function<void(absl::string_view, const struct stat&)>& cb); // Returns the base filenames for all files under a given absolute path. If // skipdots is true the returned vector will not contain "." or "..". This // method does not walk the tree recursively it only returns the elements // in that directory. PosixErrorOr<std::vector<std::string>> ListDir(absl::string_view abspath, bool skipdots); // Check that a directory contains children nodes named in expect, and does not // contain any children nodes named in exclude. PosixError DirContains(absl::string_view path, const std::vector<std::string>& expect, const std::vector<std::string>& exclude); // Same as DirContains, but adds a retry. Suitable for checking a directory // being modified asynchronously. PosixError EventuallyDirContains(absl::string_view path, const std::vector<std::string>& expect, const std::vector<std::string>& exclude); // Attempt to recursively delete a directory or file. Returns an error and // the number of undeleted directories and files. If either // undeleted_dirs or undeleted_files is nullptr then it will not be used. PosixError RecursivelyDelete(absl::string_view path, int* undeleted_dirs, int* undeleted_files); // Recursively create the directory provided or return an error. PosixError RecursivelyCreateDir(absl::string_view path); // Makes a path absolute with respect to an optional base. If no base is // provided it will use the current working directory. PosixErrorOr<std::string> MakeAbsolute(absl::string_view filename, absl::string_view base); // Generates a relative path from the source directory to the destination // (dest) file or directory. This uses ../ when necessary for destinations // which are not nested within the source. Both source and dest are required // to be absolute paths, and an empty string will be returned if they are not. PosixErrorOr<std::string> GetRelativePath(absl::string_view source, absl::string_view dest); // Returns the part of the path before the final "/", EXCEPT: // * If there is a single leading "/" in the path, the result will be the // leading "/". // * If there is no "/" in the path, the result is the empty prefix of the // input string. absl::string_view Dirname(absl::string_view path); // Return the parts of the path, split on the final "/". If there is no // "/" in the path, the first part of the output is empty and the second // is the input. If the only "/" in the path is the first character, it is // the first part of the output. std::pair<absl::string_view, absl::string_view> SplitPath( absl::string_view path); // Returns the part of the path after the final "/". If there is no // "/" in the path, the result is the same as the input. // Note that this function's behavior differs from the Unix basename // command if path ends with "/". For such paths, this function returns the // empty string. absl::string_view Basename(absl::string_view path); // Collapse duplicate "/"s, resolve ".." and "." path elements, remove // trailing "/". // // NOTE: This respects relative vs. absolute paths, but does not // invoke any system calls (getcwd(2)) in order to resolve relative // paths wrt actual working directory. That is, this is purely a // string manipulation, completely independent of process state. std::string CleanPath(absl::string_view path); // Returns the full path to the executable of the given pid or a PosixError. PosixErrorOr<std::string> ProcessExePath(int pid); #ifdef __linux__ // IsTmpfs returns true if the file at path is backed by tmpfs. PosixErrorOr<bool> IsTmpfs(const std::string& path); #endif // __linux__ // IsOverlayfs returns true if the file at path is backed by overlayfs. PosixErrorOr<bool> IsOverlayfs(const std::string& path); PosixError CheckSameFile(const FileDescriptor& fd1, const FileDescriptor& fd2); namespace internal { // Not part of the public API. std::string JoinPathImpl(std::initializer_list<absl::string_view> paths); } // namespace internal // Join multiple paths together. // All paths will be treated as relative paths, regardless of whether or not // they start with a leading '/'. That is, all paths will be concatenated // together, with the appropriate path separator inserted in between. // Arguments must be convertible to absl::string_view. // // Usage: // std::string path = JoinPath("/foo", dirname, filename); // std::string path = JoinPath(FLAGS_test_srcdir, filename); // // 0, 1, 2-path specializations exist to optimize common cases. inline std::string JoinPath() { return std::string(); } inline std::string JoinPath(absl::string_view path) { return std::string(path.data(), path.size()); } std::string JoinPath(absl::string_view path1, absl::string_view path2); template <typename... T> inline std::string JoinPath(absl::string_view path1, absl::string_view path2, absl::string_view path3, const T&... args) { return internal::JoinPathImpl({path1, path2, path3, args...}); } // A matcher which checks whether the file permissions bits for a mode value // matches an expected value. class ModePermissionMatcher : public ::testing::MatcherInterface<mode_t> { public: explicit ModePermissionMatcher(mode_t want) : want_(want) {} bool MatchAndExplain( mode_t got, ::testing::MatchResultListener* const listener) const override { const mode_t masked = got & (S_IRWXU | S_IRWXG | S_IRWXO); if (masked == want_) { return true; } *listener << "Permission 0" << std::oct << masked; return false; } void DescribeTo(std::ostream* const os) const override { *os << "File permission is 0" << std::oct << want_; } void DescribeNegationTo(std::ostream* const os) const override { *os << "File permission is not 0" << std::oct << want_; } private: mode_t want_; }; ::testing::Matcher<mode_t> PermissionIs(mode_t want); } // namespace testing } // namespace gvisor #endif // GVISOR_TEST_UTIL_FS_UTIL_H_
10,888
39.180812
80
h
gvisor
gvisor-master/test/util/fuse_util.h
// Copyright 2020 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef GVISOR_TEST_UTIL_FUSE_UTIL_H_ #define GVISOR_TEST_UTIL_FUSE_UTIL_H_ #include <linux/fuse.h> #include <sys/uio.h> #include <string> #include <vector> namespace gvisor { namespace testing { // The fundamental generation function with a single argument. If passed by // std::string or std::vector<char>, it will call specialized versions as // implemented below. template <typename T> std::vector<struct iovec> FuseGenerateIovecs(T &first) { return {(struct iovec){.iov_base = &first, .iov_len = sizeof(first)}}; } // If an argument is of type std::string, it must be used in read-only scenario. // Because we are setting up iovec, which contains the original address of a // data structure, we have to drop const qualification. Usually used with // variable-length payload data. template <typename T = std::string> std::vector<struct iovec> FuseGenerateIovecs(std::string &first) { // Pad one byte for null-terminate c-string. return {(struct iovec){.iov_base = const_cast<char *>(first.c_str()), .iov_len = first.size() + 1}}; } // If an argument is of type std::vector<char>, it must be used in write-only // scenario and the size of the variable must be greater than or equal to the // size of the expected data. Usually used with variable-length payload data. template <typename T = std::vector<char>> std::vector<struct iovec> FuseGenerateIovecs(std::vector<char> &first) { return {(struct iovec){.iov_base = first.data(), .iov_len = first.size()}}; } // A helper function to set up an array of iovec struct for testing purpose. // Use variadic class template to generalize different numbers and different // types of FUSE structs. template <typename T, typename... Types> std::vector<struct iovec> FuseGenerateIovecs(T &first, Types &...args) { auto first_iovec = FuseGenerateIovecs(first); auto iovecs = FuseGenerateIovecs(args...); first_iovec.insert(std::end(first_iovec), std::begin(iovecs), std::end(iovecs)); return first_iovec; } // Create a fuse_attr filled with the specified mode and inode. fuse_attr DefaultFuseAttr(mode_t mode, uint64_t inode, uint64_t size = 512); // Return a fuse_entry_out FUSE server response body. fuse_entry_out DefaultEntryOut(mode_t mode, uint64_t node_id, uint64_t size = 512); } // namespace testing } // namespace gvisor #endif // GVISOR_TEST_UTIL_FUSE_UTIL_H_
3,016
38.697368
80
h
gvisor
gvisor-master/test/util/io_uring_util.h
// Copyright 2022 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef GVISOR_TEST_UTIL_IOURING_UTIL_H_ #define GVISOR_TEST_UTIL_IOURING_UTIL_H_ #include <linux/fs.h> #include <sys/ioctl.h> #include <sys/mman.h> #include <atomic> #include <cerrno> #include <cstdint> #include "test/util/file_descriptor.h" #include "test/util/posix_error.h" #include "test/util/save_util.h" namespace gvisor { namespace testing { #define __NR_io_uring_setup 425 #define __NR_io_uring_enter 426 // io_uring_setup(2) flags. #define IORING_SETUP_SQPOLL (1U << 1) #define IORING_SETUP_CQSIZE (1U << 3) // io_uring_enter(2) flags #define IORING_ENTER_GETEVENTS (1U << 0) #define IORING_FEAT_SINGLE_MMAP (1U << 0) #define IORING_OFF_SQ_RING 0ULL #define IORING_OFF_CQ_RING 0x8000000ULL #define IORING_OFF_SQES 0x10000000ULL // IO_URING operation codes. #define IORING_OP_NOP 0 #define IORING_OP_READV 1 #define BLOCK_SZ kPageSize struct io_sqring_offsets { uint32_t head; uint32_t tail; uint32_t ring_mask; uint32_t ring_entries; uint32_t flags; uint32_t dropped; uint32_t array; uint32_t resv1; uint64_t resv2; }; struct io_cqring_offsets { uint32_t head; uint32_t tail; uint32_t ring_mask; uint32_t ring_entries; uint32_t overflow; uint32_t cqes; uint32_t flags; uint32_t resv1; uint64_t resv2; }; struct io_uring_params { uint32_t sq_entries; uint32_t cq_entries; uint32_t flags; uint32_t sq_thread_cpu; uint32_t sq_thread_idle; uint32_t features; uint32_t wq_fd; uint32_t resv[3]; struct io_sqring_offsets sq_off; struct io_cqring_offsets cq_off; }; struct io_uring_cqe { uint64_t user_data; int32_t res; uint32_t flags; }; struct io_uring_sqe { uint8_t opcode; uint8_t flags; uint16_t ioprio; int32_t fd; union { uint64_t off; uint64_t addr2; struct { uint32_t cmd_op; uint32_t __pad1; }; }; union { uint64_t addr; uint64_t splice_off_in; }; uint32_t len; union { __kernel_rwf_t rw_flags; uint32_t fsync_flags; uint16_t poll_events; uint32_t poll32_events; uint32_t sync_range_flags; uint32_t msg_flags; uint32_t timeout_flags; uint32_t accept_flags; uint32_t cancel_flags; uint32_t open_flags; uint32_t statx_flags; uint32_t fadvise_advice; uint32_t splice_flags; uint32_t rename_flags; uint32_t unlink_flags; uint32_t hardlink_flags; uint32_t xattr_flags; }; uint64_t user_data; union { uint16_t buf_index; uint16_t buf_group; } __attribute__((packed)); uint16_t personality; union { int32_t splice_fd_in; uint32_t file_index; }; union { struct { uint64_t addr3; uint64_t __pad2[1]; }; uint8_t cmd[0]; }; }; using IOSqringOffsets = struct io_sqring_offsets; using ICqringOffsets = struct io_cqring_offsets; using IOUringCqe = struct io_uring_cqe; using IOUringParams = struct io_uring_params; using IOUringSqe = struct io_uring_sqe; // Helper class for IO_URING class IOUring { public: IOUring() = delete; IOUring(FileDescriptor &&fd, unsigned int entries, IOUringParams &params); ~IOUring(); static PosixErrorOr<std::unique_ptr<IOUring>> InitIOUring( unsigned int entries, IOUringParams &params); uint32_t load_cq_head(); uint32_t load_cq_tail(); uint32_t load_sq_head(); uint32_t load_sq_tail(); uint32_t load_cq_overflow(); uint32_t load_sq_dropped(); void store_cq_head(uint32_t cq_head_val); void store_sq_tail(uint32_t sq_tail_val); int Enter(unsigned int to_submit, unsigned int min_complete, unsigned int flags, sigset_t *sig); IOUringCqe *get_cqes(); IOUringSqe *get_sqes(); uint32_t get_sq_mask(); unsigned *get_sq_array(); int Fd() { return iouringfd_.get(); } private: IOUringCqe *cqes_ = nullptr; FileDescriptor iouringfd_; size_t cring_sz_; size_t sring_sz_; size_t sqes_sz_; uint32_t sq_mask_; unsigned *sq_array_ = nullptr; uint32_t *cq_head_ptr_ = nullptr; uint32_t *cq_tail_ptr_ = nullptr; uint32_t *sq_head_ptr_ = nullptr; uint32_t *sq_tail_ptr_ = nullptr; uint32_t *cq_overflow_ptr_ = nullptr; uint32_t *sq_dropped_ptr_ = nullptr; void *sq_ptr_ = nullptr; void *cq_ptr_ = nullptr; void *sqe_ptr_ = nullptr; }; // This is a wrapper for the io_uring_setup(2) system call. inline int IOUringSetup(uint32_t entries, IOUringParams *params) { return syscall(__NR_io_uring_setup, entries, params); } // This is a wrapper for the io_uring_enter(2) system call. inline int IOUringEnter(unsigned int fd, unsigned int to_submit, unsigned int min_complete, unsigned int flags, sigset_t *sig) { return syscall(__NR_io_uring_enter, fd, to_submit, min_complete, flags, sig); } // Returns a new iouringfd with the given number of entries. inline PosixErrorOr<FileDescriptor> NewIOUringFD(uint32_t entries, IOUringParams &params) { memset(&params, 0, sizeof(params)); int fd = IOUringSetup(entries, &params); MaybeSave(); if (fd < 0) { return PosixError(errno, "io_uring_setup"); } return FileDescriptor(fd); } template <typename T> static inline void io_uring_atomic_write(T *p, T v) { std::atomic_store_explicit(reinterpret_cast<std::atomic<T> *>(p), v, std::memory_order_release); } template <typename T> static inline T io_uring_atomic_read(const T *p) { return std::atomic_load_explicit(reinterpret_cast<const std::atomic<T> *>(p), std::memory_order_acquire); } } // namespace testing } // namespace gvisor #endif // GVISOR_TEST_UTIL_IOURING_UTIL_H_
6,226
24.210526
79
h
gvisor
gvisor-master/test/util/linux_capability_util.h
// Copyright 2018 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Utilities for testing capabilities on Linux. #ifndef GVISOR_TEST_UTIL_LINUX_CAPABILITY_UTIL_H_ #define GVISOR_TEST_UTIL_LINUX_CAPABILITY_UTIL_H_ #ifdef __linux__ #include <errno.h> #include <linux/capability.h> #include <sys/syscall.h> #include <unistd.h> #include "test/util/cleanup.h" #include "test/util/posix_error.h" #include "test/util/save_util.h" #include "test/util/test_util.h" #ifndef _LINUX_CAPABILITY_VERSION_3 #error Expecting _LINUX_CAPABILITY_VERSION_3 support #endif namespace gvisor { namespace testing { // HaveCapability returns true if the process has the specified EFFECTIVE // capability. inline PosixErrorOr<bool> HaveCapability(int cap) { if (!cap_valid(cap)) { return PosixError(EINVAL, "Invalid capability"); } struct __user_cap_header_struct header = {_LINUX_CAPABILITY_VERSION_3, 0}; struct __user_cap_data_struct caps[_LINUX_CAPABILITY_U32S_3] = {}; RETURN_ERROR_IF_SYSCALL_FAIL(syscall(__NR_capget, &header, &caps)); MaybeSave(); return (caps[CAP_TO_INDEX(cap)].effective & CAP_TO_MASK(cap)) != 0; } // SetCapability sets the specified EFFECTIVE capability. inline PosixError SetCapability(int cap, bool set) { if (!cap_valid(cap)) { return PosixError(EINVAL, "Invalid capability"); } struct __user_cap_header_struct header = {_LINUX_CAPABILITY_VERSION_3, 0}; struct __user_cap_data_struct caps[_LINUX_CAPABILITY_U32S_3] = {}; RETURN_ERROR_IF_SYSCALL_FAIL(syscall(__NR_capget, &header, &caps)); MaybeSave(); if (set) { caps[CAP_TO_INDEX(cap)].effective |= CAP_TO_MASK(cap); } else { caps[CAP_TO_INDEX(cap)].effective &= ~CAP_TO_MASK(cap); } header = {_LINUX_CAPABILITY_VERSION_3, 0}; RETURN_ERROR_IF_SYSCALL_FAIL(syscall(__NR_capset, &header, &caps)); MaybeSave(); return NoError(); } // DropPermittedCapability drops the specified PERMITTED. The EFFECTIVE // capabilities must be a subset of PERMITTED, so those are dropped as well. inline PosixError DropPermittedCapability(int cap) { if (!cap_valid(cap)) { return PosixError(EINVAL, "Invalid capability"); } struct __user_cap_header_struct header = {_LINUX_CAPABILITY_VERSION_3, 0}; struct __user_cap_data_struct caps[_LINUX_CAPABILITY_U32S_3] = {}; RETURN_ERROR_IF_SYSCALL_FAIL(syscall(__NR_capget, &header, &caps)); MaybeSave(); caps[CAP_TO_INDEX(cap)].effective &= ~CAP_TO_MASK(cap); caps[CAP_TO_INDEX(cap)].permitted &= ~CAP_TO_MASK(cap); header = {_LINUX_CAPABILITY_VERSION_3, 0}; RETURN_ERROR_IF_SYSCALL_FAIL(syscall(__NR_capset, &header, &caps)); MaybeSave(); return NoError(); } PosixErrorOr<bool> CanCreateUserNamespace(); class AutoCapability { public: AutoCapability(int cap, bool set) : cap_(cap), set_(set) { const bool has = EXPECT_NO_ERRNO_AND_VALUE(HaveCapability(cap)); if (set != has) { EXPECT_NO_ERRNO(SetCapability(cap_, set_)); applied_ = true; } } ~AutoCapability() { if (applied_) { EXPECT_NO_ERRNO(SetCapability(cap_, !set_)); } } private: int cap_; bool set_; bool applied_ = false; }; } // namespace testing } // namespace gvisor #endif // __linux__ #endif // GVISOR_TEST_UTIL_LINUX_CAPABILITY_UTIL_H_
3,779
28.302326
76
h
gvisor
gvisor-master/test/util/logging.h
// Copyright 2018 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef GVISOR_TEST_UTIL_LOGGING_H_ #define GVISOR_TEST_UTIL_LOGGING_H_ #include <stddef.h> #include <cerrno> namespace gvisor { namespace testing { void CheckFailure(const char* cond, size_t cond_size, const char* msg, size_t msg_size, int errno_value); // If cond is false, aborts the current process. // // This macro is async-signal-safe. #define TEST_CHECK(cond) \ do { \ if (!(cond)) { \ ::gvisor::testing::CheckFailure(#cond, sizeof(#cond) - 1, nullptr, \ 0, 0); \ } \ } while (0) // If cond is false, logs msg then aborts the current process. // // This macro is async-signal-safe. #define TEST_CHECK_MSG(cond, msg) \ do { \ if (!(cond)) { \ ::gvisor::testing::CheckFailure(#cond, sizeof(#cond) - 1, msg, \ sizeof(msg) - 1, 0); \ } \ } while (0) // If cond is false, logs errno, then aborts the current process. // // This macro is async-signal-safe. #define TEST_PCHECK(cond) \ do { \ if (!(cond)) { \ ::gvisor::testing::CheckFailure(#cond, sizeof(#cond) - 1, nullptr, \ 0, errno); \ } \ } while (0) // If cond is false, logs msg and errno, then aborts the current process. // // This macro is async-signal-safe. #define TEST_PCHECK_MSG(cond, msg) \ do { \ if (!(cond)) { \ ::gvisor::testing::CheckFailure(#cond, sizeof(#cond) - 1, msg, \ sizeof(msg) - 1, errno); \ } \ } while (0) // expr must return PosixErrorOr<T>. The current process is aborted if // !PosixError<T>.ok(). // // This macro is async-signal-safe. #define TEST_CHECK_NO_ERRNO(expr) \ ({ \ auto _expr_result = (expr); \ if (!_expr_result.ok()) { \ ::gvisor::testing::CheckFailure( \ #expr, sizeof(#expr) - 1, nullptr, 0, \ _expr_result.error().errno_value()); \ } \ }) // expr must return PosixErrorOr<T>. The current process is aborted if // !PosixError<T>.ok(). Otherwise, PosixErrorOr<T> value is returned. // // This macro is async-signal-safe. #define TEST_CHECK_NO_ERRNO_AND_VALUE(expr) \ ({ \ auto _expr_result = (expr); \ if (!_expr_result.ok()) { \ ::gvisor::testing::CheckFailure( \ #expr, sizeof(#expr) - 1, nullptr, 0, \ _expr_result.error().errno_value()); \ } \ std::move(_expr_result).ValueOrDie(); \ }) // cond must be greater or equal than 0. Used to test result of syscalls. // // This macro is async-signal-safe. #define TEST_CHECK_SUCCESS(cond) TEST_PCHECK((cond) >= 0) // cond must be -1 and errno must match errno_value. Used to test errors from // syscalls. // // This macro is async-signal-safe. #define TEST_CHECK_ERRNO(cond, errno_value) \ do { \ TEST_PCHECK((cond) == -1); \ TEST_PCHECK_MSG(errno == (errno_value), #cond " expected " #errno_value); \ } while (0) } // namespace testing } // namespace gvisor #endif // GVISOR_TEST_UTIL_LOGGING_H_
5,103
41.533333
80
h
gvisor
gvisor-master/test/util/memory_util.h
// Copyright 2018 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef GVISOR_TEST_UTIL_MEMORY_UTIL_H_ #define GVISOR_TEST_UTIL_MEMORY_UTIL_H_ #include <errno.h> #include <stddef.h> #include <stdint.h> #include <sys/mman.h> #include <sys/syscall.h> #include <unistd.h> #include "absl/strings/str_format.h" #include "absl/strings/string_view.h" #include "test/util/logging.h" #include "test/util/posix_error.h" #include "test/util/save_util.h" #include "test/util/test_util.h" namespace gvisor { namespace testing { // Async-signal-safe version of munmap(2). inline int MunmapSafe(void* addr, size_t length) { return syscall(SYS_munmap, addr, length); } // RAII type for mmap'ed memory. Only usable in tests due to use of a test-only // macro that can't be named without invoking the presubmit's wrath. class Mapping { public: // Constructs a mapping that owns nothing. Mapping() = default; // Constructs a mapping that owns the mmapped memory [ptr, ptr+len). Most // users should use Mmap or MmapAnon instead. Mapping(void* ptr, size_t len) : ptr_(ptr), len_(len) {} Mapping(Mapping&& orig) : ptr_(orig.ptr_), len_(orig.len_) { orig.release(); } Mapping& operator=(Mapping&& orig) { ptr_ = orig.ptr_; len_ = orig.len_; orig.release(); return *this; } Mapping(Mapping const&) = delete; Mapping& operator=(Mapping const&) = delete; ~Mapping() { reset(); } void* ptr() const { return ptr_; } size_t len() const { return len_; } // Returns a pointer to the end of the mapping. Useful for when the mapping // is used as a thread stack. void* endptr() const { return reinterpret_cast<void*>(addr() + len_); } // Returns the start of this mapping cast to uintptr_t for ease of pointer // arithmetic. uintptr_t addr() const { return reinterpret_cast<uintptr_t>(ptr_); } // Returns the end of this mapping cast to uintptr_t for ease of pointer // arithmetic. uintptr_t endaddr() const { return reinterpret_cast<uintptr_t>(endptr()); } // Returns this mapping as a StringPiece for ease of comparison. // // This function is named view in anticipation of the eventual replacement of // StringPiece with std::string_view. absl::string_view view() const { return absl::string_view(static_cast<char const*>(ptr_), len_); } // These are both named reset for consistency with standard smart pointers. void reset(void* ptr, size_t len) { if (len_) { TEST_PCHECK(MunmapSafe(ptr_, len_) == 0); } ptr_ = ptr; len_ = len; } void reset() { reset(nullptr, 0); } void release() { ptr_ = nullptr; len_ = 0; } private: void* ptr_ = nullptr; size_t len_ = 0; }; // Wrapper around mmap(2) that returns a Mapping. inline PosixErrorOr<Mapping> Mmap(void* addr, size_t length, int prot, int flags, int fd, off_t offset) { void* ptr = mmap(addr, length, prot, flags, fd, offset); if (ptr == MAP_FAILED) { return PosixError( errno, absl::StrFormat("mmap(%p, %d, %x, %x, %d, %d)", addr, length, prot, flags, fd, offset)); } MaybeSave(); return Mapping(ptr, length); } // Convenience wrapper around Mmap for anonymous mappings. inline PosixErrorOr<Mapping> MmapAnon(size_t length, int prot, int flags) { return Mmap(nullptr, length, prot, flags | MAP_ANONYMOUS, -1, 0); } // Wrapper for mremap that returns a PosixErrorOr<>, since the return type of // void* isn't directly compatible with SyscallSucceeds. inline PosixErrorOr<void*> Mremap(void* old_address, size_t old_size, size_t new_size, int flags, void* new_address) { void* rv = mremap(old_address, old_size, new_size, flags, new_address); if (rv == MAP_FAILED) { return PosixError(errno, "mremap failed"); } return rv; } // Returns true if the page containing addr is mapped. inline bool IsMapped(uintptr_t addr) { int const rv = msync(reinterpret_cast<void*>(addr & ~(kPageSize - 1)), kPageSize, MS_ASYNC); if (rv == 0) { return true; } TEST_PCHECK_MSG(errno == ENOMEM, "msync failed with unexpected errno"); return false; } } // namespace testing } // namespace gvisor #endif // GVISOR_TEST_UTIL_MEMORY_UTIL_H_
4,832
30.180645
80
h
gvisor
gvisor-master/test/util/mount_util.h
// Copyright 2018 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef GVISOR_TEST_UTIL_MOUNT_UTIL_H_ #define GVISOR_TEST_UTIL_MOUNT_UTIL_H_ #include <errno.h> #include <sys/mount.h> #include <functional> #include <string> #include "gmock/gmock.h" #include "absl/container/flat_hash_map.h" #include "test/util/cleanup.h" #include "test/util/posix_error.h" #include "test/util/test_util.h" namespace gvisor { namespace testing { // Mount mounts the filesystem, and unmounts when the returned reference is // destroyed. inline PosixErrorOr<Cleanup> Mount(const std::string& source, const std::string& target, const std::string& fstype, uint64_t mountflags, const std::string& data, uint64_t umountflags) { if (mount(source.c_str(), target.c_str(), fstype.c_str(), mountflags, data.c_str()) == -1) { return PosixError(errno, "mount failed"); } return Cleanup([target, umountflags]() { EXPECT_THAT(umount2(target.c_str(), umountflags), SyscallSucceeds()); }); } struct ProcMountsEntry { std::string spec; std::string mount_point; std::string fstype; std::string mount_opts; uint32_t dump; uint32_t fsck; }; // ProcSelfMountsEntries returns a parsed representation of /proc/self/mounts. PosixErrorOr<std::vector<ProcMountsEntry>> ProcSelfMountsEntries(); // ProcSelfMountsEntries returns a parsed representation of mounts from the // provided content. PosixErrorOr<std::vector<ProcMountsEntry>> ProcSelfMountsEntriesFrom( const std::string& content); struct ProcMountInfoEntry { uint64_t id; uint64_t parent_id; dev_t major; dev_t minor; std::string root; std::string mount_point; std::string mount_opts; std::string optional; std::string fstype; std::string mount_source; std::string super_opts; }; // ProcSelfMountInfoEntries returns a parsed representation of // /proc/self/mountinfo. PosixErrorOr<std::vector<ProcMountInfoEntry>> ProcSelfMountInfoEntries(); // ProcSelfMountInfoEntriesFrom returns a parsed representation of // mountinfo from the provided content. PosixErrorOr<std::vector<ProcMountInfoEntry>> ProcSelfMountInfoEntriesFrom( const std::string&); // Interprets the input string mopts as a comma separated list of mount // options. A mount option can either be just a value, or a key=value pair. For // example, the string "rw,relatime,fd=7" will be parsed into a map like { "rw": // "", "relatime": "", "fd": "7" }. absl::flat_hash_map<std::string, std::string> ParseMountOptions( std::string mopts); } // namespace testing } // namespace gvisor #endif // GVISOR_TEST_UTIL_MOUNT_UTIL_H_
3,266
31.67
80
h
gvisor
gvisor-master/test/util/multiprocess_util.h
// Copyright 2018 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef GVISOR_TEST_UTIL_MULTIPROCESS_UTIL_H_ #define GVISOR_TEST_UTIL_MULTIPROCESS_UTIL_H_ #include <unistd.h> #include <algorithm> #include <string> #include <utility> #include <vector> #include "absl/strings/string_view.h" #include "test/util/cleanup.h" #include "test/util/posix_error.h" namespace gvisor { namespace testing { // Immutable holder for a dynamically-sized array of pointers to mutable char, // terminated by a null pointer, as required for the argv and envp arguments to // execve(2). class ExecveArray { public: // Constructs an empty ExecveArray. ExecveArray() = default; // Constructs an ExecveArray by copying strings from the given range. T must // be a range over ranges of char. template <typename T> explicit ExecveArray(T const& strs) : ExecveArray(strs.begin(), strs.end()) {} // Constructs an ExecveArray by copying strings from [first, last). InputIt // must be an input iterator over a range over char. template <typename InputIt> ExecveArray(InputIt first, InputIt last) { std::vector<size_t> offsets; auto output_it = std::back_inserter(str_); for (InputIt it = first; it != last; ++it) { offsets.push_back(str_.size()); auto const& s = *it; std::copy(s.begin(), s.end(), output_it); str_.push_back('\0'); } ptrs_.reserve(offsets.size() + 1); for (auto offset : offsets) { ptrs_.push_back(str_.data() + offset); } ptrs_.push_back(nullptr); } // Constructs an ExecveArray by copying strings from list. This overload must // exist independently of the single-argument template constructor because // std::initializer_list does not participate in template argument deduction // (i.e. cannot be type-inferred in an invocation of the templated // constructor). /* implicit */ ExecveArray(std::initializer_list<absl::string_view> list) : ExecveArray(list.begin(), list.end()) {} // Disable move construction and assignment since ptrs_ points into str_. ExecveArray(ExecveArray&&) = delete; ExecveArray& operator=(ExecveArray&&) = delete; char* const* get() const { return ptrs_.data(); } size_t get_size() { return str_.size(); } private: std::vector<char> str_; std::vector<char*> ptrs_; }; // Simplified version of SubProcess. Returns OK and a cleanup function to kill // the child if it made it to execve. // // fn is run between fork and exec. If it needs to fail, it should exit the // process. // // The child pid is returned via child, if provided. // execve's error code is returned via execve_errno, if provided. PosixErrorOr<Cleanup> ForkAndExec(const std::string& filename, const ExecveArray& argv, const ExecveArray& envv, const std::function<void()>& fn, pid_t* child, int* execve_errno); inline PosixErrorOr<Cleanup> ForkAndExec(const std::string& filename, const ExecveArray& argv, const ExecveArray& envv, pid_t* child, int* execve_errno) { return ForkAndExec( filename, argv, envv, [] {}, child, execve_errno); } // Equivalent to ForkAndExec, except using dirfd and flags with execveat. PosixErrorOr<Cleanup> ForkAndExecveat(int32_t dirfd, const std::string& pathname, const ExecveArray& argv, const ExecveArray& envv, int flags, const std::function<void()>& fn, pid_t* child, int* execve_errno); inline PosixErrorOr<Cleanup> ForkAndExecveat(int32_t dirfd, const std::string& pathname, const ExecveArray& argv, const ExecveArray& envv, int flags, pid_t* child, int* execve_errno) { return ForkAndExecveat( dirfd, pathname, argv, envv, flags, [] {}, child, execve_errno); } // Calls fn in a forked subprocess and returns the exit status of the // subprocess. // // fn must be async-signal-safe. Use of ASSERT/EXPECT functions is prohibited. // Use TEST_CHECK variants instead. PosixErrorOr<int> InForkedProcess(const std::function<void()>& fn); } // namespace testing } // namespace gvisor #endif // GVISOR_TEST_UTIL_MULTIPROCESS_UTIL_H_
5,163
37.537313
80
h
gvisor
gvisor-master/test/util/platform_util.h
// Copyright 2020 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef GVISOR_TEST_UTIL_PLATFORM_UTIL_H_ #define GVISOR_TEST_UTIL_PLATFORM_UTIL_H_ namespace gvisor { namespace testing { // PlatformSupport is a generic enumeration of classes of support. // // It is up to the individual functions and callers to agree on the precise // definition for each case. The document here generally refers to 32-bit // as an example. Many cases will use only NotSupported and Allowed. enum class PlatformSupport { // The feature is not supported on the current platform. // // In the case of 32-bit, this means that calls will generally be interpreted // as 64-bit calls, and there is no support for 32-bit binaries, long calls, // etc. This usually means that the underlying implementation just pretends // that 32-bit doesn't exist. NotSupported, // Calls will be ignored by the kernel with a fixed error. Ignored, // Calls will result in a SIGSEGV or similar fault. Segfault, // The feature is supported as expected. // // In the case of 32-bit, this means that the system call or far call will be // handled properly. Allowed, }; PlatformSupport PlatformSupport32Bit(); PlatformSupport PlatformSupportAlignmentCheck(); PlatformSupport PlatformSupportMultiProcess(); PlatformSupport PlatformSupportInt3(); PlatformSupport PlatformSupportVsyscall(); } // namespace testing } // namespace gvisor #endif // GVISOR_TEST_UTIL_PLATFORM_UTIL_H_
2,008
33.637931
79
h
gvisor
gvisor-master/test/util/posix_error.h
// Copyright 2018 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef GVISOR_TEST_UTIL_POSIX_ERROR_H_ #define GVISOR_TEST_UTIL_POSIX_ERROR_H_ #include <string> #include "gmock/gmock.h" #include "absl/base/attributes.h" #include "absl/strings/string_view.h" #include "absl/types/variant.h" #include "test/util/logging.h" namespace gvisor { namespace testing { // PosixError must be async-signal-safe. class ABSL_MUST_USE_RESULT PosixError { public: PosixError() {} explicit PosixError(int errno_value) : errno_(errno_value) {} PosixError(int errno_value, std::string_view msg) : errno_(errno_value) { // Check that `msg` will fit, leaving room for '\0' at the end. TEST_CHECK(msg.size() < sizeof(msg_)); msg.copy(msg_, msg.size()); } PosixError(PosixError&& other) = default; PosixError& operator=(PosixError&& other) = default; PosixError(const PosixError&) = default; PosixError& operator=(const PosixError&) = default; bool ok() const { return errno_ == 0; } // Returns a reference to *this to make matchers compatible with // PosixErrorOr. const PosixError& error() const { return *this; } int errno_value() const { return errno_; } const char* message() const { return msg_; } // ToString produces a full string representation of this posix error // including the printable representation of the errno and the error message. std::string ToString() const; // Ignores any errors. This method does nothing except potentially suppress // complaints from any tools that are checking that errors are not dropped on // the floor. void IgnoreError() const {} private: int errno_ = 0; // std::string is not async-signal-safe. We must use a c string instead. char msg_[1024] = {}; }; template <typename T> class ABSL_MUST_USE_RESULT PosixErrorOr { public: // A PosixErrorOr will check fail if it is constructed with NoError(). PosixErrorOr(const PosixError& error); PosixErrorOr(const T& value); PosixErrorOr(T&& value); PosixErrorOr(PosixErrorOr&& other) = default; PosixErrorOr& operator=(PosixErrorOr&& other) = default; PosixErrorOr(const PosixErrorOr&) = default; PosixErrorOr& operator=(const PosixErrorOr&) = default; // Conversion copy/move constructor, T must be convertible from U. template <typename U> friend class PosixErrorOr; template <typename U> PosixErrorOr(PosixErrorOr<U> other); template <typename U> PosixErrorOr& operator=(PosixErrorOr<U> other); // Returns true if this PosixErrorOr contains some T. bool ok() const; // Return a copy of the contained PosixError or NoError(). PosixError error() const; // Returns a reference to our current value, or CHECK-fails if !this->ok(). const T& ValueOrDie() const&; T& ValueOrDie() &; const T&& ValueOrDie() const&&; T&& ValueOrDie() &&; // Ignores any errors. This method does nothing except potentially suppress // complaints from any tools that are checking that errors are not dropped on // the floor. void IgnoreError() const {} private: absl::variant<T, PosixError> value_; friend class PosixErrorIsMatcherCommonImpl; }; template <typename T> PosixErrorOr<T>::PosixErrorOr(const PosixError& error) : value_(error) { TEST_CHECK_MSG( !error.ok(), "Constructing PosixErrorOr with NoError, eg. errno 0 is not allowed."); } template <typename T> PosixErrorOr<T>::PosixErrorOr(const T& value) : value_(value) {} template <typename T> PosixErrorOr<T>::PosixErrorOr(T&& value) : value_(std::move(value)) {} // Conversion copy/move constructor, T must be convertible from U. template <typename T> template <typename U> inline PosixErrorOr<T>::PosixErrorOr(PosixErrorOr<U> other) { if (absl::holds_alternative<U>(other.value_)) { // T is convertible from U. value_ = absl::get<U>(std::move(other.value_)); } else if (absl::holds_alternative<PosixError>(other.value_)) { value_ = absl::get<PosixError>(std::move(other.value_)); } else { TEST_CHECK_MSG(false, "PosixErrorOr does not contain PosixError or value"); } } template <typename T> template <typename U> inline PosixErrorOr<T>& PosixErrorOr<T>::operator=(PosixErrorOr<U> other) { if (absl::holds_alternative<U>(other.value_)) { // T is convertible from U. value_ = absl::get<U>(std::move(other.value_)); } else if (absl::holds_alternative<PosixError>(other.value_)) { value_ = absl::get<PosixError>(std::move(other.value_)); } else { TEST_CHECK_MSG(false, "PosixErrorOr does not contain PosixError or value"); } return *this; } template <typename T> PosixError PosixErrorOr<T>::error() const { if (!absl::holds_alternative<PosixError>(value_)) { return PosixError(); } return absl::get<PosixError>(value_); } template <typename T> bool PosixErrorOr<T>::ok() const { return absl::holds_alternative<T>(value_); } template <typename T> const T& PosixErrorOr<T>::ValueOrDie() const& { TEST_CHECK(absl::holds_alternative<T>(value_)); return absl::get<T>(value_); } template <typename T> T& PosixErrorOr<T>::ValueOrDie() & { TEST_CHECK(absl::holds_alternative<T>(value_)); return absl::get<T>(value_); } template <typename T> const T&& PosixErrorOr<T>::ValueOrDie() const&& { TEST_CHECK(absl::holds_alternative<T>(value_)); return std::move(absl::get<T>(value_)); } template <typename T> T&& PosixErrorOr<T>::ValueOrDie() && { TEST_CHECK(absl::holds_alternative<T>(value_)); return std::move(absl::get<T>(value_)); } extern ::std::ostream& operator<<(::std::ostream& os, const PosixError& e); template <typename T> ::std::ostream& operator<<(::std::ostream& os, const PosixErrorOr<T>& e) { os << e.error(); return os; } // NoError is a PosixError that represents a successful state, i.e. No Error. inline PosixError NoError() { return PosixError(); } // Monomorphic implementation of matcher IsPosixErrorOk() for a given type T. // T can be PosixError, PosixErrorOr<>, or a reference to either of them. template <typename T> class MonoPosixErrorIsOkMatcherImpl : public ::testing::MatcherInterface<T> { public: void DescribeTo(std::ostream* os) const override { *os << "is OK"; } void DescribeNegationTo(std::ostream* os) const override { *os << "is not OK"; } bool MatchAndExplain(T actual_value, ::testing::MatchResultListener*) const override { return actual_value.ok(); } }; // Implements IsPosixErrorOkMatcher() as a polymorphic matcher. class IsPosixErrorOkMatcher { public: template <typename T> operator ::testing::Matcher<T>() const { // NOLINT return MakeMatcher(new MonoPosixErrorIsOkMatcherImpl<T>()); } }; // Monomorphic implementation of a matcher for a PosixErrorOr. template <typename PosixErrorOrType> class IsPosixErrorOkAndHoldsMatcherImpl : public ::testing::MatcherInterface<PosixErrorOrType> { public: using ValueType = typename std::remove_reference< decltype(std::declval<PosixErrorOrType>().ValueOrDie())>::type; template <typename InnerMatcher> explicit IsPosixErrorOkAndHoldsMatcherImpl(InnerMatcher&& inner_matcher) : inner_matcher_(::testing::SafeMatcherCast<const ValueType&>( std::forward<InnerMatcher>(inner_matcher))) {} void DescribeTo(std::ostream* os) const override { *os << "is OK and has a value that "; inner_matcher_.DescribeTo(os); } void DescribeNegationTo(std::ostream* os) const override { *os << "isn't OK or has a value that "; inner_matcher_.DescribeNegationTo(os); } bool MatchAndExplain( PosixErrorOrType actual_value, ::testing::MatchResultListener* listener) const override { // We can't extract the value if it doesn't contain one. if (!actual_value.ok()) { return false; } ::testing::StringMatchResultListener inner_listener; const bool matches = inner_matcher_.MatchAndExplain( actual_value.ValueOrDie(), &inner_listener); const std::string inner_explanation = inner_listener.str(); *listener << "has a value " << ::testing::PrintToString(actual_value.ValueOrDie()); if (!inner_explanation.empty()) { *listener << " " << inner_explanation; } return matches; } private: const ::testing::Matcher<const ValueType&> inner_matcher_; }; // Implements IsOkAndHolds() as a polymorphic matcher. template <typename InnerMatcher> class IsPosixErrorOkAndHoldsMatcher { public: explicit IsPosixErrorOkAndHoldsMatcher(InnerMatcher inner_matcher) : inner_matcher_(std::move(inner_matcher)) {} // Converts this polymorphic matcher to a monomorphic one of the given type. // PosixErrorOrType can be either PosixErrorOr<T> or a reference to // PosixErrorOr<T>. template <typename PosixErrorOrType> operator ::testing::Matcher<PosixErrorOrType>() const { // NOLINT return ::testing::MakeMatcher( new IsPosixErrorOkAndHoldsMatcherImpl<PosixErrorOrType>( inner_matcher_)); } private: const InnerMatcher inner_matcher_; }; // PosixErrorIs() is a polymorphic matcher. This class is the common // implementation of it shared by all types T where PosixErrorIs() can be // used as a Matcher<T>. class PosixErrorIsMatcherCommonImpl { public: PosixErrorIsMatcherCommonImpl( ::testing::Matcher<int> code_matcher, ::testing::Matcher<const std::string&> message_matcher) : code_matcher_(std::move(code_matcher)), message_matcher_(std::move(message_matcher)) {} void DescribeTo(std::ostream* os) const; void DescribeNegationTo(std::ostream* os) const; bool MatchAndExplain(const PosixError& error, ::testing::MatchResultListener* result_listener) const; template <typename T> bool MatchAndExplain(const PosixErrorOr<T>& error_or, ::testing::MatchResultListener* result_listener) const { if (error_or.ok()) { *result_listener << "has a value " << ::testing::PrintToString(error_or.ValueOrDie()); return false; } return MatchAndExplain(error_or.error(), result_listener); } private: const ::testing::Matcher<int> code_matcher_; const ::testing::Matcher<const std::string&> message_matcher_; }; // Monomorphic implementation of matcher PosixErrorIs() for a given type // T. T can be PosixError, PosixErrorOr<>, or a reference to either of them. template <typename T> class MonoPosixErrorIsMatcherImpl : public ::testing::MatcherInterface<T> { public: explicit MonoPosixErrorIsMatcherImpl( PosixErrorIsMatcherCommonImpl common_impl) : common_impl_(std::move(common_impl)) {} void DescribeTo(std::ostream* os) const override { common_impl_.DescribeTo(os); } void DescribeNegationTo(std::ostream* os) const override { common_impl_.DescribeNegationTo(os); } bool MatchAndExplain( T actual_value, ::testing::MatchResultListener* result_listener) const override { return common_impl_.MatchAndExplain(actual_value, result_listener); } private: PosixErrorIsMatcherCommonImpl common_impl_; }; inline ::testing::Matcher<int> ToErrorCodeMatcher( const ::testing::Matcher<int>& m) { return m; } // Implements PosixErrorIs() as a polymorphic matcher. class PosixErrorIsMatcher { public: template <typename ErrorCodeMatcher> PosixErrorIsMatcher(ErrorCodeMatcher&& code_matcher, ::testing::Matcher<const std::string&> message_matcher) : common_impl_( ToErrorCodeMatcher(std::forward<ErrorCodeMatcher>(code_matcher)), std::move(message_matcher)) {} // Converts this polymorphic matcher to a monomorphic matcher of the // given type. T can be StatusOr<>, Status, or a reference to // either of them. template <typename T> operator ::testing::Matcher<T>() const { // NOLINT return MakeMatcher(new MonoPosixErrorIsMatcherImpl<T>(common_impl_)); } private: const PosixErrorIsMatcherCommonImpl common_impl_; }; // Returns a gMock matcher that matches a PosixError or PosixErrorOr<> whose // error code matches code_matcher, and whose error message matches // message_matcher. template <typename ErrorCodeMatcher> PosixErrorIsMatcher PosixErrorIs( ErrorCodeMatcher&& code_matcher, ::testing::Matcher<const std::string&> message_matcher) { return PosixErrorIsMatcher(std::forward<ErrorCodeMatcher>(code_matcher), std::move(message_matcher)); } // Returns a gMock matcher that matches a PosixError or PosixErrorOr<> whose // error code matches code_matcher. template <typename ErrorCodeMatcher> PosixErrorIsMatcher PosixErrorIs(ErrorCodeMatcher&& code_matcher) { return PosixErrorIsMatcher(std::forward<ErrorCodeMatcher>(code_matcher), ::testing::_); } // Returns a gMock matcher that matches a PosixErrorOr<> which is ok() and // value matches the inner matcher. template <typename InnerMatcher> IsPosixErrorOkAndHoldsMatcher<typename std::decay<InnerMatcher>::type> IsPosixErrorOkAndHolds(InnerMatcher&& inner_matcher) { return IsPosixErrorOkAndHoldsMatcher<typename std::decay<InnerMatcher>::type>( std::forward<InnerMatcher>(inner_matcher)); } // Internal helper for concatenating macro values. #define POSIX_ERROR_IMPL_CONCAT_INNER_(x, y) x##y #define POSIX_ERROR_IMPL_CONCAT_(x, y) POSIX_ERROR_IMPL_CONCAT_INNER_(x, y) #define POSIX_ERROR_IMPL_ASSIGN_OR_RETURN_(posixerroror, lhs, rexpr) \ auto posixerroror = (rexpr); \ if (!posixerroror.ok()) { \ return (posixerroror.error()); \ } \ lhs = std::move(posixerroror).ValueOrDie() #define EXPECT_NO_ERRNO(expression) \ EXPECT_THAT(expression, IsPosixErrorOkMatcher()) #define ASSERT_NO_ERRNO(expression) \ ASSERT_THAT(expression, IsPosixErrorOkMatcher()) #define ASSIGN_OR_RETURN_ERRNO(lhs, rexpr) \ POSIX_ERROR_IMPL_ASSIGN_OR_RETURN_( \ POSIX_ERROR_IMPL_CONCAT_(_status_or_value, __LINE__), lhs, rexpr) #define RETURN_IF_ERRNO(s) \ do { \ if (!s.ok()) { \ return s.error(); \ } \ } while (false); #define ASSERT_NO_ERRNO_AND_VALUE(expr) \ ({ \ auto _expr_result = (expr); \ ASSERT_NO_ERRNO(_expr_result); \ std::move(_expr_result).ValueOrDie(); \ }) #define EXPECT_NO_ERRNO_AND_VALUE(expr) \ ({ \ auto _expr_result = (expr); \ EXPECT_NO_ERRNO(_expr_result); \ std::move(_expr_result).ValueOrDie(); \ }) } // namespace testing } // namespace gvisor #endif // GVISOR_TEST_UTIL_POSIX_ERROR_H_
15,317
32.227766
80
h
gvisor
gvisor-master/test/util/proc_util.h
// Copyright 2018 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef GVISOR_TEST_UTIL_PROC_UTIL_H_ #define GVISOR_TEST_UTIL_PROC_UTIL_H_ #include <ostream> #include <string> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/algorithm/container.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "absl/types/optional.h" #include "test/util/fs_util.h" #include "test/util/posix_error.h" namespace gvisor { namespace testing { // ProcMapsEntry contains the data from a single line in /proc/<xxx>/maps. struct ProcMapsEntry { uint64_t start; uint64_t end; bool readable; bool writable; bool executable; bool priv; uint64_t offset; int major; int minor; int64_t inode; std::string filename; }; struct ProcSmapsEntry { ProcMapsEntry maps_entry; // These fields should always exist, as they were included in e070ad49f311 // "[PATCH] add /proc/pid/smaps". size_t size_kb; size_t rss_kb; size_t shared_clean_kb; size_t shared_dirty_kb; size_t private_clean_kb; size_t private_dirty_kb; // These fields were added later and may not be present. absl::optional<size_t> pss_kb; absl::optional<size_t> referenced_kb; absl::optional<size_t> anonymous_kb; absl::optional<size_t> anon_huge_pages_kb; absl::optional<size_t> shared_hugetlb_kb; absl::optional<size_t> private_hugetlb_kb; absl::optional<size_t> swap_kb; absl::optional<size_t> swap_pss_kb; absl::optional<size_t> kernel_page_size_kb; absl::optional<size_t> mmu_page_size_kb; absl::optional<size_t> locked_kb; // Caution: "Note that there is no guarantee that every flag and associated // mnemonic will be present in all further kernel releases. Things get // changed, the flags may be vanished or the reverse -- new added." - Linux // Documentation/filesystems/proc.txt, on VmFlags. Avoid checking for any // flags that are not extremely well-established. absl::optional<std::vector<std::string>> vm_flags; }; // Parses a ProcMaps line or returns an error. PosixErrorOr<ProcMapsEntry> ParseProcMapsLine(absl::string_view line); PosixErrorOr<std::vector<ProcMapsEntry>> ParseProcMaps( absl::string_view contents); // Returns true if vsyscall (emmulation or not) is enabled. PosixErrorOr<bool> IsVsyscallEnabled(); // Parses /proc/pid/smaps type entries PosixErrorOr<std::vector<ProcSmapsEntry>> ParseProcSmaps(absl::string_view); // Reads and parses /proc/self/smaps PosixErrorOr<std::vector<ProcSmapsEntry>> ReadProcSelfSmaps(); // Reads and parses /proc/pid/smaps PosixErrorOr<std::vector<ProcSmapsEntry>> ReadProcSmaps(pid_t); // Returns the unique entry in entries containing the given address. PosixErrorOr<ProcSmapsEntry> FindUniqueSmapsEntry( std::vector<ProcSmapsEntry> const&, uintptr_t); // Check if stack has nh flag. bool StackTHPDisabled(std::vector<ProcSmapsEntry>); // Returns true if THP is disabled for current process. bool IsTHPDisabled(); // Printer for ProcMapsEntry. inline std::ostream& operator<<(std::ostream& os, const ProcMapsEntry& entry) { std::string str = absl::StrCat(absl::Hex(entry.start, absl::PadSpec::kZeroPad8), "-", absl::Hex(entry.end, absl::PadSpec::kZeroPad8), " "); absl::StrAppend(&str, entry.readable ? "r" : "-"); absl::StrAppend(&str, entry.writable ? "w" : "-"); absl::StrAppend(&str, entry.executable ? "x" : "-"); absl::StrAppend(&str, entry.priv ? "p" : "s"); absl::StrAppend(&str, " ", absl::Hex(entry.offset, absl::PadSpec::kZeroPad8), " ", absl::Hex(entry.major, absl::PadSpec::kZeroPad2), ":", absl::Hex(entry.minor, absl::PadSpec::kZeroPad2), " ", entry.inode); if (absl::string_view(entry.filename) != "") { // Pad to column 74 int pad = 73 - str.length(); if (pad > 0) { absl::StrAppend(&str, std::string(pad, ' ')); } absl::StrAppend(&str, entry.filename); } os << str; return os; } // Printer for std::vector<ProcMapsEntry>. inline std::ostream& operator<<(std::ostream& os, const std::vector<ProcMapsEntry>& vec) { for (unsigned int i = 0; i < vec.size(); i++) { os << vec[i]; if (i != vec.size() - 1) { os << "\n"; } } return os; } // GoogleTest printer for std::vector<ProcMapsEntry>. inline void PrintTo(const std::vector<ProcMapsEntry>& vec, std::ostream* os) { *os << vec; } // Checks that /proc/pid/maps contains all of the passed mappings. // // The major, minor, and inode fields are ignored. MATCHER_P(ContainsMappings, mappings, "contains mappings:\n" + ::testing::PrintToString(mappings)) { auto contents_or = GetContents(absl::StrCat("/proc/", arg, "/maps")); if (!contents_or.ok()) { *result_listener << "Unable to read mappings: " << contents_or.error().ToString(); return false; } auto maps_or = ParseProcMaps(contents_or.ValueOrDie()); if (!maps_or.ok()) { *result_listener << "Unable to parse mappings: " << maps_or.error().ToString(); return false; } auto maps = std::move(maps_or).ValueOrDie(); // Does maps contain all elements in mappings? The comparator ignores // the major, minor, and inode fields. bool all_present = true; std::for_each(mappings.begin(), mappings.end(), [&](const ProcMapsEntry& e1) { auto it = absl::c_find_if(maps, [&e1](const ProcMapsEntry& e2) { return e1.start == e2.start && e1.end == e2.end && e1.readable == e2.readable && e1.writable == e2.writable && e1.executable == e2.executable && e1.priv == e2.priv && e1.offset == e2.offset && e1.filename == e2.filename; }); if (it == maps.end()) { // It wasn't found. if (all_present) { // We will output the message once and then a line for each mapping // that wasn't found. all_present = false; *result_listener << "Got mappings:\n" << maps << "\nThat were missing:\n"; } *result_listener << e1 << "\n"; } }); return all_present; } // LimitType is an rlimit type enum class LimitType { kCPU, kFileSize, kData, kStack, kCore, kRSS, kProcessCount, kNumberOfFiles, kMemoryLocked, kAS, kLocks, kSignalsPending, kMessageQueueBytes, kNice, kRealTimePriority, kRttime, }; const std::vector<LimitType> LimitTypes{ LimitType::kCPU, LimitType::kFileSize, LimitType::kData, LimitType::kStack, LimitType::kCore, LimitType::kRSS, LimitType::kProcessCount, LimitType::kNumberOfFiles, LimitType::kMemoryLocked, LimitType::kAS, LimitType::kLocks, LimitType::kSignalsPending, LimitType::kMessageQueueBytes, LimitType::kNice, LimitType::kRealTimePriority, LimitType::kRttime, }; std::string LimitTypeToString(LimitType type); // ProcLimitsEntry contains the data from a single line in /proc/xxx/limits. struct ProcLimitsEntry { LimitType limit_type; uint64_t cur_limit; uint64_t max_limit; }; // Parses a single line from /proc/xxx/limits. PosixErrorOr<ProcLimitsEntry> ParseProcLimitsLine(absl::string_view line); // Parses an entire /proc/xxx/limits file into lines. PosixErrorOr<std::vector<ProcLimitsEntry>> ParseProcLimits( absl::string_view contents); // Printer for ProcLimitsEntry. std::ostream& operator<<(std::ostream& os, const ProcLimitsEntry& entry); // Printer for std::vector<ProcLimitsEntry>. std::ostream& operator<<(std::ostream& os, const std::vector<ProcLimitsEntry>& vec); // GoogleTest printer for std::vector<ProcLimitsEntry>. inline void PrintTo(const std::vector<ProcLimitsEntry>& vec, std::ostream* os) { *os << vec; } } // namespace testing } // namespace gvisor #endif // GVISOR_TEST_UTIL_PROC_UTIL_H_
8,417
30.29368
80
h
gvisor
gvisor-master/test/util/pty_util.h
// Copyright 2019 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef GVISOR_TEST_UTIL_PTY_UTIL_H_ #define GVISOR_TEST_UTIL_PTY_UTIL_H_ #include "test/util/file_descriptor.h" #include "test/util/posix_error.h" namespace gvisor { namespace testing { // Opens the replica end of the passed master as R/W and nonblocking. It does // not set the replica as the controlling TTY. PosixErrorOr<FileDescriptor> OpenReplica(const FileDescriptor& master); // Identical to the above OpenReplica, but flags are all specified by the // caller. PosixErrorOr<FileDescriptor> OpenReplica(const FileDescriptor& master, int flags); // Get the number of the replica end of the master. PosixErrorOr<int> ReplicaID(const FileDescriptor& master); } // namespace testing } // namespace gvisor #endif // GVISOR_TEST_UTIL_PTY_UTIL_H_
1,395
33.9
77
h
gvisor
gvisor-master/test/util/rlimit_util.h
// Copyright 2019 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef GVISOR_TEST_UTIL_RLIMIT_UTIL_H_ #define GVISOR_TEST_UTIL_RLIMIT_UTIL_H_ #include <sys/resource.h> #include <sys/time.h> #include "test/util/cleanup.h" #include "test/util/posix_error.h" #include "test/util/test_util.h" namespace gvisor { namespace testing { PosixErrorOr<Cleanup> ScopedSetSoftRlimit(int resource, rlim_t newval); } // namespace testing } // namespace gvisor #endif // GVISOR_TEST_UTIL_RLIMIT_UTIL_H_
1,030
30.242424
75
h
gvisor
gvisor-master/test/util/save_util.h
// Copyright 2018 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef GVISOR_TEST_UTIL_SAVE_UTIL_H_ #define GVISOR_TEST_UTIL_SAVE_UTIL_H_ namespace gvisor { namespace testing { // Returns true if the environment in which the calling process is executing // allows the test to be checkpointed and restored during execution. bool IsRunningWithSaveRestore(); // May perform a co-operative save cycle. // // errno is guaranteed to be preserved. void MaybeSave(); // Causes MaybeSave to become a no-op until destroyed or reset. class DisableSave { public: DisableSave(); ~DisableSave(); DisableSave(DisableSave const&) = delete; DisableSave(DisableSave&&) = delete; DisableSave& operator=(DisableSave const&) = delete; DisableSave& operator=(DisableSave&&) = delete; // reset allows saves to continue, and is called implicitly by the destructor. // It may be called multiple times safely, but is not thread-safe. void reset(); private: bool reset_ = false; }; namespace internal { // Causes a co-operative save cycle to occur. // // errno is guaranteed to be preserved. void DoCooperativeSave(); } // namespace internal } // namespace testing } // namespace gvisor #endif // GVISOR_TEST_UTIL_SAVE_UTIL_H_
1,772
28.065574
80
h
gvisor
gvisor-master/test/util/signal_util.h
// Copyright 2018 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef GVISOR_TEST_UTIL_SIGNAL_UTIL_H_ #define GVISOR_TEST_UTIL_SIGNAL_UTIL_H_ #include <signal.h> #include <sys/syscall.h> #include <unistd.h> #include <ostream> #include "gmock/gmock.h" #include "test/util/cleanup.h" #include "test/util/file_descriptor.h" #include "test/util/posix_error.h" // Format a sigset_t as a comma separated list of numeric ranges. ::std::ostream& operator<<(::std::ostream& os, const sigset_t& sigset); namespace gvisor { namespace testing { // The maximum signal number. static constexpr int kMaxSignal = 64; // Wrapper for the tgkill(2) syscall, which glibc does not provide. inline int tgkill(pid_t tgid, pid_t tid, int sig) { return syscall(__NR_tgkill, tgid, tid, sig); } // Installs the passed sigaction and returns a cleanup function to restore the // previous handler when it goes out of scope. PosixErrorOr<Cleanup> ScopedSigaction(int sig, struct sigaction const& sa); // Updates the signal mask as per sigprocmask(2) and returns a cleanup function // to restore the previous signal mask when it goes out of scope. PosixErrorOr<Cleanup> ScopedSignalMask(int how, sigset_t const& set); // ScopedSignalMask variant that creates a mask of the single signal 'sig'. inline PosixErrorOr<Cleanup> ScopedSignalMask(int how, int sig) { sigset_t set; sigemptyset(&set); sigaddset(&set, sig); return ScopedSignalMask(how, set); } // Asserts equality of two sigset_t values. MATCHER_P(EqualsSigset, value, "equals " + ::testing::PrintToString(value)) { for (int sig = 1; sig <= kMaxSignal; ++sig) { if (sigismember(&arg, sig) != sigismember(&value, sig)) { return false; } } return true; } #ifdef __x86_64__ // Fault can be used to generate a synchronous SIGSEGV. // // This fault can be fixed up in a handler via fixup, below. inline void Fault() { // Zero and dereference %ax. asm("movabs $0, %%rax\r\n" "mov 0(%%rax), %%rax\r\n" : : : "ax"); } // FixupFault fixes up a fault generated by fault, above. inline void FixupFault(ucontext_t* ctx) { // Skip the bad instruction above. // // The encoding is 0x48 0xab 0x00. ctx->uc_mcontext.gregs[REG_RIP] += 3; } #elif __aarch64__ inline void Fault() { // Zero and dereference x0. asm("mov x0, xzr\r\n" "str xzr, [x0]\r\n" : : : "x0"); } inline void FixupFault(ucontext_t* ctx) { // Skip the bad instruction above. ctx->uc_mcontext.pc += 4; } #endif // Wrapper around signalfd(2) that returns a FileDescriptor. PosixErrorOr<FileDescriptor> NewSignalFD(sigset_t* mask, int flags = 0); } // namespace testing } // namespace gvisor #endif // GVISOR_TEST_UTIL_SIGNAL_UTIL_H_
3,260
28.116071
79
h
gvisor
gvisor-master/test/util/temp_path.h
// Copyright 2018 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef GVISOR_TEST_UTIL_TEMP_PATH_H_ #define GVISOR_TEST_UTIL_TEMP_PATH_H_ #include <sys/stat.h> #include <string> #include <utility> #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "test/util/posix_error.h" namespace gvisor { namespace testing { // Return a new temp filename, intended to be unique system-wide. std::string NextTempBasename(); // Returns an absolute path for a file in `dir` that does not yet exist. // Distinct calls to NewTempAbsPathInDir from the same process, even from // multiple threads, are guaranteed to return different paths. Distinct calls to // NewTempAbsPathInDir from different processes are not synchronized. std::string NewTempAbsPathInDir(absl::string_view const dir); // Like NewTempAbsPathInDir, but the returned path is in the test's temporary // directory, as provided by the testing framework. std::string NewTempAbsPath(); // Like NewTempAbsPathInDir, but the returned path is relative (to the current // working directory). std::string NewTempRelPath(); // Returns the absolute path for the test temp dir. std::string GetAbsoluteTestTmpdir(); // Represents a temporary file or directory. class TempPath { public: // Default creation mode for files. static constexpr mode_t kDefaultFileMode = 0644; // Default creation mode for directories. static constexpr mode_t kDefaultDirMode = 0755; // Creates a temporary file in directory `parent` with mode `mode` and // contents `content`. static PosixErrorOr<TempPath> CreateFileWith(absl::string_view parent, absl::string_view content, mode_t mode); // Creates an empty temporary subdirectory in directory `parent` with mode // `mode`. static PosixErrorOr<TempPath> CreateDirWith(absl::string_view parent, mode_t mode); // Creates a temporary symlink in directory `parent` to destination `dest`. static PosixErrorOr<TempPath> CreateSymlinkTo(absl::string_view parent, std::string const& dest); // Creates an empty temporary file in directory `parent` with mode // kDefaultFileMode. static PosixErrorOr<TempPath> CreateFileIn(absl::string_view parent); // Creates an empty temporary subdirectory in directory `parent` with mode // kDefaultDirMode. static PosixErrorOr<TempPath> CreateDirIn(absl::string_view parent); // Creates an empty temporary file in the test's temporary directory with mode // `mode`. static PosixErrorOr<TempPath> CreateFileMode(mode_t mode); // Creates an empty temporary file in the test's temporary directory with // mode kDefaultFileMode. static PosixErrorOr<TempPath> CreateFile(); // Creates an empty temporary subdirectory in the test's temporary directory // with mode kDefaultDirMode. static PosixErrorOr<TempPath> CreateDir(); // Constructs a TempPath that represents nothing. TempPath() = default; // Constructs a TempPath that represents the given path, which will be deleted // when the TempPath is destroyed. explicit TempPath(std::string path) : path_(std::move(path)) {} // Attempts to delete the represented temporary file or directory (in the // latter case, also attempts to delete its contents). ~TempPath(); // Attempts to delete the represented temporary file or directory, then // transfers ownership of the path represented by orig to this TempPath. TempPath(TempPath&& orig); TempPath& operator=(TempPath&& orig); // Changes the path this TempPath represents. If the TempPath already // represented a path, deletes and returns that path. Otherwise returns the // empty string. std::string reset(std::string newpath); std::string reset() { return reset(""); } // Forgets and returns the path this TempPath represents. The path is not // deleted. std::string release(); // Returns the path this TempPath represents. std::string path() const { return path_; } private: template <typename F> static PosixErrorOr<TempPath> CreateIn(absl::string_view const parent, F const& f) { std::string path = NewTempAbsPathInDir(parent); RETURN_IF_ERRNO(f(path)); return TempPath(std::move(path)); } std::string path_; }; } // namespace testing } // namespace gvisor #endif // GVISOR_TEST_UTIL_TEMP_PATH_H_
5,037
35.244604
80
h
gvisor
gvisor-master/test/util/temp_umask.h
// Copyright 2018 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef GVISOR_TEST_UTIL_TEMP_UMASK_H_ #define GVISOR_TEST_UTIL_TEMP_UMASK_H_ #include <sys/stat.h> #include <sys/types.h> namespace gvisor { namespace testing { class TempUmask { public: // Sets the process umask to `mask`. explicit TempUmask(mode_t mask) : old_mask_(umask(mask)) {} // Sets the process umask to its previous value. ~TempUmask() { umask(old_mask_); } private: mode_t old_mask_; }; } // namespace testing } // namespace gvisor #endif // GVISOR_TEST_UTIL_TEMP_UMASK_H_
1,104
26.625
75
h
gvisor
gvisor-master/test/util/test_util.h
// Copyright 2018 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Utilities for syscall testing. // // Initialization // ============== // // Prior to calling RUN_ALL_TESTS, all tests must use TestInit(&argc, &argv). // See the TestInit function for exact side-effects and semantics. // // Configuration // ============= // // IsRunningOnGvisor returns true if the test is known to be running on gVisor. // GvisorPlatform can be used to get more detail: // // if (GvisorPlatform() == Platform::kPtrace) { // ... // } // // SetupGvisorDeathTest ensures that signal handling does not interfere with /// tests that rely on fatal signals. // // Matchers // ======== // // ElementOf(xs) matches if the matched value is equal to an element of the // container xs. Example: // // // PASS // EXPECT_THAT(1, ElementOf({0, 1, 2})); // // // FAIL // // Value of: 3 // // Expected: one of {0, 1, 2} // // Actual: 3 // EXPECT_THAT(3, ElementOf({0, 1, 2})); // // SyscallSucceeds() matches if the syscall is successful. A successful syscall // is defined by either a return value not equal to -1, or a return value of -1 // with an errno of 0 (which is a possible successful return for e.g. // PTRACE_PEEK). Example: // // // PASS // EXPECT_THAT(open("/dev/null", O_RDONLY), SyscallSucceeds()); // // // FAIL // // Value of: open("/", O_RDWR) // // Expected: not -1 (success) // // Actual: -1 (of type int), with errno 21 (Is a directory) // EXPECT_THAT(open("/", O_RDWR), SyscallSucceeds()); // // SyscallSucceedsWithValue(m) matches if the syscall is successful, and the // value also matches m. Example: // // // PASS // EXPECT_THAT(read(4, buf, 8192), SyscallSucceedsWithValue(8192)); // // // FAIL // // Value of: read(-1, buf, 8192) // // Expected: is equal to 8192 // // Actual: -1 (of type long), with errno 9 (Bad file number) // EXPECT_THAT(read(-1, buf, 8192), SyscallSucceedsWithValue(8192)); // // // FAIL // // Value of: read(4, buf, 1) // // Expected: is > 4096 // // Actual: 1 (of type long) // EXPECT_THAT(read(4, buf, 1), SyscallSucceedsWithValue(Gt(4096))); // // SyscallFails() matches if the syscall is unsuccessful. An unsuccessful // syscall is defined by a return value of -1 with a non-zero errno. Example: // // // PASS // EXPECT_THAT(open("/", O_RDWR), SyscallFails()); // // // FAIL // // Value of: open("/dev/null", O_RDONLY) // // Expected: -1 (failure) // // Actual: 0 (of type int) // EXPECT_THAT(open("/dev/null", O_RDONLY), SyscallFails()); // // SyscallFailsWithErrno(m) matches if the syscall is unsuccessful, and errno // matches m. Example: // // // PASS // EXPECT_THAT(open("/", O_RDWR), SyscallFailsWithErrno(EISDIR)); // // // PASS // EXPECT_THAT(open("/etc/passwd", O_RDWR | O_DIRECTORY), // SyscallFailsWithErrno(AnyOf(EACCES, ENOTDIR))); // // // FAIL // // Value of: open("/dev/null", O_RDONLY) // // Expected: -1 (failure) with errno 21 (Is a directory) // // Actual: 0 (of type int) // EXPECT_THAT(open("/dev/null", O_RDONLY), SyscallFailsWithErrno(EISDIR)); // // // FAIL // // Value of: open("/", O_RDWR) // // Expected: -1 (failure) with errno 22 (Invalid argument) // // Actual: -1 (of type int), failure, but with errno 21 (Is a directory) // EXPECT_THAT(open("/", O_RDWR), SyscallFailsWithErrno(EINVAL)); // // Because the syscall matchers encode save/restore functionality, their meaning // should not be inverted via Not. That is, AnyOf(SyscallSucceedsWithValue(1), // SyscallSucceedsWithValue(2)) is permitted, but not // Not(SyscallFailsWithErrno(EPERM)). // // Syscalls // ======== // // RetryEINTR wraps a function that returns -1 and sets errno on failure // to be automatically retried when EINTR occurs. Example: // // auto rv = RetryEINTR(waitpid)(pid, &status, 0); // // ReadFd/WriteFd/PreadFd/PwriteFd are interface-compatible wrappers around the // read/write/pread/pwrite syscalls to handle both EINTR and partial // reads/writes. Example: // // EXPECT_THAT(ReadFd(fd, &buf, size), SyscallSucceedsWithValue(size)); // // General Utilities // ================= // // ApplyVec(f, xs) returns a vector containing the result of applying function // `f` to each value in `xs`. // // AllBitwiseCombinations takes a variadic number of ranges containing integers // and returns a vector containing every integer that can be formed by ORing // together exactly one integer from each list. List<T> is an alias for // std::initializer_list<T> that makes AllBitwiseCombinations more ergonomic to // use with list literals (initializer lists do not otherwise participate in // template argument deduction). Example: // // EXPECT_THAT( // AllBitwiseCombinations<int>( // List<int>{SOCK_DGRAM, SOCK_STREAM}, // List<int>{0, SOCK_NONBLOCK}), // Contains({SOCK_DGRAM, SOCK_STREAM, SOCK_DGRAM | SOCK_NONBLOCK, // SOCK_STREAM | SOCK_NONBLOCK})); // // VecCat takes a variadic number of containers and returns a vector containing // the concatenated contents. // // VecAppend takes an initial container and a variadic number of containers and // appends each to the initial container. // // RandomizeBuffer will use MTRandom to fill the given buffer with random bytes. // // GenerateIovecs will return the smallest number of iovec arrays for writing a // given total number of bytes to a file, each iovec array size up to IOV_MAX, // each iovec in each array pointing to the same buffer. #ifndef GVISOR_TEST_UTIL_TEST_UTIL_H_ #define GVISOR_TEST_UTIL_TEST_UTIL_H_ #include <stddef.h> #include <stdlib.h> #include <sys/uio.h> #include <time.h> #include <unistd.h> #include <algorithm> #include <cerrno> #include <initializer_list> #include <iterator> #include <string> #include <thread> // NOLINT: using std::thread::hardware_concurrency(). #include <utility> #include <vector> #include "gmock/gmock.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_format.h" #include "absl/strings/string_view.h" #include "absl/time/time.h" #include "test/util/fs_util.h" #include "test/util/logging.h" #include "test/util/posix_error.h" #include "test/util/save_util.h" namespace gvisor { namespace testing { constexpr char kTestOnGvisor[] = "TEST_ON_GVISOR"; // TestInit must be called prior to RUN_ALL_TESTS. // // This parses all arguments and adjusts argc and argv appropriately. // // TestInit may create background threads. void TestInit(int* argc, char*** argv); // SKIP_IF may be used to skip a test case. // // These cases are still emitted, but a SKIPPED line will appear. #define SKIP_IF(expr) \ do { \ if (expr) GTEST_SKIP() << #expr; \ } while (0) // Platform contains platform names. namespace Platform { constexpr char kNative[] = "native"; constexpr char kPtrace[] = "ptrace"; constexpr char kKVM[] = "kvm"; constexpr char kFuchsia[] = "fuchsia"; constexpr char kSystrap[] = "systrap"; } // namespace Platform bool IsRunningOnGvisor(); const std::string GvisorPlatform(); bool IsRunningWithHostinet(); bool IsIOUringEnabled(); #ifdef __linux__ void SetupGvisorDeathTest(); #endif struct KernelVersion { int major; int minor; int micro; }; bool operator==(const KernelVersion& first, const KernelVersion& second); PosixErrorOr<KernelVersion> ParseKernelVersion(absl::string_view vers_string); PosixErrorOr<KernelVersion> GetKernelVersion(); static const size_t kPageSize = sysconf(_SC_PAGESIZE); enum class CPUVendor { kIntel, kAMD, kUnknownVendor }; CPUVendor GetCPUVendor(); inline int NumCPUs() { return std::thread::hardware_concurrency(); } // Converts cpu_set_t to a std::string for easy examination. std::string CPUSetToString(const cpu_set_t& set, size_t cpus = CPU_SETSIZE); struct OpenFd { // fd is the open file descriptor number. int fd = -1; // link is the resolution of the symbolic link. std::string link; }; // Make it easier to log OpenFds to error streams. std::ostream& operator<<(std::ostream& out, std::vector<OpenFd> const& v); std::ostream& operator<<(std::ostream& out, OpenFd const& ofd); // Gets a detailed list of open fds for this process. PosixErrorOr<std::vector<OpenFd>> GetOpenFDs(); // Returns the number of hard links to a path. PosixErrorOr<uint64_t> Links(const std::string& path); inline uint64_t ns_elapsed(const struct timespec& begin, const struct timespec& end) { return (end.tv_sec - begin.tv_sec) * 1000000000 + (end.tv_nsec - begin.tv_nsec); } inline uint64_t ms_elapsed(const struct timespec& begin, const struct timespec& end) { return ns_elapsed(begin, end) / 1000000; } namespace internal { template <typename Container> class ElementOfMatcher { public: explicit ElementOfMatcher(Container container) : container_(::std::move(container)) {} template <typename T> bool MatchAndExplain(T const& rv, ::testing::MatchResultListener* const listener) const { using std::count; return count(container_.begin(), container_.end(), rv) != 0; } void DescribeTo(::std::ostream* const os) const { *os << "one of {"; char const* sep = ""; for (auto const& elem : container_) { *os << sep << elem; sep = ", "; } *os << "}"; } void DescribeNegationTo(::std::ostream* const os) const { *os << "none of {"; char const* sep = ""; for (auto const& elem : container_) { *os << sep << elem; sep = ", "; } *os << "}"; } private: Container const container_; }; template <typename E> class SyscallSuccessMatcher { public: explicit SyscallSuccessMatcher(E expected) : expected_(::std::move(expected)) {} template <typename T> operator ::testing::Matcher<T>() const { // E is one of three things: // - T, or a type losslessly and implicitly convertible to T. // - A monomorphic Matcher<T>. // - A polymorphic matcher. // SafeMatcherCast handles any of the above correctly. // // Similarly, gMock will invoke this conversion operator to obtain a // monomorphic matcher (this is how polymorphic matchers are implemented). return ::testing::MakeMatcher( new Impl<T>(::testing::SafeMatcherCast<T>(expected_))); } private: template <typename T> class Impl : public ::testing::MatcherInterface<T> { public: explicit Impl(::testing::Matcher<T> matcher) : matcher_(::std::move(matcher)) {} bool MatchAndExplain( T const& rv, ::testing::MatchResultListener* const listener) const override { if (rv == static_cast<decltype(rv)>(-1) && errno != 0) { *listener << "with errno " << PosixError(errno); return false; } bool match = matcher_.MatchAndExplain(rv, listener); if (match) { MaybeSave(); } return match; } void DescribeTo(::std::ostream* const os) const override { matcher_.DescribeTo(os); } void DescribeNegationTo(::std::ostream* const os) const override { matcher_.DescribeNegationTo(os); } private: ::testing::Matcher<T> matcher_; }; private: E expected_; }; // A polymorphic matcher equivalent to ::testing::internal::AnyMatcher, except // not in namespace ::testing::internal, and describing SyscallSucceeds()'s // match constraints (which are enforced by SyscallSuccessMatcher::Impl). class AnySuccessValueMatcher { public: template <typename T> operator ::testing::Matcher<T>() const { return ::testing::MakeMatcher(new Impl<T>()); } private: template <typename T> class Impl : public ::testing::MatcherInterface<T> { public: bool MatchAndExplain( T const& rv, ::testing::MatchResultListener* const listener) const override { return true; } void DescribeTo(::std::ostream* const os) const override { *os << "not -1 (success)"; } void DescribeNegationTo(::std::ostream* const os) const override { *os << "-1 (failure)"; } }; }; class SyscallFailureMatcher { public: explicit SyscallFailureMatcher(::testing::Matcher<int> errno_matcher) : errno_matcher_(std::move(errno_matcher)) {} template <typename T> bool MatchAndExplain(T const& rv, ::testing::MatchResultListener* const listener) const { if (rv != static_cast<decltype(rv)>(-1)) { return false; } int actual_errno = errno; *listener << "with errno " << PosixError(actual_errno); bool match = errno_matcher_.MatchAndExplain(actual_errno, listener); if (match) { MaybeSave(); } return match; } void DescribeTo(::std::ostream* const os) const { *os << "-1 (failure), with errno "; errno_matcher_.DescribeTo(os); } void DescribeNegationTo(::std::ostream* const os) const { *os << "not -1 (success), with errno "; errno_matcher_.DescribeNegationTo(os); } private: ::testing::Matcher<int> errno_matcher_; }; class SpecificErrnoMatcher : public ::testing::MatcherInterface<int> { public: explicit SpecificErrnoMatcher(int const expected) : expected_(expected) {} bool MatchAndExplain( int const actual_errno, ::testing::MatchResultListener* const listener) const override { return actual_errno == expected_; } void DescribeTo(::std::ostream* const os) const override { *os << PosixError(expected_); } void DescribeNegationTo(::std::ostream* const os) const override { *os << "not " << PosixError(expected_); } private: int const expected_; }; inline ::testing::Matcher<int> SpecificErrno(int const expected) { return ::testing::MakeMatcher(new SpecificErrnoMatcher(expected)); } } // namespace internal template <typename Container> inline ::testing::PolymorphicMatcher<internal::ElementOfMatcher<Container>> ElementOf(Container container) { return ::testing::MakePolymorphicMatcher( internal::ElementOfMatcher<Container>(::std::move(container))); } template <typename T> inline ::testing::PolymorphicMatcher< internal::ElementOfMatcher<::std::vector<T>>> ElementOf(::std::initializer_list<T> elems) { return ::testing::MakePolymorphicMatcher( internal::ElementOfMatcher<::std::vector<T>>(::std::vector<T>(elems))); } template <typename E> inline internal::SyscallSuccessMatcher<E> SyscallSucceedsWithValue(E expected) { return internal::SyscallSuccessMatcher<E>(::std::move(expected)); } inline internal::SyscallSuccessMatcher<internal::AnySuccessValueMatcher> SyscallSucceeds() { return SyscallSucceedsWithValue( ::gvisor::testing::internal::AnySuccessValueMatcher()); } inline ::testing::PolymorphicMatcher<internal::SyscallFailureMatcher> SyscallFailsWithErrno(::testing::Matcher<int> expected) { return ::testing::MakePolymorphicMatcher( internal::SyscallFailureMatcher(::std::move(expected))); } // Overload taking an int so that SyscallFailsWithErrno(<specific errno>) uses // internal::SpecificErrno (which stringifies the errno) rather than // ::testing::Eq (which doesn't). inline ::testing::PolymorphicMatcher<internal::SyscallFailureMatcher> SyscallFailsWithErrno(int const expected) { return SyscallFailsWithErrno(internal::SpecificErrno(expected)); } inline ::testing::PolymorphicMatcher<internal::SyscallFailureMatcher> SyscallFails() { return SyscallFailsWithErrno(::testing::Gt(0)); } // As of GCC 7.2, -Wall => -Wc++17-compat => -Wnoexcept-type generates an // irrelevant, non-actionable warning about ABI compatibility when // RetryEINTRImpl is constructed with a noexcept function, such as glibc's // syscall(). See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=80985. #if defined(__GNUC__) && !defined(__clang__) && \ (__GNUC__ > 7 || (__GNUC__ == 7 && __GNUC_MINOR__ >= 2)) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wnoexcept-type" #endif namespace internal { template <typename F> struct RetryEINTRImpl { F const f; explicit constexpr RetryEINTRImpl(F f) : f(std::move(f)) {} template <typename... Args> auto operator()(Args&&... args) const -> decltype(f(std::forward<Args>(args)...)) { while (true) { errno = 0; auto const ret = f(std::forward<Args>(args)...); if (ret != -1 || errno != EINTR) { return ret; } } } }; } // namespace internal template <typename F> constexpr internal::RetryEINTRImpl<F> RetryEINTR(F&& f) { return internal::RetryEINTRImpl<F>(std::forward<F>(f)); } #if defined(__GNUC__) && !defined(__clang__) && \ (__GNUC__ > 7 || (__GNUC__ == 7 && __GNUC_MINOR__ >= 2)) #pragma GCC diagnostic pop #endif namespace internal { template <typename F> ssize_t ApplyFileIoSyscall(F const& f, size_t const count) { size_t completed = 0; // `do ... while` because some callers actually want to make a syscall with a // count of 0. do { auto const cur = RetryEINTR(f)(completed); if (cur < 0) { return cur; } else if (cur == 0) { break; } completed += cur; } while (completed < count); return completed; } } // namespace internal inline PosixErrorOr<std::string> ReadAllFd(int fd) { std::string all; all.reserve(128 * 1024); // arbitrary. std::vector<char> buffer(16 * 1024); for (;;) { auto const bytes = RetryEINTR(read)(fd, buffer.data(), buffer.size()); if (bytes < 0) { return PosixError(errno, "file read"); } if (bytes == 0) { return std::move(all); } if (bytes > 0) { all.append(buffer.data(), bytes); } } } inline ssize_t ReadFd(int fd, void* buf, size_t count) { return internal::ApplyFileIoSyscall( [&](size_t completed) { return read(fd, static_cast<char*>(buf) + completed, count - completed); }, count); } inline ssize_t WriteFd(int fd, void const* buf, size_t count) { return internal::ApplyFileIoSyscall( [&](size_t completed) { return write(fd, static_cast<char const*>(buf) + completed, count - completed); }, count); } inline ssize_t PreadFd(int fd, void* buf, size_t count, off_t offset) { return internal::ApplyFileIoSyscall( [&](size_t completed) { return pread(fd, static_cast<char*>(buf) + completed, count - completed, offset + completed); }, count); } inline ssize_t PwriteFd(int fd, void const* buf, size_t count, off_t offset) { return internal::ApplyFileIoSyscall( [&](size_t completed) { return pwrite(fd, static_cast<char const*>(buf) + completed, count - completed, offset + completed); }, count); } template <typename T> using List = std::initializer_list<T>; namespace internal { template <typename T> void AppendAllBitwiseCombinations(std::vector<T>* combinations, T current) { combinations->push_back(current); } template <typename T, typename Arg, typename... Args> void AppendAllBitwiseCombinations(std::vector<T>* combinations, T current, Arg&& next, Args&&... rest) { for (auto const option : next) { AppendAllBitwiseCombinations(combinations, current | option, rest...); } } inline size_t CombinedSize(size_t accum) { return accum; } template <typename T, typename... Args> size_t CombinedSize(size_t accum, T const& x, Args&&... xs) { return CombinedSize(accum + x.size(), std::forward<Args>(xs)...); } // Base case: no more containers, so do nothing. template <typename T> void DoMoveExtendContainer(T* c) {} // Append each container next to c. template <typename T, typename U, typename... Args> void DoMoveExtendContainer(T* c, U&& next, Args&&... rest) { std::move(std::begin(next), std::end(next), std::back_inserter(*c)); DoMoveExtendContainer(c, std::forward<Args>(rest)...); } } // namespace internal template <typename T = int> std::vector<T> AllBitwiseCombinations() { return std::vector<T>(); } template <typename T = int, typename... Args> std::vector<T> AllBitwiseCombinations(Args&&... args) { std::vector<T> combinations; internal::AppendAllBitwiseCombinations(&combinations, 0, args...); return combinations; } template <typename T, typename U, typename F> std::vector<T> ApplyVec(F const& f, std::vector<U> const& us) { std::vector<T> vec; vec.reserve(us.size()); for (auto const& u : us) { vec.push_back(f(u)); } return vec; } template <typename T, typename U> std::vector<T> ApplyVecToVec(std::vector<std::function<T(U)>> const& fs, std::vector<U> const& us) { std::vector<T> vec; vec.reserve(us.size() * fs.size()); for (auto const& f : fs) { for (auto const& u : us) { vec.push_back(f(u)); } } return vec; } // Moves all elements from the containers `args` to the end of `c`. template <typename T, typename... Args> void VecAppend(T* c, Args&&... args) { c->reserve(internal::CombinedSize(c->size(), args...)); internal::DoMoveExtendContainer(c, std::forward<Args>(args)...); } // Returns a vector containing the concatenated contents of the containers // `args`. template <typename T, typename... Args> std::vector<T> VecCat(Args&&... args) { std::vector<T> combined; VecAppend(&combined, std::forward<Args>(args)...); return combined; } #define RETURN_ERROR_IF_SYSCALL_FAIL(syscall) \ do { \ if ((syscall) < 0 && errno != 0) { \ return PosixError(errno, #syscall); \ } \ } while (false) // Fill the given buffer with random bytes. void RandomizeBuffer(void* buffer, size_t len); template <typename T> inline PosixErrorOr<T> Atoi(absl::string_view str) { T ret; if (!absl::SimpleAtoi<T>(str, &ret)) { return PosixError(EINVAL, "String not a number."); } return ret; } inline PosixErrorOr<uint64_t> AtoiBase(absl::string_view str, int base) { if (base > 255 || base < 2) { return PosixError(EINVAL, "Invalid Base"); } uint64_t ret = 0; if (!absl::numbers_internal::safe_strtou64_base(str, &ret, base)) { return PosixError(EINVAL, "String not a number."); } return ret; } inline PosixErrorOr<double> Atod(absl::string_view str) { double ret; if (!absl::SimpleAtod(str, &ret)) { return PosixError(EINVAL, "String not a double type."); } return ret; } inline PosixErrorOr<float> Atof(absl::string_view str) { float ret; if (!absl::SimpleAtof(str, &ret)) { return PosixError(EINVAL, "String not a float type."); } return ret; } // Return the smallest number of iovec arrays that can be used to write // "total_bytes" number of bytes, each iovec writing one "buf". std::vector<std::vector<struct iovec>> GenerateIovecs(uint64_t total_size, void* buf, size_t buflen); // Returns bytes in 'n' megabytes. Used for readability. uint64_t Megabytes(uint64_t n); // Predicate for checking that a value is within some tolerance of another // value. Returns true iff current is in the range [target * (1 - tolerance), // target * (1 + tolerance)]. bool Equivalent(uint64_t current, uint64_t target, double tolerance); // Matcher wrapping the Equivalent predicate. MATCHER_P2(EquivalentWithin, target, tolerance, std::string(negation ? "Isn't" : "Is") + ::absl::StrFormat(" within %.2f%% of the target of %zd bytes", tolerance * 100, target)) { if (target == 0) { *result_listener << ::absl::StreamFormat("difference of infinity%%"); } else { int64_t delta = static_cast<int64_t>(arg) - static_cast<int64_t>(target); double delta_percent = static_cast<double>(delta) / static_cast<double>(target) * 100; *result_listener << ::absl::StreamFormat("difference of %.2f%%", delta_percent); } return Equivalent(arg, target, tolerance); } // Returns the absolute path to the a data dependency. 'path' is the runfile // location relative to workspace root. #ifdef __linux__ std::string RunfilePath(std::string path); #endif void TestInit(int* argc, char*** argv); int RunAllTests(void); } // namespace testing } // namespace gvisor #endif // GVISOR_TEST_UTIL_TEST_UTIL_H_
24,797
29.389706
80
h
gvisor
gvisor-master/test/util/thread_util.h
// Copyright 2018 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef GVISOR_TEST_UTIL_THREAD_UTIL_H_ #define GVISOR_TEST_UTIL_THREAD_UTIL_H_ #include <pthread.h> #ifdef __linux__ #include <sys/syscall.h> #endif #include <unistd.h> #include <functional> #include <utility> #include "test/util/logging.h" namespace gvisor { namespace testing { // ScopedThread is a minimal wrapper around pthreads. // // This is used in lieu of more complex mechanisms because it provides very // predictable behavior (no messing with timers, etc.) The thread will // automatically joined when it is destructed (goes out of scope), but can be // joined manually as well. class ScopedThread { public: // Constructs a thread that executes f exactly once. explicit ScopedThread(std::function<void*()> f) : f_(std::move(f)) { CreateThread(); } explicit ScopedThread(const std::function<void()>& f) { f_ = [=] { f(); return nullptr; }; CreateThread(); } ScopedThread(const ScopedThread& other) = delete; ScopedThread& operator=(const ScopedThread& other) = delete; // Joins the thread. ~ScopedThread() { Join(); } // Waits until this thread has finished executing. Join is idempotent and may // be called multiple times, however Join itself is not thread-safe. void* Join() { if (!joined_) { TEST_PCHECK(pthread_join(pt_, &retval_) == 0); joined_ = true; } return retval_; } private: void CreateThread() { TEST_PCHECK_MSG(pthread_create( &pt_, /* attr = */ nullptr, +[](void* arg) -> void* { return static_cast<ScopedThread*>(arg)->f_(); }, this) == 0, "thread creation failed"); } std::function<void*()> f_; pthread_t pt_; bool joined_ = false; void* retval_ = nullptr; }; #ifdef __linux__ inline pid_t gettid() { return syscall(SYS_gettid); } #endif } // namespace testing } // namespace gvisor #endif // GVISOR_TEST_UTIL_THREAD_UTIL_H_
2,606
26.734043
79
h
gvisor
gvisor-master/test/util/time_util.h
// Copyright 2019 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef GVISOR_TEST_UTIL_TIME_UTIL_H_ #define GVISOR_TEST_UTIL_TIME_UTIL_H_ #include "absl/time/time.h" namespace gvisor { namespace testing { // Sleep for at least the specified duration. Avoids glibc. void SleepSafe(absl::Duration duration); } // namespace testing } // namespace gvisor #endif // GVISOR_TEST_UTIL_TIME_UTIL_H_
934
30.166667
75
h
gvisor
gvisor-master/test/util/timer_util.h
// Copyright 2018 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef GVISOR_TEST_UTIL_TIMER_UTIL_H_ #define GVISOR_TEST_UTIL_TIMER_UTIL_H_ #include <errno.h> #ifdef __linux__ #include <sys/syscall.h> #endif #include <sys/time.h> #include <functional> #include "gmock/gmock.h" #include "absl/time/time.h" #include "test/util/cleanup.h" #include "test/util/logging.h" #include "test/util/posix_error.h" #include "test/util/test_util.h" namespace gvisor { namespace testing { // From Linux's include/uapi/asm-generic/siginfo.h. #ifndef sigev_notify_thread_id #define sigev_notify_thread_id _sigev_un._tid #endif // Returns the current time. absl::Time Now(clockid_t id); // MonotonicTimer is a simple timer that uses a monotonic clock. class MonotonicTimer { public: MonotonicTimer() {} absl::Duration Duration() { struct timespec ts; TEST_CHECK(clock_gettime(CLOCK_MONOTONIC, &ts) == 0); return absl::TimeFromTimespec(ts) - start_; } void Start() { struct timespec ts; TEST_CHECK(clock_gettime(CLOCK_MONOTONIC, &ts) == 0); start_ = absl::TimeFromTimespec(ts); } protected: absl::Time start_; }; // Sets the given itimer and returns a cleanup function that restores the // previous itimer when it goes out of scope. inline PosixErrorOr<Cleanup> ScopedItimer(int which, struct itimerval const& new_value) { struct itimerval old_value; int rc = setitimer(which, &new_value, &old_value); MaybeSave(); if (rc < 0) { return PosixError(errno, "setitimer failed"); } return Cleanup(std::function<void(void)>([which, old_value] { EXPECT_THAT(setitimer(which, &old_value, nullptr), SyscallSucceeds()); })); } #ifdef __linux__ // RAII type for a kernel "POSIX" interval timer. (The kernel provides system // calls such as timer_create that behave very similarly, but not identically, // to those described by timer_create(2); in particular, the kernel does not // implement SIGEV_THREAD. glibc builds POSIX-compliant interval timers based on // these kernel interval timers.) // // Compare implementation to FileDescriptor. class IntervalTimer { public: IntervalTimer() = default; explicit IntervalTimer(int id) { set_id(id); } IntervalTimer(IntervalTimer&& orig) : id_(orig.release()) {} IntervalTimer& operator=(IntervalTimer&& orig) { if (this == &orig) return *this; reset(orig.release()); return *this; } IntervalTimer(const IntervalTimer& other) = delete; IntervalTimer& operator=(const IntervalTimer& other) = delete; ~IntervalTimer() { reset(); } int get() const { return id_; } int release() { int const id = id_; id_ = -1; return id; } void reset() { reset(-1); } void reset(int id) { if (id_ >= 0) { TEST_PCHECK(syscall(SYS_timer_delete, id_) == 0); MaybeSave(); } set_id(id); } PosixErrorOr<struct itimerspec> Set( int flags, const struct itimerspec& new_value) const { struct itimerspec old_value = {}; if (syscall(SYS_timer_settime, id_, flags, &new_value, &old_value) < 0) { return PosixError(errno, "timer_settime"); } MaybeSave(); return old_value; } PosixErrorOr<struct itimerspec> Get() const { struct itimerspec curr_value = {}; if (syscall(SYS_timer_gettime, id_, &curr_value) < 0) { return PosixError(errno, "timer_gettime"); } MaybeSave(); return curr_value; } PosixErrorOr<int> Overruns() const { int rv = syscall(SYS_timer_getoverrun, id_); if (rv < 0) { return PosixError(errno, "timer_getoverrun"); } MaybeSave(); return rv; } private: void set_id(int id) { id_ = std::max(id, -1); } // Kernel timer_t is int; glibc timer_t is void*. int id_ = -1; }; // A wrapper around timer_create(2). PosixErrorOr<IntervalTimer> TimerCreate(clockid_t clockid, const struct sigevent& sev); #endif // __linux__ } // namespace testing } // namespace gvisor #endif // GVISOR_TEST_UTIL_TIMER_UTIL_H_
4,588
25.994118
80
h
gvisor
gvisor-master/test/util/uid_util.h
// Copyright 2018 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef GVISOR_TEST_SYSCALLS_UID_UTIL_H_ #define GVISOR_TEST_SYSCALLS_UID_UTIL_H_ #include "test/util/posix_error.h" namespace gvisor { namespace testing { // Returns true if the caller's real/effective/saved user/group IDs are all 0. PosixErrorOr<bool> IsRoot(); } // namespace testing } // namespace gvisor #endif // GVISOR_TEST_SYSCALLS_UID_UTIL_H_
957
30.933333
78
h
gvisor
gvisor-master/tools/xdp/bpf/drop.ebpf.c
// Copyright 2022 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <linux/bpf.h> #define section(secname) __attribute__((section(secname), used)) char __license[] section("license") = "Apache-2.0"; // You probably shouldn't change the section or function name. Each is used by // BPF tooling, and so changes can cause runtime failures. section("xdp") int xdp_prog(struct xdp_md *ctx) { return XDP_DROP; }
947
38.5
78
c
gvisor
gvisor-master/tools/xdp/bpf/pass.ebpf.c
// Copyright 2022 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <linux/bpf.h> #define section(secname) __attribute__((section(secname), used)) char __license[] section("license") = "Apache-2.0"; // You probably shouldn't change the section or function name. Each is used by // BPF tooling, and so changes can cause runtime failures. section("xdp") int xdp_prog(struct xdp_md *ctx) { return XDP_PASS; }
947
38.5
78
c
gvisor
gvisor-master/tools/xdp/bpf/tcpdump.ebpf.c
// Copyright 2022 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <linux/bpf.h> #define section(secname) __attribute__((section(secname), used)) char __license[] section("license") = "Apache-2.0"; // Helper functions are defined positionally in <linux/bpf.h>, and their // signatures are scattered throughout the kernel. They can be found via the // defining macro BPF_CALL_[0-5]. // TODO(b/240191988): Use vmlinux instead of this. static int (*bpf_redirect_map)(void *bpf_map, __u32 iface_index, __u64 flags) = (void *)51; struct bpf_map_def { unsigned int type; unsigned int key_size; unsigned int value_size; unsigned int max_entries; unsigned int map_flags; }; // A map of RX queue number to AF_XDP socket. We only ever use one key: 0. struct bpf_map_def section("maps") sock_map = { .type = BPF_MAP_TYPE_XSKMAP, // Note: "XSK" means AF_XDP socket. .key_size = sizeof(int), .value_size = sizeof(int), .max_entries = 1, }; section("xdp") int xdp_prog(struct xdp_md *ctx) { // Lookup the socket for the current RX queue. Veth devices by default have // only one RX queue. If one is found, redirect the packet to that socket. // Otherwise pass it on to the kernel network stack. return bpf_redirect_map(&sock_map, ctx->rx_queue_index, XDP_PASS); }
1,861
36.24
77
c
gvisor
gvisor-master/vdso/barrier.h
// Copyright 2018 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef VDSO_BARRIER_H_ #define VDSO_BARRIER_H_ namespace vdso { // Compiler Optimization barrier. inline void barrier(void) { __asm__ __volatile__("" ::: "memory"); } #if __x86_64__ inline void memory_barrier(void) { __asm__ __volatile__("mfence" ::: "memory"); } inline void read_barrier(void) { barrier(); } inline void write_barrier(void) { barrier(); } #elif __aarch64__ inline void memory_barrier(void) { __asm__ __volatile__("dmb ish" ::: "memory"); } inline void read_barrier(void) { __asm__ __volatile__("dmb ishld" ::: "memory"); } inline void write_barrier(void) { __asm__ __volatile__("dmb ishst" ::: "memory"); } #else #error "unsupported architecture" #endif } // namespace vdso #endif // VDSO_BARRIER_H_
1,335
25.72
75
h
gvisor
gvisor-master/vdso/compiler.h
// Copyright 2018 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef VDSO_COMPILER_H_ #define VDSO_COMPILER_H_ #define likely(x) __builtin_expect(!!(x), 1) #define unlikely(x) __builtin_expect(!!(x), 0) #ifndef __section #define __section(S) __attribute__((__section__(#S))) #endif #ifndef __aligned #define __aligned(N) __attribute__((__aligned__(N))) #endif #endif // VDSO_COMPILER_H_
928
29.966667
75
h
gvisor
gvisor-master/vdso/cycle_clock.h
// Copyright 2018 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef VDSO_CYCLE_CLOCK_H_ #define VDSO_CYCLE_CLOCK_H_ #include <stdint.h> #include "vdso/barrier.h" namespace vdso { #if __x86_64__ // TODO(b/74613497): The appropriate barrier instruction to use with rdtsc on // x86_64 depends on the vendor. Intel processors can use lfence but AMD may // need mfence, depending on MSR_F10H_DECFG_LFENCE_SERIALIZE_BIT. static inline uint64_t cycle_clock(void) { uint32_t lo, hi; asm volatile("lfence" : : : "memory"); asm volatile("rdtsc" : "=a"(lo), "=d"(hi)); return ((uint64_t)hi << 32) | lo; } #elif __aarch64__ static inline uint64_t cycle_clock(void) { uint64_t val; asm volatile("mrs %0, CNTVCT_EL0" : "=r"(val)::"memory"); return val; } #else #error "unsupported architecture" #endif } // namespace vdso #endif // VDSO_CYCLE_CLOCK_H_
1,402
25.980769
77
h
gvisor
gvisor-master/vdso/seqlock.h
// Copyright 2018 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Low level raw interfaces to the sequence counter used by the VDSO. #ifndef VDSO_SEQLOCK_H_ #define VDSO_SEQLOCK_H_ #include <stdint.h> #include "vdso/barrier.h" #include "vdso/compiler.h" namespace vdso { inline int32_t read_seqcount_begin(const uint64_t* s) { uint64_t seq = *s; read_barrier(); return seq & ~1; } inline int read_seqcount_retry(const uint64_t* s, uint64_t seq) { read_barrier(); return unlikely(*s != seq); } } // namespace vdso #endif // VDSO_SEQLOCK_H_
1,092
26.325
75
h
gvisor
gvisor-master/vdso/syscalls.h
// Copyright 2018 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // System call support for the VDSO. // // Provides fallback system call interfaces for getcpu() // and clock_gettime(). #ifndef VDSO_SYSCALLS_H_ #define VDSO_SYSCALLS_H_ #include <asm/unistd.h> #include <errno.h> #include <fcntl.h> #include <stddef.h> #include <sys/types.h> #define __stringify_1(x...) #x #define __stringify(x...) __stringify_1(x) namespace vdso { #if __x86_64__ struct getcpu_cache; static inline int sys_clock_gettime(clockid_t clock, struct timespec* ts) { int num = __NR_clock_gettime; asm volatile("syscall\n" : "+a"(num) : "D"(clock), "S"(ts) : "rcx", "r11", "memory"); return num; } static inline int sys_getcpu(unsigned* cpu, unsigned* node, struct getcpu_cache* cache) { int num = __NR_getcpu; asm volatile("syscall\n" : "+a"(num) : "D"(cpu), "S"(node), "d"(cache) : "rcx", "r11", "memory"); return num; } static inline void sys_rt_sigreturn(void) { asm volatile("movl $" __stringify(__NR_rt_sigreturn)", %eax \n" "syscall \n"); } #elif __aarch64__ static inline int sys_clock_gettime(clockid_t _clkid, struct timespec* _ts) { register struct timespec* ts asm("x1") = _ts; register clockid_t clkid asm("x0") = _clkid; register long ret asm("x0"); register long nr asm("x8") = __NR_clock_gettime; asm volatile("svc #0\n" : "=r"(ret) : "r"(clkid), "r"(ts), "r"(nr) : "memory"); return ret; } static inline int sys_clock_getres(clockid_t _clkid, struct timespec* _ts) { register struct timespec* ts asm("x1") = _ts; register clockid_t clkid asm("x0") = _clkid; register long ret asm("x0"); register long nr asm("x8") = __NR_clock_getres; asm volatile("svc #0\n" : "=r"(ret) : "r"(clkid), "r"(ts), "r"(nr) : "memory"); return ret; } static inline void sys_rt_sigreturn(void) { asm volatile("mov x8, #" __stringify(__NR_rt_sigreturn)" \n" "svc #0 \n"); } #else #error "unsupported architecture" #endif } // namespace vdso #endif // VDSO_SYSCALLS_H_
2,767
26.405941
77
h
gvisor
gvisor-master/vdso/vdso_time.h
// Copyright 2018 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef VDSO_VDSO_TIME_H_ #define VDSO_VDSO_TIME_H_ #include <time.h> namespace vdso { int ClockRealtime(struct timespec* ts); int ClockMonotonic(struct timespec* ts); } // namespace vdso #endif // VDSO_VDSO_TIME_H_
820
28.321429
75
h
criu
criu-master/compel/arch/aarch64/plugins/include/asm/syscall-types.h
#ifndef COMPEL_ARCH_SYSCALL_TYPES_H__ #define COMPEL_ARCH_SYSCALL_TYPES_H__ #define SA_RESTORER 0x04000000 typedef void rt_signalfn_t(int, siginfo_t *, void *); typedef rt_signalfn_t *rt_sighandler_t; typedef void rt_restorefn_t(void); typedef rt_restorefn_t *rt_sigrestore_t; #define _KNSIG 64 #define _NSIG_BPW 64 #define _KNSIG_WORDS (_KNSIG / _NSIG_BPW) typedef struct { unsigned long sig[_KNSIG_WORDS]; } k_rtsigset_t; typedef struct { rt_sighandler_t rt_sa_handler; unsigned long rt_sa_flags; rt_sigrestore_t rt_sa_restorer; k_rtsigset_t rt_sa_mask; } rt_sigaction_t; #endif /* COMPEL_ARCH_SYSCALL_TYPES_H__ */
632
20.827586
53
h
criu
criu-master/compel/arch/aarch64/src/lib/handle-elf.c
#include <string.h> #include <errno.h> #include "handle-elf.h" #include "piegen.h" #include "log.h" static const unsigned char __maybe_unused elf_ident_64_le[EI_NIDENT] = { 0x7f, 0x45, 0x4c, 0x46, 0x02, 0x01, 0x01, 0x00, /* clang-format */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; static const unsigned char __maybe_unused elf_ident_64_be[EI_NIDENT] = { 0x7f, 0x45, 0x4c, 0x46, 0x02, 0x02, 0x01, 0x00, /* clang-format */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; int handle_binary(void *mem, size_t size) { const unsigned char *elf_ident = #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ elf_ident_64_le; #else elf_ident_64_be; #endif if (memcmp(mem, elf_ident, sizeof(elf_ident_64_le)) == 0) return handle_elf_aarch64(mem, size); pr_err("Unsupported Elf format detected\n"); return -EINVAL; }
831
24.212121
72
c
criu
criu-master/compel/arch/aarch64/src/lib/infect.c
#include <stdlib.h> #include <sys/ptrace.h> #include <sys/types.h> #include <sys/uio.h> #include <asm/ptrace.h> #include <linux/elf.h> #include <compel/plugins/std/syscall-codes.h> #include "common/page.h" #include "uapi/compel/asm/infect-types.h" #include "log.h" #include "errno.h" #include "infect.h" #include "infect-priv.h" #include "asm/breakpoints.h" unsigned __page_size = 0; unsigned __page_shift = 0; /* * Injected syscall instruction */ const char code_syscall[] = { 0x01, 0x00, 0x00, 0xd4, /* SVC #0 */ 0x00, 0x00, 0x20, 0xd4 /* BRK #0 */ }; static const int code_syscall_aligned = round_up(sizeof(code_syscall), sizeof(long)); static inline void __always_unused __check_code_syscall(void) { BUILD_BUG_ON(code_syscall_aligned != BUILTIN_SYSCALL_SIZE); BUILD_BUG_ON(!is_log2(sizeof(code_syscall))); } int sigreturn_prep_regs_plain(struct rt_sigframe *sigframe, user_regs_struct_t *regs, user_fpregs_struct_t *fpregs) { struct fpsimd_context *fpsimd = RT_SIGFRAME_FPU(sigframe); memcpy(sigframe->uc.uc_mcontext.regs, regs->regs, sizeof(regs->regs)); sigframe->uc.uc_mcontext.sp = regs->sp; sigframe->uc.uc_mcontext.pc = regs->pc; sigframe->uc.uc_mcontext.pstate = regs->pstate; memcpy(fpsimd->vregs, fpregs->vregs, 32 * sizeof(__uint128_t)); fpsimd->fpsr = fpregs->fpsr; fpsimd->fpcr = fpregs->fpcr; fpsimd->head.magic = FPSIMD_MAGIC; fpsimd->head.size = sizeof(*fpsimd); return 0; } int sigreturn_prep_fpu_frame_plain(struct rt_sigframe *sigframe, struct rt_sigframe *rsigframe) { return 0; } int compel_get_task_regs(pid_t pid, user_regs_struct_t *regs, user_fpregs_struct_t *ext_regs, save_regs_t save, void *arg, __maybe_unused unsigned long flags) { user_fpregs_struct_t tmp, *fpsimd = ext_regs ? ext_regs : &tmp; struct iovec iov; int ret; pr_info("Dumping GP/FPU registers for %d\n", pid); iov.iov_base = regs; iov.iov_len = sizeof(user_regs_struct_t); if ((ret = ptrace(PTRACE_GETREGSET, pid, NT_PRSTATUS, &iov))) { pr_perror("Failed to obtain CPU registers for %d", pid); goto err; } iov.iov_base = fpsimd; iov.iov_len = sizeof(*fpsimd); if ((ret = ptrace(PTRACE_GETREGSET, pid, NT_PRFPREG, &iov))) { pr_perror("Failed to obtain FPU registers for %d", pid); goto err; } ret = save(arg, regs, fpsimd); err: return ret; } int compel_set_task_ext_regs(pid_t pid, user_fpregs_struct_t *ext_regs) { struct iovec iov; pr_info("Restoring GP/FPU registers for %d\n", pid); iov.iov_base = ext_regs; iov.iov_len = sizeof(*ext_regs); if (ptrace(PTRACE_SETREGSET, pid, NT_PRFPREG, &iov)) { pr_perror("Failed to set FPU registers for %d", pid); return -1; } return 0; } int compel_syscall(struct parasite_ctl *ctl, int nr, long *ret, unsigned long arg1, unsigned long arg2, unsigned long arg3, unsigned long arg4, unsigned long arg5, unsigned long arg6) { user_regs_struct_t regs = ctl->orig.regs; int err; regs.regs[8] = (unsigned long)nr; regs.regs[0] = arg1; regs.regs[1] = arg2; regs.regs[2] = arg3; regs.regs[3] = arg4; regs.regs[4] = arg5; regs.regs[5] = arg6; regs.regs[6] = 0; regs.regs[7] = 0; err = compel_execute_syscall(ctl, &regs, code_syscall); *ret = regs.regs[0]; return err; } void *remote_mmap(struct parasite_ctl *ctl, void *addr, size_t length, int prot, int flags, int fd, off_t offset) { long map; int err; err = compel_syscall(ctl, __NR_mmap, &map, (unsigned long)addr, length, prot, flags, fd, offset); if (err < 0 || (long)map < 0) map = 0; return (void *)map; } void parasite_setup_regs(unsigned long new_ip, void *stack, user_regs_struct_t *regs) { regs->pc = new_ip; if (stack) regs->sp = (unsigned long)stack; } bool arch_can_dump_task(struct parasite_ctl *ctl) { /* * TODO: Add proper check here */ return true; } int arch_fetch_sas(struct parasite_ctl *ctl, struct rt_sigframe *s) { long ret; int err; err = compel_syscall(ctl, __NR_sigaltstack, &ret, 0, (unsigned long)&s->uc.uc_stack, 0, 0, 0, 0); return err ? err : ret; } /* * Range for task size calculated from the following Linux kernel files: * arch/arm64/include/asm/memory.h * arch/arm64/Kconfig * * TODO: handle 32 bit tasks */ #define TASK_SIZE_MIN (1UL << 39) #define TASK_SIZE_MAX (1UL << 48) unsigned long compel_task_size(void) { unsigned long task_size; for (task_size = TASK_SIZE_MIN; task_size < TASK_SIZE_MAX; task_size <<= 1) if (munmap((void *)task_size, page_size())) break; return task_size; } static struct hwbp_cap *ptrace_get_hwbp_cap(pid_t pid) { static struct hwbp_cap info; static int available = -1; if (available == -1) { unsigned int val; struct iovec iovec = { .iov_base = &val, .iov_len = sizeof(val), }; if (ptrace(PTRACE_GETREGSET, pid, NT_ARM_HW_BREAK, &iovec) < 0) available = 0; else { info.arch = (char)((val >> 8) & 0xff); info.bp_count = (char)(val & 0xff); available = (info.arch != 0); } } return available == 1 ? &info : NULL; } int ptrace_set_breakpoint(pid_t pid, void *addr) { k_rtsigset_t block; struct hwbp_cap *info = ptrace_get_hwbp_cap(pid); struct user_hwdebug_state regs = {}; unsigned int ctrl = 0; struct iovec iovec; if (info == NULL || info->bp_count == 0) return 0; /* * The struct is copied from `arch/arm64/include/asm/hw_breakpoint.h` in * linux kernel: * struct arch_hw_breakpoint_ctrl { * __u32 __reserved : 19, * len : 8, * type : 2, * privilege : 2, * enabled : 1; * }; * * The part of `struct arch_hw_breakpoint_ctrl` bits meaning is defined * in <<ARM Architecture Reference Manual for A-profile architecture>>, * D13.3.2 DBGBCR<n>_EL1, Debug Breakpoint Control Registers. */ ctrl = ARM_BREAKPOINT_LEN_4; ctrl = (ctrl << 2) | ARM_BREAKPOINT_EXECUTE; ctrl = (ctrl << 2) | AARCH64_BREAKPOINT_EL0; ctrl = (ctrl << 1) | ENABLE_HBP; regs.dbg_regs[0].addr = (__u64)addr; regs.dbg_regs[0].ctrl = ctrl; iovec.iov_base = &regs; iovec.iov_len = (offsetof(struct user_hwdebug_state, dbg_regs) + sizeof(regs.dbg_regs[0])); if (ptrace(PTRACE_SETREGSET, pid, NT_ARM_HW_BREAK, &iovec)) return -1; /* * FIXME(issues/1429): SIGTRAP can't be blocked, otherwise its handler * will be reset to the default one. */ ksigfillset(&block); ksigdelset(&block, SIGTRAP); if (ptrace(PTRACE_SETSIGMASK, pid, sizeof(k_rtsigset_t), &block)) { pr_perror("Can't block signals for %d", pid); return -1; } if (ptrace(PTRACE_CONT, pid, NULL, NULL) != 0) { pr_perror("Unable to restart the stopped tracee process %d", pid); return -1; } return 1; } int ptrace_flush_breakpoints(pid_t pid) { struct hwbp_cap *info = ptrace_get_hwbp_cap(pid); struct user_hwdebug_state regs = {}; unsigned int ctrl = 0; struct iovec iovec; if (info == NULL || info->bp_count == 0) return 0; ctrl = ARM_BREAKPOINT_LEN_4; ctrl = (ctrl << 2) | ARM_BREAKPOINT_EXECUTE; ctrl = (ctrl << 2) | AARCH64_BREAKPOINT_EL0; ctrl = (ctrl << 1) | DISABLE_HBP; regs.dbg_regs[0].addr = 0ul; regs.dbg_regs[0].ctrl = ctrl; iovec.iov_base = &regs; iovec.iov_len = (offsetof(struct user_hwdebug_state, dbg_regs) + sizeof(regs.dbg_regs[0])); if (ptrace(PTRACE_SETREGSET, pid, NT_ARM_HW_BREAK, &iovec)) return -1; return 0; }
7,250
24.003448
115
c
criu
criu-master/compel/arch/aarch64/src/lib/include/uapi/asm/breakpoints.h
#ifndef __COMPEL_BREAKPOINTS_H__ #define __COMPEL_BREAKPOINTS_H__ #define ARCH_SI_TRAP TRAP_BRKPT #include <sys/types.h> #include <stdbool.h> struct hwbp_cap { char arch; char bp_count; }; /* copied from `linux/arch/arm64/include/asm/hw_breakpoint.h` */ /* Lengths */ #define ARM_BREAKPOINT_LEN_1 0x1 #define ARM_BREAKPOINT_LEN_2 0x3 #define ARM_BREAKPOINT_LEN_3 0x7 #define ARM_BREAKPOINT_LEN_4 0xf #define ARM_BREAKPOINT_LEN_5 0x1f #define ARM_BREAKPOINT_LEN_6 0x3f #define ARM_BREAKPOINT_LEN_7 0x7f #define ARM_BREAKPOINT_LEN_8 0xff /* Privilege Levels */ #define AARCH64_BREAKPOINT_EL1 1 #define AARCH64_BREAKPOINT_EL0 2 /* Breakpoint */ #define ARM_BREAKPOINT_EXECUTE 0 /* Watchpoints */ #define ARM_BREAKPOINT_LOAD 1 #define ARM_BREAKPOINT_STORE 2 #define AARCH64_ESR_ACCESS_MASK (1 << 6) #define DISABLE_HBP 0 #define ENABLE_HBP 1 int ptrace_set_breakpoint(pid_t pid, void *addr); int ptrace_flush_breakpoints(pid_t pid); #endif
948
21.069767
64
h
criu
criu-master/compel/arch/aarch64/src/lib/include/uapi/asm/infect-types.h
#ifndef UAPI_COMPEL_ASM_TYPES_H__ #define UAPI_COMPEL_ASM_TYPES_H__ #include <stdint.h> #include <signal.h> #include <sys/mman.h> #include <asm/ptrace.h> #define SIGMAX 64 #define SIGMAX_OLD 31 /* * Copied from the Linux kernel header arch/arm64/include/uapi/asm/ptrace.h * * A thread ARM CPU context */ typedef struct user_pt_regs user_regs_struct_t; typedef struct user_fpsimd_state user_fpregs_struct_t; #define __compel_arch_fetch_thread_area(tid, th) 0 #define compel_arch_fetch_thread_area(tctl) 0 #define compel_arch_get_tls_task(ctl, tls) #define compel_arch_get_tls_thread(tctl, tls) #define REG_RES(r) ((uint64_t)(r).regs[0]) #define REG_IP(r) ((uint64_t)(r).pc) #define SET_REG_IP(r, val) ((r).pc = (val)) #define REG_SP(r) ((uint64_t)((r).sp)) #define REG_SYSCALL_NR(r) ((uint64_t)(r).regs[8]) #define user_regs_native(pregs) true #define ARCH_SI_TRAP TRAP_BRKPT #define __NR(syscall, compat) \ ({ \ (void)compat; \ __NR_##syscall; \ }) #endif /* UAPI_COMPEL_ASM_TYPES_H__ */
1,047
23.372093
75
h
criu
criu-master/compel/arch/aarch64/src/lib/include/uapi/asm/sigframe.h
#ifndef UAPI_COMPEL_ASM_SIGFRAME_H__ #define UAPI_COMPEL_ASM_SIGFRAME_H__ #include <asm/sigcontext.h> #include <sys/ucontext.h> #include <stdint.h> /* Copied from the kernel header arch/arm64/include/uapi/asm/sigcontext.h */ #define FPSIMD_MAGIC 0x46508001 typedef struct fpsimd_context fpu_state_t; struct aux_context { struct fpsimd_context fpsimd; /* additional context to be added before "end" */ struct _aarch64_ctx end; }; // XXX: the idetifier rt_sigcontext is expected to be struct by the CRIU code #define rt_sigcontext sigcontext #include <compel/sigframe-common.h> /* Copied from the kernel source arch/arm64/kernel/signal.c */ struct rt_sigframe { siginfo_t info; ucontext_t uc; uint64_t fp; uint64_t lr; }; /* clang-format off */ #define ARCH_RT_SIGRETURN(new_sp, rt_sigframe) \ asm volatile( \ "mov sp, %0 \n" \ "mov x8, #"__stringify(__NR_rt_sigreturn)" \n" \ "svc #0 \n" \ : \ : "r"(new_sp) \ : "x8", "memory") /* clang-format on */ /* cr_sigcontext is copied from arch/arm64/include/uapi/asm/sigcontext.h */ struct cr_sigcontext { __u64 fault_address; /* AArch64 registers */ __u64 regs[31]; __u64 sp; __u64 pc; __u64 pstate; /* 4K reserved for FP/SIMD state and future expansion */ __u8 __reserved[4096] __attribute__((__aligned__(16))); }; #define RT_SIGFRAME_UC(rt_sigframe) (&rt_sigframe->uc) #define RT_SIGFRAME_REGIP(rt_sigframe) ((long unsigned int)(rt_sigframe)->uc.uc_mcontext.pc) #define RT_SIGFRAME_HAS_FPU(rt_sigframe) (1) #define RT_SIGFRAME_SIGCONTEXT(rt_sigframe) ((struct cr_sigcontext *)&(rt_sigframe)->uc.uc_mcontext) #define RT_SIGFRAME_AUX_CONTEXT(rt_sigframe) ((struct aux_context *)&(RT_SIGFRAME_SIGCONTEXT(rt_sigframe)->__reserved)) #define RT_SIGFRAME_FPU(rt_sigframe) (&RT_SIGFRAME_AUX_CONTEXT(rt_sigframe)->fpsimd) #define RT_SIGFRAME_OFFSET(rt_sigframe) 0 #define rt_sigframe_erase_sigset(sigframe) memset(&sigframe->uc.uc_sigmask, 0, sizeof(k_rtsigset_t)) #define rt_sigframe_copy_sigset(sigframe, from) memcpy(&sigframe->uc.uc_sigmask, from, sizeof(k_rtsigset_t)) #endif /* UAPI_COMPEL_ASM_SIGFRAME_H__ */
2,157
29.828571
119
h
criu
criu-master/compel/arch/arm/plugins/include/asm/syscall-types.h
#ifndef COMPEL_ARCH_SYSCALL_TYPES_H__ #define COMPEL_ARCH_SYSCALL_TYPES_H__ #define SA_RESTORER 0x04000000 typedef void rt_signalfn_t(int, siginfo_t *, void *); typedef rt_signalfn_t *rt_sighandler_t; typedef void rt_restorefn_t(void); typedef rt_restorefn_t *rt_sigrestore_t; #define _KNSIG 64 #define _NSIG_BPW 32 #define _KNSIG_WORDS (_KNSIG / _NSIG_BPW) typedef struct { unsigned long sig[_KNSIG_WORDS]; } k_rtsigset_t; typedef struct { rt_sighandler_t rt_sa_handler; unsigned long rt_sa_flags; rt_sigrestore_t rt_sa_restorer; k_rtsigset_t rt_sa_mask; } rt_sigaction_t; #endif /* COMPEL_ARCH_SYSCALL_TYPES_H__ */
632
20.827586
53
h
criu
criu-master/compel/arch/arm/src/lib/infect.c
#include <stdlib.h> #include <sys/ptrace.h> #include <sys/types.h> #include <string.h> #include <compel/plugins/std/syscall-codes.h> #include <compel/asm/processor-flags.h> #include <errno.h> #include "common/page.h" #include "uapi/compel/asm/infect-types.h" #include "log.h" #include "errno.h" #include "infect.h" #include "infect-priv.h" /* * Injected syscall instruction */ const char code_syscall[] = { 0x00, 0x00, 0x00, 0xef, /* SVC #0 */ 0xf0, 0x01, 0xf0, 0xe7 /* UDF #32 */ }; static const int code_syscall_aligned = round_up(sizeof(code_syscall), sizeof(long)); static inline __always_unused void __check_code_syscall(void) { BUILD_BUG_ON(code_syscall_aligned != BUILTIN_SYSCALL_SIZE); BUILD_BUG_ON(!is_log2(sizeof(code_syscall))); } int sigreturn_prep_regs_plain(struct rt_sigframe *sigframe, user_regs_struct_t *regs, user_fpregs_struct_t *fpregs) { struct aux_sigframe *aux = (struct aux_sigframe *)(void *)&sigframe->sig.uc.uc_regspace; sigframe->sig.uc.uc_mcontext.arm_r0 = regs->ARM_r0; sigframe->sig.uc.uc_mcontext.arm_r1 = regs->ARM_r1; sigframe->sig.uc.uc_mcontext.arm_r2 = regs->ARM_r2; sigframe->sig.uc.uc_mcontext.arm_r3 = regs->ARM_r3; sigframe->sig.uc.uc_mcontext.arm_r4 = regs->ARM_r4; sigframe->sig.uc.uc_mcontext.arm_r5 = regs->ARM_r5; sigframe->sig.uc.uc_mcontext.arm_r6 = regs->ARM_r6; sigframe->sig.uc.uc_mcontext.arm_r7 = regs->ARM_r7; sigframe->sig.uc.uc_mcontext.arm_r8 = regs->ARM_r8; sigframe->sig.uc.uc_mcontext.arm_r9 = regs->ARM_r9; sigframe->sig.uc.uc_mcontext.arm_r10 = regs->ARM_r10; sigframe->sig.uc.uc_mcontext.arm_fp = regs->ARM_fp; sigframe->sig.uc.uc_mcontext.arm_ip = regs->ARM_ip; sigframe->sig.uc.uc_mcontext.arm_sp = regs->ARM_sp; sigframe->sig.uc.uc_mcontext.arm_lr = regs->ARM_lr; sigframe->sig.uc.uc_mcontext.arm_pc = regs->ARM_pc; sigframe->sig.uc.uc_mcontext.arm_cpsr = regs->ARM_cpsr; memcpy(&aux->vfp.ufp.fpregs, &fpregs->fpregs, sizeof(aux->vfp.ufp.fpregs)); aux->vfp.ufp.fpscr = fpregs->fpscr; aux->vfp.magic = VFP_MAGIC; aux->vfp.size = VFP_STORAGE_SIZE; return 0; } int sigreturn_prep_fpu_frame_plain(struct rt_sigframe *sigframe, struct rt_sigframe *rsigframe) { return 0; } #define PTRACE_GETVFPREGS 27 int compel_get_task_regs(pid_t pid, user_regs_struct_t *regs, user_fpregs_struct_t *ext_regs, save_regs_t save, void *arg, __maybe_unused unsigned long flags) { user_fpregs_struct_t tmp, *vfp = ext_regs ? ext_regs : &tmp; int ret = -1; pr_info("Dumping GP/FPU registers for %d\n", pid); if (ptrace(PTRACE_GETVFPREGS, pid, NULL, vfp)) { pr_perror("Can't obtain FPU registers for %d", pid); goto err; } /* Did we come from a system call? */ if ((int)regs->ARM_ORIG_r0 >= 0) { /* Restart the system call */ switch ((long)(int)regs->ARM_r0) { case -ERESTARTNOHAND: case -ERESTARTSYS: case -ERESTARTNOINTR: regs->ARM_r0 = regs->ARM_ORIG_r0; regs->ARM_pc -= 4; break; case -ERESTART_RESTARTBLOCK: pr_warn("Will restore %d with interrupted system call\n", pid); regs->ARM_r0 = -EINTR; break; } } ret = save(arg, regs, vfp); err: return ret; } int compel_set_task_ext_regs(pid_t pid, user_fpregs_struct_t *ext_regs) { pr_info("Restoring GP/FPU registers for %d\n", pid); if (ptrace(PTRACE_SETVFPREGS, pid, NULL, ext_regs)) { pr_perror("Can't set FPU registers for %d", pid); return -1; } return 0; } int compel_syscall(struct parasite_ctl *ctl, int nr, long *ret, unsigned long arg1, unsigned long arg2, unsigned long arg3, unsigned long arg4, unsigned long arg5, unsigned long arg6) { user_regs_struct_t regs = ctl->orig.regs; int err; regs.ARM_r7 = (unsigned long)nr; regs.ARM_r0 = arg1; regs.ARM_r1 = arg2; regs.ARM_r2 = arg3; regs.ARM_r3 = arg4; regs.ARM_r4 = arg5; regs.ARM_r5 = arg6; err = compel_execute_syscall(ctl, &regs, code_syscall); *ret = regs.ARM_r0; return err; } void *remote_mmap(struct parasite_ctl *ctl, void *addr, size_t length, int prot, int flags, int fd, off_t offset) { long map; int err; if (offset & ~PAGE_MASK) return 0; err = compel_syscall(ctl, __NR_mmap2, &map, (unsigned long)addr, length, prot, flags, fd, offset >> 12); if (err < 0 || map > ctl->ictx.task_size) map = 0; return (void *)map; } void parasite_setup_regs(unsigned long new_ip, void *stack, user_regs_struct_t *regs) { regs->ARM_pc = new_ip; if (stack) regs->ARM_sp = (unsigned long)stack; /* Make sure flags are in known state */ regs->ARM_cpsr &= PSR_f | PSR_s | PSR_x | MODE32_BIT; } bool arch_can_dump_task(struct parasite_ctl *ctl) { /* * TODO: Add proper check here */ return true; } int arch_fetch_sas(struct parasite_ctl *ctl, struct rt_sigframe *s) { long ret; int err; err = compel_syscall(ctl, __NR_sigaltstack, &ret, 0, (unsigned long)&s->sig.uc.uc_stack, 0, 0, 0, 0); return err ? err : ret; } /* * Range for task size calculated from the following Linux kernel files: * arch/arm/include/asm/memory.h * arch/arm/Kconfig (PAGE_OFFSET values in Memory split section) */ #define TASK_SIZE_MIN 0x3f000000 #define TASK_SIZE_MAX 0xbf000000 #define SZ_1G 0x40000000 unsigned long compel_task_size(void) { unsigned long task_size; for (task_size = TASK_SIZE_MIN; task_size < TASK_SIZE_MAX; task_size += SZ_1G) if (munmap((void *)task_size, page_size())) break; return task_size; }
5,326
26.317949
115
c
criu
criu-master/compel/arch/arm/src/lib/include/uapi/asm/infect-types.h
#ifndef UAPI_COMPEL_ASM_TYPES_H__ #define UAPI_COMPEL_ASM_TYPES_H__ #include <stdint.h> #include <sys/mman.h> #define SIGMAX 64 #define SIGMAX_OLD 31 /* * Copied from the Linux kernel header arch/arm/include/asm/ptrace.h * * A thread ARM CPU context */ typedef struct { long uregs[18]; } user_regs_struct_t; #define __compel_arch_fetch_thread_area(tid, th) 0 #define compel_arch_fetch_thread_area(tctl) 0 #define compel_arch_get_tls_task(ctl, tls) #define compel_arch_get_tls_thread(tctl, tls) typedef struct user_vfp user_fpregs_struct_t; #define ARM_cpsr uregs[16] #define ARM_pc uregs[15] #define ARM_lr uregs[14] #define ARM_sp uregs[13] #define ARM_ip uregs[12] #define ARM_fp uregs[11] #define ARM_r10 uregs[10] #define ARM_r9 uregs[9] #define ARM_r8 uregs[8] #define ARM_r7 uregs[7] #define ARM_r6 uregs[6] #define ARM_r5 uregs[5] #define ARM_r4 uregs[4] #define ARM_r3 uregs[3] #define ARM_r2 uregs[2] #define ARM_r1 uregs[1] #define ARM_r0 uregs[0] #define ARM_ORIG_r0 uregs[17] /* Copied from arch/arm/include/asm/user.h */ struct user_vfp { unsigned long long fpregs[32]; unsigned long fpscr; }; struct user_vfp_exc { unsigned long fpexc; unsigned long fpinst; unsigned long fpinst2; }; #define REG_RES(regs) ((regs).ARM_r0) #define REG_IP(regs) ((regs).ARM_pc) #define SET_REG_IP(regs, val) ((regs).ARM_pc = (val)) #define REG_SP(regs) ((regs).ARM_sp) #define REG_SYSCALL_NR(regs) ((regs).ARM_r7) #define user_regs_native(pregs) true #define ARCH_SI_TRAP TRAP_BRKPT #define __NR(syscall, compat) \ ({ \ (void)compat; \ __NR_##syscall; \ }) #endif /* UAPI_COMPEL_ASM_TYPES_H__ */
1,737
21.868421
68
h
criu
criu-master/compel/arch/arm/src/lib/include/uapi/asm/processor-flags.h
#ifndef __CR_PROCESSOR_FLAGS_H__ #define __CR_PROCESSOR_FLAGS_H__ /* Copied from the Linux kernel header arch/arm/include/uapi/asm/ptrace.h */ /* * PSR bits */ #define USR26_MODE 0x00000000 #define FIQ26_MODE 0x00000001 #define IRQ26_MODE 0x00000002 #define SVC26_MODE 0x00000003 #define USR_MODE 0x00000010 #define FIQ_MODE 0x00000011 #define IRQ_MODE 0x00000012 #define SVC_MODE 0x00000013 #define ABT_MODE 0x00000017 #define UND_MODE 0x0000001b #define SYSTEM_MODE 0x0000001f #define MODE32_BIT 0x00000010 #define MODE_MASK 0x0000001f #define PSR_T_BIT 0x00000020 #define PSR_F_BIT 0x00000040 #define PSR_I_BIT 0x00000080 #define PSR_A_BIT 0x00000100 #define PSR_E_BIT 0x00000200 #define PSR_J_BIT 0x01000000 #define PSR_Q_BIT 0x08000000 #define PSR_V_BIT 0x10000000 #define PSR_C_BIT 0x20000000 #define PSR_Z_BIT 0x40000000 #define PSR_N_BIT 0x80000000 /* * Groups of PSR bits */ #define PSR_f 0xff000000 /* Flags */ #define PSR_s 0x00ff0000 /* Status */ #define PSR_x 0x0000ff00 /* Extension */ #define PSR_c 0x000000ff /* Control */ #endif
1,101
24.627907
76
h
criu
criu-master/compel/arch/arm/src/lib/include/uapi/asm/sigframe.h
#ifndef UAPI_COMPEL_ASM_SIGFRAME_H__ #define UAPI_COMPEL_ASM_SIGFRAME_H__ #include <compel/asm/infect-types.h> /* Copied from the Linux kernel header arch/arm/include/asm/sigcontext.h */ struct rt_sigcontext { unsigned long trap_no; unsigned long error_code; unsigned long oldmask; unsigned long arm_r0; unsigned long arm_r1; unsigned long arm_r2; unsigned long arm_r3; unsigned long arm_r4; unsigned long arm_r5; unsigned long arm_r6; unsigned long arm_r7; unsigned long arm_r8; unsigned long arm_r9; unsigned long arm_r10; unsigned long arm_fp; unsigned long arm_ip; unsigned long arm_sp; unsigned long arm_lr; unsigned long arm_pc; unsigned long arm_cpsr; unsigned long fault_address; }; /* Copied from the Linux kernel header arch/arm/include/asm/ucontext.h */ #define VFP_MAGIC 0x56465001 #define VFP_STORAGE_SIZE sizeof(struct vfp_sigframe) struct vfp_sigframe { unsigned long magic; unsigned long size; struct user_vfp ufp; struct user_vfp_exc ufp_exc; }; typedef struct vfp_sigframe fpu_state_t; struct aux_sigframe { /* struct crunch_sigframe crunch; struct iwmmxt_sigframe iwmmxt; */ struct vfp_sigframe vfp; unsigned long end_magic; } __attribute__((aligned(8))); #include <compel/sigframe-common.h> struct sigframe { struct rt_ucontext uc; unsigned long retcode[2]; }; struct rt_sigframe { struct rt_siginfo info; struct sigframe sig; }; /* clang-format off */ #define ARCH_RT_SIGRETURN(new_sp, rt_sigframe) \ asm volatile( \ "mov sp, %0 \n" \ "mov r7, #"__stringify(__NR_rt_sigreturn)" \n" \ "svc #0 \n" \ : \ : "r"(new_sp) \ : "memory") /* clang-format on */ #define RT_SIGFRAME_UC(rt_sigframe) (&rt_sigframe->sig.uc) #define RT_SIGFRAME_REGIP(rt_sigframe) (rt_sigframe)->sig.uc.uc_mcontext.arm_ip #define RT_SIGFRAME_HAS_FPU(rt_sigframe) 1 #define RT_SIGFRAME_AUX_SIGFRAME(rt_sigframe) ((struct aux_sigframe *)&(rt_sigframe)->sig.uc.uc_regspace) #define RT_SIGFRAME_FPU(rt_sigframe) (&RT_SIGFRAME_AUX_SIGFRAME(rt_sigframe)->vfp) #define RT_SIGFRAME_OFFSET(rt_sigframe) 0 #define rt_sigframe_erase_sigset(sigframe) memset(&sigframe->sig.uc.uc_sigmask, 0, sizeof(k_rtsigset_t)) #define rt_sigframe_copy_sigset(sigframe, from) memcpy(&sigframe->sig.uc.uc_sigmask, from, sizeof(k_rtsigset_t)) #endif /* UAPI_COMPEL_ASM_SIGFRAME_H__ */
2,408
25.766667
112
h
criu
criu-master/compel/arch/mips/plugins/include/asm/syscall-types.h
#ifndef COMPEL_ARCH_SYSCALL_TYPES_H__ #define COMPEL_ARCH_SYSCALL_TYPES_H__ /* Types for sigaction, sigprocmask syscalls */ typedef void rt_signalfn_t(int, siginfo_t *, void *); typedef rt_signalfn_t *rt_sighandler_t; typedef void rt_restorefn_t(void); typedef rt_restorefn_t *rt_sigrestore_t; #define SA_RESTORER 0x04000000 /** refer to linux-3.10/arch/mips/include/uapi/asm/signal.h*/ #define _KNSIG 128 #define _NSIG_BPW 64 #define _KNSIG_WORDS (_KNSIG / _NSIG_BPW) /* * Note: as k_rtsigset_t is the same size for 32-bit and 64-bit, * sig defined as uint64_t rather than (unsigned long) - for the * purpose if we ever going to support native 32-bit compilation. */ typedef struct { uint64_t sig[_KNSIG_WORDS]; } k_rtsigset_t; typedef struct { rt_sighandler_t rt_sa_handler; unsigned long rt_sa_flags; rt_sigrestore_t rt_sa_restorer; k_rtsigset_t rt_sa_mask; } rt_sigaction_t; #endif /* COMPEL_ARCH_SYSCALL_TYPES_H__ */
942
24.486486
65
h
criu
criu-master/compel/arch/mips/src/lib/handle-elf.c
#include <string.h> #include <errno.h> #include "handle-elf.h" #include "piegen.h" #include "log.h" static const unsigned char __maybe_unused elf_ident_64_le[EI_NIDENT] = { 0x7f, 0x45, 0x4c, 0x46, 0x02, 0x01, 0x01, 0x00, /* clang-format */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; extern int __handle_elf(void *mem, size_t size); int handle_binary(void *mem, size_t size) { if (memcmp(mem, elf_ident_64_le, sizeof(elf_ident_64_le)) == 0) return __handle_elf(mem, size); pr_err("Unsupported Elf format detected\n"); return -EINVAL; }
555
23.173913
72
c
criu
criu-master/compel/arch/mips/src/lib/infect.c
#include <sys/types.h> #include <sys/uio.h> #include <sys/auxv.h> #include <sys/mman.h> #include <errno.h> #include <compel/asm/fpu.h> #include <compel/cpu.h> #include "errno.h" #include <compel/plugins/std/syscall-codes.h> #include <compel/plugins/std/syscall.h> #include "common/err.h" #include "common/page.h" #include "asm/infect-types.h" #include "ptrace.h" #include "infect.h" #include "infect-priv.h" #include "log.h" #include "common/bug.h" /* * Injected syscall instruction * mips64el is Little Endian */ const char code_syscall[] = { 0x0c, 0x00, 0x00, 0x00, /* syscall */ 0x0d, 0x00, 0x00, 0x00 /* break */ }; /* 10-byte legacy floating point register */ struct fpreg { uint16_t significand[4]; uint16_t exponent; }; /* 16-byte floating point register */ struct fpxreg { uint16_t significand[4]; uint16_t exponent; uint16_t padding[3]; }; int sigreturn_prep_regs_plain(struct rt_sigframe *sigframe, user_regs_struct_t *regs, user_fpregs_struct_t *fpregs) { sigframe->rs_uc.uc_mcontext.sc_regs[0] = regs->regs[0]; sigframe->rs_uc.uc_mcontext.sc_regs[1] = regs->regs[1]; sigframe->rs_uc.uc_mcontext.sc_regs[2] = regs->regs[2]; sigframe->rs_uc.uc_mcontext.sc_regs[3] = regs->regs[3]; sigframe->rs_uc.uc_mcontext.sc_regs[4] = regs->regs[4]; sigframe->rs_uc.uc_mcontext.sc_regs[5] = regs->regs[5]; sigframe->rs_uc.uc_mcontext.sc_regs[6] = regs->regs[6]; sigframe->rs_uc.uc_mcontext.sc_regs[7] = regs->regs[7]; sigframe->rs_uc.uc_mcontext.sc_regs[8] = regs->regs[8]; sigframe->rs_uc.uc_mcontext.sc_regs[9] = regs->regs[9]; sigframe->rs_uc.uc_mcontext.sc_regs[10] = regs->regs[10]; sigframe->rs_uc.uc_mcontext.sc_regs[11] = regs->regs[11]; sigframe->rs_uc.uc_mcontext.sc_regs[12] = regs->regs[12]; sigframe->rs_uc.uc_mcontext.sc_regs[13] = regs->regs[13]; sigframe->rs_uc.uc_mcontext.sc_regs[14] = regs->regs[14]; sigframe->rs_uc.uc_mcontext.sc_regs[15] = regs->regs[15]; sigframe->rs_uc.uc_mcontext.sc_regs[16] = regs->regs[16]; sigframe->rs_uc.uc_mcontext.sc_regs[17] = regs->regs[17]; sigframe->rs_uc.uc_mcontext.sc_regs[18] = regs->regs[18]; sigframe->rs_uc.uc_mcontext.sc_regs[19] = regs->regs[19]; sigframe->rs_uc.uc_mcontext.sc_regs[20] = regs->regs[20]; sigframe->rs_uc.uc_mcontext.sc_regs[21] = regs->regs[21]; sigframe->rs_uc.uc_mcontext.sc_regs[22] = regs->regs[22]; sigframe->rs_uc.uc_mcontext.sc_regs[23] = regs->regs[23]; sigframe->rs_uc.uc_mcontext.sc_regs[24] = regs->regs[24]; sigframe->rs_uc.uc_mcontext.sc_regs[25] = regs->regs[25]; sigframe->rs_uc.uc_mcontext.sc_regs[26] = regs->regs[26]; sigframe->rs_uc.uc_mcontext.sc_regs[27] = regs->regs[27]; sigframe->rs_uc.uc_mcontext.sc_regs[28] = regs->regs[28]; sigframe->rs_uc.uc_mcontext.sc_regs[29] = regs->regs[29]; sigframe->rs_uc.uc_mcontext.sc_regs[30] = regs->regs[30]; sigframe->rs_uc.uc_mcontext.sc_regs[31] = regs->regs[31]; sigframe->rs_uc.uc_mcontext.sc_mdlo = regs->lo; sigframe->rs_uc.uc_mcontext.sc_mdhi = regs->hi; sigframe->rs_uc.uc_mcontext.sc_pc = regs->cp0_epc; sigframe->rs_uc.uc_mcontext.sc_fpregs[0] = fpregs->regs[0]; sigframe->rs_uc.uc_mcontext.sc_fpregs[1] = fpregs->regs[1]; sigframe->rs_uc.uc_mcontext.sc_fpregs[2] = fpregs->regs[2]; sigframe->rs_uc.uc_mcontext.sc_fpregs[3] = fpregs->regs[3]; sigframe->rs_uc.uc_mcontext.sc_fpregs[4] = fpregs->regs[4]; sigframe->rs_uc.uc_mcontext.sc_fpregs[5] = fpregs->regs[5]; sigframe->rs_uc.uc_mcontext.sc_fpregs[6] = fpregs->regs[6]; sigframe->rs_uc.uc_mcontext.sc_fpregs[7] = fpregs->regs[7]; sigframe->rs_uc.uc_mcontext.sc_fpregs[8] = fpregs->regs[8]; sigframe->rs_uc.uc_mcontext.sc_fpregs[9] = fpregs->regs[9]; sigframe->rs_uc.uc_mcontext.sc_fpregs[10] = fpregs->regs[10]; sigframe->rs_uc.uc_mcontext.sc_fpregs[11] = fpregs->regs[11]; sigframe->rs_uc.uc_mcontext.sc_fpregs[12] = fpregs->regs[12]; sigframe->rs_uc.uc_mcontext.sc_fpregs[13] = fpregs->regs[13]; sigframe->rs_uc.uc_mcontext.sc_fpregs[14] = fpregs->regs[14]; sigframe->rs_uc.uc_mcontext.sc_fpregs[15] = fpregs->regs[15]; sigframe->rs_uc.uc_mcontext.sc_fpregs[16] = fpregs->regs[16]; sigframe->rs_uc.uc_mcontext.sc_fpregs[17] = fpregs->regs[17]; sigframe->rs_uc.uc_mcontext.sc_fpregs[18] = fpregs->regs[18]; sigframe->rs_uc.uc_mcontext.sc_fpregs[19] = fpregs->regs[19]; sigframe->rs_uc.uc_mcontext.sc_fpregs[20] = fpregs->regs[20]; sigframe->rs_uc.uc_mcontext.sc_fpregs[21] = fpregs->regs[21]; sigframe->rs_uc.uc_mcontext.sc_fpregs[22] = fpregs->regs[22]; sigframe->rs_uc.uc_mcontext.sc_fpregs[23] = fpregs->regs[23]; sigframe->rs_uc.uc_mcontext.sc_fpregs[24] = fpregs->regs[24]; sigframe->rs_uc.uc_mcontext.sc_fpregs[25] = fpregs->regs[25]; sigframe->rs_uc.uc_mcontext.sc_fpregs[26] = fpregs->regs[26]; sigframe->rs_uc.uc_mcontext.sc_fpregs[27] = fpregs->regs[27]; sigframe->rs_uc.uc_mcontext.sc_fpregs[28] = fpregs->regs[28]; sigframe->rs_uc.uc_mcontext.sc_fpregs[29] = fpregs->regs[29]; sigframe->rs_uc.uc_mcontext.sc_fpregs[30] = fpregs->regs[30]; sigframe->rs_uc.uc_mcontext.sc_fpregs[31] = fpregs->regs[31]; return 0; } int sigreturn_prep_fpu_frame_plain(struct rt_sigframe *sigframe, struct rt_sigframe *rsigframe) { return 0; } int compel_get_task_regs(pid_t pid, user_regs_struct_t *regs, user_fpregs_struct_t *ext_regs, save_regs_t save, void *arg, __maybe_unused unsigned long flags) { user_fpregs_struct_t xsave = {}, *xs = ext_regs ? ext_regs : &xsave; int ret = -1; pr_info("Dumping GP/FPU registers for %d\n", pid); if (ptrace(PTRACE_GETFPREGS, pid, NULL, xs)) { pr_perror("Can't obtain FPU registers for %d", pid); return ret; } /*Restart the system call*/ if (regs->regs[0]) { switch ((long)(int)regs->regs[2]) { case ERESTARTNOHAND: case ERESTARTSYS: case ERESTARTNOINTR: regs->regs[2] = regs->regs[0]; regs->regs[7] = regs->regs[26]; regs->cp0_epc -= 4; break; case ERESTART_RESTARTBLOCK: pr_warn("Will restore %d with interrupted system call\n", pid); regs->regs[2] = -EINTR; break; } regs->regs[0] = 0; } ret = save(arg, regs, xs); return ret; } int compel_set_task_ext_regs(pid_t pid, user_fpregs_struct_t *ext_regs) { pr_info("Restoring GP/FPU registers for %d\n", pid); if (ptrace(PTRACE_SETFPREGS, pid, NULL, ext_regs)) { pr_perror("Can't set FPU registers for %d", pid); return -1; } return 0; } int compel_syscall(struct parasite_ctl *ctl, int nr, long *ret, unsigned long arg1, unsigned long arg2, unsigned long arg3, unsigned long arg4, unsigned long arg5, unsigned long arg6) { /*refer to glibc-2.20/sysdeps/unix/sysv/linux/mips/mips64/syscall.S*/ user_regs_struct_t regs = ctl->orig.regs; int err; regs.regs[2] = (unsigned long)nr; //syscall_number will be in v0 regs.regs[4] = arg1; regs.regs[5] = arg2; regs.regs[6] = arg3; regs.regs[7] = arg4; regs.regs[8] = arg5; regs.regs[9] = arg6; err = compel_execute_syscall(ctl, &regs, code_syscall); *ret = regs.regs[2]; return err; } void *remote_mmap(struct parasite_ctl *ctl, void *addr, size_t length, int prot, int flags, int fd, off_t offset) { long map; int err; err = compel_syscall(ctl, __NR_mmap, &map, (unsigned long)addr, length, prot, flags, fd, offset >> PAGE_SHIFT); if (err < 0 || IS_ERR_VALUE(map)) { pr_err("remote mmap() failed: %s\n", strerror(-map)); return NULL; } return (void *)map; } /* * regs must be inited when calling this function from original context */ void parasite_setup_regs(unsigned long new_ip, void *stack, user_regs_struct_t *regs) { regs->cp0_epc = new_ip; if (stack) { /* regs[29] is sp */ regs->regs[29] = (unsigned long)stack; } } bool arch_can_dump_task(struct parasite_ctl *ctl) { return true; } int arch_fetch_sas(struct parasite_ctl *ctl, struct rt_sigframe *s) { long ret; int err; err = compel_syscall(ctl, __NR_sigaltstack, &ret, 0, (unsigned long)&s->rs_uc.uc_stack, 0, 0, 0, 0); return err ? err : ret; } int ptrace_set_breakpoint(pid_t pid, void *addr) { return 0; } int ptrace_flush_breakpoints(pid_t pid) { return 0; } /*refer to kernel linux-3.10/arch/mips/include/asm/processor.h*/ #define TASK_SIZE32 0x7fff8000UL #define TASK_SIZE64 0x10000000000UL #define TASK_SIZE TASK_SIZE64 unsigned long compel_task_size(void) { return TASK_SIZE; } /* * Get task registers (overwrites weak function) * */ int ptrace_get_regs(int pid, user_regs_struct_t *regs) { return ptrace(PTRACE_GETREGS, pid, NULL, regs); } /* * Set task registers (overwrites weak function) */ int ptrace_set_regs(int pid, user_regs_struct_t *regs) { return ptrace(PTRACE_SETREGS, pid, NULL, regs); } void compel_relocs_apply_mips(void *mem, void *vbase, struct parasite_blob_desc *pbd) { compel_reloc_t *elf_relocs = pbd->hdr.relocs; size_t nr_relocs = pbd->hdr.nr_relocs; size_t i, j; /* * mips rebasing :load time relocation * parasite.built-in.o and restorer.built-in.o is ELF 64-bit LSB relocatable for mips. * so we have to relocate some type for R_MIPS_26 R_MIPS_HIGHEST R_MIPS_HIGHER R_MIPS_HI16 and R_MIPS_LO16 in there. * for mips64el .if toload/store data or jump instruct ,need to relocation R_TYPE */ for (i = 0, j = 0; i < nr_relocs; i++) { if (elf_relocs[i].type & COMPEL_TYPE_MIPS_26) { int *where = (mem + elf_relocs[i].offset); *where = *where | ((elf_relocs[i].addend + ((unsigned long)vbase & 0x00fffffff) /*low 28 bit*/) >> 2); } else if (elf_relocs[i].type & COMPEL_TYPE_MIPS_64) { unsigned long *where = (mem + elf_relocs[i].offset); *where = elf_relocs[i].addend + (unsigned long)vbase; } else if (elf_relocs[i].type & COMPEL_TYPE_MIPS_HI16) { /* refer to binutils mips.cc */ int *where = (mem + elf_relocs[i].offset); int v_lo16 = (unsigned long)vbase & 0x00ffff; if ((v_lo16 + elf_relocs[i].value + elf_relocs[i].addend) >= 0x8000) { *where = *where | ((((unsigned long)vbase >> 16) & 0xffff) + 0x1); } else { *where = *where | ((((unsigned long)vbase >> 16) & 0xffff)); } } else if (elf_relocs[i].type & COMPEL_TYPE_MIPS_LO16) { int *where = (mem + elf_relocs[i].offset); int v_lo16 = (unsigned long)vbase & 0x00ffff; *where = *where | ((v_lo16 + elf_relocs[i].addend) & 0xffff); } else if (elf_relocs[i].type & COMPEL_TYPE_MIPS_HIGHER) { int *where = (mem + elf_relocs[i].offset); *where = *where | ((((unsigned long)vbase + (uint64_t)0x80008000) >> 32) & 0xffff); } else if (elf_relocs[i].type & COMPEL_TYPE_MIPS_HIGHEST) { int *where = (mem + elf_relocs[i].offset); *where = *where | ((((unsigned long)vbase + (uint64_t)0x800080008000llu) >> 48) & 0xffff); } else { BUG(); } } }
10,544
32.798077
117
c
criu
criu-master/compel/arch/mips/src/lib/include/ldsodefs.h
/* * Run-time dynamic linker data structures for loaded ELF shared objects. * Copyright (C) 2000-2014 Free Software Foundation, Inc. * This file is part of the GNU C Library. * * The GNU C Library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * The GNU C Library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with the GNU C Library. If not, see * <http://www.gnu.org/licenses/>. */ #ifndef _MIPS_LDSODEFS_H #define _MIPS_LDSODEFS_H 1 #include <elf.h> struct La_mips_32_regs; struct La_mips_32_retval; struct La_mips_64_regs; struct La_mips_64_retval; #define ARCH_PLTENTER_MEMBERS \ Elf32_Addr (*mips_o32_gnu_pltenter)(Elf32_Sym *, unsigned int, uintptr_t *, uintptr_t *, \ struct La_mips_32_regs *, unsigned int *, const char *name, \ long int *framesizep); \ Elf32_Addr (*mips_n32_gnu_pltenter)(Elf32_Sym *, unsigned int, uintptr_t *, uintptr_t *, \ struct La_mips_64_regs *, unsigned int *, const char *name, \ long int *framesizep); \ Elf64_Addr (*mips_n64_gnu_pltenter)(Elf64_Sym *, unsigned int, uintptr_t *, uintptr_t *, \ struct La_mips_64_regs *, unsigned int *, const char *name, \ long int *framesizep); #define ARCH_PLTEXIT_MEMBERS \ unsigned int (*mips_o32_gnu_pltexit)(Elf32_Sym *, unsigned int, uintptr_t *, uintptr_t *, \ const struct La_mips_32_regs *, struct La_mips_32_retval *, \ const char *); \ unsigned int (*mips_n32_gnu_pltexit)(Elf32_Sym *, unsigned int, uintptr_t *, uintptr_t *, \ const struct La_mips_64_regs *, struct La_mips_64_retval *, \ const char *); \ unsigned int (*mips_n64_gnu_pltexit)(Elf64_Sym *, unsigned int, uintptr_t *, uintptr_t *, \ const struct La_mips_64_regs *, struct La_mips_64_retval *, \ const char *); /* The MIPS ABI specifies that the dynamic section has to be read-only. */ /* * The 64-bit MIPS ELF ABI uses an unusual reloc format. Each * relocation entry specifies up to three actual relocations, all at * the same address. The first relocation which required a symbol * uses the symbol in the r_sym field. The second relocation which * requires a symbol uses the symbol in the r_ssym field. If all * three relocations require a symbol, the third one uses a zero * value. * * We define these structures in internal headers because we're not * sure we want to make them part of the ABI yet. Eventually, some of * this may move into elf/elf.h. */ /* An entry in a 64 bit SHT_REL section. */ typedef struct { Elf32_Word r_sym; /* Symbol index */ unsigned char r_ssym; /* Special symbol for 2nd relocation */ unsigned char r_type3; /* 3rd relocation type */ unsigned char r_type2; /* 2nd relocation type */ unsigned char r_type1; /* 1st relocation type */ } _Elf64_Mips_R_Info; typedef union { Elf64_Xword r_info_number; _Elf64_Mips_R_Info r_info_fields; } _Elf64_Mips_R_Info_union; typedef struct { Elf64_Addr r_offset; /* Address */ _Elf64_Mips_R_Info_union r_info; /* Relocation type and symbol index */ } Elf64_Mips_Rel; typedef struct { Elf64_Addr r_offset; /* Address */ _Elf64_Mips_R_Info_union r_info; /* Relocation type and symbol index */ Elf64_Sxword r_addend; /* Addend */ } Elf64_Mips_Rela; #define ELF64_MIPS_R_SYM(i) ((__extension__(_Elf64_Mips_R_Info_union)(i)).r_info_fields.r_sym) #define ELF64_MIPS_R_TYPE(i) \ (((_Elf64_Mips_R_Info_union)(i)).r_info_fields.r_type1 | \ ((Elf32_Word)(__extension__(_Elf64_Mips_R_Info_union)(i)).r_info_fields.r_type2 << 8) | \ ((Elf32_Word)(__extension__(_Elf64_Mips_R_Info_union)(i)).r_info_fields.r_type3 << 16) | \ ((Elf32_Word)(__extension__(_Elf64_Mips_R_Info_union)(i)).r_info_fields.r_ssym << 24)) #define ELF64_MIPS_R_INFO(sym, type) \ (__extension__(_Elf64_Mips_R_Info_union)( \ __extension__(_Elf64_Mips_R_Info){ (sym), ELF64_MIPS_R_SSYM(type), ELF64_MIPS_R_TYPE3(type), \ ELF64_MIPS_R_TYPE2(type), ELF64_MIPS_R_TYPE1(type) }) \ .r_info_number) /* * These macros decompose the value returned by ELF64_MIPS_R_TYPE, and * compose it back into a value that it can be used as an argument to * ELF64_MIPS_R_INFO. */ #define ELF64_MIPS_R_SSYM(i) (((i) >> 24) & 0xff) #define ELF64_MIPS_R_TYPE3(i) (((i) >> 16) & 0xff) #define ELF64_MIPS_R_TYPE2(i) (((i) >> 8) & 0xff) #define ELF64_MIPS_R_TYPE1(i) ((i)&0xff) #define ELF64_MIPS_R_TYPEENC(type1, type2, type3, ssym) \ ((type1) | ((Elf32_Word)(type2) << 8) | ((Elf32_Word)(type3) << 16) | ((Elf32_Word)(ssym) << 24)) #undef ELF64_R_SYM #define ELF64_R_SYM(i) ELF64_MIPS_R_SYM(i) #undef ELF64_R_TYPE /*fixme*/ #define ELF64_R_TYPE(i) (ELF64_MIPS_R_TYPE(i) & 0x00ff) #undef ELF64_R_INFO #define ELF64_R_INFO(sym, type) ELF64_MIPS_R_INFO((sym), (type)) #endif
5,815
43.396947
111
h
criu
criu-master/compel/arch/mips/src/lib/include/uapi/asm/infect-types.h
#ifndef UAPI_COMPEL_ASM_TYPES_H__ #define UAPI_COMPEL_ASM_TYPES_H__ #include <stdint.h> #include <stdbool.h> #include <signal.h> #include <compel/plugins/std/asm/syscall-types.h> #include <linux/types.h> #define SIGMAX 64 #define SIGMAX_OLD 31 /* * Copied from the Linux kernel header arch/mips/include/asm/ptrace.h * * A thread MIPS CPU context */ typedef struct { /* Saved main processor registers. */ __u64 regs[32]; /* Saved special registers. */ __u64 lo; __u64 hi; __u64 cp0_epc; __u64 cp0_badvaddr; __u64 cp0_status; __u64 cp0_cause; } user_regs_struct_t; /* from linux-3.10/arch/mips/kernel/ptrace.c */ typedef struct { /* Saved fpu registers. */ __u64 regs[32]; __u32 fpu_fcr31; __u32 fpu_id; } user_fpregs_struct_t; #define MIPS_a0 regs[4] //arguments a0-a3 #define MIPS_t0 regs[8] //temporaries t0-t7 #define MIPS_v0 regs[2] #define MIPS_v1 regs[3] #define MIPS_sp regs[29] #define MIPS_ra regs[31] #define NATIVE_MAGIC 0x0A #define COMPAT_MAGIC 0x0C static inline bool user_regs_native(user_regs_struct_t *pregs) { return true; } #define __compel_arch_fetch_thread_area(tid, th) 0 #define compel_arch_fetch_thread_area(tctl) 0 #define compel_arch_get_tls_task(ctl, tls) #define compel_arch_get_tls_thread(tctl, tls) #define REG_RES(regs) ((regs).MIPS_v0) #define REG_IP(regs) ((regs).cp0_epc) #define SET_REG_IP(regs, val) ((regs).cp0_epc = (val)) #define REG_SP(regs) ((regs).MIPS_sp) #define REG_SYSCALL_NR(regs) ((regs).MIPS_v0) //#define __NR(syscall, compat) ((compat) ? __NR32_##syscall : __NR_##syscall) #define __NR(syscall, compat) __NR_##syscall #endif /* UAPI_COMPEL_ASM_TYPES_H__ */
1,660
23.072464
78
h
criu
criu-master/compel/arch/mips/src/lib/include/uapi/asm/sigframe.h
#ifndef UAPI_COMPEL_ASM_SIGFRAME_H__ #define UAPI_COMPEL_ASM_SIGFRAME_H__ #include <stdint.h> #include <stdbool.h> #include <compel/asm/fpu.h> #include <compel/plugins/std/syscall-codes.h> #include <asm/types.h> #define u32 __u32 /* sigcontext defined in /usr/include/asm/sigcontext.h*/ #define rt_sigcontext sigcontext #include <compel/sigframe-common.h> /* refer to linux-3.10/include/uapi/asm-generic/ucontext.h */ struct k_ucontext { unsigned long uc_flags; struct k_ucontext *uc_link; stack_t uc_stack; struct sigcontext uc_mcontext; k_rtsigset_t uc_sigmask; }; /* Copy from the kernel source arch/mips/kernel/signal.c */ struct rt_sigframe { u32 rs_ass[4]; /* argument save space for o32 */ u32 rs_pad[2]; /* Was: signal trampoline */ siginfo_t rs_info; struct k_ucontext rs_uc; }; #define RT_SIGFRAME_UC(rt_sigframe) (&rt_sigframe->rs_uc) #define RT_SIGFRAME_UC_SIGMASK(rt_sigframe) ((k_rtsigset_t *)(void *)&rt_sigframe->rs_uc.uc_sigmask) #define RT_SIGFRAME_REGIP(rt_sigframe) ((long unsigned int)0x00) #define RT_SIGFRAME_FPU(rt_sigframe) #define RT_SIGFRAME_HAS_FPU(rt_sigframe) 1 #define RT_SIGFRAME_OFFSET(rt_sigframe) 0 /* clang-format off */ #define ARCH_RT_SIGRETURN(new_sp, rt_sigframe) \ asm volatile( \ "move $29, %0 \n" \ "li $2, "__stringify(__NR_rt_sigreturn)" \n" \ "syscall \n" \ : \ : "r"(new_sp) \ : "$2","memory") /* clang-format on */ int sigreturn_prep_fpu_frame(struct rt_sigframe *sigframe, struct rt_sigframe *rsigframe); #define rt_sigframe_erase_sigset(sigframe) memset(&sigframe->rs_uc.uc_sigmask, 0, sizeof(k_rtsigset_t)) #define rt_sigframe_copy_sigset(sigframe, from) memcpy(&sigframe->rs_uc.uc_sigmask, from, sizeof(k_rtsigset_t)) #endif /* UAPI_COMPEL_ASM_SIGFRAME_H__ */
1,775
29.101695
111
h
criu
criu-master/compel/arch/mips/src/lib/include/uapi/asm/siginfo.h
/* * This file is subject to the terms and conditions of the GNU General Public * License. See the file "COPYING" in the main directory of this archive * for more details. * * Copyright (C) 1998, 1999, 2001, 2003 Ralf Baechle * Copyright (C) 2000, 2001 Silicon Graphics, Inc. */ #ifndef _UAPI_ASM_SIGINFO_H #define _UAPI_ASM_SIGINFO_H #define __ARCH_SIGEV_PREAMBLE_SIZE (sizeof(long) + 2 * sizeof(int)) #undef __ARCH_SI_TRAPNO /* exception code needs to fill this ... */ #define HAVE_ARCH_SIGINFO_T /* * Careful to keep union _sifields from shifting ... */ #define __ARCH_SI_PREAMBLE_SIZE (4 * sizeof(int)) #define __ARCH_SIGSYS #define SI_MAX_SIZE 128 #define SI_PAD_SIZE ((SI_MAX_SIZE - __ARCH_SI_PREAMBLE_SIZE) / sizeof(int)) #define __ARCH_SI_UID_T __kernel_uid32_t #ifndef __ARCH_SI_UID_T #define __ARCH_SI_UID_T __kernel_uid32_t #endif #ifndef __ARCH_SI_BAND_T #define __ARCH_SI_BAND_T long #endif #ifndef __ARCH_SI_CLOCK_T #define __ARCH_SI_CLOCK_T __kernel_clock_t #endif #ifndef __ARCH_SI_ATTRIBUTES #define __ARCH_SI_ATTRIBUTES #endif typedef struct siginfo { int si_signo; int si_errno; int si_code; union { int _pad[SI_PAD_SIZE]; /* kill() */ struct { __kernel_pid_t _pid; /* sender's pid */ __ARCH_SI_UID_T _uid; /* sender's uid */ } _kill; /* POSIX.1b timers */ struct { __kernel_timer_t _tid; /* timer id */ int _overrun; /* overrun count */ char _pad[sizeof(__ARCH_SI_UID_T) - sizeof(int)]; sigval_t _sigval; /* same as below */ int _sys_private; /* not to be passed to user */ } _timer; /* POSIX.1b signals */ struct { __kernel_pid_t _pid; /* sender's pid */ __ARCH_SI_UID_T _uid; /* sender's uid */ sigval_t _sigval; } _rt; /* SIGCHLD */ struct { __kernel_pid_t _pid; /* which child */ __ARCH_SI_UID_T _uid; /* sender's uid */ int _status; /* exit code */ __ARCH_SI_CLOCK_T _utime; __ARCH_SI_CLOCK_T _stime; } _sigchld; /* SIGILL, SIGFPE, SIGSEGV, SIGBUS */ struct { void *_addr; /* faulting insn/memory ref. */ #ifdef __ARCH_SI_TRAPNO int _trapno; /* TRAP # which caused the signal */ #endif short _addr_lsb; /* LSB of the reported address */ #ifndef __GENKSYMS__ struct { void *_lower; void *_upper; } _addr_bnd; #endif } _sigfault; /* SIGPOLL */ struct { __ARCH_SI_BAND_T _band; /* POLL_IN, POLL_OUT, POLL_MSG */ int _fd; } _sigpoll; /* SIGSYS */ struct { void *_call_addr; /* calling user insn */ int _syscall; /* triggering system call number */ unsigned int _arch; /* AUDIT_ARCH_* of syscall */ } _sigsys; } _sifields; } __ARCH_SI_ATTRIBUTES siginfo_t; /* * si_code values * Again these have been chosen to be IRIX compatible. */ #undef SI_ASYNCIO #undef SI_TIMER #undef SI_MESGQ #define SI_ASYNCIO -2 /* sent by AIO completion */ #endif /* _UAPI_ASM_SIGINFO_H */
2,877
22.209677
77
h
criu
criu-master/compel/arch/ppc64/plugins/include/asm/syscall-types.h
#ifndef COMPEL_ARCH_SYSCALL_TYPES_H__ #define COMPEL_ARCH_SYSCALL_TYPES_H__ #define SA_RESTORER 0x04000000U typedef void rt_signalfn_t(int, siginfo_t *, void *); typedef rt_signalfn_t *rt_sighandler_t; typedef void rt_restorefn_t(void); typedef rt_restorefn_t *rt_sigrestore_t; #define _KNSIG 64 #define _NSIG_BPW 64 #define _KNSIG_WORDS (_KNSIG / _NSIG_BPW) typedef struct { unsigned long sig[_KNSIG_WORDS]; } k_rtsigset_t; typedef struct { rt_sighandler_t rt_sa_handler; unsigned long rt_sa_flags; rt_sigrestore_t rt_sa_restorer; k_rtsigset_t rt_sa_mask; } rt_sigaction_t; #endif /* COMPEL_ARCH_SYSCALL_TYPES_H__ */
633
20.862069
53
h
criu
criu-master/compel/arch/ppc64/src/lib/handle-elf.c
#include <string.h> #include <errno.h> #include "handle-elf.h" #include "piegen.h" #include "log.h" static const unsigned char __maybe_unused elf_ident_64_le[EI_NIDENT] = { 0x7f, 0x45, 0x4c, 0x46, 0x02, 0x01, 0x01, 0x00, /* clang-format */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; static const unsigned char __maybe_unused elf_ident_64_be[EI_NIDENT] = { 0x7f, 0x45, 0x4c, 0x46, 0x02, 0x02, 0x01, 0x00, /* clang-format */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; int handle_binary(void *mem, size_t size) { const unsigned char *elf_ident = #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ elf_ident_64_le; #else elf_ident_64_be; #endif if (memcmp(mem, elf_ident, sizeof(elf_ident_64_le)) == 0) return handle_elf_ppc64(mem, size); pr_err("Unsupported Elf format detected\n"); return -EINVAL; }
829
24.151515
72
c
criu
criu-master/compel/arch/ppc64/src/lib/infect.c
#include <sys/ptrace.h> #include <sys/types.h> #include <sys/uio.h> #include <sys/user.h> #include <sys/mman.h> #include <stdint.h> #include <errno.h> #include <compel/plugins/std/syscall-codes.h> #include "uapi/compel/asm/infect-types.h" #include "errno.h" #include "log.h" #include "common/bug.h" #include "common/page.h" #include "infect.h" #include "infect-priv.h" #ifndef NT_PPC_TM_SPR #define NT_PPC_TM_CGPR 0x108 /* TM checkpointed GPR Registers */ #define NT_PPC_TM_CFPR 0x109 /* TM checkpointed FPR Registers */ #define NT_PPC_TM_CVMX 0x10a /* TM checkpointed VMX Registers */ #define NT_PPC_TM_CVSX 0x10b /* TM checkpointed VSX Registers */ #define NT_PPC_TM_SPR 0x10c /* TM Special Purpose Registers */ #endif unsigned __page_size = 0; unsigned __page_shift = 0; /* * Injected syscall instruction */ const uint32_t code_syscall[] = { 0x44000002, /* sc */ 0x0fe00000 /* twi 31,0,0 */ }; static inline __always_unused void __check_code_syscall(void) { BUILD_BUG_ON(sizeof(code_syscall) != BUILTIN_SYSCALL_SIZE); BUILD_BUG_ON(!is_log2(sizeof(code_syscall))); } static void prep_gp_regs(mcontext_t *dst, user_regs_struct_t *regs) { memcpy(dst->gp_regs, regs->gpr, sizeof(regs->gpr)); dst->gp_regs[PT_NIP] = regs->nip; dst->gp_regs[PT_MSR] = regs->msr; dst->gp_regs[PT_ORIG_R3] = regs->orig_gpr3; dst->gp_regs[PT_CTR] = regs->ctr; dst->gp_regs[PT_LNK] = regs->link; dst->gp_regs[PT_XER] = regs->xer; dst->gp_regs[PT_CCR] = regs->ccr; dst->gp_regs[PT_TRAP] = regs->trap; } static void put_fpu_regs(mcontext_t *mc, uint64_t *fpregs) { uint64_t *mcfp = (uint64_t *)mc->fp_regs; memcpy(mcfp, fpregs, sizeof(*fpregs) * NFPREG); } static void put_altivec_regs(mcontext_t *mc, __vector128 *vrregs) { vrregset_t *v_regs = (vrregset_t *)(((unsigned long)mc->vmx_reserve + 15) & ~0xful); memcpy(&v_regs->vrregs[0][0], vrregs, sizeof(uint64_t) * 2 * (NVRREG - 1)); v_regs->vrsave = *((uint32_t *)&vrregs[NVRREG - 1]); mc->v_regs = v_regs; } static void put_vsx_regs(mcontext_t *mc, uint64_t *vsxregs) { memcpy((uint64_t *)(mc->v_regs + 1), vsxregs, sizeof(*vsxregs) * NVSXREG); } int sigreturn_prep_regs_plain(struct rt_sigframe *sigframe, user_regs_struct_t *regs, user_fpregs_struct_t *fpregs) { mcontext_t *dst_tc = &sigframe->uc_transact.uc_mcontext; mcontext_t *dst = &sigframe->uc.uc_mcontext; if (fpregs->flags & USER_FPREGS_FL_TM) { prep_gp_regs(&sigframe->uc_transact.uc_mcontext, &fpregs->tm.regs); prep_gp_regs(&sigframe->uc.uc_mcontext, &fpregs->tm.regs); } else { prep_gp_regs(&sigframe->uc.uc_mcontext, regs); } if (fpregs->flags & USER_FPREGS_FL_TM) sigframe->uc.uc_link = &sigframe->uc_transact; if (fpregs->flags & USER_FPREGS_FL_FP) { if (fpregs->flags & USER_FPREGS_FL_TM) { put_fpu_regs(&sigframe->uc_transact.uc_mcontext, fpregs->tm.fpregs); put_fpu_regs(&sigframe->uc.uc_mcontext, fpregs->tm.fpregs); } else { put_fpu_regs(&sigframe->uc.uc_mcontext, fpregs->fpregs); } } if (fpregs->flags & USER_FPREGS_FL_ALTIVEC) { if (fpregs->flags & USER_FPREGS_FL_TM) { put_altivec_regs(&sigframe->uc_transact.uc_mcontext, fpregs->tm.vrregs); put_altivec_regs(&sigframe->uc.uc_mcontext, fpregs->tm.vrregs); dst_tc->gp_regs[PT_MSR] |= MSR_VEC; } else { put_altivec_regs(&sigframe->uc.uc_mcontext, fpregs->vrregs); } dst->gp_regs[PT_MSR] |= MSR_VEC; if (fpregs->flags & USER_FPREGS_FL_VSX) { if (fpregs->flags & USER_FPREGS_FL_TM) { put_vsx_regs(&sigframe->uc_transact.uc_mcontext, fpregs->tm.vsxregs); put_vsx_regs(&sigframe->uc.uc_mcontext, fpregs->tm.vsxregs); dst_tc->gp_regs[PT_MSR] |= MSR_VSX; } else { put_vsx_regs(&sigframe->uc.uc_mcontext, fpregs->vsxregs); } dst->gp_regs[PT_MSR] |= MSR_VSX; } } return 0; } static void update_vregs(mcontext_t *lcontext, mcontext_t *rcontext) { if (lcontext->v_regs) { uint64_t offset = (uint64_t)(lcontext->v_regs) - (uint64_t)lcontext; lcontext->v_regs = (vrregset_t *)((uint64_t)rcontext + offset); pr_debug("Updated v_regs:%llx (rcontext:%llx)\n", (unsigned long long)lcontext->v_regs, (unsigned long long)rcontext); } } int sigreturn_prep_fpu_frame_plain(struct rt_sigframe *frame, struct rt_sigframe *rframe) { uint64_t msr = frame->uc.uc_mcontext.gp_regs[PT_MSR]; update_vregs(&frame->uc.uc_mcontext, &rframe->uc.uc_mcontext); /* Sanity check: If TM so uc_link should be set, otherwise not */ if (MSR_TM_ACTIVE(msr) ^ (!!(frame->uc.uc_link))) { BUG(); return -1; } /* Updating the transactional state address if any */ if (frame->uc.uc_link) { update_vregs(&frame->uc_transact.uc_mcontext, &rframe->uc_transact.uc_mcontext); frame->uc.uc_link = &rframe->uc_transact; } return 0; } /* This is the layout of the POWER7 VSX registers and the way they * overlap with the existing FPR and VMX registers. * * VSR doubleword 0 VSR doubleword 1 * ---------------------------------------------------------------- * VSR[0] | FPR[0] | | * ---------------------------------------------------------------- * VSR[1] | FPR[1] | | * ---------------------------------------------------------------- * | ... | | * ---------------------------------------------------------------- * VSR[30] | FPR[30] | | * ---------------------------------------------------------------- * VSR[31] | FPR[31] | | * ---------------------------------------------------------------- * VSR[32] | VR[0] | * ---------------------------------------------------------------- * VSR[33] | VR[1] | * ---------------------------------------------------------------- * | ... | * ---------------------------------------------------------------- * VSR[62] | VR[30] | * ---------------------------------------------------------------- * VSR[63] | VR[31] | * ---------------------------------------------------------------- * * PTRACE_GETFPREGS returns FPR[0..31] + FPSCR * PTRACE_GETVRREGS returns VR[0..31] + VSCR + VRSAVE * PTRACE_GETVSRREGS returns VSR[0..31] * * PTRACE_GETVSRREGS and PTRACE_GETFPREGS are required since we need * to save FPSCR too. * * There 32 VSX double word registers to save since the 32 first VSX double * word registers are saved through FPR[0..32] and the remaining registers * are saved when saving the Altivec registers VR[0..32]. */ static int get_fpu_regs(pid_t pid, user_fpregs_struct_t *fp) { if (ptrace(PTRACE_GETFPREGS, pid, 0, (void *)&fp->fpregs) < 0) { pr_perror("Couldn't get floating-point registers"); return -1; } fp->flags |= USER_FPREGS_FL_FP; return 0; } static int get_altivec_regs(pid_t pid, user_fpregs_struct_t *fp) { if (ptrace(PTRACE_GETVRREGS, pid, 0, (void *)&fp->vrregs) < 0) { /* PTRACE_GETVRREGS returns EIO if Altivec is not supported. * This should not happen if msr_vec is set. */ if (errno != EIO) { pr_perror("Couldn't get Altivec registers"); return -1; } pr_debug("Altivec not supported\n"); } else { pr_debug("Dumping Altivec registers\n"); fp->flags |= USER_FPREGS_FL_ALTIVEC; } return 0; } /* * Since the FPR[0-31] is stored in the first double word of VSR[0-31] and * FPR are saved through the FP state, there is no need to save the upper part * of the first 32 VSX registers. * Furthermore, the 32 last VSX registers are also the 32 Altivec registers * already saved, so no need to save them. * As a consequence, only the doubleword 1 of the 32 first VSX registers have * to be saved (the ones are returned by PTRACE_GETVSRREGS). */ static int get_vsx_regs(pid_t pid, user_fpregs_struct_t *fp) { if (ptrace(PTRACE_GETVSRREGS, pid, 0, (void *)fp->vsxregs) < 0) { /* * EIO is returned in the case PTRACE_GETVRREGS is not * supported. */ if (errno != EIO) { pr_perror("Couldn't get VSX registers"); return -1; } pr_debug("VSX register's dump not supported.\n"); } else { pr_debug("Dumping VSX registers\n"); fp->flags |= USER_FPREGS_FL_VSX; } return 0; } static int get_tm_regs(pid_t pid, user_fpregs_struct_t *fpregs) { struct iovec iov; pr_debug("Dumping TM registers\n"); #define TM_REQUIRED 0 #define TM_OPTIONAL 1 #define PTRACE_GET_TM(s, n, c, u) \ do { \ iov.iov_base = &s; \ iov.iov_len = sizeof(s); \ if (ptrace(PTRACE_GETREGSET, pid, c, &iov)) { \ if (!u || errno != EIO) { \ pr_perror("Couldn't get TM " n); \ pr_err("Your kernel seems to not support the " \ "new TM ptrace API (>= 4.8)\n"); \ goto out_free; \ } \ pr_debug("TM " n " not supported.\n"); \ iov.iov_base = NULL; \ } \ } while (0) /* Get special registers */ PTRACE_GET_TM(fpregs->tm.tm_spr_regs, "SPR", NT_PPC_TM_SPR, TM_REQUIRED); /* Get checkpointed regular registers */ PTRACE_GET_TM(fpregs->tm.regs, "GPR", NT_PPC_TM_CGPR, TM_REQUIRED); /* Get checkpointed FP registers */ PTRACE_GET_TM(fpregs->tm.fpregs, "FPR", NT_PPC_TM_CFPR, TM_OPTIONAL); if (iov.iov_base) fpregs->tm.flags |= USER_FPREGS_FL_FP; /* Get checkpointed VMX (Altivec) registers */ PTRACE_GET_TM(fpregs->tm.vrregs, "VMX", NT_PPC_TM_CVMX, TM_OPTIONAL); if (iov.iov_base) fpregs->tm.flags |= USER_FPREGS_FL_ALTIVEC; /* Get checkpointed VSX registers */ PTRACE_GET_TM(fpregs->tm.vsxregs, "VSX", NT_PPC_TM_CVSX, TM_OPTIONAL); if (iov.iov_base) fpregs->tm.flags |= USER_FPREGS_FL_VSX; return 0; out_free: return -1; /* still failing the checkpoint */ } static int __get_task_regs(pid_t pid, user_regs_struct_t *regs, user_fpregs_struct_t *fpregs) { pr_info("Dumping GP/FPU registers for %d\n", pid); /* * This is inspired by kernel function check_syscall_restart in * arch/powerpc/kernel/signal.c */ #ifndef TRAP #define TRAP(r) ((r).trap & ~0xF) #endif if (TRAP(*regs) == 0x0C00 && regs->ccr & 0x10000000) { /* Restart the system call */ switch (regs->gpr[3]) { case ERESTARTNOHAND: case ERESTARTSYS: case ERESTARTNOINTR: regs->gpr[3] = regs->orig_gpr3; regs->nip -= 4; break; case ERESTART_RESTARTBLOCK: pr_warn("Will restore %d with interrupted system call\n", pid); regs->gpr[3] = EINTR; break; } } /* Resetting trap since we are now coming from user space. */ regs->trap = 0; fpregs->flags = 0; /* * Check for Transactional Memory operation in progress. * Until we have support of TM register's state through the ptrace API, * we can't checkpoint process with TM operation in progress (almost * impossible) or suspended (easy to get). */ if (MSR_TM_ACTIVE(regs->msr)) { pr_debug("Task %d has %s TM operation at 0x%lx\n", pid, (regs->msr & MSR_TMS) ? "a suspended" : "an active", regs->nip); if (get_tm_regs(pid, fpregs)) return -1; fpregs->flags = USER_FPREGS_FL_TM; } if (get_fpu_regs(pid, fpregs)) return -1; if (get_altivec_regs(pid, fpregs)) return -1; if (fpregs->flags & USER_FPREGS_FL_ALTIVEC) { /* * Save the VSX registers if Altivec registers are supported */ if (get_vsx_regs(pid, fpregs)) return -1; } return 0; } int compel_get_task_regs(pid_t pid, user_regs_struct_t *regs, user_fpregs_struct_t *ext_regs, save_regs_t save, void *arg, __maybe_unused unsigned long flags) { user_fpregs_struct_t tmp, *fpregs = ext_regs ? ext_regs : &tmp; int ret; ret = __get_task_regs(pid, regs, fpregs); if (ret) return ret; return save(arg, regs, fpregs); } int compel_set_task_ext_regs(pid_t pid, user_fpregs_struct_t *ext_regs) { int ret = 0; pr_info("Restoring GP/FPU registers for %d\n", pid); /* XXX: should restore TM registers somehow? */ if (ext_regs->flags & USER_FPREGS_FL_FP) { if (ptrace(PTRACE_SETFPREGS, pid, 0, (void *)&ext_regs->fpregs) < 0) { pr_perror("Couldn't set floating-point registers"); ret = -1; } } if (ext_regs->flags & USER_FPREGS_FL_ALTIVEC) { if (ptrace(PTRACE_SETVRREGS, pid, 0, (void *)&ext_regs->vrregs) < 0) { pr_perror("Couldn't set Altivec registers"); ret = -1; } if (ptrace(PTRACE_SETVSRREGS, pid, 0, (void *)ext_regs->vsxregs) < 0) { pr_perror("Couldn't set VSX registers"); ret = -1; } } return ret; } int compel_syscall(struct parasite_ctl *ctl, int nr, long *ret, unsigned long arg1, unsigned long arg2, unsigned long arg3, unsigned long arg4, unsigned long arg5, unsigned long arg6) { user_regs_struct_t regs = ctl->orig.regs; int err; regs.gpr[0] = (unsigned long)nr; regs.gpr[3] = arg1; regs.gpr[4] = arg2; regs.gpr[5] = arg3; regs.gpr[6] = arg4; regs.gpr[7] = arg5; regs.gpr[8] = arg6; err = compel_execute_syscall(ctl, &regs, (char *)code_syscall); *ret = regs.gpr[3]; return err; } void *remote_mmap(struct parasite_ctl *ctl, void *addr, size_t length, int prot, int flags, int fd, off_t offset) { long map = 0; int err; err = compel_syscall(ctl, __NR_mmap, &map, (unsigned long)addr, length, prot, flags, fd, offset); if (err < 0 || (long)map < 0) map = 0; return (void *)map; } void parasite_setup_regs(unsigned long new_ip, void *stack, user_regs_struct_t *regs) { /* * OpenPOWER ABI requires that r12 is set to the calling function address * to compute the TOC pointer. */ regs->gpr[12] = new_ip; regs->nip = new_ip; if (stack) regs->gpr[1] = (unsigned long)stack - STACK_FRAME_MIN_SIZE; regs->trap = 0; } bool arch_can_dump_task(struct parasite_ctl *ctl) { /* * TODO: We should detect 32bit task when BE support is done. */ return true; } int arch_fetch_sas(struct parasite_ctl *ctl, struct rt_sigframe *s) { long ret; int err; err = compel_syscall(ctl, __NR_sigaltstack, &ret, 0, (unsigned long)&s->uc.uc_stack, 0, 0, 0, 0); return err ? err : ret; } /* * Copied for the Linux kernel arch/powerpc/include/asm/processor.h * * NOTE: 32bit tasks are not supported. */ #define TASK_SIZE_64TB (0x0000400000000000UL) #define TASK_SIZE_512TB (0x0002000000000000UL) #define TASK_SIZE_MIN TASK_SIZE_64TB #define TASK_SIZE_MAX TASK_SIZE_512TB unsigned long compel_task_size(void) { unsigned long task_size; for (task_size = TASK_SIZE_MIN; task_size < TASK_SIZE_MAX; task_size <<= 1) if (munmap((void *)task_size, page_size())) break; return task_size; }
15,130
29.816701
115
c
criu
criu-master/compel/arch/ppc64/src/lib/include/uapi/asm/infect-types.h
#ifndef UAPI_COMPEL_ASM_TYPES_H__ #define UAPI_COMPEL_ASM_TYPES_H__ #include <stdbool.h> #include <signal.h> #include <stdint.h> #define SIGMAX_OLD 31 #define SIGMAX 64 /* * Copied from kernel header arch/powerpc/include/uapi/asm/ptrace.h */ typedef struct { unsigned long gpr[32]; unsigned long nip; unsigned long msr; unsigned long orig_gpr3; /* Used for restarting system calls */ unsigned long ctr; unsigned long link; unsigned long xer; unsigned long ccr; unsigned long softe; /* Soft enabled/disabled */ unsigned long trap; /* Reason for being here */ /* * N.B. for critical exceptions on 4xx, the dar and dsisr * fields are overloaded to hold srr0 and srr1. */ unsigned long dar; /* Fault registers */ unsigned long dsisr; /* on 4xx/Book-E used for ESR */ unsigned long result; /* Result of a system call */ } user_regs_struct_t; #define NVSXREG 32 #define USER_FPREGS_FL_FP 0x00001 #define USER_FPREGS_FL_ALTIVEC 0x00002 #define USER_FPREGS_FL_VSX 0x00004 #define USER_FPREGS_FL_TM 0x00010 #ifndef NT_PPC_TM_SPR #define NT_PPC_TM_CGPR 0x108 /* TM checkpointed GPR Registers */ #define NT_PPC_TM_CFPR 0x109 /* TM checkpointed FPR Registers */ #define NT_PPC_TM_CVMX 0x10a /* TM checkpointed VMX Registers */ #define NT_PPC_TM_CVSX 0x10b /* TM checkpointed VSX Registers */ #define NT_PPC_TM_SPR 0x10c /* TM Special Purpose Registers */ #endif #define MSR_TMA (1UL << 34) /* bit 29 Trans Mem state: Transactional */ #define MSR_TMS (1UL << 33) /* bit 30 Trans Mem state: Suspended */ #define MSR_TM (1UL << 32) /* bit 31 Trans Mem Available */ #define MSR_VEC (1UL << 25) #define MSR_VSX (1UL << 23) #define MSR_TM_ACTIVE(x) ((((x)&MSR_TM) && ((x) & (MSR_TMA | MSR_TMS))) != 0) typedef struct { uint64_t fpregs[NFPREG]; __vector128 vrregs[NVRREG]; uint64_t vsxregs[NVSXREG]; int flags; struct tm_regs { int flags; struct { uint64_t tfhar, texasr, tfiar; } tm_spr_regs; user_regs_struct_t regs; uint64_t fpregs[NFPREG]; __vector128 vrregs[NVRREG]; uint64_t vsxregs[NVSXREG]; } tm; } user_fpregs_struct_t; #define REG_RES(regs) ((uint64_t)(regs).gpr[3]) #define REG_IP(regs) ((uint64_t)(regs).nip) #define SET_REG_IP(regs, val) ((regs).nip = (val)) #define REG_SP(regs) ((uint64_t)(regs).gpr[1]) #define REG_SYSCALL_NR(regs) ((uint64_t)(regs).gpr[0]) #define user_regs_native(pregs) true #define ARCH_SI_TRAP TRAP_BRKPT #define __NR(syscall, compat) \ ({ \ (void)compat; \ __NR_##syscall; \ }) #define __compel_arch_fetch_thread_area(tid, th) 0 #define compel_arch_fetch_thread_area(tctl) 0 #define compel_arch_get_tls_task(ctl, tls) #define compel_arch_get_tls_thread(tctl, tls) #endif /* UAPI_COMPEL_ASM_TYPES_H__ */
2,758
27.443299
77
h