1/*
2 * Copyright (C) 2015 The Android Open Source Project
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 *  * Redistributions of source code must retain the above copyright
9 *    notice, this list of conditions and the following disclaimer.
10 *  * Redistributions in binary form must reproduce the above copyright
11 *    notice, this list of conditions and the following disclaimer in
12 *    the documentation and/or other materials provided with the
13 *    distribution.
14 *
15 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
17 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
18 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
19 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
20 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
21 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
22 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
23 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
24 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
25 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26 * SUCH DAMAGE.
27 */
28
29#include <errno.h>
30#include <sys/mman.h>
31#include <stdarg.h>
32#include <stdint.h>
33#include <unistd.h>
34
35#include "private/bionic_macros.h"
36
37extern "C" void* ___mremap(void*, size_t, size_t, int, void*);
38
39void* mremap(void* old_address, size_t old_size, size_t new_size, int flags, ...) {
40  // prevent allocations large enough for `end - start` to overflow
41  size_t rounded = BIONIC_ALIGN(new_size, PAGE_SIZE);
42  if (rounded < new_size || rounded > PTRDIFF_MAX) {
43    errno = ENOMEM;
44    return MAP_FAILED;
45  }
46
47  void* new_address = nullptr;
48  // The optional argument is only valid if the MREMAP_FIXED flag is set,
49  // so we assume it's not present otherwise.
50  if ((flags & MREMAP_FIXED) != 0) {
51    va_list ap;
52    va_start(ap, flags);
53    new_address = va_arg(ap, void*);
54    va_end(ap);
55  }
56  return ___mremap(old_address, old_size, new_size, flags, new_address);
57}
58