Remove invocation of WebSettings::setFontRenderingNormal, which is a no-op.
[chromium-blink-merge.git] / base / memory / shared_memory_posix.cc
blob2be787d75331d708f9f125ba995f6c42b3691325
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"
7 #include <errno.h>
8 #include <fcntl.h>
9 #include <sys/mman.h>
10 #include <sys/stat.h>
11 #include <sys/types.h>
12 #include <unistd.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"
26 #endif // OS_MACOSX
28 #if defined(OS_ANDROID)
29 #include "base/os_compat_android.h"
30 #include "third_party/ashmem/ashmem.h"
31 #endif
33 namespace base {
35 namespace {
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()
46 : mapped_file_(-1),
47 inode_(0),
48 mapped_size_(0),
49 memory_(NULL),
50 read_only_(false),
51 requested_size_(0) {
54 SharedMemory::SharedMemory(SharedMemoryHandle handle, bool read_only)
55 : mapped_file_(handle.fd),
56 inode_(0),
57 mapped_size_(0),
58 memory_(NULL),
59 read_only_(read_only),
60 requested_size_(0) {
61 struct stat st;
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.
65 inode_ = st.st_ino;
69 SharedMemory::SharedMemory(SharedMemoryHandle handle, bool read_only,
70 ProcessHandle process)
71 : mapped_file_(handle.fd),
72 inode_(0),
73 mapped_size_(0),
74 memory_(NULL),
75 read_only_(read_only),
76 requested_size_(0) {
77 // We don't handle this case yet (note the ignored parameter); let's die if
78 // someone comes calling.
79 NOTREACHED();
82 SharedMemory::~SharedMemory() {
83 Close();
86 // static
87 bool SharedMemory::IsHandleValid(const SharedMemoryHandle& handle) {
88 return handle.fd >= 0;
91 // static
92 SharedMemoryHandle SharedMemory::NULLHandle() {
93 return SharedMemoryHandle();
96 // static
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";
103 // static
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()))
124 return false;
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;
131 FILE *fp;
132 bool fix_size = true;
134 FilePath path;
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).
145 if (fp) {
146 if (unlink(path.value().c_str()))
147 PLOG(WARNING) << "unlink";
149 } else {
150 if (!FilePathForMemoryName(*options.name, &path))
151 return false;
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().
168 fd = HANDLE_EINTR(
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();
176 struct stat sb;
177 if (fd >= 0 &&
178 (fstat(fd, &sb) != 0 || sb.st_uid != real_uid ||
179 sb.st_uid != effective_uid)) {
180 LOG(ERROR) <<
181 "Invalid owner when opening existing shared memory file.";
182 HANDLE_EINTR(close(fd));
183 return false;
186 // An existing file was opened, so its size should not be fixed.
187 fix_size = false;
189 fp = NULL;
190 if (fd >= 0) {
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) {
196 // Get current size.
197 struct stat stat;
198 if (fstat(fileno(fp), &stat) != 0) {
199 file_util::CloseFile(fp);
200 return false;
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);
206 return false;
209 requested_size_ = options.size;
211 if (fp == NULL) {
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.";
222 #else
223 PLOG(ERROR) << "Creating shared memory in " << path.value() << " failed";
224 #endif
225 return false;
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) {
235 FilePath path;
236 if (!FilePathForMemoryName(name, &path))
237 return false;
239 if (file_util::PathExists(path)) {
240 return base::Delete(path, false);
243 // Doesn't exist, so success.
244 return true;
247 bool SharedMemory::Open(const std::string& name, bool read_only) {
248 FilePath path;
249 if (!FilePathForMemoryName(name, &path))
250 return false;
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)
263 return false;
265 if (bytes > static_cast<size_t>(std::numeric_limits<int>::max()))
266 return false;
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.
271 if (bytes == 0) {
272 DCHECK_EQ(0, offset);
273 int ashmem_bytes = ashmem_get_size_region(mapped_file_);
274 if (ashmem_bytes < 0)
275 return false;
276 bytes = ashmem_bytes;
278 #endif
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));
288 } else {
289 memory_ = NULL;
292 return mmap_succeeded;
295 bool SharedMemory::Unmap() {
296 if (memory_ == NULL)
297 return false;
299 munmap(memory_, mapped_size_);
300 memory_ = NULL;
301 mapped_size_ = 0;
302 return true;
305 SharedMemoryHandle SharedMemory::handle() const {
306 return FileDescriptor(mapped_file_, false);
309 void SharedMemory::Close() {
310 Unmap();
312 if (mapped_file_ > 0) {
313 if (HANDLE_EINTR(close(mapped_file_)) < 0)
314 PLOG(ERROR) << "close";
315 mapped_file_ = -1;
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";
345 return false;
346 } else {
347 NOTREACHED() << "Call to dup failed, errno=" << errno;
351 struct stat st;
352 if (fstat(mapped_file_, &st))
353 NOTREACHED();
354 inode_ = st.st_ino;
356 return true;
358 #endif
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,
364 FilePath* path) {
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'));
370 FilePath temp_dir;
371 if (!file_util::GetShmemTempDir(&temp_dir, false))
372 return false;
374 #if !defined(OS_MACOSX)
375 #if defined(GOOGLE_CHROME_BUILD)
376 std::string name_base = std::string("com.google.Chrome");
377 #else
378 std::string name_base = std::string("org.chromium.Chromium");
379 #endif
380 #else // OS_MACOSX
381 std::string name_base = std::string(base::mac::BaseBundleID());
382 #endif // OS_MACOSX
383 *path = temp_dir.AppendASCII(name_base + ".shmem." + mem_name);
384 return true;
387 void SharedMemory::LockOrUnlockCommon(int function) {
388 DCHECK_GE(mapped_file_, 0);
389 while (lockf(mapped_file_, function, 0) < 0) {
390 if (errno == EINTR) {
391 continue;
392 } else if (errno == ENOLCK) {
393 // temporary kernel resource exaustion
394 base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(500));
395 continue;
396 } else {
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,
408 bool close_self) {
409 const int new_fd = dup(mapped_file_);
410 if (new_fd < 0) {
411 DPLOG(ERROR) << "dup() failed.";
412 return false;
415 new_handle->fd = new_fd;
416 new_handle->auto_close = true;
418 if (close_self)
419 Close();
421 return true;
424 } // namespace base