1#!/bin/sh
2# SPDX-License-Identifier: GPL-2.0
3#
4# Generate C file mapping errno codes to errno names.
5#
6# Copyright IBM Corp. 2018
7# Author(s):  Hendrik Brueckner <brueckner@linux.vnet.ibm.com>
8
9gcc="$1"
10toolsdir="$2"
11include_path="-I$toolsdir/include/uapi"
12
13arch_string()
14{
15	echo "$1" |sed -e 'y/- /__/' |tr '[[:upper:]]' '[[:lower:]]'
16}
17
18asm_errno_file()
19{
20	local arch="$1"
21	local header
22
23	header="$toolsdir/arch/$arch/include/uapi/asm/errno.h"
24	if test -r "$header"; then
25		echo "$header"
26	else
27		echo "$toolsdir/include/uapi/asm-generic/errno.h"
28	fi
29}
30
31create_errno_lookup_func()
32{
33	local arch=$(arch_string "$1")
34	local nr name
35
36	printf "static const char *errno_to_name__%s(int err)\n{\n\tswitch (err) {\n" $arch
37
38	while read name nr; do
39		printf '\tcase %d: return "%s";\n' $nr $name
40	done
41
42	printf '\tdefault: return "(unknown)";\n\t}\n}\n'
43}
44
45process_arch()
46{
47	local arch="$1"
48	local asm_errno=$(asm_errno_file "$arch")
49
50	$gcc $CFLAGS $include_path -E -dM -x c $asm_errno \
51		|grep -hE '^#define[[:blank:]]+(E[^[:blank:]]+)[[:blank:]]+([[:digit:]]+).*' \
52		|awk '{ print $2","$3; }' \
53		|sort -t, -k2 -nu \
54		|IFS=, create_errno_lookup_func "$arch"
55}
56
57create_arch_errno_table_func()
58{
59	local archlist="$1"
60	local default="$2"
61	local arch
62
63	printf 'const char *arch_syscalls__strerrno(const char *arch, int err)\n'
64	printf '{\n'
65	for arch in $archlist; do
66		printf '\tif (!strcmp(arch, "%s"))\n' $(arch_string "$arch")
67		printf '\t\treturn errno_to_name__%s(err);\n' $(arch_string "$arch")
68	done
69	printf '\treturn errno_to_name__%s(err);\n' $(arch_string "$default")
70	printf '}\n'
71}
72
73cat <<EoHEADER
74/* SPDX-License-Identifier: GPL-2.0 */
75
76#include <string.h>
77
78EoHEADER
79
80# Create list of architectures that have a specific errno.h.
81archlist=""
82for arch in $(find $toolsdir/arch -maxdepth 1 -mindepth 1 -type d -printf "%f\n" | sort -r); do
83	test -f $toolsdir/arch/$arch/include/uapi/asm/errno.h && archlist="$archlist $arch"
84done
85
86for arch in generic $archlist; do
87	process_arch "$arch"
88done
89create_arch_errno_table_func "$archlist" "generic"
90