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/shared_memory.h"
13 #include "base/file_util.h"
14 #include "base/lazy_instance.h"
15 #include "base/logging.h"
16 #include "base/threading/platform_thread.h"
17 #include "base/safe_strerror_posix.h"
18 #include "base/synchronization/lock.h"
19 #include "base/threading/thread_restrictions.h"
20 #include "base/utf_string_conversions.h"
22 #if defined(OS_MACOSX)
23 #include "base/mac/foundation_util.h"
26 #if defined(OS_ANDROID)
27 #include "base/os_compat_android.h"
28 #include "third_party/ashmem/ashmem.h"
35 // Paranoia. Semaphores and shared memory segments should live in different
36 // namespaces, but who knows what's out there.
37 const char kSemaphoreSuffix
[] = "-sem";
39 LazyInstance
<Lock
>::Leaky g_thread_lock_
= LAZY_INSTANCE_INITIALIZER
;
43 SharedMemory::SharedMemory()
52 SharedMemory::SharedMemory(SharedMemoryHandle handle
, bool read_only
)
53 : mapped_file_(handle
.fd
),
57 read_only_(read_only
),
60 if (fstat(handle
.fd
, &st
) == 0) {
61 // If fstat fails, then the file descriptor is invalid and we'll learn this
62 // fact when Map() fails.
67 SharedMemory::SharedMemory(SharedMemoryHandle handle
, bool read_only
,
68 ProcessHandle process
)
69 : mapped_file_(handle
.fd
),
73 read_only_(read_only
),
75 // We don't handle this case yet (note the ignored parameter); let's die if
76 // someone comes calling.
80 SharedMemory::~SharedMemory() {
85 bool SharedMemory::IsHandleValid(const SharedMemoryHandle
& handle
) {
86 return handle
.fd
>= 0;
90 SharedMemoryHandle
SharedMemory::NULLHandle() {
91 return SharedMemoryHandle();
95 void SharedMemory::CloseHandle(const SharedMemoryHandle
& handle
) {
96 DCHECK_GE(handle
.fd
, 0);
97 if (HANDLE_EINTR(close(handle
.fd
)) < 0)
98 DPLOG(ERROR
) << "close";
101 bool SharedMemory::CreateAndMapAnonymous(size_t size
) {
102 return CreateAnonymous(size
) && Map(size
);
105 #if !defined(OS_ANDROID)
106 // Chromium mostly only uses the unique/private shmem as specified by
107 // "name == L"". The exception is in the StatsTable.
108 // TODO(jrg): there is no way to "clean up" all unused named shmem if
109 // we restart from a crash. (That isn't a new problem, but it is a problem.)
110 // In case we want to delete it later, it may be useful to save the value
111 // of mem_filename after FilePathForMemoryName().
112 bool SharedMemory::Create(const SharedMemoryCreateOptions
& options
) {
113 DCHECK_EQ(-1, mapped_file_
);
114 if (options
.size
== 0) return false;
116 if (options
.size
> static_cast<size_t>(std::numeric_limits
<int>::max()))
119 // This function theoretically can block on the disk, but realistically
120 // the temporary files we create will just go into the buffer cache
121 // and be deleted before they ever make it out to disk.
122 base::ThreadRestrictions::ScopedAllowIO allow_io
;
125 bool fix_size
= true;
128 if (options
.name
== NULL
|| options
.name
->empty()) {
129 // It doesn't make sense to have a open-existing private piece of shmem
130 DCHECK(!options
.open_existing
);
131 // Q: Why not use the shm_open() etc. APIs?
132 // A: Because they're limited to 4mb on OS X. FFFFFFFUUUUUUUUUUU
133 fp
= file_util::CreateAndOpenTemporaryShmemFile(&path
, options
.executable
);
135 // Deleting the file prevents anyone else from mapping it in (making it
136 // private), and prevents the need for cleanup (once the last fd is closed,
137 // it is truly freed).
139 if (unlink(path
.value().c_str()))
140 PLOG(WARNING
) << "unlink";
143 if (!FilePathForMemoryName(*options
.name
, &path
))
146 fp
= file_util::OpenFile(path
, "w+x");
147 if (fp
== NULL
&& options
.open_existing
) {
148 // "w+" will truncate if it already exists.
149 fp
= file_util::OpenFile(path
, "a+");
153 if (fp
&& fix_size
) {
156 if (fstat(fileno(fp
), &stat
) != 0) {
157 file_util::CloseFile(fp
);
160 const size_t current_size
= stat
.st_size
;
161 if (current_size
!= options
.size
) {
162 if (HANDLE_EINTR(ftruncate(fileno(fp
), options
.size
)) != 0) {
163 file_util::CloseFile(fp
);
167 created_size_
= options
.size
;
170 #if !defined(OS_MACOSX)
171 PLOG(ERROR
) << "Creating shared memory in " << path
.value() << " failed";
172 FilePath dir
= path
.DirName();
173 if (access(dir
.value().c_str(), W_OK
| X_OK
) < 0) {
174 PLOG(ERROR
) << "Unable to access(W_OK|X_OK) " << dir
.value();
175 if (dir
.value() == "/dev/shm") {
176 LOG(FATAL
) << "This is frequently caused by incorrect permissions on "
177 << "/dev/shm. Try 'sudo chmod 1777 /dev/shm' to fix.";
181 PLOG(ERROR
) << "Creating shared memory in " << path
.value() << " failed";
186 return PrepareMapFile(fp
);
189 // Our current implementation of shmem is with mmap()ing of files.
190 // These files need to be deleted explicitly.
191 // In practice this call is only needed for unit tests.
192 bool SharedMemory::Delete(const std::string
& name
) {
194 if (!FilePathForMemoryName(name
, &path
))
197 if (file_util::PathExists(path
)) {
198 return file_util::Delete(path
, false);
201 // Doesn't exist, so success.
205 bool SharedMemory::Open(const std::string
& name
, bool read_only
) {
207 if (!FilePathForMemoryName(name
, &path
))
210 read_only_
= read_only
;
212 const char *mode
= read_only
? "r" : "r+";
213 FILE *fp
= file_util::OpenFile(path
, mode
);
214 return PrepareMapFile(fp
);
217 #endif // !defined(OS_ANDROID)
219 bool SharedMemory::MapAt(off_t offset
, size_t bytes
) {
220 if (mapped_file_
== -1)
223 if (bytes
> static_cast<size_t>(std::numeric_limits
<int>::max()))
226 #if defined(OS_ANDROID)
228 int ashmem_bytes
= ashmem_get_size_region(mapped_file_
);
229 if (ashmem_bytes
< 0)
232 DCHECK_GE(static_cast<uint32
>(ashmem_bytes
), bytes
);
233 // The caller wants to determine the map region size from ashmem.
234 bytes
= ashmem_bytes
- offset
;
235 // TODO(port): we set the created size here so that it is available in
236 // transport_dib_android.cc. We should use ashmem_get_size_region()
237 // in transport_dib_android.cc.
238 created_size_
= ashmem_bytes
;
242 memory_
= mmap(NULL
, bytes
, PROT_READ
| (read_only_
? 0 : PROT_WRITE
),
243 MAP_SHARED
, mapped_file_
, offset
);
245 bool mmap_succeeded
= memory_
!= (void*)-1 && memory_
!= NULL
;
246 if (mmap_succeeded
) {
247 mapped_size_
= bytes
;
248 DCHECK_EQ(0U, reinterpret_cast<uintptr_t>(memory_
) &
249 (SharedMemory::MAP_MINIMUM_ALIGNMENT
- 1));
254 return mmap_succeeded
;
257 bool SharedMemory::Unmap() {
261 munmap(memory_
, mapped_size_
);
267 SharedMemoryHandle
SharedMemory::handle() const {
268 return FileDescriptor(mapped_file_
, false);
271 void SharedMemory::Close() {
274 if (mapped_file_
> 0) {
275 if (HANDLE_EINTR(close(mapped_file_
)) < 0)
276 PLOG(ERROR
) << "close";
281 void SharedMemory::Lock() {
282 g_thread_lock_
.Get().Acquire();
283 LockOrUnlockCommon(F_LOCK
);
286 void SharedMemory::Unlock() {
287 LockOrUnlockCommon(F_ULOCK
);
288 g_thread_lock_
.Get().Release();
291 #if !defined(OS_ANDROID)
292 bool SharedMemory::PrepareMapFile(FILE *fp
) {
293 DCHECK_EQ(-1, mapped_file_
);
294 if (fp
== NULL
) return false;
296 // This function theoretically can block on the disk, but realistically
297 // the temporary files we create will just go into the buffer cache
298 // and be deleted before they ever make it out to disk.
299 base::ThreadRestrictions::ScopedAllowIO allow_io
;
301 file_util::ScopedFILE
file_closer(fp
);
303 mapped_file_
= dup(fileno(fp
));
304 if (mapped_file_
== -1) {
305 if (errno
== EMFILE
) {
306 LOG(WARNING
) << "Shared memory creation failed; out of file descriptors";
309 NOTREACHED() << "Call to dup failed, errno=" << errno
;
314 if (fstat(mapped_file_
, &st
))
322 // For the given shmem named |mem_name|, return a filename to mmap()
323 // (and possibly create). Modifies |filename|. Return false on
324 // error, or true of we are happy.
325 bool SharedMemory::FilePathForMemoryName(const std::string
& mem_name
,
327 // mem_name will be used for a filename; make sure it doesn't
328 // contain anything which will confuse us.
329 DCHECK_EQ(std::string::npos
, mem_name
.find('/'));
330 DCHECK_EQ(std::string::npos
, mem_name
.find('\0'));
333 if (!file_util::GetShmemTempDir(&temp_dir
, false))
336 #if !defined(OS_MACOSX)
337 #if defined(GOOGLE_CHROME_BUILD)
338 std::string name_base
= std::string("com.google.Chrome");
340 std::string name_base
= std::string("org.chromium.Chromium");
343 std::string name_base
= std::string(base::mac::BaseBundleID());
345 *path
= temp_dir
.AppendASCII(name_base
+ ".shmem." + mem_name
);
349 void SharedMemory::LockOrUnlockCommon(int function
) {
350 DCHECK_GE(mapped_file_
, 0);
351 while (lockf(mapped_file_
, function
, 0) < 0) {
352 if (errno
== EINTR
) {
354 } else if (errno
== ENOLCK
) {
355 // temporary kernel resource exaustion
356 base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(500));
359 NOTREACHED() << "lockf() failed."
360 << " function:" << function
361 << " fd:" << mapped_file_
362 << " errno:" << errno
363 << " msg:" << safe_strerror(errno
);
368 bool SharedMemory::ShareToProcessCommon(ProcessHandle process
,
369 SharedMemoryHandle
*new_handle
,
371 const int new_fd
= dup(mapped_file_
);
373 DPLOG(ERROR
) << "dup() failed.";
377 new_handle
->fd
= new_fd
;
378 new_handle
->auto_close
= true;