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.
4
5 #include "base/memory/shared_memory.h"
6
7 #include <errno.h>
8 #include <fcntl.h>
9 #include <stddef.h>
10 #include <sys/mman.h>
11 #include <sys/stat.h>
12 #include <unistd.h>
13
14 #include "base/files/file_util.h"
15 #include "base/files/scoped_file.h"
16 #include "base/logging.h"
17 #include "base/posix/eintr_wrapper.h"
18 #include "base/posix/safe_strerror.h"
19 #include "base/process/process_metrics.h"
20 #include "base/profiler/scoped_tracker.h"
21 #include "base/scoped_generic.h"
22 #include "base/strings/utf_string_conversions.h"
23 #include "build/build_config.h"
24
25 #if defined(OS_ANDROID)
26 #include "base/os_compat_android.h"
27 #include "third_party/ashmem/ashmem.h"
28 #elif defined(__ANDROID__)
29 #include <cutils/ashmem.h>
30 #endif
31
32 namespace base {
33
34 namespace {
35
36 struct ScopedPathUnlinkerTraits {
InvalidValuebase::__anon4b3888fc0111::ScopedPathUnlinkerTraits37 static FilePath* InvalidValue() { return nullptr; }
38
Freebase::__anon4b3888fc0111::ScopedPathUnlinkerTraits39 static void Free(FilePath* path) {
40 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466437
41 // is fixed.
42 tracked_objects::ScopedTracker tracking_profile(
43 FROM_HERE_WITH_EXPLICIT_FUNCTION(
44 "466437 SharedMemory::Create::Unlink"));
45 if (unlink(path->value().c_str()))
46 PLOG(WARNING) << "unlink";
47 }
48 };
49
50 // Unlinks the FilePath when the object is destroyed.
51 typedef ScopedGeneric<FilePath*, ScopedPathUnlinkerTraits> ScopedPathUnlinker;
52
53 #if !defined(OS_ANDROID) && !defined(__ANDROID__)
54 // Makes a temporary file, fdopens it, and then unlinks it. |fp| is populated
55 // with the fdopened FILE. |readonly_fd| is populated with the opened fd if
56 // options.share_read_only is true. |path| is populated with the location of
57 // the file before it was unlinked.
58 // Returns false if there's an unhandled failure.
CreateAnonymousSharedMemory(const SharedMemoryCreateOptions & options,ScopedFILE * fp,ScopedFD * readonly_fd,FilePath * path)59 bool CreateAnonymousSharedMemory(const SharedMemoryCreateOptions& options,
60 ScopedFILE* fp,
61 ScopedFD* readonly_fd,
62 FilePath* path) {
63 // It doesn't make sense to have a open-existing private piece of shmem
64 DCHECK(!options.open_existing_deprecated);
65 // Q: Why not use the shm_open() etc. APIs?
66 // A: Because they're limited to 4mb on OS X. FFFFFFFUUUUUUUUUUU
67 FilePath directory;
68 ScopedPathUnlinker path_unlinker;
69 if (GetShmemTempDir(options.executable, &directory)) {
70 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466437
71 // is fixed.
72 tracked_objects::ScopedTracker tracking_profile(
73 FROM_HERE_WITH_EXPLICIT_FUNCTION(
74 "466437 SharedMemory::Create::OpenTemporaryFile"));
75 fp->reset(base::CreateAndOpenTemporaryFileInDir(directory, path));
76
77 // Deleting the file prevents anyone else from mapping it in (making it
78 // private), and prevents the need for cleanup (once the last fd is
79 // closed, it is truly freed).
80 if (*fp)
81 path_unlinker.reset(path);
82 }
83
84 if (*fp) {
85 if (options.share_read_only) {
86 // TODO(erikchen): Remove ScopedTracker below once
87 // http://crbug.com/466437 is fixed.
88 tracked_objects::ScopedTracker tracking_profile(
89 FROM_HERE_WITH_EXPLICIT_FUNCTION(
90 "466437 SharedMemory::Create::OpenReadonly"));
91 // Also open as readonly so that we can ShareReadOnlyToProcess.
92 readonly_fd->reset(HANDLE_EINTR(open(path->value().c_str(), O_RDONLY)));
93 if (!readonly_fd->is_valid()) {
94 DPLOG(ERROR) << "open(\"" << path->value() << "\", O_RDONLY) failed";
95 fp->reset();
96 return false;
97 }
98 }
99 }
100 return true;
101 }
102 #endif // !defined(OS_ANDROID) && !defined(__ANDROID__)
103 }
104
SharedMemoryCreateOptions()105 SharedMemoryCreateOptions::SharedMemoryCreateOptions()
106 : name_deprecated(nullptr),
107 open_existing_deprecated(false),
108 size(0),
109 executable(false),
110 share_read_only(false) {}
111
SharedMemory()112 SharedMemory::SharedMemory()
113 : mapped_file_(-1),
114 readonly_mapped_file_(-1),
115 mapped_size_(0),
116 memory_(NULL),
117 read_only_(false),
118 requested_size_(0) {
119 }
120
SharedMemory(const SharedMemoryHandle & handle,bool read_only)121 SharedMemory::SharedMemory(const SharedMemoryHandle& handle, bool read_only)
122 : mapped_file_(handle.fd),
123 readonly_mapped_file_(-1),
124 mapped_size_(0),
125 memory_(NULL),
126 read_only_(read_only),
127 requested_size_(0) {
128 }
129
~SharedMemory()130 SharedMemory::~SharedMemory() {
131 Unmap();
132 Close();
133 }
134
135 // static
IsHandleValid(const SharedMemoryHandle & handle)136 bool SharedMemory::IsHandleValid(const SharedMemoryHandle& handle) {
137 return handle.fd >= 0;
138 }
139
140 // static
NULLHandle()141 SharedMemoryHandle SharedMemory::NULLHandle() {
142 return SharedMemoryHandle();
143 }
144
145 // static
CloseHandle(const SharedMemoryHandle & handle)146 void SharedMemory::CloseHandle(const SharedMemoryHandle& handle) {
147 DCHECK_GE(handle.fd, 0);
148 if (IGNORE_EINTR(close(handle.fd)) < 0)
149 DPLOG(ERROR) << "close";
150 }
151
152 // static
GetHandleLimit()153 size_t SharedMemory::GetHandleLimit() {
154 return base::GetMaxFds();
155 }
156
157 // static
DuplicateHandle(const SharedMemoryHandle & handle)158 SharedMemoryHandle SharedMemory::DuplicateHandle(
159 const SharedMemoryHandle& handle) {
160 int duped_handle = HANDLE_EINTR(dup(handle.fd));
161 if (duped_handle < 0)
162 return base::SharedMemory::NULLHandle();
163 return base::FileDescriptor(duped_handle, true);
164 }
165
166 // static
GetFdFromSharedMemoryHandle(const SharedMemoryHandle & handle)167 int SharedMemory::GetFdFromSharedMemoryHandle(
168 const SharedMemoryHandle& handle) {
169 return handle.fd;
170 }
171
CreateAndMapAnonymous(size_t size)172 bool SharedMemory::CreateAndMapAnonymous(size_t size) {
173 return CreateAnonymous(size) && Map(size);
174 }
175
176 #if !defined(OS_ANDROID) && !defined(__ANDROID__)
177 // static
GetSizeFromSharedMemoryHandle(const SharedMemoryHandle & handle,size_t * size)178 bool SharedMemory::GetSizeFromSharedMemoryHandle(
179 const SharedMemoryHandle& handle,
180 size_t* size) {
181 struct stat st;
182 if (fstat(handle.fd, &st) != 0)
183 return false;
184 if (st.st_size < 0)
185 return false;
186 *size = st.st_size;
187 return true;
188 }
189
190 // Chromium mostly only uses the unique/private shmem as specified by
191 // "name == L"". The exception is in the StatsTable.
192 // TODO(jrg): there is no way to "clean up" all unused named shmem if
193 // we restart from a crash. (That isn't a new problem, but it is a problem.)
194 // In case we want to delete it later, it may be useful to save the value
195 // of mem_filename after FilePathForMemoryName().
Create(const SharedMemoryCreateOptions & options)196 bool SharedMemory::Create(const SharedMemoryCreateOptions& options) {
197 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466437
198 // is fixed.
199 tracked_objects::ScopedTracker tracking_profile1(
200 FROM_HERE_WITH_EXPLICIT_FUNCTION(
201 "466437 SharedMemory::Create::Start"));
202 DCHECK_EQ(-1, mapped_file_);
203 if (options.size == 0) return false;
204
205 if (options.size > static_cast<size_t>(std::numeric_limits<int>::max()))
206 return false;
207
208 // This function theoretically can block on the disk, but realistically
209 // the temporary files we create will just go into the buffer cache
210 // and be deleted before they ever make it out to disk.
211 base::ThreadRestrictions::ScopedAllowIO allow_io;
212
213 ScopedFILE fp;
214 bool fix_size = true;
215 ScopedFD readonly_fd;
216
217 FilePath path;
218 if (options.name_deprecated == NULL || options.name_deprecated->empty()) {
219 bool result =
220 CreateAnonymousSharedMemory(options, &fp, &readonly_fd, &path);
221 if (!result)
222 return false;
223 } else {
224 if (!FilePathForMemoryName(*options.name_deprecated, &path))
225 return false;
226
227 // Make sure that the file is opened without any permission
228 // to other users on the system.
229 const mode_t kOwnerOnly = S_IRUSR | S_IWUSR;
230
231 // First, try to create the file.
232 int fd = HANDLE_EINTR(
233 open(path.value().c_str(), O_RDWR | O_CREAT | O_EXCL, kOwnerOnly));
234 if (fd == -1 && options.open_existing_deprecated) {
235 // If this doesn't work, try and open an existing file in append mode.
236 // Opening an existing file in a world writable directory has two main
237 // security implications:
238 // - Attackers could plant a file under their control, so ownership of
239 // the file is checked below.
240 // - Attackers could plant a symbolic link so that an unexpected file
241 // is opened, so O_NOFOLLOW is passed to open().
242 fd = HANDLE_EINTR(
243 open(path.value().c_str(), O_RDWR | O_APPEND | O_NOFOLLOW));
244
245 // Check that the current user owns the file.
246 // If uid != euid, then a more complex permission model is used and this
247 // API is not appropriate.
248 const uid_t real_uid = getuid();
249 const uid_t effective_uid = geteuid();
250 struct stat sb;
251 if (fd >= 0 &&
252 (fstat(fd, &sb) != 0 || sb.st_uid != real_uid ||
253 sb.st_uid != effective_uid)) {
254 LOG(ERROR) <<
255 "Invalid owner when opening existing shared memory file.";
256 close(fd);
257 return false;
258 }
259
260 // An existing file was opened, so its size should not be fixed.
261 fix_size = false;
262 }
263
264 if (options.share_read_only) {
265 // Also open as readonly so that we can ShareReadOnlyToProcess.
266 readonly_fd.reset(HANDLE_EINTR(open(path.value().c_str(), O_RDONLY)));
267 if (!readonly_fd.is_valid()) {
268 DPLOG(ERROR) << "open(\"" << path.value() << "\", O_RDONLY) failed";
269 close(fd);
270 fd = -1;
271 return false;
272 }
273 }
274 if (fd >= 0) {
275 // "a+" is always appropriate: if it's a new file, a+ is similar to w+.
276 fp.reset(fdopen(fd, "a+"));
277 }
278 }
279 if (fp && fix_size) {
280 // Get current size.
281 struct stat stat;
282 if (fstat(fileno(fp.get()), &stat) != 0)
283 return false;
284 const size_t current_size = stat.st_size;
285 if (current_size != options.size) {
286 if (HANDLE_EINTR(ftruncate(fileno(fp.get()), options.size)) != 0)
287 return false;
288 }
289 requested_size_ = options.size;
290 }
291 if (fp == nullptr) {
292 PLOG(ERROR) << "Creating shared memory in " << path.value() << " failed";
293 FilePath dir = path.DirName();
294 if (access(dir.value().c_str(), W_OK | X_OK) < 0) {
295 PLOG(ERROR) << "Unable to access(W_OK|X_OK) " << dir.value();
296 if (dir.value() == "/dev/shm") {
297 LOG(FATAL) << "This is frequently caused by incorrect permissions on "
298 << "/dev/shm. Try 'sudo chmod 1777 /dev/shm' to fix.";
299 }
300 }
301 return false;
302 }
303
304 return PrepareMapFile(std::move(fp), std::move(readonly_fd));
305 }
306
307 // Our current implementation of shmem is with mmap()ing of files.
308 // These files need to be deleted explicitly.
309 // In practice this call is only needed for unit tests.
Delete(const std::string & name)310 bool SharedMemory::Delete(const std::string& name) {
311 FilePath path;
312 if (!FilePathForMemoryName(name, &path))
313 return false;
314
315 if (PathExists(path))
316 return base::DeleteFile(path, false);
317
318 // Doesn't exist, so success.
319 return true;
320 }
321
Open(const std::string & name,bool read_only)322 bool SharedMemory::Open(const std::string& name, bool read_only) {
323 FilePath path;
324 if (!FilePathForMemoryName(name, &path))
325 return false;
326
327 read_only_ = read_only;
328
329 const char *mode = read_only ? "r" : "r+";
330 ScopedFILE fp(base::OpenFile(path, mode));
331 ScopedFD readonly_fd(HANDLE_EINTR(open(path.value().c_str(), O_RDONLY)));
332 if (!readonly_fd.is_valid()) {
333 DPLOG(ERROR) << "open(\"" << path.value() << "\", O_RDONLY) failed";
334 return false;
335 }
336 return PrepareMapFile(std::move(fp), std::move(readonly_fd));
337 }
338 #endif // !defined(OS_ANDROID) && !defined(__ANDROID__)
339
MapAt(off_t offset,size_t bytes)340 bool SharedMemory::MapAt(off_t offset, size_t bytes) {
341 if (mapped_file_ == -1)
342 return false;
343
344 if (bytes > static_cast<size_t>(std::numeric_limits<int>::max()))
345 return false;
346
347 if (memory_)
348 return false;
349
350 #if defined(OS_ANDROID) || defined(__ANDROID__)
351 // On Android, Map can be called with a size and offset of zero to use the
352 // ashmem-determined size.
353 if (bytes == 0) {
354 DCHECK_EQ(0, offset);
355 int ashmem_bytes = ashmem_get_size_region(mapped_file_);
356 if (ashmem_bytes < 0)
357 return false;
358 bytes = ashmem_bytes;
359 }
360 #endif
361
362 memory_ = mmap(NULL, bytes, PROT_READ | (read_only_ ? 0 : PROT_WRITE),
363 MAP_SHARED, mapped_file_, offset);
364
365 bool mmap_succeeded = memory_ != (void*)-1 && memory_ != NULL;
366 if (mmap_succeeded) {
367 mapped_size_ = bytes;
368 DCHECK_EQ(0U, reinterpret_cast<uintptr_t>(memory_) &
369 (SharedMemory::MAP_MINIMUM_ALIGNMENT - 1));
370 } else {
371 memory_ = NULL;
372 }
373
374 return mmap_succeeded;
375 }
376
Unmap()377 bool SharedMemory::Unmap() {
378 if (memory_ == NULL)
379 return false;
380
381 munmap(memory_, mapped_size_);
382 memory_ = NULL;
383 mapped_size_ = 0;
384 return true;
385 }
386
handle() const387 SharedMemoryHandle SharedMemory::handle() const {
388 return FileDescriptor(mapped_file_, false);
389 }
390
Close()391 void SharedMemory::Close() {
392 if (mapped_file_ > 0) {
393 if (IGNORE_EINTR(close(mapped_file_)) < 0)
394 PLOG(ERROR) << "close";
395 mapped_file_ = -1;
396 }
397 if (readonly_mapped_file_ > 0) {
398 if (IGNORE_EINTR(close(readonly_mapped_file_)) < 0)
399 PLOG(ERROR) << "close";
400 readonly_mapped_file_ = -1;
401 }
402 }
403
404 #if !defined(OS_ANDROID) && !defined(__ANDROID__)
PrepareMapFile(ScopedFILE fp,ScopedFD readonly_fd)405 bool SharedMemory::PrepareMapFile(ScopedFILE fp, ScopedFD readonly_fd) {
406 DCHECK_EQ(-1, mapped_file_);
407 DCHECK_EQ(-1, readonly_mapped_file_);
408 if (fp == nullptr)
409 return false;
410
411 // This function theoretically can block on the disk, but realistically
412 // the temporary files we create will just go into the buffer cache
413 // and be deleted before they ever make it out to disk.
414 base::ThreadRestrictions::ScopedAllowIO allow_io;
415
416 struct stat st = {};
417 if (fstat(fileno(fp.get()), &st))
418 NOTREACHED();
419 if (readonly_fd.is_valid()) {
420 struct stat readonly_st = {};
421 if (fstat(readonly_fd.get(), &readonly_st))
422 NOTREACHED();
423 if (st.st_dev != readonly_st.st_dev || st.st_ino != readonly_st.st_ino) {
424 LOG(ERROR) << "writable and read-only inodes don't match; bailing";
425 return false;
426 }
427 }
428
429 mapped_file_ = HANDLE_EINTR(dup(fileno(fp.get())));
430 if (mapped_file_ == -1) {
431 if (errno == EMFILE) {
432 LOG(WARNING) << "Shared memory creation failed; out of file descriptors";
433 return false;
434 } else {
435 NOTREACHED() << "Call to dup failed, errno=" << errno;
436 }
437 }
438 readonly_mapped_file_ = readonly_fd.release();
439
440 return true;
441 }
442
443 // For the given shmem named |mem_name|, return a filename to mmap()
444 // (and possibly create). Modifies |filename|. Return false on
445 // error, or true of we are happy.
FilePathForMemoryName(const std::string & mem_name,FilePath * path)446 bool SharedMemory::FilePathForMemoryName(const std::string& mem_name,
447 FilePath* path) {
448 // mem_name will be used for a filename; make sure it doesn't
449 // contain anything which will confuse us.
450 DCHECK_EQ(std::string::npos, mem_name.find('/'));
451 DCHECK_EQ(std::string::npos, mem_name.find('\0'));
452
453 FilePath temp_dir;
454 if (!GetShmemTempDir(false, &temp_dir))
455 return false;
456
457 #if defined(GOOGLE_CHROME_BUILD)
458 std::string name_base = std::string("com.google.Chrome");
459 #else
460 std::string name_base = std::string("org.chromium.Chromium");
461 #endif
462 *path = temp_dir.AppendASCII(name_base + ".shmem." + mem_name);
463 return true;
464 }
465 #endif // !defined(OS_ANDROID) && !defined(__ANDROID__)
466
ShareToProcessCommon(ProcessHandle,SharedMemoryHandle * new_handle,bool close_self,ShareMode share_mode)467 bool SharedMemory::ShareToProcessCommon(ProcessHandle,
468 SharedMemoryHandle* new_handle,
469 bool close_self,
470 ShareMode share_mode) {
471 int handle_to_dup = -1;
472 switch(share_mode) {
473 case SHARE_CURRENT_MODE:
474 handle_to_dup = mapped_file_;
475 break;
476 case SHARE_READONLY:
477 // We could imagine re-opening the file from /dev/fd, but that can't make
478 // it readonly on Mac: https://codereview.chromium.org/27265002/#msg10
479 CHECK_GE(readonly_mapped_file_, 0);
480 handle_to_dup = readonly_mapped_file_;
481 break;
482 }
483
484 const int new_fd = HANDLE_EINTR(dup(handle_to_dup));
485 if (new_fd < 0) {
486 if (close_self) {
487 Unmap();
488 Close();
489 }
490 DPLOG(ERROR) << "dup() failed.";
491 return false;
492 }
493
494 new_handle->fd = new_fd;
495 new_handle->auto_close = true;
496
497 if (close_self) {
498 Unmap();
499 Close();
500 }
501
502 return true;
503 }
504
505 } // namespace base
506