sim: riscv: new port
[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 'v850': 'libgloss/v850/sys',
55 }
56 TARGETS = {
57 'bfin',
58 'cr16',
59 'd10v',
60 'fr30',
61 'frv',
62 'i960',
63 'lm32',
64 'm32r',
65 'mcore',
66 'mn10200',
67 'mn10300',
68 'msp430',
69 'pru',
70 'riscv',
71 'sparc',
72 'v850',
73 }
74
75 # Make sure TARGET_DIRS doesn't gain any typos.
76 assert not set(TARGET_DIRS) - TARGETS
77
78 # The header for the generated def file.
79 FILE_HEADER = f"""\
80 /* Newlib/libgloss macro values needed by remote target support. */
81 /* This file is machine generated by {PROG}. */\
82 """
83
84
85 def gentvals(output: TextIO, cpp: str, srctype: str, srcdir: Path,
86 headers: Iterable[str],
87 pattern: str,
88 target: str = None):
89 """Extract constants from the specified files using a regular expression.
90
91 We'll run things through the preprocessor.
92 """
93 headers = tuple(headers)
94
95 # Require all files exist in order to regenerate properly.
96 for header in headers:
97 fullpath = srcdir / header
98 assert fullpath.exists(), f'{fullpath} does not exist'
99
100 if target is None:
101 print(f'#ifdef {srctype}_defs', file=output)
102 else:
103 print(f'#ifdef NL_TARGET_{target}', file=output)
104 print(f'#ifdef {srctype}_defs', file=output)
105
106 print('\n'.join(f'/* from {x} */' for x in headers), file=output)
107
108 if target is None:
109 print(f'/* begin {srctype} target macros */', file=output)
110 else:
111 print(f'/* begin {target} {srctype} target macros */', file=output)
112
113 # Extract all the symbols.
114 srcfile = ''.join(f'#include <{x}>\n' for x in headers)
115 syms = set()
116 define_pattern = re.compile(r'^#\s*define\s+(' + pattern + ')')
117 for header in headers:
118 with open(srcdir / header, 'r', encoding='utf-8') as fp:
119 data = fp.read()
120 for line in data.splitlines():
121 m = define_pattern.match(line)
122 if m:
123 syms.add(m.group(1))
124 for sym in sorted(syms):
125 srcfile += f'#ifdef {sym}\nDEFVAL {{ "{sym}", {sym} }},\n#endif\n'
126
127 result = subprocess.run(
128 f'{cpp} -E -I"{srcdir}" -', shell=True, check=True, encoding='utf-8',
129 input=srcfile, capture_output=True)
130 for line in result.stdout.splitlines():
131 if line.startswith('DEFVAL '):
132 print(line[6:].rstrip(), file=output)
133
134 if target is None:
135 print(f'/* end {srctype} target macros */', file=output)
136 print('#endif', file=output)
137 else:
138 print(f'/* end {target} {srctype} target macros */', file=output)
139 print('#endif', file=output)
140 print('#endif', file=output)
141
142
143 def gen_common(output: TextIO, newlib: Path, cpp: str):
144 """Generate the common C library constants.
145
146 No arch should override these.
147 """
148 gentvals(output, cpp, 'errno', newlib / 'newlib/libc/include',
149 ('errno.h', 'sys/errno.h'), 'E[A-Z0-9]*')
150
151 gentvals(output, cpp, 'signal', newlib / 'newlib/libc/include',
152 ('signal.h', 'sys/signal.h'), r'SIG[A-Z0-9]*')
153
154 gentvals(output, cpp, 'open', newlib / 'newlib/libc/include',
155 ('fcntl.h', 'sys/fcntl.h', 'sys/_default_fcntl.h'), r'O_[A-Z0-9]*')
156
157
158 def gen_targets(output: TextIO, newlib: Path, cpp: str):
159 """Generate the target-specific lists."""
160 for target in sorted(TARGETS):
161 subdir = TARGET_DIRS.get(target, 'libgloss')
162 gentvals(output, cpp, 'sys', newlib / subdir, ('syscall.h',),
163 r'SYS_[_a-zA-Z0-9]*', target=target)
164
165
166 def gen(output: TextIO, newlib: Path, cpp: str):
167 """Generate all the things!"""
168 print(FILE_HEADER, file=output)
169 gen_common(output, newlib, cpp)
170 gen_targets(output, newlib, cpp)
171
172
173 def get_parser() -> argparse.ArgumentParser:
174 """Get CLI parser."""
175 parser = argparse.ArgumentParser(
176 description=__doc__,
177 formatter_class=argparse.RawDescriptionHelpFormatter)
178 parser.add_argument(
179 '-o', '--output', type=Path,
180 help='write to the specified file instead of stdout')
181 parser.add_argument(
182 '--cpp', type=str, default='cpp',
183 help='the preprocessor to use')
184 parser.add_argument(
185 '--srcroot', type=Path,
186 help='the root of this source tree')
187 parser.add_argument(
188 'newlib', nargs='?', type=Path,
189 help='path to the newlib+libgloss source tree')
190 return parser
191
192
193 def parse_args(argv: List[str]) -> argparse.Namespace:
194 """Process the command line & default options."""
195 parser = get_parser()
196 opts = parser.parse_args(argv)
197
198 if opts.srcroot is None:
199 opts.srcroot = Path(__file__).resolve().parent.parent.parent
200
201 if opts.newlib is None:
202 # Try to find newlib relative to our source tree.
203 if (opts.srcroot / 'newlib').is_dir():
204 # If newlib is manually in the same source tree, use it.
205 if (opts.srcroot / 'libgloss').is_dir():
206 opts.newlib = opts.srcroot
207 else:
208 opts.newlib = opts.srcroot / 'newlib'
209 elif (opts.srcroot.parent / 'newlib').is_dir():
210 # Or see if it's alongside the gdb/binutils repo.
211 opts.newlib = opts.srcroot.parent / 'newlib'
212 if opts.newlib is None or not opts.newlib.is_dir():
213 parser.error('unable to find newlib')
214
215 return opts
216
217
218 def main(argv: List[str]) -> int:
219 """The main entry point for scripts."""
220 opts = parse_args(argv)
221
222 if opts.output is not None:
223 output = open(opts.output, 'w', encoding='utf-8')
224 else:
225 output = sys.stdout
226
227 gen(output, opts.newlib, opts.cpp)
228 return 0
229
230
231 if __name__ == '__main__':
232 sys.exit(main(sys.argv[1:]))