1 // Copyright 2015 PDFium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "testing/utils/path_service.h"
6
7 #ifdef _WIN32
8 #include <Windows.h>
9 #elif defined(__APPLE__)
10 #include <mach-o/dyld.h>
11 #else // Linux
12 #include <linux/limits.h>
13 #include <unistd.h>
14 #endif // _WIN32
15
16 #include <string>
17
18 #include "core/fxcrt/fx_system.h"
19
20 // static
EndsWithSeparator(const std::string & path)21 bool PathService::EndsWithSeparator(const std::string& path) {
22 return path.size() > 1 && path[path.size() - 1] == PATH_SEPARATOR;
23 }
24
25 // static
GetExecutableDir(std::string * path)26 bool PathService::GetExecutableDir(std::string* path) {
27 // Get the current executable file path.
28 #ifdef _WIN32
29 char path_buffer[MAX_PATH];
30 path_buffer[0] = 0;
31
32 if (GetModuleFileNameA(NULL, path_buffer, MAX_PATH) == 0)
33 return false;
34 *path = std::string(path_buffer);
35 #elif defined(__APPLE__)
36 ASSERT(path);
37 unsigned int path_length = 0;
38 _NSGetExecutablePath(NULL, &path_length);
39 if (path_length == 0)
40 return false;
41
42 path->reserve(path_length);
43 path->resize(path_length - 1);
44 if (_NSGetExecutablePath(&((*path)[0]), &path_length))
45 return false;
46 #else // Linux
47 static const char kProcSelfExe[] = "/proc/self/exe";
48 char buf[PATH_MAX];
49 ssize_t count = ::readlink(kProcSelfExe, buf, PATH_MAX);
50 if (count <= 0)
51 return false;
52
53 *path = std::string(buf, count);
54 #endif // _WIN32
55
56 // Get the directory path.
57 std::size_t pos = path->size() - 1;
58 if (EndsWithSeparator(*path))
59 pos--;
60 std::size_t found = path->find_last_of(PATH_SEPARATOR, pos);
61 if (found == std::string::npos)
62 return false;
63 path->resize(found);
64 return true;
65 }
66
67 // static
GetSourceDir(std::string * path)68 bool PathService::GetSourceDir(std::string* path) {
69 if (!GetExecutableDir(path))
70 return false;
71
72 if (!EndsWithSeparator(*path))
73 path->push_back(PATH_SEPARATOR);
74 path->append("..");
75 path->push_back(PATH_SEPARATOR);
76 #if defined(ANDROID)
77 path->append("chromium_tests_root");
78 #else // Non-Android
79 path->append("..");
80 #endif // defined(ANDROID)
81 return true;
82 }
83
84 // static
GetTestDataDir(std::string * path)85 bool PathService::GetTestDataDir(std::string* path) {
86 if (!GetSourceDir(path))
87 return false;
88
89 if (!EndsWithSeparator(*path))
90 path->push_back(PATH_SEPARATOR);
91 path->append("testing");
92 path->push_back(PATH_SEPARATOR);
93 path->append("resources");
94 return true;
95 }
96
97 // static
GetTestFilePath(const std::string & file_name,std::string * path)98 bool PathService::GetTestFilePath(const std::string& file_name,
99 std::string* path) {
100 if (!GetTestDataDir(path))
101 return false;
102
103 if (!EndsWithSeparator(*path))
104 path->push_back(PATH_SEPARATOR);
105 path->append(file_name);
106 return true;
107 }
108