1/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#ifndef _PRIVATE_WRITEPROTECTED_H
18#define _PRIVATE_WRITEPROTECTED_H
19
20#include <errno.h>
21#include <string.h>
22#include <sys/cdefs.h>
23#include <sys/mman.h>
24#include <sys/user.h>
25
26#include "private/bionic_macros.h"
27#include "private/bionic_prctl.h"
28#include "private/libc_logging.h"
29
30template <typename T>
31union WriteProtectedContents {
32  T value;
33  char padding[PAGE_SIZE];
34
35  WriteProtectedContents() = default;
36  DISALLOW_COPY_AND_ASSIGN(WriteProtectedContents);
37} __attribute__((aligned(PAGE_SIZE)));
38
39// Write protected wrapper class that aligns its contents to a page boundary,
40// and sets the memory protection to be non-writable, except when being modified
41// explicitly.
42template <typename T>
43class WriteProtected {
44  static_assert(sizeof(T) < PAGE_SIZE,
45                "WriteProtected only supports contents up to PAGE_SIZE");
46  static_assert(__is_pod(T), "WriteProtected only supports POD contents");
47
48  WriteProtectedContents<T> contents;
49
50 public:
51  WriteProtected() = default;
52  DISALLOW_COPY_AND_ASSIGN(WriteProtected);
53
54  void initialize() {
55    // Not strictly necessary, but this will hopefully segfault if we initialize
56    // multiple times by accident.
57    memset(&contents, 0, sizeof(contents));
58
59    if (mprotect(&contents, PAGE_SIZE, PROT_READ)) {
60      __libc_fatal("failed to make WriteProtected nonwritable in initialize");
61    }
62  }
63
64  const T* operator->() {
65    return &contents.value;
66  }
67
68  const T& operator*() {
69    return contents.value;
70  }
71
72  template <typename Mutator>
73  void mutate(Mutator mutator) {
74    if (mprotect(&contents, PAGE_SIZE, PROT_READ | PROT_WRITE) != 0) {
75      __libc_fatal("failed to make WriteProtected writable in mutate: %s",
76                   strerror(errno));
77    }
78    mutator(&contents.value);
79    if (mprotect(&contents, PAGE_SIZE, PROT_READ) != 0) {
80      __libc_fatal("failed to make WriteProtected nonwritable in mutate: %s",
81                   strerror(errno));
82    }
83  }
84};
85
86#endif
87