summaryrefslogtreecommitdiffstats
path: root/mojo/edk/embedder/simple_platform_shared_buffer_android.cc
blob: 97ec976012d552b022a26a89abc7dca37f4d08f9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "mojo/edk/embedder/simple_platform_shared_buffer.h"

#include <stddef.h>
#include <stdint.h>
#include <sys/mman.h>   // For |PROT_...|.
#include <sys/types.h>  // For |off_t|.
#include <limits>
#include <utility>

#include "base/files/scoped_file.h"
#include "base/logging.h"
#include "mojo/edk/embedder/platform_handle.h"
#include "third_party/ashmem/ashmem.h"

namespace mojo {
namespace edk {

// SimplePlatformSharedBuffer --------------------------------------------------

bool SimplePlatformSharedBuffer::Init() {
  DCHECK(!handle_.is_valid());

  if (static_cast<uint64_t>(num_bytes_) >
      static_cast<uint64_t>(std::numeric_limits<off_t>::max())) {
    return false;
  }

  base::ScopedFD fd(ashmem_create_region(nullptr, num_bytes_));
  if (!fd.is_valid()) {
    DPLOG(ERROR) << "ashmem_create_region()";
    return false;
  }

  if (ashmem_set_prot_region(fd.get(), PROT_READ | PROT_WRITE) < 0) {
    DPLOG(ERROR) << "ashmem_set_prot_region()";
    return false;
  }

  handle_.reset(PlatformHandle(fd.release()));
  return true;
}

bool SimplePlatformSharedBuffer::InitFromPlatformHandle(
    ScopedPlatformHandle platform_handle) {
  DCHECK(!handle_.is_valid());

  if (static_cast<uint64_t>(num_bytes_) >
      static_cast<uint64_t>(std::numeric_limits<off_t>::max())) {
    return false;
  }

  int size = ashmem_get_size_region(platform_handle.get().handle);

  if (size < 0) {
    DPLOG(ERROR) << "ashmem_get_size_region()";
    return false;
  }

  if (static_cast<size_t>(size) != num_bytes_) {
    LOG(ERROR) << "Shared memory region has the wrong size";
    return false;
  }

  handle_ = std::move(platform_handle);
  return true;
}

}  // namespace edk
}  // namespace mojo