summaryrefslogtreecommitdiffstats
path: root/eshld/link.esh
blob: 46268639892963cf9b3255b3811478b560961f43 (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
87
88
# 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 magic number (with interpreter path), entry point name, and
	# runtime library.
	if ${make_executable}; then
		printf '#!%s\n__entry=%s\n' "${interpreter}" "${entry_point}" \
			>&3
		cat "$(dirname "${0}")/../eshtrans/eshrt/eshrtbegin.sh2" >&3
	fi
}

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

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

link_end()
{
	# Add runtime library.
	if ${make_executable}; then
		cat "$(dirname "${0}")/../eshtrans/eshrt/eshrtend.sh2" >&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
}