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/threading/thread_restrictions.h"
15
16 namespace base::apple::internal {
17
GetExecutablePath()18 base::FilePath GetExecutablePath() {
19 // Executable path can have relative references ("..") depending on
20 // how the app was launched.
21 uint32_t executable_length = 0;
22 _NSGetExecutablePath(NULL, &executable_length);
23 DCHECK_GT(executable_length, 1u);
24 // `executable_length` is the total buffer size required including the NUL
25 // terminator, while `basic_string` guarantees that enough space is reserved
26 // so that index may be any value between 0 and size() inclusive, though it is
27 // UB to set `str[size()]` to anything other than '\0'.
28 std::string executable_path(executable_length - 1, '\0');
29 int rv = _NSGetExecutablePath(executable_path.data(), &executable_length);
30 DCHECK_EQ(rv, 0);
31
32 // _NSGetExecutablePath may return paths containing ./ or ../ which makes
33 // FilePath::DirName() work incorrectly, convert it to absolute path so that
34 // paths such as DIR_SRC_TEST_DATA_ROOT can work, since we expect absolute
35 // paths to be returned here.
36 // TODO(bauerb): http://crbug.com/259796, http://crbug.com/373477
37 base::ScopedAllowBlocking allow_blocking;
38 return base::MakeAbsoluteFilePath(base::FilePath(executable_path));
39 }
40
GetModulePathForAddress(base::FilePath * path,const void * address)41 bool GetModulePathForAddress(base::FilePath* path, const void* address) {
42 Dl_info info;
43 if (dladdr(address, &info) == 0) {
44 return false;
45 }
46 *path = base::FilePath(info.dli_fname);
47 return true;
48 }
49
50 } // namespace base::apple::internal
51