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	arch="$1"
21
22	header="$toolsdir/arch/$arch/include/uapi/asm/errno.h"
23	if test -r "$header"; then
24		echo "$header"
25	else
26		echo "$toolsdir/include/uapi/asm-generic/errno.h"
27	fi
28}
29
30create_errno_lookup_func()
31{
32	arch=$(arch_string "$1")
33
34	printf "static const char *errno_to_name__%s(int err)\n{\n\tswitch (err) {\n" $arch
35
36	while read name nr; do
37		printf '\tcase %d: return "%s";\n' $nr $name
38	done
39
40	printf '\tdefault: return "(unknown)";\n\t}\n}\n'
41}
42
43process_arch()
44{
45	arch="$1"
46	asm_errno=$(asm_errno_file "$arch")
47
48	$gcc $CFLAGS $include_path -E -dM -x c $asm_errno \
49		|grep -hE '^#define[[:blank:]]+(E[^[:blank:]]+)[[:blank:]]+([[:digit:]]+).*' \
50		|awk '{ print $2","$3; }' \
51		|sort -t, -k2 -nu \
52		|IFS=, create_errno_lookup_func "$arch"
53}
54
55create_arch_errno_table_func()
56{
57	archlist="$1"
58	default="$2"
59
60	printf 'const char *arch_syscalls__strerrno(const char *arch, int err)\n'
61	printf '{\n'
62	for arch in $archlist; do
63		printf '\tif (!strcmp(arch, "%s"))\n' $(arch_string "$arch")
64		printf '\t\treturn errno_to_name__%s(err);\n' $(arch_string "$arch")
65	done
66	printf '\treturn errno_to_name__%s(err);\n' $(arch_string "$default")
67	printf '}\n'
68}
69
70cat <<EoHEADER
71/* SPDX-License-Identifier: GPL-2.0 */
72
73#include <string.h>
74
75EoHEADER
76
77# Create list of architectures that have a specific errno.h.
78archlist=""
79for arch in $(find $toolsdir/arch -maxdepth 1 -mindepth 1 -type d -printf "%f\n" | sort -r); do
80	test -f $toolsdir/arch/$arch/include/uapi/asm/errno.h && archlist="$archlist $arch"
81done
82
83for arch in generic $archlist; do
84	process_arch "$arch"
85done
86create_arch_errno_table_func "$archlist" "generic"
87