1 /*
2 * Copyright (C) 2017 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #ifndef SRC_IPC_TEST_TEST_SOCKET_H_
18 #define SRC_IPC_TEST_TEST_SOCKET_H_
19
20 #include <stdint.h>
21 #include <stdio.h>
22
23 #include <cinttypes>
24
25 #include "perfetto/base/build_config.h"
26 #include "perfetto/ext/base/unix_socket.h"
27
28 namespace perfetto {
29 namespace ipc {
30
31 struct TestSocket {
TestSocketTestSocket32 explicit constexpr TestSocket(const char* test_name)
33 : test_name_(test_name) {}
34
35 const char* test_name_;
36 char buf_[64]{};
37
38 // Inline to avoid multiple definition linker warnings (and avoid a .cc file).
39 inline base::SockFamily family();
40 inline const char* name();
41 inline void Destroy();
42 };
43
44 #if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
45
name()46 const char* TestSocket::name() {
47 uint64_t hash = 5381;
48 for (const char* c = test_name_; *c; c++)
49 hash = 33 * hash + static_cast<uint64_t>(*c);
50 snprintf(buf_, sizeof(buf_), "127.0.0.1:%" PRIu64, 40000 + (hash % 20000));
51 return buf_;
52 }
family()53 base::SockFamily TestSocket::family() {
54 return base::SockFamily::kInet;
55 }
Destroy()56 void TestSocket::Destroy() {}
57
58 #elif PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
59
name()60 const char* TestSocket::name() {
61 snprintf(buf_, sizeof(buf_), "@%s", test_name_);
62 return buf_;
63 }
family()64 base::SockFamily TestSocket::family() {
65 return base::SockFamily::kUnix;
66 }
Destroy()67 void TestSocket::Destroy() {}
68
69 #elif PERFETTO_BUILDFLAG(PERFETTO_OS_FUCHSIA)
70
name()71 const char* TestSocket::name() {
72 return "zx_socket";
73 }
family()74 base::SockFamily TestSocket::family() {
75 return base::SockFamily::kUnix;
76 }
Destroy()77 void TestSocket::Destroy() {}
78
79 #else
80
name()81 const char* TestSocket::name() {
82 snprintf(buf_, sizeof(buf_), "/tmp/%s.sock", test_name_);
83 return buf_;
84 }
family()85 base::SockFamily TestSocket::family() {
86 return base::SockFamily::kUnix;
87 }
Destroy()88 void TestSocket::Destroy() {
89 remove(name());
90 }
91 #endif
92
93 } // namespace ipc
94 } // namespace perfetto
95
96 #endif // SRC_IPC_TEST_TEST_SOCKET_H_
97