1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7 #include <android/log.h>
11 #include <sys/ioctl.h>
14 #include <sys/types.h>
17 #include "base/process_util.h"
19 #include "SharedMemoryBasic.h"
21 #include "mozilla/Ashmem.h"
26 static void LogError(const char* what
) {
27 __android_log_print(ANDROID_LOG_ERROR
, "Gecko", "%s: %s (%d)", what
,
28 strerror(errno
), errno
);
31 SharedMemoryBasic::SharedMemoryBasic()
32 : mShmFd(-1), mMemory(nullptr), mOpenRights(RightsReadWrite
) {}
34 SharedMemoryBasic::~SharedMemoryBasic() {
39 bool SharedMemoryBasic::SetHandle(Handle aHandle
, OpenRights aRights
) {
40 MOZ_ASSERT(-1 == mShmFd
, "Already Create()d");
41 mShmFd
= aHandle
.release();
42 mOpenRights
= aRights
;
46 bool SharedMemoryBasic::Create(size_t aNbytes
) {
47 MOZ_ASSERT(-1 == mShmFd
, "Already Create()d");
49 // Carve a new instance off of /dev/ashmem
50 int shmfd
= mozilla::android::ashmem_create(nullptr, aNbytes
);
52 LogError("ShmemAndroid::Create():open");
61 bool SharedMemoryBasic::Map(size_t nBytes
, void* fixed_address
) {
62 MOZ_ASSERT(nullptr == mMemory
, "Already Map()d");
65 if (mOpenRights
== RightsReadWrite
) {
69 // Don't use MAP_FIXED when a fixed_address was specified, since that can
70 // replace pages that are alread mapped at that address.
71 mMemory
= mmap(fixed_address
, nBytes
, prot
, MAP_SHARED
, mShmFd
, 0);
73 if (MAP_FAILED
== mMemory
) {
75 LogError("ShmemAndroid::Map()");
81 if (fixed_address
&& mMemory
!= fixed_address
) {
82 if (munmap(mMemory
, nBytes
)) {
83 LogError("ShmemAndroid::Map():unmap");
93 void* SharedMemoryBasic::FindFreeAddressSpace(size_t size
) {
95 mmap(NULL
, size
, PROT_NONE
, MAP_PRIVATE
| MAP_ANONYMOUS
, -1, 0);
97 return memory
!= (void*)-1 ? memory
: NULL
;
100 auto SharedMemoryBasic::CloneHandle() -> Handle
{
101 MOZ_ASSERT(mShmFd
>= 0, "Should have been Create()d by now");
103 int shmfdDup
= dup(mShmFd
);
104 if (-1 == shmfdDup
) {
105 LogError("ShmemAndroid::CloneHandle()");
109 return mozilla::UniqueFileHandle(shmfdDup
);
112 void SharedMemoryBasic::Unmap() {
117 if (munmap(mMemory
, Size())) {
118 LogError("ShmemAndroid::Unmap()");
123 void SharedMemoryBasic::CloseHandle() {
127 mOpenRights
= RightsReadWrite
;
132 } // namespace mozilla