1 /*
2 * Copyright (C) 2018 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 #include "src/base/test/utils.h"
18
19 #include <stdlib.h>
20
21 #include "perfetto/base/build_config.h"
22 #include "perfetto/base/logging.h"
23
24 #if PERFETTO_BUILDFLAG(PERFETTO_OS_LINUX) || \
25 PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID) || \
26 PERFETTO_BUILDFLAG(PERFETTO_OS_MACOSX) || \
27 PERFETTO_BUILDFLAG(PERFETTO_OS_FUCHSIA)
28 #include <limits.h>
29 #include <unistd.h>
30 #endif
31
32 #if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN) && \
33 !PERFETTO_BUILDFLAG(PERFETTO_COMPILER_GCC)
34 #include <corecrt_io.h>
35 #include <io.h>
36 #endif
37
38 #if PERFETTO_BUILDFLAG(PERFETTO_OS_MACOSX)
39 #include <mach-o/dyld.h>
40 #endif
41
42 namespace perfetto {
43 namespace base {
44
GetCurExecutableDir()45 std::string GetCurExecutableDir() {
46 std::string self_path;
47 #if PERFETTO_BUILDFLAG(PERFETTO_OS_LINUX) || \
48 PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID) || \
49 PERFETTO_BUILDFLAG(PERFETTO_OS_FUCHSIA)
50 char buf[PATH_MAX];
51 ssize_t size = readlink("/proc/self/exe", buf, sizeof(buf));
52 PERFETTO_CHECK(size != -1);
53 // readlink does not null terminate.
54 self_path = std::string(buf, static_cast<size_t>(size));
55 #elif PERFETTO_BUILDFLAG(PERFETTO_OS_MACOSX)
56 uint32_t size = 0;
57 PERFETTO_CHECK(_NSGetExecutablePath(nullptr, &size));
58 self_path.resize(size);
59 PERFETTO_CHECK(_NSGetExecutablePath(&self_path[0], &size) == 0);
60 #else
61 PERFETTO_FATAL(
62 "GetCurExecutableDir() not implemented on the current platform");
63 #endif
64 // Cut binary name.
65 return self_path.substr(0, self_path.find_last_of("/"));
66 }
67
GetTestDataPath(const std::string & path)68 std::string GetTestDataPath(const std::string& path) {
69 std::string self_path = GetCurExecutableDir();
70 std::string full_path = self_path + "/../../" + path;
71 if (access(full_path.c_str(), 0 /*F_OK*/) == 0)
72 return full_path;
73 full_path = self_path + "/" + path;
74 if (access(full_path.c_str(), 0 /*F_OK*/) == 0)
75 return full_path;
76 // Fall back to relative to root dir.
77 return path;
78 }
79
80 } // namespace base
81 } // namespace perfetto
82