sim: sh: switch syscalls to common nltvals
[binutils-gdb.git] / sim / common / gennltvals.py
1 #!/usr/bin/env python3
2 # Copyright (C) 1996-2021 Free Software Foundation, Inc.
3 #
4 # This file is part of the GNU simulators.
5 #
6 # This program is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 3 of the License, or
9 # (at your option) any later version.
10 #
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with this program. If not, see <http://www.gnu.org/licenses/>.
18
19 """Helper to generate nltvals.def.
20
21 nltvals.def is a file that describes various newlib/libgloss target values used
22 by the host/target interface. This needs to be rerun whenever the newlib source
23 changes. Developers manually run it.
24
25 If the path to newlib is not specified, it will be searched for in:
26 - the root of this source tree
27 - alongside this source tree
28 """
29
30 import argparse
31 from pathlib import Path
32 import re
33 import subprocess
34 import sys
35 from typing import Iterable, List, TextIO
36
37
38 PROG = Path(__file__).name
39
40 # Unfortunately, each newlib/libgloss port has seen fit to define their own
41 # syscall.h file. This means that system call numbers can vary for each port.
42 # Support for all this crud is kept here, rather than trying to get too fancy.
43 # If you want to try to improve this, please do, but don't break anything.
44 # Note that there is a standard syscall.h file (libgloss/syscall.h) now which
45 # hopefully more targets can use.
46 #
47 # NB: New ports should use libgloss, not newlib.
48 TARGET_DIRS = {
49 'cr16': 'libgloss/cr16/sys',
50 'd10v': 'newlib/libc/sys/d10v/sys',
51 'i960': 'libgloss/i960',
52 'mcore': 'libgloss/mcore',
53 'riscv': 'libgloss/riscv/machine',
54 'sh': 'newlib/libc/sys/sh/sys',
55 'v850': 'libgloss/v850/sys',
56 }
57 TARGETS = {
58 'bfin',
59 'cr16',
60 'd10v',
61 'fr30',
62 'frv',
63 'i960',
64 'iq2000',
65 'lm32',
66 'm32c',
67 'm32r',
68 'mcore',
69 'mn10200',
70 'mn10300',
71 'msp430',
72 'pru',
73 'riscv',
74 'rx',
75 'sh',
76 'sparc',
77 'v850',
78 }
79
80 # Make sure TARGET_DIRS doesn't gain any typos.
81 assert not set(TARGET_DIRS) - TARGETS
82
83 # The header for the generated def file.
84 FILE_HEADER = f"""\
85 /* Newlib/libgloss macro values needed by remote target support. */
86 /* This file is machine generated by {PROG}. */\
87 """
88
89
90 def gentvals(output: TextIO, cpp: str, srctype: str, srcdir: Path,
91 headers: Iterable[str],
92 pattern: str,
93 target: str = None):
94 """Extract constants from the specified files using a regular expression.
95
96 We'll run things through the preprocessor.
97 """
98 headers = tuple(headers)
99
100 # Require all files exist in order to regenerate properly.
101 for header in headers:
102 fullpath = srcdir / header
103 assert fullpath.exists(), f'{fullpath} does not exist'
104
105 if target is None:
106 print(f'#ifdef {srctype}_defs', file=output)
107 else:
108 print(f'#ifdef NL_TARGET_{target}', file=output)
109 print(f'#ifdef {srctype}_defs', file=output)
110
111 print('\n'.join(f'/* from {x} */' for x in headers), file=output)
112
113 if target is None:
114 print(f'/* begin {srctype} target macros */', file=output)
115 else:
116 print(f'/* begin {target} {srctype} target macros */', file=output)
117
118 # Extract all the symbols.
119 srcfile = ''.join(f'#include <{x}>\n' for x in headers)
120 syms = set()
121 define_pattern = re.compile(r'^#\s*define\s+(' + pattern + ')')
122 for header in headers:
123 with open(srcdir / header, 'r', encoding='utf-8') as fp:
124 data = fp.read()
125 for line in data.splitlines():
126 m = define_pattern.match(line)
127 if m:
128 syms.add(m.group(1))
129 for sym in sorted(syms):
130 srcfile += f'#ifdef {sym}\nDEFVAL {{ "{sym}", {sym} }},\n#endif\n'
131
132 result = subprocess.run(
133 f'{cpp} -E -I"{srcdir}" -', shell=True, check=True, encoding='utf-8',
134 input=srcfile, capture_output=True)
135 for line in result.stdout.splitlines():
136 if line.startswith('DEFVAL '):
137 print(line[6:].rstrip(), file=output)
138
139 if target is None:
140 print(f'/* end {srctype} target macros */', file=output)
141 print('#endif', file=output)
142 else:
143 print(f'/* end {target} {srctype} target macros */', file=output)
144 print('#endif', file=output)
145 print('#endif', file=output)
146
147
148 def gen_common(output: TextIO, newlib: Path, cpp: str):
149 """Generate the common C library constants.
150
151 No arch should override these.
152 """
153 gentvals(output, cpp, 'errno', newlib / 'newlib/libc/include',
154 ('errno.h', 'sys/errno.h'), 'E[A-Z0-9]*')
155
156 gentvals(output, cpp, 'signal', newlib / 'newlib/libc/include',
157 ('signal.h', 'sys/signal.h'), r'SIG[A-Z0-9]*')
158
159 gentvals(output, cpp, 'open', newlib / 'newlib/libc/include',
160 ('fcntl.h', 'sys/fcntl.h', 'sys/_default_fcntl.h'), r'O_[A-Z0-9]*')
161
162
163 def gen_targets(output: TextIO, newlib: Path, cpp: str):
164 """Generate the target-specific lists."""
165 for target in sorted(TARGETS):
166 subdir = TARGET_DIRS.get(target, 'libgloss')
167 gentvals(output, cpp, 'sys', newlib / subdir, ('syscall.h',),
168 r'SYS_[_a-zA-Z0-9]*', target=target)
169
170
171 def gen(output: TextIO, newlib: Path, cpp: str):
172 """Generate all the things!"""
173 print(FILE_HEADER, file=output)
174 gen_common(output, newlib, cpp)
175 gen_targets(output, newlib, cpp)
176
177
178 def get_parser() -> argparse.ArgumentParser:
179 """Get CLI parser."""
180 parser = argparse.ArgumentParser(
181 description=__doc__,
182 formatter_class=argparse.RawDescriptionHelpFormatter)
183 parser.add_argument(
184 '-o', '--output', type=Path,
185 help='write to the specified file instead of stdout')
186 parser.add_argument(
187 '--cpp', type=str, default='cpp',
188 help='the preprocessor to use')
189 parser.add_argument(
190 '--srcroot', type=Path,
191 help='the root of this source tree')
192 parser.add_argument(
193 'newlib', nargs='?', type=Path,
194 help='path to the newlib+libgloss source tree')
195 return parser
196
197
198 def parse_args(argv: List[str]) -> argparse.Namespace:
199 """Process the command line & default options."""
200 parser = get_parser()
201 opts = parser.parse_args(argv)
202
203 if opts.srcroot is None:
204 opts.srcroot = Path(__file__).resolve().parent.parent.parent
205
206 if opts.newlib is None:
207 # Try to find newlib relative to our source tree.
208 if (opts.srcroot / 'newlib').is_dir():
209 # If newlib is manually in the same source tree, use it.
210 if (opts.srcroot / 'libgloss').is_dir():
211 opts.newlib = opts.srcroot
212 else:
213 opts.newlib = opts.srcroot / 'newlib'
214 elif (opts.srcroot.parent / 'newlib').is_dir():
215 # Or see if it's alongside the gdb/binutils repo.
216 opts.newlib = opts.srcroot.parent / 'newlib'
217 if opts.newlib is None or not opts.newlib.is_dir():
218 parser.error('unable to find newlib')
219
220 return opts
221
222
223 def main(argv: List[str]) -> int:
224 """The main entry point for scripts."""
225 opts = parse_args(argv)
226
227 if opts.output is not None:
228 output = open(opts.output, 'w', encoding='utf-8')
229 else:
230 output = sys.stdout
231
232 gen(output, opts.newlib, opts.cpp)
233 return 0
234
235
236 if __name__ == '__main__':
237 sys.exit(main(sys.argv[1:]))