/*-1* SPDX-License-Identifier: BSD-2-Clause2*3* Copyright (c) 2018 Mark Johnston <[email protected]>4*5* Redistribution and use in source and binary forms, with or without6* modification, are permitted provided that the following conditions7* are met:8* 1. Redistributions of source code must retain the above copyright9* notice, this list of conditions and the following disclaimer.10* 2. Redistributions in binary form must reproduce the above copyright11* notice, this list of conditions and the following disclaimer in the12* documentation and/or other materials provided with the distribution.13*14* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND15* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE16* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE17* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE18* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL19* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS20* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)21* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT22* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY23* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF24* SUCH DAMAGE.25*/2627#include <sys/types.h>28#include <sys/syscall.h>29#include <errno.h>30#include <stdint.h>31#include <stdlib.h>3233void *__sys_break(char *nsize);3435static uintptr_t curbrk, minbrk;36static int curbrk_initted;3738static int39initbrk(void)40{41void *newbrk;4243if (!curbrk_initted) {44newbrk = __sys_break(NULL);45if (newbrk == (void *)-1)46return (-1);47curbrk = minbrk = (uintptr_t)newbrk;48curbrk_initted = 1;49}50return (0);51}5253static void *54mvbrk(void *addr)55{56uintptr_t oldbrk;5758if ((uintptr_t)addr < minbrk) {59/* Emulate legacy error handling in the syscall. */60errno = EINVAL;61return ((void *)-1);62}63if (__sys_break(addr) == (void *)-1)64return ((void *)-1);65oldbrk = curbrk;66curbrk = (uintptr_t)addr;67return ((void *)oldbrk);68}6970int71brk(const void *addr)72{7374if (initbrk() == -1)75return (-1);76if ((uintptr_t)addr < minbrk)77addr = (void *)minbrk;78return (mvbrk(__DECONST(void *, addr)) == (void *)-1 ? -1 : 0);79}8081int82_brk(const void *addr)83{8485if (initbrk() == -1)86return (-1);87return (mvbrk(__DECONST(void *, addr)) == (void *)-1 ? -1 : 0);88}8990void *91sbrk(intptr_t incr)92{9394if (initbrk() == -1)95return ((void *)-1);96if ((incr > 0 && curbrk + incr < curbrk) ||97(incr < 0 && curbrk + incr > curbrk)) {98/* Emulate legacy error handling in the syscall. */99errno = EINVAL;100return ((void *)-1);101}102return (mvbrk((void *)(curbrk + incr)));103}104105106