• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright (c) 2011 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 <stddef.h>
8 #include <sys/mman.h>
9 
10 #include "base/logging.h"
11 
12 #if defined(__ANDROID__)
13 #include <cutils/ashmem.h>
14 #else
15 #include "third_party/ashmem/ashmem.h"
16 #endif
17 
18 namespace base {
19 
20 // For Android, we use ashmem to implement SharedMemory. ashmem_create_region
21 // will automatically pin the region. We never explicitly call pin/unpin. When
22 // all the file descriptors from different processes associated with the region
23 // are closed, the memory buffer will go away.
24 
Create(const SharedMemoryCreateOptions & options)25 bool SharedMemory::Create(const SharedMemoryCreateOptions& options) {
26   DCHECK_EQ(-1, mapped_file_ );
27 
28   if (options.size > static_cast<size_t>(std::numeric_limits<int>::max()))
29     return false;
30 
31   // "name" is just a label in ashmem. It is visible in /proc/pid/maps.
32   mapped_file_ = ashmem_create_region(
33       options.name_deprecated == NULL ? "" : options.name_deprecated->c_str(),
34       options.size);
35   if (-1 == mapped_file_) {
36     DLOG(ERROR) << "Shared memory creation failed";
37     return false;
38   }
39 
40   int err = ashmem_set_prot_region(mapped_file_,
41                                    PROT_READ | PROT_WRITE | PROT_EXEC);
42   if (err < 0) {
43     DLOG(ERROR) << "Error " << err << " when setting protection of ashmem";
44     return false;
45   }
46 
47   // Android doesn't appear to have a way to drop write access on an ashmem
48   // segment for a single descriptor.  http://crbug.com/320865
49   readonly_mapped_file_ = dup(mapped_file_);
50   if (-1 == readonly_mapped_file_) {
51     DPLOG(ERROR) << "dup() failed";
52     return false;
53   }
54 
55   requested_size_ = options.size;
56 
57   return true;
58 }
59 
Delete(const std::string &)60 bool SharedMemory::Delete(const std::string&) {
61   // Like on Windows, this is intentionally returning true as ashmem will
62   // automatically releases the resource when all FDs on it are closed.
63   return true;
64 }
65 
Open(const std::string &,bool)66 bool SharedMemory::Open(const std::string&, bool /*read_only*/) {
67   // ashmem doesn't support name mapping
68   NOTIMPLEMENTED();
69   return false;
70 }
71 
72 }  // namespace base
73