2 # Copyright (C) 1996-2021 Free Software Foundation, Inc.
4 # This file is part of the GNU simulators.
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.
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.
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/>.
19 """Helper to generate nltvals.def.
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.
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
31 from pathlib
import Path
35 from typing
import Iterable
, List
, TextIO
38 PROG
= Path(__file__
).name
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.
47 # NB: New ports should use libgloss, not newlib.
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',
81 # Make sure TARGET_DIRS doesn't gain any typos.
82 assert not set(TARGET_DIRS
) - TARGETS
84 # The header for the generated def file.
86 /* Newlib/libgloss macro values needed by remote target support. */
87 /* This file is machine generated by {PROG}. */\
91 def gentvals(output
: TextIO
, cpp
: str, srctype
: str, srcdir
: Path
,
92 headers
: Iterable
[str],
95 """Extract constants from the specified files using a regular expression.
97 We'll run things through the preprocessor.
99 headers
= tuple(headers
)
101 # Require all files exist in order to regenerate properly.
102 for header
in headers
:
103 fullpath
= srcdir
/ header
104 assert fullpath
.exists(), f
'{fullpath} does not exist'
107 print(f
'#ifdef {srctype}_defs', file=output
)
109 print(f
'#ifdef NL_TARGET_{target}', file=output
)
110 print(f
'#ifdef {srctype}_defs', file=output
)
112 print('\n'.join(f
'/* from {x} */' for x
in headers
), file=output
)
115 print(f
'/* begin {srctype} target macros */', file=output
)
117 print(f
'/* begin {target} {srctype} target macros */', file=output
)
119 # Extract all the symbols.
120 srcfile
= ''.join(f
'#include <{x}>\n' for x
in headers
)
122 define_pattern
= re
.compile(r
'^#\s*define\s+(' + pattern
+ ')')
123 for header
in headers
:
124 with
open(srcdir
/ header
, 'r', encoding
='utf-8') as fp
:
126 for line
in data
.splitlines():
127 m
= define_pattern
.match(line
)
130 for sym
in sorted(syms
):
131 srcfile
+= f
'#ifdef {sym}\nDEFVAL {{ "{sym}", {sym} }},\n#endif\n'
133 result
= subprocess
.run(
134 f
'{cpp} -E -I"{srcdir}" -', shell
=True, check
=True, encoding
='utf-8',
135 input=srcfile
, capture_output
=True)
136 for line
in result
.stdout
.splitlines():
137 if line
.startswith('DEFVAL '):
138 print(line
[6:].rstrip(), file=output
)
141 print(f
'/* end {srctype} target macros */', file=output
)
142 print('#endif', file=output
)
144 print(f
'/* end {target} {srctype} target macros */', file=output
)
145 print('#endif', file=output
)
146 print('#endif', file=output
)
149 def gen_common(output
: TextIO
, newlib
: Path
, cpp
: str):
150 """Generate the common C library constants.
152 No arch should override these.
154 gentvals(output
, cpp
, 'errno', newlib
/ 'newlib/libc/include',
155 ('errno.h', 'sys/errno.h'), 'E[A-Z0-9]*')
157 gentvals(output
, cpp
, 'signal', newlib
/ 'newlib/libc/include',
158 ('signal.h', 'sys/signal.h'), r
'SIG[A-Z0-9]*')
160 gentvals(output
, cpp
, 'open', newlib
/ 'newlib/libc/include',
161 ('fcntl.h', 'sys/fcntl.h', 'sys/_default_fcntl.h'), r
'O_[A-Z0-9]*')
164 def gen_targets(output
: TextIO
, newlib
: Path
, cpp
: str):
165 """Generate the target-specific lists."""
166 for target
in sorted(TARGETS
):
167 subdir
= TARGET_DIRS
.get(target
, 'libgloss')
168 gentvals(output
, cpp
, 'sys', newlib
/ subdir
, ('syscall.h',),
169 r
'SYS_[_a-zA-Z0-9]*', target
=target
)
172 def gen(output
: TextIO
, newlib
: Path
, cpp
: str):
173 """Generate all the things!"""
174 print(FILE_HEADER
, file=output
)
175 gen_common(output
, newlib
, cpp
)
176 gen_targets(output
, newlib
, cpp
)
179 def get_parser() -> argparse
.ArgumentParser
:
180 """Get CLI parser."""
181 parser
= argparse
.ArgumentParser(
183 formatter_class
=argparse
.RawDescriptionHelpFormatter
)
185 '-o', '--output', type=Path
,
186 help='write to the specified file instead of stdout')
188 '--cpp', type=str, default
='cpp',
189 help='the preprocessor to use')
191 '--srcroot', type=Path
,
192 help='the root of this source tree')
194 'newlib', nargs
='?', type=Path
,
195 help='path to the newlib+libgloss source tree')
199 def parse_args(argv
: List
[str]) -> argparse
.Namespace
:
200 """Process the command line & default options."""
201 parser
= get_parser()
202 opts
= parser
.parse_args(argv
)
204 if opts
.srcroot
is None:
205 opts
.srcroot
= Path(__file__
).resolve().parent
.parent
.parent
207 if opts
.newlib
is None:
208 # Try to find newlib relative to our source tree.
209 if (opts
.srcroot
/ 'newlib').is_dir():
210 # If newlib is manually in the same source tree, use it.
211 if (opts
.srcroot
/ 'libgloss').is_dir():
212 opts
.newlib
= opts
.srcroot
214 opts
.newlib
= opts
.srcroot
/ 'newlib'
215 elif (opts
.srcroot
.parent
/ 'newlib').is_dir():
216 # Or see if it's alongside the gdb/binutils repo.
217 opts
.newlib
= opts
.srcroot
.parent
/ 'newlib'
218 if opts
.newlib
is None or not opts
.newlib
.is_dir():
219 parser
.error('unable to find newlib')
224 def main(argv
: List
[str]) -> int:
225 """The main entry point for scripts."""
226 opts
= parse_args(argv
)
228 if opts
.output
is not None:
229 output
= open(opts
.output
, 'w', encoding
='utf-8')
233 gen(output
, opts
.newlib
, opts
.cpp
)
237 if __name__
== '__main__':
238 sys
.exit(main(sys
.argv
[1:]))