1/* clone() implementation for Nios II.
2   Copyright (C) 2008-2022 Free Software Foundation, Inc.
3   This file is part of the GNU C Library.
4
5   The GNU C Library is free software; you can redistribute it and/or
6   modify it under the terms of the GNU Lesser General Public
7   License as published by the Free Software Foundation; either
8   version 2.1 of the License, or (at your option) any later version.
9
10   The GNU C Library is distributed in the hope that it will be useful,
11   but WITHOUT ANY WARRANTY; without even the implied warranty of
12   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13   Lesser General Public License for more details.
14
15   You should have received a copy of the GNU Lesser General Public
16   License along with the GNU C Library; if not, see
17   <https://www.gnu.org/licenses/>.  */
18
19/* clone() is even more special than fork() as it mucks with stacks
20   and invokes a function in the right context after its all over.  */
21
22#include <sysdep.h>
23#define _ERRNO_H	1
24#include <bits/errno.h>
25#include <tcb-offsets.h>
26
27/* int clone(int (*fn)(void *arg), void *child_stack, int flags, void *arg,
28	     void *parent_tidptr, void *tls, void *child_tidptr) */
29
30	.text
31ENTRY(__clone)
32	/* Sanity check arguments.  */
33	movi	r2, EINVAL
34	/* No NULL function pointers.  */
35	beq	r4, zero, SYSCALL_ERROR_LABEL
36	/* No NULL stack pointers.  */
37	beq	r5, zero, SYSCALL_ERROR_LABEL
38
39	subi	r5, r5, 8	/* Reserve argument save space.  */
40	stw	r4, 4(r5)	/* Save function pointer.  */
41	stw	r7, 0(r5)	/* Save argument pointer.  */
42
43	/* Load arguments.  */
44	mov	r4, r6
45	ldw	r6, 0(sp)
46	ldw	r7, 8(sp)
47	ldw	r8, 4(sp)
48
49	/* Do the system call.  */
50	movi	r2, SYS_ify (clone)
51
52	/* End FDE now, because in the child the unwind info will be
53	   wrong.  */
54	cfi_endproc
55	trap
56
57	/* Check for errors.  */
58	bne	r7, zero, SYSCALL_ERROR_LABEL
59	/* See if we're on the newly created thread.  */
60	beq	r2, zero, thread_start
61	/* Successful return from the parent */
62	ret
63
64thread_start:
65	cfi_startproc
66	cfi_undefined (ra)
67
68	ldw	r5, 4(sp)	/* Function pointer.  */
69	ldw	r4, 0(sp)	/* Argument pointer.  */
70	addi	sp, sp, 8
71
72        /* Call the user's function.  */
73	callr	r5
74
75	/* exit with the result.  */
76	movi	r2, SYS_ify (exit)
77	trap
78	cfi_endproc
79
80	cfi_startproc
81PSEUDO_END (__clone)
82libc_hidden_def (__clone)
83weak_alias (__clone, clone)
84