1 // Copyright 2023 The Chromium Authors
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 "base/base_paths_apple.h"
6
7 #include <dlfcn.h>
8 #include <mach-o/dyld.h>
9 #include <stdint.h>
10
11 #include "base/check_op.h"
12 #include "base/files/file_path.h"
13 #include "base/files/file_util.h"
14 #include "base/strings/string_util.h"
15 #include "base/threading/thread_restrictions.h"
16
17 namespace base::apple::internal {
18
GetExecutablePath()19 base::FilePath GetExecutablePath() {
20 // Executable path can have relative references ("..") depending on
21 // how the app was launched.
22 uint32_t executable_length = 0;
23 _NSGetExecutablePath(NULL, &executable_length);
24 DCHECK_GT(executable_length, 1u);
25 std::string executable_path;
26 int rv = _NSGetExecutablePath(
27 base::WriteInto(&executable_path, executable_length), &executable_length);
28 DCHECK_EQ(rv, 0);
29
30 // _NSGetExecutablePath may return paths containing ./ or ../ which makes
31 // FilePath::DirName() work incorrectly, convert it to absolute path so that
32 // paths such as DIR_SRC_TEST_DATA_ROOT can work, since we expect absolute
33 // paths to be returned here.
34 // TODO(bauerb): http://crbug.com/259796, http://crbug.com/373477
35 base::ScopedAllowBlocking allow_blocking;
36 return base::MakeAbsoluteFilePath(base::FilePath(executable_path));
37 }
38
GetModulePathForAddress(base::FilePath * path,const void * address)39 bool GetModulePathForAddress(base::FilePath* path, const void* address) {
40 Dl_info info;
41 if (dladdr(address, &info) == 0) {
42 return false;
43 }
44 *path = base::FilePath(info.dli_fname);
45 return true;
46 }
47
48 } // namespace base::apple::internal
49