1 // Copyright (c) 2012 The Chromium 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.
5 // Defines base::PathProviderMac which replaces base::PathProviderPosix for Mac
6 // in base/path_service.cc.
9 #import <Foundation/Foundation.h>
10 #include <mach-o/dyld.h>
12 #include "base/base_paths.h"
13 #include "base/compiler_specific.h"
14 #include "base/file_util.h"
15 #include "base/files/file_path.h"
16 #include "base/logging.h"
17 #include "base/mac/foundation_util.h"
18 #include "base/path_service.h"
19 #include "base/string_util.h"
20 #include "build/build_config.h"
24 void GetNSExecutablePath(base::FilePath* path) {
26 // Executable path can have relative references ("..") depending on
27 // how the app was launched.
28 uint32_t executable_length = 0;
29 _NSGetExecutablePath(NULL, &executable_length);
30 DCHECK_GT(executable_length, 1u);
31 std::string executable_path;
32 int rv = _NSGetExecutablePath(WriteInto(&executable_path, executable_length),
35 *path = base::FilePath(executable_path);
38 // Returns true if the module for |address| is found. |path| will contain
39 // the path to the module. Note that |path| may not be absolute.
40 bool GetModulePathForAddress(base::FilePath* path,
41 const void* address) WARN_UNUSED_RESULT;
43 bool GetModulePathForAddress(base::FilePath* path, const void* address) {
45 if (dladdr(address, &info) == 0)
47 *path = base::FilePath(info.dli_fname);
55 bool PathProviderMac(int key, base::FilePath* result) {
58 GetNSExecutablePath(result);
60 case base::FILE_MODULE:
61 return GetModulePathForAddress(result,
62 reinterpret_cast<const void*>(&base::PathProviderMac));
63 case base::DIR_APP_DATA: {
64 bool success = base::mac::GetUserDirectory(NSApplicationSupportDirectory,
67 // On IOS, this directory does not exist unless it is created explicitly.
68 if (success && !file_util::PathExists(*result))
69 success = file_util::CreateDirectory(*result);
70 #endif // defined(OS_IOS)
73 case base::DIR_SOURCE_ROOT:
74 // Go through PathService to catch overrides.
75 if (!PathService::Get(base::FILE_EXE, result))
78 // Start with the executable's directory.
79 *result = result->DirName();
82 if (base::mac::AmIBundled()) {
83 // The bundled app executables (Chromium, TestShell, etc) live five
85 // src/xcodebuild/{Debug|Release}/Chromium.app/Contents/MacOS/Chromium
86 *result = result->DirName().DirName().DirName().DirName().DirName();
88 // Unit tests execute two levels deep from the source root, eg:
89 // src/xcodebuild/{Debug|Release}/base_unittests
90 *result = result->DirName().DirName();
94 case base::DIR_USER_DESKTOP:
96 // iOS does not have desktop directories.
100 return base::mac::GetUserDirectory(NSDesktopDirectory, result);
102 case base::DIR_CACHE:
103 return base::mac::GetUserDirectory(NSCachesDirectory, result);
105 *result = base::mac::NSStringToFilePath(NSHomeDirectory());