/* $NetBSD: makecontext.c,v 1.2 2003/01/18 11:06:24 thorpej Exp $ */12/*-3* SPDX-License-Identifier: BSD-2-Clause4*5* Copyright (c) 2001 The NetBSD Foundation, Inc.6* All rights reserved.7*8* This code is derived from software contributed to The NetBSD Foundation9* by Klaus Klein.10*11* Redistribution and use in source and binary forms, with or without12* modification, are permitted provided that the following conditions13* are met:14* 1. Redistributions of source code must retain the above copyright15* notice, this list of conditions and the following disclaimer.16* 2. Redistributions in binary form must reproduce the above copyright17* notice, this list of conditions and the following disclaimer in the18* documentation and/or other materials provided with the distribution.19*20* THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS21* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED22* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR23* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS24* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR25* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF26* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS27* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN28* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)29* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE30* POSSIBILITY OF SUCH DAMAGE.31*/3233#include <stdlib.h>34#include <stddef.h>35#include <inttypes.h>36#include <ucontext.h>3738#include <stdarg.h>3940extern void _ctx_start(void);4142void43ctx_done(ucontext_t *ucp)44{4546if (ucp->uc_link == NULL)47exit(0);48else {49setcontext((const ucontext_t *)ucp->uc_link);50abort();51}52}5354__weak_reference(__makecontext, makecontext);5556void57__makecontext(ucontext_t *ucp, void (*func)(void), int argc, ...)58{59__greg_t *gr = ucp->uc_mcontext.__gregs;60int i;61unsigned int *sp;62va_list ap;6364/* Compute and align stack pointer. */65sp = (unsigned int *)66(((uintptr_t)ucp->uc_stack.ss_sp + ucp->uc_stack.ss_size -67sizeof(double)) & ~7);68/* Allocate necessary stack space for arguments exceeding r0-3. */69if (argc > 4)70sp -= argc - 4;71gr[_REG_SP] = (__greg_t)sp;72/* Wipe out frame pointer. */73gr[_REG_FP] = 0;74/* Arrange for return via the trampoline code. */75gr[_REG_PC] = (__greg_t)_ctx_start;76gr[_REG_R4] = (__greg_t)func;77gr[_REG_R5] = (__greg_t)ucp;7879va_start(ap, argc);80/* Pass up to four arguments in r0-3. */81for (i = 0; i < argc && i < 4; i++)82gr[_REG_R0 + i] = va_arg(ap, int);83/* Pass any additional arguments on the stack. */84for (argc -= i; argc > 0; argc--)85*sp++ = va_arg(ap, int);86va_end(ap);87}888990