summaryrefslogtreecommitdiffstats
path: root/eshld/link.esh
blob: f2ad486c8c617fc0211dcfff312571b47b261ced (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# Linking functions
#
# Copyright (C) 2015, 2016  Patrick "P. J." McDermott
#
# This file is part of the Eggshell Linker.
#
# The Eggshell Linker is free software: you can redistribute it
# and/or modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation, either version 3 of
# the License, or (at your option) any later version.
#
# The Eggshell Linker is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty
# of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with the Eggshell Linker  If not, see
# <http://www.gnu.org/licenses/>.

interpreter=
entry_point=
output=
make_executable=

die()
{
	local fmt="${1}"
	shift 1

	printf "eshld: ${fmt}\n" "${@}" >&2
	exit 2
}

link_begin()
{
	local interp="${1}"
	local entry="${2}"
	local out="${3}"
	local mkexec="${4}"
	shift 4

	interpreter="${interp}"
	entry_point="${entry}"
	output="${out}"
	make_executable=${mkexec}

	# Open output file.
	if ! exec 3>"${output}~"; then
		die 'Cannot open file "%s"' "${output}~"
	fi

	# Add a magic number with interpreter path and the runtime library.
	if ${make_executable}; then
		printf '#!%s\n' "${interpreter}" >&3
		eshrtbegin >&3
	fi
}

link_file()
{
	local input="${1}"

	if ! cat "${input}" >&3; then
		die 'Cannot read file "%s"' "${input}"
	fi
}

link_end()
{
	# Add calls to __init functions and the entry point.
	if ${make_executable}; then
		eshrtend "${entry_point}" >&3
	fi

	# Close output file, make it executable, and set its name.
	exec 3>&-
	if ${make_executable}; then
		if ! chmod a+x "${output}~"; then
			die 'Cannot set mode of file "%s"' "${output}~"
		fi
	fi
	if ! mv "${output}~" "${output}"; then
		die 'Cannot rename file to "%s"' "${output}"
	fi
}