dyld-732.8.tar.gz
[apple/dyld.git] / dyld3 / ClosureFileSystemPhysical.cpp
1 /*
2 * Copyright (c) 2017 Apple Inc. All rights reserved.
3 *
4 * @APPLE_LICENSE_HEADER_START@
5 *
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. Please obtain a copy of the License at
10 * http://www.opensource.apple.com/apsl/ and read it before using this
11 * file.
12 *
13 * The Original Code and all software distributed under the License are
14 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18 * Please see the License for the specific language governing rights and
19 * limitations under the License.
20 *
21 * @APPLE_LICENSE_HEADER_END@
22 */
23
24 #include "ClosureFileSystemPhysical.h"
25
26 #include <string.h>
27 #include <stdlib.h>
28 #include <unistd.h>
29 #include <fcntl.h>
30 #if BUILDING_UPDATE_DYLD_CACHE_BUILDER
31 #include <rootless.h>
32 #endif
33 #include <sys/errno.h>
34 #include <sys/mman.h>
35 #include <sys/stat.h>
36 #include <mach/mach.h>
37 #if !TARGET_OS_SIMULATOR && !TARGET_OS_DRIVERKIT
38 #include <sandbox.h>
39 #include <sandbox/private.h>
40 #endif
41
42 using dyld3::closure::FileSystemPhysical;
43
44 bool FileSystemPhysical::getRealPath(const char possiblePath[MAXPATHLEN], char realPath[MAXPATHLEN]) const {
45 __block bool success = false;
46 // first pass: open file and ask kernel for canonical path
47 forEachPath(possiblePath, ^(const char* aPath, unsigned prefixLen, bool& stop) {
48 int fd = ::open(aPath, O_RDONLY, 0);
49 if ( fd != -1 ) {
50 char tempPath[MAXPATHLEN];
51 success = (fcntl(fd, F_GETPATH, tempPath) == 0);
52 ::close(fd);
53 if ( success ) {
54 // if prefix was used, remove it
55 strcpy(realPath, &tempPath[prefixLen]);
56 }
57 stop = true;
58 }
59 });
60 if (success)
61 return success;
62
63 // second pass: file does not exist but may be a symlink to a non-existent file
64 // This is only for use on-device on platforms where dylibs are removed
65 if ( _overlayPath == nullptr && _rootPath == nullptr ) {
66 realpath(possiblePath, realPath);
67 int realpathErrno = errno;
68 // If realpath() resolves to a path which does not exist on disk, errno is set to ENOENT
69 success = (realpathErrno == ENOENT) || (realpathErrno == 0);
70 }
71 return success;
72 }
73
74 static bool sandboxBlocked(const char* path, const char* kind)
75 {
76 #if TARGET_OS_SIMULATOR || TARGET_OS_DRIVERKIT
77 // sandbox calls not yet supported in dyld_sim
78 return false;
79 #else
80 sandbox_filter_type filter = (sandbox_filter_type)(SANDBOX_FILTER_PATH | SANDBOX_CHECK_NO_REPORT);
81 return ( sandbox_check(getpid(), kind, filter, path) > 0 );
82 #endif
83 }
84
85 static bool sandboxBlockedMmap(const char* path)
86 {
87 return sandboxBlocked(path, "file-map-executable");
88 }
89
90 static bool sandboxBlockedOpen(const char* path)
91 {
92 return sandboxBlocked(path, "file-read-data");
93 }
94
95 static bool sandboxBlockedStat(const char* path)
96 {
97 return sandboxBlocked(path, "file-read-metadata");
98 }
99
100 void FileSystemPhysical::forEachPath(const char* path, void (^handler)(const char* fullPath, unsigned prefixLen, bool& stop)) const
101 {
102 bool stop = false;
103 char altPath[PATH_MAX];
104 if ( _overlayPath != nullptr ) {
105 strlcpy(altPath, _overlayPath, PATH_MAX);
106 strlcat(altPath, path, PATH_MAX);
107 handler(altPath, (unsigned)strlen(_overlayPath), stop);
108 if ( stop )
109 return;
110 }
111 if ( _rootPath != nullptr ) {
112 strlcpy(altPath, _rootPath, PATH_MAX);
113 strlcat(altPath, path, PATH_MAX);
114 handler(altPath, (unsigned)strlen(_rootPath), stop);
115 if ( stop )
116 return;
117 }
118 else {
119 handler(path, 0, stop);
120 }
121 }
122
123 static bool isFileRelativePath(const char* path)
124 {
125 if ( path[0] == '/' )
126 return false;
127 if ( path[0] != '.' )
128 return true;
129 if ( path[1] == '/' )
130 return true;
131 if ( (path[1] == '.') && (path[2] == '/') )
132 return true;
133 return false;
134 }
135
136 // Returns true on success. If an error occurs the given callback will be called with the reason.
137 // On success, info is filled with info about the loaded file. If the path supplied includes a symlink,
138 // the supplier realerPath is filled in with the real path of the file, otherwise it is set to the empty string.
139 bool FileSystemPhysical::loadFile(const char* path, LoadedFileInfo& info, char realerPath[MAXPATHLEN], void (^error)(const char* format, ...)) const {
140 if ( !_allowRelativePaths && isFileRelativePath(path) ) {
141 error("relative file paths not allowed '%s'", path);
142 return false;
143 }
144 // open file
145 __block int fd;
146 __block struct stat statBuf;
147 __block bool sipProtected = false;
148 forEachPath(path, ^(const char* aPath, unsigned prefixLen, bool& stop) {
149 fd = ::open(aPath, O_RDONLY, 0);
150 if ( fd == -1 ) {
151 int openErrno = errno;
152 if ( (openErrno == EPERM) && sandboxBlockedOpen(path) )
153 error("file system sandbox blocked open(\"%s\", O_RDONLY)", path);
154 else if ( (openErrno != ENOENT) && (openErrno != ENOTDIR) )
155 error("open(\"%s\", O_RDONLY) failed with errno=%d", path, openErrno);
156 }
157 else {
158 // get file info
159 #if TARGET_OS_SIMULATOR
160 if ( ::stat(aPath, &statBuf) != 0 ) {
161 #else
162 if ( ::fstat(fd, &statBuf) != 0 ) {
163 #endif
164 int statErr = errno;
165 if ( (statErr == EPERM) && sandboxBlockedStat(path) )
166 error("file system sandbox blocked stat(\"%s\")", path);
167 else
168 error("stat(\"%s\") failed with errno=%d", path, errno);
169 ::close(fd);
170 fd = -1;
171 }
172 else {
173 // Get the realpath of the file if it is a symlink
174 char tempPath[MAXPATHLEN];
175 if ( fcntl(fd, F_GETPATH, tempPath) == 0 ) {
176 const char* realPathWithin = &tempPath[prefixLen];
177 // Don't set the realpath if it is just the same as the regular path
178 if ( strcmp(path, realPathWithin) == 0 ) {
179 // zero out realerPath if path is fine as-is
180 // <rdar://45018392> don't trash input 'path' if realerPath is same buffer as path
181 if ( realerPath != path )
182 realerPath[0] = '\0';
183 }
184 else
185 strcpy(realerPath, realPathWithin);
186 #if BUILDING_UPDATE_DYLD_CACHE_BUILDER
187 sipProtected = (rootless_check_trusted_fd(fd) == 0);
188 #endif
189 stop = true;
190 }
191 else {
192 error("Could not get real path for \"%s\"\n", path);
193 ::close(fd);
194 fd = -1;
195 }
196 }
197 }
198 });
199 if ( fd == -1 )
200 return false;
201
202 // only regular files can be loaded
203 if ( !S_ISREG(statBuf.st_mode) ) {
204 error("not a file for %s", path);
205 ::close(fd);
206 return false;
207 }
208
209 // mach-o files must be at list one page in size
210 if ( statBuf.st_size < 4096 ) {
211 error("file too short %s", path);
212 ::close(fd);
213 return false;
214 }
215
216 info.fileContent = nullptr;
217 info.fileContentLen = statBuf.st_size;
218 info.sliceOffset = 0;
219 info.sliceLen = statBuf.st_size;
220 info.isSipProtected = sipProtected;
221 info.inode = statBuf.st_ino;
222 info.mtime = statBuf.st_mtime;
223 info.path = path;
224
225 // mmap() whole file
226 void* wholeFile = ::mmap(nullptr, (size_t)statBuf.st_size, PROT_READ, MAP_PRIVATE|MAP_RESILIENT_CODESIGN, fd, 0);
227 if ( wholeFile == MAP_FAILED ) {
228 int mmapErr = errno;
229 if ( mmapErr == EPERM ) {
230 if ( sandboxBlockedMmap(path) )
231 error("file system sandbox blocked mmap() of '%s'", path);
232 else
233 error("code signing blocked mmap() of '%s'", path);
234 }
235 else {
236 error("mmap() failed with errno=%d for %s", errno, path);
237 }
238 ::close(fd);
239 return false;
240 }
241 info.fileContent = wholeFile;
242
243 // Set unmap as the unload method.
244 info.unload = [](const LoadedFileInfo& info) {
245 ::munmap((void*)info.fileContent, (size_t)info.fileContentLen);
246 };
247
248 ::close(fd);
249 return true;
250 }
251
252 void FileSystemPhysical::unloadFile(const LoadedFileInfo& info) const {
253 if (info.unload)
254 info.unload(info);
255 }
256
257 void FileSystemPhysical::unloadPartialFile(LoadedFileInfo& info, uint64_t keepStartOffset, uint64_t keepLength) const {
258 // Unmap from 0..keepStartOffset and (keepStartOffset+keepLength)..info.fileContentLen
259 if (keepStartOffset)
260 ::munmap((void*)info.fileContent, (size_t)keepStartOffset);
261 if ((keepStartOffset + keepLength) != info.fileContentLen) {
262 // Round up to page alignment
263 keepLength = (keepLength + PAGE_SIZE - 1) & (-PAGE_SIZE);
264 ::munmap((void*)((char*)info.fileContent + keepStartOffset + keepLength), (size_t)(info.fileContentLen - (keepStartOffset + keepLength)));
265 }
266 info.fileContent = (const void*)((char*)info.fileContent + keepStartOffset);
267 info.fileContentLen = keepLength;
268 }
269
270 bool FileSystemPhysical::fileExists(const char* path, uint64_t* inode, uint64_t* mtime,
271 bool* issetuid, bool* inodesMatchRuntime) const {
272 __block bool result = false;
273 forEachPath(path, ^(const char* aPath, unsigned prefixLen, bool& stop) {
274 struct stat statBuf;
275 if ( ::stat(aPath, &statBuf) == 0 ) {
276 if (inode)
277 *inode = statBuf.st_ino;
278 if (mtime)
279 *mtime = statBuf.st_mtime;
280 if (issetuid)
281 *issetuid = (statBuf.st_mode & (S_ISUID|S_ISGID));
282 if (inodesMatchRuntime)
283 *inodesMatchRuntime = true;
284 stop = true;
285 result = true;
286 }
287 });
288 return result;
289 }