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 <inttypes.h>
21 #include <stdint.h>
22 #include <stdio.h>
23
24 #include "perfetto/base/build_config.h"
25 #include "perfetto/ext/base/unix_socket.h"
26
27 namespace perfetto {
28 namespace ipc {
29
30 struct TestSocket {
TestSocketTestSocket31 explicit constexpr TestSocket(const char* test_name)
32 : test_name_(test_name) {}
33
34 const char* test_name_;
35 char buf_[64]{};
36
37 // Inline to avoid multiple definition linker warnings (and avoid a .cc file).
38 inline base::SockFamily family();
39 inline const char* name();
40 inline void Destroy();
41 };
42
43 #if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
44
name()45 const char* TestSocket::name() {
46 uint64_t hash = 5381;
47 for (const char* c = test_name_; *c; c++)
48 hash = 33 * hash + static_cast<uint64_t>(*c);
49 snprintf(buf_, sizeof(buf_), "127.0.0.1:%" PRIu64, 40000 + (hash % 20000));
50 return buf_;
51 }
family()52 base::SockFamily TestSocket::family() {
53 return base::SockFamily::kInet;
54 }
Destroy()55 void TestSocket::Destroy() {}
56
57 #elif PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
58
name()59 const char* TestSocket::name() {
60 snprintf(buf_, sizeof(buf_), "@%s", test_name_);
61 return buf_;
62 }
family()63 base::SockFamily TestSocket::family() {
64 return base::SockFamily::kUnix;
65 }
Destroy()66 void TestSocket::Destroy() {}
67
68 #else
69
name()70 const char* TestSocket::name() {
71 snprintf(buf_, sizeof(buf_), "/tmp/%s.sock", test_name_);
72 return buf_;
73 }
family()74 base::SockFamily TestSocket::family() {
75 return base::SockFamily::kUnix;
76 }
Destroy()77 void TestSocket::Destroy() {
78 remove(name());
79 }
80 #endif
81
82 } // namespace ipc
83 } // namespace perfetto
84
85 #endif // SRC_IPC_TEST_TEST_SOCKET_H_
86