xref: /freebsd/lib/libc/aarch64/gen/makecontext.c (revision 3810b37903220af1a369d3c4032ae25fb2d7949d)
1 /*-
2  * Copyright (c) 2015 The FreeBSD Foundation
3  *
4  * This software was developed by Andrew Turner under
5  * sponsorship from the FreeBSD Foundation.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  */
28 
29 #include <sys/cdefs.h>
30 __FBSDID("$FreeBSD$");
31 
32 #include <sys/param.h>
33 
34 #include <machine/armreg.h>
35 
36 #include <inttypes.h>
37 #include <stdarg.h>
38 #include <stdlib.h>
39 #include <ucontext.h>
40 
41 void _ctx_start(void);
42 
43 void
44 ctx_done(ucontext_t *ucp)
45 {
46 
47 	if (ucp->uc_link == NULL) {
48 		exit(0);
49 	} else {
50 		setcontext((const ucontext_t *)ucp->uc_link);
51 		abort();
52 	}
53 }
54 
55 __weak_reference(__makecontext, makecontext);
56 
57 void
58 __makecontext(ucontext_t *ucp, void (*func)(void), int argc, ...)
59 {
60 	struct gpregs *gp;
61 	va_list ap;
62 	int i;
63 
64 	/* A valid context is required. */
65 	if (ucp == NULL)
66 		return;
67 
68 	if ((argc < 0) || (argc > 8))
69 		return;
70 
71 	gp = &ucp->uc_mcontext.mc_gpregs;
72 
73 	va_start(ap, argc);
74 	/* Pass up to eight arguments in x0-7. */
75 	for (i = 0; i < argc && i < 8; i++)
76 		gp->gp_x[i] = va_arg(ap, uint64_t);
77 	va_end(ap);
78 
79 	/* Set the stack */
80 	gp->gp_sp = STACKALIGN(ucp->uc_stack.ss_sp + ucp->uc_stack.ss_size);
81 	/* Arrange for return via the trampoline code. */
82 	gp->gp_elr = (__register_t)_ctx_start;
83 	gp->gp_x[19] = (__register_t)func;
84 	gp->gp_x[20] = (__register_t)ucp;
85 }
86