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 #include "base/memory/shared_memory.h"
11 #include <sys/types.h>
14 #include "base/file_util.h"
15 #include "base/lazy_instance.h"
16 #include "base/logging.h"
17 #include "base/process_util.h"
18 #include "base/safe_strerror_posix.h"
19 #include "base/strings/utf_string_conversions.h"
20 #include "base/synchronization/lock.h"
21 #include "base/threading/platform_thread.h"
22 #include "base/threading/thread_restrictions.h"
24 #if defined(OS_MACOSX)
25 #include "base/mac/foundation_util.h"
28 #if defined(OS_ANDROID)
29 #include "base/os_compat_android.h"
30 #include "third_party/ashmem/ashmem.h"
37 // Paranoia. Semaphores and shared memory segments should live in different
38 // namespaces, but who knows what's out there.
39 const char kSemaphoreSuffix
[] = "-sem";
41 LazyInstance
<Lock
>::Leaky g_thread_lock_
= LAZY_INSTANCE_INITIALIZER
;
45 SharedMemory::SharedMemory()
54 SharedMemory::SharedMemory(SharedMemoryHandle handle
, bool read_only
)
55 : mapped_file_(handle
.fd
),
59 read_only_(read_only
),
62 if (fstat(handle
.fd
, &st
) == 0) {
63 // If fstat fails, then the file descriptor is invalid and we'll learn this
64 // fact when Map() fails.
69 SharedMemory::SharedMemory(SharedMemoryHandle handle
, bool read_only
,
70 ProcessHandle process
)
71 : mapped_file_(handle
.fd
),
75 read_only_(read_only
),
77 // We don't handle this case yet (note the ignored parameter); let's die if
78 // someone comes calling.
82 SharedMemory::~SharedMemory() {
87 bool SharedMemory::IsHandleValid(const SharedMemoryHandle
& handle
) {
88 return handle
.fd
>= 0;
92 SharedMemoryHandle
SharedMemory::NULLHandle() {
93 return SharedMemoryHandle();
97 void SharedMemory::CloseHandle(const SharedMemoryHandle
& handle
) {
98 DCHECK_GE(handle
.fd
, 0);
99 if (HANDLE_EINTR(close(handle
.fd
)) < 0)
100 DPLOG(ERROR
) << "close";
104 size_t SharedMemory::GetHandleLimit() {
105 return base::GetMaxFds();
108 bool SharedMemory::CreateAndMapAnonymous(size_t size
) {
109 return CreateAnonymous(size
) && Map(size
);
112 #if !defined(OS_ANDROID)
113 // Chromium mostly only uses the unique/private shmem as specified by
114 // "name == L"". The exception is in the StatsTable.
115 // TODO(jrg): there is no way to "clean up" all unused named shmem if
116 // we restart from a crash. (That isn't a new problem, but it is a problem.)
117 // In case we want to delete it later, it may be useful to save the value
118 // of mem_filename after FilePathForMemoryName().
119 bool SharedMemory::Create(const SharedMemoryCreateOptions
& options
) {
120 DCHECK_EQ(-1, mapped_file_
);
121 if (options
.size
== 0) return false;
123 if (options
.size
> static_cast<size_t>(std::numeric_limits
<int>::max()))
126 // This function theoretically can block on the disk, but realistically
127 // the temporary files we create will just go into the buffer cache
128 // and be deleted before they ever make it out to disk.
129 base::ThreadRestrictions::ScopedAllowIO allow_io
;
132 bool fix_size
= true;
135 if (options
.name
== NULL
|| options
.name
->empty()) {
136 // It doesn't make sense to have a open-existing private piece of shmem
137 DCHECK(!options
.open_existing
);
138 // Q: Why not use the shm_open() etc. APIs?
139 // A: Because they're limited to 4mb on OS X. FFFFFFFUUUUUUUUUUU
140 fp
= file_util::CreateAndOpenTemporaryShmemFile(&path
, options
.executable
);
142 // Deleting the file prevents anyone else from mapping it in (making it
143 // private), and prevents the need for cleanup (once the last fd is closed,
144 // it is truly freed).
146 if (unlink(path
.value().c_str()))
147 PLOG(WARNING
) << "unlink";
150 if (!FilePathForMemoryName(*options
.name
, &path
))
153 // Make sure that the file is opened without any permission
154 // to other users on the system.
155 const mode_t kOwnerOnly
= S_IRUSR
| S_IWUSR
;
157 // First, try to create the file.
158 int fd
= HANDLE_EINTR(
159 open(path
.value().c_str(), O_RDWR
| O_CREAT
| O_EXCL
, kOwnerOnly
));
160 if (fd
== -1 && options
.open_existing
) {
161 // If this doesn't work, try and open an existing file in append mode.
162 // Opening an existing file in a world writable directory has two main
163 // security implications:
164 // - Attackers could plant a file under their control, so ownership of
165 // the file is checked below.
166 // - Attackers could plant a symbolic link so that an unexpected file
167 // is opened, so O_NOFOLLOW is passed to open().
169 open(path
.value().c_str(), O_RDWR
| O_APPEND
| O_NOFOLLOW
));
171 // Check that the current user owns the file.
172 // If uid != euid, then a more complex permission model is used and this
173 // API is not appropriate.
174 const uid_t real_uid
= getuid();
175 const uid_t effective_uid
= geteuid();
178 (fstat(fd
, &sb
) != 0 || sb
.st_uid
!= real_uid
||
179 sb
.st_uid
!= effective_uid
)) {
181 "Invalid owner when opening existing shared memory file.";
182 HANDLE_EINTR(close(fd
));
186 // An existing file was opened, so its size should not be fixed.
191 // "a+" is always appropriate: if it's a new file, a+ is similar to w+.
192 fp
= fdopen(fd
, "a+");
195 if (fp
&& fix_size
) {
198 if (fstat(fileno(fp
), &stat
) != 0) {
199 file_util::CloseFile(fp
);
202 const size_t current_size
= stat
.st_size
;
203 if (current_size
!= options
.size
) {
204 if (HANDLE_EINTR(ftruncate(fileno(fp
), options
.size
)) != 0) {
205 file_util::CloseFile(fp
);
209 requested_size_
= options
.size
;
212 #if !defined(OS_MACOSX)
213 PLOG(ERROR
) << "Creating shared memory in " << path
.value() << " failed";
214 FilePath dir
= path
.DirName();
215 if (access(dir
.value().c_str(), W_OK
| X_OK
) < 0) {
216 PLOG(ERROR
) << "Unable to access(W_OK|X_OK) " << dir
.value();
217 if (dir
.value() == "/dev/shm") {
218 LOG(FATAL
) << "This is frequently caused by incorrect permissions on "
219 << "/dev/shm. Try 'sudo chmod 1777 /dev/shm' to fix.";
223 PLOG(ERROR
) << "Creating shared memory in " << path
.value() << " failed";
228 return PrepareMapFile(fp
);
231 // Our current implementation of shmem is with mmap()ing of files.
232 // These files need to be deleted explicitly.
233 // In practice this call is only needed for unit tests.
234 bool SharedMemory::Delete(const std::string
& name
) {
236 if (!FilePathForMemoryName(name
, &path
))
239 if (file_util::PathExists(path
)) {
240 return base::Delete(path
, false);
243 // Doesn't exist, so success.
247 bool SharedMemory::Open(const std::string
& name
, bool read_only
) {
249 if (!FilePathForMemoryName(name
, &path
))
252 read_only_
= read_only
;
254 const char *mode
= read_only
? "r" : "r+";
255 FILE *fp
= file_util::OpenFile(path
, mode
);
256 return PrepareMapFile(fp
);
259 #endif // !defined(OS_ANDROID)
261 bool SharedMemory::MapAt(off_t offset
, size_t bytes
) {
262 if (mapped_file_
== -1)
265 if (bytes
> static_cast<size_t>(std::numeric_limits
<int>::max()))
268 #if defined(OS_ANDROID)
269 // On Android, Map can be called with a size and offset of zero to use the
270 // ashmem-determined size.
272 DCHECK_EQ(0, offset
);
273 int ashmem_bytes
= ashmem_get_size_region(mapped_file_
);
274 if (ashmem_bytes
< 0)
276 bytes
= ashmem_bytes
;
280 memory_
= mmap(NULL
, bytes
, PROT_READ
| (read_only_
? 0 : PROT_WRITE
),
281 MAP_SHARED
, mapped_file_
, offset
);
283 bool mmap_succeeded
= memory_
!= (void*)-1 && memory_
!= NULL
;
284 if (mmap_succeeded
) {
285 mapped_size_
= bytes
;
286 DCHECK_EQ(0U, reinterpret_cast<uintptr_t>(memory_
) &
287 (SharedMemory::MAP_MINIMUM_ALIGNMENT
- 1));
292 return mmap_succeeded
;
295 bool SharedMemory::Unmap() {
299 munmap(memory_
, mapped_size_
);
305 SharedMemoryHandle
SharedMemory::handle() const {
306 return FileDescriptor(mapped_file_
, false);
309 void SharedMemory::Close() {
312 if (mapped_file_
> 0) {
313 if (HANDLE_EINTR(close(mapped_file_
)) < 0)
314 PLOG(ERROR
) << "close";
319 void SharedMemory::Lock() {
320 g_thread_lock_
.Get().Acquire();
321 LockOrUnlockCommon(F_LOCK
);
324 void SharedMemory::Unlock() {
325 LockOrUnlockCommon(F_ULOCK
);
326 g_thread_lock_
.Get().Release();
329 #if !defined(OS_ANDROID)
330 bool SharedMemory::PrepareMapFile(FILE *fp
) {
331 DCHECK_EQ(-1, mapped_file_
);
332 if (fp
== NULL
) return false;
334 // This function theoretically can block on the disk, but realistically
335 // the temporary files we create will just go into the buffer cache
336 // and be deleted before they ever make it out to disk.
337 base::ThreadRestrictions::ScopedAllowIO allow_io
;
339 file_util::ScopedFILE
file_closer(fp
);
341 mapped_file_
= dup(fileno(fp
));
342 if (mapped_file_
== -1) {
343 if (errno
== EMFILE
) {
344 LOG(WARNING
) << "Shared memory creation failed; out of file descriptors";
347 NOTREACHED() << "Call to dup failed, errno=" << errno
;
352 if (fstat(mapped_file_
, &st
))
360 // For the given shmem named |mem_name|, return a filename to mmap()
361 // (and possibly create). Modifies |filename|. Return false on
362 // error, or true of we are happy.
363 bool SharedMemory::FilePathForMemoryName(const std::string
& mem_name
,
365 // mem_name will be used for a filename; make sure it doesn't
366 // contain anything which will confuse us.
367 DCHECK_EQ(std::string::npos
, mem_name
.find('/'));
368 DCHECK_EQ(std::string::npos
, mem_name
.find('\0'));
371 if (!file_util::GetShmemTempDir(&temp_dir
, false))
374 #if !defined(OS_MACOSX)
375 #if defined(GOOGLE_CHROME_BUILD)
376 std::string name_base
= std::string("com.google.Chrome");
378 std::string name_base
= std::string("org.chromium.Chromium");
381 std::string name_base
= std::string(base::mac::BaseBundleID());
383 *path
= temp_dir
.AppendASCII(name_base
+ ".shmem." + mem_name
);
387 void SharedMemory::LockOrUnlockCommon(int function
) {
388 DCHECK_GE(mapped_file_
, 0);
389 while (lockf(mapped_file_
, function
, 0) < 0) {
390 if (errno
== EINTR
) {
392 } else if (errno
== ENOLCK
) {
393 // temporary kernel resource exaustion
394 base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(500));
397 NOTREACHED() << "lockf() failed."
398 << " function:" << function
399 << " fd:" << mapped_file_
400 << " errno:" << errno
401 << " msg:" << safe_strerror(errno
);
406 bool SharedMemory::ShareToProcessCommon(ProcessHandle process
,
407 SharedMemoryHandle
*new_handle
,
409 const int new_fd
= dup(mapped_file_
);
411 DPLOG(ERROR
) << "dup() failed.";
415 new_handle
->fd
= new_fd
;
416 new_handle
->auto_close
= true;