Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(8)

Side by Side Diff: base/memory/shared_memory_posix.cc

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

Powered by Google App Engine
This is Rietveld 408576698