(root)/
strace-6.5/
tests/
tail_alloc.c
       1  /*
       2   * Copyright (c) 2015-2021 Dmitry V. Levin <ldv@strace.io>
       3   * All rights reserved.
       4   *
       5   * SPDX-License-Identifier: GPL-2.0-or-later
       6   */
       7  
       8  #include "tests.h"
       9  #include <string.h>
      10  #include <sys/mman.h>
      11  
      12  void *
      13  tail_alloc(const size_t size)
      14  {
      15  	const size_t page_size = get_page_size();
      16  	const size_t len = (size + page_size - 1) & -page_size;
      17  	const size_t alloc_size = len + 6 * page_size;
      18  
      19  	void *p = mmap(NULL, alloc_size, PROT_READ | PROT_WRITE,
      20  		       MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
      21  	if (MAP_FAILED == p)
      22  		perror_msg_and_fail("mmap(%zu)", alloc_size);
      23  
      24  	void *start_work = p + 3 * page_size;
      25  	void *tail_guard = start_work + len;
      26  
      27  	if (munmap(p, page_size) ||
      28  	    munmap(p + 2 * page_size, page_size) ||
      29  	    munmap(tail_guard, page_size) ||
      30  	    munmap(tail_guard + 2 * page_size, page_size))
      31  		perror_msg_and_fail("munmap");
      32  
      33  	memset(start_work, 0xff, len);
      34  	return tail_guard - size;
      35  }
      36  
      37  void *
      38  tail_memdup(const void *p, const size_t size)
      39  {
      40  	void *dest = tail_alloc(size);
      41  	memcpy(dest, p, size);
      42  	return dest;
      43  }